blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
140
path
stringlengths
5
183
src_encoding
stringclasses
6 values
length_bytes
int64
12
5.32M
score
float64
2.52
4.94
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
12
5.32M
download_success
bool
1 class
b0f2466bc3a8fd7fd0f7feffc6c2520dc6146aba
Rust
8176135/NoIdea_OS
/src/ipc.rs
UTF-8
750
2.703125
3
[]
no_license
use alloc::collections::VecDeque; use spin::Mutex; use spin::RwLock; use lazy_static::lazy_static; use alloc::collections::BTreeMap; use core::sync::atomic::{AtomicU32, Ordering}; pub type FifoKey = u32; lazy_static! { pub static ref FIFO_POOL: RwLock<BTreeMap<FifoKey, Mutex<VecDeque<u8>>>> = create_fifo_pool(); } fn create_fifo_pool() -> RwLock<BTreeMap<FifoKey, Mutex<VecDeque<u8>>>> { RwLock::new(BTreeMap::new()) } pub fn get_available_fifo_key() -> FifoKey { static FIFO_KEY_COUNTER: AtomicU32 = AtomicU32::new(1000); FIFO_KEY_COUNTER.fetch_add(1, Ordering::Relaxed) } // /// Simple First in First out IPC // struct FifoIpc<T> { // pub queue: Mutex<VecDeque<T>> // } // // impl<T> FifoIpc<T> { // fn a() { // RwLock:: // } // }
true
7c4ad13a4915aa501c63eefe1994f60037d687aa
Rust
Zylphrex/aoc2020
/src/Day3/part2.rs
UTF-8
439
2.78125
3
[ "MIT" ]
permissive
use crate::day3::util::{count_trues}; pub fn day3part2(input: &String) -> Option<String> { let slope = input.lines().map(|x| x.to_string()).collect(); let directions: [(usize, usize); 5] = [ (1, 1), (3, 1), (5, 1), (7, 1), (1, 2), ]; let mut prod = 1; for (dx, dy) in directions.iter() { prod *= count_trues(&slope, *dx, *dy); } return Some(prod.to_string()); }
true
0adb5d1010c174ad014f0e340b5753ecbd401e57
Rust
kobus1998/backupper
/src/main.rs
UTF-8
3,582
2.96875
3
[]
no_license
extern crate termion; extern crate walkdir; use walkdir::WalkDir; use termion::{color, style}; use std::env::{self, Args}; use std::fs; use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; struct Settings<'a> { pub options: Vec<String>, pub arguments: HashMap<String, String>, pub start: &'a Path, pub end: &'a Path } impl <'a> Settings <'a> { pub fn new() -> Settings<'a> { let settings = Settings { options: Settings::get_options(), arguments: Settings::get_arguments(), start: Path::new(""), end: Path::new("") }; settings.display_arguments(); println!(""); settings.display_options(); settings } pub fn display_options(&self) { println!("Options"); for option in &self.options { println!("{}", option); } } pub fn display_arguments(&self) { println!("Arguments"); for (key, value) in &self.arguments { println!("{}: {}", key, value); } } pub fn get_options() -> Vec<String> { env::args() .into_iter() .filter(|a| a.starts_with("-")) .collect() } pub fn get_arguments() -> HashMap<String, String> { let args: Vec<String> = env::args() .into_iter() .filter(|a| !a.starts_with("-")) .map(|a| a.to_string()) .collect(); let mut from = ""; let mut to = ""; match args.get(1) { Some(x) => from = x, None => println!("Sorry, this vector is too short.") } match args.get(2) { Some(x) => to = x, None => println!("Sorry, this vector is too short.") } let mut mapped = HashMap::new(); mapped.insert(String::from("from"), from.to_string()); mapped.insert(String::from("to"), to.to_string()); mapped } } pub struct Backup { // settings: Settings } impl Backup { pub fn new() -> Backup { Backup { // settings: Settings::new() } } pub fn create(name: &String, data: String) { let mut file = File::create(name).unwrap(); file.write_all(data.to_string().as_bytes()).unwrap(); } pub fn read(path: &Path) -> String { let mut file = File::open(&path).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents); contents } pub fn copy(start: &Path, dir: &String) { let name = start.file_name().unwrap().to_str().unwrap(); fs::create_dir_all(str::replace(dir, name, "")); Backup::create(dir, Backup::read(start)); } pub fn run(&self, start: &Path, end: &Path) { let start_name: &str = start.to_str().unwrap(); let end_name: &str = end.to_str().unwrap(); for entry in WalkDir::new(start_name).into_iter().filter_map(|e| e.ok()) { let path = entry.path(); let name = path.to_str().unwrap(); if !path.is_dir() { let path_to = str::replace(path.to_str().unwrap(), start_name, end_name); Backup::copy(path, &path_to.to_string()); } } } } fn main() { let start = Path::new("/home/superuser/Documents/bu-from"); let end = Path::new("/home/superuser/Documents/bu-to"); let settings = Settings::new(); // let backup = Backup::new(); // Backup::run_through_directories(start, end); }
true
a94574898695272e3ecf36c561aa9ae0c28e2614
Rust
vadimcn/rust
/src/librustc_incremental/persist/directory.rs
UTF-8
3,468
2.609375
3
[ "Apache-2.0", "MIT", "NCSA", "ISC", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "BSD-2-Clause", "Unlicense", "LicenseRef-scancode-other-permissive" ]
permissive
// Copyright 2014 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Code to convert a DefId into a DefPath (when serializing) and then //! back again (when deserializing). Note that the new DefId //! necessarily will not be the same as the old (and of course the //! item might even be removed in the meantime). use rustc::dep_graph::DepNode; use rustc::hir::map::DefPath; use rustc::hir::def_id::DefId; use rustc::ty::TyCtxt; use rustc::util::nodemap::DefIdMap; use std::fmt::{self, Debug}; /// Index into the DefIdDirectory #[derive(Copy, Clone, Debug, PartialOrd, Ord, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct DefPathIndex { index: u32 } #[derive(RustcEncodable, RustcDecodable)] pub struct DefIdDirectory { // N.B. don't use Removable here because these def-ids are loaded // directly without remapping, so loading them should not fail. paths: Vec<DefPath> } impl DefIdDirectory { pub fn new() -> DefIdDirectory { DefIdDirectory { paths: vec![] } } pub fn retrace(&self, tcx: TyCtxt) -> RetracedDefIdDirectory { let ids = self.paths.iter() .map(|path| tcx.retrace_path(path)) .collect(); RetracedDefIdDirectory { ids: ids } } } #[derive(Debug, RustcEncodable, RustcDecodable)] pub struct RetracedDefIdDirectory { ids: Vec<Option<DefId>> } impl RetracedDefIdDirectory { pub fn def_id(&self, index: DefPathIndex) -> Option<DefId> { self.ids[index.index as usize] } pub fn map(&self, node: &DepNode<DefPathIndex>) -> Option<DepNode<DefId>> { node.map_def(|&index| self.def_id(index)) } } pub struct DefIdDirectoryBuilder<'a,'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, hash: DefIdMap<DefPathIndex>, directory: DefIdDirectory, } impl<'a,'tcx> DefIdDirectoryBuilder<'a,'tcx> { pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefIdDirectoryBuilder<'a, 'tcx> { DefIdDirectoryBuilder { tcx: tcx, hash: DefIdMap(), directory: DefIdDirectory::new() } } pub fn add(&mut self, def_id: DefId) -> DefPathIndex { debug!("DefIdDirectoryBuilder: def_id={:?}", def_id); let tcx = self.tcx; let paths = &mut self.directory.paths; self.hash.entry(def_id) .or_insert_with(|| { let def_path = tcx.def_path(def_id); let index = paths.len() as u32; paths.push(def_path); DefPathIndex { index: index } }) .clone() } pub fn map(&mut self, node: &DepNode<DefId>) -> DepNode<DefPathIndex> { node.map_def(|&def_id| Some(self.add(def_id))).unwrap() } pub fn into_directory(self) -> DefIdDirectory { self.directory } } impl Debug for DefIdDirectory { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt.debug_list() .entries(self.paths.iter().enumerate()) .finish() } }
true
16a34a31e282c53dbec36026c4c0c8a7121e7776
Rust
lukasl93/msp430fr59941
/src/lea/leacnf1.rs
UTF-8
22,636
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
#[doc = "Reader of register LEACNF1"] pub type R = crate::R<u32, super::LEACNF1>; #[doc = "Writer for register LEACNF1"] pub type W = crate::W<u32, super::LEACNF1>; #[doc = "Register LEACNF1 `reset()`'s with value 0"] impl crate::ResetValue for super::LEACNF1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "0:0\\] This bit indicate if LEA is able to accept new Commands (SUSPEND is always accepted)\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LEABUSY_A { #[doc = "0: LEA is in Ready can accept new commands"] READY = 0, #[doc = "1: LEA is busy right now and cannot accept any commands"] BUSY = 1, } impl From<LEABUSY_A> for bool { #[inline(always)] fn from(variant: LEABUSY_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LEABUSY`"] pub type LEABUSY_R = crate::R<bool, LEABUSY_A>; impl LEABUSY_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LEABUSY_A { match self.bits { false => LEABUSY_A::READY, true => LEABUSY_A::BUSY, } } #[doc = "Checks if the value of the field is `READY`"] #[inline(always)] pub fn is_ready(&self) -> bool { *self == LEABUSY_A::READY } #[doc = "Checks if the value of the field is `BUSY`"] #[inline(always)] pub fn is_busy(&self) -> bool { *self == LEABUSY_A::BUSY } } #[doc = "Write proxy for field `LEABUSY`"] pub struct LEABUSY_W<'a> { w: &'a mut W, } impl<'a> LEABUSY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LEABUSY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "LEA is in Ready can accept new commands"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(LEABUSY_A::READY) } #[doc = "LEA is busy right now and cannot accept any commands"] #[inline(always)] pub fn busy(self) -> &'a mut W { self.variant(LEABUSY_A::BUSY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "7:4\\] These Bits indicate the actual operation mode LEA is in. Other = Reserved\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum LEAMODE_A { #[doc = "0: Off (implicit)"] OFF = 0, #[doc = "1: Ready"] READY = 1, #[doc = "2: RunS (SUSPEND)"] RUNS = 2, #[doc = "3: RunR (RESUME)"] RUNR = 3, #[doc = "4: RunA (regular command operation )"] RUNA = 4, #[doc = "5: Notify"] NOTIFY = 5, #[doc = "6: Sleep"] SLEEP = 6, #[doc = "7: RunL"] RUNL = 7, } impl From<LEAMODE_A> for u8 { #[inline(always)] fn from(variant: LEAMODE_A) -> Self { variant as _ } } #[doc = "Reader of field `LEAMODE`"] pub type LEAMODE_R = crate::R<u8, LEAMODE_A>; impl LEAMODE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, LEAMODE_A> { use crate::Variant::*; match self.bits { 0 => Val(LEAMODE_A::OFF), 1 => Val(LEAMODE_A::READY), 2 => Val(LEAMODE_A::RUNS), 3 => Val(LEAMODE_A::RUNR), 4 => Val(LEAMODE_A::RUNA), 5 => Val(LEAMODE_A::NOTIFY), 6 => Val(LEAMODE_A::SLEEP), 7 => Val(LEAMODE_A::RUNL), i => Res(i), } } #[doc = "Checks if the value of the field is `OFF`"] #[inline(always)] pub fn is_off(&self) -> bool { *self == LEAMODE_A::OFF } #[doc = "Checks if the value of the field is `READY`"] #[inline(always)] pub fn is_ready(&self) -> bool { *self == LEAMODE_A::READY } #[doc = "Checks if the value of the field is `RUNS`"] #[inline(always)] pub fn is_runs(&self) -> bool { *self == LEAMODE_A::RUNS } #[doc = "Checks if the value of the field is `RUNR`"] #[inline(always)] pub fn is_runr(&self) -> bool { *self == LEAMODE_A::RUNR } #[doc = "Checks if the value of the field is `RUNA`"] #[inline(always)] pub fn is_runa(&self) -> bool { *self == LEAMODE_A::RUNA } #[doc = "Checks if the value of the field is `NOTIFY`"] #[inline(always)] pub fn is_notify(&self) -> bool { *self == LEAMODE_A::NOTIFY } #[doc = "Checks if the value of the field is `SLEEP`"] #[inline(always)] pub fn is_sleep(&self) -> bool { *self == LEAMODE_A::SLEEP } #[doc = "Checks if the value of the field is `RUNL`"] #[inline(always)] pub fn is_runl(&self) -> bool { *self == LEAMODE_A::RUNL } } #[doc = "Write proxy for field `LEAMODE`"] pub struct LEAMODE_W<'a> { w: &'a mut W, } impl<'a> LEAMODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LEAMODE_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Off (implicit)"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(LEAMODE_A::OFF) } #[doc = "Ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(LEAMODE_A::READY) } #[doc = "RunS (SUSPEND)"] #[inline(always)] pub fn runs(self) -> &'a mut W { self.variant(LEAMODE_A::RUNS) } #[doc = "RunR (RESUME)"] #[inline(always)] pub fn runr(self) -> &'a mut W { self.variant(LEAMODE_A::RUNR) } #[doc = "RunA (regular command operation )"] #[inline(always)] pub fn runa(self) -> &'a mut W { self.variant(LEAMODE_A::RUNA) } #[doc = "Notify"] #[inline(always)] pub fn notify(self) -> &'a mut W { self.variant(LEAMODE_A::NOTIFY) } #[doc = "Sleep"] #[inline(always)] pub fn sleep(self) -> &'a mut W { self.variant(LEAMODE_A::SLEEP) } #[doc = "RunL"] #[inline(always)] pub fn runl(self) -> &'a mut W { self.variant(LEAMODE_A::RUNL) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `LEAPWST`"] pub type LEAPWST_R = crate::R<u8, u8>; #[doc = "Write proxy for field `LEAPWST`"] pub struct LEAPWST_W<'a> { w: &'a mut W, } impl<'a> LEAPWST_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `LEAASST`"] pub type LEAASST_R = crate::R<u8, u8>; #[doc = "Write proxy for field `LEAASST`"] pub struct LEAASST_W<'a> { w: &'a mut W, } impl<'a> LEAASST_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `LEADONEC`"] pub type LEADONEC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LEADONEC`"] pub struct LEADONEC_W<'a> { w: &'a mut W, } impl<'a> LEADONEC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `LEAFREEC`"] pub type LEAFREEC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LEAFREEC`"] pub struct LEAFREEC_W<'a> { w: &'a mut W, } impl<'a> LEAFREEC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `LEATIMFLTC`"] pub type LEATIMFLTC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LEATIMFLTC`"] pub struct LEATIMFLTC_W<'a> { w: &'a mut W, } impl<'a> LEATIMFLTC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "22:22\\] LEA command fault\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LEACFLTC_A { #[doc = "0: No command fault occurred since this bit was cleared"] LEACFLTC_0 = 0, #[doc = "1: At least one command fault occurred since this bit was cleared"] LEACFLTC_1 = 1, } impl From<LEACFLTC_A> for bool { #[inline(always)] fn from(variant: LEACFLTC_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LEACFLTC`"] pub type LEACFLTC_R = crate::R<bool, LEACFLTC_A>; impl LEACFLTC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LEACFLTC_A { match self.bits { false => LEACFLTC_A::LEACFLTC_0, true => LEACFLTC_A::LEACFLTC_1, } } #[doc = "Checks if the value of the field is `LEACFLTC_0`"] #[inline(always)] pub fn is_leacfltc_0(&self) -> bool { *self == LEACFLTC_A::LEACFLTC_0 } #[doc = "Checks if the value of the field is `LEACFLTC_1`"] #[inline(always)] pub fn is_leacfltc_1(&self) -> bool { *self == LEACFLTC_A::LEACFLTC_1 } } #[doc = "Write proxy for field `LEACFLTC`"] pub struct LEACFLTC_W<'a> { w: &'a mut W, } impl<'a> LEACFLTC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LEACFLTC_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No command fault occurred since this bit was cleared"] #[inline(always)] pub fn leacfltc_0(self) -> &'a mut W { self.variant(LEACFLTC_A::LEACFLTC_0) } #[doc = "At least one command fault occurred since this bit was cleared"] #[inline(always)] pub fn leacfltc_1(self) -> &'a mut W { self.variant(LEACFLTC_A::LEACFLTC_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "23:23\\] LEA memory fault indication and clear flag. This bit indicates that a fault in the memory VBUS interface occurred. The exact fault reason may be identified by checking LEAWRSTAT and LEARDSTAT. This fault is also signaled to the SYS-module as bus error when enabled (LEACNF0.LEAMEMFLTE=1). Only one fault condition is signaled until this bit is cleared. Leaving this bit set will not cause any further faults. This fault is cleared by writing a one to it. Writing a zero has no effect.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LEAMEMFLTC_A { #[doc = "0: No memory fault occurred since this bit was cleared"] LEAMEMFLTC_0 = 0, #[doc = "1: At least one memory fault since this bit was cleared"] LEAMEMFLTC_1 = 1, } impl From<LEAMEMFLTC_A> for bool { #[inline(always)] fn from(variant: LEAMEMFLTC_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LEAMEMFLTC`"] pub type LEAMEMFLTC_R = crate::R<bool, LEAMEMFLTC_A>; impl LEAMEMFLTC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LEAMEMFLTC_A { match self.bits { false => LEAMEMFLTC_A::LEAMEMFLTC_0, true => LEAMEMFLTC_A::LEAMEMFLTC_1, } } #[doc = "Checks if the value of the field is `LEAMEMFLTC_0`"] #[inline(always)] pub fn is_leamemfltc_0(&self) -> bool { *self == LEAMEMFLTC_A::LEAMEMFLTC_0 } #[doc = "Checks if the value of the field is `LEAMEMFLTC_1`"] #[inline(always)] pub fn is_leamemfltc_1(&self) -> bool { *self == LEAMEMFLTC_A::LEAMEMFLTC_1 } } #[doc = "Write proxy for field `LEAMEMFLTC`"] pub struct LEAMEMFLTC_W<'a> { w: &'a mut W, } impl<'a> LEAMEMFLTC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LEAMEMFLTC_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No memory fault occurred since this bit was cleared"] #[inline(always)] pub fn leamemfltc_0(self) -> &'a mut W { self.variant(LEAMEMFLTC_A::LEAMEMFLTC_0) } #[doc = "At least one memory fault since this bit was cleared"] #[inline(always)] pub fn leamemfltc_1(self) -> &'a mut W { self.variant(LEAMEMFLTC_A::LEAMEMFLTC_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `LEARDSTAT`"] pub type LEARDSTAT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `LEARDSTAT`"] pub struct LEARDSTAT_W<'a> { w: &'a mut W, } impl<'a> LEARDSTAT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `LEAWRSTAT`"] pub type LEAWRSTAT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `LEAWRSTAT`"] pub struct LEAWRSTAT_W<'a> { w: &'a mut W, } impl<'a> LEAWRSTAT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28); self.w } } impl R { #[doc = "Bit 0 - 0:0\\] This bit indicate if LEA is able to accept new Commands (SUSPEND is always accepted)"] #[inline(always)] pub fn leabusy(&self) -> LEABUSY_R { LEABUSY_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 4:7 - 7:4\\] These Bits indicate the actual operation mode LEA is in. Other = Reserved"] #[inline(always)] pub fn leamode(&self) -> LEAMODE_R { LEAMODE_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - 11:8\\] These bits indicate the current power consumption as a relative value. The value zero indicated only static operation (usually clock less). This register might be read out for statistical power estimation of an application. These bits are also reflected in J-STATE when debugging"] #[inline(always)] pub fn leapwst(&self) -> LEAPWST_R { LEAPWST_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - 15:12\\] These bits are used to store the internal state of the application specific processor (ASIP) inside the accelerator core. The specific meaning of those bit patterns is not shown in this document."] #[inline(always)] pub fn leaasst(&self) -> LEAASST_R { LEAASST_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bit 16 - 16:16\\] LEA done event indication and clear flag. This bit indicated the done event for LEA. This bit is cleared by writing a one to it. Writing a zero has no effect."] #[inline(always)] pub fn leadonec(&self) -> LEADONEC_R { LEADONEC_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - 17:17\\] LEA free event indication and clear flag. This bit indicated the free event for LEA. This bit is cleared by writing a one to it. Writing a zero has no effect."] #[inline(always)] pub fn leafreec(&self) -> LEAFREEC_R { LEAFREEC_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 21 - 21:21\\] LEA timeout fault indication and clear flag; This bits indicates that a timer timeout occurred. This fault is cleared by writing a one to it. Writing a zero has no effect.."] #[inline(always)] pub fn leatimfltc(&self) -> LEATIMFLTC_R { LEATIMFLTC_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - 22:22\\] LEA command fault"] #[inline(always)] pub fn leacfltc(&self) -> LEACFLTC_R { LEACFLTC_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - 23:23\\] LEA memory fault indication and clear flag. This bit indicates that a fault in the memory VBUS interface occurred. The exact fault reason may be identified by checking LEAWRSTAT and LEARDSTAT. This fault is also signaled to the SYS-module as bus error when enabled (LEACNF0.LEAMEMFLTE=1). Only one fault condition is signaled until this bit is cleared. Leaving this bit set will not cause any further faults. This fault is cleared by writing a one to it. Writing a zero has no effect."] #[inline(always)] pub fn leamemfltc(&self) -> LEAMEMFLTC_R { LEAMEMFLTC_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bits 24:27 - 27:24\\] Read Status. This bit field keeps the VBUS read status lines from the last bus error condition."] #[inline(always)] pub fn leardstat(&self) -> LEARDSTAT_R { LEARDSTAT_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:31 - 31:28\\] Write Status. This bit field keeps the VBUS write status lines from the last bus error condition."] #[inline(always)] pub fn leawrstat(&self) -> LEAWRSTAT_R { LEAWRSTAT_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bit 0 - 0:0\\] This bit indicate if LEA is able to accept new Commands (SUSPEND is always accepted)"] #[inline(always)] pub fn leabusy(&mut self) -> LEABUSY_W { LEABUSY_W { w: self } } #[doc = "Bits 4:7 - 7:4\\] These Bits indicate the actual operation mode LEA is in. Other = Reserved"] #[inline(always)] pub fn leamode(&mut self) -> LEAMODE_W { LEAMODE_W { w: self } } #[doc = "Bits 8:11 - 11:8\\] These bits indicate the current power consumption as a relative value. The value zero indicated only static operation (usually clock less). This register might be read out for statistical power estimation of an application. These bits are also reflected in J-STATE when debugging"] #[inline(always)] pub fn leapwst(&mut self) -> LEAPWST_W { LEAPWST_W { w: self } } #[doc = "Bits 12:15 - 15:12\\] These bits are used to store the internal state of the application specific processor (ASIP) inside the accelerator core. The specific meaning of those bit patterns is not shown in this document."] #[inline(always)] pub fn leaasst(&mut self) -> LEAASST_W { LEAASST_W { w: self } } #[doc = "Bit 16 - 16:16\\] LEA done event indication and clear flag. This bit indicated the done event for LEA. This bit is cleared by writing a one to it. Writing a zero has no effect."] #[inline(always)] pub fn leadonec(&mut self) -> LEADONEC_W { LEADONEC_W { w: self } } #[doc = "Bit 17 - 17:17\\] LEA free event indication and clear flag. This bit indicated the free event for LEA. This bit is cleared by writing a one to it. Writing a zero has no effect."] #[inline(always)] pub fn leafreec(&mut self) -> LEAFREEC_W { LEAFREEC_W { w: self } } #[doc = "Bit 21 - 21:21\\] LEA timeout fault indication and clear flag; This bits indicates that a timer timeout occurred. This fault is cleared by writing a one to it. Writing a zero has no effect.."] #[inline(always)] pub fn leatimfltc(&mut self) -> LEATIMFLTC_W { LEATIMFLTC_W { w: self } } #[doc = "Bit 22 - 22:22\\] LEA command fault"] #[inline(always)] pub fn leacfltc(&mut self) -> LEACFLTC_W { LEACFLTC_W { w: self } } #[doc = "Bit 23 - 23:23\\] LEA memory fault indication and clear flag. This bit indicates that a fault in the memory VBUS interface occurred. The exact fault reason may be identified by checking LEAWRSTAT and LEARDSTAT. This fault is also signaled to the SYS-module as bus error when enabled (LEACNF0.LEAMEMFLTE=1). Only one fault condition is signaled until this bit is cleared. Leaving this bit set will not cause any further faults. This fault is cleared by writing a one to it. Writing a zero has no effect."] #[inline(always)] pub fn leamemfltc(&mut self) -> LEAMEMFLTC_W { LEAMEMFLTC_W { w: self } } #[doc = "Bits 24:27 - 27:24\\] Read Status. This bit field keeps the VBUS read status lines from the last bus error condition."] #[inline(always)] pub fn leardstat(&mut self) -> LEARDSTAT_W { LEARDSTAT_W { w: self } } #[doc = "Bits 28:31 - 31:28\\] Write Status. This bit field keeps the VBUS write status lines from the last bus error condition."] #[inline(always)] pub fn leawrstat(&mut self) -> LEAWRSTAT_W { LEAWRSTAT_W { w: self } } }
true
926ee20647befe9ab5b64ef40053c5744ab8e90e
Rust
jsagfr/project-b
/src/scanner.rs
UTF-8
10,673
3.15625
3
[ "MIT" ]
permissive
use syntax::{Token}; // // Scanner Properties // // Tokens are a partition of the source // tokens are not empty // No Consequent Spaces // Spaces contains only white spaces // Comments either: // - start with "//" contains no '\n' and next token start with '\n'; // - or start with "/*" and ends with "*/", contains no inner "*/" // (accept multi-comments inside multi-comment?) // #[test] fn test_trivial(){ assert_eq!(scan(" "), vec![]); assert_eq!(scan(" \n\t"), vec![]); assert_eq!(scan("//x"), vec![]); assert_eq!(scan("// one"), vec![]); assert_eq!(scan("/* \n*/"), vec![]); assert_eq!(scan("123"), vec![Token::Integer("123")]); assert_eq!(scan("123."), vec![Token::Float("123.")]); assert_eq!(scan("123.456"), vec![Token::Float("123.456")]); assert_eq!(scan("foo_bar2"), vec![Token::Identifier("foo_bar2")]); assert_eq!(scan("THEN"), vec![Token::KwTHEN]); assert_eq!(scan("THENxxx"), vec![Token::Identifier("THENxxx")]); assert_eq!(scan("-"), vec![Token::OpMinus]); assert_eq!(scan("-->"), vec![Token::OpTotalfun]); assert_eq!(scan("◦"), vec![Token::OpBullet]); assert_eq!(scan("×"), vec![Token::OpCross]); assert_eq!(scan("·"), vec![Token::OpMdot]); } #[test] fn test_double(){ assert_eq!(scan("//xy z\n "), vec![ ]); assert_eq!(scan("\n //xy z"), vec![ ]); } #[test] fn test_unicode_1(){ // one char and one grapheme let mut reconstruct = "".to_owned(); reconstruct.push('é'); // one assert_eq!("é", reconstruct); assert_eq!(scan("é"), vec![Token::Identifier("é")]); } #[test] fn test_unicode_2(){ // two chars but one graphemes let mut reconstruct = "".to_owned(); reconstruct.push('e'); reconstruct.push('́'); assert_eq!("é", reconstruct); // the result should be 2 chars long // (if we consider composite char as legal string for identifier) //assert_eq!(scan("é"), vec![Token::Identifier("é")]); // TODO doesn't work for the moment } #[test] fn test_unicode_normalisation(){ use unicode_normalization::UnicodeNormalization; let mut composite = "".to_owned(); composite.push('e'); composite.push('́'); assert!("é" != composite); // one grapheme assert!("é" == composite); // two graphemes let normalized : String = composite.nfc().collect(); assert!("é" == normalized); // one grapheme assert!("é" != normalized); // two graphemes } #[test] fn test_unicode_alphab(){ // composable char are not alphabetic ... assert!( ! '́'.is_alphabetic()) } #[test] fn test_composed(){ assert_eq!(scan("1..2"), vec![ Token::Integer("1"), Token::OpInter, Token::Integer("2")]); } struct ScannerState <'a> { i : usize, j : usize, token : Option<Token<'a>>, source : &'a str, size_left : usize, // in bytes size_right : usize, // in bytes stop : bool, } pub fn scan <'a>(source : &'a str) -> Vec<Token> { let mut state = ScannerState{ i:0, j:0, token : None, source : source, size_left : 0, size_right : 0, stop : true, }; let mut res = vec![]; loop { state.scan_spaces(); state.scan_comment_monoline(); state.scan_comment_multiline(); state.scan_number(); for &(string,tok) in &::syntax::KEYWORDS { state.scan_string(string,tok); } state.scan_identifier(); for &(string,tok) in &::syntax::OPERATORS { state.scan_string(string,tok); } if state.stop { return res } match state.token { Some(tok) => {res.push(tok);}, None => {}, } state.i = state.j; state.size_left = state.size_right; state.token = None; state.stop = true; } } impl<'a> ScannerState<'a> { fn scan_spaces(&mut self){ let mut x = self.i; let mut new_right = self.size_left; loop { match self.source.char_indices().nth(x) { Some((i,' ')) | Some((i,'\t')) | Some((i,'\n')) => { x += 1; new_right = i + ' '.len_utf8(); }, _ => break, } } if self.j < x { self.j = x; self.size_right = new_right; self.token = None; self.stop = false; } } fn scan_comment_monoline(&mut self){ let mut x = self.i; let mut new_right = self.size_left; if self.source.chars().nth(x) == Some('/') && self.source.chars().nth(x+1) == Some('/') { x += 2; new_right += '/'.len_utf8()*2; loop { match self.source.char_indices().nth(x) { None => break, Some((_,'\n')) => break, Some((i,c)) => { x += 1; new_right = i + c.len_utf8(); }, } } } if self.j < x { self.j = x; self.size_right = new_right; self.token = None; self.stop = false; } } fn scan_comment_multiline(&mut self){ let mut x = self.i; let mut new_right = self.size_left; let mut iter = self.source.char_indices(); if iter.nth(x) == Some((new_right,'/')) && iter.next() == Some((new_right+'/'.len_utf8(),'*')) { x += 2; new_right += '/'.len_utf8() + '*'.len_utf8(); 'outer: loop { match iter.next() { Some((i,'*')) => { x += 1; new_right = i + '*'.len_utf8(); 'inner: loop { match iter.next() { Some((i,'/')) => { x += 1; new_right = i + '/'.len_utf8(); break 'outer; }, Some((i,'*')) => { x += 1; new_right = i + '*'.len_utf8(); continue 'inner; }, Some((i,c)) => { x += 1; new_right = i + c.len_utf8(); continue 'outer; }, None => { break 'outer; }, } } }, Some((i,c)) => { x += 1; new_right = i + c.len_utf8(); continue 'outer; }, None => { break 'outer; }, } } } if self.j < x { self.j = x; self.size_right = new_right; self.token = None; self.stop = false; } } fn scan_number(&mut self){ let mut x = self.i; let mut new_right = self.size_left; let mut float = false; let mut iter = self.source.char_indices().skip(x); loop { match iter.next() { Some((i,'0' ... '9')) => { x += 1; new_right = i + '0'.len_utf8(); }, Some((i,'.')) => { let mut iter_tmp = iter.clone(); // Looking for a '..' operator which can confuse with a float like "1." match iter_tmp.next() { Some((_, '.')) => break, _ => {} } if float == true { break; } float = true; x += 1; new_right = i + '.'.len_utf8(); } _ => break, } } if self.j < x { self.j = x; self.size_right = new_right; let content = &self.source[self.size_left..self.size_right]; self.token = if float { Some(Token::Float(content)) } else { Some(Token::Integer(content)) }; self.stop = false; } } fn scan_identifier(&mut self){ let mut x = self.i; let mut new_right = self.size_left; let mut iter = self.source.char_indices().skip(self.i); 'outer: loop { match iter.next() { Some((i,c)) if c.is_alphabetic() => { x += 1; new_right = i + c.len_utf8(); 'inner: loop { match iter.next() { Some((i,c)) if c.is_alphabetic() || c.is_numeric() || c == '_' => { x += 1; new_right = i + c.len_utf8(); continue 'inner; }, _ => break 'outer, } } }, _ => { break 'outer }, } } if self.j < x { self.j = x; self.size_right = new_right; let content = &self.source[self.size_left..self.size_right]; self.token = Some(Token::Identifier(content)); self.stop = false; } } fn scan_string(&mut self, keyword : &str, tok : Token<'a>){ let mut x = self.i; let mut new_right = self.size_left; let iter = self.source.char_indices().skip(self.i); let ik = keyword.chars(); for ((i,a),b) in iter.zip(ik) { if a == b { x += 1; new_right = i + a.len_utf8(); } else { break; } } if self.j < x { self.j = x; self.size_right = new_right; self.token = Some(tok); self.stop = false; } } }
true
8a88223c2edfb3c553215810abfa876c66c02b6f
Rust
jsgf/promising-future
/src/futurestream.rs
UTF-8
7,573
3.171875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
use std::sync::Arc; use std::sync::mpsc::{Sender, Receiver, channel}; use std::iter::FromIterator; use super::Pollresult::*; use super::Future; use cvmx::CvMx; /// Stream of multiple `Future`s /// /// A `FutureStream` can be used to wait for multiple `Future`s, and return them incrementally as /// they are resolved. /// /// It implements an iterator over completed `Future`s, and can be constructed from an iterator of /// `Future`s. /// /// May be cloned and the clones passed to other threads so that `Future`s may be added from multiple /// threads. #[derive(Clone)] pub struct FutureStream<T> { tx: Sender<Option<T>>, // values from Promise inner: Arc<CvMx<FutureStreamInner<T>>>, // set of waited-for futures } /// Waiter for `Future`s in a `FutureStream`. /// /// A singleton waiter for `Future`s, associated with a specific `FutureStream`. This may be used /// in a multithreaded environment to wait for `Futures` to resolve while other threads fulfill /// `Promises` and add new `Future`s to the `FutureStream`. /// /// ``` /// # use ::promising_future::{Future,FutureStream}; /// # let future = Future::with_value(()); /// let fs = FutureStream::new(); /// fs.add(future); /// // ... /// let mut waiter = fs.waiter(); /// while let Some(future) = waiter.wait() { /// match future.value() { /// None => (), // Future unfulfilled /// Some(val) => val, /// } /// } /// ``` /// /// It may also be converted into an `Iterator` over the values yielded by resolved `Future`s /// (unfulfilled `Promise`s are ignored). /// /// ``` /// # use ::promising_future::{Future,FutureStream}; /// # let fut1 = Future::with_value(()); /// let fs = FutureStream::new(); /// fs.add(fut1); /// for val in fs.waiter() { /// // ... /// } /// ``` pub struct FutureStreamWaiter<'a, T: 'a> { fs: &'a FutureStream<T>, rx: Option<Receiver<Option<T>>>, // Option so that Drop can remove it } struct FutureStreamInner<T> { pending: usize, rx: Option<Receiver<Option<T>>>, // value receiver (if not passed to a waiter) } impl<T> FutureStream<T> { pub fn new() -> FutureStream<T> { let (tx, rx) = channel(); let inner = FutureStreamInner { rx: Some(rx), pending: 0, }; FutureStream { tx: tx, inner: Arc::new(CvMx::new(inner)), } } /// Add a `Future` to the stream. pub fn add(&self, fut: Future<T>) where T: Send + 'static { let mut inner = self.inner.mx.lock().unwrap(); let tx = self.tx.clone(); inner.pending += 1; // If `tx.send()` fails, then it just means the waiter/FutureStream has gone away fut.callback_unit(move |v| { let _ = tx.send(v); }) } /// Return number of outstanding `Future`s. pub fn outstanding(&self) -> usize { self.inner.mx.lock().unwrap().pending } /// Return a singleton `FutureStreamWaiter`. If one already exists, block until it is released. pub fn waiter<'fs>(&'fs self) -> FutureStreamWaiter<'fs, T> { let mut inner = self.inner.mx.lock().unwrap(); loop { match inner.rx.take() { None => { inner = self.inner.cv.wait(inner).unwrap() }, Some(rx) => return FutureStreamWaiter::new(self, rx), } } } /// Return a singleton `FutureStreamWaiter`. Returns `None` if one already exists. pub fn try_waiter<'fs>(&'fs self) -> Option<FutureStreamWaiter<'fs, T>> { let mut inner = self.inner.mx.lock().unwrap(); match inner.rx.take() { None => None, Some(rx) => Some(FutureStreamWaiter::new(self, rx)), } } fn return_waiter(&self, rx: Receiver<Option<T>>) { let mut inner = self.inner.mx.lock().unwrap(); assert!(inner.rx.is_none()); inner.rx = Some(rx); self.inner.cv.notify_one(); } /// Return a resolved `Future` if any, but don't wait for more to resolve. pub fn poll(&self) -> Option<Future<T>> { self.waiter().poll() } /// Return resolved `Future`s. Blocks if there are outstanding `Futures` which are not yet /// resolved. Returns `None` when there are no more outstanding `Future`s. pub fn wait(&self) -> Option<Future<T>> { self.waiter().wait() } } impl<'fs, T> FutureStreamWaiter<'fs, T> { fn new(fs: &'fs FutureStream<T>, rx: Receiver<Option<T>>) -> FutureStreamWaiter<'fs, T> { FutureStreamWaiter { fs: fs, rx: Some(rx) } } /// Return resolved `Future`s. Blocks if there are outstanding `Futures` which are not yet /// resolved. Returns `None` when there are no more outstanding `Future`s. pub fn wait(&mut self) -> Option<Future<T>> { if { let l = self.fs.inner.mx.lock().unwrap(); l.pending == 0 } { // Nothing left None } else { // Wait for the next completion notification match self.rx.as_ref().unwrap().recv() { Ok(val) => { let mut l = self.fs.inner.mx.lock().unwrap(); l.pending -= 1; Some(Future::from(val)) }, Err(_) => None, } } } /// Return next resolved `Future`, but don't wait for more to resolve. pub fn poll(&mut self) -> Option<Future<T>> { let mut inner = self.fs.inner.mx.lock().unwrap(); if inner.pending == 0 { None } else { match self.rx.as_ref().unwrap().try_recv() { Ok(val) => { inner.pending -= 1; Some(Future::from(val)) }, Err(_) => None, } } } } impl<'fs, T> Drop for FutureStreamWaiter<'fs, T> { fn drop(&mut self) { // Return notifications to FutureStream self.fs.return_waiter(self.rx.take().unwrap()) } } /// Iterator for completed `Future`s in a `FutureStream`. The iterator incrementally returns values /// from resolved `Future`s, blocking while there are no unresolved `Future`s. `Future`s which /// resolve to no value are discarded. pub struct FutureStreamIter<'a, T: 'a>(FutureStreamWaiter<'a, T>); impl<'fs, T: 'fs> IntoIterator for FutureStreamWaiter<'fs, T> { type Item = T; type IntoIter = FutureStreamIter<'fs, T>; fn into_iter(self) -> Self::IntoIter { FutureStreamIter(self) } } impl<'a, T: 'a> Iterator for FutureStreamIter<'a, T> { type Item = T; // Get next Future resolved with value, if any fn next(&mut self) -> Option<Self::Item> { loop { match self.0.wait() { None => return None, Some(fut) => { match fut.poll() { Unresolved(_) => panic!("FutureStreamWait.wait returned unresolved Future"), Resolved(v@Some(_)) => return v, Resolved(None) => (), } }, } } } } impl<'a, T: 'a> IntoIterator for &'a FutureStream<T> { type Item = T; type IntoIter = FutureStreamIter<'a, T>; fn into_iter(self) -> Self::IntoIter { self.waiter().into_iter() } } impl<T: Send + 'static> FromIterator<Future<T>> for FutureStream<T> { // XXX lazily consume input iterator? fn from_iter<I>(iterator: I) -> Self where I: IntoIterator<Item=Future<T>> { let stream = FutureStream::new(); for f in iterator.into_iter() { stream.add(f) } stream } }
true
2d8bec79f525d6d1fc782b6f593147bc5241972d
Rust
agrism/bo
/src/row_test.rs
UTF-8
3,673
3.40625
3
[ "MIT" ]
permissive
use crate::Row; #[test] fn test_row_render() { // fn render(&self, start: usize, end: usize, line_number: usize, x_offset: usize) assert_eq!(Row::from("Test").render(0, 50, 1, 0), "Test"); assert_eq!(Row::from("Test").render(0, 50, 1, 4), " 1 Test"); assert_eq!(Row::from("Test").render(0, 50, 11, 4), " 11 Test"); assert_eq!(Row::from("Test").render(10, 60, 11, 4), " 11 "); assert_eq!(Row::from("\u{2764}").render(0, 50, 11, 4), " 11 \u{2764}"); } #[test] fn test_row_graphemes_index() { let row = Row::from("I \u{2764} unicode!"); let mut graphemes = row.graphemes(); assert_eq!(graphemes.next(), Some("I")); assert_eq!(graphemes.next(), Some(" ")); assert_eq!(graphemes.next(), Some("\u{2764}")); assert_eq!(graphemes.next(), Some(" ")); assert_eq!(graphemes.next(), Some("u")); } #[test] fn test_row_len() { assert_eq!(Row::from("Hello World!").len(), 12); assert_eq!(Row::from("\u{2764}\u{2764}\u{2764}!").len(), 4); // 3 unicode hearts assert_eq!(Row::from("").len(), 0); } #[test] fn test_row_is_empty() { assert!(Row::from("").is_empty()); } #[test] fn test_row_index() { assert_eq!(Row::from("I \u{2764} unicode!").index(2), "\u{2764}") } #[test] fn test_row_num_words() { assert_eq!(Row::from("I l\u{f8}ve unicode!").num_words(), 3); assert_eq!(Row::from("I \u{9ec} unicode!").num_words(), 3); // "weird cases": turns out a heart isn't alphabetic, so it's not considered // a word. assert_eq!(Row::from("I \u{2764} unicode!").num_words(), 2); assert_eq!(Row::from("I \u{2764}\u{2764} unicode!").num_words(), 2); } #[test] fn test_row_contains() { assert!(Row::from("I \u{2764} unicode!").contains("\u{2764}")); // check that the match is done on the unicode char and not the raw text assert!(!Row::from("I \u{2764} unicode!").contains("2764")); assert!(!Row::from("Hello").contains("Plop")); assert!(Row::from("Hello").contains("lo")); assert!(!Row::from("Hello").contains("LO")); } #[test] fn test_row_find() { assert_eq!(Row::from("Hello world!").find("world"), Some(6)); assert_eq!(Row::from("Hello world!").find("\u{2764}"), None); assert_eq!(Row::from("Hello \u{2764} world!").find("\u{2764}"), Some(6)); } #[test] fn test_row_is_whitespace() { // whitespaces assert!(Row::from(" ").is_whitespace()); assert!(Row::from("\t").is_whitespace()); assert!(Row::from("\t ").is_whitespace()); assert!(!Row::from("a").is_whitespace()); assert!(!Row::from("aa").is_whitespace()); assert!(!Row::from(" \u{2764}").is_whitespace()); } #[test] fn test_row_string_chars() { assert_eq!( Row::from(" \u{2764}").string.chars().collect::<Vec<char>>(), [' ', '\u{2764}'] ); } #[test] fn test_row_insert() { let mut row = Row::from("Hell"); row.insert(4, 'o'); assert_eq!(row.string, "Hello"); row.insert(8, 'o'); assert_eq!(row.string, "Helloo"); row.insert(0, '.'); assert_eq!(row.string, ".Helloo"); } #[test] fn test_row_delete() { let mut row = Row::from("Hello!"); row.delete(8); // outside the string's boundaries assert_eq!(row.string, "Hello!"); row.delete(5); assert_eq!(row.string, "Hello"); row.delete(2); assert_eq!(row.string, "Helo"); } #[test] fn test_row_append() { let mut row1 = Row::from("Hello!"); let row2 = Row::from("world!"); row1.append(&row2); assert_eq!(row1.string, "Hello!world!"); } #[test] fn test_row_split() { let mut row1 = Row::from("Hello world!"); let row2 = row1.split(5); assert_eq!(row1.string, "Hello"); assert_eq!(row2.string, " world!"); }
true
bc6bf40f07872956cca0017c59901b34f43e8f73
Rust
johnterickson/rust
/src/tools/clippy/clippy_lints/src/doc_link_with_quotes.rs
UTF-8
1,799
2.96875
3
[ "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "MIT", "LicenseRef-scancode-other-permissive", "NCSA" ]
permissive
use clippy_utils::diagnostics::span_lint; use itertools::Itertools; use rustc_ast::{AttrKind, Attribute}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Detects the syntax `['foo']` in documentation comments (notice quotes instead of backticks) /// outside of code blocks /// ### Why is this bad? /// It is likely a typo when defining an intra-doc link /// /// ### Example /// ```rust /// /// See also: ['foo'] /// fn bar() {} /// ``` /// Use instead: /// ```rust /// /// See also: [`foo`] /// fn bar() {} /// ``` #[clippy::version = "1.63.0"] pub DOC_LINK_WITH_QUOTES, pedantic, "possible typo for an intra-doc link" } declare_lint_pass!(DocLinkWithQuotes => [DOC_LINK_WITH_QUOTES]); impl EarlyLintPass for DocLinkWithQuotes { fn check_attribute(&mut self, ctx: &EarlyContext<'_>, attr: &Attribute) { if let AttrKind::DocComment(_, symbol) = attr.kind { if contains_quote_link(symbol.as_str()) { span_lint( ctx, DOC_LINK_WITH_QUOTES, attr.span, "possible intra-doc link using quotes instead of backticks", ); } } } } fn contains_quote_link(s: &str) -> bool { let mut in_backticks = false; let mut found_opening = false; for c in s.chars().tuple_windows::<(char, char)>() { match c { ('`', _) => in_backticks = !in_backticks, ('[', '\'') if !in_backticks => found_opening = true, ('\'', ']') if !in_backticks && found_opening => return true, _ => {}, } } false }
true
4eadc6a773c02f7f26cd64b5d0bacf7edcf50c23
Rust
zhxu73/jx2json-rs
/src/ast.rs
UTF-8
6,342
3.453125
3
[ "MIT" ]
permissive
use std::collections::HashMap; use std::fmt; pub enum AstNode { INTVAL(i32), DOUBLEVAL(f64), STRVAL(String), BOOLVAL(bool), NULLVAL, // key value pairs OBJECT(HashMap<String, Box<AstNode>>), LIST(Vec<Box<AstNode>>), // Variable VAR(String), ADD { left: Box<AstNode>, right: Box<AstNode>, }, SUB { left: Box<AstNode>, right: Box<AstNode>, }, MUL { left: Box<AstNode>, right: Box<AstNode>, }, DIV { left: Box<AstNode>, right: Box<AstNode>, }, MOD { left: Box<AstNode>, right: Box<AstNode>, }, AND { left: Box<AstNode>, right: Box<AstNode>, }, OR { left: Box<AstNode>, right: Box<AstNode>, }, EQ { left: Box<AstNode>, right: Box<AstNode>, }, NE { left: Box<AstNode>, right: Box<AstNode>, }, GT { left: Box<AstNode>, right: Box<AstNode>, }, GE { left: Box<AstNode>, right: Box<AstNode>, }, LT { left: Box<AstNode>, right: Box<AstNode>, }, LE { left: Box<AstNode>, right: Box<AstNode>, }, /// list comprehension COMPRE { expr: Box<AstNode>, var: String, iter_expr: Box<AstNode>, }, FUNC { name: String, params: Vec<Box<AstNode>>, }, } impl fmt::Display for AstNode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self { AstNode::INTVAL(val) => write!(f, "{}", val), AstNode::DOUBLEVAL(val) => write!(f, "{}", val), AstNode::STRVAL(val) => write!(f, "{}", val), AstNode::BOOLVAL(val) => write!(f, "{}", val), AstNode::NULLVAL => write!(f, "null"), AstNode::OBJECT(keyval_list) => { if let Err(err) = write!(f, "{{ ") { return Err(err); } for (key, value) in keyval_list { if let Err(err) = write!(f, "\"{}\" : {}", key, value) { return Err(err); } } write!(f, " }}") } AstNode::LIST(list) => { if let Err(err) = write!(f, "[ ") { return Err(err); } for node in list { if let Err(err) = write!(f, "{}", node) { return Err(err); } } write!(f, " ]") } AstNode::VAR(name) => write!(f, "{}", name), AstNode::ADD { left, right } | AstNode::SUB { left, right } | AstNode::MUL { left, right } | AstNode::DIV { left, right } | AstNode::MOD { left, right } | AstNode::AND { left, right } | AstNode::OR { left, right } | AstNode::EQ { left, right } | AstNode::NE { left, right } | AstNode::GT { left, right } | AstNode::GE { left, right } | AstNode::LT { left, right } | AstNode::LE { left, right } => { write!(f, "{} {} {}", left, self.operator_str(), right) } AstNode::COMPRE { expr, var, iter_expr, } => write!(f, "[ {} for {} in {} ]", expr, var, iter_expr), AstNode::FUNC { name, params } => { if let Err(err) = write!(f, "{}(", name) { return Err(err); } // all params except last one for param in params.iter().take(params.len() - 1) { if let Err(err) = write!(f, "{}, ", param) { return Err(err); } } // last param match params.iter().last() { Some(param) => { if let Err(err) = write!(f, "{}", param) { return Err(err); } } None => (), }; write!(f, ")") } } } } impl AstNode { fn operator_str(&self) -> &str { match &self { AstNode::ADD { left: _, right: _ } => "+", AstNode::SUB { left: _, right: _ } => "-", AstNode::MUL { left: _, right: _ } => "*", AstNode::DIV { left: _, right: _ } => "/", AstNode::MOD { left: _, right: _ } => "%", AstNode::AND { left: _, right: _ } => "&&", AstNode::OR { left: _, right: _ } => "||", AstNode::EQ { left: _, right: _ } => "==", AstNode::NE { left: _, right: _ } => "!=", AstNode::GT { left: _, right: _ } => ">", AstNode::GE { left: _, right: _ } => ">=", AstNode::LT { left: _, right: _ } => "<", AstNode::LE { left: _, right: _ } => "<=", _ => panic!(), } } pub fn is_int(&self) -> bool { match &self { AstNode::INTVAL(_) => true, _ => false, } } pub fn is_double(&self) -> bool { match &self { AstNode::DOUBLEVAL(_) => true, _ => false, } } pub fn is_str(&self) -> bool { match &self { AstNode::STRVAL(_) => true, _ => false, } } pub fn is_bool(&self) -> bool { match &self { AstNode::BOOLVAL(_) => true, _ => false, } } pub fn is_obj(&self) -> bool { match &self { AstNode::OBJECT(_) => true, _ => false, } } pub fn is_list(&self) -> bool { match &self { AstNode::LIST(_) => true, _ => false, } } pub fn is_var(&self) -> bool { match &self { AstNode::VAR(_) => true, _ => false, } } pub fn is_list_compre(&self) -> bool { match &self { AstNode::COMPRE { expr: _, var: _, iter_expr: _, } => true, _ => false, } } }
true
6771e7db1d54a3c77ef5d2ed8eaaa57a7cfecb70
Rust
rbizos/prombe
/src/http.rs
UTF-8
533
2.515625
3
[ "Apache-2.0" ]
permissive
use crate::traits::Transport; use crate::utils::Result; use async_trait::async_trait; use reqwest::get; pub struct HttpTransport {} #[async_trait] impl Transport for HttpTransport { async fn get(&self, uri: &str) -> Result<String> { match get(uri).await?.error_for_status()?.text().await { Ok(text) => Ok(text), Err(e) => Err(Box::new(e)), } } } /* timeout can be implemented with select and tokio::time::timeout or tokio::time::sleep should return => io::ErrorKind::TimedOut, */
true
a2b7cd7707531fc4f0490ac8fd31d8785c8f9ab9
Rust
clarkmoody/raytrace
/src/material/lambertian.rs
UTF-8
823
2.765625
3
[]
no_license
use rand::distributions::Uniform; use rand::rngs::ThreadRng; use super::{Material, Scatter}; use crate::hittable::Record; use crate::ray::Ray; use crate::vec::{Color, Vec3}; pub struct Lambertian { albedo: Color, } impl Lambertian { pub fn new(albedo: Color) -> Self { Self { albedo } } } impl Material for Lambertian { fn scatter( &self, _r: &Ray, hit: &Record, vec_dist: &Uniform<f64>, rng: &mut ThreadRng, ) -> Option<Scatter> { let mut scatter_direction = hit.normal + Vec3::random_unit(vec_dist, rng); if scatter_direction.near_zero() { scatter_direction = hit.normal; } Some(Scatter { ray: Ray::new(hit.point, scatter_direction), attenuation: self.albedo, }) } }
true
a39a8bcefc57cd0f5b076abf5bdcafaf5ef1d149
Rust
mslipper/lighthouse
/account_manager/src/main.rs
UTF-8
3,420
2.515625
3
[ "Apache-2.0" ]
permissive
use bls::Keypair; use clap::{App, Arg, SubCommand}; use slog::{debug, info, o, Drain}; use std::path::PathBuf; use types::test_utils::generate_deterministic_keypair; use validator_client::Config as ValidatorClientConfig; fn main() { // Logging let decorator = slog_term::TermDecorator::new().build(); let drain = slog_term::CompactFormat::new(decorator).build().fuse(); let drain = slog_async::Async::new(drain).build().fuse(); let log = slog::Logger::root(drain, o!()); // CLI let matches = App::new("Lighthouse Accounts Manager") .version("0.0.1") .author("Sigma Prime <contact@sigmaprime.io>") .about("Eth 2.0 Accounts Manager") .arg( Arg::with_name("datadir") .long("datadir") .value_name("DIR") .help("Data directory for keys and databases.") .takes_value(true), ) .subcommand( SubCommand::with_name("generate") .about("Generates a new validator private key") .version("0.0.1") .author("Sigma Prime <contact@sigmaprime.io>"), ) .subcommand( SubCommand::with_name("generate_deterministic") .about("Generates a deterministic validator private key FOR TESTING") .version("0.0.1") .author("Sigma Prime <contact@sigmaprime.io>") .arg( Arg::with_name("validator index") .long("index") .short("i") .value_name("index") .help("The index of the validator, for which the test key is generated") .takes_value(true) .required(true), ), ) .get_matches(); let config = ValidatorClientConfig::parse_args(&matches, &log) .expect("Unable to build a configuration for the account manager."); // Log configuration info!(log, ""; "data_dir" => &config.data_dir.to_str()); match matches.subcommand() { ("generate", Some(_gen_m)) => { let keypair = Keypair::random(); let key_path: PathBuf = config .save_key(&keypair) .expect("Unable to save newly generated private key."); debug!( log, "Keypair generated {:?}, saved to: {:?}", keypair.identifier(), key_path.to_string_lossy() ); } ("generate_deterministic", Some(gen_d_matches)) => { let validator_index = gen_d_matches .value_of("validator index") .expect("Validator index required.") .parse::<u64>() .expect("Invalid validator index.") as usize; let keypair = generate_deterministic_keypair(validator_index); let key_path: PathBuf = config .save_key(&keypair) .expect("Unable to save newly generated deterministic private key."); debug!( log, "Deterministic Keypair generated {:?}, saved to: {:?}", keypair.identifier(), key_path.to_string_lossy() ); } _ => panic!( "The account manager must be run with a subcommand. See help for more information." ), } }
true
d2bf9bf16e122ba4609561bff4b82b3cb18ed0b4
Rust
Hirevo/apple-music-jwt
/src/error.rs
UTF-8
1,287
2.75
3
[]
no_license
use std::convert::TryInto; use std::error; use std::fmt; use std::io; #[derive(Debug)] pub enum Error { IOError(io::Error), JWTError(jwt::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::IOError(err) => err.fmt(f), Error::JWTError(err) => err.fmt(f), } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::IOError(err) => err.source(), Error::JWTError(err) => err.source(), } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IOError(err) } } impl From<jwt::Error> for Error { fn from(err: jwt::Error) -> Error { Error::JWTError(err) } } impl TryInto<io::Error> for Error { type Error = (); fn try_into(self) -> Result<io::Error, Self::Error> { match self { Error::IOError(err) => Ok(err), _ => Err(()), } } } impl TryInto<jwt::Error> for Error { type Error = (); fn try_into(self) -> Result<jwt::Error, Self::Error> { match self { Error::JWTError(err) => Ok(err), _ => Err(()), } } }
true
d63c8917317c0e2e29ffa9d3dd94b8beb479e360
Rust
darshanparajuli/AdventOfCode2018
/src/bin/day7.rs
UTF-8
5,364
2.828125
3
[]
no_license
extern crate aoc; use std::cmp::Ordering; use std::collections::hash_map::Entry; use std::collections::{BinaryHeap, HashMap, HashSet}; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufReader}; #[derive(Debug, PartialEq, Eq, Hash)] struct Step(char); impl Step { fn work_time(&self) -> usize { 60 + self.0 as usize - 65 + 1 } } impl fmt::Display for Step { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl PartialOrd for Step { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Step { fn cmp(&self, other: &Step) -> Ordering { other.0.cmp(&self.0) } } fn main() -> Result<(), io::Error> { let arg = aoc::get_cmdline_arg()?; let steps = BufReader::new(File::open(arg)?) .lines() .map(|line| line.unwrap()) .map(|line| { let must_be_finished = line[5..6].parse::<char>().unwrap(); let before = line[36..37].parse::<char>().unwrap(); (Step(must_be_finished), Step(before)) }) .collect::<Vec<_>>(); let mut map: HashMap<&Step, Vec<&Step>> = HashMap::new(); let mut map_inv: HashMap<&Step, HashSet<&Step>> = HashMap::new(); for (m, b) in &steps { match map.entry(m) { Entry::Occupied(ref mut o) => { o.get_mut().push(b); } Entry::Vacant(v) => { v.insert(vec![b]); } } match map_inv.entry(b) { Entry::Occupied(ref mut o) => { o.get_mut().insert(m); } Entry::Vacant(v) => { let mut set = HashSet::new(); set.insert(m); v.insert(set); } } } part1(&map, &map_inv); part2(&map, &map_inv, 5); Ok(()) } fn part1(map: &HashMap<&Step, Vec<&Step>>, map_inv: &HashMap<&Step, HashSet<&Step>>) { let mut available = BinaryHeap::new(); for (k, _) in map.iter() { if !map_inv.contains_key(k) { available.push(k); } } let mut output = String::new(); let mut completed = HashSet::new(); let mut tmp = HashSet::new(); while !available.is_empty() { let mut a = available.pop().unwrap(); tmp.clear(); loop { let mut completed_previous = true; if let Some(prev_steps) = map_inv.get(a) { for i in prev_steps { if !completed.contains(i) { completed_previous = false; break; } } } if completed_previous { break; } else { if available.is_empty() { break; } else { tmp.insert(a); a = available.pop().unwrap(); } } } for i in &tmp { available.push(i); } if !completed.contains(a) { output.push(a.0.to_owned()); } completed.insert(a); if let Some(steps) = map.get(a) { for s in steps { available.push(s); } } } println!("part 1: {}", output); } fn part2( map: &HashMap<&Step, Vec<&Step>>, map_inv: &HashMap<&Step, HashSet<&Step>>, worker_count: usize, ) { let mut finished: HashSet<&Step> = HashSet::new(); let mut workers: HashMap<&Step, usize> = HashMap::new(); let mut available = BinaryHeap::new(); for (k, _) in map.iter() { if !map_inv.contains_key(k) { available.push(k); if workers.len() < worker_count { workers.insert(k, 0); } } } let mut count = 0; while !workers.is_empty() { workers.retain(|k, v| { if *v == k.work_time() { finished.insert(k); false } else { *v += 1; true } }); while workers.len() < worker_count { let mut tmp = vec![]; let mut found = false; while let Some(a) = available.pop() { let mut finished_previous = true; if let Some(prev_steps) = map_inv.get(a) { for i in prev_steps { if !finished.contains(i) { finished_previous = false; break; } } } if finished_previous { workers.insert(a, 1); found = true; if let Some(steps) = map.get(a) { for s in steps { available.push(s); } } break; } else { tmp.push(a); } } for a in tmp { available.push(a); } if !found { break; } } if !workers.is_empty() { count += 1; } } println!("part 2: {}", count); }
true
f37f9810273ab4214cf8bff4224db0884102320d
Rust
harrydevnull/AdeventCodeInRust
/day1/src/main.rs
UTF-8
583
3.3125
3
[]
no_license
use std::io::prelude::*; use std::fs::File; use std::io::Error; fn main() { let s = read_file_string().unwrap(); println!("diff is! {}",count(&s).unwrap()); } fn count(str:&str)->Result<usize,Error>{ //let mut lvec = Vec::new(); let lvec:Vec<char> = str.chars().into_iter().filter(|x| *x == '(').collect(); let rvec:Vec<char> = str.chars().into_iter().filter(|x| *x == ')').collect(); Ok((lvec.len()-rvec.len())) } fn read_file_string()-> Result<String, Error>{ let mut s = String::new(); let mut f = try!(File::open("foo.txt")); try!(f.read_to_string(&mut s)); Ok((s)) }
true
38d766e8350775ce93a6dd14cbccab6c7f4d00e6
Rust
ivardb/AdventOfCode2020
/src/days/day24/mod.rs
UTF-8
2,112
3.421875
3
[]
no_license
pub mod part1; pub mod part2; pub fn run() { part1::run(); part2::run(); } pub fn default_input() -> &'static str { include_str!("input") } pub fn parse_input(input : &str) -> Vec<Vec<Direction>> { input.lines().map(|l| { let mut chars = l.chars(); let mut nxt = chars.next(); let mut res = Vec::new(); while nxt.is_some() { res.push(match nxt.unwrap() { 'e' => Direction::East, 'n' => { match chars.next().unwrap() { 'e' => Direction::NorthEast, _ => Direction::NorthWest, } } 's' => { match chars.next().unwrap() { 'e' => Direction::SouthEast, _ => Direction::SouthWest, } } _ => Direction::West, }); nxt = chars.next(); } res }).collect() } #[derive(Clone, Copy, Hash, Eq, PartialEq)] pub enum Direction { East, SouthEast, SouthWest, West, NorthWest, NorthEast, } impl Direction { pub fn to_point(&self) -> Point { match self { Direction::East => Point {x: 1, y: -1, z: 0}, Direction::SouthEast => Point {x: 0, y: -1, z: 1}, Direction::SouthWest => Point {x: -1, y: 0, z: 1}, Direction::West => Point {x: -1, y: 1, z: 0}, Direction::NorthWest => Point {x: 0, y: 1, z: -1}, Direction::NorthEast => Point {x: 1, y: 0, z: -1}, } } pub fn all() -> Vec<Direction> { vec![Direction::East, Direction::SouthWest, Direction::SouthEast, Direction::West, Direction::NorthWest, Direction::NorthEast] } } #[derive(Clone, Copy, Hash, Eq, PartialEq)] pub struct Point { pub x: i64, pub y:i64, pub z:i64 } impl Point { pub fn add(&self, other : Point) -> Self { Point { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, } } }
true
b00946e3a2279e5cd85f3389b56746578449bacd
Rust
EdgyEdgemond/advent_of_code
/2021/src/day08.rs
UTF-8
4,229
3.421875
3
[]
no_license
use anyhow::anyhow; use itertools::Itertools; use std::collections::HashMap; pub fn question_one(inputs: &Vec<(Vec<String>, Vec<String>)>) -> anyhow::Result<i32> { let mut total: i32 = 0; for input in inputs { let c = input.1.iter().map(|o| o.len() as i32).filter(|l| [2, 3, 4, 7].contains(&l)).count(); total += c as i32; } Ok(total) } pub fn question_two(inputs: &Vec<(Vec<String>, Vec<String>)>) -> anyhow::Result<i32> { let mut total: i32 = 0; for input in inputs { let mut digits: Vec<String> = input.0.iter().map(|d| d.chars().sorted().collect::<String>()).collect(); digits.sort_by(|a, b| a.len().cmp(&b.len())); let mut map: HashMap<&str, char> = HashMap::new(); let one = digits[0].as_str(); let four = digits[2].as_str(); let seven = digits[1].as_str(); let eight = digits[9].as_str(); map.insert(one, '1'); map.insert(four, '4'); map.insert(seven, '7'); map.insert(eight, '8'); // 3 is the five char code that contains digit 7 let three = digits .iter() .filter(|d| d.len() == 5 && seven.chars().map(|c|d.contains(c)).all(|x| x)) .next() .ok_or_else(|| anyhow!("can not find 3"))? .as_str(); map.insert(three, '3'); // 9 is the combo of 4 and 3 let mut nine = String::new(); nine.push_str(three); nine.push_str(four); nine = nine .chars() .sorted() .dedup() .collect::<String>(); map.insert(nine.as_str(), '9'); // 2 is the five char code missing the same segment as 9 let lower_left = eight .chars() .filter(|c| !nine.contains(*c)) .next() .ok_or_else(|| anyhow!("can not find lower left segment."))?; let two = digits .iter() .filter(|d| d.len() == 5 && d.contains(lower_left)) .next() .ok_or_else(|| anyhow!("can not find 2"))? .as_str(); map.insert(two, '2'); // 5 is the only remaining 5 char code let five = digits .iter() .filter(|d| d.len() == 5 && !map.contains_key((*d.clone()).as_str())) .next() .ok_or_else(|| anyhow!("can not find 5"))? .as_str(); map.insert(five, '5'); // 6 is the six char code missing upper right segment let upper_right = one .chars() .filter(|c| !five.contains(*c)) .next() .ok_or_else(|| anyhow!("can not find upper right segment."))?; let six = digits .iter() .filter(|d| d.len() == 6 && !d.contains(upper_right)) .next() .ok_or_else(|| anyhow!("can not find 6"))? .as_str(); map.insert(six, '6'); // Only 0 left let zero = digits .iter() .filter(|d| !map.contains_key((*d.clone()).as_str())) .next() .ok_or_else(|| anyhow!("can not find 0"))? .as_str(); map.insert(zero, '0'); let output = input.1 .iter() .map(|o| o.chars().sorted().collect::<String>()) .map(|o| map[o.as_str()]) .collect::<String>(); let value: i32 = output.parse()?; total += value; } Ok(total) } pub fn get_input(path: &str) -> anyhow::Result<Vec<(Vec<String>, Vec<String>)>> { Ok(std::fs::read_to_string(path)? .lines() .map(|l| l.split('|').collect::<Vec<&str>>()) .map(|p| ( p[0].to_string().split_whitespace().map(|p| p.to_string()).collect::<Vec<String>>(), p[1].to_string().split_whitespace().map(|p| p.to_string()).collect::<Vec<String>>(), ) ) .collect::<Vec<(Vec<String>, Vec<String>)>>()) } fn run() -> anyhow::Result<()> { let input = get_input("input/day08.txt")?; println!("D8Q1: {}", question_one(&input)?); println!("D8Q2: {}", question_two(&input)?); Ok(()) } pub fn main() { if let Err(e) = run() { panic!("{:?}", e); } }
true
1262bc00f8b00a541bb2a2179ccef737e36923d5
Rust
crazyzh1984/linkerd2-proxy
/linkerd/stack/src/future_service.rs
UTF-8
1,552
2.59375
3
[ "Apache-2.0" ]
permissive
use futures::{ready, TryFuture, TryFutureExt}; use linkerd2_error::Error; use std::pin::Pin; use std::task::{Context, Poll}; /// Implements a `Service` from a `Future` that produces a `Service`. #[derive(Debug)] pub struct FutureService<F, S> { inner: Inner<F, S>, } #[derive(Debug)] enum Inner<F, S> { Future(F), Service(S), } // === impl FutureService === impl<F, S> FutureService<F, S> { pub fn new(fut: F) -> Self { Self { inner: Inner::Future(fut), } } } impl<F, S, Req> tower::Service<Req> for FutureService<F, S> where F: TryFuture<Ok = S> + Unpin, F::Error: Into<Error>, S: tower::Service<Req>, S::Error: Into<Error>, { type Response = S::Response; type Error = Error; type Future = futures::future::MapErr<S::Future, fn(S::Error) -> Error>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { loop { self.inner = match self.inner { Inner::Future(ref mut fut) => { let fut = Pin::new(fut); let svc = ready!(fut.try_poll(cx).map_err(Into::into)?); Inner::Service(svc) } Inner::Service(ref mut svc) => return svc.poll_ready(cx).map_err(Into::into), }; } } fn call(&mut self, req: Req) -> Self::Future { if let Inner::Service(ref mut svc) = self.inner { return svc.call(req).map_err(Into::into); } panic!("Called before ready"); } }
true
927357cb37c6211b11504e11d5235b20ec2e9921
Rust
vbkaisetsu/prima-undine
/prima_undine/src/graph.rs
UTF-8
7,410
2.734375
3
[]
no_license
use std::cell::{Cell, Ref, RefCell, RefMut}; use std::cmp; use std::cmp::{Ordering, Reverse}; use std::collections::{BinaryHeap, HashSet, VecDeque}; use std::rc::Rc; use crate::operators as op; use crate::{Device, Operator, Parameter, Shape, Tensor}; struct NodeData<'dev> { value: RefCell<Tensor<'dev>>, gradient: RefCell<Tensor<'dev>>, } struct DataRef<'arg, 'dev> where 'dev: 'arg, { op: Rc<OperatorInfo<'arg, 'dev>>, vid: usize, } struct OperatorInfo<'arg, 'dev> { operator: Box<dyn Operator<'arg, 'dev> + 'arg>, args: Vec<DataRef<'arg, 'dev>>, rets: Vec<NodeData<'arg>>, forwarded: Cell<bool>, depth: usize, } struct OperatorInfoCmp<'arg, 'dev>(Rc<OperatorInfo<'arg, 'dev>>); impl<'arg, 'dev> PartialEq for OperatorInfoCmp<'arg, 'dev> { fn eq(&self, other: &Self) -> bool { self.0.depth == other.0.depth } } impl<'arg, 'dev> Eq for OperatorInfoCmp<'arg, 'dev> {} impl<'arg, 'dev> Ord for OperatorInfoCmp<'arg, 'dev> { fn cmp(&self, other: &Self) -> Ordering { self.0.depth.cmp(&other.0.depth) } } impl<'arg, 'dev> PartialOrd for OperatorInfoCmp<'arg, 'dev> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.0.depth.cmp(&other.0.depth)) } } pub struct Node<'arg, 'dev> { data: DataRef<'arg, 'dev>, } impl<'arg, 'dev> OperatorInfo<'arg, 'dev> { fn new<T: Operator<'arg, 'dev> + 'arg>( op: T, xs: &[&Node<'arg, 'dev>], ) -> OperatorInfo<'arg, 'dev> { let arg_shapes = xs .iter() .map(|x| x.inner_value().shape) .collect::<Vec<Shape>>(); let ret_shapes = op.forward_shape(&arg_shapes); let args = xs .iter() .map(|x| DataRef { op: Rc::clone(&x.data.op), vid: x.data.vid, }) .collect::<Vec<DataRef<'arg, 'dev>>>(); let rets = ret_shapes .into_iter() .map(|s| NodeData { value: RefCell::new(op.device().new_tensor(s)), gradient: RefCell::new(op.device().new_tensor(s)), }) .collect::<Vec<NodeData>>(); let depth = xs.iter().map(|x| x.data.op.depth).fold(0, cmp::max) + 1; OperatorInfo { operator: Box::new(op), args: args, rets: rets, forwarded: Cell::new(false), depth: depth, } } } fn forward<'arg, 'dev>(op_info: Rc<OperatorInfo<'arg, 'dev>>) { let mut reached = HashSet::new(); let mut queue = VecDeque::new(); let mut forward_req = BinaryHeap::new(); queue.push_back(op_info); while let Some(op_info) = queue.pop_front() { for arg in &op_info.args { let ptr = &*arg.op as *const OperatorInfo<'arg, 'dev>; if !reached.contains(&ptr) { queue.push_back(Rc::clone(&arg.op)); reached.insert(ptr); } } forward_req.push(Reverse(OperatorInfoCmp(op_info))); } while let Some(Reverse(OperatorInfoCmp(op_info))) = forward_req.pop() { if op_info.forwarded.get() { continue; } op_info.forwarded.set(true); let xs = op_info .args .iter() .map(|data| data.op.rets[data.vid].value.borrow()) .collect::<Vec<Ref<Tensor<'arg>>>>(); let mut ys = op_info .rets .iter() .map(|ret| ret.value.borrow_mut()) .collect::<Vec<RefMut<Tensor<'arg>>>>(); let xs_ref = xs.iter().map(|x| &**x).collect::<Vec<&Tensor<'arg>>>(); let mut ys_ref = ys .iter_mut() .map(|y| &mut **y) .collect::<Vec<&mut Tensor<'arg>>>(); op_info.operator.forward(&xs_ref, &mut ys_ref); } } fn backward<'arg, 'dev>(op_info: Rc<OperatorInfo<'arg, 'dev>>) { let mut reached = HashSet::new(); let mut queue = VecDeque::new(); let mut backward_req = BinaryHeap::new(); { for ret in &op_info.rets { let mut grad = ret.gradient.borrow_mut(); grad.alloc(); grad.reset(1.); } } queue.push_back(op_info); while let Some(op_info) = queue.pop_front() { for arg in &op_info.args { let ptr = &*arg.op as *const OperatorInfo<'arg, 'dev>; if !reached.contains(&ptr) { queue.push_back(Rc::clone(&arg.op)); reached.insert(ptr); } } backward_req.push(OperatorInfoCmp(op_info)); } while let Some(OperatorInfoCmp(op_info)) = backward_req.pop() { let xs = op_info .args .iter() .map(|data| data.op.rets[data.vid].value.borrow()) .collect::<Vec<Ref<Tensor<'arg>>>>(); let ys = op_info .rets .iter() .map(|ret| ret.value.borrow()) .collect::<Vec<Ref<Tensor<'arg>>>>(); let gys = op_info .rets .iter() .map(|ret| ret.gradient.borrow()) .collect::<Vec<Ref<Tensor<'arg>>>>(); let gxs = op_info .args .iter() .map(|data| { let mut gx = data.op.rets[data.vid].gradient.borrow_mut(); if !gx.valid() { gx.alloc(); gx.reset(0.); } &data.op.rets[data.vid].gradient }) .collect::<Vec<&RefCell<Tensor<'arg>>>>(); let xs_ref = xs.iter().map(|x| &**x).collect::<Vec<&Tensor<'arg>>>(); let ys_ref = ys.iter().map(|y| &**y).collect::<Vec<&Tensor<'arg>>>(); let gys_ref = gys.iter().map(|gy| &**gy).collect::<Vec<&Tensor<'arg>>>(); op_info.operator.backward(&xs_ref, &ys_ref, &gys_ref, &gxs); } } impl<'arg, 'dev> Node<'arg, 'dev> { pub fn create<T: Operator<'arg, 'dev> + 'arg>( op: T, xs: &[&Node<'arg, 'dev>], ) -> Vec<Node<'arg, 'dev>> { let op_info = Rc::new(OperatorInfo::new(op, xs)); (0..op_info.rets.len()) .map(|i| Node { data: DataRef { op: Rc::clone(&op_info), vid: i, }, }) .collect::<Vec<Node<'arg, 'dev>>>() } pub fn inner_value(&self) -> Ref<Tensor> { self.data.op.rets[self.data.vid].value.borrow() } pub fn inner_gradient(&self) -> Ref<Tensor> { self.data.op.rets[self.data.vid].gradient.borrow() } pub fn device(&self) -> &'dev Device<'dev> { self.data.op.operator.device() } pub fn forward(&self) { forward(Rc::clone(&self.data.op)); } pub fn backward(&self) { self.forward(); backward(Rc::clone(&self.data.op)); } } impl<'arg, 'dev> From<&'arg Tensor<'dev>> for Node<'arg, 'dev> { fn from(item: &'arg Tensor<'dev>) -> Self { Node::create(op::Input::new(item), &[]).pop().unwrap() } } impl<'arg, 'dev> From<Tensor<'dev>> for Node<'arg, 'dev> { fn from(item: Tensor<'dev>) -> Self { Node::create(op::InputOwner::new(item), &[]).pop().unwrap() } } impl<'arg, 'dev> From<&'arg mut Parameter<'dev>> for Node<'arg, 'dev> { fn from(item: &'arg mut Parameter<'dev>) -> Self { Node::create(op::Parameter::new(item), &[]).pop().unwrap() } }
true
3cf3a66000b07f82c0405b7230a91b488141debf
Rust
sjb3d/aoc2020
/src/day13.rs
UTF-8
1,223
2.921875
3
[ "Unlicense" ]
permissive
use num::integer::*; fn wait_time(ts: usize, id: usize) -> usize { let r = ts % id; if r == 0 { 0 } else { id - r } } pub fn run() { let text = std::fs::read_to_string("input/day13.txt").unwrap(); let mut lines = text.lines(); let start_ts = lines.next().unwrap().parse::<usize>().unwrap(); let ids: Vec<_> = lines .next() .unwrap() .split(',') .enumerate() .filter(|&(_, s)| s != "x") .map(|(i, s)| (i, s.parse::<usize>().unwrap())) .map(|(rem, id)| (rem % id, id)) .collect(); let mut depart_wait = usize::MAX; let mut depart_id = 0; for &(_, id) in ids.iter() { let wait = wait_time(start_ts, id); if wait < depart_wait { depart_wait = wait; depart_id = id; } } println!( "day13: product is {} * {} = {}", depart_wait, depart_id, depart_wait * depart_id ); let mut ts = 0; let mut tmp_lcm = 1; for &(rem, id) in ids.iter() { while (ts + rem) % id != 0 { ts += tmp_lcm; } tmp_lcm = lcm(tmp_lcm, id); } println!("day13: timestamp is {}", ts); }
true
83a9c363143ee60f6e34316123ae5df68ea98ad3
Rust
stadust/pointercrate
/pointercrate-demonlist/src/player/claim/get.rs
UTF-8
2,430
2.6875
3
[ "MIT" ]
permissive
use crate::{ error::{DemonlistError, Result}, player::{claim::PlayerClaim, DatabasePlayer}, }; use sqlx::PgConnection; pub struct ClaimBy { pub player: DatabasePlayer, pub verified: bool, pub lock_submissions: bool, } impl PlayerClaim { pub async fn verified_claim_on(player_id: i32, connection: &mut PgConnection) -> Result<Option<PlayerClaim>> { match sqlx::query!( "SELECT member_id, lock_submissions FROM player_claims WHERE player_id = $1 AND verified", player_id ) .fetch_one(connection) .await { Ok(row) => Ok(Some(PlayerClaim { user_id: row.member_id, player_id, verified: true, lock_submissions: row.lock_submissions, })), Err(sqlx::Error::RowNotFound) => Ok(None), Err(err) => Err(err.into()), } } pub async fn by_user(user_id: i32, connection: &mut PgConnection) -> Result<Option<ClaimBy>> { match sqlx::query!( r#"SELECT verified, lock_submissions, player_id, players.name::text as "name!", players.banned FROM player_claims INNER JOIN players ON player_id=players.id WHERE member_id = $1"#, user_id ) .fetch_one(connection) .await { Ok(row) => Ok(Some(ClaimBy { player: DatabasePlayer { id: row.player_id, name: row.name, banned: row.banned, }, verified: row.verified, lock_submissions: row.lock_submissions })), Err(sqlx::Error::RowNotFound) => Ok(None), Err(err) => Err(err.into()), } } pub async fn get(member_id: i32, player_id: i32, connection: &mut PgConnection) -> Result<PlayerClaim> { match PlayerClaim::by_user(member_id, connection).await? { Some(claim) if claim.player.id == player_id => Ok(PlayerClaim { user_id: member_id, player_id, verified: claim.verified, lock_submissions: claim.lock_submissions, }), _ => Err(DemonlistError::ClaimNotFound { member_id, player_id }), } } }
true
d0bedff8a16bffa402ef5d7bfd00ee6b50132474
Rust
tldrd0117/rustExample
/ownership/src/main.rs
UTF-8
6,506
3.640625
4
[]
no_license
//소유권 규칙 //1. 러스트의 각각의 값은 해당값의 오너(owner)라고 불리우는 변수를 갖고 있다. //2. 한번에 딱 하나의 오너만 존재할 수 있다. //3. 오너가 스코프 밖으로 벗어나는 때, 값은 버려진다.(dropped). fn main() { scope(); stringType(); copy(); moveFn(); clone(); ownershipAndFunction(); returnAndScope(); need_to_be_passed_back_and_use_again(); } fn scope(){ //s는 유효하지 않는다. 아직 선언이 안됐음. let s = "hello"; //s는 이 지점부터 유효합니다. //s흫 가지고 뭔가 합니다. // 이스코프틑 이제 끝이므로 s는 더이상 유효하지 않습니다. } //스트링 리터럴의 경우, 텍스트가 최종 실행파일에 직접 하드코딩 되고, 이렇게 하면 스트링 리터럴이 빠르고 효율적이 됩니다. //불행하게도, 컴파일 타임에 크기를 알 수 없는 경우 및 실행 중 크기가 변할 수도 있는 경우는 텍스트 조각을 바이너리 파일에 접어넣을 수 없습니다. //String 타입은 변경 가능하고 커질 수 있는 텍스트를 지원하기 위해 만들어졌고, 우리는 힙에서 컴파일 타임에는 알 수 없는 어느 정도 //크기의 메모리 공간을 할당받아 내용물을 저장할 필요가 있습니다. //1. 런타임에 운영체제로부터 메모리가 요청되어야 한다. //2. String의 사용이 끝났을 떄 운영체제에게 메모리를 반납할 방법이 필요하다. //첫번째는 우리가 직접 수행합니다. 우리가 String::from을 호출하면, 구현부분에서 필요한 만큼의 메모리를 요청합니다. //두번쨰는 가비지콜렉터(GC)를 갖고 있는 언어들의 경우, GC가 더이상 사용하지 않는 메모리 조각을 계속해서 찾고 지워주며, //우리는 프로그래머로서 이와 관련한 생각을 안해도 됩니다. //GC가 없을 경우, 할당받은 메모리가 더 필요없는 시점을 알아서 명시적으로 이를 반납하는 코드를 호출하는 것은 프로그래머의 //책임입니다. //러스트는 다른 방식으로 이 문제를 다룹니다. 메모리는 변수가 소속되어 있는 스코프 밖으로 벗어나는 순간 자동으로 반납됩니다. fn stringType(){ let s = String::from("hello"); let mut s = String::from("hello"); s.push_str(", world"); //push_str()은 해당 스트링 리터럴을 스트링에 붙여줍니다. println!("{}", s); } //스택에만 있는 데이터: 복사 fn copy(){ let x = 5; let y = x; // 이경우 고정된 크기의 단순한 값이기 떄문에 5라는 값들은 스택에 푸쉬됩니다. // 정수형과 같이 커뮤ㅏ일 타임에 결정되어 있는 크기의 타입은 스택에 모두 저장되기 떄문에, 실제 값의 // 복사본이 빠르게 만들어질 수 있습니다. 이는 변수 y가 생성된 후에 x가 더 이상 유효하지 않도록 해야할 이유가 // 없다는 뜻입니다. println!("x = {}, y = {}", x, y); } //변수와 데이터가 상호작용하는 방법: 이동(move) fn moveFn(){ let s1 = String::from("hello"); let s2 = s1; println!("{}, world!", s2); // 이경우 러스트는 얕은 복사와 깊은복사와 같은 개념으로 동작하지 않고 // 첫번째 변수(s1)를 무효화 하고 두번 째 변수(s2)가 hello를 가리키게 된다. // 이를 얕은 복사라고 부르든 대신 move라고 말합니다. } //변수와 데이터가 상호작용하는 방법: 클론(clone) fn clone(){ let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {}, s2 = {}", s1, s2); // 깊은 복사와 같은 개념으로 동작한다. } // 소유권과 함수 fn ownershipAndFunction(){ let s = String::from("hello"); // s가 스코프 안으로 들어왔습니다. takes_ownership(s); // s의 값이 함수 안으로 이동했습니다. // 그리고 이제 더이상 유효하지 않습니다. let x = 5; // x가 스코프 안으로 들어왔습니다. makes_copy(x); // x가 함수 안으로 이동했습니다만, // i32는 Copy가 되므로, x를 이후에 계속 // 사용해도 됩니다. } //여기서 x는 스코프 밖으로 나가고, s도 그 후 나갑니다. 하지만 s는 이미 이동되었으므로, //별다른 일이 발생하지 않습니다. fn takes_ownership(some_string: String){ //some_string이 스코프 안으로 들어왔습니다. println!("{}", some_string); } //여기서 some_string이 스코프 밖으로 벗어났고 `drop`이 호출됩니다. 메모리는 //해제되었습니다. fn makes_copy(some_integer: i32){ //some_integer이 스코프 안으로 들어왔습니다. println!("{}", some_integer); } //여기서 some_integer가 스코프 밖으로 벗어났습니다. 별다른 일은 발생하지 않습니다. // 반환값과 스코프 fn returnAndScope(){ let s1 = gives_ownership(); //gives_ownership은 반환값을 s1에게 이동시킵니다. let s2 = String::from("hello"); //s2가 스코프 안에 들어왔습니다. let s3 = takes_and_gives_back(s2); //s2는 takes_and_gives_back 안으로 이동되었고, //이 함수가 반환값을 s3으로도 이동시켰습니다. } // 여기서 s3는 스코프 밖으로 벗어났으며 drop이 호출됩니다. s2는 스코프 밖으로 벗어났지만 // 이동되었으므로 아무 일도 일어나지 않습니다. // s1은 스코프 밖으로 벗어나서 drop이 호출됩니다. fn gives_ownership() -> String{ let some_string = String::from("hello"); some_string } fn takes_and_gives_back(a_string: String) -> String { a_string } fn need_to_be_passed_back_and_use_again(){ let s1 = String::from("hello"); let (s2, len) = calculate_length(s1); //이건 너무 많이 나간 의례절차고 일반적인 개념로서는 과한 작업이 됩니다. //러스트는 이를 위한 기능을 갖고 있으며, 참조자라고 부릅니다. println!("The length of '{}' is {}.", s2, len); } fn calculate_length(s: String) -> (String, usize){ let length = s.len(); (s, length) }
true
9f4734d23a011b124bad85d79b1b7e87845114a5
Rust
Daspien27/Advent-of-Code-2020
/src/day7.rs
UTF-8
4,414
3
3
[]
no_license
use regex::Regex; use std::collections::HashMap; #[derive(Debug)] pub struct Bag { contents : Option<Vec<(u64, String)>> } #[aoc_generator(day7)] pub fn input_generator(input: &str) -> HashMap<String,Bag> { lazy_static! { static ref BAGS_RE : Regex = Regex::new(r"(?P<bag_type>\w+ \w+) bags contain (?P<contents>(:?(:?(:?\d+ \w+ \w+ bags?)(:?, )?)+)|(:?no other bags))").unwrap(); static ref CONTENTS_RE : Regex = Regex::new(r"(?P<quantity>\d+) (?P<bag_type>\w+ \w+) bags?").unwrap(); } BAGS_RE.captures_iter(input) .map(|cap|{ let bag_type = String::from(cap.name("bag_type").unwrap().as_str()); let contents_str = cap.name("contents").unwrap().as_str(); match contents_str { "no other bags" => (bag_type, Bag{contents: None}), _ => { let content : Vec<_> = CONTENTS_RE.captures_iter(contents_str) .map(|cap|{ (cap.name("quantity").unwrap().as_str().parse().unwrap(), String::from(cap.name("bag_type").unwrap().as_str())) }) .collect(); (bag_type, Bag{contents : Some(content)}) } } }) .collect() } #[aoc(day7, part1)] pub fn solve_part1(input: &HashMap<String, Bag>) -> u64 { let mut can_contain_shiny_gold_bag: HashMap<&str, Option<bool>> = input.iter().map(|(k, _v)| (k.as_str(), None)).collect(); *can_contain_shiny_gold_bag.get_mut("shiny gold").unwrap() = Some(true); while can_contain_shiny_gold_bag.iter().find(|(_, v)| v.is_none()).is_some() { input.iter().for_each(|(k, v)| { if can_contain_shiny_gold_bag.get(k.as_str()).unwrap().is_none() { let can_contain = match &v.contents { Some(contents) => { if contents.iter().any(|(_, bag_type)|{ Some(true) == *can_contain_shiny_gold_bag.get(bag_type.as_str()).unwrap() }) { Some(true) } else if contents.iter().all(|(_, bag_type)|{ Some(false) == *can_contain_shiny_gold_bag.get(bag_type.as_str()).unwrap() }) { Some(false) } else { return; } }, None => { Some(false) } }; *can_contain_shiny_gold_bag.get_mut(k.as_str()).unwrap() = can_contain; } }); } can_contain_shiny_gold_bag.iter().map(|(_, c)| -> u64 { match c { Some(true) => 1, Some(false) => 0, None => panic!("Bad code") } }) .sum::<u64>() - 1 } #[aoc(day7, part2)] pub fn solve_part2(input: &HashMap<String, Bag>) -> u64 { let mut amount_of_nested_bags: HashMap<&str, Option<u64>> = input.iter().map(|(k, _v)| (k.as_str(), None)).collect(); while amount_of_nested_bags.get("shiny gold").unwrap().is_none() { input.iter().for_each(|(k, v)| { if amount_of_nested_bags.get(k.as_str()).unwrap().is_none() { let amount_nested = match &v.contents { Some(contents) => { contents.iter().fold(Some(0u64), |acc, (amount, bag_type)|{ acc.and_then(|acc| { amount_of_nested_bags.get(bag_type.as_str()).unwrap().and_then(|num|{ Some(acc + num * amount) }) }) }) }, None => { Some(0u64) } }; *amount_of_nested_bags.get_mut(k.as_str()).unwrap() = amount_nested.map(|v| v + 1); // add 1 for the bag itself } }); } amount_of_nested_bags.get("shiny gold").unwrap().unwrap() - 1 //exclude the shiny gold bag } #[cfg(test)] mod tests { }
true
fe6f3756342a5b8a698d48594057f827aa9b027c
Rust
nao-kobayashi/tokio_practice
/sleepus_async/src/main.rs
UTF-8
745
2.984375
3
[]
no_license
use async_std::task::{ sleep, spawn }; use std::time::Duration; async fn sleepus() { for i in 1..=10 { println!("sleepus {}", i); sleep(Duration::from_millis(500)).await; } } fn sleepus2() -> impl std::future::Future<Output=()> { async { for i in 1..=10 { println!("sleepus async block {}", i); sleep(Duration::from_millis(300)).await; } } } async fn interruptus() { for i in 1..=5 { println!("interruptus {}", i); sleep(Duration::from_millis(1000)).await; } } #[async_std::main] async fn main() { let sleepus = spawn(sleepus()); let interruprus = spawn(interruptus()); sleepus2().await; interruprus.await; sleepus.await; }
true
992a41845029fa3e8c9814be209801d504a0c8da
Rust
vinc/littlewing
/src/board.rs
UTF-8
4,382
2.984375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::prelude::v1::*; pub fn draw(squares: Vec<String>) -> String { let line = " +---+---+---+---+---+---+---+---+\n"; let file = ""; draw_with(squares, line, file) } pub fn draw_with_coordinates(squares: Vec<String>) -> String { let line = " +---+---+---+---+---+---+---+---+\n"; let file = " a b c d e f g h\n"; draw_with(squares, line, file) } pub fn draw_compact_with_coordinates(squares: Vec<String>) -> String { let line = "+--------+\n"; let file = " abcdefgh\n"; draw_with(squares, line, file) } fn draw_with(squares: Vec<String>, line: &str, file: &str) -> String { debug_assert!(squares.len() == 64); let with_spaces = line.len() > 12; let with_coords = !file.is_empty(); let mut out = String::new(); out.push_str(line); for i in (0..8).rev() { if with_spaces { out.push_str(" "); } else { out.push_str("|"); } for j in 0..8 { let s = &squares[8 * i + j]; if with_spaces { out.push_str(&format!("| {} ", s)); } else { out.push_str(&format!("{}", s)); } } if with_coords { out.push_str(&format!("| {}\n", i + 1)); } else { out.push_str("|\n"); } if with_spaces { out.push_str(line); } } if !with_spaces { out.push_str(line); } out.push_str(file); out } #[allow(dead_code)] static PIECES_WITHOUT_COORDS: &str = " \ +---+---+---+---+---+---+---+---+ | r | n | b | q | k | b | n | r | +---+---+---+---+---+---+---+---+ | p | p | p | p | p | p | p | p | +---+---+---+---+---+---+---+---+ | | | | | | | | | +---+---+---+---+---+---+---+---+ | | | | | | | | | +---+---+---+---+---+---+---+---+ | | | | | P | | | | +---+---+---+---+---+---+---+---+ | | | | | | | | | +---+---+---+---+---+---+---+---+ | P | P | P | P | | P | P | P | +---+---+---+---+---+---+---+---+ | R | N | B | Q | K | B | N | R | +---+---+---+---+---+---+---+---+ "; #[allow(dead_code)] static PIECES_WITH_COORDS: &str = " \ +---+---+---+---+---+---+---+---+ | r | n | b | q | k | b | n | r | 8 +---+---+---+---+---+---+---+---+ | p | p | p | p | p | p | p | p | 7 +---+---+---+---+---+---+---+---+ | | | | | | | | | 6 +---+---+---+---+---+---+---+---+ | | | | | | | | | 5 +---+---+---+---+---+---+---+---+ | | | | | P | | | | 4 +---+---+---+---+---+---+---+---+ | | | | | | | | | 3 +---+---+---+---+---+---+---+---+ | P | P | P | P | | P | P | P | 2 +---+---+---+---+---+---+---+---+ | R | N | B | Q | K | B | N | R | 1 +---+---+---+---+---+---+---+---+ a b c d e f g h "; #[allow(dead_code)] static BITBOARD_WITH_COORDS: &str = " \ Bitboard (0xFFFF00001000EFFF) +--------+ |11111111| 8 |11111111| 7 |00000000| 6 |00000000| 5 |00001000| 4 |00000000| 3 |11110111| 2 |11111111| 1 +--------+ abcdefgh "; #[cfg(test)] mod tests { use crate::bitboard::BitboardExt; use crate::color::*; use crate::common::*; use crate::fen::FEN; use crate::game::Game; use crate::piece_move::PieceMove; use crate::piece_move_generator::PieceMoveGenerator; use crate::square::*; use super::*; #[test] fn test_draw() { colorize(false); let mut game = Game::from_fen(DEFAULT_FEN).unwrap(); game.make_move(PieceMove::new(E2, E4, DOUBLE_PAWN_PUSH)); assert_eq!(format!("{}", game), PIECES_WITHOUT_COORDS); } #[test] fn test_draw_with_coordinates() { colorize(false); let mut game = Game::from_fen(DEFAULT_FEN).unwrap(); game.show_coordinates = true; game.make_move(PieceMove::new(E2, E4, DOUBLE_PAWN_PUSH)); assert_eq!(format!("{}", game), PIECES_WITH_COORDS); } #[test] fn test_draw_compact_with_coordinates() { colorize(false); let mut game = Game::from_fen(DEFAULT_FEN).unwrap(); game.make_move(PieceMove::new(E2, E4, DOUBLE_PAWN_PUSH)); let bb = game.bitboards[WHITE as usize] | game.bitboards[BLACK as usize]; assert_eq!(format!("{}", bb.to_debug_string()), BITBOARD_WITH_COORDS); } }
true
0e6fc89fdcc5fe390fcafec16d2532c3d8db63ba
Rust
amgarrett09/rust-trie
/src/lib.rs
UTF-8
4,582
3.78125
4
[]
no_license
pub mod trie { struct TrieNode { data: Option<char>, children: Vec<usize>, valid_word: bool, } pub struct Trie { nodes: Vec<TrieNode>, } impl Default for Trie { fn default() -> Self { Trie::new() } } impl Trie { pub fn new() -> Self { Trie { nodes: vec![TrieNode { data: None, children: Vec::new(), valid_word: false, }], } } pub fn add(&mut self, st: &str) { // The current node we're looking at let mut current = 0; for ch in st.chars() { let mut found = false; // Look at each child of the current node for child in self.nodes[current].children.iter() { // If we find the char we're looking for if self.nodes[*child].data == Some(ch) { // Change current node to that child current = *child; found = true; break; } } // If none of the children contain our char, create a new node if !found { let new_index = self.nodes.len(); self.nodes[current].children.push(new_index); self.nodes.push(TrieNode { data: Some(ch), children: Vec::new(), valid_word: false, }); // On next iteration, start at new node we just created current = new_index; } } // Set last node to be a valid endpoint for a keyword self.nodes[current].valid_word = true; } pub fn contains(&self, st: &str) -> bool { let mut current = 0; for ch in st.chars() { if self.nodes[current].children.is_empty() { return false; } let mut found = false; for child in self.nodes[current].children.iter() { if self.nodes[*child].data == Some(ch) { current = *child; found = true; break; } } if !found { return false; } } // Return true if the last char we found is a valid word endpoint self.nodes[current].valid_word } } #[cfg(test)] mod tests { use crate::trie::Trie; #[test] fn test_add() { let mut trie = Trie::new(); trie.add("hello"); assert_eq!(trie.nodes.len(), 6); assert!(trie.nodes[5].valid_word); assert!(!trie.nodes[4].valid_word); let mut char = "h".chars(); assert_eq!(trie.nodes[1].data, char.next()); assert_eq!(trie.nodes[1].children.len(), 1); assert_eq!(trie.nodes[1].children[0], 2); trie.add("hell"); assert_eq!(trie.nodes.len(), 6); assert!(trie.nodes[4].valid_word); trie.add("help"); assert_eq!(trie.nodes.len(), 7); assert_eq!(trie.nodes[3].children.len(), 2); assert_eq!(trie.nodes[3].children[1], 6); let mut char2 = "p".chars(); assert_eq!(trie.nodes[6].data, char2.next()); trie.add("cat"); assert_eq!(trie.nodes.len(), 10); let mut char = "c".chars(); assert_eq!(trie.nodes[7].data, char.next()); assert_eq!(trie.nodes[7].children.len(), 1); assert_eq!(trie.nodes[7].children[0], 8); assert_eq!(trie.nodes[9].children.len(), 0); trie.add("cap"); assert_eq!(trie.nodes.len(), 11); assert_eq!(trie.nodes[8].children.len(), 2); assert_eq!(trie.nodes[8].children[1], 10); } #[test] fn test_contains() { let mut trie = Trie::new(); assert!(!trie.contains("hello")); trie.add("hello"); assert!(trie.contains("hello")); assert!(!trie.contains("hell")); assert!(!trie.contains("help")); trie.add("help"); assert_eq!(trie.contains("help"), true); } } }
true
66faa448c0785d628a17073fff6b028b2a44b81b
Rust
jagill/rust-hyperloglog
/src/sparse_hll.rs
UTF-8
3,227
2.859375
3
[]
no_license
use crate::constants::SPARSE_PREFIX_LENGTH; use crate::linear_counting; use crate::{HyperLogLog, Merge, SetHyperLogLog}; use std::collections::BTreeMap; pub struct SparseHyperLogLog { pub(crate) buckets: BTreeMap<u32, u8>, } impl HyperLogLog for SparseHyperLogLog { fn new() -> Self { SparseHyperLogLog { buckets: BTreeMap::new(), } } fn add(&mut self, hash: u64) { self.insert(self.find_bucket(hash), self.find_value(hash)); } fn maybe_contains(&self, hash: u64) -> bool { self.buckets.contains_key(&self.find_bucket(hash)) } fn cardinality(&self) -> u64 { let total_buckets = (1u64 << SPARSE_PREFIX_LENGTH) as f64; let zero_buckets = total_buckets - (self.buckets.len() as f64); linear_counting(total_buckets, zero_buckets) } } impl SparseHyperLogLog { fn find_bucket(&self, hash: u64) -> u32 { (hash >> (64 - SPARSE_PREFIX_LENGTH)) as u32 } fn find_value(&self, hash: u64) -> u8 { (64 - SPARSE_PREFIX_LENGTH).min(hash.trailing_zeros()) as u8 } pub(crate) fn insert(&mut self, bucket: u32, value: u8) { self.buckets .entry(bucket) .and_modify(|e| *e = value.max(*e)) .or_insert(value); } pub(crate) fn get_reduced_bucket(&self, bucket: u32, prefix_length: u32) -> u32 { let excess_prefix_length = SPARSE_PREFIX_LENGTH - prefix_length; bucket >> excess_prefix_length } pub(crate) fn get_total_zeros(&self, bucket: u32, prefix_length: u32) -> u8 { let excess_prefix_length = SPARSE_PREFIX_LENGTH - prefix_length; let prefix_stop_bit = 1 << (excess_prefix_length + 1); let sparse_value_bits = (64 - SPARSE_PREFIX_LENGTH) as u8; let mut total_zeros = self.buckets[&bucket]; if total_zeros == sparse_value_bits { let zeros_in_prefix = (prefix_stop_bit & bucket).trailing_zeros() as u8; total_zeros += zeros_in_prefix; } total_zeros } } impl From<SetHyperLogLog> for SparseHyperLogLog { fn from(set_hll: SetHyperLogLog) -> Self { let mut sparse_hll = SparseHyperLogLog::new(); for hash in set_hll.set.into_iter() { sparse_hll.add(hash) } sparse_hll } } impl Merge<SparseHyperLogLog> for SparseHyperLogLog { type Output = SparseHyperLogLog; fn merge(mut self, mut rhs: SparseHyperLogLog) -> Self::Output { if self.buckets.len() >= rhs.buckets.len() { for (b, v) in rhs.buckets.into_iter() { self.insert(b, v); } self } else { for (b, v) in self.buckets.into_iter() { rhs.insert(b, v); } rhs } } } impl Merge<SetHyperLogLog> for SparseHyperLogLog { type Output = SparseHyperLogLog; fn merge(mut self, rhs: SetHyperLogLog) -> Self::Output { for x in rhs.set.into_iter() { self.add(x); } self } } impl Merge<SparseHyperLogLog> for SetHyperLogLog { type Output = SparseHyperLogLog; fn merge(self, rhs: SparseHyperLogLog) -> Self::Output { rhs.merge(self) } }
true
5f7b73503685c3c0f203858d829d50e7d99148ca
Rust
zebp/async-wormhole
/src/lib.rs
UTF-8
7,774
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
#![feature(min_const_generics)] //! async-wormhole allows you to call `.await` async calls across non-async functions, like extern "C" or JIT //! generated code. //! //! ## Motivation //! //! Sometimes, when running inside an async environment you need to call into JIT generated code (e.g. wasm) //! and .await from there. Because the JIT code is not available at compile time, the Rust compiler can't //! do their "create a state machine" magic. In the end you can't have `.await` statements in non-async //! functions. //! //! This library creates a special stack for executing the JIT code, so it's possible to suspend it at any //! point of the execution. Once you pass it a closure inside [AsyncWormhole::new](struct.AsyncWormhole.html#method.new) //! you will get back a future that you can `.await` on. The passed in closure is going to be executed on a //! new stack. //! //! Sometimes you also need to preserve thread local storage as the code inside the closure expects it to stay //! the same, but the actual execution can be moved between threads. There is a //! [proof of concept API](struct.AsyncWormhole.html#method.new_with_tls) //! to allow you to move your thread local storage with the closure across threads. //! //! ## Example //! //! ```rust //! use async_wormhole::{AsyncWormhole, AsyncYielder}; //! use switcheroo::stack::*; //! //! // non-async function //! extern "C" fn non_async(mut yielder: AsyncYielder<u32>) -> u32 { //! // Suspend the runtime until async value is ready. //! // Can contain .await calls. //! yielder.async_suspend(async { 42 }) //! } //! //! fn main() { //! let stack = EightMbStack::new().unwrap(); //! let task = AsyncWormhole::new(stack, |yielder| { //! let result = non_async(yielder); //! assert_eq!(result, 42); //! 64 //! }) //! .unwrap(); //! //! let outside = futures::executor::block_on(task); //! assert_eq!(outside.unwrap(), 64); //! } //! ``` pub mod pool; use switcheroo::stack; use switcheroo::Generator; use switcheroo::Yielder; use std::cell::Cell; use std::convert::TryInto; use std::future::Future; use std::io::Error; use std::pin::Pin; use std::task::{Context, Poll, Waker}; use std::thread::LocalKey; // This structure holds one thread local variable that is preserved across context switches. // This gives code that use thread local variables inside the closure the impression that they are // running on the same thread they started even if they have been moved to a different one. struct ThreadLocal<TLS: 'static> { reference: &'static LocalKey<Cell<*const TLS>>, value: *const TLS, } impl<TLS> Copy for ThreadLocal<TLS> {} impl<TLS> Clone for ThreadLocal<TLS> { fn clone(&self) -> Self { ThreadLocal { reference: self.reference, value: self.value, } } } /// AsyncWormhole captures a stack and a closure. It also implements Future and can be awaited on. pub struct AsyncWormhole<'a, Stack: stack::Stack, Output, TLS: 'static, const TLS_COUNT: usize> { generator: Cell<Generator<'a, Waker, Option<Output>, Stack>>, preserved_thread_locals: [ThreadLocal<TLS>; TLS_COUNT], } unsafe impl<Stack: stack::Stack, Output, TLS, const TLS_COUNT: usize> Send for AsyncWormhole<'_, Stack, Output, TLS, TLS_COUNT> { } impl<'a, Stack: stack::Stack, Output> AsyncWormhole<'a, Stack, Output, (), 0> { /// Returns a new AsyncWormhole, using the passed `stack` to execute the closure `f` on. /// The closure will not be executed right away, only if you pass AsyncWormhole to an /// async executor (.await on it). pub fn new<F>(stack: Stack, f: F) -> Result<Self, Error> where F: FnOnce(AsyncYielder<Output>) -> Output + 'a, { AsyncWormhole::new_with_tls([], stack, f) } } impl<'a, Stack: stack::Stack, Output, TLS, const TLS_COUNT: usize> AsyncWormhole<'a, Stack, Output, TLS, TLS_COUNT> { /// Similar to `new`, but allows you to capture thread local variables inside the closure. /// During the execution of the future an async executor can move the closure `f` between /// threads. From the perspective of the code inside the closure `f` the thread local /// variables will be moving with it from thread to thread. /// /// ### Safety /// /// If the thread local variable is only set and used inside of the `f` closure than it's safe /// to use it. Outside of the closure the content of it will be unpredictable. pub fn new_with_tls<F>( tls_refs: [&'static LocalKey<Cell<*const TLS>>; TLS_COUNT], stack: Stack, f: F, ) -> Result<Self, Error> where // TODO: This needs to be Send, but because Wasmtime's strucutres are not Send for now I don't // enforce it on an API level. Accroding to // https://github.com/bytecodealliance/wasmtime/issues/793#issuecomment-692740254 // it is safe to move everything connected to a Store to a different thread all at once, but this // is impossible to express with the type system. F: FnOnce(AsyncYielder<Output>) -> Output + 'a, { let generator = Generator::new(stack, |yielder, waker| { let async_yielder = AsyncYielder::new(&*yielder, waker); yielder.suspend(Some(f(async_yielder))); }); let preserved_thread_locals = tls_refs .iter() .map(|tls_ref| ThreadLocal { reference: tls_ref, value: tls_ref.with(|v| v.get()), }) .collect::<Vec<ThreadLocal<TLS>>>() .as_slice() .try_into() .unwrap(); Ok(Self { generator: Cell::new(generator), preserved_thread_locals, }) } /// Get the stack from the internal generator. pub fn stack(self) -> Stack { self.generator.into_inner().stack() } } impl<'a, Stack: stack::Stack + Unpin, Output, TLS: Unpin, const TLS_COUNT: usize> Future for AsyncWormhole<'a, Stack, Output, TLS, TLS_COUNT> { type Output = Option<Output>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { // Restore thread local values when re-entering execution for tls in self.preserved_thread_locals.iter() { tls.reference.with(|v| v.set(tls.value)); } match self.generator.get_mut().resume(cx.waker().clone()) { // If we call the future after it completed it will always return Poll::Pending. // But polling a completed future is either way undefined behaviour. None | Some(None) => { // Preserve all thread local values for tls in self.preserved_thread_locals.iter_mut() { tls.reference.with(|v| tls.value = v.get()); } Poll::Pending } Some(out) => Poll::Ready(out), } } } #[derive(Clone)] pub struct AsyncYielder<'a, Output> { yielder: &'a Yielder<Waker, Option<Output>>, waker: Waker, } impl<'a, Output> AsyncYielder<'a, Output> { pub(crate) fn new(yielder: &'a Yielder<Waker, Option<Output>>, waker: Waker) -> Self { Self { yielder, waker } } /// Takes an `impl Future` and awaits it, returning the value from it once ready. pub fn async_suspend<Fut, R>(&mut self, future: Fut) -> R where Fut: Future<Output = R>, { pin_utils::pin_mut!(future); loop { let cx = &mut Context::from_waker(&mut self.waker); self.waker = match future.as_mut().poll(cx) { Poll::Pending => self.yielder.suspend(None), Poll::Ready(result) => return result, }; } } }
true
2019b5d2160023cc3e7b28638fb2573a189d1bb5
Rust
bifrost-rs/bifrost
/bifrost-sdp/src/ntp.rs
UTF-8
4,610
3.359375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
use crate::Parse; use nom::character::complete::digit1; use nom::combinator::map_res; use nom::IResult; #[derive(Clone, Debug, PartialEq)] pub struct Instant(u64); impl Instant { pub fn from_secs(secs: u64) -> Self { Self(secs) } pub fn from_mins(mins: u64) -> Self { Self(mins * 60) } pub fn from_hours(hours: u64) -> Self { Self(hours * 3600) } pub fn from_days(days: u64) -> Self { Self(days * 86400) } pub fn as_secs(&self) -> u64 { self.0 } } impl Parse for Instant { fn parse(input: &str) -> IResult<&str, Self> { let (rest, time) = map_res(digit1, str::parse)(input)?; Ok(match rest.chars().next() { Some('d') => (&rest[1..], Self::from_days(time)), Some('h') => (&rest[1..], Self::from_hours(time)), Some('m') => (&rest[1..], Self::from_mins(time)), Some('s') => (&rest[1..], Self::from_secs(time)), _ => (rest, Self::from_secs(time)), }) } } #[derive(Clone, Debug, PartialEq)] pub struct Duration(i64); impl Duration { pub fn from_secs(secs: i64) -> Self { Self(secs) } pub fn from_mins(mins: i64) -> Self { Self(mins * 60) } pub fn from_hours(hours: i64) -> Self { Self(hours * 3600) } pub fn from_days(days: i64) -> Self { Self(days * 86400) } pub fn as_secs(&self) -> i64 { self.0 } } impl Parse for Duration { fn parse(input: &str) -> IResult<&str, Self> { let (rest, sign) = match input.chars().next() { Some('+') => (&input[1..], true), Some('-') => (&input[1..], false), _ => (input, true), }; let (rest, unsigned_time) = map_res(digit1, str::parse::<i64>)(rest)?; let time = if sign { unsigned_time } else { -unsigned_time }; Ok(match rest.chars().next() { Some('d') => (&rest[1..], Self::from_days(time)), Some('h') => (&rest[1..], Self::from_hours(time)), Some('m') => (&rest[1..], Self::from_mins(time)), Some('s') => (&rest[1..], Self::from_secs(time)), _ => (rest, Self::from_secs(time)), }) } } #[cfg(test)] mod tests { use super::*; use crate::test_util::assert_err; #[test] fn valid_instants() { assert_eq!(Instant::from_days(42).as_secs(), 42 * 86400); assert_eq!(Instant::from_hours(41).as_secs(), 41 * 3600); assert_eq!(Instant::from_mins(40).as_secs(), 40 * 60); assert_eq!(Instant::from_secs(39).as_secs(), 39); assert_eq!(Instant::parse("42dx"), Ok(("x", Instant::from_days(42)))); assert_eq!(Instant::parse("41h "), Ok((" ", Instant::from_hours(41)))); assert_eq!( Instant::parse("40m 41h"), Ok((" 41h", Instant::from_mins(40))) ); assert_eq!( Instant::parse("39s\r\n"), Ok(("\r\n", Instant::from_secs(39))) ); assert_eq!( Instant::parse("38 37\r\n"), Ok((" 37\r\n", Instant::from_secs(38))) ); assert_eq!(Instant::parse("37x"), Ok(("x", Instant::from_secs(37)))); } #[test] fn invalid_instants() { assert_err::<Instant>("s"); assert_err::<Instant>(" 42"); assert_err::<Instant>(""); assert_err::<Instant>(" "); } #[test] fn valid_durations() { assert_eq!(Duration::from_days(42).as_secs(), 42 * 86400); assert_eq!(Duration::from_hours(-41).as_secs(), -41 * 3600); assert_eq!(Duration::from_mins(40).as_secs(), 40 * 60); assert_eq!(Duration::from_secs(-39).as_secs(), -39); assert_eq!(Duration::parse("+42dx"), Ok(("x", Duration::from_days(42)))); assert_eq!( Duration::parse("-41h "), Ok((" ", Duration::from_hours(-41))) ); assert_eq!( Duration::parse("40m 41h"), Ok((" 41h", Duration::from_mins(40))) ); assert_eq!( Duration::parse("-39s\r\n"), Ok(("\r\n", Duration::from_secs(-39))) ); assert_eq!( Duration::parse("+38 37\r\n"), Ok((" 37\r\n", Duration::from_secs(38))) ); assert_eq!(Duration::parse("-37x"), Ok(("x", Duration::from_secs(-37)))); } #[test] fn invalid_durations() { assert_err::<Duration>("*42"); assert_err::<Duration>(" 42"); assert_err::<Duration>("s"); assert_err::<Duration>(""); assert_err::<Duration>(" "); } }
true
3b45bee583d928b9d54ed29cc50bfc2f7edeb90f
Rust
piyongcai/scaproust
/src/transport/async/initial.rs
UTF-8
2,354
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
// Copyright (c) 2015-2017 Contributors as noted in the AUTHORS file. // // 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. // This file may not be copied, modified, or distributed except according to those terms. use transport::async::stub::*; use transport::async::state::*; use transport::async::handshake::HandshakeTx; use transport::pipe::Context; pub struct Initial<S : AsyncPipeStub> { stub: S, proto_ids: (u16, u16) } impl<S : AsyncPipeStub> Initial<S> { pub fn new(s: S, pids: (u16, u16)) -> Initial<S> { Initial { stub: s, proto_ids: pids } } } impl<S : AsyncPipeStub> Into<HandshakeTx<S>> for Initial<S> { fn into(self) -> HandshakeTx<S> { HandshakeTx::new(self.stub, self.proto_ids) } } impl<S : AsyncPipeStub + 'static> PipeState<S> for Initial<S> { fn name(&self) -> &'static str {"Initial"} fn open(self: Box<Self>, ctx: &mut dyn Context) -> Box<dyn PipeState<S>> { transition::<Initial<S>, HandshakeTx<S>, S>(self, ctx) } } #[cfg(test)] mod tests { use transport::tests::*; use transport::async::state::*; use transport::async::tests::*; use transport::async::initial::*; #[test] fn open_should_cause_transition_to_handshake() { let stub = TestStepStream::new(); let state = Box::new(Initial::new(stub, (1, 1))); let mut ctx = TestPipeContext::new(); let new_state = state.open(&mut ctx); assert_eq!(1, ctx.get_registrations().len()); // this is caused by HandshakeTx::enter assert_eq!(0, ctx.get_reregistrations().len()); assert_eq!(0, ctx.get_deregistrations()); assert_eq!("HandshakeTx", new_state.name()); } #[test] fn close_should_cause_a_transition_to_dead() { let stub = TestStepStream::new(); let state = Box::new(Initial::new(stub, (1, 1))); let mut ctx = TestPipeContext::new(); let new_state = state.close(&mut ctx); assert_eq!(0, ctx.get_registrations().len()); assert_eq!(0, ctx.get_reregistrations().len()); assert_eq!(0, ctx.get_deregistrations()); assert_eq!("Dead", new_state.name()); } }
true
fdd00621f1d6d1940e571b76f231dc90b64054b4
Rust
krauslabs/silica-hdl
/silica-syntax/src/lib.rs
UTF-8
835
2.703125
3
[]
no_license
use lalrpop_util::lalrpop_mod; pub mod ast; pub mod visit; mod error; mod lexer; lalrpop_mod!(parser); /// Source code byte offsets, used for spans and errors. pub type BytePos = usize; /// Syntax error types. #[derive(Clone, Debug, PartialEq)] pub enum Error { InvalidToken { pos: BytePos, }, UnrecognizedToken { token: Option<(BytePos, lexer::Token, BytePos)>, expected: Vec<String>, }, ExtraToken { token: (BytePos, lexer::Token, BytePos), }, InvalidCharacter { pos: BytePos, ch: char, }, } /// Parses source code into an AST. pub fn parse_source(source: &str) -> Result<ast::Ast, Error> { let lexer = lexer::Lexer::new(source); let ast = parser::SourceFileParser::new().parse(lexer)?; Ok(ast) }
true
ab48fea424b2401d01fd8d3118e0f0db0e9fa23d
Rust
nupa/RustyTracer
/src/main.rs
UTF-8
5,235
2.65625
3
[]
no_license
use color::Color; use cgmath::{Point3, Vector3}; use cgmath::prelude::*; use image::{ImageBuffer, RgbImage, Rgb}; use ray::Ray; use crate::sphere::Sphere; use crate::hittable::Hittable; use crate::hittable_list::HittableList; use std::f64; use crate::camera::Camera; use rand::random; use std::time::Instant; use crate::material::{Lambertian, Metal, Dielectric}; use std::f64::consts::PI; mod ray; mod color; mod hittable; mod hittable_list; mod sphere; mod camera; mod material; fn color(ray: &Ray, world: &dyn Hittable, depth: i32) -> Color { if depth >= 50 { return Color::black(); } if let Some(h) = world.hit(ray, 0.001, f64::MAX) { let s = h.material.scatter(ray, &h); return match s { Some((r, a)) => a * color(&r, world, depth+1), None => Color::black() }; } let unit_direction = ray.direction.normalize(); let t = 0.5*(unit_direction.y + 1.0); return (1.0 - t) * Color::white() + t * Color::new(0.5, 0.7, 1.0); } fn color_to_rgb(color: &Color) -> Rgb<u8> { let gamma_cor = color.gamma_correct(); let ir = (255.99 * gamma_cor.r) as u8; let ig = (255.99 * gamma_cor.g) as u8; let ib = (255.99 * gamma_cor.b) as u8; return Rgb([ir, ig, ib]); } fn main() { let now = Instant::now(); let height: u32 = 320; let width: u32 = 640; let num_of_samples = 50; let mut img: RgbImage = ImageBuffer::new(width, height); let world = create_random_scene(); /*let look_from = Point3::new(3.0, 3.0, 2.0); let look_at = Point3::new(0.0, 0.0, -1.0); let dist_to_focus = (look_from - look_at).magnitude();*/ let look_from = Point3::new(13.0, 2.0, 3.0); let look_at = Point3::new(0.0, 0.0, 0.0); let dist_to_focus = 10.0; let cam = Camera::new(look_from, look_at, Vector3::new(0.0, 1.0, 0.0), 20.0, width as f64/height as f64, 0.1, dist_to_focus); for j in 0..height { print!("starting row {} ...", j); for i in 0..width { let mut col = Color::black(); for _s in 0..num_of_samples { let u = (i as f64 + random::<f64>()) / (width as f64); let v = (j as f64 + random::<f64>()) / (height as f64); let r = cam.get_ray(u, v); col += color(&r, &*world, 0); } col /= num_of_samples as f64; img.put_pixel(i, height - j - 1, color_to_rgb(&col)); } println!("done."); } img.save("images/output.png").expect("Talletus epäonnistui"); let elapsed_time = now.elapsed().as_secs(); println!("Took {}s to render the image.", elapsed_time); } fn create_world() -> Box<dyn Hittable> { let mut vec: Vec<Box<dyn Hittable>> = vec![]; vec.push(Box::new(Sphere::new(Point3::new(0.0, 0.0, -1.0), 0.5, Box::new(Lambertian::new(Color::new(0.1, 0.2, 0.5)))))); vec.push(Box::new(Sphere::new(Point3::new(0.0,-100.5,-1.0), 100.0, Box::new(Lambertian::new(Color::new(0.8, 0.8, 0.0)))))); vec.push(Box::new(Sphere::new(Point3::new(1.0, 0.0, -1.0), 0.5, Box::new(Metal::new(Color::new(0.8, 0.6, 0.2), 0.3))))); // vec.push(Box::new(Sphere::new(Point3::new(-1.0,0.0, -1.0), 0.5, Box::new(Metal::new(Color::new(0.8, 0.8, 0.8), 1.0))))); vec.push(Box::new(Sphere::new(Point3::new(-1.0,0.0, -1.0), 0.5, Box::new(Dielectric::new(1.5))))); vec.push(Box::new(Sphere::new(Point3::new(-1.0,0.0, -1.0), -0.45, Box::new(Dielectric::new(1.5))))); return Box::new(HittableList::new(vec)); } fn create_random_scene() -> Box<dyn Hittable> { let mut vec: Vec<Box<dyn Hittable>> = vec![]; vec.push(Box::new(Sphere::new(Point3::new(0.0,-1000.0, 0.0), 1000.0, Box::new(Lambertian::new(Color::new(0.5, 0.5, 0.5)))))); for a in -11..11 { for b in -11..11 { let choose_mat = random::<f64>(); let center = Point3::new(a as f64 + 0.9*random::<f64>(), 0.2, b as f64 + 0.9 * random::<f64>()); if (center.to_vec() - Vector3::new(4.0, 0.2, 0.0)).magnitude() > 0.9 { if choose_mat < 0.8 { let albedo = Color::new(random::<f64>() * random::<f64>(), random::<f64>() * random::<f64>(), random::<f64>() * random::<f64>()); vec.push(Box::new(Sphere::new(center, 0.2, Box::new(Lambertian::new(albedo))))); } else if choose_mat < 0.95 { let albedo = Color::new(0.5 * (1.0 + random::<f64>()), 0.5 * (1.0 + random::<f64>()), 0.5 * (1.0 + random::<f64>())); let fuzz = 0.5 * random::<f64>(); vec.push(Box::new(Sphere::new(center, 0.2, Box::new(Metal::new(albedo, fuzz))))); } else { vec.push(Box::new(Sphere::new(center, 0.2, Box::new(Dielectric::new(1.5))))); } } } } vec.push(Box::new(Sphere::new(Point3::new(0.0, 1.0, 0.0), 1.0, Box::new(Dielectric::new(1.5))))); vec.push(Box::new(Sphere::new(Point3::new(-4.0, 1.0, 0.0), 1.0, Box::new(Lambertian::new(Color::new(0.4, 0.2, 0.1)))))); vec.push(Box::new(Sphere::new(Point3::new(4.0, 1.0, 0.0), 1.0, Box::new(Metal::new(Color::new(0.7, 0.6, 0.5), 0.0))))); return Box::new(HittableList::new(vec)); }
true
161cc7170753fd3c48942d9d4d7826f60b1d6238
Rust
snowlock650/glossary
/src/bin/phrase_freq.rs
UTF-8
2,004
2.84375
3
[]
no_license
extern crate rustc_serialize; extern crate docopt; extern crate indexerlib; extern crate itertools; use docopt::Docopt; use std::fs::File; use std::io::Write; use std::io::BufWriter; use indexerlib::parser::TextParser; use indexerlib::counter::WordCountByFrame; use itertools::Itertools; static USAGE: &'static str = " Usage: phrase_freq [-b BLOCKSIZE] <textfile> <output> Options: -b, --block-size BLOCKSIZE The number of words in a data frame "; #[derive(Debug, RustcDecodable)] struct Args { arg_textfile: String, arg_output: String, flag_block_size: usize, } fn count_words(input_file: &mut File, output_file: &mut File, est_frame_cnt: usize, frame_size: usize) { let input = match TextParser::new(input_file) { Ok(parser) => Some(parser), Err(e) => { println!("Error opening file because {}", e); None }, }; if let Some(mut parser) = input { let mut counts = WordCountByFrame::new(est_frame_cnt, frame_size); for word in parser.word_iter() { counts.incr_word(word.to_lowercase()); } let counter = counts.get_word_counts(); let mut writer = BufWriter::new(output_file); for (key, array) in counter.iter() { let mut line: String = String::new(); let subline = array.iter().join("\t"); line.push_str(key); line.push('\t'); line.push_str(&subline); line.push('\n'); writer.write(line.as_bytes()).unwrap(); } } } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); println!("phrase_freq: {} {}", args.arg_textfile, args.arg_output); //If the files failed to open, then panic let mut input_file = File::open(args.arg_textfile).ok().unwrap(); let mut output_file = File::create(args.arg_output).ok().unwrap(); let metadata = input_file.metadata().ok().unwrap(); let est_frame_cnt: usize = metadata.len() as usize / args.flag_block_size; count_words(&mut input_file, &mut output_file, est_frame_cnt as usize, args.flag_block_size as usize); }
true
6cede0082a5802345c7d6a3393cd80934498ac4b
Rust
riddle-rs/riddle
/riddle-input/src/mouse_state.rs
UTF-8
777
3.0625
3
[ "MIT", "Apache-2.0" ]
permissive
use crate::*; use std::collections::HashSet; pub(crate) struct MouseState { logical_position: LogicalPosition, buttons: HashSet<MouseButton>, } impl MouseState { pub fn set_position(&mut self, position: LogicalPosition) { self.logical_position = position; } pub fn button_down(&mut self, button: MouseButton) { self.buttons.insert(button); } pub fn button_up(&mut self, button: MouseButton) { self.buttons.remove(&button); } pub fn position(&self) -> LogicalPosition { self.logical_position } pub fn is_button_down(&self, button: MouseButton) -> bool { self.buttons.contains(&button) } } impl Default for MouseState { fn default() -> Self { MouseState { logical_position: LogicalPosition { x: 0, y: 0 }, buttons: HashSet::new(), } } }
true
e38e154715b9245b4302d4d635797eb51f5a126c
Rust
yamagata-akita/rust_tutorial
/chapter_6/leap-year/src/method.rs
UTF-8
1,016
3.9375
4
[]
no_license
// メソッド // 関数の一種 // 構造体、列挙型、トレイトの中などに定義された関数の一種 // メソッドでは、メソッドの関連付けられたインスタンス(=レシーバ)の情報を使うことができる struct Circle { radius: u32, } // 構造体のメソッドの定義は、構造体の定義の中ではなく、implブロックの中に書く impl Circle { fn diameter(&self) -> u32 { self.radius * 2 } // 関連関数 // 構造体などデータ型そのものに関数を関連付けることができる //small_circle関連関数 fn small_circle() -> Circle { Circle { radius: 1 } } } fn main() { let circle1 = Circle { radius: 10 }; println!("Circle1's diameter: {}", circle1.diameter()); // Circleの関連関数small_circleの呼び出し // 関連関数の実行には::を用いる let circle2 = Circle::small_circle(); println!("Circle2's diameter: {}", circle2.diameter()); }
true
9ab4ea116759f7feb15a71cc158fc57ea7fa34b8
Rust
philmein23/jack-compiler
/src/token.rs
UTF-8
1,379
3.328125
3
[]
no_license
#[derive(Debug, PartialEq)] pub enum Token { Integer(i32), String(String), Identifier(String), Invalid(String), Class, Constructor, Function, Method, Field, Static, Var, Int, Char, Boolean, Void, True, False, Null, This, Let, Do, If, Else, While, Return, Plus, Minus, Asterisk, Slash, And, Or, GreaterThan, LessThan, Equal, LeftBracket, RightBracket, LeftBrace, RightBrace, LeftParen, RightParen, Dot, Comma, SemiColon, Tilde, } pub fn match_identifier(iden: &str) -> Token { match iden { "class" => Token::Class, "constructor" => Token::Constructor, "function" => Token::Function, "method" => Token::Method, "field" => Token::Field, "static" => Token::Static, "var" => Token::Var, "int" => Token::Int, "char" => Token::Char, "boolean" => Token::Void, "true" => Token::True, "false" => Token::False, "null" => Token::Null, "this" => Token::This, "let" => Token::Let, "do" => Token::Do, "if" => Token::If, "else" => Token::Else, "while" => Token::While, "return" => Token::Return, _ => Token::Identifier(iden.to_string()), } }
true
3c0f14072e6a416aa1810b7ace4a069fe661e8d9
Rust
Bruno-Messias/Rust-Learning
/struct_funtion/src/main.rs
UTF-8
1,642
3.703125
4
[ "MIT" ]
permissive
fn main() { let mut user1 = User { email: String::from("someone@hotmail.com"), username: String::from("someone"), active: true, sign_in_count: 1, }; println!("{}", user1.email); println!("{}", user1.username); println!("{}", user1.active); println!("{}", user1.sign_in_count); user1.email = String::from("anotheremail@hotmail.com"); println!("{}", user1.email); let email_new = String::from("second@gmail.com"); let new_username = String::from("thesecond"); let user2 = build_user(email_new, new_username); println!("{}", user2.email); println!("{}", user2.username); println!("{}", user2.active); println!("{}", user2.sign_in_count); let user3 = User { email: String::from("theolderemail@older.com"), username: user2.username, //Can use other struct to build a new instance ..user1 // uses the rest of user 2 atributes }; println!("{}", user3.email); println!("{}", user3.username); println!("{}", user3.active); println!("{}", user3.sign_in_count); //tuples struct struct Color(i32, i32, i32); struct Point(i32, i32, i32); let black = Color(0, 0, 0); let origin = Point(0, 0, 0); println!("{}", black.0); println!("{}", origin.2); println!("{:#?}", user1); //Need {:?} ou {:#?} } #[derive(Debug)] //Add this to release the print of the struct struct User { username: String, email: String, sign_in_count: u64, active: bool, } fn build_user(email: String, username: String) -> User { User { email, username, active: true, sign_in_count: 1, } }
true
c681eb6eabf8a77281d2ca4f7131ca0a974a279a
Rust
rust-lang/rust-analyzer
/crates/ide/src/annotations/fn_references.rs
UTF-8
2,759
2.90625
3
[ "Apache-2.0", "MIT" ]
permissive
//! This module implements a methods and free functions search in the specified file. //! We have to skip tests, so cannot reuse file_structure module. use hir::Semantics; use ide_assists::utils::test_related_attribute; use ide_db::RootDatabase; use syntax::{ast, ast::HasName, AstNode, SyntaxNode, TextRange}; use crate::FileId; pub(super) fn find_all_methods( db: &RootDatabase, file_id: FileId, ) -> Vec<(TextRange, Option<TextRange>)> { let sema = Semantics::new(db); let source_file = sema.parse(file_id); source_file.syntax().descendants().filter_map(|it| method_range(it)).collect() } fn method_range(item: SyntaxNode) -> Option<(TextRange, Option<TextRange>)> { ast::Fn::cast(item).and_then(|fn_def| { if test_related_attribute(&fn_def).is_some() { None } else { Some(( fn_def.syntax().text_range(), fn_def.name().map(|name| name.syntax().text_range()), )) } }) } #[cfg(test)] mod tests { use syntax::TextRange; use crate::fixture; use crate::TextSize; use std::ops::RangeInclusive; #[test] fn test_find_all_methods() { let (analysis, pos) = fixture::position( r#" fn private_fn() {$0} pub fn pub_fn() {} pub fn generic_fn<T>(arg: T) {} "#, ); let refs = super::find_all_methods(&analysis.db, pos.file_id); check_result(&refs, &[3..=13, 27..=33, 47..=57]); } #[test] fn test_find_trait_methods() { let (analysis, pos) = fixture::position( r#" trait Foo { fn bar() {$0} fn baz() {} } "#, ); let refs = super::find_all_methods(&analysis.db, pos.file_id); check_result(&refs, &[19..=22, 35..=38]); } #[test] fn test_skip_tests() { let (analysis, pos) = fixture::position( r#" //- /lib.rs #[test] fn foo() {$0} pub fn pub_fn() {} mod tests { #[test] fn bar() {} } "#, ); let refs = super::find_all_methods(&analysis.db, pos.file_id); check_result(&refs, &[28..=34]); } fn check_result(refs: &[(TextRange, Option<TextRange>)], expected: &[RangeInclusive<u32>]) { assert_eq!(refs.len(), expected.len()); for (i, &(full, focus)) in refs.iter().enumerate() { let range = &expected[i]; let item = focus.unwrap_or(full); assert_eq!(TextSize::from(*range.start()), item.start()); assert_eq!(TextSize::from(*range.end()), item.end()); } } }
true
730454a8ae06763086cb500393b24f55218cbeef
Rust
bugadani/Debounce
/src/lib.rs
UTF-8
2,619
3.53125
4
[]
no_license
//! This crate implements a simple debouncer #![cfg_attr(not(test), no_std)] use typenum::Unsigned; use core::marker::PhantomData; pub use typenum::consts::*; #[derive(PartialEq, Copy, Clone, Debug)] pub enum State { Touched, Released } #[derive(PartialEq, Copy, Clone, Debug)] pub enum Change { Touch, Release, NoChange(State) } impl Into<State> for bool { fn into(self) -> State { if self { State::Touched } else { State::Released } } } impl Into<State> for Change { fn into(self) -> State { match self { Change::Touch => State::Touched, Change::Release => State::Released, Change::NoChange(state) => state } } } impl State { pub fn to_change(self) -> Change { match self { State::Touched => Change::Touch, State::Released => Change::Release } } } pub struct Debounce<N> where N: Unsigned { samples: usize, state: State, _marker: PhantomData<N> } impl<N> Debounce<N> where N: Unsigned { pub fn new(initial: State) -> Self { Self { samples: 0, state: initial, _marker: PhantomData } } pub fn state(&self) -> State { self.state } pub fn update(&mut self, sample: State) -> Change { if sample != self.state { if self.samples == N::to_usize() - 1 { self.state = sample; self.samples = 0; self.state.to_change() } else { self.samples += 1; Change::NoChange(self.state) } } else { Change::NoChange(self.state) } } } #[cfg(test)] mod tests { use typenum::consts::*; use super::*; #[test] fn returns_change() { let mut debounce: Debounce<U3> = Debounce::new(State::Released); assert_eq!(Change::NoChange(State::Released), debounce.update(State::Touched)); assert_eq!(Change::NoChange(State::Released), debounce.update(State::Touched)); assert_eq!(Change::Touch, debounce.update(State::Touched)); assert_eq!(Change::NoChange(State::Touched), debounce.update(State::Touched)); assert_eq!(Change::NoChange(State::Touched), debounce.update(State::Released)); assert_eq!(Change::NoChange(State::Touched), debounce.update(State::Released)); assert_eq!(Change::Release, debounce.update(State::Released)); assert_eq!(Change::NoChange(State::Released), debounce.update(State::Released)); } }
true
3846fe622d2851969e91f76475c4f6045ecc1e41
Rust
metarmask/building-blocks
/crates/building_blocks_storage/src/array/indexer.rs
UTF-8
3,240
3.03125
3
[ "MIT" ]
permissive
use crate::{ for_each_stride_parallel_global_unchecked2, for_each_stride_parallel_global_unchecked3, Array2ForEach, Array3ForEach, ArrayForEach, Local, Local2i, Local3i, Stride, }; use building_blocks_core::prelude::*; /// When a lattice map implements `IndexedArray`, that means there is some underlying array with the location and shape dictated /// by the extent. /// /// For the sake of generic impls, if the same map also implements `Get*<Stride>`, it must use the same data layout as `Array`. pub trait IndexedArray<N> { type Indexer: ArrayIndexer<N>; fn extent(&self) -> &ExtentN<N>; #[inline] fn stride_from_local_point(&self, p: Local<N>) -> Stride where PointN<N>: Copy, { Self::Indexer::stride_from_local_point(self.extent().shape, p) } #[inline] fn strides_from_local_points(&self, points: &[Local<N>], strides: &mut [Stride]) where PointN<N>: Copy, { Self::Indexer::strides_from_local_points(self.extent().shape, points, strides) } } pub trait ArrayIndexer<N> { fn stride_from_local_point(shape: PointN<N>, point: Local<N>) -> Stride; fn for_each_point_and_stride_unchecked( for_each: ArrayForEach<N>, f: impl FnMut(PointN<N>, Stride), ); fn for_each_stride_parallel_global_unchecked( iter_extent: &ExtentN<N>, array1_extent: &ExtentN<N>, array2_extent: &ExtentN<N>, f: impl FnMut(Stride, Stride), ); #[inline] fn strides_from_local_points(shape: PointN<N>, points: &[Local<N>], strides: &mut [Stride]) where PointN<N>: Copy, { for (i, p) in points.iter().enumerate() { strides[i] = Self::stride_from_local_point(shape, *p); } } } impl ArrayIndexer<[i32; 2]> for [i32; 2] { #[inline] fn stride_from_local_point(s: Point2i, p: Local2i) -> Stride { Stride((p.y() * s.x() + p.x()) as usize) } #[inline] fn for_each_point_and_stride_unchecked( for_each: Array2ForEach, mut f: impl FnMut(Point2i, Stride), ) { for_each2!(for_each, x, y, stride, { f(PointN([x, y]), stride) }); } #[inline] fn for_each_stride_parallel_global_unchecked( iter_extent: &Extent2i, array1_extent: &Extent2i, array2_extent: &Extent2i, f: impl FnMut(Stride, Stride), ) { for_each_stride_parallel_global_unchecked2(iter_extent, array1_extent, array2_extent, f) } } impl ArrayIndexer<[i32; 3]> for [i32; 3] { #[inline] fn stride_from_local_point(s: Point3i, p: Local3i) -> Stride { Stride((p.z() * s.y() * s.x() + p.y() * s.x() + p.x()) as usize) } #[inline] fn for_each_point_and_stride_unchecked( for_each: Array3ForEach, mut f: impl FnMut(Point3i, Stride), ) { for_each3!(for_each, x, y, z, stride, { f(PointN([x, y, z]), stride) }); } #[inline] fn for_each_stride_parallel_global_unchecked( iter_extent: &Extent3i, array1_extent: &Extent3i, array2_extent: &Extent3i, f: impl FnMut(Stride, Stride), ) { for_each_stride_parallel_global_unchecked3(iter_extent, array1_extent, array2_extent, f); } }
true
22ecfe4ff0cf36e1e0e9e0236457b9cc3be71621
Rust
Avi-D-coder/github-events
/src/lib.rs
UTF-8
55,432
2.84375
3
[ "MIT", "Apache-2.0" ]
permissive
/// Feed Event API types and docs taken from [github docs](https://developer.github.com/v3/activity/events/types). /// /// Utilized [json_typegen](http://vestera.as/json_typegen/) in creation. #[macro_use] extern crate serde_derive; extern crate serde_json; mod actions; mod repository; use repository::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] enum Event { /// Triggered when a check run is `created`, `rerequested`, `completed`, or has a /// `requested_action`. The checks permission allows you to use the checks API. If you plan to /// create or modify check runs, your GitHub App will need to have the `checks:write` permission. /// If you only plan to consume check runs, your GitHub App only needs the `checks:read` /// permission. /// /// GitHub Apps with the `checks:write` permission will receive the `rerequested` action without /// subscribing to the check_run webhook event. The `rerequested` action occurs when someone /// requests to re-run your app's check from the pull request UI. See "About status checks" for /// more details about the GitHub UI. When you receive a `rerequested` action, you'll need to /// create a new check run. Only the GitHub App that someone requests to re-run the check will /// receive the `rerequested` payload. Similarly, /// only the GitHub App someone requests to perform /// an action specified by the app will receive the `requested_action` payload. /// /// GitHub Apps that have the `checks:read` permission and subscribe to the `check_run` webhook /// event receive the `created` and `completed` action payloads for all check runs in the app's /// repository. Repositories and organizations that subscribe to the `check_run` webhook event /// only receive `created` and `completed` event actions. CheckRunEvent { /// The action performed. /// Can be `Created,` `Rerequested,` `Completed,` or `RequestedAction`. action: actions::Check, /// The [`check_run`](https://developer.github.com/v3/checks/runs/). check_run: CheckRun, /// repository: Repository, organization: Organization, sender: Sender, installation: Installation, }, /// Triggered when a check suite is `completed`, `requested`, or `rerequested`. The checks permission /// allows you to use the Checks API. If you plan to create or modify check runs, your GitHub /// App will need to have the checks:write permission. If you only plan to consume check runs, /// your GitHub App only needs the checks:read permission. /// /// GitHub Apps with the checks:write permission will receive the requested and `rerequested` /// action payloads without subscribing to the `check_suite` webhook event. /// The `requested` action /// triggers when new code is pushed to the app's repository. A `rerequested` action occurs when /// someone requests to re-run the entire check suite from the pull request UI. See "[About /// status checks](https://help.github.com/articles/about-status-checks#checks)" for more /// details about the GitHub UI. When you receive the `requested` or /// `rerequested` action events, you'll need to /// [create a new check run](https://developer.github.com/v3/checks/runs/#create-a-check-run). /// Only the GitHub App that /// is being asked to run a check will receive the `requested` and `rerequested` payloads. /// /// GitHub Apps that have the `checks:read` permission and /// subscribe to the `check_suite` webhook /// event receive the completed action payload for all check suites in the app's repository. /// Repositories and organizations that subscribe to the `check_suite` /// webhook event only receive /// the `completed` event action. CheckSuiteEvent { /// The action performed. /// Can be `Created,` `Rerequested,` `Completed,` or `RequestedAction.` action: actions::Check, /// The [check_suite](https://developer.github.com/v3/checks/suites/). check_suite: CheckSuite, }, /// Triggered when a /// [commit comment](https://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository) is created. CommitCommentEvent { action: actions::Created, /// The [comment](https://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository) itself. // FIXME comment: Comment, repository: Repository, sender: Sender, }, /// Represents a created repository, branch, or tag. /// Note: webhooks will not receive this event for created repositories. /// Additionally, webhooks will not receive this event for tags /// if more than three tags are pushed at once. CreateEvent { /// The git ref (or `null` if only a repository was created). #[serde(rename = "ref")] ref_field: String, /// The object that was created. Can be one of "repository", "branch", or "tag" ref_type: String, /// The name of the repository's default branch (usually `master`). master_branch: String, /// The repository's current description. description: ::serde_json::Value, pusher_type: String, repository: Repository, sender: Sender, }, /// Represents a [deleted branch or tag](https://developer.github.com/v3/git/refs/#delete-a-reference). /// Note: webhooks will not receive this event for tags /// if more than three tags are deleted at once. DeleteEvent { /// The full git ref. #[serde(rename = "ref")] ref_field: String, /// The object that was deleted. Can be "branch" or "tag". ref_type: String, pusher_type: String, }, /// Represents a [deployment](https://developer.github.com/v3/repos/deployments/#list-deployments). /// /// Events of this type are not visible in timelines. These events are only used to trigger hooks. DeploymentEvent { /// The [deployment](https://developer.github.com/v3/repos/deployments/#list-deployments). deployment: Deployment, /// The [repository](https://developer.github.com/v3/repos/) for this deployment. repository: Repository, sender: Sender, }, /// Represents a [deployment status](https://developer.github.com/v3/repos/deployments/#list-deployment-statuses). /// /// Events of this type are not visible in timelines. /// These events are only used to trigger hooks. DeploymentStatusEvent { /// The [deployment status](https://developer.github.com/v3/repos/deployments/#list-deployment-statuses). deployment_status: DeploymentStatus, /// The [deployment](https://developer.github.com/v3/repos/deployments/#list-deployments) /// that this status is associated with. deployment: Deployment, /// The [repository](https://developer.github.com/v3/repos/) for this deployment. repository: Repository, sender: Sender, }, /// Triggered when a user [forks a /// repository](https://developer.github.com/v3/repos/forks/#create-a-fork). ForkEvent { /// The created [repository](https://developer.github.com/v3/repos/). forkee: Forkee, repository: Repository, sender: Sender, }, /// Triggered when someone revokes their authorization of a GitHub App. A GitHub App receives /// this webhook by default and cannot unsubscribe from this event. /// This event is not available in the [Events API](https://developer.github.com/v3/activity/events/). /// /// Anyone can revoke their authorization of a GitHub App from their /// [GitHub account settings page](https://github.com/settings/apps/authorizations). /// Revoking the authorization of a GitHub App does not uninstall the GitHub App. /// You should program your GitHub App so that when it receives this webhook, /// it stops calling the API on behalf of the person who revoked the token. /// If your GitHub App continues to use a revoked access token, /// it will receive the `401 Bad Credentials` error. /// For details about user-to-server requests, which require GitHub App authorization, /// see ["Identifying and authorizing users for GitHub Apps.](https://developer.github.com/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/)" GitHubAppAuthorizationEvent { action: actions::Revoked, sender: Sender, }, /// Triggered when a Wiki page is created or updated. GollumEvent { pages: Vec<Page>, repository: Repository, sender: Sender, }, /// Triggered when a GitHub App has been installed or uninstalled. InstallationEvent { /// The action that was performed. Can be either `Created` or `Deleted`. action: actions::CreatedDeleted, /// The installation itself. installation: Installation, repositories: Vec<PartialRepository>, sender: Sender, }, InstallationRepositoriesEvent { /// The action that was performed. Can be either `Added` or `Removed`. action: actions::AddedRemoved, /// The installation itself. installation: Installation, /// The choice of repositories the installation is on. Can be either "selected" or "all". repository_selection: String, /// An array of repository objects, which were added to the installation. repositories_added: Vec<PartialRepository>, /// An array of repository objects, which were removed from the installation. repositories_removed: Vec<RepositoriesRemoved>, sender: Sender, }, IssueCommentEvent { /// The action that was performed on the comment. /// Can be one of `Created`, `Edited`, or `Deleted`. action: actions::CrEdDel, /// The changes to the comment if the action was "edited". /// `changes[body][from]: String` The changes to the comment if the action was "edited". // FIXME it's unclear what the structure of changes is. changes: Option<::serde_json::Value>, /// The [issue](https://developer.github.com/v3/issues/) the comment belongs to. issue: Issue, /// The [comment](https://developer.github.com/v3/issues/comments/) itself. comment: Comment, repository: Repository, sender: Sender, }, IssueEvent(IssueEvent), LabelEvent { /// The action that was performed on the comment. /// Can be one of `Created`, `Edited`, or `Deleted`. action: actions::CrEdDel, /// The label that was added. label: Label, /// The changes to the label if the action was "edited". /// `changes[name][from]: String` The previous version of the name if the action was "edited". /// `changes[color][from]: String` The previous version of the color if the action was "edited". changes: Option<serde_json::Value>, repository: Repository, sender: Sender, }, /// Triggered when a user accepts an invitation or is removed as a collaborator to a repository, /// or has their permissions changed. MemberEvent { /// The action that was performed. Can be one of `added`, `deleted`, or `edited`. action: String, /// The user that was added. member: Member, /// The changes to the collaborator permissions if the action was `edited`. changes: MemberEventChanges, repository: Repository, sender: Sender, }, /// Triggered when a user is added or removed from a team. /// /// Events of this type are not visible in timelines. /// These events are only used to trigger hooks. MembershipEvent { /// The action that was performed. Can be "added" or "removed". action: String, /// The scope of the membership. Currently, can only be "team". scope: String, /// The [user](https://developer.github.com/v3/users/) that was added or removed. member: Member, sender: Sender, /// The [team](https://developer.github.com/v3/teams/) for the membership. team: Team, organization: Organization, }, /// Triggered when a milestone is created, closed, opened, edited, or deleted. /// /// Events of this type are not visible in timelines. /// These events are only used to trigger hooks. MilestoneEvent { /// The action that was performed. /// Can be one of `created`, `closed`, `opened`, `edited`, or `deleted`. action: String, /// The milestone itself. milestone: Milestone, /// The changes to the milestone if the action was edited. /// changes[description][from]: String` The previous version of the description if the action was `edited`. /// `changes[due_on][from]: String` The previous version of the due date if the action was `edited`. /// `changes[title][from]: String` The previous version of the title if the action was `edited`. changes: Option<::serde_json::Value>, repository: Repository, sender: Sender, }, /// Triggered when a user is added, removed, or invited to an Organization. /// Events of this type are not visible in timelines. /// These events are only used to trigger organization hooks. OrganizationEvent { /// The action that was performed. /// Can be one of: `member_added`, `member_removed`, or `member_invited`. action: String, /// The invitation for the user or email if the action is member_invited. // FIXME What is the structure of an invitation. invitation: Option<::serde_json::Value>, /// The membership between the user and the organization. /// Not present when the action is `member_invited`. membership: Membership, /// The organization in question. organization: Organization, sender: Sender, }, /// Triggered when an organization blocks or unblocks a user. OrgBlockEvent { /// The action performed. Can be `blocked` or `unblocked`. action: String, /// Information about the user that was blocked or unblocked. blocked_user: User, /// Information about the organization that blocked or unblocked the user. organization: Organization, /// Information about the user who sent the blocking/unblocking request on behalf of the organization. sender: Sender, }, /// Represents an attempted build of a GitHub Pages site, whether successful or not. /// /// Triggered on push to a GitHub Pages enabled branch /// (`gh-pages` for project pages, `master` for user and organization pages). PageBuildEvent { id: i64, /// The page [build](https://developer.github.com/v3/repos/pages/#list-pages-builds) itself. build: Build, repository: Repository, sender: Sender, }, /// Triggered when a [project card](https://developer.github.com/v3/projects/cards) is created, updated, moved, converted to an issue, or deleted. ProjectCardEvent { /// The action performed on the project card. /// Can be "created", "edited", "converted", "moved", or "deleted". action: String, /// The changes to the project card if the action was "edited" or "converted". /// `changes[note][from]: String` The previous version of the note if the action was "edited" or "converted". // FIXME should be enum changes: Option<serde_json::Value>, /// The id of the card that this card now follows if the action was "moved". /// Will be `null` if it is the first card in a column. after_id: Option<isize>, /// The [project card](https://developer.github.com/v3/projects/cards) itself. project_card: ProjectCard, repository: Repository, sender: Sender, }, /// Triggered when a [project column](https://developer.github.com/v3/projects/columns) is created, updated, moved, or deleted. ProjectColumnEvent { /// The action that was performed on the project column. /// Can be one of "created", "edited", "moved" or "deleted". action: String, /// The changes to the project column if the action was "edited". /// `changes[name][from]: String` The previous version of the name if the action was "edited". changes: serde_json::Value, /// The id of the column that this column now follows if the action was "moved". Will be null if it is the first column in a project. after_id: Option<isize>, /// The [project column](https://developer.github.com/v3/projects/columns) itself. project_column: ProjectColumn, repository: Repository, sender: Sender, }, /// Triggered when a [project](https://developer.github.com/v3/projects/) is created, updated, closed, reopened, or deleted. ProjectEvent { /// The action that was performed on the project. Can be one of "created", "edited", "closed", "reopened", or "deleted". action: String, /// The changes to the project if the action was "edited". /// `changes[name][from]: String` The previous version of the name if the action was "edited". /// `changes[body][from]: String` The previous version of the body if the action was "edited". changes: serde_json::Value, /// The [project](https://developer.github.com/v3/projects/) itself. project: Project, repository: Repository, sender: Sender, }, /// Triggered when a private repository is open sourced. /// Without a doubt: the best GitHub event. PublicEvent { repository: Repository, sender: Sender, }, /// Triggered when a pull request is assigned, unassigned, labeled, unlabeled, /// opened, edited, closed, reopened, or synchronized. /// Also triggered when a pull request review is requested, /// or when a review request is removed. PullRequestEvent { /// The action that was performed. /// Can be one of "assigned", "unassigned", "review_requested", /// "review_request_removed", "labeled", "unlabeled", /// "opened", "edited", "closed", or "reopened". /// /// If the action is "closed" and the `merged` key is `false`, /// the pull request was closed with unmerged commits. /// If the action is "closed" and the `merged` key is `true`, /// the pull request was merged. /// /// While webhooks are also triggered when a pull request is synchronized, /// Events API timelines don't include pull request events with the "synchronize" action. action: String, /// The pull request number. number: i64, /// The changes to the comment if the action was "edited". /// `changes[title][from]: String` The previous version of the title if the action was "edited". /// `changes[body][from]: String` The previous version of the body if the action was "edited". changes: serde_json::Value, /// The [pull request](https://developer.github.com/v3/pulls) itself. pull_request: PullRequest, repository: Repository, sender: Sender, }, /// Triggered when a pull request review is submitted into a non-pending state, the body is /// edited, or the review is dismissed. PullRequestReviewEvent { /// The action that was performed on the comment. Can be one of "created", "edited", or "deleted". action: String, /// The changes to the comment if the action was "edited". /// `changes[body][from]: String` The previous version of the body if the action was "edited". changes: serde_json::Value, review: Review, /// The [pull request](https://developer.github.com/v3/pulls/) the comment belongs to. pull_request: PullRequest, /// The [comment](https://developer.github.com/v3/pulls/comments) itself. repository: Repository, sender: Sender, }, /// Triggered when a [comment on a pull request's unified diff](https://developer.github.com/v3/pulls/comments) is created, edited, or deleted (in the Files Changed tab). PullRequestReviewCommentEvent { /// The action that was performed on the comment. Can be one of "created", "edited", or "deleted". action: String, /// The [comment](https://developer.github.com/v3/pulls/comments) itself. comment: Comment, /// The changes to the comment if the action was "edited". /// `changes[body][from]: String` The previous version of the body if the action was "edited". changes: serde_json::Value, /// The [pull request](https://developer.github.com/v3/pulls/) the comment belongs to. pull_request: PullRequest, repository: Repository, sender: Sender, }, /// Triggered on a push to a repository branch. /// Branch pushes and repository tag pushes also trigger webhook [`push` events](https://developer.github.com/webhooks/#events). /// Note: The webhook payload example following the table differs significantly from /// theents API payload described in the table. Among other differences, the webhook /// payload includes both sender and pusher objects. Sender and pusher are the same user /// who initiated the push event, but the sender object contains more detail. PushEvent { // FIXME the note /// The full Git ref that was pushed. Example: `refs/heads/master`. #[serde(rename = "ref")] ref_field: String, /// The SHA of the most recent commit on `ref` after the push. head: Option<String>, /// The SHA of the most recent commit on `ref` before the push. before: String, after: String, /// The number of commits in the push. size: isize, created: bool, deleted: bool, forced: bool, base_ref: ::serde_json::Value, compare: String, /// An array of commit objects describing the pushed commits. /// (The array includes a maximum of 20 commits. /// If necessary, you can use the Commits API to fetch additional commits. /// This limit is applied to timeline events only and isn't applied to webhook deliveries.) commits: Vec<Commit>, head_commit: ::serde_json::Value, repository: Repository, pusher: Pusher, sender: Sender, }, /// Triggered when a /// [release](https://developer.github.com/v3/repos/releases/#get-a-single-release) is published. ReleaseEvent { /// The action that was performed. Currently, can only be "published". action: String, /// The [release](https://developer.github.com/v3/repos/releases/#get-a-single-release) itself. release: Release, repository: Repository, sender: Sender, }, /// Triggered when a repository is created, archived, unarchived, made public, or made private. /// [Organization hooks](https://developer.github.com/v3/orgs/hooks/) are also triggered when a repository is deleted. /// /// Events of this type are not visible in timelines. These events are only used to trigger hooks. RepositoryEvent { /// The action that was performed. This can be one of `created`, `deleted` (organization hooks only), `archived`, `unarchived`, `publicized`, or `privatized`. action: String, /// The [repository](https://developer.github.com/v3/repos/) itself. repository: Repository, sender: Sender, }, /// Triggered when a successful or unsuccessful repository import finishes /// for a GitHub organization or a personal repository. /// To receive this event for a personal repository, /// you must create an empty repository prior to the import. /// This event can be triggered using either the [GitHub Importer](https://help.github.com/articles/importing-a-repository-with-github-importer/) /// or the [Source imports API](https://developer.github.com/v3/migrations/source_imports/). RepositoryImportEvent { /// The final state of the import. This can be either `success` or `failure`. status: String, /// The [repository](https://developer.github.com/v3/repos/) you are importing. repository: Repository, /// The information about the organization where the imported repository will live. organization: Organization, /// The GitHub user who is importing the repository. sender: Sender, }, /// Triggered when a [security alert](https://help.github.com/articles/about-security-alerts-for-vulnerable-dependencies/) is created, dismissed, or resolved. RepositoryVulnerabilityAlertEvent { /// The action that was performed. This can be one of `create`, `dismiss`, or `resolve`. action: String, /// The security alert of the vulnerable dependency. alert: Alert, }, /// Triggered when a new security advisory is published, updated, or withdrawn. /// A security advisory provides information about security-related vulnerabilities in software on GitHub. /// Security Advisory webhooks are available to GitHub Apps only. /// The security advisory dataset also powers the GitHub security alerts, /// see "[About security alerts for vulnerable dependencies](https://help.github.com/articles/about-security-alerts-for-vulnerable-dependencies/)." SecurityAdvisoryEvent { /// The action that was performed. The action can be one of `published`, `updated`, or `performed` for all new events. action: String, /// The details of the security advisory, including summary, description, and severity. security_advisory: SecurityAdvisory, }, /// Triggered when the status of a Git commit changes. /// Events of this type are not visible in timelines. These events are only used to trigger hooks. StatusEvent { id: i64, /// The Commit SHA. sha: String, name: String, /// The optional link added to the status. // FIXME will Option parse {}? target_url: Option<String>, context: String, /// The optional human-readable description added to the status. // FIXME will Option parse {}? description: Option<String>, /// The new state. Can be `pending`, `success`, `failure`, or `error`. state: String, commit: Commit, /// An array of branch objects containing the status' SHA. /// Each branch contains the given SHA, but the SHA may or may not be the head of the branch. /// The array includes a maximum of 10 branches. branches: Vec<Bran>, created_at: String, updated_at: String, repository: Repository, sender: Sender, }, /// Triggered when an organization's team is created or deleted. /// /// Events of this type are not visible in timelines. These events are only used to trigger organization hooks. TeamEvent { /// The action that was performed. /// Can be one of `Created`, `Deleted`, `Edited`, `AddedToRepository`, or `RemovedFromRepository`. action: actions::TeamEvent, /// The team itself. team: Team, /// The changes to the team if the action was "edited". /// `changes[description][from]: String` The previous version of the description if the action was `edited`. /// `changes[name][from]: String` The previous version of the name if the action was `edited`. /// The previous version of the team's privacy if the action was `edited`. /// /// `changes[repository][permissions][from][admin]: bool` /// The previous version of the team member's `admin` permission on a repository, if the action was `edited`. /// /// `changes[repository][permissions][from][pull]: bool` /// The previous version of the team member's `pull` permission on a repository, if the action was `edited`. /// /// `changes[repository][permissions][from][push]: bool` /// The previous version of the team member's `push` permission on a repository, if the action was `edited`. changes: serde_json::Value, /// The repository that was added or removed from to the team's purview if the action was `added_to_repository`, `removed_from_repository`, or `edited`. For `edited` actions, `repository` also contains the team's new permission levels for the repository. repository: TeamEventRepository, organization: Organization, sender: Sender, }, /// Triggered when a [repository is added to a /// team](https://developer.github.com/v3/teams/#add-or-update-team-repository). /// /// Events of this type are not visible in timelines. These events are only used to trigger hooks. TeamAddEvent { /// The [team](https://developer.github.com/v3/teams/) that was modified. Note: older events may not include this in the payload. team: Team, /// The [repository](https://developer.github.com/v3/repos/) that was added to this team. repository: Repository, organization: Organization, sender: Sender, }, /// The WatchEvent is related to [starring a repository](https://developer.github.com/v3/activity/starring/#star-a-repository), /// not [watching](https://developer.github.com/v3/activity/watching/). /// See [this API blog post](https://developer.github.com/changes/2012-09-05-watcher-api/) for an explanation. /// /// The event’s actor is the [user](https://developer.github.com/v3/users/) who starred a repository, /// and the event’s repository is the [repository](https://developer.github.com/v3/repos/) that was starred. WatchEvent { /// The action that was performed. Currently, can only be `started`. action: String, repository: Repository, sender: Sender, }, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct IssueEvent { /// The action that was performed. Can be one of `opened`, `edited`, `deleted`, `transferred`, `closed`, /// `reopened`, `assigned`, `unassigned`, `labeled`, `unlabeled`, `milestoned`, or `demilestoned`. action: String, /// The [issue](https://developer.github.com/v3/issues) itself. issue: Issue, /// The changes to the issue if the action was "edited". /// `changes[title][from]: String` The previous version of the title if the action was "edited". /// `changes[body][from]:String` The previous version of the body if the action was "edited". changes: Option<::serde_json::Value>, repository: Repository, sender: Sender, } /// FIXME add docs [`check_run`](https://developer.github.com/v3/checks/runs/) #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct CheckRun { /// The id of the check suite that this check run is part of. id: i64, head_sha: String, external_id: String, url: String, html_url: String, /// The current status of the check run. Can be `queued,` `in_progress,` or `completed.` // FIXME should be enum status: String, /// The result of the completed `check` run. /// Can be one of `success,` `failure,` `neutral,` `cancelled,` /// timed_out, or `action_required.` /// This value will be `null` until the check run has `completed.` // FIXME should be enum conclusion: Option<String>, started_at: String, completed_at: String, output: Output, /// The name of the check run. name: String, check_suite: CheckSuite, app: App, pull_requests: Vec<::serde_json::Value>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Output { title: String, summary: String, text: String, annotations_count: i64, annotations_url: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct CheckSuite { id: i64, /// The head branch name the changes are on. head_branch: String, /// The SHA of the most recent commit for this check suite. head_sha: String, /// The summary status for all check runs that are part of the check suite. /// Can be `requested`, `in_progress`, or `completed`. status: String, /// The summary conclusion for all check runs that are part of the check suite. Can be one /// `success`, `failure`, `neutral`, `cancelled`, `timed_out`, or `action_required`. /// This value will be `null` until the check run has `completed`. conclusion: String, /// URL that points to the check suite API resource. url: String, before: String, after: String, /// An array of pull requests that match this check suite. A pull request matches a check suite if /// they have the same `head_sha` and head_branch. When the check suite's `head_branch` is unknown /// (`null`) the `pull_requests` array will be empty. pull_requests: Vec<::serde_json::Value>, app: App, created_at: String, updated_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct App { id: i64, node_id: String, owner: Owner, name: String, description: ::serde_json::Value, external_url: String, html_url: String, created_at: String, updated_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Organization { login: String, id: i64, node_id: String, url: String, repos_url: String, events_url: String, hooks_url: String, issues_url: String, members_url: String, public_members_url: String, avatar_url: String, description: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Sender { login: String, id: i64, node_id: String, avatar_url: String, gravatar_id: String, url: String, html_url: String, followers_url: String, following_url: String, gists_url: String, starred_url: String, subscriptions_url: String, organizations_url: String, repos_url: String, events_url: String, received_events_url: String, #[serde(rename = "type")] type_field: String, site_admin: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Installation { id: i64, account: Account, repository_selection: String, access_tokens_url: String, repositories_url: String, html_url: String, app_id: i64, target_id: i64, target_type: String, permissions: Permissions, events: Vec<String>, created_at: i64, updated_at: i64, single_file_name: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct GeneratedType { action: String, check_suite: CheckSuite, repository: Repository, organization: Organization, sender: Sender, installation: Installation, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct HeadCommit { id: String, tree_id: String, message: String, timestamp: String, author: Author, committer: Committer, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Author { /// The git author's name. name: String, /// The git author's email address. email: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Committer { name: String, email: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct User { login: String, id: i64, node_id: String, avatar_url: String, gravatar_id: String, url: String, html_url: String, followers_url: String, following_url: String, gists_url: String, starred_url: String, subscriptions_url: String, organizations_url: String, repos_url: String, events_url: String, received_events_url: String, #[serde(rename = "type")] type_field: String, site_admin: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Comment { url: String, html_url: String, id: i64, node_id: String, user: User, position: ::serde_json::Value, line: ::serde_json::Value, path: ::serde_json::Value, commit_id: String, created_at: String, updated_at: String, author_association: String, body: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Deployment { url: String, id: i64, node_id: String, sha: String, #[serde(rename = "ref")] ref_field: String, task: String, payload: Payload, environment: String, description: ::serde_json::Value, creator: Creator, created_at: String, updated_at: String, statuses_url: String, repository_url: String, } /// FIXME Empty? #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Payload {} #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Creator { login: String, id: i64, node_id: String, avatar_url: String, gravatar_id: String, url: String, html_url: String, followers_url: String, following_url: String, gists_url: String, starred_url: String, subscriptions_url: String, organizations_url: String, repos_url: String, events_url: String, received_events_url: String, #[serde(rename = "type")] type_field: String, site_admin: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct DeploymentStatus { url: String, id: i64, node_id: String, /// The new state. Can be `pending`, `success`, `failure`, or `error`. state: String, creator: Creator, /// The optional human-readable description added to the status. description: String, /// The optional link added to the status. target_url: String, created_at: String, updated_at: String, deployment_url: String, repository_url: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Forkee { id: i64, node_id: String, name: String, full_name: String, owner: Owner, private: bool, html_url: String, description: ::serde_json::Value, fork: bool, url: String, forks_url: String, keys_url: String, collaborators_url: String, teams_url: String, hooks_url: String, issue_events_url: String, events_url: String, assignees_url: String, branches_url: String, tags_url: String, blobs_url: String, git_tags_url: String, git_refs_url: String, trees_url: String, statuses_url: String, languages_url: String, stargazers_url: String, contributors_url: String, subscribers_url: String, subscription_url: String, commits_url: String, git_commits_url: String, comments_url: String, issue_comment_url: String, contents_url: String, compare_url: String, merges_url: String, archive_url: String, downloads_url: String, issues_url: String, pulls_url: String, milestones_url: String, notifications_url: String, labels_url: String, releases_url: String, deployments_url: String, created_at: String, updated_at: String, pushed_at: String, git_url: String, ssh_url: String, clone_url: String, svn_url: String, homepage: ::serde_json::Value, size: i64, stargazers_count: i64, watchers_count: i64, language: ::serde_json::Value, has_issues: bool, has_projects: bool, has_downloads: bool, has_wiki: bool, has_pages: bool, forks_count: i64, mirror_url: ::serde_json::Value, archived: bool, open_issues_count: i64, license: ::serde_json::Value, forks: i64, open_issues: i64, watchers: i64, default_branch: String, public: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Page { /// The name of the page. page_name: String, /// The current page title. title: String, summary: ::serde_json::Value, /// The action that was performed on the page. Can be "created" or "edited". action: String, /// The latest commit SHA of the page. sha: String, /// Points to the HTML wiki page. html_url: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Account { login: String, id: i64, node_id: String, avatar_url: String, gravatar_id: String, url: String, html_url: String, followers_url: String, following_url: String, gists_url: String, starred_url: String, subscriptions_url: String, organizations_url: String, repos_url: String, events_url: String, received_events_url: String, #[serde(rename = "type")] type_field: String, site_admin: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Permissions { metadata: String, contents: String, issues: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct PartialRepository { id: i64, name: String, full_name: String, private: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct RepositoriesRemoved { id: i64, name: String, full_name: String, private: bool, } /// Triggered when an [issue comment](https://developer.github.com/v3/issues/comments/) is created, edited, or deleted. #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Issue { url: String, repository_url: String, labels_url: String, comments_url: String, events_url: String, html_url: String, id: i64, node_id: String, number: i64, title: String, user: User, /// The optional labels that were added or removed from the issue. labels: Vec<Label>, state: String, locked: bool, /// The optional user who was assigned or unassigned from the issue. assignee: ::serde_json::Value, assignees: Vec<::serde_json::Value>, milestone: ::serde_json::Value, comments: i64, created_at: String, updated_at: String, closed_at: ::serde_json::Value, author_association: String, body: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Label { id: i64, node_id: String, url: String, name: String, color: String, default: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Member { login: String, id: i64, node_id: String, avatar_url: String, gravatar_id: String, url: String, html_url: String, followers_url: String, following_url: String, gists_url: String, starred_url: String, subscriptions_url: String, organizations_url: String, repos_url: String, events_url: String, received_events_url: String, #[serde(rename = "type")] type_field: String, site_admin: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct MemberEventChanges { /// The previous permissions of the collaborator if the action was `edited` permission: Permission, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Permission { from: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Team { name: String, id: i64, node_id: String, slug: String, description: String, privacy: String, url: String, members_url: String, repositories_url: String, permission: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Milestone { url: String, html_url: String, labels_url: String, id: i64, node_id: String, number: i64, title: String, description: String, creator: Creator, open_issues: i64, closed_issues: i64, state: String, created_at: String, updated_at: String, due_on: String, closed_at: ::serde_json::Value, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Membership { url: String, state: String, role: String, organization_url: String, user: User, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Build { url: String, status: String, error: Error, pusher: Pusher, commit: String, duration: i64, created_at: String, updated_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Error { message: ::serde_json::Value, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Pusher { login: String, id: i64, node_id: String, avatar_url: String, gravatar_id: String, url: String, html_url: String, followers_url: String, following_url: String, gists_url: String, starred_url: String, subscriptions_url: String, organizations_url: String, repos_url: String, events_url: String, received_events_url: String, #[serde(rename = "type")] type_field: String, site_admin: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct ProjectCard { url: String, project_url: String, column_url: String, column_id: i64, id: i64, node_id: String, note: String, creator: Creator, created_at: String, updated_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct ProjectColumn { url: String, project_url: String, cards_url: String, id: i64, node_id: String, name: String, created_at: String, updated_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Project { owner_url: String, url: String, html_url: String, columns_url: String, id: i64, node_id: String, name: String, body: String, number: i64, state: String, creator: Creator, created_at: String, updated_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct PullRequest { url: String, id: i64, node_id: String, html_url: String, diff_url: String, patch_url: String, issue_url: String, number: i64, state: String, locked: bool, title: String, user: User, body: String, created_at: String, updated_at: String, closed_at: String, merged_at: ::serde_json::Value, merge_commit_sha: String, assignee: ::serde_json::Value, assignees: Vec<::serde_json::Value>, requested_reviewers: Vec<::serde_json::Value>, requested_teams: Vec<::serde_json::Value>, labels: Vec<::serde_json::Value>, milestone: ::serde_json::Value, commits_url: String, review_comments_url: String, review_comment_url: String, comments_url: String, statuses_url: String, head: Head, base: Base, _links: Links, author_association: String, merged: bool, mergeable: bool, rebaseable: bool, mergeable_state: String, merged_by: ::serde_json::Value, comments: i64, review_comments: i64, maintainer_can_modify: bool, commits: i64, additions: i64, deletions: i64, changed_files: i64, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Head { label: String, #[serde(rename = "ref")] ref_field: String, sha: String, user: User, repo: Repository, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Base { label: String, #[serde(rename = "ref")] ref_field: String, sha: String, user: User, repo: Repository, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Links { #[serde(rename = "self")] self_field: Link, html: Link, issue: Link, comments: Link, review_comments: Link, review_comment: Link, commits: Link, statuses: Link, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Link { href: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Review { id: i64, node_id: String, user: User, body: ::serde_json::Value, commit_id: String, submitted_at: String, state: String, html_url: String, pull_request_url: String, author_association: String, _links: ReviewLinks, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct ReviewLinks { html: Link, pull_request: PullRequest, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Commit { /// The SHA of the commit. sha: String, /// The commit message. message: String, /// The git author of the commit. author: Author, /// URL that points to the commit API resource. url: String, /// Whether this commit is distinct from any that have been pushed before. distinct: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Release { url: String, assets_url: String, upload_url: String, html_url: String, id: i64, node_id: String, tag_name: String, target_commitish: String, name: ::serde_json::Value, draft: bool, author: ReleaseAuthor, prerelease: bool, created_at: String, published_at: String, assets: Vec<::serde_json::Value>, tarball_url: String, zipball_url: String, body: ::serde_json::Value, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct ReleaseAuthor { login: String, id: i64, node_id: String, avatar_url: String, gravatar_id: String, url: String, html_url: String, followers_url: String, following_url: String, gists_url: String, starred_url: String, subscriptions_url: String, organizations_url: String, repos_url: String, events_url: String, received_events_url: String, #[serde(rename = "type")] type_field: String, site_admin: bool, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Alert { id: i64, affected_range: String, affected_package_name: String, external_reference: String, external_identifier: String, fixed_in: String, dismisser: User, dismiss_reason: String, dismissed_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct SecurityAdvisory { ghsa_id: String, summary: String, description: String, severity: String, identifiers: Vec<Identifier>, references: Vec<Reference>, published_at: String, updated_at: String, withdrawn_at: ::serde_json::Value, vulnerabilities: Vec<Vulnerability>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Identifier { value: String, #[serde(rename = "type")] type_field: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Reference { url: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Vulnerability { package: Package, severity: String, vulnerable_version_range: String, first_patched_version: FirstPatchedVersion, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Package { ecosystem: String, name: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct FirstPatchedVersion { identifier: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct StatusEventCommitNode { sha: String, node_id: String, commit: CommitTree, url: String, html_url: String, comments_url: String, author: AuthorDate, committer: CommitterDate, parents: Vec<::serde_json::Value>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct CommitTree { author: AuthorDate, committer: CommitterDate, message: String, tree: Tree, url: String, comment_count: i64, verification: Verification, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct AuthorDate { name: String, email: String, date: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct CommitterDate { name: String, email: String, date: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Tree { sha: String, url: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Verification { verified: bool, reason: String, signature: String, payload: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct Bran { name: String, commit: Commit, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct TeamEventRepository { id: i64, node_id: String, name: String, full_name: String, owner: Owner, private: bool, html_url: String, description: ::serde_json::Value, fork: bool, url: String, forks_url: String, keys_url: String, collaborators_url: String, teams_url: String, hooks_url: String, issue_events_url: String, events_url: String, assignees_url: String, branches_url: String, tags_url: String, blobs_url: String, git_tags_url: String, git_refs_url: String, trees_url: String, statuses_url: String, languages_url: String, stargazers_url: String, contributors_url: String, subscribers_url: String, subscription_url: String, commits_url: String, git_commits_url: String, comments_url: String, issue_comment_url: String, contents_url: String, compare_url: String, merges_url: String, archive_url: String, downloads_url: String, issues_url: String, pulls_url: String, milestones_url: String, notifications_url: String, labels_url: String, releases_url: String, deployments_url: String, created_at: String, updated_at: String, pushed_at: String, git_url: String, ssh_url: String, clone_url: String, svn_url: String, homepage: ::serde_json::Value, size: i64, stargazers_count: i64, watchers_count: i64, language: ::serde_json::Value, has_issues: bool, has_projects: bool, has_downloads: bool, has_wiki: bool, has_pages: bool, forks_count: i64, mirror_url: ::serde_json::Value, archived: bool, open_issues_count: i64, license: ::serde_json::Value, forks: i64, open_issues: i64, watchers: i64, default_branch: String, permissions: TeamEventPermissions, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] struct TeamEventPermissions { pull: bool, push: bool, admin: bool, }
true
00de2ee1f0139b0ace37aad1ab8bf05ded17e5ea
Rust
delaneyj/wankel
/src/math/spherical.rs
UTF-8
1,302
3.796875
4
[ "MIT" ]
permissive
use std::f32::consts::PI; use std::f32::EPSILON; use math::*; // Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system // The poles (phi) are at the positive and negative y axis. // The equator starts at positive z. #[derive(Debug,PartialEq)] pub struct Spherical { pub radius: f32, pub phi: f32, pub theta: f32, } impl Spherical { pub const DEFAULT: Spherical = Spherical { radius: 1.0, phi: 0.0, // up / down towards top and bottom pole theta: 0.0, // around the equator of the sphere }; pub fn new(radius: f32, phi: f32, theta: f32) -> Spherical { Spherical { radius: radius, phi: phi, theta: theta, } } // restrict phi to be betwee EPS and PI-EPS pub fn make_safe(&self) -> Spherical { Spherical { phi: self.phi.min(PI - EPSILON).max(EPSILON), ..*self } } pub fn from_vector3(vec3: &Vector3) -> Spherical { let radius = vec3.length(); if radius == 0.0 { Spherical::new(radius, 0.0, 0.0) } else { let phi = clamp(vec3.y / radius, -1.0, 1.0).acos(); // polar angle let theta = vec3.x.atan2(vec3.z);// equator angle around y-up axis Spherical::new(radius, phi, theta) } } }
true
2349c73ab6b4356123f1778d10a6533c35f5e9ae
Rust
pixix4/ev3dev-lang-rust
/src/motors/tacho_motor_macro.rs
UTF-8
29,645
3.390625
3
[ "MIT" ]
permissive
//! The TachoMotor provides a uniform interface for using motors with positional //! and directional feedback such as the EV3 and NXT motors. //! This feedback allows for precise control of the motors. /// The TachoMotor provides a uniform interface for using motors with positional /// and directional feedback such as the EV3 and NXT motors. /// This feedback allows for precise control of the motors. #[macro_export] macro_rules! tacho_motor { () => { /// Causes the motor to run until another command is sent. pub const COMMAND_RUN_FOREVER: &'static str = "run-forever"; /// Runs the motor to an absolute position specified by `position_sp` /// and then stops the motor using the command specified in `stop_action`. pub const COMMAND_RUN_TO_ABS_POS: &'static str = "run-to-abs-pos"; /// Runs the motor to a position relative to the current position value. /// The new position will be current `position` + `position_sp`. /// When the new position is reached, the motor will stop using the command specified by `stop_action`. pub const COMMAND_RUN_TO_REL_POS: &'static str = "run-to-rel-pos"; /// Run the motor for the amount of time specified in `time_sp` /// and then stops the motor using the command specified by `stop_action`. pub const COMMAND_RUN_TIMED: &'static str = "run-timed"; /// Runs the motor using the duty cycle specified by `duty_cycle_sp`. /// Unlike other run commands, changing `duty_cycle_sp` while running will take effect immediately. pub const COMMAND_RUN_DIRECT: &'static str = "run-direct"; /// Stop any of the run commands before they are complete using the command specified by `stop_action`. pub const COMMAND_STOP: &'static str = "stop"; /// Resets all of the motor parameter attributes to their default values. /// This will also have the effect of stopping the motor. pub const COMMAND_RESET: &'static str = "reset"; /// A positive duty cycle will cause the motor to rotate clockwise. pub const POLARITY_NORMAL: &'static str = "normal"; /// A positive duty cycle will cause the motor to rotate counter-clockwise. pub const POLARITY_INVERSED: &'static str = "inversed"; /// Power is being sent to the motor. pub const STATE_RUNNING: &'static str = "running"; /// The motor is ramping up or down and has not yet reached a pub constant output level. pub const STATE_RAMPING: &'static str = "ramping"; /// The motor is not turning, but rather attempting to hold a fixed position. pub const STATE_HOLDING: &'static str = "holding"; /// The motor is turning as fast as possible, but cannot reach its `speed_sp`. pub const STATE_OVERLOADED: &'static str = "overloaded"; /// The motor is trying to run but is not turning at all. pub const STATE_STALLED: &'static str = "stalled"; /// Removes power from the motor. The motor will freely coast to a stop. pub const STOP_ACTION_COAST: &'static str = "coast"; /// Removes power from the motor and creates a passive electrical load. /// This is usually done by shorting the motor terminals together. /// This load will absorb the energy from the rotation of the motors /// and cause the motor to stop more quickly than coasting. pub const STOP_ACTION_BRAKE: &'static str = "brake"; /// Causes the motor to actively try to hold the current position. /// If an external force tries to turn the motor, the motor will “push back” to maintain its position. pub const STOP_ACTION_HOLD: &'static str = "hold"; /// Returns the number of tacho counts in one rotation of the motor. /// /// Tacho counts are used by the position and speed attributes, /// so you can use this value to convert from rotations or degrees to tacho counts. /// (rotation motors only) /// /// # Examples /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// // Get position and count_per_rot as f32. /// let position = motor.get_position()? as f32; /// let count_per_rot = motor.get_count_per_rot()? as f32; /// /// // Calculate the rotation count. /// let rotations = position / count_per_rot; /// /// println!("The motor did {:.2} rotations", rotations); /// # Ok(()) /// # } /// ``` pub fn get_count_per_rot(&self) -> Ev3Result<i32> { self.get_attribute("count_per_rot").get() } /// Returns the number of tacho counts in one meter of travel of the motor. /// /// Tacho counts are used by the position and speed attributes, /// so you can use this value to convert from distance to tacho counts. /// (linear motors only) pub fn get_count_per_m(&self) -> Ev3Result<i32> { self.get_attribute("count_per_m").get() } /// Returns the number of tacho counts in the full travel of the motor. /// /// When combined with the count_per_m attribute, /// you can use this value to calculate the maximum travel distance of the motor. /// (linear motors only) pub fn get_full_travel_count(&self) -> Ev3Result<i32> { self.get_attribute("full_travel_count").get() } /// Returns the current duty cycle of the motor. Units are percent. /// /// Values are -100 to 100. /// /// # Examples /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::thread; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// // Set the motor command `run-direct` to start rotation. /// motor.run_direct()?; /// /// // Rotate motor forward and wait 5 seconds. /// motor.set_duty_cycle_sp(50)?; /// thread::sleep(Duration::from_secs(5)); /// /// assert_eq!(motor.get_duty_cycle()?, 50); /// # Ok(()) /// # } pub fn get_duty_cycle(&self) -> Ev3Result<i32> { self.get_attribute("duty_cycle").get() } /// Returns the current duty cycle setpoint of the motor. /// /// Units are in percent. /// Valid values are -100 to 100. A negative value causes the motor to rotate in reverse. /// /// # Examples /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::thread; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// // Rotate motor forward and wait 5 seconds. /// motor.set_duty_cycle_sp(50)?; /// thread::sleep(Duration::from_secs(5)); /// /// assert_eq!(motor.get_duty_cycle()?, 50); /// # Ok(()) /// # } pub fn get_duty_cycle_sp(&self) -> Ev3Result<i32> { self.get_attribute("duty_cycle_sp").get() } /// Sets the duty cycle setpoint of the motor. /// /// Units are in percent. /// Valid values are -100 to 100. A negative value causes the motor to rotate in reverse. /// /// # Examples /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::thread; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// // Set the motor command `run-direct` to start rotation. /// motor.run_direct()?; /// /// // Rotate motor forward and wait 5 seconds. /// motor.set_duty_cycle_sp(50)?; /// thread::sleep(Duration::from_secs(5)); /// /// // Rotate motor backward and wait 5 seconds. /// motor.set_duty_cycle_sp(-50)?; /// thread::sleep(Duration::from_secs(5)); /// # Ok(()) /// # } pub fn set_duty_cycle_sp(&self, duty_cycle: i32) -> Ev3Result<()> { self.get_attribute("duty_cycle_sp").set(duty_cycle) } /// Returns the current polarity of the motor. pub fn get_polarity(&self) -> Ev3Result<String> { self.get_attribute("polarity").get() } /// Sets the polarity of the motor. pub fn set_polarity(&self, polarity: &str) -> Ev3Result<()> { self.get_attribute("polarity").set_str_slice(polarity) } /// Returns the current position of the motor in pulses of the rotary encoder. /// /// When the motor rotates clockwise, the position will increase. /// Likewise, rotating counter-clockwise causes the position to decrease. /// The range is -2,147,483,648 and +2,147,483,647 tachometer counts (32-bit signed integer) /// /// # Examples /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// // Get position and count_per_rot as f32. /// let position = motor.get_position()? as f32; /// let count_per_rot = motor.get_count_per_rot()? as f32; /// /// // Calculate the rotation count. /// let rotations: f32 = position / count_per_rot; /// /// println!("The motor did {:.2} rotations", rotations); /// # Ok(()) /// # } /// ``` pub fn get_position(&self) -> Ev3Result<i32> { self.get_attribute("position").get() } /// Sets the current position of the motor in pulses of the rotary encoder. /// /// When the motor rotates clockwise, the position will increase. /// Likewise, rotating counter-clockwise causes the position to decrease. /// The range is -2,147,483,648 and +2,147,483,647 tachometer counts (32-bit signed integer) /// /// # Examples /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// motor.set_position(0)?; /// let position = motor.get_position()?; /// /// // If the motor is not moving, the position value /// // should not change between set and get operation. /// assert_eq!(position, 0); /// # Ok(()) /// # } /// ``` pub fn set_position(&self, position: i32) -> Ev3Result<()> { self.get_attribute("position").set(position) } /// Returns the proportional pub constant for the position PID. pub fn get_hold_pid_kp(&self) -> Ev3Result<f32> { self.get_attribute("hold_pid/Kp").get() } /// Sets the proportional pub constant for the position PID. pub fn set_hold_pid_kp(&self, kp: f32) -> Ev3Result<()> { self.get_attribute("hold_pid/Kp").set(kp) } /// Returns the integral pub constant for the position PID. pub fn get_hold_pid_ki(&self) -> Ev3Result<f32> { self.get_attribute("hold_pid/Ki").get() } /// Sets the integral pub constant for the position PID. pub fn set_hold_pid_ki(&self, ki: f32) -> Ev3Result<()> { self.get_attribute("hold_pid/Ki").set(ki) } /// Returns the derivative pub constant for the position PID. pub fn get_hold_pid_kd(&self) -> Ev3Result<f32> { self.get_attribute("hold_pid/Kd").get() } /// Sets the derivative pub constant for the position PID. pub fn set_hold_pid_kd(&self, kd: f32) -> Ev3Result<()> { self.get_attribute("hold_pid/Kd").set(kd) } /// Returns the maximum value that is accepted by the `speed_sp` attribute. /// /// This value is the speed of the motor at 9V with no load. /// Note: The actual maximum obtainable speed will be less than this /// and will depend on battery voltage and mechanical load on the motor. pub fn get_max_speed(&self) -> Ev3Result<i32> { self.get_attribute("max_speed").get() } /// Returns the current target position for the `run-to-abs-pos` and `run-to-rel-pos` commands. /// /// Units are in tacho counts. /// You can use the value returned by `counts_per_rot` to convert tacho counts to/from rotations or degrees. /// /// The range is -2,147,483,648 and +2,147,483,647 tachometer counts (32-bit signed integer). pub fn get_position_sp(&self) -> Ev3Result<i32> { self.get_attribute("position_sp").get() } /// Sets the target position for the `run-to-abs-pos` and `run-to-rel-pos` commands. /// /// Units are in tacho counts. /// You can use the value returned by `counts_per_rot` to convert tacho counts to/from rotations or degrees. /// /// The range is -2,147,483,648 and +2,147,483,647 tachometer counts (32-bit signed integer). /// /// # Examples /// /// ```ignore /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::thread; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// // Save the current position. /// let old_position = motor.get_position()?; /// /// // Rotate by 100 ticks /// let position = motor.set_position_sp(100)?; /// motor.run_to_rel_pos(None)?; /// /// // Wait till rotation is finished. /// motor.wait_until_not_moving(None); /// /// // The new position should be 100 ticks larger. /// let new_position = motor.get_position()?; /// assert_eq!(old_position + 100, new_position); /// # Ok(()) /// # } /// ``` pub fn set_position_sp(&self, position_sp: i32) -> Ev3Result<()> { self.get_attribute("position_sp").set(position_sp) } /// Returns the current motor speed in tacho counts per second. /// /// Note, this is not necessarily degrees (although it is for LEGO motors). /// Use the `count_per_rot` attribute to convert this value to RPM or deg/sec. pub fn get_speed(&self) -> Ev3Result<i32> { self.get_attribute("speed").get() } /// Returns the target speed in tacho counts per second used for all run-* commands except run-direct. /// /// A negative value causes the motor to rotate in reverse /// with the exception of run-to-*-pos commands where the sign is ignored. /// Use the `count_per_rot` attribute to convert RPM or deg/sec to tacho counts per second. /// Use the `count_per_m` attribute to convert m/s to tacho counts per second. pub fn get_speed_sp(&self) -> Ev3Result<i32> { self.get_attribute("speed_sp").get() } /// Sets the target speed in tacho counts per second used for all run-* commands except run-direct. /// /// A negative value causes the motor to rotate in reverse /// with the exception of run-to-*-pos commands where the sign is ignored. /// Use the `count_per_rot` attribute to convert RPM or deg/sec to tacho counts per second. /// Use the `count_per_m` attribute to convert m/s to tacho counts per second. pub fn set_speed_sp(&self, speed_sp: i32) -> Ev3Result<()> { self.get_attribute("speed_sp").set(speed_sp) } /// Returns the current ramp up setpoint. /// /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will increase from 0 to 100% of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and max_speed multiplied by ramp_up_sp. Values must not be negative. pub fn get_ramp_up_sp(&self) -> Ev3Result<i32> { self.get_attribute("ramp_up_sp").get() } /// Sets the ramp up setpoint. /// /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will increase from 0 to 100% of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and max_speed multiplied by ramp_up_sp. Values must not be negative. pub fn set_ramp_up_sp(&self, ramp_up_sp: i32) -> Ev3Result<()> { self.get_attribute("ramp_up_sp").set(ramp_up_sp) } /// Returns the current ramp down setpoint. /// /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will decrease from 100% down to 0 of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and 0 multiplied by ramp_down_sp. Values must not be negative. pub fn get_ramp_down_sp(&self) -> Ev3Result<i32> { self.get_attribute("ramp_down_sp").get() } /// Sets the ramp down setpoint. /// /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will decrease from 100% down to 0 of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and 0 multiplied by ramp_down_sp. Values must not be negative. pub fn set_ramp_down_sp(&self, ramp_down_sp: i32) -> Ev3Result<()> { self.get_attribute("ramp_down_sp").set(ramp_down_sp) } /// Returns the proportional pub constant for the speed regulation PID. pub fn get_speed_pid_kp(&self) -> Ev3Result<f32> { self.get_attribute("speed_pid/Kp").get() } /// Sets the proportional pub constant for the speed regulation PID. pub fn set_speed_pid_kp(&self, kp: f32) -> Ev3Result<()> { self.get_attribute("speed_pid/Kp").set(kp) } /// Returns the integral pub constant for the speed regulation PID. pub fn get_speed_pid_ki(&self) -> Ev3Result<f32> { self.get_attribute("speed_pid/Ki").get() } /// Sets the integral pub constant for the speed regulation PID. pub fn set_speed_pid_ki(&self, ki: f32) -> Ev3Result<()> { self.get_attribute("speed_pid/Ki").set(ki) } /// Returns the derivative pub constant for the speed regulation PID. pub fn get_speed_pid_kd(&self) -> Ev3Result<f32> { self.get_attribute("speed_pid/Kd").get() } /// Sets the derivative pub constant for the speed regulation PID. pub fn set_speed_pid_kd(&self, kd: f32) -> Ev3Result<()> { self.get_attribute("speed_pid/Kd").set(kd) } /// Returns a list of state flags. pub fn get_state(&self) -> Ev3Result<Vec<String>> { self.get_attribute("state").get_vec() } /// Returns the current stop action. /// /// The value determines the motors behavior when command is set to stop. pub fn get_stop_action(&self) -> Ev3Result<String> { self.get_attribute("stop_action").get() } /// Sets the stop action. /// /// The value determines the motors behavior when command is set to stop. pub fn set_stop_action(&self, stop_action: &str) -> Ev3Result<()> { self.get_attribute("stop_action").set_str_slice(stop_action) } /// Returns a list of stop actions supported by the motor controller. pub fn get_stop_actions(&self) -> Ev3Result<Vec<String>> { self.get_attribute("stop_actions").get_vec() } /// Returns the current amount of time the motor will run when using the run-timed command. /// /// Units are in milliseconds. Values must not be negative. pub fn get_time_sp(&self) -> Ev3Result<i32> { self.get_attribute("time_sp").get() } /// Sets the amount of time the motor will run when using the run-timed command. /// /// Units are in milliseconds. Values must not be negative. pub fn set_time_sp(&self, time_sp: i32) -> Ev3Result<()> { self.get_attribute("time_sp").set(time_sp) } /// Runs the motor using the duty cycle specified by `duty_cycle_sp`. /// /// Unlike other run commands, changing `duty_cycle_sp` while running will take effect immediately. pub fn run_direct(&self) -> Ev3Result<()> { self.set_command(Self::COMMAND_RUN_DIRECT) } /// Causes the motor to run until another command is sent. pub fn run_forever(&self) -> Ev3Result<()> { self.set_command(Self::COMMAND_RUN_FOREVER) } /// Runs the motor to an absolute position specified by `position_sp` /// /// and then stops the motor using the command specified in `stop_action`. pub fn run_to_abs_pos(&self, position_sp: Option<i32>) -> Ev3Result<()> { if let Some(p) = position_sp { self.set_position_sp(p)?; } self.set_command(Self::COMMAND_RUN_TO_ABS_POS) } /// Runs the motor to a position relative to the current position value. /// /// The new position will be current `position` + `position_sp`. /// When the new position is reached, the motor will stop using the command specified by `stop_action`. pub fn run_to_rel_pos(&self, position_sp: Option<i32>) -> Ev3Result<()> { if let Some(p) = position_sp { self.set_position_sp(p)?; } self.set_command(Self::COMMAND_RUN_TO_REL_POS) } /// Run the motor for the amount of time specified in `time_sp` /// /// and then stops the motor using the command specified by `stop_action`. pub fn run_timed(&self, time_sp: Option<Duration>) -> Ev3Result<()> { if let Some(duration) = time_sp { let p = duration.as_millis() as i32; self.set_time_sp(p)?; } self.set_command(Self::COMMAND_RUN_TIMED) } /// Stop any of the run commands before they are complete using the command specified by `stop_action`. pub fn stop(&self) -> Ev3Result<()> { self.set_command(Self::COMMAND_STOP) } /// Resets all of the motor parameter attributes to their default values. /// This will also have the effect of stopping the motor. pub fn reset(&self) -> Ev3Result<()> { self.set_command(Self::COMMAND_RESET) } /// Power is being sent to the motor. pub fn is_running(&self) -> Ev3Result<bool> { Ok(self .get_state()? .iter() .any(|state| state == Self::STATE_RUNNING)) } /// The motor is ramping up or down and has not yet reached a pub constant output level. pub fn is_ramping(&self) -> Ev3Result<bool> { Ok(self .get_state()? .iter() .any(|state| state == Self::STATE_RAMPING)) } /// The motor is not turning, but rather attempting to hold a fixed position. pub fn is_holding(&self) -> Ev3Result<bool> { Ok(self .get_state()? .iter() .any(|state| state == Self::STATE_HOLDING)) } /// The motor is turning as fast as possible, but cannot reach its `speed_sp`. pub fn is_overloaded(&self) -> Ev3Result<bool> { Ok(self .get_state()? .iter() .any(|state| state == Self::STATE_OVERLOADED)) } /// The motor is trying to run but is not turning at all. pub fn is_stalled(&self) -> Ev3Result<bool> { Ok(self .get_state()? .iter() .any(|state| state == Self::STATE_STALLED)) } /// Wait until condition `cond` returns true or the `timeout` is reached. /// /// The condition is checked when to the `state` attribute has changed. /// If the `timeout` is `None` it will wait an infinite time. /// /// # Examples /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// motor.run_timed(Some(Duration::from_secs(5)))?; /// /// let cond = || { /// motor.get_state() /// .unwrap_or_else(|_| vec![]) /// .iter() /// .all(|s| s != LargeMotor::STATE_RUNNING) /// }; /// motor.wait(cond, None); /// /// println!("Motor has stopped!"); /// # Ok(()) /// # } /// ``` pub fn wait<F>(&self, cond: F, timeout: Option<Duration>) -> bool where F: Fn() -> bool, { let fd = self.get_attribute("state").get_raw_fd(); wait::wait(fd, cond, timeout) } /// Wait while the `state` is in the vector `self.get_state()` or the `timeout` is reached. /// /// If the `timeout` is `None` it will wait an infinite time. /// /// # Example /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// motor.run_timed(Some(Duration::from_secs(5)))?; /// /// motor.wait_while(LargeMotor::STATE_RUNNING, None); /// /// println!("Motor has stopped!"); /// # Ok(()) /// # } /// ``` pub fn wait_while(&self, state: &str, timeout: Option<Duration>) -> bool { let cond = || { self.get_state() .unwrap_or_else(|_| vec![]) .iter() .all(|s| s != state) }; self.wait(cond, timeout) } /// Wait until the `state` is in the vector `self.get_state()` or the `timeout` is reached. /// /// If the `timeout` is `None` it will wait an infinite time. /// /// # Example /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// motor.run_timed(Some(Duration::from_secs(5)))?; /// /// motor.wait_until(LargeMotor::STATE_RUNNING, None); /// /// println!("Motor has started!"); /// # Ok(()) /// # } /// ``` pub fn wait_until(&self, state: &str, timeout: Option<Duration>) -> bool { let cond = || { self.get_state() .unwrap_or_else(|_| vec![]) .iter() .any(|s| s == state) }; self.wait(cond, timeout) } /// Wait until the motor is not moving or the timeout is reached. /// /// This is equal to `wait_while(STATE_RUNNING, timeout)`. /// If the `timeout` is `None` it will wait an infinite time. /// /// # Example /// /// ```no_run /// use ev3dev_lang_rust::motors::LargeMotor; /// use std::time::Duration; /// /// # fn main() -> ev3dev_lang_rust::Ev3Result<()> { /// // Init a tacho motor. /// let motor = LargeMotor::find()?; /// /// motor.run_timed(Some(Duration::from_secs(5)))?; /// /// motor.wait_until_not_moving(None); /// /// println!("Motor has stopped!"); /// # Ok(()) /// # } /// ``` pub fn wait_until_not_moving(&self, timeout: Option<Duration>) -> bool { self.wait_while(Self::STATE_RUNNING, timeout) } }; }
true
85af4a7114d758e0737f49824cb582f145501cc6
Rust
alistairmgreen/AdventOfCode2019
/day3/src/main.rs
UTF-8
4,107
3.46875
3
[]
no_license
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io; use std::io::prelude::BufRead; use day3::*; fn main() -> Result<(), Box<dyn Error>>{ let file = File::open("puzzle_input.txt")?; let reader = io::BufReader::new(file); let mut wires = Vec::new(); for line in reader.lines() { let line = line?; wires.push(parse_wire(&line)?); } match solve_part1(&wires) { Some(distance) => { println!("Manhattan distance to closest intersection = {}", distance); } None => { println!("Wires don't cross."); } } match solve_part2(&wires) { Some(steps) => { println!("Minimum number of steps to an intersection = {}", steps); } None => { println!("Wires don't cross."); } } Ok(()) } fn parse_wire(wire: &str) -> Result<Vec<WireSegment>, StepParseError> { wire.split(',') .map(|segment| segment.parse()) .collect() } fn solve_part1(wires: &[Vec<WireSegment>]) -> Option<i32> { let mut grid = HashMap::new(); for wire in wires { let visited = visited_points(&wire); for (position, _) in visited { *grid.entry(position).or_insert(0) += 1; } } let closest_intersection = grid.into_iter() .filter_map(|(position, count)| if count > 1 { Some(position) } else { None }) .min_by_key(|position| position.manhattan()); closest_intersection.map(|position| position.manhattan()) } fn solve_part2(wires: &[Vec<WireSegment>]) -> Option<u32> { let mut grid = HashMap::new(); for wire in wires { let visited = visited_points(&wire); for (position, steps) in visited { grid.entry(position).or_insert_with(|| {Vec::new()}).push(steps); } } grid.into_iter() .filter_map(|(_, steps)| if steps.len() > 1 { Some(steps.into_iter().sum()) } else { None }) .min() } fn visited_points(segments: &[WireSegment]) -> HashMap<Point, u32> { let mut visited = HashMap::new(); let mut position = Point { x: 0, y: 0 }; let mut steps = 0; for segment in segments { let displacement = segment.direction.displacement(); for _ in 0..segment.distance { steps += 1; position += displacement; visited.entry(position.clone()) .or_insert(steps); } } visited } #[cfg(test)] mod tests { use super::*; #[test] fn part1_example1() { let wires = vec![ parse_wire("R8,U5,L5,D3").unwrap(), parse_wire("U7,R6,D4,L4").unwrap() ]; assert_eq!(solve_part1(&wires), Some(6)) } #[test] fn part1_example2() { let wires = vec![ parse_wire("R75,D30,R83,U83,L12,D49,R71,U7,L7").unwrap(), parse_wire("U62,R66,U55,R34,D71,R55,D58,R83").unwrap() ]; assert_eq!(solve_part1(&wires), Some(159)) } #[test] fn part1_example3() { let wires = vec![ parse_wire("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51").unwrap(), parse_wire("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7").unwrap() ]; assert_eq!(solve_part1(&wires), Some(135)) } #[test] fn part2_example1() { let wires = vec![ parse_wire("R8,U5,L5,D3").unwrap(), parse_wire("U7,R6,D4,L4").unwrap() ]; assert_eq!(solve_part2(&wires), Some(30)) } #[test] fn part2_example2() { let wires = vec![ parse_wire("R75,D30,R83,U83,L12,D49,R71,U7,L7").unwrap(), parse_wire("U62,R66,U55,R34,D71,R55,D58,R83").unwrap() ]; assert_eq!(solve_part2(&wires), Some(610)) } #[test] fn part2_example3() { let wires = vec![ parse_wire("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51").unwrap(), parse_wire("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7").unwrap() ]; assert_eq!(solve_part2(&wires), Some(410)) } }
true
343bb4af74f03c2703df1c30e8fbbb117083c30f
Rust
xsoer/rust-learn
/ex-libs/src/ex_chrono.rs
UTF-8
6,946
3.3125
3
[]
no_license
use chrono::{DateTime, Datelike, Local, TimeZone, Timelike, Utc}; pub fn c_chrono() { // 获取utc时间 let utc_datetime = Utc::now(); println!("utc_datetime: {}", utc_datetime); // utc_datetime: 2021-11-01 10:05:22.349150 UTC // 获取local时间 let local_datetime = Local::now(); println!("local_datetime: {}", local_datetime); //local_datetime: 2021-11-01 18:05:22.349230 +08:00 // 获取日期的属性 println!("local_datetime 年: {}", local_datetime.year()); // local_datetime 年: 2021 println!( "local_datetime 月: 12月制:{}, 11个月制:{}", local_datetime.month(), local_datetime.month0() ); // local_datetime 月: 12月制:11, 11个月制:10 println!("local_datetime 日: {}", local_datetime.day()); // local_datetime day: 1 println!( "local_datetime 小时: 24小时制:{}, 12小时制: {:?}", local_datetime.hour(), local_datetime.hour12() ); // local_datetime 小时: 24小时制:19, 12小时制: (true, 7) println!("local_datetime 分钟: {}", local_datetime.minute()); // local_datetime local_datetime 分钟: 36 println!("local_datetime 秒: {}", local_datetime.second()); // local_datetime 秒: 31 println!("local_datetime 周几: {}", local_datetime.weekday()); // local_datetime 周几: Mon println!( "local_datetime 周几(数字): {}", local_datetime.weekday().number_from_monday() ); // local_datetime 周几(数字): 1 println!("local_dateimte 一年的第几天: {}", local_datetime.ordinal()); // local_dateimte 一年的第几天: 305 // 日期时间转时间戳。Utc和Local转换后的时间戳是一致的 println!("utc timestamp: {}", utc_datetime.timestamp()); // utc timestamp: 1635761246 println!("local timestamp: {}", local_datetime.timestamp()); // local timestamp: 1635761246 // 把时间转换成字符串 let local_str = local_datetime.to_string(); println!("lcoal_str: {}", local_str); //lcoal_str: 2021-11-01 19:24:38.939970 +08:00 // 格式化字符串 let local_str1 = local_datetime.format("%Y-%m-%dT%H:%M:%S").to_string(); println!("local_str1: {}", local_str1); //local_str1: 2021-11-01T19:24:38 // 只展示日期 let local_str2 = local_datetime.format("%Y-%m-%d").to_string(); println!("local_str2: {}", local_str2); //local_str2: 2021-11-01 // 只展示时间 let local_str3 = local_datetime.format("%H:%M:%S").to_string(); println!("local_str3: {}", local_str3); //local_str3: 19:24:38 // 获取日期格式 let local_date = local_datetime.date(); println!("local_date: {}", local_date); //local_date: 2021-11-01+08:00 assert_eq!(Utc::today(), Utc::now().date()); assert_eq!(Local::today(), Local::now().date()); // 手动创建日期时间 let local_handle_datetime1 = Local.ymd(2021, 10, 15).and_hms(10, 12, 30); println!("local_handle_datetime1: {}", local_handle_datetime1); //local_handle_datetime1: 2021-10-15 10:12:30 +08:00 // 手动创建带有毫秒级的时间 let local_handle_datetime2 = Local.ymd(2021, 10, 27).and_hms_milli(18, 18, 18, 889); println!("local_handle_datetime2: {}", local_handle_datetime2); // local_handle_datetime2: 2021-10-20 18:18:18.889 +08:00 // 两个日期时间的差值 let sub_datetime = local_handle_datetime2 - local_handle_datetime1; println!( "相差:{}天, {}小时, {}分钟, {}秒, {}周. 格式化:{}", sub_datetime.num_days(), sub_datetime.num_hours(), sub_datetime.num_minutes(), sub_datetime.num_seconds(), sub_datetime.num_weeks(), sub_datetime.to_string() ); // 相差:12天, 296小时, 17765分钟, 1065948秒, 1周. 格式化:P12DT29148.889S // 获取前3天的日期 let three_days_before = local_datetime - chrono::Duration::days(3); println!("three_days_before: {}", three_days_before); //three_days_before: 2021-10-29 19:55:41.982785 +08:00 // 获取下周的今天 let next_week_day = local_datetime + chrono::Duration::weeks(1); println!("next_week_day: {}", next_week_day); // next_week_day: 2021-11-08 19:55:41.982785 +08:00 // 字符串转换时间 let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9); let fixed_dt = dt.with_timezone(&chrono::FixedOffset::east(8 * 3600)); // 设置时区 // 用parse来转换 assert_eq!( "2014-11-28T12:00:09Z".parse::<chrono::DateTime<Utc>>(), Ok(dt.clone()) ); assert_eq!( "2014-11-28T20:00:09+08:00".parse::<chrono::DateTime<Utc>>(), Ok(dt.clone()) ); assert_eq!( "2014-11-28T20:00:09+08:00".parse::<chrono::DateTime<chrono::FixedOffset>>(), Ok(fixed_dt.clone()) ); // 用DateTime结构来转换 assert_eq!( DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"), Ok(fixed_dt.clone()) ); assert_eq!( DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"), Ok(fixed_dt.clone()) ); assert_eq!( DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()) ); // 通过Utc的datetime_from_str转换 assert_eq!( Utc.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()) ); assert_eq!( Utc.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()) ); // 时间戳转换成时间 let dt = Utc.timestamp(1_500_000_000, 0); assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000"); // Utc转换成Local let utc_now = Utc::now(); let local_now = utc_now .with_timezone(&chrono::FixedOffset::east(8 * 3600)) .format("%Y-%m-%d %H:%M:%S") .to_string(); println!("local_now {}", local_now); } pub mod date_format { use chrono::{DateTime, FixedOffset, Local, TimeZone, Utc}; use serde::{self, Deserialize, Deserializer, Serializer}; const FORMAT: &'static str = "%Y-%m-%d %H:%M:%S"; pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let s = date .with_timezone(&FixedOffset::east(8 * 3600)) .format(FORMAT) .to_string(); serializer.serialize_str(&s) } pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; let r = Local .datetime_from_str(&s, FORMAT) .map_err(serde::de::Error::custom)?; Ok(DateTime::from(r)) } } #[cfg(test)] mod tests { use super::*; #[test] fn t_c_chrono() { c_chrono(); } }
true
2f5ba506bcd63bf217e739e4b82df4721a14e81c
Rust
unknownue/GLSLCookbook.rs
/examples/chapter05/sceneprojtex.rs
UTF-8
8,370
2.515625
3
[]
no_license
use cookbook::scene::{Scene, GLSourceCode}; use cookbook::error::{GLResult, GLErrorKind, BufferCreationErrorKind}; use cookbook::objects::{Teapot, Plane}; use cookbook::texture::load_texture; use cookbook::{Mat4F, Mat3F, Vec3F}; use cookbook::Drawable; use glium::backend::Facade; use glium::program::{Program, ProgramCreationError}; use glium::uniforms::UniformBuffer; use glium::texture::texture2d::Texture2d; use glium::{Surface, uniform, implement_uniform_block}; #[derive(Debug)] pub struct SceneProjTex { program: glium::Program, teapot: Teapot, plane: Plane, flower_tex: Texture2d, teapot_material: UniformBuffer<MaterialInfo>, plane_material : UniformBuffer<MaterialInfo>, light_buffer : UniformBuffer<LightInfo>, project_matrix: Mat4F, projection: Mat4F, angle: f32, is_animate: bool, } #[allow(non_snake_case)] #[repr(C)] #[derive(Debug, Clone, Copy, Default)] struct LightInfo { LightPosition: [f32; 4], L : [f32; 3], _padding1: f32, La: [f32; 3], } #[allow(non_snake_case)] #[repr(C)] #[derive(Debug, Clone, Copy, Default)] struct MaterialInfo { Ka: [f32; 3], _padding1: f32, Kd: [f32; 3], _padding2: f32, Ks: [f32; 3], Shininess: f32, } impl Scene for SceneProjTex { fn new(display: &impl Facade) -> GLResult<SceneProjTex> { // Shader Program ------------------------------------------------------------ let program = SceneProjTex::compile_shader_program(display) .map_err(GLErrorKind::CreateProgram)?; // ---------------------------------------------------------------------------- // Initialize Mesh ------------------------------------------------------------ let teapot = Teapot::new(display, 14, Mat4F::identity())?; let plane = Plane::new(display, 100.0, 100.0, 1, 1, 1.0, 1.0)?; // ---------------------------------------------------------------------------- // Initialize Textures -------------------------------------------------------- let flower_tex = load_texture(display, "media/texture/flower.png")?; // ---------------------------------------------------------------------------- // Initialize MVP ------------------------------------------------------------- let projection = Mat4F::identity(); let angle = 90.0_f32.to_radians(); let is_animate = true; let proj_pos = Vec3F::new(2.0, 5.0, 5.0); let proj_at = Vec3F::new(-2.0, -4.0, 0.0); let proj_up = Vec3F::new(0.0, 1.0, 0.0); let proj_view = Mat4F::look_at_rh(proj_pos, proj_at, proj_up); let proj_proj = Mat4F::perspective_rh_zo(30.0_f32.to_radians(), 1.0, 0.2, 1000.0); let bias = Mat4F::scaling_3d(Vec3F::new(0.5, 0.5, 0.5)) .translated_3d(Vec3F::new(0.5, 0.5, 0.5)); let project_matrix = bias * proj_proj * proj_view; // ---------------------------------------------------------------------------- // Initialize Uniforms -------------------------------------------------------- glium::implement_uniform_block!(LightInfo, LightPosition, L, La); let light_buffer = UniformBuffer::immutable(display, LightInfo { LightPosition: [0.0_f32, 0.0, 0.0, 1.0], L: [1.0_f32, 1.0, 1.0], La: [0.2_f32, 0.2, 0.2], ..Default::default() }).map_err(BufferCreationErrorKind::UniformBlock)?; glium::implement_uniform_block!(MaterialInfo, Ka, Kd, Ks, Shininess); let teapot_material = UniformBuffer::immutable(display, MaterialInfo { Ka: [0.1, 0.1, 0.1], Kd: [0.5, 0.2, 0.1], Ks: [0.95, 0.95, 0.95], Shininess: 100.0, ..Default::default() }).map_err(BufferCreationErrorKind::UniformBlock)?; let plane_material = UniformBuffer::immutable(display, MaterialInfo { Ka: [0.1, 0.1, 0.1], Kd: [0.4, 0.4, 0.4], Ks: [0.0, 0.0, 0.0], Shininess: 1.0, ..Default::default() }).map_err(BufferCreationErrorKind::UniformBlock)?; // ---------------------------------------------------------------------------- let scene = SceneProjTex { program, teapot, plane, flower_tex, teapot_material, plane_material, light_buffer, projection, project_matrix, angle, is_animate, }; Ok(scene) } fn update(&mut self, delta_time: f32) { const TWO_PI: f32 = std::f32::consts::PI * 2.0; const ROTATE_SPEED: f32 = std::f32::consts::PI / 2.0; if self.is_animating() { self.angle = (self.angle + delta_time * ROTATE_SPEED) % TWO_PI; } } fn render(&mut self, frame: &mut glium::Frame) -> GLResult<()> { frame.clear_color_srgb(0.5, 0.5, 0.5, 1.0); frame.clear_depth(1.0); let draw_params = glium::draw_parameters::DrawParameters { depth: glium::Depth { test: glium::DepthTest::IfLess, write: true, ..Default::default() }, ..Default::default() }; // Render teapot ---------------------------------------------------------- let camera_pos = Vec3F::new(7.0 * self.angle.cos(), 2.0, 7.0 * self.angle.sin()); let view = Mat4F::look_at_rh(camera_pos, Vec3F::zero(), Vec3F::unit_y()); let model = Mat4F::rotation_x(-90.0_f32.to_radians()) .translated_3d(Vec3F::new(0.0, -1.0, 0.0)); let mv: Mat4F = view * model; let uniforms = uniform! { LightInfo: &self.light_buffer, MaterialInfo: &self.teapot_material, ProjectorTex: self.flower_tex.sampled() .wrap_function(glium::uniforms::SamplerWrapFunction::BorderClamp) .minify_filter(glium::uniforms::MinifySamplerFilter::Nearest) .magnify_filter(glium::uniforms::MagnifySamplerFilter::Linear), ProjectorMatrix: self.project_matrix.into_col_arrays(), ModelMatrix: model.into_col_arrays(), ModelViewMatrix: mv.clone().into_col_arrays(), NormalMatrix: Mat3F::from(mv).into_col_arrays(), MVP: (self.projection * mv).into_col_arrays(), }; self.teapot.render(frame, &self.program, &draw_params, &uniforms)?; // ------------------------------------------------------------------------- // Render plane ---------------------------------------------------------- let model = Mat4F::translation_3d(Vec3F::new(0.0, -0.75, 0.0)); let mv: Mat4F = view * model; let uniforms = uniform! { LightInfo: &self.light_buffer, MaterialInfo: &self.plane_material, ProjectorTex: self.flower_tex.sampled() .wrap_function(glium::uniforms::SamplerWrapFunction::BorderClamp) .minify_filter(glium::uniforms::MinifySamplerFilter::Nearest) .magnify_filter(glium::uniforms::MagnifySamplerFilter::Linear), ProjectorMatrix: self.project_matrix.into_col_arrays(), ModelViewMatrix: mv.clone().into_col_arrays(), ModelMatrix: model.into_col_arrays(), NormalMatrix: Mat3F::from(mv).into_col_arrays(), MVP: (self.projection * mv).into_col_arrays(), }; self.plane.render(frame, &self.program, &draw_params, &uniforms) // ------------------------------------------------------------------------- } fn resize(&mut self, _display: &impl Facade, width: u32, height: u32) -> GLResult<()> { self.projection = Mat4F::perspective_rh_zo(50.0_f32.to_radians(), width as f32 / height as f32, 0.3, 100.0); Ok(()) } fn is_animating(&self) -> bool { self.is_animate } fn toggle_animation(&mut self) { self.is_animate = !self.is_animate; } } impl SceneProjTex { fn compile_shader_program(display: &impl Facade) -> Result<Program, ProgramCreationError> { let vertex_shader_code = include_str!("shaders/projtex.vert.glsl"); let fragment_shader_code = include_str!("shaders/projtex.frag.glsl"); let sources = GLSourceCode::new(vertex_shader_code, fragment_shader_code) .with_srgb_output(true); glium::Program::new(display, sources) } }
true
698b6302c870bf39cfb9f38c3f2e901ca56ec475
Rust
dsherret/swc
/ecmascript/minifier/src/compress/drop_console.rs
UTF-8
2,455
2.765625
3
[ "MIT", "Apache-2.0" ]
permissive
use std::{borrow::Cow, mem::take}; use swc_common::pass::CompilerPass; use swc_ecma_ast::*; use swc_ecma_transforms::pass::JsPass; use swc_ecma_visit::{as_folder, noop_visit_mut_type, VisitMut, VisitMutWith}; pub fn drop_console() -> impl JsPass + VisitMut { as_folder(DropConsole { done: false }) } struct DropConsole { /// Invoking this pass multiple times is simply waste of time. done: bool, } impl CompilerPass for DropConsole { fn name() -> Cow<'static, str> { "drop-console".into() } } impl VisitMut for DropConsole { noop_visit_mut_type!(); fn visit_mut_expr(&mut self, n: &mut Expr) { if self.done { return; } n.visit_mut_children_with(self); match n { Expr::Call(CallExpr { span, callee, args, .. }) => { // Find console.log let callee = match callee { ExprOrSuper::Expr(callee) => callee, _ => return, }; match &**callee { Expr::Member(MemberExpr { obj: ExprOrSuper::Expr(callee_obj), prop: callee_prop, computed: false, .. }) => { match (&**callee_obj, &**callee_prop) { (Expr::Ident(obj), Expr::Ident(prop)) => { if obj.sym != *"console" { return; } match &*prop.sym { "log" | "info" => {} _ => return, } } _ => return, } // Sioplifier will remove side-effect-free items. *n = Expr::Seq(SeqExpr { span: *span, exprs: take(args).into_iter().map(|arg| arg.expr).collect(), }) } _ => {} } } _ => {} } } fn visit_mut_module(&mut self, n: &mut Module) { if self.done { return; } n.visit_mut_children_with(self); self.done = true; } }
true
17517543d7eedba50cc504ce38bd88d9f72bb791
Rust
mdzik/hyperqueue
/crates/hyperqueue/src/common/manager/common.rs
UTF-8
1,411
3.59375
4
[ "MIT" ]
permissive
use std::time::Duration; /// Format a duration as a PBS/Slurm time string, e.g. 01:05:02 pub(super) fn format_duration(duration: &Duration) -> String { let mut seconds = duration.as_secs(); let hours = seconds / 3600; seconds %= 3600; let minutes = seconds / 60; seconds %= 60; format!("{:02}:{:02}:{:02}", hours, minutes, seconds) } /// Parse duration from string pub fn parse_hms_duration(raw_time: &str) -> anyhow::Result<Duration> { use chrono::Duration as ChronoDuration; let numbers: Vec<&str> = raw_time.split(':').collect(); let duration = ChronoDuration::hours(numbers[0].parse()?) + ChronoDuration::minutes(numbers[1].parse()?) + ChronoDuration::seconds(numbers[2].parse()?); Ok(duration.to_std()?) } #[cfg(test)] mod test { use super::{format_duration, parse_hms_duration}; use std::time::Duration; #[test] fn test_format_duration() { assert_eq!(format_duration(&Duration::from_secs(0)), "00:00:00"); assert_eq!(format_duration(&Duration::from_secs(1)), "00:00:01"); assert_eq!(format_duration(&Duration::from_secs(61)), "00:01:01"); assert_eq!(format_duration(&Duration::from_secs(3661)), "01:01:01"); } #[test] fn test_parse_hms_duration() { let date = parse_hms_duration("03:01:34").unwrap(); assert_eq!(date, Duration::from_secs(3 * 3600 + 60 + 34)); } }
true
01fd5605076804de2fbca2f023cc998227a7e9f3
Rust
baszalmstra/rosty
/crates/rosty_xmlrpc_fmt/src/value.rs
UTF-8
3,850
3.109375
3
[ "MIT" ]
permissive
use base64; use serde::de::Unexpected; use std; use std::collections::HashMap; use xml::escape::escape_str_pcdata; #[derive(Clone, Debug, PartialEq)] pub enum Value { Int(i32), Bool(bool), String(String), Double(f64), DateTime(String), Base64(Vec<u8>), Array(Vec<Value>), Struct(HashMap<String, Value>), } impl Value { pub fn unexpected(&self) -> Unexpected { match *self { Value::Int(v) => Unexpected::Signed(i64::from(v)), Value::Bool(v) => Unexpected::Bool(v), Value::String(ref v) => Unexpected::Str(v), Value::Double(v) => Unexpected::Float(v), Value::DateTime(_) => Unexpected::Other("dateTime.iso8601"), Value::Base64(ref v) => Unexpected::Bytes(v), Value::Array(_) => Unexpected::Seq, Value::Struct(_) => Unexpected::Map, } } } pub type Params = Vec<Value>; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Fault { #[serde(rename = "faultCode")] pub code: i32, #[serde(rename = "faultString")] pub message: String, } impl Fault { pub fn new<T>(code: i32, message: T) -> Fault where T: Into<String>, { Fault { code, message: message.into(), } } } pub type Response = std::result::Result<Params, Fault>; #[derive(Clone, Debug, PartialEq)] pub struct Call { pub name: String, pub params: Params, } pub trait ToXml { fn to_xml(&self) -> String; } impl ToXml for Call { fn to_xml(&self) -> String { format!( include_str!("templates/call.xml"), name = self.name, params = self .params .iter() .map(|param| format!("<param>{}</param>", param.to_xml())) .collect::<String>() ) } } impl ToXml for Response { fn to_xml(&self) -> String { match *self { Ok(ref params) => format!( include_str!("templates/response_success.xml"), params = params .iter() .map(|param| format!("<param>{}</param>", param.to_xml())) .collect::<String>() ), Err(Fault { code, ref message }) => format!( include_str!("templates/response_fault.xml"), code = code, message = message ), } } } impl ToXml for Value { fn to_xml(&self) -> String { match *self { Value::Int(v) => format!("<value><i4>{}</i4></value>", v), Value::Bool(v) => format!( "<value><boolean>{}</boolean></value>", if v { 1 } else { 0 } ), Value::String(ref v) => { format!("<value><string>{}</string></value>", escape_str_pcdata(v)) } Value::Double(v) => format!("<value><double>{}</double></value>", v), Value::DateTime(ref v) => { format!("<value><dateTime.iso8601>{}</dateTime.iso8601></value>", v) } Value::Base64(ref v) => { format!("<value><base64>{}</base64></value>", base64::encode(v)) } Value::Array(ref v) => format!( "<value><array><data>{}</data></array></value>", v.iter().map(Value::to_xml).collect::<String>() ), Value::Struct(ref v) => format!( "<value><struct>{}</struct></value>", v.iter() .map(|(key, value)| format!( "<member><name>{}</name>{}</member>", key, value.to_xml() )) .collect::<String>() ), } } }
true
bb3507c95e0d2276f577a4eedbead3b70ff68932
Rust
0xflotus/skim
/src/curses.rs
UTF-8
35,772
2.71875
3
[ "MIT" ]
permissive
// An abstract layer towards ncurses-rs, which provides keycode, color scheme support // Modeled after fzf //use ncurses::*; use nix::libc; use options::SkimOptions; use std::cmp::{max, min}; use std::collections::HashMap; use std::fmt; use std::fs::OpenOptions; use std::io::prelude::*; use std::io::{stdin, stdout, Write}; use std::os::unix::io::{IntoRawFd, RawFd}; use std::sync::RwLock; use termion; use termion::raw::IntoRawMode; use termion::screen::AlternateScreen; use termion::{color, style}; use unicode_width::UnicodeWidthChar; pub static COLOR_NORMAL: u16 = 0; pub static COLOR_PROMPT: u16 = 1; pub static COLOR_MATCHED: u16 = 2; pub static COLOR_CURRENT: u16 = 3; pub static COLOR_CURRENT_MATCH: u16 = 4; pub static COLOR_SPINNER: u16 = 5; pub static COLOR_INFO: u16 = 6; pub static COLOR_CURSOR: u16 = 7; pub static COLOR_SELECTED: u16 = 8; pub static COLOR_HEADER: u16 = 9; pub static COLOR_BORDER: u16 = 10; static COLOR_USER: u16 = 11; #[allow(non_camel_case_types)] pub type attr_t = u16; lazy_static! { // all colors are refered by the pair number static ref RESOURCE_MAP: RwLock<HashMap<attr_t, String>> = RwLock::new(HashMap::new()); // COLOR_MAP is used to store ((fg <<8 ) | bg) -> attr_t, used to handle ANSI code static ref COLOR_MAP: RwLock<HashMap<String, attr_t>> = RwLock::new(HashMap::new()); } // register the color as color pair fn register_resource(key: attr_t, resource: String) { let mut resource_map = RESOURCE_MAP .write() .expect("curses:register_resource: failed to lock resource map"); resource_map.entry(key).or_insert_with(|| resource); } pub fn register_ansi(ansi: String) -> attr_t { //let fg = if fg == -1 { *FG.read().unwrap() } else {fg}; //let bg = if bg == -1 { *BG.read().unwrap() } else {bg}; let mut color_map = COLOR_MAP .write() .expect("curses:register_ansi: failed to lock color map"); let pair_num = color_map.len() as u16; if color_map.contains_key(&ansi) { *color_map .get(&ansi) .unwrap_or_else(|| panic!("curses:register_ansi: failed to get ansi: {}", &ansi)) } else { let next_pair = COLOR_USER + pair_num; register_resource(next_pair, ansi.clone()); color_map.insert(ansi, next_pair); next_pair } } // utility function to check if an attr_t contains background color or reset background pub fn ansi_contains_reset(key: attr_t) -> bool { let resource_map = RESOURCE_MAP .read() .expect("curses: ansi_contains_reset: failed to lock RESOURCE_MAP"); let ansi = resource_map.get(&key); if ansi.is_none() { return false; } let text = ansi.as_ref().unwrap(); text == &"\x1B[m" || text == &"\x1B[0m" || text.ends_with(";0m") } //============================================================================== #[derive(PartialEq, Eq, Clone, Debug, Copy)] pub enum Margin { Fixed(u16), Percent(u16), } // A curse object is an abstraction of the screen to be draw on // | // | // | // +------------+ start_line // | ^ | // | < | <-- top = start_line + margin_top // | (margins) | // | >| <-- bottom = end_line - margin_bottom // | v | // +------------+ end_line // | // | pub struct Window { top: u16, bottom: u16, left: u16, right: u16, wrap: bool, border: Option<Direction>, stdout_buffer: String, current_y: u16, current_x: u16, } impl Default for Window { fn default() -> Self { Window { top: 0, bottom: 0, left: 0, right: 0, wrap: false, border: None, stdout_buffer: String::new(), current_x: 0, current_y: 0, } } } impl Window { pub fn new(top: u16, right: u16, bottom: u16, left: u16, wrap: bool, border: Option<Direction>) -> Self { Window { top, bottom, left, right, border, wrap, stdout_buffer: String::with_capacity(CURSES_BUF_SIZE), current_x: 0, current_y: 0, } } pub fn reshape(&mut self, top: u16, right: u16, bottom: u16, left: u16) { self.top = top; self.right = right; self.bottom = bottom; self.left = left; } pub fn set_border(&mut self, border: Option<Direction>) { self.border = border; } pub fn draw_border(&mut self) { //debug!("curses:window:draw_border: TRBL: {}, {}, {}, {}", self.top, self.right, self.bottom, self.left); let (y, x) = self.getyx(); self.attron(COLOR_BORDER); match self.border { Some(Direction::Up) => { self.stdout_buffer .push_str(format!("{}", termion::cursor::Goto(self.left + 1, self.top + 1)).as_str()); self.stdout_buffer .push_str(&"─".repeat((self.right - self.left) as usize)); } Some(Direction::Down) => { self.stdout_buffer .push_str(format!("{}", termion::cursor::Goto(self.left + 1, self.bottom)).as_str()); self.stdout_buffer .push_str(&"─".repeat((self.right - self.left) as usize)); } Some(Direction::Left) => for i in self.top..self.bottom { self.stdout_buffer .push_str(format!("{}", termion::cursor::Goto(self.left + 1, i + 1)).as_str()); self.stdout_buffer.push('│') }, Some(Direction::Right) => for i in self.top..self.bottom { self.stdout_buffer .push_str(format!("{}", termion::cursor::Goto(self.right, i + 1)).as_str()); self.stdout_buffer.push('│') }, _ => {} } self.attroff(COLOR_BORDER); self.mv(y, x); } #[rustfmt::skip] pub fn mv(&mut self, y: u16, x: u16) { self.current_y = y; self.current_x = x; let (target_y, target_x) = match self.border { Some(Direction::Up) => ((y+self.top+1+1), (x+self.left+1)), Some(Direction::Down) => ((y+self.top+1), (x+self.left+1)), Some(Direction::Left) => ((y+self.top+1), (x+self.left+1+1)), Some(Direction::Right) => ((y+self.top+1), (x+self.left+1)), _ => ((y+self.top+1), (x+self.left+1)), }; self.stdout_buffer.push_str(format!("{}", termion::cursor::Goto(target_x, target_y)).as_str()); } pub fn get_maxyx(&self) -> (u16, u16) { assert!(self.bottom >= self.top); assert!(self.right >= self.left); let (max_y, max_x) = (self.bottom - self.top, self.right - self.left); // window is hidden if max_y == 0 || max_x == 0 { return (0, 0); } match self.border { Some(Direction::Up) | Some(Direction::Down) => (max_y - 1, max_x), Some(Direction::Left) | Some(Direction::Right) => (max_y, max_x - 1), _ => (max_y, max_x), } } pub fn getyx(&mut self) -> (u16, u16) { (self.current_y, self.current_x) } pub fn clrtoeol(&mut self) { let (y, x) = self.getyx(); let (max_y, max_x) = self.get_maxyx(); if y >= max_y || x >= max_x { return; } self.attron(COLOR_NORMAL); self.stdout_buffer.push_str(&" ".repeat((max_x - x) as usize)); self.mv(y, x); } pub fn clrtoend(&mut self) { let (y, _) = self.getyx(); let (max_y, _) = self.get_maxyx(); //debug!("curses:window:clrtoend: y/x: {}/{}, max_y/max_x: {}/{}", y, x, max_y, max_x); self.clrtoeol(); for row in y + 1..max_y { self.mv(row, 0); self.clrtoeol(); } } pub fn printw(&mut self, text: &str) { //debug!("curses:window:printw: {:?}", text); for ch in text.chars() { self.add_char(ch); } } pub fn cprint(&mut self, text: &str, pair: u16, _is_bold: bool) { self.attron(pair); self.printw(text); self.attroff(pair); } pub fn caddch(&mut self, ch: char, pair: u16, _is_bold: bool) { self.attron(pair); self.add_char(ch); self.attroff(pair); } pub fn addch(&mut self, ch: char) { self.add_char(ch); } fn add_char(&mut self, ch: char) { let (max_y, _) = self.get_maxyx(); let (y, _) = self.getyx(); if y >= max_y { return; } //debug!("curses:window:add_char: {:?}", ch); match ch { '\t' => { let tabstop = 8; let rest = 8 - self.current_x % tabstop; for _ in 0..rest { self.add_char_raw(' '); } } '\r' => { let (y, _) = self.getyx(); self.mv(y, 0); } '\n' => { let (y, _) = self.getyx(); self.clrtoeol(); self.mv(y + 1, 0); } ch => { self.add_char_raw(ch); } } } fn add_char_raw(&mut self, ch: char) { let (max_y, max_x) = self.get_maxyx(); let (y, x) = self.getyx(); let text_width = ch.width().unwrap_or(2) as u16; let target_x = x + text_width; // no enough space to print if (y >= max_y) || (target_x > max_x && y == max_y - 1) || (!self.wrap && target_x > max_x) { return; } if target_x > max_x { self.mv(y + 1, 0); } self.stdout_buffer.push(ch); let (y, x) = self.getyx(); let target_x = x + text_width; let final_x = if self.wrap { target_x % max_x } else { target_x }; let final_y = y + if self.wrap { target_x / max_x } else { 0 }; self.mv(final_y, final_x); } pub fn attr_on(&mut self, attr: attr_t) { if attr == 0 { self.attrclear(); } else { self.attron(attr); } } fn attron(&mut self, key: attr_t) { let resource_map = RESOURCE_MAP .read() .expect("curses:attron: failed to lock RESOURCE_MAP for read"); if let Some(s) = resource_map.get(&key) { self.stdout_buffer.push_str(s); } } fn attroff(&mut self, key: attr_t) { if key == COLOR_NORMAL { return; } self.stdout_buffer .push_str(format!("{}{}", color::Fg(color::Reset), color::Bg(color::Reset)).as_str()); } fn attrclear(&mut self) { self.stdout_buffer .push_str(format!("{}{}{}", color::Fg(color::Reset), color::Bg(color::Reset), style::Reset).as_str()); } pub fn write_to_term(&mut self, term: &mut Write) { write!(term, "{}", &self.stdout_buffer).expect("curses:write_to_term: error on writting to terminal"); self.stdout_buffer.clear(); } pub fn hide_cursor(&mut self) { self.stdout_buffer .push_str(format!("{}", termion::cursor::Hide).as_str()); } pub fn show_cursor(&mut self) { self.stdout_buffer .push_str(format!("{}", termion::cursor::Show).as_str()); } pub fn move_cursor_right(&mut self, offset: u16) { self.stdout_buffer .push_str(format!("{}", termion::cursor::Right(offset)).as_str()); let (_, max_x) = self.get_maxyx(); self.current_x = min(self.current_x + offset, max_x); } pub fn close(&mut self) { // to erase all contents, including border let spaces = " ".repeat((self.right - self.left) as usize); for row in (self.top..self.bottom).rev() { self.stdout_buffer .push_str(format!("{}", termion::cursor::Goto(self.left + 1, row + 1)).as_str()); self.stdout_buffer.push_str(&spaces); } self.stdout_buffer .push_str(format!("{}", termion::cursor::Goto(self.left + 1, self.top + 1)).as_str()); } } #[derive(PartialEq, Eq, Clone, Debug, Copy)] pub enum Direction { Up, Down, Left, Right, } pub struct Curses { //screen: SCREEN, term: Option<Box<Write>>, top: u16, bottom: u16, left: u16, right: u16, start_y: i32, // +3 means 3 lines from top, -3 means 3 lines from bottom, height: Margin, min_height: u16, margin_top: Margin, margin_bottom: Margin, margin_left: Margin, margin_right: Margin, // preview window status preview_direction: Direction, preview_size: Margin, preview_shown: bool, pub win_main: Window, pub win_preview: Window, // other stuff orig_stdout_fd: Option<RawFd>, } unsafe impl Send for Curses {} const CURSES_BUF_SIZE: usize = 100 * 1024; impl Curses { pub fn new(options: &SkimOptions) -> Self { ColorTheme::init_from_options(options); // parse the option of window height of skim let min_height = options .min_height .map(|x| x.parse::<u16>().unwrap_or(10)) .expect("min_height should have default values"); let height = options .height .map(Curses::parse_margin_string) .expect("height should have default values"); // If skim is invoked by pipeline `echo 'abc' | sk | awk ...` // The the output is redirected. We need to open /dev/tty for output. let istty = unsafe { libc::isatty(libc::STDOUT_FILENO as i32) } != 0; let orig_stdout_fd = if !istty { unsafe { let stdout_fd = libc::dup(libc::STDOUT_FILENO); let tty = OpenOptions::new() .write(true) .open("/dev/tty") .expect("curses:new: failed to open /dev/tty"); libc::dup2(tty.into_raw_fd(), libc::STDOUT_FILENO); Some(stdout_fd) } } else { None }; let (max_y, _) = Curses::terminal_size(); let (term, y): (Box<Write>, u16) = if Margin::Percent(100) == height { ( Box::new(AlternateScreen::from( stdout().into_raw_mode().expect("failed to set terminal to raw mode"), )), 0, ) } else { let term = Box::new(stdout().into_raw_mode().expect("failed to set terminal to raw mode")); let (y, _) = Curses::get_cursor_pos(); // reserve the necessary lines to show skim (in case current cursor is at the bottom // of the screen) Curses::reserve_lines(max_y, height, min_height); (term, y) }; // keep the start position on the screen let start_y = if height == Margin::Percent(100) { 0 } else { let height = match height { Margin::Percent(p) => max(p * max_y / 100, min_height), Margin::Fixed(rows) => rows, }; if y + height >= max_y { -i32::from(height) } else { i32::from(y) } }; // parse options for margin let margins = options .margin .map(Curses::parse_margin) .expect("option margin is should be specified (by default)"); let (margin_top, margin_right, margin_bottom, margin_left) = margins; // parse options for preview window let preview_cmd_exist = options.preview != None; let (preview_direction, preview_size, preview_wrap, preview_shown) = options .preview_window .map(Curses::parse_preview) .expect("option 'preview-window' should be set (by default)"); let mut ret = Curses { term: Some(term), top: 0, bottom: 0, left: 0, right: 0, start_y, height, min_height, margin_top, margin_bottom, margin_left, margin_right, preview_direction, preview_size, preview_shown: preview_cmd_exist && preview_shown, win_main: Window::new(0, 0, 0, 0, false, None), win_preview: Window::new(0, 0, 0, 0, preview_wrap, None), orig_stdout_fd, }; ret.resize(); ret } fn reserve_lines(max_y: u16, height: Margin, min_height: u16) { let rows = match height { Margin::Percent(100) => { return; } Margin::Percent(percent) => max(min_height, max_y * percent / 100), Margin::Fixed(rows) => rows, }; print!("{}", "\n".repeat(max(0, rows - 1) as usize)); stdout() .flush() .expect("curses:reserve_lines: failed to write to stdout"); } fn get_cursor_pos() -> (u16, u16) { let mut stdout = stdout() .into_raw_mode() .expect("curses:get_cursor_pos: failed to set stdout to raw mode"); let mut f = stdin(); write!(stdout, "\x1B[6n").expect("curses:get_cursor_pos: failed to write to stdout"); stdout.flush().expect("curses:get_cursor_pos: failed to flush stdout"); let mut read_chars = Vec::new(); loop { let mut buf = [0; 1]; let _ = f.read(&mut buf); read_chars.push(buf[0]); if buf[0] == b'R' { break; } } let seq = String::from_utf8(read_chars).expect("curses:get_cursor_pos: invalid utf8 string read"); let beg = seq.rfind('[').expect("curses:get_cursor_pos: invalid control sequence"); let coords: Vec<&str> = seq[(beg + 1)..seq.len() - 1].split(';').collect(); stdout.flush().expect("curses:get_cursor_pos: failed to flush stdout"); let y = coords[0] .parse::<u16>() .expect("curses:get_cursor_pos: invalid position y"); let x = coords[1] .parse::<u16>() .expect("curses:get_cursor_pos: invalid position x"); (y - 1, x - 1) } fn parse_margin_string(margin: &str) -> Margin { if margin.ends_with('%') { Margin::Percent(min(100, margin[0..margin.len() - 1].parse::<u16>().unwrap_or(100))) } else { Margin::Fixed(margin.parse::<u16>().unwrap_or(0)) } } pub fn parse_margin(margin_option: &str) -> (Margin, Margin, Margin, Margin) { let margins = margin_option.split(',').collect::<Vec<&str>>(); match margins.len() { 1 => { let margin = Curses::parse_margin_string(margins[0]); (margin, margin, margin, margin) } 2 => { let margin_tb = Curses::parse_margin_string(margins[0]); let margin_rl = Curses::parse_margin_string(margins[1]); (margin_tb, margin_rl, margin_tb, margin_rl) } 3 => { let margin_top = Curses::parse_margin_string(margins[0]); let margin_rl = Curses::parse_margin_string(margins[1]); let margin_bottom = Curses::parse_margin_string(margins[2]); (margin_top, margin_rl, margin_bottom, margin_rl) } 4 => { let margin_top = Curses::parse_margin_string(margins[0]); let margin_right = Curses::parse_margin_string(margins[1]); let margin_bottom = Curses::parse_margin_string(margins[2]); let margin_left = Curses::parse_margin_string(margins[3]); (margin_top, margin_right, margin_bottom, margin_left) } _ => (Margin::Fixed(0), Margin::Fixed(0), Margin::Fixed(0), Margin::Fixed(0)), } } // -> (direction, size, wrap, shown) fn parse_preview(preview_option: &str) -> (Direction, Margin, bool, bool) { let options = preview_option.split(':').collect::<Vec<&str>>(); let mut direction = Direction::Right; let mut shown = true; let mut wrap = false; let mut size = Margin::Percent(50); for option in options { // mistake if option.is_empty() { continue; } let first_char = option.chars().next().unwrap_or('A'); // raw string if first_char.is_digit(10) { size = Curses::parse_margin_string(option); } else { match option.to_uppercase().as_str() { "UP" => direction = Direction::Up, "DOWN" => direction = Direction::Down, "LEFT" => direction = Direction::Left, "RIGHT" => direction = Direction::Right, "HIDDEN" => shown = false, "WRAP" => wrap = true, _ => {} } } } (direction, size, wrap, shown) } #[rustfmt::skip] pub fn resize(&mut self) { let (max_y, max_x) = Curses::terminal_size(); let height = self.height(); let start = if self.start_y >= 0 { self.start_y } else { i32::from(max_y) + self.start_y }; let start = min(max_y-height, max(0, start as u16)); self.top = start + match self.margin_top { Margin::Fixed(num) => num, Margin::Percent(per) => per * height / 100, }; self.bottom = start + height - match self.margin_bottom { Margin::Fixed(num) => num, Margin::Percent(per) => per * height / 100, }; self.left = match self.margin_left { Margin::Fixed(num) => num, Margin::Percent(per) => per * max_x / 100, }; self.right = max_x - match self.margin_right { Margin::Fixed(num) => num, Margin::Percent(per) => per * max_x / 100, }; //debug!("curses:resize, TRBL: {}/{}/{}/{}", self.top, self.right, self.bottom, self.left); let height = self.bottom - self.top; let width = self.right - self.left; let preview_height = match self.preview_size { Margin::Fixed(x) => x, Margin::Percent(x) => height * x / 100, }; let preview_width = match self.preview_size { Margin::Fixed(x) => x, Margin::Percent(x) => width * x / 100, }; if !self.preview_shown { self.win_main.reshape(self.top, self.right, self.bottom, self.left); self.win_preview.reshape(0, 0, 0, 0); } else { match self.preview_direction { Direction::Up => { self.win_preview.reshape(self.top, self.right, self.top+preview_height, self.left); self.win_main.reshape(self.top+preview_height, self.right, self.bottom, self.left); self.win_preview.set_border(Some(Direction::Down)); } Direction::Down => { self.win_preview.reshape(self.bottom-preview_height, self.right, self.bottom, self.left); self.win_main.reshape(self.top, self.right, self.bottom-preview_height, self.left); self.win_preview.set_border(Some(Direction::Up)); } Direction::Left => { self.win_preview.reshape(self.top, self.left+preview_width, self.bottom, self.left); self.win_main.reshape(self.top, self.right, self.bottom, self.left+preview_width); self.win_preview.set_border(Some(Direction::Right)); } Direction::Right => { self.win_preview.reshape(self.top, self.right, self.bottom, self.right-preview_width); self.win_main.reshape(self.top, self.right-preview_width, self.bottom, self.left); self.win_preview.set_border(Some(Direction::Left)); } } } } pub fn toggle_preview_window(&mut self) { self.preview_shown = !self.preview_shown; } fn terminal_size() -> (u16, u16) { let (max_x, max_y) = termion::terminal_size().expect("curses:terminal_size: failed to get terminal size"); (max_y, max_x) } fn height(&self) -> u16 { let (max_y, _) = Curses::terminal_size(); match self.height { Margin::Percent(100) => max_y, Margin::Percent(p) => min(max_y, max(p * max_y / 100, self.min_height)), Margin::Fixed(rows) => min(max_y, rows), } } pub fn close(&mut self) { self.win_preview.close(); self.win_main.close(); self.refresh(); { // put it in a special scope so that the "smcup" will be called before stdout is // restored let _ = self.term.take(); } // flush the previous drop, so that ToMainScreen is written before restore stdout().flush().expect("curses:close: failed to flush to stdout"); // restore the original fd if self.orig_stdout_fd.is_some() { unsafe { libc::dup2( self.orig_stdout_fd.expect("curses:close, failed to get fd"), libc::STDOUT_FILENO, ); } } } pub fn refresh(&mut self) { let term = self.term.as_mut().expect("curses:refresh: failed to get terminal"); self.win_preview.write_to_term(term); self.win_main.write_to_term(term); term.flush().expect("curses:refresh: failed to flush terminal"); } } struct ColorWrapper(Box<color::Color>); impl color::Color for ColorWrapper { fn write_fg(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.write_fg(f) } fn write_bg(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.write_bg(f) } } impl<'a> color::Color for &'a ColorWrapper { fn write_fg(&self, f: &mut fmt::Formatter) -> fmt::Result { (*self).write_fg(f) } fn write_bg(&self, f: &mut fmt::Formatter) -> fmt::Result { (*self).write_bg(f) } } #[rustfmt::skip] pub struct ColorTheme { fg: ColorWrapper, // text fg bg: ColorWrapper, // text bg matched: ColorWrapper, matched_bg: ColorWrapper, current: ColorWrapper, current_bg: ColorWrapper, current_match: ColorWrapper, current_match_bg: ColorWrapper, spinner: ColorWrapper, info: ColorWrapper, prompt: ColorWrapper, cursor: ColorWrapper, selected: ColorWrapper, header: ColorWrapper, border: ColorWrapper, } #[rustfmt::skip] impl ColorTheme { pub fn init_from_options(options: &SkimOptions) { // register let theme = if let Some(color) = options.color { ColorTheme::from_options(color) } else { ColorTheme::dark256() }; theme.register_self(); } fn default16() -> Self { ColorTheme { fg: ColorWrapper(Box::new(color::Reset)), bg: ColorWrapper(Box::new(color::Reset)), matched: ColorWrapper(Box::new(color::Green)), matched_bg: ColorWrapper(Box::new(color::Black)), current: ColorWrapper(Box::new(color::Yellow)), current_bg: ColorWrapper(Box::new(color::Black)), current_match: ColorWrapper(Box::new(color::Green)), current_match_bg: ColorWrapper(Box::new(color::Black)), spinner: ColorWrapper(Box::new(color::Green)), info: ColorWrapper(Box::new(color::White)), prompt: ColorWrapper(Box::new(color::Blue)), cursor: ColorWrapper(Box::new(color::Red)), selected: ColorWrapper(Box::new(color::Magenta)), header: ColorWrapper(Box::new(color::Cyan)), border: ColorWrapper(Box::new(color::LightBlack)), } } fn dark256() -> Self { ColorTheme { fg: ColorWrapper(Box::new(color::Reset)), bg: ColorWrapper(Box::new(color::Reset)), matched: ColorWrapper(Box::new(color::AnsiValue(108))), matched_bg: ColorWrapper(Box::new(color::AnsiValue(0))), current: ColorWrapper(Box::new(color::AnsiValue(254))), current_bg: ColorWrapper(Box::new(color::AnsiValue(236))), current_match: ColorWrapper(Box::new(color::AnsiValue(151))), current_match_bg: ColorWrapper(Box::new(color::AnsiValue(236))), spinner: ColorWrapper(Box::new(color::AnsiValue(148))), info: ColorWrapper(Box::new(color::AnsiValue(144))), prompt: ColorWrapper(Box::new(color::AnsiValue(110))), cursor: ColorWrapper(Box::new(color::AnsiValue(161))), selected: ColorWrapper(Box::new(color::AnsiValue(168))), header: ColorWrapper(Box::new(color::AnsiValue(109))), border: ColorWrapper(Box::new(color::AnsiValue(59))), } } fn molokai256() -> Self { ColorTheme { fg: ColorWrapper(Box::new(color::Reset)), bg: ColorWrapper(Box::new(color::Reset)), matched: ColorWrapper(Box::new(color::AnsiValue(234))), matched_bg: ColorWrapper(Box::new(color::AnsiValue(186))), current: ColorWrapper(Box::new(color::AnsiValue(254))), current_bg: ColorWrapper(Box::new(color::AnsiValue(236))), current_match: ColorWrapper(Box::new(color::AnsiValue(234))), current_match_bg: ColorWrapper(Box::new(color::AnsiValue(186))), spinner: ColorWrapper(Box::new(color::AnsiValue(148))), info: ColorWrapper(Box::new(color::AnsiValue(144))), prompt: ColorWrapper(Box::new(color::AnsiValue(110))), cursor: ColorWrapper(Box::new(color::AnsiValue(161))), selected: ColorWrapper(Box::new(color::AnsiValue(168))), header: ColorWrapper(Box::new(color::AnsiValue(109))), border: ColorWrapper(Box::new(color::AnsiValue(59))), } } fn light256() -> Self { ColorTheme { fg: ColorWrapper(Box::new(color::Reset)), bg: ColorWrapper(Box::new(color::Reset)), matched: ColorWrapper(Box::new(color::AnsiValue(0))), matched_bg: ColorWrapper(Box::new(color::AnsiValue(220))), current: ColorWrapper(Box::new(color::AnsiValue(237))), current_bg: ColorWrapper(Box::new(color::AnsiValue(251))), current_match: ColorWrapper(Box::new(color::AnsiValue(66))), current_match_bg: ColorWrapper(Box::new(color::AnsiValue(251))), spinner: ColorWrapper(Box::new(color::AnsiValue(65))), info: ColorWrapper(Box::new(color::AnsiValue(101))), prompt: ColorWrapper(Box::new(color::AnsiValue(25))), cursor: ColorWrapper(Box::new(color::AnsiValue(161))), selected: ColorWrapper(Box::new(color::AnsiValue(168))), header: ColorWrapper(Box::new(color::AnsiValue(31))), border: ColorWrapper(Box::new(color::AnsiValue(145))), } } fn from_options(color: &str) -> Self { let mut theme = ColorTheme::dark256(); for pair in color.split(',') { let color: Vec<&str> = pair.split(':').collect(); if color.len() < 2 { theme = match color[0] { "molokai" => ColorTheme::molokai256(), "light" => ColorTheme::light256(), "16" => ColorTheme::default16(), "dark" | "default" | _ => ColorTheme::dark256(), }; continue; } let new_color = if color[1].len() == 7 { // 256 color let r = u8::from_str_radix(&color[1][1..3], 16).unwrap_or(255); let g = u8::from_str_radix(&color[1][3..5], 16).unwrap_or(255); let b = u8::from_str_radix(&color[1][5..7], 16).unwrap_or(255); ColorWrapper(Box::new(color::Rgb(r, g, b))) } else { ColorWrapper(Box::new(color::AnsiValue(color[1].parse::<u8>().unwrap_or(255)))) }; match color[0] { "fg" => theme.fg = new_color, "bg" => theme.bg = new_color, "matched" => theme.matched = new_color, "matched_bg" => theme.matched_bg = new_color, "current" => theme.current = new_color, "current_bg" => theme.current_bg = new_color, "current_match" => theme.current_match = new_color, "current_match_bg" => theme.current_match_bg = new_color, "spinner" => theme.spinner = new_color, "info" => theme.info = new_color, "prompt" => theme.prompt = new_color, "cursor" => theme.cursor = new_color, "selected" => theme.selected = new_color, "header" => theme.header = new_color, "border" => theme.border = new_color, _ => {} } } theme } fn register_self(&self) { register_resource(COLOR_NORMAL, String::new()); register_resource(COLOR_PROMPT, format!("{}{}", color::Fg(&self.prompt), color::Bg(&self.bg))); register_resource(COLOR_MATCHED, format!("{}{}", color::Fg(&self.matched), color::Bg(&self.matched_bg))); register_resource(COLOR_CURRENT, format!("{}{}", color::Fg(&self.current), color::Bg(&self.current_bg))); register_resource(COLOR_CURRENT_MATCH, format!("{}{}", color::Fg(&self.current_match), color::Bg(&self.current_match_bg))); register_resource(COLOR_SPINNER, format!("{}{}", color::Fg(&self.spinner), color::Bg(&self.bg))); register_resource(COLOR_INFO, format!("{}{}", color::Fg(&self.info), color::Bg(&self.bg))); register_resource(COLOR_CURSOR, format!("{}{}", color::Fg(&self.cursor), color::Bg(&self.current_bg))); register_resource(COLOR_SELECTED, format!("{}{}", color::Fg(&self.selected), color::Bg(&self.current_bg))); register_resource(COLOR_HEADER, format!("{}{}", color::Fg(&self.header), color::Bg(&self.bg))); register_resource(COLOR_BORDER, format!("{}{}", color::Fg(&self.border), color::Bg(&self.bg))); } }
true
921feab056feb09c0d7d95f1493ad153608bcfcd
Rust
dremonkey/lodestone-simplify
/src/lib.rs
UTF-8
6,494
3.328125
3
[]
no_license
use std::collections::BTreeSet; use std::ops::{Add, Mul, Sub}; extern crate rustc_serialize; use rustc_serialize::{Decoder, Decodable}; use rustc_serialize::json::{Json, ToJson}; #[derive(Debug, Clone, Copy)] pub struct Point { pub x: f64, pub y: f64 } pub fn simplify( points: Vec<Point>, tolerance: f64, hq: bool) -> Vec<Point> { let sq_tolerance = tolerance * tolerance; let pts = if hq { points } else { simplify_radial_distance(points, sq_tolerance) }; simplify_douglas_peucker(pts, sq_tolerance) } impl ToJson for Point { fn to_json(&self) -> Json { Json::Array(vec![self.x.to_json(), self.y.to_json()]) } } impl Decodable for Point { fn decode<D: Decoder>(d: &mut D) -> Result<Point, D::Error> { d.read_seq(|decoder, len| { if len != 2 { let msg = format!("Expecting array of length: {}, but found {}", 2, len); panic!(msg); } let point = Point { x: try!(decoder.read_seq_elt(0, Decodable::decode)), y: try!(decoder.read_seq_elt(1, Decodable::decode)) }; Ok(point) }) } } impl PartialEq for Point { fn eq(&self, other: &Self) -> bool { self.x == other.x && self.y == other.y } } impl Add for Point { type Output = Point; fn add(self, other: Self) -> Self { let x = self.x + other.x; let y = self.y + other.y; Point{x: x, y: y} } } impl Mul for Point { type Output = Point; fn mul(self, other: Self) -> Self { let x = self.x * other.x; let y = self.y * other.y; Point{x: x, y: y} } } impl Sub for Point { type Output = Point; fn sub(self, other: Self) -> Self { let x = self.x - other.x; let y = self.y - other.y; Point{x: x, y: y} } } impl Point { pub fn sq_dist(&self, other: &Self) -> f64 { let dx = self.x - other.x; let dy = self.x - other.y; dx * dx + dy * dy } } /// http://paulbourke.net/geometry/pointlineplane/ /// /// ## Parameters /// * pt - standalone point /// * pt1 - Line segment endpoint /// * pt2 - Line segment endpoint fn get_square_segment_distance(p: Point, p1: Point, p2: Point) -> f64 { let mut x = p1.x; let mut y = p1.y; let mut dx = p2.x - x; let mut dy = p2.y - y; if dx != 0.0 || dy != 0.0 { let t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy); if t > 1.0 { x = p2.x; y = p2.y; } else if t > 0.0 { x += dx * t; y += dy * t; } } dx = p.x - x; dy = p.y - y; dx * dx + dy * dy } /// Basic distance-based simplification fn simplify_radial_distance( points: Vec<Point>, sq_tolerance: f64) -> Vec<Point> { let last = points.last().unwrap().clone(); let mut prev = points.first().unwrap(); let mut new_points = vec![prev.clone()]; let mut iter = points.iter(); iter.next(); // skip the first point for point in points.iter() { if point.sq_dist(prev) > sq_tolerance { new_points.push(point.clone()); prev = point; } } if prev.clone() != last { new_points.push(last); } new_points } fn simplify_douglas_peucker( points: Vec<Point>, sq_tolerance: f64) -> Vec<Point> { let len = points.len(); let mut first = 0; let mut last = len - 1; let mut pair = (first, last); let mut markers = BTreeSet::new(); let mut stack: Vec<(usize, usize)> = vec![]; let mut index = 0; // keep first and last indices.. markers.insert(first); markers.insert(last); loop { let mut max_sq_dist = 0.0; first = pair.0; last = pair.1; for i in first+1..last { let pt1 = points[i]; let sq_dist = get_square_segment_distance(pt1, points[first], points[last]); if sq_dist > max_sq_dist { index = i; max_sq_dist = sq_dist; } } if max_sq_dist > sq_tolerance { markers.insert(index); stack.push((first, index)); stack.push((index, last)); } match stack.pop() { Some(p) => pair = p, None => break } } markers.iter().map(|&i| points[i]).collect() } #[cfg(test)] mod tests { use super::{ Point, get_square_segment_distance, simplify_radial_distance, simplify_douglas_peucker }; #[test] fn test_add() { let pt1 = Point{x: 2.0, y: 2.0}; let pt2 = Point{x: 1.0, y: 1.0}; let pt3 = Point{x: 1.0, y: 1.0}; assert_eq!(pt1 + pt2, Point{x: 3.0, y: 3.0}); assert_eq!(pt2 + pt3, Point{x: 2.0, y: 2.0}); } #[test] fn test_mul() { let pt1 = Point{x: 4.0, y: 4.0}; let pt2 = Point{x: 2.0, y: 2.0}; let pt3 = Point{x: 1.0, y: 1.0}; assert_eq!(pt1 * pt2, Point{x: 8.0, y: 8.0}); assert_eq!(pt2 * pt3, Point{x: 2.0, y: 2.0}); } #[test] fn test_sub() { let pt1 = Point{x: 2.0, y: 2.0}; let pt2 = Point{x: 1.0, y: 1.0}; let pt3 = Point{x: 1.0, y: 1.0}; assert_eq!(pt1 - pt2, Point{x: 1.0, y: 1.0}); assert_eq!(pt2 - pt3, Point{x: 0.0, y: 0.0}); assert_eq!(pt2 - pt1, Point{x: -1.0, y: -1.0}); } #[test] fn test_get_square_segment_distance() { let pt1 = Point{x: 2.0, y: 2.0}; let pt2 = Point{x: 0.0, y: 0.0}; let pt3 = Point{x: 4.0, y: 0.0}; let pt4 = Point{x: 4.0, y: 4.0}; let pt5 = Point{x: 224.55, y: 250.15}; let pt6 = Point{x: 866.36, y: 480.77}; let pt7 = Point{x: 784.20, y: 218.16}; let pt8 = Point{x: 779.60, y: 216.87}; assert_eq!(get_square_segment_distance(pt1, pt2, pt3), 4.0); assert_eq!(get_square_segment_distance(pt1, pt2, pt4), 0.0); assert_eq!(get_square_segment_distance(pt7, pt5, pt6), 48117.146246042365); assert_eq!(get_square_segment_distance(pt8, pt5, pt6), 47967.43057247439); } #[test] fn test_simplify_radial_distance() { let pt1 = Point{x: 0.0, y: 0.0}; let pt2 = Point{x: 1.0, y: 1.0}; let pt3 = Point{x: 2.0, y: 2.0}; let pt4 = Point{x: 3.0, y: 3.0}; let pt5 = Point{x: 4.0, y: 4.0}; let points = vec![pt1, pt2, pt3, pt4, pt5]; let sq_tolerance = 4.0; let expected = vec![pt1, pt3, pt5]; assert_eq!(expected, simplify_radial_distance(points, sq_tolerance)); } #[test] fn test_simplify_douglas_peucker() { let pt1 = Point{x: 0.0, y: 0.0}; let pt2 = Point{x: 1.0, y: 1.0}; let pt3 = Point{x: 2.0, y: 2.0}; let pt4 = Point{x: 3.0, y: 3.0}; let pt5 = Point{x: 4.0, y: 4.0}; let points = vec![pt1, pt2, pt3, pt4, pt5]; let sq_tolerance = 4.0; let expected = vec![pt1, pt5]; assert_eq!(expected, simplify_douglas_peucker(points, sq_tolerance)); } }
true
c29b55abc817ba4f7f09fbf80f13e23bd3334918
Rust
sybila/biodivine-aeon-server
/src/scc/algo_saturated_reachability/mod.rs
UTF-8
2,363
2.796875
3
[ "MIT" ]
permissive
use crate::GraphTaskContext; use biodivine_lib_param_bn::biodivine_std::traits::Set; use biodivine_lib_param_bn::symbolic_async_graph::{GraphColoredVertices, SymbolicAsyncGraph}; use biodivine_lib_param_bn::VariableId; /// Performs one reachability step using the saturation scheme. /// /// The `universe` is an upper bound on what elements can be added to the `set`. Using `variables` /// you can restrict the considered transitions. Finally, `step` implements update in one /// variable. /// /// Returns `true` if fixpoint has been reached. pub fn reachability_step<F>( set: &mut GraphColoredVertices, universe: &GraphColoredVertices, variables: &[VariableId], step: F, ) -> bool where F: Fn(VariableId, &GraphColoredVertices) -> GraphColoredVertices, { if variables.is_empty() { return true; } for var in variables.iter().rev() { let stepped = step(*var, set).minus(set).intersect(universe); if !stepped.is_empty() { *set = set.union(&stepped); return false; } } true } /// Fully compute reachable states from `initial` inside `universe` using transitions under /// `variables`. /// /// The process is cancellable using the `GraphTaskContext`, in which case the result is valid, /// but not complete. pub fn reach_fwd( ctx: &GraphTaskContext, graph: &SymbolicAsyncGraph, initial: &GraphColoredVertices, universe: &GraphColoredVertices, variables: &[VariableId], ) -> GraphColoredVertices { let mut set = initial.clone(); while !ctx.is_cancelled() { if reachability_step(&mut set, universe, variables, |v, s| graph.var_post(v, s)) { break; } } set } /// Fully compute back-reachable states from `initial` inside `universe` using transitions under /// `variables`. /// /// The process is cancellable using the `GraphTaskContext`, in which case the result is valid, /// but not complete. pub fn reach_bwd( ctx: &GraphTaskContext, graph: &SymbolicAsyncGraph, initial: &GraphColoredVertices, universe: &GraphColoredVertices, variables: &[VariableId], ) -> GraphColoredVertices { let mut set = initial.clone(); while !ctx.is_cancelled() { if reachability_step(&mut set, universe, variables, |v, s| graph.var_pre(v, s)) { break; } } set }
true
988f3cc94f501e30bd6dc5dd23fa6f96c85ca2ae
Rust
FilippoRanza/fsa-net
/src/engine/full_space.rs
UTF-8
3,043
2.84375
3
[ "MIT" ]
permissive
use crate::graph; use crate::network; use crate::state_table; use std::collections::VecDeque; use super::engine_utils::{get_next_index, get_next_state}; use super::EngineConfig; pub struct FullSpaceResult { pub graph: graph::Graph<network::TransEvent>, pub states: Vec<network::State>, pub complete: bool, } pub fn compute_full_space(net: &network::Network, conf: &EngineConfig) -> FullSpaceResult { let mut builder = graph::GraphBuilder::new(); let mut table = state_table::StateTable::new(); let mut stack = VecDeque::new(); let begin_state = net.get_initial_state(); let begin_index = table.insert_state(begin_state); stack.push_front(begin_index); let mut timeout = false; let timer = conf.timer_factory.new_timer(); while let Some(state_index) = get_next_state(&mut stack, &timer, &mut timeout) { let curr_state = table.get_object(state_index); if curr_state.is_final() { builder.add_final_node(state_index); } else { builder.add_simple_node(state_index); } let next_state = net.step_one(curr_state); for (ev, next_state) in next_state.into_iter() { let next_index = get_next_index(next_state, &mut table, &mut stack); builder.add_arc(state_index, next_index, ev); } } let (graph, states) = conf.mode.build_graph(builder, table); FullSpaceResult { graph, states, complete: !timeout, } } impl Into<super::NetworkResult> for FullSpaceResult { fn into(self) -> super::NetworkResult { super::NetworkResult::FullSpace(self) } } #[cfg(test)] mod test { use super::super::EngineConfig; use super::super::GraphMode; use super::*; use crate::compiler::compile; use crate::timer; use fsa_net_parser::parse; use test_utils::load_code_from_file; #[test] fn test_full_space() { let src_code = load_code_from_file("simple-network"); let code = parse(&src_code).expect("`simple-network` should be syntactically correct"); let comp_res = compile(&code).expect("`simple-network` should be semantically correct"); let net = &comp_res.compile_network[0].net; let config = EngineConfig::new(GraphMode::Full, timer::TimerFactory::from_value(None)); let result = compute_full_space(&net, &config); let adjacent_list = result.graph.get_adjacent_list(); assert_eq!(adjacent_list.len(), 15); let expected = vec![ vec![1], // 0 vec![2], // 1 vec![3, 4], // 2 vec![7, 8], // 3 vec![5], // 4 vec![0, 6], // 5 vec![], // 6 vec![9], // 7 vec![9], // 8 vec![10, 1], // 9 vec![11], // 10 vec![12], // 11 vec![13, 8], // 12 vec![14], // 13 vec![], // 14 ]; assert_eq!(adjacent_list, &expected); } }
true
a32c02329761340d2fc38827d7ebc286785cecda
Rust
Azure/azure-sdk-for-rust
/services/autorust/openapi/src/schema.rs
UTF-8
7,212
2.828125
3
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
permissive
use crate::*; use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use std::fmt::Display; // http://json.schemastore.org/swagger-2.0 /// The transfer protocol of the API. Values MUST be from the list: "http", "https", "ws", "wss". /// If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself. #[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum Scheme { #[default] Http, Https, Ws, Wss, } impl Display for Scheme { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Scheme::Http => write!(f, "http"), Scheme::Https => write!(f, "https"), Scheme::Ws => write!(f, "ws"), Scheme::Wss => write!(f, "wss"), } } } /// https://swagger.io/docs/specification/data-models/data-types/ /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum DataType { String, Number, Integer, Boolean, Array, Object, File, } /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityRequirementObject pub type SecurityRequirement = IndexMap<String, Vec<String>>; /// https://swagger.io/docs/specification/2-0/describing-responses/ /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responseObject #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] pub struct Response { #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub schema: Option<ReferenceOr<Schema>>, #[serde(default, skip_serializing_if = "IndexMap::is_empty")] pub headers: IndexMap<String, ReferenceOr<Header>>, #[serde(rename = "x-ms-error-response", skip_serializing_if = "Option::is_none")] pub x_ms_error_response: Option<bool>, } #[allow(clippy::large_enum_variant)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(untagged)] pub enum AdditionalProperties { Boolean(bool), Schema(ReferenceOr<Schema>), } /// common fields in both Schema Object & Parameter Object /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SchemaCommon { #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#items-object #[serde(rename = "type", skip_serializing_if = "Option::is_none")] pub type_: Option<DataType>, #[serde(skip_serializing_if = "Option::is_none")] pub format: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub items: Box<Option<ReferenceOr<Schema>>>, #[serde(skip_serializing_if = "Option::is_none")] pub default: Option<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] pub maximum: Option<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] pub exclusive_maximum: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub minimum: Option<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] pub exclusive_minimum: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub max_length: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] pub min_length: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] pub pattern: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub max_items: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] pub min_items: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] pub unique_items: Option<bool>, #[serde(rename = "enum", default, skip_serializing_if = "Vec::is_empty")] pub enum_: Vec<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] pub multiple_of: Option<f64>, #[serde(rename = "x-ms-enum", skip_serializing_if = "Option::is_none")] pub x_ms_enum: Option<MsEnum>, #[serde(rename = "x-ms-client-name", skip_serializing_if = "Option::is_none")] pub x_ms_client_name: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub xml: Option<MsXml>, } /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Schema { #[serde(flatten)] pub common: SchemaCommon, #[serde(skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub required: Vec<String>, #[serde(default, skip_serializing_if = "IndexMap::is_empty")] pub properties: IndexMap<String, ReferenceOr<Schema>>, #[serde(skip_serializing_if = "Option::is_none")] pub additional_properties: Box<Option<AdditionalProperties>>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub all_of: Vec<ReferenceOr<Schema>>, #[serde(skip_serializing_if = "Option::is_none")] pub discriminator: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub read_only: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub external_docs: Option<ExternalDocumentation>, #[serde(rename = "x-ms-secret", skip_serializing_if = "Option::is_none")] pub x_ms_secret: Option<bool>, /// indicates that the Definition Schema Object is a resource as defined by the Resource Manager API /// https://github.com/Azure/autorest/blob/master/docs/extensions/readme.md#x-ms-azure-resource #[serde(rename = "x-ms-azure-resource", skip_serializing_if = "Option::is_none")] pub x_ms_azure_resource: Option<bool>, /// provides insight to Autorest on how to generate code. It doesn't alter the modeling of what is actually sent on the wire /// https://github.com/Azure/autorest/blob/master/docs/extensions/readme.md#x-ms-mutability #[serde(rename = "x-ms-mutability", default, skip_serializing_if = "Vec::is_empty")] pub x_ms_mutability: Vec<MsMutability>, /// allows specific Definition Objects to be excluded from code generation /// https://github.com/Azure/autorest/blob/master/docs/extensions/readme.md#x-ms-external #[serde(rename = "x-ms-external", skip_serializing_if = "Option::is_none")] pub x_ms_external: Option<bool>, #[serde(rename = "x-nullable", skip_serializing_if = "Option::is_none")] pub x_nullable: Option<bool>, #[serde(rename = "x-ms-discriminator-value", skip_serializing_if = "Option::is_none")] pub x_ms_discriminator_value: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub example: Option<serde_json::Value>, }
true
1587e24d9eb9be92ed8d696ff4c5718e237114f7
Rust
emanuelpalm/arspec
/arspec/src/spec/verify/mod.rs
UTF-8
1,033
3.171875
3
[]
no_license
use std::collections::HashMap; pub struct Duplicate<'a, E> { pub original: &'a E, pub duplicate: &'a E, } pub fn find_duplicate<E>(items: &[E]) -> Option<Duplicate<E>> where E: AsRef<str>, { let len = items.len(); if len < 16 { for a in items { let a0 = a.as_ref(); let mut count = 0; for b in items { if a0 == b.as_ref() { count += 1; if count > 1 { return Some(Duplicate { original: a, duplicate: b, }); } } } } } else { let mut map = HashMap::with_capacity(items.len()); for item in items { if let Some(original) = map.insert(item.as_ref(), item) { return Some(Duplicate { original, duplicate: item, }); } } } None }
true
a143063b3765b9bae7789f88aab20abc909f3f9d
Rust
amedeekirk/learning-rust
/vectors.rs
UTF-8
589
3.296875
3
[]
no_license
/* * Follow Along code for learning rust with Derek Banas * https://www.youtube.com/watch?v=U1EFgCNLDB8 */ use std:: {i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64}; use std::io::stdin; fn main() { let mut vect = vec![1,2,3,4,5]; println!("Item 2: {}", vect[1]); for i in &vect { println!("Vect: {}", i); } // Add and remove values on array vect.push(6); vect.pop(); // Keeps terminal open let mut input = String::new(); stdin().read_line(&mut input) .ok() .expect("Couldn't read line"); }
true
c7d40bd43f4e6ebf4a0c7d112e314952565c65e7
Rust
chutchinson/chip-8
/src/timer.rs
UTF-8
702
3.25
3
[]
no_license
use std::time::{Instant, Duration}; pub struct Timer { frequency: Duration, clock: Instant, state: bool } impl Timer { pub fn new(frequency_ns: u32) -> Self { Timer { frequency: Duration::new(0, frequency_ns), clock: Instant::now(), state: false } } pub fn reset(&mut self) { self.state = false; self.clock = Instant::now(); } pub fn active(&self) -> bool { self.state } pub fn tick(&mut self) { self.state = if self.clock.elapsed() >= self.frequency { self.clock = Instant::now(); true } else { false } } }
true
50b31d2d3b77ababd149886f512c592ec7025cb1
Rust
filecoin-project/rust-fil-proofs
/filecoin-hashers/src/types.rs
UTF-8
3,451
2.609375
3
[ "Apache-2.0", "MIT" ]
permissive
use std::fmt::Debug; use std::hash::Hash as StdHash; #[cfg(feature = "poseidon")] pub use crate::poseidon_types::*; use bellperson::{ gadgets::{boolean::Boolean, num::AllocatedNum}, ConstraintSystem, SynthesisError, }; use blstrs::Scalar as Fr; use ff::PrimeField; use merkletree::{ hash::{Algorithm as LightAlgorithm, Hashable as LightHashable}, merkle::Element, }; use rand::RngCore; use serde::{de::DeserializeOwned, Serialize}; pub trait Domain: Ord + Copy + Clone + AsRef<[u8]> + Default + Debug + Eq + Send + Sync + From<Fr> + From<<Fr as PrimeField>::Repr> + Into<Fr> + Serialize + DeserializeOwned + Element + StdHash { #[allow(clippy::wrong_self_convention)] fn into_bytes(&self) -> Vec<u8>; fn try_from_bytes(raw: &[u8]) -> anyhow::Result<Self>; /// Write itself into the given slice, LittleEndian bytes. fn write_bytes(&self, _: &mut [u8]) -> anyhow::Result<()>; fn random<R: RngCore>(rng: &mut R) -> Self; } pub trait HashFunction<T: Domain>: Clone + Debug + Send + Sync + LightAlgorithm<T> { fn hash(data: &[u8]) -> T; fn hash2(a: &T, b: &T) -> T; fn hash_md(input: &[T]) -> T { // Default to binary. assert!(input.len() > 1, "hash_md needs more than one element."); input .iter() .skip(1) .fold(input[0], |acc, elt| Self::hash2(&acc, elt)) } fn hash_leaf(data: &dyn LightHashable<Self>) -> T { let mut a = Self::default(); data.hash(&mut a); let item_hash = a.hash(); a.leaf(item_hash) } fn hash_single_node(data: &dyn LightHashable<Self>) -> T { let mut a = Self::default(); data.hash(&mut a); a.hash() } fn hash_leaf_circuit<CS: ConstraintSystem<Fr>>( mut cs: CS, left: &AllocatedNum<Fr>, right: &AllocatedNum<Fr>, height: usize, ) -> Result<AllocatedNum<Fr>, SynthesisError> { let left_bits = left.to_bits_le(cs.namespace(|| "left num into bits"))?; let right_bits = right.to_bits_le(cs.namespace(|| "right num into bits"))?; Self::hash_leaf_bits_circuit(cs, &left_bits, &right_bits, height) } fn hash_multi_leaf_circuit<Arity: 'static + PoseidonArity, CS: ConstraintSystem<Fr>>( cs: CS, leaves: &[AllocatedNum<Fr>], height: usize, ) -> Result<AllocatedNum<Fr>, SynthesisError>; fn hash_md_circuit<CS: ConstraintSystem<Fr>>( _cs: &mut CS, _elements: &[AllocatedNum<Fr>], ) -> Result<AllocatedNum<Fr>, SynthesisError> { unimplemented!(); } fn hash_leaf_bits_circuit<CS: ConstraintSystem<Fr>>( _cs: CS, _left: &[Boolean], _right: &[Boolean], _height: usize, ) -> Result<AllocatedNum<Fr>, SynthesisError> { unimplemented!(); } fn hash_circuit<CS: ConstraintSystem<Fr>>( cs: CS, bits: &[Boolean], ) -> Result<AllocatedNum<Fr>, SynthesisError>; fn hash2_circuit<CS>( cs: CS, a: &AllocatedNum<Fr>, b: &AllocatedNum<Fr>, ) -> Result<AllocatedNum<Fr>, SynthesisError> where CS: ConstraintSystem<Fr>; } pub trait Hasher: Clone + Debug + Eq + Default + Send + Sync { type Domain: Domain + LightHashable<Self::Function> + AsRef<Self::Domain>; type Function: HashFunction<Self::Domain>; fn name() -> String; }
true
2cb2983e7f42f235a83ec779a140dbc9e1d306f4
Rust
stearnsc/config_loader
/src/lib.rs
UTF-8
8,598
2.625
3
[]
no_license
#![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate itertools; #[macro_use] extern crate lazy_static; extern crate regex; extern crate serde; extern crate toml; #[cfg(test)] #[macro_use] extern crate serde_derive; use std::fs::File; use std::env; use std::io::Read; use serde::de::DeserializeOwned; use std::path::{Path, PathBuf}; use regex::Regex; use std::collections::BTreeMap; use itertools::Itertools; lazy_static! { static ref ENV_FLAG_REQ: Regex = Regex::new("^<<ENV:([a-zA-Z0-9_]*)>>$").unwrap(); static ref ENV_FLAG_OPT: Regex = Regex::new("^<<ENV\\?:([a-zA-Z0-9_]*)>>$").unwrap(); } pub fn load_config<C: DeserializeOwned, P: AsRef<Path>>(config_path: Option<P>) -> Result<C, Error> { let mut config_file = open_config_file(config_path)?; let mut s = String::new(); config_file.read_to_string(&mut s)?; load_config_from_str(&s) } pub fn load_config_from_str<C: DeserializeOwned>(config_str: &str) -> Result<C, Error> { let loaded_config = load_env_variables(toml::from_str(config_str)?)?; // is there a better way to do this than shortcutting through string? let loaded_config_str = toml::to_string(&loaded_config)?; let config = toml::from_str(&loaded_config_str)?; Ok(config) } fn open_config_file<T: AsRef<Path>>(path: Option<T>) -> Result<File, Error> { match path { Some(path) => File::open(path), None => { let default_path = get_default_config_path() .ok_or(String::from("Default config file not found"))?; File::open(default_path) } }.map_err(|e| e.into()) } fn get_default_config_path() -> Option<PathBuf> { let mut path = env::current_dir() .expect("Error finding executable directory"); path.push("Config.toml"); if path.exists() { Some(path) } else { None } } fn load_env_variables(config: toml::value::Table) -> Result<toml::Value, Error> { config.into_iter().fold(Ok(BTreeMap::new()), |mut result, (k, v)| { match load_env_variable(v) { Ok(Some(new_v)) => { if let Ok(ref mut m) = result.as_mut() { m.insert(k, new_v); } result }, Ok(None) => result, Err(e) => { match result { Ok(_) => Err(e), Err(existing_err) => Err(combine_errors(existing_err, e)) } } } }).map(|table| toml::Value::Table(table)) } fn load_env_variable(value: toml::Value) -> Result<Option<toml::Value>, Error> { match value { toml::Value::String(ref s) if ENV_FLAG_REQ.is_match(s) => { let env_key = s .trim_left_matches("<<ENV:") .trim_right_matches(">>"); match env::var(env_key) { Ok(env_var) => Ok(Some(toml::Value::String(env_var))), Err(env::VarError::NotPresent) => Err(ErrorKind::EnvVarMissing(env_key.to_owned()).into()), Err(e) => Err(e.into()) } }, toml::Value::String(ref s) if ENV_FLAG_OPT.is_match(&s) => { let env_key = s .trim_left_matches("<<ENV?:") .trim_right_matches(">>"); match env::var(env_key) { Ok(env_var) => Ok(Some(toml::Value::String(env_var))), Err(env::VarError::NotPresent) => Ok(None), Err(e) => Err(e.into()) } }, toml::Value::Table(table) => load_env_variables(table).map(|vs| Some(vs)), other_value => Ok(Some(other_value)) } } fn combine_errors(e1: Error, e2: Error) -> Error { match (e1, e2) { (Error(ErrorKind::Multiple(mut es1), _), Error(ErrorKind::Multiple(es2), _)) => { es1.extend(es2); ErrorKind::Multiple(es1).into() }, (Error(ErrorKind::Multiple(mut es), _), other) | (other, Error(ErrorKind::Multiple(mut es), _)) => { es.push(other); ErrorKind::Multiple(es).into() }, (e1, e2) => { ErrorKind::Multiple(vec![e1, e2]).into() } } } error_chain! { types { Error, ErrorKind, ResultExt; } foreign_links { Io(::std::io::Error); Env(env::VarError); Deserialization(toml::de::Error); Serialization(toml::ser::Error); } errors { EnvVarMissing(key: String) { description("Required environment variable missing") display("Required environment variable '{}' not set", key) } Multiple(errs: Vec<Error>) { description("Multiple errors") display("Errors: {}", errs.iter().join(", ")) } } } #[cfg(test)] mod tests { use super::load_config_from_str; use std::env; #[derive(Debug, Deserialize)] struct SubConfig { thing1: String, thing2: String } #[derive(Debug, Deserialize)] struct Config { foo: String, bar: i32, baz: Option<String>, more: SubConfig } #[test] fn it_works_when_all_defined() { let config_str = r#" foo = "foo value" bar = 1234 baz = "baz value" [more] thing1 = "thing1 value" thing2 = "thing2 value" "#; let config: Config = load_config_from_str(config_str).unwrap(); assert_eq!(&config.foo, "foo value"); assert_eq!(config.bar, 1234); assert_eq!(&config.baz, &Some("baz value".to_string())); assert_eq!(&config.more.thing1, "thing1 value"); assert_eq!(&config.more.thing2, "thing2 value"); } #[test] fn it_works_when_opt_empty() { let config_str = r#" foo = "foo value" bar = 1234 [more] thing1 = "thing1 value" thing2 = "thing2 value" "#; let config: Config = load_config_from_str(config_str).unwrap(); assert_eq!(&config.foo, "foo value"); assert_eq!(config.bar, 1234); assert_eq!(&config.baz, &None); assert_eq!(&config.more.thing1, "thing1 value"); assert_eq!(&config.more.thing2, "thing2 value"); } #[test] fn it_works_when_env_var_required() { let config_str = r#" foo = "<<ENV:FOO1>>" bar = 1234 baz = "baz value" [more] thing1 = "thing1 value" thing2 = "thing2 value" "#; env::set_var("FOO1", "env foo value"); let config: Config = load_config_from_str(config_str).unwrap(); assert_eq!(&config.foo, "env foo value"); assert_eq!(config.bar, 1234); assert_eq!(&config.baz, &Some("baz value".to_string())); assert_eq!(&config.more.thing1, "thing1 value"); assert_eq!(&config.more.thing2, "thing2 value"); } #[test] fn it_fails_when_required_env_var_missing() { let config_str = r#" foo = "<<ENV:FOO2>>" bar = 1234 baz = "<<ENV:BAZ2>>" [more] thing1 = "thing1 value" thing2 = "thing2 value" "#; assert!(load_config_from_str::<Config>(config_str).is_err()) } //Tests combined here to avoid race condition between accessing env #[test] fn it_works_when_env_var_optional() { let config_str = r#" foo = "foo value" bar = 1234 baz = "<<ENV?:BAZ>>" [more] thing1 = "thing1 value" thing2 = "thing2 value" "#; env::set_var("BAZ", "env baz value"); let config1: Config = load_config_from_str(config_str).unwrap(); assert_eq!(&config1.foo, "foo value"); assert_eq!(config1.bar, 1234); assert_eq!(&config1.baz, &Some("env baz value".to_string())); assert_eq!(&config1.more.thing1, "thing1 value"); assert_eq!(&config1.more.thing2, "thing2 value"); env::remove_var("BAZ"); let config2: Config = load_config_from_str(config_str).unwrap(); assert_eq!(&config2.foo, "foo value"); assert_eq!(config2.bar, 1234); assert_eq!(&config2.baz, &None); assert_eq!(&config2.more.thing1, "thing1 value"); assert_eq!(&config2.more.thing2, "thing2 value"); } }
true
065ef836b7f679c93981bf853536c5817a99601c
Rust
guolianwei/ruststudy
/src/main.rs
UTF-8
5,338
3.53125
4
[]
no_license
extern crate rand; use rand::Rng; use std::cmp::Ordering; use std::io; use std::fs::File; use std::io::ErrorKind; include!("vect.rs"); include!("borrow.rs"); include!("fun.rs"); include!("closures.rs"); fn read_from_file() -> Result<String, io::Error> { let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) } fn read_username_from_file() -> Result<String, io::Error> { let mut s = String::new(); File::open("hello.txt")?.read_to_string(&mut s)?; Ok(s) } fn main() { let f= File::open("hello.txt"); let f1= File::open("hello.txt").expect("Failed to open hello.txt"); let f = match f { Ok(file) => file, Err(ref error) if error.kind() == ErrorKind::NotFound =>{ match File::create("hello.txt") { Ok(fc)=>fc, Err(e)=>{ panic!( "Tried to create file but there was a problem:{:?}", e ) }, } }, Err(error) =>{ panic!( "There was a problem opening the file:{:?}", error ) } }; let c=Circle { x:0.0f64, y:0.0f64, radius:1.0f64, }; let s= Square { x:0.0f64, y:0.0f64, side:1.0f64, }; print_area(s); print_area(c); vect_test(1); println!("Guess the number!"); println!("Please input you Guess."); let _secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is:{}", _secret_number); vect_out_of_index(); vect_show(2); let _f: fn(i32) -> i32; let _f = plus_one; _f(1); let _six = _f(5); let mut x: i32 = 1; x = 7; let _x = x; // x is now immutable and is bound to 7 let _y = 4; let _y = "I can also be bound to text"; //`y` is now of a different type print_number(5); println!(" The number to add one:{}", add_one(34)); loop { let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line!"); let x = 6; let y = 10; println!("x and y {} and {}", x, y); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed {}", guess); match guess.cmp(&_secret_number) { Ordering::Less => println!("Too small"), Ordering::Greater => println!("Too big"), Ordering::Equal => { println!("You win"); break; } } } borrow_example(); } fn print_number(x: i32) { println!("x is {}", x); } fn add_one(x: i32) -> i32 { x + 1 } fn plus_one(x: i32) -> i32 { x + 1 } fn diverges() -> ! { panic!("This function never returns!"); } fn arrays_show() -> ! { let _a = [1, 2, 3]; //a:[i32,3] let mut m = [1, 2, 3]; //m:[i32;3] let _a = [0; 20]; //There is an shorthand for initializing each elment of an array to the same value let _a = [1, 2, 3]; let _names = ["Graydon", "Brian", "Niko"]; //names:[&str;3] println!("The second name is :{}", _names[1]); println!("a has {} elments", _a.len()); panic!("This function never returns!"); } fn primitive_types() -> ! { let _x = true; let _y: bool = false; let _x = 'x'; let _two_hearts = '※'; let _x = 42; // x has type i32 let _y = 1.0; //y has type `f64` panic!("This function never returns!"); } fn slice_array() { //a portion of an array without copying. let _a = [1, 2, 3, 4, 5]; let _complete = &_a[..]; //A slice containing all of the elments in `a` let _middle = &_a[1..4]; //A slice of `a`:only the elments `1`,`2`, and `3`. } fn tuples() { let _x = (1, "elaborate"); // We will elaborate further when we cover Strings and references. let _x: (i32, &str) = (1, "parentheses and commas heterogeneous heterogeneous"); } fn you_can_assign_one_tuple_into_another() { let mut _x = (1, 2); //x:(i32,i32) let y = (2, 3); _x = y; } fn functions_also_have_a_type() { fn foo(x: i32) -> i32 { x } let x: fn(i32) -> i32 = foo; // in this case ,x is an 'function pointer' to a function that takes an i32 and returns an i32; } fn if_fun_grasp_the_nuances() { let _x = 5; if _x == 5 { println!("x is five!"); } let y = if _x == 5 { 10 } else { 15 }; } fn while_fn(arg: i32) -> i32 { let mut x = 5; let mut done = false; while !done { x += x - 3; println!("{}", x); if x % 5 == 0 { done = true; } } x } fn slice_syntax(arg: i32) -> i32 { let a = [0, 1, 2, 3, 4]; let _complete = &a[..]; //A slice containing all of the elements in `a`; let _middle = &a[1..4]; //A slice of a :only the elments 1,2,3; 7 } fn vect_show(arg: i32) -> i32 { let v = vec![1, 2, 3, 4, 5]; let v1 = vec![0; 10]; // ten zeros println!("the third element of v is {}", v[2]); 2 } fn vect_out_of_index() { let v = vec![1, 2, 3]; //out of bounds Access match v.get(7) { Some(_x) => println!("Item 7 is {}", _x), None => println!("Sorry this vect is to Short."), } }
true
1da47c1abe7d03eca0b42af5dc9fb8205a134466
Rust
artslob/ray-tracing-one-weekend
/src/world.rs
UTF-8
3,746
3.046875
3
[]
no_license
use crate::hittable::{HitRecord, Hittable}; use crate::materials; use crate::ray::Ray; use crate::sphere::Sphere; use crate::utils; use crate::vec3::{Color, Point3}; type ThreadHittable = dyn Hittable + Sync + Send; pub struct World { list: Vec<Box<ThreadHittable>>, } impl World { pub fn new(list: Vec<Box<ThreadHittable>>) -> Self { Self { list } } pub fn add(&mut self, value: Box<ThreadHittable>) { self.list.push(value) } pub fn with_items() -> Self { let mut the_world = Self::new(vec![]); let material_ground = materials::Lambertian::new(Color { x: 0.5, y: 0.5, z: 0.5, }); the_world.add(Box::new(Sphere::new( Point3 { x: 0.0, y: -1000., z: 0.0, }, 1000., Box::new(material_ground), ))); for a in -11..11 { for b in -11..11 { let choose_mat = utils::random_double(); let center = Point3 { x: a as f64 + 0.9 * utils::random_double(), y: 0.2, z: b as f64 + 0.9 * utils::random_double(), }; let another_point = Point3 { x: 4., y: 0.2, z: 0., }; if (center - another_point).length() <= 0.9 { continue; } let sphere_material: Box<dyn materials::Material + Send + Sync> = if choose_mat < 0.8 { // diffuse let albedo = Color::random() * Color::random(); Box::new(materials::Lambertian::new(albedo)) } else if choose_mat < 0.95 { // metal let albedo = Color::random_range(0.5, 1.); let fuzz = utils::random_double_range(0., 0.5); Box::new(materials::Metal::new(albedo, fuzz)) } else { // glass Box::new(materials::Dielectric::new(1.5)) }; the_world.add(Box::new(Sphere::new(center, 0.2, sphere_material))); } } the_world.add(Box::new(Sphere::new( Point3 { x: 0.0, y: 1.0, z: 0.0, }, 1., Box::new(materials::Dielectric::new(1.5)), ))); the_world.add(Box::new(Sphere::new( Point3 { x: -4.0, y: 1.0, z: 0.0, }, 1., Box::new(materials::Lambertian::new(Color { x: 0.4, y: 0.2, z: 0.1, })), ))); the_world.add(Box::new(Sphere::new( Point3 { x: 4.0, y: 1.0, z: 0.0, }, 1., Box::new(materials::Metal::new( Color { x: 0.7, y: 0.6, z: 0.5, }, 0.1, )), ))); the_world } } impl Hittable for World { fn hit(&self, ray: &Ray, min: f64, max: f64) -> Option<HitRecord> { let mut closest = max; let mut result: Option<HitRecord> = None; for hittable in self.list.iter() { if let Some(record) = hittable.hit(ray, min, closest) { closest = record.t; result = Some(record); } } result } }
true
f0bee5309ce983ece2d52501c106147989606067
Rust
baitcenter/cvmath
/examples/svgdoc.rs
UTF-8
8,765
2.78125
3
[]
no_license
/*! Generates the SVG for the documentation and serves as a simple example. */ #![allow(dead_code)] extern crate cvmath; use cvmath::prelude::*; mod svg; use self::svg::SvgWriter; const ARROW_SIZE: f32 = 8.0; //---------------------------------------------------------------- fn main() { write_svg("src/vec.rs:LEN_HAT", &len_hat()); write_svg("src/vec.rs:DIST_HAT", &dist_hat()); write_svg("src/vec.rs:LERP", &lerp()); write_svg("src/vec.rs:SLERP", &slerp()); write_svg("src/vec.rs:NLERP", &nlerp()); write_svg("src/vec.rs:SCALAR_PROJECT", &scalar_project()); write_svg("src/vec.rs:REFLECT_2D", &reflect_2d()); } fn write_svg(id: &str, svg: &str) { println!("{} {}", id, svg); let mut s = id.split(":"); // Split between file & tag // Read the file contents use std::io::{Read, Write}; use std::fs::File; let path = s.next().unwrap(); let contents = { let mut file = File::open(path).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); contents }; // Replace the svg let tag = s.next().unwrap(); let start = contents.find(&format!("<!--{}-->", tag)).unwrap(); let end = start + contents[start..].find("\n").unwrap(); let spliced = format!("{}<!--{}-->{}{}", &contents[..start], tag, svg, &contents[end..]); // Write the file contents back let mut file = File::create(path).unwrap(); file.write_all(spliced.as_ref()).unwrap(); } //---------------------------------------------------------------- // Drawing for len_hat fn len_hat() -> String { let this = Point2(360.5, 20.0); let origin = Point2(40.0, 100.0); let vhat = Point2(this.x, origin.y); let mut svg = SvgWriter::new(400, 120); svg.arrow(origin..this, ARROW_SIZE).stroke("black"); svg.arrow(origin..vhat, ARROW_SIZE).stroke("grey").stroke_width(0.5); svg.arrow(vhat..this, ARROW_SIZE).stroke("grey").stroke_width(0.5); svg.circle(origin, 2.0); svg.text(this + Point2(5.0, 0.0), "this"); svg.text((origin + vhat) * 0.5 + Point2(0.0, 15.0), "x").fill("grey"); svg.text((vhat + this) * 0.5 + Point2(5.0, 0.0), "y").fill("grey"); svg.close() } //---------------------------------------------------------------- // Drawing for dist_hat fn dist_hat() -> String { let this = Point2(40.0, 100.0); let to = Point2(360.5, 20.0); let vhat = Point2(to.x, this.y); let mut svg = SvgWriter::new(400, 120); svg.line(this..to).stroke("black"); svg.arrow(this..vhat, ARROW_SIZE).stroke("grey").stroke_width(0.5); svg.arrow(vhat..to, ARROW_SIZE).stroke("grey").stroke_width(0.5); svg.circle(this, 2.0); svg.circle(to, 2.0); svg.text(this + Point2(-20.0, -10.0), "this"); svg.text(to + Point2(5.0, 0.0), "to"); svg.text((this + vhat) * 0.5 + Point2(0.0, 15.0), "x").fill("grey"); svg.text((vhat + to) * 0.5 + Point2(5.0, 0.0), "y").fill("grey"); svg.close() } //---------------------------------------------------------------- // Drawing for lerp fn lerp() -> String { let v1 = Point2(40.0, 100.0); let v2 = Point2(360.0, 20.0); let tgreen = 0.2; let vgreen = v1.lerp(v2, tgreen); let tblue = 0.5; let vblue = v1.lerp(v2, tblue); let mut svg = SvgWriter::new(400, 120); svg.line(v1..vgreen).stroke("green"); svg.line(vgreen..vblue).stroke("blue"); svg.line(vblue..v2).stroke("black"); svg.circle(v1, 2.0).fill("black"); svg.circle(v2, 2.0).fill("black"); svg.circle(vgreen, 2.0).fill("green"); svg.circle(vblue, 2.0).fill("blue"); svg.text(v1 - Point2(20.0, 10.0), "self").fill("black"); svg.text(v2 - Point2(15.0, -20.0), "rhs").fill("black"); svg.text(vgreen - Point2(20.0, -20.0), "t = 0.2").fill("green"); svg.text(vblue - Point2(20.0, -20.0), "t = 0.5").fill("blue"); svg.close() } //---------------------------------------------------------------- // Drawing for slerp and nlerp fn slerp_nlerp<F: Fn(Point2<f32>, Point2<f32>, f32) -> Point2<f32>>(f: F, name: &str) -> String { let v1 = Point2(100.0, 70.0); let v2 = Point2(300.0, 70.0); // Calculate circle center given two points and a radius let radius = 120.0; let vhalf = (v1 + v2) * 0.5; let vdist = v1.dist(v2); let vbase = (v2 - v1).cw().resize((radius * radius - vdist * vdist * 0.25f32).sqrt()); let center = vhalf + vbase; // vhalf - vbase for the other solution // Calculate lerp let lerp = v1.lerp(v2, 0.75); // Calculate slerps let leg1 = v1 - center; let leg2 = v2 - center; let slerp = center + f(leg1, leg2, 0.75); let p1 = center + f(leg1, leg2, 0.25); let p2 = center + f(leg1, leg2, 0.5); let cstart = center + f(leg1, leg2, -0.1); let cend = center + f(leg1, leg2, 1.1); // Render time let mut svg = SvgWriter::new(400, 140); svg.arrow(center..v1, ARROW_SIZE).stroke("black").stroke_width(0.5); svg.arrow(center..v2, ARROW_SIZE).stroke("black").stroke_width(0.5); svg.arrow(center..p1, ARROW_SIZE).stroke("green").stroke_width(0.25); svg.arrow(center..p2, ARROW_SIZE).stroke("green").stroke_width(0.25); svg.arrow(center..slerp, ARROW_SIZE).stroke("green"); svg.arc(cstart, v1, radius).stroke("black").stroke_width(0.5); svg.arc(v1, slerp, radius).stroke("green"); svg.arc(slerp, v2, radius).stroke("black"); svg.arc(v2, cend, radius).stroke("black").stroke_width(0.5); svg.line(v1..lerp).stroke("blue").stroke_width(0.5); svg.circle(v1, 2.0).fill("black"); svg.circle(v2, 2.0).fill("black"); svg.circle(lerp, 2.0).fill("blue"); svg.circle(slerp, 2.0).fill("green"); svg.text(p1 - Point2(45.0, 5.0), "t = 0.25").fill("green").font_size(10.0); svg.text(p2 - Point2(20.0, 5.0), "t = 0.50").fill("green").font_size(10.0); svg.text(slerp - Point2(0.0, 5.0), "t = 0.75").fill("green").font_size(10.0); svg.text(lerp - Point2(20.0, -20.0), "lerp").fill("blue"); svg.text(slerp - Point2(60.0, -10.0), name).fill("green"); svg.text(v1 - Point2(50.0, 0.0), "self").fill("black"); svg.text(v2 - Point2(-10.0, 0.0), "rhs").fill("black"); svg.close() } fn slerp() -> String { slerp_nlerp(Point2::slerp, "slerp") } fn nlerp() -> String { slerp_nlerp(Point2::nlerp, "nlerp") } //---------------------------------------------------------------- // Drawing for scalar_project fn scalar_project() -> String { let v = Point2(360.0, 120.0); let this = Point2(200.0, 20.0); let origin = Point2(40.0, 160.0); let p = origin + (this - origin).project(v - origin); // Calculate the right angle symbol let ra = (v - origin).resize(20.0); let pra1 = p - ra; let pra2 = pra1 + ra.ccw(); let pra3 = pra2 + ra; // Calculate the scalar projection length let offset = (p - origin).resize(15.0).cw(); let sl1 = origin + offset; let sl2 = p + offset; let sll1 = sl1 - offset * 0.25; let sll2 = sl1 + offset * 0.25; let slr1 = sl2 - offset * 0.25; let slr2 = sl2 + offset * 0.25; // Render time let mut svg = SvgWriter::new(400, 200); svg.arrow(origin..this, ARROW_SIZE).stroke("black"); svg.arrow(origin..v, ARROW_SIZE).stroke("black"); svg.circle(origin, 2.0).fill("black"); svg.line(p..this).stroke("black").stroke_dasharray(&[5.0, 5.0]).stroke_width(0.5); svg.line(pra1..pra2).stroke("black").stroke_width(0.5); svg.line(pra2..pra3).stroke("black").stroke_width(0.5); svg.line(sl1..sl2).stroke("black").stroke_width(1.5); svg.line(sll1..sll2).stroke("black").stroke_width(1.5); svg.line(slr1..slr2).stroke("black").stroke_width(1.5); svg.text(this + Vec2(5.0, 5.0), "self").fill("black"); svg.text(v + Vec2(-20.0, 22.0), "v").fill("black"); svg.close() } //---------------------------------------------------------------- // Drawing for reflect fn reflect_2d() -> String { // Calculate data let v = Vec2 { x: 10.0, y: 2.5 }; let this = Vec2 { x: 4.0, y: 4.0 }; let p = this.project(v); let pv = p - this; let result = p + pv; let origin = Vec2::origin(); // Visualize data let transform = Affine2::translate((40.0f32, 120.0f32)) * Mat2::scale((25.0, -25.0)); let this = transform * this; let v = transform * v; let p = transform * p; let pv = transform * pv; let result = transform * result; let origin = transform * origin; let mut svg = SvgWriter::new(400, 200); svg.line(this..result).stroke("black").stroke_width(0.5).stroke_dasharray(&[5.0, 5.0]); svg.line(p..pv).stroke("black").stroke_width(0.5).stroke_dasharray(&[5.0, 5.0]); svg.line(pv..result).stroke("black").stroke_width(0.5).stroke_dasharray(&[5.0, 5.0]); svg.arrow(origin..v, ARROW_SIZE).stroke("black"); svg.arrow(origin..this, ARROW_SIZE).stroke("black"); svg.arrow(origin..result, ARROW_SIZE).stroke("red"); svg.circle(p, 2.0).fill("black"); svg.text(v, "v").fill("black"); svg.text(this, "self").fill("black"); svg.text(p + Vec2(8.0, 10.0), "p").fill("black"); svg.text(result, "result").fill("red"); svg.text(p.lerp(pv, 0.9) + Vec2(-15.0, -5.0), "-self").fill("black"); svg.text(pv.lerp(result, 0.8) + Vec2(0.0, 15.0), "+p").fill("black"); svg.close() }
true
abf9465acfa70d74d7ab3bb5842374d80ccd0b68
Rust
agapeteo/rust-data-algo
/src/linked_list/cons_list.rs
UTF-8
887
3.3125
3
[]
no_license
use std::fmt::{Display}; enum ConsList<T> { Empty, Elem(T, Box<ConsList<T>>), } impl<T: PartialEq + Display> ConsList<T> { fn new() -> Self { ConsList::Empty } fn print_elements(&self) { let mut cur_list = self; while let ConsList::Elem(elem, boxed_list) = cur_list { println!("elem: {}", elem); cur_list = boxed_list; } } } #[cfg(test)] mod test { use super::*; #[test] fn test() { let list_1: ConsList<i32> = ConsList::Elem(0, Box::new(ConsList::Elem(1, Box::new(ConsList::Elem(2, Box::new(ConsList::Empty)))))); list_1.print_elements(); } }
true
bf9ccd0e4271767740f91c35e6257d4a80be8213
Rust
JonnyWalker81/rusty_fit
/src/field_definition.rs
UTF-8
362
2.9375
3
[ "MIT" ]
permissive
#[derive(Copy, Clone, Debug)] pub struct FieldDefinition { pub field_number: u8, pub size: u8, pub base_type_number: u8 } impl FieldDefinition { pub fn new(field_num: u8, s: u8, btn: u8) -> FieldDefinition { FieldDefinition { field_number: field_num, size: s, base_type_number: btn } } }
true
05416a33b4095a585e8a0cd3cb993a9836cb8b9f
Rust
spacemeshos/svm
/crates/host/codec/src/section/sections/deploy.rs
UTF-8
1,209
2.640625
3
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
use svm_types::{Address, DeploySection, Layer, TemplateAddr, TransactionId}; use crate::{Codec, ParseError, ReadExt, WriteExt}; /// /// # `Deploy Section` /// /// +------------------+----------------+---------------+-------------+ /// | | | | | /// | Transaction Id | Layer | Deployer | Template | /// | (32 bytes) | (8 bytes) | (Address) | (Address) | /// | | | | | /// +------------------+----------------+---------------+-------------+ /// /// impl Codec for DeploySection { type Error = ParseError; fn encode(&self, w: &mut impl WriteExt) { self.tx_id().encode(w); (self.layer().0 as u64).encode(w); self.deployer().encode(w); self.template().encode(w); } fn decode(reader: &mut impl ReadExt) -> Result<Self, ParseError> { let tx_id = TransactionId::decode(reader)?; let layer = Layer(u64::decode(reader)?); let deployer = Address::decode(reader)?; let template = TemplateAddr::decode(reader)?; Ok(DeploySection::new(tx_id, layer, deployer, template)) } }
true
bd0fe6a81b9cb0e84d21ac6d2f59ffcb548f46ce
Rust
justinmayhew/lox
/src/scanner.rs
UTF-8
10,606
3.375
3
[]
no_license
use std::fmt; use std::iter::Peekable; use std::str::Chars; use Result; #[derive(Clone, Debug, PartialEq)] pub enum Token { LeftParen, RightParen, LeftBrace, RightBrace, Comma, Dot, Minus, Plus, Semicolon, Slash, Star, Bang, BangEqual, Equal, EqualEqual, Greater, GreaterEqual, Less, LessEqual, Identifier(String), String(String), Number(f64), And, Class, Else, False, Fun, For, If, Nil, Or, Print, Return, Super, This, True, Var, While, Eof, } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::LeftParen => write!(f, "("), Token::RightParen => write!(f, ")"), Token::LeftBrace => write!(f, "{{"), Token::RightBrace => write!(f, "}}"), Token::Comma => write!(f, ","), Token::Dot => write!(f, "."), Token::Minus => write!(f, "-"), Token::Plus => write!(f, "+"), Token::Semicolon => write!(f, ";"), Token::Slash => write!(f, "/"), Token::Star => write!(f, "*"), Token::Bang => write!(f, "!"), Token::BangEqual => write!(f, "!="), Token::Equal => write!(f, "="), Token::EqualEqual => write!(f, "=="), Token::Greater => write!(f, ">"), Token::GreaterEqual => write!(f, ">="), Token::Less => write!(f, "<"), Token::LessEqual => write!(f, "<="), Token::Identifier(ref s) | Token::String(ref s) => write!(f, "{}", s), Token::Number(n) => write!(f, "{}", n), Token::And => write!(f, "and"), Token::Class => write!(f, "class"), Token::Else => write!(f, "else"), Token::False => write!(f, "false"), Token::Fun => write!(f, "fun"), Token::For => write!(f, "for"), Token::If => write!(f, "if"), Token::Nil => write!(f, "nil"), Token::Or => write!(f, "or"), Token::Print => write!(f, "print"), Token::Return => write!(f, "return"), Token::Super => write!(f, "super"), Token::This => write!(f, "this"), Token::True => write!(f, "true"), Token::Var => write!(f, "var"), Token::While => write!(f, "while"), Token::Eof => write!(f, "EOF"), } } } #[derive(Clone, Debug, PartialEq)] pub struct Item { token: Token, line: usize, } impl Item { fn new(token: Token, line: usize) -> Self { Self { token, line } } pub fn token(&self) -> &Token { &self.token } pub fn line(&self) -> usize { self.line } pub fn location(&self) -> String { if self.token == Token::Eof { "end".into() } else { format!("'{}'", self.token) } } } pub struct Scanner<'s> { src: Peekable<Chars<'s>>, peek: Option<char>, line: usize, } impl<'s> Scanner<'s> { pub fn new(src: &'s str) -> Self { Self { src: src.chars().peekable(), peek: None, line: 1, } } pub fn scan(&mut self) -> (Vec<Item>, bool) { let mut items = Vec::new(); let mut had_error = false; loop { match self.next_item() { Ok(item) => { let stop = *item.token() == Token::Eof; items.push(item); if stop { break; } } Err(err) => { eprintln!("[line {}] Error: {}.", self.line, err.description()); had_error = true; } } } (items, had_error) } pub fn next_item(&mut self) -> Result<Item> { self.eat_whitespace(); let ch = match self.get() { Some(ch) => ch, None => return Ok(Item::new(Token::Eof, self.line)), }; let token = match ch { '(' => Token::LeftParen, ')' => Token::RightParen, '{' => Token::LeftBrace, '}' => Token::RightBrace, ',' => Token::Comma, '.' => Token::Dot, '-' => Token::Minus, '+' => Token::Plus, ';' => Token::Semicolon, '*' => Token::Star, '!' => if self.next_is('=') { Token::BangEqual } else { Token::Bang }, '=' => if self.next_is('=') { Token::EqualEqual } else { Token::Equal }, '<' => if self.next_is('=') { Token::LessEqual } else { Token::Less }, '>' => if self.next_is('=') { Token::GreaterEqual } else { Token::Greater }, '/' => if self.next_is('/') { self.eat_line(); return self.next_item(); } else { Token::Slash }, c => if c == '"' { Token::String(self.eat_string()?) } else if is_digit(c) { Token::Number(self.eat_number(c)?) } else if is_alpha_or_underscore(c) { self.eat_identifier_or_keyword(c) } else { return Err(From::from("Unexpected character")); }, }; Ok(Item::new(token, self.line)) } fn get(&mut self) -> Option<char> { self.peek.take().or_else(|| self.src.next()) } fn next_is(&mut self, expected: char) -> bool { if let Some(c) = self.get() { if c == expected { return true; } else { self.peek = Some(c); } } false } fn eat_line(&mut self) { while let Some(c) = self.get() { if c == '\n' { self.line += 1; break; } } } fn eat_whitespace(&mut self) { while let Some(c) = self.get() { if c == '\n' { self.line += 1; } else if !c.is_whitespace() { self.peek = Some(c); break; } } } fn eat_string(&mut self) -> Result<String> { let mut s = String::new(); while let Some(c) = self.get() { if c == '\n' { self.line += 1; } else if c == '"' { return Ok(s); } s.push(c); } Err(From::from("Unterminated string")) } fn eat_number(&mut self, first: char) -> Result<f64> { let mut s = first.to_string(); let mut saw_decimal = false; while let Some(c) = self.get() { if is_digit(c) { s.push(c); } else if !saw_decimal && c == '.' && self.src.peek().map(|c| is_digit(*c)).unwrap_or(false) { saw_decimal = true; s.push(c); } else { self.peek = Some(c); break; } } Ok(s.parse()?) } fn eat_identifier_or_keyword(&mut self, first: char) -> Token { let mut s = first.to_string(); while let Some(c) = self.get() { if is_alpha_numeric_or_underscore(c) { s.push(c); } else { self.peek = Some(c); break; } } match s.as_ref() { "and" => return Token::And, "class" => return Token::Class, "else" => return Token::Else, "false" => return Token::False, "for" => return Token::For, "fun" => return Token::Fun, "if" => return Token::If, "nil" => return Token::Nil, "or" => return Token::Or, "print" => return Token::Print, "return" => return Token::Return, "super" => return Token::Super, "this" => return Token::This, "true" => return Token::True, "var" => return Token::Var, "while" => return Token::While, _ => {} } Token::Identifier(s) } } fn is_digit(c: char) -> bool { c >= '0' && c <= '9' } fn is_alpha_or_underscore(c: char) -> bool { c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') } fn is_alpha_numeric_or_underscore(c: char) -> bool { is_alpha_or_underscore(c) || is_digit(c) } #[cfg(test)] mod tests { use super::*; macro_rules! next { ($scanner:expr, $expect:expr) => ( assert_eq!(*$scanner.next_item().unwrap().token(), $expect); ) } #[test] fn print() { let mut scanner = Scanner::new(r#"print "hello, world""#); next!(scanner, Token::Print); next!(scanner, Token::String("hello, world".into())); next!(scanner, Token::Eof); } #[test] fn string() { let mut scanner = Scanner::new(r#""a string""#); next!(scanner, Token::String("a string".into())); next!(scanner, Token::Eof); } #[test] fn number() { let mut scanner = Scanner::new("123"); next!(scanner, Token::Number(123.0)); next!(scanner, Token::Eof); } #[test] fn identifier() { let mut scanner = Scanner::new("foo"); next!(scanner, Token::Identifier("foo".into())); next!(scanner, Token::Eof); } #[test] fn conditional() { let mut scanner = Scanner::new("if (even) { total / 2; } else { total; }"); next!(scanner, Token::If); next!(scanner, Token::LeftParen); next!(scanner, Token::Identifier("even".into())); next!(scanner, Token::RightParen); next!(scanner, Token::LeftBrace); next!(scanner, Token::Identifier("total".into())); next!(scanner, Token::Slash); next!(scanner, Token::Number(2.0)); next!(scanner, Token::Semicolon); next!(scanner, Token::RightBrace); next!(scanner, Token::Else); next!(scanner, Token::LeftBrace); next!(scanner, Token::Identifier("total".into())); next!(scanner, Token::Semicolon); next!(scanner, Token::RightBrace); next!(scanner, Token::Eof); } }
true
014d702fc925fa3447bd1c5fe3671976fbdc5b8d
Rust
rodrimati1992/type_level
/type_level_values/src/const_wrapper/tests.rs
UTF-8
3,220
2.78125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
use self::type_level_Dim2d::fields; use super::*; use crate_::field_traits::{GetFieldMt, MapFieldMt}; use crate_::fn_adaptors::*; use crate_::std_ops::*; use core_extensions::type_level_bool::False; #[derive(Debug, Clone, TypeLevel, PartialEq)] #[typelevel( // skip_derive, // print_derive, reexport(Struct), )] struct Dim2d { width: u32, height: u32, } type Wrapper0 = Construct<Dim2dType, ((fields::width, U3), (fields::height, U5))>; #[test] fn whole_ops() { let v: ConstWrapper<()> = ().to_cw(); let _: () = v.identity_(()); let v: ConstWrapper<&'static str> = v.set::<&'static str>(); let _: &'static str = v.identity_("hello"); let v: ConstWrapper<True> = v.set_val(True); let _: True = v.identity_(True); } #[test] fn get_field() { let v0 = Wrapper0::CW; assert_eq!(v0[fields::width].get_as(u32::T), 3); assert_eq!(v0[fields::height].get_as(u32::T), 5); let _: U3 = v0.field(fields::width); let _: U5 = v0.field(fields::height); } #[test] fn set_field() { { let v0 = Wrapper0::CW .set_field_val(fields::width, U0::MTVAL) .set_field_val(fields::height, U1::MTVAL); let _: ConstDim2d<U0, U1> = *v0; assert_eq!( v0.get_runt(), Dim2d { width: 0, height: 1 } ); } { let v0 = Wrapper0::CW .set_field::<fields::width, U10>() .set_field::<fields::height, U20>(); let _: ConstDim2d<U10, U20> = *v0; assert_eq!( v0.get_runt(), Dim2d { width: 10, height: 20 } ); } } #[test] fn map_field() { let v0 = Wrapper0::CW; let v0 = v0 .map_field(fields::width, <AddMt<U3>>::CW) .map_field_fn(fields::height, |v| v * U2::MTVAL); assert_eq!(v0[fields::width].get_as(u32::T), 6); assert_eq!(v0[fields::height].get_as(u32::T), 10); let _: U6 = *v0.width; let _: U10 = *v0.height; } #[test] fn map_all_to() { let v0 = Wrapper0::CW; { let v0 = v0.map_to(fields::width, <GetFieldMt<fields::height>>::CW); assert_eq!(v0.width.get_as(u32::T), 5); assert_eq!(v0.height.get_as(u32::T), 5); let _: U5 = *v0.width; let _: U5 = *v0.height; } { let v0: ConstWrapper<_> = v0.map_to_fn(fields::height, |v| v.width.get()); assert_eq!(v0.width.get_as(u32::T), 3); assert_eq!(v0.height.get_as(u32::T), 3); let _: U3 = *v0.width; let _: U3 = *v0.height; } } #[test] fn map_all() { let v0 = Wrapper0::CW; { let v0 = v0.map(MapFieldMt::<fields::height, AddMt<U3>>::CW); assert_eq!(v0.width.get_as(u32::T), 3); assert_eq!(v0.height.get_as(u32::T), 8); let _: U3 = *v0.width; let _: U8 = *v0.height; } { let v0 = v0.map_fn(|v| { v.to_cw() .set_field_val(fields::height, *v.height + U3::MTVAL) }); assert_eq!(v0.width.get_as(u32::T), 3); assert_eq!(v0.height.get_as(u32::T), 8); let _: U3 = *v0.width; let _: U8 = *v0.height; } }
true
19ab80d22da583ae71c55d95e3d4f754518e4b17
Rust
jelipo/rust-8080
/src/cpu/register.rs
UTF-8
2,381
3.28125
3
[]
no_license
/// The register of Intel 8080 pub struct Register { pub a: u8, pub b: u8, pub c: u8, pub d: u8, pub e: u8, pub h: u8, pub l: u8, // 程序计数器, the address of next opcode pub pc: u16, // 栈指针 pub sp: u16, // FLAGS /// Z (zero) set to 1 when the result is equal to zero pub flag_z: bool, /// S (sign) set to 1 when bit 7 (the most significant bit or MSB) of the math instruction is set pub flag_s: bool, /// 答案具有偶数奇偶校验时设置P(奇偶校验),奇数奇偶校验时清除 pub flag_p: bool, /// 当指令导致进位或借位到高位时,CY(进位)设置为1 pub flag_cy: bool, /// AC (auxillary carry) is used mostly for BCD (binary coded decimal) math. /// Read the data book for more details, Space Invaders doesn't use it. pub flag_ac: bool, } impl Register { pub fn get_af(&self) -> u16 { (self.a as u16) << 8 | (self.get_flags() as u16) } pub fn get_bc(&self) -> u16 { (self.b as u16) << 8 | (self.c as u16) } pub fn get_de(&self) -> u16 { (self.d as u16) << 8 | (self.e as u16) } pub fn get_hl(&self) -> u16 { (self.h as u16) << 8 | (self.l as u16) } // Also known as 'B' in Intel Doc pub fn set_bc(&mut self, value: u16) { self.b = (value >> 8) as u8; self.c = value as u8; } // Also known as 'D' in Intel Doc pub fn set_de(&mut self, value: u16) { self.d = (value >> 8) as u8; self.e = value as u8; } // Also known as 'H' in Intel Doc pub fn set_hl(&mut self, value: u16) { self.h = (value >> 8) as u8; self.l = value as u8; } pub fn get_flags(&self) -> u8 { // S:7 Z:6 A:4 P:2 C:0 let mut bits = 0b0000_0010; if self.flag_z { bits |= 0b0100_0000 } if self.flag_s { bits |= 0b1000_0000 } if self.flag_p { bits |= 0b0000_0100 } if self.flag_cy { bits |= 0b0000_0001 } if self.flag_ac { bits |= 0b0001_0000 } bits } pub fn set_flags(&mut self, flags: u8) { // S:7 Z:6 A:4 P:2 C:0 self.flag_z = flags & 0b0100_0000 != 0; self.flag_s = flags & 0b1000_0000 != 0; self.flag_p = flags & 0b0000_0100 != 0; self.flag_cy = flags & 0b0000_0001 != 0; self.flag_ac = flags & 0b0001_0000 != 0; } }
true
47dd07233ced85ca0f66c8b952bef50aa8a8acf6
Rust
whitf/simbld
/director/src/heimdallr/mod.rs
UTF-8
333
2.953125
3
[]
no_license
use std::thread; use std::time::Duration; pub struct Heimdallr { online: bool, } impl Heimdallr { pub fn new() -> Self { Heimdallr { online: false, } } pub fn run(&mut self) { self.online = true; println!(" Heimdallr module started."); while self.online { thread::sleep(Duration::from_secs(7)); } } }
true
3056d08c659709bfed5580d949637d216a7e7ec1
Rust
max-sixty/expect-test
/src/lib.rs
UTF-8
4,291
3.265625
3
[]
no_license
#![allow(unused_imports)] use std::env; use std::fmt; use std::io; use std::io::Write; use std::str; use std::error::Error; use std::fs; use std::fs::File; use std::io::prelude::*; #[macro_use] extern crate pretty_assertions; extern crate difference; use difference::{Changeset, Difference}; pub struct Expect { pub file_name: String, buf: String, } // #[derive(Debug)] pub struct ExpectErr { #[allow(dead_code)] changeset: Changeset, } pub enum Mode { Test, Reset, } impl Error for ExpectErr { fn description(&self) -> &str { "Something bad happened" } } impl fmt::Debug for ExpectErr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Oh no, something bad went down") } } impl fmt::Display for ExpectErr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Oh no, something bad went down") } } fn read_mode() -> Mode { let args: Vec<String> = env::args().collect(); if args.iter().any(|v| v == "--expect_reset") { Mode::Reset } else { Mode::Test } } impl Expect { pub fn new(file_name: String) -> Expect { let buf = String::new(); Expect { file_name, buf } } pub fn push(&mut self, s: &str) { self.buf.push_str(s); } fn file_path(&self) -> std::path::PathBuf { env::current_dir() .unwrap() .join("expect") .join(&self.file_name) } fn expectation(&self) -> String { fs::read_to_string(self.file_path()).unwrap_or("".to_string()) } // pub fn correct(&self) -> () { // let expectation = self.expectation().unwrap(); // let result = self.buf.clone(); // assert_eq!(expectation, result) // } pub fn correct(&self) -> std::result::Result<(), ExpectErr> { let expectation = self.expectation(); let result = self.buf.clone(); let changeset = Changeset::new(&expectation, &result, "\"\""); match changeset.distance { 0 => Ok(()), _ => Err(ExpectErr { changeset }), } } pub fn finish(&self) -> Result<(), Box<Error>> { match read_mode() { // Mode::Test => self.correct().map_err(|e| e.into()), Mode::Test => match self.correct() { Ok(()) => Ok(()), Err(changeset) => { assert!(false, changeset); Err(changeset).map_err(|e| e.into()) } }, Mode::Reset => self.write_to_file().map_err(|e| e.into()), } } pub fn write_to_file(&self) -> Result<(), io::Error> { let result = self.buf.clone(); fs::write(self.file_path(), result) } } // I don't think you're allowed to panic within a Drop, so this doesn't work // impl Drop for Expect { // fn drop(&mut self) { // match self.correct() { // Ok(()) => {} // Err(_e) => panic!("whoops"), //println!("whoops!"), // Err(e)), // } // } // } #[cfg(test)] mod tests { use super::*; #[test] fn create_expect() { let _s = Expect::new("test1".to_string()); // let _s = Expect::new(&"test1"); } #[test] fn write_to_expect_incorrect() { let mut s = Expect::new("test1".to_string()); s.push("x"); assert!(s.correct().is_err()); } #[test] fn write_to_expect_multiple_correct() { let mut s = Expect::new("test1".to_string()); s.push("he"); s.push("llo"); assert!(s.correct().is_ok()); } #[test] fn write_to_expect_correct() { let mut s = Expect::new("test1".to_string()); s.push("hello"); assert!(s.correct().is_ok()); } #[test] fn write_to_file() { let mut s = Expect::new("test2".to_string()); fs::remove_file(s.file_path()).ok(); s.push("hello"); s.write_to_file().unwrap(); let contents = fs::read_to_string(s.file_path()).unwrap(); assert!(contents == "hello") } } #[cfg(test)] mod trials { use super::*; #[test] fn testing() { let mut s = Expect::new("testing".to_string()); s.push("Hi Hi Hello"); s.finish().ok(); } }
true
e8872827eb1ab042b2bc2ffcafbe5a7ce527e26f
Rust
JolloDede/Rustchat
/tcpClient/src/main.rs
UTF-8
3,253
2.96875
3
[]
no_license
extern crate iui; use iui::prelude::*; use iui::controls::*; use std::io::{self, ErrorKind, Read, Write}; use std::net::TcpStream; use std::sync::mpsc::{self, TryRecvError}; use std::thread; use std::time::Duration; use std::str; const LOCAL: &str = "127.0.0.1:10000"; const MSG_SIZE: usize = 32; fn main() { gui(); two(); } fn gui(){ let ui = UI::init().expect("cant create UI"); let mut win = Window::new(&ui, "Rustchat", 400, 400, WindowType::NoMenubar); let mut vbox = VerticalBox::new(&ui); let mut footer = HorizontalBox::new(&ui); let mut text_vbox = VerticalBox::new(&ui); text_vbox.set_padded(&ui, true); let text_msg = Label::new(&ui, "Message"); let text_msgs = Label::new(&ui, "Message2"); let message = Entry::new(&ui); let mut btn_send = Button::new(&ui, "Send"); btn_send.on_clicked(&ui, { let text = message.value(&ui); println!("Send {}", text); move |_| { println!("Send {}", text); } }); let btn_emoji = Button::new(&ui, "Emoji"); text_vbox.append(&ui, text_msg, LayoutStrategy::Compact); text_vbox.append(&ui, text_msgs, LayoutStrategy::Compact); footer.append(&ui, btn_emoji, LayoutStrategy::Compact); footer.append(&ui, message, LayoutStrategy::Stretchy); footer.append(&ui, btn_send, LayoutStrategy::Compact); vbox.append(&ui, text_vbox, LayoutStrategy::Stretchy); vbox.append(&ui, footer, LayoutStrategy::Compact); win.set_child(&ui, vbox); win.show(&ui); ui.main(); } // fn send(){ // println!("Send") // } fn two (){ let mut client = TcpStream::connect(LOCAL).expect("Stream failed to connect"); client.set_nonblocking(true).expect("failed to initiate non-blocking"); let (tx, rx) = mpsc::channel::<String>(); thread::spawn(move || loop { let mut buff = vec![0; MSG_SIZE]; match client.read_exact(&mut buff) { Ok(_) => { let msg = buff.into_iter().take_while(|&x| x != 0).collect::<Vec<_>>(); // println!("message recv {:?}", msg); Print the buffer let res = String::from_utf8(msg).expect("Found invalid UTF-8"); println!("messag recv {}", res); }, Err(ref err) if err.kind() == ErrorKind::WouldBlock => (), Err(_) => { println!("connection with server was severed"); break; } } match rx.try_recv() { Ok(msg) => { let mut buff = msg.clone().into_bytes(); buff.resize(MSG_SIZE, 0); client.write_all(&buff).expect("writing to socket failed"); println!("message sent {:?}", msg); }, Err(TryRecvError::Empty) => (), Err(TryRecvError::Disconnected) => break } thread::sleep(Duration::from_millis(100)); }); println!("Write a Message:"); loop { let mut buff = String::new(); io::stdin().read_line(&mut buff).expect("reading from stdin failed"); let msg = buff.trim().to_string(); if msg == ":quit" || tx.send(msg).is_err() {break} } println!("bye bye!"); }
true
4f09053bf335732c3381835423be95fe40eea555
Rust
Juzley/adventofcode2019
/day10/src/main.rs
UTF-8
11,515
3.140625
3
[]
no_license
use num_integer; use std::collections::HashSet; use std::f64; use std::fs::File; use std::io::{BufRead, BufReader}; const ASTEROID_CHAR: char = '#'; const TARGET_VAPORIZE_COUNT: usize = 200; #[derive(Clone, Debug)] struct Map { // Set of asteroid coordinates. asteroids: HashSet<(i32, i32)>, } impl Map { fn from_strings(input: &[String]) -> Map { let mut asteroids = HashSet::new(); for y in 0..input.len() { input[y] .chars() .enumerate() .filter_map(|(x, c)| match c { ASTEROID_CHAR => Some(x), _ => None, }) .for_each(|x| { asteroids.insert((x as i32, y as i32)); }); } return Map { asteroids: asteroids, }; } fn from_file(filename: &str) -> Map { let file = File::open(filename).expect("Failed to open file"); let reader = BufReader::new(file); let result: Result<Vec<String>, _> = reader.lines().collect(); let input = result.expect("Failed to read lines"); return Map::from_strings(&input); } fn find_visible_asteroids(&self, src: (i32, i32)) -> Vec<(i32, i32)> { // Brute-force: loop through all asteroids and determine if // we can see this asteroid by checking for other asteroids // that block it. let mut asteroids = Vec::new(); for tgt in &self.asteroids { if src == *tgt { continue; } let (tx, ty) = *tgt; // Find the step size along the line from the source to // the target asteroid that will land exactly on map // coordinates that we can use to check for asteroids. let gcd = num_integer::gcd(tx - src.0, ty - src.1); let step = ((tx - src.0) / gcd, (ty - src.1) / gcd); // Check for blocking asteroids along the line from // source to target. let mut blocked = false; let mut cur_location = (src.0 + step.0, src.1 + step.1); while cur_location != (tx, ty) { if self.asteroids.contains(&cur_location) { blocked = true; break; } cur_location = (cur_location.0 + step.0, cur_location.1 + step.1); } if !blocked { asteroids.push(*tgt); } } return asteroids; } fn vaporize_asteroids(&mut self, asteroids: &[(i32, i32)]) { for location in asteroids { self.asteroids.remove(location); } } } // Find the location on a map that can see the most asteroids. // Return that location, plus the number of asteroids that can be // seen from it. fn find_optimal_monitoring_location(map: &Map) -> ((i32, i32), u32) { let mut max_asteroids = 0; let mut best_space = (0, 0); for src in &map.asteroids { let asteroids = map.find_visible_asteroids(*src); if asteroids.len() > max_asteroids { max_asteroids = asteroids.len(); best_space = *src; } } return (best_space, max_asteroids as u32); } fn find_bearing(src: (i32, i32), dst: (i32, i32)) -> f64 { let theta = ((dst.0 - src.0) as f64).atan2((src.1 - dst.1) as f64); if theta < 0.0 { return theta + f64::consts::PI * 2.0; } return theta; } fn find_nth_vaporized(m: &Map, laser_loc: (i32, i32), n: usize) -> (i32, i32) { let mut vaporized = 0; let mut map = m.clone(); assert!(n > 0); let n = n - 1; loop { let mut asteroids = map.find_visible_asteroids(laser_loc); if asteroids.is_empty() { panic!("No visible asteroids!"); } if asteroids.len() + vaporized <= n { // We vaporize all these asteroids without reaching the count map.vaporize_asteroids(&asteroids); vaporized += asteroids.len(); } else { // We only get part way through these asteroids, sort by the // order the laser will hit each one. asteroids.sort_by(|a, b| { find_bearing(laser_loc, *a) .partial_cmp(&find_bearing(laser_loc, *b)) .unwrap() }); return asteroids[n - vaporized]; } } } fn main() { // Part 1 let map = Map::from_file("input"); let (coords, count) = find_optimal_monitoring_location(&map); println!("Best location {:?} sees {} asteroids", coords, count); // Part 2 let result = find_nth_vaporized(&map, coords, TARGET_VAPORIZE_COUNT); println!( "Vaporized asteroid number {}: {:?}. Answer {}", TARGET_VAPORIZE_COUNT, result, result.0 * 100 + result.1 ); } #[cfg(test)] mod tests { use super::*; #[test] fn bearing_test() { let diff = (find_bearing((0, 1), (0, 0)) - 0.0).abs(); assert!(diff < 1e-10); let diff = (find_bearing((0, 0), (1, 0)) - std::f64::consts::FRAC_PI_2).abs(); assert!(diff < 1e-10); let diff = (find_bearing((0, 0), (0, 1)) - std::f64::consts::PI).abs(); assert!(diff < 1e-10); let diff = (find_bearing((1, 0), (0, 0)) - std::f64::consts::FRAC_PI_2 * 3.0).abs(); assert!(diff < 1e-10); } #[test] fn pt1_example_1() { let strs = vec![ String::from(".#..#"), String::from("....."), String::from("#####"), String::from("....#"), String::from("...##"), ]; let map = Map::from_strings(&strs); let (coords, count) = find_optimal_monitoring_location(&map); assert_eq!(coords, (3, 4)); assert_eq!(count, 8); } #[test] fn pt1_example_2() { let strs = vec![ String::from("......#.#."), String::from("#..#.#...."), String::from("..#######."), String::from(".#.#.###.."), String::from(".#..#....."), String::from("..#....#.#"), String::from("#..#....#."), String::from(".##.#..###"), String::from("##...#..#."), String::from(".#....####"), ]; let map = Map::from_strings(&strs); let (coords, count) = find_optimal_monitoring_location(&map); assert_eq!(coords, (5, 8)); assert_eq!(count, 33); } #[test] fn pt1_example_3() { let strs = vec![ String::from("#.#...#.#."), String::from(".###....#."), String::from(".#....#..."), String::from("##.#.#.#.#"), String::from("....#.#.#."), String::from(".##..###.#"), String::from("..#...##.."), String::from("..##....##"), String::from("......#..."), String::from(".####.###."), ]; let map = Map::from_strings(&strs); let (coords, count) = find_optimal_monitoring_location(&map); assert_eq!(coords, (1, 2)); assert_eq!(count, 35); } #[test] fn pt1_example_4() { let strs = vec![ String::from(".#..#..###"), String::from("####.###.#"), String::from("....###.#."), String::from("..###.##.#"), String::from("##.##.#.#."), String::from("....###..#"), String::from("..#.#..#.#"), String::from("#..#.#.###"), String::from(".##...##.#"), String::from(".....#.#.."), ]; let map = Map::from_strings(&strs); let (coords, count) = find_optimal_monitoring_location(&map); assert_eq!(coords, (6, 3)); assert_eq!(count, 41); } #[test] fn pt1_example_5() { let strs = vec![ String::from(".#..##.###...#######"), String::from("##.############..##."), String::from(".#.######.########.#"), String::from(".###.#######.####.#."), String::from("#####.##.#.##.###.##"), String::from("..#####..#.#########"), String::from("####################"), String::from("#.####....###.#.#.##"), String::from("##.#################"), String::from("#####.##.###..####.."), String::from("..######..##.#######"), String::from("####.##.####...##..#"), String::from(".#####..#.######.###"), String::from("##...#.##########..."), String::from("#.##########.#######"), String::from(".####.#.###.###.#.##"), String::from("....##.##.###..#####"), String::from(".#.#.###########.###"), String::from("#.#.#.#####.####.###"), String::from("###.##.####.##.#..##"), ]; let map = Map::from_strings(&strs); let (coords, count) = find_optimal_monitoring_location(&map); assert_eq!(coords, (11, 13)); assert_eq!(count, 210); } #[test] fn pt2_example_1() { let strs = vec![ String::from(".#....#####...#.."), String::from("##...##.#####..##"), String::from("##...#...#.#####."), String::from("..#.....X...###.."), String::from("..#.#.....#....##"), ]; let map = Map::from_strings(&strs); println!("{}", map.asteroids.len()); let station_coords = (8, 3); let tests = vec![(9, (15, 1)), (18, (4, 4)), (27, (5, 1)), (36, (14, 3))]; for (n, exp_coords) in tests { let coords = find_nth_vaporized(&map, station_coords, n); assert_eq!(coords, exp_coords); } } #[test] fn pt2_example_2() { let strs = vec![ String::from(".#..##.###...#######"), String::from("##.############..##."), String::from(".#.######.########.#"), String::from(".###.#######.####.#."), String::from("#####.##.#.##.###.##"), String::from("..#####..#.#########"), String::from("####################"), String::from("#.####....###.#.#.##"), String::from("##.#################"), String::from("#####.##.###..####.."), String::from("..######..##.#######"), String::from("####.##.####...##..#"), String::from(".#####..#.######.###"), String::from("##...#.##########..."), String::from("#.##########.#######"), String::from(".####.#.###.###.#.##"), String::from("....##.##.###..#####"), String::from(".#.#.###########.###"), String::from("#.#.#.#####.####.###"), String::from("###.##.####.##.#..##"), ]; let map = Map::from_strings(&strs); let (station_coords, count) = find_optimal_monitoring_location(&map); let tests = vec![ (1, (11, 12)), (2, (12, 1)), (3, (12, 2)), (10, (12, 8)), (20, (16, 0)), (50, (16, 9)), (100, (10, 16)), (199, (9, 6)), (200, (8, 2)), (201, (10, 9)), (299, (11, 1)), ]; for (n, exp_coords) in tests { let coords = find_nth_vaporized(&map, station_coords, n); assert_eq!(coords, exp_coords); } } }
true
1605c28f7f104907f42217809f6c329c75f3e650
Rust
JonathanWoollett-Light/actix-auth
/src/main.rs
UTF-8
2,055
2.625
3
[]
no_license
mod config; mod database; mod handlers; mod models; use crate::handlers::*; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_web::{web, App, HttpServer}; use dotenv::dotenv; use mongodb::Client; use std::{env, io::Result}; // The names of the database and collection we want to use. const DB: &str = "auth"; const COLLECTION: &str = "users"; // Run with: "cargo run <username> <password>" #[actix_web::main] async fn main() -> Result<()> { println!("Started."); // Gets command line arguments let args: Vec<String> = env::args().collect(); // Connects to MongoDB database // (right now setup for connecting to atlass cluster) let uri_str = format!( "mongodb+srv://{}:{}@cluster0.wwsrh.mongodb.net/local?retryWrites=true&w=majority", args[1], args[2] ); let client = Client::with_uri_str(&uri_str) .await .expect("Could not connect to database"); println!("Connected to databse."); // Loads config file dotenv().ok(); let config = crate::config::Config::from_env().unwrap(); let move_config = config.clone(); // This is probably a bad way of doing this println!("Running..."); // Starts server HttpServer::new(move || { App::new() // Adds database connection client to server data .data(client.clone()) // Adds auth service .wrap(IdentityService::new( CookieIdentityPolicy::new(&move_config.auth.salt.as_bytes()).secure(false), // Restrict to https? )) // Routes .route("/", web::get().to(status)) .route("/user{_:/?}", web::get().to(get_user)) .route("/user/register{_:/?}", web::post().to(register)) .route("/user/login{_:/?}", web::get().to(get_login)) .route("/user/login{_:/?}", web::post().to(login)) .route("/user/logout{_:/?}", web::post().to(logout)) }) .bind(format!("{}:{}", config.server.host, config.server.port))? .run() .await }
true
42fbda1ac383ae912b5b45837d9a70ab34512914
Rust
siku2/AoC2018
/src/puzzles/day24.rs
UTF-8
7,808
3.109375
3
[ "MIT" ]
permissive
use std::collections::HashMap; use std::collections::HashSet; use std::io::BufRead; use regex::Regex; use utils; type SideType = String; type AttackType = String; type Weakness = String; type Immunity = String; #[derive(Clone, Debug, PartialEq)] struct Group { id: usize, side: SideType, units: u32, hp: u32, attack_damage: u32, attack_type: AttackType, initiative: u32, weaknesses: HashSet<Weakness>, immunities: HashSet<Immunity>, } impl Group { fn parse(text: &str, id: usize, side: SideType) -> Option<Group> { lazy_static! { static ref REGEX:Regex = Regex::new(r#"(?P<units>\d+) units each with (?P<hp>\d+) hit points(?: \((?P<traits>.+)\))? with an attack that does (?P<attack_damage>\d+) (?P<attack_type>\w+) damage at initiative (?P<initiative>\d+)"#) .unwrap(); }; // let REGEX: Regex = Regex::new(r#""#).unwrap(); let captures = REGEX.captures(text)?; let units: u32 = captures.name("units").unwrap().as_str().parse().unwrap(); let hp: u32 = captures.name("hp").unwrap().as_str().parse().unwrap(); let attack_damage: u32 = captures.name("attack_damage").unwrap().as_str().parse().unwrap(); let initiative: u32 = captures.name("initiative").unwrap().as_str().parse().unwrap(); let attack_type: AttackType = captures.name("attack_type").unwrap().as_str().to_string(); let mut weaknesses = HashSet::new(); let mut immunities = HashSet::new(); if let Some(traits) = captures.name("traits").and_then(|m| Some(m.as_str())) { traits.split("; ") .for_each(|part| { if let [trait_type, attack_types] = part.split(" to ").collect::<Vec<&str>>()[..] { let attack_types = attack_types.split(", ") .map(|s| s.to_string()) .collect::<Vec<String>>(); match trait_type { "weak" => &mut weaknesses, "immune" => &mut immunities, _ => panic!("nope, won't deal with that shit lol") }.extend(attack_types); } }) } Some(Group { id, side, units, hp, attack_damage, initiative, attack_type, weaknesses, immunities }) } fn effective_power(&self) -> u32 { self.units * self.attack_damage } fn alive(&self) -> bool { return self.units > 0; } fn pick_target<'a, T: Iterator<Item=&'a Group>>(&self, enemies: &mut T) -> Option<&'a Group> { let target = enemies .max_by(|a, b| (self.damage_against(a), a.effective_power(), a.initiative) .cmp(&(self.damage_against(b), b.effective_power(), b.initiative)) )?; if self.damage_against(target) > 0 { Some(target) } else { None } } fn damage_against(&self, other: &Group) -> u32 { if other.immunities.contains(&self.attack_type) { 0 } else if other.weaknesses.contains(&self.attack_type) { 2 * self.effective_power() } else { self.effective_power() } } fn take_damage(&mut self, amount: u32) { let deaths = amount / self.hp; if deaths >= self.units { self.units = 0; } else { self.units -= deaths; } } fn take_damage_from(&mut self, other: &Group) { let dmg = other.damage_against(&self); self.take_damage(dmg); } } fn get_groups<T: BufRead>(input: T) -> HashMap<usize, Group> { let lines = utils::get_lines(input); let mut units = HashMap::new(); let mut target = "immune"; let mut id = 0; for line in lines { if line == "Immune System:" { target = "immune"; } else if line == "Infection:" { target = "infection"; } else if line == "" { continue; } else { units.insert(id, Group::parse(line.as_str(), id, target.to_string()) .expect("couldn't get group data")); id += 1; } } units } fn battle(units_map: &mut HashMap<usize, Group>) -> bool { loop { let mut unit_ids: Vec<usize> = units_map.keys().map(|id| id.clone()).collect(); unit_ids.sort_unstable_by(|a, b| (units_map[a].effective_power(), units_map[a].initiative) .cmp(&(units_map[b].effective_power(), units_map[b].initiative))); let mut chosen = HashSet::new(); let mut target_map = HashMap::new(); for unit_id in unit_ids.iter().rev() { let unit = units_map.get(unit_id).unwrap(); let target = unit.pick_target(&mut unit_ids.iter() .filter_map(|id| { let u = units_map.get(id).unwrap(); if u.alive() && u.side != unit.side && !chosen.contains(id) { Some(u) } else { None } })); if let Some(target) = target { target_map.insert(unit.id, target.id); chosen.insert(target.id); } } unit_ids.sort_unstable_by(|a, b| units_map[a].initiative.cmp(&units_map[b].initiative)); let mut any_killed = false; for unit_id in unit_ids.iter().rev() { let unit = units_map.get(unit_id).unwrap().clone(); if !unit.alive() { continue; } if let Some(target_id) = target_map.get(unit_id) { let target = units_map.get_mut(target_id).unwrap(); let pre_units = target.units; target.take_damage_from(&unit); if pre_units != target.units { any_killed = true; } } } let mut alive_count = HashMap::new(); let mut to_remove = HashSet::new(); for unit_id in unit_ids.iter() { let unit = units_map.get(unit_id).unwrap(); if unit.alive() { let side = unit.side.clone(); let count = alive_count.get(&side).unwrap_or(&0) + 1; alive_count.insert(side, count); } else { to_remove.insert(unit_id.clone()); } } for id in to_remove { units_map.remove(&id); } if !any_killed { return false; } if alive_count.len() < 2 { break; } } true } pub fn solve_first<T: BufRead>(input: T) -> u32 { let mut units_map = get_groups(input); battle(&mut units_map); units_map.values().map(|g| g.units).sum::<u32>() } pub fn solve_second<T: BufRead>(input: T) -> u32 { let original_units_map = get_groups(input); let mut i = 0; loop { let mut units_map = original_units_map.clone(); for (_, unit) in units_map.iter_mut() { if unit.side == "immune" { unit.attack_damage += i; } } if battle(&mut units_map) { let remaining = units_map.iter().next().unwrap().1; if remaining.side == "immune" { return units_map.values().map(|u| u.units).sum(); } } i += 1; } } pub fn solve<T: BufRead>(problem: u8, input: T) -> Result<String, String> { match problem { 1 => Result::Ok(solve_first(input).to_string()), 2 => Result::Ok(solve_second(input).to_string()), _ => Result::Err("This problem only has 2 parts!".to_string()) } }
true
c655485e2d0bb0a009a903f9156f84d97206a69d
Rust
Janonard/lv2rs
/core/src/lib.rs
UTF-8
3,925
2.640625
3
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-mit-taylor-variant", "ISC" ]
permissive
//! This crate contains the complete contents of the //! [LV2 core library](http://lv2plug.in/ns/lv2core/lv2core.html) with additional constructions //! to make the use of LV2 as idiomatic and safe as possible. //! //! This is a frozen prototype and therefore, development of this crate will not continue here. Further //! development continues as [rust-lv2](https://github.com/rust-dsp/rust-lv2). mod feature; mod plugin; pub mod ports; pub mod uris; pub use feature::{Feature, FeaturesList}; pub use plugin::*; /// Create lv2 export functions. /// /// This macro takes a struct that implements [`Plugin`](trait.Plugin.html) and creates the required /// functions a plugin needs to export in order to be found and used by plugin hosts. /// /// In order to properly work, it needs three arguments: /// * The namespace of the `lv2rs-core` crate: You may use this crate via re-exports and /// therefore, the name of the namespace is needed in order to call the appropiate functions. /// * The struct type that should be used as the Plugin implementation. /// * The URI of the plugin. Please note that the URI needs to be a bytes-array and null-terminated, /// since the C world has to interact with it. /// /// extern crate lv2rs_core as lv2core; /// use std::ffi::CStr; /// use lv2core::ports::*; /// /// struct MyPlugin {} /// /// impl lv2core::Plugin for MyPlugin { /// fn instantiate( /// _descriptor: &lv2core::Descriptor, /// _rate: f64, /// _bundle_path: &CStr, /// _features: Option<&lv2core::FeaturesList> /// ) -> Option<Self> { /// Some(Self {}) /// } /// /// fn connect_port(&mut self, _port: u32, _data: *mut ()) {} /// /// fn run(&mut self, _n_samples: u32) {} /// } /// /// lv2core::lv2_main!(lv2core, MyPlugin, b"http://example.org/Dummy\0"); /// #[macro_export] macro_rules! lv2_main { ($c:ident, $s:ty, $u:expr) => { const PLUGIN_URI: &'static [u8] = $u; const PLUGIN_DESCRIPTOR: $c::Descriptor = $c::Descriptor { uri: PLUGIN_URI.as_ptr() as *const std::os::raw::c_char, instantiate: instantiate, connect_port: connect_port, activate: activate, run: run, deactivate: deactivate, cleanup: cleanup, extension_data: extension_data, }; unsafe extern "C" fn instantiate( descriptor: *const $c::Descriptor, rate: f64, bundle_path: *const std::os::raw::c_char, features: *const *const $c::Feature, ) -> $c::Handle { $c::instantiate::<$s>(descriptor, rate, bundle_path, features) } unsafe extern "C" fn connect_port( instance: $c::Handle, port: u32, data: *mut std::os::raw::c_void, ) { $c::connect_port::<$s>(instance, port, data); } unsafe extern "C" fn activate(instance: $c::Handle) { $c::activate::<$s>(instance); } unsafe extern "C" fn run(instance: $c::Handle, n_samples: u32) { $c::run::<$s>(instance, n_samples); } unsafe extern "C" fn deactivate(instance: $c::Handle) { $c::deactivate::<$s>(instance); } unsafe extern "C" fn cleanup(instance: $c::Handle) { $c::cleanup::<$s>(instance); } unsafe extern "C" fn extension_data( uri: *const std::os::raw::c_char, ) -> *const std::os::raw::c_void { $c::extension_data::<$s>(uri) } #[no_mangle] pub unsafe extern "C" fn lv2_descriptor(index: u32) -> *const $c::Descriptor { if index == 0 { &PLUGIN_DESCRIPTOR } else { std::ptr::null() } } }; }
true
e467f590ff1f81857d9a1920b1f0cccb8aecb68d
Rust
chutslar/rust-avec-sdl
/src/controller/mod.rs
UTF-8
5,735
2.8125
3
[ "MIT" ]
permissive
#![allow(dead_code)] pub extern crate sdl2; use self::sdl2::GameControllerSubsystem; use controller::sdl2::controller::{Axis, Button, GameController}; pub struct Controllers { pool: Vec<GameController>, } impl Controllers { pub fn new(controller_subsystem: &GameControllerSubsystem) -> Self { let available = match controller_subsystem.num_joysticks() { Ok(n) => n, Err(_e) => 0, }; let mut result = Controllers { pool: Vec::new() }; for id in 0..available { if controller_subsystem.is_game_controller(id) { match controller_subsystem.open(id) { Ok(c) => { result.pool.push(c); } Err(_e) => (), } } } result } pub fn any(&self) -> bool { self.pool.len() > 0 } pub fn exists(&self, number: usize) -> bool { number < self.pool.len() } pub fn num(&self) -> usize { return self.pool.len(); } pub fn name(&self, number: usize) -> Option<String> { if number < self.pool.len() { return Some(self.pool[number].name()); } None } pub fn mapping(&self, number: usize) -> Option<String> { if number < self.pool.len() { return Some(self.pool[number].mapping()); } None } pub fn attached(&self, number: usize) -> Option<bool> { if number < self.pool.len() { return Some(self.pool[number].attached()); } None } pub fn instance_id(&self, number: usize) -> Option<i32> { if number < self.pool.len() { return Some(self.pool[number].instance_id()); } None } pub fn axis(&self, number: usize, axis: Axis) -> Option<i16> { if number < self.pool.len() { return Some(self.pool[number].axis(axis)); } None } pub fn button(&self, number: usize, button: Button) -> Option<bool> { if number < self.pool.len() { return Some(self.pool[number].button(button)); } None } pub fn button_down(&self, number: usize, button: Button, state: &ControllerState) -> Option<bool> { match self.button(number, button) { Some(down) => { match state.button(number, button) { Some(was_down) => Some(down && !was_down), None => None, } } None => None, } } pub fn button_up(&self, number: usize, button: Button, state: &ControllerState) -> Option<bool> { match self.button(number, button) { Some(down) => { match state.button(number, button) { Some(was_down) => Some(!down && was_down), None => None, } } None => None, } } } #[derive(Clone)] struct ButtonState(u16); impl ButtonState { fn new() -> Self { ButtonState(0) } fn activate(&mut self, button: Button) { self.0 = self.0 | ((1 as u16) << button as i32); } fn deactivate(&mut self, button: Button) { self.0 = self.0 & !((1 as u16) << button as i32); } fn button(&self, button: Button) -> bool { self.0 & ((1 as u16) << button as i32) > 0 } } pub struct ControllerState { buttons: Vec<ButtonState>, } impl ControllerState { pub fn new(controllers: &Controllers) -> Self { let mut result = ControllerState { buttons: Vec::new()}; result.buttons.resize(controllers.num(), ButtonState::new()); result } pub fn button(&self, number: usize, button: Button) -> Option<bool> { if number < self.buttons.len() { return Some(self.buttons[number].button(button)); } None } pub fn update(&mut self, controllers: &Controllers) { for i in 0..controllers.num() { let mut tally : u16 = 0; if controllers.button(i, Button::A).unwrap() { tally += 1; } if controllers.button(i, Button::B).unwrap() { tally += 2; } if controllers.button(i, Button::X).unwrap() { tally += 4; } if controllers.button(i, Button::Y).unwrap() { tally += 8; } if controllers.button(i, Button::Back).unwrap() { tally += 16; } if controllers.button(i, Button::Guide).unwrap() { tally += 32; } if controllers.button(i, Button::Start).unwrap() { tally += 64; } if controllers.button(i, Button::LeftStick).unwrap() { tally += 128; } if controllers.button(i, Button::RightStick).unwrap() { tally += 256; } if controllers.button(i, Button::LeftShoulder).unwrap() { tally += 512; } if controllers.button(i, Button::RightShoulder).unwrap() { tally += 1024; } if controllers.button(i, Button::DPadUp).unwrap() { tally += 2048; } if controllers.button(i, Button::DPadDown).unwrap() { tally += 4096; } if controllers.button(i, Button::DPadLeft).unwrap() { tally += 8192; } if controllers.button(i, Button::DPadRight).unwrap() { tally += 16384; } self.buttons[i].0 = tally; } } }
true
9616824a56bd7fa8c6be116aab2ad32e6db42d11
Rust
or17191/texlab
/src/hover/bibtex_entry_type.rs
UTF-8
3,310
2.9375
3
[ "MIT" ]
permissive
use crate::syntax::*; use crate::workspace::*; use futures_boxed::boxed; use lsp_types::*; #[derive(Debug, PartialEq, Eq, Clone)] pub struct BibtexEntryTypeHoverProvider; impl FeatureProvider for BibtexEntryTypeHoverProvider { type Params = TextDocumentPositionParams; type Output = Option<Hover>; #[boxed] async fn execute<'a>( &'a self, request: &'a FeatureRequest<TextDocumentPositionParams>, ) -> Option<Hover> { if let SyntaxTree::Bibtex(tree) = &request.document().tree { for entry in tree.entries() { if entry.ty.range().contains(request.params.position) { let ty = &entry.ty.text()[1..]; if let Some(documentation) = LANGUAGE_DATA.entry_type_documentation(ty) { return Some(Hover { contents: HoverContents::Markup(MarkupContent { kind: MarkupKind::Markdown, value: documentation.into(), }), range: None, }); } } } } None } } #[cfg(test)] mod tests { use super::*; use lsp_types::Position; #[test] fn test_known_entry_type() { let hover = test_feature( BibtexEntryTypeHoverProvider, FeatureSpec { files: vec![FeatureSpec::file("foo.bib", "@article{foo,}")], main_file: "foo.bib", position: Position::new(0, 3), ..FeatureSpec::default() }, ); assert_eq!( hover, Some(Hover { contents: HoverContents::Markup(MarkupContent { kind: MarkupKind::Markdown, value: LANGUAGE_DATA .entry_type_documentation("article") .unwrap() .into(), }), range: None, }) ); } #[test] fn test_unknown_entry_type() { let hover = test_feature( BibtexEntryTypeHoverProvider, FeatureSpec { files: vec![FeatureSpec::file("foo.bib", "@foo{bar,}")], main_file: "foo.bib", position: Position::new(0, 3), ..FeatureSpec::default() }, ); assert_eq!(hover, None); } #[test] fn test_entry_key() { let hover = test_feature( BibtexEntryTypeHoverProvider, FeatureSpec { files: vec![FeatureSpec::file("foo.bib", "@article{foo,}")], main_file: "foo.bib", position: Position::new(0, 11), ..FeatureSpec::default() }, ); assert_eq!(hover, None); } #[test] fn test_latex() { let hover = test_feature( BibtexEntryTypeHoverProvider, FeatureSpec { files: vec![FeatureSpec::file("foo.tex", "\\foo")], main_file: "foo.tex", position: Position::new(0, 3), ..FeatureSpec::default() }, ); assert_eq!(hover, None); } }
true
98a6a0894defc97236980a11fe3caf3b9e0edda6
Rust
Malique-Auguste/Nariva
/compiler/src/parser/operator.rs
UTF-8
1,214
3.75
4
[]
no_license
use crate::lexer::token::TokenType; use std::convert::TryFrom; #[derive(Debug, PartialEq)] pub enum Operator { Plus, Dash, Star, Slash, Bang, Equal, Greater, Lesser, EqualEqual, BangEqual, GreaterEqual, LesserEqual, } impl TryFrom<TokenType> for Operator { type Error = String; fn try_from(o: TokenType) -> Result<Operator, String> { match o { TokenType::Dash => Ok(Operator::Dash), TokenType::Plus => Ok(Operator::Plus), TokenType::Star => Ok(Operator::Star), TokenType::Slash => Ok(Operator::Slash), TokenType::Bang => Ok(Operator::Bang), TokenType::Equal => Ok(Operator::Equal), TokenType::Greater => Ok(Operator::Greater), TokenType::Lesser => Ok(Operator::Lesser), TokenType::EqualEqual => Ok(Operator::EqualEqual), TokenType::LesserEqual => Ok(Operator::LesserEqual), TokenType::GreaterEqual => Ok(Operator::GreaterEqual), TokenType::BangEqual => Ok(Operator::BangEqual), _ => Err(format!("{:?}, is not an operator", o)) } } }
true
9a552fbe1164aa54c8f76c08fb3678028be85a16
Rust
cyberbono3/intro-to-Rust
/happy_animal.rs
UTF-8
370
3.296875
3
[]
no_license
//creates happy animal (generic func) with two restrictions trait Animal and default constructor //we come up with instance inside the function fn happy_animal<A: Animal + Default>() -> A { let mut animal = A::default(); let food = make_food(); animal.eat(food); animal //return animal } fn main() { let walrus = happy_animal::<Walrus>(); }
true
6a60dcce2b9d5d2554a83d33683c6c0f191ee0c0
Rust
Sousa99/Apre-2021
/em-bayesian/src/lib.rs
UTF-8
8,445
2.859375
3
[ "MIT" ]
permissive
use nalgebra::{DMatrix}; use itertools::izip; use std::collections::HashMap; pub type Element = f64; pub type Matrix = DMatrix<Element>; // ======================== AUXILIARY TYPES ======================== type PosteriorsReturn = HashMap<(usize, usize), Element>; #[derive(Clone)] pub struct EMBayesianParameter { prior: f64, likelihoods: Vec<Element>, } pub struct EMBayesian { step: i32, dimension: usize, x: Vec<Matrix>, parameters: Vec<EMBayesianParameter>, } impl EMBayesian { pub fn do_iteration(&mut self) { self.step = self.step + 1; println!("==================================== STEP {} ====================================", self.step); let posteriors = self.do_e_step(); self.compute_data_probability(false); let new_params = self.do_m_step(posteriors); self.parameters = new_params; } pub fn compute_final_data_probability(&self) { println!("==================================== FINAL DATA PROBABILITY COMPUTATION ===================================="); self.compute_data_probability(true); } fn do_e_step(&mut self) -> PosteriorsReturn { println!("E Step:"); let mut posteriors : PosteriorsReturn = PosteriorsReturn::new(); for (point_index, point) in self.x.iter().enumerate() { println!(); println!("\t- For x({}):", point_index + 1); let mut joint_probabilities : Vec<Element> = Vec::new(); let mut sum_joint_probabilities : Element = 0.0; for (cluster_index, parameter) in self.parameters.iter().enumerate() { println!("\t\t- For Cluster = {}:", cluster_index + 1); // Do Calculations let prior = parameter.prior; let likelihood = compute_likelihood(point.clone(), parameter.likelihoods.clone()); let joint_probability = compute_joint_probability(prior, likelihood); // Print Results println!("\t\t\t- Prior: p(C = {}) = {}:", cluster_index + 1, prior); println!("\t\t\t- Likelihood: p(x^({}) | C = {}) = {}:", point_index + 1, cluster_index + 1, likelihood); println!("\t\t\t- Joint Probability: p(C = {}, x^({})) = {}:", cluster_index + 1, point_index + 1, joint_probability); // Update stored values joint_probabilities.push(joint_probability); sum_joint_probabilities = sum_joint_probabilities + joint_probability; } println!(); println!("\t\t- Updating normalized posteriors:"); for (cluster_index, joint_probability) in joint_probabilities.iter().enumerate() { // Do Calculations let normalized_posterior : Element = joint_probability / sum_joint_probabilities; posteriors.insert((cluster_index + 1, point_index + 1), normalized_posterior); // Print Results println!("\t\t\t- C = {}: p(C = {} | x^({}))= {}:", cluster_index + 1, cluster_index + 1, point_index + 1, normalized_posterior); } } return posteriors; } fn do_m_step(&mut self, posteriors: PosteriorsReturn ) -> Vec<EMBayesianParameter> { println!("M Step:"); let mut new_params : Vec<EMBayesianParameter> = Vec::new(); let sum_posteriors_all : Element = sum_of_all_posteriors(&posteriors); for cluster_index in 0..self.parameters.len() { println!(); println!("\t- For C = {}:", cluster_index + 1); // ====== Compute Sum of Posteriors ====== let mut sum_posteriors_cluster : Element = 0.0; for point_index in 0..self.x.len() { let posterior : Element = *posteriors.get(&(cluster_index + 1, point_index + 1)).unwrap(); sum_posteriors_cluster = sum_posteriors_cluster + posterior; } // ====== Compute New Likelihoods ====== let mut likelihoods : Vec<Element> = Vec::new(); for dimension in 0..self.dimension { let mut likelihood : Element = 0.0; for point_index in 0..self.x.len() { let posterior : Element = *posteriors.get(&(cluster_index + 1, point_index + 1)).unwrap(); let dimension_value : Element = self.x[point_index][dimension]; if dimension_value == 1.0 { likelihood = likelihood + posterior } } likelihoods.push(likelihood / sum_posteriors_cluster); } // ====== Compute New Prior ====== let new_prior : Element = sum_posteriors_cluster / sum_posteriors_all; // ====== Print new Parameters ====== println!(); for (dimension, likelihood) in likelihoods.iter().enumerate() { println!("\t\tp( x_{} = 1 | C = {} ) = {}", dimension + 1, cluster_index + 1, likelihood); } println!(); println!("\t\tPrior: p(C = {}) = {}", cluster_index + 1, new_prior); // Create and save back new Params let new_param : EMBayesianParameter = EMBayesianParameter { prior: new_prior, likelihoods: likelihoods, }; new_params.push(new_param); } return new_params; } fn compute_data_probability(&self, print: bool) { let mut probability : Element = 1.0; for (point_index, point) in self.x.iter().enumerate() { if print { println!(); println!("- For x({}):", point_index + 1); } let mut sum_joint_probabilities : Element = 0.0; for (cluster_index, parameter) in self.parameters.iter().enumerate() { if print { println!("\t- For Cluster = {}:", cluster_index + 1) } // Do Calculations let prior = parameter.prior; let likelihood = compute_likelihood(point.clone(), parameter.likelihoods.clone()); let joint_probability = compute_joint_probability(prior, likelihood); // Print Results if print { println!("\t\t- Prior: p(C = {}) = {}:", cluster_index + 1, prior); println!("\t\t- Likelihood: p(x^({}) | C = {}) = {}:", point_index + 1, cluster_index + 1, likelihood); println!("\t\t- Joint Probability: p(C = {}, x^({})) = {}:", cluster_index + 1, point_index + 1, joint_probability); } // Update stored values sum_joint_probabilities = sum_joint_probabilities + joint_probability; } probability = probability * sum_joint_probabilities; } println!(); println!("Data Probability = {}", probability); println!(); } } pub fn build_em_bayesian(dimension: usize, x: Vec<Matrix>, priors: Vec<f64>, likelihoods: Vec<Vec<Element>>) -> EMBayesian { let mut parameters : Vec<EMBayesianParameter> = Vec::new(); for (prior, sub_likelihoods) in izip!(priors, likelihoods) { let new_parameter : EMBayesianParameter = EMBayesianParameter { prior: prior, likelihoods: sub_likelihoods, }; parameters.push(new_parameter); } let new_em : EMBayesian = EMBayesian { step: 0, dimension: dimension, x: x, parameters: parameters, }; return new_em; } // ============================= UTIL FUNCTIONS ============================= fn compute_likelihood(x: Matrix, likelihoods: Vec<Element>) -> Element { let mut result: Element = 1.0; for (&point_value, &likelihood) in x.iter().zip(likelihoods.iter()) { if point_value == 1.0 { result = result * likelihood } else { result = result * ( 1.0 - likelihood ) } } return result; } fn compute_joint_probability(prior: Element, likelihood: Element) -> Element { return prior * likelihood; } fn sum_of_all_posteriors(posteriors: &PosteriorsReturn) -> Element { let mut sum : Element = 0.0; for (_, element) in posteriors { sum = sum + *element; } return sum; }
true
c16242b4a819a8b6491b1d35dfe1f6ccfa35bed9
Rust
christopherjreid/advent-of-code-2020-rust
/src/days_of_advent/day02/mod.rs
UTF-8
4,018
2.953125
3
[]
no_license
pub mod parsers; pub mod policies; use crate::days_of_advent::common::io; use crate::days_of_advent::day02::parsers::regex_range_password_policy_parser::RegexRangePasswordPolicyParser; use crate::days_of_advent::day02::parsers::regex_index_password_policy_parser::RegexIndexPasswordPolicyParser; use crate::days_of_advent::day02::parsers::range_password_policy_parser::RangePasswordPolicyParser; use crate::days_of_advent::day02::parsers::index_password_policy_parser::IndexPasswordPolicyParser; use crate::days_of_advent::day02::policies::range_password_policy::RangePasswordPolicy; use crate::days_of_advent::day02::policies::index_password_policy::IndexPasswordPolicy; use crate::days_of_advent::day02::policies::validates_password::ValidatesPassword; pub fn run() -> () { let puzzle_input = io::load_input_from_file("day02"); if puzzle_input.is_err() { panic!("Could not load entries from file"); } let puzzle_input = puzzle_input.unwrap(); let regex_range_parser = RegexRangePasswordPolicyParser::new(); let regex_index_parser = RegexIndexPasswordPolicyParser::new(); let range_policies: Vec<(String, RangePasswordPolicy)> = puzzle_input .lines() .map(|line| regex_range_parser.parse(line)) .collect(); let index_policies: Vec<(String, IndexPasswordPolicy)> = puzzle_input .lines() .map(|line| regex_index_parser.parse(line)) .collect(); let num_valid_range_passwords = count_valid_passwords(&range_policies).unwrap(); let num_valid_index_passwords = count_valid_passwords(&index_policies).unwrap(); let results = String::from(format!( "The given password file has {} passwords that match the range policy\n\ The given password file has {} passwords that match the index policy", num_valid_range_passwords, num_valid_index_passwords )); let report = io::format_day_report(2, "Password Philosophy", "Count the passwords that match the policies", &results); println!("{}", &report); } fn count_valid_passwords( passwords_with_policies: &[(String, impl ValidatesPassword)], ) -> Result<u32, &str> { let mut valid_passwords: u32 = 0; for entry in passwords_with_policies { if entry.1.is_password_valid(&entry.0.to_string()) { valid_passwords += 1; } } Ok(valid_passwords) } #[cfg(test)] mod tests { #[test] fn provided_acceptance_test() { use super::RangePasswordPolicyParser; let input = "1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc"; let solution = 2; let parser = super::RegexRangePasswordPolicyParser::new(); let policies: Vec<(String, super::RangePasswordPolicy)> = input.lines().map(|line| parser.parse(line)).collect(); let num_valid_passwords = super::count_valid_passwords(&policies).unwrap(); assert_eq!(num_valid_passwords, solution); } #[test] fn check_password_1() { use super::ValidatesPassword; let policy = super::RangePasswordPolicy { range: std::ops::RangeInclusive::new(1, 3), character: 'a', }; let password = "abcde"; let result = policy.is_password_valid(&password); assert_eq!(result, true); } #[test] fn check_password_2() { use super::ValidatesPassword; let policy = super::RangePasswordPolicy { range: std::ops::RangeInclusive::new(1, 3), character: 'b', }; let password = "cdefg"; let result = policy.is_password_valid(&password); assert_eq!(result, false); } #[test] fn check_password_3() { use super::ValidatesPassword; let policy = super::RangePasswordPolicy { range: std::ops::RangeInclusive::new(2, 9), character: 'c', }; let password = "ccccccccc"; let result = policy.is_password_valid(&password); assert_eq!(result, true); } }
true
dd7cdfbfd7f81faa1843903a2322de785d79a09c
Rust
JM4ier/oxidized
/src/commands/play/runner.rs
UTF-8
8,105
3
3
[]
no_license
use super::*; pub struct GameRunner<T: 'static, G: PvpGame<T>> { game: G, game_name: &'static str, description: &'static str, mode: GameMode, players: Vec<Player<T, G>>, timeout: f64, turn: usize, board: Message, last_turn: Instant, guild_id: u64, moves: Vec<T>, } #[derive(Copy, Clone, PartialEq, Eq)] enum GameMode { Casual, Competitive, } impl GameMode { fn as_str(&self) -> &'static str { match self { Self::Casual => "casual", Self::Competitive => "competitive", } } } enum Player<T, G: PvpGame<T>> { Person(UserId), Ai(Box<dyn AiPlayer<T, G> + Send + Sync>), } impl<T, G: PvpGame<T>> Player<T, G> { async fn id(&self, ctx: &Context) -> UserId { match self { Self::Person(id) => *id, Self::Ai(_) => ctx.cache.current_user().await.id, } } } impl<T, G: PvpGame<T>> PartialEq for Player<T, G> { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Person(me), Self::Person(other)) => me == other, _ => false, } } } impl<T, G: PvpGame<T>> Player<T, G> { fn is_ai(&self) -> bool { match self { Self::Ai(_) => true, _ => false, } } } fn get_description(game: &'static str) -> &'static str { let cmds = commands(); let cmd = cmds .iter() .filter(|c| c.options.names.contains(&game)) .next() .expect("this function was called with the name of a command that doesn't exist."); cmd.options.desc.unwrap_or("\u{200b}") } impl<Input: 'static + Clone, G: PvpGame<Input> + Send + Sync> GameRunner<Input, G> { pub async fn new<'a>( ctx: &'a Context, prompt: &'a Message, game: G, game_name: &'static str, timeout: f64, ) -> CommandResult<Self> { create_tables(game_name)?; let guild_id = *prompt.guild_id.ok_or("no server id")?.as_u64(); let challenger = prompt.author.id; let challenged = match prompt.mentions.iter().next() { Some(c) => c, None => { prompt .err_reply(ctx, "You need to tag another person to play against!") .await?; unreachable!(); } }; let mut mode = GameMode::Casual; let me = ctx.cache.current_user().await.id; let challenged = if challenged.id == me { // this is a bot game if let Some(ai) = G::ai() { Player::Ai(ai) } else { prompt .err_reply(ctx, "This game doesn't support AI players.") .await?; unreachable!(); } } else { // against a person // can only play competitively against other people if challenger != challenged.id { mode = GameMode::Competitive; } let dialog_txt = format!( "{}, you have been invited by {} to play a {} game of {}. To start the game, confirm this with a reaction within ten seconds.", challenged.mention(), challenger.mention(), mode.as_str(), G::title() ); if confirm_dialog(ctx, prompt, "Game Invite", &dialog_txt, &challenged).await? { Player::Person(challenged.id) } else { Err("no confirmation")? } }; let board = prompt .ereply(ctx, |e| e.title(G::title()).description("Loading game...")) .await?; G::input().prepare(ctx, &board).await?; let players = vec![Player::Person(challenger), challenged]; Ok(Self { game, game_name, description: get_description(game_name), mode, players, timeout, turn: 0, board, last_turn: Instant::now(), moves: Vec::new(), guild_id, }) } /// when a move takes to long fn forfeit(&self) -> bool { self.time_left() == 0.0 } /// how much time is left for the current move fn time_left(&self) -> f64 { (self.timeout - self.last_turn.elapsed().as_secs_f64()).max(0.0) } /// returns a Mention of the player with the index async fn mention_player(&self, ctx: &Context, idx: usize) -> Mention { self.players[idx].id(ctx).await.mention() } /// updates the game field async fn draw(&mut self, ctx: &Context) -> CommandResult { let mentions = vec![ self.mention_player(ctx, 0).await, self.mention_player(ctx, 1).await, ]; let countdown = "<a:_:808040888235589772> <a:_:808040929515667526>"; let status = match self.game.status() { _ if self.forfeit() => format!( "{} won by inactivity of {}.", mentions[1 - self.turn], mentions[self.turn], ), GameState::Win(p) => format!("{} won!", mentions[p]), GameState::Tie => String::from("It's a tie!"), _ => format!( "{}({}) plays next.\nTime left: {} seconds. (updated every once in a while)", mentions[self.turn].mention(), G::figures()[self.turn], self.time_left() as u64 ), }; let board = self.game.draw(); let desc = self.description; self.board .eedit(ctx, |e| { e.title(G::title()); e.description(desc); e.field("Board", board, false); e.field("Status", status, false) }) .await?; Ok(()) } /// runs the game pub async fn run(&mut self, ctx: &Context) -> CommandResult { 'game: loop { self.last_turn = Instant::now(); let play = loop { self.draw(ctx).await?; if self.forfeit() { break 'game; } let timeout = Duration::from_secs_f64(self.time_left().min(10.0)); let play = match &mut self.players[self.turn] { Player::Person(id) => tryc!(G::input() .receive_input(ctx, &self.board, id, timeout) .await .ok()), Player::Ai(ai) => ai.make_move(&self.game, self.turn), }; let state = self.game.make_move(play.clone(), self.turn); if state != GameState::Invalid { self.moves.push(play); break state; } if self.players[self.turn].is_ai() { // AI is the one that made the invalid move let err_msg = format!( "The AI for this game sucks and tries to do invalid moves, {} pls fix.", DISCORD_AUTHOR ); self.board.err_reply(ctx, &err_msg).await?; } }; if play.is_finished() { break; } else { self.turn = 1 - self.turn; } } self.draw(ctx).await?; if self.mode == GameMode::Competitive { let winner = match self.game.status() { GameState::Win(p) => Some(p), _ if self.forfeit() => Some(1 - self.turn), _ => None, }; let mut players = Vec::new(); for p in self.players.iter() { players.push(*p.id(ctx).await.as_u64()); } // TODO // log_game(self.game_name, server, &players, &self.moves, winner)?; elo::process_game(self.game_name, self.guild_id, &players, winner)?; } Ok(()) } }
true
5c3438e932561077a969b34131d7ea0aab89667a
Rust
tormol/udplite
/examples/hello_udplite.rs
UTF-8
817
2.609375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
extern crate udplite; use udplite::UdpLiteSocket; fn main() { let any = UdpLiteSocket::bind("0.0.0.0:0").expect("create UDP-Lite socket"); println!("addr of randomly bound socket {:?}: {:?}", any, any.local_addr()); println!( "default checksum coverage: send={:?}, recv filter={:?}", any.send_checksum_coverage(), any.recv_checksum_coverage_filter(), ); any.set_send_checksum_coverage(Some(0)).expect("set send cscov to the minimum"); any.set_recv_checksum_coverage_filter(Some(0)).expect("disable recv cscov filter"); any.send_to(b"Hello, UDP-Lite", any.local_addr().unwrap()).expect("send datagram"); let mut buf = [0; 20]; let len = any.recv(&mut buf).expect("receive datagram"); println!("received {}", String::from_utf8_lossy(&buf[..len])); }
true
3cd8d4ce0626f3e4804136173938b6df91c5dc0a
Rust
neuroradiology/unlisp-llvm
/runtime/src/defs.rs
UTF-8
11,698
2.78125
3
[ "MIT" ]
permissive
use libc::c_char; use libc::c_void; use libc::strcmp; use std::ffi::CStr; use std::ffi::VaList; use std::fmt; use std::ptr; use crate::{exceptions, symbols, predefined}; // TODO: revise usage of Copy here #[derive(Clone, Copy)] #[repr(C)] pub union UntaggedObject { int: i64, list: *mut List, sym: *mut Symbol, function: *mut Function, string: *const c_char, } #[derive(Clone, Eq, PartialEq)] #[repr(C)] pub enum ObjType { Int64 = 1, List = 2, Symbol = 3, Function = 4, String = 5, } impl fmt::Display for ObjType { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let name = match self { ObjType::Int64 => "int", ObjType::List => "list", ObjType::Function => "function", ObjType::Symbol => "symbol", ObjType::String => "string", }; write!(f, "{}", name) } } #[repr(C)] #[derive(Clone)] pub struct Object { pub ty: ObjType, pub obj: UntaggedObject, } impl PartialEq for Object { fn eq(&self, rhs: &Self) -> bool { if self.ty != rhs.ty { return false; } unsafe { match self.ty { ObjType::Int64 => self.obj.int == rhs.obj.int, ObjType::List => *self.obj.list == *rhs.obj.list, ObjType::Function => self.obj.function == rhs.obj.function, ObjType::Symbol => self.obj.sym == rhs.obj.sym, ObjType::String => strcmp(self.obj.string, rhs.obj.string) == 0, } } } } impl Object { fn type_err(&self, target_ty: ObjType) -> ! { unsafe { exceptions::raise_cast_error(format!("{}", self.ty), format!("{}", target_ty)) }; } pub fn unpack_int(&self) -> i64 { if self.ty == ObjType::Int64 { unsafe { self.obj.int } } else { self.type_err(ObjType::Int64); } } pub fn unpack_list(&self) -> *mut List { if self.ty == ObjType::List { unsafe { self.obj.list } } else { self.type_err(ObjType::List); } } pub fn unpack_symbol(&self) -> *mut Symbol { if self.ty == ObjType::Symbol { unsafe { self.obj.sym } } else { self.type_err(ObjType::Symbol); } } pub fn unpack_function(&self) -> *mut Function { if self.ty == ObjType::Function { unsafe { self.obj.function } } else { self.type_err(ObjType::Function); } } pub fn unpack_string(&self) -> *const c_char { if self.ty == ObjType::String { unsafe { self.obj.string } } else { self.type_err(ObjType::String); } } pub fn from_int(i: i64) -> Object { Self { ty: ObjType::Int64, obj: UntaggedObject { int: i }, } } pub fn from_list(list: *mut List) -> Object { Self { ty: ObjType::List, obj: UntaggedObject { list: list }, } } pub fn from_symbol(sym: *mut Symbol) -> Object { Self { ty: ObjType::Symbol, obj: UntaggedObject { sym: sym }, } } pub fn from_function(function: *mut Function) -> Object { Self { ty: ObjType::Function, obj: UntaggedObject { function: function }, } } pub fn from_string(string: *const c_char) -> Object { Self { ty: ObjType::String, obj: UntaggedObject { string: string }, } } pub fn nil() -> Object { let list = List::empty(); Object::from_list(Box::into_raw(Box::new(list))) } } unsafe fn display_list(mut list: *const List, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { if (*list).len == 0 { write!(f, "nil")?; } else { write!(f, "(")?; let mut is_first = true; while (*list).len != 0 { let val = &(*(*(*list).node).val); if is_first { write!(f, "{}", val)?; is_first = false; } else { write!(f, " {}", val)?; } list = (*(*list).node).next; } write!(f, ")")?; } Ok(()) } impl fmt::Display for Object { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { unsafe { match self.ty { ObjType::Int64 => write!(f, "{}", self.obj.int), ObjType::List => display_list(self.obj.list, f), ObjType::Function => write!( f, "#<FUNCTION{}/{}>", if (*self.obj.function).is_macro { "+MACRO" } else { "" }, (*self.obj.function).arg_count ), ObjType::Symbol => write!( f, "{}", CStr::from_ptr((*self.obj.sym).name).to_str().unwrap() ), ObjType::String => write!( f, "\"{}\"", CStr::from_ptr(self.obj.string).to_str().unwrap() ), } } } } #[repr(C)] pub struct Node { pub val: *mut Object, pub next: *mut List, } #[repr(C)] #[derive(Clone)] pub struct List { pub node: *mut Node, pub len: u64, } impl PartialEq for List { fn eq(&self, rhs: &Self) -> bool { if self.len != rhs.len { return false; } if self.len == 0 { return true; } unsafe { *((*self.node).val) == *((*rhs.node).val) && *((*self.node).next) == *((*rhs.node).next) } } } impl List { pub fn empty() -> List { List { node: ptr::null_mut(), len: 0, } } pub unsafe fn first(&self) -> Object { (*(*self.node).val).clone() } pub unsafe fn rest(&self) -> List { (*self.rest_ptr()).clone() } pub unsafe fn rest_ptr(&self) -> *mut List { (*self.node).next } pub fn cons(&self, obj: Object) -> List { List { len: self.len + 1, node: Box::into_raw(Box::new(Node { val: Box::into_raw(Box::new(obj)), next: Box::into_raw(Box::new(self.clone())), })), } } } #[repr(C)] pub struct Symbol { pub name: *const c_char, pub function: *mut Function, } impl Symbol { pub fn new(name: *const c_char) -> Self { Self { name: name, function: ptr::null_mut(), } } } #[repr(C)] #[allow(dead_code)] pub enum FunctionType { Function = 0, Closure = 1, } #[repr(C)] pub struct Function { pub ty: FunctionType, pub name: *const c_char, pub arglist: *const *const c_char, pub arg_count: u64, pub is_macro: bool, pub invoke_f_ptr: *const c_void, pub apply_to_f_ptr: *const c_void, pub has_restarg: bool, } impl Function { pub const FIELDS_COUNT: u32 = 8; } #[no_mangle] pub extern "C" fn unlisp_rt_intern_sym(name: *const c_char) -> *mut Symbol { symbols::get_or_intern_symbol_by_ptr(name) } #[used] static INTERN_SYM: extern "C" fn(name: *const c_char) -> *mut Symbol = unlisp_rt_intern_sym; #[no_mangle] pub extern "C" fn unlisp_rt_object_from_int(i: i64) -> Object { Object::from_int(i) } #[used] static OBJ_FROM_INT: extern "C" fn(i: i64) -> Object = unlisp_rt_object_from_int; #[no_mangle] pub extern "C" fn unlisp_rt_object_from_string(string: *const c_char) -> Object { Object::from_string(string) } #[used] static OBJ_FROM_STRING: extern "C" fn(*const c_char) -> Object = unlisp_rt_object_from_string; #[no_mangle] pub extern "C" fn unlisp_rt_int_from_obj(o: Object) -> i64 { o.unpack_int() } #[used] static INT_FROM_OBJ: extern "C" fn(Object) -> i64 = unlisp_rt_int_from_obj; #[no_mangle] pub extern "C" fn unlisp_rt_object_from_function(f: *mut Function) -> Object { Object::from_function(f) } #[used] static OBJ_FROM_FN: extern "C" fn(f: *mut Function) -> Object = unlisp_rt_object_from_function; #[no_mangle] pub extern "C" fn unlisp_rt_object_from_symbol(s: *mut Symbol) -> Object { Object::from_symbol(s) } #[used] static OBJ_FROM_SYM: extern "C" fn(f: *mut Symbol) -> Object = unlisp_rt_object_from_symbol; #[no_mangle] pub extern "C" fn unlisp_rt_object_from_list(list: List) -> Object { Object::from_list(Box::into_raw(Box::new(list))) } #[used] static OBJ_FROM_LIST: extern "C" fn(List) -> Object = unlisp_rt_object_from_list; #[no_mangle] pub extern "C" fn unlisp_rt_object_is_nil(o: Object) -> bool { o.ty == ObjType::List && { let list_ptr = o.unpack_list(); unsafe { (*list_ptr).len == 0 } } } #[used] static IS_NIL: extern "C" fn(Object) -> bool = unlisp_rt_object_is_nil; #[no_mangle] pub extern "C" fn unlisp_rt_nil_object() -> Object { let list = List { node: ptr::null_mut(), len: 0, }; Object::from_list(Box::into_raw(Box::new(list))) } #[used] static NIL_OBJ: extern "C" fn() -> Object = unlisp_rt_nil_object; #[no_mangle] pub extern "C" fn unlisp_rt_check_arity(f: *const Function, arg_count: u64) -> bool { let has_restarg = unsafe { (*f).has_restarg }; let params_count = unsafe { (*f).arg_count }; let is_incorrect = (arg_count < params_count) || (!has_restarg && params_count != arg_count); !is_incorrect } #[used] static CHECK_ARITY: extern "C" fn(f: *const Function, arg_count: u64) -> bool = unlisp_rt_check_arity; extern "C" { pub fn va_list_to_obj_array(n: u64, list: VaList) -> *mut Object; } pub fn obj_array_to_list(n: u64, arr: *mut Object, list: Option<*mut List>) -> *mut List { let mut list = list.unwrap_or_else(|| { Box::into_raw(Box::new(List { node: ptr::null_mut(), len: 0, })) }); for i in (0..n).rev() { list = Box::into_raw(Box::new(List { len: unsafe { (*list).len } + 1, node: Box::into_raw(Box::new(Node { val: unsafe { arr.offset(i as isize) }, next: list, })), })) } list } #[no_mangle] pub extern "C" fn unlisp_rt_va_list_into_list(n: u64, va_list: VaList) -> Object { let obj_array = unsafe { va_list_to_obj_array(n, va_list) }; let list = obj_array_to_list(n, obj_array, None); Object::from_list(list) } #[used] static VALIST_TO_LIST: extern "C" fn(n: u64, va_list: VaList) -> Object = unlisp_rt_va_list_into_list; #[no_mangle] pub unsafe extern "C" fn unlisp_rt_list_first(list: List) -> Object { list.first() } #[used] static LIST_FIRST: unsafe extern "C" fn(List) -> Object = unlisp_rt_list_first; #[no_mangle] pub unsafe extern "C" fn unlisp_rt_list_rest(list: List) -> List { list.rest() } #[used] static LIST_REST: unsafe extern "C" fn(List) -> List = unlisp_rt_list_rest; #[no_mangle] pub unsafe extern "C" fn unlisp_rt_list_cons(el: Object, list: List) -> List { list.cons(el) } #[used] static LIST_CONS: unsafe extern "C" fn(Object, List) -> List = unlisp_rt_list_cons; #[inline(never)] #[no_mangle] pub extern "C" fn unlisp_rt_empty_list() -> List { let list = List { node: ptr::null_mut(), len: 0, }; list } #[used] static EMPTY_LIST: extern "C" fn() -> List = unlisp_rt_empty_list; #[no_mangle] pub extern "C" fn unlisp_rt_init_runtime() { symbols::init(); predefined::init(); } #[used] static INIT_RT: extern "C" fn() = unlisp_rt_init_runtime;
true
eee0b87b73efea56140405a85b4050382ce9561b
Rust
doraneko94/Rust
/ABS/abc086c/src/main.rs
UTF-8
921
3.453125
3
[]
no_license
fn read1<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn readn<T: std::str::FromStr>(delimeter: &str) -> Vec<T> { let s = read1::<String>(); s.split(delimeter).map(|e| e.parse().ok().unwrap()).collect::<Vec<T>>() } fn main() { let mut v: Vec<Vec<i32>> = vec!(vec!(0, 0, 0)); let n = read1::<u32>(); for _ in 0..n { v.push(readn::<i32>(" ")); } let mut flag = true; for i in 0..n { let dt = (v[i as usize][0] - v[(i+1) as usize][0]).abs(); let dx = (v[i as usize][1] - v[(i+1) as usize][1]).abs(); let dy = (v[i as usize][2] - v[(i+1) as usize][2]).abs(); if dx + dy > dt || (dt - (dx + dy)) % 2 != 0 { flag = false; break; } } if flag { println!("Yes"); } else { println!("No"); } }
true
a1526eaef7b7ff66f2167b1bdfa5eecd187f743e
Rust
xCrypt0r/Baekjoon
/src/15/15780.rs
UTF-8
736
2.640625
3
[ "MIT" ]
permissive
/** * 15780. 멀티탭 충분하니? * * 작성자: xCrypt0r * 언어: Rust 2018 * 사용 메모리: 13,028 KB * 소요 시간: 4 ms * 해결 날짜: 2020년 9월 30일 */ #![allow(non_snake_case)] use std::io; fn main() { let stdin = io::stdin(); let mut s = String::new(); stdin.read_line(&mut s).unwrap(); let v: Vec<i32> = s .split_whitespace() .map(|s| s.parse().unwrap()) .collect(); let mut N = v[0]; s.clear(); stdin.read_line(&mut s).unwrap(); let A: Vec<i32> = s .split_whitespace() .map(|s| s.parse().unwrap()) .collect(); for a in A { N -= (a + 1) / 2; } print!("{}", if N <= 0 { "YES" } else { "NO" }); }
true
9f7ccc4ad044b2269f50730b2b758b06b5ffdab9
Rust
indygreg/starlark-rust
/starlark/src/values/types/record.rs
UTF-8
14,099
2.859375
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //! A `record` type, comprising of a fixed set of fields. //! //! Calling `record()` produces a [`RecordType`]. Calling [`RecordType`] produces a [`Record`]. //! The field names of the record are only stored once, potentially reducing memory usage. //! Created in Starlark using the `record()` function, which accepts keyword arguments. //! The keys become field names, and values are the types. Calling the resulting //! function produces an actual record. //! //! ``` //! # starlark::assert::is_true(r#" //! IpAddress = record(host=str.type, port=int.type) //! rec = IpAddress(host="localhost", port=80) //! rec.port == 80 //! # "#); //! ``` //! //! It is also possible to use `field(type, default)` type to give defaults: //! //! ``` //! # starlark::assert::is_true(r#" //! IpAddress = record(host=str.type, port=field(int.type, 80)) //! rec = IpAddress(host="localhost") //! rec.port == 80 //! # "#); //! ``` use crate as starlark; use crate::{ codemap::Span, collections::SmallMap, eval::{Arguments, Evaluator, ParametersParser, ParametersSpec}, values::{ comparison::equals_slice, function::{NativeFunction, FUNCTION_TYPE}, typing::TypeCompiled, ComplexValue, Freezer, FrozenValue, Heap, StarlarkValue, Trace, Value, ValueLike, }, }; use either::Either; use gazebo::{ any::AnyLifetime, cell::AsARef, coerce::{coerce_ref, Coerce}, prelude::*, }; use std::{ cell::RefCell, collections::hash_map::DefaultHasher, fmt::Debug, hash::{Hash, Hasher}, }; /// The result of `field()`. #[derive(Clone, Debug, Dupe, Trace)] pub struct FieldGen<V> { pub(crate) typ: V, default: Option<V>, } // Manual because no instance for Option<V> unsafe impl<From: Coerce<To>, To> Coerce<FieldGen<To>> for FieldGen<From> {} /// The result of `record()`, being the type of records. #[derive(Debug, Trace)] pub struct RecordTypeGen<V, Typ> { /// The name of this type, e.g. MyRecord /// Either `Option<String>` or a `RefCell` thereof. typ: Typ, /// The V is the type the field must satisfy (e.g. `"string"`) fields: SmallMap<String, (FieldGen<V>, TypeCompiled)>, /// The construction function, which takes a hidden parameter (this type) /// followed by the arguments of the field. /// Creating these on every invoke is pretty expensive (profiling shows) /// so compute them in advance and cache. constructor: V, } pub type RecordType<'v> = RecordTypeGen<Value<'v>, RefCell<Option<String>>>; pub type FrozenRecordType = RecordTypeGen<FrozenValue, Option<String>>; /// An actual record. #[derive(Clone, Debug, Trace, Coerce)] #[repr(C)] pub struct RecordGen<V> { typ: V, // Must be RecordType values: Vec<V>, } starlark_complex_value!(pub(crate) Field); starlark_complex_values!(RecordType); starlark_complex_value!(pub Record); impl<V> FieldGen<V> { pub(crate) fn new(typ: V, default: Option<V>) -> Self { Self { typ, default } } } fn collect_repr_record<'s, 't, V: 't>( items: impl Iterator<Item = (&'s String, &'t V)>, add: impl Fn(&'t V, &mut String), collector: &mut String, ) { collector.push_str("record("); for (i, (name, typ)) in items.enumerate() { if i != 0 { collector.push_str(", "); } collector.push_str(name); collector.push('='); add(typ, collector); } collector.push(')'); } fn record_fields<'v>( x: Either<&'v RecordType<'v>, &'v FrozenRecordType>, ) -> &'v SmallMap<String, (FieldGen<Value<'v>>, TypeCompiled)> { x.either(|x| &x.fields, |x| coerce_ref(&x.fields)) } impl<'v> RecordType<'v> { pub(crate) fn new( fields: SmallMap<String, (FieldGen<Value<'v>>, TypeCompiled)>, heap: &'v Heap, ) -> Self { let constructor = heap.alloc(Self::make_constructor(&fields)); Self { typ: RefCell::new(None), fields, constructor, } } fn make_constructor( fields: &SmallMap<String, (FieldGen<Value<'v>>, TypeCompiled)>, ) -> NativeFunction { let mut parameters = ParametersSpec::with_capacity("record".to_owned(), fields.len()); parameters.no_args(); for (name, field) in fields { if field.0.default.is_some() { parameters.optional(name); } else { parameters.required(name); } } // We want to get the value of `me` into the function, but that doesn't work since it // might move between threads - so we create the NativeFunction and apply it later. NativeFunction::new( move |eval, this, mut param_parser: ParametersParser| { let this = this.unwrap(); let fields = record_fields(RecordType::from_value(this).unwrap()); let mut values = Vec::with_capacity(fields.len()); for (name, field) in fields.iter() { match field.0.default { None => { let v: Value = param_parser.next(name)?; v.check_type_compiled(field.0.typ, &field.1, Some(name))?; values.push(v); } Some(default) => { let v: Option<Value> = param_parser.next_opt(name)?; match v { None => values.push(default), Some(v) => { v.check_type_compiled(field.0.typ, &field.1, Some(name))?; values.push(v); } } } } } Ok(eval.heap().alloc_complex(Record { typ: this, values })) }, parameters.signature(), parameters, ) } } impl<'v, V: ValueLike<'v>> RecordGen<V> { pub const TYPE: &'static str = "record"; fn get_record_type(&self) -> Either<&'v RecordType<'v>, &'v FrozenRecordType> { // Safe to unwrap because we always ensure typ is RecordType RecordType::from_value(self.typ.to_value()).unwrap() } fn get_record_fields(&self) -> &'v SmallMap<String, (FieldGen<Value<'v>>, TypeCompiled)> { record_fields(self.get_record_type()) } } impl<'v> ComplexValue<'v> for Field<'v> { type Frozen = FrozenField; fn freeze(self, freezer: &Freezer) -> anyhow::Result<Self::Frozen> { Ok(FrozenField { typ: self.typ.freeze(freezer)?, default: self.default.into_try_map(|x| x.freeze(freezer))?, }) } } impl<'v, V: ValueLike<'v>> StarlarkValue<'v> for FieldGen<V> where Self: AnyLifetime<'v>, { starlark_type!("field"); fn collect_repr(&self, collector: &mut String) { collector.push_str("field("); self.typ.collect_repr(collector); if let Some(d) = self.default { collector.push_str(", "); d.collect_repr(collector); } collector.push(')'); } fn get_hash(&self) -> anyhow::Result<u64> { let mut s = DefaultHasher::new(); s.write_u64(self.typ.get_hash()?); self.default.is_some().hash(&mut s); if let Some(d) = self.default { s.write_u64(d.get_hash()?); } Ok(s.finish()) } } impl<'v> ComplexValue<'v> for RecordType<'v> { type Frozen = FrozenRecordType; fn freeze(self, freezer: &Freezer) -> anyhow::Result<Self::Frozen> { let mut fields = SmallMap::with_capacity(self.fields.len()); for (k, t) in self.fields.into_iter_hashed() { fields.insert_hashed(k, (t.0.freeze(freezer)?, t.1)); } Ok(FrozenRecordType { typ: self.typ.into_inner(), fields, constructor: self.constructor.freeze(freezer)?, }) } } impl<'v, Typ, V: ValueLike<'v>> StarlarkValue<'v> for RecordTypeGen<V, Typ> where Self: AnyLifetime<'v>, FieldGen<V>: AnyLifetime<'v>, Typ: AsARef<Option<String>> + Debug, { starlark_type!(FUNCTION_TYPE); fn collect_repr(&self, collector: &mut String) { collect_repr_record(self.fields.iter(), |x, s| x.0.collect_repr(s), collector); } fn get_hash(&self) -> anyhow::Result<u64> { let mut s = DefaultHasher::new(); for (name, typ) in &self.fields { name.hash(&mut s); // No need to hash typ.1, since it was computed from typ.0 s.write_u64(typ.0.get_hash()?); } Ok(s.finish()) } fn invoke( &self, me: Value<'v>, location: Option<Span>, mut args: Arguments<'v, '_>, eval: &mut Evaluator<'v, '_>, ) -> anyhow::Result<Value<'v>> { args.this = Some(me); self.constructor.invoke(location, args, eval) } fn extra_memory(&self) -> usize { // We don't capture the memory beneath the TypeCompiled, since we don't know how big // those closures are. let typ = self.typ.as_aref(); typ.as_ref().map_or(0, |s| s.capacity()) + self.fields.extra_memory() } fn dir_attr(&self) -> Vec<String> { vec!["type".to_owned()] } fn has_attr(&self, attribute: &str) -> bool { attribute == "type" } fn get_attr(&self, attribute: &str, heap: &'v Heap) -> Option<Value<'v>> { if attribute == "type" { Some(heap.alloc(self.typ.as_aref().as_deref().unwrap_or(Record::TYPE))) } else { None } } fn equals(&self, other: Value<'v>) -> anyhow::Result<bool> { fn eq<'v>( a: &RecordTypeGen<impl ValueLike<'v>, impl AsARef<Option<String>>>, b: &RecordTypeGen<impl ValueLike<'v>, impl AsARef<Option<String>>>, ) -> anyhow::Result<bool> { if a.typ.as_aref() != b.typ.as_aref() { return Ok(false); }; if a.fields.len() != b.fields.len() { return Ok(false); }; for ((k1, t1), (k2, t2)) in a.fields.iter().zip(b.fields.iter()) { // We require that the types and defaults are both equal. if k1 != k2 || !t1.0.typ.equals(t2.0.typ.to_value())? || t1.0.default.map(ValueLike::to_value) != t2.0.default.map(ValueLike::to_value) { return Ok(false); } } Ok(true) } match RecordType::from_value(other) { Some(Either::Left(other)) => eq(self, &*other), Some(Either::Right(other)) => eq(self, &*other), _ => Ok(false), } } fn export_as(&self, variable_name: &str, _eval: &mut Evaluator<'v, '_>) { if let Some(typ) = self.typ.as_ref_cell() { let mut typ = typ.borrow_mut(); if typ.is_none() { *typ = Some(variable_name.to_owned()) } } } } impl<'v> ComplexValue<'v> for Record<'v> { type Frozen = FrozenRecord; fn freeze(self, freezer: &Freezer) -> anyhow::Result<Self::Frozen> { Ok(FrozenRecord { typ: self.typ.freeze(freezer)?, values: self.values.try_map(|v| v.freeze(freezer))?, }) } } impl<'v, V: ValueLike<'v>> StarlarkValue<'v> for RecordGen<V> where Self: AnyLifetime<'v>, { starlark_type!(Record::TYPE); fn matches_type(&self, ty: &str) -> bool { if ty == Record::TYPE { return true; } match self.get_record_type() { Either::Left(x) => Some(ty) == x.typ.borrow().as_deref(), Either::Right(x) => Some(ty) == x.typ.as_deref(), } } fn to_json(&self) -> anyhow::Result<String> { let mut s = "{".to_owned(); s += &self .get_record_fields() .keys() .zip(&self.values) .map(|(k, v)| Ok(format!("\"{}\":{}", k, v.to_json()?))) .collect::<anyhow::Result<Vec<String>>>()? .join(","); s += "}"; Ok(s) } fn collect_repr(&self, collector: &mut String) { collect_repr_record( self.get_record_fields().keys().zip(&self.values), |x, s| x.collect_repr(s), collector, ); } fn equals(&self, other: Value<'v>) -> anyhow::Result<bool> { match Record::from_value(other) { Some(other) if self.typ.equals(other.typ)? => { equals_slice(&self.values, &other.values, |x, y| x.equals(*y)) } _ => Ok(false), } } fn get_attr(&self, attribute: &str, _heap: &'v Heap) -> Option<Value<'v>> { let i = self.get_record_fields().get_index_of(attribute)?; Some(self.values[i].to_value()) } fn get_hash(&self) -> anyhow::Result<u64> { let mut s = DefaultHasher::new(); s.write_u64(self.typ.get_hash()?); for v in &self.values { s.write_u64(v.get_hash()?); } Ok(s.finish()) } fn has_attr(&self, attribute: &str) -> bool { self.get_record_fields().contains_key(attribute) } fn dir_attr(&self) -> Vec<String> { self.get_record_fields().keys().cloned().collect() } }
true
a3256e8fa4df12ddcd5d7d31e2a126367ae9f1a6
Rust
ethankhall/pagerduty-cli
/src/v2/mod.rs
UTF-8
2,726
3.0625
3
[ "BSD-3-Clause" ]
permissive
extern crate log; use serde::Deserialize; use std::cmp::Ordering; mod api; use api::*; #[derive(Debug, Deserialize, Clone, Eq, Ord, PartialEq, PartialOrd)] pub struct PagerDutyUserGroups { pub users: Vec<PagerDutyUser>, pub depth: u8, } #[derive(Debug, Deserialize, Clone, Eq, PartialEq)] pub struct EscalationPolicy { pub id: String, pub description: Option<String>, pub policy_name: String, pub oncall_groups: Vec<PagerDutyUserGroups>, pub services: Vec<String>, } impl EscalationPolicy { #[cfg(test)] fn new(id: &str, policy_name: &str) -> Self { let formatted_name = format!("oncall-{}", policy_name); EscalationPolicy { id: id.to_string(), description: None, policy_name: policy_name.to_string(), oncall_groups: vec![PagerDutyUserGroups { users: vec![PagerDutyUser { id: formatted_name.clone(), name: formatted_name.clone(), email: formatted_name, }], depth: 1, }], services: vec![], } } } #[test] fn when_different_do_not_match() { assert_ne!( EscalationPolicy::new("abc123", "policy-1"), EscalationPolicy::new("def456", "policy-2") ); } impl PartialOrd for EscalationPolicy { fn partial_cmp(&self, other: &EscalationPolicy) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for EscalationPolicy { fn cmp(&self, other: &EscalationPolicy) -> Ordering { self.policy_name.cmp(&other.policy_name) } } #[derive(Debug, Deserialize, Clone, Ord, PartialOrd, PartialEq, Eq)] pub struct PagerDutyUser { pub id: String, pub name: String, pub email: String, } impl PagerDutyUser { pub fn to_display(&self) -> String { format!("{} ({})", self.name, self.email) } } pub struct PagerDutyClient { api: PagerDutyApi, } impl PagerDutyClient { pub fn new(auth_token: &str) -> Self { let api = PagerDutyApi::new(auth_token.into()); PagerDutyClient { api } } pub async fn fetch_policies_for_account(&self) -> Vec<EscalationPolicy> { self.api.get_escalation_policies().await } } #[test] fn order_will_be_alpha() { let policy1 = EscalationPolicy::new("ABC123", "Connect"); let policy2 = EscalationPolicy::new("DEF456", "Go"); let mut vec = vec![policy1.clone(), policy2.clone()]; vec.sort(); assert_eq!("Connect", vec[0].policy_name); assert_eq!("Go", vec[1].policy_name); let mut vec = vec![policy2, policy1]; vec.sort(); assert_eq!("Connect", vec[0].policy_name); assert_eq!("Go", vec[1].policy_name); }
true
bf382bd7e7920ea6f6339b6fcabd4218164a2d98
Rust
jcrowgey/aoc_2018
/src/two.rs
UTF-8
1,992
3.4375
3
[]
no_license
use std::collections::HashMap; use std::io::BufRead; pub fn two_a<I>(buf: I) -> i32 where I: BufRead, { let mut two_count = 0; let mut three_count = 0; for line in buf.lines() { let mut char_counts = HashMap::new(); for chr in line.unwrap().chars() { match char_counts.get(&chr) { Some(count) => char_counts.insert(chr, count + 1), None => char_counts.insert(chr, 1), }; } let mut two_flag = false; let mut three_flag = false; for val in char_counts.values() { if !two_flag { if val == &2 { two_count += 1; two_flag = true; } } if !three_flag { if val == &3 { three_count += 1; three_flag = true; } } if two_flag && three_flag { break; } } } two_count * three_count } pub fn two_b<I>(buf: I) -> String where I: BufRead, { let mut ids = Vec::<String>::new(); let mut answer = String::from("i give up"); 'outer: for x in buf.lines() { let x = x.unwrap(); for y in ids.iter() { let sames: Vec<(char, char)> = x.chars().zip(y.chars()).filter(|p| p.0 == p.1).collect(); if sames.len() == (x.len() - 1) { answer = sames.iter().map(|x| x.0).collect(); break 'outer; } } ids.push(x.clone()); } answer } #[cfg(test)] mod tests { use super::*; #[test] fn test_two_a() { let input = b"abcdef\nbababc\nabbcde\nabcccd\naabcdd\nabcdee\nababab\n"; assert_eq!(12, two_a(&input[..])); } #[test] fn test_two_b() { let input = b"abcde\nfghij\nklmno\npqrst\nfguij\naxcye\nwvxyz\n"; assert_eq!("fgij".to_string(), two_b(&input[..])); } }
true
f0bf104a1e088c9dded5eddc6eb1895b613271e1
Rust
TrashPandacoot/domo-pitchfork
/src/domo/user.rs
UTF-8
5,982
3.46875
3
[ "MIT" ]
permissive
//! Domo Users API //! //! # [`UsersRequestBuilder`](`crate::pitchfork::UsersRequestBuilder`) implements all available user API endpoints and functionality //! //! Additional Resources: //! - [Domo Users API Reference](https://developer.domo.com/docs/users-api-reference/users) use crate::domo::group::Group; use crate::error::PitchforkError; use crate::pitchfork::{DomoRequest, UsersRequestBuilder}; use log::debug; use reqwest::Method; use serde::{Deserialize, Serialize}; use std::marker::PhantomData; // [User Object](https://developer.domo.com/docs/users-api-reference/users-2) #[derive(Clone, Debug, Serialize, Deserialize)] pub struct User { pub id: Option<u32>, pub title: Option<String>, pub email: Option<String>, #[serde(rename = "alternateEmail")] pub alternate_email: Option<String>, pub role: Option<String>, pub phone: Option<String>, pub name: Option<String>, pub location: Option<String>, pub timezone: Option<String>, // Might not show up in json unless it's been changed from the instance default tz #[serde(rename = "employeeId")] pub employee_id: Option<String>, // key doesn't show up in json if Null #[serde(rename = "roleId")] pub role_id: Option<usize>, #[serde(rename = "employeeNumber")] pub employee_number: Option<usize>, // Doesn't show up in JSON if it's null #[serde(rename = "createdAt")] pub created_at: Option<String>, //TODO: make this a datetime #[serde(rename = "updatedAt")] pub updated_at: Option<String>, //TODO: make this a datetime pub deleted: Option<bool>, #[serde(rename = "image")] pub image_uri: Option<String>, pub groups: Option<Vec<Group>>, pub locale: Option<String>, } // TODO: is the 'Editor' role not available to the api our is the documentation wrong? pub enum Role { Participant, Privileged, Admin, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Owner { pub id: u32, pub name: String, } impl<'t> UsersRequestBuilder<'t, User> { /// Returns a user object if valid user ID was provided. /// When requesting, if the user ID is related to a user that has been deleted, /// a subset of the user information will be returned, /// including a deleted property, which will be true. /// /// # Example /// ```no_run /// # use domo_pitchfork::error::PitchforkError; /// use domo_pitchfork::pitchfork::DomoPitchfork; /// let domo = DomoPitchfork::with_token("token"); /// let user_id = 123; // user id for user to get details for. /// let user_info = domo.users().info(user_id)?; /// println!("User Details: \n{:#?}", user_info); /// # Ok::<(), PitchforkError>(()) /// ``` pub fn info(mut self, user_id: u64) -> Result<User, PitchforkError> { self.url.push_str(&user_id.to_string()); let req = Self { method: Method::GET, auth: self.auth, url: self.url, resp_t: PhantomData, body: None, }; req.retrieve_and_deserialize_json() } /// List Users starting from a given offset up to a given limit. /// Max limit is 500. /// offset is the offset of the user ID to begin list of users within the response. /// # Example /// ```no_run /// # use domo_pitchfork::error::PitchforkError; /// use domo_pitchfork::pitchfork::DomoPitchfork; /// let domo = DomoPitchfork::with_token("token"); /// let list = domo.users().list(5,0)?; /// list.iter().map(|u| println!("User Name: {}", u.name.as_ref().unwrap())); /// # Ok::<(),PitchforkError>(()) /// ``` pub fn list(mut self, limit: u32, offset: u32) -> Result<Vec<User>, PitchforkError> { self.url .push_str(&format!("?limit={}&offset={}", limit, offset)); let req = Self { method: Method::GET, auth: self.auth, url: self.url, resp_t: PhantomData, body: None, }; let ds_list = serde_json::from_reader(req.send_json()?)?; Ok(ds_list) } pub fn create(self, user: &User) -> Result<User, PitchforkError> { // TODO: validate that required fields: name, email, role were provided let body = serde_json::to_string(user)?; debug!("body: {}", body); let req = Self { method: Method::POST, auth: self.auth, url: self.url, resp_t: PhantomData, body: Some(body), }; req.retrieve_and_deserialize_json() } /// Delete the User for the given id. /// This is destructive and cannot be reversed. /// # Example /// ```no_run /// # use domo_pitchfork::pitchfork::DomoPitchfork; /// # let token = "token_here"; /// let domo = DomoPitchfork::with_token(&token); /// /// let user_id = 123; // user id of user to delete. /// // if it fails to delete, print err msg. /// if let Err(e) = domo.users().delete(user_id) { /// println!("{}", e) /// } /// ``` pub fn delete(mut self, user_id: u64) -> Result<(), PitchforkError> { self.url.push_str(&user_id.to_string()); let req = Self { method: Method::DELETE, auth: self.auth, url: self.url, resp_t: PhantomData, body: None, }; req.send_json()?; Ok(()) } /// Update an existing user. /// Known Limitation: as of 4/10/19 all user fields are required by the Domo API pub fn modify(mut self, user_id: u64, user: &User) -> Result<(), PitchforkError> { self.url.push_str(&user_id.to_string()); let body = serde_json::to_string(user)?; debug!("body: {}", body); let req = Self { method: Method::PUT, auth: self.auth, url: self.url, resp_t: PhantomData, body: Some(body), }; req.send_json()?; Ok(()) } }
true
052da81c813d17b985b126ed6d3ed7661aa5b463
Rust
wez/max32630
/max32630_svd/src/i2cm0/ctrl/mod.rs
UTF-8
8,408
2.640625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#[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::CTRL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `tx_fifo_en`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TX_FIFO_ENR { #[doc = r" Reserved"] _Reserved(bool), } impl TX_FIFO_ENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { TX_FIFO_ENR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TX_FIFO_ENR { match value { i => TX_FIFO_ENR::_Reserved(i), } } } #[doc = "Possible values of the field `rx_fifo_en`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RX_FIFO_ENR { #[doc = r" Reserved"] _Reserved(bool), } impl RX_FIFO_ENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { RX_FIFO_ENR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> RX_FIFO_ENR { match value { i => RX_FIFO_ENR::_Reserved(i), } } } #[doc = "Possible values of the field `mstr_reset_en`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTR_RESET_ENR { #[doc = r" Reserved"] _Reserved(bool), } impl MSTR_RESET_ENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MSTR_RESET_ENR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MSTR_RESET_ENR { match value { i => MSTR_RESET_ENR::_Reserved(i), } } } #[doc = "Values that can be written to the field `tx_fifo_en`"] pub enum TX_FIFO_ENW {} impl TX_FIFO_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _TX_FIFO_ENW<'a> { w: &'a mut W, } impl<'a> _TX_FIFO_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TX_FIFO_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `rx_fifo_en`"] pub enum RX_FIFO_ENW {} impl RX_FIFO_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _RX_FIFO_ENW<'a> { w: &'a mut W, } impl<'a> _RX_FIFO_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: RX_FIFO_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `mstr_reset_en`"] pub enum MSTR_RESET_ENW {} impl MSTR_RESET_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _MSTR_RESET_ENW<'a> { w: &'a mut W, } impl<'a> _MSTR_RESET_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MSTR_RESET_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 2 - Master Transaction FIFO Enable"] #[inline] pub fn tx_fifo_en(&self) -> TX_FIFO_ENR { TX_FIFO_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 3 - Master Results FIFO Enable"] #[inline] pub fn rx_fifo_en(&self) -> RX_FIFO_ENR { RX_FIFO_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 7 - Master Reset"] #[inline] pub fn mstr_reset_en(&self) -> MSTR_RESET_ENR { MSTR_RESET_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 2 - Master Transaction FIFO Enable"] #[inline] pub fn tx_fifo_en(&mut self) -> _TX_FIFO_ENW { _TX_FIFO_ENW { w: self } } #[doc = "Bit 3 - Master Results FIFO Enable"] #[inline] pub fn rx_fifo_en(&mut self) -> _RX_FIFO_ENW { _RX_FIFO_ENW { w: self } } #[doc = "Bit 7 - Master Reset"] #[inline] pub fn mstr_reset_en(&mut self) -> _MSTR_RESET_ENW { _MSTR_RESET_ENW { w: self } } }
true
6de26037afc96408817bb868e423b7879a51f80d
Rust
collinprince/rust-book
/projects/blog_post_rustic/src/lib.rs
UTF-8
1,096
3.515625
4
[]
no_license
pub struct Post { content: String, } impl Post { pub fn new() -> DraftPost { DraftPost { content: String::new(), } } pub fn content(&self) -> &str { &self.content } } pub struct DraftPost { content: String, } impl DraftPost { pub fn add_text(&mut self, new_text: &str) { self.content.push_str(new_text); } pub fn request_review(self) -> PendingReview { PendingReview { content: self.content, } } } pub struct PendingReview { content: String, } impl PendingReview { pub fn approve(self) -> Post { Post { content: self.content, } } pub fn reject(self) -> DraftPost { DraftPost { content: self.content, } } } #[cfg(test)] mod tests { use super::*; #[test] fn sample_flow() { let mut post = Post::new(); post.add_text("Hello there"); let post = post.request_review(); let post = post.approve(); assert_eq!("Hello there", post.content()); } }
true
413b5d6481c8e34f47e284e9310db2aa5bbb352a
Rust
ric2b/Vivaldi-browser
/chromium/third_party/rust/which/v4/crate/src/checker.rs
UTF-8
1,802
2.71875
3
[ "MIT", "BSD-3-Clause", "Apache-2.0", "LGPL-2.0-or-later", "GPL-1.0-or-later" ]
permissive
use crate::finder::Checker; #[cfg(unix)] use std::ffi::CString; use std::fs; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; use std::path::Path; pub struct ExecutableChecker; impl ExecutableChecker { pub fn new() -> ExecutableChecker { ExecutableChecker } } impl Checker for ExecutableChecker { #[cfg(unix)] fn is_valid(&self, path: &Path) -> bool { CString::new(path.as_os_str().as_bytes()) .map(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) == 0 }) .unwrap_or(false) } #[cfg(windows)] fn is_valid(&self, _path: &Path) -> bool { true } } pub struct ExistedChecker; impl ExistedChecker { pub fn new() -> ExistedChecker { ExistedChecker } } impl Checker for ExistedChecker { #[cfg(target_os = "windows")] fn is_valid(&self, path: &Path) -> bool { fs::symlink_metadata(path) .map(|metadata| { let file_type = metadata.file_type(); file_type.is_file() || file_type.is_symlink() }) .unwrap_or(false) } #[cfg(not(target_os = "windows"))] fn is_valid(&self, path: &Path) -> bool { fs::metadata(path) .map(|metadata| metadata.is_file()) .unwrap_or(false) } } pub struct CompositeChecker { checkers: Vec<Box<dyn Checker>>, } impl CompositeChecker { pub fn new() -> CompositeChecker { CompositeChecker { checkers: Vec::new(), } } pub fn add_checker(mut self, checker: Box<dyn Checker>) -> CompositeChecker { self.checkers.push(checker); self } } impl Checker for CompositeChecker { fn is_valid(&self, path: &Path) -> bool { self.checkers.iter().all(|checker| checker.is_valid(path)) } }
true
e654fe00fa61984684328c29f0ef97fcaa5846a3
Rust
data-niklas/cash
/src/lang/doc.rs
UTF-8
2,739
3.359375
3
[ "MIT" ]
permissive
use std::collections::HashMap; use lazy_static::*; lazy_static! { pub static ref FUNCTIONS: HashMap<&'static str, &'static str> = { let mut m = HashMap::new(); //Math m.insert("abs", "Returns the absolute value of a number"); m.insert("ceil", "Ceils the number"); m.insert("floor", "Floors the number"); m.insert("round", "Rounds the number to the closest int"); m.insert("signum", "Returns 1.0 if the number is >= +0.0, else -1.0 (for <= -0.0)"); m.insert("sin", "sin function"); m.insert("cos", "cos function"); m.insert("tan", "tan function"); m.insert("asin", "asin function"); m.insert("acos", "acos function"); m.insert("atan", "atan function"); m.insert("sinh", "sinh function"); m.insert("cosh", "cosh function"); m.insert("tanh", "tanh function"); m.insert("asinh", "asinh function"); m.insert("acosh", "acosh function"); m.insert("atanh", "atanh function"); m.insert("log", "Calculates the logarithm to a given base"); m.insert("lg", "Calculates the logarithm to base 10"); m.insert("ld", "Calculates the logarithm to base 2"); m.insert("ln", "Calculates the logarithm to base e"); m.insert("rand", "Returns a random value between 0 and 1"); //Type m.insert("type", "Returns the type of the value"); //Casting m.insert("int", "Attempts to cast a value to an int"); m.insert("string", "Attempts to cast a value to an int"); m.insert("float", "Attempts to cast a value to an int"); m.insert("bool", "Attempts to cast a value to an int"); m.insert("print", "Prints all args after each other"); m.insert("println", "Prints all args after each other and inserts newlines"); m.insert("vars", "Print all vars"); m.insert("len", "Length of an array / string"); m.insert("each", "Executes a function for each value of an array or dict"); m.insert("map", "Maps a value of an array or dict via a function"); m.insert("join", "Joins an array into a string, using a given delimeter"); //Control m.insert("quit", "Exits cash"); m.insert("exit", "Exits cash"); m.insert("cd", "Change current dir"); m.insert("include", "Include another file"); m.insert("clear", "Clears the screen"); m.insert("cls", "Clears the screen"); m.insert("return", "Returns from the current block and returns up to 1 result"); m.insert("help", "shows this help or shows the help of a given command"); //time m.insert("wait", "Waits for x seconds"); m }; }
true
ffc885401b0a21fc8e038a0402ff1161ce97494f
Rust
bobbyrward/adventofcode2020
/rust/adventofcode/src/main.rs
UTF-8
1,512
2.65625
3
[]
no_license
#[macro_use] mod args; mod command; mod point; use anyhow::Result; use clap::Clap; use tracing_subscriber::FmtSubscriber; use crate::command::Command; #[allow(unused_imports)] use crate::point::Point; macro_rules! solution { ($($day:ident),+) => { $( mod $day; )+ pub enum Day { $( #[allow(non_camel_case_types)] $day, )+ } #[derive(Debug, Clap)] pub enum Solutions { $( #[allow(non_camel_case_types)] $day { #[clap(subcommand)] contents: crate::$day::Args, }, )+ } fn input(day: Day) -> &'static str { match day { $(Day::$day { .. } => include_str!(concat!("../../../inputs/", stringify!($day), ".txt")),)+ } } // stringify!($day) impl Command for Solutions { fn execute(&self) -> anyhow::Result<String> { match self { $(Self::$day { contents } => contents.execute(),)+ } } } } } // NOTE: Each solution module must be added here solution!(day01, day02, day03, day04, day06); fn main() -> Result<()> { let args = args::Args::parse(); FmtSubscriber::builder() .with_env_filter(args.env_filter()) .init(); let solution = args.command.execute()?; println!("Solution:\n{}", solution); Ok(()) }
true
02d1dee98fa56ebed72c8b9920bdd429fb2bd443
Rust
icedland/iced
/src/rust/iced-x86-py/src/instruction.rs
UTF-8
177,154
2.609375
3
[ "MIT" ]
permissive
// SPDX-License-Identifier: MIT // Copyright (C) 2018-present iced project and contributors use crate::enum_utils::{to_code, to_code_size, to_mvex_reg_mem_conv, to_op_kind, to_register, to_rep_prefix_kind, to_rounding_control}; use crate::memory_operand::MemoryOperand; use crate::op_code_info::OpCodeInfo; use crate::utils::{get_temporary_byte_array_ref, to_value_error}; use bincode::{deserialize, serialize}; use core::hash::{Hash, Hasher}; use pyo3::class::basic::CompareOp; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyBytes; use std::collections::hash_map::DefaultHasher; /// A 16/32/64-bit x86 instruction. Created by :class:`Decoder` or by ``Instruction.create*()`` methods. /// /// Examples: /// /// A decoder is usually used to create instructions: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # xchg ah,[rdx+rsi+16h] /// data = b"\x86\x64\x32\x16" /// decoder = Decoder(64, data, ip=0x1234_5678) /// /// instr = decoder.decode() /// /// # Instruction supports __bool__() and returns True if it's /// # a valid instruction: /// if not instr: /// print("Invalid instruction (garbage, data, etc)") /// # The above code is the same as: /// if instr.code == Code.INVALID: /// print("Not an instruction") /// /// But there are also static `Instruction.create*()` methods that can be used to create instructions: /// /// .. testcode:: /// /// nop = Instruction.create(Code.NOPD) /// xor = Instruction.create_reg_i32(Code.XOR_RM64_IMM8, Register.R14, -1) /// rep_stosd = Instruction.create_rep_stosd(64) /// add = Instruction.create_mem_i32(Code.ADD_RM64_IMM8, MemoryOperand(Register.RCX, Register.RDX, 8, 0x1234_5678), 2) /// print(f"{nop}") /// print(f"{xor}") /// print(f"{rep_stosd}") /// print(f"{add}") /// /// Output: /// /// .. testoutput:: /// /// nop /// xor r14,0FFFFFFFFFFFFFFFFh /// rep stosd /// add qword ptr [rcx+rdx*8+12345678h],2 /// /// Once you have an instruction you can format it either by using a :class:`Formatter` /// or by calling the instruction's ``__repr__()``, ``__str__()`` or ``__format__()`` methods. /// /// .. testcode:: /// /// # Continued from the above example /// /// formatter = Formatter(FormatterSyntax.INTEL) /// /// # Change some options /// formatter.uppercase_mnemonics = True /// formatter.space_after_operand_separator = True /// formatter.first_operand_char_index = 8 /// /// print(f"disasm : {formatter.format(instr)}") /// # `instr.mnemonic` also returns a `Mnemonic` enum /// print(f"mnemonic: {formatter.format_mnemonic(instr, FormatMnemonicOptions.NO_PREFIXES)}") /// print(f"operands: {formatter.format_all_operands(instr)}") /// # `instr.op0_kind`/etc return operand kind, see also `instr.op0_register`, etc to get reg/mem info /// print(f"op #0 : {formatter.format_operand(instr, 0)}") /// print(f"op #1 : {formatter.format_operand(instr, 1)}") /// print(f"reg RCX : {formatter.format_register(Register.RCX)}") /// /// Output: /// /// .. testoutput:: /// /// disasm : XCHG [rdx+rsi+16h], ah /// mnemonic: XCHG /// operands: [rdx+rsi+16h], ah /// op #0 : [rdx+rsi+16h] /// op #1 : ah /// reg RCX : rcx /// /// .. testcode:: /// /// # A formatter isn't needed if you like most of the default options. /// # repr() == str() == format() all return the same thing. /// print(f"disasm : {repr(instr)}") /// print(f"disasm : {str(instr)}") /// print(f"disasm : {instr}") /// /// Output: /// /// .. testoutput:: /// /// disasm : xchg ah,[rdx+rsi+16h] /// disasm : xchg ah,[rdx+rsi+16h] /// disasm : xchg ah,[rdx+rsi+16h] /// /// .. testcode:: /// /// # __format__() supports a format spec argument, see the table below /// print(f"disasm : {instr:f}") /// print(f"disasm : {instr:g}") /// print(f"disasm : {instr:i}") /// print(f"disasm : {instr:m}") /// print(f"disasm : {instr:n}") /// print(f"disasm : {instr:gxsSG}") /// /// Output: /// /// .. testoutput:: /// /// disasm : xchg [rdx+rsi+16h],ah /// disasm : xchg %ah,0x16(%rdx,%rsi) /// disasm : xchg [rdx+rsi+16h],ah /// disasm : xchg ah,[rdx+rsi+16h] /// disasm : xchg ah,[rdx+rsi+16h] /// disasm : xchgb %ah, %ds:0x16(%rdx,%rsi) /// /// The following format specifiers are supported in any order. If you omit the /// formatter kind, the default formatter is used (eg. masm): /// /// ====== ============================================================================= /// F-Spec Description /// ====== ============================================================================= /// f Fast formatter (masm-like syntax) /// g GNU Assembler formatter /// i Intel (XED) formatter /// m masm formatter /// n nasm formatter /// X Uppercase hex numbers with ``0x`` prefix /// x Lowercase hex numbers with ``0x`` prefix /// H Uppercase hex numbers with ``h`` suffix /// h Lowercase hex numbers with ``h`` suffix /// r RIP-relative memory operands use RIP register instead of abs addr (``[rip+123h]`` vs ``[123456789ABCDEF0h]``) /// U Uppercase everything except numbers and hex prefixes/suffixes (ignored by fast fmt) /// s Add a space after the operand separator /// S Always show the segment register (memory operands) /// B Don't show the branch size (``SHORT`` or ``NEAR PTR``) (ignored by fast fmt) /// G (GNU Assembler): Add mnemonic size suffix (eg. ``movl`` vs ``mov``) /// M Always show the memory size (eg. ``BYTE PTR``) even when not needed /// _ Use digit separators (eg. ``0x12345678`` vs ``0x1234_5678``) (ignored by fast fmt) /// ====== ============================================================================= #[pyclass(module = "iced_x86._iced_x86_py")] #[derive(Copy, Clone)] pub(crate) struct Instruction { pub(crate) instr: iced_x86::Instruction, } #[pymethods] impl Instruction { #[new] #[pyo3(text_signature = "()")] pub(crate) fn new() -> Self { Self { instr: iced_x86::Instruction::default() } } /// Set the internal state with the given unpickled state. /// /// Args: /// state (Any): unpickled state #[pyo3(text_signature = "($self, state)")] fn __setstate__(&mut self, py: Python<'_>, state: PyObject) -> PyResult<()> { match state.extract::<&PyBytes>(py) { Ok(s) => { self.instr = deserialize(s.as_bytes()).map_err(to_value_error)?; Ok(()) } Err(e) => Err(e), } } /// Get the unpickled state corresponding to the instruction. /// /// Returns: /// bytes: The unpickled state #[pyo3(text_signature = "($self)")] fn __getstate__(&self, py: Python<'_>) -> PyResult<PyObject> { let state = PyBytes::new(py, &serialize(&self.instr).map_err(to_value_error)?).to_object(py); Ok(state) } /// Returns a copy of this instance. /// /// Returns: /// Instruction: A copy of this instance /// /// This is identical to :class:`Instruction.copy` #[pyo3(text_signature = "($self)")] fn __copy__(&self) -> Self { *self } /// Returns a copy of this instance. /// /// Args: /// memo (Any): memo dict /// /// Returns: /// Instruction: A copy of this instance /// /// This is identical to :class:`Instruction.copy` #[pyo3(text_signature = "($self, memo)")] fn __deepcopy__(&self, _memo: &PyAny) -> Self { *self } /// Returns a copy of this instance. /// /// Returns: /// Instruction: A copy of this instance #[pyo3(text_signature = "($self)")] fn copy(&self) -> Self { *self } /// Checks if two instructions are equal, comparing all bits, not ignoring anything. ``==`` ignores some fields. /// /// Args: /// other (:class:`Instruction`): Other instruction /// /// Returns: /// bool: ``True`` if `other` is exactly identical to this instance #[pyo3(text_signature = "($self, other)")] fn eq_all_bits(&self, other: &Self) -> bool { self.instr.eq_all_bits(&other.instr) } /// int: (``u16``) Gets the 16-bit IP of the instruction #[getter] fn ip16(&self) -> u16 { self.instr.ip16() } #[setter] fn set_ip16(&mut self, new_value: u16) { self.instr.set_ip16(new_value) } /// int: (``u32``) Gets the 32-bit IP of the instruction #[getter] fn ip32(&self) -> u32 { self.instr.ip32() } #[setter] fn set_ip32(&mut self, new_value: u32) { self.instr.set_ip32(new_value) } /// int: (``u64``) Gets the 64-bit IP of the instruction #[getter] fn ip(&self) -> u64 { self.instr.ip() } #[setter] fn set_ip(&mut self, new_value: u64) { self.instr.set_ip(new_value) } /// int: (``u16``) Gets the 16-bit IP of the next instruction #[getter] fn next_ip16(&self) -> u16 { self.instr.next_ip16() } #[setter] fn set_next_ip16(&mut self, new_value: u16) { self.instr.set_next_ip16(new_value) } /// int: (``u32``) Gets the 32-bit IP of the next instruction #[getter] fn next_ip32(&self) -> u32 { self.instr.next_ip32() } #[setter] fn set_next_ip32(&mut self, new_value: u32) { self.instr.set_next_ip32(new_value) } /// int: (``u64``) Gets the 64-bit IP of the next instruction #[getter] fn next_ip(&self) -> u64 { self.instr.next_ip() } #[setter] fn set_next_ip(&mut self, new_value: u64) { self.instr.set_next_ip(new_value) } /// :class:`CodeSize`: Gets the code size (a :class:`CodeSize` enum value) when the instruction was decoded. /// /// Note: /// This value is informational and can be used by a formatter. #[getter] fn code_size(&self) -> u32 { self.instr.code_size() as u32 } #[setter] fn set_code_size(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_code_size(to_code_size(new_value)?); Ok(()) } /// bool: Checks if it's an invalid instruction (:class:`Instruction.code` == :class:`Code.INVALID`) #[getter] fn is_invalid(&self) -> bool { self.instr.is_invalid() } /// :class:`Code`: Gets the instruction code (a :class:`Code` enum value), see also :class:`Instruction.mnemonic` #[getter] fn code(&self) -> u32 { self.instr.code() as u32 } #[setter] fn set_code(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_code(to_code(new_value)?); Ok(()) } /// :class:`Mnemonic`: Gets the mnemonic (a :class:`Mnemonic` enum value), see also :class:`Instruction.code` #[getter] fn mnemonic(&self) -> u32 { self.instr.mnemonic() as u32 } /// int: Gets the operand count. An instruction can have 0-5 operands. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # add [rax],ebx /// data = b"\x01\x18" /// decoder = Decoder(64, data) /// instr = decoder.decode() /// /// assert instr.op_count == 2 #[getter] fn op_count(&self) -> u32 { self.instr.op_count() } /// int: (``u8``) Gets the length of the instruction, 0-15 bytes. /// /// You can also call `len(instr)` to get this value. /// /// Note: /// This is just informational. If you modify the instruction or create a new one, this method could return the wrong value. #[getter] fn len(&self) -> usize { self.instr.len() } #[setter] fn set_len(&mut self, new_value: usize) { self.instr.set_len(new_value) } /// bool: ``True`` if the instruction has the ``XACQUIRE`` prefix (``F2``) #[getter] fn has_xacquire_prefix(&self) -> bool { self.instr.has_xacquire_prefix() } #[setter] fn set_has_xacquire_prefix(&mut self, new_value: bool) { self.instr.set_has_xacquire_prefix(new_value) } /// bool: ``True`` if the instruction has the ``XRELEASE`` prefix (``F3``) #[getter] fn has_xrelease_prefix(&self) -> bool { self.instr.has_xrelease_prefix() } #[setter] fn set_has_xrelease_prefix(&mut self, new_value: bool) { self.instr.set_has_xrelease_prefix(new_value) } /// bool: ``True`` if the instruction has the ``REPE`` or ``REP`` prefix (``F3``) #[getter] fn has_rep_prefix(&self) -> bool { self.instr.has_rep_prefix() } #[setter] fn set_has_rep_prefix(&mut self, new_value: bool) { self.instr.set_has_rep_prefix(new_value) } /// bool: ``True`` if the instruction has the ``REPE`` or ``REP`` prefix (``F3``) #[getter] fn has_repe_prefix(&self) -> bool { self.instr.has_repe_prefix() } #[setter] fn set_has_repe_prefix(&mut self, new_value: bool) { self.instr.set_has_repe_prefix(new_value) } /// bool: ``True`` if the instruction has the ``REPNE`` prefix (``F2``) #[getter] fn has_repne_prefix(&self) -> bool { self.instr.has_repne_prefix() } #[setter] fn set_has_repne_prefix(&mut self, new_value: bool) { self.instr.set_has_repne_prefix(new_value) } /// bool: ``True`` if the instruction has the ``LOCK`` prefix (``F0``) #[getter] fn has_lock_prefix(&self) -> bool { self.instr.has_lock_prefix() } #[setter] fn set_has_lock_prefix(&mut self, new_value: bool) { self.instr.set_has_lock_prefix(new_value) } /// :class:`OpKind`: Gets operand #0's kind (an :class:`OpKind` enum value) if the operand exists (see :class:`Instruction.op_count` and :class:`Instruction.op_kind`) #[getter] fn op0_kind(&self) -> u32 { self.instr.op0_kind() as u32 } #[setter] fn set_op0_kind(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op0_kind(to_op_kind(new_value)?); Ok(()) } /// :class:`OpKind`: Gets operand #1's kind (an :class:`OpKind` enum value) if the operand exists (see :class:`Instruction.op_count` and :class:`Instruction.op_kind`) #[getter] fn op1_kind(&self) -> u32 { self.instr.op1_kind() as u32 } #[setter] fn set_op1_kind(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op1_kind(to_op_kind(new_value)?); Ok(()) } /// :class:`OpKind`: Gets operand #2's kind (an :class:`OpKind` enum value) if the operand exists (see :class:`Instruction.op_count` and :class:`Instruction.op_kind`) #[getter] fn op2_kind(&self) -> u32 { self.instr.op2_kind() as u32 } #[setter] fn set_op2_kind(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op2_kind(to_op_kind(new_value)?); Ok(()) } /// :class:`OpKind`: Gets operand #3's kind (an :class:`OpKind` enum value) if the operand exists (see :class:`Instruction.op_count` and :class:`Instruction.op_kind`) #[getter] fn op3_kind(&self) -> u32 { self.instr.op3_kind() as u32 } #[setter] fn set_op3_kind(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op3_kind(to_op_kind(new_value)?); Ok(()) } /// :class:`OpKind`: Gets operand #4's kind (an :class:`OpKind` enum value) if the operand exists (see :class:`Instruction.op_count` and :class:`Instruction.op_kind`) #[getter] fn op4_kind(&self) -> u32 { self.instr.op4_kind() as u32 } #[setter] fn set_op4_kind(&mut self, new_value: u32) -> PyResult<()> { self.instr.try_set_op4_kind(to_op_kind(new_value)?).map_err(to_value_error) } /// Gets an operand's kind (an :class:`OpKind` enum value) if it exists (see :class:`Instruction.op_count`) /// /// Args: /// `operand` (int): Operand number, 0-4 /// /// Returns: /// :class:`OpKind`: The operand's operand kind /// /// Raises: /// ValueError: If `operand` is invalid /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # add [rax],ebx /// data = b"\x01\x18" /// decoder = Decoder(64, data) /// instr = decoder.decode() /// /// assert instr.op_count == 2 /// assert instr.op_kind(0) == OpKind.MEMORY /// assert instr.memory_base == Register.RAX /// assert instr.memory_index == Register.NONE /// assert instr.op_kind(1) == OpKind.REGISTER /// assert instr.op_register(1) == Register.EBX #[pyo3(text_signature = "($self, operand)")] fn op_kind(&self, operand: u32) -> PyResult<u32> { self.instr.try_op_kind(operand).map_or_else(|e| Err(to_value_error(e)), |op_kind| Ok(op_kind as u32)) } /// Sets an operand's kind /// /// Args: /// `operand` (int): Operand number, 0-4 /// `op_kind` (:class:`OpKind`): Operand kind /// /// Raises: /// ValueError: If `operand` is invalid #[pyo3(text_signature = "($self, operand, op_kind)")] fn set_op_kind(&mut self, operand: u32, op_kind: u32) -> PyResult<()> { self.instr.try_set_op_kind(operand, to_op_kind(op_kind)?).map_err(to_value_error) } /// bool: Checks if the instruction has a segment override prefix, see :class:`Instruction.segment_prefix` #[getter] fn has_segment_prefix(&self) -> bool { self.instr.has_segment_prefix() } /// :class:`Register`: Gets the segment override prefix (a :class:`Register` enum value) or :class:`Register.NONE` if none. /// /// See also :class:`Instruction.memory_segment`. /// /// Use this method if the operand has kind :class:`OpKind.MEMORY`, /// :class:`OpKind.MEMORY_SEG_SI`, :class:`OpKind.MEMORY_SEG_ESI`, :class:`OpKind.MEMORY_SEG_RSI` #[getter] fn segment_prefix(&self) -> u32 { self.instr.segment_prefix() as u32 } #[setter] fn set_segment_prefix(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_segment_prefix(to_register(new_value)?); Ok(()) } /// :class:`Register`: Gets the effective segment register used to reference the memory location (a :class:`Register` enum value). /// /// Use this method if the operand has kind :class:`OpKind.MEMORY`, /// :class:`OpKind.MEMORY_SEG_SI`, :class:`OpKind.MEMORY_SEG_ESI`, :class:`OpKind.MEMORY_SEG_RSI` #[getter] fn memory_segment(&self) -> u32 { self.instr.memory_segment() as u32 } /// int: (``u8``) Gets the size of the memory displacement in bytes. /// /// Valid values are ``0``, ``1`` (16/32/64-bit), ``2`` (16-bit), ``4`` (32-bit), ``8`` (64-bit). /// /// Note that the return value can be 1 and :class:`Instruction.memory_displacement` may still not fit in /// a signed byte if it's an EVEX/MVEX encoded instruction. /// /// Use this method if the operand has kind :class:`OpKind.MEMORY` #[getter] fn memory_displ_size(&self) -> u32 { self.instr.memory_displ_size() } #[setter] fn set_memory_displ_size(&mut self, new_value: u32) { self.instr.set_memory_displ_size(new_value) } /// bool: ``True`` if the data is broadcast (EVEX instructions only) #[getter] fn is_broadcast(&self) -> bool { self.instr.is_broadcast() } #[setter] fn set_is_broadcast(&mut self, new_value: bool) { self.instr.set_is_broadcast(new_value) } /// bool: ``True`` if eviction hint bit is set (``{eh}``) (MVEX instructions only) #[getter] fn is_mvex_eviction_hint(&self) -> bool { self.instr.is_mvex_eviction_hint() } #[setter] fn set_is_mvex_eviction_hint(&mut self, new_value: bool) { self.instr.set_is_mvex_eviction_hint(new_value) } /// :class:`MvexRegMemConv`: (MVEX) Register/memory operand conversion function (an :class:`MvexRegMemConv` enum value) #[getter] fn mvex_reg_mem_conv(&self) -> u32 { self.instr.mvex_reg_mem_conv() as u32 } #[setter] fn set_mvex_reg_mem_conv(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_mvex_reg_mem_conv(to_mvex_reg_mem_conv(new_value)?); Ok(()) } /// :class:`MemorySize`: Gets the size of the memory location (a :class:`MemorySize` enum value) that is referenced by the operand. /// /// See also :class:`Instruction.is_broadcast`. /// /// Use this method if the operand has kind :class:`OpKind.MEMORY`, /// :class:`OpKind.MEMORY_SEG_SI`, :class:`OpKind.MEMORY_SEG_ESI`, :class:`OpKind.MEMORY_SEG_RSI`, /// :class:`OpKind.MEMORY_ESDI`, :class:`OpKind.MEMORY_ESEDI`, :class:`OpKind.MEMORY_ESRDI` #[getter] fn memory_size(&self) -> u32 { self.instr.memory_size() as u32 } /// int: (``u8``) Gets the index register scale value, valid values are ``*1``, ``*2``, ``*4``, ``*8``. /// /// Use this method if the operand has kind :class:`OpKind.MEMORY` #[getter] fn memory_index_scale(&self) -> u32 { self.instr.memory_index_scale() } #[setter] fn set_memory_index_scale(&mut self, new_value: u32) { self.instr.set_memory_index_scale(new_value) } /// int: (``u64``) Gets the memory operand's displacement or the 64-bit absolute address if it's /// an ``EIP`` or ``RIP`` relative memory operand. /// /// Use this method if the operand has kind :class:`OpKind.MEMORY` #[getter] fn memory_displacement(&self) -> u64 { self.instr.memory_displacement64() } #[setter] fn set_memory_displacement(&mut self, new_value: u64) { self.instr.set_memory_displacement64(new_value) } /// Gets an operand's immediate value /// /// Args: /// `operand` (int): Operand number, 0-4 /// /// Returns: /// int: (``u64``) The immediate /// /// Raises: /// ValueError: If `operand` is invalid or not immediate. #[pyo3(text_signature = "($self, operand)")] fn immediate(&self, operand: u32) -> PyResult<u64> { self.instr.try_immediate(operand).map_err(to_value_error) } /// Sets an operand's immediate value /// /// Args: /// `operand` (int): Operand number, 0-4 /// `new_value` (int): (``i32``) Immediate /// /// Raises: /// ValueError: If `operand` is invalid or if it's not an immediate operand #[pyo3(text_signature = "($self, operand, new_value)")] fn set_immediate_i32(&mut self, operand: u32, new_value: i32) -> PyResult<()> { self.instr.try_set_immediate_i32(operand, new_value).map_err(to_value_error) } /// Sets an operand's immediate value /// /// Args: /// `operand` (int): Operand number, 0-4 /// `new_value` (int): (``u32``) Immediate /// /// Raises: /// ValueError: If `operand` is invalid or if it's not an immediate operand #[pyo3(text_signature = "($self, operand, new_value)")] fn set_immediate_u32(&mut self, operand: u32, new_value: u32) -> PyResult<()> { self.instr.try_set_immediate_u32(operand, new_value).map_err(to_value_error) } /// Sets an operand's immediate value /// /// Args: /// `operand` (int): Operand number, 0-4 /// `new_value` (int): (``i64``) Immediate /// /// Raises: /// ValueError: If `operand` is invalid or if it's not an immediate operand #[pyo3(text_signature = "($self, operand, new_value)")] fn set_immediate_i64(&mut self, operand: u32, new_value: i64) -> PyResult<()> { self.instr.try_set_immediate_i64(operand, new_value).map_err(to_value_error) } /// Sets an operand's immediate value /// /// Args: /// `operand` (int): Operand number, 0-4 /// `new_value` (int): (``u64``) Immediate /// /// Raises: /// ValueError: If `operand` is invalid or if it's not an immediate operand #[pyo3(text_signature = "($self, operand, new_value)")] fn set_immediate_u64(&mut self, operand: u32, new_value: u64) -> PyResult<()> { self.instr.try_set_immediate_u64(operand, new_value).map_err(to_value_error) } /// int: (``u8``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE8` #[getter] fn immediate8(&self) -> u8 { self.instr.immediate8() } #[setter] fn set_immediate8(&mut self, new_value: u8) { self.instr.set_immediate8(new_value) } /// int: (``u8``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE8_2ND` #[getter] fn immediate8_2nd(&self) -> u8 { self.instr.immediate8_2nd() } #[setter] fn set_immediate8_2nd(&mut self, new_value: u8) { self.instr.set_immediate8_2nd(new_value) } /// int: (``u16``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE16` #[getter] fn immediate16(&self) -> u16 { self.instr.immediate16() } #[setter] fn set_immediate16(&mut self, new_value: u16) { self.instr.set_immediate16(new_value); } /// int: (``u32``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE32` #[getter] fn immediate32(&self) -> u32 { self.instr.immediate32() } #[setter] fn set_immediate32(&mut self, new_value: u32) { self.instr.set_immediate32(new_value); } /// int: (``u64``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE64` #[getter] fn immediate64(&self) -> u64 { self.instr.immediate64() } #[setter] fn set_immediate64(&mut self, new_value: u64) { self.instr.set_immediate64(new_value); } /// int: (``i16``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE8TO16` #[getter] fn immediate8to16(&self) -> i16 { self.instr.immediate8to16() } #[setter] fn set_immediate8to16(&mut self, new_value: i16) { self.instr.set_immediate8to16(new_value) } /// int: (``i32``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE8TO32` #[getter] fn immediate8to32(&self) -> i32 { self.instr.immediate8to32() } #[setter] fn set_immediate8to32(&mut self, new_value: i32) { self.instr.set_immediate8to32(new_value) } /// int: (``i64``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE8TO64` #[getter] fn immediate8to64(&self) -> i64 { self.instr.immediate8to64() } #[setter] fn set_immediate8to64(&mut self, new_value: i64) { self.instr.set_immediate8to64(new_value); } /// int: (``i64``) Gets the operand's immediate value. /// /// Use this method if the operand has kind :class:`OpKind.IMMEDIATE32TO64` #[getter] fn immediate32to64(&self) -> i64 { self.instr.immediate32to64() } #[setter] fn set_immediate32to64(&mut self, new_value: i64) { self.instr.set_immediate32to64(new_value); } /// int: (``u16``) Gets the operand's branch target. /// /// Use this method if the operand has kind :class:`OpKind.NEAR_BRANCH16` #[getter] fn near_branch16(&self) -> u16 { self.instr.near_branch16() } #[setter] fn set_near_branch16(&mut self, new_value: u16) { self.instr.set_near_branch16(new_value); } /// int: (``u32``) Gets the operand's branch target. /// /// Use this method if the operand has kind :class:`OpKind.NEAR_BRANCH32` #[getter] fn near_branch32(&self) -> u32 { self.instr.near_branch32() } #[setter] fn set_near_branch32(&mut self, new_value: u32) { self.instr.set_near_branch32(new_value); } /// int: (``u64``) Gets the operand's branch target. /// /// Use this method if the operand has kind :class:`OpKind.NEAR_BRANCH64` #[getter] fn near_branch64(&self) -> u64 { self.instr.near_branch64() } #[setter] fn set_near_branch64(&mut self, new_value: u64) { self.instr.set_near_branch64(new_value); } /// int: (``u64``) Gets the near branch target if it's a ``CALL``/``JMP``/``Jcc`` near branch instruction /// /// (i.e., if :class:`Instruction.op0_kind` is :class:`OpKind.NEAR_BRANCH16`, :class:`OpKind.NEAR_BRANCH32` or :class:`OpKind.NEAR_BRANCH64`) #[getter] fn near_branch_target(&self) -> u64 { self.instr.near_branch_target() } /// int: (``u16``) Gets the operand's branch target. /// /// Use this method if the operand has kind :class:`OpKind.FAR_BRANCH16` #[getter] fn far_branch16(&self) -> u16 { self.instr.far_branch16() } #[setter] fn set_far_branch16(&mut self, new_value: u16) { self.instr.set_far_branch16(new_value); } /// int: (``u32``) Gets the operand's branch target. /// /// Use this method if the operand has kind :class:`OpKind.FAR_BRANCH32` #[getter] fn far_branch32(&self) -> u32 { self.instr.far_branch32() } #[setter] fn set_far_branch32(&mut self, new_value: u32) { self.instr.set_far_branch32(new_value); } /// int: (`16``) Gets the operand's branch target selector. /// /// Use this method if the operand has kind :class:`OpKind.FAR_BRANCH16` or :class:`OpKind.FAR_BRANCH32` #[getter] fn far_branch_selector(&self) -> u16 { self.instr.far_branch_selector() } #[setter] fn set_far_branch_selector(&mut self, new_value: u16) { self.instr.set_far_branch_selector(new_value); } /// :class:`Register`: Gets the memory operand's base register (a :class:`Register` enum value) or :class:`Register.NONE` if none. /// /// Use this method if the operand has kind :class:`OpKind.MEMORY` #[getter] fn memory_base(&self) -> u32 { self.instr.memory_base() as u32 } #[setter] fn set_memory_base(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_memory_base(to_register(new_value)?); Ok(()) } /// :class:`Register`: Gets the memory operand's index register (a :class:`Register` enum value) or :class:`Register.NONE` if none. /// /// Use this method if the operand has kind :class:`OpKind.MEMORY` #[getter] fn memory_index(&self) -> u32 { self.instr.memory_index() as u32 } #[setter] fn set_memory_index(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_memory_index(to_register(new_value)?); Ok(()) } /// :class:`Register`: Gets operand #0's register value (a :class:`Register` enum value). /// /// Use this method if operand #0 (:class:`Instruction.op0_kind`) has kind :class:`OpKind.REGISTER`, see :class:`Instruction.op_count` and :class:`Instruction.op_register` #[getter] fn op0_register(&self) -> u32 { self.instr.op0_register() as u32 } #[setter] fn set_op0_register(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op0_register(to_register(new_value)?); Ok(()) } /// :class:`Register`: Gets operand #1's register value (a :class:`Register` enum value). /// /// Use this method if operand #1 (:class:`Instruction.op0_kind`) has kind :class:`OpKind.REGISTER`, see :class:`Instruction.op_count` and :class:`Instruction.op_register` #[getter] fn op1_register(&self) -> u32 { self.instr.op1_register() as u32 } #[setter] fn set_op1_register(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op1_register(to_register(new_value)?); Ok(()) } /// :class:`Register`: Gets operand #2's register value (a :class:`Register` enum value). /// /// Use this method if operand #2 (:class:`Instruction.op0_kind`) has kind :class:`OpKind.REGISTER`, see :class:`Instruction.op_count` and :class:`Instruction.op_register` #[getter] fn op2_register(&self) -> u32 { self.instr.op2_register() as u32 } #[setter] fn set_op2_register(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op2_register(to_register(new_value)?); Ok(()) } /// :class:`Register`: Gets operand #3's register value (a :class:`Register` enum value). /// /// Use this method if operand #3 (:class:`Instruction.op0_kind`) has kind :class:`OpKind.REGISTER`, see :class:`Instruction.op_count` and :class:`Instruction.op_register` #[getter] fn op3_register(&self) -> u32 { self.instr.op3_register() as u32 } #[setter] fn set_op3_register(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op3_register(to_register(new_value)?); Ok(()) } /// :class:`Register`: Gets operand #4's register value (a :class:`Register` enum value). /// /// Use this method if operand #4 (:class:`Instruction.op0_kind`) has kind :class:`OpKind.REGISTER`, see :class:`Instruction.op_count` and :class:`Instruction.op_register` #[getter] fn op4_register(&self) -> u32 { self.instr.op4_register() as u32 } #[setter] fn set_op4_register(&mut self, new_value: u32) -> PyResult<()> { self.instr.try_set_op4_register(to_register(new_value)?).map_err(to_value_error) } /// Gets the operand's register value (a :class:`Register` enum value). /// /// Use this method if the operand has kind :class:`OpKind.REGISTER` /// /// Args: /// `operand` (int): Operand number, 0-4 /// /// Returns: /// :class:`Register`: The operand's register value /// /// Raises: /// ValueError: If `operand` is invalid /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # add [rax],ebx /// data = b"\x01\x18" /// decoder = Decoder(64, data) /// instr = decoder.decode() /// /// assert instr.op_count == 2 /// assert instr.op_kind(0) == OpKind.MEMORY /// assert instr.op_kind(1) == OpKind.REGISTER /// assert instr.op_register(1) == Register.EBX #[pyo3(text_signature = "($self, operand)")] fn op_register(&self, operand: u32) -> PyResult<u32> { self.instr.try_op_register(operand).map_or_else(|e| Err(to_value_error(e)), |register| Ok(register as u32)) } /// Sets the operand's register value. /// /// Use this method if the operand has kind :class:`OpKind.REGISTER` /// /// Args: /// `operand` (int): Operand number, 0-4 /// `new_value` (:class:`Register`): New value /// /// Raises: /// ValueError: If `operand` is invalid #[pyo3(text_signature = "($self, operand, new_value)")] fn set_op_register(&mut self, operand: u32, new_value: u32) -> PyResult<()> { self.instr.try_set_op_register(operand, to_register(new_value)?).map_err(to_value_error) } /// :class:`Register`: Gets the opmask register (:class:`Register.K1` - :class:`Register.K7`) or :class:`Register.NONE` if none (a :class:`Register` enum value) #[getter] fn op_mask(&self) -> u32 { self.instr.op_mask() as u32 } #[setter] fn set_op_mask(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_op_mask(to_register(new_value)?); Ok(()) } /// bool: Checks if there's an opmask register (:class:`Instruction.op_mask`) #[getter] fn has_op_mask(&self) -> bool { self.instr.has_op_mask() } /// bool: ``True`` if zeroing-masking, ``False`` if merging-masking. /// /// Only used by most EVEX encoded instructions that use opmask registers. #[getter] fn zeroing_masking(&self) -> bool { self.instr.zeroing_masking() } #[setter] fn set_zeroing_masking(&mut self, new_value: bool) { self.instr.set_zeroing_masking(new_value); } /// bool: ``True`` if merging-masking, ``False`` if zeroing-masking. /// /// Only used by most EVEX encoded instructions that use opmask registers. #[getter] fn merging_masking(&self) -> bool { self.instr.merging_masking() } #[setter] fn set_merging_masking(&mut self, new_value: bool) { self.instr.set_merging_masking(new_value); } /// :class:`RoundingControl`: Gets the rounding control (a :class:`RoundingControl` enum value) or :class:`RoundingControl.NONE` if the instruction doesn't use it. /// /// Note: /// SAE is implied but :class:`Instruction.suppress_all_exceptions` still returns ``False``. #[getter] fn rounding_control(&self) -> u32 { self.instr.rounding_control() as u32 } #[setter] fn set_rounding_control(&mut self, new_value: u32) -> PyResult<()> { self.instr.set_rounding_control(to_rounding_control(new_value)?); Ok(()) } /// int: (``u8``) Gets the number of elements in a ``db``/``dw``/``dd``/``dq`` directive. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREBYTE`, :class:`Code.DECLAREWORD`, :class:`Code.DECLAREDWORD`, :class:`Code.DECLAREQWORD` #[getter] fn declare_data_len(&self) -> usize { self.instr.declare_data_len() } #[setter] fn set_declare_data_len(&mut self, new_value: usize) { self.instr.set_declare_data_len(new_value); } /// Sets a new ``db`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREBYTE` /// /// Args: /// `index` (int): Index (0-15) /// `new_value` (int): (``i8``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_byte_value_i8(&mut self, index: usize, new_value: i8) -> PyResult<()> { self.instr.try_set_declare_byte_value_i8(index, new_value).map_err(to_value_error) } /// Sets a new ``db`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREBYTE` /// /// Args: /// `index` (int): Index (0-15) /// `new_value` (int): (``u8``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_byte_value(&mut self, index: usize, new_value: u8) -> PyResult<()> { self.instr.try_set_declare_byte_value(index, new_value).map_err(to_value_error) } /// Gets a ``db`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREBYTE` /// /// Args: /// `index` (int): Index (0-15) /// /// Returns: /// int: (``u8``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_byte_value(&self, index: usize) -> PyResult<u8> { let value = self.instr.try_get_declare_byte_value(index).map_err(to_value_error)?; Ok(value) } /// Gets a ``db`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREBYTE` /// /// Args: /// `index` (int): Index (0-15) /// /// Returns: /// int: (``i8``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_byte_value_i8(&self, index: usize) -> PyResult<i8> { let value = self.instr.try_get_declare_byte_value(index).map_err(to_value_error)?; Ok(value as i8) } /// Sets a new ``dw`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREWORD` /// /// Args: /// `index` (int): Index (0-7) /// `new_value` (int): (``i16``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_word_value_i16(&mut self, index: usize, new_value: i16) -> PyResult<()> { self.instr.try_set_declare_word_value_i16(index, new_value).map_err(to_value_error) } /// Sets a new ``dw`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREWORD` /// /// Args: /// `index` (int): Index (0-7) /// `new_value` (int): (``u16``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_word_value(&mut self, index: usize, new_value: u16) -> PyResult<()> { self.instr.try_set_declare_word_value(index, new_value).map_err(to_value_error) } /// Gets a ``dw`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREWORD` /// /// Args: /// `index` (int): Index (0-7) /// /// Returns: /// int: (``u16``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_word_value(&self, index: usize) -> PyResult<u16> { let value = self.instr.try_get_declare_word_value(index).map_err(to_value_error)?; Ok(value) } /// Gets a ``dw`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREWORD` /// /// Args: /// `index` (int): Index (0-7) /// /// Returns: /// int: (``i16``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_word_value_i16(&self, index: usize) -> PyResult<i16> { let value = self.instr.try_get_declare_word_value(index).map_err(to_value_error)?; Ok(value as i16) } /// Sets a new ``dd`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREDWORD` /// /// Args: /// `index` (int): Index (0-3) /// `new_value` (int): (``i32``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_dword_value_i32(&mut self, index: usize, new_value: i32) -> PyResult<()> { self.instr.try_set_declare_dword_value_i32(index, new_value).map_err(to_value_error) } /// Sets a new ``dd`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREDWORD` /// /// Args: /// `index` (int): Index (0-3) /// `new_value` (int): (``u32``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_dword_value(&mut self, index: usize, new_value: u32) -> PyResult<()> { self.instr.try_set_declare_dword_value(index, new_value).map_err(to_value_error) } /// Gets a ``dd`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREDWORD` /// /// Args: /// `index` (int): Index (0-3) /// /// Returns: /// int: (``u32``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_dword_value(&self, index: usize) -> PyResult<u32> { let value = self.instr.try_get_declare_dword_value(index).map_err(to_value_error)?; Ok(value) } /// Gets a ``dd`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREDWORD` /// /// Args: /// `index` (int): Index (0-3) /// /// Returns: /// int: (``i32``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_dword_value_i32(&self, index: usize) -> PyResult<i32> { let value = self.instr.try_get_declare_dword_value(index).map_err(to_value_error)?; Ok(value as i32) } /// Sets a new ``dq`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREQWORD` /// /// Args: /// `index` (int): Index (0-1) /// `new_value` (int): (``i64``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_qword_value_i64(&mut self, index: usize, new_value: i64) -> PyResult<()> { self.instr.try_set_declare_qword_value_i64(index, new_value).map_err(to_value_error) } /// Sets a new ``dq`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREQWORD` /// /// Args: /// `index` (int): Index (0-1) /// `new_value` (int): (``u64``) New value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index, new_value)")] fn set_declare_qword_value(&mut self, index: usize, new_value: u64) -> PyResult<()> { self.instr.try_set_declare_qword_value(index, new_value).map_err(to_value_error) } /// Gets a ``dq`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREQWORD` /// /// Args: /// `index` (int): Index (0-1) /// /// Returns: /// int: (``u64``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_qword_value(&self, index: usize) -> PyResult<u64> { let value = self.instr.try_get_declare_qword_value(index).map_err(to_value_error)?; Ok(value) } /// Gets a ``dq`` value, see also :class:`Instruction.declare_data_len`. /// /// Can only be called if :class:`Instruction.code` is :class:`Code.DECLAREQWORD` /// /// Args: /// `index` (int): Index (0-1) /// /// Returns: /// int: (``i64``) The value /// /// Raises: /// ValueError: If `index` is invalid #[pyo3(text_signature = "($self, index)")] fn get_declare_qword_value_i64(&self, index: usize) -> PyResult<i64> { let value = self.instr.try_get_declare_qword_value(index).map_err(to_value_error)?; Ok(value as i64) } /// bool: Checks if this is a VSIB instruction, see also :class:`Instruction.is_vsib32`, :class:`Instruction.is_vsib64` #[getter] fn is_vsib(&self) -> bool { self.instr.is_vsib() } /// bool: VSIB instructions only (:class:`Instruction.is_vsib`): ``True`` if it's using 32-bit indexes, ``False`` if it's using 64-bit indexes #[getter] fn is_vsib32(&self) -> bool { self.instr.is_vsib32() } /// bool: VSIB instructions only (:class:`Instruction.is_vsib`): ``True`` if it's using 64-bit indexes, ``False`` if it's using 32-bit indexes #[getter] fn is_vsib64(&self) -> bool { self.instr.is_vsib64() } /// bool, None: Checks if it's a vsib instruction. /// /// - Returns ``True`` if it's a VSIB instruction with 64-bit indexes /// - Returns ``False`` if it's a VSIB instruction with 32-bit indexes /// - Returns `None` if it's not a VSIB instruction. #[getter] fn vsib(&self) -> Option<bool> { self.instr.vsib() } /// bool: Gets the suppress all exceptions flag (EVEX/MVEX encoded instructions). Note that if :class:`Instruction.rounding_control` is not :class:`RoundingControl.NONE`, SAE is implied but this method will still return ``False``. #[getter] fn suppress_all_exceptions(&self) -> bool { self.instr.suppress_all_exceptions() } #[setter] fn set_suppress_all_exceptions(&mut self, new_value: bool) { self.instr.set_suppress_all_exceptions(new_value); } /// bool: Checks if the memory operand is ``RIP``/``EIP`` relative #[getter] fn is_ip_rel_memory_operand(&self) -> bool { self.instr.is_ip_rel_memory_operand() } /// int: (``u64``) Gets the ``RIP``/``EIP`` releative address (:class:`Instruction.memory_displacement`). /// /// This method is only valid if there's a memory operand with ``RIP``/``EIP`` relative addressing, see :class:`Instruction.is_ip_rel_memory_operand` #[getter] fn ip_rel_memory_address(&self) -> u64 { self.instr.ip_rel_memory_address() } /// int: (``i32``) Gets the number of bytes added to ``SP``/``ESP``/``RSP`` or 0 if it's not an instruction that pushes or pops data. /// /// This method assumes the instruction doesn't change the privilege level (eg. ``IRET/D/Q``). If it's the ``LEAVE`` /// instruction, this method returns 0. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # pushfq /// data = b"\x9C" /// decoder = Decoder(64, data) /// instr = decoder.decode() /// /// assert instr.is_stack_instruction /// assert instr.stack_pointer_increment == -8 #[getter] fn stack_pointer_increment(&self) -> i32 { self.instr.stack_pointer_increment() } /// Gets the FPU status word's ``TOP`` increment value and whether it's a conditional or unconditional push/pop and whether ``TOP`` is written. /// /// Returns: /// :class:`FpuStackIncrementInfo`: FPU stack info /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # ficomp dword ptr [rax] /// data = b"\xDA\x18" /// decoder = Decoder(64, data) /// instr = decoder.decode() /// /// info = instr.fpu_stack_increment_info() /// # It pops the stack once /// assert info.increment == 1 /// assert not info.conditional /// assert info.writes_top #[pyo3(text_signature = "($self)")] fn fpu_stack_increment_info(&self) -> FpuStackIncrementInfo { FpuStackIncrementInfo { info: self.instr.fpu_stack_increment_info() } } /// :class:`EncodingKind`: Instruction encoding, eg. Legacy, 3DNow!, VEX, EVEX, XOP (an :class:`EncodingKind` enum value) /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # vmovaps xmm1,xmm5 /// data = b"\xC5\xF8\x28\xCD" /// decoder = Decoder(64, data) /// instr = decoder.decode() /// /// assert instr.encoding == EncodingKind.VEX #[getter] fn encoding(&self) -> u32 { self.instr.encoding() as u32 } /// Gets the CPU or CPUID feature flags (a list of :class:`CpuidFeature` enum values) /// /// Returns: /// List[:class:`CpuidFeature`]: CPU or CPUID feature flags /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # vmovaps xmm1,xmm5 /// # vmovaps xmm10{k3}{z},xmm19 /// data = b"\xC5\xF8\x28\xCD\x62\x31\x7C\x8B\x28\xD3" /// decoder = Decoder(64, data) /// /// # vmovaps xmm1,xmm5 /// instr = decoder.decode() /// cpuid = instr.cpuid_features() /// assert len(cpuid) == 1 /// assert cpuid[0] == CpuidFeature.AVX /// /// # vmovaps xmm10{k3}{z},xmm19 /// instr = decoder.decode() /// cpuid = instr.cpuid_features() /// assert len(cpuid) == 2 /// assert cpuid[0] == CpuidFeature.AVX512VL /// assert cpuid[1] == CpuidFeature.AVX512F #[pyo3(text_signature = "($self)")] fn cpuid_features(&self) -> Vec<u32> { self.instr.cpuid_features().iter().map(|x| *x as u32).collect() } /// :class:`FlowControl`: Control flow info (a :class:`FlowControl` enum value) /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # or ecx,esi /// # ud0 rcx,rsi /// # call rcx /// data = b"\x0B\xCE\x48\x0F\xFF\xCE\xFF\xD1" /// decoder = Decoder(64, data) /// /// # or ecx,esi /// instr = decoder.decode() /// assert instr.flow_control == FlowControl.NEXT /// /// # ud0 rcx,rsi /// instr = decoder.decode() /// assert instr.flow_control == FlowControl.EXCEPTION /// /// # call rcx /// instr = decoder.decode() /// assert instr.flow_control == FlowControl.INDIRECT_CALL #[getter] fn flow_control(&self) -> u32 { self.instr.flow_control() as u32 } /// bool: ``True`` if it's a privileged instruction (all CPL=0 instructions (except ``VMCALL``) and IOPL instructions ``IN``, ``INS``, ``OUT``, ``OUTS``, ``CLI``, ``STI``) #[getter] fn is_privileged(&self) -> bool { self.instr.is_privileged() } /// bool: ``True`` if this is an instruction that implicitly uses the stack pointer (``SP``/``ESP``/``RSP``), eg. ``CALL``, ``PUSH``, ``POP``, ``RET``, etc. /// /// See also :class:`Instruction.stack_pointer_increment` /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # or ecx,esi /// # push rax /// data = b"\x0B\xCE\x50" /// decoder = Decoder(64, data) /// /// # or ecx,esi /// instr = decoder.decode() /// assert not instr.is_stack_instruction /// /// # push rax /// instr = decoder.decode() /// assert instr.is_stack_instruction /// assert instr.stack_pointer_increment == -8 #[getter] fn is_stack_instruction(&self) -> bool { self.instr.is_stack_instruction() } /// bool: ``True`` if it's an instruction that saves or restores too many registers (eg. ``FXRSTOR``, ``XSAVE``, etc). #[getter] fn is_save_restore_instruction(&self) -> bool { self.instr.is_save_restore_instruction() } /// bool: ``True`` if it's a "string" instruction, such as ``MOVS``, ``LODS``, ``SCAS``, etc. #[getter] fn is_string_instruction(&self) -> bool { self.instr.is_string_instruction() } /// :class:`RflagsBits`: All flags that are read by the CPU when executing the instruction. /// /// This method returns an :class:`RflagsBits` value. See also :class:`Instruction.rflags_modified`. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # adc rsi,rcx /// # xor rdi,5Ah /// data = b"\x48\x11\xCE\x48\x83\xF7\x5A" /// decoder = Decoder(64, data) /// /// # adc rsi,rcx /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.CF /// assert instr.rflags_written == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.NONE /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.NONE /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// /// # xor rdi,5Ah /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.NONE /// assert instr.rflags_written == RflagsBits.SF | RflagsBits.ZF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.OF | RflagsBits.CF /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.AF /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF #[getter] fn rflags_read(&self) -> u32 { self.instr.rflags_read() } /// :class:`RflagsBits`: All flags that are written by the CPU, except those flags that are known to be undefined, always set or always cleared. /// /// This method returns an :class:`RflagsBits` value. See also :class:`Instruction.rflags_modified`. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # adc rsi,rcx /// # xor rdi,5Ah /// data = b"\x48\x11\xCE\x48\x83\xF7\x5A" /// decoder = Decoder(64, data) /// /// # adc rsi,rcx /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.CF /// assert instr.rflags_written == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.NONE /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.NONE /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// /// # xor rdi,5Ah /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.NONE /// assert instr.rflags_written == RflagsBits.SF | RflagsBits.ZF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.OF | RflagsBits.CF /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.AF /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF #[getter] fn rflags_written(&self) -> u32 { self.instr.rflags_written() } /// :class:`RflagsBits`: All flags that are always cleared by the CPU. /// /// This method returns an :class:`RflagsBits` value. See also :class:`Instruction.rflags_modified`. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # adc rsi,rcx /// # xor rdi,5Ah /// data = b"\x48\x11\xCE\x48\x83\xF7\x5A" /// decoder = Decoder(64, data) /// /// # adc rsi,rcx /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.CF /// assert instr.rflags_written == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.NONE /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.NONE /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// /// # xor rdi,5Ah /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.NONE /// assert instr.rflags_written == RflagsBits.SF | RflagsBits.ZF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.OF | RflagsBits.CF /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.AF /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF #[getter] fn rflags_cleared(&self) -> u32 { self.instr.rflags_cleared() } /// :class:`RflagsBits`: All flags that are always set by the CPU. /// /// This method returns an :class:`RflagsBits` value. See also :class:`Instruction.rflags_modified`. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # adc rsi,rcx /// # xor rdi,5Ah /// data = b"\x48\x11\xCE\x48\x83\xF7\x5A" /// decoder = Decoder(64, data) /// /// # adc rsi,rcx /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.CF /// assert instr.rflags_written == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.NONE /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.NONE /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// /// # xor rdi,5Ah /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.NONE /// assert instr.rflags_written == RflagsBits.SF | RflagsBits.ZF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.OF | RflagsBits.CF /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.AF /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF #[getter] fn rflags_set(&self) -> u32 { self.instr.rflags_set() } /// :class:`RflagsBits`: All flags that are undefined after executing the instruction. /// /// This method returns an :class:`RflagsBits` value. See also :class:`Instruction.rflags_modified`. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # adc rsi,rcx /// # xor rdi,5Ah /// data = b"\x48\x11\xCE\x48\x83\xF7\x5A" /// decoder = Decoder(64, data) /// /// # adc rsi,rcx /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.CF /// assert instr.rflags_written == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.NONE /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.NONE /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// /// # xor rdi,5Ah /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.NONE /// assert instr.rflags_written == RflagsBits.SF | RflagsBits.ZF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.OF | RflagsBits.CF /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.AF /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF #[getter] fn rflags_undefined(&self) -> u32 { self.instr.rflags_undefined() } /// :class:`RflagsBits`: All flags that are modified by the CPU. This is ``rflags_written + rflags_cleared + rflags_set + rflags_undefined``. /// /// This method returns an :class:`RflagsBits` value. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # adc rsi,rcx /// # xor rdi,5Ah /// data = b"\x48\x11\xCE\x48\x83\xF7\x5A" /// decoder = Decoder(64, data) /// /// # adc rsi,rcx /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.CF /// assert instr.rflags_written == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.NONE /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.NONE /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF /// /// # xor rdi,5Ah /// instr = decoder.decode() /// assert instr.rflags_read == RflagsBits.NONE /// assert instr.rflags_written == RflagsBits.SF | RflagsBits.ZF | RflagsBits.PF /// assert instr.rflags_cleared == RflagsBits.OF | RflagsBits.CF /// assert instr.rflags_set == RflagsBits.NONE /// assert instr.rflags_undefined == RflagsBits.AF /// assert instr.rflags_modified == RflagsBits.OF | RflagsBits.SF | RflagsBits.ZF | RflagsBits.AF | RflagsBits.CF | RflagsBits.PF #[getter] fn rflags_modified(&self) -> u32 { self.instr.rflags_modified() } /// bool: Checks if it's a ``Jcc SHORT`` or ``Jcc NEAR`` instruction #[getter] fn is_jcc_short_or_near(&self) -> bool { self.instr.is_jcc_short_or_near() } /// bool: Checks if it's a ``Jcc NEAR`` instruction #[getter] fn is_jcc_near(&self) -> bool { self.instr.is_jcc_near() } /// bool: Checks if it's a ``Jcc SHORT`` instruction #[getter] fn is_jcc_short(&self) -> bool { self.instr.is_jcc_short() } /// bool: Checks if it's a ``JMP SHORT`` instruction #[getter] fn is_jmp_short(&self) -> bool { self.instr.is_jmp_short() } /// bool: Checks if it's a ``JMP NEAR`` instruction #[getter] fn is_jmp_near(&self) -> bool { self.instr.is_jmp_near() } /// bool: Checks if it's a ``JMP SHORT`` or a ``JMP NEAR`` instruction #[getter] fn is_jmp_short_or_near(&self) -> bool { self.instr.is_jmp_short_or_near() } /// bool: Checks if it's a ``JMP FAR`` instruction #[getter] fn is_jmp_far(&self) -> bool { self.instr.is_jmp_far() } /// bool: Checks if it's a ``CALL NEAR`` instruction #[getter] fn is_call_near(&self) -> bool { self.instr.is_call_near() } /// bool: Checks if it's a ``CALL FAR`` instruction #[getter] fn is_call_far(&self) -> bool { self.instr.is_call_far() } /// bool: Checks if it's a ``JMP NEAR reg/[mem]`` instruction #[getter] fn is_jmp_near_indirect(&self) -> bool { self.instr.is_jmp_near_indirect() } /// bool: Checks if it's a ``JMP FAR [mem]`` instruction #[getter] fn is_jmp_far_indirect(&self) -> bool { self.instr.is_jmp_far_indirect() } /// bool: Checks if it's a ``CALL NEAR reg/[mem]`` instruction #[getter] fn is_call_near_indirect(&self) -> bool { self.instr.is_call_near_indirect() } /// bool: Checks if it's a ``CALL FAR [mem]`` instruction #[getter] fn is_call_far_indirect(&self) -> bool { self.instr.is_call_far_indirect() } /// bool: Checks if it's a ``JKccD SHORT`` or ``JKccD NEAR`` instruction #[getter] fn is_jkcc_short_or_near(&self) -> bool { self.instr.is_jkcc_short_or_near() } /// bool: Checks if it's a ``JKccD NEAR`` instruction #[getter] fn is_jkcc_near(&self) -> bool { self.instr.is_jkcc_near() } /// bool: Checks if it's a ``JKccD SHORT`` instruction #[getter] fn is_jkcc_short(&self) -> bool { self.instr.is_jkcc_short() } /// bool: Checks if it's a ``JCXZ SHORT``, ``JECXZ SHORT`` or ``JRCXZ SHORT`` instruction #[getter] pub fn is_jcx_short(&self) -> bool { self.instr.code().is_jcx_short() } /// bool: Checks if it's a ``LOOPcc SHORT`` instruction #[getter] pub fn is_loopcc(&self) -> bool { self.instr.code().is_loopcc() } /// bool: Checks if it's a ``LOOP SHORT`` instruction #[getter] pub fn is_loop(&self) -> bool { self.instr.code().is_loop() } /// Negates the condition code, eg. ``JE`` -> ``JNE``. /// /// Can be used if it's ``Jcc``, ``SETcc``, ``CMOVcc``, ``CMPccXADD``, ``LOOPcc`` and does nothing if the instruction doesn't have a condition code. /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # setbe al /// data = b"\x0F\x96\xC0" /// decoder = Decoder(64, data) /// /// instr = decoder.decode() /// assert instr.code == Code.SETBE_RM8 /// assert instr.condition_code == ConditionCode.BE /// instr.negate_condition_code() /// assert instr.code == Code.SETA_RM8 /// assert instr.condition_code == ConditionCode.A #[pyo3(text_signature = "($self)")] fn negate_condition_code(&mut self) { self.instr.negate_condition_code() } /// Converts ``Jcc/JMP NEAR`` to ``Jcc/JMP SHORT`` and does nothing if it's not a ``Jcc/JMP NEAR`` instruction /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # jbe near ptr label /// data = b"\x0F\x86\x5A\xA5\x12\x34" /// decoder = Decoder(64, data) /// /// instr = decoder.decode() /// assert instr.code == Code.JBE_REL32_64 /// instr.as_short_branch() /// assert instr.code == Code.JBE_REL8_64 /// instr.as_short_branch() /// assert instr.code == Code.JBE_REL8_64 #[pyo3(text_signature = "($self)")] fn as_short_branch(&mut self) { self.instr.as_short_branch() } /// Converts ``Jcc/JMP SHORT`` to ``Jcc/JMP NEAR`` and does nothing if it's not a ``Jcc/JMP SHORT`` instruction /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # jbe short label /// data = b"\x76\x5A" /// decoder = Decoder(64, data) /// /// instr = decoder.decode() /// assert instr.code == Code.JBE_REL8_64 /// instr.as_near_branch() /// assert instr.code == Code.JBE_REL32_64 /// instr.as_near_branch() /// assert instr.code == Code.JBE_REL32_64 #[pyo3(text_signature = "($self)")] fn as_near_branch(&mut self) { self.instr.as_near_branch() } /// :class:`ConditionCode`: Gets the condition code (a :class:`ConditionCode` enum value) if it's ``Jcc``, ``SETcc``, ``CMOVcc``, ``CMPccXADD``, ``LOOPcc`` else :class:`ConditionCode.NONE` is returned /// /// Examples: /// /// .. testcode:: /// /// from iced_x86 import * /// /// # setbe al /// # jl short label /// # cmovne ecx,esi /// # nop /// data = b"\x0F\x96\xC0\x7C\x5A\x0F\x45\xCE\x90" /// decoder = Decoder(64, data) /// /// # setbe al /// instr = decoder.decode() /// assert instr.condition_code == ConditionCode.BE /// /// # jl short label /// instr = decoder.decode() /// assert instr.condition_code == ConditionCode.L /// /// # cmovne ecx,esi /// instr = decoder.decode() /// assert instr.condition_code == ConditionCode.NE /// /// # nop /// instr = decoder.decode() /// assert instr.condition_code == ConditionCode.NONE #[getter] fn condition_code(&self) -> u32 { self.instr.condition_code() as u32 } /// Gets the :class:`OpCodeInfo` /// /// Returns: /// :class:`OpCodeInfo`: Op code info #[pyo3(text_signature = "($self)")] fn op_code(&self) -> PyResult<OpCodeInfo> { OpCodeInfo::new(self.instr.code() as u32) } // GENERATOR-BEGIN: Create // ⚠️This was generated by GENERATOR!🦹‍♂️ /// Creates an instruction with no operands /// /// Args: /// `code` (:class:`Code`): Code value /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code)")] fn create(code: u32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with(code) }) } /// Creates an instruction with 1 operand /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register)")] fn create_reg(code: u32, register: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with1(code, register).map_err(to_value_error)? }) } /// Creates an instruction with 1 operand /// /// Args: /// `code` (:class:`Code`): Code value /// `immediate` (int): (``i32``) op0: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, immediate)")] fn create_i32(code: u32, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with1(code, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 1 operand /// /// Args: /// `code` (:class:`Code`): Code value /// `immediate` (int): (``u32``) op0: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, immediate)")] fn create_u32(code: u32, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with1(code, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 1 operand /// /// Args: /// `code` (:class:`Code`): Code value /// `memory` (:class:`MemoryOperand`): op0: Memory operand /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, memory)")] fn create_mem(code: u32, memory: MemoryOperand) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with1(code, memory.mem).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2)")] fn create_reg_reg(code: u32, register1: u32, register2: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, register1, register2).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `immediate` (int): (``i32``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, immediate)")] fn create_reg_i32(code: u32, register: u32, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, register, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `immediate` (int): (``u32``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, immediate)")] fn create_reg_u32(code: u32, register: u32, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, register, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `immediate` (int): (``i64``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, immediate)")] fn create_reg_i64(code: u32, register: u32, immediate: i64) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, register, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `immediate` (int): (``u64``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, immediate)")] fn create_reg_u64(code: u32, register: u32, immediate: u64) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, register, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `memory` (:class:`MemoryOperand`): op1: Memory operand /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, memory)")] fn create_reg_mem(code: u32, register: u32, memory: MemoryOperand) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, register, memory.mem).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `immediate` (int): (``i32``) op0: Immediate value /// `register` (:class:`Register`): op1: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, immediate, register)")] fn create_i32_reg(code: u32, immediate: i32, register: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, immediate, register).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `immediate` (int): (``u32``) op0: Immediate value /// `register` (:class:`Register`): op1: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, immediate, register)")] fn create_u32_reg(code: u32, immediate: u32, register: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, immediate, register).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `immediate1` (int): (``i32``) op0: Immediate value /// `immediate2` (int): (``i32``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, immediate1, immediate2)")] fn create_i32_i32(code: u32, immediate1: i32, immediate2: i32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, immediate1, immediate2).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `immediate1` (int): (``u32``) op0: Immediate value /// `immediate2` (int): (``u32``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, immediate1, immediate2)")] fn create_u32_u32(code: u32, immediate1: u32, immediate2: u32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, immediate1, immediate2).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `memory` (:class:`MemoryOperand`): op0: Memory operand /// `register` (:class:`Register`): op1: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, memory, register)")] fn create_mem_reg(code: u32, memory: MemoryOperand, register: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, memory.mem, register).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `memory` (:class:`MemoryOperand`): op0: Memory operand /// `immediate` (int): (``i32``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, memory, immediate)")] fn create_mem_i32(code: u32, memory: MemoryOperand, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 2 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `memory` (:class:`MemoryOperand`): op0: Memory operand /// `immediate` (int): (``u32``) op1: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, memory, immediate)")] fn create_mem_u32(code: u32, memory: MemoryOperand, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with2(code, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3)")] fn create_reg_reg_reg(code: u32, register1: u32, register2: u32, register3: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register1, register2, register3).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `immediate` (int): (``i32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, immediate)")] fn create_reg_reg_i32(code: u32, register1: u32, register2: u32, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register1, register2, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `immediate` (int): (``u32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, immediate)")] fn create_reg_reg_u32(code: u32, register1: u32, register2: u32, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register1, register2, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `memory` (:class:`MemoryOperand`): op2: Memory operand /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, memory)")] fn create_reg_reg_mem(code: u32, register1: u32, register2: u32, memory: MemoryOperand) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register1, register2, memory.mem).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `immediate1` (int): (``i32``) op1: Immediate value /// `immediate2` (int): (``i32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, immediate1, immediate2)")] fn create_reg_i32_i32(code: u32, register: u32, immediate1: i32, immediate2: i32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register, immediate1, immediate2).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `immediate1` (int): (``u32``) op1: Immediate value /// `immediate2` (int): (``u32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, immediate1, immediate2)")] fn create_reg_u32_u32(code: u32, register: u32, immediate1: u32, immediate2: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register, immediate1, immediate2).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `memory` (:class:`MemoryOperand`): op1: Memory operand /// `register2` (:class:`Register`): op2: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, memory, register2)")] fn create_reg_mem_reg(code: u32, register1: u32, memory: MemoryOperand, register2: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register1, memory.mem, register2).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `memory` (:class:`MemoryOperand`): op1: Memory operand /// `immediate` (int): (``i32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, memory, immediate)")] fn create_reg_mem_i32(code: u32, register: u32, memory: MemoryOperand, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register` (:class:`Register`): op0: Register /// `memory` (:class:`MemoryOperand`): op1: Memory operand /// `immediate` (int): (``u32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register, memory, immediate)")] fn create_reg_mem_u32(code: u32, register: u32, memory: MemoryOperand, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, register, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `memory` (:class:`MemoryOperand`): op0: Memory operand /// `register1` (:class:`Register`): op1: Register /// `register2` (:class:`Register`): op2: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, memory, register1, register2)")] fn create_mem_reg_reg(code: u32, memory: MemoryOperand, register1: u32, register2: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, memory.mem, register1, register2).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `memory` (:class:`MemoryOperand`): op0: Memory operand /// `register` (:class:`Register`): op1: Register /// `immediate` (int): (``i32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, memory, register, immediate)")] fn create_mem_reg_i32(code: u32, memory: MemoryOperand, register: u32, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, memory.mem, register, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 3 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `memory` (:class:`MemoryOperand`): op0: Memory operand /// `register` (:class:`Register`): op1: Register /// `immediate` (int): (``u32``) op2: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, memory, register, immediate)")] fn create_mem_reg_u32(code: u32, memory: MemoryOperand, register: u32, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register = to_register(register)?; Ok(Instruction { instr: iced_x86::Instruction::with3(code, memory.mem, register, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `register4` (:class:`Register`): op3: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, register4)")] fn create_reg_reg_reg_reg(code: u32, register1: u32, register2: u32, register3: u32, register4: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; let register4 = to_register(register4)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, register3, register4).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `immediate` (int): (``i32``) op3: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, immediate)")] fn create_reg_reg_reg_i32(code: u32, register1: u32, register2: u32, register3: u32, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, register3, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `immediate` (int): (``u32``) op3: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, immediate)")] fn create_reg_reg_reg_u32(code: u32, register1: u32, register2: u32, register3: u32, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, register3, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `memory` (:class:`MemoryOperand`): op3: Memory operand /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, memory)")] fn create_reg_reg_reg_mem(code: u32, register1: u32, register2: u32, register3: u32, memory: MemoryOperand) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, register3, memory.mem).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `immediate1` (int): (``i32``) op2: Immediate value /// `immediate2` (int): (``i32``) op3: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, immediate1, immediate2)")] fn create_reg_reg_i32_i32(code: u32, register1: u32, register2: u32, immediate1: i32, immediate2: i32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, immediate1, immediate2).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `immediate1` (int): (``u32``) op2: Immediate value /// `immediate2` (int): (``u32``) op3: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, immediate1, immediate2)")] fn create_reg_reg_u32_u32(code: u32, register1: u32, register2: u32, immediate1: u32, immediate2: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, immediate1, immediate2).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `memory` (:class:`MemoryOperand`): op2: Memory operand /// `register3` (:class:`Register`): op3: Register /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, memory, register3)")] fn create_reg_reg_mem_reg(code: u32, register1: u32, register2: u32, memory: MemoryOperand, register3: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, memory.mem, register3).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `memory` (:class:`MemoryOperand`): op2: Memory operand /// `immediate` (int): (``i32``) op3: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, memory, immediate)")] fn create_reg_reg_mem_i32(code: u32, register1: u32, register2: u32, memory: MemoryOperand, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 4 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `memory` (:class:`MemoryOperand`): op2: Memory operand /// `immediate` (int): (``u32``) op3: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, memory, immediate)")] fn create_reg_reg_mem_u32(code: u32, register1: u32, register2: u32, memory: MemoryOperand, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; Ok(Instruction { instr: iced_x86::Instruction::with4(code, register1, register2, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 5 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `register4` (:class:`Register`): op3: Register /// `immediate` (int): (``i32``) op4: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, register4, immediate)")] fn create_reg_reg_reg_reg_i32(code: u32, register1: u32, register2: u32, register3: u32, register4: u32, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; let register4 = to_register(register4)?; Ok(Instruction { instr: iced_x86::Instruction::with5(code, register1, register2, register3, register4, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 5 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `register4` (:class:`Register`): op3: Register /// `immediate` (int): (``u32``) op4: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, register4, immediate)")] fn create_reg_reg_reg_reg_u32(code: u32, register1: u32, register2: u32, register3: u32, register4: u32, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; let register4 = to_register(register4)?; Ok(Instruction { instr: iced_x86::Instruction::with5(code, register1, register2, register3, register4, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 5 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `memory` (:class:`MemoryOperand`): op3: Memory operand /// `immediate` (int): (``i32``) op4: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, memory, immediate)")] fn create_reg_reg_reg_mem_i32(code: u32, register1: u32, register2: u32, register3: u32, memory: MemoryOperand, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with5(code, register1, register2, register3, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 5 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `register3` (:class:`Register`): op2: Register /// `memory` (:class:`MemoryOperand`): op3: Memory operand /// `immediate` (int): (``u32``) op4: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, register3, memory, immediate)")] fn create_reg_reg_reg_mem_u32(code: u32, register1: u32, register2: u32, register3: u32, memory: MemoryOperand, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with5(code, register1, register2, register3, memory.mem, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 5 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `memory` (:class:`MemoryOperand`): op2: Memory operand /// `register3` (:class:`Register`): op3: Register /// `immediate` (int): (``i32``) op4: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, memory, register3, immediate)")] fn create_reg_reg_mem_reg_i32(code: u32, register1: u32, register2: u32, memory: MemoryOperand, register3: u32, immediate: i32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with5(code, register1, register2, memory.mem, register3, immediate).map_err(to_value_error)? }) } /// Creates an instruction with 5 operands /// /// Args: /// `code` (:class:`Code`): Code value /// `register1` (:class:`Register`): op0: Register /// `register2` (:class:`Register`): op1: Register /// `memory` (:class:`MemoryOperand`): op2: Memory operand /// `register3` (:class:`Register`): op3: Register /// `immediate` (int): (``u32``) op4: Immediate value /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If one of the operands is invalid (basic checks) #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, register1, register2, memory, register3, immediate)")] fn create_reg_reg_mem_reg_u32(code: u32, register1: u32, register2: u32, memory: MemoryOperand, register3: u32, immediate: u32) -> PyResult<Self> { let code = to_code(code)?; let register1 = to_register(register1)?; let register2 = to_register(register2)?; let register3 = to_register(register3)?; Ok(Instruction { instr: iced_x86::Instruction::with5(code, register1, register2, memory.mem, register3, immediate).map_err(to_value_error)? }) } /// Creates a new near/short branch instruction /// /// Args: /// `code` (:class:`Code`): Code value /// `target` (int): (``u64``) Target address /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If the created instruction doesn't have a near branch operand #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, target)")] fn create_branch(code: u32, target: u64) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with_branch(code, target).map_err(to_value_error)? }) } /// Creates a new far branch instruction /// /// Args: /// `code` (:class:`Code`): Code value /// `selector` (int): (``u16``) Selector/segment value /// `offset` (int): (``u32``) Offset /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If the created instruction doesn't have a far branch operand #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(code, selector, offset)")] fn create_far_branch(code: u32, selector: u16, offset: u32) -> PyResult<Self> { let code = to_code(code)?; Ok(Instruction { instr: iced_x86::Instruction::with_far_branch(code, selector, offset).map_err(to_value_error)? }) } /// Creates a new ``XBEGIN`` instruction /// /// Args: /// `bitness` (int): (``u32``) 16, 32, or 64 /// `target` (int): (``u64``) Target address /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `bitness` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(bitness, target)")] fn create_xbegin(bitness: u32, target: u64) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_xbegin(bitness, target).map_err(to_value_error)? }) } /// Creates a ``OUTSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_outsb(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_outsb(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP OUTSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_outsb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_outsb(address_size).map_err(to_value_error)? }) } /// Creates a ``OUTSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_outsw(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_outsw(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP OUTSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_outsw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_outsw(address_size).map_err(to_value_error)? }) } /// Creates a ``OUTSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_outsd(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_outsd(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP OUTSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_outsd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_outsd(address_size).map_err(to_value_error)? }) } /// Creates a ``LODSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_lodsb(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_lodsb(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP LODSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_lodsb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_lodsb(address_size).map_err(to_value_error)? }) } /// Creates a ``LODSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_lodsw(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_lodsw(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP LODSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_lodsw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_lodsw(address_size).map_err(to_value_error)? }) } /// Creates a ``LODSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_lodsd(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_lodsd(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP LODSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_lodsd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_lodsd(address_size).map_err(to_value_error)? }) } /// Creates a ``LODSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_lodsq(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_lodsq(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP LODSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_lodsq(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_lodsq(address_size).map_err(to_value_error)? }) } /// Creates a ``SCASB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_scasb(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_scasb(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE SCASB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_scasb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_scasb(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE SCASB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_scasb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_scasb(address_size).map_err(to_value_error)? }) } /// Creates a ``SCASW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_scasw(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_scasw(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE SCASW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_scasw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_scasw(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE SCASW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_scasw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_scasw(address_size).map_err(to_value_error)? }) } /// Creates a ``SCASD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_scasd(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_scasd(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE SCASD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_scasd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_scasd(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE SCASD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_scasd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_scasd(address_size).map_err(to_value_error)? }) } /// Creates a ``SCASQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_scasq(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_scasq(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE SCASQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_scasq(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_scasq(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE SCASQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_scasq(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_scasq(address_size).map_err(to_value_error)? }) } /// Creates a ``INSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_insb(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_insb(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP INSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_insb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_insb(address_size).map_err(to_value_error)? }) } /// Creates a ``INSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_insw(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_insw(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP INSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_insw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_insw(address_size).map_err(to_value_error)? }) } /// Creates a ``INSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_insd(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_insd(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP INSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_insd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_insd(address_size).map_err(to_value_error)? }) } /// Creates a ``STOSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_stosb(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_stosb(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP STOSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_stosb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_stosb(address_size).map_err(to_value_error)? }) } /// Creates a ``STOSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_stosw(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_stosw(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP STOSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_stosw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_stosw(address_size).map_err(to_value_error)? }) } /// Creates a ``STOSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_stosd(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_stosd(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP STOSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_stosd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_stosd(address_size).map_err(to_value_error)? }) } /// Creates a ``STOSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, rep_prefix = 0)")] #[pyo3(signature = (address_size, rep_prefix = 0))] fn create_stosq(address_size: u32, rep_prefix: u32) -> PyResult<Self> { let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_stosq(address_size, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP STOSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_stosq(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_stosq(address_size).map_err(to_value_error)? }) } /// Creates a ``CMPSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_cmpsb(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_cmpsb(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE CMPSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_cmpsb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_cmpsb(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE CMPSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_cmpsb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_cmpsb(address_size).map_err(to_value_error)? }) } /// Creates a ``CMPSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_cmpsw(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_cmpsw(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE CMPSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_cmpsw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_cmpsw(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE CMPSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_cmpsw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_cmpsw(address_size).map_err(to_value_error)? }) } /// Creates a ``CMPSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_cmpsd(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_cmpsd(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE CMPSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_cmpsd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_cmpsd(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE CMPSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_cmpsd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_cmpsd(address_size).map_err(to_value_error)? }) } /// Creates a ``CMPSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_cmpsq(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_cmpsq(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REPE CMPSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repe_cmpsq(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repe_cmpsq(address_size).map_err(to_value_error)? }) } /// Creates a ``REPNE CMPSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_repne_cmpsq(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_repne_cmpsq(address_size).map_err(to_value_error)? }) } /// Creates a ``MOVSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_movsb(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_movsb(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP MOVSB`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_movsb(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_movsb(address_size).map_err(to_value_error)? }) } /// Creates a ``MOVSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_movsw(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_movsw(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP MOVSW`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_movsw(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_movsw(address_size).map_err(to_value_error)? }) } /// Creates a ``MOVSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_movsd(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_movsd(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP MOVSD`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_movsd(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_movsd(address_size).map_err(to_value_error)? }) } /// Creates a ``MOVSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// `rep_prefix` (:class:`RepPrefixKind`): Rep prefix or :class:`RepPrefixKind.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, segment_prefix = 0, rep_prefix = 0)")] #[pyo3(signature = (address_size, segment_prefix = 0, rep_prefix = 0))] fn create_movsq(address_size: u32, segment_prefix: u32, rep_prefix: u32) -> PyResult<Self> { let segment_prefix = to_register(segment_prefix)?; let rep_prefix = to_rep_prefix_kind(rep_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_movsq(address_size, segment_prefix, rep_prefix).map_err(to_value_error)? }) } /// Creates a ``REP MOVSQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size)")] fn create_rep_movsq(address_size: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::with_rep_movsq(address_size).map_err(to_value_error)? }) } /// Creates a ``MASKMOVQ`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `register1` (:class:`Register`): Register /// `register2` (:class:`Register`): Register /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, register1, register2, segment_prefix = 0)")] #[pyo3(signature = (address_size, register1, register2, segment_prefix = 0))] fn create_maskmovq(address_size: u32, register1: u32, register2: u32, segment_prefix: u32) -> PyResult<Self> { let register1 = to_register(register1)?; let register2 = to_register(register2)?; let segment_prefix = to_register(segment_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_maskmovq(address_size, register1, register2, segment_prefix).map_err(to_value_error)? }) } /// Creates a ``MASKMOVDQU`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `register1` (:class:`Register`): Register /// `register2` (:class:`Register`): Register /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, register1, register2, segment_prefix = 0)")] #[pyo3(signature = (address_size, register1, register2, segment_prefix = 0))] fn create_maskmovdqu(address_size: u32, register1: u32, register2: u32, segment_prefix: u32) -> PyResult<Self> { let register1 = to_register(register1)?; let register2 = to_register(register2)?; let segment_prefix = to_register(segment_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_maskmovdqu(address_size, register1, register2, segment_prefix).map_err(to_value_error)? }) } /// Creates a ``VMASKMOVDQU`` instruction /// /// Args: /// `address_size` (int): (``u32``) 16, 32, or 64 /// `register1` (:class:`Register`): Register /// `register2` (:class:`Register`): Register /// `segment_prefix` (:class:`Register`): Segment override or :class:`Register.NONE` /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `address_size` is not one of 16, 32, 64. #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(address_size, register1, register2, segment_prefix = 0)")] #[pyo3(signature = (address_size, register1, register2, segment_prefix = 0))] fn create_vmaskmovdqu(address_size: u32, register1: u32, register2: u32, segment_prefix: u32) -> PyResult<Self> { let register1 = to_register(register1)?; let register2 = to_register(register2)?; let segment_prefix = to_register(segment_prefix)?; Ok(Instruction { instr: iced_x86::Instruction::with_vmaskmovdqu(address_size, register1, register2, segment_prefix).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0)")] fn create_declare_byte_1(b0: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_1(b0).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1)")] fn create_declare_byte_2(b0: u8, b1: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_2(b0, b1).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2)")] fn create_declare_byte_3(b0: u8, b1: u8, b2: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_3(b0, b1, b2).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3)")] fn create_declare_byte_4(b0: u8, b1: u8, b2: u8, b3: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_4(b0, b1, b2, b3).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4)")] fn create_declare_byte_5(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_5(b0, b1, b2, b3, b4).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5)")] fn create_declare_byte_6(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_6(b0, b1, b2, b3, b4, b5).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6)")] fn create_declare_byte_7(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_7(b0, b1, b2, b3, b4, b5, b6).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7)")] fn create_declare_byte_8(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_8(b0, b1, b2, b3, b4, b5, b6, b7).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8)")] fn create_declare_byte_9(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_9(b0, b1, b2, b3, b4, b5, b6, b7, b8).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// `b9` (int): (``u8``) Byte 9 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9)")] fn create_declare_byte_10(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8, b9: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_10(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// `b9` (int): (``u8``) Byte 9 /// `b10` (int): (``u8``) Byte 10 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10)")] fn create_declare_byte_11(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8, b9: u8, b10: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_11(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// `b9` (int): (``u8``) Byte 9 /// `b10` (int): (``u8``) Byte 10 /// `b11` (int): (``u8``) Byte 11 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11)")] fn create_declare_byte_12(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8, b9: u8, b10: u8, b11: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_12(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// `b9` (int): (``u8``) Byte 9 /// `b10` (int): (``u8``) Byte 10 /// `b11` (int): (``u8``) Byte 11 /// `b12` (int): (``u8``) Byte 12 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12)")] fn create_declare_byte_13(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8, b9: u8, b10: u8, b11: u8, b12: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_13(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// `b9` (int): (``u8``) Byte 9 /// `b10` (int): (``u8``) Byte 10 /// `b11` (int): (``u8``) Byte 11 /// `b12` (int): (``u8``) Byte 12 /// `b13` (int): (``u8``) Byte 13 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13)")] fn create_declare_byte_14(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8, b9: u8, b10: u8, b11: u8, b12: u8, b13: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_14(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// `b9` (int): (``u8``) Byte 9 /// `b10` (int): (``u8``) Byte 10 /// `b11` (int): (``u8``) Byte 11 /// `b12` (int): (``u8``) Byte 12 /// `b13` (int): (``u8``) Byte 13 /// `b14` (int): (``u8``) Byte 14 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14)")] fn create_declare_byte_15(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8, b9: u8, b10: u8, b11: u8, b12: u8, b13: u8, b14: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_15(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `b0` (int): (``u8``) Byte 0 /// `b1` (int): (``u8``) Byte 1 /// `b2` (int): (``u8``) Byte 2 /// `b3` (int): (``u8``) Byte 3 /// `b4` (int): (``u8``) Byte 4 /// `b5` (int): (``u8``) Byte 5 /// `b6` (int): (``u8``) Byte 6 /// `b7` (int): (``u8``) Byte 7 /// `b8` (int): (``u8``) Byte 8 /// `b9` (int): (``u8``) Byte 9 /// `b10` (int): (``u8``) Byte 10 /// `b11` (int): (``u8``) Byte 11 /// `b12` (int): (``u8``) Byte 12 /// `b13` (int): (``u8``) Byte 13 /// `b14` (int): (``u8``) Byte 14 /// `b15` (int): (``u8``) Byte 15 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15)")] fn create_declare_byte_16(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8, b8: u8, b9: u8, b10: u8, b11: u8, b12: u8, b13: u8, b14: u8, b15: u8) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_byte_16(b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15).map_err(to_value_error)? }) } /// Creates a ``db``/``.byte`` asm directive /// /// Args: /// `data` (bytes, bytearray): Data /// /// Returns: /// :class:`Instruction`: Created instruction /// /// Raises: /// ValueError: If `len(data)` is not 1-16 /// TypeError: If `data` is not a supported type #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(data)")] fn create_declare_byte(data: &PyAny) -> PyResult<Self> { let data = unsafe { get_temporary_byte_array_ref(data)? }; Ok(Instruction { instr: iced_x86::Instruction::with_declare_byte(data).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0)")] fn create_declare_word_1(w0: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_1(w0).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// `w1` (int): (``u16``) Word 1 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0, w1)")] fn create_declare_word_2(w0: u16, w1: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_2(w0, w1).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// `w1` (int): (``u16``) Word 1 /// `w2` (int): (``u16``) Word 2 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0, w1, w2)")] fn create_declare_word_3(w0: u16, w1: u16, w2: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_3(w0, w1, w2).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// `w1` (int): (``u16``) Word 1 /// `w2` (int): (``u16``) Word 2 /// `w3` (int): (``u16``) Word 3 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0, w1, w2, w3)")] fn create_declare_word_4(w0: u16, w1: u16, w2: u16, w3: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_4(w0, w1, w2, w3).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// `w1` (int): (``u16``) Word 1 /// `w2` (int): (``u16``) Word 2 /// `w3` (int): (``u16``) Word 3 /// `w4` (int): (``u16``) Word 4 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0, w1, w2, w3, w4)")] fn create_declare_word_5(w0: u16, w1: u16, w2: u16, w3: u16, w4: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_5(w0, w1, w2, w3, w4).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// `w1` (int): (``u16``) Word 1 /// `w2` (int): (``u16``) Word 2 /// `w3` (int): (``u16``) Word 3 /// `w4` (int): (``u16``) Word 4 /// `w5` (int): (``u16``) Word 5 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0, w1, w2, w3, w4, w5)")] fn create_declare_word_6(w0: u16, w1: u16, w2: u16, w3: u16, w4: u16, w5: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_6(w0, w1, w2, w3, w4, w5).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// `w1` (int): (``u16``) Word 1 /// `w2` (int): (``u16``) Word 2 /// `w3` (int): (``u16``) Word 3 /// `w4` (int): (``u16``) Word 4 /// `w5` (int): (``u16``) Word 5 /// `w6` (int): (``u16``) Word 6 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0, w1, w2, w3, w4, w5, w6)")] fn create_declare_word_7(w0: u16, w1: u16, w2: u16, w3: u16, w4: u16, w5: u16, w6: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_7(w0, w1, w2, w3, w4, w5, w6).map_err(to_value_error)? }) } /// Creates a ``dw``/``.word`` asm directive /// /// Args: /// `w0` (int): (``u16``) Word 0 /// `w1` (int): (``u16``) Word 1 /// `w2` (int): (``u16``) Word 2 /// `w3` (int): (``u16``) Word 3 /// `w4` (int): (``u16``) Word 4 /// `w5` (int): (``u16``) Word 5 /// `w6` (int): (``u16``) Word 6 /// `w7` (int): (``u16``) Word 7 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(w0, w1, w2, w3, w4, w5, w6, w7)")] fn create_declare_word_8(w0: u16, w1: u16, w2: u16, w3: u16, w4: u16, w5: u16, w6: u16, w7: u16) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_word_8(w0, w1, w2, w3, w4, w5, w6, w7).map_err(to_value_error)? }) } /// Creates a ``dd``/``.int`` asm directive /// /// Args: /// `d0` (int): (``u32``) Dword 0 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(d0)")] fn create_declare_dword_1(d0: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_dword_1(d0).map_err(to_value_error)? }) } /// Creates a ``dd``/``.int`` asm directive /// /// Args: /// `d0` (int): (``u32``) Dword 0 /// `d1` (int): (``u32``) Dword 1 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(d0, d1)")] fn create_declare_dword_2(d0: u32, d1: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_dword_2(d0, d1).map_err(to_value_error)? }) } /// Creates a ``dd``/``.int`` asm directive /// /// Args: /// `d0` (int): (``u32``) Dword 0 /// `d1` (int): (``u32``) Dword 1 /// `d2` (int): (``u32``) Dword 2 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(d0, d1, d2)")] fn create_declare_dword_3(d0: u32, d1: u32, d2: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_dword_3(d0, d1, d2).map_err(to_value_error)? }) } /// Creates a ``dd``/``.int`` asm directive /// /// Args: /// `d0` (int): (``u32``) Dword 0 /// `d1` (int): (``u32``) Dword 1 /// `d2` (int): (``u32``) Dword 2 /// `d3` (int): (``u32``) Dword 3 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(d0, d1, d2, d3)")] fn create_declare_dword_4(d0: u32, d1: u32, d2: u32, d3: u32) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_dword_4(d0, d1, d2, d3).map_err(to_value_error)? }) } /// Creates a ``dq``/``.quad`` asm directive /// /// Args: /// `q0` (int): (``u64``) Qword 0 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(q0)")] fn create_declare_qword_1(q0: u64) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_qword_1(q0).map_err(to_value_error)? }) } /// Creates a ``dq``/``.quad`` asm directive /// /// Args: /// `q0` (int): (``u64``) Qword 0 /// `q1` (int): (``u64``) Qword 1 /// /// Returns: /// :class:`Instruction`: Created instruction #[rustfmt::skip] #[staticmethod] #[pyo3(text_signature = "(q0, q1)")] fn create_declare_qword_2(q0: u64, q1: u64) -> PyResult<Self> { Ok(Instruction { instr: iced_x86::Instruction::try_with_declare_qword_2(q0, q1).map_err(to_value_error)? }) } // GENERATOR-END: Create fn __format__(&self, format_spec: &str) -> PyResult<String> { self.format(format_spec) } fn __repr__(&self) -> PyResult<String> { self.format("") } fn __str__(&self) -> PyResult<String> { self.format("") } fn __richcmp__(&self, other: PyRef<'_, Instruction>, op: CompareOp) -> PyObject { match op { CompareOp::Eq => (self.instr == other.instr).into_py(other.py()), CompareOp::Ne => (self.instr != other.instr).into_py(other.py()), _ => other.py().NotImplemented(), } } fn __hash__(&self) -> u64 { let mut hasher = DefaultHasher::new(); self.instr.hash(&mut hasher); hasher.finish() } fn __bool__(&self) -> bool { !self.instr.is_invalid() } fn __len__(&self) -> usize { self.instr.len() } } impl Instruction { fn format(&self, format_spec: &str) -> PyResult<String> { enum FormatSpecFmtKind { Fast, Gas, Intel, Masm, Nasm, } let mut fmt_kind = FormatSpecFmtKind::Masm; for c in format_spec.chars() { match c { 'f' => fmt_kind = FormatSpecFmtKind::Fast, 'g' => fmt_kind = FormatSpecFmtKind::Gas, 'i' => fmt_kind = FormatSpecFmtKind::Intel, 'm' => fmt_kind = FormatSpecFmtKind::Masm, 'n' => fmt_kind = FormatSpecFmtKind::Nasm, _ => {} } } let mut fmt_opts = match fmt_kind { FormatSpecFmtKind::Fast => iced_x86::FormatterOptions::with_masm(), FormatSpecFmtKind::Gas => iced_x86::FormatterOptions::with_gas(), FormatSpecFmtKind::Intel => iced_x86::FormatterOptions::with_intel(), FormatSpecFmtKind::Masm => iced_x86::FormatterOptions::with_masm(), FormatSpecFmtKind::Nasm => iced_x86::FormatterOptions::with_nasm(), }; for c in format_spec.chars() { match c { 'f' | 'g' | 'i' | 'm' | 'n' => {} 'X' | 'x' => { fmt_opts.set_uppercase_hex(c == 'X'); fmt_opts.set_hex_prefix("0x"); fmt_opts.set_hex_suffix(""); } 'H' | 'h' => { fmt_opts.set_uppercase_hex(c == 'H'); fmt_opts.set_hex_prefix(""); fmt_opts.set_hex_suffix("h"); } 'r' => fmt_opts.set_rip_relative_addresses(true), 'U' => fmt_opts.set_uppercase_all(true), 's' => fmt_opts.set_space_after_operand_separator(true), 'S' => fmt_opts.set_always_show_segment_register(true), 'B' => fmt_opts.set_show_branch_size(false), 'G' => fmt_opts.set_gas_show_mnemonic_size_suffix(true), 'M' => fmt_opts.set_memory_size_options(iced_x86::MemorySizeOptions::Always), '_' => fmt_opts.set_digit_separator("_"), _ => return Err(PyValueError::new_err(format!("Unknown format specifier '{}' ('{}')", c, format_spec))), } } let mut output = String::new(); match fmt_kind { FormatSpecFmtKind::Fast => { let mut formatter = iced_x86::FastFormatter::new(); formatter.options_mut().set_space_after_operand_separator(fmt_opts.space_after_operand_separator()); formatter.options_mut().set_rip_relative_addresses(fmt_opts.rip_relative_addresses()); formatter.options_mut().set_always_show_segment_register(fmt_opts.always_show_segment_register()); formatter.options_mut().set_always_show_memory_size(fmt_opts.memory_size_options() == iced_x86::MemorySizeOptions::Always); formatter.options_mut().set_uppercase_hex(fmt_opts.uppercase_hex()); formatter.options_mut().set_use_hex_prefix(fmt_opts.hex_prefix() == "0x"); formatter.format(&self.instr, &mut output); } FormatSpecFmtKind::Gas => { use iced_x86::Formatter; let mut formatter = iced_x86::GasFormatter::new(); *formatter.options_mut() = fmt_opts; formatter.format(&self.instr, &mut output); } FormatSpecFmtKind::Intel => { use iced_x86::Formatter; let mut formatter = iced_x86::IntelFormatter::new(); *formatter.options_mut() = fmt_opts; formatter.format(&self.instr, &mut output); } FormatSpecFmtKind::Masm => { use iced_x86::Formatter; let mut formatter = iced_x86::MasmFormatter::new(); *formatter.options_mut() = fmt_opts; formatter.format(&self.instr, &mut output); } FormatSpecFmtKind::Nasm => { use iced_x86::Formatter; let mut formatter = iced_x86::NasmFormatter::new(); *formatter.options_mut() = fmt_opts; formatter.format(&self.instr, &mut output); } }; Ok(output) } } /// Contains the FPU ``TOP`` increment, whether it's conditional and whether the instruction writes to ``TOP`` /// /// Args: /// `increment` (int): (``i32``) Used if `writes_top` is ``True``. Value added to ``TOP``. /// `conditional` (bool): ``True`` if it's a conditional push/pop (eg. ``FPTAN`` or ``FSINCOS``) /// `writes_top` (bool): ``True`` if ``TOP`` is written (it's a conditional/unconditional push/pop, ``FNSAVE``, ``FLDENV``, etc) #[pyclass(module = "iced_x86._iced_x86_py")] pub(crate) struct FpuStackIncrementInfo { info: iced_x86::FpuStackIncrementInfo, } #[pymethods] impl FpuStackIncrementInfo { #[new] #[pyo3(text_signature = "(increment, conditional, writes_top)")] fn new(increment: i32, conditional: bool, writes_top: bool) -> Self { Self { info: iced_x86::FpuStackIncrementInfo::new(increment, conditional, writes_top) } } /// int: (``i32``) Used if :class:`FpuStackIncrementInfo.writes_top` is ``True``. Value added to ``TOP``. /// /// This is negative if it pushes one or more values and positive if it pops one or more values /// and ``0`` if it writes to ``TOP`` (eg. ``FLDENV``, etc) without pushing/popping anything. #[getter] fn increment(&self) -> i32 { self.info.increment() } /// bool: ``True`` if it's a conditional push/pop (eg. ``FPTAN`` or ``FSINCOS``) #[getter] fn conditional(&self) -> bool { self.info.conditional() } /// bool: ``True`` if ``TOP`` is written (it's a conditional/unconditional push/pop, ``FNSAVE``, ``FLDENV``, etc) #[getter] fn writes_top(&self) -> bool { self.info.writes_top() } }
true
aa3d62913fecc40c2ca7973e029b0454fdceb201
Rust
remram44/locked-pancake
/gc/src/lib.rs
UTF-8
4,626
3.140625
3
[]
no_license
use std::cell::RefCell; use std::marker::PhantomData; use std::ops::Deref; use std::ptr::NonNull; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct GcFlag(u8); pub trait Traceable: 'static { fn trace(&self, flag: GcFlag); } pub trait GcAllocator { fn alloc<T: Traceable>(&mut self, value: T) -> GcRef<T>; fn mark<T: Traceable>(&self, gc_ref: GcRef<T>); fn sweep(&mut self); } pub struct SimpleGcAllocator { flag: GcFlag, pub(crate) values: Vec<NonNull<dyn ValueTrait>>, } impl Default for SimpleGcAllocator { fn default() -> SimpleGcAllocator { SimpleGcAllocator { flag: GcFlag(1), values: Vec::new(), } } } trait ValueTrait { fn dealloc(&mut self, flag: GcFlag) -> bool; } impl GcAllocator for SimpleGcAllocator { fn alloc<T: Traceable>(&mut self, value: T) -> GcRef<T> { // Allocate value and GcValue wrapper let gc_value = GcValue { value: Some(value), flag: RefCell::new(GcFlag(0)), }; let ptr: &mut GcValue<T> = Box::leak(Box::new(gc_value)); // Store reference in vec let ptr_t: NonNull<dyn ValueTrait> = { let r: &dyn ValueTrait = ptr; r.into() }; self.values.push(ptr_t.into()); // Return GcRef GcRef { ptr: ptr.into(), phantom: PhantomData, } } fn mark<T: Traceable>(&self, gc_ref: GcRef<T>) { gc_ref.trace_ref(self.flag); } fn sweep(&mut self) { // Sweep let flag = self.flag; self.values.retain(|v| { let v: &mut dyn ValueTrait = unsafe { &mut *v.as_ptr() }; let deleted = v.dealloc(flag); !deleted }); // Switch flag self.flag = GcFlag(match self.flag.0 { 1 => 2, _ => 1, }); } } pub struct GcValue<T: Traceable> { value: Option<T>, flag: RefCell<GcFlag>, } impl<T: Traceable> ValueTrait for GcValue<T> { fn dealloc(&mut self, flag: GcFlag) -> bool { if *self.flag.borrow() != flag { self.value.take(); true } else { false } } } pub struct GcRef<T: Traceable> { ptr: NonNull<GcValue<T>>, phantom: PhantomData<T>, } impl<T: Traceable> Clone for GcRef<T> { fn clone(&self) -> GcRef<T> { GcRef { ptr: self.ptr, phantom: PhantomData, } } } impl<T: Traceable> GcRef<T> { pub fn trace_ref(&self, flag: GcFlag) { let gc_value = self.inner(); let mut flag_ref = gc_value.flag.borrow_mut(); if *flag_ref != flag { *flag_ref = flag; if let Some(ref value) = gc_value.value { value.trace(flag); } } } fn inner(&self) -> &GcValue<T> { unsafe { &*self.ptr.as_ptr() } } } impl<T: Traceable> Deref for GcRef<T> { type Target = T; fn deref(&self) -> &T { let gc_value = self.inner(); match gc_value.value { Some(ref v) => v, None => panic!("Attempt to dereference freed GcRef"), } } } #[cfg(test)] mod tests { use super::{GcAllocator, GcFlag, GcRef, SimpleGcAllocator, Traceable}; enum Value { Integer(i32), Array(Vec<GcRef<Value>>), } impl Traceable for Value { fn trace(&self, flag: GcFlag) { match self { Value::Integer(_) => {} Value::Array(v) => { for elem in v { elem.trace_ref(flag); } } } } } #[test] fn test_gc() { let mut gc: SimpleGcAllocator = Default::default(); let int1 = gc.alloc(Value::Integer(1)); let int2 = gc.alloc(Value::Integer(2)); let int3 = gc.alloc(Value::Integer(3)); let _int4 = gc.alloc(Value::Integer(4)); let arr1 = gc.alloc(Value::Array(vec![int1.clone()])); let _arr2 = gc.alloc(Value::Array(vec![int1.clone(), int2.clone()])); // Mark & sweep gc.mark(arr1.clone()); gc.mark(int3.clone()); gc.sweep(); assert_eq!(gc.values.len(), 3); assert_eq!( gc.values .iter() .map(|v| v.as_ptr() as *const u8) .collect::<Vec<_>>(), vec![int1, int3, arr1] .iter() .map(|v| v.ptr.as_ptr() as *const u8) .collect::<Vec<_>>(), ); } }
true
15c11212f5a751a9b81e4f6a1ddc96b7b1a323c4
Rust
MindFlavor/azure-sdk-for-rust
/sdk/core/src/request_options/if_source_match_condition.rs
UTF-8
1,044
2.84375
3
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
use crate::headers::*; use crate::AddAsHeader; use http::request::Builder; #[derive(Debug, Clone, Copy, PartialEq)] pub enum IfSourceMatchCondition<'a> { Match(&'a str), NotMatch(&'a str), } impl<'a> AddAsHeader for IfSourceMatchCondition<'a> { fn add_as_header(&self, builder: Builder) -> Builder { match self { IfSourceMatchCondition::Match(etag) => builder.header(SOURCE_IF_MATCH, *etag), IfSourceMatchCondition::NotMatch(etag) => builder.header(SOURCE_IF_NONE_MATCH, *etag), } } fn add_as_header2( &self, request: &mut crate::Request, ) -> Result<(), crate::errors::HTTPHeaderError> { let (header_name, header_value) = match self { IfSourceMatchCondition::Match(etag) => (SOURCE_IF_MATCH, etag), IfSourceMatchCondition::NotMatch(etag) => (SOURCE_IF_NONE_MATCH, etag), }; request .headers_mut() .append(header_name, http::HeaderValue::from_str(header_value)?); Ok(()) } }
true
a7af7e0b021b78e0b3bf6b94efeaa9a282df3054
Rust
JonathanBrouwer/aoc2019
/src/day10/main1.rs
UTF-8
3,997
3.390625
3
[]
no_license
#[derive(PartialEq, Debug)] pub struct Point { x: usize, y: usize } pub fn main(input: &str) -> usize { let mut points: Vec<Point> = Vec::new(); input.lines().enumerate().for_each(|(y, l)| { l.chars().enumerate().for_each(|(x, c)| { if c == '#' { points.push(Point {x, y}); } }); }); // Check which points let mut max: usize = 0; let mut point: &Point= &Point{x:0,y:0}; for p1 in &points { let mut count: usize = 0; 'test: for p2 in &points { if p1 == p2 { continue; } for test in &points { if p1 == test || p2 == test { continue; } if is_in_line(p1, p2, test) { continue 'test; } } count += 1; } if(count > max) { point = p1; max = count; } } println!("{:?}", point); return max; } //Does test block the view from p1 to p2? fn is_in_line(a: &Point, b: &Point, target: &Point) -> bool { let a1 = (a.x as f64, a.y as f64); let b1 = (b.x as f64, b.y as f64); let target1 = (target.x as f64, target.y as f64); is_in_line_f64(&a1, &b1, &target1) } fn is_in_line_f64(a: &(f64, f64), b: &(f64, f64), target: &(f64, f64)) -> bool { let dist_1 = dist(a, target); let dist_2 = dist(target, b); let dist_full = dist(a, b); dist_1 + dist_2 - dist_full < 0.00000001 } fn dist(a: &(f64, f64), b: &(f64, f64)) -> f64 { (((a.0 - b.0).powf(2.0) + (a.1 - b.1).powf(2.0)) as f64).sqrt() } pub fn points_intersect(p1: &Point, p2: &Point, test: &Point) -> bool { let slope_tp1 = ((test.y as f64 - p1.y as f64)) /((test.x as f64-p1.x as f64)); let slope_p2p1 = ((p2.y as f64- p1.y as f64)) /((p2.x as f64-p1.x as f64)); if ((slope_p2p1.is_infinite() && slope_tp1.is_infinite()) || (slope_tp1-slope_p2p1).abs() < 0.000001) { return manhatten_dist(test, p1) < manhatten_dist(p2, p1); } return false; } pub fn manhatten_dist(p1: &Point, p2: &Point) -> usize { return (p1.x as i64 - p2.x as i64).abs() as usize + (p1.y as i64 - p2.y as i64).abs() as usize; } #[cfg(test)] mod test { use crate::day10::main1::main; #[test] fn test_day8_part1_1() { let input = ".#..# ..... ##### ....# ...##"; let result = main(input); assert_eq!(result, 8); } #[test] fn test_day8_part1_2() { let input = "......#.#. #..#.#.... ..#######. .#.#.###.. .#..#..... ..#....#.# #..#....#. .##.#..### ##...#..#. .#....####"; let result = main(input); assert_eq!(result, 33); } #[test] fn test_day8_part1_3() { let input = "#.#...#.#. .###....#. .#....#... ##.#.#.#.# ....#.#.#. .##..###.# ..#...##.. ..##....## ......#... .####.###."; let result = main(input); assert_eq!(result, 35); } #[test] fn test_day8_part1_4() { let input = ".#..#..### ####.###.# ....###.#. ..###.##.# ##.##.#.#. ....###..# ..#.#..#.# #..#.#.### .##...##.# .....#.#.."; let result = main(input); assert_eq!(result, 41); } #[test] fn test_day8_part1_5() { let input = ".#..##.###...####### ##.############..##. .#.######.########.# .###.#######.####.#. #####.##.#.##.###.## ..#####..#.######### #################### #.####....###.#.#.## ##.################# #####.##.###..####.. ..######..##.####### ####.##.####...##..# .#####..#.######.### ##...#.##########... #.##########.####### .####.#.###.###.#.## ....##.##.###..##### .#.#.###########.### #.#.#.#####.####.### ###.##.####.##.#..##"; let result = main(input); assert_eq!(result, 210); } #[test] fn test_main_real() { let input = include_str!("input.txt"); let result = main(input); println!("Result: {}", result); } }
true