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
71ab0bfcbe04301a4e8b5d8d853b6f4bf29369ae
Rust
blue-yonder/vikos
/examples/mean.rs
UTF-8
851
2.859375
3
[ "MIT" ]
permissive
use vikos::{cost, learn_history, teacher}; fn main() { // mean is 9, but of course we do not know that yet let history = [1.0, 3.0, 4.0, 7.0, 8.0, 11.0, 29.0]; // The mean is just a simple number ... let mut model = 0.0; // ... which minimizes the square error let cost = cost::LeastSquares {}; // Use stochasic gradient descent with an annealed learning rate let teacher = teacher::GradientDescentAl { l0: 0.3, t: 4.0 }; // Train 100 (admitettly repetitive) events // We use the `map` iterator adaptor to extend an empty feature vector to each data point learn_history( &teacher, &cost, &mut model, history.iter().cycle().take(100).map(|&y| ((), y)), ); // Since we know the model's type is `Constant`, we could just access the members println!("{}", model); }
true
dcb94b53ba8b09b982417a2239edaf52193ab098
Rust
pygaur/Rust-Training
/examples/10-generics-traits-lifetimes/simple_generics.rs
UTF-8
787
3.890625
4
[]
no_license
use std::fmt::Debug; fn display<T: Debug>(x: T) { println!("{:?}", x); } // fn largest<T>(i: T, j: T) -> T { // if i > j { // return i // } else { // return j // } // } // fn largest(i: i32, j: i32) -> i32 { // if i > j { // return i // } else { // return j // } // } // fn largest(i: &str, j: &str) -> &str { // if i > j { // return i // } else { // return j // } // } #[derive(Debug)] struct Point(i32, i32); fn main() { let x = 10.12; display(x); display("Hello"); display(Point(10, 12)); // let (a, b) = (10, 12); // println!("The largest is: {}", largest(a, b)); // let (a, b) = ("hello", "hi"); // println!("The largest is: {}", largest(a, b)); }
true
8ecdd5e0b59aec505a41d053b04281018f94a0b7
Rust
FranklinChen/immutable-list-rust
/src/lib.rs
UTF-8
8,083
3.515625
4
[]
no_license
//! Immmutable, persistent list as in FP languages. use std::mem; /// Use reference counting instead of GC for sharing. use std::rc::Rc; /// Simplest possible definition of an immutable list as in FP. /// /// A `List` is either empty or a shared pointer to a `Cons` cell. #[derive(PartialEq, Debug)] pub struct List<T>(Option<Rc<Cons<T>>>); #[derive(PartialEq, Debug)] pub struct Cons<T> { elem: T, next: List<T>, } impl<T> Cons<T> { #[inline(always)] pub fn new(elem: T, next: List<T>) -> Self { Cons { elem, next } } #[inline(always)] pub fn singleton(elem: T) -> Self { Cons::new(elem, List::empty()) } } #[macro_export] macro_rules! list { [] => (List::empty()); [$x:expr] => (List::singleton($x)); [$x:expr, $($xs:expr),*] => ( list!($($xs),*).into_cons($x) ) } impl<T> Clone for List<T> { /// Just bump up the reference count. #[inline(always)] fn clone(&self) -> Self { List(self.0.clone()) } } impl<T> List<T> { #[inline(always)] pub fn try_as_ref(&self) -> Option<&Rc<Cons<T>>> { self.0.as_ref() } #[inline(always)] pub fn head(&self) -> Option<&T> { self.try_as_ref().map(|r| &r.elem) } #[inline(always)] pub fn tail(&self) -> Option<&List<T>> { self.try_as_ref().map(|r| &r.next) } /// Bump up reference count when returning the tail of the list. #[inline(always)] pub fn into_tail(&self) -> Option<List<T>> { self.tail().cloned() } #[inline(always)] pub fn empty() -> Self { List(None) } /// OO API is backwards from FP, but does same thing, prepending. /// /// This variant does not take ownership of the new tail. #[inline(always)] pub fn cons(&self, elem: T) -> Self { List(Some(Rc::new(Cons::new(elem, self.clone())))) } /// Special version of cons that takes ownership of the new tail. #[inline(always)] pub fn into_cons(self, elem: T) -> Self { List(Some(Rc::new(Cons::new(elem, self)))) } #[inline(always)] pub fn singleton(elem: T) -> Self { List(Some(Rc::new(Cons::singleton(elem)))) } /// Danger of stack overflow because of non-tail recursion. #[inline(always)] pub fn map_recursive<U, F>(&self, f: F) -> List<U> where F: Fn(&T) -> U, { self.map_recursive_helper(&f) } /// Danger of stack overflow because of non-tail recursion. /// /// Use `into_cons` because nobody else sees the intermediate /// list. fn map_recursive_helper<U, F>(&self, f: &F) -> List<U> where F: Fn(&T) -> U, { match self.try_as_ref() { None => List::empty(), Some(r) => r.next.map_recursive_helper(f).into_cons(f(&r.elem)), } } /// Iterative rather than recursive. pub fn map<U, F>(&self, f: F) -> List<U> where F: Fn(&T) -> U, { match self.try_as_ref() { None => List::empty(), Some(r) => { // New Cons, with an initially empty tail. let first = Rc::new(Cons::singleton(f(&r.elem))); let first_ptr: *mut Cons<U> = unsafe { // Turn *const to just * mem::transmute(Rc::into_raw(first)) }; // Pointer to next in current cell. // We want to write in a new next. let mut current_ptr = first_ptr; let mut self_remaining = &r.next; while let Some(r) = self_remaining.try_as_ref() { let new_rc = Rc::new(Cons::singleton(f(&r.elem))); let next_ptr: *mut Cons<U> = unsafe { mem::transmute(Rc::into_raw(new_rc)) }; // Patch in the new tail. unsafe { (*current_ptr).next = List(Some(Rc::from_raw(next_ptr))); } current_ptr = next_ptr; self_remaining = &r.next; } List(Some(unsafe { Rc::from_raw(first_ptr) })) } } } } impl<T: Clone> List<T> { /// Append a copy of `xs` to `ys`, preserving `ys` through structural /// sharing. pub fn append(&self, other: &List<T>) -> List<T> { match self.try_as_ref() { None => match other.try_as_ref() { None => List::empty(), Some(r) => // Here's where we increase the reference count. { List(Some(r.clone())) } }, Some(r) => // Recursive append our tail, then prepend a clone of elem. { r.next.append(other).into_cons(r.elem.clone()) } } } } impl<T> List<T> { /// List identity rather than structural equality. /// /// Use unsafe hacking! But it is unlikely `Rc` will be anything /// other than a pointer to stuff, so this should be OK. pub fn same(&self, other: &List<T>) -> bool { match (self.try_as_ref(), other.try_as_ref()) { (Some(self_rc), Some(other_rc)) => Rc::ptr_eq(self_rc, other_rc), (None, None) => true, (_, _) => false, } } } #[cfg(test)] mod test { use super::*; /// [0, 1, 2] fn list_012() -> List<usize> { List::empty().into_cons(2).into_cons(1).into_cons(0) } /// [3, 4, 5] fn list_345() -> List<usize> { List::empty().into_cons(5).into_cons(4).into_cons(3) } fn list_012345() -> List<usize> { List::empty() .into_cons(5) .into_cons(4) .into_cons(3) .into_cons(2) .into_cons(1) .into_cons(0) } #[test] fn sharing_with_immutable_cons_compiles() { let list1 = list_012(); let _x = list1.cons(100); let _y = list1.cons(200); } #[test] fn equal_by_structure() { let list1 = list_012(); let list2 = list_012(); assert_eq!(list1, list2); } #[test] fn equal_but_not_same_list() { let list1 = list_012(); let list2 = list_012(); assert!(!list1.same(&list2)); } #[test] fn same_as_itself() { let list1 = list_012(); assert!(list1.same(&list1)); } impl<T> List<T> { fn unsafe_into_tail(&self) -> List<T> { self.into_tail().unwrap() } } #[test] fn append_copies_first_and_shares_second() { let list1 = list_012(); let list2 = list_345(); let result = list1.append(&list2); let fresh = list_012345(); // Equal but not the same as a fresh list. assert_eq!(result, fresh); assert!(!result.same(&fresh)); // Walk over to the sharing point. let sublist = result .unsafe_into_tail() .unsafe_into_tail() .unsafe_into_tail(); assert_eq!(sublist, list2); // Sublist within result is the same as original second list. assert!(sublist.same(&list2)); } #[test] fn map_recursive_works() { let list1 = list_012(); let list2 = list_345(); let result = list1.map_recursive(|x| x + 3); assert_eq!(result, list2); } #[test] fn test_list_macro_empty() { let l: List<i32> = list![]; assert_eq!(None, l.head()); } #[test] fn test_list_macro_one_element() { let l: List<i32> = list![1]; assert_eq!(1, *l.head().unwrap()); } #[test] fn test_list_macro() { let l: List<i32> = list![1, 2, 3, 4, 5]; assert_eq!(1, *l.head().unwrap()); assert_eq!(2, *l.tail().map(List::head).unwrap().unwrap()); } #[test] fn map_iterative_works() { let list1 = list_012(); let list2 = list_345(); let result = list1.map(|x| x + 3); assert_eq!(result, list2); } }
true
d47e09f0392b9c3e9aa64dbbb20c0d8773f3c982
Rust
5HT-ST0LE-THIS-PROJECT/n2o-1
/src/io/unix/errno.rs
UTF-8
9,042
2.953125
3
[]
no_license
use libc::{c_int, c_char}; use std::ffi::CStr; use libc; use std::{self, fmt}; use core; #[derive(Clone, Copy, Debug, PartialEq)] pub enum Error { Sys(Errno), InvalidPath, } impl Error { pub fn from_errno(errno: Errno) -> Error { Error::Sys(errno) } pub fn last() -> Error { Error::Sys(Errno::last()) } pub fn invalid_argument() -> Error { Error::Sys(Errno(22)) // EINVAL } pub fn errno(&self) -> Errno { match *self { Error::Sys(errno) => errno, Error::InvalidPath => Errno(22), // EINVAL } } } impl From<Errno> for Error { fn from(errno: Errno) -> Error { Error::from_errno(errno) } } impl std::error::Error for Error { fn description(&self) -> &str { match self { &Error::InvalidPath => "Invalid path", &Error::Sys(ref errno) => errno.desc(), } } } #[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Debug)] pub struct Errno(pub c_int); impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Error::InvalidPath => write!(f, "Invalid path"), &Error::Sys(errno) => write!(f, "{:?}: {}", errno, errno.desc()), } } } impl fmt::Display for Errno { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut buf = [0 as c_char; 1024]; unsafe { if strerror_r(self.0, buf.as_mut_ptr(), buf.len() as libc::size_t) < 0 { let Errno(fm_err) = errno(); if fm_err != libc::ERANGE { return write!(fmt, "OS Error {} (strerror_r returned error {})", self.0, fm_err); } } } let c_str = unsafe { CStr::from_ptr(buf.as_ptr()) }; fmt.write_str(&String::from_utf8_lossy(c_str.to_bytes())) } } pub fn errno() -> Errno { unsafe { Errno(*errno_location()) } } pub fn set_errno(Errno(errno): Errno) { unsafe { *errno_location() = errno; } } extern "C" { #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os = "freebsd"), link_name = "__error")] #[cfg_attr(target_os = "linux", link_name = "__errno_location")] fn errno_location() -> *mut c_int; #[cfg_attr(target_os = "linux", link_name = "__xpg_strerror_r")] fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int; } pub trait ErrnoSentinel: Sized { fn sentinel() -> Self; } impl ErrnoSentinel for isize { fn sentinel() -> Self { -1 } } impl ErrnoSentinel for i32 { fn sentinel() -> Self { -1 } } impl ErrnoSentinel for i64 { fn sentinel() -> Self { -1 } } pub fn sys_errno() -> i32 { unsafe { (*errno_location()) as i32 } } pub fn last() -> Errno { Errno(sys_errno()) } unsafe fn clear() -> () { *errno_location() = 0; } pub fn int(errno: Errno) -> i32 { return errno.0; } pub enum ErrConst { UnknownErrno = 0, EPERM = 1, ENOENT = 2, ESRCH = 3, EINTR = 4, EIO = 5, ENXIO = 6, E2BIG = 7, ENOEXEC = 8, EBADF = 9, ECHILD = 10, EDEADLK = 11, ENOMEM = 12, EACCES = 13, EFAULT = 14, ENOTBLK = 15, EBUSY = 16, EEXIST = 17, EXDEV = 18, ENODEV = 19, ENOTDIR = 20, EISDIR = 21, EINVAL = 22, ENFILE = 23, EMFILE = 24, ENOTTY = 25, ETXTBSY = 26, EFBIG = 27, ENOSPC = 28, ESPIPE = 29, EROFS = 30, EMLINK = 31, EPIPE = 32, EDOM = 33, ERANGE = 34, EAGAIN = 35, EINPROGRESS = 36, EALREADY = 37, ENOTSOCK = 38, EDESTADDRREQ = 39, EMSGSIZE = 40, EPROTOTYPE = 41, ENOPROTOOPT = 42, EPROTONOSUPPORT = 43, ESOCKTNOSUPPORT = 44, // ENOTSUP = 45, EPFNOSUPPORT = 46, EAFNOSUPPORT = 47, EADDRINUSE = 48, EADDRNOTAVAIL = 49, ENETDOWN = 50, ENETUNREACH = 51, ENETRESET = 52, ECONNABORTED = 53, ECONNRESET = 54, ENOBUFS = 55, EISCONN = 56, ENOTCONN = 57, ESHUTDOWN = 58, ETOOMANYREFS = 59, ETIMEDOUT = 60, ECONNREFUSED = 61, ELOOP = 62, ENAMETOOLONG = 63, EHOSTDOWN = 64, EHOSTUNREACH = 65, ENOTEMPTY = 66, ENOLCK = 77, ENOSYS = 78, ENOMSG = 83, EIDRM = 82, EMAXIM = 10000000, } pub fn desc(errno: Errno) -> &'static str { let m: ErrConst = unsafe { core::mem::transmute::<i32, ErrConst>(errno.0) }; match m { ErrConst::UnknownErrno => "Unknown errno", ErrConst::EPERM => "Operation not permitted", ErrConst::ENOENT => "No such file or directory", ErrConst::ESRCH => "No such process", ErrConst::EINTR => "Interrupted system call", ErrConst::EIO => "I/O error", ErrConst::ENXIO => "No such device or address", ErrConst::E2BIG => "Argument list too long", ErrConst::ENOEXEC => "Exec format error", ErrConst::EBADF => "Bad file number", ErrConst::ECHILD => "No child processes", ErrConst::EAGAIN => "Try again", ErrConst::ENOMEM => "Out of memory", ErrConst::EACCES => "Permission denied", ErrConst::EFAULT => "Bad address", ErrConst::ENOTBLK => "Block device required", ErrConst::EBUSY => "Device or resource busy", ErrConst::EEXIST => "File exists", ErrConst::EXDEV => "Cross-device link", ErrConst::ENODEV => "No such device", ErrConst::ENOTDIR => "Not a directory", ErrConst::EISDIR => "Is a directory", ErrConst::EINVAL => "Invalid argument", ErrConst::ENFILE => "File table overflow", ErrConst::EMFILE => "Too many open files", ErrConst::ENOTTY => "Not a typewriter", ErrConst::ETXTBSY => "Text file busy", ErrConst::EFBIG => "File too large", ErrConst::ENOSPC => "No space left on device", ErrConst::ESPIPE => "Illegal seek", ErrConst::EROFS => "Read-only file system", ErrConst::EMLINK => "Too many links", ErrConst::EPIPE => "Broken pipe", ErrConst::EDOM => "Math argument out of domain of func", ErrConst::ERANGE => "Math result not representable", ErrConst::EDEADLK => "Resource deadlock would occur", ErrConst::ENAMETOOLONG => "File name too long", ErrConst::ENOLCK => "No record locks available", ErrConst::ENOSYS => "Function not implemented", ErrConst::ENOTEMPTY => "Directory not empty", ErrConst::ELOOP => "Too many symbolic links encountered", ErrConst::ENOMSG => "No message of desired type", ErrConst::EIDRM => "Identifier removed", ErrConst::EINPROGRESS => "Operation now in progress", ErrConst::EALREADY => "Operation already in progress", ErrConst::ENOTSOCK => "Socket operation on non-socket", ErrConst::EDESTADDRREQ => "Destination address required", ErrConst::EMSGSIZE => "Message too long", ErrConst::EPROTOTYPE => "Protocol wrong type for socket", ErrConst::ENOPROTOOPT => "Protocol not available", ErrConst::EPROTONOSUPPORT => "Protocol not supported", ErrConst::ESOCKTNOSUPPORT => "Socket type not supported", ErrConst::EPFNOSUPPORT => "Protocol family not supported", ErrConst::EAFNOSUPPORT => "Address family not supported by protocol", ErrConst::EADDRINUSE => "Address already in use", ErrConst::EADDRNOTAVAIL => "Cannot assign requested address", ErrConst::ENETDOWN => "Network is down", ErrConst::ENETUNREACH => "Network is unreachable", ErrConst::ENETRESET => "Network dropped connection because of reset", ErrConst::ECONNABORTED => "Software caused connection abort", ErrConst::ECONNRESET => "Connection reset by peer", ErrConst::ENOBUFS => "No buffer space available", ErrConst::EISCONN => "Transport endpoint is already connected", ErrConst::ENOTCONN => "Transport endpoint is not connected", ErrConst::ESHUTDOWN => "Cannot send after transport endpoint shutdown", ErrConst::ETOOMANYREFS => "Too many references: cannot splice", ErrConst::ETIMEDOUT => "Connection timed out", ErrConst::ECONNREFUSED => "Connection refused", ErrConst::EHOSTDOWN => "Host is down", ErrConst::EHOSTUNREACH => "No route to host", ErrConst::EMAXIM => "", } } impl Errno { pub fn last() -> Self { last() } pub fn desc(self) -> &'static str { desc(self) } pub unsafe fn clear() -> () { clear() } pub fn result<S: ErrnoSentinel + PartialEq<S>>(value: S) -> Result<S> { if value == S::sentinel() { Err(Error::Sys(Self::last())) } else { Ok(value) } } } pub type Result<T> = std::result::Result<T, Error>;
true
ff0d5229fb6b76c5370dabf0296b56b3a80042a0
Rust
mdesmet/kvstore
/src/kv.rs
UTF-8
6,939
3.359375
3
[]
no_license
use failure::Error; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs; use std::io::{BufRead, BufReader, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; /// `Result` will contain the result of a `KvStore` operation pub type Result<T> = std::result::Result<T, Error>; /// `KvStore` is a simple-to-use, efficient key value store pub struct KvStore { path: PathBuf, store: fs::File, map: HashMap<String, u64>, } #[derive(Serialize, Deserialize)] #[serde(tag = "type")] enum Command { Write { key: String, value: String }, Remove { key: String }, } impl KvStore { /// Opens a database file pub fn open(path: &Path) -> Result<KvStore> { let path = path.join("db.json"); let file = fs::OpenOptions::new() .read(true) .create(true) .append(true) .open(&path)?; let mut kv_store = KvStore { path, store: file, map: HashMap::new(), }; kv_store.create_map()?; Ok(kv_store) } /// sets or updates the value in the key value store at the requested key /// /// # Examples /// /// ``` /// use kvs::KvStore; /// use std::path::Path; /// let mut kv = KvStore::open(Path::new(".")).expect("Could not open file"); /// kv.set("key".to_owned(), "value".to_owned()).expect("Could not set key"); /// ``` pub fn set(&mut self, key: String, value: String) -> Result<()> { self.write_record(Command::Write { key: key.to_owned(), value: value.to_owned(), })?; Ok(()) } /// `get(key)` retrieves the value in the key value store at the requested key /// # Examples /// /// ``` /// use kvs::KvStore; /// use std::path::Path; /// let mut kv = KvStore::open(Path::new(".")).expect("Could not open file");; /// kv.set("key".to_owned(), "value".to_owned()).expect("Could not set value");; /// assert_eq!(Some("value".to_owned()), kv.get("key".to_owned()).expect("Could not get key")); /// ``` // - "get" // - The user invokes `kvs get mykey` // - `kvs` reads the entire log, one command at a time, recording the // affected key and file offset of the command to an in-memory _key -> log // pointer_ map // - It then checks the map for the log pointer // - If it fails, it prints "Key not found", and exits with exit code 0 // - If it succeeds // - It deserializes the command to get the last recorded value of the key // - It prints the value to stdout and exits with exit code 0 pub fn get(&mut self, key: String) -> Result<Option<String>> { let position = self.map.get(&key).cloned(); match position { Some(position) => { let record = self.read_record(position)?; match record { Some(Command::Write { key: _, value }) => Ok(Some(value.to_owned())), _ => Ok(None), } } None => Ok(None), } } /// `get(key)` removes the value in the key value store at the requested key /// # Examples /// /// ``` /// use kvs::KvStore; /// use std::path::Path; /// let mut kv = KvStore::open(Path::new(".")).expect("Could not open file");; /// kv.set("key".to_owned(), "value".to_owned()); /// kv.remove("key".to_owned()).expect("Could not remove key");; /// assert_eq!(None, kv.get("key".to_owned()).expect("could not get key")); /// ``` pub fn remove(&mut self, key: String) -> Result<()> { let value = self.get(key.to_owned())?; match value { Some(_) => { self.write_record(Command::Remove { key: key.to_owned(), })?; Ok(()) } None => Err(failure::err_msg("Key not found")), } } fn write_record(&mut self, command: Command) -> Result<()> { let mut file = &self.store; let position = file.seek(SeekFrom::End(0))?; { let mut command = serde_json::to_string(&command)?; command.push_str("\n"); file.write_all(command.as_bytes())?; } match command { Command::Write { key, value: _ } => { self.map.insert(key.to_owned(), position); } Command::Remove { key } => { self.map.remove(&key); } } self.compact_log()?; self.create_map()?; Ok(()) } fn read_record(&mut self, position: u64) -> Result<Option<Command>> { let mut reader = BufReader::new(&self.store); reader.seek(SeekFrom::Start(position))?; let mut buffer = String::new(); let len = reader.read_line(&mut buffer)?; if len == 0 { return Ok(None); } Ok(Some(serde_json::from_str(&buffer)?)) } fn create_map(&mut self) -> Result<()> { let mut reader = BufReader::new(&self.store); reader.seek(SeekFrom::Start(0))?; loop { let mut buffer = String::new(); let position = reader.seek(SeekFrom::Current(0))?; let result = reader.read_line(&mut buffer)?; match result { 0 => break, _ => { let command = serde_json::from_str(&buffer); match command { Ok(Command::Write { key, value: _ }) => { self.map.insert(key.to_owned(), position); } Ok(Command::Remove { key }) => { self.map.remove(&key); } Err(_) => continue, } } } } Ok(()) } fn compact_log(&mut self) -> Result<()> { let current_file_name = &self.path; let mut new_file_name = Path::new(&self.path).to_path_buf(); new_file_name.set_extension("json.temp"); let mut reader = BufReader::new(&self.store); reader.seek(SeekFrom::Start(0))?; let mut new_file = std::fs::OpenOptions::new() .create(true) .write(true) .open(Path::new(&new_file_name))?; for (_, position) in &self.map { let mut buffer = String::new(); reader.seek(SeekFrom::Start(*position))?; reader.read_line(&mut buffer)?; buffer.push_str("\n"); new_file.write(&buffer.as_bytes())?; } fs::rename(new_file_name, current_file_name)?; self.store = std::fs::OpenOptions::new() .read(true) .create(true) .append(true) .open(&current_file_name)?; Ok(()) } }
true
38a69360da046c6507fc23894794c831f78f4148
Rust
xacrimon/dashmap
/src/try_result.rs
UTF-8
1,665
3.640625
4
[ "MIT" ]
permissive
/// Represents the result of a non-blocking read from a [DashMap](crate::DashMap). #[derive(Debug)] pub enum TryResult<R> { /// The value was present in the map, and the lock for the shard was successfully obtained. Present(R), /// The shard wasn't locked, and the value wasn't present in the map. Absent, /// The shard was locked. Locked, } impl<R> TryResult<R> { /// Returns `true` if the value was present in the map, and the lock for the shard was successfully obtained. pub fn is_present(&self) -> bool { matches!(self, TryResult::Present(_)) } /// Returns `true` if the shard wasn't locked, and the value wasn't present in the map. pub fn is_absent(&self) -> bool { matches!(self, TryResult::Absent) } /// Returns `true` if the shard was locked. pub fn is_locked(&self) -> bool { matches!(self, TryResult::Locked) } /// If `self` is [Present](TryResult::Present), returns the reference to the value in the map. /// Panics if `self` is not [Present](TryResult::Present). pub fn unwrap(self) -> R { match self { TryResult::Present(r) => r, TryResult::Locked => panic!("Called unwrap() on TryResult::Locked"), TryResult::Absent => panic!("Called unwrap() on TryResult::Absent"), } } /// If `self` is [Present](TryResult::Present), returns the reference to the value in the map. /// If `self` is not [Present](TryResult::Present), returns `None`. pub fn try_unwrap(self) -> Option<R> { match self { TryResult::Present(r) => Some(r), _ => None, } } }
true
d9390fcd3c455271ec95e6c5aaaf7f60574f92e0
Rust
erglabs/arti
/crates/tor-dirmgr/src/docid.rs
UTF-8
6,915
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
//! Declare a general purpose "document ID type" for tracking which //! documents we want and which we have. use std::{borrow::Borrow, collections::HashMap}; use tor_dirclient::request; use tor_netdoc::doc::{ authcert::AuthCertKeyIds, microdesc::MdDigest, netstatus::ConsensusFlavor, routerdesc::RdDigest, }; /// The identity of a single document, in enough detail to load it /// from storage. #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] #[non_exhaustive] pub enum DocId { /// A request for the most recent consensus document. LatestConsensus { /// The flavor of consensus to request. flavor: ConsensusFlavor, /// Rules for loading this consensus from the cache. cache_usage: CacheUsage, }, /// A request for an authority certificate, by the SHA1 digests of /// its identity key and signing key. AuthCert(AuthCertKeyIds), /// A request for a single microdescriptor, by SHA256 digest. Microdesc(MdDigest), /// A request for the router descriptor of a public relay, by SHA1 /// digest. RouterDesc(RdDigest), } /// The underlying type of a DocId. /// /// Documents with the same type can be grouped into the same query; others /// cannot. #[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)] #[non_exhaustive] pub(crate) enum DocType { /// A consensus document Consensus(ConsensusFlavor), /// An authority certificate AuthCert, /// A microdescriptor Microdesc, /// A router descriptor. RouterDesc, } impl DocId { /// Return the associated doctype of this DocId. pub(crate) fn doctype(&self) -> DocType { use DocId::*; use DocType as T; match self { LatestConsensus { flavor: f, .. } => T::Consensus(*f), AuthCert(_) => T::AuthCert, Microdesc(_) => T::Microdesc, RouterDesc(_) => T::RouterDesc, } } } /// A request for a specific kind of directory resource that a DirMgr can /// request. #[derive(Clone, Debug)] pub(crate) enum ClientRequest { /// Request for a consensus Consensus(request::ConsensusRequest), /// Request for one or more authority certificates AuthCert(request::AuthCertRequest), /// Request for one or more microdescriptors Microdescs(request::MicrodescRequest), /// Request for one or more router descriptors RouterDescs(request::RouterDescRequest), } impl ClientRequest { /// Turn a ClientRequest into a Requestable. pub(crate) fn as_requestable(&self) -> &(dyn request::Requestable + Send + Sync) { use ClientRequest::*; match self { Consensus(a) => a, AuthCert(a) => a, Microdescs(a) => a, RouterDescs(a) => a, } } } /// Description of how to start out a given bootstrap attempt. #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub enum CacheUsage { /// The bootstrap attempt will only use the cache. Therefore, don't /// load a pending consensus from the cache, since we won't be able /// to find enough information to make it usable. CacheOnly, /// The bootstrap attempt is willing to download information or to /// use the cache. Therefore, we want the latest cached /// consensus, whether it is pending or not. CacheOkay, /// The bootstrap attempt is trying to fetch a new consensus. Therefore, /// we don't want a consensus from the cache. MustDownload, } impl CacheUsage { /// Turn this CacheUsage into a pending field for use with /// SqliteStorage. pub(crate) fn pending_requirement(&self) -> Option<bool> { match self { CacheUsage::CacheOnly => Some(false), _ => None, } } } /// A group of DocIds that can be downloaded or loaded from the database /// together. /// /// TODO: Perhaps this should be the same as ClientRequest? #[derive(Clone, Debug)] pub(crate) enum DocQuery { /// A request for the latest consensus LatestConsensus { /// A desired flavor of consensus flavor: ConsensusFlavor, /// Whether we can or must use the cache cache_usage: CacheUsage, }, /// A request for authority certificates AuthCert(Vec<AuthCertKeyIds>), /// A request for microdescriptors Microdesc(Vec<MdDigest>), /// A request for router descriptors RouterDesc(Vec<RdDigest>), } impl DocQuery { /// Construct an "empty" docquery from the given DocId pub(crate) fn empty_from_docid(id: &DocId) -> Self { match *id { DocId::LatestConsensus { flavor, cache_usage, } => Self::LatestConsensus { flavor, cache_usage, }, DocId::AuthCert(_) => Self::AuthCert(Vec::new()), DocId::Microdesc(_) => Self::Microdesc(Vec::new()), DocId::RouterDesc(_) => Self::RouterDesc(Vec::new()), } } /// Add `id` to this query, if possible. fn push(&mut self, id: DocId) { match (self, id) { (Self::LatestConsensus { .. }, DocId::LatestConsensus { .. }) => {} (Self::AuthCert(ids), DocId::AuthCert(id)) => ids.push(id), (Self::Microdesc(ids), DocId::Microdesc(id)) => ids.push(id), (Self::RouterDesc(ids), DocId::RouterDesc(id)) => ids.push(id), (_, _) => panic!(), } } /// If this query contains too many documents to download with a single /// request, divide it up. pub(crate) fn split_for_download(self) -> Vec<Self> { use DocQuery::*; /// How many objects can be put in a single HTTP GET line? const N: usize = 500; match self { LatestConsensus { .. } => vec![self], AuthCert(mut v) => { v.sort_unstable(); v[..].chunks(N).map(|s| AuthCert(s.to_vec())).collect() } Microdesc(mut v) => { v.sort_unstable(); v[..].chunks(N).map(|s| Microdesc(s.to_vec())).collect() } RouterDesc(mut v) => { v.sort_unstable(); v[..].chunks(N).map(|s| RouterDesc(s.to_vec())).collect() } } } } impl From<DocId> for DocQuery { fn from(d: DocId) -> DocQuery { let mut result = DocQuery::empty_from_docid(&d); result.push(d); result } } /// Given a list of DocId, split them up into queries, by type. pub(crate) fn partition_by_type<T>(collection: T) -> HashMap<DocType, DocQuery> where T: IntoIterator<Item = DocId>, { let mut result = HashMap::new(); for item in collection.into_iter() { let b = item.borrow(); let tp = b.doctype(); result .entry(tp) .or_insert_with(|| DocQuery::empty_from_docid(b)) .push(item); } result }
true
5f7a02be1c14f5492881bcba27076e0142c695bd
Rust
mesalock-linux/crates-sgx
/vendor/sgx_tstd/src/io/buffered.rs
UTF-8
23,971
3.0625
3
[ "Apache-2.0" ]
permissive
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // 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.. //! Buffering wrappers for I/O traits use crate::io::prelude::*; use crate::error; use crate::io::{ self, Error, ErrorKind, Initializer, IoSlice, IoSliceMut, SeekFrom, DEFAULT_BUF_SIZE, }; use crate::memchr; use core::cmp; use core::fmt; /// The `BufReader` struct adds buffering to any reader. /// /// It can be excessively inefficient to work directly with a [`Read`] instance. /// For example, every call to [`read`][`TcpStream::read`] on [`TcpStream`] /// results in a system call. A `BufReader` performs large, infrequent reads on /// the underlying [`Read`] and maintains an in-memory buffer of the results. /// /// `BufReader` can improve the speed of programs that make *small* and /// *repeated* read calls to the same file or network socket. It does not /// help when reading very large amounts at once, or reading just one or a few /// times. It also provides no advantage when reading from a source that is /// already in memory, like a `Vec<u8>`. /// /// When the `BufReader<R>` is dropped, the contents of its buffer will be /// discarded. Creating multiple instances of a `BufReader<R>` on the same /// stream can cause data loss. Reading from the underlying reader after /// unwrapping the `BufReader<R>` with `BufReader::into_inner` can also cause /// data loss. /// /// [`Read`]: ../../std/io/trait.Read.html /// [`TcpStream::read`]: ../../std/net/struct.TcpStream.html#method.read /// [`TcpStream`]: ../../std/net/struct.TcpStream.html /// pub struct BufReader<R> { inner: R, buf: Box<[u8]>, pos: usize, cap: usize, } impl<R: Read> BufReader<R> { /// Creates a new `BufReader<R>` with a default buffer capacity. The default is currently 8 KB, /// but may change in the future. /// pub fn new(inner: R) -> BufReader<R> { BufReader::with_capacity(DEFAULT_BUF_SIZE, inner) } /// Creates a new `BufReader<R>` with the specified buffer capacity. /// pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> { unsafe { let mut buffer = Vec::with_capacity(capacity); buffer.set_len(capacity); inner.initializer().initialize(&mut buffer); BufReader { inner, buf: buffer.into_boxed_slice(), pos: 0, cap: 0 } } } } impl<R> BufReader<R> { /// Gets a reference to the underlying reader. /// /// It is inadvisable to directly read from the underlying reader. /// pub fn get_ref(&self) -> &R { &self.inner } /// Gets a mutable reference to the underlying reader. /// /// It is inadvisable to directly read from the underlying reader. /// pub fn get_mut(&mut self) -> &mut R { &mut self.inner } /// Returns a reference to the internally buffered data. /// /// Unlike `fill_buf`, this will not attempt to fill the buffer if it is empty. /// pub fn buffer(&self) -> &[u8] { &self.buf[self.pos..self.cap] } /// Returns the number of bytes the internal buffer can hold at once. /// pub fn capacity(&self) -> usize { self.buf.len() } /// Unwraps this `BufReader<R>`, returning the underlying reader. /// /// Note that any leftover data in the internal buffer is lost. Therefore, /// a following read from the underlying reader may lead to data loss. /// pub fn into_inner(self) -> R { self.inner } /// Invalidates all data in the internal buffer. #[inline] fn discard_buffer(&mut self) { self.pos = 0; self.cap = 0; } } impl<R: Seek> BufReader<R> { /// Seeks relative to the current position. If the new position lies within the buffer, /// the buffer will not be flushed, allowing for more efficient seeks. /// This method does not return the location of the underlying reader, so the caller /// must track this information themselves if it is required. pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> { let pos = self.pos as u64; if offset < 0 { if let Some(new_pos) = pos.checked_sub((-offset) as u64) { self.pos = new_pos as usize; return Ok(()); } } else { if let Some(new_pos) = pos.checked_add(offset as u64) { if new_pos <= self.cap as u64 { self.pos = new_pos as usize; return Ok(()); } } } self.seek(SeekFrom::Current(offset)).map(drop) } } impl<R: Read> Read for BufReader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { // If we don't have any buffered data and we're doing a massive read // (larger than our internal buffer), bypass our internal buffer // entirely. if self.pos == self.cap && buf.len() >= self.buf.len() { self.discard_buffer(); return self.inner.read(buf); } let nread = { let mut rem = self.fill_buf()?; rem.read(buf)? }; self.consume(nread); Ok(nread) } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { let total_len = bufs.iter().map(|b| b.len()).sum::<usize>(); if self.pos == self.cap && total_len >= self.buf.len() { self.discard_buffer(); return self.inner.read_vectored(bufs); } let nread = { let mut rem = self.fill_buf()?; rem.read_vectored(bufs)? }; self.consume(nread); Ok(nread) } // we can't skip unconditionally because of the large buffer case in read. unsafe fn initializer(&self) -> Initializer { self.inner.initializer() } } impl<R: Read> BufRead for BufReader<R> { fn fill_buf(&mut self) -> io::Result<&[u8]> { // If we've reached the end of our internal buffer then we need to fetch // some more data from the underlying reader. // Branch using `>=` instead of the more correct `==` // to tell the compiler that the pos..cap slice is always valid. if self.pos >= self.cap { debug_assert!(self.pos == self.cap); self.cap = self.inner.read(&mut self.buf)?; self.pos = 0; } Ok(&self.buf[self.pos..self.cap]) } fn consume(&mut self, amt: usize) { self.pos = cmp::min(self.pos + amt, self.cap); } } impl<R> fmt::Debug for BufReader<R> where R: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("BufReader") .field("reader", &self.inner) .field("buffer", &format_args!("{}/{}", self.cap - self.pos, self.buf.len())) .finish() } } impl<R: Seek> Seek for BufReader<R> { /// Seek to an offset, in bytes, in the underlying reader. /// /// The position used for seeking with `SeekFrom::Current(_)` is the /// position the underlying reader would be at if the `BufReader<R>` had no /// internal buffer. /// /// Seeking always discards the internal buffer, even if the seek position /// would otherwise fall within it. This guarantees that calling /// `.into_inner()` immediately after a seek yields the underlying reader /// at the same position. /// /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`]. /// /// See [`std::io::Seek`] for more details. /// /// Note: In the edge case where you're seeking with `SeekFrom::Current(n)` /// where `n` minus the internal buffer length overflows an `i64`, two /// seeks will be performed instead of one. If the second seek returns /// `Err`, the underlying reader will be left at the same position it would /// have if you called `seek` with `SeekFrom::Current(0)`. /// /// [`BufReader::seek_relative`]: struct.BufReader.html#method.seek_relative /// [`std::io::Seek`]: trait.Seek.html fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { let result: u64; if let SeekFrom::Current(n) = pos { let remainder = (self.cap - self.pos) as i64; // it should be safe to assume that remainder fits within an i64 as the alternative // means we managed to allocate 8 exbibytes and that's absurd. // But it's not out of the realm of possibility for some weird underlying reader to // support seeking by i64::min_value() so we need to handle underflow when subtracting // remainder. if let Some(offset) = n.checked_sub(remainder) { result = self.inner.seek(SeekFrom::Current(offset))?; } else { // seek backwards by our remainder, and then by the offset self.inner.seek(SeekFrom::Current(-remainder))?; self.discard_buffer(); result = self.inner.seek(SeekFrom::Current(n))?; } } else { // Seeking with Start/End doesn't care about our buffer length. result = self.inner.seek(pos)?; } self.discard_buffer(); Ok(result) } } /// Wraps a writer and buffers its output. /// /// It can be excessively inefficient to work directly with something that /// implements [`Write`]. For example, every call to /// [`write`][`TcpStream::write`] on [`TcpStream`] results in a system call. A /// `BufWriter<W>` keeps an in-memory buffer of data and writes it to an underlying /// writer in large, infrequent batches. /// /// `BufWriter<W>` can improve the speed of programs that make *small* and /// *repeated* write calls to the same file or network socket. It does not /// help when writing very large amounts at once, or writing just one or a few /// times. It also provides no advantage when writing to a destination that is /// in memory, like a `Vec<u8>`. /// /// It is critical to call [`flush`] before `BufWriter<W>` is dropped. Though /// dropping will attempt to flush the the contents of the buffer, any errors /// that happen in the process of dropping will be ignored. Calling [`flush`] /// ensures that the buffer is empty and thus dropping will not even attempt /// file operations. /// /// By wrapping the stream with a `BufWriter<W>`, these ten writes are all grouped /// together by the buffer and will all be written out in one system call when /// the `stream` is flushed. /// /// [`Write`]: ../../std/io/trait.Write.html /// [`TcpStream::write`]: ../../std/net/struct.TcpStream.html#method.write /// [`TcpStream`]: ../../std/net/struct.TcpStream.html /// [`flush`]: #method.flush pub struct BufWriter<W: Write> { inner: Option<W>, buf: Vec<u8>, // #30888: If the inner writer panics in a call to write, we don't want to // write the buffered data a second time in BufWriter's destructor. This // flag tells the Drop impl if it should skip the flush. panicked: bool, } /// An error returned by `into_inner` which combines an error that /// happened while writing out the buffer, and the buffered writer object /// which may be used to recover from the condition. /// #[derive(Debug)] pub struct IntoInnerError<W>(W, Error); impl<W: Write> BufWriter<W> { /// Creates a new `BufWriter<W>` with a default buffer capacity. The default is currently 8 KB, /// but may change in the future. /// pub fn new(inner: W) -> BufWriter<W> { BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner) } /// Creates a new `BufWriter<W>` with the specified buffer capacity. /// pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> { BufWriter { inner: Some(inner), buf: Vec::with_capacity(capacity), panicked: false } } fn flush_buf(&mut self) -> io::Result<()> { let mut written = 0; let len = self.buf.len(); let mut ret = Ok(()); while written < len { self.panicked = true; let r = self.inner.as_mut().unwrap().write(&self.buf[written..]); self.panicked = false; match r { Ok(0) => { ret = Err(Error::new(ErrorKind::WriteZero, "failed to write the buffered data")); break; } Ok(n) => written += n, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => { ret = Err(e); break; } } } if written > 0 { self.buf.drain(..written); } ret } /// Gets a reference to the underlying writer. /// pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() } /// Gets a mutable reference to the underlying writer. /// /// It is inadvisable to directly write to the underlying writer. /// pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() } /// Returns a reference to the internally buffered data. /// pub fn buffer(&self) -> &[u8] { &self.buf } /// Returns the number of bytes the internal buffer can hold without flushing. /// pub fn capacity(&self) -> usize { self.buf.capacity() } /// Unwraps this `BufWriter<W>`, returning the underlying writer. /// /// The buffer is written out before returning the writer. /// /// # Errors /// /// An `Err` will be returned if an error occurs while flushing the buffer. /// pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> { match self.flush_buf() { Err(e) => Err(IntoInnerError(self, e)), Ok(()) => Ok(self.inner.take().unwrap()), } } } impl<W: Write> Write for BufWriter<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { if self.buf.len() + buf.len() > self.buf.capacity() { self.flush_buf()?; } if buf.len() >= self.buf.capacity() { self.panicked = true; let r = self.get_mut().write(buf); self.panicked = false; r } else { self.buf.write(buf) } } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { let total_len = bufs.iter().map(|b| b.len()).sum::<usize>(); if self.buf.len() + total_len > self.buf.capacity() { self.flush_buf()?; } if total_len >= self.buf.capacity() { self.panicked = true; let r = self.get_mut().write_vectored(bufs); self.panicked = false; r } else { self.buf.write_vectored(bufs) } } fn flush(&mut self) -> io::Result<()> { self.flush_buf().and_then(|()| self.get_mut().flush()) } } impl<W: Write> fmt::Debug for BufWriter<W> where W: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("BufWriter") .field("writer", &self.inner.as_ref().unwrap()) .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity())) .finish() } } impl<W: Write + Seek> Seek for BufWriter<W> { /// Seek to the offset, in bytes, in the underlying writer. /// /// Seeking always writes out the internal buffer before seeking. fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { self.flush_buf().and_then(|_| self.get_mut().seek(pos)) } } impl<W: Write> Drop for BufWriter<W> { fn drop(&mut self) { if self.inner.is_some() && !self.panicked { // dtors should not panic, so we ignore a failed flush let _r = self.flush_buf(); } } } impl<W> IntoInnerError<W> { /// Returns the error which caused the call to `into_inner()` to fail. /// /// This error was returned when attempting to write the internal buffer. /// pub fn error(&self) -> &Error { &self.1 } /// Returns the buffered writer instance which generated the error. /// /// The returned object can be used for error recovery, such as /// re-inspecting the buffer. /// pub fn into_inner(self) -> W { self.0 } } impl<W> From<IntoInnerError<W>> for Error { fn from(iie: IntoInnerError<W>) -> Error { iie.1 } } impl<W: Send + fmt::Debug> error::Error for IntoInnerError<W> { fn description(&self) -> &str { error::Error::description(self.error()) } } impl<W> fmt::Display for IntoInnerError<W> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.error().fmt(f) } } /// Wraps a writer and buffers output to it, flushing whenever a newline /// (`0x0a`, `'\n'`) is detected. /// /// The [`BufWriter`][bufwriter] struct wraps a writer and buffers its output. /// But it only does this batched write when it goes out of scope, or when the /// internal buffer is full. Sometimes, you'd prefer to write each line as it's /// completed, rather than the entire buffer at once. Enter `LineWriter`. It /// does exactly that. /// /// Like [`BufWriter`][bufwriter], a `LineWriter`’s buffer will also be flushed when the /// `LineWriter` goes out of scope or when its internal buffer is full. /// /// [bufwriter]: struct.BufWriter.html /// /// If there's still a partial line in the buffer when the `LineWriter` is /// dropped, it will flush those contents. /// pub struct LineWriter<W: Write> { inner: BufWriter<W>, need_flush: bool, } impl<W: Write> LineWriter<W> { /// Creates a new `LineWriter`. /// pub fn new(inner: W) -> LineWriter<W> { // Lines typically aren't that long, don't use a giant buffer LineWriter::with_capacity(1024, inner) } /// Creates a new `LineWriter` with a specified capacity for the internal /// buffer. /// pub fn with_capacity(capacity: usize, inner: W) -> LineWriter<W> { LineWriter { inner: BufWriter::with_capacity(capacity, inner), need_flush: false } } /// Gets a reference to the underlying writer. /// pub fn get_ref(&self) -> &W { self.inner.get_ref() } /// Gets a mutable reference to the underlying writer. /// /// Caution must be taken when calling methods on the mutable reference /// returned as extra writes could corrupt the output stream. /// pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() } /// Unwraps this `LineWriter`, returning the underlying writer. /// /// The internal buffer is written out before returning the writer. /// /// # Errors /// /// An `Err` will be returned if an error occurs while flushing the buffer. /// pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> { self.inner.into_inner().map_err(|IntoInnerError(buf, e)| { IntoInnerError(LineWriter { inner: buf, need_flush: false }, e) }) } } impl<W: Write> Write for LineWriter<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { if self.need_flush { self.flush()?; } // Find the last newline character in the buffer provided. If found then // we're going to write all the data up to that point and then flush, // otherwise we just write the whole block to the underlying writer. let i = match memchr::memrchr(b'\n', buf) { Some(i) => i, None => return self.inner.write(buf), }; // Ok, we're going to write a partial amount of the data given first // followed by flushing the newline. After we've successfully written // some data then we *must* report that we wrote that data, so future // errors are ignored. We set our internal `need_flush` flag, though, in // case flushing fails and we need to try it first next time. let n = self.inner.write(&buf[..=i])?; self.need_flush = true; if self.flush().is_err() || n != i + 1 { return Ok(n); } // At this point we successfully wrote `i + 1` bytes and flushed it out, // meaning that the entire line is now flushed out on the screen. While // we can attempt to finish writing the rest of the data provided. // Remember though that we ignore errors here as we've successfully // written data, so we need to report that. match self.inner.write(&buf[i + 1..]) { Ok(i) => Ok(n + i), Err(_) => Ok(n), } } // Vectored writes are very similar to the writes above, but adjusted for // the list of buffers that we have to write. fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { if self.need_flush { self.flush()?; } // Find the last newline, and failing that write the whole buffer let last_newline = bufs .iter() .enumerate() .rev() .filter_map(|(i, buf)| { let pos = memchr::memrchr(b'\n', buf)?; Some((i, pos)) }) .next(); let (i, j) = match last_newline { Some(pair) => pair, None => return self.inner.write_vectored(bufs), }; let (prefix, suffix) = bufs.split_at(i); let (buf, suffix) = suffix.split_at(1); let buf = &buf[0]; // Write everything up to the last newline, flushing afterwards. Note // that only if we finished our entire `write_vectored` do we try the // subsequent // `write` let mut n = 0; let prefix_amt = prefix.iter().map(|i| i.len()).sum(); if prefix_amt > 0 { n += self.inner.write_vectored(prefix)?; self.need_flush = true; } if n == prefix_amt { match self.inner.write(&buf[..=j]) { Ok(m) => n += m, Err(e) if n == 0 => return Err(e), Err(_) => return Ok(n), } self.need_flush = true; } if self.flush().is_err() || n != j + 1 + prefix_amt { return Ok(n); } // ... and now write out everything remaining match self.inner.write(&buf[j + 1..]) { Ok(i) => n += i, Err(_) => return Ok(n), } if suffix.iter().map(|s| s.len()).sum::<usize>() == 0 { return Ok(n); } match self.inner.write_vectored(suffix) { Ok(i) => Ok(n + i), Err(_) => Ok(n), } } fn flush(&mut self) -> io::Result<()> { self.inner.flush()?; self.need_flush = false; Ok(()) } } impl<W: Write> fmt::Debug for LineWriter<W> where W: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("LineWriter") .field("writer", &self.inner.inner) .field( "buffer", &format_args!("{}/{}", self.inner.buf.len(), self.inner.buf.capacity()), ) .finish() } }
true
d58757446fed2183d9793266ebcd311ac924b4f3
Rust
sagarnayak/RustTestWebApp
/src/controllers/multi_thread_task.rs
UTF-8
472
2.765625
3
[]
no_license
use std::time::Duration; use rand::Rng; use std::thread::sleep; #[get("/startMultiThreading")] pub async fn start_multi_thread() -> &'static str { for i in 0..1000 { tokio::spawn( async move { // println!("Start timer {}.", &i); sleep(Duration::from_secs(rand::thread_rng().gen_range(1..3))); println!("Completed task number {}", i); } ); } "started the multi thread" }
true
5111fbaaec8afce95e4dee79f2b88f429b5ea1e4
Rust
clinuxrulz/ilc_ecs
/src/ecs/scene_ctx.rs
UTF-8
632
2.609375
3
[]
no_license
use crate::ecs::ComponentType; use crate::ecs::EntityId; use crate::ecs::IsComponent; pub trait SceneCtx { // for Undo/Redo capabilities fn create_entity_with_id(&mut self, entity_id: EntityId); fn create_entity(&mut self) -> EntityId; fn destroy_entity(&mut self, entity_id: EntityId); fn get_component<A>(&self, entity_id: EntityId, component_type: ComponentType<A>) -> Option<A>; fn set_component<A:IsComponent>(&mut self, entity_id: EntityId, component: A); fn children(&self, entity_id: EntityId) -> Vec<EntityId>; fn entities_of_type(&self, component_type_name: &str) -> Vec<EntityId>; }
true
547015b6a1dcf7b6330f33d652a7832b3a16a4b1
Rust
mida-hub/hobby
/atcoder/rust/beginner/contest/abc234/src/bin/c.rs
UTF-8
486
3.046875
3
[]
no_license
fn to_bin(v: i64) -> String { format!("{:b}", v).to_string() } fn to_int(s: String) -> i64 { s.parse::<i64>().unwrap() } fn main() { proconio::input! { k: i64, }; let str_bin_k = to_bin(k); let mut ans = "".to_string(); for s in str_bin_k.chars() { // println!("{}", s); // 文字列から整数変換->2倍する->文字列に直す ans.push_str(&(2 * to_int(s.to_string())).to_string()); } println!("{}", ans); }
true
a5d16aee67d71d26698a4be1acc3bb894647543c
Rust
ferrous-systems/imxrt1052
/src/pwm1/sm2octrl/mod.rs
UTF-8
26,271
2.734375
3
[]
no_license
#[doc = r" Value read from the register"] pub struct R { bits: u16, } #[doc = r" Value to write to the register"] pub struct W { bits: u16, } impl super::SM2OCTRL { #[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 `PWMXFS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWMXFSR { #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] PWMXFS_0, #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] PWMXFS_1, #[doc = "Output is tristated."] PWMXFS_2, #[doc = "Output is tristated."] PWMXFS_3, } impl PWMXFSR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PWMXFSR::PWMXFS_0 => 0, PWMXFSR::PWMXFS_1 => 1, PWMXFSR::PWMXFS_2 => 2, PWMXFSR::PWMXFS_3 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PWMXFSR { match value { 0 => PWMXFSR::PWMXFS_0, 1 => PWMXFSR::PWMXFS_1, 2 => PWMXFSR::PWMXFS_2, 3 => PWMXFSR::PWMXFS_3, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWMXFS_0`"] #[inline] pub fn is_pwmxfs_0(&self) -> bool { *self == PWMXFSR::PWMXFS_0 } #[doc = "Checks if the value of the field is `PWMXFS_1`"] #[inline] pub fn is_pwmxfs_1(&self) -> bool { *self == PWMXFSR::PWMXFS_1 } #[doc = "Checks if the value of the field is `PWMXFS_2`"] #[inline] pub fn is_pwmxfs_2(&self) -> bool { *self == PWMXFSR::PWMXFS_2 } #[doc = "Checks if the value of the field is `PWMXFS_3`"] #[inline] pub fn is_pwmxfs_3(&self) -> bool { *self == PWMXFSR::PWMXFS_3 } } #[doc = "Possible values of the field `PWMBFS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWMBFSR { #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] PWMBFS_0, #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] PWMBFS_1, #[doc = "Output is tristated."] PWMBFS_2, #[doc = "Output is tristated."] PWMBFS_3, } impl PWMBFSR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PWMBFSR::PWMBFS_0 => 0, PWMBFSR::PWMBFS_1 => 1, PWMBFSR::PWMBFS_2 => 2, PWMBFSR::PWMBFS_3 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PWMBFSR { match value { 0 => PWMBFSR::PWMBFS_0, 1 => PWMBFSR::PWMBFS_1, 2 => PWMBFSR::PWMBFS_2, 3 => PWMBFSR::PWMBFS_3, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWMBFS_0`"] #[inline] pub fn is_pwmbfs_0(&self) -> bool { *self == PWMBFSR::PWMBFS_0 } #[doc = "Checks if the value of the field is `PWMBFS_1`"] #[inline] pub fn is_pwmbfs_1(&self) -> bool { *self == PWMBFSR::PWMBFS_1 } #[doc = "Checks if the value of the field is `PWMBFS_2`"] #[inline] pub fn is_pwmbfs_2(&self) -> bool { *self == PWMBFSR::PWMBFS_2 } #[doc = "Checks if the value of the field is `PWMBFS_3`"] #[inline] pub fn is_pwmbfs_3(&self) -> bool { *self == PWMBFSR::PWMBFS_3 } } #[doc = "Possible values of the field `PWMAFS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWMAFSR { #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] PWMAFS_0, #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] PWMAFS_1, #[doc = "Output is tristated."] PWMAFS_2, #[doc = "Output is tristated."] PWMAFS_3, } impl PWMAFSR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PWMAFSR::PWMAFS_0 => 0, PWMAFSR::PWMAFS_1 => 1, PWMAFSR::PWMAFS_2 => 2, PWMAFSR::PWMAFS_3 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PWMAFSR { match value { 0 => PWMAFSR::PWMAFS_0, 1 => PWMAFSR::PWMAFS_1, 2 => PWMAFSR::PWMAFS_2, 3 => PWMAFSR::PWMAFS_3, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWMAFS_0`"] #[inline] pub fn is_pwmafs_0(&self) -> bool { *self == PWMAFSR::PWMAFS_0 } #[doc = "Checks if the value of the field is `PWMAFS_1`"] #[inline] pub fn is_pwmafs_1(&self) -> bool { *self == PWMAFSR::PWMAFS_1 } #[doc = "Checks if the value of the field is `PWMAFS_2`"] #[inline] pub fn is_pwmafs_2(&self) -> bool { *self == PWMAFSR::PWMAFS_2 } #[doc = "Checks if the value of the field is `PWMAFS_3`"] #[inline] pub fn is_pwmafs_3(&self) -> bool { *self == PWMAFSR::PWMAFS_3 } } #[doc = "Possible values of the field `POLX`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum POLXR { #[doc = "PWM_X output not inverted. A high level on the PWM_X pin represents the \"on\" or \"active\" state."] POLX_0, #[doc = "PWM_X output inverted. A low level on the PWM_X pin represents the \"on\" or \"active\" state."] POLX_1, } impl POLXR { #[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 { POLXR::POLX_0 => false, POLXR::POLX_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> POLXR { match value { false => POLXR::POLX_0, true => POLXR::POLX_1, } } #[doc = "Checks if the value of the field is `POLX_0`"] #[inline] pub fn is_polx_0(&self) -> bool { *self == POLXR::POLX_0 } #[doc = "Checks if the value of the field is `POLX_1`"] #[inline] pub fn is_polx_1(&self) -> bool { *self == POLXR::POLX_1 } } #[doc = "Possible values of the field `POLB`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum POLBR { #[doc = "PWM_B output not inverted. A high level on the PWM_B pin represents the \"on\" or \"active\" state."] POLB_0, #[doc = "PWM_B output inverted. A low level on the PWM_B pin represents the \"on\" or \"active\" state."] POLB_1, } impl POLBR { #[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 { POLBR::POLB_0 => false, POLBR::POLB_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> POLBR { match value { false => POLBR::POLB_0, true => POLBR::POLB_1, } } #[doc = "Checks if the value of the field is `POLB_0`"] #[inline] pub fn is_polb_0(&self) -> bool { *self == POLBR::POLB_0 } #[doc = "Checks if the value of the field is `POLB_1`"] #[inline] pub fn is_polb_1(&self) -> bool { *self == POLBR::POLB_1 } } #[doc = "Possible values of the field `POLA`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum POLAR { #[doc = "PWM_A output not inverted. A high level on the PWM_A pin represents the \"on\" or \"active\" state."] POLA_0, #[doc = "PWM_A output inverted. A low level on the PWM_A pin represents the \"on\" or \"active\" state."] POLA_1, } impl POLAR { #[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 { POLAR::POLA_0 => false, POLAR::POLA_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> POLAR { match value { false => POLAR::POLA_0, true => POLAR::POLA_1, } } #[doc = "Checks if the value of the field is `POLA_0`"] #[inline] pub fn is_pola_0(&self) -> bool { *self == POLAR::POLA_0 } #[doc = "Checks if the value of the field is `POLA_1`"] #[inline] pub fn is_pola_1(&self) -> bool { *self == POLAR::POLA_1 } } #[doc = r" Value of the field"] pub struct PWMX_INR { bits: bool, } impl PWMX_INR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[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"] pub struct PWMB_INR { bits: bool, } impl PWMB_INR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[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"] pub struct PWMA_INR { bits: bool, } impl PWMA_INR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[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 = "Values that can be written to the field `PWMXFS`"] pub enum PWMXFSW { #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] PWMXFS_0, #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] PWMXFS_1, #[doc = "Output is tristated."] PWMXFS_2, #[doc = "Output is tristated."] PWMXFS_3, } impl PWMXFSW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PWMXFSW::PWMXFS_0 => 0, PWMXFSW::PWMXFS_1 => 1, PWMXFSW::PWMXFS_2 => 2, PWMXFSW::PWMXFS_3 => 3, } } } #[doc = r" Proxy"] pub struct _PWMXFSW<'a> { w: &'a mut W, } impl<'a> _PWMXFSW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PWMXFSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] #[inline] pub fn pwmxfs_0(self) -> &'a mut W { self.variant(PWMXFSW::PWMXFS_0) } #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] #[inline] pub fn pwmxfs_1(self) -> &'a mut W { self.variant(PWMXFSW::PWMXFS_1) } #[doc = "Output is tristated."] #[inline] pub fn pwmxfs_2(self) -> &'a mut W { self.variant(PWMXFSW::PWMXFS_2) } #[doc = "Output is tristated."] #[inline] pub fn pwmxfs_3(self) -> &'a mut W { self.variant(PWMXFSW::PWMXFS_3) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PWMBFS`"] pub enum PWMBFSW { #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] PWMBFS_0, #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] PWMBFS_1, #[doc = "Output is tristated."] PWMBFS_2, #[doc = "Output is tristated."] PWMBFS_3, } impl PWMBFSW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PWMBFSW::PWMBFS_0 => 0, PWMBFSW::PWMBFS_1 => 1, PWMBFSW::PWMBFS_2 => 2, PWMBFSW::PWMBFS_3 => 3, } } } #[doc = r" Proxy"] pub struct _PWMBFSW<'a> { w: &'a mut W, } impl<'a> _PWMBFSW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PWMBFSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] #[inline] pub fn pwmbfs_0(self) -> &'a mut W { self.variant(PWMBFSW::PWMBFS_0) } #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] #[inline] pub fn pwmbfs_1(self) -> &'a mut W { self.variant(PWMBFSW::PWMBFS_1) } #[doc = "Output is tristated."] #[inline] pub fn pwmbfs_2(self) -> &'a mut W { self.variant(PWMBFSW::PWMBFS_2) } #[doc = "Output is tristated."] #[inline] pub fn pwmbfs_3(self) -> &'a mut W { self.variant(PWMBFSW::PWMBFS_3) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PWMAFS`"] pub enum PWMAFSW { #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] PWMAFS_0, #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] PWMAFS_1, #[doc = "Output is tristated."] PWMAFS_2, #[doc = "Output is tristated."] PWMAFS_3, } impl PWMAFSW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PWMAFSW::PWMAFS_0 => 0, PWMAFSW::PWMAFS_1 => 1, PWMAFSW::PWMAFS_2 => 2, PWMAFSW::PWMAFS_3 => 3, } } } #[doc = r" Proxy"] pub struct _PWMAFSW<'a> { w: &'a mut W, } impl<'a> _PWMAFSW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PWMAFSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Output is forced to logic 0 state prior to consideration of output polarity control."] #[inline] pub fn pwmafs_0(self) -> &'a mut W { self.variant(PWMAFSW::PWMAFS_0) } #[doc = "Output is forced to logic 1 state prior to consideration of output polarity control."] #[inline] pub fn pwmafs_1(self) -> &'a mut W { self.variant(PWMAFSW::PWMAFS_1) } #[doc = "Output is tristated."] #[inline] pub fn pwmafs_2(self) -> &'a mut W { self.variant(PWMAFSW::PWMAFS_2) } #[doc = "Output is tristated."] #[inline] pub fn pwmafs_3(self) -> &'a mut W { self.variant(PWMAFSW::PWMAFS_3) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `POLX`"] pub enum POLXW { #[doc = "PWM_X output not inverted. A high level on the PWM_X pin represents the \"on\" or \"active\" state."] POLX_0, #[doc = "PWM_X output inverted. A low level on the PWM_X pin represents the \"on\" or \"active\" state."] POLX_1, } impl POLXW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { POLXW::POLX_0 => false, POLXW::POLX_1 => true, } } } #[doc = r" Proxy"] pub struct _POLXW<'a> { w: &'a mut W, } impl<'a> _POLXW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: POLXW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "PWM_X output not inverted. A high level on the PWM_X pin represents the \"on\" or \"active\" state."] #[inline] pub fn polx_0(self) -> &'a mut W { self.variant(POLXW::POLX_0) } #[doc = "PWM_X output inverted. A low level on the PWM_X pin represents the \"on\" or \"active\" state."] #[inline] pub fn polx_1(self) -> &'a mut W { self.variant(POLXW::POLX_1) } #[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 = 8; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `POLB`"] pub enum POLBW { #[doc = "PWM_B output not inverted. A high level on the PWM_B pin represents the \"on\" or \"active\" state."] POLB_0, #[doc = "PWM_B output inverted. A low level on the PWM_B pin represents the \"on\" or \"active\" state."] POLB_1, } impl POLBW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { POLBW::POLB_0 => false, POLBW::POLB_1 => true, } } } #[doc = r" Proxy"] pub struct _POLBW<'a> { w: &'a mut W, } impl<'a> _POLBW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: POLBW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "PWM_B output not inverted. A high level on the PWM_B pin represents the \"on\" or \"active\" state."] #[inline] pub fn polb_0(self) -> &'a mut W { self.variant(POLBW::POLB_0) } #[doc = "PWM_B output inverted. A low level on the PWM_B pin represents the \"on\" or \"active\" state."] #[inline] pub fn polb_1(self) -> &'a mut W { self.variant(POLBW::POLB_1) } #[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 = 9; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } #[doc = "Values that can be written to the field `POLA`"] pub enum POLAW { #[doc = "PWM_A output not inverted. A high level on the PWM_A pin represents the \"on\" or \"active\" state."] POLA_0, #[doc = "PWM_A output inverted. A low level on the PWM_A pin represents the \"on\" or \"active\" state."] POLA_1, } impl POLAW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { POLAW::POLA_0 => false, POLAW::POLA_1 => true, } } } #[doc = r" Proxy"] pub struct _POLAW<'a> { w: &'a mut W, } impl<'a> _POLAW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: POLAW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "PWM_A output not inverted. A high level on the PWM_A pin represents the \"on\" or \"active\" state."] #[inline] pub fn pola_0(self) -> &'a mut W { self.variant(POLAW::POLA_0) } #[doc = "PWM_A output inverted. A low level on the PWM_A pin represents the \"on\" or \"active\" state."] #[inline] pub fn pola_1(self) -> &'a mut W { self.variant(POLAW::POLA_1) } #[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 = 10; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u16 { self.bits } #[doc = "Bits 0:1 - PWM_X Fault State"] #[inline] pub fn pwmxfs(&self) -> PWMXFSR { PWMXFSR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u16) as u8 }) } #[doc = "Bits 2:3 - PWM_B Fault State"] #[inline] pub fn pwmbfs(&self) -> PWMBFSR { PWMBFSR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u16) as u8 }) } #[doc = "Bits 4:5 - PWM_A Fault State"] #[inline] pub fn pwmafs(&self) -> PWMAFSR { PWMAFSR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u16) as u8 }) } #[doc = "Bit 8 - PWM_X Output Polarity"] #[inline] pub fn polx(&self) -> POLXR { POLXR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } #[doc = "Bit 9 - PWM_B Output Polarity"] #[inline] pub fn polb(&self) -> POLBR { POLBR::_from({ const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } #[doc = "Bit 10 - PWM_A Output Polarity"] #[inline] pub fn pola(&self) -> POLAR { POLAR::_from({ const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u16) != 0 }) } #[doc = "Bit 13 - PWM_X Input"] #[inline] pub fn pwmx_in(&self) -> PWMX_INR { let bits = { const MASK: bool = true; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u16) != 0 }; PWMX_INR { bits } } #[doc = "Bit 14 - PWM_B Input"] #[inline] pub fn pwmb_in(&self) -> PWMB_INR { let bits = { const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u16) != 0 }; PWMB_INR { bits } } #[doc = "Bit 15 - PWM_A Input"] #[inline] pub fn pwma_in(&self) -> PWMA_INR { let bits = { const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u16) != 0 }; PWMA_INR { bits } } } 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: u16) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:1 - PWM_X Fault State"] #[inline] pub fn pwmxfs(&mut self) -> _PWMXFSW { _PWMXFSW { w: self } } #[doc = "Bits 2:3 - PWM_B Fault State"] #[inline] pub fn pwmbfs(&mut self) -> _PWMBFSW { _PWMBFSW { w: self } } #[doc = "Bits 4:5 - PWM_A Fault State"] #[inline] pub fn pwmafs(&mut self) -> _PWMAFSW { _PWMAFSW { w: self } } #[doc = "Bit 8 - PWM_X Output Polarity"] #[inline] pub fn polx(&mut self) -> _POLXW { _POLXW { w: self } } #[doc = "Bit 9 - PWM_B Output Polarity"] #[inline] pub fn polb(&mut self) -> _POLBW { _POLBW { w: self } } #[doc = "Bit 10 - PWM_A Output Polarity"] #[inline] pub fn pola(&mut self) -> _POLAW { _POLAW { w: self } } }
true
037a9e08538f832e5baa1f77071f19c23ee4b4ce
Rust
Frixxie/weatherlogger
/src/main.rs
UTF-8
3,146
3.296875
3
[ "MIT" ]
permissive
mod weather; use futures::future::try_join_all; use reqwest::get; use serde::Deserialize; use serde_json::Value; use std::io; use std::path::PathBuf; use std::sync::Arc; use structopt::StructOpt; use tokio::fs; #[derive(Debug, StructOpt)] #[structopt( name = "weatherlogger", about = "Logs the weather from https://openweathermap.com" )] struct Opt { ///Use isp location #[structopt(short, long)] isp_loc: bool, ///Config file #[structopt(short, long, default_value = "./config.json")] config_file: PathBuf, } /// Config struct /// For convenience #[derive(Deserialize)] struct Config { apikey: String, locations: Vec<String>, dbconnectionstring: String, } impl Config { ///Creates a config instance. pub async fn new(config_file: PathBuf) -> Result<Config, io::Error> { Ok(serde_json::from_str(&fs::read_to_string(config_file).await.unwrap()).unwrap()) } } async fn get_weather_openweathermap(api: &str, loc: &str) -> weather::Weather { //Gets the weather from openweathermap.com let url = format!( "https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}", loc, api ); let response = get(&url).await.unwrap().text().await.unwrap(); //converting to json so it can be printed let v: Value = serde_json::from_str(&response).unwrap(); v.try_into().unwrap() } /// Gets the city based on ip async fn get_city(url: &str) -> String { get(url).await.unwrap().text().await.unwrap() } #[tokio::main] async fn main() -> Result<(), io::Error> { //reading in loc and apikey let opt = Opt::from_args(); //Gets the current configuration let config = Arc::new(Config::new(opt.config_file).await.unwrap()); let dbconnectionstring = config.dbconnectionstring.clone(); let client_options = mongodb::options::ClientOptions::parse(&dbconnectionstring) .await .unwrap(); let db_client = mongodb::Client::with_options(client_options).unwrap(); let db = db_client.database("weatherlogger"); //Getting the location if opt.isp_loc { let loc = get_city("http://ip-api.com/line/?fields=city").await; println!("{}", get_weather_openweathermap(&config.apikey, &loc).await); } else { //vector for containing the join_handles spawned from the tokio threads let mut futures = Vec::new(); for loc in config.locations.clone() { //needed for move let apikey = config.apikey.clone(); futures.push(tokio::spawn(async move { get_weather_openweathermap(&apikey, &loc).await })); } //Joining the futures let reses: Vec<weather::Weather> = try_join_all(futures) .await? .into_iter() .map(|res| res) .collect(); //inserting into the database let collection = db.collection::<weather::Weather>("weatherlog"); collection.insert_many(&reses, None).await.unwrap(); //printing to stdout for res in &reses { println!("{}", res); } } Ok(()) }
true
a55bb237e21f47c3e8d1adf77c09c338a344ae87
Rust
nimiq/core-rs
/utils/tests/throttled_queue/mod.rs
UTF-8
1,100
3.21875
3
[ "Apache-2.0" ]
permissive
use std::thread::sleep; use std::time::Duration; use nimiq_collections::queue::Queue; use nimiq_utils::throttled_queue::*; #[test] fn it_can_enqueue_dequeue() { let mut queue = ThrottledQueue::new(1000, Duration::default(), 0, None); queue.enqueue(1); queue.enqueue(2); queue.enqueue(8); queue.remove(&8); queue.enqueue(3); queue.enqueue(4); assert_eq!(queue.len(), 4); assert_eq!(queue.dequeue(), Some(1)); assert_eq!(queue.dequeue_multi(2), vec![2, 3]); assert!(queue.check_available()); assert_eq!(queue.num_available(), 1); } #[test] fn it_can_throttle() { let interval = Duration::new(0, 50000000); let mut queue = ThrottledQueue::new(2, interval, 1, Some(10)); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); queue.enqueue(5); queue.enqueue(6); // TODO: This test is dependent on timing! assert_eq!(queue.dequeue_multi(3), vec![1, 2]); sleep(interval); assert_eq!(queue.dequeue_multi(2), vec![3]); sleep(3 * interval); assert_eq!(queue.num_available(), 2); }
true
2012974c8d0f471060bd4d345c6c26ed1e5cd0bf
Rust
vishalbelsare/sss-cli
/src/bin/split.rs
UTF-8
9,035
2.53125
3
[ "MIT" ]
permissive
#[macro_use] extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate rand; extern crate shamirsecretsharing_cli; extern crate shamirsecretsharing; use std::env; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::process::exit; use clap::{App, Arg, ArgMatches}; use rand::random; use shamirsecretsharing::hazmat::create_keyshares; use shamirsecretsharing::hazmat::KEY_SIZE; use shamirsecretsharing_cli::*; /// Parse the command line arguments fn argparse<'a>() -> ArgMatches<'a> { App::new("secret-share-split") .version(crate_version!()) .author(crate_authors!()) .about("Generate n shares of a file with recombination treshold t") .arg(Arg::with_name("count") .short("n") .long("count") .value_name("n") .help("The amount of shares that will be created") .takes_value(true) .required(true)) .arg(Arg::with_name("threshold") .short("t") .long("threshold") .value_name("k") .help("The treshold for restoring the file") .takes_value(true) .required(true)) .arg(Arg::with_name("FILE").help("Specifies the input file that will be secret-shared")) .get_matches() } fn main() { // If not log level has been set, default to info if env::var_os("RUST_LOG") == None { env::set_var("RUST_LOG", "secret_share_split=info"); } // Init env_logger env_logger::init(); // Parse command line arguments let matches = argparse(); let input_fn = matches.value_of("FILE"); let count = matches .value_of("count") .unwrap() .parse::<isize>() .map_err(|_| { error!("count is not a valid number"); exit(1); }) .and_then(|x| if 2 <= x && x <= 255 { Ok(x) } else { Err(x) }) .unwrap_or_else(|x| { error!("count must be a number between 2 and 255 (instead of {})", x); exit(1); }) as u8; let treshold = matches .value_of("threshold") .unwrap() .parse::<isize>() .map_err(|_| { error!("threshold is not a valid number"); exit(1); }) .and_then(|x| if 2 <= x && x <= (count as isize) { Ok(x) } else { Err(x) }) .unwrap_or_else(|x| { error!("threshold must be a number between 2 and {} (instead of {})", count, x); exit(1); }) as u8; // Open the input file and read its contents let mut input_file: Box<dyn Read> = match input_fn { None | Some("-") => Box::new(std::io::stdin()), Some(input_fn) => { Box::new(File::open(input_fn).unwrap_or_else(|err| { error!("error while opening file '{}': {}", input_fn, err); exit(1); })) } }; // We are not able to use the normal API for variable length plaintexts, so we will have to // use the hazmat API and encrypt the file ourselves let key: [u8; KEY_SIZE] = random(); trace!("creating keyshares"); let keyshares = create_keyshares(&key, count, treshold) .unwrap_or_else(|err| { error!("{}", err); exit(1); }); // Encrypt the contents of the file let mut ciphertext = Vec::new(); trace!("encrypting secret"); crypto_secretbox(&mut ciphertext as &mut dyn Write, &mut *input_file, &NONCE, &key) .expect("unexpected error during encryption, this is probably a bug"); // Construct the full shares let full_shares = keyshares.iter() .map(|ks| ks.iter() .chain(ciphertext.iter())); // Write the shares to stdout let mut buf = String::new(); let buf_maxsize = 4 * 2u32.pow(20) as usize; // size 4Mb trace!("writing shares to output file"); for share in full_shares { for byte in share { if let Err(err) = write!(&mut buf as &mut dyn fmt::Write, "{:02x}", byte) { error!("{}", err); exit(1); } if buf.len() >= buf_maxsize { print!("{}", buf); buf.clear() } } println!("{}", buf); buf.clear() } drop(buf); } #[cfg(test)] mod tests { extern crate duct; use self::duct::cmd; macro_rules! cmd { ( $program:expr, $( $arg:expr ),* ) => ( { let args = [ $( $arg ),* ]; cmd($program, args.iter()) } ) } macro_rules! run_self { ( $( $arg:expr ),* ) => ( { let args = ["run", "--quiet", "--bin", "secret-share-split", "--", $( $arg ),* ]; cmd(env!("CARGO"), args.iter()) } ) } const ERR_RANGE: std::ops::Range<usize> = 22..27; const MSG_RANGE: std::ops::RangeFrom<usize> = 48..; #[test] fn functional() { let secret = "Hello World!"; let echo = cmd!("echo", "-n", secret); let output = echo.pipe(run_self!("--count", "5", "--threshold", "4")) .read() .unwrap(); let mut idx = 0; for line in output.lines() { assert_eq!(line.len(), 2 * (49 + secret.len())); let x = format!("{:02}", idx + 1); assert!(line.starts_with(&x)); idx += 1; } assert_eq!(idx, 5); } #[test] fn no_args() { let output = run_self!() .unchecked() .stderr_to_stdout() .read() .unwrap(); assert!(output.starts_with("error: The following required arguments were not provided: --count <n> --threshold <k>")); } #[test] fn no_count() { let output = run_self!("--threshold", "4") .unchecked() .stderr_to_stdout() .read() .unwrap(); assert!(output.starts_with("error: The following required arguments were not provided: --count <n>")); } #[test] fn no_threshold() { let output = run_self!("--count", "5") .unchecked() .stderr_to_stdout() .read() .unwrap(); assert!(output.starts_with("error: The following required arguments were not provided: --threshold <k>")); } #[test] fn count_parse() { let output = run_self!("--count", "not a number", "--threshold", "4") .unchecked() .stderr_to_stdout() .read() .unwrap(); assert_eq!(&output[ERR_RANGE], "ERROR"); assert_eq!(&output[MSG_RANGE], "count is not a valid number"); } #[test] fn count_range() { macro_rules! test_bad_count { ($n:expr, $k:expr) => ( let output = run_self!("--count", $n, "--threshold", $k) .unchecked().stderr_to_stdout().read().unwrap(); assert_eq!(&output[ERR_RANGE], "ERROR"); assert_eq!(&output[MSG_RANGE], format!("count must be a number between 2 \ and 255 (instead of {})", $n)); ) } test_bad_count!("0", "4"); test_bad_count!("1", "4"); test_bad_count!("256", "4"); } #[test] fn threshold_parse() { let output = run_self!("--count", "5", "--threshold", "not a number") .unchecked() .stderr_to_stdout() .read() .unwrap(); assert_eq!(&output[ERR_RANGE], "ERROR"); assert_eq!(&output[MSG_RANGE], "threshold is not a valid number"); } #[test] fn threshold_range() { macro_rules! test_bad_threshold { ($n:expr, $k:expr) => ( let output = run_self!("--count", $n, "--threshold", $k) .unchecked().stderr_to_stdout().read().unwrap(); assert_eq!(&output[ERR_RANGE], "ERROR"); assert_eq!(&output[MSG_RANGE], format!("threshold must be a number between 2 \ and 5 (instead of {})", $k)); ) } test_bad_threshold!("5", "0"); test_bad_threshold!("5", "1"); test_bad_threshold!("5", "6"); test_bad_threshold!("5", "256"); } #[test] fn nonexistent_file() { let output = run_self!("--count", "5", "--threshold", "4", "nonexistent") .unchecked() .stderr_to_stdout() .read() .unwrap(); assert_eq!(&output[ERR_RANGE], "ERROR"); assert_eq!(&output[MSG_RANGE], "error while opening file \'nonexistent\': \ No such file or directory (os error 2)"); } }
true
7a6779e848ccd6af1f659c10771e50d06163c610
Rust
rust-lang/rust
/tests/ui/suggestions/dont-wrap-ambiguous-receivers.rs
UTF-8
499
2.875
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
mod banana { //~^ HELP the following traits are implemented but not in scope pub struct Chaenomeles; pub trait Apple { fn pick(&self) {} } impl Apple for Chaenomeles {} pub trait Peach { fn pick(&self, a: &mut ()) {} } impl<Mango: Peach> Peach for Box<Mango> {} impl Peach for Chaenomeles {} } fn main() { banana::Chaenomeles.pick() //~^ ERROR no method named //~| HELP items from traits can only be used if the trait is in scope }
true
131582dda70e3eb164c27f7b8369005853ddfc19
Rust
nfrasser/lasgun
/src/scene/node.rs
UTF-8
3,739
3.25
3
[ "MIT" ]
permissive
// This module contains structures for providing a simple representation of the // contents of a scene. The elements here are later used to build up a full scene use cgmath::{prelude::*, Deg}; use crate::{space::*, Material}; use super::{ObjRef as Obj}; pub enum SceneNode { /// A geometric shape its material Geometry(Shape, Material), /// Reference to a triangle mesh loaded in the scene Mesh(Obj, Option<Material>), /// A collection of multiple scene nodes Group(Aggregate) } pub enum Shape { /// Sphere with origin and radius Sphere([f64; 3], f64), /// Cube with origin and dimensions from that origin Cube([f64; 3], f64), /// Similar to cube: a rectagular prism with start and end corners Cuboid([f64; 3], [f64; 3]), } pub struct Aggregate { pub contents: Vec<SceneNode>, pub transform: Transformation, /// If true, reverses orientation of normal shading vectors for all /// children. Useful for capturing the inside or backface of a shape/mesh. /// Also known as "swap handedness". pub swap_backface: bool } impl Aggregate { pub fn new() -> Aggregate { Aggregate { contents: vec![], transform: Transformation::identity(), swap_backface: false } } #[inline] pub fn add(&mut self, node: SceneNode) { self.contents.push(node) } pub fn add_group(&mut self, aggregate: Aggregate) { self.add(SceneNode::Group(aggregate)) } pub fn add_sphere(&mut self, center: [f64; 3], radius: f64, material: Material) { let shape = Shape::Sphere(center, radius); self.add(SceneNode::Geometry(shape, material)) } pub fn add_cube(&mut self, origin: [f64; 3], dim: f64, material: Material) { let shape = Shape::Cube(origin, dim); self.add(SceneNode::Geometry(shape, material)) } pub fn add_box(&mut self, minbound: [f64; 3], maxbound: [f64; 3], material: Material) { let shape = Shape::Cuboid(minbound, maxbound); self.add(SceneNode::Geometry(shape, material)) } /// Add a simple mesh that provides its own material properties (or defaults /// to a simple material provided by Material::default()) pub fn add_obj(&mut self, mesh: Obj) { self.add(SceneNode::Mesh(mesh, None)) } /// Add a simple mesh that's made of a single material pub fn add_obj_of(&mut self, mesh: Obj, material: Material) { self.add(SceneNode::Mesh(mesh, Some(material))) } #[inline] pub fn swap_backface(&mut self) { self.swap_backface = !self.swap_backface } #[inline] pub fn translate(&mut self, delta: [f64; 3]) -> &mut Self { let delta = Vector::new(delta[0], delta[1], delta[2]); self.transform.concat_self(&Transformation::translate(delta)); self } #[inline] pub fn scale(&mut self, x: f64, y: f64, z: f64) -> &mut Self { self.transform.concat_self(&Transformation::scale(x, y, z)); self } #[inline] pub fn rotate_x(&mut self, theta: f64) -> &mut Self { self.transform.concat_self(&Transformation::rotate_x(Deg(theta))); self } #[inline] pub fn rotate_y(&mut self, theta: f64) -> &mut Self { self.transform.concat_self(&Transformation::rotate_y(Deg(theta))); self } #[inline] pub fn rotate_z(&mut self, theta: f64) -> &mut Self { self.transform.concat_self(&Transformation::rotate_z(Deg(theta))); self } #[inline] pub fn rotate(&mut self, theta: f64, axis: [f64; 3]) -> &mut Self { let axis = Vector { x: axis[0], y: axis[1], z: axis[2] }; self.transform.concat_self(&Transformation::rotate(Deg(theta), axis)); self } }
true
c77f55d97069e2f9bcf96befc8bf08b2c047cb24
Rust
necrobious/aws-kms-ca
/aws-kms-ca-x509/src/certificate/validity.rs
UTF-8
3,718
2.921875
3
[]
no_license
use yasna::models::UTCTime; use time::OffsetDateTime; use yasna::{ ASN1Result, DERWriter, DEREncodable, BERReader, BERDecodable, }; #[cfg(feature = "tracing")] use tracing::{debug}; #[derive(Clone, Debug, PartialEq,)] pub struct Validity { pub not_before: OffsetDateTime, pub not_after: OffsetDateTime, } impl BERDecodable for Validity { #[cfg_attr(feature = "tracing", tracing::instrument(name = "Validity::decode_ber"))] fn decode_ber(reader: BERReader) -> ASN1Result<Self> { #[cfg(feature = "tracing")] debug!("parsing validity"); reader.read_sequence(|reader| { let nb = *reader.next().read_utctime()?.datetime(); let na = *reader.next().read_utctime()?.datetime(); Ok(Validity { not_before: nb, not_after: na, }) }) } } impl DEREncodable for Validity { fn encode_der(&self, writer: DERWriter) { writer.write_sequence(|writer| { let nb = UTCTime::from_datetime(self.not_before); let na = UTCTime::from_datetime(self.not_after); writer.next().write_utctime(&nb); writer.next().write_utctime(&na); }); } } #[cfg(test)] mod tests { use super::*; use time::macros::datetime; #[test] fn validity_should_decode_correctly () { let asserted = vec!(0x30,0x1e, // SEQUENCE, 30 bytes 0x17,0x0d, // UTCTime type, len 13 bytes 0x32,0x30, // yy - 20 in ASCII 0x30,0x39, // MM - 09 in ASCII 0x30,0x39, // dd - 09 in ASCII 0x30,0x31, // HH - 01 in ASCII 0x34,0x36, // mm - 46 in ASCII 0x34,0x30, // ss - 40 in ASCII 0x5a, // tz - Z in ASCII 0x17,0x0d, // UTCTime type, len 13 bytes 0x32,0x31, // yy - 21 in ASCII 0x30,0x39, // MM - 09 in ASCII 0x30,0x39, // dd - 09 in ASCII 0x30,0x31, // HH - 01 in ASCII 0x34,0x36, // mm - 46 in ASCII 0x34,0x30, // ss - 40 in ASCII 0x5a); // tz - Z let then = datetime!(2020-09-09 01:46:40 UTC); let when = datetime!(2021-09-09 01:46:40 UTC); let expected = Ok(Validity { not_before: then, not_after: when }); let actual = yasna::parse_der(&asserted, Validity::decode_ber); assert_eq!(actual, expected); } #[test] fn validity_should_encode_correctly () { let expected = vec!(0x30,0x1e, // SEQUENCE, 30 bytes 0x17,0x0d, // UTCTime type, len 13 bytes 0x32,0x30, // yy - 20 in ASCII 0x30,0x39, // MM - 09 in ASCII 0x30,0x39, // dd - 09 in ASCII 0x30,0x31, // HH - 01 in ASCII 0x34,0x36, // mm - 46 in ASCII 0x34,0x30, // ss - 40 in ASCII 0x5a, // tz - Z in ASCII 0x17,0x0d, // UTCTime type, len 13 bytes 0x32,0x31, // yy - 21 in ASCII 0x30,0x39, // MM - 09 in ASCII 0x30,0x39, // dd - 09 in ASCII 0x30,0x31, // HH - 01 in ASCII 0x34,0x36, // mm - 46 in ASCII 0x34,0x30, // ss - 40 in ASCII 0x5a); // tz - Z let then = datetime!(2020-09-09 01:46:40 UTC); //Utc.ymd(2020, 9, 9).and_hms(1, 46, 40); let when = datetime!(2021-09-09 01:46:40 UTC); //Utc.ymd(2021, 9, 9).and_hms(1, 46, 40); let validity = Validity { not_before: then, not_after: when }; let der = yasna::encode_der(&validity); assert_eq!(der, expected); } }
true
b51a9707d1c919cd7663a4659374f32aa7973122
Rust
matt-thomson/advent-of-code
/2019/src/day02.rs
UTF-8
1,516
3.328125
3
[ "MIT" ]
permissive
use std::path::PathBuf; use structopt::StructOpt; use crate::intcode::Program; use crate::problem::Problem; #[derive(Debug, StructOpt)] pub struct Day02 { #[structopt(parse(from_os_str))] input: PathBuf, target: i64, } impl Problem for Day02 { type Output = i64; fn part_one(&self) -> i64 { let program = Program::read(&self.input); output(&program, 12, 2) } fn part_two(&self) -> i64 { let program = Program::read(&self.input); let max = program.len().min(100) as i64; for noun in 0..max { for verb in 0..max { if output(&program, noun, verb) == self.target { return noun * 100 + verb; } } } unreachable!(); } } fn output(program: &Program, noun: i64, verb: i64) -> i64 { let mut computer = program.launch(); computer.poke(1, noun); computer.poke(2, verb); computer.run(&[]); computer.peek(0) } #[cfg(test)] mod tests { use super::*; use crate::problem::Problem; #[test] fn test_part_one() { let input = PathBuf::from("fixtures/day02.txt"); let target = 3100; let problem = Day02 { input, target }; assert_eq!(problem.part_one(), 3100); } #[test] fn test_part_two() { let input = PathBuf::from("fixtures/day02.txt"); let target = 3100; let problem = Day02 { input, target }; assert_eq!(problem.part_two(), 412); } }
true
0b76b64ee69f0fa5bff2499ee3a3719a33ad6c22
Rust
bumzack/godot
/game-physics/src/particle_contacts/particle_rod_constraint.rs
UTF-8
2,182
2.796875
3
[]
no_license
use math::prelude::*; use crate::force::particle_force_types::ParticleIdx; use crate::{ParticleConstraintOps, ParticleContact, ParticleForceRegistry, ParticleForceRegistryOps, ParticleOps}; pub struct ParticleRodConstraint { length: f32, particle: Option<ParticleIdx>, anchor: Tuple4D, } impl ParticleConstraintOps for ParticleRodConstraint { fn add_contact(&mut self, registry: &ParticleForceRegistry, limit: usize) -> Option<Vec<ParticleContact>> { // find length of cable let current_len = self.current_length(registry); //check overextended if current_len == self.length { return None; } let mut contact = ParticleContact::new(); contact.set_particle0(self.particle); contact.set_particle1(None); let p0 = registry.get_particle(self.particle.unwrap()); let normal = &self.anchor - p0.get_position(); let normal = Tuple4D::normalize(&normal); // the contact normal depends on whether extend or compress if current_len > self.length { contact.set_contact_normal(normal); contact.set_penetration(current_len - self.length) } else { contact.set_contact_normal(&normal * (-1.0)); contact.set_penetration(self.length - current_len); } contact.set_restitution(0.0); Some(vec![contact]) } fn current_length(&self, registry: &ParticleForceRegistry) -> f32 { let p0 = &registry.get_particle(self.particle.unwrap()); let relative_distance = &self.anchor - p0.get_position(); Tuple4D::magnitude(&relative_distance) } } impl ParticleRodConstraint { pub fn new() -> ParticleRodConstraint { ParticleRodConstraint { length: 0.0, particle: None, anchor: Tuple4D::empty(), } } pub fn set_length(&mut self, length: f32) { self.length = length; } pub fn get_length(&mut self) -> f32 { self.length } pub fn set_particle(&mut self, p0: Option<ParticleIdx>) { self.particle = p0; } } // TODO #[test] fn test_particle_contact() {}
true
d7c094fcdf2c3ae533371eb08762348ee131b73a
Rust
lamafab/serde-scale
/serde-scale-tests/tests/conformance.rs
UTF-8
5,133
2.578125
3
[ "Zlib" ]
permissive
// Copyright (C) 2020 Stephane Raux. Distributed under the zlib license. use parity_scale_codec::{Encode, OptionBool}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::{ error::Error, fmt::Debug, }; fn roundtrips<T>(v: &T) -> Result<(), Box<dyn Error>> where T: Debug + Serialize + DeserializeOwned + PartialEq, { let rebuilt = serde_scale::from_slice::<T>(&serde_scale::to_vec(v)?)?; if *v == rebuilt { Ok(()) } else { let msg = format!( "Values before and after serialization differ.\n\ Before: {:?}\n\ After: {:?}", v, rebuilt, ); Err(msg.into()) } } fn same_as_codec<T, U>(v: &T, codec_v: &U) -> Result<(), Box<dyn Error>> where T: Debug + Serialize, U: Encode, { let out = serde_scale::to_vec(v)?; let codec_out = codec_v.encode(); if out == codec_out { Ok(()) } else { let msg = format!( "Serialization result differs from the reference implementation.\n\ serde-scale: {:?}\n\ parity-scale-codec: {:?}", out, codec_out, ); Err(msg.into()) } } struct TestInfo<T, U> { value: T, codec_value: U, } impl<T, U> TestInfo<T, U> { fn new(value: T, codec_value: U) -> Self { Self { value, codec_value } } } impl<T: Clone> From<T> for TestInfo<T, T> { fn from(x: T) -> Self { TestInfo { value: x.clone(), codec_value: x, } } } trait Test { fn run<T, U, I>(&self, info: I) -> Result<(), Box<dyn Error>> where I: Into<TestInfo<T, U>>, T: Debug + Serialize + DeserializeOwned + PartialEq, U: Encode; fn run_with<T, U>(&self, value: T, codec_value: U) -> Result<(), Box<dyn Error>> where T: Debug + Serialize + DeserializeOwned + PartialEq, U: Encode, { self.run(TestInfo::new(value, codec_value)) } } struct Roundtrips; impl Test for Roundtrips { fn run<T, U, I>(&self, info: I) -> Result<(), Box<dyn Error>> where I: Into<TestInfo<T, U>>, T: Debug + Serialize + DeserializeOwned + PartialEq, U: Encode, { let info = info.into(); roundtrips(&info.value).map_err(|e| { format!("{:?} did not roundtrip:\n{}", info.value, e).into() }) } } struct SameAsCodec; impl Test for SameAsCodec { fn run<T, U, I>(&self, info: I) -> Result<(), Box<dyn Error>> where I: Into<TestInfo<T, U>>, T: Debug + Serialize + DeserializeOwned + PartialEq, U: Encode, { let info = info.into(); same_as_codec(&info.value, &info.codec_value).map_err(|e| { format!( "{:?} serialized differently from reference implementation:\n{}", info.value, e, ).into() }) } } fn apply_test<T: Test>(test: T) { let results = vec![ test.run(i8::min_value()), test.run(1_i8), test.run(i8::max_value()), test.run(i16::min_value()), test.run(1_i8), test.run(i16::max_value()), test.run(i32::min_value()), test.run(1_i32), test.run(i32::max_value()), test.run(i64::min_value()), test.run(1_i64), test.run(i64::max_value()), test.run(u8::min_value()), test.run(1_u8), test.run(u8::max_value()), test.run(u16::min_value()), test.run(1_u16), test.run(u16::max_value()), test.run(u32::min_value()), test.run(1_u32), test.run(u32::max_value()), test.run(u64::min_value()), test.run(1_u64), test.run(u64::max_value()), test.run(false), test.run(true), test.run(None::<i32>), test.run(Some(3_i32)), test.run_with(None::<bool>, OptionBool(None)), test.run_with(Some(false), OptionBool(Some(false))), test.run_with(Some(true), OptionBool(Some(true))), test.run(Ok::<i32, String>(3)), test.run(Err::<String, i32>(3)), test.run(vec![1, 2, 3]), test.run(String::from("foo")), test.run((3, String::from("foo"))), test.run(Operator { name: "+".into(), priority: 2 }), test.run(Expression::Const(3)), test.run(Expression::Op( Box::new(Expression::Const(2)), Operator { name: "+".into(), priority: 2 }, Box::new(Expression::Const(3)), )), ]; let error_msg = results .into_iter() .flat_map(|r| r.err()) .map(|e| format!("\n{}\n", e)) .collect::<String>(); assert!(error_msg.is_empty(), error_msg); } #[test] fn data_set_roundtrips() { apply_test(Roundtrips); } #[test] fn results_match_codec() { apply_test(SameAsCodec); } #[derive(Clone, Debug, Deserialize, Encode, PartialEq, Serialize)] struct Operator { name: String, priority: u8, } #[derive(Clone, Debug, Deserialize, Encode, PartialEq, Serialize)] enum Expression { Const(i32), Op(Box<Expression>, Operator, Box<Expression>), }
true
0148f930886345f1011217658ca45b8298f304d5
Rust
LeonardoRiojaMachineVentures/Varied
/Cargoless/sum.rs
UTF-8
2,413
3.4375
3
[]
no_license
enum Paren { Open, Close, } impl Paren { fn validate(x : Vec<Paren>) -> Result<bool, ()> { let mut count = 0usize; for i in x.iter() { match i { Paren::Open => { count = match count.checked_add(1) { Some(a) => {a}, None => {return Err(());}, } }, Paren::Close => { count = match count.checked_sub(1) { Some(a) => {a}, None => {return Ok(false);}, } }, } } return Ok(count == 0usize); } } /* set n &Natural let k &Natural : &Natural::LessThanEq(n k) $ Set::is_finite(n) let a &Natural let b &Natural let c &Natural : &Natural::GreaterThanEq(a b) : &Natural::GreaterThanEq(b c) $ &Natural::GreaterThanEq(a c) $ Set::order_is_transitive(set &Natural &Natural::GreaterThanEq) $ Set::order_is_transitive(n &Natural::GreaterThanEq) let p SortedArray(n GreaterThanEq) enum Char ClosingP OpeningP ClosingA OpeningA impl Char validate(x let [Char]) (let Boolean) */ enum Paren { CurlyOpen, CurlyClose, SquareOpen, SquareClose, } impl Paren { fn validate(x : Vec<Paren>) -> bool { let mut left = 0; let mut right = 1; fn is_end(left : Option<&Paren>, right : Option<&Paren>) -> bool { } fn is_match(left : &Paren, right : &Paren) -> bool { use crate::Paren::*; match (left, right) { (CurlyOpen, CurlyClose) => true, (SquareOpen, SquareClose) => true, _ => false, } } } } fn pair_sum_sequence(n : u8) -> u8 { let mut sum = 0u8; for i in 0..n { sum += pair_sum(i, i + 1); } return sum; } fn pair_sum(a : u8, b : u8) -> u8 { return a + b } fn sum(x : u8) -> u8 { if x == 0 { return 0; } return (x + sum(x - 1)); } fn main() { println!("{}", pair_sum_sequence(5)); println!("{}", sum(5)); println!("{}", what(5)); } fn what(n : u8) -> u8 { if n <= 1 { return 1; } return what(n - 1) + what(n - 1); } fn sum_and_product(v : &[u8]) -> () { let mut sum = 0u8; let mut product = 1; for i in v { sum += i; product *= i; } }
true
612b4e35133809bece5082a83ff9758ad2d47ee7
Rust
jDomantas/ccg
/crates/game/src/loader/config.rs
UTF-8
1,117
2.796875
3
[]
no_license
use std::collections::HashMap; use serde::Deserialize; #[derive(Deserialize, Debug)] pub struct Card { pub icon: String, pub title: String, pub description: Vec<String>, pub effect: CardEffect, } #[derive(Deserialize, Debug)] pub enum CardEffect { None, Enemy { icon: String, attack: u32, health: u32, #[serde(default)] rewards: Vec<CardEffect>, }, Buff(Buff), BossBuff(Buff), Heal { health: u32, }, Coins { amount: u32, }, Attack { use_base: bool, bonus: u32, }, HealEnemy { health: u32, }, Weapon { icon: String, damage: u32, durability: u32, }, Buy { price: u32, effect: Box<CardEffect>, }, Disarm, } #[derive(Deserialize, Debug)] pub enum Buff { NextAttackBonus { bonus: u32 }, AttackBonus { bonus: u32 }, } #[derive(Deserialize, Debug)] pub struct Decks { pub draw: HashMap<String, u32>, pub trap: HashMap<String, u32>, pub treasure: HashMap<String, u32>, pub boss: String, }
true
af7a7ea6d1fd26c15257fdcae105708ec6402ea3
Rust
sgrowe/advent-of-code-2019
/src/int_code.rs
UTF-8
9,139
3.46875
3
[]
no_license
use std::num::ParseIntError; use std::str::FromStr; #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Mode { Position, Immediate, } impl Mode { fn from_i64(int: i64) -> Mode { if int == 0 { Mode::Position } else { Mode::Immediate } } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Instruction { Add([Mode; 3]), Multiply([Mode; 3]), ReadInput(Mode), WriteOutput(Mode), JumpIfTrue([Mode; 2]), JumpIfFalse([Mode; 2]), LessThan([Mode; 3]), Equals([Mode; 3]), } impl Instruction { fn from_i64(op_code: i64) -> Instruction { let code = op_code % 100; let mode_1 = Mode::from_i64((op_code / 100) % 10); let mode_2 = Mode::from_i64((op_code / 1000) % 10); let mode_3 = Mode::from_i64((op_code / 10000) % 10); match code { 1 => Instruction::Add([mode_1, mode_2, mode_3]), 2 => Instruction::Multiply([mode_1, mode_2, mode_3]), 3 => Instruction::ReadInput(mode_1), 4 => Instruction::WriteOutput(mode_1), 5 => Instruction::JumpIfTrue([mode_1, mode_2]), 6 => Instruction::JumpIfFalse([mode_1, mode_2]), 7 => Instruction::LessThan([mode_1, mode_2, mode_3]), 8 => Instruction::Equals([mode_1, mode_2, mode_3]), _ => panic!("Unexpected opcode: {}", op_code), } } fn width(&self) -> usize { match self { Instruction::Add(_) => 4, Instruction::Multiply(_) => 4, Instruction::ReadInput(_) => 2, Instruction::WriteOutput(_) => 2, Instruction::JumpIfTrue(_) => 3, Instruction::JumpIfFalse(_) => 3, Instruction::LessThan(_) => 4, Instruction::Equals(_) => 4, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Program { pub code: Vec<i64>, i: usize, } impl Program { pub fn new(code: Vec<i64>) -> Program { Program { code, i: 0 } } pub fn run<I>(&mut self, inputs: I) -> Vec<i64> where I: IntoIterator<Item = i64>, { let mut inputs_iter = inputs.into_iter(); let mut outputs = Vec::new(); while let Some(output) = self.run_until_next_output(&mut inputs_iter) { outputs.push(output); } outputs } pub fn run_until_next_output<I>(&mut self, inputs: &mut I) -> Option<i64> where I: Iterator<Item = i64>, { while self.code[self.i] != 99 { let instruction = Instruction::from_i64(self.code[self.i]); match instruction { Instruction::Add([mode_1, mode_2, mode_3]) => { let x = self.read(1, mode_1); let y = self.read(2, mode_2); self.write(3, mode_3, x + y); } Instruction::Multiply([mode_1, mode_2, mode_3]) => { let x = self.read(1, mode_1); let y = self.read(2, mode_2); self.write(3, mode_3, x * y); } Instruction::ReadInput(mode) => { let input = inputs.next().expect("No input given"); self.write(1, mode, input); } Instruction::WriteOutput(mode) => { let output = self.read(1, mode); self.i += instruction.width(); return Some(output); } Instruction::JumpIfTrue([mode_1, mode_2]) => { if self.read(1, mode_1) != 0 { self.i = self.read(2, mode_2) as usize; continue; } } Instruction::JumpIfFalse([mode_1, mode_2]) => { if self.read(1, mode_1) == 0 { self.i = self.read(2, mode_2) as usize; continue; } } Instruction::LessThan([mode_1, mode_2, mode_3]) => { let x = self.read(1, mode_1); let y = self.read(2, mode_2); let out = if x < y { 1 } else { 0 }; self.write(3, mode_3, out); } Instruction::Equals([mode_1, mode_2, mode_3]) => { let x = self.read(1, mode_1); let y = self.read(2, mode_2); let out = if x == y { 1 } else { 0 }; self.write(3, mode_3, out); } } self.i += instruction.width(); } None } fn read(&self, offset: usize, mode: Mode) -> i64 { let val = self.code[self.i + offset]; match mode { Mode::Position => self.code[val as usize], Mode::Immediate => val, } } fn write(&mut self, offset: usize, mode: Mode, value: i64) { let write_addr = match mode { Mode::Position => self.code[self.i + offset] as usize, Mode::Immediate => self.i + offset, }; self.code[write_addr] = value; } } impl FromStr for Program { type Err = ParseIntError; fn from_str(input: &str) -> Result<Program, Self::Err> { input .split(',') .map(|s| s.parse::<i64>()) .collect::<Result<Vec<i64>, _>>() .map(Program::new) } } #[cfg(test)] mod day_two_tests { use super::*; fn assert_program_output_is(input: &str, expected_code: Vec<i64>) { let mut program = input.parse::<Program>().unwrap(); program.run(vec![]); assert_eq!(program.code, expected_code) } #[test] fn example_input() { assert_program_output_is( "1,9,10,3,2,3,11,0,99,30,40,50", vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50], ) } #[test] fn example_test_case_1() { assert_program_output_is("1,0,0,0,99", vec![2, 0, 0, 0, 99]) } #[test] fn example_test_case_2() { assert_program_output_is("2,3,0,3,99", vec![2, 3, 0, 6, 99]) } #[test] fn example_test_case_3() { assert_program_output_is("2,4,4,5,99,0", vec![2, 4, 4, 5, 99, 9801]) } #[test] fn example_test_case_4() { assert_program_output_is("1,1,1,4,99,5,6,0,99", vec![30, 1, 1, 4, 2, 5, 6, 0, 99]) } } #[cfg(test)] mod day_five_part_one_tests { use super::*; use std::fs::read_to_string; #[test] fn allows_different_modes_for_operations() { let mut program = "1002,4,3,4,33".parse::<Program>().unwrap(); program.run(vec![]); assert_eq!(program.code, vec![1002, 4, 3, 4, 99]); } #[test] fn supports_negative_values_in_program_code() { let mut program = "1101,100,-1,4,0".parse::<Program>().unwrap(); program.run(vec![]); assert_eq!(program.code, vec![1101, 100, -1, 4, 99]); } #[test] fn supports_op_codes_3_and_4() { let mut program = "3,0,4,0,99".parse::<Program>().unwrap(); let output = program.run(vec![5]); assert_eq!(output, vec!(5)); } #[test] fn runs_diagnostic_program_correctly() { let mut program = read_to_string("src/five.txt") .unwrap() .trim() .parse::<Program>() .unwrap(); let output = program.run(vec![1]); let test_codes = &output[0..output.len() - 1]; assert!(test_codes.iter().all(|&x| x == 0)); } } #[cfg(test)] mod day_five_part_two_tests { use super::*; #[test] fn example_case_1() { let program = "3,9,8,9,10,9,4,9,99,-1,8".parse::<Program>().unwrap(); assert_eq!(program.clone().run(vec!(7)), vec!(0)); assert_eq!(program.clone().run(vec!(8)), vec!(1)); assert_eq!(program.clone().run(vec!(9)), vec!(0)); } #[test] fn example_jump_case_1() { let program = "3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9" .parse::<Program>() .unwrap(); assert_eq!(program.clone().run(vec!(0)), vec!(0)); assert_eq!(program.clone().run(vec!(1)), vec!(1)); assert_eq!(program.clone().run(vec!(-5)), vec!(1)); } #[test] fn example_jump_case_2() { let program = "3,3,1105,-1,9,1101,0,0,12,4,12,99,1" .parse::<Program>() .unwrap(); assert_eq!(program.clone().run(vec!(0)), vec!(0)); assert_eq!(program.clone().run(vec!(1)), vec!(1)); assert_eq!(program.clone().run(vec!(-5)), vec!(1)); } #[test] fn larger_example() { let program = "3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99" .parse::<Program>() .unwrap(); assert_eq!(program.clone().run(vec!(7)), vec!(999)); assert_eq!(program.clone().run(vec!(8)), vec!(1000)); assert_eq!(program.clone().run(vec!(9)), vec!(1001)); } }
true
563f23a15a2f49bda873c09c5885bb0a7b614aba
Rust
youngqqcn/RustNotes
/examples/ch16/rust_mutex_1.rs
UTF-8
1,770
3.75
4
[]
no_license
use std::sync::{ Mutex, Arc }; use std::rc::Rc; /* fn foo1() { let counter_mtx = Mutex::new(0); let mut threads = Vec::new();; for i in 0..10 { let hd = std::thread::spawn( move || { let mut num = counter_mtx.lock().expect("lock error"); *num += 1; }); threads.push(hd); } for thd in threads { thd.join().expect("join error"); } println!("{:?}", *counter_mtx.lock().expect("lock error")); } */ /* // `std::rc::Rc<std::sync::Mutex<i32>>` cannot be sent between threads safely fn foo2() { let counter_rc = Rc::new( Mutex::new(0) ); let mut threads = Vec::new();; for i in 0..10 { let cnt = counter_rc.clone(); let hd = std::thread::spawn( move || { let mut num = cnt.lock().expect("lock error"); *num += 1; }); threads.push(hd); } for thd in threads { thd.join().expect("join error"); } println!("{:?}", *counter_rc.lock().expect("lock error")); } */ fn foo3() { let counter_arc = Arc::new( Mutex::new(0) ); let mut threads = Vec::new(); for _ in 0..10 { let cnt = counter_arc.clone(); let hd = std::thread::spawn( move || { let mut num = cnt.lock().expect("lock error"); // pub fn lock(&self) -> LockResult<MutexGuard<T>> // lock() 返回的是 MutexGuard ,离开作用域会自动 unlock // 需要解引用才能获取到 T *num += 1; }); threads.push(hd); } for thd in threads { thd.join().expect("join error"); } println!("{:?}", *counter_arc.lock().expect("lock error")); } fn main() { // foo1(); // foo2(); foo3(); }
true
cfa88732e6efc51100fa3f2a3c7c23c368ac1911
Rust
AreebSiddiqui/ONSITE-PIAIC-
/chapter6_1/e1/src/main.rs
UTF-8
223
2.515625
3
[]
no_license
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; fn main () { let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); println!("{}",localhost_v4); }
true
5ecb9d4a7006de26e896ee349d8bfb91c53cbf1f
Rust
neutronest/GynooR
/tests/test_geometry.rs
UTF-8
454
2.71875
3
[ "MIT" ]
permissive
extern crate gynoo_r; use gynoo_r::geometry; #[test] fn test_gvector() { let mut v1 = geometry::GVector{x:1.0, y:2.0, z:3.0}; let mut v2 = geometry::GVector{x:2.0, y:3.0, z:4.0}; let mut v3 = v1 + v2; let mut v4 = geometry::GVector{x:20.0, y:30.0, z:40.0}; println!("v3: {:?}", v3); println!("v1+v4: {:?}", v1.clone()+v4); println!("v3.len: {:?}", v3.length()); v3.normalize(); println!("v1.normalize: {:?}", v3); }
true
cfdc86a6ed383f02ddfb55b58133e6cd7a13324f
Rust
mkalam-alami/advent-of-code
/2020-rust/day18parser.rs
UTF-8
3,620
3.796875
4
[]
no_license
use std::fmt::Display; pub struct Expression { left: ExpressionHand, right: ExpressionHand, operator: char } impl Expression { pub fn evaluate(&self) -> usize { match self.operator { '*' => self.left.evaluate() * self.right.evaluate(), '+' => self.left.evaluate() + self.right.evaluate(), _ => panic!("unknown operator {}", self.operator) } } } impl Display for Expression { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { write!(f, "E({} {} {})", self.left, self.operator, self.right) } } pub enum ExpressionHand { VALUE(usize), EXPRESSION(Box<Expression>) } impl ExpressionHand { fn evaluate(&self) -> usize { match self { ExpressionHand::VALUE(v) => *v, ExpressionHand::EXPRESSION(expression) => expression.evaluate() } } } impl Display for ExpressionHand { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { match self { ExpressionHand::VALUE(v) => write!(f, "{}", v), ExpressionHand::EXPRESSION(expression) => write!(f, "{}", expression) } } } pub struct Parser<'a> { pub input: &'a str } impl <'a> Parser<'a> { pub fn new(input: &'a str) -> Parser<'a> { Parser { input } } pub fn parse(&mut self) -> Expression { self.parse_expression(self.input.chars() .rev() .map(|l| match l { '(' => ')', ')' => '(', _ => l }) .collect::<String>() .as_str()) } fn parse_expression(&self, input: &'a str) -> Expression { // println!("parsing: {}", input); let left: ExpressionHand; let c = input.as_bytes()[0] as char; let mut next_char = 1; match c { '(' => { let closing_parenthesis = self.find_closing_parenthesis_index(input); // println!("inside parentheses: {} ({}=> {})", &input[1..closing_parenthesis - 1], input, closing_parenthesis); let child_expression: Expression = self.parse_expression(&input[1..closing_parenthesis - 1]); left = ExpressionHand::EXPRESSION(Box::from(child_expression)); next_char = closing_parenthesis; }, _ => { // println!("left is {}", c); left = ExpressionHand::VALUE(c.to_string().parse::<usize>().unwrap()); } } if next_char >= input.len() { return Expression { left, right: ExpressionHand::VALUE(0), operator: '+' }; } // println!("searching operator at {} of input {}", next_char, input); let operator = input.chars().nth(next_char).expect("fell off expression while parsing operator"); let right: ExpressionHand; let remaining = &input[next_char + 1..input.len()]; if next_char + 1 == input.len() - 1 { // println!("right is {}", remaining); right = ExpressionHand::VALUE(remaining.parse::<usize>().unwrap()); } else { // println!("right is sub-expression {}", remaining); let child_expression: Expression = self.parse_expression(remaining); right = ExpressionHand::EXPRESSION(Box::from(child_expression)); } Expression { left, right, operator } } fn find_closing_parenthesis_index(&self, input: &str) -> usize { let mut it = input.chars(); let mut open_parenthesis_inside = 0; let mut index = 0; while let Some(c) = it.next() { index += 1; // println!("{}", c); match c { '(' => open_parenthesis_inside += 1, ')' => { if open_parenthesis_inside > 1 { open_parenthesis_inside -= 1; } else { break; } }, _ => () } } index } }
true
cdab1d372d1f898b2084aefb18494dfd1324e694
Rust
geokala/korama
/src/music_library.rs
UTF-8
4,650
2.8125
3
[]
no_license
use id3::Tag; use std::ffi::OsStr; use std::fs::read_to_string; use std::path::{Path, PathBuf}; use crate::delimiters::{END_OF_FIELD, END_OF_HEADER}; use crate::shared::{DynamicSource, Saveable}; use crate::track::Track; const EXTENSION: &str = "lib"; #[derive(Clone)] pub struct MusicLibrary { name: String, path: String, tracks: Vec<Track>, } impl MusicLibrary { pub fn new(name: String, path: String) -> MusicLibrary { MusicLibrary{ name, path, tracks: Vec::new(), } } pub fn load(saved_library_path: String, saved_library_name: String) -> MusicLibrary { let mut library_path = PathBuf::from(&saved_library_path); library_path.push(OsStr::new(&format!("{}.{}", &saved_library_name, &EXTENSION))); let saved_data = match read_to_string(&library_path) { Ok(data) => data, Err(err) => panic!("Could not load library from {}: {:#?}", library_path.display(), err), }; let header_details = MusicLibrary::process_save_header(&saved_data); let tracks = MusicLibrary::load_tracks(&saved_data); MusicLibrary{ name: header_details[0].to_string(), path: header_details[1].to_string(), tracks: tracks, } } pub fn get_path(&self) -> &str { &self.path } pub fn scan(&mut self) { let mut scan_paths = Vec::new(); scan_paths.push(Path::new(&self.path).to_path_buf()); while scan_paths.len() > 0 { let current_path = scan_paths.pop().unwrap(); for entry in current_path.read_dir().expect("Could not read {}.") { let entry = entry.unwrap().path(); if entry.is_file() { let extension = match entry.extension() { Some(osstr) => osstr, None => OsStr::new(""), }; if extension == OsStr::new("mp3") { self.add_track_details(&entry); } } else if entry.is_dir() { scan_paths.push(entry.to_path_buf()); } } } } fn add_track_details(&mut self, path: &Path) { let tags = match Tag::read_from_path(path) { Ok(res) => res, Err(_) => { println!("Unable to read id3v2 tags for {}", path.display()); return; }, }; let track_name: String = match tags.get("TIT2") { Some(res) => res.to_string(), None => { println!("Could not get track name (id3v2 TIT2 tag) for {}", path.display()); return; }, }; let artist: String = match tags.get("TPE1") { Some(res) => res.to_string(), None => { println!("Could not get artist (id3v2 TPE1 tag) for {}", path.display()); return; }, }; let album: String = match tags.get("TALB") { Some(res) => res.to_string(), None => String::from(""), // Album is not required }; let track_number: String = match tags.get("TRCK") { Some(res) => res.to_string(), None => String::from(""), // Track number is not required }; self.tracks.push( Track { track_name, artist, album, track_number, path: String::from(path.to_str().unwrap()), } ); } pub fn get_tracks_by_title(&self) -> Vec<Track> { let tracks = &mut self.tracks.clone(); tracks.sort_by(|a, b| a.order_by_track(b)); tracks.clone() } pub fn get_tracks_by_artist_and_album(&self) -> Vec<Track> { let tracks = &mut self.tracks.clone(); tracks.sort_by(|a, b| a.order_by_artist_and_album(b)); tracks.clone() } } impl Saveable for MusicLibrary { fn get_extension(&self) -> &str { EXTENSION } fn get_name(&self) -> &str { &self.name } fn get_tracks(&self) -> Vec<Track> { self.tracks.clone() } fn get_header(&self) -> String { let mut header = String::new(); // Generate header header.push_str(&self.name); header.push(END_OF_FIELD); header.push_str(&self.path); header.push(END_OF_HEADER); header } } impl DynamicSource for MusicLibrary { fn get_tracks(&self) -> Vec<Track> { self.tracks.clone() } }
true
53deacfbdac894cafd0b6dfce895f2bfb5948fed
Rust
GiorgiBeriashvili/cli-timer
/src/color.rs
UTF-8
562
3.140625
3
[ "Apache-2.0", "MIT" ]
permissive
use std::io::Write; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub fn apply_color(colored: bool, text: String, color: Color) { if colored { print_colored(color, text); } else { print_colored(Color::White, text); } } pub fn print_colored(color: Color, text: String) { let mut stdout = StandardStream::stdout(ColorChoice::Always); stdout .set_color(ColorSpec::new().set_fg(Some(color))) .unwrap(); writeln!(&mut stdout, "{}", text).unwrap(); stdout.reset().unwrap(); }
true
9760023f9c23b3ff1ffc5b98e3de11dc14eb5449
Rust
Gregoor/bevy_contrib_bobox
/examples/outline_2d.rs
UTF-8
4,239
2.609375
3
[ "MIT" ]
permissive
use bevy::prelude::*; use bevy_contrib_bobox::{Outline2dPlugin, OutlineConfiguration, OutlineMaterial}; fn main() { //env_logger::init(); App::build() .add_resource(WindowDescriptor { width: 600, height: 400, ..Default::default() }) .add_plugins(DefaultPlugins) .add_plugin(Outline2dPlugin) .add_startup_system(setup.system()) .add_system(input_system.system()) .add_system(update_system.system()) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut outline_materials: ResMut<Assets<OutlineMaterial>>, mut color_materials: ResMut<Assets<ColorMaterial>>, ) { commands .spawn(Camera2dComponents::default()) .spawn(SpriteComponents { material: color_materials.add(asset_server.load("icon.png").into()), transform: Transform { translation: Vec3::new(-100.0, -20.0, 0.0), ..Default::default() }, ..Default::default() }) .with(outline_materials.add(OutlineMaterial { configuration: OutlineConfiguration { color: Color::rgba(1.0, 0.0, 0.0, 1.0), ..Default::default() }, with_outline: true, })); commands .spawn(Camera2dComponents::default()) .spawn(SpriteComponents { material: color_materials.add(asset_server.load("playerShip1_red.png").into()), transform: Transform { translation: Vec3::new(150.0, -20.0, 0.0), ..Default::default() }, ..Default::default() }) .with(outline_materials.add(OutlineMaterial { configuration: OutlineConfiguration { color: Color::rgba(1.0, 0.5, 1.0, 1.0), ..Default::default() }, with_outline: true, })); commands .spawn(UiCameraComponents::default()) .spawn(TextComponents { style: Style { align_self: AlignSelf::FlexEnd, ..Default::default() }, text: Text { value: "".to_string(), font: asset_server.load("FiraSans-Bold.ttf"), style: TextStyle { font_size: 20.0, color: Color::WHITE, }, }, ..Default::default() }); // Just to ease keyboard input modification and text visualization commands.insert_resource(OutlineMaterial { with_outline: true, configuration: OutlineConfiguration { width: 3, inside: 1, ..Default::default() }, }); } fn input_system(input: Res<Input<KeyCode>>, mut ref_material: ResMut<OutlineMaterial>) { if input.just_pressed(KeyCode::Space) { ref_material.with_outline = !ref_material.with_outline; } if input.just_pressed(KeyCode::I) { ref_material.configuration.inside = if ref_material.configuration.inside == 0 { 1 } else { 0 }; } if input.just_pressed(KeyCode::W) { ref_material.configuration.width = match ref_material.configuration.width { x if x < 10 => x + 1, _ => 1, }; } } fn update_system( ref_material: ChangedRes<OutlineMaterial>, mut outline_materials: ResMut<Assets<OutlineMaterial>>, query: Query<&Handle<OutlineMaterial>>, mut texts: Query<Mut<Text>>, ) { for handle in query.iter() { let mut outline_material = outline_materials.get_mut(handle).unwrap(); outline_material.with_outline = ref_material.with_outline; outline_material.configuration.width = ref_material.configuration.width; outline_material.configuration.inside = ref_material.configuration.inside; } for mut text in texts.iter_mut() { text.value = format!( "Use keys <Space> <I> <W>\nwith_outline: {}\nwidth: {}\ninside: {}", ref_material.with_outline, ref_material.configuration.width, ref_material.configuration.inside ); } }
true
1c45d33d0cddad7d617990e5167f5acd44ff132f
Rust
Amdrel/nes-rs
/src/nes/instruction.rs
UTF-8
92,863
2.78125
3
[ "Apache-2.0", "MIT" ]
permissive
// Copyright 2016 Walter Kuppens. // // 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 byteorder::{LittleEndian, ReadBytesExt}; use nes::cpu::CPU; use nes::memory::Memory; use nes::opcode::Opcode::*; use nes::opcode::{decode_opcode, opcode_len, Opcode}; use std::io::Cursor; use utils::arithmetic::add_relative; use utils::paging::{page_cross, PageCross}; /// All 6502 instructions are a maximum size of 3 bytes. The first byte is the /// opcode which is determines the action of the instruction. The following 2 /// bytes are the arguments and are present depending on the opcode. #[derive(Debug, PartialEq)] pub struct Instruction(pub u8, pub u8, pub u8); impl Instruction { /// Parses an instruction from memory at the address of the program counter. pub fn parse(pc: usize, memory: &mut Memory) -> Instruction { let raw_opcode = memory.read_u8(pc); let opcode = decode_opcode(raw_opcode); let len = opcode_len(&opcode); match len { 1 => Instruction(raw_opcode, 0, 0), 2 => Instruction(raw_opcode, memory.read_u8(pc + 1), 0), 3 => Instruction(raw_opcode, memory.read_u8(pc + 1), memory.read_u8(pc + 2)), _ => panic!("Invalid instruction length returned"), } } /// Disassembles the instruction into human readable assembly. Each opcode is /// mapped to a human readable name and a pretty print function. The pretty /// print function mimic Nintendulator and are used during CPU log /// comparisons. pub fn disassemble(&self, cpu: &CPU, memory: &mut Memory) -> String { let opcode = self.opcode(); let len = opcode_len(&opcode); match opcode { ANDImm => self.disassemble_immediate("AND"), ANDZero => self.disassemble_zero_page("AND", memory), ANDZeroX => self.disassemble_zero_page_x("AND", memory, cpu), ANDAbs => self.disassemble_absolute("AND", memory), ANDAbsX => self.disassemble_absolute_x("AND", memory, cpu), ANDAbsY => self.disassemble_absolute_y("AND", memory, cpu), ANDIndX => self.disassemble_indirect_x("AND", memory, cpu), ANDIndY => self.disassemble_indirect_y("AND", memory, cpu), BCCRel => self.disassemble_relative("BCC", len, cpu), BCSRel => self.disassemble_relative("BCS", len, cpu), BEQRel => self.disassemble_relative("BEQ", len, cpu), BMIRel => self.disassemble_relative("BMI", len, cpu), EORImm => self.disassemble_immediate("EOR"), EORZero => self.disassemble_zero_page("EOR", memory), EORZeroX => self.disassemble_zero_page_x("EOR", memory, cpu), EORAbs => self.disassemble_absolute("EOR", memory), EORAbsX => self.disassemble_absolute_x("EOR", memory, cpu), EORAbsY => self.disassemble_absolute_y("EOR", memory, cpu), EORIndX => self.disassemble_indirect_x("EOR", memory, cpu), EORIndY => self.disassemble_indirect_y("EOR", memory, cpu), ORAImm => self.disassemble_immediate("ORA"), ORAZero => self.disassemble_zero_page("ORA", memory), ORAZeroX => self.disassemble_zero_page_x("ORA", memory, cpu), ORAAbs => self.disassemble_absolute("ORA", memory), ORAAbsX => self.disassemble_absolute_x("ORA", memory, cpu), ORAAbsY => self.disassemble_absolute_y("ORA", memory, cpu), ORAIndX => self.disassemble_indirect_x("ORA", memory, cpu), ORAIndY => self.disassemble_indirect_y("ORA", memory, cpu), BITZero => self.disassemble_zero_page("BIT", memory), BITAbs => self.disassemble_absolute("BIT", memory), BNERel => self.disassemble_relative("BNE", len, cpu), BPLRel => self.disassemble_relative("BPL", len, cpu), BVCRel => self.disassemble_relative("BVC", len, cpu), BVSRel => self.disassemble_relative("BVS", len, cpu), CLCImp => self.disassemble_implied("CLC"), CLDImp => self.disassemble_implied("CLD"), CLIImp => self.disassemble_implied("CLI"), CLVImp => self.disassemble_implied("CLV"), ADCImm => self.disassemble_immediate("ADC"), ADCZero => self.disassemble_zero_page("ADC", memory), ADCZeroX => self.disassemble_zero_page_x("ADC", memory, cpu), ADCAbs => self.disassemble_absolute("ADC", memory), ADCAbsX => self.disassemble_absolute_x("ADC", memory, cpu), ADCAbsY => self.disassemble_absolute_y("ADC", memory, cpu), ADCIndX => self.disassemble_indirect_x("ADC", memory, cpu), ADCIndY => self.disassemble_indirect_y("ADC", memory, cpu), SBCImm => self.disassemble_immediate("SBC"), SBCZero => self.disassemble_zero_page("SBC", memory), SBCZeroX => self.disassemble_zero_page_x("SBC", memory, cpu), SBCAbs => self.disassemble_absolute("SBC", memory), SBCAbsX => self.disassemble_absolute_x("SBC", memory, cpu), SBCAbsY => self.disassemble_absolute_y("SBC", memory, cpu), SBCIndX => self.disassemble_indirect_x("SBC", memory, cpu), SBCIndY => self.disassemble_indirect_y("SBC", memory, cpu), CMPImm => self.disassemble_immediate("CMP"), CMPZero => self.disassemble_zero_page("CMP", memory), CMPZeroX => self.disassemble_zero_page_x("CMP", memory, cpu), CMPAbs => self.disassemble_absolute("CMP", memory), CMPAbsX => self.disassemble_absolute_x("CMP", memory, cpu), CMPAbsY => self.disassemble_absolute_y("CMP", memory, cpu), CMPIndX => self.disassemble_indirect_x("CMP", memory, cpu), CMPIndY => self.disassemble_indirect_y("CMP", memory, cpu), CPXImm => self.disassemble_immediate("CPX"), CPXZero => self.disassemble_zero_page("CPX", memory), CPXAbs => self.disassemble_absolute("CPX", memory), CPYImm => self.disassemble_immediate("CPY"), CPYZero => self.disassemble_zero_page("CPY", memory), CPYAbs => self.disassemble_absolute("CPY", memory), INCZero => self.disassemble_zero_page("INC", memory), INCZeroX => self.disassemble_zero_page_x("INC", memory, cpu), INCAbs => self.disassemble_absolute("INC", memory), INCAbsX => self.disassemble_absolute_x("INC", memory, cpu), INXImp => self.disassemble_implied("INX"), INYImp => self.disassemble_implied("INY"), DECZero => self.disassemble_zero_page("DEC", memory), DECZeroX => self.disassemble_zero_page_x("DEC", memory, cpu), DECAbs => self.disassemble_absolute("DEC", memory), DECAbsX => self.disassemble_absolute_x("DEC", memory, cpu), DEXImp => self.disassemble_implied("DEX"), DEYImp => self.disassemble_implied("DEY"), ASLAcc => self.disassemble_accumulator("ASL"), ASLZero => self.disassemble_zero_page("ASL", memory), ASLZeroX => self.disassemble_zero_page_x("ASL", memory, cpu), ASLAbs => self.disassemble_absolute("ASL", memory), ASLAbsX => self.disassemble_absolute_x("ASL", memory, cpu), LSRAcc => self.disassemble_accumulator("LSR"), LSRZero => self.disassemble_zero_page("LSR", memory), LSRZeroX => self.disassemble_zero_page_x("LSR", memory, cpu), LSRAbs => self.disassemble_absolute("LSR", memory), LSRAbsX => self.disassemble_absolute_x("LSR", memory, cpu), ROLAcc => self.disassemble_accumulator("ROL"), ROLZero => self.disassemble_zero_page("ROL", memory), ROLZeroX => self.disassemble_zero_page_x("ROL", memory, cpu), ROLAbs => self.disassemble_absolute("ROL", memory), ROLAbsX => self.disassemble_absolute_x("ROL", memory, cpu), RORAcc => self.disassemble_accumulator("ROR"), RORZero => self.disassemble_zero_page("ROR", memory), RORZeroX => self.disassemble_zero_page_x("ROR", memory, cpu), RORAbs => self.disassemble_absolute("ROR", memory), RORAbsX => self.disassemble_absolute_x("ROR", memory, cpu), JMPAbs => self.disassemble_absolute_noref("JMP"), JMPInd => self.disassemble_indirect("JMP", memory), JSRAbs => self.disassemble_absolute_noref("JSR"), LDAImm => self.disassemble_immediate("LDA"), LDAZero => self.disassemble_zero_page("LDA", memory), LDAZeroX => self.disassemble_zero_page_x("LDA", memory, cpu), LDAAbs => self.disassemble_absolute("LDA", memory), LDAAbsX => self.disassemble_absolute_x("LDA", memory, cpu), LDAAbsY => self.disassemble_absolute_y("LDA", memory, cpu), LDAIndX => self.disassemble_indirect_x("LDA", memory, cpu), LDAIndY => self.disassemble_indirect_y("LDA", memory, cpu), LDXImm => self.disassemble_immediate("LDX"), LDXZero => self.disassemble_zero_page("LDX", memory), LDXZeroY => self.disassemble_zero_page_y("LDX", memory, cpu), LDXAbs => self.disassemble_absolute("LDX", memory), LDXAbsY => self.disassemble_absolute_y("LDX", memory, cpu), LDYImm => self.disassemble_immediate("LDY"), LDYZero => self.disassemble_zero_page("LDY", memory), LDYZeroX => self.disassemble_zero_page_x("LDY", memory, cpu), LDYAbs => self.disassemble_absolute("LDY", memory), LDYAbsX => self.disassemble_absolute_x("LDY", memory, cpu), BRKImp => self.disassemble_implied("BRK"), NOPImp => self.disassemble_implied("NOP"), PHAImp => self.disassemble_implied("PHA"), PHPImp => self.disassemble_implied("PHP"), PLAImp => self.disassemble_implied("PLA"), PLPImp => self.disassemble_implied("PLP"), RTIImp => self.disassemble_implied("RTI"), RTSImp => self.disassemble_implied("RTS"), SECImp => self.disassemble_implied("SEC"), SEDImp => self.disassemble_implied("SED"), SEIImp => self.disassemble_implied("SEI"), STAZero => self.disassemble_zero_page("STA", memory), STAZeroX => self.disassemble_zero_page_x("STA", memory, cpu), STAAbs => self.disassemble_absolute("STA", memory), STAAbsX => self.disassemble_absolute_x("STA", memory, cpu), STAAbsY => self.disassemble_absolute_y("STA", memory, cpu), STAIndX => self.disassemble_indirect_x("STA", memory, cpu), STAIndY => self.disassemble_indirect_y("STA", memory, cpu), STXZero => self.disassemble_zero_page("STX", memory), STXZeroY => self.disassemble_zero_page_y("STX", memory, cpu), STXAbs => self.disassemble_absolute("STX", memory), STYZero => self.disassemble_zero_page("STY", memory), STYZeroX => self.disassemble_zero_page_x("STY", memory, cpu), STYAbs => self.disassemble_absolute("STY", memory), TAXImp => self.disassemble_implied("TAX"), TAYImp => self.disassemble_implied("TAY"), TSXImp => self.disassemble_implied("TSX"), TXAImp => self.disassemble_implied("TXA"), TXSImp => self.disassemble_implied("TXS"), TYAImp => self.disassemble_implied("TYA"), _ => "GARBAGE".to_string(), } } /// Logs a human-readable representation of the instruction along with the /// CPU state in an easy to parse format. /// /// TODO: Return a string for the test suite so CPU correctness can be /// checked. Also it may be more appropriate to move this function into the /// CPU. pub fn log(&self, cpu: &CPU, memory: &mut Memory) -> String { let opcode = self.opcode(); // Get human readable hex of the instruction bytes. A pattern match is // used as bytes that do not exist in an instruction should not be // displayed (rather than displaying the default struct value 0). This // is to keep the logs consistent with Nintendulator's logs. let instr_str = match opcode_len(&opcode) { 1 => format!("{:02X} ", self.0), 2 => format!("{:02X} {:02X} ", self.0, self.1), 3 => format!("{:02X} {:02X} {:02X}", self.0, self.1, self.2), _ => panic!("Invalid instruction length given"), }; // Prints the CPU state and disassembled instruction in a nice parsable // format. In the future this output will be used for automatically // testing the CPU's accuracy. // // NOTE: CYC is not cycles like the name sugests, but PPU dots. The PPU // can output 3 dots every CPU cycle on NTSC (PAL outputs an extra dot // every fifth CPU cycle). // 0 6 16 48 53 58 63 68 74 let disassembled = self.disassemble(cpu, memory); return format!( "{:04X} {} {:30} A:{:02X} X:{:02X} Y:{:02X} P:{:02X} SP:{:02X} CYC:{:3}", cpu.pc, instr_str, disassembled, cpu.a, cpu.x, cpu.y, cpu.p, cpu.sp, cpu.ppu_dots ); } /// Execute the instruction with a routine that corresponds with it's /// opcode. All routines for every instruction in the 6502 instruction set /// are present here. #[inline(always)] pub fn execute(&self, cpu: &mut CPU, memory: &mut Memory) { let opcode = self.opcode(); let len = opcode_len(&opcode) as u16; match opcode { ANDImm => { cpu.a &= self.immediate(); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 2; cpu.pc += len; } ANDZero => { cpu.a &= self.dereference_zero_page(memory); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 3; cpu.pc += len; } ANDZeroX => { cpu.a &= self.dereference_zero_page_x(memory, cpu); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 4; cpu.pc += len; } ANDAbs => { cpu.a &= self.dereference_absolute(memory); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 4; cpu.pc += len; } ANDAbsX => { let (addr, page_cross) = self.absolute_x(cpu); cpu.a &= memory.read_u8(addr); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 4; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } ANDAbsY => { let (addr, page_cross) = self.absolute_y(cpu); cpu.a &= memory.read_u8(addr); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 4; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } ANDIndX => { cpu.a &= self.dereference_indirect_x(memory, cpu); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 6; cpu.pc += len; } ANDIndY => { let (addr, page_cross) = self.indirect_y(cpu, memory); cpu.a &= memory.read_u8(addr); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 5; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } BCCRel => { if !cpu.carry_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } BCSRel => { if cpu.carry_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } BEQRel => { if cpu.zero_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } BMIRel => { if cpu.negative_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } EORImm => { let result = cpu.a ^ self.immediate(); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } EORZero => { let result = cpu.a ^ self.dereference_zero_page(memory); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 3; cpu.pc += len; } EORZeroX => { let result = cpu.a ^ self.dereference_zero_page_x(memory, cpu); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } EORAbs => { let result = cpu.a ^ self.dereference_absolute(memory); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } EORAbsX => { let (addr, page_cross) = self.absolute_x(cpu); let result = cpu.a ^ memory.read_u8(addr); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } EORAbsY => { let (addr, page_cross) = self.absolute_y(cpu); let result = cpu.a ^ memory.read_u8(addr); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } EORIndX => { let result = cpu.a ^ self.dereference_indirect_x(memory, cpu); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } EORIndY => { let (addr, page_cross) = self.indirect_y(cpu, memory); let result = cpu.a ^ memory.read_u8(addr); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 5; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } ORAImm => { let result = cpu.a | self.immediate(); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } ORAZero => { let result = cpu.a | self.dereference_zero_page(memory); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 3; cpu.pc += len; } ORAZeroX => { let result = cpu.a | self.dereference_zero_page_x(memory, cpu); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } ORAAbs => { let result = cpu.a | self.dereference_absolute(memory); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } ORAAbsX => { let (addr, page_cross) = self.absolute_x(cpu); let result = cpu.a | memory.read_u8(addr); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } ORAAbsY => { let (addr, page_cross) = self.absolute_y(cpu); let result = cpu.a | memory.read_u8(addr); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } ORAIndX => { let result = cpu.a | self.dereference_indirect_x(memory, cpu); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } ORAIndY => { let (addr, page_cross) = self.indirect_y(cpu, memory); let result = cpu.a | memory.read_u8(addr); cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 5; if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.pc += len; } BITZero => { let byte = self.dereference_zero_page(memory); let result = byte & cpu.a; cpu.toggle_zero_flag(result); let mask = 0xC0; cpu.p = (cpu.p & !mask) | (byte & mask); cpu.cycles += 3; cpu.pc += len; } BITAbs => { let byte = self.dereference_absolute(memory); let result = byte & cpu.a; cpu.toggle_zero_flag(result); let mask = 0xC0; cpu.p = (cpu.p & !mask) | (byte & mask); cpu.cycles += 4; cpu.pc += len; } BNERel => { if !cpu.zero_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } BPLRel => { if !cpu.negative_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } BVCRel => { if !cpu.overflow_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } BVSRel => { if cpu.overflow_flag_set() { let old_pc = cpu.pc as usize; cpu.pc = add_relative(cpu.pc, self.relative()); cpu.cycles += 1; if page_cross(old_pc.wrapping_add(len as usize), cpu.pc as usize) != PageCross::Same { cpu.cycles += 2; } } cpu.cycles += 2; cpu.pc += len; } CLCImp => { cpu.unset_carry_flag(); cpu.cycles += 2; cpu.pc += len; } CLDImp => { cpu.unset_decimal_mode(); cpu.cycles += 2; cpu.pc += len; } CLIImp => { cpu.unset_interrupt_disable(); cpu.cycles += 2; cpu.pc += len; } CLVImp => { cpu.unset_overflow_flag(); cpu.cycles += 2; cpu.pc += len; } ADCImm => { let arg = self.immediate(); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } ADCZero => { let arg = self.dereference_zero_page(memory); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 3; cpu.pc += len; } ADCZeroX => { let arg = self.dereference_zero_page_x(memory, cpu); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } ADCAbs => { let arg = self.dereference_absolute(memory); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } ADCAbsX => { let (addr, page_cross) = self.absolute_x(cpu); let arg = memory.read_u8(addr); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } ADCAbsY => { let (addr, page_cross) = self.absolute_y(cpu); let arg = memory.read_u8(addr); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } ADCIndX => { let arg = self.dereference_indirect_x(memory, cpu); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } ADCIndY => { let (addr, page_cross) = self.indirect_y(cpu, memory); let arg = memory.read_u8(addr); let (result, overflow); if cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_add(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_add(arg); result = r; overflow = o; } if !(cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 5; cpu.pc += len; } SBCImm => { let arg = self.immediate(); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } SBCZero => { let arg = self.dereference_zero_page(memory); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 3; cpu.pc += len; } SBCZeroX => { let arg = self.dereference_zero_page_x(memory, cpu); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } SBCAbs => { let arg = self.dereference_absolute(memory); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } SBCAbsX => { let (addr, page_cross) = self.absolute_x(cpu); let arg = memory.read_u8(addr); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } SBCAbsY => { let (addr, page_cross) = self.absolute_y(cpu); let arg = memory.read_u8(addr); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } SBCIndX => { let arg = self.dereference_indirect_x(memory, cpu); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } SBCIndY => { let (addr, page_cross) = self.indirect_y(cpu, memory); let arg = memory.read_u8(addr); let (result, overflow); if !cpu.carry_flag_set() { let (r, o) = cpu.a.overflowing_sub(arg.wrapping_add(1)); result = r; overflow = o; } else { let (r, o) = cpu.a.overflowing_sub(arg); result = r; overflow = o; } if (cpu.a ^ arg) & (cpu.a ^ result) & 0x80 == 0x80 { cpu.set_overflow_flag(); } else { cpu.unset_overflow_flag(); } cpu.a = result; cpu.toggle_carry_flag(!overflow); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 5; cpu.pc += len; } CMPImm => { let arg = self.immediate(); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } CMPZero => { let arg = self.dereference_zero_page(memory); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 3; cpu.pc += len; } CMPZeroX => { let arg = self.dereference_zero_page_x(memory, cpu); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } CMPAbs => { let arg = self.dereference_absolute(memory); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } CMPAbsX => { let (addr, page_cross) = self.absolute_x(cpu); let arg = memory.read_u8(addr); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } CMPAbsY => { let (addr, page_cross) = self.absolute_y(cpu); let arg = memory.read_u8(addr); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } CMPIndX => { let arg = self.dereference_indirect_x(memory, cpu); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } CMPIndY => { let (addr, page_cross) = self.indirect_y(cpu, memory); let arg = memory.read_u8(addr); let result = cpu.a.wrapping_sub(arg); if cpu.a >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 5; cpu.pc += len; } CPXImm => { let arg = self.immediate(); let result = cpu.x.wrapping_sub(arg); if cpu.x >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } CPXZero => { let arg = self.dereference_zero_page(memory); let result = cpu.x.wrapping_sub(arg); if cpu.x >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 3; cpu.pc += len; } CPXAbs => { let arg = self.dereference_absolute(memory); let result = cpu.x.wrapping_sub(arg); if cpu.x >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } CPYImm => { let arg = self.immediate(); let result = cpu.y.wrapping_sub(arg); if cpu.y >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } CPYZero => { let arg = self.dereference_zero_page(memory); let result = cpu.y.wrapping_sub(arg); if cpu.y >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 3; cpu.pc += len; } CPYAbs => { let arg = self.dereference_absolute(memory); let result = cpu.y.wrapping_sub(arg); if cpu.y >= arg { cpu.set_carry_flag(); } else { cpu.unset_carry_flag() } if result == 0 { cpu.set_zero_flag(); } else { cpu.unset_zero_flag(); } cpu.toggle_negative_flag(result); cpu.cycles += 4; cpu.pc += len; } INCZero => { let addr = self.zero_page(); let result = memory.read_u8(addr).wrapping_add(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 5; cpu.pc += len; } INCZeroX => { let addr = self.zero_page_x(cpu); let result = memory.read_u8(addr).wrapping_add(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } INCAbs => { let addr = self.absolute(); let result = memory.read_u8(addr).wrapping_add(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } INCAbsX => { let (addr, _) = self.absolute_x(cpu); let result = memory.read_u8(addr).wrapping_add(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 7; cpu.pc += len; } INXImp => { let result = cpu.x.wrapping_add(1); cpu.x = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } INYImp => { let result = cpu.y.wrapping_add(1); cpu.y = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } DECZero => { let addr = self.zero_page(); let result = memory.read_u8(addr).wrapping_sub(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 5; cpu.pc += len; } DECZeroX => { let addr = self.zero_page_x(cpu); let result = memory.read_u8(addr).wrapping_sub(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } DECAbs => { let addr = self.absolute(); let result = memory.read_u8(addr).wrapping_sub(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 6; cpu.pc += len; } DECAbsX => { let (addr, _) = self.absolute_x(cpu); let result = memory.read_u8(addr).wrapping_sub(1); memory.write_u8(addr, result); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 7; cpu.pc += len; } DEXImp => { let result = cpu.x.wrapping_sub(1); cpu.x = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } DEYImp => { let result = cpu.y.wrapping_sub(1); cpu.y = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } ASLAcc => { let carry = cpu.a & 0x80 == 0x80; let result = cpu.a << 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.a = result; cpu.cycles += 2; cpu.pc += len; } ASLZero => { let addr = self.zero_page(); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = mem << 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 5; cpu.pc += len; } ASLZeroX => { let addr = self.zero_page_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = mem << 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } ASLAbs => { let addr = self.absolute(); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = mem << 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } ASLAbsX => { let (addr, _) = self.absolute_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = mem << 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 7; cpu.pc += len; } LSRAcc => { let carry = cpu.a & 0x1 == 0x1; let result = cpu.a >> 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.a = result; cpu.cycles += 2; cpu.pc += len; } LSRZero => { let addr = self.zero_page(); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = mem >> 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 5; cpu.pc += len; } LSRZeroX => { let addr = self.zero_page_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = mem >> 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } LSRAbs => { let addr = self.absolute(); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = mem >> 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } LSRAbsX => { let (addr, _) = self.absolute_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = mem >> 1; cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 7; cpu.pc += len; } RORAcc => { let carry = cpu.a & 0x1 == 0x1; let result = (cpu.a >> 1) | (cpu.p << 7); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.a = result; cpu.cycles += 2; cpu.pc += len; } RORZero => { let addr = self.zero_page(); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = (mem >> 1) | (cpu.p << 7); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 5; cpu.pc += len; } RORZeroX => { let addr = self.zero_page_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = (mem >> 1) | (cpu.p << 7); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } RORAbs => { let addr = self.absolute(); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = (mem >> 1) | (cpu.p << 7); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } RORAbsX => { let (addr, _) = self.absolute_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x1 == 0x1; let result = (mem >> 1) | (cpu.p << 7); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 7; cpu.pc += len; } ROLAcc => { let carry = cpu.a & 0x80 == 0x80; let result = (cpu.a << 1) | (cpu.p & 0x1); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.a = result; cpu.cycles += 2; cpu.pc += len; } ROLZero => { let addr = self.zero_page(); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = (mem << 1) | (cpu.p & 0x1); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 5; cpu.pc += len; } ROLZeroX => { let addr = self.zero_page_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = (mem << 1) | (cpu.p & 0x1); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } ROLAbs => { let addr = self.absolute(); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = (mem << 1) | (cpu.p & 0x1); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 6; cpu.pc += len; } ROLAbsX => { let (addr, _) = self.absolute_x(cpu); let mem = memory.read_u8(addr); let carry = mem & 0x80 == 0x80; let result = (mem << 1) | (cpu.p & 0x1); cpu.toggle_carry_flag(carry); cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); memory.write_u8(addr, result); cpu.cycles += 7; cpu.pc += len; } JMPAbs => { cpu.pc = self.absolute() as u16; cpu.cycles += 3; } JMPInd => { // A special version of indirect addressing is implemented here // due to a bug in the indirect JMP operation. // https://github.com/Reshurum/nes-rs/issues/3 let arg = self.arg_u16() as usize; cpu.pc = memory.read_u16_wrapped_msb(arg); cpu.cycles += 5; } JSRAbs => { let pc = cpu.pc; memory.stack_push_u16(cpu, pc + len - 1); cpu.pc = self.absolute() as u16; cpu.cycles += 6; } LDAImm => { cpu.a = self.immediate(); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 2; cpu.pc += len; } LDAZero => { cpu.a = memory.read_u8(self.zero_page()); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 3; cpu.pc += len; } LDAZeroX => { cpu.a = memory.read_u8(self.zero_page_x(cpu)); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 4; cpu.pc += len; } LDAAbs => { cpu.a = memory.read_u8(self.absolute()); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 4; cpu.pc += len; } LDAAbsX => { let (addr, page_cross) = self.absolute_x(cpu); cpu.a = memory.read_u8(addr); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } LDAAbsY => { let (addr, page_cross) = self.absolute_y(cpu); cpu.a = memory.read_u8(addr); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } LDAIndX => { let (addr, _) = self.indirect_x(cpu, memory); cpu.a = memory.read_u8(addr); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 6; cpu.pc += len; } LDAIndY => { let (addr, page_cross) = self.indirect_y(cpu, memory); cpu.a = memory.read_u8(addr); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 5; cpu.pc += len; } LDXImm => { cpu.x = self.immediate(); let x = cpu.x; cpu.toggle_zero_flag(x); cpu.toggle_negative_flag(x); cpu.cycles += 2; cpu.pc += len; } LDXZero => { cpu.x = memory.read_u8(self.zero_page()); let x = cpu.x; cpu.toggle_zero_flag(x); cpu.toggle_negative_flag(x); cpu.cycles += 3; cpu.pc += len; } LDXZeroY => { cpu.x = memory.read_u8(self.zero_page_y(cpu)); let x = cpu.x; cpu.toggle_zero_flag(x); cpu.toggle_negative_flag(x); cpu.cycles += 4; cpu.pc += len; } LDXAbs => { cpu.x = memory.read_u8(self.absolute()); let x = cpu.x; cpu.toggle_zero_flag(x); cpu.toggle_negative_flag(x); cpu.cycles += 4; cpu.pc += len; } LDXAbsY => { let (addr, page_cross) = self.absolute_y(cpu); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.x = memory.read_u8(addr); let x = cpu.x; cpu.toggle_zero_flag(x); cpu.toggle_negative_flag(x); cpu.cycles += 4; cpu.pc += len; } LDYImm => { cpu.y = self.immediate(); let y = cpu.y; cpu.toggle_zero_flag(y); cpu.toggle_negative_flag(y); cpu.cycles += 2; cpu.pc += len; } LDYZero => { cpu.y = self.dereference_zero_page(memory); let y = cpu.y; cpu.toggle_zero_flag(y); cpu.toggle_negative_flag(y); cpu.cycles += 3; cpu.pc += len; } LDYZeroX => { cpu.y = self.dereference_zero_page_x(memory, cpu); let y = cpu.y; cpu.toggle_zero_flag(y); cpu.toggle_negative_flag(y); cpu.cycles += 4; cpu.pc += len; } LDYAbs => { cpu.y = self.dereference_absolute(memory); let y = cpu.y; cpu.toggle_zero_flag(y); cpu.toggle_negative_flag(y); cpu.cycles += 4; cpu.pc += len; } LDYAbsX => { let (addr, page_cross) = self.absolute_x(cpu); cpu.y = memory.read_u8(addr); let y = cpu.y; cpu.toggle_zero_flag(y); cpu.toggle_negative_flag(y); if page_cross != PageCross::Same { cpu.cycles += 1; } cpu.cycles += 4; cpu.pc += len; } BRKImp => { // Fires an IRQ interrupt. let p = cpu.p; let pc = cpu.pc.wrapping_add(len); memory.stack_push_u16(cpu, pc); memory.stack_push_u8(cpu, p); cpu.set_break_command(); cpu.cycles += 7; cpu.pc = pc; } NOPImp => { // This is the most difficult instruction to implement. cpu.cycles += 2; cpu.pc += len; } PHAImp => { let a = cpu.a; memory.stack_push_u8(cpu, a); cpu.cycles += 3; cpu.pc += len; } PHPImp => { let p = cpu.p | 0x10; // Ensure bit 5 is always set. memory.stack_push_u8(cpu, p); cpu.cycles += 3; cpu.pc += len; } PLAImp => { cpu.a = memory.stack_pop_u8(cpu); let a = cpu.a; cpu.toggle_zero_flag(a); cpu.toggle_negative_flag(a); cpu.cycles += 4; cpu.pc += len; } PLPImp => { let old_flags = cpu.p; let p = (memory.stack_pop_u8(cpu) & 0xEF) | (old_flags & 0x20); cpu.p = p; cpu.cycles += 4; cpu.pc += len; } RTIImp => { let result = (memory.stack_pop_u8(cpu) & 0xEF) | (cpu.p & 0x20); cpu.p = result; cpu.pc = memory.stack_pop_u16(cpu); cpu.cycles += 6; } RTSImp => { cpu.pc = memory.stack_pop_u16(cpu) + len; cpu.cycles += 6; } SECImp => { cpu.set_carry_flag(); cpu.cycles += 2; cpu.pc += len; } SEDImp => { cpu.set_decimal_mode(); cpu.cycles += 2; cpu.pc += len; } SEIImp => { cpu.set_interrupt_disable(); cpu.cycles += 2; cpu.pc += len; } STAZero => { memory.write_u8(self.zero_page(), cpu.a); cpu.cycles += 3; cpu.pc += len; } STAZeroX => { memory.write_u8(self.zero_page_x(cpu), cpu.a); cpu.cycles += 4; cpu.pc += len; } STAAbs => { memory.write_u8(self.absolute(), cpu.a); cpu.cycles += 4; cpu.pc += len; } STAAbsX => { memory.write_u8(self.absolute_x(cpu).0, cpu.a); cpu.cycles += 5; cpu.pc += len; } STAAbsY => { memory.write_u8(self.absolute_y(cpu).0, cpu.a); cpu.cycles += 5; cpu.pc += len; } STAIndX => { let addr = self.indirect_x(cpu, memory).0; memory.write_u8(addr, cpu.a); cpu.cycles += 6; cpu.pc += len; } STAIndY => { let addr = self.indirect_y(cpu, memory).0; memory.write_u8(addr, cpu.a); cpu.cycles += 6; cpu.pc += len; } STXZero => { memory.write_u8(self.zero_page(), cpu.x); cpu.cycles += 3; cpu.pc += len; } STXZeroY => { memory.write_u8(self.zero_page_y(cpu), cpu.x); cpu.cycles += 4; cpu.pc += len; } STXAbs => { memory.write_u8(self.absolute(), cpu.x); cpu.cycles += 4; cpu.pc += len; } STYZero => { memory.write_u8(self.zero_page(), cpu.y); cpu.cycles += 3; cpu.pc += len; } STYZeroX => { memory.write_u8(self.zero_page_x(cpu), cpu.y); cpu.cycles += 4; cpu.pc += len; } STYAbs => { memory.write_u8(self.absolute(), cpu.y); cpu.cycles += 4; cpu.pc += len; } TAXImp => { let result = cpu.a; cpu.x = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } TAYImp => { let result = cpu.a; cpu.y = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } TSXImp => { let result = cpu.sp; cpu.x = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } TXAImp => { let result = cpu.x; cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } TXSImp => { let result = cpu.x; cpu.sp = result; cpu.cycles += 2; cpu.pc += len; } TYAImp => { let result = cpu.y; cpu.a = result; cpu.toggle_zero_flag(result); cpu.toggle_negative_flag(result); cpu.cycles += 2; cpu.pc += len; } _ => { panic!("Unimplemented opcode found: {:?}", opcode); } }; cpu.poll_irq(memory); // Poll IRQ after execution. } /// Obtain the opcode of the instruction. #[inline(always)] fn opcode(&self) -> Opcode { decode_opcode(self.0) } /// Read the instruction argument as an 8-bit value. #[inline(always)] fn arg_u8(&self) -> u8 { self.1 } /// Read the instruction argument as a 16-bit value. #[inline(always)] fn arg_u16(&self) -> u16 { let mut reader = Cursor::new(vec![self.1, self.2]); reader.read_u16::<LittleEndian>().unwrap() } /// Dereferences a zero page address in the instruction. #[inline(always)] fn dereference_u8(&self, memory: &mut Memory) -> u8 { memory.read_u8(self.arg_u8() as usize) } /// Dereferences a memory address in the instruction. #[inline(always)] fn dereference_u16(&self, memory: &mut Memory) -> u8 { memory.read_u8(self.arg_u16() as usize) } // Addressing mode utility functions here. These are used to simplify the // development of instructions and a good explanation of addressing modes // can be found at https://skilldrick.github.io/easy6502/#addressing. /// Accumulator addressing simply gets values from the accumulator register /// rather than from the instruction. #[inline(always)] fn accumulator(&self, cpu: &CPU) -> u8 { cpu.a } /// Directly return the argument. Immediate addressing simply stores the /// value in the argument unlike other addressing modes which typically use /// this space for memory addresses. #[inline(always)] fn immediate(&self) -> u8 { self.arg_u8() } /// Returns an address from the instruction arguments that's between /// $00-$FF. This is used for zero page addressing which is typically faster /// than it's counterpart absolute addressing. #[inline(always)] fn zero_page(&self) -> usize { self.arg_u8() as usize } /// Returns a zero page address stored in the instruction with the X /// register added to it. #[inline(always)] fn zero_page_x(&self, cpu: &CPU) -> usize { self.arg_u8().wrapping_add(cpu.x) as usize } /// Returns a zero page address stored in the instruction with the Y /// register added to it. #[inline(always)] fn zero_page_y(&self, cpu: &CPU) -> usize { self.arg_u8().wrapping_add(cpu.y) as usize } /// Returns a signed variation of the 8-bit argument. Relative addressing is /// used for branch operations and uses a signed integer containing an /// offset of bytes of where to place the program counter. #[inline(always)] fn relative(&self) -> i8 { self.arg_u8() as i8 } /// Returns an address from the instruction argument unaltered. #[inline(always)] fn absolute(&self) -> usize { self.arg_u16() as usize } /// Returns an address from the instruction argument with the value in the X /// register added to it. #[inline(always)] fn absolute_x(&self, cpu: &CPU) -> (usize, PageCross) { let base_addr = self.arg_u16(); let addr = base_addr.wrapping_add(cpu.x as u16) as usize; let page_cross = page_cross(base_addr as usize, addr); (addr, page_cross) } /// Returns an address from the instruction argument with the value in the Y /// register added to it. #[inline(always)] fn absolute_y(&self, cpu: &CPU) -> (usize, PageCross) { let base_addr = self.arg_u16(); let addr = base_addr.wrapping_add(cpu.y as u16) as usize; let page_cross = page_cross(base_addr as usize, addr); (addr, page_cross) } /// Indirect addressing uses an absolute address to lookup another address. #[inline(always)] fn indirect(&self, memory: &mut Memory) -> usize { let arg = self.arg_u16() as usize; memory.read_u16_wrapped_msb(arg) as usize } /// Calculates a memory address using by adding X to the 8-bit value in the /// instruction, THEN use that address to find ANOTHER address, then return /// THAT address. /// /// TODO: Remove page cross detection as indirect x never has a page /// crossing penalty. #[inline(always)] fn indirect_x(&self, cpu: &CPU, memory: &mut Memory) -> (usize, PageCross) { let arg = self.arg_u8(); let addr = arg.wrapping_add(cpu.x) as usize; let page_cross = page_cross(arg as usize, addr); (memory.read_u16_wrapped_msb(addr) as usize, page_cross) } /// Sane version of indirect_x that gets the zero page address in the /// instruction, adds Y to it, then returns the resulting address. #[inline(always)] fn indirect_y(&self, cpu: &CPU, memory: &mut Memory) -> (usize, PageCross) { let arg = self.arg_u8() as usize; let base_addr = memory.read_u16_wrapped_msb(arg); let addr = base_addr.wrapping_add(cpu.y as u16) as usize; let page_cross = page_cross(base_addr as usize, addr); (addr, page_cross) } /// Dereferences a zero page address. #[inline(always)] fn dereference_zero_page(&self, memory: &mut Memory) -> u8 { let addr = self.zero_page(); memory.read_u8(addr) } /// Dereferences a zero page x address. #[inline(always)] fn dereference_zero_page_x(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.zero_page_x(cpu); memory.read_u8(addr) } /// Dereferences a zero page y address. #[inline(always)] fn dereference_zero_page_y(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.zero_page_y(cpu); memory.read_u8(addr) } /// Dereferences an absolute address. #[inline(always)] fn dereference_absolute(&self, memory: &mut Memory) -> u8 { let addr = self.absolute(); memory.read_u8(addr) } /// Dereferences an absolute x address. #[inline(always)] fn dereference_absolute_x(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.absolute_x(cpu).0; memory.read_u8(addr) } /// Dereferences an absolute y address. #[inline(always)] fn dereference_absolute_y(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.absolute_y(cpu).0; memory.read_u8(addr) } /// Dereferences an indirect address. #[inline(always)] fn dereference_indirect(&self, memory: &mut Memory) -> u8 { let addr = self.indirect(memory); memory.read_u8(addr) } /// Dereferences an indirect x address. #[inline(always)] fn dereference_indirect_x(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.indirect_x(cpu, memory).0; memory.read_u8(addr) } /// Dereferences an indirect y address. #[inline(always)] fn dereference_indirect_y(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.indirect_y(cpu, memory).0; memory.read_u8(addr) } /// Dereferences a zero page address. #[inline(always)] fn dereference_zero_page_unrestricted(&self, memory: &mut Memory) -> u8 { let addr = self.zero_page(); memory.read_u8_unrestricted(addr) } /// Dereferences a zero page x address. #[inline(always)] fn dereference_zero_page_x_unrestricted(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.zero_page_x(cpu); memory.read_u8_unrestricted(addr) } /// Dereferences a zero page y address. #[inline(always)] fn dereference_zero_page_y_unrestricted(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.zero_page_y(cpu); memory.read_u8_unrestricted(addr) } /// Dereferences an absolute address. #[inline(always)] fn dereference_absolute_unrestricted(&self, memory: &mut Memory) -> u8 { let addr = self.absolute(); memory.read_u8_unrestricted(addr) } /// Dereferences an absolute x address. #[inline(always)] fn dereference_absolute_x_unrestricted(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.absolute_x(cpu).0; memory.read_u8_unrestricted(addr) } /// Dereferences an absolute y address. #[inline(always)] fn dereference_absolute_y_unrestricted(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.absolute_y(cpu).0; memory.read_u8_unrestricted(addr) } /// Dereferences an indirect address. #[inline(always)] fn dereference_indirect_unrestricted(&self, memory: &mut Memory) -> u8 { let addr = self.indirect(memory); memory.read_u8_unrestricted(addr) } /// Dereferences an indirect x address. #[inline(always)] fn dereference_indirect_x_unrestricted(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.indirect_x(cpu, memory).0; memory.read_u8_unrestricted(addr) } /// Dereferences an indirect y address. #[inline(always)] fn dereference_indirect_y_unrestricted(&self, memory: &mut Memory, cpu: &CPU) -> u8 { let addr = self.indirect_y(cpu, memory).0; memory.read_u8_unrestricted(addr) } // Functions for aiding in disassembly. Each addressing mode has it's own // disassembly format in Nintendulator logs. These functions simply fill in // the blanks with provided parameters. /// Disassembles the instruction as if it's using accumulator addressing. fn disassemble_accumulator(&self, instr: &str) -> String { format!("{} A", instr) } /// Disassembles the instruction as if it's using implied addressing. fn disassemble_implied(&self, instr: &str) -> String { format!("{}", instr) } /// Disassembles the instruction as if it's using immediate addressing. fn disassemble_immediate(&self, instr: &str) -> String { format!("{} #${:02X}", instr, self.1) } /// Disassembles the instruction as if it's using zero page addressing. fn disassemble_zero_page(&self, instr: &str, memory: &mut Memory) -> String { format!( "{} ${:02X} = {:02X}", instr, self.1, self.dereference_zero_page_unrestricted(memory) ) } /// Disassembles the instruction as if it's using zero page x addressing. fn disassemble_zero_page_x(&self, instr: &str, memory: &mut Memory, cpu: &CPU) -> String { format!( "{} ${:02X},X @ {:02X} = {:02X}", instr, self.1, self.zero_page_x(cpu), self.dereference_zero_page_x_unrestricted(memory, cpu) ) } /// Disassembles the instruction as if it's using zero page y addressing. fn disassemble_zero_page_y(&self, instr: &str, memory: &mut Memory, cpu: &CPU) -> String { format!( "{} ${:02X},Y @ {:02X} = {:02X}", instr, self.1, self.zero_page_y(cpu), self.dereference_zero_page_y_unrestricted(memory, cpu) ) } /// Disassembles the instruction as if it's using relative addressing. fn disassemble_relative(&self, instr: &str, len: u8, cpu: &CPU) -> String { let rel = add_relative(cpu.pc, self.relative()); format!("{} ${:04X}", instr, rel + len as u16) } /// Disassembles the instruction as if it's using absolute addressing. /// /// NOTE: This function differs from disassemble_absolute as it does not /// dereference the value at the address. This is primarily used for JMP /// instructions for which the address is used directly. fn disassemble_absolute_noref(&self, instr: &str) -> String { format!("{} ${:02X}{:02X}", instr, self.2, self.1) } /// Disassembles the instruction as if it's using absolute addressing. fn disassemble_absolute(&self, instr: &str, memory: &mut Memory) -> String { format!( "{} ${:02X}{:02X} = {:02X}", instr, self.2, self.1, self.dereference_absolute_unrestricted(memory) ) } /// Disassembles the instruction as if it's using absolute x addressing. fn disassemble_absolute_x(&self, instr: &str, memory: &mut Memory, cpu: &CPU) -> String { format!( "{} ${:02x}{:02X},X @ {:04X} = {:02X}", instr, self.2, self.1, self.absolute_x(cpu).0, self.dereference_absolute_x_unrestricted(memory, cpu) ) } /// Disassembles the instruction as if it's using absolute y addressing. fn disassemble_absolute_y(&self, instr: &str, memory: &mut Memory, cpu: &CPU) -> String { format!( "{} ${:02X}{:02X},Y @ {:04X} = {:02X}", instr, self.2, self.1, self.absolute_y(cpu).0, self.dereference_absolute_y_unrestricted(memory, cpu) ) } /// Disassembles the instruction as if it's using indirect addressing. fn disassemble_indirect(&self, instr: &str, memory: &mut Memory) -> String { format!( "{} (${:02X}{:02X}) = {:04X}", instr, self.2, self.1, self.indirect(memory) ) } /// Disassembles the instruction as if it's using indirect x addressing. fn disassemble_indirect_x(&self, instr: &str, memory: &mut Memory, cpu: &CPU) -> String { format!( "{} (${:02X},X) @ {:02X} = {:04X} = {:02X}", instr, self.1, self.1.wrapping_add(cpu.x), self.indirect_x(cpu, memory).0, self.dereference_indirect_x_unrestricted(memory, cpu) ) } /// Disassembles the instruction as if it's using indirect y addressing. fn disassemble_indirect_y(&self, instr: &str, memory: &mut Memory, cpu: &CPU) -> String { format!( "{} (${:02X}),Y = {:04X} @ {:04X} = {:02X}", instr, self.1, memory.read_u16_wrapped_msb(self.arg_u16() as usize), self.indirect_y(cpu, memory).0, self.dereference_indirect_y_unrestricted(memory, cpu) ) } }
true
837b86f4e994d7fb2466c46fae0f52f08969c604
Rust
LevitatingOrange/oblivious-transfer
/src/common/digest/mod.rs
UTF-8
1,045
2.875
3
[]
no_license
use generic_array::{ArrayLength, GenericArray}; pub mod sha3; /// A simple trait to generalize hashing functions used by this library. /// It is very similiar to the trait from the crate digest but customized to fit this library's needs. /// One can use any hash function to initialize the BaseOT and OTExtensions though special care must be taken /// when selecting one as any security flaw will transitively harm the security of the oblivious transfer. /// /// As a general, fits-most implementation, a wrapper around tiny-keccaks SHA3 implementation is provided. pub trait Digest { type OutputSize: ArrayLength<u8>; fn input(&mut self, data: &[u8]); fn result(self) -> GenericArray<u8, Self::OutputSize>; } /// Used for ot extensions, this trait generalizes variable-length hashing functions. /// /// As a general, fits-most implementation, a wrapper asround tiny-keccaks Keccak implementation is provided. pub trait ArbitraryDigest { fn input(&mut self, data: &[u8]); fn result(self, output_size: usize) -> Vec<u8>; }
true
488c296bbfe749e9b9e2a4baed077b45341fe1ce
Rust
danleechina/Leetcode
/Rust_Sol/src/archive0/s307.rs
UTF-8
1,361
3.3125
3
[]
no_license
struct NumArray { sum_nums: Vec<i32>, } use std::cmp::min; use std::cmp::max; impl NumArray { fn new(nums: Vec<i32>) -> Self { return NumArray { sum_nums: NumArray::sum(nums), }; } fn sum(nums: Vec<i32>) -> Vec<i32> { let mut res = vec![0; nums.len()]; if nums.is_empty() { return res; } let mut i = 1; res[0] = nums[0]; while i < res.len() { res[i] = res[i - 1] + nums[i]; i += 1; } res } fn update(&mut self, i: i32, val: i32) { let old_val: i32; let mut i = i as usize; if i >= self.sum_nums.len() { return; } if i == 0 { old_val = self.sum_nums[i]; } else { old_val = self.sum_nums[i] - self.sum_nums[i - 1]; } let diff = val - old_val; while i < self.sum_nums.len() { self.sum_nums[i] += diff; i += 1; } } fn sum_range(&self, i: i32, j: i32) -> i32 { if self.sum_nums.is_empty() { return 0; } let mut i = i as usize; let mut j = j as usize; i = min(i, self.sum_nums.len() - 1); j = min(j, self.sum_nums.len() - 1); i = max(0, i); j = max(0, j); if i == 0 { return self.sum_nums[j]; } return self.sum_nums[j] - self.sum_nums[i - 1]; } }
true
e035d708b17b849307f5bb7ffd7421bf17061f32
Rust
ryban/rust-noise
/examples/step.rs
UTF-8
1,160
2.765625
3
[ "MIT" ]
permissive
// step.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::fbm::FBM; use noise::utils::step; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main() { let mut ngen = FBM::new_rand(24, 0.5, 2.5, 175.0); let steps: &[f64] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]; println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for x in range(0, img_size) { for y in range(0, img_size) { let xx = x as f64; let yy = y as f64; let nn = ngen.get_value2d(xx, yy); let n = step(nn, steps); let col = (n * 255.0) as u8; let pixel = image::Luma(col); imbuf.put_pixel(x, y, pixel); } } let end = precise_time_s(); let fout = File::create(&Path::new("step.png")).unwrap(); let _ = image::ImageLuma8(imbuf).save(fout, image::PNG); println!("step.png saved"); println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
true
5b9494cbf2cbadfe743a7423b5c60ffdcc041680
Rust
bevyengine/bevy-website
/generate-release/src/migration_guide.rs
UTF-8
2,874
2.640625
3
[ "MIT" ]
permissive
use crate::{ github_client::{GithubClient, GithubIssuesResponse}, helpers::{get_merged_prs, get_pr_area}, markdown::write_markdown_section, }; use std::{collections::BTreeMap, fmt::Write, path::PathBuf}; pub fn generate_migration_guide( title: &str, weight: i32, from: &str, to: &str, path: PathBuf, client: &mut GithubClient, ) -> anyhow::Result<()> { let mut output = String::new(); // Write the frontmatter based on given parameters write!( &mut output, r#"+++ title = "{title}" weight = {weight} sort_by = "weight" template = "docs-section.html" page_template = "docs-section.html" insert_anchor_links = "right" [extra] long_title = "Migration Guide: {title}" +++ Bevy relies heavily on improvements in the Rust language and compiler. As a result, the Minimum Supported Rust Version (MSRV) is "the latest stable release" of Rust."# )?; writeln!(&mut output)?; writeln!(&mut output, "<div class=\"migration-guide\">")?; let mut areas = BTreeMap::<String, Vec<(String, GithubIssuesResponse)>>::new(); let merged_breaking_prs = get_merged_prs(client, from, to, Some("C-Breaking-Change"))?; for (pr, _, title) in &merged_breaking_prs { let area = get_pr_area(pr); areas .entry(area) .or_insert(Vec::new()) .push((title.clone(), pr.clone())); } for (area, prs) in areas { println!("Area: {area}"); let area = area.replace("A-", ""); let areas = area.split(" + ").collect::<Vec<_>>(); let mut prs = prs; prs.sort_by_key(|k| k.1.closed_at); for (title, pr) in prs { println!("# {title}"); // Write title for the PR with correct heading and github url writeln!( &mut output, "\n### [{}](https://github.com/bevyengine/bevy/pull/{})", title, pr.number )?; // Write custom HTML to show area tag on each section write!(&mut output, "\n<div class=\"migration-guide-area-tags\">")?; for area in &areas { write!( &mut output, "\n <div class=\"migration-guide-area-tag\">{area}</div>" )?; } write!(&mut output, "\n</div>")?; writeln!(&mut output)?; write_markdown_section( pr.body.as_ref().unwrap(), "migration guide", &mut output, true, )?; } } writeln!(&mut output, "</div>")?; println!( "\nFound {} breaking PRs merged by bors", merged_breaking_prs.len() ); std::fs::write(path, output)?; Ok(()) }
true
2084f8277ef8665a45ddbd50447581e6ccc17cf4
Rust
stalwartlabs/mail-builder
/src/encoders/encode.rs
UTF-8
3,832
2.53125
3
[ "Apache-2.0", "MIT" ]
permissive
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use std::io::{self, Write}; use super::{base64::base64_encode_mime, quoted_printable::quoted_printable_encode}; pub enum EncodingType { Base64, QuotedPrintable(bool), None, } pub fn get_encoding_type(input: &[u8], is_inline: bool, is_body: bool) -> EncodingType { let base64_len = (input.len() * 4 / 3 + 3) & !3; let mut qp_len = if !is_inline { input.len() / 76 } else { 0 }; let mut is_ascii = true; let mut needs_encoding = false; let mut line_len = 0; let mut prev_ch = 0; for (pos, &ch) in input.iter().enumerate() { line_len += 1; if ch >= 127 || ((ch == b' ' || ch == b'\t') && ((is_body && matches!(input.get(pos + 1..), Some([b'\n', ..] | [b'\r', b'\n', ..]))) || pos == input.len() - 1)) { qp_len += 3; if !needs_encoding { needs_encoding = true; } if is_ascii && ch >= 127 { is_ascii = false; } } else if ch == b'=' || (!is_body && ch == b'\r') || (is_inline && (ch == b'\t' || ch == b'\r' || ch == b'\n' || ch == b'?')) { qp_len += 3; } else if ch == b'\n' { if !needs_encoding && line_len > 997 { needs_encoding = true; } if is_body { if prev_ch != b'\r' { qp_len += 1; } qp_len += 1; } else { if !needs_encoding && prev_ch != b'\r' { needs_encoding = true; } qp_len += 3; } line_len = 0; } else { qp_len += 1; } prev_ch = ch; } if !needs_encoding { EncodingType::None } else if qp_len < base64_len { EncodingType::QuotedPrintable(is_ascii) } else { EncodingType::Base64 } } pub fn rfc2047_encode(input: &str, mut output: impl Write) -> io::Result<usize> { Ok(match get_encoding_type(input.as_bytes(), true, false) { EncodingType::Base64 => { output.write_all(b"\"=?utf-8?B?")?; let bytes_written = base64_encode_mime(input.as_bytes(), &mut output, true)? + 14; output.write_all(b"?=\"")?; bytes_written } EncodingType::QuotedPrintable(is_ascii) => { if !is_ascii { output.write_all(b"\"=?utf-8?Q?")?; } else { output.write_all(b"\"=?us-ascii?Q?")?; } let bytes_written = quoted_printable_encode(input.as_bytes(), &mut output, true, false)? + if is_ascii { 19 } else { 14 }; output.write_all(b"?=\"")?; bytes_written } EncodingType::None => { let mut bytes_written = 2; output.write_all(b"\"")?; for &ch in input.as_bytes() { if ch == b'\\' || ch == b'"' { output.write_all(b"\\")?; bytes_written += 1; } else if ch == b'\r' || ch == b'\n' { continue; } output.write_all(&[ch])?; bytes_written += 1; } output.write_all(b"\"")?; bytes_written } }) }
true
043e6f1c29ce342503edaea539cda2d75ca020a6
Rust
SCRTHodl/blockchain
/dmbc/src/currency/offers/offers.rs
UTF-8
4,465
3.203125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use currency::offers::Offer; use exonum::crypto::{PublicKey, Hash}; #[derive(Debug, Eq, PartialEq)] pub struct CloseOffer { pub wallet: PublicKey, pub price: u64, pub amount: u64, pub tx_hash: Hash, } encoding_struct! { #[derive(Eq, PartialOrd, Ord)] struct Offers { price: u64, offers: Vec<Offer>, } } impl Offers { pub fn insert(&mut self, offer: Offer) { let mut offers = self.offers(); if offers.len() > 0 { let last = offers.iter().last().unwrap(); if last.wallet() == offer.wallet() && last.tx_hash() == offer.tx_hash() { eprintln!("last = {:#?}", last); eprintln!("offer = {:#?}", offer); panic!("last offer equal add offer"); } } offers.push(offer); *self = Offers::new(self.price(), offers); } pub fn close(&mut self, amount: u64) -> Vec<CloseOffer> { let mut closed_offers: Vec<CloseOffer> = vec![]; let mut amount_closed = 0u64; let mut offers = self.offers(); for k in 0..offers.len() { if amount - amount_closed > 0 && offers[k].amount() > amount - amount_closed { offers[k].remove_amount(amount - amount_closed); closed_offers.push(CloseOffer { wallet: offers[k].wallet().clone(), price: self.price(), amount: amount - amount_closed, tx_hash: offers[k].tx_hash().clone(), }); amount_closed = amount; } else if offers[k].amount() <= amount - amount_closed { amount_closed += offers[k].amount(); let a = offers[k].amount(); offers[k].remove_amount(a); closed_offers.push(CloseOffer { wallet: offers[k].wallet().clone(), price: self.price(), amount: a, tx_hash: offers[k].tx_hash().clone(), }); } else { break; } } offers.retain(|o|o.amount() > 0); *self = Offers::new(self.price(), offers); closed_offers } } #[cfg(test)] mod test { use currency::offers::{CloseOffer, Offer, Offers}; use exonum::crypto; use exonum::crypto::gen_keypair; #[test] #[should_panic] fn offers_insert_offer_panic() { let (wallet, _) = gen_keypair(); let tx_hash = &crypto::hash("tx1".as_bytes()); let amount = 10; let price = 12; let mut offers = Offers::new(price, vec![Offer::new(&wallet, amount, tx_hash)]); offers.insert(Offer::new(&wallet, amount, tx_hash)); assert_eq!(vec![Offer::new(&wallet, 2 * amount, tx_hash)], offers.offers()); } #[test] fn offers_insert_offer() { let (wallet, _) = gen_keypair(); let tx_hash1 = &crypto::hash("tx1".as_bytes()); let tx_hash2 = &crypto::hash("tx2".as_bytes()); let amount = 10; let price = 12; let mut offers = Offers::new(price, vec![]); offers.insert(Offer::new(&wallet, amount, tx_hash1)); assert_eq!(vec![Offer::new(&wallet, amount, tx_hash1)], offers.offers()); offers.insert(Offer::new(&wallet, amount, tx_hash2)); assert_eq!(vec![Offer::new(&wallet, amount, tx_hash1), Offer::new(&wallet, amount, tx_hash2)], offers.offers()); } #[test] fn offers_close_offer() { let (wallet, _) = gen_keypair(); let price = 10; let o = vec![ Offer::new(&wallet, 1, &crypto::hash("tx1".as_bytes())), Offer::new(&wallet, 3, &crypto::hash("tx2".as_bytes())), Offer::new(&wallet, 5, &crypto::hash("tx3".as_bytes())) ]; let mut bids = Offers::new(price, o); let result = bids.close(5); let hash1 = crypto::hash("tx1".as_bytes()); let hash2 = crypto::hash("tx2".as_bytes()); let hash3 = crypto::hash("tx3".as_bytes()); let cs = vec![ CloseOffer { wallet, price, amount: 1, tx_hash: hash1 }, CloseOffer { wallet, price, amount: 3, tx_hash: hash2 }, CloseOffer { wallet, price, amount: 1, tx_hash: hash3 } ]; assert_eq!(cs, result); assert_eq!(vec![Offer::new(&wallet, 4, &crypto::hash("tx3".as_bytes()))], bids.offers()); } }
true
5f474337b8c824f98175ca33eb7ad730c4f3714d
Rust
VisionistInc/advent-of-code-2020
/cicavey/10/src/main.rs
UTF-8
1,733
3.375
3
[ "MIT" ]
permissive
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> { let file = File::open(filename).expect("no such file"); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect("Could not parse line")) .collect() } fn main() { let lines = lines_from_file("input.txt"); let mut values: Vec<u64> = lines .into_iter() .map(|l| l.parse::<u64>().unwrap()) .collect(); values.sort(); // Add entry for your device values.insert(0, 0); let max = values.last().unwrap() + 3; values.push(max); // Calculate all differences let diff: Vec<u64> = values.windows(2).map(|w| w[1] - w[0]).collect(); // Histogram differences let mut hist = HashMap::new(); for v in diff { *hist.entry(v).or_insert(0) += 1; } let magic = hist.get(&1).unwrap() * hist.get(&3).unwrap(); dbg!(magic); let mut lookup = vec![0; (max + 1) as usize]; lookup[0] = 1; // For every value calculate the total number of possible routes from the previous three values // Use lookup table // Full disclosure - I tried the brute force / recursive version and it obviously didn't work for larger case // Attempted to build a graph, too much work. Considered the route summing after skimming other solutions for v in values.iter_mut().skip(1) { let i = *v as usize; // saturating_sub is the bounded sub let mut sum: u64 = 0; for k in i.saturating_sub(3)..i { sum += *lookup.get(k).unwrap_or(&0); } lookup[i] = sum; } dbg!(lookup.last().unwrap()); }
true
783e934f743af60f924efcca913d81e53baf0caa
Rust
ghcom275/unsafe-io
/src/raw_handle_or_socket.rs
UTF-8
4,587
3.09375
3
[ "Apache-2.0", "LLVM-exception", "MIT" ]
permissive
//! The `RawHandleOrSocket` type, providing a minimal Windows analog for the //! Posix-ish `AsRawFd` type. #[cfg(feature = "os_pipe")] use os_pipe::{PipeReader, PipeWriter}; use std::{ fmt, fs::File, io::{Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock}, net::TcpStream, os::windows::io::{AsRawHandle, AsRawSocket, RawHandle, RawSocket}, process::{ChildStderr, ChildStdin, ChildStdout}, }; /// Windows has multiple types, so we use an enum to abstract over them. It's /// reasonable to worry that this might be trying too hard to make Windows work /// like Unix, however in this case, the number of types is small, so the enum /// is simple and the overhead is relatively low, and the benefit is that we /// can abstract over all the major `Read` and `Write` resources. #[derive(Copy, Clone)] pub enum RawHandleOrSocket { /// A `RawHandle`. Handle(RawHandle), /// A `RawSocket`. Socket(RawSocket), } /// The windows `HANDLE` and `SOCKET` types may be sent between threads. unsafe impl Send for RawHandleOrSocket {} /// Like [`std::os::windows::io::AsRawHandle`] and /// [`std::os::windows::io::AsRawSocket`], but implementable by types which /// can implement either one. pub trait AsRawHandleOrSocket { /// Like [`std::os::windows::io::AsRawHandle::as_raw_handle`] and /// [`std::os::windows::io::AsRawSocket::as_raw_socket`] but can return /// either type. fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket; } impl AsRawHandleOrSocket for Stdin { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl<'a> AsRawHandleOrSocket for StdinLock<'a> { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl AsRawHandleOrSocket for Stdout { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl<'a> AsRawHandleOrSocket for StdoutLock<'a> { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl AsRawHandleOrSocket for Stderr { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl<'a> AsRawHandleOrSocket for StderrLock<'a> { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl AsRawHandleOrSocket for File { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl AsRawHandleOrSocket for ChildStdin { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl AsRawHandleOrSocket for ChildStdout { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl AsRawHandleOrSocket for ChildStderr { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } impl AsRawHandleOrSocket for TcpStream { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Socket(Self::as_raw_socket(self)) } } #[cfg(feature = "os_pipe")] impl AsRawHandleOrSocket for PipeReader { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } #[cfg(feature = "os_pipe")] impl AsRawHandleOrSocket for PipeWriter { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { RawHandleOrSocket::Handle(Self::as_raw_handle(self)) } } #[cfg(windows)] impl fmt::Debug for RawHandleOrSocket { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut b = f.debug_struct("RawHandleOrSocket"); // Just print the raw sockets; don't try to print the path or any // information about it, because this information is otherwise // unavailable to safe portable Rust code. match self { RawHandleOrSocket::Handle(raw_handle) => b.field("raw_handle", &raw_handle), RawHandleOrSocket::Socket(raw_socket) => b.field("raw_socket", &raw_socket), }; b.finish() } }
true
1e660ec705c46aa248a6552dab381ea38231632d
Rust
pseudo-social/nymdex
/src/main.rs
UTF-8
1,359
2.515625
3
[ "MIT" ]
permissive
mod application; mod logger; mod producer; use producer::{amqp::AMQPProducer, kafka::KafkaProducer, Producer}; #[actix::main] #[doc(hidden)] /// Where the magic happens 🌌 async fn main() -> Result<(), Box<dyn std::error::Error>> { // Setup the indexer application::initialize()?; // Setup the producer let producer_type = producer::get_type()?; if !(producer_type == producer::Type::Kafka || producer_type == producer::Type::AMQP) { log::error!( "Only kafka & amqp are currently supported as a producer_type, more to come soon!" ); } // Setup the indexer let indexer = application::create_near_indexer(); let block_stream = indexer.streamer(); // Spawn consumers based on specified type match producer_type { producer::Type::Kafka => { let mut producer = KafkaProducer::new().await; actix::spawn(async move { producer.consume(block_stream).await }); } producer::Type::AMQP => { let mut producer = AMQPProducer::new().await; actix::spawn(async move { producer.consume(block_stream).await }); } _ => log::error!("This should never happen, praise be to the aether."), } // Wait til a SIG-INT tokio::signal::ctrl_c().await?; log::info!("Shutting down nymdex..."); Ok(()) }
true
95508caf1f3ba2be3ed9ae9d7d50794f90648eed
Rust
grogers0/advent_of_code
/2019/day14/src/main.rs
UTF-8
5,628
3.0625
3
[ "MIT" ]
permissive
use std::cmp::Ordering; use std::collections::HashMap; use std::io::{self, Read}; #[derive(Debug)] struct Reaction { inputs: HashMap<String, u64>, output_amount: u64 } fn parse(puzzle_input: &str) -> HashMap<String, Reaction> { puzzle_input.trim().lines().map(|line| { let mut sp = line.split("=>"); let inputs = sp.next().unwrap(); let output = sp.next().unwrap(); let mut sp = output.trim().split(" "); let output_amount = sp.next().unwrap().parse().unwrap(); let output_chemical = sp.next().unwrap().to_string(); let inputs = inputs.trim().split(",").map(|input| { let mut sp = input.trim().split(" "); let input_amount = sp.next().unwrap().parse().unwrap(); let input_chemical = sp.next().unwrap().to_string(); (input_chemical, input_amount) }).collect(); (output_chemical, Reaction { inputs: inputs, output_amount: output_amount }) }).collect() } fn resolve_one_reaction(reaction: &Reaction, needed_chemicals: &mut HashMap<String, i64>, chemical: &str, amount: u64) { let times = ((amount + reaction.output_amount - 1) / reaction.output_amount) as i64; debug_assert!(times > 0); for (input_chemical, input_amount) in reaction.inputs.iter() { *needed_chemicals.entry(input_chemical.to_string()).or_insert(0) += times * *input_amount as i64; } *needed_chemicals.get_mut(chemical).unwrap() -= times * reaction.output_amount as i64; } fn resolve_next_reaction(reactions: &HashMap<String, Reaction>, needed_chemicals: &mut HashMap<String, i64>) -> bool { for (needed_chemical, needed_amount) in needed_chemicals.clone() { if needed_chemical != "ORE" && needed_amount > 0 { resolve_one_reaction(&reactions[&needed_chemical], needed_chemicals, &needed_chemical, needed_amount as u64); return true; } } false } fn resolve_reactions(reactions: &HashMap<String, Reaction>, needed_chemicals: &mut HashMap<String, i64>) { while resolve_next_reaction(reactions, needed_chemicals) { } } fn ore_needed_for_fuel(reactions: &HashMap<String, Reaction>, fuel: u64) -> u64 { let mut needed_chemicals = HashMap::new(); needed_chemicals.insert("FUEL".to_string(), fuel as i64); resolve_reactions(reactions, &mut needed_chemicals); needed_chemicals["ORE"] as u64 } fn fuel_for_available_ore_upper_bound(reactions: &HashMap<String, Reaction>, ore: u64) -> u64 { for fuel_exp in 1.. { let fuel = 1 << fuel_exp; if ore_needed_for_fuel(reactions, fuel) > ore { return fuel } } panic!() } fn fuel_for_available_ore(reactions: &HashMap<String, Reaction>, ore: u64) -> u64 { let mut max = fuel_for_available_ore_upper_bound(reactions, ore); let mut min = max / 2; while max - min > 1 { let mid = min + (max - min) / 2; match ore_needed_for_fuel(reactions, mid).cmp(&ore) { Ordering::Equal => return mid, Ordering::Less => min = mid, Ordering::Greater => max = mid } } min } fn part1(puzzle_input: &str) -> u64 { let reactions = parse(puzzle_input); ore_needed_for_fuel(&reactions, 1) } fn part2(puzzle_input: &str) -> u64 { let reactions = parse(puzzle_input); fuel_for_available_ore(&reactions, 1_000_000_000_000) } fn main() { let mut puzzle_input = String::new(); io::stdin().read_to_string(&mut puzzle_input).unwrap(); println!("{}", part1(&puzzle_input)); println!("{}", part2(&puzzle_input)); } #[cfg(test)] mod tests { use super::*; const EX1: &str = " 10 ORE => 10 A 1 ORE => 1 B 7 A, 1 B => 1 C 7 A, 1 C => 1 D 7 A, 1 D => 1 E 7 A, 1 E => 1 FUEL"; const EX2: &str = " 9 ORE => 2 A 8 ORE => 3 B 7 ORE => 5 C 3 A, 4 B => 1 AB 5 B, 7 C => 1 BC 4 C, 1 A => 1 CA 2 AB, 3 BC, 4 CA => 1 FUEL"; const EX3: &str = " 157 ORE => 5 NZVS 165 ORE => 6 DCFZ 44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL 12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ 179 ORE => 7 PSHF 177 ORE => 5 HKGWZ 7 DCFZ, 7 PSHF => 2 XJWVT 165 ORE => 2 GPVTF 3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT"; const EX4: &str = " 2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG 17 NVRVD, 3 JNWZP => 8 VPVL 53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL 22 VJHF, 37 MNCFX => 5 FWMGM 139 ORE => 4 NVRVD 144 ORE => 7 JNWZP 5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC 5 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV 145 ORE => 6 MNCFX 1 NVRVD => 8 CXFTF 1 VJHF, 6 MNCFX => 4 RFSQX 176 ORE => 6 VJHF"; const EX5: &str = " 171 ORE => 8 CNZTR 7 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL 114 ORE => 4 BHXH 14 VRPVC => 6 BMBT 6 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL 6 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT 15 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW 13 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW 5 BMBT => 4 WPTQ 189 ORE => 9 KTJDG 1 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP 12 VRPVC, 27 CNZTR => 2 XDBXC 15 KTJDG, 12 BHXH => 5 XCVML 3 BHXH, 2 VRPVC => 7 MZWV 121 ORE => 7 VRPVC 7 XCVML => 6 RJRHP 5 BHXH, 4 VRPVC => 5 LTCX"; #[test] fn test_part1() { assert_eq!(part1(EX1), 31); assert_eq!(part1(EX2), 165); assert_eq!(part1(EX3), 13312); assert_eq!(part1(EX4), 180697); assert_eq!(part1(EX5), 2210736); } #[test] fn test_part2() { assert_eq!(part2(EX3), 82892753); assert_eq!(part2(EX4), 5586022); assert_eq!(part2(EX5), 460664); } }
true
3ce191b17235166a4fa94fe19033d9190bd116b2
Rust
davideGiovannini/rust_sdl2_engine
/leek/src/font/mod.rs
UTF-8
3,522
3.359375
3
[]
no_license
use sdl2::rect::Rect; use sdl2::render::{Texture, WindowCanvas}; pub struct BitmapFont { texture: Texture, char_width: u32, char_height: u32, } impl BitmapFont { // TODO maybe create from Path instead of from Texture // TODO also could be useful to have a function on Engine that returns the bitmap font pub fn new(texture: Texture, char_size: (u32, u32)) -> Self { BitmapFont { texture, char_width: char_size.0, char_height: char_size.1, } } pub fn vram_size(&self) -> usize { let tex_query = self.texture.query(); let pixels = tex_query.width * tex_query.height; tex_query.format.byte_size_of_pixels(pixels as usize) } pub fn set_color(&self, red: u8, green: u8, blue: u8) { unsafe { use sdl2::get_error; use sdl2::sys; let raw = self.texture.raw(); let ret = sys::SDL_SetTextureColorMod(raw, red, green, blue); if ret != 0 { panic!("Error setting color mod: {}", get_error()) } } } // TODO improve this // TODO at least during debug check that the char are in the correct range (can be handled) pub fn render_text(&self, text: &str, point: (i32, i32), renderer: &mut WindowCanvas) { let width = self.texture.query().width; let width = width - width % self.char_width; let mut line = 0; // This is needed to rebalance the index when going on a new line \n let mut x_counter_offset = 0; for (char_count, character) in text.char_indices() { if character == '\n' { line += 1; x_counter_offset = char_count + 1; continue; } let char_index = character as usize - 32; let src_x = ((char_index as u32 * self.char_width) % width) as i32; let src_y = ((char_index as u32 * self.char_width / width) * self.char_height) as i32; let src_rect = Rect::new(src_x, src_y, self.char_width, self.char_height); let dest_x = ((char_count - x_counter_offset) as u32 * self.char_width) as i32; let dest_y = (line * self.char_height) as i32; let dest_rect = Rect::new( dest_x + point.0, dest_y + point.1, self.char_width, self.char_height, ); renderer.copy(&self.texture, src_rect, dest_rect).unwrap(); } } pub fn render_text_from_right( &self, text: &str, point: (i32, i32), renderer: &mut WindowCanvas, ) { let width = (self.char_width) as usize; self.render_text( text, (point.0 - (text.len() * width) as i32, point.1), renderer, ) } // TODO add other functions (to print text centered or right aligned) pub fn render_text_centered(&self, text: &str, point: (i32, i32), renderer: &mut WindowCanvas) { let mut n_lines = 0; let mut largest_line = 0; for line in text.lines() { largest_line = largest_line.max(line.chars().count()); n_lines += 1; } let width = (largest_line as u32 * self.char_width) as i32; let heigth = (n_lines as u32 * self.char_height) as i32; let x = point.0 - width / 2; let y = point.1 - heigth / 2; self.render_text(text, (x, y), renderer) } }
true
4c676ab989d73ee08e32ad929f5db6c78e6f6c3d
Rust
timvermeulen/advent-of-code
/src/solutions/year2015/day05.rs
UTF-8
1,193
3.375
3
[]
no_license
fn part1(input: &str) -> usize { input.lines().filter(|&s| is_nice1(s)).count() } fn is_nice1(string: &str) -> bool { string.chars().filter(|&c| "aeiou".contains(c)).count() >= 3 && string .chars() .zip(string.chars().skip(1)) .any(|(a, b)| a == b) && !["ab", "cd", "pq", "xy"].iter().any(|&s| string.contains(s)) } fn part2(input: &str) -> usize { input.lines().filter(|&s| is_nice2(s)).count() } fn is_nice2(string: &str) -> bool { rule1(string) && rule2(string) } fn rule1(string: &str) -> bool { let bytes = string.as_bytes(); (0..bytes.len() - 3).any(|i| { bytes[i + 2..] .windows(2) .any(|s| s[0] == bytes[i] && s[1] == bytes[i + 1]) }) } fn rule2(string: &str) -> bool { string .chars() .zip(string.chars().skip(2)) .any(|(a, b)| a == b) } pub fn solve(input: &str) -> (usize, usize) { (part1(input), part2(input)) } #[cfg(test)] use super::*; #[async_std::test] async fn test() -> Result<(), InputError> { let input = get_input(2015, 5).await?; assert_eq!(part1(&input), 258); assert_eq!(part2(&input), 53); Ok(()) }
true
cfe1aa8bfec31520a804c8ba65015c70adfc774d
Rust
kccqzy/ucla-cs-111-spring2018
/lab1a-rust/src/main.rs
UTF-8
5,988
2.578125
3
[]
no_license
extern crate nix; extern crate termios; use std::os::unix::process::ExitStatusExt; use nix::sys::signal::Signal; use std::ops::BitOr; use std::process::{Command, Stdio}; use std::fs::File; use std::io::{Error, Read, Write}; use std::os::unix::prelude::*; use std::process::exit; use nix::poll::{poll, EventFlags, PollFd}; use nix::unistd::Pid; use nix::sys::signal::kill; use termios::*; const CR: u8 = 13; const LF: u8 = 10; pub struct RawTerminalRAII { pub original_termios: termios::Termios, } impl RawTerminalRAII { fn new() -> RawTerminalRAII { let fd = 0; let mut termios = Termios::from_fd(fd).unwrap(); let orig = termios; termios.c_iflag = ISTRIP; termios.c_oflag = 0; termios.c_lflag = 0; tcsetattr(fd, TCSANOW, &termios).unwrap(); RawTerminalRAII { original_termios: orig, } } } impl Drop for RawTerminalRAII { fn drop(&mut self) { match tcsetattr(0, TCSANOW, &self.original_termios) { Ok(_) => (), _ => exit(1), } } } fn read_char_echo(stdin: &mut File, stdout: &mut File) -> Option<u8> { let mut buf = [0]; let read_size = stdin.read(&mut buf).unwrap(); if read_size == 0 { None } else { if buf[0] == CR || buf[0] == LF { stdout.write_all(&[CR, LF]).unwrap(); Some(buf[0]) } else if buf[0] == 4 { None } else { stdout.write(&buf).unwrap(); Some(buf[0]) } } } fn do_echo(stdin: &mut File, stdout: &mut File) { loop { if read_char_echo(stdin, stdout).is_none() { break; } } } fn translate_buffer(inbuf: &[u8]) -> Vec<u8> { inbuf .iter() .flat_map(|c| { if *c == LF { Some(CR).into_iter().chain(Some(LF).into_iter()) } else { Some(*c).into_iter().chain(None.into_iter()) } }) .collect() } fn do_shell(stdin: &mut File, stdout: &mut File) { let mut child = Command::new("/bin/bash") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .unwrap(); let pid = Pid::from_raw(child.id() as i32); { // Inspecting the source here reveals that the child's stdin and stdout are // thin wrappers of a file descriptor. No buffering yay! let child_stdout_fd = child.stdout.as_ref().unwrap().as_raw_fd(); let mut poll_fds = [ PollFd::new(0, EventFlags::POLLIN), PollFd::new(child_stdout_fd, EventFlags::POLLIN), ]; fn has_input(pfd: &PollFd) -> bool { pfd.revents() .map_or(false, |e| e.contains(EventFlags::POLLIN)) } fn has_hup(pfd: &PollFd) -> bool { pfd.revents().map_or(false, |e| { e.intersects(EventFlags::POLLHUP.bitor(EventFlags::POLLERR)) }) } loop { poll(&mut poll_fds, -1).unwrap(); // Does the shell have any output for us? if child.stdout.is_some() && has_input(&poll_fds[1]) { let mut buf = [0; 65536]; let bytes_read = child.stdout.as_mut().unwrap().read(&mut buf).unwrap(); if bytes_read == 0 { child.stdout = None; poll_fds[1] = PollFd::new(-1, EventFlags::empty()); } else { let outbuf = translate_buffer(&buf[0..bytes_read]); stdout.write_all(&outbuf).unwrap(); continue; // The shell may have had more output beyond those we've consumed, so // try reading again. } } // Has the shell exited? if child.stdout.is_some() && has_hup(&poll_fds[1]) { child.stdout = None; poll_fds[1] = PollFd::new(-1, EventFlags::empty()); } // Has the user typed anything here? if child.stdin.is_some() && has_input(&poll_fds[0]) { match read_char_echo(stdin, stdout) { None => child.stdin = None, Some(3) => kill(pid, Some(Signal::SIGINT)).unwrap(), Some(c) => child .stdin .as_mut() .unwrap() .write_all(&[if c == CR { LF } else { c }]) .unwrap_or_else(|e: Error| { if let std::io::ErrorKind::BrokenPipe = e.kind() { child.stdout = None; poll_fds[1] = PollFd::new(-1, EventFlags::empty()); } else { panic!("unexpected error when writing to shell: {:?}", e) } }), } } // Has the user closed it? if child.stdin.is_some() && has_hup(&poll_fds[0]) { child.stdin = None } if child.stdout.is_none() { break; } } } // Now perform orderly shutdown let status = child.wait().unwrap(); eprintln!( "SHELL EXIT SIGNAL={} STATUS={}\r", status.signal().unwrap_or(0), status.code().unwrap_or(0) ) } fn main() { let mut stdin = unsafe { File::from_raw_fd(0) }; let mut stdout = unsafe { File::from_raw_fd(1) }; let args: Vec<String> = std::env::args().collect(); if args.len() == 2 && args[1] == "--shell" { let _raw_terminal_raii = RawTerminalRAII::new(); do_shell(&mut stdin, &mut stdout) } else if args.len() > 1 { eprintln!("{}: unrecognized arguments", args[0]) } else { let _raw_terminal_raii = RawTerminalRAII::new(); do_echo(&mut stdin, &mut stdout) } }
true
373b458444f541f320fb1e48faca9fd98d7f4b6f
Rust
ykafia/SyracuseRust
/src/base_types.rs
UTF-8
5,678
3.28125
3
[]
no_license
use std::fmt; use std::ops::{Add, AddAssign, Sub}; pub struct Value { pub x: u64, pub y: u64, } impl fmt::Display for Value { // This trait requires `fmt` with this exact signature. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}-{}", self.x, self.y) } } #[derive(Clone)] pub struct SyracuseInfo { pub flight: u64, pub height: u64, pub above_flight: u64, pub updated_above: bool, pub init: u64, pub seen: Vec<u64>, } #[derive(Clone)] pub struct TypeLists { pub type1: Vec<u64>, pub type2: Vec<u64>, pub type3: Vec<u64>, pub type4: Vec<u64>, } impl fmt::Display for SyracuseInfo { // This trait requires `fmt` with this exact signature. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Flight : {}\nHeight : {}\nAbove Flight : {}\n", self.flight, self.height, self.above_flight ) } } impl Add<Value> for Value { type Output = Value; fn add(self, other: Value) -> Value { let added = self.x.checked_add(other.x); match added { Some(_x) => Value { x: self.x + other.x, y: self.y + other.y, }, None => { let rest = std::u64::MAX - self.x; let unit = other.x - rest; Value { x: unit, y: self.y + other.y + 1, } } } } } impl Sub<Value> for Value { type Output = Value; fn sub(self, other: Value) -> Value { let added = self.x.checked_sub(other.x); match added { Some(_x) => Value { x: self.x - other.x, y: self.y - other.y, }, None => { let rest = other.x - self.x; let unit = std::u64::MAX - rest; Value { x: unit, y: self.y - other.y - 1, } } } } } impl Add<u64> for Value { type Output = Value; fn add(self, other: u64) -> Value { let added = self.x.checked_add(other); match added { Some(_x) => Value { x: self.x + other, y: self.y, }, None => { let rest = std::u64::MAX - self.x; let unit = other - rest; Value { x: unit, y: self.y + 1, } } } } } impl Sub<u64> for Value { type Output = Value; fn sub(self, other: u64) -> Value { let added = self.x.checked_add(other); match added { Some(_x) => Value { x: self.x - other, y: self.y, }, None => { let rest = other - self.x; let unit = std::u64::MAX - rest; Value { x: unit, y: self.y - 1, } } } } } impl AddAssign<u64> for Value { fn add_assign(&mut self, other: u64) { let added = self.x + other; if added < self.x { self.x = self.x + other; self.y = self.y + 1; } else { self.x = self.x + other; } } } // Check syracuse types here fn max_flight(arr: &Vec<SyracuseInfo>) -> u64 { let mut max = 0u64; for i in arr.iter() { if i.flight > max { max = i.flight; } } return max; } fn max_height(arr: &Vec<SyracuseInfo>) -> u64 { let mut max = 0u64; for i in arr.iter() { if i.height > max { max = i.height; } } return max; } fn max_above(arr: &Vec<SyracuseInfo>) -> u64 { let mut max = 0u64; for i in arr.iter() { if i.above_flight > max { max = i.above_flight; } } return max; } pub fn list_type1(prev: &Vec<SyracuseInfo>) -> Vec<u64>{ let mut uniques:Vec<u64> = Vec::new(); let mut result:Vec<u64> = Vec::new(); for i in prev.iter() { uniques.extend(&i.seen); } uniques = unique(uniques); let maxval = match uniques.last() { Some(x) => x, None => &0u64 }; for x in 1u64..*maxval { if uniques.contains(&x) && &x%2!=0 { result.push(x); } } return result; } pub fn is_type2(prev: &Vec<SyracuseInfo>, syr: &SyracuseInfo) -> bool { let max = max_flight(prev); if max < syr.flight { return true; } else { return false; } } pub fn is_type3(prev: &Vec<SyracuseInfo>, syr: &SyracuseInfo) -> bool { let max = max_height(prev); if max < syr.height { return true; } else { return false; } } pub fn is_type4(prev: &Vec<SyracuseInfo>, syr: &SyracuseInfo) -> bool { let max = max_above(prev); if max < syr.above_flight { return true; } else { return false; } } pub fn types_head(data: &TypeLists) { println!("List of Type 1 :\n"); for j in data.type1.iter() { print!(" {} |", j); } println!("\n\nList of Type 2 :\n"); for j in data.type2.iter() { print!(" {} |", j); } println!("\n\nList of Type 3 :\n"); for j in data.type3.iter() { print!(" {} |", j); } println!("\n\nList of Type 4 :\n"); for j in data.type4.iter() { print!(" {} |", j); } } pub fn unique(a: Vec<u64>) -> Vec<u64> { let mut x = a.clone(); x.sort(); x.dedup(); return x; }
true
a6d4f619208e6c1c2b8d6227fccb037f1143871f
Rust
zezic/nona
/src/color.rs
UTF-8
2,258
3.390625
3
[ "MIT" ]
permissive
use clamped::Clamp; use std::ops::Rem; #[derive(Debug, Copy, Clone, Default)] pub struct Color { pub r: f32, pub g: f32, pub b: f32, pub a: f32, } impl Color { pub fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color { Color { r, g, b, a } } pub fn rgb(r: f32, g: f32, b: f32) -> Color { Color { r, g, b, a: 1.0 } } pub fn rgba_i(r: u8, g: u8, b: u8, a: u8) -> Color { Color { r: r as f32 / 255.0, g: g as f32 / 255.0, b: b as f32 / 255.0, a: a as f32 / 255.0, } } pub fn rgb_i(r: u8, g: u8, b: u8) -> Color { Self::rgba_i(r, g, b, 255) } pub fn lerp(self, c: Color, u: f32) -> Color { let u = u.clamped(0.0, 1.0); let om = 1.0 - u; Color { r: self.r * om + c.r * u, g: self.g * om + c.g * u, b: self.b * om + c.b * u, a: self.a * om + c.a * u, } } pub fn hsla(h: f32, s: f32, l: f32, a: f32) -> Color { let mut h = h.rem(1.0); if h < 0.0 { h += 1.0; } let s = s.clamped(0.0, 1.0); let l = l.clamped(0.0, 1.0); let m2 = if l <= 0.5 { l * (1.0 + s) } else { l + s - l * s }; let m1 = 2.0 * l - m2; Color { r: hue(h + 1.0 / 3.0, m1, m2).clamped(0.0, 1.0), g: hue(h, m1, m2).clamped(0.0, 1.0), b: hue(h - 1.0 / 3.0, m1, m2).clamped(0.0, 1.0), a, } } pub fn hsl(h: f32, s: f32, l: f32) -> Color { Self::hsla(h, s, l, 1.0) } } impl From<(f32, f32, f32)> for Color { fn from((r, g, b): (f32, f32, f32)) -> Self { Color::rgb(r, g, b) } } impl From<(f32, f32, f32, f32)> for Color { fn from((r, g, b, a): (f32, f32, f32, f32)) -> Self { Color::rgba(r, g, b, a) } } fn hue(mut h: f32, m1: f32, m2: f32) -> f32 { if h < 0.0 { h += 1.0; } if h > 1.0 { h -= 1.0 }; if h < 1.0 / 6.0 { return m1 + (m2 - m1) * h * 6.0; } else if h < 3.0 / 6.0 { m2 } else if h < 4.0 / 6.0 { m1 + (m2 - m1) * (2.0 / 3.0 - h) * 6.0 } else { m1 } }
true
3ddb17a39f8a426bc96fe755e68f5ee2c7a7e3ff
Rust
rome/tools
/xtask/coverage/src/compare.rs
UTF-8
2,834
2.609375
3
[ "MIT" ]
permissive
use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use xtask::project_root; use crate::results::emit_compare; use crate::util::decode_maybe_utf16_string; use crate::TestResults; // this is the filename of the results coming from `main` branch const BASE_RESULT_FILE: &str = "base_results.json"; // this is the filename of the results coming from the current PR const NEW_RESULT_FILE: &str = "new_results.json"; pub fn coverage_compare( base_result_path: Option<&str>, new_result_path: Option<&str>, markdown: bool, ) { // resolve the path passed as argument, or retrieve the default one let base_result_dir = if let Some(base_result_path) = base_result_path { PathBuf::from(base_result_path) } else { project_root().join(BASE_RESULT_FILE) }; // resolve the path passed as argument, or retrieve the default one let new_result_dir = if let Some(new_result_path) = new_result_path { PathBuf::from(new_result_path) } else { project_root().join(NEW_RESULT_FILE) }; if !base_result_dir.exists() { panic!( "The path to the base results doesn't exist: {:?}", base_result_dir ); } if !&new_result_dir.exists() { panic!( "The path to the new results doesn't exist: {:?}", new_result_dir ); } let mut base_results = read_test_results(base_result_dir.as_path(), "base") .into_iter() .collect::<Vec<_>>(); // Sort suite names to get a stable result in CI comments base_results.sort_unstable_by(|(suite_a, _), (suite_b, _)| suite_a.cmp(suite_b)); let mut new_results = read_test_results(new_result_dir.as_path(), "new"); for (suite, base) in base_results.into_iter() { let new_result = new_results.remove(&suite).unwrap_or_else(TestResults::new); emit_compare(&base, &new_result, suite.as_str(), markdown); } for (suite, new) in new_results.drain() { emit_compare(&TestResults::new(), &new, suite.as_str(), markdown); } } fn read_test_results(path: &Path, name: &'static str) -> HashMap<String, TestResults> { let mut file = File::open(path) .unwrap_or_else(|err| panic!("Can't read the file of the {} results: {:?}", name, err)); let mut buffer = Vec::new(); file.read_to_end(&mut buffer) .unwrap_or_else(|err| panic!("Can't read the file of the {} results: {:?}", name, err)); let content = decode_maybe_utf16_string(&buffer) .unwrap_or_else(|err| panic!("Can't read the file of the {} results: {:?}", name, err)); serde_json::from_str(&content).unwrap_or_else(|err| { panic!( "Can't parse the JSON file of the {} results: {:?}", name, err ) }) }
true
b82270d93b926745d4b57800e6bc9719077511e6
Rust
JoseFilipeFerreira/carage
/carage/src/img/api.rs
UTF-8
2,899
2.65625
3
[]
no_license
use super::{File, FileApi}; use crate::{ car::Car, fairings::{Claims, Db}, }; use lazy_static::lazy_static; use rocket::serde::json::Json; use rocket::{ data::{Limits, ToByteUnit}, fs::NamedFile, }; use std::{ fs, io::{self, Write}, path::Path, }; use uuid::Uuid; lazy_static! { pub static ref ROUTES: Vec<rocket::Route> = routes![get, create, remove]; } #[get("/<id>")] pub async fn get(conn: Db, id: String) -> Option<NamedFile> { let id = Uuid::parse_str(&id).unwrap(); let path = match conn.run(move |c| File::get(id, c)).await { Ok(f) => Some(f.id), _ => None, }?; NamedFile::open(Path::new("images/").join(format!("{}", path))) .await .ok() } #[post("/create", data = "<img>")] pub async fn create( conn: Db, img: Json<FileApi>, claims: Claims, limits: &Limits, ) -> Result<Json<File>, std::io::Error> { let limits = limits.clone(); conn.run(move |c| { let car = Car::get(&img.car_id, c).unwrap(); if car.owner == claims.email { let id = Uuid::new_v4(); let path = Path::new("images/").join(id.to_string()); let bytes = image_base64::from_base64(img.image.clone()); if bytes.len() > limits.get("file/image").unwrap_or_else(|| 10.mebibytes()) { Err(io::Error::new(io::ErrorKind::InvalidInput, "Image too big")) } else { let mut image_file = fs::File::create(path)?; image_file.write_all(&bytes) }?; let db_entry = File { id, filename: img.filename.clone(), car_id: img.car_id.clone(), }; db_entry .insert(c) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "Invalid base64 format")) } else { Err(io::Error::new(io::ErrorKind::InvalidInput, "Image too big")) } }) .await .map(Json) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "Invalid base64 format")) } #[delete("/remove/<img>")] pub async fn remove(conn: Db, claims: Claims, img: String) -> Option<Json<File>> { if let Ok(id) = Uuid::parse_str(&img) { match conn .run(move |c| { let file = File::get(id, c)?; let car = Car::get(&file.car_id, c)?; if car.owner == claims.email { let f = File::delete(id, c); fs::remove_file(Path::new("images/").join(img.clone())) .map_err(|_| diesel::result::Error::NotFound)?; f } else { Err(diesel::result::Error::NotFound) } }) .await { Ok(u) => Some(Json(u)), _ => None, } } else { None } }
true
3347c4cdea2b5233c0db39cf96c5197b1b5aec61
Rust
mattjmcnaughton/hacks
/binstaller/src/main.rs
UTF-8
2,493
2.6875
3
[]
no_license
use std::error::Error; use std::fs; use std::io::Read; use std::path::Path; use flate2::read::GzDecoder; use quicli::prelude::*; use structopt::StructOpt; use tar::Archive; use tempfile::tempdir; use xz2::read::XzDecoder; #[derive(Debug, StructOpt)] struct Cli { remote_url: String, destination_directory: String, extracted_artifact_base: String, binary_name: String, #[structopt(flatten)] verbosity: Verbosity, } fn main() -> Result<(), Box<dyn Error>> { let args = Cli::from_args(); args.verbosity.setup_env_logger("binstaller")?; run(&args.remote_url, &args.destination_directory, &args.extracted_artifact_base, &args.binary_name) } fn run(remote_url: &String, destination_directory: &String, extracted_artifact_base: &String, binary_name: &String) -> Result<(), Box<dyn Error>> { let url = reqwest::Url::parse(remote_url)?; let artifact_path_segments = url.path_segments().ok_or(format!("Cannot parse {} into path segments", remote_url))?; let artifact_name = artifact_path_segments.last().ok_or(format!("Cannot extract artifact name from path segments returned by {}", remote_url))?; // Long-term, long into async w/ reqwest. let res = reqwest::blocking::get(url.as_str())?; let decoder = decoder_factory(artifact_name, res)?; let mut archive = Archive::new(decoder); let tmp_dir = tempdir()?; info!("Unpacking tar into {:?}", tmp_dir.path()); archive.unpack(tmp_dir.path())?; let src_path = tmp_dir.path().join(extracted_artifact_base).join(binary_name); // TODO: This is hacky let dest_path = Path::new(destination_directory).join(Path::new(binary_name).file_name().unwrap()); info!("Copying file from {:?} to {:?}", src_path, dest_path); fs::copy(src_path, dest_path)?; Ok(()) } fn decoder_factory(remote_artifact_name: &str, result: reqwest::blocking::Response) -> Result<Box<dyn Read>, Box<dyn Error>> { if remote_artifact_name.ends_with(".xz") { info!("Identified extractable file type: {}", "xz"); Ok(Box::new(XzDecoder::new(result))) } else if remote_artifact_name.ends_with(".gz") { info!("Identified extractable file type: {}", "gz"); Ok(Box::new(GzDecoder::new(result))) } else { // https://doc.rust-lang.org/std/convert/trait.From.html#impl-From%3C%26%27_%20str%3E let boxed_err = Box::<dyn Error>::from(format!("Cannot determine decoder for {}", remote_artifact_name)); Err(boxed_err) } }
true
a810d280e9ea5bd1635716c29f2ecb792f2cc655
Rust
bobwhitelock/exercism-exercises
/rust/hamming/src/lib.rs
UTF-8
332
3.296875
3
[]
no_license
pub fn hamming_distance<'a>(strand: &'a str, other: &'a str) -> Result<u32, &'a str> { if strand.chars().count() != other.chars().count() { return Err("inputs of different length") } let distance = strand.chars().zip(other.chars()) .filter(|&(s, o)| s != o) .count() as u32; Ok(distance) }
true
ebe1f18a86d3b9adf1987232fd794451b763a5ce
Rust
alexander-zw/plusplus
/src/main.rs
UTF-8
1,565
2.984375
3
[]
no_license
/// Main file that handles terminal arguments. mod tokenizer; mod compiler; use std::fs::File; use std::io::Write; use crate::tokenizer::Tokenizer; use crate::compiler::Compiler; fn compile_pp_file(filename: &str) { print_title(); println!("[ INFO ] Trying to open {}...", filename); let tokenizer = Tokenizer::new(filename); println!("[ INFO ] Compiling {}...", filename); let mut compiler = Compiler::new(tokenizer); compiler.compile(); let mut output_filename = String::from(&filename[..filename.len()-2]); output_filename.push_str("js"); println!("[ INFO ] Successfully compiled to {}!", output_filename); } fn write_to_file(output_filename: String, lines: Vec<String>) { let mut outfile = File::create(&output_filename) .expect(&format!("[ ERROR ] Could not create output file {}!", &output_filename)); for line in &lines { outfile.write_all(line.as_bytes()) .expect("[ ERROR ] Could not write to output file!"); } } fn print_long_info() { print_title(); println!("Written by: {}", env!("CARGO_PKG_AUTHORS")); println!("Homepage: {}", env!("CARGO_PKG_HOMEPAGE")); println!("Usage: pp [option] [ source.pp ] [args]"); } fn print_title() { println!("{} (v{}), {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_DESCRIPTION")); } fn main() { let args: Vec<String> = std::env::args().collect(); match args.len() { 2 => compile_pp_file(&args[1]), _ => print_long_info() } }
true
05f57b07591de90f33d9972c776096c7e3a119af
Rust
ldfdev/Exercises-from-the-book-Beginning-Rust-From-Novice-To-Expert
/Chapter 9/compiler_infers_()_retun_type_for_functions_by_default.rs
UTF-8
249
2.8125
3
[]
no_license
// not specifying a return type in function's signature // resumes to having () rturn type fn create_a_pair() { // returning a tuple when compiler infers () type // yields error[E0308]: mismatched types (1,2) } fn main() { }
true
247597d2f2b06d8eb841906b4724e433a49f4f48
Rust
brianarpie/rusty-sorts
/src/main.rs
UTF-8
1,706
3.140625
3
[]
no_license
mod sorts; mod benchmark; extern crate rand; use rand::distributions::{IndependentSample, Range}; use std::i32; fn main() { // TODO: move the array instantiation into a separate method. const ARRAY_LENGTH: usize = 10000; let mut array: [i32; ARRAY_LENGTH] = [0;ARRAY_LENGTH]; let between = Range::new(0, 1000); let mut rng = rand::thread_rng(); for i in 0..ARRAY_LENGTH { array[i] = between.ind_sample(&mut rng); } let mut array1 = array; let insertion = sorts::insertion_sort; let insertion_time = time_sort(&insertion, &mut array1); let mut array2 = array; let selection = sorts::selection_sort; let selection_time = time_sort(&selection, &mut array2); let mut array3 = array; let merge = sorts::merge_sort; let merge_time = time_sort(&merge, &mut array3); let mut array4 = array; let quick = sorts::quick_sort; let quick_time = time_sort(&quick, &mut array4); println!("sorting {} elements", ARRAY_LENGTH); println!("selection: {}ms", selection_time); println!("insertion: {}ms", insertion_time); println!("merge: {}ms", merge_time); println!("quick: {}ms", quick_time); } fn time_sort(sort: &Fn(&mut[i32]) -> &mut[i32], array: &mut[i32]) -> usize { let mut timer = benchmark::Timer::new(); timer.start(); let sorted_array = sort(array); timer.stop(); verify_sorted(sorted_array); timer.get_elapsed_in_ms() as usize } fn verify_sorted(array: &mut[i32]) { let mut i_min = i32::MIN; for i in 0..array.len() { if array[i] >= i_min { i_min = array[i]; } else { panic!("Sort method failed to sort!"); } } }
true
02b17963b5f947c2843bb50d281b9827d80fe6c3
Rust
Twinklebear/bspline
/src/lib.rs
UTF-8
9,247
3.28125
3
[ "MIT" ]
permissive
//! [![logo](http://i.imgur.com/dnpEXyh.jpg)](http://i.imgur.com/RUEw8EW.png) //! //! bspline //! === //! A library for computing B-spline interpolating curves on generic control points. bspline can //! be used to evaluate B-splines of varying orders on any type that can be linearly interpolated, //! ranging from floats, positions, RGB colors to transformation matrices and so on. //! //! The bspline logo was generated using this library with a cubic B-spline in 2D for the positioning //! of the curve and a quadratic B-spline in RGB space to color it (check out the //! [logo](https://github.com/Twinklebear/bspline/blob/master/examples/logo.rs) example!). Other //! much simpler examples of 1D and 2D quadratic, cubic and quartic B-splines can also be found in //! the [examples](https://github.com/Twinklebear/bspline/tree/master/examples). //! //! # 1D Example //! //! This example shows how to create the 1D cardinal cubic B-spline example shown on [Wikipedia's //! B-splines page](https://en.wikipedia.org/wiki/B-spline). For examples of evaluating the spline //! to an image and saving the output see the [examples](https://github.com/Twinklebear/bspline/tree/master/examples). //! //! ```rust //! let points = vec![0.0, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0]; //! let knots = vec![-2.0, -2.0, -2.0, -2.0, -1.0, 0.0, 1.0, 2.0, 2.0, 2.0, 2.0]; //! let degree = 3; //! let spline = bspline::BSpline::new(degree, points, knots); //! ``` //! //! # Readings on B-splines //! //! The library assumes you are familiar at some level with how B-splines work, e.g. how //! control points and knots and effect the curve produced. No interactive //! editor is provided (at least currently). Some good places to start reading about B-splines to //! effectively use this library can be found below. //! //! - [Wikipedia page on B-splines](https://en.wikipedia.org/wiki/B-spline) //! - [Fundamentals of Computer Graphics](http://www.amazon.com/Fundamentals-Computer-Graphics-Peter-Shirley/dp/1568814690) //! (has a good chapter on curves) //! - [Splines and B-splines: An Introduction](http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v07/undervisningsmateriale/kap1.pdf) //! - [Geometric Modeling](http://atrey.karlin.mff.cuni.cz/projekty/vrr/doc/grafika/geometric%20modelling.pdf) //! - [A nice set of interactive examples](https://www.ibiblio.org/e-notes/Splines/Intro.htm) //! use std::ops::{Add, Mul}; use std::slice::Iter; extern crate trait_set; use trait_set::trait_set; extern crate num_traits; #[cfg(not(feature = "nalgebra-support"))] trait_set! { pub trait Float = num_traits::Float; } #[cfg(feature = "nalgebra-support")] extern crate nalgebra; #[cfg(feature = "nalgebra-support")] trait_set! { pub trait Float = nalgebra::RealField + Copy; } /// The interpolate trait is used to linearly interpolate between two types (or in the /// case of Quaternions, spherically linearly interpolate). The B-spline curve uses this /// trait to compute points on the curve for the given parameter value. /// /// A default implementation of this trait is provided for all `T` that are `Mul<f32, Output = T> /// + Add<Output = T> + Copy` as these are the only operations needed to linearly interpolate the /// values. Any type implementing this trait should perform whatever the appropriate linear /// interpolaton is for the type. pub trait Interpolate<F> { /// Linearly interpolate between `self` and `other` using `t`, for example with floats: /// /// ```text /// self * (1.0 - t) + other * t /// ``` /// /// If the result returned is not a correct linear interpolation of the values the /// curve produced using the value may not be correct. fn interpolate(&self, other: &Self, t: F) -> Self; } impl<T: Mul<F, Output = T> + Add<Output = T> + Copy, F: Float> Interpolate<F> for T { fn interpolate(&self, other: &Self, t: F) -> Self { *self * (F::one() - t) + *other * t } } /// Represents a B-spline curve that will use polynomials of the specified degree /// to interpolate between the control points given the knots. #[derive(Clone, Debug)] pub struct BSpline<T: Interpolate<F> + Copy, F: Float> { /// Degree of the polynomial that we use to make the curve segments degree: usize, /// Control points for the curve control_points: Vec<T>, /// The knot vector knots: Vec<F>, } impl<T: Interpolate<F> + Copy, F: Float> BSpline<T, F> { /// Create a new B-spline curve of the desired `degree` that will interpolate /// the `control_points` using the `knots`. The knots should be sorted in non-decreasing /// order otherwise they will be sorted for you, which may lead to undesired knots /// for control points. Note that here we use the interpolating polynomial degree, /// if you're familiar with the convention of "B-spline curve order" the degree is `curve_order - 1`. /// /// Your curve must have a valid number of control points and knots or the function will panic. A B-spline /// curve requires at least as one more control point than the degree (`control_points.len() > /// degree`) and the number of knots should be equal to `control_points.len() + degree + 1`. pub fn new(degree: usize, control_points: Vec<T>, mut knots: Vec<F>) -> BSpline<T, F> { if control_points.len() <= degree { panic!("Too few control points for curve"); } if knots.len() != control_points.len() + degree + 1 { panic!( "Invalid number of knots, got {}, expected {}", knots.len(), control_points.len() + degree + 1 ); } knots.sort_by(|a, b| a.partial_cmp(b).unwrap()); BSpline { degree, control_points, knots, } } /// Compute a point on the curve at `t`, the parameter **must** be in the inclusive range /// of values returned by `knot_domain`. If `t` is out of bounds this function will assert /// on debug builds and on release builds you'll likely get an out of bounds crash. pub fn point(&self, t: F) -> T { debug_assert!(t >= self.knot_domain().0 && t <= self.knot_domain().1); // Find the first index with a knot value greater than the t we're searching for. We want // to find i such that: knot[i] <= t < knot[i + 1] let i = match upper_bounds(&self.knots[..], t) { Some(x) if x == 0 => self.degree, Some(x) if x >= self.knots.len() - self.degree - 1 => { self.knots.len() - self.degree - 1 } Some(x) => x, None => self.knots.len() - self.degree - 1, }; self.de_boor_iterative(t, i) } /// Get an iterator over the control points. pub fn control_points(&self) -> Iter<T> { self.control_points.iter() } /// Get an iterator over the knots. pub fn knots(&self) -> Iter<F> { self.knots.iter() } /// Get the min and max knot domain values for finding the `t` range to compute /// the curve over. The curve is only defined over the inclusive range `[min, max]`, /// passing a `t` value outside of this range will result in an assert on debug builds /// and likely a crash on release builds. pub fn knot_domain(&self) -> (F, F) { ( self.knots[self.degree], self.knots[self.knots.len() - 1 - self.degree], ) } /// Iteratively compute de Boor's B-spline algorithm, this computes the recursive /// de Boor algorithm tree from the bottom up. At each level we use the results /// from the previous one to compute this level and store the results in the /// array indices we no longer need to compute the current level (the left one /// used computing node j). fn de_boor_iterative(&self, t: F, i_start: usize) -> T { let mut tmp = Vec::with_capacity(self.degree + 1); for j in 0..=self.degree { let p = j + i_start - self.degree - 1; tmp.push(self.control_points[p]); } for lvl in 0..self.degree { let k = lvl + 1; for j in 0..self.degree - lvl { let i = j + k + i_start - self.degree; let alpha = (t - self.knots[i - 1]) / (self.knots[i + self.degree - k] - self.knots[i - 1]); debug_assert!(alpha.is_finite()); tmp[j] = tmp[j].interpolate(&tmp[j + 1], alpha); } } tmp[0] } } /// Return the index of the first element greater than the value passed. /// The data **must** be sorted. If no element greater than the value /// passed is found the function returns None. fn upper_bounds<F: Float>(data: &[F], value: F) -> Option<usize> { let mut first = 0usize; let mut step; let mut count = data.len() as isize; while count > 0 { step = count / 2; let it = first + step as usize; if !value.lt(&data[it]) { first = it + 1; count -= step + 1; } else { count = step; } } // If we didn't find an element greater than value if first == data.len() { None } else { Some(first) } }
true
56fe0f25e702739561bd71e2b87c50822ee62ade
Rust
mcheshkov/icfpc2020
/app/parser.rs
UTF-8
4,456
2.734375
3
[ "MIT" ]
permissive
use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::Path; use text_parser::Action; mod text_parser; fn is_constant(action: &Action) -> bool { match action { Action::Number(_) => true, Action::Value("nil") => true, Action::List(args) => args.iter().all(is_constant), _ => false, } } fn parse_binding<'a, 'b>(actions: &'a [Action<'b>]) -> (&'b str, Action<'b>) { if let [Action::Value(id), Action::Value("="), rest] = actions { (id, rest.clone()) } else { panic!("Could not parse binding"); } } fn is_synonim(action: &Action) -> bool { match action { Action::Value(_) => true, _ => false, } } fn contains_no_references(action: &Action) -> bool { match action { Action::Number(_) => true, Action::Value(s) => !s.starts_with(":"), Action::List(items) => items.iter().all(contains_no_references), Action::SingleArgApplication(func, operand) => { contains_no_references(func) && contains_no_references(operand) } Action::MultipleArgApplication(func, operands) => { contains_no_references(func) && operands.iter().all(contains_no_references) } } } fn write_to_file(collection: &HashMap<&str, Action>, file: &mut File) { let mut items = collection.iter().collect::<Vec<_>>(); items.sort(); for (ident, body) in items { writeln!(file, "{} = {}", ident, body.to_string()).expect("Could not write line"); } } type Bindings<'a> = HashMap<&'a str, Action<'a>>; fn replace_all<'a, 'b>(mut bindings: Bindings<'a>, replacements: &'b Bindings<'a>) -> Bindings<'a> { bindings = bindings .into_iter() .map(|(k, mut value)| { for (ident, body) in replacements.iter() { let (new_value, _) = value.substitute_value(ident, body); value = new_value; } (k, value) }) .collect(); bindings .into_iter() .map(|(k, value)| (k, value.reduce_all_max().0)) .collect() } fn replace_matching<F: FnMut(&Action) -> bool>( bindings: Bindings, mut f: F, ) -> (Bindings, Bindings) { let (replacements, new_bindings) = bindings .into_iter() .partition::<HashMap<_, _>, _>(|(_, value)| f(value)); (replace_all(new_bindings, &replacements), replacements) } fn main() -> () { let mut input_file = File::open(Path::new("galaxy.txt")).expect("Could not open galaxy.txt"); let mut data = String::new(); input_file .read_to_string(&mut data) .expect("Could not read galaxy.txt to string"); let mut known_file = File::create(Path::new("known.txt")).expect("Could not open known.txt"); let mut unknown_file = File::create(Path::new("unknown.txt")).expect("Could not open unknown.txt"); let mut removed_file = File::create(Path::new("removed.txt")).expect("Could not open removed.txt"); let mut all_bindings = HashMap::new(); for line in data.lines() { let actions = Action::parse_reduced(line); let (ident, body) = parse_binding(&actions); all_bindings.insert(ident, body); } let mut removed: HashMap<&str, Action> = HashMap::new(); let mut something_changed = true; while something_changed { something_changed = false; let (new_all_bindings, substitutki) = replace_matching(all_bindings, is_constant); something_changed = something_changed || !substitutki.is_empty(); removed.extend(substitutki); all_bindings = new_all_bindings; let (new_all_bindings, substitutki) = replace_matching(all_bindings, contains_no_references); something_changed = something_changed || !substitutki.is_empty(); removed.extend(substitutki); all_bindings = new_all_bindings; let (new_all_bindings, substitutki) = replace_matching(all_bindings, is_synonim); something_changed = something_changed || !substitutki.is_empty(); removed.extend(substitutki); all_bindings = new_all_bindings; } write_to_file(&removed, &mut removed_file); let (known, unknown) = all_bindings .into_iter() .partition::<HashMap<_, _>, _>(|(_, body)| is_constant(body)); write_to_file(&known, &mut known_file); write_to_file(&unknown, &mut unknown_file); }
true
6ddc9d7686fc65421bc000d5a37277e5158cc14f
Rust
paholg/spin
/src/lib.rs
UTF-8
5,290
2.890625
3
[]
no_license
//! This is a module comment! #![feature(const_fn)] #![feature(question_mark)] // spin stuff: #![cfg_attr(feature = "spin", no_std)] #![cfg_attr(feature = "spin", feature(plugin))] #![cfg_attr(feature = "spin", plugin(macro_zinc))] // #![cfg_attr(feature = "spin", feature(core_float))] #[cfg(feature = "spin")] extern crate zinc; #[cfg(feature = "spin")] pub mod spin; // sim stuff: #[cfg(feature = "sim")] extern crate core; #[cfg(feature = "sim")] #[macro_use] extern crate glium; #[cfg(feature = "sim")] pub mod sim; #[cfg(feature = "sim")] pub use sim as spin; // general stuff: extern crate typenum; #[macro_use] pub extern crate generic_array; // pub extern crate dimensioned as dim; pub extern crate rand; pub use spin::{Spin, rng}; pub mod color; pub mod text; /// The number of LEDs. pub const NLEDS: usize = 16; /// The distance from the center to the first LED. pub const R0: f32 = 0.2; /// The diameter of an LED. pub const LED_SIZE: f32 = 2.8; /// The distance between LEDs. pub const LED_SPACE: f32 = 0.2; // TODO: Update Dimensioned, then work in all this shit // pub mod milli { // make_units_adv! { // Milli, Unitless, one, f32, 1.0; // base { // P1, Millimeter, mm, mm; // P1, Millisecond, ms, ms; // } // derived {} // } // } // pub use milli::{Millimeter, Millisecond, mm, ms}; // use dim::Dim; // const R0: Dim<Millimeter, f32> = Dim::new(0.2); // const LED_SIZE: Dim<Millimeter, f32> = Dim::new(2.8); // const LED_SPACE: Dim<Millimeter, f32> = Dim::new(0.2); use typenum::NonZero; use generic_array::ArrayLength; use color::Rgb; /// A convenience trait to make ArrayLength easier to use with the datastructures in this crate. pub trait Len: Clone + NonZero + ArrayLength<(f32, Rgb)> + ArrayLength<Rgb> + ArrayLength<(f32, [Rgb; NLEDS])> + ArrayLength<[Rgb; NLEDS]> {} impl<T> Len for T where T: Clone + NonZero + ArrayLength<(f32, Rgb)> + ArrayLength<Rgb> + ArrayLength<(f32, [Rgb; NLEDS])> + ArrayLength<[Rgb; NLEDS]> {} use generic_array::GenericArray; pub struct LedMatrix<N: Len> { data: GenericArray<(f32, [Rgb; NLEDS]), N>, } use core::f32::consts::PI; impl<N: Len> LedMatrix<N> { pub fn new(led_strips: GenericArray<[Rgb; NLEDS], N>) -> LedMatrix<N> { let mut points = led_strips.map(|&l| (0.0, l)); let step = 2.0 * PI / points.len() as f32; for (i, point) in points.iter_mut().enumerate() { point.0 = i as f32 * step; } LedMatrix { data: points } } pub fn with_angles(led_strips: GenericArray<(f32, [Rgb; NLEDS]), N>) -> LedMatrix<N> { // fixme: ensure led_strips is sorted, and that angles are in [0, 2*PI) LedMatrix { data: led_strips } } } pub struct LedMatrixSlice { data: [(f32, [Rgb; NLEDS])], } impl LedMatrixSlice { pub fn with_angles(led_strips: &[(f32, [Rgb; NLEDS])]) -> &LedMatrixSlice { // fixme: ensure led_strips is sorted, and that angles are in [0, 2*PI) unsafe { core::mem::transmute(led_strips) } } /// Get an LED strip from the matrix. `i` must be in [0.0, 2.0*PI). pub fn get(&self, i: f32) -> [Rgb; NLEDS] { assert!(i >= 0.0 && i < 2.0 * PI); let mut min_index = 0; let (mut min, ref min_strip) = self.data[min_index]; let mut min_strip = min_strip; if i <= min { return min_strip.clone(); } let mut max_index = self.data.len() - 1; let (mut max, ref max_strip) = self.data[max_index]; let mut max_strip = max_strip; if i >= max { return max_strip.clone(); } while min_index < max_index - 1 { let index = min_index + (max_index - min_index) / 2; let (p, ref strip) = self.data[index]; if i <= p { max = p; max_strip = strip; max_index = index; } else { min = p; min_strip = strip; min_index = index; } } let factor = (i - min) / (max - min); // fixme: switch to zip once GenericArray has it unsafe { let mut res: [Rgb; NLEDS] = ::core::mem::uninitialized(); let colors = min_strip.iter() .zip(max_strip.iter()) .map(|(min_color, max_color)| min_color.mix(max_color, factor)); for (r, color) in res.iter_mut().zip(colors) { ::core::ptr::write(r, color); } res } } } impl ::core::ops::Index<f32> for LedMatrixSlice { type Output = [Rgb; NLEDS]; /// If `phi` is not one of the angles that `Self` stores, will return the led strip /// corresponding to the next lower one fn index(&self, phi: f32) -> &Self::Output { assert!(phi >= 0.0 && phi < 2.0 * PI); let len = self.data.len(); for i in 0..len { if phi <= self.data[i].0 { return &self.data[i].1; } } &self.data[len-1].1 } } use core::ops::Deref; impl<N: Len> Deref for LedMatrix<N> { type Target = LedMatrixSlice; fn deref(&self) -> &Self::Target { unsafe { ::core::mem::transmute(&*self.data) } } }
true
d10c0351e945cf22e19c4fe7c9342a52381a7339
Rust
RCasatta/rusty-paper-wallet
/src/html.rs
UTF-8
4,288
3.078125
3
[ "MIT" ]
permissive
use crate::Result; use maud::{html, PreEscaped}; use qr_code::QrCode; use std::io::Cursor; const CSS: &str = include_str!("html.css"); #[derive(Debug, Clone)] pub struct WalletData { /// Alias name of the owner of the paper wallet, shown in public part pub alias: String, /// Address of the paper wallet pub address: String, /// Address of the paper wallet, uppercase if bech32 to improve QR code pub address_qr: String, /// Descriptor containing aliases pub descriptor_alias: String, /// Legend containing Alias -> Key correspondence pub legend_rows: Vec<String>, /// Descriptor containing keys pub descriptor_qr: String, } /// Converts `input` in base64 and returns a data url pub fn to_data_url<T: AsRef<[u8]>>(input: T, content_type: &str) -> String { let base64 = base64::encode(input.as_ref()); format!("data:{};base64,{}", content_type, base64) } /// Creates QR containing `message` and encode it in data url fn create_bmp_base64_qr(message: &str) -> Result<String> { let qr = QrCode::new(message.as_bytes())?; // The `.mul(3)` with pixelated rescale shouldn't be needed, however, some printers doesn't // recognize it resulting in a blurry image, starting with a bigger image mostly prevents the // issue at the cost of a bigger image size. let bmp = qr.to_bmp().mul(3)?; let mut cursor = Cursor::new(vec![]); bmp.write(&mut cursor).unwrap(); Ok(to_data_url(cursor.into_inner(), "image/bmp")) } /// Creates the inner html of a single paper wallet fn inner(data: &WalletData) -> Result<PreEscaped<String>> { let public_qr = create_bmp_base64_qr(&data.address_qr)?; let private_qr = create_bmp_base64_qr(&data.descriptor_qr)?; let single = html! { div class="single" { div { div class="break-word" { span class="bold" { (&data.alias) } br; (&data.address) } div class="center" { img class="qr" src=(public_qr) { } } } div class="black" {} div { div class="break-word" { div class="pad" { (&data.descriptor_alias) } @for row in &data.legend_rows { div class="pad" { (*row) } } } div class="center" { img class="qr" src=(private_qr) { } } } } }; Ok(single) } /// Returns the html page containing the given `paper_wallets` pub fn paper_wallets(paper_wallets: &[WalletData]) -> Result<String> { let mut paper_wallets_html = vec![]; for paper_wallet in paper_wallets { paper_wallets_html.push(inner(paper_wallet).unwrap()); } let css = CSS.replace('\n', "").replace(" ", " ").replace(" ", " "); let html = html! { (maud::DOCTYPE) html { head { meta charset="UTF-8" {} title { "Bitcoin Paper Wallet" } style { (css) } } body { @for paper_wallet in &paper_wallets_html { (*paper_wallet) } } } }; Ok(html.into_string()) } #[cfg(test)] mod test { use crate::html::{inner, paper_wallets, to_data_url, WalletData}; #[test] fn test_html() { let data = WalletData { alias: "Riccardo".to_string(), address: "bc1qthxwqly0f3uyllhxezmyukrjwkxer6ezdlekhu".to_string(), address_qr: "BC1QTHXWQLY0F3UYLLHXEZMYUKRJWKXER6EZDLEKHU".to_string(), descriptor_alias: "wpkh(Riccardo)".to_string(), legend_rows: vec![ "Riccardo: L2a7AaJEv2ef5UE25keeHNhfN45jMepMLS9dar2ChL68fJ4L8NfL".to_string(), ], descriptor_qr: "L2a7AaJEv2ef5UE25keeHNhfN45jMepMLS9dar2ChL68fJ4L8NfL".to_string(), }; let inner_html = inner(&data).unwrap(); assert!(inner_html.into_string().contains(&data.address)); let paper_wallets_data = vec![data.clone(), data.clone()]; let html = paper_wallets(&paper_wallets_data).unwrap(); println!("{}", to_data_url(&html, "text/html")); } }
true
b8e2064747141d2d7c1f5144c98bbbdc0b3e6ad6
Rust
jnpn/rdupes
/src/mt.rs
UTF-8
708
2.546875
3
[]
no_license
use std::thread; use walkdir::WalkDir; use std::channels; mod mt { /* * * scan-thread -> <scan-queue> -> hash-thread -> <hash-q> -> map-thread -> <map-q> -> screen-thread * * - scan-p: (fn, ctime) * - hash-p: (fn, ctime, hash) * - map-p : (hash, [(fn, ctime)]), hash-count * * - screen-s: { scanned-count hash-count start-time delta-time } * */ fn twalk(dir, tx, f) { thread::spawn(||{ for fn in walkdir(dir) { tx.send(f(fn)) } }) } fn thash(rx, tx) {} fn tmap(rx, tx) {} fn tshow(rx) { let s = Screen { scanned: 0, hashed: 0, start: 0, delta: 0 } for m in rx { // update s } } }
true
57ca2013802501cbb73b21e0e37a10f25e6afdb9
Rust
run-mojo/listpack
/src/old.rs
UTF-8
69,880
2.78125
3
[]
no_license
#![allow(dead_code)] extern crate libc; mod zigzag; pub mod raw; use std::mem; use std::mem::size_of; use zigzag::ZigZag; pub const HDR_SIZE: i32 = 6; pub const MIN_SIZE: i32 = 7; // HDR + TERMINATOR pub const EMPTY: &'static [u8] = &[]; const INTBUF_SIZE: usize = 21; /// Used for determining how to treat the "at" element pointer during insertion. pub enum Placement { /// Insert the element immediately before the specified element pointer. Before = 0, /// Insert the element immediately before the specified element pointer. After = 1, /// Replace the value at element with the specified value. Replace = 2, } /// A listpack is encoded into a single linear chunk of memory. It has a fixed /// length header of six bytes (instead of ten bytes of ziplist, since we no /// longer need a pointer to the start of the last element). The header is /// followed by the listpack elements. In theory the data structure does not need /// any terminator, however for certain concerns, a special entry marking the /// end of the listpack is provided, in the form of a single byte with value /// FF (255). The main advantages of the terminator are the ability to scan the /// listpack without holding (and comparing at each iteration) the address of /// the end of the listpack, and to recognize easily if a listpack is well /// formed or truncated. These advantages are, in the idea of the writer, worth /// the additional byte needed in the representation. /// /// <tot-bytes> <num-elements> <element-1> ... <element-N> <listpack-end-byte> /// /// The six byte header, composed of the tot-bytes and num-elements fields is /// encoded in the following way: /// /// * `tot-bytes`: 32 bit unsigned integer holding the total amount of bytes /// representing the listpack. Including the header itself and the terminator. /// This basically is the total size of the allocation needed to hold the listpack /// and allows to jump at the end in order to scan the listpack in reverse order, /// from the last to the first element, when needed. /// * `num-elements`: 16 bit unsigned integer holding the total number of elements /// the listpack holds. However if this field is set to 65535, which is the greatest /// unsigned integer representable in 16 bit, it means that the number of listpack /// elements is not known, so a LIST-LENGTH operation will require to fully scan /// the listpack. This happens when, at some point, the listpack has a number of /// elements equal or greater than 65535. The num-elements field will be set again /// to a lower number the first time a LIST-LENGTH operation detects the elements /// count returned in the representable range. /// /// All integers in the listpack are stored in little endian format, if not /// otherwise specified (certain special encodings are in big endian because /// it is more natural to represent them in this way for the way the specification /// maps to C code). pub struct Listpack { lp: *mut listpack } /// Pointer to an element within the listpack. pub type Element = *mut u8; /// Listpacks are composed of elements that are either an derivative of a /// 64bit integer or a string blob. pub enum Value { Int(i64), String(*const u8, usize), } #[repr(packed)] #[derive(Copy, Clone)] pub struct StrValue(*const u8, u32); #[repr(packed)] pub union Val { pub int: i64, pub string: StrValue, } /// Return the existing Rax allocator. pub unsafe fn allocator() -> ( extern "C" fn(size: libc::size_t) -> *mut u8, extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8, extern "C" fn(ptr: *mut libc::c_void)) { (lp_malloc, lp_realloc, lp_free) } /// Listpack internally makes calls to "malloc", "realloc" and "free" for all of it's /// heap memory needs. These calls can be patched with the supplied hooks. /// Do not call this method after Listpack has been used at all. This must /// be called before using or calling any Listpack API function. pub unsafe fn set_allocator( malloc: extern "C" fn(size: libc::size_t) -> *mut u8, realloc: extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8, free: extern "C" fn(ptr: *mut libc::c_void)) { lp_malloc = malloc; lp_realloc = realloc; lp_free = free; } impl Into<Val> for u8 { #[inline] fn into(self) -> Val { Val { int: self as i64 } } } /// impl Into<Value> for u8 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for u8 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { if len == 0 || ptr.is_null() { u8::default() } else { *ptr } } } } } impl Into<Value> for i8 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for i8 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { if len == 0 { i8::default() } else { *ptr as Self } } } } } impl Into<Value> for u16 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for u16 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as Self, 2 => u16::from_le(*(ptr as *mut [u8; size_of::<u16>()] as *mut u16)) as Self, _ => Self::default() } } } } } impl Into<Value> for i16 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for i16 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as i8 as Self, 2 => i16::from_le(*(ptr as *mut [u8; size_of::<Self>()] as *mut Self)) as Self, _ => Self::default() } } } } } impl Into<Value> for u32 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for u32 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as Self, 2 => u16::from_le(*(ptr as *mut [u8; size_of::<u16>()] as *mut u16)) as Self, 4 => u32::from_le(*(ptr as *mut [u8; size_of::<u32>()] as *mut u32)) as Self, _ => Self::default() } } } } } impl Into<Value> for i32 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for i32 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as Self, 2 => i16::from_le(*(ptr as *mut [u8; size_of::<i16>()] as *mut i16)) as Self, 4 => i32::from_le(*(ptr as *mut [u8; size_of::<i32>()] as *mut i32)) as Self, _ => Self::default() } } } } } impl Into<Value> for u64 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for u64 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as Self, 2 => u16::from_le(*(ptr as *mut [u8; size_of::<u16>()] as *mut u16)) as Self, 4 => u32::from_le(*(ptr as *mut [u8; size_of::<u32>()] as *mut u32)) as Self, 8 => u64::from_le(*(ptr as *mut [u8; size_of::<u64>()] as *mut u64)) as Self, _ => Self::default() } } } } } impl Into<Value> for i64 { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for i64 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as i8 as Self, 2 => i16::from_le(*(ptr as *mut [u8; size_of::<i16>()] as *mut i16)) as Self, 4 => i32::from_le(*(ptr as *mut [u8; size_of::<i32>()] as *mut i32)) as Self, 8 => i64::from_le(*(ptr as *mut [u8; size_of::<i64>()] as *mut i64)) as Self, _ => Self::default() } } } } } impl Into<Value> for isize { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for isize { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as i8 as Self, 2 => i16::from_le(*(ptr as *mut [u8; size_of::<i16>()] as *mut i16)) as Self, 4 => i32::from_le(*(ptr as *mut [u8; size_of::<i32>()] as *mut i32)) as Self, 8 => i64::from_le(*(ptr as *mut [u8; size_of::<i64>()] as *mut i64)) as Self, _ => Self::default() } } } } } impl Into<Value> for usize { #[inline] fn into(self) -> Value { Value::Int(self as i64) } } impl From<Value> for usize { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as Self, 2 => u16::from_le(*(ptr as *mut [u8; size_of::<u16>()] as *mut u16)) as Self, 4 => u32::from_le(*(ptr as *mut [u8; size_of::<u32>()] as *mut u32)) as Self, 8 => u64::from_le(*(ptr as *mut [u8; size_of::<u64>()] as *mut u64)) as Self, _ => Self::default() } } } } } impl Into<Value> for f32 { #[inline] fn into(self) -> Value { Value::Int(self.to_bits() as i64) } } impl From<Value> for f32 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => Self::from_bits(i as u32), &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as Self, 2 => f32::from_bits( u16::from_le( *(ptr as *mut [u8; size_of::<u16>()] as *mut u16) ) as u32 ), 4 => f32::from_bits( u32::from_le( *(ptr as *mut [u8; size_of::<Self>()] as *mut u32) ) ), 8 => f64::from_bits( u64::from_le( *(ptr as *mut [u8; size_of::<Self>()] as *mut u64) ) ) as f32, _ => Self::default() } } } } } impl Into<Value> for f64 { #[inline] fn into(self) -> Value { Value::Int(self.to_bits() as i64) } } impl From<Value> for f64 { #[inline] fn from(v: Value) -> Self { match &v { &Value::Int(i) => Self::from_bits(i as u64), &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as Self, 2 => f64::from_bits( u16::from_le( *(ptr as *mut [u8; size_of::<u16>()] as *mut u16) ) as u64 ), 4 => f32::from_bits( u32::from_le( *(ptr as *mut [u8; size_of::<Self>()] as *mut u32) ) ) as f64, 8 => f64::from_bits( u64::from_le( *(ptr as *mut [u8; size_of::<Self>()] as *mut u64) ) ), _ => Self::default() } } } } } impl Into<Value> for u128 { #[inline] fn into(self) -> Value { Value::String( &self as *const _ as *const u8, size_of::<u128>(), ) } } impl From<Value> for u128 { fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as u8 as u128, 2 => u16::from_le(*(ptr as *mut [u8; size_of::<u16>()] as *mut u16)) as Self, 4 => u32::from_le(*(ptr as *mut [u8; size_of::<u32>()] as *mut u32)) as Self, 8 => u64::from_le(*(ptr as *mut [u8; size_of::<u64>()] as *mut u64)) as Self, 16 => Self::from_le(*(ptr as *mut [u8; size_of::<Self>()] as *mut Self)), _ => Self::default() } } } } } impl Into<Value> for i128 { #[inline] fn into(self) -> Value { Value::String( &self as *const _ as *const u8, std::mem::size_of::<i128>(), ) } } impl From<Value> for i128 { fn from(v: Value) -> Self { match &v { &Value::Int(i) => i as Self, &Value::String(ptr, len) => unsafe { match len { 1 => *ptr as i8 as i128, 2 => i16::from_le(*(ptr as *mut [u8; size_of::<i16>()] as *mut i16)) as i128, 4 => i32::from_le(*(ptr as *mut [u8; size_of::<i32>()] as *mut i32)) as i128, 8 => i64::from_le(*(ptr as *mut [u8; size_of::<i64>()] as *mut i64)) as i128, 16 => Self::from_le(*(ptr as *mut [u8; size_of::<Self>()] as *mut Self)), _ => Self::default() } } } } } impl<'a> Into<Value> for &'a str { #[inline] fn into(self) -> Value { Value::String(self.as_ptr(), self.len()) } } impl<'a> Into<Value> for &'a [u8] { #[inline] fn into(self) -> Value { Value::String(self.as_ptr(), self.len()) } } impl<'a> Into<Value> for &'a String { #[inline] fn into(self) -> Value { Value::String(self.as_ptr(), self.len()) } } impl Into<Value> for String { #[inline] fn into(self) -> Value { Value::String(self.as_ptr(), self.len()) } } impl<'a> Into<Value> for &'a Vec<u8> { #[inline] fn into(self) -> Value { Value::String(self.as_ptr(), self.len()) } } impl Into<Value> for Vec<u8> { #[inline] fn into(self) -> Value { Value::String(self.as_ptr(), self.len()) } } impl Value { #[inline] pub fn as_bytes<'a>(&self) -> &'a [u8] { match *self { Value::Int(v) => { unsafe { std::slice::from_raw_parts( &v as *const _ as *const u8, std::mem::size_of::<i64>(), ) } } Value::String(ptr, len) => { if ptr.is_null() || len == 0 { EMPTY } else { unsafe { std::slice::from_raw_parts(ptr, len as usize) } } } } } #[inline] pub fn as_str<'a>(&self) -> &'a str { match *self { Value::Int(v) => { unsafe { std::str::from_utf8_unchecked( std::slice::from_raw_parts( &v as *const _ as *const u8, std::mem::size_of::<i64>(), ) ) } } Value::String(ptr, len) => { unsafe { std::str::from_utf8_unchecked( std::slice::from_raw_parts(ptr, len as usize) ) } } } } } impl PartialEq for Value { fn eq(&self, other: &Value) -> bool { match self { &Value::Int(v) => { match other { &Value::Int(v2) => v == v2, &Value::String(_, _) => false } } &Value::String(ptr, len) => { match other { &Value::Int(_) => false, &Value::String(ptr2, len2) => unsafe { if len != len2 { false } else if ptr == ptr2 { true } else if ptr.is_null() || ptr2.is_null() { false } else { libc::memcmp( ptr as *mut libc::c_void, ptr2 as *mut libc::c_void, len as usize, ) == 0 } } } } } } } impl PartialOrd for Value { fn partial_cmp(&self, other: &Value) -> Option<std::cmp::Ordering> { Some(match self { &Value::Int(v) => { match other { &Value::Int(v2) => { v.cmp(&v2) } &Value::String(_, _) => std::cmp::Ordering::Less } } &Value::String(ptr, len) => { match other { &Value::Int(_) => std::cmp::Ordering::Greater, &Value::String(ptr2, len2) => unsafe { match len.cmp(&len2) { std::cmp::Ordering::Less => { if len == 0 { std::cmp::Ordering::Less } else { let r = libc::memcmp( ptr as *mut libc::c_void, ptr2 as *mut libc::c_void, len as usize, ); if r <= 0 { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } } } std::cmp::Ordering::Equal => { if len <= 0 { std::cmp::Ordering::Equal } else { let r = libc::memcmp( ptr as *mut libc::c_void, ptr2 as *mut libc::c_void, len as usize, ); if r == 0 { std::cmp::Ordering::Equal } else if r < 0 { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } } } std::cmp::Ordering::Greater => { if len2 == 0 { std::cmp::Ordering::Greater } else { let r = libc::memcmp( ptr as *mut libc::c_void, ptr2 as *mut libc::c_void, len as usize, ); if r >= 0 { std::cmp::Ordering::Greater } else { std::cmp::Ordering::Less } } } } } } } }) } } pub trait Int: Clone + Default + std::fmt::Debug { fn to_int64(self) -> i64; } impl Int for isize { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for usize { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for f32 { #[inline] fn to_int64(self) -> i64 { self.to_bits() as i64 } } impl Int for f64 { #[inline] fn to_int64(self) -> i64 { self.to_bits() as i64 } } impl Int for i8 { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for u8 { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for i16 { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for u16 { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for i32 { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for u32 { #[inline] fn to_int64(self) -> i64 { self as i64 } } impl Int for i64 { #[inline] fn to_int64(self) -> i64 { self } } impl Int for u64 { #[inline] fn to_int64(self) -> i64 { self as i64 } } pub trait Str<RHS = Self>: Clone + Default + std::fmt::Debug { type Output: Str; fn encode(self) -> Self::Output; fn to_buf(&self) -> (*const u8, usize); fn from_buf(ptr: *const u8, len: usize) -> RHS; } impl Str for f32 { type Output = u32; #[inline] fn encode(self) -> Self::Output { // Encode as u32 Little Endian // self.to_bits().to_le() unsafe { mem::transmute(mem::transmute::<f32, u32>(self).to_le()) } } #[inline] fn to_buf(&self) -> (*const u8, usize) { // This should never get called since we represent as a u32 (self as *const _ as *const u8, std::mem::size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> f32 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { // We used a Little u32 to encode so let's reverse it f32::from_bits( u32::from_le( *(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut u32) ) ) } } } impl Str for f64 { type Output = u64; #[inline] fn encode(self) -> Self::Output { // Encode as u64 Little Endian unsafe { std::mem::transmute(std::mem::transmute::<f64, u64>(self).to_le()) } } #[inline] fn to_buf(&self) -> (*const u8, usize) { // This should never get called since we represent as a u64 (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> f64 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { // We used a Little Endian u64 to encode so let's reverse it f64::from_bits( u64::from_le( *(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64) ) ) } } } impl Str for isize { type Output = isize; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> isize { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { isize::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut isize)) } } } impl Str for usize { type Output = usize; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, std::mem::size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> usize { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { usize::from_le(*(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut usize)) } } } impl Str for i8 { type Output = i8; #[inline] fn encode(self) -> Self::Output { self } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> Self { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { *ptr as Self::Output } } } impl Str for u8 { type Output = u8; #[inline] fn encode(self) -> Self::Output { self } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> Self { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { *ptr as Self::Output } } } impl Str for i16 { type Output = i16; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> Self { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { i16::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i16)) } } } impl Str for u16 { type Output = u16; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> u16 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { u16::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u16)) } } } impl Str for i32 { type Output = i32; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> i32 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { i32::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i32)) } } } impl Str for u32 { type Output = u32; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, std::mem::size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> u32 { if len != std::mem::size_of::<Self::Output>() { return Self::default(); } unsafe { u32::from_le(*(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut u32)) } } } impl Str for i64 { type Output = i64; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> i64 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { i64::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i64)) } } } impl Str for u64 { type Output = u64; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> u64 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { u64::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64)) } } } impl Str for i128 { type Output = i128; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> i128 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { i128::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i128)) } } } impl Str for u128 { type Output = u128; #[inline] fn encode(self) -> Self::Output { self.to_le() } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self as *const _ as *const u8, size_of::<Self::Output>()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> u128 { if len != size_of::<Self::Output>() { return Self::default(); } unsafe { u128::from_le(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u128)) } } } impl Str for Vec<u8> { type Output = Vec<u8>; #[inline] fn encode(self) -> Vec<u8> { self } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self.as_ptr(), self.len()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> Vec<u8> { unsafe { Vec::from_raw_parts(ptr as *mut u8, len, len) } } } impl<'a> Str for &'a [u8] { type Output = &'a [u8]; #[inline] fn encode(self) -> &'a [u8] { self } #[inline] fn to_buf(&self) -> (*const u8, usize) { (self.as_ptr(), self.len()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> &'a [u8] { unsafe { std::slice::from_raw_parts(ptr, len) } } } impl<'a> Str for &'a str { type Output = &'a str; #[inline] fn encode(self) -> Self::Output { self } #[inline] fn to_buf(&self) -> (*const u8, usize) { ((*self).as_ptr(), self.len()) } #[inline] fn from_buf(ptr: *const u8, len: usize) -> &'a str { unsafe { std::str::from_utf8( std::slice::from_raw_parts(ptr, len) ).unwrap_or_default() } } } pub struct ListpackWriter { lp: Listpack, // writer: std::io::BufWriter, } impl Listpack { /// Constructs a new empty listpack. pub fn new() -> Listpack { return Listpack { lp: unsafe { lpNew() } }; } /// Return the number of elements inside the listpack. This function attempts /// to use the cached value when within range, otherwise a full scan is /// needed. As a side effect of calling this function, the listpack header /// could be modified, because if the count is found to be already within /// the 'numele' header field range, the new value is set. #[inline] pub fn len(&self) -> u32 { unsafe { u32::from_le(lpLength(self.lp) as u32) } } /// Return the total number of bytes the listpack is composed of. #[inline] pub fn size(&self) -> u32 { unsafe { u32::from_le(lpBytes(self.lp)) } } /// Decodes and returns the entry value of the element. /// /// If the function is called against a badly encoded listpack, so that there /// is no valid way to parse it, the function returns like if there was an /// integer encoded with value 12345678900000000 + <unrecognized byte>, this may /// be an hint to understand that something is wrong. To crash in this case is /// not sensible because of the different requirements of the application using /// this lib. /// /// Similarly, there is no error returned since the listpack normally can be /// assumed to be valid, so that would be a very high API cost. However a function /// in order to check the integrity of the listpack at load time is provided, /// check is_valid(). #[inline] pub fn get(&self, ele: Element) -> Value { unsafe { let mut val_or_len: libc::int64_t = 0; let val = lpGet(ele, &mut val_or_len, std::ptr::null_mut()); if val.is_null() { // Little Endian Value::Int(i64::from_le(val_or_len)) } else { Value::String(val, val_or_len as usize) } } } /// #[inline] pub fn get_int(&self, ele: Element) -> i64 { self.get_int_or(ele, 0) } /// #[inline] pub fn get_int_or(&self, ele: Element, default: i64) -> i64 { match self.get(ele) { Value::Int(v) => v, _ => default } } #[inline] pub fn get_i8(&self, ele: Element) -> i8 { i8::from(self.get(ele)) } #[inline] pub fn append_i8(&mut self, v: i8) -> bool { self.append_int(v as i64) } #[inline] pub fn replace_i8(&mut self, ele: Element, v: i8) -> Option<Element> { self.replace_int(ele, v as i64) } #[inline] pub fn insert_i8(&mut self, v: i8, place: Placement, at: Element) -> Option<Element> { self.insert_int(v, place, at) } #[inline] pub fn append_i8_fixed(&mut self, v: i8) -> bool { self.append_str(v) } #[inline] pub fn get_u8(&self, ele: Element) -> u8 { u8::from(self.get(ele)) } #[inline] pub fn append_u8(&mut self, v: u8) -> bool { self.append_int(v as i64) } #[inline] pub fn append_u8_fixed(&mut self, v: u8) -> bool { self.append_str(v) } #[inline] pub fn get_i16(&self, ele: Element) -> i16 { i16::from(self.get(ele)) } #[inline] pub fn append_i16(&mut self, v: i16) -> bool { self.append_int(v as i64) } #[inline] pub fn append_i16_fixed(&mut self, v: i16) -> bool { self.append_str(v) } #[inline] pub fn get_u16(&self, ele: Element) -> u16 { u16::from(self.get(ele)) } #[inline] pub fn append_u16(&mut self, v: u16) -> bool { self.append_int(v as i64) } #[inline] pub fn append_u16_fixed(&mut self, v: u16) -> bool { self.append_str(v) } #[inline] pub fn get_i32(&self, ele: Element) -> i32 { i32::from(self.get(ele)) } #[inline] pub fn append_i32(&mut self, v: i32) -> bool { self.append_int(v as i64) } #[inline] pub fn append_i32_fixed(&mut self, v: i32) -> bool { self.append_str(v) } #[inline] pub fn get_u32(&self, ele: Element) -> u32 { u32::from(self.get(ele)) } #[inline] pub fn append_u32(&mut self, v: u32) -> bool { self.append_int(v as i64) } #[inline] pub fn append_u32_fixed(&mut self, v: u32) -> bool { self.append_str(v) } #[inline] pub fn get_i64(&self, ele: Element) -> i64 { i64::from(self.get(ele)) } #[inline] pub fn append_i64(&mut self, v: i64) -> bool { self.append_int(v) } #[inline] pub fn append_i64_fixed(&mut self, v: i64) -> bool { self.append_str(v) } #[inline] pub fn get_u64(&self, ele: Element) -> u64 { u64::from(self.get(ele)) } #[inline] pub fn append_u64(&mut self, v: u64) -> bool { self.append_int(v as i64) } #[inline] pub fn append_u64_fixed(&mut self, v: u64) -> bool { self.append_str(v) } /// Get a zigzag encoded byte. #[inline] pub fn get_negative_8(&self, ele: Element) -> i8 { u8::from(self.get(ele)).zigzag() as i8 } #[inline] pub fn append_negative_8(&mut self, v: i8) -> bool { self.append_int(v.zigzag()) } #[inline] pub fn insert_negative_8(&mut self, v: i8, place: Placement, at: Element) -> Option<Element> { self.insert_int(v.zigzag(), place, at) } #[inline] pub fn replace_negative_8(&mut self, ele: Element, with: i8) -> Option<Element> { self.replace_int(ele, with.zigzag()) } #[inline] pub fn get_negative_16(&self, ele: Element) -> i16 { u16::from(self.get(ele)).zigzag() as i16 } #[inline] pub fn append_negative_16(&mut self, v: i16) -> bool { self.append_int(v.zigzag()) } #[inline] pub fn insert_negative_16(&mut self, v: i16, place: Placement, at: Element) -> Option<Element> { self.insert_int(v.zigzag(), place, at) } #[inline] pub fn replace_negative_16(&mut self, ele: Element, v: i16) -> Option<Element> { self.replace_int(ele, v.zigzag()) } #[inline] pub fn get_negative_32(&self, ele: Element) -> i32 { u32::from(self.get(ele)).zigzag() as i32 } #[inline] pub fn append_negative_32(&mut self, v: i32) -> bool { self.append_int(v.zigzag()) } #[inline] pub fn insert_negative_32(&mut self, v: i32, place: Placement, at: Element) -> Option<Element> { self.insert_int(v.zigzag(), place, at) } #[inline] pub fn replace_negative_32(&mut self, ele: Element, v: i32) -> Option<Element> { self.replace_int(ele, v.zigzag()) } #[inline] pub fn get_negative_64(&self, ele: Element) -> i64 { u64::from(self.get(ele)).zigzag() as i64 } #[inline] pub fn append_negative_64(&mut self, v: i64) -> bool { self.append_int(v.zigzag()) } #[inline] pub fn insert_negative_64(&mut self, v: i64, place: Placement, at: Element) -> Option<Element> { self.insert_int(v.zigzag(), place, at) } #[inline] pub fn replace_negative_64(&mut self, ele: Element, v: i64) -> Option<Element> { self.replace_int(ele, v.zigzag()) } #[inline] pub fn get_isize(&self, ele: Element) -> isize { isize::from(self.get(ele)) } #[inline] pub fn append_isize(&mut self, v: isize) -> bool { self.append_int(v as i64) } #[inline] pub fn append_isize_fixed(&mut self, v: isize) -> bool { self.append_str(v) } #[inline] pub fn get_usize(&self, ele: Element) -> usize { usize::from(self.get(ele)) } #[inline] pub fn append_usize(&mut self, v: usize) -> bool { self.append_int(v as i64) } #[inline] pub fn append_usize_fixed(&mut self, v: usize) -> bool { self.append_str(v) } #[inline] pub fn get_f32(&self, ele: Element) -> f32 { f32::from(self.get(ele)) } #[inline] pub fn append_f32(&mut self, v: f32) -> bool { self.append_int(v.to_bits() as i64) } #[inline] pub fn append_f32_fixed(&mut self, v: f32) -> bool { self.append_str(v) } #[inline] pub fn get_f64(&self, ele: Element) -> f64 { f64::from(self.get(ele)) } #[inline] pub fn append_f64(&mut self, v: f64) -> bool { self.append_int(v.to_bits() as i64) } #[inline] pub fn append_f64_fixed(&mut self, v: f64) -> bool { self.append_str(v) } #[inline] pub fn get_i128(&self, ele: Element) -> i128 { i128::from(self.get(ele)) } #[inline] pub fn append_i128(&mut self, v: i128) -> bool { // Is it within 64bit boundaries? if v < i64::max_value() as i128 && v > i64::min_value() as i128 { self.append_int(v as i64) } else { self.append_str(v) } } #[inline] pub fn get_u128(&self, ele: Element) -> u128 { u128::from(self.get(ele)) } #[inline] pub fn append_u128(&mut self, v: u128) -> bool { // Is it within 64bit boundaries? if v < i64::max_value() as u128 { self.append_int(v as i64) } else { self.append_str(v) } } /// #[inline] pub fn get_str(&self, ele: Element) -> &str { self.get_str_or(ele, "") } /// #[inline] pub fn get_str_or<'a>(&self, ele: Element, default: &'a str) -> &'a str { match self.get(ele) { Value::String(ptr, len) => { unsafe { std::str::from_utf8_unchecked( std::slice::from_raw_parts(ptr, len as usize) ) } } Value::Int(_) => { // let s: &'a mut String = Box::leak(Box::new(format!("{}", v))); // s.as_str() default } } } /// Insert, delete or replace the specified element 'ele' of length 'len' at /// the specified position 'p', with 'p' being a listpack element pointer /// obtained with first(), last(), index(), next(), prev() or /// seek(). /// /// The element is inserted before, after, or replaces the element pointed /// by 'p' depending on the 'where' argument, that can be BEFORE, AFTER /// or REPLACE. /// /// If 'ele' is set to NULL, the function removes the element pointed by 'p' /// instead of inserting one. /// /// Returns None on out of memory or when the listpack total length would exceed /// the max allowed size of 2^32-1, otherwise the new pointer to the listpack /// holding the new element is returned (and the old pointer passed is no longer /// considered valid) /// /// If 'newp' is not NULL, at the end of a successful call '*newp' will be set /// to the address of the element just added, so that it will be possible to /// continue an iteration with next() and prev(). /// /// For deletion operations ('ele' set to None) 'newp' is set to the next /// element, on the right of the deleted one, or to NULL if the deleted element /// was the last one. pub fn insert( &mut self, value: Value, place: Placement, at: Element, ) -> Option<Element> { match value { Value::Int(v) => self.insert_int(v, place, at), Value::String(ptr, len) => { let newp: &mut *mut u8 = &mut std::ptr::null_mut(); let new_lp = unsafe { lpInsert( self.lp, ptr, len as u32, at, place as libc::c_int, newp, ) }; if !new_lp.is_null() { self.lp = new_lp; if (*newp).is_null() { None } else { Some(*newp) } } else { None } } } } /// Append the specified element 'ele' of length 'len' at the end of the /// listpack. It is implemented in terms of insert(), so the return value is /// the same as insert(). pub fn append_ref(&mut self, value: &Value) -> bool { match value { &Value::Int(v) => self.append_int(v), &Value::String(ptr, len) => { let new_lp = unsafe { lpAppend( self.lp, ptr, len as u32, ) }; if !new_lp.is_null() { self.lp = new_lp; true } else { false } } } } /// Append the specified element 'ele' of length 'len' at the end of the /// listpack. It is implemented in terms of insert(), so the return value is /// the same as insert(). pub fn append(&mut self, value: Value) -> bool { match value { Value::Int(v) => self.append_int(v), Value::String(ptr, len) => { let new_lp = unsafe { lpAppend( self.lp, ptr, len as u32, ) }; if !new_lp.is_null() { self.lp = new_lp; true } else { false } } } } /// pub fn replace(&mut self, pos: Element, value: Value) -> Option<Element> { match value { Value::Int(v) => self.replace_int(pos, v), Value::String(ptr, len) => unsafe { let mut newp: &mut *mut u8 = &mut std::ptr::null_mut(); let new_lp = lpInsert( self.lp, ptr, len as u32, pos, Placement::Replace as libc::c_int, newp, ); if !new_lp.is_null() { self.lp = new_lp; if (*newp).is_null() { None } else { Some(*newp) } } else { None } } } } /// Insert, delete or replace the specified element 'ele' of length 'len' at /// the specified position 'p', with 'p' being a listpack element pointer /// obtained with first(), last(), index(), next(), prev() or seek(). /// /// The element is inserted before, after, or replaces the element pointed /// by 'p' depending on the 'where' argument, that can be BEFORE, AFTER /// or REPLACE. /// /// If 'ele' is set to NULL, the function removes the element pointed by 'p' /// instead of inserting one. /// /// Returns None on out of memory or when the listpack total length would exceed /// the max allowed size of 2^32-1, otherwise the new pointer to the listpack /// holding the new element is returned (and the old pointer passed is no longer /// considered valid) /// /// If 'newp' is not NULL, at the end of a successful call '*newp' will be set /// to the address of the element just added, so that it will be possible to /// continue an iteration with next() and prev(). pub fn insert_int<V>( &mut self, value: V, place: Placement, p: Element, ) -> Option<Element> where V: Int { unsafe { let i = value.to_int64().to_le(); let newp: &mut *mut u8 = &mut std::ptr::null_mut(); let new_lp = lpInsertInt64( self.lp, i, p, place as libc::c_int, newp, ); if !new_lp.is_null() { self.lp = new_lp; if (*newp).is_null() { None } else { Some(*newp) } } else { None } } } /// Append the specified element 'ele' of length 'len' at the end of the /// listpack. It is implemented in terms of insert(), so the return value is /// the same as insert(). /// /// Returns true if it succeeded or false when out-of-memory or when the /// listpack total length would exceed the max allowed size of 2^32-1 pub fn append_int<V>(&mut self, value: V) -> bool where V: Int { unsafe { let i = value.to_int64().to_le(); let result = lpAppendInt64(self.lp, i); if !result.is_null() { self.lp = result; true } else { false } } } pub fn replace_int<V>(&mut self, mut pos: Element, value: V) -> Option<Element> where V: Int { unsafe { let i = value.to_int64(); let newp: &mut *mut u8 = &mut pos; let new_lp = lpReplaceInt64(self.lp, newp, i); if !new_lp.is_null() { self.lp = new_lp; if (*newp).is_null() { None } else { Some(*newp) } } else { None } } } /// Insert, delete or replace the specified element 'ele' of length 'len' at /// the specified position 'p', with 'p' being a listpack element pointer /// obtained with first(), last(), index(), next(), prev() or /// seek(). /// /// The element is inserted before, after, or replaces the element pointed /// by 'p' depending on the 'where' argument, that can be BEFORE, AFTER /// or REPLACE. /// /// If 'ele' is set to NULL, the function removes the element pointed by 'p' /// instead of inserting one. /// /// Returns None on out of memory or when the listpack total length would exceed /// the max allowed size of 2^32-1, otherwise the new pointer to the listpack /// holding the new element is returned (and the old pointer passed is no longer /// considered valid) /// /// If 'newp' is not NULL, at the end of a successful call '*newp' will be set /// to the address of the element just added, so that it will be possible to /// continue an iteration with next() and prev(). /// /// For deletion operations ('ele' set to None) 'newp' is set to the next /// element, on the right of the deleted one, or to NULL if the deleted element /// was the last one. /// /// If None is returned then it failed because of out-of-memory or invalid /// element pointer. pub fn insert_str<V>( &mut self, value: V, place: Placement, at: Element, ) -> Option<Element> where V: Str { unsafe { let v = value.encode(); let (ele, size) = v.to_buf(); let newp: &mut *mut u8 = &mut std::ptr::null_mut(); let result = lpInsert( self.lp, ele, size as u32, at, place as libc::c_int, newp, ); if result.is_null() { None } else { self.lp = result; if newp.is_null() { None } else { Some(*newp as Element) } } } } /// Append the specified element 'ele' of length 'len' at the end of the /// listpack. It is implemented in terms of insert(), so the return value is /// the same as insert(). pub fn append_str<V>(&mut self, value: V) -> bool where V: Str { unsafe { let v = value.encode(); let (ele, size) = v.to_buf(); let result = lpAppend(self.lp, ele, size as u32); if !result.is_null() { self.lp = result; true } else { false } } } /// Replace the specified element with the specified value pub fn replace_str<V>(&mut self, value: V, at: Element) where V: Str { self.insert_str(value, Placement::Replace, at); } /// Remove the element pointed by 'p', and return the resulting listpack. /// If 'newp' is not NULL, the next element pointer (to the right of the /// deleted one) is returned by reference. If the deleted element was the /// last one, '*newp' is set to None. pub fn delete(&mut self, p: Element) -> Option<Element> { unsafe { let newp: &mut *mut u8 = &mut std::ptr::null_mut(); let result = lpDelete(self.lp, p, newp); if result.is_null() { if newp.is_null() { None } else { Some(*newp) } } else { self.lp = result; if newp.is_null() { None } else { Some(*newp) } } } } /// Return a pointer to the first element of the listpack, or None if the /// listpack has no elements. pub fn first(&self) -> Option<Element> { first(self.lp) } /// Return a pointer to the last element of the listpack, or None if the /// listpack has no elements. pub fn last(&self) -> Option<Element> { last(self.lp) } pub fn start(&self) -> Element { std::ptr::null_mut() } pub fn first_or_next(&self, after: Element) -> Option<Element> { first_or_next(self.lp, after) } /// /* If 'after' points to an element of the listpack, calling next() will return /// the pointer to the next element (the one on the right), or None if 'after' /// already pointed to the last element of the listpack. */ #[inline] pub fn next(&self, after: Element) -> Option<Element> { next(self.lp, after) } #[inline] pub fn last_or_prev(&self, after: Element) -> Option<Element> { last_or_prev(self.lp, after) } /// If 'p' points to an element of the listpack, calling prev() will return /// the pointer to the previous element (the one on the left), or None if 'before' /// already pointed to the first element of the listpack. #[inline] pub fn prev(&self, before: Element) -> Option<Element> { prev(self.lp, before) } /// Seek the specified element and returns the pointer to the seeked element. /// Positive indexes specify the zero-based element to seek from the head to /// the tail, negative indexes specify elements starting from the tail, where /// -1 means the last element, -2 the penultimate and so forth. If the index /// is out of range, NULL is returned. #[inline] pub fn seek(&self, index: i64) -> Option<Element> { seek(self.lp, index) } #[inline] pub fn iter(&self) -> ListpackIterator { ListpackIterator { lp: self.lp, ele: std::ptr::null_mut(), } } // pub unsafe fn unsafe_set_bytes(&mut self, len: u32) { // let p = self.lp as *mut u8; // *p.offset(1) = (len & 0xff) as u8; // *p.offset(2) = ((len >> 8) & 0xff) as u8; // *p.offset(3) = ((len >> 16) & 0xff) as u8; // *p.offset(4) = ((len >> 24) & 0xff) as u8; // } // // pub unsafe fn unsafe_set_len(&mut self, len: u16) { // let p = self.lp as *mut u8; // *p.offset(5) = (len & 0xff) as u8; // *p.offset(6) = ((len >> 8) & 0xff) as u8; // } } // Drop -> "lpFree" impl Drop for Listpack { fn drop(&mut self) { unsafe { lp_free(self.lp as *mut libc::c_void) } } } impl std::iter::IntoIterator for Listpack { type Item = Value; type IntoIter = ListpackIterator; fn into_iter(self) -> <Self as IntoIterator>::IntoIter { ListpackIterator { lp: (&self).lp, ele: std::ptr::null_mut(), } } } #[inline] pub fn seek(lp: *mut listpack, index: i64) -> Option<Element> { unsafe { let data = lpSeek(lp, index as libc::c_long); if data.is_null() { None } else { Some(data) } } } #[inline] fn get_val(ele: Element) -> Value { unsafe { let mut val_or_len: libc::int64_t = 0; let val = lpGet(ele, &mut val_or_len, std::ptr::null_mut()); if val.is_null() { // Little Endian Value::Int(i64::from_le(val_or_len)) } else { Value::String(val, val_or_len as usize) } } } /// Return a pointer to the first element of the listpack, or None if the /// listpack has no elements. #[inline] pub fn first(lp: *mut listpack) -> Option<Element> { unsafe { let ele = lpFirst(lp); if ele.is_null() { None } else { Some(ele) } } } /// Return a pointer to the last element of the listpack, or None if the /// listpack has no elements. #[inline] fn last(lp: *mut listpack) -> Option<Element> { unsafe { let ele = lpLast(lp); if ele.is_null() { None } else { Some(ele) } } } #[inline] pub fn first_or_next(lp: *mut listpack, after: Element) -> Option<Element> { if after.is_null() { first(lp) } else { next(lp, after) } } /// If 'after' points to an element of the listpack, calling next() will return /// the pointer to the next element (the one on the right), or None if 'after' /// already pointed to the last element of the listpack. #[inline] pub fn next(lp: *mut listpack, after: Element) -> Option<Element> { unsafe { let ele = lpNext(lp, after); if ele.is_null() { None } else { Some(ele) } } } /// #[inline] pub fn last_or_prev(lp: *mut listpack, after: Element) -> Option<Element> { if after.is_null() { last(lp) } else { prev(lp, after) } } /// If 'p' points to an element of the listpack, calling prev() will return /// the pointer to the previous element (the one on the left), or None if 'before' /// already pointed to the first element of the listpack. #[inline] pub fn prev(lp: *mut listpack, before: Element) -> Option<Element> { unsafe { let ele = lpPrev(lp, before); if ele.is_null() { None } else { Some(ele) } } } pub struct ListpackIterator { pub lp: *mut listpack, pub ele: Element, } impl ListpackIterator { #[inline] pub fn seek(&mut self, index: i64) -> Option<Value> { match seek(self.lp, index as libc::c_long) { Some(ele) => { self.ele = ele; Some(get_val(ele)) } None => None } } #[inline] pub fn first(&mut self) -> Option<Value> { match first(self.lp) { Some(ele) => { self.ele = ele; Some(get_val(ele)) } None => None } } #[inline] pub fn last(&mut self) -> Option<Value> { match last(self.lp) { Some(ele) => { self.ele = ele; Some(get_val(ele)) } None => None } } } impl std::iter::Iterator for ListpackIterator { type Item = Value; fn next(&mut self) -> Option<<Self as Iterator>::Item> { match first_or_next(self.lp, self.ele) { Some(e) => { self.ele = e; Some(get_val(e)) } None => None } } } impl std::iter::DoubleEndedIterator for ListpackIterator { fn next_back(&mut self) -> Option<<Self as Iterator>::Item> { match last_or_prev(self.lp, self.ele) { Some(e) => { self.ele = e; Some(get_val(e)) } None => None } } } /// Opaque C type from listpack.c #[allow(non_snake_case)] #[allow(non_camel_case_types)] #[repr(C)] pub struct listpack; #[allow(improper_ctypes)] #[allow(non_snake_case)] #[allow(non_camel_case_types)] #[link(name = "listpack", kind = "static")] extern "C" { #[no_mangle] pub static mut lp_malloc: extern "C" fn(size: libc::size_t) -> *mut u8; #[no_mangle] pub static mut lp_realloc: extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8; #[no_mangle] pub static mut lp_free: extern "C" fn(ptr: *mut libc::c_void); fn lp_ll2string( dst: *mut u8, dstlen: libc::size_t, svalue: libc::c_longlong, ) -> libc::c_int; pub fn lpNew() -> *mut listpack; fn lpFree(lp: *mut listpack); fn lpInsert( lp: *mut listpack, ele: *const u8, size: libc::uint32_t, p: *mut u8, wh: libc::c_int, newp: &mut *mut u8, ) -> *mut listpack; fn lpAppend( lp: *mut listpack, ele: *const u8, size: libc::uint32_t) -> *mut listpack; fn lpDelete( lp: *mut listpack, p: *mut u8, newp: *mut *mut u8, ) -> *mut listpack; fn lpLength( lp: *mut listpack ) -> libc::uint32_t; pub fn lpGet( p: *mut u8, count: *mut libc::int64_t, intbuf: *mut u8, ) -> *mut u8; pub fn lpGetInteger( ele: *mut u8 ) -> libc::int64_t; pub fn lpFirst(lp: *mut listpack) -> *mut u8; fn lpLast(lp: *mut listpack) -> *mut u8; fn lpNext( lp: *mut listpack, p: *mut u8, ) -> *mut u8; fn lpPrev( lp: *mut listpack, p: *mut u8, ) -> *mut u8; fn lpBytes( lp: *mut listpack ) -> libc::uint32_t; fn lpSeek( lp: *mut listpack, index: libc::c_long, ) -> *mut u8; fn lpInsertInt64( lp: *mut listpack, value: libc::int64_t, p: *mut u8, wh: libc::c_int, newp: *mut *mut u8, ) -> *mut listpack; pub fn lpAppendInt64( lp: *mut listpack, value: libc::int64_t, ) -> *mut listpack; fn lpReplaceInt64( lp: *mut listpack, pos: &mut *mut u8, value: libc::int64_t, ) -> *mut listpack; } /// A facade to represent a series of contiguous fields as a Record. pub trait Adapter {} #[cfg(test)] mod tests { use *; fn print_cmp(lp: &mut Listpack, ele_1: Element, ele_2: Element) { match ele_1.cmp(&ele_2) { std::cmp::Ordering::Less => { println!("{} < {}", lp.get_str(ele_1), lp.get_str(ele_2)); ; } std::cmp::Ordering::Equal => { println!("{} == {}", lp.get_str(ele_1), lp.get_str(ele_2)); } std::cmp::Ordering::Greater => { println!("{} > {}", lp.get_str(ele_1), lp.get_str(ele_2)); } } } #[test] fn test_cmp() { let mut lp = Listpack::new(); lp.append_str("hello"); lp.append_str("bye"); let ele_1 = lp.first().unwrap(); let ele_2 = lp.seek(1).unwrap(); print_cmp(&mut lp, ele_1, ele_2); } #[test] fn test_replace() { let mut lp = Listpack::new(); println!("lp size before append_i32: {}", lp.size()); lp.append_i32(1); println!("lp size before append_i32_fixed: {}", lp.size()); lp.append_i32_fixed(1); println!("lp size after append_i32_fixed: {}", lp.size()); let v1 = lp.get_i32(lp.first().unwrap()); let v2 = lp.get_i32(lp.next(lp.first().unwrap()).unwrap()); assert_eq!(v1, v2); } #[test] fn test_append_helpers() { let mut lp = Listpack::new(); println!("lp size before append_i32: {}", lp.size()); lp.append_i32(1); println!("lp size before append_i32_fixed: {}", lp.size()); lp.append_i32_fixed(1); println!("lp size after append_i32_fixed: {}", lp.size()); let v1 = lp.get_i32(lp.first().unwrap()); let v2 = lp.get_i32(lp.next(lp.first().unwrap()).unwrap()); assert_eq!(v1, v2); } #[test] fn zigzag_int_test() { let mut lp = Listpack::new(); let v: i32 = -55; lp.append_negative_32(v); println!("w/ zigzag:"); let ele = lp.first().unwrap(); println!("value {}", v); println!("zigzag {}", v.zigzag()); println!("get {}", lp.get_negative_32(ele)); println!(); println!("Bytes: {}", lp.size()); println!("Length: {}", lp.len()); println!("Bytes / Element: {}", (lp.size() - 7) as f32 / lp.len() as f32); println!(); println!("w/o zigzag:"); lp = Listpack::new(); lp.append_int(v); let ele = lp.first().unwrap(); println!("value {}", v); println!("zigzag {}", v.zigzag()); println!("get {}", lp.get_i32(ele)); println!(); println!("Bytes: {}", lp.size()); println!("Length: {}", lp.len()); println!("Bytes / Element: {}", (lp.size() - 7) as f32 / lp.len() as f32); } #[test] fn zigzag_test() { let mut lp = Listpack::new(); lp.append_int(1.012_f32); let ele = lp.first().unwrap(); println!("{}", 1.012_f32.to_bits()); println!("{}", 1.012_f32.to_bits().zigzag()); println!("{}", lp.get_f32(ele)); println!(); println!("Bytes: {}", lp.size()); println!("Length: {}", lp.len()); println!("Bytes / Element: {}", (lp.size() - 7) as f32 / lp.len() as f32); } #[test] fn size_of_value() { println!("{}", std::mem::size_of::<Value>()); println!("{}", std::mem::size_of::<Val>()); println!("{}", std::mem::size_of::<StrValue>()); } #[test] fn test_multiple() { let mut lp = Listpack::new(); for i in 0..24 { lp.append((i as u8).into()); } lp.append(Value::Int(25)); lp.append("hi".into()); lp.append_str("hello"); lp.append_str("bye"); println!("Iterate forward..."); let mut ele = lp.start(); while let Some(v) = lp.first_or_next(ele) { ele = v; let val = lp.get(ele); match val { Value::Int(v) => { println!("Int -> {}", v); } Value::String(_v, _len) => { println!("String -> {}", val.as_str()); } } } println!(); println!("Iterate backward..."); let mut ele = lp.start(); while let Some(v) = lp.last_or_prev(ele) { ele = v; let val = lp.get(ele); match val { Value::Int(v) => { println!("Int -> {}", v); } Value::String(_v, _len) => { println!("String -> {}", val.as_str()); } } } println!(); println!("Seeking to index 10..."); match lp.seek(10) { Some(el) => { println!("Found..."); let val = lp.get(el); match val { Value::Int(v) => { println!("Int -> {}", v); } Value::String(_v, _len) => { println!("String -> {}", val.as_str()); } } } None => { println!("Not Found!"); } } println!(); println!("Seeking to index 100..."); match lp.seek(100) { Some(el) => { println!("Found..."); let val = lp.get(el); match val { Value::Int(v) => { println!("Int -> {}", v); } Value::String(_v, _len) => { println!("String -> {}", val.as_str()); } } } None => { println!("Not Found!"); } } println!(); println!("iterate with rust iterator"); for val in lp.iter() { match val { Value::Int(v) => { println!("Int -> {}", v); } Value::String(_v, _len) => { println!("String -> {}", val.as_str()); } } } println!(); println!("iterate with rust iterator in reverse"); for val in lp.iter().rev() { match val { Value::Int(v) => { println!("Int -> {}", v); } Value::String(_v, _len) => { println!("String -> {}", val.as_str()); } } } println!(); println!("Bytes: {}", lp.size()); println!("Length: {}", lp.len()); println!("Bytes / Element: {}", (lp.size() - 7) as f32 / lp.len() as f32); // assert_eq!(lp.len(), 3); } }
true
7ec9a571b508d5527b5ae5d239af9ac3f16141d6
Rust
wyyerd-contrib/juniper
/juniper/src/integrations/uuid.rs
UTF-8
673
2.984375
3
[ "BSD-2-Clause" ]
permissive
use uuid::Uuid; use Value; graphql_scalar!(Uuid { description: "Uuid" resolve(&self) -> Value { Value::string(self.to_string()) } from_input_value(v: &InputValue) -> Option<Uuid> { v.as_string_value() .and_then(|s| Uuid::parse_str(s).ok()) } }); #[cfg(test)] mod test { use uuid::Uuid; #[test] fn uuid_from_input_value() { let raw = "123e4567-e89b-12d3-a456-426655440000"; let input = ::InputValue::String(raw.to_string()); let parsed: Uuid = ::FromInputValue::from_input_value(&input).unwrap(); let id = Uuid::parse_str(raw).unwrap(); assert_eq!(parsed, id); } }
true
5daaa1a1d40d3de6c56f6ab8a8963e11c8bdffd1
Rust
mnts26/aws-sdk-rust
/sdk/route53domains/src/output.rs
UTF-8
97,720
2.546875
3
[ "Apache-2.0" ]
permissive
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>The ViewBilling response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ViewBillingOutput { /// <p>If there are more billing records than you specified for <code>MaxItems</code> in the request, submit another /// request and include the value of <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> pub next_page_marker: std::option::Option<std::string::String>, /// <p>A summary of billing records.</p> pub billing_records: std::option::Option<std::vec::Vec<crate::model::BillingRecord>>, } impl std::fmt::Debug for ViewBillingOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ViewBillingOutput"); formatter.field("next_page_marker", &self.next_page_marker); formatter.field("billing_records", &self.billing_records); formatter.finish() } } /// See [`ViewBillingOutput`](crate::output::ViewBillingOutput) pub mod view_billing_output { /// A builder for [`ViewBillingOutput`](crate::output::ViewBillingOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) next_page_marker: std::option::Option<std::string::String>, pub(crate) billing_records: std::option::Option<std::vec::Vec<crate::model::BillingRecord>>, } impl Builder { /// <p>If there are more billing records than you specified for <code>MaxItems</code> in the request, submit another /// request and include the value of <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> pub fn next_page_marker(mut self, input: impl Into<std::string::String>) -> Self { self.next_page_marker = Some(input.into()); self } pub fn set_next_page_marker( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.next_page_marker = input; self } pub fn billing_records(mut self, input: impl Into<crate::model::BillingRecord>) -> Self { let mut v = self.billing_records.unwrap_or_default(); v.push(input.into()); self.billing_records = Some(v); self } pub fn set_billing_records( mut self, input: std::option::Option<std::vec::Vec<crate::model::BillingRecord>>, ) -> Self { self.billing_records = input; self } /// Consumes the builder and constructs a [`ViewBillingOutput`](crate::output::ViewBillingOutput) pub fn build(self) -> crate::output::ViewBillingOutput { crate::output::ViewBillingOutput { next_page_marker: self.next_page_marker, billing_records: self.billing_records, } } } } impl ViewBillingOutput { /// Creates a new builder-style object to manufacture [`ViewBillingOutput`](crate::output::ViewBillingOutput) pub fn builder() -> crate::output::view_billing_output::Builder { crate::output::view_billing_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateTagsForDomainOutput {} impl std::fmt::Debug for UpdateTagsForDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateTagsForDomainOutput"); formatter.finish() } } /// See [`UpdateTagsForDomainOutput`](crate::output::UpdateTagsForDomainOutput) pub mod update_tags_for_domain_output { /// A builder for [`UpdateTagsForDomainOutput`](crate::output::UpdateTagsForDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UpdateTagsForDomainOutput`](crate::output::UpdateTagsForDomainOutput) pub fn build(self) -> crate::output::UpdateTagsForDomainOutput { crate::output::UpdateTagsForDomainOutput {} } } } impl UpdateTagsForDomainOutput { /// Creates a new builder-style object to manufacture [`UpdateTagsForDomainOutput`](crate::output::UpdateTagsForDomainOutput) pub fn builder() -> crate::output::update_tags_for_domain_output::Builder { crate::output::update_tags_for_domain_output::Builder::default() } } /// <p>The UpdateDomainNameservers response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateDomainNameserversOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for UpdateDomainNameserversOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateDomainNameserversOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`UpdateDomainNameserversOutput`](crate::output::UpdateDomainNameserversOutput) pub mod update_domain_nameservers_output { /// A builder for [`UpdateDomainNameserversOutput`](crate::output::UpdateDomainNameserversOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`UpdateDomainNameserversOutput`](crate::output::UpdateDomainNameserversOutput) pub fn build(self) -> crate::output::UpdateDomainNameserversOutput { crate::output::UpdateDomainNameserversOutput { operation_id: self.operation_id, } } } } impl UpdateDomainNameserversOutput { /// Creates a new builder-style object to manufacture [`UpdateDomainNameserversOutput`](crate::output::UpdateDomainNameserversOutput) pub fn builder() -> crate::output::update_domain_nameservers_output::Builder { crate::output::update_domain_nameservers_output::Builder::default() } } /// <p>The UpdateDomainContactPrivacy response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateDomainContactPrivacyOutput { /// <p>Identifier for tracking the progress of the request. To use this ID to query the operation status, use GetOperationDetail.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for UpdateDomainContactPrivacyOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateDomainContactPrivacyOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`UpdateDomainContactPrivacyOutput`](crate::output::UpdateDomainContactPrivacyOutput) pub mod update_domain_contact_privacy_output { /// A builder for [`UpdateDomainContactPrivacyOutput`](crate::output::UpdateDomainContactPrivacyOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To use this ID to query the operation status, use GetOperationDetail.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`UpdateDomainContactPrivacyOutput`](crate::output::UpdateDomainContactPrivacyOutput) pub fn build(self) -> crate::output::UpdateDomainContactPrivacyOutput { crate::output::UpdateDomainContactPrivacyOutput { operation_id: self.operation_id, } } } } impl UpdateDomainContactPrivacyOutput { /// Creates a new builder-style object to manufacture [`UpdateDomainContactPrivacyOutput`](crate::output::UpdateDomainContactPrivacyOutput) pub fn builder() -> crate::output::update_domain_contact_privacy_output::Builder { crate::output::update_domain_contact_privacy_output::Builder::default() } } /// <p>The UpdateDomainContact response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateDomainContactOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for UpdateDomainContactOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateDomainContactOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`UpdateDomainContactOutput`](crate::output::UpdateDomainContactOutput) pub mod update_domain_contact_output { /// A builder for [`UpdateDomainContactOutput`](crate::output::UpdateDomainContactOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`UpdateDomainContactOutput`](crate::output::UpdateDomainContactOutput) pub fn build(self) -> crate::output::UpdateDomainContactOutput { crate::output::UpdateDomainContactOutput { operation_id: self.operation_id, } } } } impl UpdateDomainContactOutput { /// Creates a new builder-style object to manufacture [`UpdateDomainContactOutput`](crate::output::UpdateDomainContactOutput) pub fn builder() -> crate::output::update_domain_contact_output::Builder { crate::output::update_domain_contact_output::Builder::default() } } /// <p>The <code>TransferDomainToAnotherAwsAccount</code> response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TransferDomainToAnotherAwsAccountOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, /// <p>To finish transferring a domain to another AWS account, the account that the domain is being transferred to must submit an /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html">AcceptDomainTransferFromAnotherAwsAccount</a> /// request. The request must include the value of the <code>Password</code> element that was returned in the /// <code>TransferDomainToAnotherAwsAccount</code> response.</p> pub password: std::option::Option<std::string::String>, } impl std::fmt::Debug for TransferDomainToAnotherAwsAccountOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TransferDomainToAnotherAwsAccountOutput"); formatter.field("operation_id", &self.operation_id); formatter.field("password", &self.password); formatter.finish() } } /// See [`TransferDomainToAnotherAwsAccountOutput`](crate::output::TransferDomainToAnotherAwsAccountOutput) pub mod transfer_domain_to_another_aws_account_output { /// A builder for [`TransferDomainToAnotherAwsAccountOutput`](crate::output::TransferDomainToAnotherAwsAccountOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, pub(crate) password: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// <p>To finish transferring a domain to another AWS account, the account that the domain is being transferred to must submit an /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html">AcceptDomainTransferFromAnotherAwsAccount</a> /// request. The request must include the value of the <code>Password</code> element that was returned in the /// <code>TransferDomainToAnotherAwsAccount</code> response.</p> pub fn password(mut self, input: impl Into<std::string::String>) -> Self { self.password = Some(input.into()); self } pub fn set_password(mut self, input: std::option::Option<std::string::String>) -> Self { self.password = input; self } /// Consumes the builder and constructs a [`TransferDomainToAnotherAwsAccountOutput`](crate::output::TransferDomainToAnotherAwsAccountOutput) pub fn build(self) -> crate::output::TransferDomainToAnotherAwsAccountOutput { crate::output::TransferDomainToAnotherAwsAccountOutput { operation_id: self.operation_id, password: self.password, } } } } impl TransferDomainToAnotherAwsAccountOutput { /// Creates a new builder-style object to manufacture [`TransferDomainToAnotherAwsAccountOutput`](crate::output::TransferDomainToAnotherAwsAccountOutput) pub fn builder() -> crate::output::transfer_domain_to_another_aws_account_output::Builder { crate::output::transfer_domain_to_another_aws_account_output::Builder::default() } } /// <p>The TransferDomain response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TransferDomainOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for TransferDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TransferDomainOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`TransferDomainOutput`](crate::output::TransferDomainOutput) pub mod transfer_domain_output { /// A builder for [`TransferDomainOutput`](crate::output::TransferDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`TransferDomainOutput`](crate::output::TransferDomainOutput) pub fn build(self) -> crate::output::TransferDomainOutput { crate::output::TransferDomainOutput { operation_id: self.operation_id, } } } } impl TransferDomainOutput { /// Creates a new builder-style object to manufacture [`TransferDomainOutput`](crate::output::TransferDomainOutput) pub fn builder() -> crate::output::transfer_domain_output::Builder { crate::output::transfer_domain_output::Builder::default() } } /// <p>The RetrieveDomainAuthCode response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RetrieveDomainAuthCodeOutput { /// <p>The authorization code for the domain.</p> pub auth_code: std::option::Option<std::string::String>, } impl std::fmt::Debug for RetrieveDomainAuthCodeOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RetrieveDomainAuthCodeOutput"); formatter.field("auth_code", &"*** Sensitive Data Redacted ***"); formatter.finish() } } /// See [`RetrieveDomainAuthCodeOutput`](crate::output::RetrieveDomainAuthCodeOutput) pub mod retrieve_domain_auth_code_output { /// A builder for [`RetrieveDomainAuthCodeOutput`](crate::output::RetrieveDomainAuthCodeOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) auth_code: std::option::Option<std::string::String>, } impl Builder { /// <p>The authorization code for the domain.</p> pub fn auth_code(mut self, input: impl Into<std::string::String>) -> Self { self.auth_code = Some(input.into()); self } pub fn set_auth_code(mut self, input: std::option::Option<std::string::String>) -> Self { self.auth_code = input; self } /// Consumes the builder and constructs a [`RetrieveDomainAuthCodeOutput`](crate::output::RetrieveDomainAuthCodeOutput) pub fn build(self) -> crate::output::RetrieveDomainAuthCodeOutput { crate::output::RetrieveDomainAuthCodeOutput { auth_code: self.auth_code, } } } } impl RetrieveDomainAuthCodeOutput { /// Creates a new builder-style object to manufacture [`RetrieveDomainAuthCodeOutput`](crate::output::RetrieveDomainAuthCodeOutput) pub fn builder() -> crate::output::retrieve_domain_auth_code_output::Builder { crate::output::retrieve_domain_auth_code_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResendContactReachabilityEmailOutput { /// <p>The domain name for which you requested a confirmation email.</p> pub domain_name: std::option::Option<std::string::String>, /// <p>The email address for the registrant contact at the time that we sent the verification email.</p> pub email_address: std::option::Option<std::string::String>, /// <p> /// <code>True</code> if the email address for the registrant contact has already been verified, and <code>false</code> otherwise. /// If the email address has already been verified, we don't send another confirmation email.</p> pub is_already_verified: std::option::Option<bool>, } impl std::fmt::Debug for ResendContactReachabilityEmailOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResendContactReachabilityEmailOutput"); formatter.field("domain_name", &self.domain_name); formatter.field("email_address", &self.email_address); formatter.field("is_already_verified", &self.is_already_verified); formatter.finish() } } /// See [`ResendContactReachabilityEmailOutput`](crate::output::ResendContactReachabilityEmailOutput) pub mod resend_contact_reachability_email_output { /// A builder for [`ResendContactReachabilityEmailOutput`](crate::output::ResendContactReachabilityEmailOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain_name: std::option::Option<std::string::String>, pub(crate) email_address: std::option::Option<std::string::String>, pub(crate) is_already_verified: std::option::Option<bool>, } impl Builder { /// <p>The domain name for which you requested a confirmation email.</p> pub fn domain_name(mut self, input: impl Into<std::string::String>) -> Self { self.domain_name = Some(input.into()); self } pub fn set_domain_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_name = input; self } /// <p>The email address for the registrant contact at the time that we sent the verification email.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// <p> /// <code>True</code> if the email address for the registrant contact has already been verified, and <code>false</code> otherwise. /// If the email address has already been verified, we don't send another confirmation email.</p> pub fn is_already_verified(mut self, input: bool) -> Self { self.is_already_verified = Some(input); self } pub fn set_is_already_verified(mut self, input: std::option::Option<bool>) -> Self { self.is_already_verified = input; self } /// Consumes the builder and constructs a [`ResendContactReachabilityEmailOutput`](crate::output::ResendContactReachabilityEmailOutput) pub fn build(self) -> crate::output::ResendContactReachabilityEmailOutput { crate::output::ResendContactReachabilityEmailOutput { domain_name: self.domain_name, email_address: self.email_address, is_already_verified: self.is_already_verified, } } } } impl ResendContactReachabilityEmailOutput { /// Creates a new builder-style object to manufacture [`ResendContactReachabilityEmailOutput`](crate::output::ResendContactReachabilityEmailOutput) pub fn builder() -> crate::output::resend_contact_reachability_email_output::Builder { crate::output::resend_contact_reachability_email_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RenewDomainOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for RenewDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RenewDomainOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`RenewDomainOutput`](crate::output::RenewDomainOutput) pub mod renew_domain_output { /// A builder for [`RenewDomainOutput`](crate::output::RenewDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`RenewDomainOutput`](crate::output::RenewDomainOutput) pub fn build(self) -> crate::output::RenewDomainOutput { crate::output::RenewDomainOutput { operation_id: self.operation_id, } } } } impl RenewDomainOutput { /// Creates a new builder-style object to manufacture [`RenewDomainOutput`](crate::output::RenewDomainOutput) pub fn builder() -> crate::output::renew_domain_output::Builder { crate::output::renew_domain_output::Builder::default() } } /// <p>The RejectDomainTransferFromAnotherAwsAccount response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RejectDomainTransferFromAnotherAwsAccountOutput { /// <p>The identifier that <code>TransferDomainToAnotherAwsAccount</code> returned to track the progress of the request. /// Because the transfer request was rejected, the value is no longer valid, and you can't use <code>GetOperationDetail</code> /// to query the operation status.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for RejectDomainTransferFromAnotherAwsAccountOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RejectDomainTransferFromAnotherAwsAccountOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`RejectDomainTransferFromAnotherAwsAccountOutput`](crate::output::RejectDomainTransferFromAnotherAwsAccountOutput) pub mod reject_domain_transfer_from_another_aws_account_output { /// A builder for [`RejectDomainTransferFromAnotherAwsAccountOutput`](crate::output::RejectDomainTransferFromAnotherAwsAccountOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The identifier that <code>TransferDomainToAnotherAwsAccount</code> returned to track the progress of the request. /// Because the transfer request was rejected, the value is no longer valid, and you can't use <code>GetOperationDetail</code> /// to query the operation status.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`RejectDomainTransferFromAnotherAwsAccountOutput`](crate::output::RejectDomainTransferFromAnotherAwsAccountOutput) pub fn build(self) -> crate::output::RejectDomainTransferFromAnotherAwsAccountOutput { crate::output::RejectDomainTransferFromAnotherAwsAccountOutput { operation_id: self.operation_id, } } } } impl RejectDomainTransferFromAnotherAwsAccountOutput { /// Creates a new builder-style object to manufacture [`RejectDomainTransferFromAnotherAwsAccountOutput`](crate::output::RejectDomainTransferFromAnotherAwsAccountOutput) pub fn builder( ) -> crate::output::reject_domain_transfer_from_another_aws_account_output::Builder { crate::output::reject_domain_transfer_from_another_aws_account_output::Builder::default() } } /// <p>The RegisterDomain response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RegisterDomainOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for RegisterDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RegisterDomainOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`RegisterDomainOutput`](crate::output::RegisterDomainOutput) pub mod register_domain_output { /// A builder for [`RegisterDomainOutput`](crate::output::RegisterDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`RegisterDomainOutput`](crate::output::RegisterDomainOutput) pub fn build(self) -> crate::output::RegisterDomainOutput { crate::output::RegisterDomainOutput { operation_id: self.operation_id, } } } } impl RegisterDomainOutput { /// Creates a new builder-style object to manufacture [`RegisterDomainOutput`](crate::output::RegisterDomainOutput) pub fn builder() -> crate::output::register_domain_output::Builder { crate::output::register_domain_output::Builder::default() } } /// <p>The ListTagsForDomain response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListTagsForDomainOutput { /// <p>A list of the tags that are associated with the specified domain.</p> pub tag_list: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl std::fmt::Debug for ListTagsForDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListTagsForDomainOutput"); formatter.field("tag_list", &self.tag_list); formatter.finish() } } /// See [`ListTagsForDomainOutput`](crate::output::ListTagsForDomainOutput) pub mod list_tags_for_domain_output { /// A builder for [`ListTagsForDomainOutput`](crate::output::ListTagsForDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) tag_list: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { pub fn tag_list(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tag_list.unwrap_or_default(); v.push(input.into()); self.tag_list = Some(v); self } pub fn set_tag_list( mut self, input: std::option::Option<std::vec::Vec<crate::model::Tag>>, ) -> Self { self.tag_list = input; self } /// Consumes the builder and constructs a [`ListTagsForDomainOutput`](crate::output::ListTagsForDomainOutput) pub fn build(self) -> crate::output::ListTagsForDomainOutput { crate::output::ListTagsForDomainOutput { tag_list: self.tag_list, } } } } impl ListTagsForDomainOutput { /// Creates a new builder-style object to manufacture [`ListTagsForDomainOutput`](crate::output::ListTagsForDomainOutput) pub fn builder() -> crate::output::list_tags_for_domain_output::Builder { crate::output::list_tags_for_domain_output::Builder::default() } } /// <p>The ListOperations response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListOperationsOutput { /// <p>Lists summaries of the operations.</p> pub operations: std::option::Option<std::vec::Vec<crate::model::OperationSummary>>, /// <p>If there are more operations than you specified for <code>MaxItems</code> in the request, submit another /// request and include the value of <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> pub next_page_marker: std::option::Option<std::string::String>, } impl std::fmt::Debug for ListOperationsOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListOperationsOutput"); formatter.field("operations", &self.operations); formatter.field("next_page_marker", &self.next_page_marker); formatter.finish() } } /// See [`ListOperationsOutput`](crate::output::ListOperationsOutput) pub mod list_operations_output { /// A builder for [`ListOperationsOutput`](crate::output::ListOperationsOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operations: std::option::Option<std::vec::Vec<crate::model::OperationSummary>>, pub(crate) next_page_marker: std::option::Option<std::string::String>, } impl Builder { pub fn operations(mut self, input: impl Into<crate::model::OperationSummary>) -> Self { let mut v = self.operations.unwrap_or_default(); v.push(input.into()); self.operations = Some(v); self } pub fn set_operations( mut self, input: std::option::Option<std::vec::Vec<crate::model::OperationSummary>>, ) -> Self { self.operations = input; self } /// <p>If there are more operations than you specified for <code>MaxItems</code> in the request, submit another /// request and include the value of <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> pub fn next_page_marker(mut self, input: impl Into<std::string::String>) -> Self { self.next_page_marker = Some(input.into()); self } pub fn set_next_page_marker( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.next_page_marker = input; self } /// Consumes the builder and constructs a [`ListOperationsOutput`](crate::output::ListOperationsOutput) pub fn build(self) -> crate::output::ListOperationsOutput { crate::output::ListOperationsOutput { operations: self.operations, next_page_marker: self.next_page_marker, } } } } impl ListOperationsOutput { /// Creates a new builder-style object to manufacture [`ListOperationsOutput`](crate::output::ListOperationsOutput) pub fn builder() -> crate::output::list_operations_output::Builder { crate::output::list_operations_output::Builder::default() } } /// <p>The ListDomains response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListDomainsOutput { /// <p>A summary of domains.</p> pub domains: std::option::Option<std::vec::Vec<crate::model::DomainSummary>>, /// <p>If there are more domains than you specified for <code>MaxItems</code> in the request, submit another /// request and include the value of <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> pub next_page_marker: std::option::Option<std::string::String>, } impl std::fmt::Debug for ListDomainsOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListDomainsOutput"); formatter.field("domains", &self.domains); formatter.field("next_page_marker", &self.next_page_marker); formatter.finish() } } /// See [`ListDomainsOutput`](crate::output::ListDomainsOutput) pub mod list_domains_output { /// A builder for [`ListDomainsOutput`](crate::output::ListDomainsOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domains: std::option::Option<std::vec::Vec<crate::model::DomainSummary>>, pub(crate) next_page_marker: std::option::Option<std::string::String>, } impl Builder { pub fn domains(mut self, input: impl Into<crate::model::DomainSummary>) -> Self { let mut v = self.domains.unwrap_or_default(); v.push(input.into()); self.domains = Some(v); self } pub fn set_domains( mut self, input: std::option::Option<std::vec::Vec<crate::model::DomainSummary>>, ) -> Self { self.domains = input; self } /// <p>If there are more domains than you specified for <code>MaxItems</code> in the request, submit another /// request and include the value of <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> pub fn next_page_marker(mut self, input: impl Into<std::string::String>) -> Self { self.next_page_marker = Some(input.into()); self } pub fn set_next_page_marker( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.next_page_marker = input; self } /// Consumes the builder and constructs a [`ListDomainsOutput`](crate::output::ListDomainsOutput) pub fn build(self) -> crate::output::ListDomainsOutput { crate::output::ListDomainsOutput { domains: self.domains, next_page_marker: self.next_page_marker, } } } } impl ListDomainsOutput { /// Creates a new builder-style object to manufacture [`ListDomainsOutput`](crate::output::ListDomainsOutput) pub fn builder() -> crate::output::list_domains_output::Builder { crate::output::list_domains_output::Builder::default() } } /// <p>The GetOperationDetail response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetOperationDetailOutput { /// <p>The identifier for the operation.</p> pub operation_id: std::option::Option<std::string::String>, /// <p>The current status of the requested operation in the system.</p> pub status: std::option::Option<crate::model::OperationStatus>, /// <p>Detailed information on the status including possible errors.</p> pub message: std::option::Option<std::string::String>, /// <p>The name of a domain.</p> pub domain_name: std::option::Option<std::string::String>, /// <p>The type of operation that was requested.</p> pub r#type: std::option::Option<crate::model::OperationType>, /// <p>The date when the request was submitted.</p> pub submitted_date: std::option::Option<smithy_types::Instant>, } impl std::fmt::Debug for GetOperationDetailOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetOperationDetailOutput"); formatter.field("operation_id", &self.operation_id); formatter.field("status", &self.status); formatter.field("message", &self.message); formatter.field("domain_name", &self.domain_name); formatter.field("r#type", &self.r#type); formatter.field("submitted_date", &self.submitted_date); formatter.finish() } } /// See [`GetOperationDetailOutput`](crate::output::GetOperationDetailOutput) pub mod get_operation_detail_output { /// A builder for [`GetOperationDetailOutput`](crate::output::GetOperationDetailOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::OperationStatus>, pub(crate) message: std::option::Option<std::string::String>, pub(crate) domain_name: std::option::Option<std::string::String>, pub(crate) r#type: std::option::Option<crate::model::OperationType>, pub(crate) submitted_date: std::option::Option<smithy_types::Instant>, } impl Builder { /// <p>The identifier for the operation.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// <p>The current status of the requested operation in the system.</p> pub fn status(mut self, input: crate::model::OperationStatus) -> Self { self.status = Some(input); self } pub fn set_status( mut self, input: std::option::Option<crate::model::OperationStatus>, ) -> Self { self.status = input; self } /// <p>Detailed information on the status including possible errors.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// <p>The name of a domain.</p> pub fn domain_name(mut self, input: impl Into<std::string::String>) -> Self { self.domain_name = Some(input.into()); self } pub fn set_domain_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_name = input; self } /// <p>The type of operation that was requested.</p> pub fn r#type(mut self, input: crate::model::OperationType) -> Self { self.r#type = Some(input); self } pub fn set_type(mut self, input: std::option::Option<crate::model::OperationType>) -> Self { self.r#type = input; self } /// <p>The date when the request was submitted.</p> pub fn submitted_date(mut self, input: smithy_types::Instant) -> Self { self.submitted_date = Some(input); self } pub fn set_submitted_date( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.submitted_date = input; self } /// Consumes the builder and constructs a [`GetOperationDetailOutput`](crate::output::GetOperationDetailOutput) pub fn build(self) -> crate::output::GetOperationDetailOutput { crate::output::GetOperationDetailOutput { operation_id: self.operation_id, status: self.status, message: self.message, domain_name: self.domain_name, r#type: self.r#type, submitted_date: self.submitted_date, } } } } impl GetOperationDetailOutput { /// Creates a new builder-style object to manufacture [`GetOperationDetailOutput`](crate::output::GetOperationDetailOutput) pub fn builder() -> crate::output::get_operation_detail_output::Builder { crate::output::get_operation_detail_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDomainSuggestionsOutput { /// <p>A list of possible domain names. If you specified <code>true</code> for <code>OnlyAvailable</code> in the request, /// the list contains only domains that are available for registration.</p> pub suggestions_list: std::option::Option<std::vec::Vec<crate::model::DomainSuggestion>>, } impl std::fmt::Debug for GetDomainSuggestionsOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDomainSuggestionsOutput"); formatter.field("suggestions_list", &self.suggestions_list); formatter.finish() } } /// See [`GetDomainSuggestionsOutput`](crate::output::GetDomainSuggestionsOutput) pub mod get_domain_suggestions_output { /// A builder for [`GetDomainSuggestionsOutput`](crate::output::GetDomainSuggestionsOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) suggestions_list: std::option::Option<std::vec::Vec<crate::model::DomainSuggestion>>, } impl Builder { pub fn suggestions_list( mut self, input: impl Into<crate::model::DomainSuggestion>, ) -> Self { let mut v = self.suggestions_list.unwrap_or_default(); v.push(input.into()); self.suggestions_list = Some(v); self } pub fn set_suggestions_list( mut self, input: std::option::Option<std::vec::Vec<crate::model::DomainSuggestion>>, ) -> Self { self.suggestions_list = input; self } /// Consumes the builder and constructs a [`GetDomainSuggestionsOutput`](crate::output::GetDomainSuggestionsOutput) pub fn build(self) -> crate::output::GetDomainSuggestionsOutput { crate::output::GetDomainSuggestionsOutput { suggestions_list: self.suggestions_list, } } } } impl GetDomainSuggestionsOutput { /// Creates a new builder-style object to manufacture [`GetDomainSuggestionsOutput`](crate::output::GetDomainSuggestionsOutput) pub fn builder() -> crate::output::get_domain_suggestions_output::Builder { crate::output::get_domain_suggestions_output::Builder::default() } } /// <p>The GetDomainDetail response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDomainDetailOutput { /// <p>The name of a domain.</p> pub domain_name: std::option::Option<std::string::String>, /// <p>The name of the domain.</p> pub nameservers: std::option::Option<std::vec::Vec<crate::model::Nameserver>>, /// <p>Specifies whether the domain registration is set to renew automatically.</p> pub auto_renew: std::option::Option<bool>, /// <p>Provides details about the domain administrative contact.</p> pub admin_contact: std::option::Option<crate::model::ContactDetail>, /// <p>Provides details about the domain registrant.</p> pub registrant_contact: std::option::Option<crate::model::ContactDetail>, /// <p>Provides details about the domain technical contact.</p> pub tech_contact: std::option::Option<crate::model::ContactDetail>, /// <p>Specifies whether contact information is concealed from WHOIS queries. If the value is <code>true</code>, /// WHOIS ("who is") queries return contact information either for Amazon Registrar (for .com, .net, and .org domains) /// or for our registrar associate, Gandi (for all other TLDs). If the value is <code>false</code>, /// WHOIS queries return the information that you entered for the admin contact.</p> pub admin_privacy: std::option::Option<bool>, /// <p>Specifies whether contact information is concealed from WHOIS queries. If the value is <code>true</code>, /// WHOIS ("who is") queries return contact information either for Amazon Registrar (for .com, .net, and .org domains) /// or for our registrar associate, Gandi (for all other TLDs). If the value is <code>false</code>, /// WHOIS queries return the information that you entered for the registrant contact (domain owner).</p> pub registrant_privacy: std::option::Option<bool>, /// <p>Specifies whether contact information is concealed from WHOIS queries. If the value is <code>true</code>, /// WHOIS ("who is") queries return contact information either for Amazon Registrar (for .com, .net, and .org domains) /// or for our registrar associate, Gandi (for all other TLDs). If the value is <code>false</code>, /// WHOIS queries return the information that you entered for the technical contact.</p> pub tech_privacy: std::option::Option<bool>, /// <p>Name of the registrar of the domain as identified in the registry. Domains with a .com, .net, or .org TLD are registered by /// Amazon Registrar. All other domains are registered by our registrar associate, Gandi. The value for domains that are registered by /// Gandi is <code>"GANDI SAS"</code>. </p> pub registrar_name: std::option::Option<std::string::String>, /// <p>The fully qualified name of the WHOIS server that can answer the WHOIS query for the domain.</p> pub who_is_server: std::option::Option<std::string::String>, /// <p>Web address of the registrar.</p> pub registrar_url: std::option::Option<std::string::String>, /// <p>Email address to contact to report incorrect contact information for a domain, to report that the domain /// is being used to send spam, to report that someone is cybersquatting on a domain name, or report some other type of abuse.</p> pub abuse_contact_email: std::option::Option<std::string::String>, /// <p>Phone number for reporting abuse.</p> pub abuse_contact_phone: std::option::Option<std::string::String>, /// <p>Reserved for future use.</p> pub registry_domain_id: std::option::Option<std::string::String>, /// <p>The date when the domain was created as found in the response to a WHOIS query. The date and time is in /// Unix time format and Coordinated Universal time (UTC).</p> pub creation_date: std::option::Option<smithy_types::Instant>, /// <p>The last updated date of the domain as found in the response to a WHOIS query. The date and time is in /// Unix time format and Coordinated Universal time (UTC).</p> pub updated_date: std::option::Option<smithy_types::Instant>, /// <p>The date when the registration for the domain is set to expire. The date and time is in /// Unix time format and Coordinated Universal time (UTC).</p> pub expiration_date: std::option::Option<smithy_types::Instant>, /// <p>Reseller of the domain. Domains registered or transferred using Route 53 domains will have <code>"Amazon"</code> /// as the reseller. </p> pub reseller: std::option::Option<std::string::String>, /// <p>Reserved for future use.</p> pub dns_sec: std::option::Option<std::string::String>, /// <p>An array of domain name status codes, also known as Extensible Provisioning Protocol (EPP) status codes.</p> /// <p>ICANN, the organization that maintains a central database of domain names, has developed a set of domain name /// status codes that tell you the status of a variety of operations on a domain name, for example, registering a domain name, /// transferring a domain name to another registrar, renewing the registration for a domain name, and so on. All registrars /// use this same set of status codes.</p> /// <p>For a current list of domain name status codes and an explanation of what each code means, go to the /// <a href="https://www.icann.org/">ICANN website</a> and search for <code>epp status codes</code>. /// (Search on the ICANN website; web searches sometimes return an old version of the document.)</p> pub status_list: std::option::Option<std::vec::Vec<std::string::String>>, } impl std::fmt::Debug for GetDomainDetailOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDomainDetailOutput"); formatter.field("domain_name", &self.domain_name); formatter.field("nameservers", &self.nameservers); formatter.field("auto_renew", &self.auto_renew); formatter.field("admin_contact", &"*** Sensitive Data Redacted ***"); formatter.field("registrant_contact", &"*** Sensitive Data Redacted ***"); formatter.field("tech_contact", &"*** Sensitive Data Redacted ***"); formatter.field("admin_privacy", &self.admin_privacy); formatter.field("registrant_privacy", &self.registrant_privacy); formatter.field("tech_privacy", &self.tech_privacy); formatter.field("registrar_name", &self.registrar_name); formatter.field("who_is_server", &self.who_is_server); formatter.field("registrar_url", &self.registrar_url); formatter.field("abuse_contact_email", &self.abuse_contact_email); formatter.field("abuse_contact_phone", &self.abuse_contact_phone); formatter.field("registry_domain_id", &self.registry_domain_id); formatter.field("creation_date", &self.creation_date); formatter.field("updated_date", &self.updated_date); formatter.field("expiration_date", &self.expiration_date); formatter.field("reseller", &self.reseller); formatter.field("dns_sec", &self.dns_sec); formatter.field("status_list", &self.status_list); formatter.finish() } } /// See [`GetDomainDetailOutput`](crate::output::GetDomainDetailOutput) pub mod get_domain_detail_output { /// A builder for [`GetDomainDetailOutput`](crate::output::GetDomainDetailOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain_name: std::option::Option<std::string::String>, pub(crate) nameservers: std::option::Option<std::vec::Vec<crate::model::Nameserver>>, pub(crate) auto_renew: std::option::Option<bool>, pub(crate) admin_contact: std::option::Option<crate::model::ContactDetail>, pub(crate) registrant_contact: std::option::Option<crate::model::ContactDetail>, pub(crate) tech_contact: std::option::Option<crate::model::ContactDetail>, pub(crate) admin_privacy: std::option::Option<bool>, pub(crate) registrant_privacy: std::option::Option<bool>, pub(crate) tech_privacy: std::option::Option<bool>, pub(crate) registrar_name: std::option::Option<std::string::String>, pub(crate) who_is_server: std::option::Option<std::string::String>, pub(crate) registrar_url: std::option::Option<std::string::String>, pub(crate) abuse_contact_email: std::option::Option<std::string::String>, pub(crate) abuse_contact_phone: std::option::Option<std::string::String>, pub(crate) registry_domain_id: std::option::Option<std::string::String>, pub(crate) creation_date: std::option::Option<smithy_types::Instant>, pub(crate) updated_date: std::option::Option<smithy_types::Instant>, pub(crate) expiration_date: std::option::Option<smithy_types::Instant>, pub(crate) reseller: std::option::Option<std::string::String>, pub(crate) dns_sec: std::option::Option<std::string::String>, pub(crate) status_list: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// <p>The name of a domain.</p> pub fn domain_name(mut self, input: impl Into<std::string::String>) -> Self { self.domain_name = Some(input.into()); self } pub fn set_domain_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_name = input; self } pub fn nameservers(mut self, input: impl Into<crate::model::Nameserver>) -> Self { let mut v = self.nameservers.unwrap_or_default(); v.push(input.into()); self.nameservers = Some(v); self } pub fn set_nameservers( mut self, input: std::option::Option<std::vec::Vec<crate::model::Nameserver>>, ) -> Self { self.nameservers = input; self } /// <p>Specifies whether the domain registration is set to renew automatically.</p> pub fn auto_renew(mut self, input: bool) -> Self { self.auto_renew = Some(input); self } pub fn set_auto_renew(mut self, input: std::option::Option<bool>) -> Self { self.auto_renew = input; self } /// <p>Provides details about the domain administrative contact.</p> pub fn admin_contact(mut self, input: crate::model::ContactDetail) -> Self { self.admin_contact = Some(input); self } pub fn set_admin_contact( mut self, input: std::option::Option<crate::model::ContactDetail>, ) -> Self { self.admin_contact = input; self } /// <p>Provides details about the domain registrant.</p> pub fn registrant_contact(mut self, input: crate::model::ContactDetail) -> Self { self.registrant_contact = Some(input); self } pub fn set_registrant_contact( mut self, input: std::option::Option<crate::model::ContactDetail>, ) -> Self { self.registrant_contact = input; self } /// <p>Provides details about the domain technical contact.</p> pub fn tech_contact(mut self, input: crate::model::ContactDetail) -> Self { self.tech_contact = Some(input); self } pub fn set_tech_contact( mut self, input: std::option::Option<crate::model::ContactDetail>, ) -> Self { self.tech_contact = input; self } /// <p>Specifies whether contact information is concealed from WHOIS queries. If the value is <code>true</code>, /// WHOIS ("who is") queries return contact information either for Amazon Registrar (for .com, .net, and .org domains) /// or for our registrar associate, Gandi (for all other TLDs). If the value is <code>false</code>, /// WHOIS queries return the information that you entered for the admin contact.</p> pub fn admin_privacy(mut self, input: bool) -> Self { self.admin_privacy = Some(input); self } pub fn set_admin_privacy(mut self, input: std::option::Option<bool>) -> Self { self.admin_privacy = input; self } /// <p>Specifies whether contact information is concealed from WHOIS queries. If the value is <code>true</code>, /// WHOIS ("who is") queries return contact information either for Amazon Registrar (for .com, .net, and .org domains) /// or for our registrar associate, Gandi (for all other TLDs). If the value is <code>false</code>, /// WHOIS queries return the information that you entered for the registrant contact (domain owner).</p> pub fn registrant_privacy(mut self, input: bool) -> Self { self.registrant_privacy = Some(input); self } pub fn set_registrant_privacy(mut self, input: std::option::Option<bool>) -> Self { self.registrant_privacy = input; self } /// <p>Specifies whether contact information is concealed from WHOIS queries. If the value is <code>true</code>, /// WHOIS ("who is") queries return contact information either for Amazon Registrar (for .com, .net, and .org domains) /// or for our registrar associate, Gandi (for all other TLDs). If the value is <code>false</code>, /// WHOIS queries return the information that you entered for the technical contact.</p> pub fn tech_privacy(mut self, input: bool) -> Self { self.tech_privacy = Some(input); self } pub fn set_tech_privacy(mut self, input: std::option::Option<bool>) -> Self { self.tech_privacy = input; self } /// <p>Name of the registrar of the domain as identified in the registry. Domains with a .com, .net, or .org TLD are registered by /// Amazon Registrar. All other domains are registered by our registrar associate, Gandi. The value for domains that are registered by /// Gandi is <code>"GANDI SAS"</code>. </p> pub fn registrar_name(mut self, input: impl Into<std::string::String>) -> Self { self.registrar_name = Some(input.into()); self } pub fn set_registrar_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.registrar_name = input; self } /// <p>The fully qualified name of the WHOIS server that can answer the WHOIS query for the domain.</p> pub fn who_is_server(mut self, input: impl Into<std::string::String>) -> Self { self.who_is_server = Some(input.into()); self } pub fn set_who_is_server( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.who_is_server = input; self } /// <p>Web address of the registrar.</p> pub fn registrar_url(mut self, input: impl Into<std::string::String>) -> Self { self.registrar_url = Some(input.into()); self } pub fn set_registrar_url( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.registrar_url = input; self } /// <p>Email address to contact to report incorrect contact information for a domain, to report that the domain /// is being used to send spam, to report that someone is cybersquatting on a domain name, or report some other type of abuse.</p> pub fn abuse_contact_email(mut self, input: impl Into<std::string::String>) -> Self { self.abuse_contact_email = Some(input.into()); self } pub fn set_abuse_contact_email( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.abuse_contact_email = input; self } /// <p>Phone number for reporting abuse.</p> pub fn abuse_contact_phone(mut self, input: impl Into<std::string::String>) -> Self { self.abuse_contact_phone = Some(input.into()); self } pub fn set_abuse_contact_phone( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.abuse_contact_phone = input; self } /// <p>Reserved for future use.</p> pub fn registry_domain_id(mut self, input: impl Into<std::string::String>) -> Self { self.registry_domain_id = Some(input.into()); self } pub fn set_registry_domain_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.registry_domain_id = input; self } /// <p>The date when the domain was created as found in the response to a WHOIS query. The date and time is in /// Unix time format and Coordinated Universal time (UTC).</p> pub fn creation_date(mut self, input: smithy_types::Instant) -> Self { self.creation_date = Some(input); self } pub fn set_creation_date( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.creation_date = input; self } /// <p>The last updated date of the domain as found in the response to a WHOIS query. The date and time is in /// Unix time format and Coordinated Universal time (UTC).</p> pub fn updated_date(mut self, input: smithy_types::Instant) -> Self { self.updated_date = Some(input); self } pub fn set_updated_date( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.updated_date = input; self } /// <p>The date when the registration for the domain is set to expire. The date and time is in /// Unix time format and Coordinated Universal time (UTC).</p> pub fn expiration_date(mut self, input: smithy_types::Instant) -> Self { self.expiration_date = Some(input); self } pub fn set_expiration_date( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.expiration_date = input; self } /// <p>Reseller of the domain. Domains registered or transferred using Route 53 domains will have <code>"Amazon"</code> /// as the reseller. </p> pub fn reseller(mut self, input: impl Into<std::string::String>) -> Self { self.reseller = Some(input.into()); self } pub fn set_reseller(mut self, input: std::option::Option<std::string::String>) -> Self { self.reseller = input; self } /// <p>Reserved for future use.</p> pub fn dns_sec(mut self, input: impl Into<std::string::String>) -> Self { self.dns_sec = Some(input.into()); self } pub fn set_dns_sec(mut self, input: std::option::Option<std::string::String>) -> Self { self.dns_sec = input; self } pub fn status_list(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.status_list.unwrap_or_default(); v.push(input.into()); self.status_list = Some(v); self } pub fn set_status_list( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.status_list = input; self } /// Consumes the builder and constructs a [`GetDomainDetailOutput`](crate::output::GetDomainDetailOutput) pub fn build(self) -> crate::output::GetDomainDetailOutput { crate::output::GetDomainDetailOutput { domain_name: self.domain_name, nameservers: self.nameservers, auto_renew: self.auto_renew, admin_contact: self.admin_contact, registrant_contact: self.registrant_contact, tech_contact: self.tech_contact, admin_privacy: self.admin_privacy, registrant_privacy: self.registrant_privacy, tech_privacy: self.tech_privacy, registrar_name: self.registrar_name, who_is_server: self.who_is_server, registrar_url: self.registrar_url, abuse_contact_email: self.abuse_contact_email, abuse_contact_phone: self.abuse_contact_phone, registry_domain_id: self.registry_domain_id, creation_date: self.creation_date, updated_date: self.updated_date, expiration_date: self.expiration_date, reseller: self.reseller, dns_sec: self.dns_sec, status_list: self.status_list, } } } } impl GetDomainDetailOutput { /// Creates a new builder-style object to manufacture [`GetDomainDetailOutput`](crate::output::GetDomainDetailOutput) pub fn builder() -> crate::output::get_domain_detail_output::Builder { crate::output::get_domain_detail_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetContactReachabilityStatusOutput { /// <p>The domain name for which you requested the reachability status.</p> pub domain_name: std::option::Option<std::string::String>, /// <p>Whether the registrant contact has responded. Values include the following:</p> /// <dl> /// <dt>PENDING</dt> /// <dd> /// <p>We sent the confirmation email and haven't received a response yet.</p> /// </dd> /// <dt>DONE</dt> /// <dd> /// <p>We sent the email and got confirmation from the registrant contact.</p> /// </dd> /// <dt>EXPIRED</dt> /// <dd> /// <p>The time limit expired before the registrant contact responded.</p> /// </dd> /// </dl> pub status: std::option::Option<crate::model::ReachabilityStatus>, } impl std::fmt::Debug for GetContactReachabilityStatusOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetContactReachabilityStatusOutput"); formatter.field("domain_name", &self.domain_name); formatter.field("status", &self.status); formatter.finish() } } /// See [`GetContactReachabilityStatusOutput`](crate::output::GetContactReachabilityStatusOutput) pub mod get_contact_reachability_status_output { /// A builder for [`GetContactReachabilityStatusOutput`](crate::output::GetContactReachabilityStatusOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain_name: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::ReachabilityStatus>, } impl Builder { /// <p>The domain name for which you requested the reachability status.</p> pub fn domain_name(mut self, input: impl Into<std::string::String>) -> Self { self.domain_name = Some(input.into()); self } pub fn set_domain_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_name = input; self } /// <p>Whether the registrant contact has responded. Values include the following:</p> /// <dl> /// <dt>PENDING</dt> /// <dd> /// <p>We sent the confirmation email and haven't received a response yet.</p> /// </dd> /// <dt>DONE</dt> /// <dd> /// <p>We sent the email and got confirmation from the registrant contact.</p> /// </dd> /// <dt>EXPIRED</dt> /// <dd> /// <p>The time limit expired before the registrant contact responded.</p> /// </dd> /// </dl> pub fn status(mut self, input: crate::model::ReachabilityStatus) -> Self { self.status = Some(input); self } pub fn set_status( mut self, input: std::option::Option<crate::model::ReachabilityStatus>, ) -> Self { self.status = input; self } /// Consumes the builder and constructs a [`GetContactReachabilityStatusOutput`](crate::output::GetContactReachabilityStatusOutput) pub fn build(self) -> crate::output::GetContactReachabilityStatusOutput { crate::output::GetContactReachabilityStatusOutput { domain_name: self.domain_name, status: self.status, } } } } impl GetContactReachabilityStatusOutput { /// Creates a new builder-style object to manufacture [`GetContactReachabilityStatusOutput`](crate::output::GetContactReachabilityStatusOutput) pub fn builder() -> crate::output::get_contact_reachability_status_output::Builder { crate::output::get_contact_reachability_status_output::Builder::default() } } /// <p>The EnableDomainTransferLock response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct EnableDomainTransferLockOutput { /// <p>Identifier for tracking the progress of the request. To use this ID to query the operation status, use GetOperationDetail.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for EnableDomainTransferLockOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("EnableDomainTransferLockOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`EnableDomainTransferLockOutput`](crate::output::EnableDomainTransferLockOutput) pub mod enable_domain_transfer_lock_output { /// A builder for [`EnableDomainTransferLockOutput`](crate::output::EnableDomainTransferLockOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To use this ID to query the operation status, use GetOperationDetail.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`EnableDomainTransferLockOutput`](crate::output::EnableDomainTransferLockOutput) pub fn build(self) -> crate::output::EnableDomainTransferLockOutput { crate::output::EnableDomainTransferLockOutput { operation_id: self.operation_id, } } } } impl EnableDomainTransferLockOutput { /// Creates a new builder-style object to manufacture [`EnableDomainTransferLockOutput`](crate::output::EnableDomainTransferLockOutput) pub fn builder() -> crate::output::enable_domain_transfer_lock_output::Builder { crate::output::enable_domain_transfer_lock_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct EnableDomainAutoRenewOutput {} impl std::fmt::Debug for EnableDomainAutoRenewOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("EnableDomainAutoRenewOutput"); formatter.finish() } } /// See [`EnableDomainAutoRenewOutput`](crate::output::EnableDomainAutoRenewOutput) pub mod enable_domain_auto_renew_output { /// A builder for [`EnableDomainAutoRenewOutput`](crate::output::EnableDomainAutoRenewOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`EnableDomainAutoRenewOutput`](crate::output::EnableDomainAutoRenewOutput) pub fn build(self) -> crate::output::EnableDomainAutoRenewOutput { crate::output::EnableDomainAutoRenewOutput {} } } } impl EnableDomainAutoRenewOutput { /// Creates a new builder-style object to manufacture [`EnableDomainAutoRenewOutput`](crate::output::EnableDomainAutoRenewOutput) pub fn builder() -> crate::output::enable_domain_auto_renew_output::Builder { crate::output::enable_domain_auto_renew_output::Builder::default() } } /// <p>The DisableDomainTransferLock response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisableDomainTransferLockOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for DisableDomainTransferLockOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisableDomainTransferLockOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`DisableDomainTransferLockOutput`](crate::output::DisableDomainTransferLockOutput) pub mod disable_domain_transfer_lock_output { /// A builder for [`DisableDomainTransferLockOutput`](crate::output::DisableDomainTransferLockOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`DisableDomainTransferLockOutput`](crate::output::DisableDomainTransferLockOutput) pub fn build(self) -> crate::output::DisableDomainTransferLockOutput { crate::output::DisableDomainTransferLockOutput { operation_id: self.operation_id, } } } } impl DisableDomainTransferLockOutput { /// Creates a new builder-style object to manufacture [`DisableDomainTransferLockOutput`](crate::output::DisableDomainTransferLockOutput) pub fn builder() -> crate::output::disable_domain_transfer_lock_output::Builder { crate::output::disable_domain_transfer_lock_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisableDomainAutoRenewOutput {} impl std::fmt::Debug for DisableDomainAutoRenewOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisableDomainAutoRenewOutput"); formatter.finish() } } /// See [`DisableDomainAutoRenewOutput`](crate::output::DisableDomainAutoRenewOutput) pub mod disable_domain_auto_renew_output { /// A builder for [`DisableDomainAutoRenewOutput`](crate::output::DisableDomainAutoRenewOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`DisableDomainAutoRenewOutput`](crate::output::DisableDomainAutoRenewOutput) pub fn build(self) -> crate::output::DisableDomainAutoRenewOutput { crate::output::DisableDomainAutoRenewOutput {} } } } impl DisableDomainAutoRenewOutput { /// Creates a new builder-style object to manufacture [`DisableDomainAutoRenewOutput`](crate::output::DisableDomainAutoRenewOutput) pub fn builder() -> crate::output::disable_domain_auto_renew_output::Builder { crate::output::disable_domain_auto_renew_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteTagsForDomainOutput {} impl std::fmt::Debug for DeleteTagsForDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteTagsForDomainOutput"); formatter.finish() } } /// See [`DeleteTagsForDomainOutput`](crate::output::DeleteTagsForDomainOutput) pub mod delete_tags_for_domain_output { /// A builder for [`DeleteTagsForDomainOutput`](crate::output::DeleteTagsForDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`DeleteTagsForDomainOutput`](crate::output::DeleteTagsForDomainOutput) pub fn build(self) -> crate::output::DeleteTagsForDomainOutput { crate::output::DeleteTagsForDomainOutput {} } } } impl DeleteTagsForDomainOutput { /// Creates a new builder-style object to manufacture [`DeleteTagsForDomainOutput`](crate::output::DeleteTagsForDomainOutput) pub fn builder() -> crate::output::delete_tags_for_domain_output::Builder { crate::output::delete_tags_for_domain_output::Builder::default() } } /// <p>The CheckDomainTransferability response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CheckDomainTransferabilityOutput { /// <p>A complex type that contains information about whether the specified domain can be transferred to Route 53.</p> pub transferability: std::option::Option<crate::model::DomainTransferability>, } impl std::fmt::Debug for CheckDomainTransferabilityOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CheckDomainTransferabilityOutput"); formatter.field("transferability", &self.transferability); formatter.finish() } } /// See [`CheckDomainTransferabilityOutput`](crate::output::CheckDomainTransferabilityOutput) pub mod check_domain_transferability_output { /// A builder for [`CheckDomainTransferabilityOutput`](crate::output::CheckDomainTransferabilityOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) transferability: std::option::Option<crate::model::DomainTransferability>, } impl Builder { /// <p>A complex type that contains information about whether the specified domain can be transferred to Route 53.</p> pub fn transferability(mut self, input: crate::model::DomainTransferability) -> Self { self.transferability = Some(input); self } pub fn set_transferability( mut self, input: std::option::Option<crate::model::DomainTransferability>, ) -> Self { self.transferability = input; self } /// Consumes the builder and constructs a [`CheckDomainTransferabilityOutput`](crate::output::CheckDomainTransferabilityOutput) pub fn build(self) -> crate::output::CheckDomainTransferabilityOutput { crate::output::CheckDomainTransferabilityOutput { transferability: self.transferability, } } } } impl CheckDomainTransferabilityOutput { /// Creates a new builder-style object to manufacture [`CheckDomainTransferabilityOutput`](crate::output::CheckDomainTransferabilityOutput) pub fn builder() -> crate::output::check_domain_transferability_output::Builder { crate::output::check_domain_transferability_output::Builder::default() } } /// <p>The CheckDomainAvailability response includes the following elements.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CheckDomainAvailabilityOutput { /// <p>Whether the domain name is available for registering.</p> /// <note> /// <p>You can register only domains designated as <code>AVAILABLE</code>.</p> /// </note> /// <p>Valid values:</p> /// <dl> /// <dt>AVAILABLE</dt> /// <dd> /// <p>The domain name is available.</p> /// </dd> /// <dt>AVAILABLE_RESERVED</dt> /// <dd> /// <p>The domain name is reserved under specific conditions.</p> /// </dd> /// <dt>AVAILABLE_PREORDER</dt> /// <dd> /// <p>The domain name is available and can be preordered.</p> /// </dd> /// <dt>DONT_KNOW</dt> /// <dd> /// <p>The TLD registry didn't reply with a definitive answer about whether the domain name is available. /// Route 53 can return this response for a variety of reasons, for example, the registry is performing maintenance. /// Try again later.</p> /// </dd> /// <dt>PENDING</dt> /// <dd> /// <p>The TLD registry didn't return a response in the expected amount of time. When the response is delayed, /// it usually takes just a few extra seconds. You can resubmit the request immediately.</p> /// </dd> /// <dt>RESERVED</dt> /// <dd> /// <p>The domain name has been reserved for another person or organization.</p> /// </dd> /// <dt>UNAVAILABLE</dt> /// <dd> /// <p>The domain name is not available.</p> /// </dd> /// <dt>UNAVAILABLE_PREMIUM</dt> /// <dd> /// <p>The domain name is not available.</p> /// </dd> /// <dt>UNAVAILABLE_RESTRICTED</dt> /// <dd> /// <p>The domain name is forbidden.</p> /// </dd> /// </dl> pub availability: std::option::Option<crate::model::DomainAvailability>, } impl std::fmt::Debug for CheckDomainAvailabilityOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CheckDomainAvailabilityOutput"); formatter.field("availability", &self.availability); formatter.finish() } } /// See [`CheckDomainAvailabilityOutput`](crate::output::CheckDomainAvailabilityOutput) pub mod check_domain_availability_output { /// A builder for [`CheckDomainAvailabilityOutput`](crate::output::CheckDomainAvailabilityOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) availability: std::option::Option<crate::model::DomainAvailability>, } impl Builder { /// <p>Whether the domain name is available for registering.</p> /// <note> /// <p>You can register only domains designated as <code>AVAILABLE</code>.</p> /// </note> /// <p>Valid values:</p> /// <dl> /// <dt>AVAILABLE</dt> /// <dd> /// <p>The domain name is available.</p> /// </dd> /// <dt>AVAILABLE_RESERVED</dt> /// <dd> /// <p>The domain name is reserved under specific conditions.</p> /// </dd> /// <dt>AVAILABLE_PREORDER</dt> /// <dd> /// <p>The domain name is available and can be preordered.</p> /// </dd> /// <dt>DONT_KNOW</dt> /// <dd> /// <p>The TLD registry didn't reply with a definitive answer about whether the domain name is available. /// Route 53 can return this response for a variety of reasons, for example, the registry is performing maintenance. /// Try again later.</p> /// </dd> /// <dt>PENDING</dt> /// <dd> /// <p>The TLD registry didn't return a response in the expected amount of time. When the response is delayed, /// it usually takes just a few extra seconds. You can resubmit the request immediately.</p> /// </dd> /// <dt>RESERVED</dt> /// <dd> /// <p>The domain name has been reserved for another person or organization.</p> /// </dd> /// <dt>UNAVAILABLE</dt> /// <dd> /// <p>The domain name is not available.</p> /// </dd> /// <dt>UNAVAILABLE_PREMIUM</dt> /// <dd> /// <p>The domain name is not available.</p> /// </dd> /// <dt>UNAVAILABLE_RESTRICTED</dt> /// <dd> /// <p>The domain name is forbidden.</p> /// </dd> /// </dl> pub fn availability(mut self, input: crate::model::DomainAvailability) -> Self { self.availability = Some(input); self } pub fn set_availability( mut self, input: std::option::Option<crate::model::DomainAvailability>, ) -> Self { self.availability = input; self } /// Consumes the builder and constructs a [`CheckDomainAvailabilityOutput`](crate::output::CheckDomainAvailabilityOutput) pub fn build(self) -> crate::output::CheckDomainAvailabilityOutput { crate::output::CheckDomainAvailabilityOutput { availability: self.availability, } } } } impl CheckDomainAvailabilityOutput { /// Creates a new builder-style object to manufacture [`CheckDomainAvailabilityOutput`](crate::output::CheckDomainAvailabilityOutput) pub fn builder() -> crate::output::check_domain_availability_output::Builder { crate::output::check_domain_availability_output::Builder::default() } } /// <p>The <code>CancelDomainTransferToAnotherAwsAccount</code> response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CancelDomainTransferToAnotherAwsAccountOutput { /// <p>The identifier that <code>TransferDomainToAnotherAwsAccount</code> returned to track the progress of the request. /// Because the transfer request was canceled, the value is no longer valid, and you can't use <code>GetOperationDetail</code> /// to query the operation status.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for CancelDomainTransferToAnotherAwsAccountOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CancelDomainTransferToAnotherAwsAccountOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`CancelDomainTransferToAnotherAwsAccountOutput`](crate::output::CancelDomainTransferToAnotherAwsAccountOutput) pub mod cancel_domain_transfer_to_another_aws_account_output { /// A builder for [`CancelDomainTransferToAnotherAwsAccountOutput`](crate::output::CancelDomainTransferToAnotherAwsAccountOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The identifier that <code>TransferDomainToAnotherAwsAccount</code> returned to track the progress of the request. /// Because the transfer request was canceled, the value is no longer valid, and you can't use <code>GetOperationDetail</code> /// to query the operation status.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`CancelDomainTransferToAnotherAwsAccountOutput`](crate::output::CancelDomainTransferToAnotherAwsAccountOutput) pub fn build(self) -> crate::output::CancelDomainTransferToAnotherAwsAccountOutput { crate::output::CancelDomainTransferToAnotherAwsAccountOutput { operation_id: self.operation_id, } } } } impl CancelDomainTransferToAnotherAwsAccountOutput { /// Creates a new builder-style object to manufacture [`CancelDomainTransferToAnotherAwsAccountOutput`](crate::output::CancelDomainTransferToAnotherAwsAccountOutput) pub fn builder() -> crate::output::cancel_domain_transfer_to_another_aws_account_output::Builder { crate::output::cancel_domain_transfer_to_another_aws_account_output::Builder::default() } } /// <p>The AcceptDomainTransferFromAnotherAwsAccount response includes the following element.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AcceptDomainTransferFromAnotherAwsAccountOutput { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub operation_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for AcceptDomainTransferFromAnotherAwsAccountOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("AcceptDomainTransferFromAnotherAwsAccountOutput"); formatter.field("operation_id", &self.operation_id); formatter.finish() } } /// See [`AcceptDomainTransferFromAnotherAwsAccountOutput`](crate::output::AcceptDomainTransferFromAnotherAwsAccountOutput) pub mod accept_domain_transfer_from_another_aws_account_output { /// A builder for [`AcceptDomainTransferFromAnotherAwsAccountOutput`](crate::output::AcceptDomainTransferFromAnotherAwsAccountOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) operation_id: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for tracking the progress of the request. To query the operation status, use /// <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>.</p> pub fn operation_id(mut self, input: impl Into<std::string::String>) -> Self { self.operation_id = Some(input.into()); self } pub fn set_operation_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.operation_id = input; self } /// Consumes the builder and constructs a [`AcceptDomainTransferFromAnotherAwsAccountOutput`](crate::output::AcceptDomainTransferFromAnotherAwsAccountOutput) pub fn build(self) -> crate::output::AcceptDomainTransferFromAnotherAwsAccountOutput { crate::output::AcceptDomainTransferFromAnotherAwsAccountOutput { operation_id: self.operation_id, } } } } impl AcceptDomainTransferFromAnotherAwsAccountOutput { /// Creates a new builder-style object to manufacture [`AcceptDomainTransferFromAnotherAwsAccountOutput`](crate::output::AcceptDomainTransferFromAnotherAwsAccountOutput) pub fn builder( ) -> crate::output::accept_domain_transfer_from_another_aws_account_output::Builder { crate::output::accept_domain_transfer_from_another_aws_account_output::Builder::default() } }
true
1c03fd590aba17a0122bea6488e57eb82f6b1cae
Rust
rust-lang/rust
/tests/rustdoc/empty-impl-block-private.rs
UTF-8
831
2.9375
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
#![feature(inherent_associated_types)] #![allow(incomplete_features)] #![crate_name = "foo"] // @has 'foo/struct.Foo.html' pub struct Foo; // There are 3 impl blocks with public item and one that should not be displayed // because it only contains private items. // @count - '//*[@class="impl"]' 'impl Foo' 3 // Impl block only containing private items should not be displayed. /// Private impl Foo { const BAR: u32 = 0; type FOO = i32; fn hello() {} } // But if any element of the impl block is public, it should be displayed. /// Not private impl Foo { pub const BAR: u32 = 0; type FOO = i32; fn hello() {} } /// Not private impl Foo { const BAR: u32 = 0; pub type FOO = i32; fn hello() {} } /// Not private impl Foo { const BAR: u32 = 0; type FOO = i32; pub fn hello() {} }
true
264f55c049f71f069b75fb6e66b54f90bc380226
Rust
vinca-rosea/RayTracingInOneWeekend
/src/material.rs
UTF-8
3,215
2.90625
3
[]
no_license
use super::*; pub fn schlick(cosine: f64, ref_idx: f64) -> f64 { let mut r0 = (1.0 - ref_idx) / (1.0 + ref_idx); r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - cosine).powi(5) } pub trait Material { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool; } pub struct Lambertian { pub albedo: Vec3, } impl Lambertian { pub fn new(albedo: Vec3) -> Self { Lambertian { albedo } } } impl Material for Lambertian { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { let scatter_direction = &rec.normal + &random_unit_vector(); let new_scattered = Ray::new(rec.p.clone(), scatter_direction, Default::default()); scattered.assign(&new_scattered); attenuation.assign(&self.albedo); true } } pub struct Metal { pub albedo: Vec3, pub fuzz: f64, } impl Metal { pub fn new(albedo: Vec3, fuzz: f64) -> Self { Metal { albedo, fuzz: if fuzz < 1.0 { fuzz } else { 1.0 }, } } } impl Material for Metal { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { let reflected = reflect(&unit_vector(r_in.direction()), &rec.normal); let new_scattered = Ray::new( rec.p.clone(), &reflected + &(self.fuzz * &random_in_unit_sphere()), Default::default(), ); scattered.assign(&new_scattered); attenuation.assign(&self.albedo); dot(scattered.direction(), &rec.normal) > 0.0 } } pub struct Dielectric { pub ref_idx: f64, } impl Dielectric { pub fn new(ref_idx: f64) -> Self { Self { ref_idx } } } impl Material for Dielectric { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { attenuation.assign(&Color::new(1.0, 1.0, 1.0)); let etai_over_etat = if rec.front_face { 1.0 / self.ref_idx } else { self.ref_idx }; let unit_direction = unit_vector(r_in.direction()); let cos_theta = dot(&-&unit_direction, &rec.normal).min(1.0); let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); if (etai_over_etat * sin_theta > 1.0) || (random_double() < schlick(cos_theta, etai_over_etat)) { let reflected = reflect(&unit_direction, &rec.normal); scattered.assign(&Ray::new(rec.p.clone(), reflected, Default::default())); return true; } let refracted = refract(&unit_direction, &rec.normal, etai_over_etat); scattered.assign(&Ray::new(rec.p.clone(), refracted, Default::default())); true } } pub struct UninitMaterial {} impl Material for UninitMaterial { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { false } }
true
7e1426700fc751626f5229ae5b4d7e54e1d82331
Rust
OTL/kiss3d
/src/post_processing/sobel_edge_highlight.rs
UTF-8
5,781
2.640625
3
[ "BSD-2-Clause" ]
permissive
//! A post-processing effect to highlight edges. use gl; use gl::types::*; use na::Vector2; use resource::{BufferType, AllocationType, Shader, ShaderUniform, ShaderAttribute, RenderTarget, GPUVec}; use post_processing::post_processing_effect::PostProcessingEffect; #[path = "../error.rs"] mod error; /// Post processing effect which turns everything in grayscales. pub struct SobelEdgeHighlight { shiftx: f32, shifty: f32, zn: f32, zf: f32, threshold: f32, shader: Shader, gl_nx: ShaderUniform<GLfloat>, gl_ny: ShaderUniform<GLfloat>, gl_fbo_depth: ShaderUniform<GLint>, gl_fbo_texture: ShaderUniform<GLint>, gl_znear: ShaderUniform<GLfloat>, gl_zfar: ShaderUniform<GLfloat>, gl_threshold: ShaderUniform<GLfloat>, gl_v_coord: ShaderAttribute<Vector2<f32>>, gl_fbo_vertices: GPUVec<Vector2<f32>> } impl SobelEdgeHighlight { /// Creates a new SobelEdgeHighlight post processing effect. pub fn new(threshold: f32) -> SobelEdgeHighlight { let fbo_vertices: Vec<Vector2<GLfloat>> = vec!( Vector2::new(-1.0, -1.0), Vector2::new(1.0, -1.0), Vector2::new(-1.0, 1.0), Vector2::new(1.0, 1.0)); let mut fbo_vertices = GPUVec::new(fbo_vertices, BufferType::Array, AllocationType::StaticDraw); fbo_vertices.load_to_gpu(); fbo_vertices.unload_from_ram(); let mut shader = Shader::new_from_str(VERTEX_SHADER, FRAGMENT_SHADER); shader.use_program(); SobelEdgeHighlight { shiftx: 0.0, shifty: 0.0, zn: 0.0, zf: 0.0, threshold: threshold, gl_nx: shader.get_uniform("nx").unwrap(), gl_ny: shader.get_uniform("ny").unwrap(), gl_fbo_depth: shader.get_uniform("fbo_depth").unwrap(), gl_fbo_texture: shader.get_uniform("fbo_texture").unwrap(), gl_znear: shader.get_uniform("znear").unwrap(), gl_zfar: shader.get_uniform("zfar").unwrap(), gl_threshold: shader.get_uniform("threshold").unwrap(), gl_v_coord: shader.get_attrib("v_coord").unwrap(), gl_fbo_vertices: fbo_vertices, shader: shader, } } } impl PostProcessingEffect for SobelEdgeHighlight { fn update(&mut self, _: f32, w: f32, h: f32, znear: f32, zfar: f32) { self.shiftx = 2.0 / w; self.shifty = 2.0 / h; self.zn = znear; self.zf = zfar; } fn draw(&mut self, target: &RenderTarget) { self.gl_v_coord.enable(); /* * Finalize draw */ verify!(gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT)); self.shader.use_program(); self.gl_threshold.upload(&self.threshold); self.gl_nx.upload(&self.shiftx); self.gl_ny.upload(&self.shifty); self.gl_znear.upload(&self.zn); self.gl_zfar.upload(&self.zf); verify!(gl::ActiveTexture(gl::TEXTURE0)); verify!(gl::BindTexture(gl::TEXTURE_2D, target.texture_id())); self.gl_fbo_texture.upload(&0); verify!(gl::ActiveTexture(gl::TEXTURE1)); verify!(gl::BindTexture(gl::TEXTURE_2D, target.depth_id())); self.gl_fbo_depth.upload(&1); self.gl_v_coord.bind(&mut self.gl_fbo_vertices); verify!(gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4)); self.gl_v_coord.disable(); } } static VERTEX_SHADER: &'static str = "#version 120 attribute vec2 v_coord; uniform sampler2D fbo_depth; uniform sampler2D fbo_texture; uniform float nx; uniform float ny; uniform float znear; uniform float zfar; uniform float threshold; varying vec2 f_texcoord; void main(void) { gl_Position = vec4(v_coord, 0.0, 1.0); f_texcoord = (v_coord + 1.0) / 2.0; }"; static FRAGMENT_SHADER: &'static str = "#version 120 uniform sampler2D fbo_depth; uniform sampler2D fbo_texture; uniform float nx; uniform float ny; uniform float znear; uniform float zfar; uniform float threshold; varying vec2 f_texcoord; float lin_depth(vec2 uv) { float nlin_depth = texture2D(fbo_depth, uv).x; return znear * zfar / ((nlin_depth * (zfar - znear)) - zfar); } void main(void) { vec2 texcoord = f_texcoord; float KX[9] = float[](1, 0, -1, 2, 0, -2, 1, 0, -1); float gx = 0; for (int i = -1; i < 2; ++i) { for (int j = -1; j < 2; ++j) { int off = (i + 1) * 3 + j + 1; gx += KX[off] * lin_depth(vec2(f_texcoord.x + i * nx, f_texcoord.y + j * ny)); } } float KY[9] = float[](1, 2, 1, 0, 0, 0, -1, -2, -1); float gy = 0; for (int i = -1; i < 2; ++i) { for (int j = -1; j < 2; ++j) { int off = (i + 1) * 3 + j + 1; gy += KY[off] * lin_depth(vec2(f_texcoord.x + i * nx, f_texcoord.y + j * ny)); } } float gradient = sqrt(gx * gx + gy * gy); float edge; if (gradient > threshold) { edge = 0.0; } else { edge = 1.0 - gradient / threshold; } vec4 color = texture2D(fbo_texture, texcoord); gl_FragColor = vec4(edge * color.xyz, 1.0); }";
true
99db814a206d583c4584360c979bf96f75ba86fe
Rust
aylei/leetcode-rust
/src/solution/s0077_combinations.rs
UTF-8
1,751
3.625
4
[ "Apache-2.0" ]
permissive
/** * [77] Combinations * * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. * * Example: * * * Input: n = 4, k = 2 * Output: * [ * [2,4], * [3,4], * [2,3], * [1,2], * [1,3], * [1,4], * ] * * */ pub struct Solution {} // problem: https://leetcode.com/problems/combinations/ // discuss: https://leetcode.com/problems/combinations/discuss/?currentPage=1&orderBy=most_votes&query= // submission codes start here impl Solution { pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> { let mut res: Vec<Vec<i32>> = Vec::new(); Solution::backtrack(1, n, k, vec![], &mut res); res } fn backtrack(start: i32, end: i32, k: i32, curr: Vec<i32>, result: &mut Vec<Vec<i32>>) { if k < 1 { result.push(curr); return; } if end - start + 1 < k { // elements is not enough, return quickly return; } for i in start..end + 1 { let mut vec = curr.clone(); vec.push(i); Solution::backtrack(i + 1, end, k - 1, vec, result); } } } // submission codes end #[cfg(test)] mod tests { use super::*; #[test] fn test_77() { assert_eq!( Solution::combine(4, 2), vec![ vec![1, 2], vec![1, 3], vec![1, 4], vec![2, 3], vec![2, 4], vec![3, 4] ] ); assert_eq!(Solution::combine(1, 1), vec![vec![1]]); let empty: Vec<Vec<i32>> = vec![]; assert_eq!(Solution::combine(0, 1), empty); assert_eq!(Solution::combine(2, 1), vec![vec![1], vec![2]]); } }
true
94fc9ea06cca3e1e99d9e39610efcc7b95f0cc05
Rust
TheBlueHeron/The-Rust-Book
/smart_pointers/src/main.rs
UTF-8
4,834
3.65625
4
[ "Unlicense" ]
permissive
use crate::List::{Cons, Nil}; use crate::MultiOwnerList::{Cns, Nl}; use std::cell::RefCell; use std::ops::Deref; use std::rc::Rc; use std::rc::Weak; fn main() { let b = Box::new(5); // 5 is stored on the heap; the box (pointer) data is stored on the stack // box implements only Deref trait and Drop trait and only provides indirection and heap allocation println!("b = {}", b); // recursive list using box 'indirection' to get a recursive type with known size let _list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); let x = 5; let y = &x; assert_eq!(5, x); assert_eq!(5, *y); // use dereferencing to follow pointer to value; works on boxes too let x = 5; let y = MyBox::new(x); assert_eq!(5, x); assert_eq!(5, *y); // dereferencing possible, because Deref trait is implemented let m = MyBox::new(String::from("Rust")); hello(&m); // deref coercion also works! hello(&(*m)[..]); // syntax without deref coercion! let c = CustomSmartPointer { data: String::from("my stuff"), }; //c.drop(); // not allowed drop(c); // std::mem::drop(_x: T) let d = CustomSmartPointer { data: String::from("other stuff"), }; println!("CustomSmartPointers created."); // Using Rc<T> to Share Data let a = Rc::new(Cns(5, Rc::new(Cns(10, Rc::new(Nl))))); println!("count after creating a = {}", Rc::strong_count(&a)); let b = Cns(3, Rc::clone(&a)); // no deep clone is made, only reference count is increased println!("count after creating b = {}", Rc::strong_count(&a)); { let c = Cns(4, Rc::clone(&a)); // b and c share ownership of a, but immutably! println!("count after creating c = {}", Rc::strong_count(&a)); } println!("count after c goes out of scope = {}", Rc::strong_count(&a)); // Interior Mutability: A Mutable Borrow to an Immutable Value // see lib.rs // Using Weak<T> to prevent reference cycles and memory leaks let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), }); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); println!("leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf)); { let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]), // the Node in leaf now has two owners: leaf and branch }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); // use weak reference to branch as parent for leaf println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); // The lack of infinite output here indicates that this code doesn’t create a reference cycle println!("branch strong = {}, weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch)); // leaf.parent has a weak reference to branch println!("leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf)); // branch has a strong reference stored in branche.children, so strong count = 2 } // branch node is dropped here, because the weak count of 1 from leaf.parent has no bearing on whether or not Node is dropped -> no memory leaks! println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); // The parent is now None again println!("leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf)); } // Cons list definition -> won't compile because of infinite size enum List { // Cons(i32, List), // recursive variant with undeterminable size Cons(i32, Box<List>), // recursive variant with determinable size (size = i32 size + size of pointer to boxed item on the heap, i.e. a usize) Nil, // the non-recursive variant that signals the end of the list } enum MultiOwnerList { Cns(i32, Rc<MultiOwnerList>), Nl, } struct MyBox<T>(T); // MyBox is a tuple struct with one element of type T impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; // defines an associated type for the Deref trait to use (see Chapter 19 Advanced Features) fn deref(&self) -> &Self::Target { &self.0 // return a reference to the value we want to access with the * operator; no move takes place } } fn hello(name: &str) { println!("Hello, {}!", name); } struct CustomSmartPointer { data: String, } impl Drop for CustomSmartPointer { fn drop(&mut self) { println!("Dropping CustomSmartPointer with data `{}`!", self.data); } } #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>>, // internally mutable collection of nodes that can have multiple ownership }
true
0e7933216094497d70292335a7e7c83c665173e8
Rust
leudz/shipyard
/src/borrow/non_send_sync.rs
UTF-8
691
2.703125
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use core::convert::{AsMut, AsRef}; use core::ops::{Deref, DerefMut}; /// Type used to access `!Send + !Sync` storages. #[cfg_attr(docsrs, doc(cfg(feature = "thread_local")))] pub struct NonSendSync<T: ?Sized>(pub(crate) T); impl<T: ?Sized> AsRef<T> for NonSendSync<T> { fn as_ref(&self) -> &T { &self.0 } } impl<T: ?Sized> AsMut<T> for NonSendSync<T> { fn as_mut(&mut self) -> &mut T { &mut self.0 } } impl<T: ?Sized> Deref for NonSendSync<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T: ?Sized> DerefMut for NonSendSync<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
true
02b1322a689a3d3a1da05e68fdaf9343bc56834a
Rust
awsdocs/aws-doc-sdk-examples
/rust_dev_preview/examples/dynamodb/src/scenario/movies/startup.rs
UTF-8
5,771
2.78125
3
[ "Apache-2.0", "MIT" ]
permissive
use super::Movie; use crate::scenario::error::Error; use aws_sdk_dynamodb::{ operation::create_table::builders::CreateTableFluentBuilder, types::{ AttributeDefinition, KeySchemaElement, KeyType, ProvisionedThroughput, ScalarAttributeType, TableStatus, WriteRequest, }, Client, }; use futures::future::join_all; use std::{collections::HashMap, time::Duration}; use tracing::{debug, info, trace}; const CAPACITY: i64 = 10; #[tracing::instrument(level = "trace")] pub async fn initialize(client: &Client, table_name: &str) -> Result<(), Error> { info!("Initializing Movies DynamoDB in {table_name}"); if table_exists(client, table_name).await? { info!("Found existing table {table_name}"); } else { info!("Table does not exist, creating {table_name}"); create_table(client, table_name, "year", "title", CAPACITY) .send() .await?; await_table(client, table_name).await?; load_data(client, table_name).await?; } Ok(()) } #[tracing::instrument(level = "trace")] // Does table exist? // snippet-start:[dynamodb.rust.movies-does_table_exist] pub async fn table_exists(client: &Client, table: &str) -> Result<bool, Error> { debug!("Checking for table: {table}"); let table_list = client.list_tables().send().await; match table_list { Ok(list) => Ok(list.table_names().as_ref().unwrap().contains(&table.into())), Err(e) => Err(e.into()), } } // snippet-end:[dynamodb.rust.movies-does_table_exist] #[tracing::instrument(level = "trace")] // snippet-start:[dynamodb.rust.movies-create_table_request] pub fn create_table( client: &Client, table_name: &str, primary_key: &str, sort_key: &str, capacity: i64, ) -> CreateTableFluentBuilder { info!("Creating table: {table_name} with capacity {capacity} and key structure {primary_key}:{sort_key}"); client .create_table() .table_name(table_name) .key_schema( KeySchemaElement::builder() .attribute_name(primary_key) .key_type(KeyType::Hash) .build(), ) .attribute_definitions( AttributeDefinition::builder() .attribute_name(primary_key) .attribute_type(ScalarAttributeType::N) .build(), ) .key_schema( KeySchemaElement::builder() .attribute_name(sort_key) .key_type(KeyType::Range) .build(), ) .attribute_definitions( AttributeDefinition::builder() .attribute_name(sort_key) .attribute_type(ScalarAttributeType::S) .build(), ) .provisioned_throughput( ProvisionedThroughput::builder() .read_capacity_units(capacity) .write_capacity_units(capacity) .build(), ) } // snippet-end:[dynamodb.rust.movies-create_table_request] const TABLE_WAIT_POLLS: u64 = 6; const TABLE_WAIT_TIMEOUT: u64 = 5; // Takes about 30 seconds in my experience. pub async fn await_table(client: &Client, table_name: &str) -> Result<(), Error> { // TODO: Use an adaptive backoff retry, rather than a sleeping loop. for _ in 0..TABLE_WAIT_POLLS { debug!("Checking if table is ready: {table_name}"); if let Some(table) = client .describe_table() .table_name(table_name) .send() .await? .table() { if matches!(table.table_status, Some(TableStatus::Active)) { debug!("Table is ready"); return Ok(()); } else { debug!("Table is NOT ready") } } tokio::time::sleep(Duration::from_secs(TABLE_WAIT_TIMEOUT)).await; } Err(Error::table_not_ready(table_name)) } // Must be less than 26. const CHUNK_SIZE: usize = 25; pub async fn load_data(client: &Client, table_name: &str) -> Result<(), Error> { debug!("Loading data into table {table_name}"); let data: Vec<Movie> = serde_json::from_str(include_str!("../../../moviedata.json")) .expect("loading large movies dataset"); let data_size = data.len(); trace!("Loading {data_size} items in batches of {CHUNK_SIZE}"); let ops = data .iter() .map(|v| { WriteRequest::builder() .set_put_request(Some(v.into())) .build() }) .collect::<Vec<WriteRequest>>(); let batches = ops .chunks(CHUNK_SIZE) .map(|chunk| write_batch(client, table_name, chunk)); let batches_count = batches.len(); trace!("Awaiting batches, count: {batches_count}"); join_all(batches).await; Ok(()) } pub async fn write_batch( client: &Client, table_name: &str, ops: &[WriteRequest], ) -> Result<(), Error> { assert!( ops.len() <= 25, "Cannot write more than 25 items in a batch" ); let mut unprocessed = Some(HashMap::from([(table_name.to_string(), ops.to_vec())])); while unprocessed_count(unprocessed.as_ref(), table_name) > 0 { let count = unprocessed_count(unprocessed.as_ref(), table_name); trace!("Adding {count} unprocessed items"); unprocessed = client .batch_write_item() .set_request_items(unprocessed) .send() .await? .unprocessed_items; } Ok(()) } fn unprocessed_count( unprocessed: Option<&HashMap<String, Vec<WriteRequest>>>, table_name: &str, ) -> usize { unprocessed .map(|m| m.get(table_name).map(|v| v.len()).unwrap_or_default()) .unwrap_or_default() }
true
9fe7bdb7b4fbdeadddc32638f7b51637d7c49a07
Rust
Skgland/Response-Time-Analysis-for-Fixed-Priority-Servers
/rta-for-fps-lib/tests/consolidated_tests/server_tests.rs
UTF-8
1,232
2.6875
3
[]
no_license
use crate::rta_lib::curve::Curve; use crate::rta_lib::iterators::CurveIterator; use crate::rta_lib::server::{Server, ServerKind}; use crate::rta_lib::task::Task; use crate::rta_lib::time::TimeUnit; use crate::rta_lib::window::Window; #[test] fn deferrable_server() { // Example 6. with t = 18 let tasks = &[Task::new(1, 5, 0), Task::new(2, 8, 0)]; let server = Server::new( tasks, TimeUnit::from(2), TimeUnit::from(4), ServerKind::Deferrable, ); let result = server .constraint_demand_curve_iter() .take_while_curve(|window| window.end <= TimeUnit::from(18)) .normalize(); let expected_result = unsafe { // the example in the paper is confusing as // either (4,5) and (5,6) should not have been merged to (4,6) // or (15,16) and (16,18) should be merged to (15,18) // the latter is done here as it allows for the usage of a Curve Curve::from_windows_unchecked(vec![ Window::new(0, 2), Window::new(4, 6), Window::new(8, 10), Window::new(12, 13), Window::new(15, 18), ]) }; crate::util::assert_curve_eq(&expected_result, result); }
true
0becb1d001e88b1d3b97e4794135391372135ba7
Rust
jiyilanzhou/chw
/local_rust/learn_rust/44learn_box1/src/main.rs
UTF-8
2,764
3.421875
3
[]
no_license
/* // detect[dɪˈtekt]v.检测,探测 box 适用场景: (1)当有一个在编译时未知大小的类型,而又需要再确切大小的上下文中使用这个类型值的时候; (举例子:在一个 list 环境下,存放数据,但是每个元素的大小在编译时又不确定) (2)当有大量数据并希望在确保数据不被拷贝的情况下转移所有权的时候; (3)当希望拥有一个值并只关心它的类型是否实现了特定 trait 而不是其具体类型时。 */ use List::Cons; use List::Nil; /* //循环嵌套: enum List { Cons(i32, List), // 编译时未知 List 大小类型 Nil, } fn main() { / * 编译报错: 递归类型拥有无穷大小 error[E0072]: recursive type `List` has infinite size enum List { ^^^^^^^^^ recursive type has infinite size Cons(i32, List), ---- recursive without indirection = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `List` representable error[E0391]: cycle detected when processing `List` enum List { ^^^^^^^^^ = note: ...which again requires processing `List`,completing the cycle = note: cycle used when computing dropck types for `Canonical { max_universe: U0, variables: [], value: ParamEnvAnd { param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, def_id: None } , value: List } }` // 处理时检测到循环 List // detect[dɪˈtekt]v.检测,探测 * / let list = Cons(1, Cons(2, Cons(3, Nil))); } // 类比 C 语言中的定义如下: struct List { int value; struct List l; // 结构体无限循环嵌套 // struct List *next; }; */ /* 使用 Box<T> 智能指针解决无限循环问题: // 类比 C 语言中的如下定义: struct List { int value; // C 语言使用指针解决"结构体递归嵌套"问题 struct List *next; // 使用指针(占用空间大小一定) //struct List l; // 避免使用结构体无限循环嵌套 }; */ // Rust 使用 Box<T> 智能指针解决 List 无限循环问题: enum List { Cons(i32, Box<List>), Nil, } fn main() { // 使用 Box<T> 创建链表 let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); println!("Hello World!"); }
true
5d5af8c1378fd1d537bd13b332ea79550ab66f35
Rust
okuvshynov/hcl
/src/data/metric_parse.rs
UTF-8
798
3.546875
4
[ "MIT" ]
permissive
fn base<'a>(v: &'a str) -> &'a str { &v[0..v.len() - 1] } pub fn metric_parse(s: &str) -> Result<f64, std::num::ParseFloatError> { let s = s.trim(); let (exponent, mantissa) = match s.to_uppercase().chars().last() { Some('K') => (1.0e3, base(s)), Some('M') => (1.0e6, base(s)), Some('G') => (1.0e9, base(s)), Some('T') => (1.0e12, base(s)), _ => (1.0, s), }; mantissa.parse::<f64>().map(|m| m * exponent) } #[cfg(test)] mod tests { use super::*; #[test] fn metric_parse_test() { assert_eq!(1234.0, metric_parse("1.234k").unwrap()); assert_eq!(1234000.0, metric_parse("1.234M").unwrap()); assert_eq!(123.0, metric_parse("123").unwrap()); assert!(metric_parse("123OLOLOL").is_err()); } }
true
dfdf3480aa2100e981f5d0d954016d304df78774
Rust
efancier-cn/embedded-gui
/src/state/mod.rs
UTF-8
1,081
2.8125
3
[]
no_license
//! Visual state container. pub mod selection; pub trait StateGroup { const MASK: u32; } pub trait State { type Group: StateGroup; const VALUE: u32; } #[macro_export] macro_rules! state_group { ($([$group:ident: $mask:literal] = { $($state:ident = $value:literal),+ $(,)? })+) => { $( pub struct $group; impl $crate::state::StateGroup for $group { const MASK: u32 = $mask; } $( pub struct $state; impl $crate::state::State for $state { type Group = $group; const VALUE: u32 = $value; } )+ )+ }; } #[derive(Copy, Clone, Default)] pub struct WidgetState(u32); impl WidgetState { pub fn has_state<S: State>(self, _state: S) -> bool { self.0 & S::Group::MASK == S::VALUE } pub fn set_state<S: State>(&mut self, _state: S) -> bool { let old = self.0; self.0 = (self.0 & !S::Group::MASK) | S::VALUE; self.0 != old } }
true
482ed15bad3f077e7bbdf6aeb0c2e9b5e53a411f
Rust
lineCode/lyken
/gll/src/lib.rs
UTF-8
11,012
2.53125
3
[ "MIT", "Apache-2.0" ]
permissive
#![feature(conservative_impl_trait, decl_macro, from_ref, str_escape)] extern crate indexing; extern crate ordermap; use indexing::container_traits::Trustworthy; use indexing::{scope, Container}; use std::cmp::{Ordering, Reverse}; use std::collections::{BTreeSet, BinaryHeap, HashMap}; use std::fmt; use std::hash::{Hash, Hasher}; use std::io::{self, Write}; use std::ops::Deref; pub mod grammar; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Range<'id>(pub indexing::Range<'id>); impl<'id> Deref for Range<'id> { type Target = indexing::Range<'id>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'id> PartialOrd for Range<'id> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { (self.start(), self.end()).partial_cmp(&(other.start(), other.end())) } } impl<'id> Ord for Range<'id> { fn cmp(&self, other: &Self) -> Ordering { (self.start(), self.end()).cmp(&(other.start(), other.end())) } } impl<'id> Hash for Range<'id> { fn hash<H: Hasher>(&self, state: &mut H) { (self.start(), self.end()).hash(state); } } impl<'id> Range<'id> { pub fn subtract(self, other: Self) -> Self { assert_eq!(self.start(), other.start()); Range(self.split_at(other.len()).1) } } pub struct Parser<'id, L: Label, I> { pub input: Container<'id, I>, pub gss: CallGraph<'id, L>, pub sppf: ParseGraph<'id, L>, } pub struct Threads<'id, L: Label> { queue: BinaryHeap<Call<'id, (Continuation<'id, L>, Range<'id>)>>, seen: BTreeSet<Call<'id, (Continuation<'id, L>, Range<'id>)>>, } impl<'id, L: Label> Threads<'id, L> { pub fn spawn(&mut self, next: Continuation<'id, L>, result: Range<'id>, range: Range<'id>) { let t = Call { callee: (next, result), range, }; if self.seen.insert(t) { self.queue.push(t); } } pub fn steal(&mut self) -> Option<Call<'id, (Continuation<'id, L>, Range<'id>)>> { if let Some(t) = self.queue.pop() { loop { let old = self.seen.iter().rev().next().cloned(); if let Some(old) = old { // TODO also check end point for proper "t.range includes old.range". if !t.range.contains(old.range.start()).is_some() { self.seen.remove(&old); continue; } } break; } Some(t) } else { self.seen.clear(); None } } } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Continuation<'id, L: Label> { pub code: L, pub stack: Call<'id, L>, pub state: usize, } #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Call<'id, C> { pub callee: C, pub range: Range<'id>, } impl<'id, C: fmt::Display> fmt::Display for Call<'id, C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}({}..{})", self.callee, self.range.start(), self.range.end() ) } } impl<'id, C: PartialOrd> PartialOrd for Call<'id, C> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { (Reverse(self.range), &self.callee).partial_cmp(&(Reverse(other.range), &other.callee)) } } impl<'id, C: Ord> Ord for Call<'id, C> { fn cmp(&self, other: &Self) -> Ordering { (Reverse(self.range), &self.callee).cmp(&(Reverse(other.range), &other.callee)) } } pub struct CallGraph<'id, L: Label> { pub threads: Threads<'id, L>, returns: HashMap<Call<'id, L>, BTreeSet<Continuation<'id, L>>>, pub results: HashMap<Call<'id, L>, BTreeSet<Range<'id>>>, } impl<'id, L: Label> CallGraph<'id, L> { pub fn print(&self, out: &mut Write) -> io::Result<()> { writeln!(out, "digraph gss {{")?; writeln!(out, " graph [rankdir=RL]")?; for (source, returns) in &self.returns { for next in returns { writeln!( out, r#" "{}" -> "{}" [label="{}"]"#, source, next.stack, next.code )?; } } writeln!(out, "}}") } pub fn call(&mut self, call: Call<'id, L>, next: Continuation<'id, L>) { let returns = self.returns.entry(call).or_insert(BTreeSet::new()); if returns.insert(next) { if returns.len() > 1 { if let Some(results) = self.results.get(&call) { for &result in results { self.threads .spawn(next, result, call.range.subtract(result)); } } } else { let dummy = Range(call.range.frontiers().0); self.threads.spawn( Continuation { code: call.callee, stack: call, state: 0, }, dummy, call.range, ); } } } pub fn ret(&mut self, call: Call<'id, L>, result: Range<'id>) { if self.results .entry(call) .or_insert(BTreeSet::new()) .insert(result) { if let Some(returns) = self.returns.get(&call) { for &next in returns { self.threads .spawn(next, result, call.range.subtract(result)); } } } } } pub struct ParseGraph<'id, L: Label> { pub children: HashMap<ParseNode<'id, L>, BTreeSet<usize>>, } impl<'id, L: Label> ParseGraph<'id, L> { pub fn add(&mut self, l: L, range: Range<'id>, child: usize) { self.children .entry(ParseNode { l: Some(l), range }) .or_insert(BTreeSet::new()) .insert(child); } pub fn unary_children<'a>( &'a self, node: ParseNode<'id, L>, ) -> impl Iterator<Item = ParseNode<'id, L>> + 'a { match node.l.unwrap().kind() { LabelKind::Unary(l) => self.children[&node].iter().map(move |&i| { assert_eq!(i, 0); ParseNode { l, range: node.range, } }), _ => unreachable!(), } } pub fn binary_children<'a>( &'a self, node: ParseNode<'id, L>, ) -> impl Iterator<Item = (ParseNode<'id, L>, ParseNode<'id, L>)> + 'a { match node.l.unwrap().kind() { LabelKind::Binary(left_l, right_l) => self.children[&node].iter().map(move |&i| { let (left, right, _) = node.range.split_at(i); ( ParseNode { l: left_l, range: Range(left), }, ParseNode { l: right_l, range: Range(right), }, ) }), _ => unreachable!(), } } pub fn print(&self, out: &mut Write) -> io::Result<()> { writeln!(out, "digraph sppf {{")?; let mut p = 0; for (source, children) in &self.children { writeln!(out, r#" "{}" [shape=box]"#, source)?; match source.l.unwrap().kind() { LabelKind::Choice => for &child in children { let child = ParseNode { l: Some(L::from_usize(child)), range: source.range, }; writeln!(out, r#" p{} [label="" shape=point]"#, p)?; writeln!(out, r#" "{}" -> p{}:n"#, source, p)?; writeln!(out, r#" p{}:s -> "{}":n [dir=none]"#, p, child)?; p += 1; }, LabelKind::Unary(l) => for &child in children { assert_eq!(child, 0); let child = ParseNode { l, range: source.range, }; writeln!(out, r#" p{} [label="" shape=point]"#, p)?; writeln!(out, r#" "{}" -> p{}:n"#, source, p)?; writeln!(out, r#" p{}:s -> "{}":n [dir=none]"#, p, child)?; p += 1; }, LabelKind::Binary(left_l, right_l) => for &child in children { let (left, right, _) = source.range.split_at(child); let (left, right) = ( ParseNode { l: left_l, range: Range(left), }, ParseNode { l: right_l, range: Range(right), }, ); writeln!(out, r#" p{} [label="" shape=point]"#, p)?; writeln!(out, r#" "{}" -> p{}:n"#, source, p)?; writeln!(out, r#" p{}:sw -> "{}":n [dir=none]"#, p, left)?; writeln!(out, r#" p{}:se -> "{}":n [dir=none]"#, p, right)?; p += 1; }, } } writeln!(out, "}}") } } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ParseNode<'id, L: Label> { pub l: Option<L>, pub range: Range<'id>, } impl<'id, L: Label> ParseNode<'id, L> { pub fn terminal(range: Range<'id>) -> ParseNode<'id, L> { ParseNode { l: None, range } } } impl<'id, L: Label> fmt::Display for ParseNode<'id, L> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(l) = self.l { write!(f, "{} @ {}..{}", l, self.range.start(), self.range.end()) } else { write!(f, "{}..{}", self.range.start(), self.range.end()) } } } impl<'a, L: Label, I: Trustworthy> Parser<'a, L, I> { pub fn with<F, R>(input: I, f: F) -> R where F: for<'id> FnOnce(Parser<'id, L, I>) -> R, { scope(input, |input| { f(Parser { input, gss: CallGraph { threads: Threads { queue: BinaryHeap::new(), seen: BTreeSet::new(), }, returns: HashMap::new(), results: HashMap::new(), }, sppf: ParseGraph { children: HashMap::new(), }, }) }) } } pub enum LabelKind<L: Label> { Unary(Option<L>), Binary(Option<L>, Option<L>), Choice, } pub trait Label: fmt::Display + Ord + Hash + Copy + 'static { fn kind(self) -> LabelKind<Self>; fn from_usize(i: usize) -> Self; fn to_usize(self) -> usize; }
true
d032eb648f31bfeb65179bbd93cf660ea8e6063e
Rust
clinuxrulz/sodium-rust-demo
/core/src/math/cos.rs
UTF-8
264
2.859375
3
[]
no_license
pub trait Cos { type Output; fn cos(self) -> Self::Output; } impl Cos for f32 { type Output = f32; fn cos(self) -> f32 { self.cos() } } impl Cos for f64 { type Output = f64; fn cos(self) -> f64 { self.cos() } }
true
4f94075eacf5889d4eeb7180c76b4cf79d662a11
Rust
Symforian/University
/Rust/List_7/5.last_dig_huge/src/main.rs
UTF-8
1,549
3.53125
4
[]
no_license
fn last_digit(lst: &[u64]) -> u64 { fn trim_number(number: u128, base: u128) -> u128{ return if number < base { number } else { number % base + base } } if lst.len()==0 {return 1;} let first = *(lst.iter().last().unwrap()) as u128; let folded = lst.iter().clone().take(lst.len()-1).collect::<Vec<&u64>>().iter().skip(1).rev() .fold(first, |first, x| (trim_number(**x as u128, 20)).pow(trim_number(first,4) as u32)); (((lst[0]%10) as u128).pow(trim_number(folded,4) as u32)%10) as u64 } fn main() { println!("Last of 0^0 is: {:?} should be: 1",last_digit(&[0, 0])); } #[cfg(test)] mod tests { use super::last_digit; #[test] fn test1() { assert_eq!(last_digit(&[3,4,2]), 1); } #[test] fn test2() { assert_eq!(last_digit(&[1,2,3,4,5,6,7,8,9,10]), 1); } #[test] fn test3() { assert_eq!(last_digit(&[0, 0, 0]), 0); } #[test] fn test4() { assert_eq!(last_digit(&[7, 6, 21]), 1); } #[test] fn test5() { assert_eq!(last_digit(&[12, 30, 21]), 6); } #[test] fn test6() { assert_eq!(last_digit(&[937640, 767456, 981242]), 0); } #[test] fn test7() { assert_eq!(last_digit(&[123232, 694022, 140249]), 6); } #[test] fn test8() { assert_eq!(last_digit(&[2, 2, 101, 2]), 6); } #[test] fn test9() { assert_eq!(last_digit(&[2123, 212341, 101, 21231]), 3); } #[test] fn test10() { assert_eq!(last_digit(&[]), 1); } }
true
b3152fd5ddd2e0e9b76870c36b9b833ad03f6e59
Rust
JonasBak/imglang
/tests/heap_rc.rs
UTF-8
3,511
2.96875
3
[]
no_license
use imglang::*; fn run_script(input: &'static str) -> VM { let mut lexer = Lexer::new(&input.to_string()).unwrap(); let mut ast = parse(&mut lexer).unwrap(); TypeChecker::annotate_types(&mut ast, None).unwrap(); let chunks = Compiler::compile(&ast, None); let mut output: Vec<u8> = vec![]; let mut vm = VM::new(chunks, None); vm.run(&mut output); vm } #[test] fn count_objects_multiple_assignments() { let vm = run_script( r#" var a = "only object"; var b = a; var c = a; a = a = a = a = a; "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn count_objects_reassign() { let vm = run_script( r#" var a = "fist object"; var b = "second object"; a = b; "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn count_objects_nested_scopes() { let vm = run_script( r#" { var a = "heap 1"; var b = "heap 2"; { var c = "heap 3"; } a = b = a = b = a; } "#, ); assert_eq!(vm.heap_ptr().count_objects(), 0); } #[test] fn count_objects_shadowed_variables() { let vm = run_script( r#" var a = "heap 1"; { var b = "heap 2"; { var a = b; } } "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn count_objects_combined_scopes() { let vm = run_script( r#" var a = "outer"; { var b = "inner 1"; var c = "inner 2"; a = b; } "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn count_objects_expr_statements() { let vm = run_script( r#" var a = "outer"; "string literal"; a; "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn count_objects_function_return() { let vm = run_script( r#" fun returnString() str { var a = "string 1"; var b = "string 2"; var c = "string 3"; return "string 4"; } returnString(); returnString(); returnString(); returnString(); returnString(); returnString(); var a = returnString(); "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn count_objects_function_argument() { let vm = run_script( r#" fun stringArg(a str) { print a; } stringArg("string 1"); var a = "string 2"; stringArg(a); "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn count_objects_function_return_argument() { let vm = run_script( r#" fun stringArg(a str) str { var b = "some var"; return a; } var a = "string 2"; stringArg(a); var b = stringArg(a); a = stringArg(a); "#, ); assert_eq!(vm.heap_ptr().count_objects(), 1); } #[test] fn closure_variables_freed_correctly() { let vm = run_script( r#" { var a = 1; var b = 2; var closure = fun[a, b]() float { var c = 3; return a + b + c; }; var closure2 = closure; closure2(); } "#, ); assert_eq!(vm.heap_ptr().count_objects(), 0); }
true
577dc5e9d11c8d621d9eaabae53e43a815ea25ba
Rust
AndreasOM/ggj19
/src/fb.rs
UTF-8
1,858
3.046875
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#[derive(Debug)] pub struct FB { pub width: isize, pub height: isize, buffer: Vec<u32>, } impl FB { pub fn new( width: isize, height: isize ) -> FB { FB { width: width, height: height, buffer: vec![0; ( width * height ) as usize], } } pub fn buffer( &mut self ) -> &mut Vec<u32> { &mut self.buffer } pub fn mix( l: u32, r: u32, m: f32 ) -> u32 { let im = 1.0 - m; let lr = ( ( ( l >> 24 ) & 0xff ) as f32 * m ) as u32; let lg = ( ( ( l >> 16 ) & 0xff ) as f32 * m ) as u32; let lb = ( ( ( l >> 8 ) & 0xff ) as f32 * m ) as u32; let la = ( ( ( l >> 0 ) & 0xff ) as f32 * m ) as u32; let rr = ( ( ( r >> 24 ) & 0xff ) as f32 * im ) as u32; let rg = ( ( ( r >> 16 ) & 0xff ) as f32 * im ) as u32; let rb = ( ( ( r >> 8 ) & 0xff ) as f32 * im ) as u32; let ra = ( ( ( r >> 0 ) & 0xff ) as f32 * im ) as u32; ( ( lr + rr ) << 24 ) | ( ( lg + rg ) << 16 ) | ( ( lb + rb ) << 8 ) | ( ( la + ra ) << 0 ) } pub fn fill_rect( &mut self, sx: isize, sy: isize, ex: isize, ey: isize, col: u32 ) { let ex = if ex < self.width { ex } else { self.width }; let ey = if ey < self.height { ey } else { self.height }; for y in sy..ey { for x in sx..ex { let p = ( y * self.width + x ) as usize; self.buffer[ p ] = col; } } } pub fn blit_rect( &mut self, sx: isize, sy: isize, ex: isize, ey: isize, data: &Vec< u32 >, offset: isize, width: isize ) { let h = ey - sy; let w = ex - sx; let mut src = offset; let mut dst = self.width * sy + sx; // ARGB ! for y in 0..h { for x in 0..w { let fg = data[ src as usize ]; let a = ( ( fg >> 24 ) & 0xff ) as f32 / 255.0;// + 1; self.buffer[ dst as usize ] = FB::mix( fg, self.buffer[ dst as usize ], a ); src += 1; dst += 1; } src -= w; src += width; dst -= w; dst += self.width; } } }
true
484907de16d9ba751a92049a4da42dcd418977a8
Rust
statianzo/imposters
/src/ch06_datastructures/heap.rs
UTF-8
3,242
3.859375
4
[ "ISC" ]
permissive
use std::iter::FromIterator; use std::slice::Iter; pub struct Heap<T: PartialOrd> { elements: Vec<T>, } fn parent_index(index: usize) -> usize { (index - 1) / 2 } impl<T: PartialOrd> Heap<T> { pub fn new() -> Self { Heap { elements: Vec::new(), } } pub fn len(&self) -> usize { self.elements.len() } pub fn push(&mut self, item: T) { self.elements.push(item); let mut i = self.len() - 1; while i > 0 && self.elements[i] > self.elements[parent_index(i)] { self.elements.swap(i, parent_index(i)); i = parent_index(i) } } pub fn pop(&mut self) -> Option<T> { if self.len() > 0 { let result = self.elements.swap_remove(0); self.heapify(0); Some(result) } else { None } } fn heapify(&mut self, index: usize) { let mut largest = index; let left = 2 * index + 1; let right = 2 * index + 2; if left < self.len() && self.elements[left] > self.elements[largest] { largest = left } if right < self.len() && self.elements[right] > self.elements[largest] { largest = right } if largest != index { self.elements.swap(index, largest); self.heapify(index) } } pub fn iter(&self) -> Iter<T> { self.elements.iter() } } impl<T> FromIterator<T> for Heap<T> where T: PartialOrd, { fn from_iter<I: IntoIterator<Item = T>>(source: I) -> Self { let mut heap = Heap::new(); for i in source { heap.push(i) } heap } } #[cfg(test)] mod test { use super::Heap; #[test] fn test_new() { let heap: Heap<u32> = Heap::new(); assert_eq!(heap.len(), 0); } #[test] fn test_push() { let mut heap = Heap::new(); heap.push(5); assert_eq!(heap.len(), 1); } #[test] fn test_push_pop() { let mut heap = Heap::new(); heap.push(5); assert_eq!(heap.pop().unwrap(), 5); assert_eq!(heap.len(), 0); } #[test] fn test_priority() { let mut heap = Heap::new(); heap.push(5); heap.push(10); heap.push(7); heap.push(6); heap.push(3); heap.push(6); heap.push(7); heap.push(6); assert_eq!(heap.pop().unwrap(), 10); assert_eq!(heap.pop().unwrap(), 7); assert_eq!(heap.pop().unwrap(), 7); assert_eq!(heap.pop().unwrap(), 6); assert_eq!(heap.pop().unwrap(), 6); assert_eq!(heap.pop().unwrap(), 6); assert_eq!(heap.pop().unwrap(), 5); assert_eq!(heap.pop().unwrap(), 3); assert_eq!(heap.len(), 0); } #[test] fn test_from_iter() { let mut heap: Heap<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); assert_eq!(heap.len(), 10); assert_eq!(heap.pop().unwrap(), 10); } #[test] fn test_iter() { let heap: Heap<u32> = vec![1, 2, 3, 4, 5].into_iter().collect(); let result: u32 = heap.iter().sum(); assert_eq!(result, 15); } }
true
a85a7feb2901e7a383231796bdc96f812ad6d240
Rust
mambisi/edgekv
/src/schema.rs
UTF-8
6,226
3.140625
3
[]
no_license
use anyhow::Result; use std::io::{Read}; use crc32fast::Hasher; pub(crate) fn crc_checksum<P : AsRef<[u8]>>(payload : P) -> u32 { let mut hasher = Hasher::new(); hasher.update(payload.as_ref()); hasher.finalize() } #[derive(Debug, Clone, PartialOrd, PartialEq)] pub(crate) struct DataEntry { crc: u32, level: i64, key_size: u64, value_size: u64, key: Vec<u8>, value: Vec<u8>, } pub(crate) trait Encoder { fn encode(&self) -> Vec<u8>; } pub(crate) trait Decoder { fn decode<R: Read>(rdr: &mut R) -> Result<Self> where Self: Sized; } impl Encoder for DataEntry { fn encode(&self) -> Vec<u8> { let content = self.encode_content(); let crc = crc_checksum(&content); let mut buf = vec![]; buf.extend_from_slice(&crc.to_be_bytes()); buf.extend_from_slice(&content); return buf; } } impl Decoder for DataEntry { fn decode<R: Read>(rdr: &mut R) -> Result<Self> where Self: Sized { let mut out = Self { crc: 0, level: 0, key_size: 0, value_size: 0, key: vec![], value: vec![], }; let mut raw_crc_bytes = [0_u8; 4]; let mut raw_level_bytes = [0_u8; 8]; let mut raw_key_size_bytes = [0_u8; 8]; let mut raw_value_size_bytes = [0_u8; 8]; rdr.read_exact(&mut raw_crc_bytes)?; rdr.read_exact(&mut raw_level_bytes)?; rdr.read_exact(&mut raw_key_size_bytes)?; rdr.read_exact(&mut raw_value_size_bytes)?; out.crc = u32::from_be_bytes(raw_crc_bytes); out.level = i64::from_be_bytes(raw_level_bytes); out.key_size = u64::from_be_bytes(raw_key_size_bytes); out.value_size = u64::from_be_bytes(raw_value_size_bytes); let mut raw_key_bytes = vec![0_u8; out.key_size as usize]; let mut raw_value_bytes = vec![0_u8; out.value_size as usize]; rdr.read_exact(&mut raw_key_bytes); rdr.read_exact(&mut raw_value_bytes); out.key = raw_key_bytes; out.value = raw_value_bytes; Ok(out) } } impl DataEntry { pub(crate) fn new(level: i64, key: Vec<u8>, value: Vec<u8>) -> Self { let key_size = key.len() as u64; let value_size = value.len() as u64; Self { crc: 0, level, key_size, value_size, key, value, } } pub fn check_crc(&self) -> bool { self.crc == crc_checksum(&self.encode_content()) } fn encode_content(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend_from_slice(&self.level.to_be_bytes()); buf.extend_from_slice(&self.key_size.to_be_bytes()); buf.extend_from_slice(&self.value_size.to_be_bytes()); buf.extend_from_slice(&self.key); buf.extend_from_slice(&self.value); buf } pub(crate) fn key(&self) -> Vec<u8> { self.key.to_owned() } pub(crate) fn value(&self) -> Vec<u8> { self.value.to_owned() } } pub(crate) struct HintEntry { level: i64, key_size: u64, value_size: u64, data_entry_position: u64, key: Vec<u8>, } impl HintEntry { pub(crate) fn from(entry: &DataEntry, position: u64) -> Self { Self { level: entry.level, key_size: entry.key_size, value_size: entry.value_size, data_entry_position: position, key: entry.key.clone(), } } pub(crate) fn tombstone(key : Vec<u8>) -> Self { Self { level: -1, key_size: key.len() as u64, value_size: 0, data_entry_position: 0, key, } } pub(crate) fn data_entry_position(&self) -> u64 { self.data_entry_position } pub(crate) fn is_deleted(&self) -> bool { self.level < 0 && self.value_size == 0 && self.data_entry_position == 0 } pub(crate) fn key_size(&self) -> u64 { self.key_size } pub(crate) fn value_size(&self) -> u64 { self.value_size } pub(crate) fn level(&self) -> i64 { self.level } pub(crate) fn key(&self) -> Vec<u8> { self.key.to_owned() } } impl Encoder for HintEntry { fn encode(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend_from_slice(&self.level.to_be_bytes()); buf.extend_from_slice(&self.key_size.to_be_bytes()); buf.extend_from_slice(&self.value_size.to_be_bytes()); buf.extend_from_slice(&self.data_entry_position.to_be_bytes()); buf.extend_from_slice(&self.key); buf } } impl Decoder for HintEntry { fn decode<R: Read>(rdr: &mut R) -> Result<Self> where Self: Sized { let mut out = Self { level: 0, key_size: 0, value_size: 0, data_entry_position: 0, key: vec![], }; let mut raw_level_bytes = [0_u8; 8]; let mut raw_key_size_bytes = [0_u8; 8]; let mut raw_value_size_bytes = [0_u8; 8]; let mut raw_data_entry_pos_size_bytes = [0_u8; 8]; rdr.read_exact(&mut raw_level_bytes)?; rdr.read_exact(&mut raw_key_size_bytes)?; rdr.read_exact(&mut raw_value_size_bytes)?; rdr.read_exact(&mut raw_data_entry_pos_size_bytes)?; out.level = i64::from_be_bytes(raw_level_bytes); out.key_size = u64::from_be_bytes(raw_key_size_bytes); out.value_size = u64::from_be_bytes(raw_value_size_bytes); out.data_entry_position = u64::from_be_bytes(raw_data_entry_pos_size_bytes); let mut raw_key_bytes = vec![0_u8; out.key_size as usize]; rdr.read_exact(&mut raw_key_bytes); out.key = raw_key_bytes; Ok(out) } } #[cfg(test)] mod tests { use crate::schema::{DataEntry, Encoder, Decoder}; use std::io::{Cursor}; #[test] fn decode_encode_test() { let rec = DataEntry::new(0,vec![2, 2, 3, 54, 12], vec![32, 4, 1, 32, 65, 78]); let e = rec.encode(); let d = DataEntry::decode(&mut Cursor::new(e)).unwrap(); println!("{:#?}", d); println!("{}", d.check_crc()) } }
true
e4f950a54e736c3cec5e323270039de6ddbcaa8a
Rust
njeisecke/umya-spreadsheet
/src/structs/drawing/charts/view_3d.rs
UTF-8
4,371
2.71875
3
[ "MIT" ]
permissive
// c:view3D use super::RotateX; use super::RotateY; use super::RightAngleAxes; use super::Perspective; use writer::driver::*; use reader::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Default, Debug)] pub struct View3D { rotate_x: Option<RotateX>, rotate_y: Option<RotateY>, right_angle_axes: Option<RightAngleAxes>, perspective: Option<Perspective>, } impl View3D { pub fn get_rotate_x(&self)-> &Option<RotateX> { &self.rotate_x } pub fn get_rotate_x_mut(&mut self)-> &mut Option<RotateX> { &mut self.rotate_x } pub fn set_rotate_x(&mut self, value:RotateX)-> &mut View3D { self.rotate_x = Some(value); self } pub fn get_rotate_y(&self)-> &Option<RotateY> { &self.rotate_y } pub fn get_rotate_y_mut(&mut self)-> &mut Option<RotateY> { &mut self.rotate_y } pub fn set_rotate_y(&mut self, value:RotateY)-> &mut View3D { self.rotate_y = Some(value); self } pub fn get_right_angle_axes(&self)-> &Option<RightAngleAxes> { &self.right_angle_axes } pub fn get_right_angle_axes_mut(&mut self)-> &mut Option<RightAngleAxes> { &mut self.right_angle_axes } pub fn set_right_angle_axes(&mut self, value:RightAngleAxes)-> &mut View3D { self.right_angle_axes = Some(value); self } pub fn get_perspective(&self)-> &Option<Perspective> { &self.perspective } pub fn get_perspective_mut(&mut self)-> &mut Option<Perspective> { &mut self.perspective } pub fn set_perspective(&mut self, value:Perspective)-> &mut View3D { self.perspective = Some(value); self } pub(crate) fn set_attributes( &mut self, reader:&mut Reader<std::io::BufReader<std::fs::File>>, _e:&BytesStart ) { let mut buf = Vec::new(); loop { match reader.read_event(&mut buf) { Ok(Event::Empty(ref e)) => { match e.name() { b"c:rotX" => { let mut obj = RotateX::default(); obj.set_attributes(reader, e); self.set_rotate_x(obj); }, b"c:rotY" => { let mut obj = RotateY::default(); obj.set_attributes(reader, e); self.set_rotate_y(obj); }, b"c:rAngAx" => { let mut obj = RightAngleAxes::default(); obj.set_attributes(reader, e); self.set_right_angle_axes(obj); }, b"c:perspective" => { let mut obj = Perspective::default(); obj.set_attributes(reader, e); self.set_perspective(obj); }, _ => (), } }, Ok(Event::End(ref e)) => { match e.name() { b"c:view3D" => return, _ => (), } }, Ok(Event::Eof) => panic!("Error not find {} end element", "c:view3D"), Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), } buf.clear(); } } pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) { // c:view3D write_start_tag(writer, "c:view3D", vec![], false); // c:rotX match &self.rotate_x { Some(v) => {v.write_to(writer);}, None => {} } // c:rotY match &self.rotate_y { Some(v) => {v.write_to(writer);}, None => {} } // c:rAngAx match &self.right_angle_axes { Some(v) => {v.write_to(writer);}, None => {} } // c:perspective match &self.perspective { Some(v) => {v.write_to(writer);}, None => {} } write_end_tag(writer, "c:view3D"); } }
true
885c8b6f536949c96c922c6be71127ca014ac4f1
Rust
hppRC/competitive-hpp-rs
/src/utils/math.rs
UTF-8
1,929
3.453125
3
[ "MIT" ]
permissive
pub trait MathUtils { /// ## Example: /// ``` /// use competitive_hpp::prelude::*; /// /// assert_eq!(16.log2_trunc(), 4); /// assert_eq!(10.log2_trunc(), 3); /// ``` fn log2_trunc(self) -> Self; fn sqrt_floor(self) -> Self; fn sqrt_ceil(self) -> Self; } macro_rules! impl_digit_utils(($($ty:ty),*) => { $( impl MathUtils for $ty { #[inline] fn log2_trunc(self) -> Self { (self as f64).log2().trunc() as Self } #[inline] fn sqrt_floor(self) -> Self { (self as f64).sqrt() as Self } #[inline] fn sqrt_ceil(self) -> Self { let tmp = (self as f64).sqrt() as Self; if tmp * tmp == self { tmp } else { tmp + 1 } } } )* }); impl_digit_utils!(u64, u32, i64, i32, usize, isize); #[cfg(test)] mod tests { use super::*; macro_rules! impl_math_tests (($ty:ty) => { assert_eq!((16 as $ty).log2_trunc(), 4); assert_eq!((10 as $ty).log2_trunc(), 3); assert_eq!((9 as $ty).sqrt_floor(), 3); assert_eq!((10 as $ty).sqrt_floor(), 3); assert_eq!((15 as $ty).sqrt_floor(), 3); assert_eq!((9 as $ty).sqrt_ceil(), 3); assert_eq!((10 as $ty).sqrt_ceil(), 4); assert_eq!((10 as $ty).sqrt_ceil(), 4); }); #[test] fn u64_math_test() { impl_math_tests!(u64); } #[test] fn u32_math_test() { impl_math_tests!(u32); } #[test] fn i64_math_test() { impl_math_tests!(i64); } #[test] fn i32_math_test() { impl_math_tests!(i32); } #[test] fn usize_math_test() { impl_math_tests!(usize); } #[test] fn isize_math_test() { impl_math_tests!(isize); } }
true
a2c513589c525f46d3851685d3350b7985e49083
Rust
Hoblovski/riscv
/src/paging/recursive.rs
UTF-8
8,006
3.03125
3
[ "ISC" ]
permissive
use super::frame_alloc::*; use super::page_table::*; use addr::*; pub trait Mapper { /// Creates a new mapping in the page table. /// /// This function might need additional physical frames to create new page tables. These /// frames are allocated from the `allocator` argument. At most three frames are required. fn map_to<A>(&mut self, page: Page, frame: Frame, flags: PageTableFlags, allocator: &mut A) -> Result<MapperFlush, MapToError> where A: FrameAllocator; /// Removes a mapping from the page table and returns the frame that used to be mapped. /// /// Note that no page tables or pages are deallocated. fn unmap(&mut self, page: Page) -> Result<(Frame, MapperFlush), UnmapError>; /// Return the frame that the specified page is mapped to. fn translate_page(&self, page: Page) -> Option<Frame>; /// Maps the given frame to the virtual page with the same address. fn identity_map<A>(&mut self, frame: Frame, flags: PageTableFlags, allocator: &mut A) -> Result<MapperFlush, MapToError> where A: FrameAllocator, { let page = Page::of_addr(VirtAddr::new(frame.start_address().as_u32() as usize)); self.map_to(page, frame, flags, allocator) } } #[must_use = "Page Table changes must be flushed or ignored."] pub struct MapperFlush(Page); impl MapperFlush { /// Create a new flush promise fn new(page: Page) -> Self { MapperFlush(page) } /// Flush the page from the TLB to ensure that the newest mapping is used. pub fn flush(self) { use asm::sfence_vma; sfence_vma(0, self.0.start_address()); } /// Don't flush the TLB and silence the “must be used” warning. pub fn ignore(self) {} } /// This error is returned from `map_to` and similar methods. #[derive(Debug)] pub enum MapToError { /// An additional frame was needed for the mapping process, but the frame allocator /// returned `None`. FrameAllocationFailed, /// An upper level page table entry has the `HUGE_PAGE` flag set, which means that the /// given page is part of an already mapped huge page. ParentEntryHugePage, /// The given page is already mapped to a physical frame. PageAlreadyMapped, } /// An error indicating that an `unmap` call failed. #[derive(Debug)] pub enum UnmapError { /// An upper level page table entry has the `HUGE_PAGE` flag set, which means that the /// given page is part of a huge page and can't be freed individually. ParentEntryHugePage, /// The given page is not mapped to a physical frame. PageNotMapped, /// The page table entry for the given page points to an invalid physical address. InvalidFrameAddress(PhysAddr), } /// A recursive page table is a last level page table with an entry mapped to the table itself. /// /// This struct implements the `Mapper` trait. pub struct RecursivePageTable<'a> { p2: &'a mut PageTable, recursive_index: usize, } /// An error indicating that the given page table is not recursively mapped. /// /// Returned from `RecursivePageTable::new`. #[derive(Debug)] pub struct NotRecursivelyMapped; impl<'a> RecursivePageTable<'a> { /// Creates a new RecursivePageTable from the passed level 2 PageTable. /// /// The page table must be recursively mapped, that means: /// /// - The page table must have one recursive entry, i.e. an entry that points to the table /// itself. /// - The page table must be active, i.e. the satp register must contain its physical address. /// /// Otherwise `Err(NotRecursivelyMapped)` is returned. pub fn new(table: &'a mut PageTable) -> Result<Self, NotRecursivelyMapped> { let page = Page::of_addr(VirtAddr::new(table as *const _ as usize)); let recursive_index = page.p2_index(); use register::satp; type F = PageTableFlags; if page.p1_index() != recursive_index + 1 || satp::read().frame() != table[recursive_index].frame() || satp::read().frame() != table[recursive_index + 1].frame() || !table[recursive_index].flags().contains(F::VALID) || table[recursive_index].flags().contains(F::READABLE | F::WRITABLE) || !table[recursive_index + 1].flags().contains(F::VALID | F::READABLE | F::WRITABLE) { return Err(NotRecursivelyMapped); } Ok(RecursivePageTable { p2: table, recursive_index, }) } /// Creates a new RecursivePageTable without performing any checks. /// /// The `recursive_index` parameter must be the index of the recursively mapped entry. pub unsafe fn new_unchecked(table: &'a mut PageTable, recursive_index: usize) -> Self { RecursivePageTable { p2: table, recursive_index, } } fn create_p1_if_not_exist<A>(&mut self, p2_index: usize, allocator: &mut A) -> Result<(), MapToError> where A: FrameAllocator, { type F = PageTableFlags; if self.p2[p2_index].is_unused() { if let Some(frame) = allocator.alloc() { self.p2[p2_index].set(frame, F::VALID); self.edit_p1(p2_index, |p1| p1.zero()); } else { return Err(MapToError::FrameAllocationFailed); } } Ok(()) } /// Edit a p1 page. /// During the editing, the flag of entry `p2[p2_index]` is temporarily set to V+R+W. fn edit_p1<F, T>(&mut self, p2_index: usize, f: F) -> T where F: FnOnce(&mut PageTable) -> T { type F = PageTableFlags; let flags = self.p2[p2_index].flags_mut(); assert_ne!(p2_index, self.recursive_index, "can not edit recursive index"); assert_ne!(p2_index, self.recursive_index + 1, "can not edit recursive index"); assert!(flags.contains(F::VALID), "try to edit a nonexistent p1 table"); assert!(!flags.contains(F::READABLE) && !flags.contains(F::WRITABLE), "try to edit a 4M page as p1 table"); flags.insert(F::READABLE | F::WRITABLE); let p1 = Page::from_page_table_indices(self.recursive_index, p2_index); let p1 = unsafe{ &mut *(p1.start_address().as_usize() as *mut PageTable) }; let ret = f(p1); flags.remove(F::READABLE | F::WRITABLE); ret } } impl<'a> Mapper for RecursivePageTable<'a> { fn map_to<A>(&mut self, page: Page, frame: Frame, flags: PageTableFlags, allocator: &mut A) -> Result<MapperFlush, MapToError> where A: FrameAllocator, { use self::PageTableFlags as Flags; self.create_p1_if_not_exist(page.p2_index(), allocator)?; self.edit_p1(page.p2_index(), |p1| { if !p1[page.p1_index()].is_unused() { return Err(MapToError::PageAlreadyMapped); } p1[page.p1_index()].set(frame, flags); Ok(MapperFlush::new(page)) }) } fn unmap(&mut self, page: Page) -> Result<(Frame, MapperFlush), UnmapError> { use self::PageTableFlags as Flags; if self.p2[page.p2_index()].is_unused() { return Err(UnmapError::PageNotMapped); } self.edit_p1(page.p2_index(), |p1| { let p1_entry = &mut p1[page.p1_index()]; if !p1_entry.flags().contains(Flags::VALID) { return Err(UnmapError::PageNotMapped); } let frame = p1_entry.frame(); p1_entry.set_unused(); Ok((frame, MapperFlush::new(page))) }) } fn translate_page(&self, page: Page) -> Option<Frame> { if self.p2[page.p2_index()].is_unused() { return None; } let self_mut = unsafe{ &mut *(self as *const _ as *mut Self) }; self_mut.edit_p1(page.p2_index(), |p1| { let p1_entry = &p1[page.p1_index()]; if p1_entry.is_unused() { return None; } Some(p1_entry.frame()) }) } }
true
7159b6b3adb3727a2d53e42ea3e5f8360371e5c9
Rust
mwillsey/simple-lang
/src/syntax/ast.rs
UTF-8
5,553
3.03125
3
[]
no_license
use std::rc::Rc; use im::{HashMap as Map, HashSet as Set}; pub type RcType = Rc<Type>; pub type RcPattern = Rc<Pattern>; pub type RcExpr = Rc<Expr>; pub type RcDecl = Rc<Decl>; #[derive(Debug, PartialEq)] pub enum Type { Int, Float, Tuple(Vec<RcType>), Fn(Vec<RcType>, RcType), Named(Name), } pub type Name = Rc<str>; /// Literal values #[derive(Debug, Clone, PartialEq)] pub enum Literal { Int(i32), Float(f64), } /// Patterns #[derive(Debug, PartialEq)] pub enum Pattern { Wildcard, Annotated(RcPattern, RcType), Literal(Literal), Binder(Name), Tuple(Vec<RcPattern>), // Record(Vec<(String, RcPattern)>), // Tag(String, RcPattern), } #[derive(Debug, Clone, PartialEq)] pub enum Bop { Add, Sub, Mul, Div, } /// Expressions #[derive(Debug, PartialEq)] pub enum Expr { Var(Name), // Ann(RcExpr, RcType), // Annotated expressions Literal(Literal), Bop { bop: Bop, e1: RcExpr, e2: RcExpr, }, Block(Block), Lambda { params: Vec<RcPattern>, body: RcExpr, }, Call { func: RcExpr, args: Vec<RcExpr>, }, Tuple(Vec<RcExpr>), Struct { name: Name, fields: Map<Name, RcExpr>, }, FieldAccess { expr: RcExpr, name: Name, }, } #[derive(Debug, PartialEq)] pub struct Block { pub stmts: Vec<Stmt>, pub expr: RcExpr, } #[derive(Debug, PartialEq)] pub enum Stmt { Let { pat: RcPattern, expr: RcExpr }, } /// Expressions impl Expr { pub fn free_vars(&self) -> Set<Name> { self.free_vars_not_bound(&Set::new()) } fn free_vars_not_bound(&self, bound: &Set<Name>) -> Set<Name> { match self { Expr::Var(name) => { if !bound.contains(name) { Set::unit(name.clone()) } else { Set::new() } } // Ann(RcExpr, RcType), // Annotated expressions Expr::Literal(_) => Set::new(), Expr::Bop { e1, e2, .. } => { e1.free_vars_not_bound(bound) + e2.free_vars_not_bound(bound) } Expr::Lambda { params, body } => { let mut bound = bound.clone(); for pat in params { pat.add_bound_vars(&mut bound) } body.free_vars_not_bound(&bound) } Expr::Call { func, args } => { let func_fv = func.free_vars_not_bound(bound); let args_fv = Set::unions(args.iter().map(|a| a.free_vars_not_bound(bound))); func_fv + args_fv } Expr::Block(block) => block.free_vars_not_bound(bound), Expr::Tuple(exprs) => Set::unions(exprs.iter().map(|e| e.free_vars_not_bound(bound))), Expr::Struct { name: _, fields } => { Set::unions(fields.values().map(|e| e.free_vars_not_bound(bound))) } Expr::FieldAccess { expr, name: _ } => expr.free_vars_not_bound(bound), } } } impl Block { fn free_vars_not_bound(&self, bound: &Set<Name>) -> Set<Name> { let mut bound = bound.clone(); let stmts_free = Set::unions(self.stmts.iter().map(|s| s.free_vars_not_bound(&mut bound))); stmts_free + self.expr.free_vars_not_bound(&bound) } } impl Stmt { fn free_vars_not_bound(&self, bound: &mut Set<Name>) -> Set<Name> { match self { Stmt::Let { pat, expr } => { let free = expr.free_vars(); pat.add_bound_vars(bound); free } } } } impl Pattern { fn add_bound_vars(&self, bound: &mut Set<Name>) { match self { Pattern::Wildcard => (), Pattern::Annotated(pat, _typ) => pat.add_bound_vars(bound), Pattern::Literal(_) => (), Pattern::Binder(name) => { bound.insert(name.clone()); } Pattern::Tuple(pats) => { for pat in pats { pat.add_bound_vars(bound) } } } } } #[derive(Debug, PartialEq, Clone)] pub enum Decl { Struct(Struct), } #[derive(Debug, PartialEq, Clone)] pub struct Struct { pub name: Name, pub fields: Map<Name, RcType>, } #[derive(Debug, PartialEq)] pub struct Program { pub decls: Vec<Decl>, } impl Program { pub fn get_struct(&self, name: &str) -> Result<Struct, String> { for d in &self.decls { match d { Decl::Struct(s) if s.name.as_ref() == name => return Ok(s.clone()), _ => (), } } Err("struct not found".into()) } } pub fn name(s: &'static str) -> Name { s.into() } pub fn var(s: &'static str) -> RcExpr { Expr::Var(s.into()).into() } pub fn int(i: i32) -> RcExpr { Expr::Literal(Literal::Int(i)).into() } #[cfg(test)] mod tests { use super::*; use crate::syntax::grammar::expr; fn set(strs: &[&str]) -> Set<Name> { strs.iter().map(|s| s.to_string()).collect() } #[test] fn test_free_variables() { let e = expr!(|x| x + x); assert_eq!(e.free_vars(), set(&[])); let e = expr!(x + x); assert_eq!(e.free_vars(), set(&["x"])); let e = expr!(|x| y + x); assert_eq!(e.free_vars(), set(&["y"])); let e = expr!(|y| |x| x + y + z); assert_eq!(e.free_vars(), set(&["z"])); } }
true
15bdc7b94f27e36df0ede9bf076491c4c47660cd
Rust
triamero/advent-of-code-2018
/src/days/day3.rs
UTF-8
3,853
3.015625
3
[ "MIT" ]
permissive
use super::day; use super::day_result::DayResult; pub struct Day3(); impl day::Day for Day3 { fn get_name(&self) -> String { return String::from("day3"); } fn compute_first(&self, input: &Vec<String>) -> DayResult { let claims = input.iter().map(|x| Claim::new(x)).collect::<Vec<Claim>>(); let mut fabric = create_fabric(); for c1 in &claims { for i in c1.top_left.x..c1.bottom_right.x + 1 { for j in c1.top_left.y..c1.bottom_right.y + 1 { fabric[i as usize][j as usize].claim_ids.push(c1.id); } } } let mut more_than_one_claim_count = 0; for i in 0..1001 { for j in 0..1001 { if fabric[i][j].claim_ids.len() > 1 { more_than_one_claim_count += 1; } } } return DayResult::from_i32(more_than_one_claim_count); } fn compute_second(&self, input: &Vec<String>) -> DayResult { let claims = input.iter().map(|x| Claim::new(x)).collect::<Vec<Claim>>(); let mut fabric = create_fabric(); for c1 in &claims { for i in c1.top_left.x..c1.bottom_right.x + 1 { for j in c1.top_left.y..c1.bottom_right.y + 1 { fabric[i as usize][j as usize].claim_ids.push(c1.id); } } } let mut id = -1; for c1 in &claims { let mut same_id = true; for i in c1.top_left.x..c1.bottom_right.x + 1 { for j in c1.top_left.y..c1.bottom_right.y + 1 { if fabric[i as usize][j as usize].claim_ids.len() != 1 { same_id = false; break; } } if !same_id { break; } } if same_id { id = c1.id; break; } } return DayResult::from_i32(id); } } struct Claim { /// Идентификатор id: i32, /// Левая верхняя точка top_left: Point, /// Правая нижняя точка bottom_right: Point, } impl Claim { fn new(line: &str) -> Claim { // #12 @ 512,893: 16x22 // [0]=#12 [1]=@ [2]=512,893: [3]=16x22 let splits = line.trim().split(" ").collect::<Vec<&str>>(); let coords: Vec<&str> = splits[2].trim_matches(':').split(',').collect(); let sizes: Vec<&str> = splits[3].split('x').collect(); let top_left = Point::new( coords[0].parse::<i32>().unwrap() + 1, coords[1].parse::<i32>().unwrap() + 1, ); let bottom_right = Point::new( top_left.x + sizes[0].parse::<i32>().unwrap() - 1, top_left.y + sizes[1].parse::<i32>().unwrap() - 1, ); return Claim { id: splits[0].trim_matches('#').parse::<i32>().unwrap(), top_left: top_left, bottom_right: bottom_right, }; } } struct Point { x: i32, y: i32, } impl Point { fn new(x: i32, y: i32) -> Point { Point { x: x, y: y } } } struct Inch { claim_ids: Vec<i32>, } impl Inch { fn new() -> Inch { return Inch { claim_ids: Vec::new(), }; } } fn create_fabric() -> Vec<Vec<Inch>> { let mut fabric: Vec<Vec<Inch>> = Vec::new(); for _i in 0..1001 { let mut vec: Vec<Inch> = Vec::new(); for _j in 0..1001 { vec.push(Inch::new()); } fabric.push(vec); } fabric }
true
5db0f35a94a4313fd9b5ba78bada82253b718133
Rust
mdsherry/rocket-auth-login
/src/authorization.rs
UTF-8
18,881
3.046875
3
[ "Apache-2.0" ]
permissive
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: String, } #[derive(Debug, Clone)] pub struct AuthCont<T: AuthorizeCookie> { pub cookie: T, } #[derive(Debug, Clone, FromForm)] pub struct AuthFail { pub user: String, pub msg: String, } impl AuthFail { pub fn new(user: String, msg: String) -> AuthFail { AuthFail { user, msg, } } } #[derive(Debug, Clone)] pub struct LoginCont<T: AuthorizeForm> { pub form: T, } impl<T: AuthorizeForm + Clone> LoginCont<T> { pub fn form(&self) -> T { self.form.clone() } } /// The CookieId trait contains a single method, `cookie_id()`. /// The `cookie_id()` function returns the name or id of the cookie. /// Note: if you have another cookie of the same name that is secured /// that already exists (say created by running the tls_example then database_example) /// if your cookies have the same name it will not work. This is because /// if the existing cookie is set to secured you attempt to login without /// using tls the cookie will not work correctly and login will fail. pub trait CookieId { /// Ensure `cookie_id()` does not conflict with other cookies that /// may be set using secured when not using tls. Secured cookies /// will only work usnig tls and cookies of the same name could /// create problems. fn cookie_id<'a>() -> &'a str { "sid" } } /// ## Cookie Data /// The AuthorizeCookie trait is used with a custom data structure that /// will contain the data in the cookie. This trait provides methods /// to store and retrieve a data structure from a cookie's string contents. /// /// Using a request guard a route can easily check whether the user is /// a valid Administrator or any custom user type. /// /// ### Example /// /// ``` /// /// use rocket::{Request, Outcome}; /// use rocket::request::FromRequest; /// use auth::authorization::*; /// // Define a custom data type that hold the cookie information /// pub struct AdministratorCookie { /// pub userid: u32, /// pub username: String, /// pub display: Option<String>, /// } /// /// // Implement CookieId for AdministratorCookie /// impl CookieId for AdministratorCookie { /// // Tell /// type CookieType = AdministratorCookie; /// fn cookie_id<'a>() -> &'a str { /// "asid" /// } /// } /// /// // Implement AuthorizeCookie for the AdministratorCookie /// // This code can be changed to use other serialization formats /// impl AuthorizeCookie for AdministratorCookie { /// fn store_cookie(&self) -> String { /// ::serde_json::to_string(self).expect("Could not serialize structure") /// } /// fn retrieve_cookie(string: String) -> Option<Self> { /// let mut des_buf = string.clone(); /// let des: Result<AdministratorCookie, _> = ::serde_json::from_str(&mut des_buf); /// if let Ok(cooky) = des { /// Some(cooky) /// } else { /// None /// } /// } /// } /// /// // Implement FromRequest for the Cookie type to allow direct /// // use of the type in routes, instead of through AuthCont /// // /// // The only part that needs to be changed is the impl and /// // function return type; the type should match your struct /// impl<'a, 'r> FromRequest<'a, 'r> for AdministratorCookie { /// type Error = (); /// // Change the return type to match your type /// fn from_request(request: &'a Request<'r>) -> ::rocket::request::Outcome<AdministratorCookie,Self::Error>{ /// let cid = AdministratorCookie::cookie_id(); /// let mut cookies = request.cookies(); /// /// match cookies.get_private(cid) { /// Some(cookie) => { /// if let Some(cookie_deserialized) = AdministratorCookie::retrieve_cookie(cookie.value().to_string()) { /// Outcome::Success( /// cookie_deserialized /// ) /// } else { /// Outcome::Forward(()) /// } /// }, /// None => Outcome::Forward(()) /// } /// } /// } /// /// // In your route use the AdministratorCookie request guard to ensure /// // that only verified administrators can reach a page /// #[get("/administrator", rank=1)] /// fn admin_page(admin: AdministratorCookie) -> Html<String> { /// // Show the display field in AdminstratorCookie as defined above /// Html( format!("Welcome adminstrator {}!", admin.display) ) /// } /// #[get("/administrator", rank=2)] /// fn admin_login_form() -> Html<String> { /// // Html form here, see the example directory for a complete example /// } /// /// fn main() { /// rocket::ignite().mount("/", routes![admin_page, admin_login_form]).launc(); /// } /// /// ``` /// pub trait AuthorizeCookie : CookieId { /// Serialize the cookie data type - must be implemented by cookie data type fn store_cookie(&self) -> String; /// Deserialize the cookie data type - must be implemented by cookie data type fn retrieve_cookie(String) -> Option<Self> where Self: Sized; /// Deletes a cookie. This does not need to be implemented, it defaults to removing /// the private key with the named specified by cookie_id() method. fn delete_cookie(cookies: &mut Cookies) { cookies.remove_private( Cookie::named( Self::cookie_id() ) ); } } /// ## Form Data /// The AuthorizeForm trait handles collecting a submitted login form into a /// data structure and authenticating the credentials inside. It also contains /// default methods to process the login and conditionally redirecting the user /// to the correct page depending upon successful authentication or failure. /// /// ### Authentication Failure /// Upon failure the user is redirected to a page with a query string specified /// by the `fail_url()` method. This allows the specified username to persist /// across attempts. /// /// ### Flash Message /// The `flash_redirect()` method redirects the user but also adds a cookie /// called a flash message that once read is deleted immediately. This is used /// to indicate why the authentication failed. If the user refreshes the page /// after failing to login the message that appears above the login indicating /// why it failed will disappear. To redirect without a flash message use the /// `redirect()` method instead of `flash_redirect()`. /// /// ## Example /// ``` /// /// use rocket::{Request, Outcome}; /// use std::collections::HashMap; /// use auth::authorization::*; /// // Create the structure that will contain the login form data /// #[derive(Debug, Clone, Serialize, Deserialize)] /// pub struct AdministratorForm { /// pub username: String, /// pub password: String, /// } /// /// // Ipmlement CookieId for the form structure /// impl CookieId for AdministratorForm { /// fn cookie_id<'a>() -> &'a str { /// "acid" /// } /// } /// /// // Implement the AuthorizeForm for the form structure /// impl AuthorizeForm for AdministratorForm { /// type CookieType = AdministratorCookie; /// /// /// Authenticate the credentials inside the login form /// fn authenticate(&self) -> Result<Self::CookieType, AuthFail> { /// // The code in this function should be replace with whatever /// // you use to authenticate users. /// println!("Authenticating {} with password: {}", &self.username, &self.password); /// if &self.username == "administrator" && &self.password != "" { /// Ok( /// AdministratorCookie { /// userid: 1, /// username: "administrator".to_string(), /// display: Some("Administrator".to_string()), /// } /// ) /// } else { /// Err( /// AuthFail::new(self.username.to_string(), "Incorrect username".to_string()) /// ) /// } /// } /// /// /// Create a new login form instance /// fn new_form(user: &str, pass: &str, _extras: Option<HashMap<String, String>>) -> Self { /// AdministratorForm { /// username: user.to_string(), /// password: pass.to_string(), /// } /// } /// } /// /// # fn main() {} /// /// ``` /// /// # Example Code /// For more detailed example please see the example directory. /// The example directory contains a fully working example of processing /// and checking login information. /// pub trait AuthorizeForm : CookieId { type CookieType: AuthorizeCookie; /// Determine whether the login form structure containts /// valid credentials, otherwise send back the username and /// a message indicating why it failed in the `AuthFail` struct /// /// Must be implemented on the login form structure fn authenticate(&self) -> Result<Self::CookieType, AuthFail>; /// Create a new login form Structure with /// the specified username and password. /// The first parameter is the username, then password, /// and then optionally a HashMap containing any extra fields. /// /// Must be implemented on the login form structure /// // /// The password is a u8 slice, allowing passwords to be stored without // /// being converted to hex. The slice is sufficient because new_form() // /// is called within the from_form() function, so when the password is // /// collected as a vector of bytes the reference to those bytes are sent // /// to the new_form() method. fn new_form(&str, &str, Option<HashMap<String, String>>) -> Self; /// The `fail_url()` method is used to create a url that the user is sent /// to when the authentication fails. The default implementation /// redirects the user to the /page?user=<ateempted_username> /// which enables the form to display the username that was attempted /// and unlike FlashMessages it will persist across refreshes fn fail_url(user: &str) -> String { let mut output = String::with_capacity(user.len() + 10); output.push_str("?user="); output.push_str(user); output } /// Sanitizes the username before storing in the login form structure. /// The default implementation uses the `sanitize()` function in the /// `sanitization` module. This can be overriden in your /// `impl AuthorizeForm for {login structure}` implementation to /// customize how the text is cleaned/sanitized. fn clean_username(string: &str) -> String { sanitize(string) } /// Sanitizes the password before storing in the login form structure. /// The default implementation uses the `sanitize_oassword()` function in the /// `sanitization` module. This can be overriden in your /// `impl AuthorizeForm for {login structure}` implementation to /// customize how the text is cleaned/sanitized. fn clean_password(string: &str) -> String { sanitize_password(string) } /// Sanitizes any extra variables before storing in the login form structure. /// The default implementation uses the `sanitize()` function in the /// `sanitization` module. This can be overriden in your /// `impl AuthorizeForm for {login structure}` implementation to /// customize how the text is cleaned/sanitized. fn clean_extras(string: &str) -> String { sanitize(string) } /// Redirect the user to one page on successful authentication or /// another page (with a `FlashMessage` indicating why) if authentication fails. /// /// `FlashMessage` is used to indicate why the authentication failed /// this is so that the user can see why it failed but when they refresh /// it will disappear, enabling a clean start, but with the user name /// from the url's query string (determined by `fail_url()`) fn flash_redirect(&self, ok_redir: impl Into<String>, err_redir: impl Into<String>, cookies: &mut Cookies) -> Result<Redirect, Flash<Redirect>> { match self.authenticate() { Ok(cooky) => { let cid = Self::cookie_id(); let contents = cooky.store_cookie(); cookies.add_private(Cookie::new(cid, contents)); Ok(Redirect::to(ok_redir.into())) }, Err(fail) => { let mut furl = err_redir.into(); if &fail.user != "" { let furl_qrystr = Self::fail_url(&fail.user); furl.push_str(&furl_qrystr); } Err( Flash::error(Redirect::to(furl), &fail.msg) ) }, } } /// Redirect the user to one page on successful authentication or /// another page if authentication fails. fn redirect(&self, ok_redir: &str, err_redir: &str, cookies: &mut Cookies) -> Result<Redirect, Redirect> { match self.authenticate() { Ok(cooky) => { let cid = Self::cookie_id(); let contents = cooky.store_cookie(); cookies.add_private(Cookie::new(cid, contents)); Ok(Redirect::to(ok_redir.to_string())) }, Err(fail) => { let mut furl = String::from(err_redir); if &fail.user != "" { let furl_qrystr = Self::fail_url(&fail.user); furl.push_str(&furl_qrystr); } Err( Redirect::to(furl) ) }, } } } impl<T: AuthorizeCookie + Clone> AuthCont<T> { pub fn cookie_data(&self) -> T { // Todo: change the signature from &self to self // and remove the .clone() method call self.cookie.clone() } } /// # Request Guard /// Request guard for the AuthCont (Authentication Container). /// This allows a route to call a user type like: /// /// ```rust,no_run /// /// use auth::authorization::*; /// # use administration:*; /// use rocket; /// #[get("/protected")] /// fn protected(container: AuthCont<AdministratorCookie>) -> Html<String> { /// let admin = container.cookie; /// String::new() /// } /// /// # fn main() { /// # rocket::ignite().mount("/", routes![]).launch(); /// # } /// /// ``` /// impl<'a, 'r, T: AuthorizeCookie> FromRequest<'a, 'r> for AuthCont<T> { type Error = (); fn from_request(request: &'a Request<'r>) -> ::rocket::request::Outcome<AuthCont<T>,Self::Error>{ let cid = T::cookie_id(); let mut cookies = request.cookies(); match cookies.get_private(cid) { Some(cookie) => { if let Some(cookie_deserialized) = T::retrieve_cookie(cookie.value().to_string()) { Outcome::Success( AuthCont { cookie: cookie_deserialized, } ) } else { Outcome::Forward(()) } }, None => Outcome::Forward(()) } } } /// #Collecting Login Form Data /// If your login form requires more than just a username and password the /// extras parameter, in `AuthorizeForm::new_form(user, pass, extras)`, holds /// all other fields in a `HashMap<String, String>` to allow processing any /// field that was submitted. The username and password are separate because /// those are universal fields. /// /// ## Custom Username/Password Field Names /// By default the function will look for a username and a password field. /// If your form does not use those particular names you can always use the /// extras `HashMap` to retrieve the username and password when using different /// input box names. The function will return `Ok()` even if no username or /// password was entered, this is to allow custom field names to be accessed /// and authenticated by the `authenticate()` method. impl<'f, A: AuthorizeForm> FromForm<'f> for LoginCont<A> { type Error = &'static str; fn from_form(form_items: &mut FormItems<'f>, _strict: bool) -> Result<Self, Self::Error> { let mut user: String = String::new(); let mut pass: String = String::new(); let mut extras: HashMap<String, String> = HashMap::new(); for FormItem { key, value, .. } in form_items { match key.as_str(){ "username" => { user = A::clean_username(&value.url_decode().unwrap_or(String::new())); }, "password" => { pass = A::clean_password(&value.url_decode().unwrap_or(String::new())); }, // _ => {}, a => { // extras.insert( a.to_string(), A::clean_extras( &value.url_decode().unwrap_or(String::new()) ) ); extras.insert( a.to_string(), value.url_decode().unwrap_or(String::new()) ); }, } } // Do not need to check for username / password here, // if the authentication method requires them it will // fail at that point. Ok( LoginCont { form: if extras.len() == 0 { A::new_form(&user, &pass, None) } else { A::new_form(&user, &pass, Some(extras)) }, } ) } } impl<'f> FromForm<'f> for UserQuery { type Error = &'static str; fn from_form(form_items: &mut FormItems<'f>, _strict: bool) -> Result<UserQuery, Self::Error> { let mut name: String = String::new(); for FormItem { key, value, .. } in form_items { match key.as_str() { "user" => { name = sanitize( &value.url_decode().unwrap_or(String::new()) ); }, _ => {}, } } Ok(UserQuery { user: name }) } }
true
062d8a4222909eec58ea563a083f3006617b4737
Rust
fivemoreminix/keycrypt-recrypted
/rust/src/main.rs
UTF-8
1,886
3.3125
3
[]
no_license
use keycrypt::*; use std::path::{Path, PathBuf}; use structopt::StructOpt; #[derive(StructOpt)] #[structopt(name = "keycrypt", about = "The keyboard-based encryption algorithm.")] struct Opt { /// Whether to "encode" or "decode" #[structopt(short, long, default_value = "auto")] action: String, /// When "decode" is the action, a path to a wordlist is required #[structopt(short, long, required_if("action", "decrypt"))] wordlist: Option<PathBuf>, /// The message to perform the action on. Can be enclosed in quotes #[structopt()] message: String, /// Silence the auto message #[structopt(short, long)] silence: bool, } fn main() { let mut opt = Opt::from_args(); if &opt.action == "auto" { if opt.message.contains(|c: char| c.is_ascii_digit()) { opt.action = "decode".to_string(); if !opt.silence { println!("Chose to decode"); } } else { opt.action = "encode".to_string(); if !opt.silence { println!("Chose to encode"); } } } if &opt.action == "encode" { println!("{}", encrypt_string(&opt.message)); } else if &opt.action == "decode" { if opt.wordlist.is_none() { eprintln!("error: You forgot to provide a wordlist for decoding!"); std::process::exit(1); } let words = match load_wordlist(&opt.wordlist.unwrap()) { Ok(words) => words, Err(e) => { eprintln!("error: {:?} was encountered trying to open the wordlist provided", e); std::process::exit(1); } }; println!("{}", decrypt_ascii_string(&opt.message, &words)); } else { eprintln!("error: {:?} is not a valid action", &opt.action); std::process::exit(1); } }
true
d7a579da75261a69d4d3ecf38c64352bbe98a3eb
Rust
rust-lang/rust
/tests/ui/borrowck/issue-70919-drop-in-loop.rs
UTF-8
502
3
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
// Regression test for issue #70919 // Tests that we don't emit a spurious "borrow might be used" error // when we have an explicit `drop` in a loop // check-pass struct WrapperWithDrop<'a>(&'a mut bool); impl<'a> Drop for WrapperWithDrop<'a> { fn drop(&mut self) { } } fn drop_in_loop() { let mut base = true; let mut wrapper = WrapperWithDrop(&mut base); loop { drop(wrapper); base = false; wrapper = WrapperWithDrop(&mut base); } } fn main() { }
true
7f7e0ab5c6a1dbc2811ad37006fc73ad3ea7213b
Rust
Akagi201/learning-rust
/error-handling/read-file/src/main.rs
UTF-8
522
3.59375
4
[ "MIT" ]
permissive
fn main() { let path = "/tmp/dat"; // 文件路径 match read_file(path) { // 判断方法结果 Ok(file) => { println!("{}", file) } // OK 代表读取到文件内容,正确打印文件内容 Err(e) => { println!("{} {}", path, e) } // Err 代表结果不存在,打印错误结果 } } fn read_file(path: &str) -> Result<String, std::io::Error> { // Result 作为结果返回值 std::fs::read_to_string(path) // 读取文件内容 }
true
c2718a540f2ab8025163df2db359e199d34d46b6
Rust
spacedragon/rust-git
/src/model/tag.rs
UTF-8
5,052
2.765625
3
[]
no_license
use super::object::ObjectType; use super::id::Id; use super::commit::Identity; use nom::IResult; use nom::bytes::complete::{tag, take_while, take_until, take_till}; use nom::combinator::{map_res, rest}; use nom::character::complete::{not_line_ending, line_ending}; use nom::character::is_space; use crate::model::commit::*; use crate::model::object::{parse_object_type, GitObject}; use nom::branch::alt; use nom::multi::separated_list; use std::collections::HashMap; use crate::errors::*; use crate::model::repository::Repository; #[derive(Debug, Clone, PartialEq)] pub struct Tag { id : Id, object_type: ObjectType, object: Id, tag: String, tagger: Option<Identity>, message: String, other: HashMap<String, String>, } impl Tag { pub fn id(&self) -> &Id { &self.id } pub fn tag(&self) -> &str { self.tag.as_str() } pub fn tagger(&self) -> &Option<Identity> { &self.tagger } pub fn message(&self) -> &str { self.message.as_str() } pub fn object(&self) -> &Id { &self.object } pub fn object_type(&self) -> ObjectType { self.object_type.clone() } pub fn from(repo: &dyn Repository,obj: &GitObject) -> Result<Self> { if obj.object_type() == ObjectType::TAG { let buf = repo.read_content(&obj)?; let tag: Tag = parse_tag_object(&buf, obj.id()).map(|res| res.1) .map_err(|_|ErrorKind::ParseError)?; Ok(tag) } else { Err(ErrorKind::InvalidObjectType.into()) } } } pub enum Attr { Object(Id), Tagger(Identity), Tag(String), Type(ObjectType), Unknown(String, String), } fn parse_object(input :&[u8]) -> IResult<&[u8] , Attr> { let (input, _key) = tag("object")(input)?; let (input, _) = take_while(is_space)(input)?; let (input, id) = map_res(not_line_ending, id_from_str_bytes)(input)?; Ok((input, Attr::Object(id))) } fn parse_tagger(input: &[u8]) -> IResult<&[u8], Attr> { let (input, _key) = tag("tagger")(input)?; let (input, _) = tag(" ")(input)?; let (input, identity) = parse_identity(input)?; Ok((input, Attr::Tagger(identity))) } fn parse_tag(input: &[u8]) -> IResult<&[u8], Attr> { let (input, _key) = tag("tag")(input)?; let (input, _) = tag(" ")(input)?; let (input, tag) = map_res(not_line_ending, std::str::from_utf8)(input)?; Ok((input, Attr::Tag(tag.to_string()))) } fn parse_type(input: &[u8]) -> IResult<&[u8], Attr> { let (input, _key) = tag("type")(input)?; let (input, _) = tag(" ")(input)?; let (input, object_type) = parse_object_type(input)?; Ok((input, Attr::Type(object_type))) } fn parse_attr(input: &[u8]) -> IResult<&[u8], Attr> { let (input, key) = map_res(take_till(is_space), std::str::from_utf8)(input)?; let (input, _) = take_while(is_space)(input)?; let (input, value) = map_res(not_line_ending, std::str::from_utf8)(input)?; Ok((input, Attr::Unknown(key.to_owned(), value.to_owned()))) } fn parse_attrs(input: &[u8]) -> IResult<&[u8], Attr> { let (input, attr) = alt(( parse_object, parse_type, parse_tag, parse_tagger, parse_attr ))(input)?; Ok((input, attr)) } fn parse_tag_object<'a>(input :&'a[u8], id: &Id) -> IResult<&'a[u8] , Tag> { let (input, attrs_str) = take_until("\n\n")(input)?; let (_, attrs) = separated_list(line_ending, parse_attrs)(attrs_str)?; let (input, message) = map_res(rest, std::str::from_utf8)(input)?; let mut tag = Tag { object_type: ObjectType::BLOB, id: id.to_owned(), object: Id::default(), tag: "".to_string(), message: message.trim().to_owned(), tagger: None, other: HashMap::new() }; for attr in attrs { match attr { Attr::Tag(t) => tag.tag = t, Attr::Tagger(identity) => tag.tagger = Some(identity), Attr::Object(id) => tag.object = id, Attr::Type(t) => tag.object_type = t, Attr::Unknown(k, v) => { tag.other.insert(k, v); } } } Ok((input, tag)) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; use chrono::{FixedOffset, TimeZone}; #[test] fn test_parse_tag() { let str = b"object a541069eb298c4969982721adea07e526d899351 type commit tag v0.1 tagger spacedragon <allendragon@gmail.com> 1565707955 +0800 a tag"; let id = Id::default(); let (_, tag) = parse_tag_object(str, &id).expect("parse failed"); assert_eq!(tag.object, Id::from_str("a541069eb298c4969982721adea07e526d899351").unwrap()); assert_eq!(tag.object_type, ObjectType::COMMIT); assert_eq!(tag.tagger, Some(Identity { name: "spacedragon".to_string(), email: "allendragon@gmail.com".to_string(), date: FixedOffset::east(8 * 3600).timestamp(1565707955, 0), })); assert_eq!(tag.tag, "v0.1".to_string()); assert_eq!(tag.message, "a tag".to_string()); } }
true
1eb4194e090fe7e4ea8a2e37ee7e9e0e94ef8b20
Rust
wangjun861205/nbauth-rust
/src/request.rs
UTF-8
466
2.859375
3
[]
no_license
use serde::Deserialize; #[derive(Debug, Clone, Deserialize)] pub struct SignUp { pub phone: String, pub password: String, } #[derive(Debug, Clone, Deserialize)] pub struct SignIn { pub phone: String, pub password: String, } #[derive(Debug, Clone, Deserialize)] pub struct VerifyToken(pub String); #[derive(Debug, Clone, Deserialize)] pub struct ChangePassword { pub phone: String, pub old_password: String, pub new_password: String, }
true
0eb14bcede809f273baecd8bb2bf0802fb9f2bbd
Rust
lamedh-dev/aws-lambda-rust-runtime
/lambda-http/examples/hello-http-without-macros.rs
UTF-8
616
2.765625
3
[ "Apache-2.0" ]
permissive
use lamedh_http::{ handler, lambda::{Context, Error}, IntoResponse, Request, RequestExt, Response, }; #[tokio::main] async fn main() -> Result<(), Error> { lamedh_runtime::run(handler(func)).await?; Ok(()) } async fn func(event: Request, _: Context) -> Result<impl IntoResponse, Error> { Ok(match event.query_string_parameters().get("first_name") { Some(first_name) => format!("Hello, {}!", first_name).into_response(), _ => Response::builder() .status(400) .body("Empty first name".into()) .expect("failed to render response"), }) }
true
40092dfd0ab586cfae885aade1e81ed409e63515
Rust
savnik/aoc2019
/day02a/src/main.rs
UTF-8
1,426
3.265625
3
[]
no_license
fn main() { let mut input = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,6,1,19,1,5,19,23,2,6,23,27,1,27,5,31,2,9,31,35,1,5,35,39,2,6,39,43,2,6,43,47,1,5,47,51,2,9,51,55,1,5,55,59,1,10,59,63,1,63,6,67,1,9,67,71,1,71,6,75,1,75,13,79,2,79,13,83,2,9,83,87,1,87,5,91,1,9,91,95,2,10,95,99,1,5,99,103,1,103,9,107,1,13,107,111,2,111,10,115,1,115,5,119,2,13,119,123,1,9,123,127,1,5,127,131,2,131,6,135,1,135,5,139,1,139,6,143,1,143,6,147,1,2,147,151,1,151,5,0,99,2,14,0,0]; // Repace position 1 and two with 12 and 2 input[1] = 12; input[2] = 2; let mut index = 0; loop { match input[index] { // Addition 1 => { let read_index_a = input[index+1]; let read_index_b = input[index+2]; let write_index = input[index+3]; input[write_index] = input[read_index_a] + input[read_index_b]; } // Multiplication 2 => { let read_index_a = input[index+1]; let read_index_b = input[index+2]; let write_index = input[index+3]; input[write_index] = input[read_index_a] * input[read_index_b]; } // Program termination 99 => { println!("{}", input[0]); return; } other => panic!("invalid opcode {}", other), } index += 4; } }
true
0e1ca2a818f6d26e9aa0efdb0dd53a1943e8fedb
Rust
jingfee/advent-of-code-rust
/src/y2020/day25.rs
UTF-8
1,600
3.15625
3
[]
no_license
use crate::solver::Solver; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; pub struct Problem; impl Solver for Problem { type Input = (usize, usize); type Output1 = usize; type Output2 = usize; fn parse_input(&self, file: File) -> (usize, usize) { let buf_reader = BufReader::new(file); let mut lines = buf_reader.lines(); ( lines.nth(0).unwrap().unwrap().parse::<usize>().unwrap(), lines.nth(0).unwrap().unwrap().parse::<usize>().unwrap(), ) } fn solve_part_one(&self, input: &(usize, usize)) -> usize { let loop_size_card = find_loop_size(input.0); transform_subject_number(input.1, loop_size_card) } fn solve_part_two(&self, _input: &(usize, usize)) -> usize { 0 } } fn find_loop_size(public_key: usize) -> usize { let mut i = 1; let mut value = 1; loop { value = (value * 7) % 20201227; if value == public_key { break; } i = i + 1; } i } fn transform_subject_number(subject_number: usize, loop_size: usize) -> usize { let mut value = 1; for _i in 0..loop_size { value = (value * subject_number) % 20201227; } value } #[cfg(test)] mod tests { use crate::y2020::day25::*; #[test] fn test_find_loop_size() { assert_eq!(find_loop_size(5764801), 8); assert_eq!(find_loop_size(17807724), 11); assert_eq!(transform_subject_number(17807724, 8), 14897079); assert_eq!(transform_subject_number(5764801, 11), 14897079); } }
true
ea3f3f2580043804ecab352ce6a365b53fbbca6e
Rust
smburdick/dbie
/src/bitmap_vector.rs
UTF-8
1,567
3.390625
3
[]
no_license
mod bitmap_vector { use std::mem; type Word = u64; struct BitmapVector { value: Vec<Word> // TODO could make this an array } impl BitmapVector { fn clone(&self) -> Self { return Self { value: self.value.clone() }; } fn word_length(&self) -> usize { return mem::size_of::<Word>() * 8; } } trait AlgorithmicBitmapVector { fn from_uncompressed(vector: BitmapVector) -> Self; fn and(&self, other: &Self) -> Self; //fn or(&self, other: &BitmapVector) -> BitmapVector; //fn clone(&self) -> Self; } struct WAHMetadata { } struct WAHVector { value: BitmapVector // TODO documentation on vectors // /** // // 2 types of words: literal, fill // Most sig bit = flag // Literal = (flag, litval) when flag = 0 // rem 63 bits are uncompressed bit seq // Fill = (flag, val, len) when flag = 1 // bit with val repeats for len bits when uncompressed // // */ } impl AlgorithmicBitmapVector for WAHVector { // WAHVector::from_uncompressed fn from_uncompressed(vector: BitmapVector) -> WAHVector { // TODO compress vector return WAHVector { value: vector }; } // TODO generic binary 'op' function fn and(&self, other: &WAHVector) -> WAHVector { return WAHVector { value: self.value.clone() }; // TODO } } }
true
dba0d270d57a89c81622ca60b8b7577a8ede0134
Rust
dhedegaard/adventofcode2017
/day19/src/main.rs
UTF-8
3,760
3.875
4
[]
no_license
extern crate time; use std::fs::File; use std::io::Read; use time::now; type Maze = Vec<Vec<char>>; #[derive(Debug, PartialEq)] enum Direction { Up, Down, Left, Right, } fn parse(input: &str) -> Maze { input.lines().map(|line| line.chars().collect()).collect() } fn traverse(maze: &Maze) -> (String, usize) { let mut result = vec![]; let mut steps = 0; // We always start by going down. let mut dir = Direction::Down; // Determine the start position. let (mut x, mut y) = (maze[0].iter().position(|e| *e == '|').unwrap(), 0); loop { // Start by moving in the diretion we're facing. match dir { Direction::Down => { if y + 1 >= maze.len() { break; } y += 1; } Direction::Up => { if y <= 0 { break; } y -= 1; } Direction::Left => { if x <= 0 { break; } x -= 1; } Direction::Right => { if x + 1 >= maze[y].len() { break; } x += 1; } }; steps += 1; // Fetch the current character from the maze. let c = maze[y][x]; // If we hit a character, add it to the result. if c.is_alphabetic() { result.push(c); } // If we're at a crossroads, look for another direction to move to. if c == '+' { if dir == Direction::Up || dir == Direction::Down { if x > 0 && maze[y][x - 1] != ' ' { dir = Direction::Left; } else if x + 1 < maze[y].len() && maze[y][x + 1] != ' ' { dir = Direction::Right; } else { panic!("Unable to move left or right"); } } else if dir == Direction::Left || dir == Direction::Right { if y > 1 && maze[y - 1].len() > x && maze[y - 1][x] != ' ' { dir = Direction::Up; } else if y + 1 < maze.len() && maze[y + 1].len() > x && maze[y + 1][x] != ' ' { dir = Direction::Down; } else { panic!("Unable to move up or down"); } } else { panic!("Hit crossroads, direction is weird: {:?}", dir); } } // If we're outside the track, stop now. if c == ' ' { break; } } (result.iter().collect(), steps) } fn get_input() -> String { let mut input = String::new(); File::open("input.txt") .unwrap() .read_to_string(&mut input) .unwrap(); input } fn main() { { let before = now(); let result = traverse(&parse(&get_input())); println!("part1: {}\ttook: {}", result.0, now() - before); } { let before = now(); let result = traverse(&parse(&get_input())); println!("part2: {}\t\ttook: {}", result.1, now() - before); } } #[cfg(test)] mod tests { use super::*; const TEST_INPUT: &'static str = " | | +--+ A | C F---|----E|--+ | | | D +B-+ +--+ "; #[test] fn test_examples1() { let maze = parse(TEST_INPUT); assert_eq!(traverse(&maze).0, "ABCDEF"); } #[test] fn test_result() { let maze = parse(&get_input()); assert_eq!(traverse(&maze).0, "GEPYAWTMLK"); } #[test] fn test_examples2() { let maze = parse(TEST_INPUT); assert_eq!(traverse(&maze).1, 38); } }
true
aba024edee93dd4707d739713f1bf106f63922a6
Rust
0rvar/advent-of-code-2018
/day06/src/main.rs
UTF-8
2,374
3.234375
3
[]
no_license
use shared::*; use std::collections::HashMap; use std::collections::HashSet; #[derive(Debug, PartialEq, Eq, Hash, Clone)] struct Claim { id: isize, distance: usize, } fn main() { let input = include_str!("input.txt") .trim() .split("\n") .map(|x| { let parts = x .split(", ") .map(|x| x.parse().unwrap()) .collect::<Vec<isize>>(); (parts[0], parts[1]) }) .collect::<Vec<_>>(); let mut map: HashMap<Position, Claim> = HashMap::new(); let mut region_sizes: HashMap<usize, usize> = HashMap::new(); let mut infinite_area_ids = HashSet::new(); let min_x = 0; let min_y = 0; let max_x = 500; let max_y = 500; for x in min_x..=max_x { for y in min_y..=max_y { let mut claim = Claim { id: -1, distance: 100000, }; for (index, coordinate) in input.iter().enumerate() { let distance: usize = manhattan_distance(coordinate.0, coordinate.1, x, y); if distance == claim.distance { claim.id = -2; // The "multiple equidistant" claim } else if distance < claim.distance { claim.id = index as isize; claim.distance = distance; } } if x == max_x || y == max_y || x == min_x || y == min_y { infinite_area_ids.insert(claim.id); } if claim.id >= 0 { *region_sizes.entry(claim.id as usize).or_insert(0) += 1; map.insert(Position { x, y }, claim); } } } for x in &infinite_area_ids { region_sizes.remove(&(*x as usize)); } println!( "Part 1: {}", region_sizes.iter().max_by_key(|&(_, v)| v).unwrap().1 ); let mut area_size = 0usize; for x in min_x..=max_x { for y in min_y..=max_y { let mut total_distance = 0usize; for coordinate in &input { let distance: usize = manhattan_distance(coordinate.0, coordinate.1, x, y); total_distance += distance; } if total_distance < 10000 { area_size += 1; } } } println!("Part 2: {}", area_size); }
true
fa5f7b02086301babbd7ca12c216bea8ec7d1d3a
Rust
timcryt/poker-durak
/src/comb/test.rs
UTF-8
12,389
2.90625
3
[]
no_license
#[cfg(test)] mod tests { use crate::card::*; use crate::comb::*; #[test] fn comb_test_straight_flush() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ten, suit: CardSuit::Hearts }, Card { rank: CardRank::Jack, suit: CardSuit::Hearts }, Card { rank: CardRank::Queen, suit: CardSuit::Hearts }, Card { rank: CardRank::King, suit: CardSuit::Hearts }, Card { rank: CardRank::Ace, suit: CardSuit::Hearts }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::StraightFlush(CardRank::Ace) ); assert_eq!( Comb::new( vec![ Card { rank: CardRank::Two, suit: CardSuit::Hearts }, Card { rank: CardRank::Three, suit: CardSuit::Hearts }, Card { rank: CardRank::Four, suit: CardSuit::Hearts }, Card { rank: CardRank::Five, suit: CardSuit::Hearts }, Card { rank: CardRank::Ace, suit: CardSuit::Hearts }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::StraightFlush(CardRank::Five) ); } #[test] fn comb_test_four_of_a_kind() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ace, suit: CardSuit::Spades }, Card { rank: CardRank::Ace, suit: CardSuit::Clubs }, Card { rank: CardRank::Ace, suit: CardSuit::Diamonds }, Card { rank: CardRank::Ace, suit: CardSuit::Hearts }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::FourOfAKind(CardRank::Ace) ); } #[test] fn comb_test_full_house() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ace, suit: CardSuit::Spades }, Card { rank: CardRank::Ace, suit: CardSuit::Clubs }, Card { rank: CardRank::Ace, suit: CardSuit::Diamonds }, Card { rank: CardRank::King, suit: CardSuit::Hearts }, Card { rank: CardRank::King, suit: CardSuit::Diamonds } ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::FullHouse((CardRank::Ace, CardRank::King)) ); assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ace, suit: CardSuit::Spades }, Card { rank: CardRank::Ace, suit: CardSuit::Clubs }, Card { rank: CardRank::King, suit: CardSuit::Spades }, Card { rank: CardRank::King, suit: CardSuit::Hearts }, Card { rank: CardRank::King, suit: CardSuit::Diamonds } ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::FullHouse((CardRank::King, CardRank::Ace)) ); } #[test] fn comb_test_flush() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Nine, suit: CardSuit::Hearts }, Card { rank: CardRank::Jack, suit: CardSuit::Hearts }, Card { rank: CardRank::Queen, suit: CardSuit::Hearts }, Card { rank: CardRank::King, suit: CardSuit::Hearts }, Card { rank: CardRank::Ace, suit: CardSuit::Hearts }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::Flush([ CardRank::Ace, CardRank::King, CardRank::Queen, CardRank::Jack, CardRank::Nine ]) ); } #[test] fn comb_test_straight() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ten, suit: CardSuit::Hearts }, Card { rank: CardRank::Jack, suit: CardSuit::Spades }, Card { rank: CardRank::Queen, suit: CardSuit::Diamonds }, Card { rank: CardRank::King, suit: CardSuit::Clubs }, Card { rank: CardRank::Ace, suit: CardSuit::Hearts }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::Straight(CardRank::Ace) ); assert_eq!( Comb::new( vec![ Card { rank: CardRank::Two, suit: CardSuit::Hearts }, Card { rank: CardRank::Three, suit: CardSuit::Spades }, Card { rank: CardRank::Four, suit: CardSuit::Diamonds }, Card { rank: CardRank::Five, suit: CardSuit::Clubs }, Card { rank: CardRank::Ace, suit: CardSuit::Hearts }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::Straight(CardRank::Five) ); } #[test] fn comb_test_set() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ace, suit: CardSuit::Spades }, Card { rank: CardRank::Ace, suit: CardSuit::Clubs }, Card { rank: CardRank::Ace, suit: CardSuit::Diamonds }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::Set(CardRank::Ace) ); } #[test] fn comb_test_two_pairs() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ace, suit: CardSuit::Spades }, Card { rank: CardRank::Ace, suit: CardSuit::Clubs }, Card { rank: CardRank::King, suit: CardSuit::Hearts }, Card { rank: CardRank::King, suit: CardSuit::Diamonds } ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::TwoPairs((CardRank::Ace, CardRank::King)) ); } #[test] fn comb_test_pair() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ace, suit: CardSuit::Spades }, Card { rank: CardRank::Ace, suit: CardSuit::Clubs }, ] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::Pair(CardRank::Ace) ); } #[test] fn comb_test_highest_card() { assert_eq!( Comb::new( vec![Card { rank: CardRank::Ace, suit: CardSuit::Spades },] .into_iter() .collect::<HashSet<_>>() ) .unwrap() .rank, CombRank::HighestCard(CardRank::Ace) ); } #[test] fn comb_test_nothing() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ace, suit: CardSuit::Spades }, Card { rank: CardRank::King, suit: CardSuit::Hearts }, ] .into_iter() .collect::<HashSet<_>>() ) .is_none(), true ); } #[test] fn comb_regression_test_all_flush() { assert_eq!( Comb::new( vec![ Card { rank: CardRank::Ten, suit: CardSuit::Spades, }, Card { rank: CardRank::Queen, suit: CardSuit::Hearts, }, Card { rank: CardRank::Two, suit: CardSuit::Spades, }, Card { rank: CardRank::Jack, suit: CardSuit::Hearts, }, Card { rank: CardRank::Two, suit: CardSuit::Diamonds, }, ] .into_iter() .collect() ), None ) } }
true
146cf21688d876533ea24703863c7a67b4865587
Rust
ngortheone/runt
/src/config.rs
UTF-8
2,484
3.09375
3
[ "MIT" ]
permissive
use std::fs::File; use std::io::Read; use std::path::PathBuf; use std::process::Command; use std::vec::Vec; #[derive(Deserialize, Clone)] pub struct Account { pub account: String, pub server: String, pub port: Option<u16>, pub username: String, pub maildir: String, pub password_command: Option<String>, pub password: Option<String>, pub exclude: Option<Vec<String>>, pub idle: Option<Vec<String>>, pub max_concurrency: Option<usize>, } #[derive(Deserialize, Clone)] pub struct Config { pub accounts: Vec<Account>, } impl Config { pub fn new() -> Config { let mut dir = Config::dir(); dir.push("config"); let mut f = File::open(dir).unwrap(); let mut buf: String = String::new(); f.read_to_string(&mut buf).unwrap(); let mut configs: Config = toml::from_str(&buf).unwrap(); for config in &mut configs.accounts { if config.port.is_none() { config.port = Some(993); } if config.password_command.is_some() { let password = Command::new("sh") .arg("-c") .arg(config.password_command.clone().unwrap()) .output() .expect("Could not execute password_command"); config.password = Some( String::from_utf8(password.stdout.as_slice().to_vec()) .unwrap() .trim() .to_string(), ); } } configs } pub fn dir() -> PathBuf { let mut home = match dirs_next::home_dir() { Some(path) => path, _ => PathBuf::from(""), }; home.push(".runt"); home } } impl Account { /// Is this mailbox excluded from synchronization? pub fn is_mailbox_excluded(&self, name: &str) -> bool { if let Some(exclude) = &self.exclude { exclude.contains(&name.to_string()) } else { false } } /// Is this mailbox one we want to IDLE on? /// If the account has a `idle` member, then only mailboxes /// in that list are IDLEd. Otherwise everything that is not /// `exclude`d is IDLEd. pub fn is_mailbox_idled(&self, name: &str) -> bool { if let Some(idle) = &self.idle { idle.contains(&name.to_string()) } else { true } } }
true
cd5d5eb642185bbeec076f3f947a4b0004c7a7c5
Rust
brianjimenez/rust-gso
/src/swarm.rs
UTF-8
2,326
3.03125
3
[ "Apache-2.0" ]
permissive
use super::glowworm::Glowworm; use super::glowworm::distance; use rand::Rng; #[derive(Debug)] pub struct Swarm { pub glowworms: Vec<Glowworm>, } impl Swarm { pub fn new() -> Swarm { Swarm { glowworms: Vec::new(), } } pub fn add_glowworms(&mut self, positions: &Vec<Vec<f64>>) { for i in 0..positions.len() { let x = positions[i][0]; let y = positions[i][1]; self.glowworms.push(Glowworm::new(i as u32, x, y)); } } pub fn update_luciferin(&mut self) { for glowworm in self.glowworms.iter_mut() { glowworm.compute_luciferin(); } } pub fn movement_phase(&mut self, rng: &mut rand::prelude::StdRng) { // Save original positions let mut positions: Vec<Vec<f64>> = Vec::new(); for glowworm in self.glowworms.iter(){ positions.push(glowworm.landscape_position.clone()); } // First search for each glowworm's neighbors let mut neighbors: Vec<Vec<u32>> = Vec::new(); for i in 0..self.glowworms.len() { let mut this_neighbors = Vec::new(); let g1 = &self.glowworms[i]; for j in 0..self.glowworms.len() { if i != j { let g2 = &self.glowworms[j]; if g1.luciferin < g2.luciferin { let distance = distance(g1, g2); if distance < g1.vision_range { this_neighbors.push(g2.id); } } } } neighbors.push(this_neighbors); } // Second compute probability moving towards the neighbor let mut luciferins = Vec::new(); for glowworm in self.glowworms.iter_mut() { luciferins.push(glowworm.luciferin); } for i in 0..self.glowworms.len() { let glowworm = &mut self.glowworms[i]; glowworm.neighbors = neighbors[i].clone(); glowworm.compute_probability_moving_toward_neighbor(&luciferins); } // Finally move to the selected position for i in 0..self.glowworms.len() { let glowworm = &mut self.glowworms[i]; let neighbor_id = glowworm.select_random_neighbor(rng.gen::<f64>()); let position = &positions[neighbor_id as usize]; glowworm.move_towards(neighbor_id, position); glowworm.update_vision_range(); } } }
true