text
stringlengths
8
4.13M
use chrono::NaiveDate; #[derive(Clone, Debug)] pub struct TimeFrame { pub start: NaiveDate, pub end: NaiveDate, } impl TimeFrame { pub fn new(start: NaiveDate, end: NaiveDate) -> TimeFrame { TimeFrame { start, end } } }
use std::error::Error; use std::thread; use std::time::Duration; use rainbow_hat_rs::buzzer::Buzzer; const NOTES: [u32; 36] = [ 71, 71, 71, 71, 71, 71, 71, 64, 67, 71, 69, 69, 69, 69, 69, 69, 69, 62, 66, 69, 71, 71, 71, 71, 71, 71, 71, 73, 74, 77, 74, 71, 69, 66, 64, 64 ]; const TIMES: [u32; 36] = [ 300, 50, 50, 300, 50, 50, 300, 300, 300, 200, 300, 50, 50, 300, 50, 50, 300, 300, 300, 200, 300, 50, 50, 300, 50, 50, 300, 300, 300, 200, 300, 300, 300, 300, 600, 600 ]; /// Play a melody with the buzzer. fn main() -> Result<(), Box<dyn Error>> { let mut buzzer = Buzzer::new()?; for i in 0..36 { buzzer.midi_note(NOTES[i], TIMES[i] as f64 / 1000.0)?; thread::sleep(Duration::from_millis(50)); } Ok(()) }
// mod generated; // use generated::generate; use example_02_set_01::generate; fn main() { let generated_files = generate(); let size: usize = generated_files.values().map(|x| x.data.len()).sum(); println!("count: {}, size: {}", generated_files.len(), size); }
#[macro_use] extern crate failure; // #[macro_use] // extern crate lazy_static; #[macro_use] extern crate serde; #[macro_use] extern crate derive_new; #[cfg(test)] #[macro_use] extern crate serde_json; #[macro_use] mod macros; pub mod core; pub mod json; pub mod prelude; // pub mod core; // pub mod json; // pub mod matchers;
pub fn and(a: bool, b: bool) -> bool { a && b } pub fn or(a: bool, b: bool) -> bool { a || b } pub fn not(a: bool) -> bool { !a } pub fn nand(a: bool, b: bool) -> bool { !(a && b) } pub fn nor(a: bool, b: bool) -> bool { !(a || b) } pub fn xor(a: bool, b: bool) -> bool { (a || b) && (!a || !b) } pub fn impli(a: bool, b: bool) -> bool { (a && b) || !a } pub fn equ(a: bool, b: bool) -> bool { impli(a, b) && impli(b, a) } pub fn table2(f: fn(bool, bool) -> bool) -> Vec<(bool, bool, bool)> { vec![ (true, true, f(true, true)), (true, false, f(true, false)), (false, true, f(false, true)), (false, false, f(false, false)), ] } #[cfg(test)] mod tests { use super::*; #[test] fn test_nand() { assert_eq!(nand(true, true), false); assert_eq!(nand(true, false), true); assert_eq!(nand(false, true), true); assert_eq!(nand(false, false), true); } #[test] fn test_nor() { assert_eq!(nor(true, true), false); assert_eq!(nor(true, false), false); assert_eq!(nor(false, true), false); assert_eq!(nor(false, false), true); } #[test] fn test_xor() { assert_eq!(xor(true, true), false); assert_eq!(xor(true, false), true); assert_eq!(xor(false, true), true); assert_eq!(xor(false, false), false); } #[test] fn test_impli() { assert_eq!(impli(true, true), true); assert_eq!(impli(true, false), false); assert_eq!(impli(false, true), true); assert_eq!(impli(false, false), true); } #[test] fn test_equ() { assert_eq!(equ(true, true), true); assert_eq!(equ(true, false), false); assert_eq!(equ(false, true), false); assert_eq!(equ(false, false), true); } #[test] fn test_table2() { let f = |a, b| and(a, or(a, b)); assert_eq!( table2(f), vec![ (true, true, true), (true, false, true), (false, true, false), (false, false, false) ] ); } }
#[doc = "Reader of register SDMMC_ID"] pub type R = crate::R<u32, super::SDMMC_ID>; #[doc = "Reader of field `IP_ID`"] pub type IP_ID_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - SDMMC IP identification."] #[inline(always)] pub fn ip_id(&self) -> IP_ID_R { IP_ID_R::new((self.bits & 0xffff_ffff) as u32) } }
struct Segment { x1: u32, y1: u32, x2: u32, y2: u32, } fn main() { let input = std::fs::read_to_string("input.txt").unwrap(); let lines: Vec<&str> = input.split("\n").collect(); // parse to struct let mut segments: Vec<Segment> = Vec::new(); for line in lines { let parts: Vec<&str> = line.split(" -> ").collect(); let s: Vec<u32> = parts[0] .split(",") .map(|v| v.parse::<u32>().unwrap()) .collect(); let e: Vec<u32> = parts[1] .split(",") .map(|v| v.parse::<u32>().unwrap()) .collect(); segments.push(Segment { x1: s[0], y1: s[1], x2: e[0], y2: e[1], }) } // solve println!("part 1={}", part1(&segments)); println!("part 2={}", part2(&segments)); } fn part1(segments: &Vec<Segment>) -> u32 { let mut ret: u32 = 0; let mut seen = std::collections::HashMap::<String, u32>::new(); for seg in segments { if seg.x1 == seg.x2 { let range = get_range(seg.y1, seg.y2); for y in range { let k = key(seg.x1, y); let v: u32 = match seen.get(&k) { None => 0, Some(i) => *i, }; match v { 0 => { seen.insert(k, 1); } 1 => { seen.insert(k, v + 1); ret += 1; } _ => { seen.insert(k, v + 1); } } } } else if seg.y1 == seg.y2 { let range = get_range(seg.x1, seg.x2); for x in range { let k = key(x, seg.y1); let v: u32 = match seen.get(&k) { None => 0, Some(i) => *i, }; match v { 0 => { seen.insert(k, 1); } 1 => { seen.insert(k, v + 1); ret += 1; } _ => { seen.insert(k, v + 1); } } } } } ret } fn part2(segments: &Vec<Segment>) -> u32 { let mut ret: u32 = 0; let mut seen = std::collections::HashMap::<String, u32>::new(); for seg in segments { // lots of copy / paste ¯\_(ツ)_/¯ if seg.x1 == seg.x2 { let range = get_range(seg.y1, seg.y2); for y in range { let k = key(seg.x1, y); let v: u32 = match seen.get(&k) { None => 0, Some(i) => *i, }; match v { 0 => { seen.insert(k, 1); } 1 => { seen.insert(k, v + 1); ret += 1; } _ => { seen.insert(k, v + 1); } } } } else if seg.y1 == seg.y2 { let range = get_range(seg.x1, seg.x2); for x in range { let k = key(x, seg.y1); let v: u32 = match seen.get(&k) { None => 0, Some(i) => *i, }; match v { 0 => { seen.insert(k, 1); } 1 => { seen.insert(k, v + 1); ret += 1; } _ => { seen.insert(k, v + 1); } } } } else { let mut rangex = get_range(seg.x1, seg.x2); let mut rangey = get_range(seg.y1, seg.y2); loop { let x = match &rangex.next() { None => break, Some(i) => *i, }; let y = match &rangey.next() { None => break, Some(i) => *i, }; let k = key(x, y); let v: u32 = match seen.get(&k) { None => 0, Some(i) => *i, }; match v { 0 => { seen.insert(k, 1); } 1 => { seen.insert(k, v + 1); ret += 1; } _ => { seen.insert(k, v + 1); } } } } } ret } fn key(x: u32, y: u32) -> String { format!["{} {}", x, y] } // return a increasing or decreasing range from x to y, inclusive fn get_range(x: u32, y: u32) -> Box<dyn Iterator<Item = u32>> { if x < y { return Box::new(x..y + 1); } Box::new((y..x + 1).rev()) }
use std::fmt; use std::slice; use crate::erts::term::prelude::{Boxed, Encoded, Term}; /// This struct contains the set of roots which are to be scanned during garbage collection /// /// The root set is effectively a vector of pointers to terms, i.e. pointers to the roots, /// rather than the roots directly, this is because the roots are modified during garbage /// collection to point to the new locations of the values they reference, so we need the /// pointer to the root to perform the replacement pub struct RootSet(Vec<Boxed<Term>>); impl RootSet { pub fn new(roots: &mut [Term]) -> Self { let len = roots.len(); let mut set = Vec::with_capacity(len); if len > 0 { for root in roots { // Skip immediates if root.is_immediate() { continue; } set.push(unsafe { Boxed::new_unchecked(root) }); } } Self(set) } pub fn empty() -> Self { Self(Vec::new()) } #[inline] pub fn push(&mut self, root: *mut Term) { let root = unsafe { &mut *root }; // Ignore immediates if root.is_immediate() { return; } self.0.push(Boxed::new(root).unwrap()); } #[inline] pub fn push_range(&mut self, start: *mut Term, size: usize) { let end = unsafe { start.add(size) }; let mut pos = start; while pos < end { let term = unsafe { &*pos }; if term.is_boxed() || term.is_non_empty_list() { // Add pointer to box self.0.push(unsafe { Boxed::new_unchecked(pos) }); pos = unsafe { pos.add(1) }; } else if term.is_header() { // Add pointer to header self.0.push(unsafe { Boxed::new_unchecked(pos) }); pos = unsafe { pos.add(term.arity()) }; } else { // For all others, skip over pos = unsafe { pos.add(1) }; } } } #[inline] pub fn iter(&self) -> slice::Iter<Boxed<Term>> { self.0.as_slice().iter() } } impl From<Vec<Boxed<Term>>> for RootSet { #[inline] fn from(roots: Vec<Boxed<Term>>) -> Self { Self(roots) } } // NOTE: This is for legacy code that should probably be removed impl From<&mut [Term]> for RootSet { fn from(roots: &mut [Term]) -> Self { Self::new(roots) } } impl Default for RootSet { fn default() -> Self { Self::empty() } } impl fmt::Debug for RootSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for root in self.0.iter().map(|b| b.as_ptr()) { unsafe { let term = &*root; let decoded = term.decode(); f.write_fmt(format_args!( " {:p}: {:0bit_len$b} {:?}\n", root, *(root as *const usize), decoded, bit_len = (core::mem::size_of::<usize>() * 8) ))?; } } Ok(()) } } #[cfg(test)] mod tests { use core::ptr; use crate::erts::process::alloc::TermAlloc; use crate::erts::term::prelude::*; use crate::erts::testing::RegionHeap; use super::*; #[test] fn modified_rootset_updates_roots() { let mut heap = RegionHeap::default(); let tuple = heap .tuple_from_slice(&[atom!("hello"), atom!("world")]) .unwrap(); let mut stack_ref: Term = tuple.into(); let mut rootset = RootSet::empty(); rootset.push(&mut stack_ref as *mut _); for root in rootset.iter() { let root_ref = root.as_ref(); assert!(root_ref.is_boxed()); unsafe { ptr::write(root.as_ptr(), Term::NIL); } } assert_eq!(stack_ref, Term::NIL); } }
// // Sysinfo // // Copyright (c) 2017 Guillaume Gomez // #[cfg(not(target_os = "windows"))] use std::fs; #[cfg(not(target_os = "windows"))] use std::path::{Path, PathBuf}; #[cfg(not(target_os = "windows"))] use std::ffi::OsStr; #[cfg(not(target_os = "windows"))] use std::os::unix::ffi::OsStrExt; #[cfg(not(target_os = "windows"))] use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT}; use Pid; #[cfg(not(target_os = "windows"))] pub fn realpath(original: &Path) -> PathBuf { if let Some(original_str) = original.to_str() { let ori = Path::new(original_str); // Right now lstat on windows doesn't work quite well if cfg!(windows) { return PathBuf::from(ori); } let result = PathBuf::from(original); let mut result_s = result.to_str().unwrap_or("").as_bytes().to_vec(); result_s.push(0); let mut buf: stat = unsafe { ::std::mem::uninitialized() }; let res = unsafe { lstat(result_s.as_ptr() as *const c_char, &mut buf as *mut stat) }; if res < 0 || (buf.st_mode & S_IFMT) != S_IFLNK { PathBuf::new() } else { match fs::read_link(&result) { Ok(f) => f, Err(_) => PathBuf::new(), } } } else { PathBuf::new() } } /* convert a path to a NUL-terminated Vec<u8> suitable for use with C functions */ #[cfg(not(target_os = "windows"))] pub fn to_cpath(path: &Path) -> Vec<u8> { let path_os: &OsStr = path.as_ref(); let mut cpath = path_os.as_bytes().to_vec(); cpath.push(0); cpath } /// Returns the pid for the current process. #[cfg(not(target_os = "windows"))] pub fn get_current_pid() -> Pid { unsafe { ::libc::getpid() } } /// Returns the pid for the current process. #[cfg(target_os = "windows")] pub fn get_current_pid() -> Pid { use winapi::um::processthreadsapi::GetCurrentProcessId; unsafe { GetCurrentProcessId() as Pid } }
// Translated from C++ to Rust. The original C++ code can be found at // https://github.com/jk-jeon/dragonbox and carries the following license: // // Copyright 2020-2021 Junekey Jeon // // The contents of this file may be used under the terms of // the Apache License v2.0 with LLVM Exceptions. // // (See accompanying file LICENSE-Apache or copy at // https://llvm.org/foundation/relicensing/LICENSE.txt) // // Alternatively, the contents of this file may be used under the terms of // the Boost Software License, Version 1.0. // (See accompanying file LICENSE-Boost or copy at // https://www.boost.org/LICENSE_1_0.txt) // // Unless required by applicable law or agreed to in writing, this software // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. use core::ptr; // sign(1) + significand(17) + decimal_point(1) + exp_marker(1) + exp_sign(1) + exp(3) pub(crate) const MAX_OUTPUT_STRING_LENGTH: usize = 1 + 17 + 1 + 1 + 1 + 3; pub(crate) unsafe fn to_chars(x: f64, mut buffer: *mut u8) -> *mut u8 { let br = x.to_bits(); let exponent_bits = crate::extract_exponent_bits(br); let s = crate::remove_exponent_bits(br, exponent_bits); if crate::is_negative(s) { *buffer = b'-'; buffer = buffer.add(1); } if crate::is_nonzero(br) { let result = crate::to_decimal(x); to_chars_detail(result.significand, result.exponent, buffer) } else { ptr::copy_nonoverlapping(b"0E0".as_ptr(), buffer, 3); buffer.add(3) } } #[rustfmt::skip] static RADIX_100_TABLE: [u8; 200] = [ b'0', b'0', b'0', b'1', b'0', b'2', b'0', b'3', b'0', b'4', b'0', b'5', b'0', b'6', b'0', b'7', b'0', b'8', b'0', b'9', b'1', b'0', b'1', b'1', b'1', b'2', b'1', b'3', b'1', b'4', b'1', b'5', b'1', b'6', b'1', b'7', b'1', b'8', b'1', b'9', b'2', b'0', b'2', b'1', b'2', b'2', b'2', b'3', b'2', b'4', b'2', b'5', b'2', b'6', b'2', b'7', b'2', b'8', b'2', b'9', b'3', b'0', b'3', b'1', b'3', b'2', b'3', b'3', b'3', b'4', b'3', b'5', b'3', b'6', b'3', b'7', b'3', b'8', b'3', b'9', b'4', b'0', b'4', b'1', b'4', b'2', b'4', b'3', b'4', b'4', b'4', b'5', b'4', b'6', b'4', b'7', b'4', b'8', b'4', b'9', b'5', b'0', b'5', b'1', b'5', b'2', b'5', b'3', b'5', b'4', b'5', b'5', b'5', b'6', b'5', b'7', b'5', b'8', b'5', b'9', b'6', b'0', b'6', b'1', b'6', b'2', b'6', b'3', b'6', b'4', b'6', b'5', b'6', b'6', b'6', b'7', b'6', b'8', b'6', b'9', b'7', b'0', b'7', b'1', b'7', b'2', b'7', b'3', b'7', b'4', b'7', b'5', b'7', b'6', b'7', b'7', b'7', b'8', b'7', b'9', b'8', b'0', b'8', b'1', b'8', b'2', b'8', b'3', b'8', b'4', b'8', b'5', b'8', b'6', b'8', b'7', b'8', b'8', b'8', b'9', b'9', b'0', b'9', b'1', b'9', b'2', b'9', b'3', b'9', b'4', b'9', b'5', b'9', b'6', b'9', b'7', b'9', b'8', b'9', b'9', ]; #[rustfmt::skip] static TRAILING_ZERO_COUNT_TABLE: [i8; 100] = [ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; fn decimal_length_minus_1(v: u32) -> i32 { debug_assert!(v < 1000000000); if v >= 100000000 { 8 } else if v >= 10000000 { 7 } else if v >= 1000000 { 6 } else if v >= 100000 { 5 } else if v >= 10000 { 4 } else if v >= 1000 { 3 } else if v >= 100 { 2 } else if v >= 10 { 1 } else { 0 } } // Granlund-Montgomery style fast division struct QuotientRemainderPair { quotient: u32, remainder: u32, } fn fast_div<const DIVISOR: u32, const MAX_PRECISION: u32, const ADDITIONAL_PRECISION: u32>( n: u32, ) -> QuotientRemainderPair { debug_assert!(MAX_PRECISION > 0 && MAX_PRECISION <= 32); debug_assert!(n < (1 << MAX_PRECISION)); let left_end = (((1 << (MAX_PRECISION + ADDITIONAL_PRECISION)) + DIVISOR - 1) / DIVISOR) as u32; let right_end = (((1 << ADDITIONAL_PRECISION) * ((1 << MAX_PRECISION) + 1)) / DIVISOR) as u32; // Ensures sufficient precision. debug_assert!(left_end <= right_end); // Ensures no overflow. debug_assert!(left_end <= (1 << (32 - MAX_PRECISION)) as u32); let quotient = (n * left_end) >> (MAX_PRECISION + ADDITIONAL_PRECISION); let remainder = n - DIVISOR * quotient; QuotientRemainderPair { quotient, remainder, } } unsafe fn to_chars_detail(significand: u64, mut exponent: i32, mut buffer: *mut u8) -> *mut u8 { let mut s32: u32; let mut remaining_digits_minus_1: i32; let mut exponent_position: i32; let mut may_have_more_trailing_zeros = false; if significand >> 32 != 0 { // Since significand is at most 10^17, the quotient is at most 10^9, so // it fits inside 32-bit integer s32 = (significand / 1_0000_0000) as u32; let mut r = (significand as u32).wrapping_sub(s32.wrapping_mul(1_0000_0000)); remaining_digits_minus_1 = decimal_length_minus_1(s32) + 8; exponent += remaining_digits_minus_1; exponent_position = remaining_digits_minus_1 + 2; if r != 0 { // Print 8 digits // `c = r % 1_0000` https://bugs.llvm.org/show_bug.cgi?id=38217 let c = r - 1_0000 * (r / 1_0000); r /= 1_0000; // c1 = r / 100; c2 = r % 100; let QuotientRemainderPair { quotient: c1, remainder: c2, } = fast_div::<100, 14, 5>(r); // c3 = c / 100; c4 = c % 100; let QuotientRemainderPair { quotient: c3, remainder: c4, } = fast_div::<100, 14, 5>(c); 'after_print_label: loop { 'print_c1_label: loop { 'print_c2_label: loop { 'print_c3_label: loop { 'print_c4_label: loop { let mut tz = *TRAILING_ZERO_COUNT_TABLE.get_unchecked(c4 as usize); if tz == 0 { break 'print_c4_label; } else if tz == 1 { *buffer.offset(remaining_digits_minus_1 as isize) = *RADIX_100_TABLE.get_unchecked(c4 as usize * 2); exponent_position -= 1; break 'print_c3_label; } tz = *TRAILING_ZERO_COUNT_TABLE.get_unchecked(c3 as usize); if tz == 0 { exponent_position -= 2; break 'print_c3_label; } else if tz == 1 { *buffer.offset(remaining_digits_minus_1 as isize - 2) = *RADIX_100_TABLE.get_unchecked(c3 as usize * 2); exponent_position -= 3; break 'print_c2_label; } tz = *TRAILING_ZERO_COUNT_TABLE.get_unchecked(c2 as usize); if tz == 0 { exponent_position -= 4; break 'print_c2_label; } else if tz == 1 { *buffer.offset(remaining_digits_minus_1 as isize - 4) = *RADIX_100_TABLE.get_unchecked(c2 as usize * 2); exponent_position -= 5; break 'print_c1_label; } tz = *TRAILING_ZERO_COUNT_TABLE.get_unchecked(c1 as usize); if tz == 0 { exponent_position -= 6; break 'print_c1_label; } // We assumed r != 0, so c1 cannot be zero in this case. debug_assert!(tz == 1); *buffer.offset(remaining_digits_minus_1 as isize - 6) = *RADIX_100_TABLE.get_unchecked(c1 as usize * 2); exponent_position -= 7; break 'after_print_label; } ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c4 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize), 2, ); break; } ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c3 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize - 2), 2, ); break; } ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c2 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize - 4), 2, ); break; } ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c1 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize - 6), 2, ); break; } } // r != 0 else { // r == 0 exponent_position -= 8; may_have_more_trailing_zeros = true; } remaining_digits_minus_1 -= 8; } else { s32 = significand as u32; if s32 >= 10_0000_0000 { remaining_digits_minus_1 = 9; } else { remaining_digits_minus_1 = decimal_length_minus_1(s32); } exponent += remaining_digits_minus_1; exponent_position = remaining_digits_minus_1 + 2; may_have_more_trailing_zeros = true; } while remaining_digits_minus_1 >= 4 { // c = s32 % 1_0000` https://bugs.llvm.org/show_bug.cgi?id=38217 let c = s32 - 1_0000 * (s32 / 1_0000); s32 /= 1_0000; // c1 = c / 100; c2 = c % 100; let QuotientRemainderPair { quotient: c1, remainder: c2, } = fast_div::<100, 14, 5>(c); 'inside_loop_after_print_label: loop { 'inside_loop_print_c1_label: loop { 'inside_loop_print_c2_label: loop { if may_have_more_trailing_zeros { let mut tz = *TRAILING_ZERO_COUNT_TABLE.get_unchecked(c2 as usize); if tz == 0 { may_have_more_trailing_zeros = false; break 'inside_loop_print_c2_label; } else if tz == 1 { may_have_more_trailing_zeros = false; exponent_position -= 1; *buffer.offset(remaining_digits_minus_1 as isize) = *RADIX_100_TABLE.get_unchecked(c2 as usize * 2); break 'inside_loop_print_c1_label; } tz = *TRAILING_ZERO_COUNT_TABLE.get_unchecked(c1 as usize); if tz == 0 { may_have_more_trailing_zeros = false; exponent_position -= 2; break 'inside_loop_print_c1_label; } else if tz == 1 { may_have_more_trailing_zeros = false; exponent_position -= 3; *buffer.offset(remaining_digits_minus_1 as isize - 2) = *RADIX_100_TABLE.get_unchecked(c1 as usize * 2); break 'inside_loop_after_print_label; } exponent_position -= 4; break 'inside_loop_after_print_label; } break; } ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c2 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize), 2, ); break; } ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c1 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize - 2), 2, ); break; } remaining_digits_minus_1 -= 4; } if remaining_digits_minus_1 >= 2 { // c1 = s32 / 100; c2 = s32 % 100; let QuotientRemainderPair { quotient: c1, remainder: c2, } = fast_div::<100, 14, 5>(s32); s32 = c1; if may_have_more_trailing_zeros { let tz = *TRAILING_ZERO_COUNT_TABLE.get_unchecked(c2 as usize); exponent_position -= tz as i32; if tz == 0 { ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c2 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize), 2, ); may_have_more_trailing_zeros = false; } else if tz == 1 { *buffer.offset(remaining_digits_minus_1 as isize) = *RADIX_100_TABLE.get_unchecked(c2 as usize * 2); may_have_more_trailing_zeros = false; } } else { ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(c2 as usize * 2), buffer.offset(remaining_digits_minus_1 as isize), 2, ); } remaining_digits_minus_1 -= 2; } if remaining_digits_minus_1 > 0 { debug_assert!(remaining_digits_minus_1 == 1); // d1 = s32 / 10; d2 = s32 % 10; let QuotientRemainderPair { quotient: d1, remainder: d2, } = fast_div::<10, 7, 3>(s32); *buffer = b'0' + d1 as u8; if may_have_more_trailing_zeros && d2 == 0 { buffer = buffer.add(1); } else { *buffer.add(1) = b'.'; *buffer.add(2) = b'0' + d2 as u8; buffer = buffer.offset(exponent_position as isize); } } else { *buffer = b'0' + s32 as u8; if may_have_more_trailing_zeros { buffer = buffer.add(1); } else { *buffer.add(1) = b'.'; buffer = buffer.offset(exponent_position as isize); } } // Print exponent and return if exponent < 0 { ptr::copy_nonoverlapping(b"E-".as_ptr(), buffer, 2); buffer = buffer.add(2); exponent = -exponent; } else { *buffer = b'E'; buffer = buffer.add(1); } if exponent >= 100 { // d1 = exponent / 10; d2 = exponent % 10; let QuotientRemainderPair { quotient: d1, remainder: d2, } = fast_div::<10, 10, 3>(exponent as u32); ptr::copy_nonoverlapping(RADIX_100_TABLE.as_ptr().add(d1 as usize * 2), buffer, 2); *buffer.add(2) = b'0' + d2 as u8; buffer = buffer.add(3); } else if exponent >= 10 { ptr::copy_nonoverlapping( RADIX_100_TABLE.as_ptr().add(exponent as usize * 2), buffer, 2, ); buffer = buffer.add(2); } else { *buffer = b'0' + exponent as u8; buffer = buffer.add(1); } buffer }
use bincode::serialize; use ckb_jsonrpc_types::{JsonBytes, ScriptHashType}; use ckb_simple_account_layer::{run_with_context, CkbBlake2bHasher, Config, RunContext}; use ckb_types::{ bytes::{BufMut, Bytes, BytesMut}, core, packed, prelude::*, H160, H256, }; use ckb_vm::{ registers::{A0, A1, A7}, Error as VMError, Memory, Register, SupportMachine, }; use rocksdb::{WriteBatch, DB}; use sparse_merkle_tree::{default_store::DefaultStore, SparseMerkleTree, H256 as SmtH256}; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::error::Error as StdError; use std::sync::Arc; use std::thread::sleep; use std::time::Duration; use super::{db_get, value, Key, Loader}; use crate::client::HttpRpcClient; use crate::types::{ parse_log, smth256_to_h256, vm_load_data, vm_load_h160, vm_load_h256, vm_load_i32, vm_load_i64, vm_load_u32, vm_load_u8, CallKind, ContractAddress, ContractChange, ContractMeta, EoaAddress, RunConfig, WitnessData, }; pub const TYPE_ARGS_LEN: usize = 20; // 32 bytes storage root + 32 bytes code_hash pub const OUTPUT_DATA_LEN: usize = 32 + 32; pub struct Indexer { pub db: Arc<DB>, pub loader: Loader, pub client: HttpRpcClient, pub run_config: RunConfig, } impl Indexer { pub fn new(db: Arc<DB>, ckb_uri: &str, run_config: RunConfig) -> Self { let loader = Loader::new(Arc::clone(&db), ckb_uri).unwrap(); Indexer { db, loader, client: HttpRpcClient::new(ckb_uri.to_string()), run_config, } } // Ideally this should never return. The caller is responsible for wrapping // it into a separate thread. pub fn index(&mut self) -> Result<(), String> { let type_code_hash: H256 = self.run_config.type_script.code_hash().unpack(); let type_hash_type = { let ty = core::ScriptHashType::try_from(self.run_config.type_script.hash_type()).unwrap(); ScriptHashType::from(ty) }; log::info!("type code hash: {:x}", type_code_hash); log::info!("type hash type: {:?}", type_hash_type); let last_block_key_bytes = Bytes::from(&Key::Last); loop { let next_header = if let Some(value::Last { number, hash }) = db_get(&self.db, &last_block_key_bytes)? { match self.client.get_header_by_number(number + 1)? { Some(header) if header.inner.parent_hash == hash => header, // Rollback Some(_header) => { log::info!("Rollback block, nubmer={}, hash={}", number, hash); let block_delta_key = Bytes::from(&Key::BlockDelta(number)); let block_delta: value::BlockDelta = db_get(&self.db, &block_delta_key)? .unwrap_or_else(|| panic!("Can not load BlockDelta({})", number)); let last_block_info_opt = if number >= 1 { let last_block_map_key = Bytes::from(&Key::BlockMap(number - 1)); let block_hash: value::BlockMap = db_get(&self.db, &last_block_map_key)?.unwrap_or_else(|| { panic!("Can not load BlockMap({})", number - 1) }); Some(value::Last { number: number - 1, hash: block_hash.0, }) } else { None }; let mut batch = WriteBatch::default(); for (address, is_create) in block_delta.contracts { let change_start_key = Key::ContractChange { address: address.clone(), number: Some(number), tx_index: None, output_index: None, }; let change_end_key = Key::ContractChange { address: address.clone(), number: Some(number + 1), tx_index: None, output_index: None, }; let logs_start_key = Key::ContractLogs { address: address.clone(), number: Some(number), tx_index: None, output_index: None, }; let logs_end_key = Key::ContractLogs { address: address.clone(), number: Some(number + 1), tx_index: None, output_index: None, }; batch.delete_range( &Bytes::from(&change_start_key), &Bytes::from(&change_end_key), ); batch.delete_range( &Bytes::from(&logs_start_key), &Bytes::from(&logs_end_key), ); if is_create { batch.delete(&Bytes::from(&Key::ContractMeta(address))); } } for (lock_hash, tx_index, output_index, value) in block_delta.added_cells { batch.delete(&Bytes::from(&Key::LockLiveCell { lock_hash, number: Some(number), tx_index: Some(tx_index), output_index: Some(output_index), })); batch.delete(&Bytes::from(&Key::LiveCellMap(value.out_point()))); } for (lock_hash, old_number, tx_index, output_index, value) in block_delta.removed_cells { let key = Key::LockLiveCell { lock_hash, number: Some(old_number), tx_index: Some(tx_index), output_index: Some(output_index), }; batch.put(&Bytes::from(&key), &serialize(&value).unwrap()); let map_key = Key::LiveCellMap(value.out_point()); let map_value = value::LiveCellMap { number: old_number, tx_index, }; batch.put(&Bytes::from(&map_key), &serialize(&map_value).unwrap()); } for contract_address in block_delta.destructed_contracts { let key_bytes = Bytes::from(&Key::ContractMeta(contract_address.clone())); let mut meta: value::ContractMeta = db_get(&self.db, &key_bytes)? .ok_or_else(|| { format!("no such contract: {:x}", contract_address.0) })?; assert_eq!(meta.destructed, true); meta.destructed = false; batch.put(&key_bytes, &serialize(&meta).unwrap()); } batch.delete(&Bytes::from(&Key::BlockMap(number))); batch.delete(&block_delta_key); // Update last block info if let Some(block_info) = last_block_info_opt { let value_bytes = serialize(&block_info).map_err(|err| err.to_string())?; batch.put(&last_block_key_bytes, &value_bytes); } self.db.write(batch).map_err(|err| err.to_string())?; continue; } None => { // Reach the tip, wait 200ms for next block sleep(Duration::from_millis(100)); // TODO: clean up OLD block delta here (before tip-200) continue; } } } else { self.client.get_header_by_number(0)?.unwrap() }; let next_block = match self.client.get_block(next_header.hash.clone())? { Some(block) => block, None => { log::warn!("Can not get block by hash: {:?}", next_header.hash); sleep(Duration::from_millis(200)); continue; } }; let next_number = next_header.inner.number.value(); let next_hash = next_header.hash; log::info!( "Process block: hash={:#x}, number={}", next_hash, next_number ); let mut block_changes: Vec<ContractChange> = Vec::new(); let mut block_codes: Vec<ContractMeta> = Vec::new(); let mut destructed_contracts: Vec<ContractAddress> = Vec::new(); let mut added_cells: HashSet<(H256, u32, u32, value::LockLiveCell)> = HashSet::new(); let mut removed_cells: HashSet<(H256, u64, u32, u32, value::LockLiveCell)> = HashSet::new(); let mut block_added_cells: HashMap<value::LockLiveCell, value::LiveCellMap> = HashMap::default(); let mut block_removed_cells: HashSet<value::LockLiveCell> = HashSet::default(); for (tx_index, (tx, tx_hash)) in next_block .transactions .into_iter() .map(|tx| (tx.inner, tx.hash)) .enumerate() { log::debug!("process tx: hash={:#x}, tx_index: {}", tx_hash, tx_index); // Information from upper level // 1. block number // 2. tx_hash // 3. tx_index let mut script_groups: HashMap<ContractAddress, ContractInfo> = HashMap::default(); for (input_index, input) in tx.inputs.into_iter().enumerate() { // Information from input // 1. is_create // // - old storage if input.previous_output.tx_hash == H256::default() { continue; } let prev_tx = self .client .get_transaction(input.previous_output.tx_hash.clone())? .unwrap() .transaction .inner; let prev_index = input.previous_output.index.value() as usize; let output = prev_tx.outputs[prev_index].clone(); let output_data_size = prev_tx.outputs_data[prev_index].len() as u32; let data = prev_tx.outputs_data[prev_index].clone().into_bytes(); let capacity = output.capacity.value(); if let Some(ref type_script) = output.type_ { log::debug!( "inputs[{}]: type_script.code_hash={:x}", input_index, type_script.code_hash ); log::debug!( "inputs[{}]: type_script.hash_type={:?}", input_index, type_script.hash_type ); } let type_script = output.type_.clone().unwrap_or_default(); if data.len() == OUTPUT_DATA_LEN && type_script.code_hash == type_code_hash && type_script.hash_type == type_hash_type && type_script.args.len() == TYPE_ARGS_LEN { log::debug!("match type script: input_index={}", input_index); let address = ContractAddress::try_from(type_script.args.as_bytes()) .expect("checked length"); let change = self.loader.load_latest_contract_change( address.clone(), None, false, true, )?; let mut info = ContractInfo::default(); info.tree = change.merkle_tree(); info.input = Some((input_index, change)); script_groups.insert(address, info); } let out_point = packed::OutPoint::from(input.previous_output.clone()); let prev_tx_hash = input.previous_output.tx_hash; let prev_output_index = input.previous_output.index.value(); let lock_hash: H256 = packed::Script::from(output.lock) .calc_script_hash() .unpack(); let value = value::LockLiveCell { tx_hash: prev_tx_hash, output_index: prev_output_index, capacity, data_size: output_data_size, type_script_hash: output .type_ .map(packed::Script::from) .map(|data| data.calc_script_hash().unpack()), }; let info: value::LiveCellMap = block_added_cells.get(&value).cloned().unwrap_or_else(|| { db_get(&self.db, &Bytes::from(&Key::LiveCellMap(out_point.clone()))) .unwrap() .unwrap() }); block_removed_cells.insert(value.clone()); removed_cells.insert(( lock_hash, info.number, info.tx_index, prev_output_index, value, )); } for (output_index, output) in tx.outputs.into_iter().enumerate() { // Information from output // 1. contract address // 2. output_index let data = tx.outputs_data[output_index].clone().into_bytes(); let data_size = data.len() as u32; if let Some(ref type_script) = output.type_ { log::debug!( "outputs[{}]: type_script.code_hash={:x}", output_index, type_script.code_hash ); log::debug!( "outputs[{}]: type_script.hash_type={:?}", output_index, type_script.hash_type ); } let type_script = output.type_.clone().unwrap_or_default(); if data.len() == OUTPUT_DATA_LEN && type_script.code_hash == type_code_hash && type_script.hash_type == type_hash_type && type_script.args.len() == TYPE_ARGS_LEN { log::debug!("match type script: output_index={}", output_index); let address = ContractAddress::try_from(type_script.args.as_bytes()) .expect("checked length"); let info = script_groups.entry(address).or_default(); if info.output.is_some() { panic!("multiple output contract address"); } info.output = Some((output_index, packed::CellOutput::from(output.clone()))); } let lock_hash: H256 = packed::Script::from(output.lock) .calc_script_hash() .unpack(); let value = value::LockLiveCell { tx_hash: tx_hash.clone(), output_index: output_index as u32, capacity: output.capacity.value(), data_size, type_script_hash: output .type_ .map(packed::Script::from) .map(|data| data.calc_script_hash().unpack()), }; block_added_cells.insert( value.clone(), value::LiveCellMap { number: next_number, tx_index: tx_index as u32, }, ); added_cells.insert((lock_hash, tx_index as u32, output_index as u32, value)); } if let Some(mut extractor) = ContractExtractor::init( self.run_config.clone(), tx_hash, tx_index as u32, tx.witnesses, script_groups, )? { extractor.run().map_err(|err| err.to_string())?; block_changes.extend(extractor.get_contract_changes(next_number)); block_codes.extend(extractor.get_created_contracts()); destructed_contracts.extend(extractor.get_destructed_contracts()); } } let mut batch = WriteBatch::default(); // Key::BlockMap let block_map_value_bytes = serialize(&value::BlockMap(next_hash.clone())).unwrap(); batch.put( &Bytes::from(&Key::BlockMap(next_number)), &block_map_value_bytes, ); // Key::Last let last_block_info = value::Last { number: next_number, hash: next_hash.clone(), }; let last_block_info_bytes = serialize(&last_block_info).unwrap(); batch.put(&last_block_key_bytes, &last_block_info_bytes); let mut block_contracts: HashMap<ContractAddress, bool> = HashMap::default(); for change in block_changes { block_contracts.insert(change.address.clone(), change.is_create); // Key::ContractChange let db_value_bytes = serialize(&change.db_value()).unwrap(); batch.put(&Bytes::from(&change.db_key()), &db_value_bytes); // Key::ContractLogs if let Some(key_logs) = change.db_key_logs() { let db_value_logs_bytes = serialize(&change.db_value_logs()).unwrap(); batch.put(&Bytes::from(&key_logs), &db_value_logs_bytes); } } for code in block_codes { // NOTE: May have another transaction after the contract created block_contracts.insert(code.address.clone(), true); // Key::ContractMeta let db_value_bytes = serialize(&code.db_value()).unwrap(); batch.put(&Bytes::from(&code.db_key()), &db_value_bytes); } let common_cells = block_added_cells .keys() .cloned() .collect::<HashSet<_>>() .intersection(&block_removed_cells) .cloned() .collect::<HashSet<_>>(); for (lock_hash, tx_index, output_index, value) in added_cells.clone() { if common_cells.contains(&value) { continue; } log::debug!( "Add live cell: tx_hash={:#x}, index={}", value.tx_hash, value.output_index ); let key = Key::LockLiveCell { lock_hash, number: Some(next_number), tx_index: Some(tx_index), output_index: Some(output_index), }; batch.put(&Bytes::from(&key), &serialize(&value).unwrap()); let map_key = Key::LiveCellMap(value.out_point()); let map_value = value::LiveCellMap { number: next_number, tx_index, }; batch.put(&Bytes::from(&map_key), &serialize(&map_value).unwrap()); } for (lock_hash, number, tx_index, output_index, value) in removed_cells.clone() { if common_cells.contains(&value) { continue; } log::debug!( "Remove live cell: tx_hash={:#x}, index={}", value.tx_hash, value.output_index ); let key = Key::LockLiveCell { lock_hash, number: Some(number), tx_index: Some(tx_index), output_index: Some(output_index), }; batch.delete(&Bytes::from(&key)); batch.delete(&Bytes::from(&Key::LiveCellMap(value.out_point()))); } // selfdestruct for contract_address in &destructed_contracts { // For clean up logs when rollback block_contracts.insert(contract_address.clone(), false); let key_bytes = Bytes::from(&Key::ContractMeta(contract_address.clone())); let mut meta: value::ContractMeta = db_get(&self.db, &key_bytes)? .ok_or_else(|| format!("no such contract: {:x}", contract_address.0))?; assert_eq!(meta.destructed, false); meta.destructed = true; batch.put(&key_bytes, &serialize(&meta).unwrap()); } // Key::BlockDelta let block_delta = value::BlockDelta { contracts: block_contracts.into_iter().collect::<Vec<_>>(), added_cells: added_cells.into_iter().collect::<Vec<_>>(), removed_cells: removed_cells.into_iter().collect::<Vec<_>>(), destructed_contracts, }; let block_contracts_bytes = serialize(&block_delta).unwrap(); batch.put( &Bytes::from(&Key::BlockDelta(next_number)), &block_contracts_bytes, ); self.db.write(batch).map_err(|err| err.to_string())?; } } } // Extract eth contract changes from CKB transaction // 0. produce contract metas (CREATE) // 1. produce contract changes // 2. produce contract logs // 3. produce SELFDESTRUCT contracts pub struct ContractExtractor { run_config: RunConfig, tx_hash: H256, tx_index: u32, entrance_contract: ContractAddress, current_contract: ContractAddress, // script_hash => (input, output, programs) script_groups: HashMap<ContractAddress, ContractInfo>, } #[derive(Default)] pub struct ContractInfo { input: Option<(usize, ContractChange)>, output: Option<(usize, packed::CellOutput)>, // Increased by 1 after ckb-vm run a program program_index: usize, programs: Vec<WitnessData>, // Updated by ckb-vm logs: Vec<(Vec<H256>, Bytes)>, selfdestruct: Option<Bytes>, // Updated by ckb-vm tree: SparseMerkleTree<CkbBlake2bHasher, SmtH256, DefaultStore<SmtH256>>, } impl ContractInfo { pub fn selfdestruct(&self) -> Option<ContractAddress> { assert_eq!( self.output.is_none(), self.programs[self.programs.len() - 1] .selfdestruct .is_some(), ); let last_program = &self.programs[self.programs.len() - 1]; last_program .selfdestruct .as_ref() .map(|_| last_program.program.destination.clone()) } pub fn is_create(&self) -> bool { self.input.is_none() } pub fn code(&self) -> Bytes { if self.is_create() { self.programs[0].return_data.clone() } else { self.programs[0].program.code.clone() } } pub fn current_program(&self) -> &WitnessData { &self.programs[self.program_index] } pub fn get_meta(&self, address: &ContractAddress, tx_hash: &H256) -> Option<ContractMeta> { if self.is_create() { let output_index = self.output.as_ref().map(|(index, _)| *index).unwrap() as u32; Some(ContractMeta { address: address.clone(), code: self.code(), tx_hash: tx_hash.clone(), output_index, destructed: false, }) } else { None } } pub fn get_change( &self, address: &ContractAddress, number: u64, tx_index: u32, tx_hash: &H256, ) -> Option<ContractChange> { if let Some((output_index, output)) = self.output.as_ref() { let new_storage: HashMap<H256, H256> = self .tree .store() .leaves_map() .values() .map(|leaf| (smth256_to_h256(&leaf.key), smth256_to_h256(&leaf.value))) .collect(); let tx_origin = self.programs[0].program.tx_origin.clone(); let capacity: u64 = output.capacity().unpack(); Some(ContractChange { tx_origin, address: address.clone(), number, tx_index, output_index: *output_index as u32, tx_hash: tx_hash.clone(), new_storage, logs: self.logs.clone(), capacity, is_create: self.is_create(), }) } else { None } } } impl ContractExtractor { pub fn init( run_config: RunConfig, tx_hash: H256, tx_index: u32, witnesses: Vec<JsonBytes>, mut script_groups: HashMap<ContractAddress, ContractInfo>, ) -> Result<Option<ContractExtractor>, String> { let mut tx_origin = EoaAddress::default(); let mut entrance_contract = None; for (addr, info) in script_groups.iter_mut() { let witness_index = if let Some((input_index, _)) = info.input { input_index } else if let Some((output_index, _)) = info.output { output_index } else { panic!("Input/Output both empty"); }; let mut start = 0; let witness_args = packed::WitnessArgs::from_slice(witnesses[witness_index].as_bytes()) .map_err(|err| err.to_string())?; let raw_witness = witness_args .input_type() .to_opt() .or_else(|| witness_args.output_type().to_opt()) .map(|witness_data| witness_data.raw_data()) .ok_or_else(|| { format!( "can not find raw witness data in witnesses[{}]", witness_index ) })?; while let Some((offset, witness_data)) = WitnessData::load_from(&raw_witness[start..])? { if tx_origin == EoaAddress::default() { tx_origin = witness_data.program.tx_origin.clone(); } if tx_origin != witness_data.program.tx_origin { panic!("multiple tx_origin in one transaction"); } if !witness_data.signature.iter().all(|byte| *byte == 0) { if entrance_contract.is_some() { panic!("Multiple entrance contract"); } entrance_contract = Some(addr.clone()); } info.programs.push(witness_data); start += offset; } } if entrance_contract.is_none() && !script_groups.is_empty() { panic!("Invalid transaction"); } Ok(entrance_contract.map(|entrance_contract| { let current_contract = entrance_contract.clone(); ContractExtractor { run_config, tx_hash, tx_index, entrance_contract, current_contract, script_groups, } })) } pub fn run(&mut self) -> Result<(), Box<dyn StdError>> { let entrance_contract = self.entrance_contract.clone(); self.run_with(&entrance_contract).map(|_| ()) } pub fn run_with(&mut self, contract: &ContractAddress) -> Result<Bytes, Box<dyn StdError>> { self.current_contract = contract.clone(); let (tree_clone, program_data) = { let info = self .script_groups .get(contract) .ok_or_else(|| format!("No such contract to run: {:x}", contract.0))?; let tree_clone = SparseMerkleTree::new(*info.tree.root(), info.tree.store().clone()); let program_data = info.current_program().program_data(); (tree_clone, program_data) }; let config = Config::from(&self.run_config); let result = match run_with_context(&config, &tree_clone, &program_data, self) { Ok(result) => result, Err(err) => { log::warn!("Error: {:?}", err); return Err(err); } }; let info = self .script_groups .get_mut(contract) .ok_or_else(|| format!("No such contract to run: {:x}", contract.0))?; let return_data = info.current_program().return_data.clone(); result.commit(&mut info.tree).unwrap(); info.program_index += 1; Ok(return_data) } pub fn get_contract_changes(&self, number: u64) -> Vec<ContractChange> { self.script_groups .iter() .filter_map(|(addr, info)| info.get_change(addr, number, self.tx_index, &self.tx_hash)) .collect() } pub fn get_created_contracts(&self) -> Vec<ContractMeta> { self.script_groups .iter() .filter_map(|(addr, info)| info.get_meta(addr, &self.tx_hash)) .collect() } pub fn get_destructed_contracts(&self) -> Vec<ContractAddress> { self.script_groups .values() .filter_map(|info| info.selfdestruct()) .collect() } } impl<Mac: SupportMachine> RunContext<Mac> for ContractExtractor { fn ecall(&mut self, machine: &mut Mac) -> Result<bool, VMError> { let code = machine.registers()[A7].to_u64(); match code { // ckb_debug 2177 => { let mut addr = machine.registers()[A0].to_u64(); let mut buffer = Vec::new(); loop { let byte = machine .memory_mut() .load8(&Mac::REG::from_u64(addr))? .to_u8(); if byte == 0 { break; } buffer.push(byte); addr += 1; } let s = String::from_utf8(buffer).map_err(|_| VMError::ParseError)?; log::debug!("ckb_debug: {}", s); Ok(true) } // return 3075 => Ok(true), // LOG{0,1,2,3,4} 3076 => { let data_address = machine.registers()[A0].to_u64(); let data_length = machine.registers()[A1].to_u32(); let data = vm_load_data(machine, data_address, data_length)?; self.script_groups .get_mut(&self.current_contract) .unwrap() .logs .push(parse_log(&data[..]).unwrap()); Ok(true) } // SELFDESTRUCT 3077 => { let data_address = machine.registers()[A0].to_u64(); let data_length = machine.registers()[A1].to_u32(); let data = vm_load_data(machine, data_address, data_length)?; self.script_groups .get_mut(&self.current_contract) .unwrap() .selfdestruct = Some(data.into()); Ok(true) } // CALL 3078 => { let mut msg_data_address = machine.registers()[A0].to_u64(); let kind_value: u8 = vm_load_u8(machine, msg_data_address)?; msg_data_address += 1; let _flags: u32 = vm_load_u32(machine, msg_data_address)?; msg_data_address += 4; let _depth: i32 = vm_load_i32(machine, msg_data_address)?; msg_data_address += 4; let _gas: i64 = vm_load_i64(machine, msg_data_address)?; msg_data_address += 8; let destination: H160 = vm_load_h160(machine, msg_data_address)?; msg_data_address += 20; let _sender: H160 = vm_load_h160(machine, msg_data_address)?; msg_data_address += 20; let input_size: u32 = vm_load_u32(machine, msg_data_address)?; msg_data_address += 4; let _input_data: Vec<u8> = vm_load_data(machine, msg_data_address, input_size)?; msg_data_address += input_size as u64; let _value: H256 = vm_load_h256(machine, msg_data_address)?; let kind = CallKind::try_from(kind_value).unwrap(); let destination = ContractAddress(destination); let saved_current_contract = self.current_contract.clone(); let return_data = self .run_with(&destination) .map_err(|_err| VMError::Unexpected)?; let create_address = if kind == CallKind::CREATE { destination } else { ContractAddress(H160::default()) }; self.current_contract = saved_current_contract; // Store return_data to VM memory let result_data_address = machine.registers()[A0].to_u64(); let mut result_data = BytesMut::default(); result_data.put(&(return_data.len() as u32).to_le_bytes()[..]); result_data.put(return_data.as_ref()); result_data.put(create_address.0.as_bytes()); machine .memory_mut() .store_bytes(result_data_address, result_data.as_ref())?; Ok(true) } _ => Ok(false), } } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::account::{Account, AccountContext}; use account_common::{FidlLocalAccountId, LocalAccountId}; use failure::Error; use fidl::encoding::OutOfLine; use fidl::endpoints::{ClientEnd, ServerEnd}; use fidl_fuchsia_auth::{AuthState, AuthStateSummary, AuthenticationContextProviderMarker}; use fidl_fuchsia_auth_account::{AccountMarker, Status}; use fidl_fuchsia_auth_account_internal::{ AccountHandlerContextMarker, AccountHandlerContextProxy, AccountHandlerControlRequest, AccountHandlerControlRequestStream, }; use fuchsia_async as fasync; use futures::prelude::*; use log::{error, info, warn}; use parking_lot::RwLock; use std::path::{Path, PathBuf}; use std::sync::Arc; /// The core state of the AccountHandler, i.e. the Account (once it is known) and references to /// the execution context and a TokenManager. pub struct AccountHandler { // An optional `Account` that we are handling. // // This will be None until a particular Account is established over the control channel. Once // set, the account will never be cleared or modified. account: RwLock<Option<Arc<Account>>>, // TODO(jsankey): Add TokenManager and AccountHandlerContext. } impl AccountHandler { /// (Temporary) A fixed AuthState that is used for all accounts until authenticators are /// available. pub const DEFAULT_AUTH_STATE: AuthState = AuthState { summary: AuthStateSummary::Unknown }; /// Constructs a new AccountHandler. pub fn new() -> AccountHandler { Self { account: RwLock::new(None) } } /// Asynchronously handles the supplied stream of `AccountHandlerControlRequest` messages. pub async fn handle_requests_from_stream( &self, mut stream: AccountHandlerControlRequestStream, ) -> Result<(), Error> { while let Some(req) = await!(stream.try_next())? { await!(self.handle_request(req))?; } Ok(()) } /// Dispatches an `AccountHandlerControlRequest` message to the appropriate handler method /// based on its type. pub async fn handle_request( &self, req: AccountHandlerControlRequest, ) -> Result<(), fidl::Error> { match req { AccountHandlerControlRequest::CreateAccount { context, responder } => { let response = await!(self.create_account(context)); responder.send( response.0, response.1.map(FidlLocalAccountId::from).as_mut().map(OutOfLine), )?; } AccountHandlerControlRequest::LoadAccount { context, id, responder } => { let response = await!(self.load_account(id.into(), context)); responder.send(response)?; } AccountHandlerControlRequest::RemoveAccount { responder } => { let response = self.remove_account(); responder.send(response)?; } AccountHandlerControlRequest::GetAccount { auth_context_provider, account, responder, } => { let response = self.get_account(auth_context_provider, account); responder.send(response)?; } AccountHandlerControlRequest::Terminate { control_handle } => { // TODO(jsankey): Close any open files once we have them and shutdown dependant // channels on the account, personae, and token manager. info!("Gracefully shutting down AccountHandler"); control_handle.shutdown(); } } Ok(()) } /// Turn the context client end into a proxy, query it for the account_parent_dir and return /// the (proxy, account_dir_parent) as a tuple. async fn init_context( context: ClientEnd<AccountHandlerContextMarker>, ) -> Result<(AccountHandlerContextProxy, PathBuf), Status> { let context_proxy = context.into_proxy().map_err(|err| { warn!("Error using AccountHandlerContext {:?}", err); Status::InvalidRequest })?; let account_dir_parent = await!(context_proxy.get_account_dir_parent()).map_err(|err| { warn!("Error calling AccountHandlerContext.get_account_dir_parent() {:?}", err); Status::InvalidRequest })?; Ok((context_proxy, PathBuf::from(account_dir_parent))) } async fn create_account( &self, context: ClientEnd<AccountHandlerContextMarker>, ) -> (Status, Option<LocalAccountId>) { let (context_proxy, account_dir_parent) = match await!(Self::init_context(context)) { Err(status) => return (status, None), Ok(result) => result, }; let mut account_lock = self.account.write(); if account_lock.is_some() { warn!("AccountHandler is already initialized"); (Status::InvalidRequest, None) } else { // TODO(jsankey): Longer term, local ID may need to be related to the global ID rather // than just a random number. let local_account_id = LocalAccountId::new(rand::random::<u64>()); let account_dir = Self::account_dir(&account_dir_parent, &local_account_id); // Construct an Account value to maintain state inside this directory let account = match Account::create(local_account_id.clone(), &account_dir, context_proxy) { Ok(account) => account, Err(err) => { return (err.status, None); } }; *account_lock = Some(Arc::new(account)); info!("Created new Fuchsia account"); (Status::Ok, Some(local_account_id)) } } async fn load_account( &self, id: LocalAccountId, context: ClientEnd<AccountHandlerContextMarker>, ) -> Status { let (context_proxy, account_dir_parent) = match await!(Self::init_context(context)) { Err(status) => return status, Ok(result) => result, }; let mut account_lock = self.account.write(); if account_lock.is_some() { warn!("AccountHandler is already initialized"); Status::InvalidRequest } else { let account_dir = Self::account_dir(&account_dir_parent, &id); let account = match Account::load(id.clone(), &account_dir, context_proxy) { Ok(account) => account, Err(err) => return err.status, }; *account_lock = Some(Arc::new(account)); Status::Ok } } fn remove_account(&self) -> Status { let mut account_lock = self.account.write(); let account = match &*account_lock { Some(account) => account, None => { warn!("No account is initialized or it has already been removed"); return Status::InvalidRequest; } }; match account.remove() { Ok(()) => { info!("Deleted Fuchsia account {:?}", &account.id()); *account_lock = None; Status::Ok } Err(err) => { warn!("Could not remove account: {:?}", err); err.status } } } fn get_account( &self, auth_context_provider_client_end: ClientEnd<AuthenticationContextProviderMarker>, account_server_end: ServerEnd<AccountMarker>, ) -> Status { let account = if let Some(account) = &*self.account.read() { Arc::clone(account) } else { warn!("AccountHandler not yet initialized"); return Status::NotFound; }; let context = match auth_context_provider_client_end.into_proxy() { Ok(acp) => AccountContext { auth_ui_context_provider: acp }, Err(err) => { warn!("Error using AuthenticationContextProvider {:?}", err); return Status::InvalidRequest; } }; let stream = match account_server_end.into_stream() { Ok(stream) => stream, Err(e) => { warn!("Error opening Account channel {:?}", e); return Status::IoError; } }; fasync::spawn( async move { await!(account.handle_requests_from_stream(&context, stream)) .unwrap_or_else(|e| error!("Error handling Account channel {:?}", e)) }, ); Status::Ok } /// Returns the directory that should be used for the specified LocalAccountId fn account_dir(account_dir_parent: &Path, account_id: &LocalAccountId) -> PathBuf { PathBuf::from(account_dir_parent).join(account_id.to_canonical_string()) } } #[cfg(test)] mod tests { use super::*; use crate::test_util::*; use fidl::endpoints::create_endpoints; use fidl_fuchsia_auth_account_internal::{ AccountHandlerControlMarker, AccountHandlerControlProxy, }; use fuchsia_async as fasync; use parking_lot::Mutex; use std::path::Path; use std::sync::Arc; // Will not match a randomly generated account id with high probability. const WRONG_ACCOUNT_ID: u64 = 111111; fn request_stream_test<TestFn, Fut>(tmp_dir: &Path, test_fn: TestFn) where TestFn: FnOnce(AccountHandlerControlProxy, ClientEnd<AccountHandlerContextMarker>) -> Fut, Fut: Future<Output = Result<(), Error>>, { let mut executor = fasync::Executor::new().expect("Failed to create executor"); let test_object = AccountHandler::new(); let fake_context = Arc::new(FakeAccountHandlerContext::new(&tmp_dir.to_string_lossy())); let ahc_client_end = spawn_context_channel(fake_context.clone()); let (client_end, server_end) = create_endpoints::<AccountHandlerControlMarker>().unwrap(); let proxy = client_end.into_proxy().unwrap(); let request_stream = server_end.into_stream().unwrap(); fasync::spawn( async move { await!(test_object.handle_requests_from_stream(request_stream)) .unwrap_or_else(|err| panic!("Fatal error handling test request: {:?}", err)) }, ); executor.run_singlethreaded(test_fn(proxy, ahc_client_end)).expect("Executor run failed.") } #[test] fn test_get_account_before_initialization() { let location = TempLocation::new(); request_stream_test(&location.path, async move |proxy, _| { let (_, account_server_end) = create_endpoints().unwrap(); let (acp_client_end, _) = create_endpoints().unwrap(); assert_eq!( await!(proxy.get_account(acp_client_end, account_server_end))?, Status::NotFound ); Ok(()) }); } #[test] fn test_double_initialize() { let location = TempLocation::new(); let path = &location.path; request_stream_test(&path, async move |proxy, ahc_client_end| { let (status, account_id_optional) = await!(proxy.create_account(ahc_client_end))?; assert_eq!(status, Status::Ok); assert!(account_id_optional.is_some()); let fake_context_2 = Arc::new(FakeAccountHandlerContext::new(&path.to_string_lossy())); let ahc_client_end_2 = spawn_context_channel(fake_context_2.clone()); assert_eq!( await!(proxy.create_account(ahc_client_end_2))?, (Status::InvalidRequest, None) ); Ok(()) }); } #[test] fn test_create_and_get_account() { let location = TempLocation::new(); request_stream_test(&location.path, async move |account_handler_proxy, ahc_client_end| { let (status, account_id_optional) = await!(account_handler_proxy.create_account(ahc_client_end))?; assert_eq!(status, Status::Ok); assert!(account_id_optional.is_some()); let (account_client_end, account_server_end) = create_endpoints().unwrap(); let (acp_client_end, _) = create_endpoints().unwrap(); assert_eq!( await!(account_handler_proxy.get_account(acp_client_end, account_server_end))?, Status::Ok ); // The account channel should now be usable. let account_proxy = account_client_end.into_proxy().unwrap(); assert_eq!( await!(account_proxy.get_auth_state())?, (Status::Ok, Some(Box::new(AccountHandler::DEFAULT_AUTH_STATE))) ); Ok(()) }); } #[test] fn test_create_and_load_account() { // Check that an account is persisted when account handlers are restarted let location = TempLocation::new(); let acc_id_holder: Arc<Mutex<Option<FidlLocalAccountId>>> = Arc::new(Mutex::new(None)); let acc_id_holder_clone = Arc::clone(&acc_id_holder); request_stream_test(&location.path, async move |proxy, ahc_client_end| { let (status, account_id_optional) = await!(proxy.create_account(ahc_client_end))?; assert_eq!(status, Status::Ok); *acc_id_holder_clone.lock() = account_id_optional.map(|x| *x); Ok(()) }); request_stream_test(&location.path, async move |proxy, ahc_client_end| { match acc_id_holder.lock().as_mut() { Some(mut acc_id) => { assert_eq!( await!(proxy.load_account(ahc_client_end, &mut acc_id))?, Status::Ok ); } None => panic!("Create account did not return a valid account id to get"), } Ok(()) }); } #[test] fn test_create_and_remove_account() { let location = TempLocation::new(); let path = location.path.clone(); request_stream_test(&location.path, async move |proxy, ahc_client_end| { let (status, account_id_optional) = await!(proxy.create_account(ahc_client_end))?; assert_eq!(status, Status::Ok); assert!(account_id_optional.is_some()); let account_path = path.join(account_id_optional.unwrap().id.to_string()); assert!(account_path.is_dir()); assert_eq!(await!(proxy.remove_account())?, Status::Ok); assert_eq!(account_path.exists(), false); Ok(()) }); } #[test] fn test_remove_account_before_initialization() { let location = TempLocation::new(); request_stream_test(&location.path, async move |proxy, _| { assert_eq!(await!(proxy.remove_account())?, Status::InvalidRequest); Ok(()) }); } #[test] fn test_create_and_remove_account_twice() { let location = TempLocation::new(); request_stream_test(&location.path, async move |proxy, ahc_client_end| { let (status, account_id_optional) = await!(proxy.create_account(ahc_client_end))?; assert_eq!(status, Status::Ok); assert!(account_id_optional.is_some()); assert_eq!(await!(proxy.remove_account())?, Status::Ok); assert_eq!( await!(proxy.remove_account())?, Status::InvalidRequest // You can only remove once ); Ok(()) }); } #[test] fn test_load_account_not_found() { let location = TempLocation::new(); request_stream_test(&location.path, async move |proxy, ahc_client_end| { assert_eq!( await!(proxy.load_account( ahc_client_end, &mut FidlLocalAccountId { id: WRONG_ACCOUNT_ID } ))?, Status::NotFound ); Ok(()) }); } }
extern crate chip16; extern crate sdl2; use chip16::{Cpu, Rom}; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use std::env; use std::fs::File; use std::time::Duration; fn main() { let filename = env::args().nth(1).unwrap(); let file = File::open(filename).unwrap(); let rom = Rom::new(file).unwrap(); let cpu = Cpu::new(); // cpu.load(rom); run(cpu); } fn run(mut cpu: Cpu) { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem .window("chip16_sdl2", 800, 600) .position_centered() .build() .unwrap(); let mut canvas = window.into_canvas().build().unwrap(); let texture_creator = canvas.texture_creator(); // let texture = texture_creator. canvas.set_draw_color(Color::RGB(255, 0, 0)); canvas.clear(); canvas.present(); let mut event_pump = sdl_context.event_pump().unwrap(); 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => break 'running, _ => {} } } } }
pub mod index; pub mod binary_file_parser; #[derive(Debug)] pub enum ParseError { CantOpenFile, CantReadFile, CantParseFile, }
/// A magma. pub trait Magma: Clone { /// Performs a binary operation. fn op(&self, rhs: &Self) -> Self; /// Assigns `self.op(rhs)` to `self`. fn op_assign_right(&mut self, rhs: &Self) { *self = self.op(rhs); } /// Assigns `lhs.op(self)` to `self`. fn op_assign_left(&mut self, lhs: &Self) { *self = lhs.op(self); } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::FCRIS { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct FLASH_FCRIS_ARISR { bits: bool, } impl FLASH_FCRIS_ARISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_FCRIS_ARISW<'a> { w: &'a mut W, } impl<'a> _FLASH_FCRIS_ARISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct FLASH_FCRIS_PRISR { bits: bool, } impl FLASH_FCRIS_PRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_FCRIS_PRISW<'a> { w: &'a mut W, } impl<'a> _FLASH_FCRIS_PRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct FLASH_FCRIS_ERISR { bits: bool, } impl FLASH_FCRIS_ERISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_FCRIS_ERISW<'a> { w: &'a mut W, } impl<'a> _FLASH_FCRIS_ERISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct FLASH_FCRIS_VOLTRISR { bits: bool, } impl FLASH_FCRIS_VOLTRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_FCRIS_VOLTRISW<'a> { w: &'a mut W, } impl<'a> _FLASH_FCRIS_VOLTRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct FLASH_FCRIS_INVDRISR { bits: bool, } impl FLASH_FCRIS_INVDRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_FCRIS_INVDRISW<'a> { w: &'a mut W, } impl<'a> _FLASH_FCRIS_INVDRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct FLASH_FCRIS_ERRISR { bits: bool, } impl FLASH_FCRIS_ERRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_FCRIS_ERRISW<'a> { w: &'a mut W, } impl<'a> _FLASH_FCRIS_ERRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 11); self.w.bits |= ((value as u32) & 1) << 11; self.w } } #[doc = r"Value of the field"] pub struct FLASH_FCRIS_PROGRISR { bits: bool, } impl FLASH_FCRIS_PROGRISR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_FCRIS_PROGRISW<'a> { w: &'a mut W, } impl<'a> _FLASH_FCRIS_PROGRISW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 13); self.w.bits |= ((value as u32) & 1) << 13; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Access Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_aris(&self) -> FLASH_FCRIS_ARISR { let bits = ((self.bits >> 0) & 1) != 0; FLASH_FCRIS_ARISR { bits } } #[doc = "Bit 1 - Programming Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_pris(&self) -> FLASH_FCRIS_PRISR { let bits = ((self.bits >> 1) & 1) != 0; FLASH_FCRIS_PRISR { bits } } #[doc = "Bit 2 - EEPROM Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_eris(&self) -> FLASH_FCRIS_ERISR { let bits = ((self.bits >> 2) & 1) != 0; FLASH_FCRIS_ERISR { bits } } #[doc = "Bit 9 - Pump Voltage Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_voltris(&self) -> FLASH_FCRIS_VOLTRISR { let bits = ((self.bits >> 9) & 1) != 0; FLASH_FCRIS_VOLTRISR { bits } } #[doc = "Bit 10 - Invalid Data Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_invdris(&self) -> FLASH_FCRIS_INVDRISR { let bits = ((self.bits >> 10) & 1) != 0; FLASH_FCRIS_INVDRISR { bits } } #[doc = "Bit 11 - Erase Verify Error Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_erris(&self) -> FLASH_FCRIS_ERRISR { let bits = ((self.bits >> 11) & 1) != 0; FLASH_FCRIS_ERRISR { bits } } #[doc = "Bit 13 - Program Verify Error Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_progris(&self) -> FLASH_FCRIS_PROGRISR { let bits = ((self.bits >> 13) & 1) != 0; FLASH_FCRIS_PROGRISR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Access Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_aris(&mut self) -> _FLASH_FCRIS_ARISW { _FLASH_FCRIS_ARISW { w: self } } #[doc = "Bit 1 - Programming Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_pris(&mut self) -> _FLASH_FCRIS_PRISW { _FLASH_FCRIS_PRISW { w: self } } #[doc = "Bit 2 - EEPROM Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_eris(&mut self) -> _FLASH_FCRIS_ERISW { _FLASH_FCRIS_ERISW { w: self } } #[doc = "Bit 9 - Pump Voltage Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_voltris(&mut self) -> _FLASH_FCRIS_VOLTRISW { _FLASH_FCRIS_VOLTRISW { w: self } } #[doc = "Bit 10 - Invalid Data Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_invdris(&mut self) -> _FLASH_FCRIS_INVDRISW { _FLASH_FCRIS_INVDRISW { w: self } } #[doc = "Bit 11 - Erase Verify Error Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_erris(&mut self) -> _FLASH_FCRIS_ERRISW { _FLASH_FCRIS_ERRISW { w: self } } #[doc = "Bit 13 - Program Verify Error Raw Interrupt Status"] #[inline(always)] pub fn flash_fcris_progris(&mut self) -> _FLASH_FCRIS_PROGRISW { _FLASH_FCRIS_PROGRISW { w: self } } }
#[doc = "Reader of register DMAMR"] pub type R = crate::R<u32, super::DMAMR>; #[doc = "Writer for register DMAMR"] pub type W = crate::W<u32, super::DMAMR>; #[doc = "Register DMAMR `reset()`'s with value 0"] impl crate::ResetValue for super::DMAMR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SWR`"] pub type SWR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SWR`"] pub struct SWR_W<'a> { w: &'a mut W, } impl<'a> SWR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `DA`"] pub type DA_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DA`"] pub struct DA_W<'a> { w: &'a mut W, } impl<'a> DA_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `TXPR`"] pub type TXPR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXPR`"] pub struct TXPR_W<'a> { w: &'a mut W, } impl<'a> TXPR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `PR`"] pub type PR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PR`"] pub struct PR_W<'a> { w: &'a mut W, } impl<'a> PR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12); self.w } } #[doc = "Reader of field `INTM`"] pub type INTM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `INTM`"] pub struct INTM_W<'a> { w: &'a mut W, } impl<'a> INTM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } impl R { #[doc = "Bit 0 - Software Reset"] #[inline(always)] pub fn swr(&self) -> SWR_R { SWR_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - DMA Tx or Rx Arbitration Scheme"] #[inline(always)] pub fn da(&self) -> DA_R { DA_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 11 - Transmit priority"] #[inline(always)] pub fn txpr(&self) -> TXPR_R { TXPR_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bits 12:14 - Priority ratio"] #[inline(always)] pub fn pr(&self) -> PR_R { PR_R::new(((self.bits >> 12) & 0x07) as u8) } #[doc = "Bits 16:17 - Interrupt Mode"] #[inline(always)] pub fn intm(&self) -> INTM_R { INTM_R::new(((self.bits >> 16) & 0x03) as u8) } } impl W { #[doc = "Bit 0 - Software Reset"] #[inline(always)] pub fn swr(&mut self) -> SWR_W { SWR_W { w: self } } #[doc = "Bit 1 - DMA Tx or Rx Arbitration Scheme"] #[inline(always)] pub fn da(&mut self) -> DA_W { DA_W { w: self } } #[doc = "Bit 11 - Transmit priority"] #[inline(always)] pub fn txpr(&mut self) -> TXPR_W { TXPR_W { w: self } } #[doc = "Bits 12:14 - Priority ratio"] #[inline(always)] pub fn pr(&mut self) -> PR_W { PR_W { w: self } } #[doc = "Bits 16:17 - Interrupt Mode"] #[inline(always)] pub fn intm(&mut self) -> INTM_W { INTM_W { w: self } } }
use crate::common::{Board, Coordinate, Player}; use crate::strategy::Strategy; pub struct NaiveStrategy { player: Player, } impl NaiveStrategy { pub fn new(player: Player) -> NaiveStrategy { NaiveStrategy { player } } } impl Strategy for NaiveStrategy { fn make_move(&mut self, board: Board) -> Option<Coordinate> { for x in 0..8 { for y in 0..8 { if board.is_valid_move(Coordinate { x, y }, self.player) { return Some(Coordinate { x, y }); } } } return None; } fn to_string(&self) -> String { format!("naive strategy") } }
mod utils; use gdal::Dataset; fn main() { let ds = Dataset::open(fixture!("roads.geojson")).unwrap(); let mut layer = ds.layer(0).unwrap(); for _ in layer.features() { let _ = layer.defn(); } }
/// Test fixture, actual output, or expected result /// /// This provides conveniences for tracking the intended format (binary vs text). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Data { inner: DataInner, } #[derive(Clone, Debug, PartialEq, Eq)] enum DataInner { Binary(Vec<u8>), Text(String), #[cfg(feature = "json")] Json(serde_json::Value), } #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash)] pub enum DataFormat { Binary, Text, #[cfg(feature = "json")] Json, } impl Default for DataFormat { fn default() -> Self { DataFormat::Text } } impl Data { /// Mark the data as binary (no post-processing) pub fn binary(raw: impl Into<Vec<u8>>) -> Self { Self { inner: DataInner::Binary(raw.into()), } } /// Mark the data as text (post-processing) pub fn text(raw: impl Into<String>) -> Self { Self { inner: DataInner::Text(raw.into()), } } #[cfg(feature = "json")] pub fn json(raw: impl Into<serde_json::Value>) -> Self { Self { inner: DataInner::Json(raw.into()), } } /// Empty test data pub fn new() -> Self { Self::text("") } /// Load test data from a file pub fn read_from( path: &std::path::Path, data_format: Option<DataFormat>, ) -> Result<Self, crate::Error> { let data = match data_format { Some(df) => match df { DataFormat::Binary => { let data = std::fs::read(&path) .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; Self::binary(data) } DataFormat::Text => { let data = std::fs::read_to_string(&path) .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; Self::text(data) } #[cfg(feature = "json")] DataFormat::Json => { let data = std::fs::read_to_string(&path) .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; Self::json(serde_json::from_str::<serde_json::Value>(&data).unwrap()) } }, None => { let data = std::fs::read(&path) .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; let data = Self::binary(data); match path .extension() .and_then(|e| e.to_str()) .unwrap_or_default() { #[cfg(feature = "json")] "json" => data.try_coerce(DataFormat::Json), _ => data.try_coerce(DataFormat::Text), } } }; Ok(data) } /// Overwrite a snapshot pub fn write_to(&self, path: &std::path::Path) -> Result<(), crate::Error> { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| { format!("Failed to create parent dir for {}: {}", path.display(), e) })?; } std::fs::write(path, self.to_bytes()) .map_err(|e| format!("Failed to write {}: {}", path.display(), e).into()) } /// Post-process text /// /// See [utils][crate::utils] pub fn normalize(self, op: impl Normalize) -> Self { op.normalize(self) } /// Return the underlying `String` /// /// Note: this will not inspect binary data for being a valid `String`. pub fn render(&self) -> Option<String> { match &self.inner { DataInner::Binary(_) => None, DataInner::Text(data) => Some(data.to_owned()), #[cfg(feature = "json")] DataInner::Json(value) => Some(serde_json::to_string_pretty(value).unwrap()), } } pub fn to_bytes(&self) -> Vec<u8> { match &self.inner { DataInner::Binary(data) => data.clone(), DataInner::Text(data) => data.clone().into_bytes(), #[cfg(feature = "json")] DataInner::Json(value) => serde_json::to_vec_pretty(value).unwrap(), } } pub fn try_coerce(self, format: DataFormat) -> Self { match (self.inner, format) { (DataInner::Binary(inner), DataFormat::Binary) => Self::binary(inner), (DataInner::Text(inner), DataFormat::Text) => Self::text(inner), #[cfg(feature = "json")] (DataInner::Json(inner), DataFormat::Json) => Self::json(inner), (DataInner::Binary(inner), _) => { if is_binary(&inner) { Self::binary(inner) } else { match String::from_utf8(inner) { Ok(str) => { let coerced = Self::text(str).try_coerce(format); // if the Text cannot be coerced into the correct format // reset it back to Binary if coerced.format() != format { coerced.try_coerce(DataFormat::Binary) } else { coerced } } Err(err) => { let bin = err.into_bytes(); Self::binary(bin) } } } } #[cfg(feature = "json")] (DataInner::Text(inner), DataFormat::Json) => { match serde_json::from_str::<serde_json::Value>(&inner) { Ok(json) => Self::json(json), Err(_) => Self::text(inner), } } (inner, DataFormat::Binary) => Self::binary(Self { inner }.to_bytes()), // This variant is already covered unless structured data is enabled #[cfg(feature = "structured-data")] (inner, DataFormat::Text) => { let remake = Self { inner }; if let Some(str) = remake.render() { Self::text(str) } else { remake } } } } /// Outputs the current `DataFormat` of the underlying data pub fn format(&self) -> DataFormat { match &self.inner { DataInner::Binary(_) => DataFormat::Binary, DataInner::Text(_) => DataFormat::Text, #[cfg(feature = "json")] DataInner::Json(_) => DataFormat::Json, } } } impl std::fmt::Display for Data { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.inner { DataInner::Binary(data) => String::from_utf8_lossy(data).fmt(f), DataInner::Text(data) => data.fmt(f), #[cfg(feature = "json")] DataInner::Json(data) => serde_json::to_string_pretty(data).unwrap().fmt(f), } } } impl Default for Data { fn default() -> Self { Self::new() } } impl<'d> From<&'d Data> for Data { fn from(other: &'d Data) -> Self { other.clone() } } impl From<Vec<u8>> for Data { fn from(other: Vec<u8>) -> Self { Self::binary(other) } } impl<'b> From<&'b [u8]> for Data { fn from(other: &'b [u8]) -> Self { other.to_owned().into() } } impl From<String> for Data { fn from(other: String) -> Self { Self::text(other) } } impl<'s> From<&'s String> for Data { fn from(other: &'s String) -> Self { other.clone().into() } } impl<'s> From<&'s str> for Data { fn from(other: &'s str) -> Self { other.to_owned().into() } } pub trait Normalize { fn normalize(&self, data: Data) -> Data; } pub struct NormalizeNewlines; impl Normalize for NormalizeNewlines { fn normalize(&self, data: Data) -> Data { match data.inner { DataInner::Binary(bin) => Data::binary(bin), DataInner::Text(text) => { let lines = crate::utils::normalize_lines(&text); Data::text(lines) } #[cfg(feature = "json")] DataInner::Json(value) => { let mut value = value; normalize_value(&mut value, crate::utils::normalize_lines); Data::json(value) } } } } pub struct NormalizePaths; impl Normalize for NormalizePaths { fn normalize(&self, data: Data) -> Data { match data.inner { DataInner::Binary(bin) => Data::binary(bin), DataInner::Text(text) => { let lines = crate::utils::normalize_paths(&text); Data::text(lines) } #[cfg(feature = "json")] DataInner::Json(value) => { let mut value = value; normalize_value(&mut value, crate::utils::normalize_paths); Data::json(value) } } } } pub struct NormalizeMatches<'a> { substitutions: &'a crate::Substitutions, pattern: &'a Data, } impl<'a> NormalizeMatches<'a> { pub fn new(substitutions: &'a crate::Substitutions, pattern: &'a Data) -> Self { NormalizeMatches { substitutions, pattern, } } } impl Normalize for NormalizeMatches<'_> { fn normalize(&self, data: Data) -> Data { match data.inner { DataInner::Binary(bin) => Data::binary(bin), DataInner::Text(text) => { let lines = self .substitutions .normalize(&text, &self.pattern.render().unwrap()); Data::text(lines) } #[cfg(feature = "json")] DataInner::Json(value) => { let mut value = value; if let DataInner::Json(exp) = &self.pattern.inner { normalize_value_matches(&mut value, exp, self.substitutions); } Data::json(value) } } } } #[cfg(feature = "structured-data")] fn normalize_value(value: &mut serde_json::Value, op: fn(&str) -> String) { match value { serde_json::Value::String(str) => { *str = op(str); } serde_json::Value::Array(arr) => { arr.iter_mut().for_each(|value| normalize_value(value, op)); } serde_json::Value::Object(obj) => { obj.iter_mut() .for_each(|(_, value)| normalize_value(value, op)); } _ => {} } } #[cfg(feature = "structured-data")] fn normalize_value_matches( actual: &mut serde_json::Value, expected: &serde_json::Value, substitutions: &crate::Substitutions, ) { use serde_json::Value::*; match (actual, expected) { // "{...}" is a wildcard (act, String(exp)) if exp == "{...}" => { *act = serde_json::json!("{...}"); } (String(act), String(exp)) => { *act = substitutions.normalize(act, exp); } (Array(act), Array(exp)) => { act.iter_mut() .zip(exp) .for_each(|(a, e)| normalize_value_matches(a, e, substitutions)); } (Object(act), Object(exp)) => { act.iter_mut() .zip(exp) .filter(|(a, e)| a.0 == e.0) .for_each(|(a, e)| normalize_value_matches(a.1, e.1, substitutions)); } (_, _) => {} } } #[cfg(feature = "detect-encoding")] fn is_binary(data: &[u8]) -> bool { match content_inspector::inspect(data) { content_inspector::ContentType::BINARY | // We don't support these content_inspector::ContentType::UTF_16LE | content_inspector::ContentType::UTF_16BE | content_inspector::ContentType::UTF_32LE | content_inspector::ContentType::UTF_32BE => { true }, content_inspector::ContentType::UTF_8 | content_inspector::ContentType::UTF_8_BOM => { false }, } } #[cfg(not(feature = "detect-encoding"))] fn is_binary(_data: &[u8]) -> bool { false } #[cfg(test)] mod test { use super::*; #[cfg(feature = "json")] use serde_json::json; // Tests for checking to_bytes and render produce the same results #[test] fn text_to_bytes_render() { let d = Data::text(String::from("test")); let bytes = d.to_bytes(); let bytes = String::from_utf8(bytes).unwrap(); let rendered = d.render().unwrap(); assert_eq!(bytes, rendered); } #[test] #[cfg(feature = "json")] fn json_to_bytes_render() { let d = Data::json(json!({"name": "John\\Doe\r\n"})); let bytes = d.to_bytes(); let bytes = String::from_utf8(bytes).unwrap(); let rendered = d.render().unwrap(); assert_eq!(bytes, rendered); } // Tests for checking all types are coercible to each other and // for when the coercion should fail #[test] fn binary_to_text() { let binary = String::from("test").into_bytes(); let d = Data::binary(binary); let text = d.try_coerce(DataFormat::Text); assert_eq!(DataFormat::Text, text.format()) } #[test] fn binary_to_text_not_utf8() { let binary = b"\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00".to_vec(); let d = Data::binary(binary); let d = d.try_coerce(DataFormat::Text); assert_ne!(DataFormat::Text, d.format()); assert_eq!(DataFormat::Binary, d.format()); } #[test] #[cfg(feature = "json")] fn binary_to_json() { let value = json!({"name": "John\\Doe\r\n"}); let binary = serde_json::to_vec_pretty(&value).unwrap(); let d = Data::binary(binary); let json = d.try_coerce(DataFormat::Json); assert_eq!(DataFormat::Json, json.format()); } #[test] #[cfg(feature = "json")] fn binary_to_json_not_utf8() { let binary = b"\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00".to_vec(); let d = Data::binary(binary); let d = d.try_coerce(DataFormat::Json); assert_ne!(DataFormat::Json, d.format()); assert_eq!(DataFormat::Binary, d.format()); } #[test] #[cfg(feature = "json")] fn binary_to_json_not_json() { let binary = String::from("test").into_bytes(); let d = Data::binary(binary); let d = d.try_coerce(DataFormat::Json); assert_ne!(DataFormat::Json, d.format()); assert_eq!(DataFormat::Binary, d.format()); } #[test] fn text_to_binary() { let text = String::from("test"); let d = Data::text(text); let binary = d.try_coerce(DataFormat::Binary); assert_eq!(DataFormat::Binary, binary.format()); } #[test] #[cfg(feature = "json")] fn text_to_json() { let value = json!({"name": "John\\Doe\r\n"}); let text = serde_json::to_string_pretty(&value).unwrap(); let d = Data::text(text); let json = d.try_coerce(DataFormat::Json); assert_eq!(DataFormat::Json, json.format()); } #[test] #[cfg(feature = "json")] fn text_to_json_not_json() { let text = String::from("test"); let d = Data::text(text); let json = d.try_coerce(DataFormat::Json); assert_eq!(DataFormat::Text, json.format()); } #[test] #[cfg(feature = "json")] fn json_to_binary() { let value = json!({"name": "John\\Doe\r\n"}); let d = Data::json(value); let binary = d.try_coerce(DataFormat::Binary); assert_eq!(DataFormat::Binary, binary.format()); } #[test] #[cfg(feature = "json")] fn json_to_text() { let value = json!({"name": "John\\Doe\r\n"}); let d = Data::json(value); let text = d.try_coerce(DataFormat::Text); assert_eq!(DataFormat::Text, text.format()); } // Tests for coercible conversions create the same output as to_bytes/render // // render does not need to be checked against bin -> text since render // outputs None for binary #[test] fn text_to_bin_coerce_equals_to_bytes() { let text = String::from("test"); let d = Data::text(text); let binary = d.clone().try_coerce(DataFormat::Binary); assert_eq!(Data::binary(d.to_bytes()), binary); } #[test] #[cfg(feature = "json")] fn json_to_bin_coerce_equals_to_bytes() { let json = json!({"name": "John\\Doe\r\n"}); let d = Data::json(json); let binary = d.clone().try_coerce(DataFormat::Binary); assert_eq!(Data::binary(d.to_bytes()), binary); } #[test] #[cfg(feature = "json")] fn json_to_text_coerce_equals_render() { let json = json!({"name": "John\\Doe\r\n"}); let d = Data::json(json); let text = d.clone().try_coerce(DataFormat::Text); assert_eq!(Data::text(d.render().unwrap()), text); } // Tests for normalization on json #[test] #[cfg(feature = "json")] fn json_normalize_paths_and_lines() { let json = json!({"name": "John\\Doe\r\n"}); let data = Data::json(json); let data = data.normalize(NormalizePaths); assert_eq!(Data::json(json!({"name": "John/Doe\r\n"})), data); let data = data.normalize(NormalizeNewlines); assert_eq!(Data::json(json!({"name": "John/Doe\n"})), data); } #[test] #[cfg(feature = "json")] fn json_normalize_obj_paths_and_lines() { let json = json!({ "person": { "name": "John\\Doe\r\n", "nickname": "Jo\\hn\r\n", } }); let data = Data::json(json); let data = data.normalize(NormalizePaths); let assert = json!({ "person": { "name": "John/Doe\r\n", "nickname": "Jo/hn\r\n", } }); assert_eq!(Data::json(assert), data); let data = data.normalize(NormalizeNewlines); let assert = json!({ "person": { "name": "John/Doe\n", "nickname": "Jo/hn\n", } }); assert_eq!(Data::json(assert), data); } #[test] #[cfg(feature = "json")] fn json_normalize_array_paths_and_lines() { let json = json!({"people": ["John\\Doe\r\n", "Jo\\hn\r\n"]}); let data = Data::json(json); let data = data.normalize(NormalizePaths); let paths = json!({"people": ["John/Doe\r\n", "Jo/hn\r\n"]}); assert_eq!(Data::json(paths), data); let data = data.normalize(NormalizeNewlines); let new_lines = json!({"people": ["John/Doe\n", "Jo/hn\n"]}); assert_eq!(Data::json(new_lines), data); } #[test] #[cfg(feature = "json")] fn json_normalize_array_obj_paths_and_lines() { let json = json!({ "people": [ { "name": "John\\Doe\r\n", "nickname": "Jo\\hn\r\n", } ] }); let data = Data::json(json); let data = data.normalize(NormalizePaths); let paths = json!({ "people": [ { "name": "John/Doe\r\n", "nickname": "Jo/hn\r\n", } ] }); assert_eq!(Data::json(paths), data); let data = data.normalize(NormalizeNewlines); let new_lines = json!({ "people": [ { "name": "John/Doe\n", "nickname": "Jo/hn\n", } ] }); assert_eq!(Data::json(new_lines), data); } #[test] #[cfg(feature = "json")] fn json_normalize_matches_string() { let exp = json!({"name": "{...}"}); let expected = Data::json(exp); let actual = json!({"name": "JohnDoe"}); let actual = Data::json(actual).normalize(NormalizeMatches { substitutions: &Default::default(), pattern: &expected, }); if let (DataInner::Json(exp), DataInner::Json(act)) = (expected.inner, actual.inner) { assert_eq!(exp, act); } } #[test] #[cfg(feature = "json")] fn json_normalize_matches_array() { let exp = json!({"people": "{...}"}); let expected = Data::json(exp); let actual = json!({ "people": [ { "name": "JohnDoe", "nickname": "John", } ] }); let actual = Data::json(actual).normalize(NormalizeMatches { substitutions: &Default::default(), pattern: &expected, }); if let (DataInner::Json(exp), DataInner::Json(act)) = (expected.inner, actual.inner) { assert_eq!(exp, act); } } #[test] #[cfg(feature = "json")] fn json_normalize_matches_obj() { let exp = json!({"people": "{...}"}); let expected = Data::json(exp); let actual = json!({ "people": { "name": "JohnDoe", "nickname": "John", } }); let actual = Data::json(actual).normalize(NormalizeMatches { substitutions: &Default::default(), pattern: &expected, }); if let (DataInner::Json(exp), DataInner::Json(act)) = (expected.inner, actual.inner) { assert_eq!(exp, act); } } #[test] #[cfg(feature = "json")] fn json_normalize_matches_diff_order_array() { let exp = json!({ "people": ["John", "Jane"] }); let expected = Data::json(exp); let actual = json!({ "people": ["Jane", "John"] }); let actual = Data::json(actual).normalize(NormalizeMatches { substitutions: &Default::default(), pattern: &expected, }); if let (DataInner::Json(exp), DataInner::Json(act)) = (expected.inner, actual.inner) { assert_ne!(exp, act); } } }
use super::{account::has_token_account, errors::SpliffError, state::SolanaClient}; use serde::Deserialize; use solana_sdk::{ program_pack::Pack, pubkey::Pubkey, signer::{keypair::Keypair, Signer}, transaction::Transaction, }; use spl_associated_token_account::*; use spl_token::{ self, instruction::{initialize_mint, mint_to_checked}, state::Mint, }; fn new_throwaway_signer() -> (Keypair, Pubkey) { let keypair = Keypair::new(); let pubkey = keypair.pubkey(); (keypair, pubkey) } #[derive(Deserialize, Debug)] pub struct TokenSupply { pub supply: f64, pub decimals: u8, } pub struct Token { pub address: Pubkey, pub signer: Keypair, pub supply: f64, pub decimals: u8, pub mint_tx: String, pub minter_token_account: Pubkey, } pub fn get_rent_exempt_fee(solana_client: &SolanaClient) -> Result<u64, SpliffError> { return match solana_client .client .get_minimum_balance_for_rent_exemption(spl_token::state::Mint::LEN) { Ok(fee) => Ok(fee), Err(err) => Err(SpliffError::SolanaAPIError(format!( "Failed while calculating minimum balance for rent exemption blockhash :\n{:?}", err ))), }; } pub fn create_token( token_supply: &TokenSupply, solana_client: &SolanaClient, ) -> Result<Token, SpliffError> { let (token_signer, token) = new_throwaway_signer(); let rent_exempt_fee = match get_rent_exempt_fee(solana_client) { Ok(fee) => fee, Err(err) => return Err(err), }; let create_token_instruction = solana_sdk::system_instruction::create_account( &solana_client.pubkey, //fee payer &token, rent_exempt_fee, Mint::LEN as u64, &spl_token::id(), //owner ); let initialize_mint_instruction = match initialize_mint( &spl_token::id(), &token, &solana_client.pubkey, None, token_supply.decimals, ) { Ok(instruction) => instruction, Err(err) => { return Err(SpliffError::SolanaProgramError(format!( "Failied to make initialize mint instruction:\n{:?}", err ))); } }; let create_token_account_instruction = create_associated_token_account( &solana_client.pubkey, //Funding address &solana_client.pubkey, //Wallet address &token, ); let token_account = get_associated_token_address(&solana_client.pubkey, &token); let mint_amount = spl_token::ui_amount_to_amount(token_supply.supply, token_supply.decimals); let mint_supply_instruction = match mint_to_checked( &spl_token::id(), &token, &token_account, &solana_client.pubkey, &vec![&solana_client.pubkey, &token], mint_amount, token_supply.decimals, ) { Ok(res) => res, Err(err) => { return Err(SpliffError::SolanaProgramError(format!( "Failed to make mint supply instructions:\n{:?}", err ))); } }; let instructions = vec![ create_token_instruction, initialize_mint_instruction, create_token_account_instruction, mint_supply_instruction, ]; let (recent_blockhash, _fee_calculator) = match solana_client.client.get_recent_blockhash() { Ok(result) => result, Err(err) => { return Err(SpliffError::SolanaAPIError(format!( "Failed to calculate recent blockhash:\n{:?}", err ))); } }; let init_token_transaction = Transaction::new_signed_with_payer( &instructions, Some(&solana_client.pubkey), &vec![&solana_client.keypair, &token_signer], recent_blockhash, ); let tx_signature = match solana_client .client .send_and_confirm_transaction(&init_token_transaction) { Ok(signature) => signature.to_string(), Err(err) => { return Err(SpliffError::SolanaAPIError(format!( "Failed while excecuting transaction:\n{:?}", err ))); } }; let result = Token { address: token, signer: token_signer, supply: token_supply.supply, decimals: token_supply.decimals, mint_tx: tx_signature, minter_token_account: token_account, }; return Ok(result); } pub struct TokenTransfer { pub sender: Pubkey, pub recipient: Pubkey, pub token: Pubkey, pub sender_account: Pubkey, pub recipient_account: Pubkey, pub tx_signature: String, } pub fn transfer_token( token_pubkey: &Pubkey, sender: &Keypair, recipient: &Pubkey, solana_client: &SolanaClient, amount: u64, ) -> Result<TokenTransfer, SpliffError> { let source_account = get_associated_token_address(&sender.pubkey(), &token_pubkey); match has_token_account(&recipient, &token_pubkey, &solana_client) { Ok(res) => { if !res { return Err(SpliffError::SolanaProgramError(format!( "For {} address, token account for {} token not found", &recipient, &token_pubkey ))); } } Err(err) => { return Err(SpliffError::SolanaProgramError(format!( "Failed to get account details of {} address for {} token:\n{:?}", &recipient, &token_pubkey, err ))); } } let recipient_account = get_associated_token_address(&recipient, &token_pubkey); // let transfer_instruction = match spl_token::instruction::transfer_checked( // &spl_token::id(), // &source_pubkey, // &token_pubkey, // &to_pubkey, // &solana_client.pubkey, // &vec![&solana_client.pubkey], // token_transfer_request.amount, // 0, // ) let transfer_instruction = match spl_token::instruction::transfer( &spl_token::id(), //Token program id &source_account, //source_pubkey &recipient_account, //Destination pubkey &solana_client.pubkey, &vec![&solana_client.pubkey], amount, //amount ) { Ok(instruction) => instruction, Err(err) => { return Err(SpliffError::SolanaProgramError(format!( "Failed while creating token transfer instruction:\n{:?}", err ))); } }; let (recent_blockhash, _fee_calculator) = match solana_client.client.get_recent_blockhash() { Ok(result) => result, Err(err) => { return Err(SpliffError::SolanaAPIError(format!( "Failed to calculate recent blockhash:\n{:?}", err ))); } }; let transfer_transaction = Transaction::new_signed_with_payer( &vec![transfer_instruction], Some(&solana_client.pubkey), &vec![&solana_client.keypair], recent_blockhash, ); let tx_signature = match solana_client .client .send_and_confirm_transaction(&transfer_transaction) { Ok(signature) => signature.to_string(), Err(err) => { return Err(SpliffError::SolanaAPIError(format!( "Failed to excecute transaction:\n{:?}", err ))); } }; let token_transfer = TokenTransfer { sender: sender.pubkey(), recipient: recipient.clone(), token: token_pubkey.clone(), sender_account: source_account, recipient_account: recipient_account, tx_signature, }; return Ok(token_transfer); }
use { anyhow::Error as AnyhowError, env_logger::{init_from_env, Env}, log::info, }; pub(crate) mod util { use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; #[derive(Clone)] pub struct DebugAs<F>(pub F) where F: Fn(&mut Formatter<'_>) -> FmtResult; impl<F> Debug for DebugAs<F> where F: Fn(&mut Formatter<'_>) -> FmtResult, { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { let Self(d) = self; d(f) } } #[derive(Clone)] pub struct DisplayAs<F>(pub F) where F: Fn(&mut Formatter<'_>) -> FmtResult; impl<F> Display for DisplayAs<F> where F: Fn(&mut Formatter<'_>) -> FmtResult, { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { let Self(d) = self; d(f) } } } mod devices { use { crate::util::{DebugAs, DisplayAs}, log::error, std::{ convert::TryFrom, fmt::{Debug, Display, Formatter, Result as FmtResult}, io::Error as IoError, mem::{size_of, MaybeUninit}, ptr::{null, null_mut}, }, wide_str::wide_str, winapi::{ shared::{ guiddef::GUID, minwindef::{DWORD, FALSE, TRUE}, winerror::ERROR_NO_MORE_ITEMS, }, um::{ handleapi::INVALID_HANDLE_VALUE, setupapi::{ SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo, SetupDiGetClassDevsW, DIGCF_ALLCLASSES, DIGCF_PRESENT, HDEVINFO, SP_DEVINFO_DATA, }, }, }, }; #[derive(Debug)] pub struct DeviceInfoSet(pub HDEVINFO); impl Drop for DeviceInfoSet { fn drop(&mut self) { let Self(handle) = self; unsafe { match SetupDiDestroyDeviceInfoList(*handle) { TRUE => (), FALSE => error!("`DeviceInfoSet::drop` failed: {}", IoError::last_os_error()), _ => unreachable!(), } } } } #[derive(Clone)] pub struct Guid(pub GUID); impl Debug for Guid { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { #[allow(non_snake_case)] let Self(GUID { Data1, Data2, Data3, Data4, }) = self; write!( f, "{{{:08X}-{:04X}-{:04X}-{}}}", Data1, Data2, Data3, DisplayAs(|f| { Data4.iter().try_for_each(|d| write!(f, "{:02X}", d)) }), ) } } impl Display for Guid { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { <Self as Debug>::fmt(self, f) } } #[derive(Clone, Debug)] pub struct DeviceClassFilter<'a> { guid: Option<Guid>, enumerator: Option<PlugNPlayEnumeratorIdentifier<'a>>, flags: DWORD, } impl DeviceClassFilter<'static> { pub fn all() -> Self { Self { enumerator: None, guid: None, flags: DIGCF_ALLCLASSES, } } } impl<'a> DeviceClassFilter<'a> { pub fn enumerator<'b: 'a>( self, pnp_enum_id: Option<PlugNPlayEnumeratorIdentifier<'b>>, ) -> DeviceClassFilter<'b> { let Self { guid, enumerator: _, flags, } = self; DeviceClassFilter { enumerator: pnp_enum_id, guid, flags, } } pub fn present_devices(mut self, yes: bool) -> Self { if yes { self.flags |= DIGCF_PRESENT; } else { self.flags &= !DIGCF_PRESENT; } self } } #[derive(Clone, Debug)] pub enum PlugNPlayEnumeratorIdentifier<'a> { // TODO: Add easy handling of a `Guid` instance Pci, Usb, Custom(&'a [u16]), } impl PlugNPlayEnumeratorIdentifier<'_> { /// The `_guid_write_buf` is here for forwards compatibility for when the `Guid` case is /// added to this enum. fn as_pcwstr(&self, _guid_write_buf: &mut [u16; 101]) -> &[u16] { match self { Self::Pci => &wide_str!("PCI"), Self::Usb => &wide_str!("USB"), Self::Custom(buf) => buf, } } } impl DeviceInfoSet { /// TODO: Prove that this is a safe interface! pub unsafe fn get_devices_of_class(filter: DeviceClassFilter) -> Result<Self, IoError> { let DeviceClassFilter { guid, enumerator, flags, } = filter; let mut small_enum_name_buf = [0; 101]; match SetupDiGetClassDevsW( guid.as_ref() .map(|Guid(g)| -> *const GUID { &*g }) .unwrap_or(null()), enumerator .as_ref() .map(|e| -> *const u16 { e.as_pcwstr(&mut small_enum_name_buf).as_ptr() }) .unwrap_or(null()), null_mut(), flags, ) { INVALID_HANDLE_VALUE => Err(IoError::last_os_error()), handle => Ok(Self(handle)), } } pub fn iter(&self) -> DeviceInfoIter<'_> { DeviceInfoIter { set_handle: self, idx: 0, } } } #[derive(Clone, Debug)] pub struct DeviceInfoIter<'a> { set_handle: &'a DeviceInfoSet, idx: u32, } #[derive(Clone)] pub struct DeviceInfo(SP_DEVINFO_DATA); impl Debug for DeviceInfo { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { #[allow(non_snake_case)] let Self(SP_DEVINFO_DATA { cbSize, ClassGuid, DevInst, Reserved, }) = self; f.debug_struct("DeviceInfo") .field("cbSize", cbSize) .field("ClassGuid", &Guid(ClassGuid.clone())) .field("DevInst", &DebugAs(|f| write!(f, "{:08X}", DevInst))) .field("Reserved", &DebugAs(|f| write!(f, "{:p}", Reserved))) .finish() } } impl DeviceInfoIter<'_> { /// TODO: Verify safety, at which point this can implement `Iterator`. pub unsafe fn next(&mut self) -> Option<Result<DeviceInfo, IoError>> { let Self { idx, set_handle: DeviceInfoSet(ref handle), } = self; let mut device_info = { let mut device_info = MaybeUninit::<SP_DEVINFO_DATA>::zeroed(); (*device_info.as_mut_ptr()).cbSize = u32::try_from(size_of::<SP_DEVINFO_DATA>()).unwrap(); device_info }; match SetupDiEnumDeviceInfo(*handle, *idx, device_info.as_mut_ptr()) { TRUE => { *idx = idx.checked_add(1).unwrap(); Some(Ok(DeviceInfo(device_info.assume_init()))) } FALSE => { let e = IoError::last_os_error(); if e.raw_os_error() == Some(ERROR_NO_MORE_ITEMS as i32) { None } else { Some(Err(e)) } } _ => unreachable!(), } } } } use devices::*; fn main() -> Result<(), AnyhowError> { init_from_env(Env::new().default_filter_or("nzxt_interview=info")); info!("Checking out present USB devices..."); let device_info_set = unsafe { DeviceInfoSet::get_devices_of_class( DeviceClassFilter::all() .enumerator(Some(PlugNPlayEnumeratorIdentifier::Usb)) .present_devices(true), )? }; let mut iter = device_info_set.iter(); while let Some(device_info) = unsafe { iter.next() } { let device_info = device_info?; println!("{:?}", device_info); } info!("Device enumeration ended."); Ok(()) }
use rand::Rng; use rand::thread_rng; use bus::Bus; use std::time::{Instant, Duration}; pub struct Cpu { bus: Bus, pc: u16, sp: u8, stack: [u16; 16], i: usize, v: [u8; 16], pub video: [[u8; 64]; 32], key: [bool; 16], delay_timer: u8, pub sound_timer: u8, delay_duration: Instant, pub make_sound: bool, } impl Cpu { pub fn new(bus: Bus) -> Cpu { Cpu { bus, pc: 0x200, sp: 0, stack: [0; 16], i: 0, v: [0; 16], video: [[0; 64]; 32], key: [false; 16], delay_timer: 0, sound_timer: 0, delay_duration: Instant::now(), make_sound: false, } } pub fn run_next_instruction(&mut self) { let lhs = self.bus.load(self.pc) as u16; let rhs = self.bus.load(self.pc + 1) as u16; let instruction = ((lhs << 8) | rhs) as u16; self.pc = self.pc.wrapping_add(2); self.decode(instruction); } fn set_v(&mut self, addr: u8, value: u8) { self.v[addr as usize] = value; } fn get_v(&self, addr: u8) -> u8 { self.v[addr as usize] } pub fn decrease_timers(&mut self, now: Instant) { if now - self.delay_duration > Duration::from_millis(16) { if self.delay_timer > 0 { self.delay_timer -= 1; } self.make_sound = false; if self.sound_timer > 0 { if self.sound_timer == 1 { self.make_sound = true; } self.sound_timer -= 1; } self.delay_duration = Instant::now(); } } fn decode(&mut self, instruction: u16) { let opcode = instruction >> 12; let nnn = instruction & 0x0fff; let nn = (instruction & 0x00ff) as u8; let n = (instruction & 0x000f) as u8; let x = ((instruction & 0x0f00) >> 8) as u8; let y = ((instruction & 0x00f0) >> 4) as u8; //println!("{:#06x}", instruction); match opcode { 0x0 => { match nn { 0xe0 => { self.video = [[0; 64]; 32]; } 0xee => { self.pc = self.stack[self.sp as usize]; self.sp = self.sp.wrapping_sub(1); } _ => panic!("Unknown instruction {:#06x}", instruction), } } 0x1 => { self.pc = nnn; } 0x2 => { self.sp = self.sp.wrapping_add(1); self.stack[self.sp as usize] = self.pc; self.pc = nnn; } 0x3 => { let vx = self.get_v(x); if vx == nn { self.pc = self.pc.wrapping_add(2); } } 0x4 => { let vx = self.get_v(x); if vx != nn { self.pc = self.pc.wrapping_add(2); } } 0x5 => { let vx = self.get_v(x); let vy = self.get_v(y); if vx == vy { self.pc = self.pc.wrapping_add(2); } } 0x6 => { self.set_v(x, nn); } 0x7 => { let old_v = self.get_v(x); self.set_v(x, old_v.wrapping_add(nn)); } 0x8 => { match n { 0x0 => { let vy = self.get_v(y); self.set_v(x, vy); } 0x1 => { let vx = self.get_v(x); let vy = self.get_v(y); self.set_v(x, vx | vy); } 0x2 => { let vx = self.get_v(x); let vy = self.get_v(y); self.set_v(x, vx & vy); } 0x3 => { let vx = self.get_v(x); let vy = self.get_v(y); self.set_v(x, vx ^ vy); } 0x4 => { let vx = self.get_v(x); let vy = self.get_v(y); let old_vx = vx; self.set_v(x, vx.wrapping_add(vy)); let new_vx = self.get_v(x); if new_vx < old_vx { self.set_v(0xf, 1); } else { self.set_v(0xf, 0); } } 0x5 => { let vx = self.get_v(x); let vy = self.get_v(y); let old_vx = vx; self.set_v(x, vx.wrapping_sub(vy)); let new_vx = self.get_v(x); if new_vx > old_vx { self.set_v(0xf, 1); } else { self.set_v(0xf, 0); } } 0x6 => { let vy = self.get_v(y); self.set_v(y, vy >> 1); self.set_v(x, vy >> 1); self.set_v(0xf, vy & 1); } 0x7 => { let vx = self.get_v(x); let vy = self.get_v(y); let old_vy = vy; self.set_v(x, vy.wrapping_sub(vx)); let new_vy = self.get_v(y); if new_vy > old_vy { self.set_v(0xf, 1); } else { self.set_v(0xf, 0); } } 0xe => { let vy = self.get_v(y); self.set_v(y, vy << 1); self.set_v(x, vy << 1); self.set_v(0xf, vy >> 7); } _ => panic!("Unknown instruction {:#06x}", instruction), } } 0x9 => { let vx = self.get_v(x); let vy = self.get_v(y); if vx != vy { self.pc = self.pc.wrapping_add(2); } } 0xa => { self.i = nnn as usize; } 0xb => { let value = self.get_v(0); self.pc = nnn.wrapping_add(value as u16); } 0xc => { let rand = thread_rng().gen::<u32>(); self.set_v(x, (rand & nn as u32) as u8); } 0xd => { self.draw(x, y, n); } 0xe => { match nn { 0x9e => { let key = self.key[self.get_v(x) as usize]; if key { self.pc = self.pc.wrapping_add(2); } } 0xa1 => { let key = self.key[self.get_v(x) as usize]; if !key { self.pc = self.pc.wrapping_add(2); } } _ => panic!("Unknown instruction {:#06x}", instruction), } } 0xf => { match nn { 0x07 => { let value = self.delay_timer; self.set_v(x, value); } 0x0a => { let mut pressed = false; for index in 0x0..0xf { if self.key[index] { self.set_v(x, index as u8); pressed = true; } } if !pressed { // Blocking Operation. All instruction halted until next key event. self.pc = self.pc.wrapping_sub(2); } } 0x15 => { let value = self.get_v(x); self.delay_timer = value; } 0x18 => { let value = self.get_v(x); self.sound_timer = value; } 0x1e => { let vx = self.get_v(x); self.i = self.i.wrapping_add(vx as usize); } 0x29 => { let value = self.get_v(x); self.i = value as usize * 5; // Font 4x5. } 0x33 => { let value = self.get_v(x); self.bus.store(self.i as u16, value / 100); self.bus.store((self.i + 1) as u16, (value % 100) / 10); self.bus.store((self.i + 2) as u16, value % 10); } 0x55 => { for index in 0..x { let value = self.get_v(index); self.bus.store((self.i as u8 + index) as u16, value); } } 0x65 => { for index in 0..x { let value = self.bus.load((self.i as u8 + index) as u16); self.set_v(index, value); } } _ => panic!("Unknown instruction {:#06x}", instruction), } } _ => panic!("Unknown instruction {:#06x}", instruction), } } fn draw(&mut self, x: u8, y: u8, n: u8) { let col = self.get_v(x) % 64; let row = self.get_v(y) % 32; self.set_v(0xf, 0); for offset in 0..n { let pixel = self.bus.rom.load(self.i.wrapping_add(offset as usize) as u16); for coll_offset in 0..8 { if (pixel & 0x80 >> coll_offset) > 0 { if self.video[((row + offset) % 32) as usize][((col + coll_offset) % 64) as usize] == 1 { self.set_v(0xf, 1); } self.video[((row + offset) % 32) as usize][((col + coll_offset) % 64) as usize] ^= 1; } } } } pub fn read_keys(&mut self, key_code: usize, status: bool) { self.key[key_code] = status; } }
#![deny(warnings)] use clap::{App, Arg}; use ipmpsc::{Sender, SharedRingBuffer}; use std::io::{self, BufRead}; fn main() -> Result<(), Box<dyn std::error::Error>> { let matches = App::new("ipmpsc-send") .about("ipmpsc sender example") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .arg( Arg::with_name("map file") .help( "File to use for shared memory ring buffer. \ This should have already been created and initialized by the receiver.", ) .required(true), ) .get_matches(); let map_file = matches.value_of("map file").unwrap(); let tx = Sender::new(SharedRingBuffer::open(map_file)?); let mut buffer = String::new(); let stdin = io::stdin(); let mut handle = stdin.lock(); println!("Ready! Enter some lines of text to send them to the receiver."); while handle.read_line(&mut buffer)? > 0 { tx.send(&buffer)?; buffer.clear(); } Ok(()) }
use std::{collections::HashMap, fmt::Debug, hash::Hash, sync::Arc}; use async_trait::async_trait; use parking_lot::Mutex; use tokio::sync::{Barrier, Notify}; use super::Loader; #[derive(Debug)] enum TestLoaderResponse<V> { Answer { v: V, block: Option<Arc<Barrier>> }, Panic, } /// An easy-to-mock [`Loader`]. #[derive(Debug, Default)] pub struct TestLoader<K = u8, Extra = bool, V = String> where K: Clone + Debug + Eq + Hash + Send + 'static, Extra: Clone + Debug + Send + 'static, V: Clone + Debug + Send + 'static, { responses: Mutex<HashMap<K, Vec<TestLoaderResponse<V>>>>, blocked: Mutex<Option<Arc<Notify>>>, loaded: Mutex<Vec<(K, Extra)>>, } impl<K, V, Extra> TestLoader<K, Extra, V> where K: Clone + Debug + Eq + Hash + Send + 'static, Extra: Clone + Debug + Send + 'static, V: Clone + Debug + Send + 'static, { /// Mock next value for given key-value pair. pub fn mock_next(&self, k: K, v: V) { self.mock_inner(k, TestLoaderResponse::Answer { v, block: None }); } /// Block on next load for given key-value pair. /// /// Return a barrier that can be used to unblock the load. #[must_use] pub fn block_next(&self, k: K, v: V) -> Arc<Barrier> { let block = Arc::new(Barrier::new(2)); self.mock_inner( k, TestLoaderResponse::Answer { v, block: Some(Arc::clone(&block)), }, ); block } /// Panic when loading value for `k`. /// /// If this is used together with [`block_global`](Self::block_global), the panic will occur AFTER /// blocking. pub fn panic_next(&self, k: K) { self.mock_inner(k, TestLoaderResponse::Panic); } fn mock_inner(&self, k: K, response: TestLoaderResponse<V>) { let mut responses = self.responses.lock(); responses.entry(k).or_default().push(response); } /// Block all [`load`](Self::load) requests until [`unblock`](Self::unblock) is called. /// /// If this is used together with [`panic_once`](Self::panic_once), the panic will occur /// AFTER blocking. pub fn block_global(&self) { let mut blocked = self.blocked.lock(); assert!(blocked.is_none()); *blocked = Some(Arc::new(Notify::new())); } /// Unblock all requests. /// /// Returns number of requests that were blocked. pub fn unblock_global(&self) -> usize { let handle = self.blocked.lock().take().unwrap(); let blocked_count = Arc::strong_count(&handle) - 1; handle.notify_waiters(); blocked_count } /// List all keys that were loaded. /// /// Contains duplicates if keys were loaded multiple times. pub fn loaded(&self) -> Vec<(K, Extra)> { self.loaded.lock().clone() } } impl<K, Extra, V> Drop for TestLoader<K, Extra, V> where K: Clone + Debug + Eq + Hash + Send + 'static, Extra: Clone + Debug + Send + 'static, V: Clone + Debug + Send + 'static, { fn drop(&mut self) { // prevent double-panic (i.e. aborts) if !std::thread::panicking() { for entries in self.responses.lock().values() { assert!(entries.is_empty(), "mocked response left"); } } } } #[async_trait] impl<K, V, Extra> Loader for TestLoader<K, Extra, V> where K: Clone + Debug + Eq + Hash + Send + 'static, Extra: Clone + Debug + Send + 'static, V: Clone + Debug + Send + 'static, { type K = K; type Extra = Extra; type V = V; async fn load(&self, k: Self::K, extra: Self::Extra) -> Self::V { self.loaded.lock().push((k.clone(), extra)); // need to capture the cloned notify handle, otherwise the lock guard leaks into the // generator let maybe_block = self.blocked.lock().clone(); if let Some(block) = maybe_block { block.notified().await; } let response = { let mut guard = self.responses.lock(); let entries = guard.get_mut(&k).expect("entry not mocked"); assert!(!entries.is_empty(), "no mocked response left"); entries.remove(0) }; match response { TestLoaderResponse::Answer { v, block } => { if let Some(block) = block { block.wait().await; } v } TestLoaderResponse::Panic => { panic!("test") } } } } #[cfg(test)] mod tests { use futures::FutureExt; use super::*; #[tokio::test] #[should_panic(expected = "entry not mocked")] async fn test_loader_panic_entry_unknown() { let loader = TestLoader::<u8, (), String>::default(); loader.load(1, ()).await; } #[tokio::test] #[should_panic(expected = "no mocked response left")] async fn test_loader_panic_no_mocked_reponse_left() { let loader = TestLoader::default(); loader.mock_next(1, String::from("foo")); loader.load(1, ()).await; loader.load(1, ()).await; } #[test] #[should_panic(expected = "mocked response left")] fn test_loader_panic_requests_left() { let loader = TestLoader::<u8, (), String>::default(); loader.mock_next(1, String::from("foo")); } #[test] #[should_panic(expected = "panic-by-choice")] fn test_loader_no_double_panic() { let loader = TestLoader::<u8, (), String>::default(); loader.mock_next(1, String::from("foo")); panic!("panic-by-choice"); } #[tokio::test] async fn test_loader_nonblocking_mock() { let loader = TestLoader::default(); loader.mock_next(1, String::from("foo")); loader.mock_next(1, String::from("bar")); loader.mock_next(2, String::from("baz")); assert_eq!(loader.load(1, ()).await, String::from("foo")); assert_eq!(loader.load(2, ()).await, String::from("baz")); assert_eq!(loader.load(1, ()).await, String::from("bar")); } #[tokio::test] async fn test_loader_blocking_mock() { let loader = Arc::new(TestLoader::default()); let loader_barrier = loader.block_next(1, String::from("foo")); loader.mock_next(2, String::from("bar")); let is_blocked_barrier = Arc::new(Barrier::new(2)); let loader_captured = Arc::clone(&loader); let is_blocked_barrier_captured = Arc::clone(&is_blocked_barrier); let handle = tokio::task::spawn(async move { let mut fut_load = loader_captured.load(1, ()).fuse(); futures::select_biased! { _ = fut_load => { panic!("should not finish"); } _ = is_blocked_barrier_captured.wait().fuse() => {} } fut_load.await }); is_blocked_barrier.wait().await; // can still load other entries assert_eq!(loader.load(2, ()).await, String::from("bar")); // unblock load loader_barrier.wait().await; assert_eq!(handle.await.unwrap(), String::from("foo")); } }
mod buffer_tag; mod context_tag; mod project_tag; use crate::process::ShellCommand; use dirs::Dirs; use itertools::Itertools; use once_cell::sync::Lazy; use paths::AbsPathBuf; use rayon::prelude::*; use std::collections::HashMap; use std::hash::Hash; use std::io::{BufRead, BufReader, Error, ErrorKind, Result}; use std::ops::Deref; use std::path::{Path, PathBuf}; use subprocess::{Exec, NullFile}; pub use self::buffer_tag::{BufferTag, BufferTagItem, Scope}; pub use self::context_tag::{ buffer_tag_items, buffer_tags_lines, current_context_tag, current_context_tag_async, fetch_buffer_tags, }; pub use self::project_tag::{ProjectTag, ProjectTagItem}; pub const EXCLUDE: &str = ".git,*.json,node_modules,target,_build,build,dist"; pub static DEFAULT_EXCLUDE_OPT: Lazy<String> = Lazy::new(|| { EXCLUDE .split(',') .map(|x| format!("--exclude={x}")) .join(" ") }); /// Directory for the `tags` files. pub static CTAGS_TAGS_DIR: Lazy<PathBuf> = Lazy::new(|| { let tags_dir = Dirs::project().data_dir().join("tags"); std::fs::create_dir_all(&tags_dir).expect("Couldn't create tags directory for vim-clap"); tags_dir }); pub static CTAGS_EXISTS: Lazy<bool> = Lazy::new(|| { std::process::Command::new("ctags") .arg("--version") .stderr(std::process::Stdio::inherit()) .output() .ok() .and_then(|output| { let stdout = String::from_utf8_lossy(&output.stdout); stdout .split('\n') .next() .map(|line| line.starts_with("Universal Ctags")) }) .unwrap_or(false) }); /// If the ctags executable supports `--output-format=json`. pub static CTAGS_HAS_JSON_FEATURE: Lazy<bool> = Lazy::new(|| { fn detect_json_feature() -> std::io::Result<bool> { let output = std::process::Command::new("ctags") .arg("--list-features") .stderr(std::process::Stdio::inherit()) .output()?; let stdout = String::from_utf8_lossy(&output.stdout); if stdout.split('\n').any(|x| x.starts_with("json")) { Ok(true) } else { Err(Error::new(ErrorKind::Other, "ctags has no +json feature")) } } detect_json_feature().unwrap_or(false) }); /// Used to specify the language when working with `readtags`. static LANG_MAPS: Lazy<HashMap<String, String>> = Lazy::new(|| { fn generate_lang_maps() -> Result<HashMap<String, String>> { let output = std::process::Command::new("ctags") .arg("--list-maps") .stderr(std::process::Stdio::inherit()) .output()?; let stdout = String::from_utf8_lossy(&output.stdout); let mut lang_maps = HashMap::new(); for line in stdout.split('\n') { let mut items = line.split_whitespace(); if let Some(lang) = items.next() { for item in items { // There are a few edge cases that the item is not like `*.rs`, e.g., // Asm *.A51 *.29[kK] *.[68][68][kKsSxX] *.[xX][68][68] *.asm *.ASM *.s *.Shh // it's okay to ignore them and only take care of the most common cases. if let Some(ext) = item.strip_prefix("*.") { lang_maps.insert(ext.to_string(), lang.to_string()); } } } } Ok(lang_maps) } generate_lang_maps().unwrap_or_else(|e| { tracing::error!(error = ?e, "Failed to initialize LANG_MAPS from `ctags --list-maps`"); Default::default() }) }); /// Returns the ctags language given the file extension. /// /// So that we can search the tags by specifying the language later. pub fn get_language(file_extension: &str) -> Option<&str> { LANG_MAPS.get(file_extension).map(AsRef::as_ref) } #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct TagsGenerator<'a, P> { languages: Option<String>, kinds_all: &'a str, fields: &'a str, extras: &'a str, exclude_opt: &'a str, files: &'a [AbsPathBuf], dir: P, } impl<'a, P: AsRef<Path> + Hash> TagsGenerator<'a, P> { pub fn new( languages: Option<String>, kinds_all: &'a str, fields: &'a str, extras: &'a str, files: &'a [AbsPathBuf], dir: P, exclude_opt: &'a str, ) -> Self { Self { languages, kinds_all, fields, extras, files, dir, exclude_opt, } } pub fn with_dir(dir: P) -> Self { Self { languages: None, kinds_all: "*", fields: "*", extras: "*", files: Default::default(), dir, exclude_opt: DEFAULT_EXCLUDE_OPT.deref(), } } pub fn set_languages(&mut self, languages: String) { self.languages = Some(languages); } /// Returns the path of tags file. /// /// The file path of generated tags is determined by the hash of command itself. pub fn tags_path(&self) -> PathBuf { let mut tags_path = CTAGS_TAGS_DIR.deref().clone(); tags_path.push(utils::calculate_hash(self).to_string()); tags_path } /// Executes the command to generate the tags file. pub fn generate_tags(&self) -> Result<()> { // TODO: detect the languages by dir if not explicitly specified? let languages_opt = self .languages .as_ref() .map(|language| format!("--languages={language}")) .unwrap_or_default(); let mut cmd = format!( "ctags {} --kinds-all='{}' --fields='{}' --extras='{}' {} -f '{}' -R", languages_opt, self.kinds_all, self.fields, self.extras, self.exclude_opt, self.tags_path().display() ); // pass the input files. if !self.files.is_empty() { cmd.push(' '); cmd.push_str(&self.files.iter().map(|f| f.display()).join(" ")); } let exit_status = Exec::shell(&cmd) .stderr(NullFile) // ignore the line: ctags: warning... .cwd(self.dir.as_ref()) .join() .map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?; if !exit_status.success() { return Err(Error::new(ErrorKind::Other, "Failed to generate tags file")); } Ok(()) } } #[derive(Debug)] pub struct ProjectCtagsCommand { std_cmd: std::process::Command, shell_cmd: ShellCommand, } impl ProjectCtagsCommand { pub const TAGS_CMD: &'static [&'static str] = &["ctags", "-R", "-x", "--output-format=json", "--fields=+n"]; const BASE_TAGS_CMD: &str = "ctags -R -x --output-format=json --fields=+n"; /// Creates an instance of [`ProjectCtagsCommand`]. pub fn new(std_cmd: std::process::Command, shell_cmd: ShellCommand) -> Self { Self { std_cmd, shell_cmd } } pub fn with_cwd(cwd: PathBuf) -> Self { let mut std_cmd = std::process::Command::new(Self::TAGS_CMD[0]); std_cmd.current_dir(&cwd).args(&Self::TAGS_CMD[1..]).args( EXCLUDE .split(',') .map(|exclude| format!("--exclude={exclude}")), ); let shell_cmd = ShellCommand::new( format!("{} {}", Self::BASE_TAGS_CMD, DEFAULT_EXCLUDE_OPT.deref()), cwd, ); Self::new(std_cmd, shell_cmd) } /// Parallel version of [`formatted_lines`]. pub fn par_formatted_lines(&mut self) -> Result<Vec<String>> { self.std_cmd.output().map(|output| { output .stdout .par_split(|x| x == &b'\n') .filter_map(|tag| { if let Ok(tag) = serde_json::from_slice::<ProjectTag>(tag) { Some(tag.format_proj_tag()) } else { None } }) .collect::<Vec<_>>() }) } pub fn stdout(&mut self) -> Result<Vec<u8>> { let stdout = self.std_cmd.output()?.stdout; Ok(stdout) } /// Returns an iterator of raw line of ctags output. pub fn lines(&self) -> Result<impl Iterator<Item = String>> { let exec_cmd = Exec::cmd(self.std_cmd.get_program()) .args(self.std_cmd.get_args().collect::<Vec<_>>().as_slice()); Ok(BufReader::new( exec_cmd .stream_stdout() .map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?, ) .lines() .flatten()) } /// Returns an iterator of tag line in a formatted form. fn formatted_tags_iter(&self) -> Result<impl Iterator<Item = String>> { Ok(self.lines()?.filter_map(|tag| { if let Ok(tag) = serde_json::from_str::<ProjectTag>(&tag) { Some(tag.format_proj_tag()) } else { None } })) } pub fn tag_item_iter(&self) -> Result<impl Iterator<Item = ProjectTagItem>> { Ok(self.lines()?.filter_map(|tag| { if let Ok(tag) = serde_json::from_str::<ProjectTag>(&tag) { Some(tag.into_project_tag_item()) } else { None } })) } /// Returns a tuple of (total, cache_path) if the cache exists. pub fn ctags_cache(&self) -> Option<(usize, PathBuf)> { self.shell_cmd .cache_digest() .map(|digest| (digest.total, digest.cached_path)) } /// Runs the command and writes the cache to the disk. #[allow(unused)] fn create_cache(&self) -> Result<(usize, PathBuf)> { let mut total = 0usize; let mut formatted_tags_iter = self.formatted_tags_iter()?.map(|x| { total += 1; x }); let lines = formatted_tags_iter.join("\n"); let cache_path = self .shell_cmd .clone() .write_cache(total, lines.as_bytes())?; Ok((total, cache_path)) } /// Parallel version of `create_cache`. pub fn par_create_cache(&mut self) -> Result<(usize, PathBuf)> { // TODO: do not store all the output in memory and redirect them to a file directly. let lines = self.par_formatted_lines()?; let total = lines.len(); let lines = lines.into_iter().join("\n"); let cache_path = self .shell_cmd .clone() .write_cache(total, lines.as_bytes())?; Ok((total, cache_path)) } pub async fn execute_and_write_cache(mut self) -> Result<Vec<String>> { let lines = self.par_formatted_lines()?; { let lines = lines.clone(); let total = lines.len(); let lines = lines.into_iter().join("\n"); if let Err(e) = self.shell_cmd.clone().write_cache(total, lines.as_bytes()) { tracing::error!("Failed to write ctags cache: {e}"); } } Ok(lines) } } // /pattern/, /^pattern$/ pub fn trim_pattern(pattern: &str) -> &str { let pattern = pattern.strip_prefix('/').unwrap_or(pattern); let pattern = pattern.strip_suffix('/').unwrap_or(pattern); let pattern = pattern.strip_prefix('^').unwrap_or(pattern); let pattern = pattern.strip_suffix('$').unwrap_or(pattern); pattern.trim() }
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //! # LibWallet API Definition //! This module contains the Rust backend implementations of the functionality that a wallet for the Tari Base Layer //! will require. The module contains a number of sub-modules that are implemented as async services. These services are //! collected into the main Wallet container struct which manages spinning up all the component services and maintains a //! collection of the handles required to interact with those services. //! This files contains the API calls that will be exposed to external systems that make use of this module. The API //! will be exposed via FFI and will consist of API calls that the FFI client can make into the Wallet module and a set //! of Callbacks that the client must implement and provide to the Wallet module to receive asynchronous replies and //! updates. //! //! # Wallet Flow Documentation //! This documentation will described the flows of the core tasks that the Wallet library supports and will then //! describe how to use the test functions to produce the behaviour of a second wallet without needing to set one up. //! //! ## Generate Test Data //! The `generate_wallet_test_data(...)` function will generate some test data in the wallet. The data generated will be //! as follows: //! //! - Some Contacts //! - Add outputs to the wallet that make up its Available Balance that can be spent //! - Create transaction history //! - Pending Inbound Transactions //! - Pending Outbound Transactions //! - Completed Transactions //! //! ## Send Transaction //! To send a transaction your wallet must have available funds and you must had added the recipient's Public Key as a //! `Contact`. //! //! To send a transaction: //! 1. Call the `send_transaction(dest_public_key, amount, fee_per_gram, message)` function which will result in a //! `PendingOutboundTransaction` being produced and transmitted to the recipient and the funds becoming //! encumbered and appearing in the `PendingOutgoingBalance` and any change will appear in the //! `PendingIncomingBalance`. //! 2. Wait until the recipient replies to the sent transaction which will result in the `PendingOutboundTransaction` //! becoming a `CompletedTransaction` with the `Completed` status. This means that the transaction has been //! negotiated between the parties and is now ready to be broadcast to the Base Layer. The funds are still //! encumbered as pending because the transaction has not been mined yet. //! 3. The finalized `CompletedTransaction' will be sent back to the the receiver so that they have a copy. //! 4. The wallet will broadcast the `CompletedTransaction` to a Base Node to be added to the mempool. its status will //! from `Completed` to `Broadcast. //! 5. Wait until the transaction is mined. The `CompleteTransaction` status will then move from `Broadcast` to `Mined` //! and the pending funds will be spent and received. //! //! ## Receive a Transaction //! 1. When a transaction is received it will appear as an `InboundTransaction` and the amount to be received will //! appear as a `PendingIncomingBalance`. The wallet backend will be listening for these transactions and will //! immediately reply to the sending wallet. //! 2. The sender will send back the finalized `CompletedTransaction` //! 3. This wallet will also broadcast the `CompletedTransaction` to a Base Node to be added to the mempool, its status //! will move from `Completed` to `Broadcast`. This is done so that the Receiver can be sure the finalized //! transaction is broadcast. //! 6. This wallet will then monitor the Base Layer to see when the transaction is mined which means the //! `CompletedTransaction` status will become `Mined` and the funds will then move from the `PendingIncomingBalance` //! to the `AvailableBalance`. //! //! ## Using the test functions //! The above two flows both require a second wallet for this wallet to interact with. Because we do not yet have a live //! Test Net and the communications layer is not quite ready the library supplies four functions to help simulate the //! second wallets role in these flows. The following will describe how to use these functions to produce the flows. //! //! ### Send Transaction with test functions //! 1. Send Transaction as above to produce a `PendingOutboundTransaction`. //! 2. Call the `complete_sent_transaction(...)` function with the tx_id of the sent transaction to simulate a reply. //! This will move the `PendingOutboundTransaction` to become a `CompletedTransaction` with the `Completed` status. //! 3. Call the 'broadcast_transaction(...)` function with the tx_id of the sent transaction and its status will move //! from 'Completed' to 'Broadcast' which means it has been broadcast to the Base Layer Mempool but not mined yet. //! from 'Completed' to 'Broadcast' which means it has been broadcast to the Base Layer Mempool but not mined yet. //! 4. Call the `mined_transaction(...)` function with the tx_id of the sent transaction which will change //! the status of the `CompletedTransaction` from `Broadcast` to `Mined`. The pending funds will also become //! finalized as spent and available funds respectively. //! //! ### Receive Transaction with test functions //! Under normal operation another wallet would initiate a Receive Transaction flow by sending you a transaction. We //! will use the `receive_test_transaction(...)` function to initiate the flow: //! //! 1. Calling `receive_test_transaction(...)` will produce an `InboundTransaction`, the amount of the transaction will //! appear under the `PendingIncomingBalance`. //! 2. To simulate detecting the `InboundTransaction` being broadcast to the Base Layer Mempool call //! `broadcast_transaction(...)` function. This will change the `InboundTransaction` to a //! `CompletedTransaction` with the `Broadcast` status. The funds will still reflect in the pending balance. //! 3. Call the `mined_transaction(...)` function with the tx_id of the received transaction which will //! change the status of the `CompletedTransaction` from `Broadcast` to `Mined`. The pending funds will also //! become finalized as spent and available funds respectively #![recursion_limit = "512"] #[cfg(test)] #[macro_use] extern crate lazy_static; extern crate libc; extern crate tari_wallet; mod callback_handler; mod error; use crate::{callback_handler::CallbackHandler, error::InterfaceError}; use core::ptr; use error::LibWalletError; use libc::{c_char, c_int, c_longlong, c_uchar, c_uint, c_ulonglong, c_ushort}; use log::{LevelFilter, *}; use log4rs::{ append::file::FileAppender, config::{Appender, Config, Root}, encode::pattern::PatternEncoder, }; use rand::rngs::OsRng; use std::{ boxed::Box, ffi::{CStr, CString}, path::PathBuf, slice, sync::Arc, time::Duration, }; use tari_comms::{ multiaddr::Multiaddr, peer_manager::{NodeIdentity, PeerFeatures}, socks, tor, }; use tari_comms_dht::{DbConnectionUrl, DhtConfig}; use tari_core::transactions::{tari_amount::MicroTari, types::CryptoFactories}; use tari_crypto::{ keys::{PublicKey, SecretKey}, tari_utilities::ByteArray, }; use tari_p2p::transport::{TorConfig, TransportType}; use tari_utilities::{hex, hex::Hex, message_format::MessageFormat}; use tari_wallet::{ contacts_service::storage::{database::Contact, sqlite_db::ContactsServiceSqliteDatabase}, error::WalletError, output_manager_service::storage::sqlite_db::OutputManagerSqliteDatabase, storage::{connection_manager::run_migration_and_create_sqlite_connection, sqlite_db::WalletSqliteDatabase}, testnet_utils::{ broadcast_transaction, complete_sent_transaction, finalize_received_transaction, generate_wallet_test_data, get_next_memory_address, mine_transaction, receive_test_transaction, }, transaction_service::storage::{ database::{InboundTransaction, OutboundTransaction, TransactionDatabase, TransactionStatus}, sqlite_db::TransactionServiceSqliteDatabase, }, util::emoji::EmojiId, wallet::WalletConfig, }; use tokio::runtime::Runtime; const LOG_TARGET: &str = "wallet_ffi"; pub type TariWallet = tari_wallet::wallet::Wallet< WalletSqliteDatabase, TransactionServiceSqliteDatabase, OutputManagerSqliteDatabase, ContactsServiceSqliteDatabase, >; pub type TariTransportType = tari_p2p::transport::TransportType; pub type TariPublicKey = tari_comms::types::CommsPublicKey; pub type TariPrivateKey = tari_comms::types::CommsSecretKey; pub type TariCommsConfig = tari_p2p::initialization::CommsConfig; pub struct TariContacts(Vec<TariContact>); pub type TariContact = tari_wallet::contacts_service::storage::database::Contact; pub type TariCompletedTransaction = tari_wallet::transaction_service::storage::database::CompletedTransaction; pub struct TariCompletedTransactions(Vec<TariCompletedTransaction>); pub type TariPendingInboundTransaction = tari_wallet::transaction_service::storage::database::InboundTransaction; pub type TariPendingOutboundTransaction = tari_wallet::transaction_service::storage::database::OutboundTransaction; pub struct TariPendingInboundTransactions(Vec<TariPendingInboundTransaction>); pub struct TariPendingOutboundTransactions(Vec<TariPendingOutboundTransaction>); #[derive(Debug, PartialEq)] pub struct ByteVector(Vec<c_uchar>); // declared like this so that it can be exposed to external header /// -------------------------------- Strings ------------------------------------------------ /// /// Frees memory for a char array /// /// ## Arguments /// `ptr` - The pointer to be freed /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C. /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn string_destroy(ptr: *mut c_char) { if !ptr.is_null() { let _ = CString::from_raw(ptr); } } /// -------------------------------------------------------------------------------------------- /// /// -------------------------------- ByteVector ------------------------------------------------ /// /// Creates a ByteVector /// /// ## Arguments /// `byte_array` - The pointer to the byte array /// `element_count` - The number of elements in byte_array /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut ByteVector` - Pointer to the created ByteVector. Note that it will be ptr::null_mut() /// if the byte_array pointer was null or if the elements in the byte_vector don't match /// element_count when it is created /// /// # Safety /// The ```byte_vector_destroy``` function must be called when finished with a ByteVector to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn byte_vector_create( byte_array: *const c_uchar, element_count: c_uint, error_out: *mut c_int, ) -> *mut ByteVector { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut bytes = ByteVector(Vec::new()); if byte_array.is_null() { error = LibWalletError::from(InterfaceError::NullError("byte_array".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { let array: &[c_uchar] = slice::from_raw_parts(byte_array, element_count as usize); bytes.0 = array.to_vec(); if bytes.0.len() != element_count as usize { error = LibWalletError::from(InterfaceError::AllocationError).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } } Box::into_raw(Box::new(bytes)) } /// Frees memory for a ByteVector /// /// ## Arguments /// `bytes` - The pointer to a ByteVector /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn byte_vector_destroy(bytes: *mut ByteVector) { if !bytes.is_null() { Box::from_raw(bytes); } } /// Gets a c_uchar at position in a ByteVector /// /// ## Arguments /// `ptr` - The pointer to a ByteVector /// `position` - The integer position /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_uchar` - Returns a character. Note that the character will be a null terminator (0) if ptr /// is null or if the position is invalid /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn byte_vector_get_at(ptr: *mut ByteVector, position: c_uint, error_out: *mut c_int) -> c_uchar { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if ptr.is_null() { error = LibWalletError::from(InterfaceError::NullError("ptr".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0 as c_uchar; } let len = byte_vector_get_length(ptr, error_out) as c_int - 1; // clamp to length if len < 0 || position > len as c_uint { error = LibWalletError::from(InterfaceError::PositionInvalidError).code; ptr::swap(error_out, &mut error as *mut c_int); return 0 as c_uchar; } (*ptr).0[position as usize] } /// Gets the number of elements in a ByteVector /// /// ## Arguments /// `ptr` - The pointer to a ByteVector /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_uint` - Returns the integer number of elements in the ByteVector. Note that it will be zero /// if ptr is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn byte_vector_get_length(vec: *const ByteVector, error_out: *mut c_int) -> c_uint { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if vec.is_null() { error = LibWalletError::from(InterfaceError::NullError("vec".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } (*vec).0.len() as c_uint } /// -------------------------------------------------------------------------------------------- /// /// -------------------------------- Public Key ------------------------------------------------ /// /// Creates a TariPublicKey from a ByteVector /// /// ## Arguments /// `bytes` - The pointer to a ByteVector /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `TariPublicKey` - Returns a public key. Note that it will be ptr::null_mut() if bytes is null or /// if there was an error with the contents of bytes /// /// # Safety /// The ```public_key_destroy``` function must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn public_key_create(bytes: *mut ByteVector, error_out: *mut c_int) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let v; if bytes.is_null() { error = LibWalletError::from(InterfaceError::NullError("bytes".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { v = (*bytes).0.clone(); } let pk = TariPublicKey::from_bytes(&v); match pk { Ok(pk) => Box::into_raw(Box::new(pk)), Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Frees memory for a TariPublicKey /// /// ## Arguments /// `pk` - The pointer to a TariPublicKey /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn public_key_destroy(pk: *mut TariPublicKey) { if !pk.is_null() { Box::from_raw(pk); } } /// Gets a ByteVector from a TariPublicKey /// /// ## Arguments /// `pk` - The pointer to a TariPublicKey /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut ByteVector` - Returns a pointer to a ByteVector. Note that it returns ptr::null_mut() if pk is null /// /// # Safety /// The ```byte_vector_destroy``` function must be called when finished with the ByteVector to prevent a memory leak. #[no_mangle] pub unsafe extern "C" fn public_key_get_bytes(pk: *mut TariPublicKey, error_out: *mut c_int) -> *mut ByteVector { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut bytes = ByteVector(Vec::new()); if pk.is_null() { error = LibWalletError::from(InterfaceError::NullError("pk".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { bytes.0 = (*pk).to_vec(); } Box::into_raw(Box::new(bytes)) } /// Creates a TariPublicKey from a TariPrivateKey /// /// ## Arguments /// `secret_key` - The pointer to a TariPrivateKey /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPublicKey` - Returns a pointer to a TariPublicKey /// /// # Safety /// The ```private_key_destroy``` method must be called when finished with a private key to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn public_key_from_private_key( secret_key: *mut TariPrivateKey, error_out: *mut c_int, ) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if secret_key.is_null() { error = LibWalletError::from(InterfaceError::NullError("secret_key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let m = TariPublicKey::from_secret_key(&(*secret_key)); Box::into_raw(Box::new(m)) } /// Creates a TariPublicKey from a char array /// /// ## Arguments /// `key` - The pointer to a char array which is hex encoded /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPublicKey` - Returns a pointer to a TariPublicKey. Note that it returns ptr::null_mut() /// if key is null or if there was an error creating the TariPublicKey from key /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn public_key_from_hex(key: *const c_char, error_out: *mut c_int) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let key_str; if key.is_null() { error = LibWalletError::from(InterfaceError::NullError("key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { key_str = CStr::from_ptr(key).to_str().unwrap().to_owned(); } let public_key = TariPublicKey::from_hex(key_str.as_str()); match public_key { Ok(public_key) => Box::into_raw(Box::new(public_key)), Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Creates a char array from a TariPublicKey in emoji format /// /// ## Arguments /// `pk` - The pointer to a TariPublicKey /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut c_char` - Returns a pointer to a char array. Note that it returns empty /// if emoji is null or if there was an error creating the emoji string from TariPublicKey /// /// # Safety /// The ```string_destroy``` method must be called when finished with a string from rust to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn public_key_to_emoji_id(pk: *mut TariPublicKey, error_out: *mut c_int) -> *mut c_char { let mut error = 0; let mut result = CString::new("").unwrap(); ptr::swap(error_out, &mut error as *mut c_int); if pk.is_null() { error = LibWalletError::from(InterfaceError::NullError("key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return CString::into_raw(result); } let emoji = EmojiId::from_pubkey(&(*pk)); result = CString::new(emoji.as_str()).unwrap(); CString::into_raw(result) } /// Creates a TariPublicKey from a char array in emoji format /// /// ## Arguments /// `const *c_char` - The pointer to a TariPublicKey /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut c_char` - Returns a pointer to a TariPublicKey. Note that it returns null on error. /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn emoji_id_to_public_key(emoji: *const c_char, error_out: *mut c_int) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if emoji.is_null() { error = LibWalletError::from(InterfaceError::NullError("emoji".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } match CStr::from_ptr(emoji) .to_str() .map_err(|_| ()) .and_then(EmojiId::str_to_pubkey) { Ok(pk) => Box::into_raw(Box::new(pk)), Err(_) => { error = LibWalletError::from(InterfaceError::InvalidEmojiId).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// -------------------------------------------------------------------------------------------- /// /// -------------------------------- Private Key ----------------------------------------------- /// /// Creates a TariPrivateKey from a ByteVector /// /// ## Arguments /// `bytes` - The pointer to a ByteVector /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPrivateKey` - Returns a pointer to a TariPublicKey. Note that it returns ptr::null_mut() /// if bytes is null or if there was an error creating the TariPrivateKey from bytes /// /// # Safety /// The ```private_key_destroy``` method must be called when finished with a TariPrivateKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn private_key_create(bytes: *mut ByteVector, error_out: *mut c_int) -> *mut TariPrivateKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let v; if bytes.is_null() { error = LibWalletError::from(InterfaceError::NullError("bytes".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { v = (*bytes).0.clone(); } let pk = TariPrivateKey::from_bytes(&v); match pk { Ok(pk) => Box::into_raw(Box::new(pk)), Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Frees memory for a TariPrivateKey /// /// ## Arguments /// `pk` - The pointer to a TariPrivateKey /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn private_key_destroy(pk: *mut TariPrivateKey) { if !pk.is_null() { Box::from_raw(pk); } } /// Gets a ByteVector from a TariPrivateKey /// /// ## Arguments /// `pk` - The pointer to a TariPrivateKey /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut ByteVectror` - Returns a pointer to a ByteVector. Note that it returns ptr::null_mut() /// if pk is null /// /// # Safety /// The ```byte_vector_destroy``` must be called when finished with a ByteVector to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn private_key_get_bytes(pk: *mut TariPrivateKey, error_out: *mut c_int) -> *mut ByteVector { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut bytes = ByteVector(Vec::new()); if pk.is_null() { error = LibWalletError::from(InterfaceError::NullError("pk".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { bytes.0 = (*pk).to_vec(); } Box::into_raw(Box::new(bytes)) } /// Generates a TariPrivateKey /// /// ## Arguments /// `()` - Does not take any arguments /// /// ## Returns /// `*mut TariPrivateKey` - Returns a pointer to a TariPrivateKey /// /// # Safety /// The ```private_key_destroy``` method must be called when finished with a TariPrivateKey to prevent a memory leak. #[no_mangle] pub unsafe extern "C" fn private_key_generate() -> *mut TariPrivateKey { let secret_key = TariPrivateKey::random(&mut OsRng); Box::into_raw(Box::new(secret_key)) } /// Creates a TariPrivateKey from a char array /// /// ## Arguments /// `key` - The pointer to a char array which is hex encoded /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPrivateKey` - Returns a pointer to a TariPublicKey. Note that it returns ptr::null_mut() /// if key is null or if there was an error creating the TariPrivateKey from key /// /// # Safety /// The ```private_key_destroy``` method must be called when finished with a TariPrivateKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn private_key_from_hex(key: *const c_char, error_out: *mut c_int) -> *mut TariPrivateKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let key_str; if key.is_null() { error = LibWalletError::from(InterfaceError::NullError("key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { key_str = CStr::from_ptr(key).to_str().unwrap().to_owned(); } let secret_key = TariPrivateKey::from_hex(key_str.as_str()); match secret_key { Ok(secret_key) => Box::into_raw(Box::new(secret_key)), Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// -------------------------------------------------------------------------------------------- /// /// ----------------------------------- Contact -------------------------------------------------/// /// Creates a TariContact /// /// ## Arguments /// `alias` - The pointer to a char array /// `public_key` - The pointer to a TariPublicKey /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariContact` - Returns a pointer to a TariContact. Note that it returns ptr::null_mut() /// if alias is null or if pk is null /// /// # Safety /// The ```contact_destroy``` method must be called when finished with a TariContact #[no_mangle] pub unsafe extern "C" fn contact_create( alias: *const c_char, public_key: *mut TariPublicKey, error_out: *mut c_int, ) -> *mut TariContact { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let alias_string; if alias.is_null() { error = LibWalletError::from(InterfaceError::NullError("alias".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } else { alias_string = CStr::from_ptr(alias).to_str().unwrap().to_owned(); } if public_key.is_null() { error = LibWalletError::from(InterfaceError::NullError("public_key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let contact = Contact { alias: alias_string, public_key: (*public_key).clone(), }; Box::into_raw(Box::new(contact)) } /// Gets the alias of the TariContact /// /// ## Arguments /// `contact` - The pointer to a TariContact /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut c_char` - Returns a pointer to a char array. Note that it returns an empty char array if /// contact is null /// /// # Safety /// The ```string_destroy``` method must be called when finished with a string from rust to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn contact_get_alias(contact: *mut TariContact, error_out: *mut c_int) -> *mut c_char { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut a = CString::new("").unwrap(); if contact.is_null() { error = LibWalletError::from(InterfaceError::NullError("contact".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); } else { a = CString::new((*contact).alias.clone()).unwrap(); } CString::into_raw(a) } /// Gets the TariPublicKey of the TariContact /// /// ## Arguments /// `contact` - The pointer to a TariContact /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPublicKey` - Returns a pointer to a TariPublicKey. Note that it returns /// ptr::null_mut() if contact is null /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn contact_get_public_key( contact: *mut TariContact, error_out: *mut c_int, ) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if contact.is_null() { error = LibWalletError::from(InterfaceError::NullError("contact".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } Box::into_raw(Box::new((*contact).public_key.clone())) } /// Frees memory for a TariContact /// /// ## Arguments /// `contact` - The pointer to a TariContact /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn contact_destroy(contact: *mut TariContact) { if !contact.is_null() { Box::from_raw(contact); } } /// ----------------------------------- Contacts -------------------------------------------------/// /// Gets the length of TariContacts /// /// ## Arguments /// `contacts` - The pointer to a TariContacts /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_uint` - Returns number of elements in , zero if contacts is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn contacts_get_length(contacts: *mut TariContacts, error_out: *mut c_int) -> c_uint { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut len = 0; if contacts.is_null() { error = LibWalletError::from(InterfaceError::NullError("contacts".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); } else { len = (*contacts).0.len(); } len as c_uint } /// Gets a TariContact from TariContacts at position /// /// ## Arguments /// `contacts` - The pointer to a TariContacts /// `position` - The integer position /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariContact` - Returns a TariContact, note that it returns ptr::null_mut() if contacts is /// null or position is invalid /// /// # Safety /// The ```contact_destroy``` method must be called when finished with a TariContact to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn contacts_get_at( contacts: *mut TariContacts, position: c_uint, error_out: *mut c_int, ) -> *mut TariContact { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if contacts.is_null() { error = LibWalletError::from(InterfaceError::NullError("contacts".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let len = contacts_get_length(contacts, error_out) as c_int - 1; if len < 0 || position > len as c_uint { error = LibWalletError::from(InterfaceError::PositionInvalidError).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } Box::into_raw(Box::new((*contacts).0[position as usize].clone())) } /// Frees memory for a TariContacts /// /// ## Arguments /// `contacts` - The pointer to a TariContacts /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn contacts_destroy(contacts: *mut TariContacts) { if !contacts.is_null() { Box::from_raw(contacts); } } /// -------------------------------------------------------------------------------------------- /// /// ----------------------------------- CompletedTransactions ----------------------------------- /// /// Gets the length of a TariCompletedTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariCompletedTransactions /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_uint` - Returns the number of elements in a TariCompletedTransactions, note that it will be /// zero if transactions is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transactions_get_length( transactions: *mut TariCompletedTransactions, error_out: *mut c_int, ) -> c_uint { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut len = 0; if transactions.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); } else { len = (*transactions).0.len(); } len as c_uint } /// Gets a TariCompletedTransaction from a TariCompletedTransactions at position /// /// ## Arguments /// `transactions` - The pointer to a TariCompletedTransactions /// `position` - The integer position /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariCompletedTransaction` - Returns a pointer to a TariCompletedTransaction, /// note that ptr::null_mut() is returned if transactions is null or position is invalid /// /// # Safety /// The ```completed_transaction_destroy``` method must be called when finished with a TariCompletedTransaction to /// prevent a memory leak #[no_mangle] pub unsafe extern "C" fn completed_transactions_get_at( transactions: *mut TariCompletedTransactions, position: c_uint, error_out: *mut c_int, ) -> *mut TariCompletedTransaction { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transactions.is_null() { error = LibWalletError::from(InterfaceError::NullError("transactions".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let len = completed_transactions_get_length(transactions, error_out) as c_int - 1; if len < 0 || position > len as c_uint { error = LibWalletError::from(InterfaceError::PositionInvalidError).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } Box::into_raw(Box::new((*transactions).0[position as usize].clone())) } /// Frees memory for a TariCompletedTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariCompletedTransaction /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transactions_destroy(transactions: *mut TariCompletedTransactions) { if !transactions.is_null() { Box::from_raw(transactions); } } /// -------------------------------------------------------------------------------------------- /// /// ----------------------------------- OutboundTransactions ------------------------------------ /// /// Gets the length of a TariPendingOutboundTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariPendingOutboundTransactions /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_uint` - Returns the number of elements in a TariPendingOutboundTransactions, note that it will be /// zero if transactions is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transactions_get_length( transactions: *mut TariPendingOutboundTransactions, error_out: *mut c_int, ) -> c_uint { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut len = 0; if transactions.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); } else { len = (*transactions).0.len(); } len as c_uint } /// Gets a TariPendingOutboundTransaction of a TariPendingOutboundTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariPendingOutboundTransactions /// `position` - The integer position /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPendingOutboundTransaction` - Returns a pointer to a TariPendingOutboundTransaction, /// note that ptr::null_mut() is returned if transactions is null or position is invalid /// /// # Safety /// The ```pending_outbound_transaction_destroy``` method must be called when finished with a /// TariPendingOutboundTransaction to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn pending_outbound_transactions_get_at( transactions: *mut TariPendingOutboundTransactions, position: c_uint, error_out: *mut c_int, ) -> *mut TariPendingOutboundTransaction { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transactions.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let len = pending_outbound_transactions_get_length(transactions, error_out) as c_int - 1; if len < 0 || position > len as c_uint { error = LibWalletError::from(InterfaceError::PositionInvalidError).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } Box::into_raw(Box::new((*transactions).0[position as usize].clone())) } /// Frees memory for a TariPendingOutboundTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariPendingOutboundTransactions /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transactions_destroy(transactions: *mut TariPendingOutboundTransactions) { if !transactions.is_null() { Box::from_raw(transactions); } } /// -------------------------------------------------------------------------------------------- /// /// ----------------------------------- InboundTransactions ------------------------------------- /// /// Gets the length of a TariPendingInboundTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariPendingInboundTransactions /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_uint` - Returns the number of elements in a TariPendingInboundTransactions, note that /// it will be zero if transactions is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_inbound_transactions_get_length( transactions: *mut TariPendingInboundTransactions, error_out: *mut c_int, ) -> c_uint { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut len = 0; if transactions.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); } else { len = (*transactions).0.len(); } len as c_uint } /// Gets a TariPendingInboundTransaction of a TariPendingInboundTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariPendingInboundTransactions /// `position` - The integer position /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPendingOutboundTransaction` - Returns a pointer to a TariPendingInboundTransaction, /// note that ptr::null_mut() is returned if transactions is null or position is invalid /// /// # Safety /// The ```pending_inbound_transaction_destroy``` method must be called when finished with a /// TariPendingOutboundTransaction to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn pending_inbound_transactions_get_at( transactions: *mut TariPendingInboundTransactions, position: c_uint, error_out: *mut c_int, ) -> *mut TariPendingInboundTransaction { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transactions.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let len = pending_inbound_transactions_get_length(transactions, error_out) as c_int - 1; if len < 0 || position > len as c_uint { error = LibWalletError::from(InterfaceError::PositionInvalidError).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } Box::into_raw(Box::new((*transactions).0[position as usize].clone())) } /// Frees memory for a TariPendingInboundTransactions /// /// ## Arguments /// `transactions` - The pointer to a TariPendingInboundTransactions /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_inbound_transactions_destroy(transactions: *mut TariPendingInboundTransactions) { if !transactions.is_null() { Box::from_raw(transactions); } } /// -------------------------------------------------------------------------------------------- /// /// ----------------------------------- CompletedTransaction ------------------------------------- /// /// Gets the TransactionID of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the TransactionID, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_transaction_id( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } (*transaction).tx_id as c_ulonglong } /// Gets the destination TariPublicKey of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TairPublicKey` - Returns the destination TariPublicKey, note that it will be /// ptr::null_mut() if transaction is null /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_destination_public_key( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let m = (*transaction).destination_public_key.clone(); Box::into_raw(Box::new(m)) } /// Gets the source TariPublicKey of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TairPublicKey` - Returns the source TariPublicKey, note that it will be /// ptr::null_mut() if transaction is null /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_source_public_key( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let m = (*transaction).source_public_key.clone(); Box::into_raw(Box::new(m)) } /// Gets the status of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_int` - Returns the status which corresponds to: /// | Value | Interpretation | /// |---|---| /// | -1 | TxNullError | /// | 0 | Completed | /// | 1 | Broadcast | /// | 2 | Mined | /// | 3 | Imported | /// | 4 | Pending | /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_status( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> c_int { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return -1; } let status = (*transaction).status.clone(); status as c_int } /// Gets the amount of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the amount, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_amount( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } c_ulonglong::from((*transaction).amount) } /// Gets the fee of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the fee, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_fee( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } c_ulonglong::from((*transaction).fee) } /// Gets the timestamp of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the timestamp, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_timestamp( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> c_longlong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } (*transaction).timestamp.timestamp() as c_longlong } /// Gets the message of a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*const c_char` - Returns the pointer to the char array, note that it will return a pointer /// to an empty char array if transaction is null /// /// # Safety /// The ```string_destroy``` method must be called when finished with string coming from rust to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn completed_transaction_get_message( transaction: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> *const c_char { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let message = (*transaction).message.clone(); let mut result = CString::new("").unwrap(); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result.into_raw(); } result = CString::new(message).unwrap(); result.into_raw() } /// Frees memory for a TariCompletedTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariCompletedTransaction /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn completed_transaction_destroy(transaction: *mut TariCompletedTransaction) { if !transaction.is_null() { Box::from_raw(transaction); } } /// -------------------------------------------------------------------------------------------- /// /// ----------------------------------- OutboundTransaction ------------------------------------- /// /// Gets the TransactionId of a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the TransactionID, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_get_transaction_id( transaction: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } (*transaction).tx_id as c_ulonglong } /// Gets the destination TariPublicKey of a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPublicKey` - Returns the destination TariPublicKey, note that it will be /// ptr::null_mut() if transaction is null /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_get_destination_public_key( transaction: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let m = (*transaction).destination_public_key.clone(); Box::into_raw(Box::new(m)) } /// Gets the amount of a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the amount, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_get_amount( transaction: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } c_ulonglong::from((*transaction).amount) } /// Gets the fee of a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the fee, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_get_fee( transaction: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } c_ulonglong::from((*transaction).fee) } /// Gets the timestamp of a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the timestamp, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_get_timestamp( transaction: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> c_longlong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } (*transaction).timestamp.timestamp() as c_longlong } /// Gets the message of a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*const c_char` - Returns the pointer to the char array, note that it will return a pointer /// to an empty char array if transaction is null /// /// # Safety /// The ```string_destroy``` method must be called when finished with a string coming from rust to prevent a memory /// leak #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_get_message( transaction: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> *const c_char { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let message = (*transaction).message.clone(); let mut result = CString::new("").unwrap(); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result.into_raw(); } result = CString::new(message).unwrap(); result.into_raw() } /// Gets the status of a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_int` - Returns the status which corresponds to: /// | Value | Interpretation | /// |---|---| /// | -1 | TxNullError | /// | 0 | Completed | /// | 1 | Broadcast | /// | 2 | Mined | /// | 3 | Imported | /// | 4 | Pending | /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_get_status( transaction: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> c_int { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return -1; } let status = (*transaction).status.clone(); status as c_int } /// Frees memory for a TariPendingOutboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingOutboundTransaction /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_outbound_transaction_destroy(transaction: *mut TariPendingOutboundTransaction) { if !transaction.is_null() { Box::from_raw(transaction); } } /// -------------------------------------------------------------------------------------------- /// /// /// ----------------------------------- InboundTransaction ------------------------------------- /// /// Gets the TransactionId of a TariPendingInboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingInboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the TransactonId, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_inbound_transaction_get_transaction_id( transaction: *mut TariPendingInboundTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } (*transaction).tx_id as c_ulonglong } /// Gets the source TariPublicKey of a TariPendingInboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingInboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPublicKey` - Returns a pointer to the source TariPublicKey, note that it will be /// ptr::null_mut() if transaction is null /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn pending_inbound_transaction_get_source_public_key( transaction: *mut TariPendingInboundTransaction, error_out: *mut c_int, ) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let m = (*transaction).source_public_key.clone(); Box::into_raw(Box::new(m)) } /// Gets the amount of a TariPendingInboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingInboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the amount, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_inbound_transaction_get_amount( transaction: *mut TariPendingInboundTransaction, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } c_ulonglong::from((*transaction).amount) } /// Gets the timestamp of a TariPendingInboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingInboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the timestamp, note that it will be zero if transaction is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_inbound_transaction_get_timestamp( transaction: *mut TariPendingInboundTransaction, error_out: *mut c_int, ) -> c_longlong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } (*transaction).timestamp.timestamp() as c_longlong } /// Gets the message of a TariPendingInboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingInboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*const c_char` - Returns the pointer to the char array, note that it will return a pointer /// to an empty char array if transaction is null /// /// # Safety /// The ```string_destroy``` method must be called when finished with a string coming from rust to prevent a memory /// leak #[no_mangle] pub unsafe extern "C" fn pending_inbound_transaction_get_message( transaction: *mut TariPendingInboundTransaction, error_out: *mut c_int, ) -> *const c_char { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let message = (*transaction).message.clone(); let mut result = CString::new("").unwrap(); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result.into_raw(); } result = CString::new(message).unwrap(); result.into_raw() } /// Gets the status of a TariPendingInboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingInboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_int` - Returns the status which corresponds to: /// | Value | Interpretation | /// |---|---| /// | -1 | TxNullError | /// | 0 | Completed | /// | 1 | Broadcast | /// | 2 | Mined | /// | 3 | Imported | /// | 4 | Pending | /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_inbound_transaction_get_status( transaction: *mut TariPendingInboundTransaction, error_out: *mut c_int, ) -> c_int { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if transaction.is_null() { error = LibWalletError::from(InterfaceError::NullError("transaction".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return -1; } let status = (*transaction).status.clone(); status as c_int } /// Frees memory for a TariPendingInboundTransaction /// /// ## Arguments /// `transaction` - The pointer to a TariPendingInboundTransaction /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn pending_inbound_transaction_destroy(transaction: *mut TariPendingInboundTransaction) { if !transaction.is_null() { Box::from_raw(transaction); } } /// -------------------------------------------------------------------------------------------- /// /// ----------------------------------- Transport Types -----------------------------------------/// /// Creates a memory transport type /// /// ## Arguments /// `()` - Does not take any arguments /// /// ## Returns /// `*mut TariTransportType` - Returns a pointer to a memory TariTransportType /// /// # Safety /// The ```transport_type_destroy``` method must be called when finished with a TariTransportType to prevent a memory /// leak #[no_mangle] pub unsafe extern "C" fn transport_memory_create() -> *mut TariTransportType { let transport = TariTransportType::Memory { listener_address: get_next_memory_address(), }; Box::into_raw(Box::new(transport)) } /// Creates a tcp transport type /// /// ## Arguments /// `listener_address` - The pointer to a char array /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariTransportType` - Returns a pointer to a tcp TariTransportType, null on error. /// /// # Safety /// The ```transport_type_destroy``` method must be called when finished with a TariTransportType to prevent a memory /// leak #[no_mangle] pub unsafe extern "C" fn transport_tcp_create( listener_address: *const c_char, error_out: *mut c_int, ) -> *mut TariTransportType { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let listener_address_str; if !listener_address.is_null() { listener_address_str = CStr::from_ptr(listener_address).to_str().unwrap().to_owned(); } else { error = LibWalletError::from(InterfaceError::NullError("listener_address".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let transport = TariTransportType::Tcp { listener_address: listener_address_str.parse::<Multiaddr>().unwrap(), tor_socks_config: None, }; Box::into_raw(Box::new(transport)) } /// Creates a tor transport type /// /// ## Arguments /// `control_server_address` - The pointer to a char array /// `tor_cookie` - The pointer to a ByteVector containing the contents of the tor cookie file, can be null /// `tor_identity` - The pointer to a ByteVector containing the tor identity, can be null. /// `tor_port` - The tor port /// `socks_username` - The pointer to a char array containing the socks username, can be null /// `socks_password` - The pointer to a char array containing the socks password, can be null /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariTransportType` - Returns a pointer to a tor TariTransportType, null on error. /// /// # Safety /// The ```transport_type_destroy``` method must be called when finished with a TariTransportType to prevent a memory /// leak #[no_mangle] pub unsafe extern "C" fn transport_tor_create( control_server_address: *const c_char, tor_cookie: *const ByteVector, tor_identity: *const ByteVector, tor_port: c_ushort, socks_username: *const c_char, socks_password: *const c_char, error_out: *mut c_int, ) -> *mut TariTransportType { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let control_address_str; if !control_server_address.is_null() { control_address_str = CStr::from_ptr(control_server_address).to_str().unwrap().to_owned(); } else { error = LibWalletError::from(InterfaceError::NullError("control_server_address".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let username_str; let password_str; let authentication = if !socks_username.is_null() && !socks_password.is_null() { username_str = CStr::from_ptr(socks_username).to_str().unwrap().to_owned(); password_str = CStr::from_ptr(socks_password).to_str().unwrap().to_owned(); socks::Authentication::Password(username_str, password_str) } else { socks::Authentication::None }; let tor_authentication = if !tor_cookie.is_null() { let cookie_hex = hex::to_hex((*tor_cookie).0.as_slice()); tor::Authentication::Cookie(cookie_hex) } else { tor::Authentication::None }; let mut identity = None; if !tor_identity.is_null() { let bytes = (*tor_identity).0.as_slice(); match tor::TorIdentity::from_binary(bytes) { Ok(ident) => { identity = Some(Box::new(ident)); }, Err(err) => { error = LibWalletError::from(InterfaceError::DeserializationError(format!( "Failed to deserialize tor identity: {}", err ))) .code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); }, } } let tor_config = TorConfig { control_server_addr: control_address_str.parse::<Multiaddr>().unwrap(), control_server_auth: tor_authentication, identity, port_mapping: tor::PortMapping::from_port(tor_port), socks_address_override: None, socks_auth: authentication, }; let transport = TariTransportType::Tor(tor_config); Box::into_raw(Box::new(transport)) } /// Gets the address for a memory transport type /// /// ## Arguments /// `transport` - Pointer to a TariTransportType /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut c_char` - Returns the address as a pointer to a char array, array will be empty on error /// /// # Safety /// Can only be used with a memory transport type, will crash otherwise #[no_mangle] pub unsafe extern "C" fn transport_memory_get_address( transport: *const TariTransportType, error_out: *mut c_int, ) -> *mut c_char { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut address = CString::new("").unwrap(); if !transport.is_null() { match &*transport { TransportType::Memory { listener_address } => { address = CString::new(listener_address.to_string()).unwrap(); }, _ => { error = LibWalletError::from(InterfaceError::NullError("transport".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); }, }; } else { error = LibWalletError::from(InterfaceError::NullError("transport".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); } address.into_raw() } /// Gets the private key for tor /// /// ## Arguments /// `wallet` - Pointer to a TariWallet /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut ByteVector` - Returns the serialized tor identity as a pointer to a ByteVector, contents for ByteVector will /// be empty on error. /// /// # Safety /// Can only be used with a tor transport type, will crash otherwise #[no_mangle] pub unsafe extern "C" fn wallet_get_tor_identity(wallet: *const TariWallet, error_out: *mut c_int) -> *mut ByteVector { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let identity_bytes; if !wallet.is_null() { let service = (*wallet).comms.hidden_service(); match service { Some(s) => { let tor_identity = s.tor_identity(); identity_bytes = tor_identity.to_binary().unwrap(); }, None => { identity_bytes = Vec::new(); }, }; } else { identity_bytes = Vec::new(); error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); } let bytes = ByteVector(identity_bytes); Box::into_raw(Box::new(bytes)) } /// Frees memory for a TariTransportType /// /// ## Arguments /// `transport` - The pointer to a TariTransportType /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety #[no_mangle] pub unsafe extern "C" fn transport_type_destroy(transport: *mut TariTransportType) { if !transport.is_null() { Box::from_raw(transport); } } /// ---------------------------------------------------------------------------------------------/// /// ----------------------------------- CommsConfig ---------------------------------------------/// /// Creates a TariCommsConfig. The result from this function is required when initializing a TariWallet. /// /// ## Arguments /// `public_address` - The public address char array pointer. This is the address that the wallet advertises publicly to /// peers /// `listener_address` - The listener address char array pointer. This is the address that inbound peer /// connections are moved to after initial connection. Default if null is 0.0.0.0:7898 which will accept connections /// from all IP address on port 7898 /// `database_name` - The database name char array pointer. This is the unique name of this /// wallet's database `database_path` - The database path char array pointer which. This is the folder path where the /// database files will be created and the application has write access to /// `secret_key` - The TariSecretKey pointer. This is the secret key corresponding to the Public key that represents /// this node on the Tari comms network /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariCommsConfig` - Returns a pointer to a TariCommsConfig, if any of the parameters are /// null or a problem is encountered when constructing the NetAddress a ptr::null_mut() is returned /// /// # Safety /// The ```comms_config_destroy``` method must be called when finished with a TariCommsConfig to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn comms_config_create( public_address: *const c_char, transport_type: *const TariTransportType, database_name: *const c_char, datastore_path: *const c_char, secret_key: *mut TariPrivateKey, discovery_timeout_in_secs: c_ulonglong, error_out: *mut c_int, ) -> *mut TariCommsConfig { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let public_address_str; if !public_address.is_null() { public_address_str = CStr::from_ptr(public_address).to_str().unwrap().to_owned(); } else { error = LibWalletError::from(InterfaceError::NullError("public_address".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let database_name_string; if !database_name.is_null() { database_name_string = CStr::from_ptr(database_name).to_str().unwrap().to_owned(); } else { error = LibWalletError::from(InterfaceError::NullError("database_name".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let datastore_path_string; if !datastore_path.is_null() { datastore_path_string = CStr::from_ptr(datastore_path).to_str().unwrap().to_owned(); } else { error = LibWalletError::from(InterfaceError::NullError("datastore_path".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let datastore_path = PathBuf::from(datastore_path_string); let dht_database_path = datastore_path.join("dht.db"); let public_address = public_address_str.parse::<Multiaddr>(); match public_address { Ok(public_address) => { let ni = NodeIdentity::new( (*secret_key).clone(), public_address, PeerFeatures::COMMUNICATION_CLIENT, ); match ni { Ok(ni) => { let config = TariCommsConfig { node_identity: Arc::new(ni), transport_type: (*transport_type).clone(), datastore_path, peer_database_name: database_name_string, max_concurrent_inbound_tasks: 100, outbound_buffer_size: 100, dht: DhtConfig { discovery_request_timeout: Duration::from_secs(discovery_timeout_in_secs), database_url: DbConnectionUrl::File(dht_database_path), ..Default::default() }, // TODO: This should be set to false for non-test wallets. See the `allow_test_addresses` field // docstring for more info. allow_test_addresses: true, listener_liveness_whitelist_cidrs: Vec::new(), listener_liveness_max_sessions: 0, }; Box::into_raw(Box::new(config)) }, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } }, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Frees memory for a TariCommsConfig /// /// ## Arguments /// `wc` - The TariCommsConfig pointer /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn comms_config_destroy(wc: *mut TariCommsConfig) { if !wc.is_null() { Box::from_raw(wc); } } /// ---------------------------------------------------------------------------------------------- /// /// ------------------------------------- Wallet -------------------------------------------------/// /// Creates a TariWallet /// /// ## Arguments /// `config` - The TariCommsConfig pointer /// `log_path` - An optional file path to the file where the logs will be written. If no log is required pass *null* /// pointer. /// `callback_received_transaction` - The callback function pointer matching the function signature. This will be called /// when an inbound transaction is received. /// `callback_received_transaction_reply` - The callback function pointer matching the function signature. This will be /// called when a reply is received for a pending outbound transaction /// `callback_received_finalized_transaction` - The callback function pointer matching the function signature. This will /// be called when a Finalized version on an Inbound transaction is received /// `callback_transaction_broadcast` - The callback function pointer matching the function signature. This will be /// called when a Finalized transaction is detected a Broadcast to a base node mempool. /// `callback_transaction_mined` - The callback function pointer matching the function signature. This will be called /// when a Broadcast transaction is detected as mined. /// `callback_discovery_process_complete` - The callback function pointer matching the function signature. This will be /// called when a `send_transacion(..)` call is made to a peer whose address is not known and a discovery process must /// be conducted. The outcome of the discovery process is relayed via this callback /// `callback_base_node_sync_complete` - The callback function pointer matching the function signature. This is called /// when a Base Node Sync process is completed or times out. The request_key is used to identify which request this /// callback references and a result of true means it was successful and false that the process timed out and new one /// will be started /// `error_out` - Pointer to an int which will be modified /// to an error code should one occur, may not be null. Functions as an out parameter. /// ## Returns /// `*mut TariWallet` - Returns a pointer to a TariWallet, note that it returns ptr::null_mut() /// if config is null, a wallet error was encountered or if the runtime could not be created /// /// # Safety /// The ```wallet_destroy``` method must be called when finished with a TariWallet to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_create( config: *mut TariCommsConfig, log_path: *const c_char, callback_received_transaction: unsafe extern "C" fn(*mut TariPendingInboundTransaction), callback_received_transaction_reply: unsafe extern "C" fn(*mut TariCompletedTransaction), callback_received_finalized_transaction: unsafe extern "C" fn(*mut TariCompletedTransaction), callback_transaction_broadcast: unsafe extern "C" fn(*mut TariCompletedTransaction), callback_transaction_mined: unsafe extern "C" fn(*mut TariCompletedTransaction), callback_direct_send_result: unsafe extern "C" fn(c_ulonglong, bool), callback_store_and_forward_send_result: unsafe extern "C" fn(c_ulonglong, bool), callback_transaction_cancellation: unsafe extern "C" fn(c_ulonglong), callback_base_node_sync_complete: unsafe extern "C" fn(u64, bool), error_out: *mut c_int, ) -> *mut TariWallet { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if config.is_null() { error = LibWalletError::from(InterfaceError::NullError("config".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } if !log_path.is_null() { let path = CStr::from_ptr(log_path).to_str().unwrap().to_owned(); let logfile = FileAppender::builder() .encoder(Box::new(PatternEncoder::new( "{d(%Y-%m-%d %H:%M:%S.%f)} [{t}] {l:5} {m}{n}", ))) .append(false) .build(path.as_str()) .unwrap(); let lconfig = Config::builder() .appender(Appender::builder().build("logfile", Box::new(logfile))) .build(Root::builder().appender("logfile").build(LevelFilter::Debug)) .unwrap(); log4rs::init_config(lconfig).expect("Should be able to start logging"); debug!(target: LOG_TARGET, "Logging started"); } let runtime = Runtime::new(); let factories = CryptoFactories::default(); let w; match runtime { Ok(runtime) => { let sql_database_path = (*config) .datastore_path .join((*config).peer_database_name.clone()) .with_extension("sqlite3"); let connection = run_migration_and_create_sqlite_connection(&sql_database_path) .map_err(|e| { error!( target: LOG_TARGET, "Error creating Sqlite Connection in Wallet: {:?}", e ); e }) .expect("Could not open Sqlite db"); let wallet_backend = WalletSqliteDatabase::new(connection.clone()); let transaction_backend = TransactionServiceSqliteDatabase::new(connection.clone()); let output_manager_backend = OutputManagerSqliteDatabase::new(connection.clone()); let contacts_backend = ContactsServiceSqliteDatabase::new(connection); debug!(target: LOG_TARGET, "Databases Initialized"); w = TariWallet::new( WalletConfig { comms_config: (*config).clone(), factories, transaction_service_config: None, }, runtime, wallet_backend, transaction_backend.clone(), output_manager_backend, contacts_backend, ); match w { Ok(w) => { // Start Callback Handler let callback_handler = CallbackHandler::new( TransactionDatabase::new(transaction_backend), w.transaction_service.get_event_stream_fused(), w.output_manager_service.get_event_stream_fused(), w.comms.shutdown_signal(), callback_received_transaction, callback_received_transaction_reply, callback_received_finalized_transaction, callback_transaction_broadcast, callback_transaction_mined, callback_direct_send_result, callback_store_and_forward_send_result, callback_transaction_cancellation, callback_base_node_sync_complete, ); w.runtime.spawn(callback_handler.start()); Box::into_raw(Box::new(w)) }, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } }, Err(e) => { error = LibWalletError::from(InterfaceError::TokioError(e.to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Signs a message using the public key of the TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer. /// `msg` - The message pointer. /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// ## Returns /// `*mut c_char` - Returns the pointer to the hexadecimal representation of the signature and /// public nonce, seperated by a pipe character. Empty if an error occured. /// /// # Safety /// The ```string_destroy``` method must be called when finished with a string coming from rust to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_sign_message( wallet: *mut TariWallet, msg: *const c_char, error_out: *mut c_int, ) -> *mut c_char { let mut error = 0; let mut result = CString::new("").unwrap(); ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result.into_raw(); } if msg.is_null() { error = LibWalletError::from(InterfaceError::NullError("message".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result.into_raw(); } let nonce = TariPrivateKey::random(&mut OsRng); let secret = (*wallet).comms.node_identity().secret_key().clone(); let message = CStr::from_ptr(msg).to_str().unwrap().to_owned(); let signature = (*wallet).sign_message(secret, nonce, &message); match signature { Ok(s) => { let hex_sig = s.get_signature().to_hex(); let hex_nonce = s.get_public_nonce().to_hex(); let hex_return = format!("{}|{}", hex_sig, hex_nonce); result = CString::new(hex_return).unwrap(); }, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); }, } result.into_raw() } /// Verifies the signature of the message signed by a TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer. /// `public_key` - The pointer to the TariPublicKey of the wallet which originally signed the message /// `hex_sig_nonce` - The pointer to the sting containing the hexadecimal representation of the /// signature and public nonce seperated by a pipe character. /// `msg` - The pointer to the msg the signature will be checked against. /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// ## Returns /// `bool` - Returns if the signature is valid or not, will be false if an error occurs. /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_verify_message_signature( wallet: *mut TariWallet, public_key: *mut TariPublicKey, hex_sig_nonce: *const c_char, msg: *const c_char, error_out: *mut c_int, ) -> bool { let mut error = 0; let mut result = false; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result; } if public_key.is_null() { error = LibWalletError::from(InterfaceError::NullError("public key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result; } if hex_sig_nonce.is_null() { error = LibWalletError::from(InterfaceError::NullError("signature".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result; } if msg.is_null() { error = LibWalletError::from(InterfaceError::NullError("message".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return result; } let message = CStr::from_ptr(msg).to_str().unwrap().to_owned(); let hex = CStr::from_ptr(hex_sig_nonce).to_str().unwrap().to_owned(); let hex_keys: Vec<&str> = hex.split('|').collect(); if hex_keys.len() != 2 { error = LibWalletError::from(InterfaceError::PositionInvalidError).code; ptr::swap(error_out, &mut error as *mut c_int); return result; } let secret = TariPrivateKey::from_hex(hex_keys.get(0).unwrap()); match secret { Ok(p) => { let public_nonce = TariPublicKey::from_hex(hex_keys.get(1).unwrap()); match public_nonce { Ok(pn) => result = (*wallet).verify_message_signature((*public_key).clone(), pn, p, message), Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); }, } }, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); }, } result } /// This function will generate some test data in the wallet. The data generated will be /// as follows: /// /// - Some Contacts /// - Add outputs to the wallet that make up its Available Balance that can be spent /// - Create transaction history /// - Pending Inbound Transactions /// - Pending Outbound Transactions /// - Completed Transactions /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_test_generate_data( wallet: *mut TariWallet, datastore_path: *const c_char, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } let datastore_path_string; if !datastore_path.is_null() { datastore_path_string = CStr::from_ptr(datastore_path).to_str().unwrap().to_owned(); } else { error = LibWalletError::from(InterfaceError::NullError("datastore_path".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match generate_wallet_test_data( &mut *wallet, datastore_path_string.as_str(), (*wallet).transaction_backend.clone(), ) { Ok(_) => true, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// This function simulates an external `TariWallet` sending a transaction to this `TariWallet` /// which will become a `TariPendingInboundTransaction` /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_test_receive_transaction(wallet: *mut TariWallet, error_out: *mut c_int) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match receive_test_transaction(&mut *wallet) { Ok(_) => true, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// This function simulates a receiver accepting and replying to a `TariPendingOutboundTransaction`. /// This results in that transaction being "completed" and it's status set to `Broadcast` which /// indicated it is in a base_layer mempool. /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `tx` - The TariPendingOutboundTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_test_complete_sent_transaction( wallet: *mut TariWallet, tx: *mut TariPendingOutboundTransaction, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } if tx.is_null() { error = LibWalletError::from(InterfaceError::NullError("tx".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match complete_sent_transaction(&mut *wallet, (*tx).tx_id) { Ok(_) => true, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// This function checks to determine if a TariCompletedTransaction was originally a TariPendingOutboundTransaction /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `tx` - The TariCompletedTransaction /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if the transaction was originally sent from the wallet /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_is_completed_transaction_outbound( wallet: *mut TariWallet, tx: *mut TariCompletedTransaction, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } if tx.is_null() { error = LibWalletError::from(InterfaceError::NullError("tx".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } if (*tx).source_public_key == (*wallet).comms.node_identity().public_key().clone() { return true; } false } /// This function will simulate the process when a completed transaction is broadcast to /// the base layer mempool. The function will update the status of the completed transaction /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `tx` - The pending inbound transaction to operate on /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_test_finalize_received_transaction( wallet: *mut TariWallet, tx: *mut TariPendingInboundTransaction, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match finalize_received_transaction(&mut *wallet, (*tx).tx_id) { Ok(_) => true, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// This function will simulate the process when a completed transaction is broadcast to /// the base layer mempool. The function will update the status of the completed transaction /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `tx_id` - The transaction id to operate on /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_test_broadcast_transaction( wallet: *mut TariWallet, tx_id: c_ulonglong, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match broadcast_transaction(&mut *wallet, tx_id) { Ok(_) => true, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// This function will simulate the process when a completed transaction is detected as mined on /// the base layer. The function will update the status of the completed transaction AND complete /// the transaction on the Output Manager Service which will update the status of the outputs /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `tx_id` - The transaction id to operate on /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_test_mine_transaction( wallet: *mut TariWallet, tx_id: c_ulonglong, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match mine_transaction(&mut *wallet, tx_id) { Ok(_) => true, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// Adds a base node peer to the TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `public_key` - The TariPublicKey pointer /// `address` - The pointer to a char array /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_add_base_node_peer( wallet: *mut TariWallet, public_key: *mut TariPublicKey, address: *const c_char, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } if public_key.is_null() { error = LibWalletError::from(InterfaceError::NullError("public_key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } let address_string; if !address.is_null() { address_string = CStr::from_ptr(address).to_str().unwrap().to_owned(); } else { error = LibWalletError::from(InterfaceError::NullError("address".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match (*wallet).set_base_node_peer((*public_key).clone(), address_string) { Ok(_) => true, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// Upserts a TariContact to the TariWallet. If the contact does not exist it will be Inserted. If it does exist the /// Alias will be updated. /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `contact` - The TariContact pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_upsert_contact( wallet: *mut TariWallet, contact: *mut TariContact, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } if contact.is_null() { error = LibWalletError::from(InterfaceError::NullError("contact".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match (*wallet) .runtime .block_on((*wallet).contacts_service.upsert_contact((*contact).clone())) { Ok(_) => true, Err(e) => { error = LibWalletError::from(WalletError::ContactsServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// Removes a TariContact from the TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `tx` - The TariPendingInboundTransaction pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - Returns if successful or not /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_remove_contact( wallet: *mut TariWallet, contact: *mut TariContact, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } if contact.is_null() { error = LibWalletError::from(InterfaceError::NullError("contact".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match (*wallet) .runtime .block_on((*wallet).contacts_service.remove_contact((*contact).public_key.clone())) { Ok(_) => true, Err(e) => { error = LibWalletError::from(WalletError::ContactsServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// Gets the available balance from a TariWallet. This is the balance the user can spend. /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - The available balance, 0 if wallet is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_get_available_balance(wallet: *mut TariWallet, error_out: *mut c_int) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } match (*wallet) .runtime .block_on((*wallet).output_manager_service.get_balance()) { Ok(b) => c_ulonglong::from(b.available_balance), Err(e) => { error = LibWalletError::from(WalletError::OutputManagerError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); 0 }, } } /// Gets the incoming balance from a `TariWallet`. This is the uncleared balance of Tari that is /// expected to come into the `TariWallet` but is not yet spendable. /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - The incoming balance, 0 if wallet is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_get_pending_incoming_balance( wallet: *mut TariWallet, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } match (*wallet) .runtime .block_on((*wallet).output_manager_service.get_balance()) { Ok(b) => c_ulonglong::from(b.pending_incoming_balance), Err(e) => { error = LibWalletError::from(WalletError::OutputManagerError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); 0 }, } } /// Gets the outgoing balance from a `TariWallet`. This is the uncleared balance of Tari that has /// been spent /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - The outgoing balance, 0 if wallet is null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_get_pending_outgoing_balance( wallet: *mut TariWallet, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } match (*wallet) .runtime .block_on((*wallet).output_manager_service.get_balance()) { Ok(b) => c_ulonglong::from(b.pending_outgoing_balance), Err(e) => { error = LibWalletError::from(WalletError::OutputManagerError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); 0 }, } } /// Sends a TariPendingOutboundTransaction /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `dest_public_key` - The TariPublicKey pointer of the peer /// `amount` - The amount /// `fee_per_gram` - The transaction fee /// `message` - The pointer to a char array /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `unsigned long long` - Returns 0 if unsuccessful or the TxId of the sent transaction if successful /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_send_transaction( wallet: *mut TariWallet, dest_public_key: *mut TariPublicKey, amount: c_ulonglong, fee_per_gram: c_ulonglong, message: *const c_char, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } if dest_public_key.is_null() { error = LibWalletError::from(InterfaceError::NullError("dest_public_key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } let message_string = if !message.is_null() { CStr::from_ptr(message).to_str().unwrap().to_owned() } else { error = LibWalletError::from(InterfaceError::NullError("message".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); CString::new("").unwrap().to_str().unwrap().to_owned() }; match (*wallet) .runtime .block_on((*wallet).transaction_service.send_transaction( (*dest_public_key).clone(), MicroTari::from(amount), MicroTari::from(fee_per_gram), message_string, )) { Ok(tx_id) => tx_id, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); 0 }, } } /// Get the TariContacts from a TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariContacts` - returns the contacts, note that it returns ptr::null_mut() if /// wallet is null /// /// # Safety /// The ```contacts_destroy``` method must be called when finished with a TariContacts to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_contacts(wallet: *mut TariWallet, error_out: *mut c_int) -> *mut TariContacts { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut contacts = Vec::new(); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let retrieved_contacts = (*wallet).runtime.block_on((*wallet).contacts_service.get_contacts()); match retrieved_contacts { Ok(mut retrieved_contacts) => { contacts.append(&mut retrieved_contacts); Box::into_raw(Box::new(TariContacts(contacts))) }, Err(e) => { error = LibWalletError::from(WalletError::ContactsServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Get the TariCompletedTransactions from a TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariCompletedTransactions` - returns the transactions, note that it returns ptr::null_mut() if /// wallet is null or an error is encountered /// /// # Safety /// The ```completed_transactions_destroy``` method must be called when finished with a TariCompletedTransactions to /// prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_completed_transactions( wallet: *mut TariWallet, error_out: *mut c_int, ) -> *mut TariCompletedTransactions { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut completed = Vec::new(); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let completed_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_completed_transactions()); match completed_transactions { Ok(completed_transactions) => { // The frontend specification calls for completed transactions that have not yet been mined to be // classified as Pending Transactions. In order to support this logic without impacting the practical // definitions and storage of a MimbleWimble CompletedTransaction we will remove CompletedTransactions with // the Completed and Broadcast states from the list returned by this FFI function for tx in completed_transactions .values() .filter(|ct| ct.status != TransactionStatus::Completed) .filter(|ct| ct.status != TransactionStatus::Broadcast) { completed.push(tx.clone()); } Box::into_raw(Box::new(TariCompletedTransactions(completed))) }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Get the TariPendingInboundTransactions from a TariWallet /// /// Currently a CompletedTransaction with the Status of Completed and Broadcast is considered Pending by the frontend /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPendingInboundTransactions` - returns the transactions, note that it returns ptr::null_mut() if /// wallet is null or and error is encountered /// /// # Safety /// The ```pending_inbound_transactions_destroy``` method must be called when finished with a /// TariPendingInboundTransactions to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_pending_inbound_transactions( wallet: *mut TariWallet, error_out: *mut c_int, ) -> *mut TariPendingInboundTransactions { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut pending = Vec::new(); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let pending_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_pending_inbound_transactions()); match pending_transactions { Ok(pending_transactions) => { for tx in pending_transactions.values() { pending.push(tx.clone()); } if let Ok(completed_txs) = (*wallet) .runtime .block_on((*wallet).transaction_service.get_completed_transactions()) { // The frontend specification calls for completed transactions that have not yet been mined to be // classified as Pending Transactions. In order to support this logic without impacting the practical // definitions and storage of a MimbleWimble CompletedTransaction we will add those transaction to the // list here in the FFI interface let my_public_key = (*wallet).comms.node_identity().public_key().clone(); for ct in completed_txs .values() .filter(|ct| ct.status == TransactionStatus::Completed || ct.status == TransactionStatus::Broadcast) .filter(|ct| ct.destination_public_key == my_public_key) { pending.push(InboundTransaction::from(ct.clone())); } } Box::into_raw(Box::new(TariPendingInboundTransactions(pending))) }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Get the TariPendingOutboundTransactions from a TariWallet /// /// Currently a CompletedTransaction with the Status of Completed and Broadcast is considered Pending by the frontend /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPendingOutboundTransactions` - returns the transactions, note that it returns ptr::null_mut() if /// wallet is null or and error is encountered /// /// # Safety /// The ```pending_outbound_transactions_destroy``` method must be called when finished with a /// TariPendingOutboundTransactions to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_pending_outbound_transactions( wallet: *mut TariWallet, error_out: *mut c_int, ) -> *mut TariPendingOutboundTransactions { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); let mut pending = Vec::new(); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let pending_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_pending_outbound_transactions()); match pending_transactions { Ok(pending_transactions) => { for tx in pending_transactions.values() { pending.push(tx.clone()); } if let Ok(completed_txs) = (*wallet) .runtime .block_on((*wallet).transaction_service.get_completed_transactions()) { // The frontend specification calls for completed transactions that have not yet been mined to be // classified as Pending Transactions. In order to support this logic without impacting the practical // definitions and storage of a MimbleWimble CompletedTransaction we will add those transaction to the // list here in the FFI interface let my_public_key = (*wallet).comms.node_identity().public_key().clone(); for ct in completed_txs .values() .filter(|ct| ct.status == TransactionStatus::Completed || ct.status == TransactionStatus::Broadcast) .filter(|ct| ct.source_public_key == my_public_key) { pending.push(OutboundTransaction::from(ct.clone())); } } Box::into_raw(Box::new(TariPendingOutboundTransactions(pending))) }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); ptr::null_mut() }, } } /// Get the TariCompletedTransaction from a TariWallet by its' TransactionId /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `transaction_id` - The TransactionId /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariCompletedTransaction` - returns the transaction, note that it returns ptr::null_mut() if /// wallet is null, an error is encountered or if the transaction is not found /// /// # Safety /// The ```completed_transaction_destroy``` method must be called when finished with a TariCompletedTransaction to /// prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_completed_transaction_by_id( wallet: *mut TariWallet, transaction_id: c_ulonglong, error_out: *mut c_int, ) -> *mut TariCompletedTransaction { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let completed_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_completed_transactions()); match completed_transactions { Ok(completed_transactions) => { if let Some(tx) = completed_transactions.get(&transaction_id) { if tx.status != TransactionStatus::Completed && tx.status != TransactionStatus::Broadcast { let completed = tx.clone(); return Box::into_raw(Box::new(completed)); } } error = 108; ptr::swap(error_out, &mut error as *mut c_int); }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); }, } ptr::null_mut() } /// Get the TariPendingInboundTransaction from a TariWallet by its' TransactionId /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `transaction_id` - The TransactionId /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPendingInboundTransaction` - returns the transaction, note that it returns ptr::null_mut() if /// wallet is null, an error is encountered or if the transaction is not found /// /// # Safety /// The ```pending_inbound_transaction_destroy``` method must be called when finished with a /// TariPendingInboundTransaction to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_pending_inbound_transaction_by_id( wallet: *mut TariWallet, transaction_id: c_ulonglong, error_out: *mut c_int, ) -> *mut TariPendingInboundTransaction { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let pending_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_pending_inbound_transactions()); let completed_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_completed_transactions()); match completed_transactions { Ok(completed_transactions) => { if let Some(tx) = completed_transactions.get(&transaction_id) { if tx.status == TransactionStatus::Broadcast || tx.status == TransactionStatus::Completed { let completed = tx.clone(); let pending_tx = TariPendingInboundTransaction::from(completed); return Box::into_raw(Box::new(pending_tx)); } } }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); }, } match pending_transactions { Ok(pending_transactions) => { if let Some(tx) = pending_transactions.get(&transaction_id) { let pending = tx.clone(); return Box::into_raw(Box::new(pending)); } error = 108; ptr::swap(error_out, &mut error as *mut c_int); }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); }, } ptr::null_mut() } /// Get the TariPendingOutboundTransaction from a TariWallet by its' TransactionId /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `transaction_id` - The TransactionId /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPendingOutboundTransaction` - returns the transaction, note that it returns ptr::null_mut() if /// wallet is null, an error is encountered or if the transaction is not found /// /// # Safety /// The ```pending_outbound_transaction_destroy``` method must be called when finished with a /// TariPendingOutboundtransaction to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_pending_outbound_transaction_by_id( wallet: *mut TariWallet, transaction_id: c_ulonglong, error_out: *mut c_int, ) -> *mut TariPendingOutboundTransaction { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let pending_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_pending_outbound_transactions()); let completed_transactions = (*wallet) .runtime .block_on((*wallet).transaction_service.get_completed_transactions()); match completed_transactions { Ok(completed_transactions) => { if let Some(tx) = completed_transactions.get(&transaction_id) { if tx.status == TransactionStatus::Broadcast || tx.status == TransactionStatus::Completed { let completed = tx.clone(); let pending_tx = TariPendingOutboundTransaction::from(completed); return Box::into_raw(Box::new(pending_tx)); } } }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); }, } match pending_transactions { Ok(pending_transactions) => { if let Some(tx) = pending_transactions.get(&transaction_id) { let pending = tx.clone(); return Box::into_raw(Box::new(pending)); } error = 108; ptr::swap(error_out, &mut error as *mut c_int); }, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); }, } ptr::null_mut() } /// Get the TariPublicKey from a TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `*mut TariPublicKey` - returns the public key, note that ptr::null_mut() is returned /// if wc is null /// /// # Safety /// The ```public_key_destroy``` method must be called when finished with a TariPublicKey to prevent a memory leak #[no_mangle] pub unsafe extern "C" fn wallet_get_public_key(wallet: *mut TariWallet, error_out: *mut c_int) -> *mut TariPublicKey { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return ptr::null_mut(); } let pk = (*wallet).comms.node_identity().public_key().clone(); Box::into_raw(Box::new(pk)) } /// Import a UTXO into the wallet. This will add a spendable UTXO and create a faux completed transaction to record the /// event. /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `amount` - The value of the UTXO in MicroTari /// `spending_key` - The private spending key /// `source_public_key` - The public key of the source of the transaction /// `message` - The message that the transaction will have /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns the TransactionID of the generated transaction, note that it will be zero if transaction is /// null /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_import_utxo( wallet: *mut TariWallet, amount: c_ulonglong, spending_key: *mut TariPrivateKey, source_public_key: *mut TariPublicKey, message: *const c_char, error_out: *mut c_int, ) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } if spending_key.is_null() { error = LibWalletError::from(InterfaceError::NullError("spending_key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } if source_public_key.is_null() { error = LibWalletError::from(InterfaceError::NullError("source_public_key".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } let message_string = if !message.is_null() { CStr::from_ptr(message).to_str().unwrap().to_owned() } else { error = LibWalletError::from(InterfaceError::NullError("message".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); CString::new("Imported UTXO").unwrap().to_str().unwrap().to_owned() }; match (*wallet).import_utxo( MicroTari::from(amount), &(*spending_key).clone(), &(*source_public_key).clone(), message_string, ) { Ok(tx_id) => tx_id, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); 0 }, } } /// Cancel a Pending Outbound Transaction /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `transaction_id` - The TransactionId /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `bool` - returns whether the transaction could be cancelled /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_cancel_pending_transaction( wallet: *mut TariWallet, transaction_id: c_ulonglong, error_out: *mut c_int, ) -> bool { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return false; } match (*wallet) .runtime .block_on((*wallet).transaction_service.cancel_transaction(transaction_id)) { Ok(_) => true, Err(e) => { error = LibWalletError::from(WalletError::TransactionServiceError(e)).code; ptr::swap(error_out, &mut error as *mut c_int); false }, } } /// This function will tell the wallet to query the set base node to confirm the status of wallet data. For example this /// will check that Unspent Outputs stored in the wallet are still available as UTXO's on the blockchain. This will also /// trigger a request for outstanding SAF messages to you neighbours /// /// ## Arguments /// `wallet` - The TariWallet pointer /// `error_out` - Pointer to an int which will be modified to an error code should one occur, may not be null. Functions /// as an out parameter. /// /// ## Returns /// `c_ulonglong` - Returns a unique Request Key that is used to identify which callbacks refer to this specific sync /// request. Note the result will be 0 if there was an error /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_sync_with_base_node(wallet: *mut TariWallet, error_out: *mut c_int) -> c_ulonglong { let mut error = 0; ptr::swap(error_out, &mut error as *mut c_int); if wallet.is_null() { error = LibWalletError::from(InterfaceError::NullError("wallet".to_string())).code; ptr::swap(error_out, &mut error as *mut c_int); return 0; } match (*wallet).sync_with_base_node() { Ok(request_key) => request_key, Err(e) => { error = LibWalletError::from(e).code; ptr::swap(error_out, &mut error as *mut c_int); 0 }, } } /// Frees memory for a TariWallet /// /// ## Arguments /// `wallet` - The TariWallet pointer /// /// ## Returns /// `()` - Does not return a value, equivalent to void in C /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn wallet_destroy(wallet: *mut TariWallet) { if !wallet.is_null() { let m = Box::from_raw(wallet); m.shutdown(); } } /// This function will log the provided string at debug level. To be used to have a client log messages to the LibWallet /// logs. /// /// ## Arguments /// `msg` - A string that will be logged at the debug level. If msg is null nothing will be done. /// /// # Safety /// None #[no_mangle] pub unsafe extern "C" fn log_debug_message(msg: *const c_char) { if !msg.is_null() { let message = CStr::from_ptr(msg).to_str().unwrap().to_owned(); debug!(target: LOG_TARGET, "{}", message); } } #[cfg(test)] mod test { extern crate libc; use crate::*; use libc::{c_char, c_uchar, c_uint}; use std::{ffi::CString, sync::Mutex}; use tari_core::transactions::tari_amount::uT; use tari_wallet::{testnet_utils::random_string, transaction_service::storage::database::TransactionStatus}; use tempdir::TempDir; fn type_of<T>(_: T) -> String { std::any::type_name::<T>().to_string() } #[derive(Debug)] struct CallbackState { pub received_tx_callback_called: bool, pub received_tx_reply_callback_called: bool, pub received_finalized_tx_callback_called: bool, pub broadcast_tx_callback_called: bool, pub mined_tx_callback_called: bool, pub direct_send_callback_called: bool, pub store_and_forward_send_callback_called: bool, pub tx_cancellation_callback_called: bool, pub base_node_sync_callback_called: bool, } impl CallbackState { fn new() -> Self { Self { received_tx_callback_called: false, received_tx_reply_callback_called: false, received_finalized_tx_callback_called: false, broadcast_tx_callback_called: false, mined_tx_callback_called: false, direct_send_callback_called: false, store_and_forward_send_callback_called: false, base_node_sync_callback_called: false, tx_cancellation_callback_called: false, } } fn reset(&mut self) { self.received_tx_callback_called = false; self.received_tx_reply_callback_called = false; self.received_finalized_tx_callback_called = false; self.broadcast_tx_callback_called = false; self.mined_tx_callback_called = false; self.direct_send_callback_called = false; self.store_and_forward_send_callback_called = false; self.tx_cancellation_callback_called = false; self.base_node_sync_callback_called = false; } } lazy_static! { static ref CALLBACK_STATE_FFI: Mutex<CallbackState> = { let c = Mutex::new(CallbackState::new()); c }; } unsafe extern "C" fn received_tx_callback(tx: *mut TariPendingInboundTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariPendingInboundTransaction>() ); let mut lock = CALLBACK_STATE_FFI.lock().unwrap(); lock.received_tx_callback_called = true; drop(lock); pending_inbound_transaction_destroy(tx); } unsafe extern "C" fn received_tx_reply_callback(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); assert_eq!((*tx).status, TransactionStatus::Completed); let mut lock = CALLBACK_STATE_FFI.lock().unwrap(); lock.received_tx_reply_callback_called = true; drop(lock); completed_transaction_destroy(tx); } unsafe extern "C" fn received_tx_finalized_callback(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); assert_eq!((*tx).status, TransactionStatus::Completed); let mut lock = CALLBACK_STATE_FFI.lock().unwrap(); lock.received_finalized_tx_callback_called = true; drop(lock); completed_transaction_destroy(tx); } unsafe extern "C" fn broadcast_callback(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); let mut lock = CALLBACK_STATE_FFI.lock().unwrap(); lock.broadcast_tx_callback_called = true; drop(lock); assert_eq!((*tx).status, TransactionStatus::Broadcast); completed_transaction_destroy(tx); } unsafe extern "C" fn mined_callback(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); assert_eq!((*tx).status, TransactionStatus::Mined); let mut lock = CALLBACK_STATE_FFI.lock().unwrap(); lock.mined_tx_callback_called = true; drop(lock); completed_transaction_destroy(tx); } unsafe extern "C" fn direct_send_callback(_tx_id: c_ulonglong, _result: bool) { assert!(true); } unsafe extern "C" fn store_and_forward_send_callback(_tx_id: c_ulonglong, _result: bool) { assert!(true); } unsafe extern "C" fn tx_cancellation_callback(_tx_id: c_ulonglong) { assert!(true); } unsafe extern "C" fn base_node_sync_process_complete_callback(_tx_id: c_ulonglong, _result: bool) { assert!(true); } unsafe extern "C" fn received_tx_callback_bob(tx: *mut TariPendingInboundTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariPendingInboundTransaction>() ); pending_inbound_transaction_destroy(tx); } unsafe extern "C" fn received_tx_reply_callback_bob(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); assert_eq!((*tx).status, TransactionStatus::Completed); completed_transaction_destroy(tx); } unsafe extern "C" fn received_tx_finalized_callback_bob(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); assert_eq!((*tx).status, TransactionStatus::Completed); completed_transaction_destroy(tx); } unsafe extern "C" fn broadcast_callback_bob(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); assert_eq!((*tx).status, TransactionStatus::Broadcast); completed_transaction_destroy(tx); } unsafe extern "C" fn mined_callback_bob(tx: *mut TariCompletedTransaction) { assert_eq!(tx.is_null(), false); assert_eq!( type_of((*tx).clone()), std::any::type_name::<TariCompletedTransaction>() ); assert_eq!((*tx).status, TransactionStatus::Mined); completed_transaction_destroy(tx); } unsafe extern "C" fn direct_send_callback_bob(_tx_id: c_ulonglong, _result: bool) { assert!(true); } unsafe extern "C" fn store_and_forward_send_callback_bob(_tx_id: c_ulonglong, _result: bool) { assert!(true); } unsafe extern "C" fn tx_cancellation_callback_bob(_tx_id: c_ulonglong) { assert!(true); } unsafe extern "C" fn base_node_sync_process_complete_callback_bob(_tx_id: c_ulonglong, _result: bool) { assert!(true); } #[test] fn test_bytevector() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let bytes: [c_uchar; 4] = [2, 114, 34, 255]; let bytes_ptr = byte_vector_create(bytes.as_ptr(), bytes.len() as c_uint, error_ptr); assert_eq!(error, 0); let length = byte_vector_get_length(bytes_ptr, error_ptr); assert_eq!(error, 0); assert_eq!(length, bytes.len() as c_uint); let byte = byte_vector_get_at(bytes_ptr, 2, error_ptr); assert_eq!(error, 0); assert_eq!(byte, bytes[2]); byte_vector_destroy(bytes_ptr); } } #[test] fn test_bytevector_dont_panic() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let bytes_ptr = byte_vector_create(ptr::null_mut(), 20 as c_uint, error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("bytes_ptr".to_string())).code ); assert_eq!(byte_vector_get_length(bytes_ptr, error_ptr), 0); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("bytes_ptr".to_string())).code ); byte_vector_destroy(bytes_ptr); } } #[test] fn test_transport_type_memory() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let transport = transport_memory_create(); let _address = transport_memory_get_address(transport, error_ptr); assert_eq!(error, 0); } } #[test] fn test_transport_type_tcp() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let address_listener = CString::new("/ip4/127.0.0.1/tcp/0").unwrap(); let address_listener_str: *const c_char = CString::into_raw(address_listener.clone()) as *const c_char; let _transport = transport_tcp_create(address_listener_str, error_ptr); assert_eq!(error, 0); } } #[test] fn test_transport_type_tor() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let address_control = CString::new("/ip4/127.0.0.1/tcp/8080").unwrap(); let address_control_str: *const c_char = CString::into_raw(address_control.clone()) as *const c_char; let _transport = transport_tor_create( address_control_str, ptr::null_mut(), ptr::null_mut(), 8080, ptr::null_mut(), ptr::null_mut(), error_ptr, ); assert_eq!(error, 0); } } #[test] fn test_keys() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let private_key = private_key_generate(); let public_key = public_key_from_private_key(private_key, error_ptr); assert_eq!(error, 0); let private_bytes = private_key_get_bytes(private_key, error_ptr); assert_eq!(error, 0); let public_bytes = public_key_get_bytes(public_key, error_ptr); assert_eq!(error, 0); let private_key_length = byte_vector_get_length(private_bytes, error_ptr); assert_eq!(error, 0); let public_key_length = byte_vector_get_length(public_bytes, error_ptr); assert_eq!(error, 0); assert_eq!(private_key_length, 32); assert_eq!(public_key_length, 32); assert_ne!((*private_bytes), (*public_bytes)); let emoji = public_key_to_emoji_id(public_key, error_ptr) as *mut c_char; let emoji_str = CStr::from_ptr(emoji).to_str().unwrap(); assert!(EmojiId::is_valid(emoji_str)); let pk_emoji = emoji_id_to_public_key(emoji, error_ptr); assert_eq!((*public_key), (*pk_emoji)); private_key_destroy(private_key); public_key_destroy(public_key); public_key_destroy(pk_emoji); byte_vector_destroy(public_bytes); byte_vector_destroy(private_bytes); } } #[test] fn test_keys_dont_panic() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let private_key = private_key_create(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("bytes_ptr".to_string())).code ); let public_key = public_key_from_private_key(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("secret_key_ptr".to_string())).code ); let private_bytes = private_key_get_bytes(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("pk_ptr".to_string())).code ); let public_bytes = public_key_get_bytes(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("pk_ptr".to_string())).code ); let private_key_length = byte_vector_get_length(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("vec_ptr".to_string())).code ); let public_key_length = byte_vector_get_length(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("vec_ptr".to_string())).code ); assert_eq!(private_key_length, 0); assert_eq!(public_key_length, 0); private_key_destroy(private_key); public_key_destroy(public_key); byte_vector_destroy(public_bytes); byte_vector_destroy(private_bytes); } } #[test] fn test_contact() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let test_contact_private_key = private_key_generate(); let test_contact_public_key = public_key_from_private_key(test_contact_private_key, error_ptr); let test_str = "Test Contact"; let test_contact_str = CString::new(test_str).unwrap(); let test_contact_alias: *const c_char = CString::into_raw(test_contact_str) as *const c_char; let test_contact = contact_create(test_contact_alias, test_contact_public_key, error_ptr); let alias = contact_get_alias(test_contact, error_ptr); let alias_string = CString::from_raw(alias).to_str().unwrap().to_owned(); assert_eq!(alias_string, test_str); let contact_key = contact_get_public_key(test_contact, error_ptr); let contact_key_bytes = public_key_get_bytes(contact_key, error_ptr); let contact_bytes_len = byte_vector_get_length(contact_key_bytes, error_ptr); assert_eq!(contact_bytes_len, 32); contact_destroy(test_contact); public_key_destroy(test_contact_public_key); private_key_destroy(test_contact_private_key); string_destroy(test_contact_alias as *mut c_char); byte_vector_destroy(contact_key_bytes); } } #[test] fn test_contact_dont_panic() { unsafe { let mut error = 0; let error_ptr = &mut error as *mut c_int; let test_contact_private_key = private_key_generate(); let test_contact_public_key = public_key_from_private_key(test_contact_private_key, error_ptr); let test_str = "Test Contact"; let test_contact_str = CString::new(test_str).unwrap(); let test_contact_alias: *const c_char = CString::into_raw(test_contact_str) as *const c_char; let mut _test_contact = contact_create(ptr::null_mut(), test_contact_public_key, error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("alias_ptr".to_string())).code ); _test_contact = contact_create(test_contact_alias, ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("public_key_ptr".to_string())).code ); let _alias = contact_get_alias(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("contact_ptr".to_string())).code ); let _contact_key = contact_get_public_key(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("contact_ptr".to_string())).code ); let contact_key_bytes = public_key_get_bytes(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("contact_ptr".to_string())).code ); let contact_bytes_len = byte_vector_get_length(ptr::null_mut(), error_ptr); assert_eq!( error, LibWalletError::from(InterfaceError::NullError("contact_ptr".to_string())).code ); assert_eq!(contact_bytes_len, 0); contact_destroy(_test_contact); public_key_destroy(test_contact_public_key); private_key_destroy(test_contact_private_key); string_destroy(test_contact_alias as *mut c_char); byte_vector_destroy(contact_key_bytes); } } #[test] fn test_wallet_ffi() { unsafe { { let mut lock = CALLBACK_STATE_FFI.lock().unwrap(); lock.reset(); } let mut error = 0; let error_ptr = &mut error as *mut c_int; let secret_key_alice = private_key_generate(); let public_key_alice = public_key_from_private_key(secret_key_alice.clone(), error_ptr); let db_name_alice = CString::new(random_string(8).as_str()).unwrap(); let db_name_alice_str: *const c_char = CString::into_raw(db_name_alice.clone()) as *const c_char; let alice_temp_dir = TempDir::new(random_string(8).as_str()).unwrap(); let db_path_alice = CString::new(alice_temp_dir.path().to_str().unwrap()).unwrap(); let db_path_alice_str: *const c_char = CString::into_raw(db_path_alice.clone()) as *const c_char; let transport_type_alice = transport_memory_create(); let address_alice = transport_memory_get_address(transport_type_alice, error_ptr); let address_alice_str = CStr::from_ptr(address_alice).to_str().unwrap().to_owned(); let address_alice_str: *const c_char = CString::new(address_alice_str).unwrap().into_raw() as *const c_char; let alice_config = comms_config_create( address_alice_str, transport_type_alice, db_name_alice_str, db_path_alice_str, secret_key_alice, 20, error_ptr, ); let alice_wallet = wallet_create( alice_config, ptr::null(), received_tx_callback, received_tx_reply_callback, received_tx_finalized_callback, broadcast_callback, mined_callback, direct_send_callback, store_and_forward_send_callback, tx_cancellation_callback, base_node_sync_process_complete_callback, error_ptr, ); let secret_key_bob = private_key_generate(); let public_key_bob = public_key_from_private_key(secret_key_bob.clone(), error_ptr); let db_name_bob = CString::new(random_string(8).as_str()).unwrap(); let db_name_bob_str: *const c_char = CString::into_raw(db_name_bob.clone()) as *const c_char; let bob_temp_dir = TempDir::new(random_string(8).as_str()).unwrap(); let db_path_bob = CString::new(bob_temp_dir.path().to_str().unwrap()).unwrap(); let db_path_bob_str: *const c_char = CString::into_raw(db_path_bob.clone()) as *const c_char; let transport_type_bob = transport_memory_create(); let address_bob = transport_memory_get_address(transport_type_bob, error_ptr); let address_bob_str = CStr::from_ptr(address_bob).to_str().unwrap().to_owned(); let address_bob_str: *const c_char = CString::new(address_bob_str).unwrap().into_raw() as *const c_char; let bob_config = comms_config_create( address_bob_str, transport_type_bob, db_name_bob_str, db_path_bob_str, secret_key_bob, 20, error_ptr, ); let bob_wallet = wallet_create( bob_config, ptr::null(), received_tx_callback_bob, received_tx_reply_callback_bob, received_tx_finalized_callback_bob, broadcast_callback_bob, mined_callback_bob, direct_send_callback_bob, store_and_forward_send_callback_bob, tx_cancellation_callback_bob, base_node_sync_process_complete_callback_bob, error_ptr, ); let sig_msg = CString::new("Test Contact").unwrap(); let sig_msg_str: *const c_char = CString::into_raw(sig_msg) as *const c_char; let sig_msg_compare = CString::new("Test Contact").unwrap(); let sig_msg_compare_str: *const c_char = CString::into_raw(sig_msg_compare) as *const c_char; let sig_nonce_str: *mut c_char = wallet_sign_message(alice_wallet, sig_msg_str, error_ptr) as *mut c_char; let alice_wallet_key = wallet_get_public_key(alice_wallet, error_ptr); let verify_msg = wallet_verify_message_signature( alice_wallet, alice_wallet_key, sig_nonce_str, sig_msg_compare_str, error_ptr, ); assert_eq!(verify_msg, true); let test_contact_private_key = private_key_generate(); let test_contact_public_key = public_key_from_private_key(test_contact_private_key, error_ptr); let test_contact_str = CString::new("Test Contact").unwrap(); let test_contact_alias: *const c_char = CString::into_raw(test_contact_str) as *const c_char; let test_contact = contact_create(test_contact_alias, test_contact_public_key, error_ptr); let contact_added = wallet_upsert_contact(alice_wallet, test_contact, error_ptr); assert_eq!(contact_added, true); let contact_removed = wallet_remove_contact(alice_wallet, test_contact, error_ptr); assert_eq!(contact_removed, true); contact_destroy(test_contact); public_key_destroy(test_contact_public_key); private_key_destroy(test_contact_private_key); string_destroy(test_contact_alias as *mut c_char); let generated = wallet_test_generate_data(alice_wallet, db_path_alice_str, error_ptr); assert_eq!(generated, true); assert_eq!( (wallet_get_completed_transactions(&mut (*alice_wallet), error_ptr)).is_null(), false ); assert_eq!( (wallet_get_pending_inbound_transactions(&mut (*alice_wallet), error_ptr)).is_null(), false ); assert_eq!( (wallet_get_pending_outbound_transactions(&mut (*alice_wallet), error_ptr)).is_null(), false ); let inbound_transactions: std::collections::HashMap< u64, tari_wallet::transaction_service::storage::database::InboundTransaction, > = (*alice_wallet) .runtime .block_on((*alice_wallet).transaction_service.get_pending_inbound_transactions()) .unwrap(); assert_eq!(inbound_transactions.len(), 0); // `wallet_test_generate_data(...)` creates 5 completed inbound tx which should appear in this list let ffi_inbound_txs = wallet_get_pending_inbound_transactions(&mut (*alice_wallet), error_ptr); assert_eq!(pending_inbound_transactions_get_length(ffi_inbound_txs, error_ptr), 5); wallet_test_receive_transaction(alice_wallet, error_ptr); let inbound_transactions: std::collections::HashMap< u64, tari_wallet::transaction_service::storage::database::InboundTransaction, > = (*alice_wallet) .runtime .block_on((*alice_wallet).transaction_service.get_pending_inbound_transactions()) .unwrap(); assert_eq!(inbound_transactions.len(), 1); let ffi_inbound_txs = wallet_get_pending_inbound_transactions(&mut (*alice_wallet), error_ptr); assert_eq!(pending_inbound_transactions_get_length(ffi_inbound_txs, error_ptr), 6); let mut found_pending = false; for i in 0..pending_inbound_transactions_get_length(ffi_inbound_txs, error_ptr) { let pending_tx = pending_inbound_transactions_get_at(ffi_inbound_txs, i, error_ptr); let status = pending_inbound_transaction_get_status(pending_tx, error_ptr); if status == 4 { found_pending = true; } } assert!(found_pending, "At least 1 transaction should be in the Pending state"); // `wallet_test_generate_data(...)` creates 9 completed outbound transactions that are not mined let ffi_outbound_txs = wallet_get_pending_outbound_transactions(&mut (*alice_wallet), error_ptr); assert_eq!(pending_outbound_transactions_get_length(ffi_outbound_txs, error_ptr), 9); let mut found_broadcast = false; for i in 0..pending_outbound_transactions_get_length(ffi_outbound_txs, error_ptr) { let pending_tx = pending_outbound_transactions_get_at(ffi_outbound_txs, i, error_ptr); let status = pending_outbound_transaction_get_status(pending_tx, error_ptr); if status == 1 { found_broadcast = true; } } assert!( found_broadcast, "At least 1 transaction should be in the Broadcast state" ); let completed_transactions: std::collections::HashMap< u64, tari_wallet::transaction_service::storage::database::CompletedTransaction, > = (*alice_wallet) .runtime .block_on((*alice_wallet).transaction_service.get_completed_transactions()) .unwrap(); let num_completed_tx_pre = completed_transactions.len(); for (_k, v) in inbound_transactions { let tx_ptr = Box::into_raw(Box::new(v.clone())); wallet_test_finalize_received_transaction(alice_wallet, tx_ptr, error_ptr); break; } let completed_transactions: std::collections::HashMap< u64, tari_wallet::transaction_service::storage::database::CompletedTransaction, > = (*alice_wallet) .runtime .block_on((*alice_wallet).transaction_service.get_completed_transactions()) .unwrap(); assert_eq!(num_completed_tx_pre + 1, completed_transactions.len()); // At this stage there is only 1 Mined transaction created by the `wallet_test_generate_data(...)` function let ffi_completed_txs = wallet_get_completed_transactions(&mut (*alice_wallet), error_ptr); assert_eq!(completed_transactions_get_length(ffi_completed_txs, error_ptr), 1); for x in 0..completed_transactions_get_length(ffi_completed_txs, error_ptr) { let id_completed = completed_transactions_get_at(&mut (*ffi_completed_txs), x, error_ptr); let id_completed_get = wallet_get_completed_transaction_by_id( &mut (*alice_wallet), (&mut (*id_completed)).tx_id, error_ptr, ); if (&mut (*id_completed)).status == TransactionStatus::Mined { assert_eq!((*id_completed), (*id_completed_get)); assert_eq!((*id_completed_get).status, TransactionStatus::Mined); } else { assert_eq!(id_completed_get, ptr::null_mut()); let pk_compare = wallet_get_public_key(&mut (*alice_wallet), error_ptr); if (&mut (*pk_compare)).as_bytes() == (&mut (*id_completed)).destination_public_key.as_bytes() { let id_inbound_get = wallet_get_pending_inbound_transaction_by_id( &mut (*alice_wallet), (&mut (*id_completed_get)).tx_id, error_ptr, ); assert_ne!(id_inbound_get, ptr::null_mut()); assert_ne!((&mut (*id_inbound_get)).status, TransactionStatus::Mined); pending_inbound_transaction_destroy(&mut (*id_inbound_get)); } else { let id_outbound_get = wallet_get_pending_outbound_transaction_by_id( &mut (*alice_wallet), (&mut (*id_completed_get)).tx_id, error_ptr, ); assert_ne!(id_outbound_get, ptr::null_mut()); assert_ne!((&mut (*id_outbound_get)).status, TransactionStatus::Mined); pending_outbound_transaction_destroy(&mut (*id_outbound_get)); } public_key_destroy(&mut (*pk_compare)); } completed_transaction_destroy(&mut (*id_completed)); completed_transaction_destroy(&mut (*id_completed_get)); } // TODO: Test transaction collection and transaction methods let completed_transactions: std::collections::HashMap< u64, tari_wallet::transaction_service::storage::database::CompletedTransaction, > = (*alice_wallet) .runtime .block_on((*alice_wallet).transaction_service.get_completed_transactions()) .unwrap(); for (_k, v) in completed_transactions { if v.status == TransactionStatus::Completed { let tx_ptr = Box::into_raw(Box::new(v.clone())); wallet_test_broadcast_transaction(alice_wallet, (*tx_ptr).tx_id, error_ptr); wallet_test_mine_transaction(alice_wallet, (*tx_ptr).tx_id, error_ptr); } } // Now all completed transactions are mined as should be returned let ffi_completed_txs = wallet_get_completed_transactions(&mut (*alice_wallet), error_ptr); assert_eq!(completed_transactions_get_length(ffi_completed_txs, error_ptr), 15); let contacts = wallet_get_contacts(alice_wallet, error_ptr); assert_eq!(contacts_get_length(contacts, error_ptr), 4); let utxo_spending_key = private_key_generate(); let utxo_value = 20000; let pre_balance = (*alice_wallet) .runtime .block_on((*alice_wallet).output_manager_service.get_balance()) .unwrap(); let secret_key_base_node = private_key_generate(); let public_key_base_node = public_key_from_private_key(secret_key_base_node.clone(), error_ptr); let utxo_message_str = CString::new("UTXO Import").unwrap(); let utxo_message: *const c_char = CString::into_raw(utxo_message_str) as *const c_char; let utxo_tx_id = wallet_import_utxo( alice_wallet, utxo_value, utxo_spending_key, public_key_base_node, utxo_message, error_ptr, ); let post_balance = (*alice_wallet) .runtime .block_on((*alice_wallet).output_manager_service.get_balance()) .unwrap(); assert_eq!( pre_balance.available_balance + utxo_value * uT, post_balance.available_balance ); let import_transaction = (*alice_wallet) .runtime .block_on((*alice_wallet).transaction_service.get_completed_transactions()) .unwrap() .remove(&utxo_tx_id) .expect("Tx should be in collection"); assert_eq!(import_transaction.amount, utxo_value * uT); assert_eq!(wallet_sync_with_base_node(alice_wallet, error_ptr), 0); let mut peer_added = wallet_add_base_node_peer(alice_wallet, public_key_bob.clone(), address_bob_str, error_ptr); assert_eq!(peer_added, true); peer_added = wallet_add_base_node_peer(bob_wallet, public_key_alice.clone(), address_alice_str, error_ptr); assert_eq!(peer_added, true); (*alice_wallet) .runtime .block_on( (*alice_wallet) .comms .connection_manager() .dial_peer((*bob_wallet).comms.node_identity().node_id().clone()), ) .unwrap(); assert!(wallet_sync_with_base_node(alice_wallet, error_ptr) > 0); let lock = CALLBACK_STATE_FFI.lock().unwrap(); assert!(lock.received_tx_callback_called); assert!(lock.received_tx_reply_callback_called); assert!(lock.received_finalized_tx_callback_called); assert!(lock.broadcast_tx_callback_called); assert!(lock.mined_tx_callback_called); drop(lock); // Not testing for the discovery_process_completed callback as its tricky to evoke and it is unit tested // elsewhere // free string memory string_destroy(db_name_alice_str as *mut c_char); string_destroy(db_path_alice_str as *mut c_char); string_destroy(address_alice_str as *mut c_char); string_destroy(db_name_bob_str as *mut c_char); string_destroy(db_path_bob_str as *mut c_char); string_destroy(address_bob_str as *mut c_char); // free wallet memory wallet_destroy(alice_wallet); wallet_destroy(bob_wallet); // free keys private_key_destroy(secret_key_alice); private_key_destroy(secret_key_bob); public_key_destroy(public_key_alice); public_key_destroy(public_key_bob); // free config memory comms_config_destroy(bob_config); comms_config_destroy(alice_config); transport_type_destroy(transport_type_alice); transport_type_destroy(transport_type_bob); } } }
use std::sync::Arc; use crate::Vec2; use crate::Vec2I; use crate::Vec2UI; use crate::graphics::{Backend, BufferUsage}; use super::AccelerationStructureInstance; use super::BottomLevelAccelerationStructureInfo; use super::BufferInfo; use super::LoadOp; use super::MemoryUsage; use super::RenderpassRecordingMode; use super::ShaderType; use super::StoreOp; use super::SubpassInfo; use super::TextureViewInfo; use super::TopLevelAccelerationStructureInfo; use super::texture::TextureLayout; #[derive(Clone)] pub struct Viewport { pub position: Vec2, pub extent: Vec2, pub min_depth: f32, pub max_depth: f32 } #[derive(Clone)] pub struct Scissor { pub position: Vec2I, pub extent: Vec2UI } #[derive(Clone, Debug, Copy, PartialEq, Hash)] pub enum CommandBufferType { Primary, Secondary } #[derive(Clone)] pub enum PipelineBinding<'a, B: Backend> { Graphics(&'a Arc<B::GraphicsPipeline>), Compute(&'a Arc<B::ComputePipeline>), RayTracing(&'a Arc<B::RayTracingPipeline>), } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum IndexFormat { U16, U32 } pub trait CommandBuffer<B: Backend> { fn set_pipeline(&mut self, pipeline: PipelineBinding<B>); fn set_vertex_buffer(&mut self, vertex_buffer: &Arc<B::Buffer>, offset: usize); fn set_index_buffer(&mut self, index_buffer: &Arc<B::Buffer>, offset: usize, format: IndexFormat); fn set_viewports(&mut self, viewports: &[ Viewport ]); fn set_scissors(&mut self, scissors: &[ Scissor ]); fn upload_dynamic_data<T>(&mut self, data: &[T], usage: BufferUsage) -> Arc<B::Buffer> where T: 'static + Send + Sync + Sized + Clone; fn upload_dynamic_data_inline<T>(&mut self, data: &[T], visible_for_shader_stage: ShaderType) where T: 'static + Send + Sync + Sized + Clone; fn create_temporary_buffer(&mut self, info: &BufferInfo, memory_usage: MemoryUsage) -> Arc<B::Buffer>; fn draw(&mut self, vertices: u32, offset: u32); fn draw_indexed(&mut self, instances: u32, first_instance: u32, indices: u32, first_index: u32, vertex_offset: i32); fn draw_indexed_indirect(&mut self, draw_buffer: &Arc<B::Buffer>, draw_buffer_offset: u32, count_buffer: &Arc<B::Buffer>, count_buffer_offset: u32, max_draw_count: u32, stride: u32); fn draw_indirect(&mut self, draw_buffer: &Arc<B::Buffer>, draw_buffer_offset: u32, count_buffer: &Arc<B::Buffer>, count_buffer_offset: u32, max_draw_count: u32, stride: u32); fn bind_sampling_view(&mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<B::TextureView>); fn bind_sampling_view_and_sampler(&mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<B::TextureView>, sampler: &Arc<B::Sampler>); fn bind_sampling_view_and_sampler_array(&mut self, frequency: BindingFrequency, binding: u32, textures_and_samplers: &[(&Arc<B::TextureView>, &Arc<B::Sampler>)]); fn bind_storage_view_array(&mut self, frequency: BindingFrequency, binding: u32, textures: &[&Arc<B::TextureView>]); fn bind_uniform_buffer(&mut self, frequency: BindingFrequency, binding: u32, buffer: &Arc<B::Buffer>, offset: usize, length: usize); fn bind_storage_buffer(&mut self, frequency: BindingFrequency, binding: u32, buffer: &Arc<B::Buffer>, offset: usize, length: usize); fn bind_storage_texture(&mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<B::TextureView>); fn bind_sampler(&mut self, frequency: BindingFrequency, binding: u32, sampler: &Arc<B::Sampler>); fn bind_acceleration_structure(&mut self, frequency: BindingFrequency, binding: u32, acceleration_structure: &Arc<B::AccelerationStructure>); fn track_texture_view(&mut self, texture_view: &Arc<B::TextureView>); fn finish_binding(&mut self); fn begin_label(&mut self, label: &str); fn end_label(&mut self); fn dispatch(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32); fn blit(&mut self, src_texture: &Arc<B::Texture>, src_array_layer: u32, src_mip_level: u32, dst_texture: &Arc<B::Texture>, dst_array_layer: u32, dst_mip_level: u32); fn finish(self) -> B::CommandBufferSubmission; fn clear_storage_texture(&mut self, view: &Arc<B::Texture>, array_layer: u32, mip_level: u32, values: [u32; 4]); fn clear_storage_buffer(&mut self, buffer: &Arc<B::Buffer>, offset: usize, length_in_u32s: usize, value: u32); fn begin_render_pass(&mut self, renderpass_info: &RenderPassBeginInfo<B>, recording_mode: RenderpassRecordingMode); fn advance_subpass(&mut self); fn end_render_pass(&mut self); fn barrier(&mut self, barriers: &[Barrier<B>]); fn flush_barriers(&mut self); fn create_query_range(&mut self, count: u32) -> Arc<B::QueryRange>; fn begin_query(&mut self, query_range: &Arc<B::QueryRange>, query_index: u32); fn end_query(&mut self, query_range: &Arc<B::QueryRange>, query_index: u32); fn copy_query_results_to_buffer(&mut self, query_range: &Arc<B::QueryRange>, buffer: &Arc<B::Buffer>, start_index: u32, count: u32); // TODO: inherit bound resources for convenience fn inheritance(&self) -> &Self::CommandBufferInheritance; type CommandBufferInheritance: Send + Sync; fn execute_inner(&mut self, submission: Vec<B::CommandBufferSubmission>); // RT fn create_bottom_level_acceleration_structure(&mut self, info: &BottomLevelAccelerationStructureInfo<B>, size: usize, target_buffer: &Arc<B::Buffer>, scratch_buffer: &Arc<B::Buffer>) -> Arc<B::AccelerationStructure>; fn upload_top_level_instances(&mut self, instances: &[AccelerationStructureInstance<B>]) -> Arc<B::Buffer>; fn create_top_level_acceleration_structure(&mut self, info: &TopLevelAccelerationStructureInfo<B>, size: usize, target_buffer: &Arc<B::Buffer>, scratch_buffer: &Arc<B::Buffer>) -> Arc<B::AccelerationStructure>; fn trace_ray(&mut self, width: u32, height: u32, depth: u32); } pub enum FenceRef<'a, B: Backend> { Fence { fence: &'a Arc<B::Fence>, value: u64 }, WSIFence(&'a B::WSIFence) } pub trait Queue<B: Backend> { fn create_command_buffer(&self) -> B::CommandBuffer; fn create_inner_command_buffer(&self, inheritance: &<B::CommandBuffer as CommandBuffer<B>>::CommandBufferInheritance) -> B::CommandBuffer; fn submit(&self, submission: B::CommandBufferSubmission, wait_fences: &[FenceRef<B>], signal_fences: &[FenceRef<B>], delayed: bool); fn present(&self, swapchain: &Arc<B::Swapchain>, wait_fence: &B::WSIFence, delayed: bool); fn process_submissions(&self); } pub enum RenderPassAttachmentView<'a, B: Backend> { RenderTarget(&'a Arc<B::TextureView>), DepthStencil(&'a Arc<B::TextureView>) } pub struct RenderPassAttachment<'a, B: Backend> { pub view: RenderPassAttachmentView<'a, B>, pub load_op: LoadOp, pub store_op: StoreOp } pub struct RenderPassBeginInfo<'a, B: Backend> { pub attachments: &'a [RenderPassAttachment<'a, B>], pub subpasses: &'a [SubpassInfo<'a>] } bitflags! { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct BarrierSync: u32 { const VERTEX_INPUT = 0b1; const VERTEX_SHADER = 0b10; const FRAGMENT_SHADER = 0b100; const COMPUTE_SHADER = 0b1000; const EARLY_DEPTH = 0b10000; const LATE_DEPTH = 0b100000; const RENDER_TARGET = 0b1000000; const COPY = 0b10000000; const RESOLVE = 0b100000000; const INDIRECT = 0b1000000000; const INDEX_INPUT = 0b10000000000; const HOST = 0b100000000000; const ACCELERATION_STRUCTURE_BUILD = 0b1000000000000; const RAY_TRACING = 0b10000000000000; } } bitflags! { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct BarrierAccess: u32 { const INDEX_READ = 0b1; const INDIRECT_READ = 0b10; const VERTEX_INPUT_READ = 0b100; const CONSTANT_READ = 0b1000; const STORAGE_READ = 0b10000; const STORAGE_WRITE = 0b100000; const SAMPLING_READ = 0b1000000; const COPY_READ = 0b10000000; const COPY_WRITE = 0b100000000; const RESOLVE_READ = 0b1000000000; const RESOLVE_WRITE = 0b10000000000; const DEPTH_STENCIL_READ = 0b100000000000; const DEPTH_STENCIL_WRITE = 0b1000000000000; const RENDER_TARGET_READ = 0b10000000000000; const RENDER_TARGET_WRITE = 0b100000000000000; const SHADER_READ = 0b1000000000000000; const SHADER_WRITE = 0b10000000000000000; const MEMORY_READ = 0b100000000000000000; const MEMORY_WRITE = 0b1000000000000000000; const HOST_READ = 0b10000000000000000000; const HOST_WRITE = 0b100000000000000000000; const ACCELERATION_STRUCTURE_READ = 0b1000000000000000000000; const ACCELERATION_STRUCTURE_WRITE = 0b10000000000000000000000; } } impl BarrierAccess { pub fn write_mask() -> BarrierAccess { BarrierAccess::STORAGE_WRITE | BarrierAccess::COPY_WRITE | BarrierAccess::DEPTH_STENCIL_WRITE | BarrierAccess::RESOLVE_WRITE | BarrierAccess::RENDER_TARGET_WRITE | BarrierAccess::RENDER_TARGET_WRITE | BarrierAccess::SHADER_WRITE | BarrierAccess::MEMORY_WRITE | BarrierAccess::HOST_WRITE | BarrierAccess::ACCELERATION_STRUCTURE_WRITE } pub fn is_write(&self) -> bool { let writes = Self::write_mask(); self.intersects(writes) } } #[derive(Clone, Hash, PartialEq, Eq)] pub struct BarrierTextureRange { pub base_mip_level: u32, pub mip_level_length: u32, pub base_array_layer: u32, pub array_layer_length: u32, } impl Default for BarrierTextureRange { fn default() -> Self { Self { base_mip_level: 0, mip_level_length: 1, base_array_layer: 0, array_layer_length: 1 } } } impl From<&TextureViewInfo> for BarrierTextureRange { fn from(view_info: &TextureViewInfo) -> Self { Self { base_array_layer: view_info.base_array_layer, base_mip_level: view_info.base_mip_level, array_layer_length: view_info.array_layer_length, mip_level_length: view_info.mip_level_length, } } } pub enum Barrier<'a, B: Backend> { TextureBarrier { old_sync: BarrierSync, new_sync: BarrierSync, old_layout: TextureLayout, new_layout: TextureLayout, old_access: BarrierAccess, new_access: BarrierAccess, texture: &'a Arc<B::Texture>, range: BarrierTextureRange, }, BufferBarrier { old_sync: BarrierSync, new_sync: BarrierSync, old_access: BarrierAccess, new_access: BarrierAccess, buffer: &'a Arc<B::Buffer> }, GlobalBarrier { old_sync: BarrierSync, new_sync: BarrierSync, old_access: BarrierAccess, new_access: BarrierAccess, } } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug)] pub enum BindingFrequency { VeryFrequent = 0, Frequent = 1, Frame = 2, } pub trait InnerCommandBufferProvider<B: Backend> : Send + Sync { fn get_inner_command_buffer(&self) -> B::CommandBuffer; }
//! This mod contains shared portions of the kubernetes implementations. //! //! Here are a few pointers to the resources that were used as an inspiration: //! //! - https://github.com/kubernetes/client-go/blob/master/tools/clientcmd/api/types.go //! //! A part of the official Kubernetes client library (in Go) that contains //! the structure for KUBECONFIG files. Used for reference on naming things. //! //! - https://github.com/kubernetes/apimachinery/blob/master/pkg/watch/watch.go //! //! The reference design of the watchers composition and interfaces that's //! known to work. //! //! - https://github.com/kubernetes/client-go/blob/master/rest/config.go //! //! The reference implementation on preparing the in-cluster config. //! #![cfg(feature = "kubernetes")] #![warn(missing_docs)] pub mod api_watcher; pub mod client; pub mod debounce; pub mod hash_value; pub mod instrumenting_watcher; pub mod mock_watcher; pub mod multi_response_decoder; pub mod reflector; pub mod resource_version; pub mod state; pub mod stream; pub mod watch_request_builder; pub mod watcher; // Reexports for more elegant public API. pub use debounce::Debounce; pub use hash_value::HashValue; pub use multi_response_decoder::MultiResponseDecoder; pub use reflector::Reflector; pub use watch_request_builder::WatchRequestBuilder;
use nom::{ bytes::complete::tag, combinator::{map, opt}, sequence::{preceded, tuple}, Err, }; use super::error::{PineError, PineErrorKind, PineResult}; use super::input::{Input, StrRange}; use super::name::{varname, varname_ws, VarName}; use super::stat_expr::all_exp; use super::stat_expr_types::{Exp, FunctionCall, RVVarName}; use super::state::AstState; use super::utils::eat_sep; #[derive(Debug, PartialEq)] struct FuncCallArg<'a> { pub name: Option<VarName<'a>>, pub arg: Exp<'a>, pub range: StrRange, } impl<'a> FuncCallArg<'a> { pub fn new(name: Option<VarName<'a>>, arg: Exp<'a>, range: StrRange) -> FuncCallArg<'a> { FuncCallArg { name, arg, range } } } fn func_call_arg<'a>(input: Input<'a>, state: &AstState) -> PineResult<'a, FuncCallArg<'a>> { if let Ok((input, result)) = map( tuple(( |s| varname_ws(s, state), eat_sep(tag("=")), |s| all_exp(s, state), )), |s| FuncCallArg { name: Some(s.0), range: StrRange::new(s.0.range.start, s.2.range().end), arg: s.2, }, )(input) { Ok((input, result)) } else { let result = map( |s| all_exp(s, state), |s| FuncCallArg { name: None, range: s.range(), arg: s, }, )(input)?; Ok(result) } } pub fn func_call_args<'a>( input: Input<'a>, state: &AstState, ) -> PineResult<'a, (Vec<Exp<'a>>, Vec<(VarName<'a>, Exp<'a>)>)> { let (input, arg1) = opt(|s| func_call_arg(s, state))(input)?; if arg1.is_none() { return Ok((input, (vec![], vec![]))); } let arg1 = arg1.unwrap(); let mut is_dict_args = arg1.name.is_some(); let mut pos_args: Vec<Exp> = vec![]; let mut dict_args: Vec<(VarName, Exp)> = vec![]; if is_dict_args { dict_args = vec![(arg1.name.unwrap(), arg1.arg)] } else { pos_args = vec![arg1.arg]; }; let mut cur_input = input; while let Ok((next_input, arg)) = preceded(eat_sep(tag(",")), |s| func_call_arg(s, state))(cur_input) { match arg.name { Some(name) => { is_dict_args = true; dict_args.push((name, arg.arg)); } _ => { if is_dict_args { return Err(Err::Error(PineError::from_pine_kind( input, PineErrorKind::InvalidFuncCallArgs, ))); } pos_args.push(arg.arg); } } cur_input = next_input; } Ok((cur_input, (pos_args, dict_args))) } pub fn func_call<'a>(input: Input<'a>, state: &AstState) -> PineResult<'a, FunctionCall<'a>> { let (input, (method, (_, (pos_args, dict_args), paren_r))) = tuple(( |s| varname(s, state), tuple(( eat_sep(tag("(")), |s| func_call_args(s, state), eat_sep(tag(")")), )), ))(input)?; let start = method.range.start; Ok(( input, FunctionCall::new_no_ctxid( Exp::VarName(RVVarName::new(method)), pos_args, dict_args, StrRange::new(start, paren_r.end), ), )) } pub fn func_call_ws<'a>(input: Input<'a>, state: &AstState) -> PineResult<'a, FunctionCall<'a>> { eat_sep(|s| func_call(s, state))(input) } #[cfg(test)] mod tests { use super::super::input::Position; use super::super::stat_expr_types::*; use super::*; use crate::ast::string::*; use std::convert::TryInto; use std::fmt::Debug; fn check_res<'a, F, O>(s: &'a str, handler: F, res: O) where F: Fn(Input<'a>, &AstState) -> PineResult<'a, O>, O: Debug + PartialEq, { let test_input = Input::new_with_str(s); let input_len: u32 = test_input.len().try_into().unwrap(); assert_eq!( handler(test_input, &AstState::new()), Ok(( Input::new("", Position::new(0, input_len), Position::max()), res )) ); } #[test] fn func_call_test() { check_res( "a = true", func_call_arg, FuncCallArg { name: Some(VarName::new_with_start("a", Position::new(0, 0))), arg: Exp::Bool(BoolNode::new( true, StrRange::from_start("true", Position::new(0, 4)), )), range: StrRange::new(Position::new(0, 0), Position::new(0, 8)), }, ); check_res( "funa(arg1, arg2, a = true)", func_call_ws, FunctionCall::new_no_ctxid( Exp::VarName(RVVarName::new(VarName::new( "funa", StrRange::from_start("funa", Position::new(0, 0)), ))), vec![ Exp::VarName(RVVarName::new(VarName::new( "arg1", StrRange::from_start("arg1", Position::new(0, 5)), ))), Exp::VarName(RVVarName::new(VarName::new( "arg2", StrRange::from_start("arg2", Position::new(0, 11)), ))), ], vec![( VarName::new("a", StrRange::from_start("a", Position::new(0, 17))), Exp::Bool(BoolNode::new( true, StrRange::from_start("true", Position::new(0, 21)), )), )], StrRange::from_start("funa(arg1, arg2, a = true)", Position::new(0, 0)), ), ); check_res( "funa()", func_call_ws, FunctionCall::new_no_ctxid( Exp::VarName(RVVarName::new(VarName::new( "funa", StrRange::from_start("funa", Position::new(0, 0)), ))), vec![], vec![], StrRange::from_start("funa()", Position::new(0, 0)), ), ); check_res( r#"funa("s1", "s2")"#, func_call_ws, FunctionCall::new_no_ctxid( Exp::VarName(RVVarName::new(VarName::new( "funa", StrRange::from_start("funa", Position::new(0, 0)), ))), vec![ Exp::Str(StringNode::new( String::from("s1"), StrRange::from_start(r#"s1"#, Position::new(0, 6)), )), Exp::Str(StringNode::new( String::from("s2"), StrRange::from_start(r#"s2"#, Position::new(0, 12)), )), ], vec![], StrRange::from_start(r#"funa("s1", "s2")"#, Position::new(0, 0)), ), ); } #[test] fn func_call_recursive_test() { check_res( "funa(funb())", func_call_ws, FunctionCall::new_no_ctxid( Exp::VarName(RVVarName::new(VarName::new( "funa", StrRange::from_start("funa", Position::new(0, 0)), ))), vec![Exp::FuncCall(Box::new(FunctionCall::new_no_ctxid( Exp::VarName(RVVarName::new(VarName::new( "funb", StrRange::from_start("funb", Position::new(0, 5)), ))), vec![], vec![], StrRange::from_start("funb()", Position::new(0, 5)), )))], vec![], StrRange::from_start("funa(funb())", Position::new(0, 0)), ), ); } }
#![cfg(feature = "rblas")] extern crate rblas; #[macro_use] extern crate ndarray; use rblas::Gemm; use rblas::attribute::Transpose; use ndarray::{ OwnedArray, }; use ndarray::blas::AsBlas; #[test] fn strided_matrix() { // smoke test, a matrix multiplication of uneven size let (n, m) = (45, 33); let mut a = OwnedArray::linspace(0., ((n * m) - 1) as f32, n as usize * m as usize ).into_shape((n, m)).unwrap(); let mut b = ndarray::linalg::eye(m); let mut res = OwnedArray::zeros(a.dim()); Gemm::gemm(&1., Transpose::NoTrans, &a.blas(), Transpose::NoTrans, &b.blas(), &0., &mut res.blas()); assert_eq!(res, a); // matrix multiplication, strided let mut aprim = a.to_shared(); aprim.islice(s![0..12, 0..11]); println!("{:?}", aprim.shape()); println!("{:?}", aprim.strides()); let mut b = ndarray::linalg::eye(aprim.shape()[1]); let mut res = OwnedArray::zeros(aprim.dim()); Gemm::gemm(&1., Transpose::NoTrans, &aprim.blas(), Transpose::NoTrans, &b.blas(), &0., &mut res.blas()); println!("{:?}", aprim); println!("{:?}", b); println!("{:?}", res); println!("{:?}", &res - &aprim); assert_eq!(res, aprim); // Transposed matrix multiply let (np, mp) = aprim.dim(); let mut res = OwnedArray::zeros((mp, np)); let mut b = ndarray::linalg::eye(np); Gemm::gemm(&1., Transpose::Trans, &aprim.blas(), Transpose::NoTrans, &b.blas(), &0., &mut res.blas()); let mut at = aprim.clone(); at.swap_axes(0, 1); assert_eq!(at, res); // strided, needs copy let mut abis = a.to_shared(); abis.islice(s![0..12, ..;2]); println!("{:?}", abis.shape()); println!("{:?}", abis.strides()); let mut b = ndarray::linalg::eye(abis.shape()[1]); let mut res = OwnedArray::zeros(abis.dim()); Gemm::gemm(&1., Transpose::NoTrans, &abis.blas(), Transpose::NoTrans, &b.blas(), &0., &mut res.blas()); println!("{:?}", abis); println!("{:?}", b); println!("{:?}", res); println!("{:?}", &res - &abis); assert_eq!(res, abis); }
pub mod prelude { pub use super::difficulty_select::DifficultySelect; pub use super::ingame::Ingame; pub use super::level_load::LevelLoad; pub use super::paused::Paused; pub use super::startup::Startup; pub use super::win::Win; } pub mod state_prelude { pub const QUIT_UI_RON_PATH: &str = "ui/_quit.ron"; pub const BACK_UI_RON_PATH: &str = "ui/_back.ron"; pub const COMPLETION_TEXT_UI_RON_PATH: &str = "ui/_completion_text.ron"; pub use amethyst::ecs::{World, WorldExt}; pub use amethyst::ui::{UiEvent, UiEventType}; pub use amethyst::{State, StateData, StateEvent, Trans}; pub use deathframe::custom_game_data::CustomGameData; pub use deathframe::input_manager::InputManager; pub use deathframe::menu::prelude::*; pub use super::prelude::*; pub use crate::audio::prelude::*; pub use crate::components::prelude::*; pub use crate::helpers::*; pub use crate::input::prelude::*; pub use crate::level_manager::Level; pub use crate::resources::prelude::*; pub use crate::savefile_data::prelude::*; pub use crate::settings::prelude::*; pub use crate::systems::helpers::*; pub use crate::CustomData; } mod difficulty_select; mod ingame; mod level_load; mod paused; mod startup; mod win;
use actix_web::{Error,actix::Message}; use share::schema::users; use chrono::{Utc, NaiveDateTime}; use model::response::{Msgs, SigninMsgs, UserInfoMsgs}; use model::response::MyError; #[derive(Debug,Serialize,Deserialize,PartialEq,Identifiable,Queryable)] pub struct User { pub id: i32, pub email: String, pub username: String, pub password: String, pub created_at: NaiveDateTime, } #[derive(Debug,Serialize,Deserialize,Insertable)] #[table_name="users"] pub struct NewUser<'a> { pub email: &'a str, pub username: &'a str, pub password: &'a str, pub created_at: NaiveDateTime, } #[derive(Deserialize,Serialize, Debug)] pub struct SignupUser { pub username: String, pub email: String, pub password: String, pub confirm_password: String, } #[derive(Deserialize,Serialize, Debug)] pub struct SigninUser { pub username: String, pub password: String, } #[derive(Debug, Serialize, Deserialize)] pub struct UserInfo { pub user_id: String, } #[derive(Deserialize,Serialize, Debug)] pub struct UserUpdate { pub user_id: i32, pub newname: String, pub newmail: String, pub newpassword: String, pub confirm_newpassword: String, } #[derive(Debug, Serialize, Deserialize)] pub struct UserDelete { pub user_id: String, } impl Message for SignupUser { type Result = Result<Msgs, Error>; } impl Message for SigninUser { type Result = Result<SigninMsgs, Error>; } impl Message for UserInfo { type Result = Result<UserInfoMsgs, Error>; } impl Message for UserUpdate { type Result = Result<Msgs, Error>; } impl Message for UserDelete { type Result = Result<Msgs, MyError>; } impl User { pub fn new() -> User { User { id: 0, email: "".to_string(), username: "".to_string(), password: "".to_string(), created_at: Utc::now().naive_utc(), } } }
fn main(){ let a = "123".to_string(); // aというラベルに123というデータを与える → 1つのアドレス → スタックの1番目 let ra= &a; // スタック2番目。所有権を借りている。aは死んでいない。 println!("{}",a); // let a1 = ra * 10; // スタック3番目。ra*10というデータを新しく作成。a1というラベルを割り当てる println!("{}",a); }
use std::fs::File; use std::io::{Read, Write}; use serde::{Deserialize, Serialize}; use toml; const CONFIG_PATH: &str = "./config.toml"; #[derive(Serialize, Deserialize)] pub struct Config { pub binding: String, pub ssl_key_path: String, pub ssl_cert_path: String, pub secret: String } impl Config { fn generate_new_config() -> Config { println!(" === Initial Configuration ==="); let mut binding = String::new(); let mut ssl_key_path = String::new(); let mut ssl_cert_path = String::new(); let mut secret = String::new(); // Get HTTPS binding address { println!("HTTPS Server Binding Address (e.g. localhost:443): "); let buffer = std::io::stdin().read_line(&mut binding).unwrap(); binding.pop(); // Remove trailing \n } // Get SSL key path { println!("SSL Private Key Path (e.g. key.pem): "); let buffer = std::io::stdin().read_line(&mut ssl_key_path).unwrap(); ssl_key_path.pop(); // Remove trailing \n } // Get SSL certificate path { println!("SSL Certificate Path (e.g. cert.pem): "); let buffer = std::io::stdin().read_line(&mut ssl_cert_path).unwrap(); ssl_cert_path.pop(); // Remove trailing \n } // Get server secret { println!("Server Secret: "); let buffer = std::io::stdin().read_line(&mut secret).unwrap(); secret.pop(); // Remove trailing \n } Config { binding, ssl_key_path, ssl_cert_path, secret } } pub fn load() -> Config { match File::open(CONFIG_PATH) { Ok(mut f) => { let mut file_contents = String::new(); f.read_to_string(&mut file_contents).unwrap(); let c: Config = match toml::from_str(file_contents.as_str()) { Ok(c) => c, Err(_) => { println!("Error: config file is corrupt."); println!("Please delete '{}' and try again.", CONFIG_PATH); panic!("CORRUPT CONFIG FILE"); } }; c }, Err(_) => { // Generate new config let mut f = File::create(CONFIG_PATH).unwrap(); let c = Config::generate_new_config(); // Write to file f.write_all(toml::to_string(&c).unwrap().as_bytes()).unwrap(); c } } } }
use super::Collector; use collector::top_collector::TopCollector; use fastfield::FastFieldReader; use fastfield::FastValue; use schema::Field; use DocAddress; use DocId; use Result; use Score; use SegmentReader; /// The Top Field Collector keeps track of the K documents /// sorted by a fast field in the index /// /// The implementation is based on a `BinaryHeap`. /// The theorical complexity for collecting the top `K` out of `n` documents /// is `O(n log K)`. /// /// ```rust /// #[macro_use] /// extern crate tantivy; /// use tantivy::schema::{SchemaBuilder, TEXT, FAST}; /// use tantivy::{Index, Result, DocId}; /// use tantivy::collector::TopFieldCollector; /// use tantivy::query::QueryParser; /// /// # fn main() { example().unwrap(); } /// fn example() -> Result<()> { /// let mut schema_builder = SchemaBuilder::new(); /// let title = schema_builder.add_text_field("title", TEXT); /// let rating = schema_builder.add_u64_field("rating", FAST); /// let schema = schema_builder.build(); /// let index = Index::create_in_ram(schema); /// { /// let mut index_writer = index.writer_with_num_threads(1, 3_000_000)?; /// index_writer.add_document(doc!( /// title => "The Name of the Wind", /// rating => 92u64, /// )); /// index_writer.add_document(doc!( /// title => "The Diary of Muadib", /// rating => 97u64, /// )); /// index_writer.add_document(doc!( /// title => "A Dairy Cow", /// rating => 63u64, /// )); /// index_writer.add_document(doc!( /// title => "The Diary of a Young Girl", /// rating => 80u64, /// )); /// index_writer.commit().unwrap(); /// } /// /// index.load_searchers()?; /// let searcher = index.searcher(); /// /// { /// let mut top_collector = TopFieldCollector::with_limit(rating, 2); /// let query_parser = QueryParser::for_index(&index, vec![title]); /// let query = query_parser.parse_query("diary")?; /// searcher.search(&*query, &mut top_collector).unwrap(); /// /// let score_docs: Vec<(u64, DocId)> = top_collector /// .top_docs() /// .into_iter() /// .map(|(field, doc_address)| (field, doc_address.doc())) /// .collect(); /// /// assert_eq!(score_docs, vec![(97u64, 1), (80, 3)]); /// } /// /// Ok(()) /// } /// ``` pub struct TopFieldCollector<T: FastValue> { field: Field, collector: TopCollector<T>, fast_field: Option<FastFieldReader<T>>, } impl<T: FastValue + PartialOrd + Clone> TopFieldCollector<T> { /// Creates a top field collector, with a number of documents equal to "limit". /// /// The given field name must be a fast field, otherwise the collector have an error while /// collecting results. /// /// # Panics /// The method panics if limit is 0 pub fn with_limit(field: Field, limit: usize) -> Self { TopFieldCollector { field, collector: TopCollector::with_limit(limit), fast_field: None, } } /// Returns K best documents sorted the given field name in decreasing order. /// /// Calling this method triggers the sort. /// The result of the sort is not cached. pub fn docs(&self) -> Vec<DocAddress> { self.collector.docs() } /// Returns K best FieldDocuments sorted in decreasing order. /// /// Calling this method triggers the sort. /// The result of the sort is not cached. pub fn top_docs(&self) -> Vec<(T, DocAddress)> { self.collector.top_docs() } /// Return true iff at least K documents have gone through /// the collector. #[inline] pub fn at_capacity(&self) -> bool { self.collector.at_capacity() } } impl<T: FastValue + PartialOrd + Clone> Collector for TopFieldCollector<T> { fn set_segment(&mut self, segment_id: u32, segment: &SegmentReader) -> Result<()> { self.collector.set_segment_id(segment_id); self.fast_field = Some(segment.fast_field_reader(self.field)?); Ok(()) } fn collect(&mut self, doc: DocId, _score: Score) { let field_value = self .fast_field .as_ref() .expect("collect() was called before set_segment. This should never happen.") .get(doc); self.collector.collect(doc, field_value); } fn requires_scoring(&self) -> bool { false } } #[cfg(test)] mod tests { use super::*; use query::Query; use query::QueryParser; use schema::Field; use schema::IntOptions; use schema::Schema; use schema::{SchemaBuilder, FAST, TEXT}; use Index; use IndexWriter; use TantivyError; const TITLE: &str = "title"; const SIZE: &str = "size"; #[test] fn test_top_collector_not_at_capacity() { let mut schema_builder = SchemaBuilder::new(); let title = schema_builder.add_text_field(TITLE, TEXT); let size = schema_builder.add_u64_field(SIZE, FAST); let schema = schema_builder.build(); let (index, query) = index("beer", title, schema, |index_writer| { index_writer.add_document(doc!( title => "bottle of beer", size => 12u64, )); index_writer.add_document(doc!( title => "growler of beer", size => 64u64, )); index_writer.add_document(doc!( title => "pint of beer", size => 16u64, )); }); let searcher = index.searcher(); let mut top_collector = TopFieldCollector::with_limit(size, 4); searcher.search(&*query, &mut top_collector).unwrap(); assert!(!top_collector.at_capacity()); let score_docs: Vec<(u64, DocId)> = top_collector .top_docs() .into_iter() .map(|(field, doc_address)| (field, doc_address.doc())) .collect(); assert_eq!(score_docs, vec![(64, 1), (16, 2), (12, 0)]); } #[test] #[should_panic] fn test_field_does_not_exist() { let mut schema_builder = SchemaBuilder::new(); let title = schema_builder.add_text_field(TITLE, TEXT); let size = schema_builder.add_u64_field(SIZE, FAST); let schema = schema_builder.build(); let (index, _) = index("beer", title, schema, |index_writer| { index_writer.add_document(doc!( title => "bottle of beer", size => 12u64, )); }); let searcher = index.searcher(); let segment = searcher.segment_reader(0); let mut top_collector: TopFieldCollector<u64> = TopFieldCollector::with_limit(Field(2), 4); let _ = top_collector.set_segment(0, segment); } #[test] fn test_field_not_fast_field() { let mut schema_builder = SchemaBuilder::new(); let title = schema_builder.add_text_field(TITLE, TEXT); let size = schema_builder.add_u64_field(SIZE, IntOptions::default()); let schema = schema_builder.build(); let (index, _) = index("beer", title, schema, |index_writer| { index_writer.add_document(doc!( title => "bottle of beer", size => 12u64, )); }); let searcher = index.searcher(); let segment = searcher.segment_reader(0); let mut top_collector: TopFieldCollector<u64> = TopFieldCollector::with_limit(size, 4); assert_matches!( top_collector.set_segment(0, segment), Err(TantivyError::FastFieldError(_)) ); } #[test] #[should_panic] fn test_collect_before_set_segment() { let mut top_collector: TopFieldCollector<u64> = TopFieldCollector::with_limit(Field(0), 4); top_collector.collect(0, 0f32); } #[test] #[should_panic] fn test_top_0() { let _: TopFieldCollector<u64> = TopFieldCollector::with_limit(Field(0), 0); } fn index( query: &str, query_field: Field, schema: Schema, mut doc_adder: impl FnMut(&mut IndexWriter) -> (), ) -> (Index, Box<Query>) { let index = Index::create_in_ram(schema); let mut index_writer = index.writer_with_num_threads(1, 3_000_000).unwrap(); doc_adder(&mut index_writer); index_writer.commit().unwrap(); index.load_searchers().unwrap(); let query_parser = QueryParser::for_index(&index, vec![query_field]); let query = query_parser.parse_query(query).unwrap(); (index, query) } }
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use rabble::{self, Pid, CorrelationId, Envelope}; use msg::Msg; use super::utils::QuorumTracker; use vr::vr_msg::{self, VrMsg, RecoveryResponse, ClientOp}; use vr::VrCtx; use vr::vr_fsm::{Transition, VrState, State}; use vr::states::Backup; use api::Backend; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RecoveryPrimary { pub pid: Pid, pub view: u64, pub op: u64, pub commit_num: u64, pub state: Backend, pub log_start: u64, pub log_tail: Vec<ClientOp> } /// The recovery state of the VR Protocol where a replica is recovering data from a quorum of /// replicas state!(Recovery { ctx: VrCtx, nonce: u64, // Primary from the latest view we've heard from primary: Option<RecoveryPrimary>, responses: QuorumTracker<()> }); impl Transition for Recovery { fn handle(mut self, msg: VrMsg, from: Pid, _: CorrelationId, output: &mut Vec<Envelope<Msg>>) -> VrState { match msg { VrMsg::Tick => { if self.responses.is_expired() { let cid = CorrelationId::pid(self.ctx.pid.clone()); self.responses = QuorumTracker::new(self.ctx.quorum, self.ctx.idle_timeout_ms); self.primary = None; self.ctx.broadcast(self.recovery_msg(), cid, output); } self.into() }, VrMsg::RecoveryResponse(msg) => { self.update_recovery_state(from, msg, output); self.commit_recovery(output) }, _ => self.into() } } } impl Recovery { pub fn new(ctx: VrCtx, nonce: u64) -> Recovery { let quorum = ctx.quorum; Recovery { ctx: ctx, nonce: nonce, primary: None, // Expire immediately so recovery is started on the next tick responses: QuorumTracker::new(quorum, 0) } } fn has_quorum(&self) -> bool { let current_view = self.ctx.view; self.responses.has_super_quorum() && self.primary.as_ref().map_or(false, |p| p.view == current_view) } fn commit_recovery(mut self, output: &mut Vec<Envelope<Msg>>) -> VrState { if self.has_quorum() { let commit_num = { let primary = self.primary.take().unwrap(); self.ctx.op = primary.op; self.ctx.backend = primary.state; self.ctx.log_start = primary.log_start; self.ctx.log = primary.log_tail; // Don't attempt to commit operations that are already part of the backend state // They don't exist in the log anyway. self.ctx.commit_num = primary.log_start; primary.commit_num }; let mut backup = Backup::new(self.ctx); backup.set_primary(output); // This isn't in the VR protocol, but we send a PrepareOk here so that // the primary can update it's min_accept table in case it committed operations while // this replica was down. let cid = CorrelationId::pid(backup.ctx.pid.clone()); backup.send_prepare_ok(cid, output); return backup.commit(commit_num, output); } self.into() } fn update_recovery_state(&mut self, from: Pid, msg: RecoveryResponse, output: &mut Vec<Envelope<Msg>>) { if msg.nonce != self.nonce { return; } if msg.epoch < self.ctx.epoch { return; } // If we get a response from a replica in a later epoch, we learn the config from the // message and try again with the new group. If this replica isn't a member of the new group // it shuts down. if msg.epoch > self.ctx.epoch { let cid = CorrelationId::pid(self.ctx.pid.clone()); self.ctx.epoch = msg.epoch; self.ctx.view = msg.view; self.ctx.old_config = msg.old_config.unwrap(); self.ctx.new_config = msg.new_config.unwrap(); self.ctx.quorum = self.ctx.new_config.replicas.len() as u64 / 2 + 1; self.primary = None; self.responses = QuorumTracker::new(self.ctx.quorum, self.ctx.idle_timeout_ms); self.ctx.broadcast(self.recovery_msg(), cid, output); return; } if msg.view > self.ctx.view { self.ctx.view = msg.view; } let response_from_primary = msg.op.is_some(); if response_from_primary && msg.view == self.ctx.view { self.ctx.global_min_accept = msg.global_min_accept; self.primary = Some(RecoveryPrimary { pid: from.clone(), view: msg.view, op: msg.op.unwrap(), commit_num: msg.commit_num.unwrap(), state: msg.state.unwrap(), log_start: msg.log_start.unwrap(), log_tail: msg.log_tail.unwrap() }); } self.responses.insert(from, ()) } fn recovery_msg(&self) -> rabble::Msg<Msg> { vr_msg::Recovery { epoch: self.ctx.epoch, nonce: self.nonce, }.into() } }
/// The 6 bytes required to notify of being a V1 binary PROXY protocol /// connection. /// /// Excerpt from the specification: /// /// > This is the format specified in version 1 of the protocol. It consists in one /// > line of US-ASCII text matching exactly the following block, sent immediately /// > and at once upon the connection establishment and prepended before any data /// > flowing from the sender to the receiver : /// > /// > - a string identifying the protocol : "PROXY" ( \x50 \x52 \x4F \x58 \x59 ) /// > Seeing this string indicates that this is version 1 of the protocol. /// > /// > - exactly one space : " " ( \x20 ) pub const CONNECTION_PREFIX: [u8; 6] = [b'P', b'R', b'O', b'X', b'Y', b' ']; /// The CR-LF sequence (commonly denoted `\r\n`). pub const CRLF: [u8; 2] = [0x0D, 0x0A]; /// The CR-LF sequence (commonly denoted `\r\n`). pub const CRLF_STR: &str = "\x0D\x0A"; /// The IPv4 family denotation. pub const TCP4: [u8; 4] = [b'T', b'C', b'P', b'4']; /// The IPv4 family denotation. pub const TCP4_STR: &str = "TCP4"; /// The IPv6 family denotation. pub const TCP6: [u8; 4] = [b'T', b'C', b'P', b'6']; /// The IPv6 family denotation. pub const TCP6_STR: &str = "TCP6"; /// The UNKNOWN family denotation. pub const UNKNOWN: [u8; 7] = [b'U', b'N', b'K', b'N', b'O', b'W', b'N']; /// The UNKNOWN family denotation. pub const UNKNOWN_STR: &str = "UNKNOWN"; /// The smallest possible header. pub const UNKNOWN_PROXY_HEADER: [u8; 15] = [ b'P', b'R', b'O', b'X', b'Y', b' ', b'U', b'N', b'K', b'N', b'O', b'W', b'N', 0x0D, 0x0A, ]; #[allow(dead_code)] // Compiler bug - https://github.com/rust-lang/rust/issues/64362 #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] pub enum ProxyAddressFamily { Unknown, IPv4, IPv6, } impl ProxyAddressFamily { pub fn min_length(self) -> usize { match self { ProxyAddressFamily::Unknown => 0, ProxyAddressFamily::IPv4 => 7, ProxyAddressFamily::IPv6 => 3, } } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::STAT { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EPI_STAT_ACTIVER { bits: bool, } impl EPI_STAT_ACTIVER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_STAT_ACTIVEW<'a> { w: &'a mut W, } impl<'a> _EPI_STAT_ACTIVEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct EPI_STAT_NBRBUSYR { bits: bool, } impl EPI_STAT_NBRBUSYR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_STAT_NBRBUSYW<'a> { w: &'a mut W, } impl<'a> _EPI_STAT_NBRBUSYW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct EPI_STAT_WBUSYR { bits: bool, } impl EPI_STAT_WBUSYR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_STAT_WBUSYW<'a> { w: &'a mut W, } impl<'a> _EPI_STAT_WBUSYW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct EPI_STAT_INITSEQR { bits: bool, } impl EPI_STAT_INITSEQR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_STAT_INITSEQW<'a> { w: &'a mut W, } impl<'a> _EPI_STAT_INITSEQW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct EPI_STAT_XFEMPTYR { bits: bool, } impl EPI_STAT_XFEMPTYR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_STAT_XFEMPTYW<'a> { w: &'a mut W, } impl<'a> _EPI_STAT_XFEMPTYW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct EPI_STAT_XFFULLR { bits: bool, } impl EPI_STAT_XFFULLR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_STAT_XFFULLW<'a> { w: &'a mut W, } impl<'a> _EPI_STAT_XFFULLW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Register Active"] #[inline(always)] pub fn epi_stat_active(&self) -> EPI_STAT_ACTIVER { let bits = ((self.bits >> 0) & 1) != 0; EPI_STAT_ACTIVER { bits } } #[doc = "Bit 4 - Non-Blocking Read Busy"] #[inline(always)] pub fn epi_stat_nbrbusy(&self) -> EPI_STAT_NBRBUSYR { let bits = ((self.bits >> 4) & 1) != 0; EPI_STAT_NBRBUSYR { bits } } #[doc = "Bit 5 - Write Busy"] #[inline(always)] pub fn epi_stat_wbusy(&self) -> EPI_STAT_WBUSYR { let bits = ((self.bits >> 5) & 1) != 0; EPI_STAT_WBUSYR { bits } } #[doc = "Bit 6 - Initialization Sequence"] #[inline(always)] pub fn epi_stat_initseq(&self) -> EPI_STAT_INITSEQR { let bits = ((self.bits >> 6) & 1) != 0; EPI_STAT_INITSEQR { bits } } #[doc = "Bit 7 - External FIFO Empty"] #[inline(always)] pub fn epi_stat_xfempty(&self) -> EPI_STAT_XFEMPTYR { let bits = ((self.bits >> 7) & 1) != 0; EPI_STAT_XFEMPTYR { bits } } #[doc = "Bit 8 - External FIFO Full"] #[inline(always)] pub fn epi_stat_xffull(&self) -> EPI_STAT_XFFULLR { let bits = ((self.bits >> 8) & 1) != 0; EPI_STAT_XFFULLR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Register Active"] #[inline(always)] pub fn epi_stat_active(&mut self) -> _EPI_STAT_ACTIVEW { _EPI_STAT_ACTIVEW { w: self } } #[doc = "Bit 4 - Non-Blocking Read Busy"] #[inline(always)] pub fn epi_stat_nbrbusy(&mut self) -> _EPI_STAT_NBRBUSYW { _EPI_STAT_NBRBUSYW { w: self } } #[doc = "Bit 5 - Write Busy"] #[inline(always)] pub fn epi_stat_wbusy(&mut self) -> _EPI_STAT_WBUSYW { _EPI_STAT_WBUSYW { w: self } } #[doc = "Bit 6 - Initialization Sequence"] #[inline(always)] pub fn epi_stat_initseq(&mut self) -> _EPI_STAT_INITSEQW { _EPI_STAT_INITSEQW { w: self } } #[doc = "Bit 7 - External FIFO Empty"] #[inline(always)] pub fn epi_stat_xfempty(&mut self) -> _EPI_STAT_XFEMPTYW { _EPI_STAT_XFEMPTYW { w: self } } #[doc = "Bit 8 - External FIFO Full"] #[inline(always)] pub fn epi_stat_xffull(&mut self) -> _EPI_STAT_XFFULLW { _EPI_STAT_XFFULLW { w: self } } }
use fuzzcheck::DefaultMutator; #[derive(DefaultMutator, Clone)] pub enum X { A, } #[derive(DefaultMutator, Clone)] pub enum Y { A(), } #[derive(DefaultMutator, Clone)] pub enum Z { A {}, }
use std::{ future::Future, pin::Pin, task::{self, Poll}, }; use actix_rt::ArbiterHandle; use pin_project_lite::pin_project; use crate::{ actor::{Actor, AsyncContext, Supervised}, address::{channel, Addr}, context::Context, contextimpl::ContextFut, mailbox::DEFAULT_CAPACITY, }; pin_project! { /// Actor supervisor /// /// A Supervisor manages incoming messages for an actor. In case of actor failure, /// the supervisor creates a new execution context and restarts the actor's lifecycle. /// A Supervisor does not re-create their actor, it just calls the `restarting()` /// method. /// /// Supervisors have the same lifecycle as actors. If all addresses to /// a supervisor gets dropped and its actor does not execute anything, the supervisor /// terminates. /// /// Supervisors can not guarantee that their actors successfully processes incoming /// messages. If the actor fails during message processing, the message can not be /// recovered. The sender would receive an `Err(Cancelled)` error in this situation. /// /// # Examples /// /// ``` /// # use actix::prelude::*; /// #[derive(Message)] /// #[rtype(result = "()")] /// struct Die; /// /// struct MyActor; /// /// impl Actor for MyActor { /// type Context = Context<Self>; /// } /// /// // To use actor with supervisor actor has to implement `Supervised` trait /// impl actix::Supervised for MyActor { /// fn restarting(&mut self, ctx: &mut Context<MyActor>) { /// println!("restarting"); /// } /// } /// /// impl Handler<Die> for MyActor { /// type Result = (); /// /// fn handle(&mut self, _: Die, ctx: &mut Context<MyActor>) { /// ctx.stop(); /// # System::current().stop(); /// } /// } /// /// fn main() { /// let mut sys = System::new(); /// /// let addr = sys.block_on(async { actix::Supervisor::start(|_| MyActor) }); /// addr.do_send(Die); /// /// sys.run(); /// } /// ``` #[derive(Debug)] pub struct Supervisor<A> where A: Supervised, A: Actor<Context = Context<A>> { #[pin] fut: ContextFut<A, Context<A>>, } } impl<A> Supervisor<A> where A: Supervised + Actor<Context = Context<A>>, { /// Start new supervised actor in current tokio runtime. /// /// Type of returned address depends on variable type. For example to get /// `Addr<Syn, _>` of newly created actor, use explicitly `Addr<Syn, /// _>` type as type of a variable. /// /// ``` /// # use actix::prelude::*; /// struct MyActor; /// /// impl Actor for MyActor { /// type Context = Context<Self>; /// } /// /// # impl actix::Supervised for MyActor {} /// # fn main() { /// # System::new().block_on(async { /// // Get `Addr` of a MyActor actor /// let addr = actix::Supervisor::start(|_| MyActor); /// # System::current().stop(); /// # });} /// ``` pub fn start<F>(f: F) -> Addr<A> where F: FnOnce(&mut A::Context) -> A + 'static, A: Actor<Context = Context<A>>, { // create actor let mut ctx = Context::new(); let act = f(&mut ctx); let addr = ctx.address(); let fut = ctx.into_future(act); // create supervisor actix_rt::spawn(Self { fut }); addr } /// Start new supervised actor in arbiter's thread. pub fn start_in_arbiter<F>(sys: &ArbiterHandle, f: F) -> Addr<A> where A: Actor<Context = Context<A>>, F: FnOnce(&mut Context<A>) -> A + Send + 'static, { let (tx, rx) = channel::channel(DEFAULT_CAPACITY); sys.spawn_fn(move || { let mut ctx = Context::with_receiver(rx); let act = f(&mut ctx); let fut = ctx.into_future(act); actix_rt::spawn(Self { fut }); }); Addr::new(tx) } } #[doc(hidden)] impl<A> Future for Supervisor<A> where A: Supervised + Actor<Context = Context<A>>, { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { let mut this = self.project(); loop { match this.fut.as_mut().poll(cx) { Poll::Pending => return Poll::Pending, Poll::Ready(_) => { // stop if context's address is not connected if !this.fut.restart() { return Poll::Ready(()); } } } } } }
//! Simplenote API #![feature(proc_macro)] #[macro_use] extern crate log; extern crate url; extern crate reqwest; extern crate base64; #[macro_use] extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate error_chain; mod errors; mod api; mod model; pub use api::Simplenote; pub use model::Note; pub use errors::{Result, Error};
struct Percolation { size: i64, grid: Vec<Vec<(i64, i64)>>, sizes: Vec<Vec<i64>>, } impl Percolation { fn new(size: i64) -> Percolation { let mut result = Percolation { size, grid: Vec::new(), sizes: Vec::new(), }; for x in 0..size { result.grid.push(Vec::new()); result.sizes.push(Vec::new()); for y in 0..size { result.grid[x as usize].push((x, y)); result.sizes[x as usize].push(0); } } result.grid.push(Vec::new()); result.sizes.push(Vec::new()); // virtual top result.grid[size as usize].push((size, 0)); result.sizes[size as usize].push(0); // virtual bottom result.grid[size as usize].push((size, 1)); result.sizes[size as usize].push(0); for x in 0..size { result.union((size, 0), (x, 0)); result.union((size, 1), (x, size - 1)); } result } fn union(&mut self, start: (i64, i64), end: (i64, i64)) { let start_root = self.get_root(start); let end_root = self.get_root(end); if self.sizes[start_root.0 as usize][start_root.1 as usize] >= self.sizes[end_root.0 as usize][end_root.1 as usize] { self.grid[end_root.0 as usize][end_root.1 as usize] = start_root; self.sizes[start_root.0 as usize][start_root.1 as usize] += 1; } else { self.grid[start_root.0 as usize][start_root.1 as usize] = end_root; self.sizes[end_root.0 as usize][end_root.1 as usize] += 1 } } fn connected(&mut self, start: (i64, i64), end: (i64, i64)) -> bool { let start_root = self.get_root(start); let end_root = self.get_root(end); start_root.0 == end_root.0 && start_root.1 == end_root.1 } fn get_root(&mut self, item: (i64, i64)) -> (i64, i64) { let mut result = self.grid[item.0 as usize][item.1 as usize]; while result.0 != self.grid[result.0 as usize][result.1 as usize].0 && result.1 != self.grid[result.0 as usize][result.1 as usize].1 { self.grid[result.0 as usize][result.1 as usize] = self.grid [self.grid[result.0 as usize][result.1 as usize].0 as usize] [self.grid[result.0 as usize][result.1 as usize].1 as usize]; result = self.grid[result.0 as usize][result.1 as usize]; } result } fn percolates(&mut self) -> bool { self.connected((self.size, 0), (self.size, 1)) } } #[cfg(test)] mod test { use crate::percolation::Percolation; #[test] pub fn new() { let percolation = Percolation::new(5); assert_eq!(percolation.grid[0][0], (5, 0)); assert_eq!(percolation.grid[0][1], (0, 1)); assert_eq!(percolation.grid[0][2], (0, 2)); assert_eq!(percolation.grid[0][3], (0, 3)); assert_eq!(percolation.grid[0][4], (5, 1)); assert_eq!(percolation.grid[1][0], (5, 0)); assert_eq!(percolation.grid[1][1], (1, 1)); assert_eq!(percolation.grid[1][2], (1, 2)); assert_eq!(percolation.grid[1][3], (1, 3)); assert_eq!(percolation.grid[1][4], (5, 1)); assert_eq!(percolation.grid[2][0], (5, 0)); assert_eq!(percolation.grid[2][1], (2, 1)); assert_eq!(percolation.grid[2][2], (2, 2)); assert_eq!(percolation.grid[2][3], (2, 3)); assert_eq!(percolation.grid[2][4], (5, 1)); assert_eq!(percolation.grid[3][0], (5, 0)); assert_eq!(percolation.grid[3][1], (3, 1)); assert_eq!(percolation.grid[3][2], (3, 2)); assert_eq!(percolation.grid[3][3], (3, 3)); assert_eq!(percolation.grid[3][4], (5, 1)); assert_eq!(percolation.grid[4][0], (5, 0)); assert_eq!(percolation.grid[4][1], (4, 1)); assert_eq!(percolation.grid[4][2], (4, 2)); assert_eq!(percolation.grid[4][3], (4, 3)); assert_eq!(percolation.grid[4][4], (5, 1)); } #[test] fn percolates_column_1() { let mut percolation = Percolation::new(5); percolation.union((0, 0), (0, 1)); percolation.union((0, 1), (0, 2)); percolation.union((0, 2), (0, 3)); percolation.union((0, 3), (0, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_column_2() { let mut percolation = Percolation::new(5); percolation.union((1, 0), (1, 1)); percolation.union((1, 1), (1, 2)); percolation.union((1, 2), (1, 3)); percolation.union((1, 3), (1, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_column_3() { let mut percolation = Percolation::new(5); percolation.union((2, 0), (2, 1)); percolation.union((2, 1), (2, 2)); percolation.union((2, 2), (2, 3)); percolation.union((2, 3), (2, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_column_4() { let mut percolation = Percolation::new(5); percolation.union((3, 0), (3, 1)); percolation.union((3, 1), (3, 2)); percolation.union((3, 2), (3, 3)); percolation.union((3, 3), (3, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_column_5() { let mut percolation = Percolation::new(5); percolation.union((4, 0), (4, 1)); percolation.union((4, 1), (4, 2)); percolation.union((4, 2), (4, 3)); percolation.union((4, 3), (4, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_2() { let mut percolation = Percolation::new(5); percolation.union((0, 0), (0, 1)); percolation.union((0, 1), (1, 1)); percolation.union((1, 1), (1, 2)); percolation.union((1, 2), (1, 3)); percolation.union((1, 3), (1, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_3() { let mut percolation = Percolation::new(5); percolation.union((0, 0), (0, 1)); percolation.union((0, 1), (1, 1)); percolation.union((1, 1), (2, 1)); percolation.union((2, 1), (2, 2)); percolation.union((2, 2), (2, 3)); percolation.union((2, 3), (2, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_4() { let mut percolation = Percolation::new(5); percolation.union((0, 0), (0, 1)); percolation.union((0, 1), (1, 1)); percolation.union((1, 1), (2, 1)); percolation.union((2, 1), (3, 1)); percolation.union((3, 1), (3, 2)); percolation.union((3, 2), (3, 3)); percolation.union((3, 3), (3, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn percolates_5() { let mut percolation = Percolation::new(5); percolation.union((0, 0), (0, 1)); percolation.union((0, 1), (1, 1)); percolation.union((1, 1), (2, 1)); percolation.union((2, 1), (3, 1)); percolation.union((3, 1), (4, 1)); percolation.union((4, 1), (4, 2)); percolation.union((4, 2), (4, 3)); percolation.union((4, 3), (4, 4)); assert_eq!(percolation.percolates(), true); } #[test] fn does_not_percolate() { let mut percolation = Percolation::new(5); percolation.union((0, 0), (0, 1)); percolation.union((0, 3), (0, 4)); percolation.union((1, 0), (1, 1)); percolation.union((1, 3), (1, 4)); percolation.union((2, 0), (2, 1)); percolation.union((2, 3), (2, 4)); percolation.union((3, 0), (3, 1)); percolation.union((3, 3), (3, 4)); percolation.union((4, 0), (4, 1)); percolation.union((4, 3), (4, 4)); assert_eq!(percolation.percolates(), false); } }
// Copyright (c) Calibra Research // SPDX-License-Identifier: Apache-2.0 use super::*; #[test] fn test_block_signing() { let b = Record::make_block( Command { proposer: Author(1), index: 2, }, NodeTime(2), QuorumCertificateHash(47), Round(3), Author(2), ); assert!(b.signature().check(b.digest(), b.author()).is_ok()); assert!(b.signature().check(b.digest(), Author(1)).is_err()); let b2 = Record::make_block( Command { proposer: Author(3), index: 2, }, NodeTime(2), QuorumCertificateHash(47), Round(3), Author(2), ); assert!(b.signature().check(b2.digest(), b.author()).is_err()); }
//! Various helpers for Actix applications to use during testing. use std::sync::mpsc; use std::{net, thread}; use actix_rt::{Runtime, System}; use actix_server::{Server, StreamServiceFactory}; use futures::Future; use net2::TcpBuilder; use tokio_reactor::Handle; use tokio_tcp::TcpStream; /// The `TestServer` type. /// /// `TestServer` is very simple test server that simplify process of writing /// integration tests for actix-net applications. /// /// # Examples /// /// ```rust /// use actix_service::{fn_service, IntoNewService}; /// use actix_test_server::TestServer; /// /// fn main() { /// let srv = TestServer::with(|| fn_service( /// |sock| { /// println!("New connection: {:?}", sock); /// Ok::<_, ()>(()) /// } /// )); /// /// println!("SOCKET: {:?}", srv.connect()); /// } /// ``` pub struct TestServer; /// Test server runstime pub struct TestServerRuntime { addr: net::SocketAddr, host: String, port: u16, rt: Runtime, } impl TestServer { /// Start new test server with application factory pub fn with<F: StreamServiceFactory>(factory: F) -> TestServerRuntime { let (tx, rx) = mpsc::channel(); // run server in separate thread thread::spawn(move || { let sys = System::new("actix-test-server"); let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap(); let local_addr = tcp.local_addr().unwrap(); Server::build() .listen("test", tcp, factory)? .workers(1) .disable_signals() .start(); tx.send((System::current(), local_addr)).unwrap(); sys.run() }); let (system, addr) = rx.recv().unwrap(); System::set_current(system); let rt = Runtime::new().unwrap(); let host = format!("{}", addr.ip()); let port = addr.port(); TestServerRuntime { addr, rt, host, port, } } /// Get firat available unused local address pub fn unused_addr() -> net::SocketAddr { let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap(); let socket = TcpBuilder::new_v4().unwrap(); socket.bind(&addr).unwrap(); socket.reuse_address(true).unwrap(); let tcp = socket.to_tcp_listener().unwrap(); tcp.local_addr().unwrap() } } impl TestServerRuntime { /// Execute future on current runtime pub fn block_on<F, I, E>(&mut self, fut: F) -> Result<I, E> where F: Future<Item = I, Error = E>, { self.rt.block_on(fut) } /// Spawn future to the current runtime pub fn spawn<F>(&mut self, fut: F) where F: Future<Item = (), Error = ()> + 'static, { self.rt.spawn(fut); } /// Test server host pub fn host(&self) -> &str { &self.host } /// Test server port pub fn port(&self) -> u16 { self.port } /// Get test server address pub fn addr(&self) -> net::SocketAddr { self.addr } /// Stop http server fn stop(&mut self) { System::current().stop(); } /// Connect to server, return tokio TcpStream pub fn connect(&self) -> std::io::Result<TcpStream> { TcpStream::from_std(net::TcpStream::connect(self.addr)?, &Handle::default()) } } impl Drop for TestServerRuntime { fn drop(&mut self) { self.stop() } }
use crate::Counter; use num_traits::{One, Zero}; use std::hash::Hash; use std::ops::AddAssign; impl<T, N> Extend<T> for Counter<T, N> where T: Hash + Eq, N: AddAssign + Zero + One, { /// Extend a `Counter` with an iterator of items. /// /// ```rust /// # use counter::Counter; /// # use std::collections::HashMap; /// let mut counter = "abbccc".chars().collect::<Counter<_>>(); /// counter.extend("bccddd".chars()); /// let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter().cloned().collect::<HashMap<_, _>>(); /// assert_eq!(counter.into_map(), expect); /// ``` fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { self.update(iter); } } impl<T, N> Extend<(T, N)> for Counter<T, N> where T: Hash + Eq, N: AddAssign + Zero, { /// Extend a counter with `(item, count)` tuples. /// /// The counts of duplicate items are summed. /// ```rust /// # use counter::Counter; /// # use std::collections::HashMap; /// let mut counter = "abbccc".chars().collect::<Counter<_>>(); /// counter.extend([('a', 1), ('b', 2), ('c', 3), ('a', 4)].iter().cloned()); /// let expect = [('a', 6), ('b', 4), ('c', 6)].iter() /// .cloned().collect::<HashMap<_, _>>(); /// assert_eq!(counter.into_map(), expect); /// ``` fn extend<I: IntoIterator<Item = (T, N)>>(&mut self, iter: I) { for (item, item_count) in iter { let entry = self.map.entry(item).or_insert_with(N::zero); *entry += item_count; } } } impl<'a, T: 'a, N: 'a> Extend<(&'a T, &'a N)> for Counter<T, N> where T: Hash + Eq + Clone, N: AddAssign + Zero + Clone, { /// Extend a counter with `(item, count)` tuples. /// /// You can extend a `Counter` with another `Counter`: /// ```rust /// # use counter::Counter; /// # use std::collections::HashMap; /// let mut counter = "abbccc".chars().collect::<Counter<_>>(); /// let another = "bccddd".chars().collect::<Counter<_>>(); /// counter.extend(&another); /// let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter() /// .cloned().collect::<HashMap<_, _>>(); /// assert_eq!(counter.into_map(), expect); /// ``` fn extend<I: IntoIterator<Item = (&'a T, &'a N)>>(&mut self, iter: I) { for (item, item_count) in iter { let entry = self.map.entry(item.clone()).or_insert_with(N::zero); *entry += item_count.clone(); } } }
#[doc = "Reader of register CR2"] pub type R = crate::R<u32, super::CR2>; #[doc = "Writer for register CR2"] pub type W = crate::W<u32, super::CR2>; #[doc = "Register CR2 `reset()`'s with value 0"] impl crate::ResetValue for super::CR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Temperature sensor and VREFINT enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TSVREFE_A { #[doc = "0: Temperature sensor and V_REFINT channel disabled"] DISABLED = 0, #[doc = "1: Temperature sensor and V_REFINT channel enabled"] ENABLED = 1, } impl From<TSVREFE_A> for bool { #[inline(always)] fn from(variant: TSVREFE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TSVREFE`"] pub type TSVREFE_R = crate::R<bool, TSVREFE_A>; impl TSVREFE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TSVREFE_A { match self.bits { false => TSVREFE_A::DISABLED, true => TSVREFE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TSVREFE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TSVREFE_A::ENABLED } } #[doc = "Write proxy for field `TSVREFE`"] pub struct TSVREFE_W<'a> { w: &'a mut W, } impl<'a> TSVREFE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TSVREFE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Temperature sensor and V_REFINT channel disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TSVREFE_A::DISABLED) } #[doc = "Temperature sensor and V_REFINT channel enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TSVREFE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Start conversion of regular channels\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWSTART_A { #[doc = "0: Reset state"] STARTED = 0, #[doc = "1: Starting conversion of regular channels"] NOTSTARTED = 1, } impl From<SWSTART_A> for bool { #[inline(always)] fn from(variant: SWSTART_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SWSTART`"] pub type SWSTART_R = crate::R<bool, SWSTART_A>; impl SWSTART_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SWSTART_A { match self.bits { false => SWSTART_A::STARTED, true => SWSTART_A::NOTSTARTED, } } #[doc = "Checks if the value of the field is `STARTED`"] #[inline(always)] pub fn is_started(&self) -> bool { *self == SWSTART_A::STARTED } #[doc = "Checks if the value of the field is `NOTSTARTED`"] #[inline(always)] pub fn is_not_started(&self) -> bool { *self == SWSTART_A::NOTSTARTED } } #[doc = "Start conversion of regular channels\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWSTART_AW { #[doc = "1: Start conversion of regular channels"] START = 1, } impl From<SWSTART_AW> for bool { #[inline(always)] fn from(variant: SWSTART_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `SWSTART`"] pub struct SWSTART_W<'a> { w: &'a mut W, } impl<'a> SWSTART_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SWSTART_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Start conversion of regular channels"] #[inline(always)] pub fn start(self) -> &'a mut W { self.variant(SWSTART_AW::START) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Start conversion of injected channels\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum JSWSTART_A { #[doc = "0: Reset state"] STARTED = 0, #[doc = "1: Starting conversion of injected channels"] NOTSTARTED = 1, } impl From<JSWSTART_A> for bool { #[inline(always)] fn from(variant: JSWSTART_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `JSWSTART`"] pub type JSWSTART_R = crate::R<bool, JSWSTART_A>; impl JSWSTART_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> JSWSTART_A { match self.bits { false => JSWSTART_A::STARTED, true => JSWSTART_A::NOTSTARTED, } } #[doc = "Checks if the value of the field is `STARTED`"] #[inline(always)] pub fn is_started(&self) -> bool { *self == JSWSTART_A::STARTED } #[doc = "Checks if the value of the field is `NOTSTARTED`"] #[inline(always)] pub fn is_not_started(&self) -> bool { *self == JSWSTART_A::NOTSTARTED } } #[doc = "Start conversion of injected channels\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum JSWSTART_AW { #[doc = "1: Start conversion of injected channels"] START = 1, } impl From<JSWSTART_AW> for bool { #[inline(always)] fn from(variant: JSWSTART_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `JSWSTART`"] pub struct JSWSTART_W<'a> { w: &'a mut W, } impl<'a> JSWSTART_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: JSWSTART_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Start conversion of injected channels"] #[inline(always)] pub fn start(self) -> &'a mut W { self.variant(JSWSTART_AW::START) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "External trigger conversion mode for regular channels\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EXTTRIG_A { #[doc = "0: Conversion on external event disabled"] DISABLED = 0, #[doc = "1: Conversion on external event enabled"] ENABLED = 1, } impl From<EXTTRIG_A> for bool { #[inline(always)] fn from(variant: EXTTRIG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EXTTRIG`"] pub type EXTTRIG_R = crate::R<bool, EXTTRIG_A>; impl EXTTRIG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EXTTRIG_A { match self.bits { false => EXTTRIG_A::DISABLED, true => EXTTRIG_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == EXTTRIG_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == EXTTRIG_A::ENABLED } } #[doc = "Write proxy for field `EXTTRIG`"] pub struct EXTTRIG_W<'a> { w: &'a mut W, } impl<'a> EXTTRIG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTTRIG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Conversion on external event disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EXTTRIG_A::DISABLED) } #[doc = "Conversion on external event enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(EXTTRIG_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "External event select for regular group\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EXTSEL_A { #[doc = "0: Timer 3 CC1 event"] TIM3CC1 = 0, #[doc = "1: Timer 2 CC3 event"] TIM2CC3 = 1, #[doc = "2: Timer 1 CC3 event"] TIM1CC3 = 2, #[doc = "3: Timer 8 CC1 event"] TIM8CC1 = 3, #[doc = "4: Timer 8 TRGO event"] TIM8TRGO = 4, #[doc = "5: Timer 5 CC1 event"] TIM5CC1 = 5, #[doc = "6: Timer 5 CC3 event"] TIM5CC3 = 6, #[doc = "7: SWSTART"] SWSTART = 7, } impl From<EXTSEL_A> for u8 { #[inline(always)] fn from(variant: EXTSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `EXTSEL`"] pub type EXTSEL_R = crate::R<u8, EXTSEL_A>; impl EXTSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EXTSEL_A { match self.bits { 0 => EXTSEL_A::TIM3CC1, 1 => EXTSEL_A::TIM2CC3, 2 => EXTSEL_A::TIM1CC3, 3 => EXTSEL_A::TIM8CC1, 4 => EXTSEL_A::TIM8TRGO, 5 => EXTSEL_A::TIM5CC1, 6 => EXTSEL_A::TIM5CC3, 7 => EXTSEL_A::SWSTART, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `TIM3CC1`"] #[inline(always)] pub fn is_tim3cc1(&self) -> bool { *self == EXTSEL_A::TIM3CC1 } #[doc = "Checks if the value of the field is `TIM2CC3`"] #[inline(always)] pub fn is_tim2cc3(&self) -> bool { *self == EXTSEL_A::TIM2CC3 } #[doc = "Checks if the value of the field is `TIM1CC3`"] #[inline(always)] pub fn is_tim1cc3(&self) -> bool { *self == EXTSEL_A::TIM1CC3 } #[doc = "Checks if the value of the field is `TIM8CC1`"] #[inline(always)] pub fn is_tim8cc1(&self) -> bool { *self == EXTSEL_A::TIM8CC1 } #[doc = "Checks if the value of the field is `TIM8TRGO`"] #[inline(always)] pub fn is_tim8trgo(&self) -> bool { *self == EXTSEL_A::TIM8TRGO } #[doc = "Checks if the value of the field is `TIM5CC1`"] #[inline(always)] pub fn is_tim5cc1(&self) -> bool { *self == EXTSEL_A::TIM5CC1 } #[doc = "Checks if the value of the field is `TIM5CC3`"] #[inline(always)] pub fn is_tim5cc3(&self) -> bool { *self == EXTSEL_A::TIM5CC3 } #[doc = "Checks if the value of the field is `SWSTART`"] #[inline(always)] pub fn is_swstart(&self) -> bool { *self == EXTSEL_A::SWSTART } } #[doc = "Write proxy for field `EXTSEL`"] pub struct EXTSEL_W<'a> { w: &'a mut W, } impl<'a> EXTSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Timer 3 CC1 event"] #[inline(always)] pub fn tim3cc1(self) -> &'a mut W { self.variant(EXTSEL_A::TIM3CC1) } #[doc = "Timer 2 CC3 event"] #[inline(always)] pub fn tim2cc3(self) -> &'a mut W { self.variant(EXTSEL_A::TIM2CC3) } #[doc = "Timer 1 CC3 event"] #[inline(always)] pub fn tim1cc3(self) -> &'a mut W { self.variant(EXTSEL_A::TIM1CC3) } #[doc = "Timer 8 CC1 event"] #[inline(always)] pub fn tim8cc1(self) -> &'a mut W { self.variant(EXTSEL_A::TIM8CC1) } #[doc = "Timer 8 TRGO event"] #[inline(always)] pub fn tim8trgo(self) -> &'a mut W { self.variant(EXTSEL_A::TIM8TRGO) } #[doc = "Timer 5 CC1 event"] #[inline(always)] pub fn tim5cc1(self) -> &'a mut W { self.variant(EXTSEL_A::TIM5CC1) } #[doc = "Timer 5 CC3 event"] #[inline(always)] pub fn tim5cc3(self) -> &'a mut W { self.variant(EXTSEL_A::TIM5CC3) } #[doc = "SWSTART"] #[inline(always)] pub fn swstart(self) -> &'a mut W { self.variant(EXTSEL_A::SWSTART) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 17)) | (((value as u32) & 0x07) << 17); self.w } } #[doc = "External trigger conversion mode for injected channels\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum JEXTTRIG_A { #[doc = "0: Conversion on external event disabled"] DISABLED = 0, #[doc = "1: Conversion on external event enabled"] ENABLED = 1, } impl From<JEXTTRIG_A> for bool { #[inline(always)] fn from(variant: JEXTTRIG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `JEXTTRIG`"] pub type JEXTTRIG_R = crate::R<bool, JEXTTRIG_A>; impl JEXTTRIG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> JEXTTRIG_A { match self.bits { false => JEXTTRIG_A::DISABLED, true => JEXTTRIG_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == JEXTTRIG_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == JEXTTRIG_A::ENABLED } } #[doc = "Write proxy for field `JEXTTRIG`"] pub struct JEXTTRIG_W<'a> { w: &'a mut W, } impl<'a> JEXTTRIG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: JEXTTRIG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Conversion on external event disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(JEXTTRIG_A::DISABLED) } #[doc = "Conversion on external event enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(JEXTTRIG_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "External event select for injected group\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum JEXTSEL_A { #[doc = "0: Timer 1 TRGO event"] TIM1TRGO = 0, #[doc = "1: Timer 1 CC4 event"] TIM1CC4 = 1, #[doc = "2: Timer 4 CC3 event"] TIM4CC3 = 2, #[doc = "3: Timer 8 CC2 event"] TIM8CC2 = 3, #[doc = "4: Timer 8 CC4 event"] TIM8CC4 = 4, #[doc = "5: Timer 5 TRGO event"] TIM5TRGO = 5, #[doc = "6: Timer 5 CC4 event"] TIM5CC4 = 6, #[doc = "7: JSWSTART"] JSWSTART = 7, } impl From<JEXTSEL_A> for u8 { #[inline(always)] fn from(variant: JEXTSEL_A) -> Self { variant as _ } } #[doc = "Reader of field `JEXTSEL`"] pub type JEXTSEL_R = crate::R<u8, JEXTSEL_A>; impl JEXTSEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> JEXTSEL_A { match self.bits { 0 => JEXTSEL_A::TIM1TRGO, 1 => JEXTSEL_A::TIM1CC4, 2 => JEXTSEL_A::TIM4CC3, 3 => JEXTSEL_A::TIM8CC2, 4 => JEXTSEL_A::TIM8CC4, 5 => JEXTSEL_A::TIM5TRGO, 6 => JEXTSEL_A::TIM5CC4, 7 => JEXTSEL_A::JSWSTART, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `TIM1TRGO`"] #[inline(always)] pub fn is_tim1trgo(&self) -> bool { *self == JEXTSEL_A::TIM1TRGO } #[doc = "Checks if the value of the field is `TIM1CC4`"] #[inline(always)] pub fn is_tim1cc4(&self) -> bool { *self == JEXTSEL_A::TIM1CC4 } #[doc = "Checks if the value of the field is `TIM4CC3`"] #[inline(always)] pub fn is_tim4cc3(&self) -> bool { *self == JEXTSEL_A::TIM4CC3 } #[doc = "Checks if the value of the field is `TIM8CC2`"] #[inline(always)] pub fn is_tim8cc2(&self) -> bool { *self == JEXTSEL_A::TIM8CC2 } #[doc = "Checks if the value of the field is `TIM8CC4`"] #[inline(always)] pub fn is_tim8cc4(&self) -> bool { *self == JEXTSEL_A::TIM8CC4 } #[doc = "Checks if the value of the field is `TIM5TRGO`"] #[inline(always)] pub fn is_tim5trgo(&self) -> bool { *self == JEXTSEL_A::TIM5TRGO } #[doc = "Checks if the value of the field is `TIM5CC4`"] #[inline(always)] pub fn is_tim5cc4(&self) -> bool { *self == JEXTSEL_A::TIM5CC4 } #[doc = "Checks if the value of the field is `JSWSTART`"] #[inline(always)] pub fn is_jswstart(&self) -> bool { *self == JEXTSEL_A::JSWSTART } } #[doc = "Write proxy for field `JEXTSEL`"] pub struct JEXTSEL_W<'a> { w: &'a mut W, } impl<'a> JEXTSEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: JEXTSEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Timer 1 TRGO event"] #[inline(always)] pub fn tim1trgo(self) -> &'a mut W { self.variant(JEXTSEL_A::TIM1TRGO) } #[doc = "Timer 1 CC4 event"] #[inline(always)] pub fn tim1cc4(self) -> &'a mut W { self.variant(JEXTSEL_A::TIM1CC4) } #[doc = "Timer 4 CC3 event"] #[inline(always)] pub fn tim4cc3(self) -> &'a mut W { self.variant(JEXTSEL_A::TIM4CC3) } #[doc = "Timer 8 CC2 event"] #[inline(always)] pub fn tim8cc2(self) -> &'a mut W { self.variant(JEXTSEL_A::TIM8CC2) } #[doc = "Timer 8 CC4 event"] #[inline(always)] pub fn tim8cc4(self) -> &'a mut W { self.variant(JEXTSEL_A::TIM8CC4) } #[doc = "Timer 5 TRGO event"] #[inline(always)] pub fn tim5trgo(self) -> &'a mut W { self.variant(JEXTSEL_A::TIM5TRGO) } #[doc = "Timer 5 CC4 event"] #[inline(always)] pub fn tim5cc4(self) -> &'a mut W { self.variant(JEXTSEL_A::TIM5CC4) } #[doc = "JSWSTART"] #[inline(always)] pub fn jswstart(self) -> &'a mut W { self.variant(JEXTSEL_A::JSWSTART) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12); self.w } } #[doc = "Data alignment\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ALIGN_A { #[doc = "0: Right Alignment"] RIGHT = 0, #[doc = "1: Left Alignment"] LEFT = 1, } impl From<ALIGN_A> for bool { #[inline(always)] fn from(variant: ALIGN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ALIGN`"] pub type ALIGN_R = crate::R<bool, ALIGN_A>; impl ALIGN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ALIGN_A { match self.bits { false => ALIGN_A::RIGHT, true => ALIGN_A::LEFT, } } #[doc = "Checks if the value of the field is `RIGHT`"] #[inline(always)] pub fn is_right(&self) -> bool { *self == ALIGN_A::RIGHT } #[doc = "Checks if the value of the field is `LEFT`"] #[inline(always)] pub fn is_left(&self) -> bool { *self == ALIGN_A::LEFT } } #[doc = "Write proxy for field `ALIGN`"] pub struct ALIGN_W<'a> { w: &'a mut W, } impl<'a> ALIGN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ALIGN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Right Alignment"] #[inline(always)] pub fn right(self) -> &'a mut W { self.variant(ALIGN_A::RIGHT) } #[doc = "Left Alignment"] #[inline(always)] pub fn left(self) -> &'a mut W { self.variant(ALIGN_A::LEFT) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Direct memory access mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DMA_A { #[doc = "0: DMA mode disabled"] DISABLED = 0, #[doc = "1: DMA mode enabled"] ENABLED = 1, } impl From<DMA_A> for bool { #[inline(always)] fn from(variant: DMA_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DMA`"] pub type DMA_R = crate::R<bool, DMA_A>; impl DMA_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DMA_A { match self.bits { false => DMA_A::DISABLED, true => DMA_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == DMA_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == DMA_A::ENABLED } } #[doc = "Write proxy for field `DMA`"] pub struct DMA_W<'a> { w: &'a mut W, } impl<'a> DMA_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DMA_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "DMA mode disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA_A::DISABLED) } #[doc = "DMA mode enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reset calibration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RSTCAL_A { #[doc = "0: Calibration register initialized"] INITIALIZED = 0, #[doc = "1: Initializing calibration register"] NOTINITIALIZED = 1, } impl From<RSTCAL_A> for bool { #[inline(always)] fn from(variant: RSTCAL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RSTCAL`"] pub type RSTCAL_R = crate::R<bool, RSTCAL_A>; impl RSTCAL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RSTCAL_A { match self.bits { false => RSTCAL_A::INITIALIZED, true => RSTCAL_A::NOTINITIALIZED, } } #[doc = "Checks if the value of the field is `INITIALIZED`"] #[inline(always)] pub fn is_initialized(&self) -> bool { *self == RSTCAL_A::INITIALIZED } #[doc = "Checks if the value of the field is `NOTINITIALIZED`"] #[inline(always)] pub fn is_not_initialized(&self) -> bool { *self == RSTCAL_A::NOTINITIALIZED } } #[doc = "Reset calibration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RSTCAL_AW { #[doc = "1: Initialize calibration register"] INITIALIZE = 1, } impl From<RSTCAL_AW> for bool { #[inline(always)] fn from(variant: RSTCAL_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `RSTCAL`"] pub struct RSTCAL_W<'a> { w: &'a mut W, } impl<'a> RSTCAL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RSTCAL_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Initialize calibration register"] #[inline(always)] pub fn initialize(self) -> &'a mut W { self.variant(RSTCAL_AW::INITIALIZE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "A/D calibration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CAL_A { #[doc = "0: Calibration completed"] COMPLETE = 0, #[doc = "1: Calibrating"] NOTCOMPLETE = 1, } impl From<CAL_A> for bool { #[inline(always)] fn from(variant: CAL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CAL`"] pub type CAL_R = crate::R<bool, CAL_A>; impl CAL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CAL_A { match self.bits { false => CAL_A::COMPLETE, true => CAL_A::NOTCOMPLETE, } } #[doc = "Checks if the value of the field is `COMPLETE`"] #[inline(always)] pub fn is_complete(&self) -> bool { *self == CAL_A::COMPLETE } #[doc = "Checks if the value of the field is `NOTCOMPLETE`"] #[inline(always)] pub fn is_not_complete(&self) -> bool { *self == CAL_A::NOTCOMPLETE } } #[doc = "A/D calibration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CAL_AW { #[doc = "1: Enable calibration"] START = 1, } impl From<CAL_AW> for bool { #[inline(always)] fn from(variant: CAL_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `CAL`"] pub struct CAL_W<'a> { w: &'a mut W, } impl<'a> CAL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CAL_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable calibration"] #[inline(always)] pub fn start(self) -> &'a mut W { self.variant(CAL_AW::START) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Continuous conversion\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CONT_A { #[doc = "0: Single conversion mode"] SINGLE = 0, #[doc = "1: Continuous conversion mode"] CONTINUOUS = 1, } impl From<CONT_A> for bool { #[inline(always)] fn from(variant: CONT_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CONT`"] pub type CONT_R = crate::R<bool, CONT_A>; impl CONT_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CONT_A { match self.bits { false => CONT_A::SINGLE, true => CONT_A::CONTINUOUS, } } #[doc = "Checks if the value of the field is `SINGLE`"] #[inline(always)] pub fn is_single(&self) -> bool { *self == CONT_A::SINGLE } #[doc = "Checks if the value of the field is `CONTINUOUS`"] #[inline(always)] pub fn is_continuous(&self) -> bool { *self == CONT_A::CONTINUOUS } } #[doc = "Write proxy for field `CONT`"] pub struct CONT_W<'a> { w: &'a mut W, } impl<'a> CONT_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CONT_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Single conversion mode"] #[inline(always)] pub fn single(self) -> &'a mut W { self.variant(CONT_A::SINGLE) } #[doc = "Continuous conversion mode"] #[inline(always)] pub fn continuous(self) -> &'a mut W { self.variant(CONT_A::CONTINUOUS) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "A/D converter ON / OFF\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADON_A { #[doc = "0: Disable ADC conversion/calibration and go to power down mode"] DISABLED = 0, #[doc = "1: Enable ADC and to start conversion"] ENABLED = 1, } impl From<ADON_A> for bool { #[inline(always)] fn from(variant: ADON_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADON`"] pub type ADON_R = crate::R<bool, ADON_A>; impl ADON_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ADON_A { match self.bits { false => ADON_A::DISABLED, true => ADON_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == ADON_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == ADON_A::ENABLED } } #[doc = "Write proxy for field `ADON`"] pub struct ADON_W<'a> { w: &'a mut W, } impl<'a> ADON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Disable ADC conversion/calibration and go to power down mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(ADON_A::DISABLED) } #[doc = "Enable ADC and to start conversion"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(ADON_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 23 - Temperature sensor and VREFINT enable"] #[inline(always)] pub fn tsvrefe(&self) -> TSVREFE_R { TSVREFE_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 22 - Start conversion of regular channels"] #[inline(always)] pub fn swstart(&self) -> SWSTART_R { SWSTART_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 21 - Start conversion of injected channels"] #[inline(always)] pub fn jswstart(&self) -> JSWSTART_R { JSWSTART_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - External trigger conversion mode for regular channels"] #[inline(always)] pub fn exttrig(&self) -> EXTTRIG_R { EXTTRIG_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bits 17:19 - External event select for regular group"] #[inline(always)] pub fn extsel(&self) -> EXTSEL_R { EXTSEL_R::new(((self.bits >> 17) & 0x07) as u8) } #[doc = "Bit 15 - External trigger conversion mode for injected channels"] #[inline(always)] pub fn jexttrig(&self) -> JEXTTRIG_R { JEXTTRIG_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 12:14 - External event select for injected group"] #[inline(always)] pub fn jextsel(&self) -> JEXTSEL_R { JEXTSEL_R::new(((self.bits >> 12) & 0x07) as u8) } #[doc = "Bit 11 - Data alignment"] #[inline(always)] pub fn align(&self) -> ALIGN_R { ALIGN_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 8 - Direct memory access mode"] #[inline(always)] pub fn dma(&self) -> DMA_R { DMA_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 3 - Reset calibration"] #[inline(always)] pub fn rstcal(&self) -> RSTCAL_R { RSTCAL_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - A/D calibration"] #[inline(always)] pub fn cal(&self) -> CAL_R { CAL_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Continuous conversion"] #[inline(always)] pub fn cont(&self) -> CONT_R { CONT_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - A/D converter ON / OFF"] #[inline(always)] pub fn adon(&self) -> ADON_R { ADON_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 23 - Temperature sensor and VREFINT enable"] #[inline(always)] pub fn tsvrefe(&mut self) -> TSVREFE_W { TSVREFE_W { w: self } } #[doc = "Bit 22 - Start conversion of regular channels"] #[inline(always)] pub fn swstart(&mut self) -> SWSTART_W { SWSTART_W { w: self } } #[doc = "Bit 21 - Start conversion of injected channels"] #[inline(always)] pub fn jswstart(&mut self) -> JSWSTART_W { JSWSTART_W { w: self } } #[doc = "Bit 20 - External trigger conversion mode for regular channels"] #[inline(always)] pub fn exttrig(&mut self) -> EXTTRIG_W { EXTTRIG_W { w: self } } #[doc = "Bits 17:19 - External event select for regular group"] #[inline(always)] pub fn extsel(&mut self) -> EXTSEL_W { EXTSEL_W { w: self } } #[doc = "Bit 15 - External trigger conversion mode for injected channels"] #[inline(always)] pub fn jexttrig(&mut self) -> JEXTTRIG_W { JEXTTRIG_W { w: self } } #[doc = "Bits 12:14 - External event select for injected group"] #[inline(always)] pub fn jextsel(&mut self) -> JEXTSEL_W { JEXTSEL_W { w: self } } #[doc = "Bit 11 - Data alignment"] #[inline(always)] pub fn align(&mut self) -> ALIGN_W { ALIGN_W { w: self } } #[doc = "Bit 8 - Direct memory access mode"] #[inline(always)] pub fn dma(&mut self) -> DMA_W { DMA_W { w: self } } #[doc = "Bit 3 - Reset calibration"] #[inline(always)] pub fn rstcal(&mut self) -> RSTCAL_W { RSTCAL_W { w: self } } #[doc = "Bit 2 - A/D calibration"] #[inline(always)] pub fn cal(&mut self) -> CAL_W { CAL_W { w: self } } #[doc = "Bit 1 - Continuous conversion"] #[inline(always)] pub fn cont(&mut self) -> CONT_W { CONT_W { w: self } } #[doc = "Bit 0 - A/D converter ON / OFF"] #[inline(always)] pub fn adon(&mut self) -> ADON_W { ADON_W { w: self } } }
use std::io::Read; fn read<T: std::str::FromStr>() -> T { let token: String = std::io::stdin() .bytes() .map(|c| c.ok().unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect(); token.parse().ok().unwrap() } fn main() { let n: usize = read(); let mut a = vec![vec![0; n]; n]; for i in 0..n { for k in 0..n { a[(i + k) % n][(n + i - k) % n] = i + 1; } } for r in a { println!( "{}", r.iter() .map(|x| x.to_string()) .collect::<Vec<_>>() .join(" ") ); } }
use super::log1p; /* atanh(x) = log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2 ~= x + x^3/3 + o(x^5) */ /// Inverse hyperbolic tangent (f64) /// /// Calculates the inverse hyperbolic tangent of `x`. /// Is defined as `log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2`. #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn atanh(x: f64) -> f64 { let u = x.to_bits(); let e = ((u >> 52) as usize) & 0x7ff; let sign = (u >> 63) != 0; /* |x| */ let mut y = f64::from_bits(u & 0x7fff_ffff_ffff_ffff); if e < 0x3ff - 1 { if e < 0x3ff - 32 { /* handle underflow */ if e == 0 { force_eval!(y as f32); } } else { /* |x| < 0.5, up to 1.7ulp error */ y = 0.5 * log1p(2.0 * y + 2.0 * y * y / (1.0 - y)); } } else { /* avoid overflow */ y = 0.5 * log1p(2.0 * (y / (1.0 - y))); } if sign { -y } else { y } }
pub fn find_primes_up_to(limit: u32) -> Vec<u32> { let mut v: Vec<_> = (2..limit).collect(); for i in 2..limit { v.retain(|&x| x <= i || x % i != 0); } v } pub fn nth(n: u32) -> u32 { let a = n as usize; let v = find_primes_up_to(105000); //to make it faster, the limit made close t the maximum answer on test let mut ans = 0; for i in 0..v.len() { if i == a { ans = v[i]; } } return ans; }
use wasm_bindgen::prelude::*; use serde::{Deserialize, Serialize}; mod models; use models::{Stock, StockMove, StockMoveAction, StockMoveEvent, Action, Restore, Event, StockMoveId, ItemCode, LocationCode, Quantity}; type Revision = usize; #[derive(Debug, Deserialize, Serialize)] struct Response<T> { state: T, event: StockMoveEvent, revision: Revision, } #[derive(Debug, Deserialize, Serialize)] struct StoredResponse<T> { snapshot: T, events: Vec<StockMoveEvent>, } #[wasm_bindgen] extern { #[wasm_bindgen(js_namespace = console)] fn log(s: String); #[wasm_bindgen(js_namespace = sample)] fn events_for_move(id: StockMoveId) -> JsValue; #[wasm_bindgen(js_namespace = sample)] fn events_for_stock(item: ItemCode, location: LocationCode) -> JsValue; } #[wasm_bindgen] pub fn start(id: StockMoveId, item: ItemCode, qty: Quantity, from: LocationCode, to: LocationCode) -> JsValue { let cmd = StockMoveAction::start(id.clone(), item, qty, from, to); action(id, cmd) } #[wasm_bindgen] pub fn assign(id: StockMoveId) -> JsValue { action(id.clone(), StockMoveAction::assign(id)) } #[wasm_bindgen] pub fn cancel(id: StockMoveId) -> JsValue { action(id.clone(), StockMoveAction::cancel(id)) } #[wasm_bindgen] pub fn shipment(id: StockMoveId, qty: Quantity) -> JsValue { let cmd = if qty > 0 { StockMoveAction::shipment(id.clone(), qty) } else { StockMoveAction::shipment_failure(id.clone()) }; action(id, cmd) } #[wasm_bindgen] pub fn arrival(id: StockMoveId, qty: Quantity) -> JsValue { action(id.clone(), StockMoveAction::arrival(id, qty)) } #[wasm_bindgen] pub fn status(id: StockMoveId) -> JsValue { to_jsvalue(&restore_move(id)) } #[wasm_bindgen] pub fn new_stock(item: ItemCode, location: LocationCode, managed: bool) -> JsValue { let r = match managed { true => Stock::managed_new(item, location), false => Stock::unmanaged_new(item, location), }; to_jsvalue(&r) } #[wasm_bindgen] pub fn stock_status(item: ItemCode, location: LocationCode) -> JsValue { to_jsvalue(&restore_stock(item, location)) } fn action(id: StockMoveId, cmd: Option<StockMoveAction>) -> JsValue { let (state, rev) = restore_move(id) .unwrap_or( (StockMove::Nothing, 0) ); let r = cmd .map(|c| (state, c)) .and_then(|(s, c)| Action::action(&(s.clone(), restore_stock), &c) .and_then(|e| e.apply(s).map(|s| Response { state: s, event: e, revision: rev + 1 } ) ) ); to_jsvalue(&r) } fn restore_move(id: StockMoveId) -> Option<(StockMove, Revision)> { events_for_move(id) .into_serde::<StoredResponse<StockMove>>() .ok() .map(|r| { let rev = r.events.len(); (r.snapshot.restore(r.events.iter()), rev) }) } fn restore_stock(item: ItemCode, location: LocationCode) -> Option<Stock> { events_for_stock(item, location) .into_serde::<StoredResponse<Stock>>() .ok() .map(|r| r.snapshot.restore(r.events.iter())) } fn to_jsvalue<T>(v: &T) -> JsValue where T: serde::ser::Serialize, { JsValue::from_serde(v).unwrap_or(JsValue::null()) }
// Copyright (c) The cargo-guppy Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::parser::ParseError; use crate::platform::{Platform, TargetFeatures}; use crate::Target; use crate::TargetSpec; use cfg_expr::{Expression, Predicate}; use std::sync::Arc; use std::{error, fmt}; /// An error that occurred during target evaluation. #[derive(PartialEq)] #[non_exhaustive] pub enum EvalError { /// An invalid target spec was specified. InvalidSpec(ParseError), /// The platform was not found in the database. PlatformNotFound, } impl fmt::Display for EvalError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { EvalError::InvalidSpec(_) => write!(f, "invalid target spec"), EvalError::PlatformNotFound => write!(f, "platform not found in database"), } } } impl fmt::Debug for EvalError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { <EvalError as fmt::Display>::fmt(self, f) } } impl error::Error for EvalError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { EvalError::InvalidSpec(err) => Some(err), EvalError::PlatformNotFound => None, } } } /// Evaluates the given spec against the provided target and returns `Some(true)` on a successful /// match, and `Some(false)` on a failing match. /// /// This defaults to treating target features as unknown, and returns `None` if the overall result /// is unknown. /// /// For more advanced uses, see `TargetSpec::eval`. /// /// For more information, see the crate-level documentation. pub fn eval(spec_or_triple: &str, platform: &str) -> Result<Option<bool>, EvalError> { let target_spec = spec_or_triple .parse::<TargetSpec>() .map_err(EvalError::InvalidSpec)?; match Platform::new(platform, TargetFeatures::Unknown) { None => Err(EvalError::PlatformNotFound), Some(platform) => Ok(target_spec.eval(&platform)), } } pub(crate) fn eval_target(target: &Target<'_>, platform: &Platform<'_>) -> Option<bool> { match target { Target::TargetInfo(ref target_info) => Some(platform.triple() == target_info.triple), Target::Spec(ref expr) => eval_expr(expr, platform), } } fn eval_expr(spec: &Arc<Expression>, platform: &Platform<'_>) -> Option<bool> { spec.eval(|pred| { match pred { Predicate::Target(target) => Some(target.matches(platform.target_info())), Predicate::TargetFeature(feature) => platform.target_features().matches(feature), Predicate::Test | Predicate::DebugAssertions | Predicate::ProcMacro => { // Known families that always evaluate to false. See // https://docs.rs/cargo-platform/0.1.1/src/cargo_platform/lib.rs.html#76. Some(false) } Predicate::Feature(_) => { // NOTE: This is not supported by Cargo which always evaluates this to false. See // https://github.com/rust-lang/cargo/issues/7442 for more details. Some(false) } Predicate::Flag(flag) => { // This returns false by default but true in some cases. Some(platform.has_flag(flag)) } Predicate::KeyValue { .. } => { unreachable!("these predicates are disallowed at TargetSpec construction time") } } }) } #[cfg(test)] mod tests { use super::*; #[test] fn test_windows() { assert_eq!( eval("cfg(windows)", "x86_64-pc-windows-msvc"), Ok(Some(true)), ); } #[test] fn test_not_target_os() { assert_eq!( eval( "cfg(not(target_os = \"windows\"))", "x86_64-unknown-linux-gnu" ), Ok(Some(true)), ); } #[test] fn test_not_target_os_false() { assert_eq!( eval( "cfg(not(target_os = \"windows\"))", "x86_64-pc-windows-msvc" ), Ok(Some(false)), ); } #[test] fn test_exact_triple() { assert_eq!( eval("x86_64-unknown-linux-gnu", "x86_64-unknown-linux-gnu"), Ok(Some(true)), ); } #[test] fn test_redox() { assert_eq!( eval( "cfg(any(unix, target_os = \"redox\"))", "x86_64-unknown-linux-gnu" ), Ok(Some(true)), ); } #[test] fn test_bogus_families() { // Known bogus families. for family in &["test", "debug_assertions", "proc_macro"] { let cfg = format!("cfg({})", family); let cfg_not = format!("cfg(not({}))", family); assert_eq!(eval(&cfg, "x86_64-unknown-linux-gnu"), Ok(Some(false))); assert_eq!(eval(&cfg_not, "x86_64-unknown-linux-gnu"), Ok(Some(true))); } // Unknown bogus families. let platform = Platform::new("x86_64-unknown-linux-gnu", TargetFeatures::Unknown).unwrap(); let mut platform_with_flags = platform.clone(); platform_with_flags.add_flags(&["foo", "bar"]); for family in &["foo", "bar"] { let cfg = format!("cfg({})", family); let cfg_not = format!("cfg(not({}))", family); // eval always means flags are evaluated to false. assert_eq!(eval(&cfg, "x86_64-unknown-linux-gnu"), Ok(Some(false))); assert_eq!(eval(&cfg_not, "x86_64-unknown-linux-gnu"), Ok(Some(true))); let spec: TargetSpec = cfg.parse().unwrap(); let spec_not: TargetSpec = cfg_not.parse().unwrap(); // flag missing means false. assert_eq!(spec.eval(&platform), Some(false)); assert_eq!(spec_not.eval(&platform), Some(true)); // flag present means true. assert_eq!(spec.eval(&platform_with_flags), Some(true)); assert_eq!(spec_not.eval(&platform_with_flags), Some(false)); } for family in &["baz", "nonsense"] { let cfg = format!("cfg({})", family); let cfg_not = format!("cfg(not({}))", family); // eval always means flags are evaluated to false. assert_eq!(eval(&cfg, "x86_64-unknown-linux-gnu"), Ok(Some(false))); assert_eq!(eval(&cfg_not, "x86_64-unknown-linux-gnu"), Ok(Some(true))); let spec: TargetSpec = cfg.parse().unwrap(); let spec_not: TargetSpec = cfg_not.parse().unwrap(); // flag missing means false. assert_eq!(spec.eval(&platform), Some(false)); assert_eq!(spec_not.eval(&platform), Some(true)); // flag still missing means false. assert_eq!(spec.eval(&platform_with_flags), Some(false)); assert_eq!(spec_not.eval(&platform_with_flags), Some(true)); } } #[test] fn test_target_feature() { // target features are unknown by default. assert_eq!( eval("cfg(target_feature = \"sse\")", "x86_64-unknown-linux-gnu"), Ok(None), ); assert_eq!( eval( "cfg(target_feature = \"atomics\")", "x86_64-unknown-linux-gnu", ), Ok(None), ); assert_eq!( eval( "cfg(not(target_feature = \"fxsr\"))", "x86_64-unknown-linux-gnu", ), Ok(None), ); fn eval_unknown(spec: &str, platform: &str) -> Option<bool> { let platform = Platform::new(platform, TargetFeatures::features(&["sse", "sse2"])) .expect("platform should be found"); let spec: TargetSpec = spec.parse().unwrap(); spec.eval(&platform) } assert_eq!( eval_unknown("cfg(target_feature = \"sse\")", "x86_64-unknown-linux-gnu"), Some(true), ); assert_eq!( eval_unknown( "cfg(not(target_feature = \"sse\"))", "x86_64-unknown-linux-gnu", ), Some(false), ); assert_eq!( eval_unknown("cfg(target_feature = \"fxsr\")", "x86_64-unknown-linux-gnu"), Some(false), ); assert_eq!( eval_unknown( "cfg(not(target_feature = \"fxsr\"))", "x86_64-unknown-linux-gnu", ), Some(true), ); fn eval_all(spec: &str, platform: &str) -> Option<bool> { let platform = Platform::new(platform, TargetFeatures::All).expect("platform should be found"); let spec: TargetSpec = spec.parse().unwrap(); spec.eval(&platform) } assert_eq!( eval_all("cfg(target_feature = \"sse\")", "x86_64-unknown-linux-gnu"), Some(true), ); assert_eq!( eval_all( "cfg(not(target_feature = \"sse\"))", "x86_64-unknown-linux-gnu", ), Some(false), ); assert_eq!( eval_all("cfg(target_feature = \"fxsr\")", "x86_64-unknown-linux-gnu"), Some(true), ); assert_eq!( eval_all( "cfg(not(target_feature = \"fxsr\"))", "x86_64-unknown-linux-gnu", ), Some(false), ); } }
// revisions: base nll // ignore-compare-mode-nll //[nll] compile-flags: -Z borrowck=mir #![feature(trait_upcasting)] #![allow(incomplete_features)] trait Foo<'a>: Bar<'a> {} trait Bar<'a> {} fn test_correct(x: &dyn Foo<'static>) { let _ = x as &dyn Bar<'static>; } fn test_wrong1<'a>(x: &dyn Foo<'static>, y: &'a u32) { let _ = x as &dyn Bar<'a>; // Error //[base]~^ ERROR mismatched types //[nll]~^^ ERROR lifetime may not live long enough } fn test_wrong2<'a>(x: &dyn Foo<'a>) { let _ = x as &dyn Bar<'static>; // Error //[base]~^ ERROR mismatched types //[nll]~^^ ERROR lifetime may not live long enough } fn main() {}
extern crate chrono; use self::chrono::prelude::{DateTime, Utc}; use signal::Signal; use order::{OrderKind, OrderBuilder, OcaGroup}; use order::policy::{OrderPolicy, OrderPolicyError}; pub struct SimpleOrderPolicy { order_kind: OrderKind, oca: Option<OcaGroup>, active_until: Option<DateTime<Utc>>, active_after: Option<DateTime<Utc>> } impl SimpleOrderPolicy { pub fn new(order_kind: OrderKind) -> Self { SimpleOrderPolicy { order_kind: order_kind, oca: None, active_until: None, active_after: None } } pub fn oca(&self) -> &Option<OcaGroup> { &self.oca } pub fn set_oca(mut self, value: Option<OcaGroup>) -> Self { self.oca = value; self } pub fn active_until(&self) -> &Option<DateTime<Utc>> { &self.active_until } pub fn set_active_until(mut self, value: Option<DateTime<Utc>>) -> Self { self.active_until = value; self } pub fn active_after(&self) -> &Option<DateTime<Utc>> { &self.active_after } pub fn set_active_after(mut self, value: Option<DateTime<Utc>>) -> Self { self.active_after = value; self } } impl OrderPolicy for SimpleOrderPolicy { fn create_order(&self, signal: &Signal) -> Result<OrderBuilder, OrderPolicyError> { Ok( OrderBuilder::unallocated( self.order_kind.clone(), signal.symbol_id().clone(), signal.direction().clone() ) .set_active_after(self.active_after().clone()) .set_active_until(self.active_until().clone()) .set_oca(self.oca().clone()) ) } }
use std::time::Duration; use crate::{ RotatorEvent, RotatorResult, }; use crate::value::get_secret_value; pub fn test_secret(e: RotatorEvent) -> RotatorResult<()> { let timeout = Duration::from_secs(2); let _value = match get_secret_value(&e.secret_id, Some("AWSPENDING"), Some(&e.client_request_token), timeout) { Ok(value) => { info!("testSecret: Successfully retrieved secret for {}.", e.secret_id); Ok(value) }, Err(err) => { error!("testSecret: Error retrieving secret for ARN {} and version {}: {:?}.", e.secret_id, e.client_request_token, err); Err(err) } }?; // todo: test secret on resource Ok(()) }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IPhoneCallBlockedTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPhoneCallBlockedTriggerDetails { type Vtable = IPhoneCallBlockedTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa4a690a2_e4c1_427f_864e_e470477ddb67); } #[repr(C)] #[doc(hidden)] pub struct IPhoneCallBlockedTriggerDetails_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhoneCallBlockedReason) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPhoneCallOriginDataRequestTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPhoneCallOriginDataRequestTriggerDetails { type Vtable = IPhoneCallOriginDataRequestTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6e9b5b3f_c54b_4e82_4cc9_e329a4184592); } #[repr(C)] #[doc(hidden)] pub struct IPhoneCallOriginDataRequestTriggerDetails_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPhoneIncomingCallDismissedTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPhoneIncomingCallDismissedTriggerDetails { type Vtable = IPhoneIncomingCallDismissedTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbad30276_83b6_5732_9c38_0c206546196a); } #[repr(C)] #[doc(hidden)] pub struct IPhoneIncomingCallDismissedTriggerDetails_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhoneIncomingCallDismissedReason) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPhoneIncomingCallNotificationTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPhoneIncomingCallNotificationTriggerDetails { type Vtable = IPhoneIncomingCallNotificationTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2b0e6044_9b32_5d42_8222_d2812e39fb21); } #[repr(C)] #[doc(hidden)] pub struct IPhoneIncomingCallNotificationTriggerDetails_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPhoneLineChangedTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPhoneLineChangedTriggerDetails { type Vtable = IPhoneLineChangedTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc6d321e7_d11d_40d8_b2b7_e40a01d66249); } #[repr(C)] #[doc(hidden)] pub struct IPhoneLineChangedTriggerDetails_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhoneLineChangeKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lineproperty: PhoneLineProperties, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPhoneNewVoicemailMessageTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPhoneNewVoicemailMessageTriggerDetails { type Vtable = IPhoneNewVoicemailMessageTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x13a8c01b_b831_48d3_8ba9_8d22a6580dcf); } #[repr(C)] #[doc(hidden)] pub struct IPhoneNewVoicemailMessageTriggerDetails_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PhoneCallBlockedReason(pub i32); impl PhoneCallBlockedReason { pub const InCallBlockingList: PhoneCallBlockedReason = PhoneCallBlockedReason(0i32); pub const PrivateNumber: PhoneCallBlockedReason = PhoneCallBlockedReason(1i32); pub const UnknownNumber: PhoneCallBlockedReason = PhoneCallBlockedReason(2i32); } impl ::core::convert::From<i32> for PhoneCallBlockedReason { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PhoneCallBlockedReason { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PhoneCallBlockedReason { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Calls.Background.PhoneCallBlockedReason;i4)"); } impl ::windows::core::DefaultType for PhoneCallBlockedReason { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PhoneCallBlockedTriggerDetails(pub ::windows::core::IInspectable); impl PhoneCallBlockedTriggerDetails { pub fn PhoneNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn LineId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn CallBlockedReason(&self) -> ::windows::core::Result<PhoneCallBlockedReason> { let this = self; unsafe { let mut result__: PhoneCallBlockedReason = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhoneCallBlockedReason>(result__) } } } unsafe impl ::windows::core::RuntimeType for PhoneCallBlockedTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Calls.Background.PhoneCallBlockedTriggerDetails;{a4a690a2-e4c1-427f-864e-e470477ddb67})"); } unsafe impl ::windows::core::Interface for PhoneCallBlockedTriggerDetails { type Vtable = IPhoneCallBlockedTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa4a690a2_e4c1_427f_864e_e470477ddb67); } impl ::windows::core::RuntimeName for PhoneCallBlockedTriggerDetails { const NAME: &'static str = "Windows.ApplicationModel.Calls.Background.PhoneCallBlockedTriggerDetails"; } impl ::core::convert::From<PhoneCallBlockedTriggerDetails> for ::windows::core::IUnknown { fn from(value: PhoneCallBlockedTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&PhoneCallBlockedTriggerDetails> for ::windows::core::IUnknown { fn from(value: &PhoneCallBlockedTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhoneCallBlockedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhoneCallBlockedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PhoneCallBlockedTriggerDetails> for ::windows::core::IInspectable { fn from(value: PhoneCallBlockedTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&PhoneCallBlockedTriggerDetails> for ::windows::core::IInspectable { fn from(value: &PhoneCallBlockedTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhoneCallBlockedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhoneCallBlockedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PhoneCallBlockedTriggerDetails {} unsafe impl ::core::marker::Sync for PhoneCallBlockedTriggerDetails {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PhoneCallOriginDataRequestTriggerDetails(pub ::windows::core::IInspectable); impl PhoneCallOriginDataRequestTriggerDetails { pub fn RequestId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn PhoneNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for PhoneCallOriginDataRequestTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Calls.Background.PhoneCallOriginDataRequestTriggerDetails;{6e9b5b3f-c54b-4e82-4cc9-e329a4184592})"); } unsafe impl ::windows::core::Interface for PhoneCallOriginDataRequestTriggerDetails { type Vtable = IPhoneCallOriginDataRequestTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6e9b5b3f_c54b_4e82_4cc9_e329a4184592); } impl ::windows::core::RuntimeName for PhoneCallOriginDataRequestTriggerDetails { const NAME: &'static str = "Windows.ApplicationModel.Calls.Background.PhoneCallOriginDataRequestTriggerDetails"; } impl ::core::convert::From<PhoneCallOriginDataRequestTriggerDetails> for ::windows::core::IUnknown { fn from(value: PhoneCallOriginDataRequestTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&PhoneCallOriginDataRequestTriggerDetails> for ::windows::core::IUnknown { fn from(value: &PhoneCallOriginDataRequestTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhoneCallOriginDataRequestTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhoneCallOriginDataRequestTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PhoneCallOriginDataRequestTriggerDetails> for ::windows::core::IInspectable { fn from(value: PhoneCallOriginDataRequestTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&PhoneCallOriginDataRequestTriggerDetails> for ::windows::core::IInspectable { fn from(value: &PhoneCallOriginDataRequestTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhoneCallOriginDataRequestTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhoneCallOriginDataRequestTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PhoneCallOriginDataRequestTriggerDetails {} unsafe impl ::core::marker::Sync for PhoneCallOriginDataRequestTriggerDetails {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PhoneIncomingCallDismissedReason(pub i32); impl PhoneIncomingCallDismissedReason { pub const Unknown: PhoneIncomingCallDismissedReason = PhoneIncomingCallDismissedReason(0i32); pub const CallRejected: PhoneIncomingCallDismissedReason = PhoneIncomingCallDismissedReason(1i32); pub const TextReply: PhoneIncomingCallDismissedReason = PhoneIncomingCallDismissedReason(2i32); pub const ConnectionLost: PhoneIncomingCallDismissedReason = PhoneIncomingCallDismissedReason(3i32); } impl ::core::convert::From<i32> for PhoneIncomingCallDismissedReason { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PhoneIncomingCallDismissedReason { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PhoneIncomingCallDismissedReason { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Calls.Background.PhoneIncomingCallDismissedReason;i4)"); } impl ::windows::core::DefaultType for PhoneIncomingCallDismissedReason { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PhoneIncomingCallDismissedTriggerDetails(pub ::windows::core::IInspectable); impl PhoneIncomingCallDismissedTriggerDetails { pub fn LineId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn PhoneNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn DismissalTime(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } pub fn TextReplyMessage(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Reason(&self) -> ::windows::core::Result<PhoneIncomingCallDismissedReason> { let this = self; unsafe { let mut result__: PhoneIncomingCallDismissedReason = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhoneIncomingCallDismissedReason>(result__) } } } unsafe impl ::windows::core::RuntimeType for PhoneIncomingCallDismissedTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Calls.Background.PhoneIncomingCallDismissedTriggerDetails;{bad30276-83b6-5732-9c38-0c206546196a})"); } unsafe impl ::windows::core::Interface for PhoneIncomingCallDismissedTriggerDetails { type Vtable = IPhoneIncomingCallDismissedTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbad30276_83b6_5732_9c38_0c206546196a); } impl ::windows::core::RuntimeName for PhoneIncomingCallDismissedTriggerDetails { const NAME: &'static str = "Windows.ApplicationModel.Calls.Background.PhoneIncomingCallDismissedTriggerDetails"; } impl ::core::convert::From<PhoneIncomingCallDismissedTriggerDetails> for ::windows::core::IUnknown { fn from(value: PhoneIncomingCallDismissedTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&PhoneIncomingCallDismissedTriggerDetails> for ::windows::core::IUnknown { fn from(value: &PhoneIncomingCallDismissedTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhoneIncomingCallDismissedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhoneIncomingCallDismissedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PhoneIncomingCallDismissedTriggerDetails> for ::windows::core::IInspectable { fn from(value: PhoneIncomingCallDismissedTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&PhoneIncomingCallDismissedTriggerDetails> for ::windows::core::IInspectable { fn from(value: &PhoneIncomingCallDismissedTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhoneIncomingCallDismissedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhoneIncomingCallDismissedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PhoneIncomingCallDismissedTriggerDetails {} unsafe impl ::core::marker::Sync for PhoneIncomingCallDismissedTriggerDetails {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PhoneIncomingCallNotificationTriggerDetails(pub ::windows::core::IInspectable); impl PhoneIncomingCallNotificationTriggerDetails { pub fn LineId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn CallId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for PhoneIncomingCallNotificationTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Calls.Background.PhoneIncomingCallNotificationTriggerDetails;{2b0e6044-9b32-5d42-8222-d2812e39fb21})"); } unsafe impl ::windows::core::Interface for PhoneIncomingCallNotificationTriggerDetails { type Vtable = IPhoneIncomingCallNotificationTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2b0e6044_9b32_5d42_8222_d2812e39fb21); } impl ::windows::core::RuntimeName for PhoneIncomingCallNotificationTriggerDetails { const NAME: &'static str = "Windows.ApplicationModel.Calls.Background.PhoneIncomingCallNotificationTriggerDetails"; } impl ::core::convert::From<PhoneIncomingCallNotificationTriggerDetails> for ::windows::core::IUnknown { fn from(value: PhoneIncomingCallNotificationTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&PhoneIncomingCallNotificationTriggerDetails> for ::windows::core::IUnknown { fn from(value: &PhoneIncomingCallNotificationTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhoneIncomingCallNotificationTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhoneIncomingCallNotificationTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PhoneIncomingCallNotificationTriggerDetails> for ::windows::core::IInspectable { fn from(value: PhoneIncomingCallNotificationTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&PhoneIncomingCallNotificationTriggerDetails> for ::windows::core::IInspectable { fn from(value: &PhoneIncomingCallNotificationTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhoneIncomingCallNotificationTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhoneIncomingCallNotificationTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PhoneIncomingCallNotificationTriggerDetails {} unsafe impl ::core::marker::Sync for PhoneIncomingCallNotificationTriggerDetails {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PhoneLineChangeKind(pub i32); impl PhoneLineChangeKind { pub const Added: PhoneLineChangeKind = PhoneLineChangeKind(0i32); pub const Removed: PhoneLineChangeKind = PhoneLineChangeKind(1i32); pub const PropertiesChanged: PhoneLineChangeKind = PhoneLineChangeKind(2i32); } impl ::core::convert::From<i32> for PhoneLineChangeKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PhoneLineChangeKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PhoneLineChangeKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Calls.Background.PhoneLineChangeKind;i4)"); } impl ::windows::core::DefaultType for PhoneLineChangeKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PhoneLineChangedTriggerDetails(pub ::windows::core::IInspectable); impl PhoneLineChangedTriggerDetails { pub fn LineId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn ChangeType(&self) -> ::windows::core::Result<PhoneLineChangeKind> { let this = self; unsafe { let mut result__: PhoneLineChangeKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhoneLineChangeKind>(result__) } } pub fn HasLinePropertyChanged(&self, lineproperty: PhoneLineProperties) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), lineproperty, &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for PhoneLineChangedTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Calls.Background.PhoneLineChangedTriggerDetails;{c6d321e7-d11d-40d8-b2b7-e40a01d66249})"); } unsafe impl ::windows::core::Interface for PhoneLineChangedTriggerDetails { type Vtable = IPhoneLineChangedTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc6d321e7_d11d_40d8_b2b7_e40a01d66249); } impl ::windows::core::RuntimeName for PhoneLineChangedTriggerDetails { const NAME: &'static str = "Windows.ApplicationModel.Calls.Background.PhoneLineChangedTriggerDetails"; } impl ::core::convert::From<PhoneLineChangedTriggerDetails> for ::windows::core::IUnknown { fn from(value: PhoneLineChangedTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&PhoneLineChangedTriggerDetails> for ::windows::core::IUnknown { fn from(value: &PhoneLineChangedTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhoneLineChangedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhoneLineChangedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PhoneLineChangedTriggerDetails> for ::windows::core::IInspectable { fn from(value: PhoneLineChangedTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&PhoneLineChangedTriggerDetails> for ::windows::core::IInspectable { fn from(value: &PhoneLineChangedTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhoneLineChangedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhoneLineChangedTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PhoneLineChangedTriggerDetails {} unsafe impl ::core::marker::Sync for PhoneLineChangedTriggerDetails {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PhoneLineProperties(pub u32); impl PhoneLineProperties { pub const None: PhoneLineProperties = PhoneLineProperties(0u32); pub const BrandingOptions: PhoneLineProperties = PhoneLineProperties(1u32); pub const CanDial: PhoneLineProperties = PhoneLineProperties(2u32); pub const CellularDetails: PhoneLineProperties = PhoneLineProperties(4u32); pub const DisplayColor: PhoneLineProperties = PhoneLineProperties(8u32); pub const DisplayName: PhoneLineProperties = PhoneLineProperties(16u32); pub const NetworkName: PhoneLineProperties = PhoneLineProperties(32u32); pub const NetworkState: PhoneLineProperties = PhoneLineProperties(64u32); pub const Transport: PhoneLineProperties = PhoneLineProperties(128u32); pub const Voicemail: PhoneLineProperties = PhoneLineProperties(256u32); } impl ::core::convert::From<u32> for PhoneLineProperties { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PhoneLineProperties { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PhoneLineProperties { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Calls.Background.PhoneLineProperties;u4)"); } impl ::windows::core::DefaultType for PhoneLineProperties { type DefaultType = Self; } impl ::core::ops::BitOr for PhoneLineProperties { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for PhoneLineProperties { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for PhoneLineProperties { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for PhoneLineProperties { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for PhoneLineProperties { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PhoneNewVoicemailMessageTriggerDetails(pub ::windows::core::IInspectable); impl PhoneNewVoicemailMessageTriggerDetails { pub fn LineId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn VoicemailCount(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn OperatorMessage(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for PhoneNewVoicemailMessageTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Calls.Background.PhoneNewVoicemailMessageTriggerDetails;{13a8c01b-b831-48d3-8ba9-8d22a6580dcf})"); } unsafe impl ::windows::core::Interface for PhoneNewVoicemailMessageTriggerDetails { type Vtable = IPhoneNewVoicemailMessageTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x13a8c01b_b831_48d3_8ba9_8d22a6580dcf); } impl ::windows::core::RuntimeName for PhoneNewVoicemailMessageTriggerDetails { const NAME: &'static str = "Windows.ApplicationModel.Calls.Background.PhoneNewVoicemailMessageTriggerDetails"; } impl ::core::convert::From<PhoneNewVoicemailMessageTriggerDetails> for ::windows::core::IUnknown { fn from(value: PhoneNewVoicemailMessageTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&PhoneNewVoicemailMessageTriggerDetails> for ::windows::core::IUnknown { fn from(value: &PhoneNewVoicemailMessageTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhoneNewVoicemailMessageTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhoneNewVoicemailMessageTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PhoneNewVoicemailMessageTriggerDetails> for ::windows::core::IInspectable { fn from(value: PhoneNewVoicemailMessageTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&PhoneNewVoicemailMessageTriggerDetails> for ::windows::core::IInspectable { fn from(value: &PhoneNewVoicemailMessageTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhoneNewVoicemailMessageTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhoneNewVoicemailMessageTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PhoneNewVoicemailMessageTriggerDetails {} unsafe impl ::core::marker::Sync for PhoneNewVoicemailMessageTriggerDetails {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PhoneTriggerType(pub i32); impl PhoneTriggerType { pub const NewVoicemailMessage: PhoneTriggerType = PhoneTriggerType(0i32); pub const CallHistoryChanged: PhoneTriggerType = PhoneTriggerType(1i32); pub const LineChanged: PhoneTriggerType = PhoneTriggerType(2i32); pub const AirplaneModeDisabledForEmergencyCall: PhoneTriggerType = PhoneTriggerType(3i32); pub const CallOriginDataRequest: PhoneTriggerType = PhoneTriggerType(4i32); pub const CallBlocked: PhoneTriggerType = PhoneTriggerType(5i32); pub const IncomingCallDismissed: PhoneTriggerType = PhoneTriggerType(6i32); pub const IncomingCallNotification: PhoneTriggerType = PhoneTriggerType(7i32); } impl ::core::convert::From<i32> for PhoneTriggerType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PhoneTriggerType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PhoneTriggerType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Calls.Background.PhoneTriggerType;i4)"); } impl ::windows::core::DefaultType for PhoneTriggerType { type DefaultType = Self; }
use amethyst::core::{ timing::Time, SystemDesc, Transform}; use amethyst::derive::SystemDesc; use amethyst::ecs::{Join, Read, ReadStorage, System, SystemData, World, WriteStorage}; use amethyst::input::{InputHandler, StringBindings}; use crate::ball::Ball; use crate::paddle::{Paddle, Side, PADDLE_WIDTH}; use crate::pong::ARENA_WIDTH; #[derive(SystemDesc)] pub struct BallSystem; impl<'s> System<'s> for BallSystem { type SystemData = (WriteStorage<'s, Transform>, ReadStorage<'s, Ball>, Read<'s, Time>); fn run(&mut self, (mut transforms, balls, time): Self::SystemData) { for (ball, transform) in (&balls, &mut transforms).join() { transform.prepend_translation_x(ball.velocity.0 * time.delta_seconds()); transform.prepend_translation_y(ball.velocity.1 * time.delta_seconds()); } } }
use std::io::prelude::*; use std::fs::File; #[derive(Debug, PartialEq, Clone, Copy)] enum Register { A, B, C, D } #[derive(Debug, PartialEq, Clone, Copy)] enum Op { Cpy, Inc, Dec, Jnz } #[derive(Debug, PartialEq, Clone, Copy)] enum Arg { Reg(Register), Literal(i32) } #[derive(Debug)] struct Instruction { lineno: usize, op: Op, lhs: Arg, rhs: Option<Arg> } struct Program { instructions: Vec<Instruction> } #[derive(Debug)] struct State { a: i32, b: i32, c: i32, d: i32 } impl State { fn new(a: i32, b: i32, c: i32, d: i32) -> State { State { a: a, b: b, c: c, d: d } } fn read(&self, reg: Register) -> i32 { match reg { Register::A => self.a, Register::B => self.b, Register::C => self.c, Register::D => self.d } } fn write(&mut self, reg: Register, val: i32) { match reg { Register::A => self.a = val, Register::B => self.b = val, Register::C => self.c = val, Register::D => self.d = val } } } fn parse_arg(arg_str: &str) -> Arg { match arg_str { "a" => Arg::Reg(Register::A), "b" => Arg::Reg(Register::B), "c" => Arg::Reg(Register::C), "d" => Arg::Reg(Register::D), x => Arg::Literal(x.parse::<i32>().unwrap()), } } fn parse_instr((lineno, line): (usize, &str)) -> Instruction { let tokens: Vec<&str> = line.split_whitespace().collect(); Instruction { lineno: lineno, op: match tokens.get(0) { Some(x) => match *x { "cpy" => Op::Cpy, "inc" => Op::Inc, "dec" => Op::Dec, "jnz" => Op::Jnz, _ => panic!() }, None => panic!() }, lhs: match tokens.get(1) { Some(arg) => parse_arg(arg), None => panic!() }, rhs: match tokens.get(2) { Some(arg) => Some(parse_arg(arg)), None => None } } } fn parse_prog(source: String) -> Program { Program { instructions: source.lines() .enumerate() .map(parse_instr) .collect() } } fn execute_program<'a>(prog: &Program, state: &'a mut State) -> &'a mut State { let mut line = 0; while let Some(instr) = prog.instructions.get(line) { match instr.op { Op::Cpy => { let dst = match instr.rhs { Some(Arg::Reg(r)) => r, _ => panic!() }; match instr.lhs { Arg::Reg(src) => { let val = state.read(src); state.write(dst, val); }, Arg::Literal(x) => state.write(dst, x) }; }, op @ Op::Inc | op @ Op::Dec => { let src = match instr.lhs { Arg::Reg(r) => r, _ => panic!() }; let val = state.read(src); state.write(src, val + if op == Op::Inc { 1 } else { -1 }); }, Op::Jnz => { let cond = match instr.lhs { Arg::Literal(x) => x, Arg::Reg(r) => state.read(r) }; if cond != 0 { match instr.rhs { Some(Arg::Literal(x)) => { line = (line as i32 + x) as usize; continue; }, _ => panic!() }; }; } } line += 1; } state } fn main() { let mut f = File::open("input.txt").unwrap(); let mut s = String::new(); f.read_to_string(&mut s).unwrap(); let prog = parse_prog(s); // Part 1 let mut state = State::new(0, 0, 0, 0); println!("final state (part 1): {:?}", execute_program(&prog, &mut state)); // Part 2 state = State::new(0, 0, 1, 0); println!("final state (part 2): {:?}", execute_program(&prog, &mut state)); }
use crate::datastructure::DataStructure; use crate::shader::shaders::{ambient, diffuse, emittance, specular}; use crate::shader::Shader; use crate::util::ray::Ray; use crate::util::vector::Vector; #[derive(Debug)] pub struct MtlShader; impl Shader for MtlShader { fn shade<'s>(&self, ray: &Ray, datastructure: &'s (dyn DataStructure + 's)) -> Vector { let intersection = if let Some(intersection) = datastructure.intersects(&ray) { intersection } else { return Vector::repeated(0f64); }; // let pointlight = Vector::new(3., 1.0, 0.); let pointlight = Vector::new(100., 100., 100.); let brightness = Vector::repeated(1f64); let hit_pos = intersection.hit_pos(); let part_amb = ambient(&intersection) * Vector::repeated(0.1); let part_emi = emittance(&intersection); let part_diff = diffuse(&intersection, hit_pos, pointlight) * brightness; let part_spec = specular(&intersection, hit_pos, pointlight, intersection.ray.origin) * brightness; part_amb + part_emi + part_diff + part_spec } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to 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. use std::ops::Range; use std::sync::Arc; use std::time::Duration; use std::time::Instant; use backoff::backoff::Backoff; use backoff::ExponentialBackoffBuilder; use common_base::base::ProgressValues; use common_catalog::table::Table; use common_catalog::table::TableExt; use common_catalog::table_context::TableContext; use common_exception::ErrorCode; use common_exception::Result; use common_expression::TableSchema; use common_expression::TableSchemaRef; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableStatistics; use common_meta_app::schema::UpdateTableMetaReq; use common_meta_app::schema::UpsertTableCopiedFileReq; use common_meta_types::MatchSeq; use common_sql::field_default_value; use opendal::Operator; use storages_common_cache::CacheAccessor; use storages_common_cache_manager::CachedObject; use storages_common_table_meta::meta::ClusterKey; use storages_common_table_meta::meta::ColumnStatistics; use storages_common_table_meta::meta::Location; use storages_common_table_meta::meta::SegmentInfo; use storages_common_table_meta::meta::Statistics; use storages_common_table_meta::meta::TableSnapshot; use storages_common_table_meta::meta::TableSnapshotStatistics; use storages_common_table_meta::meta::Versioned; use storages_common_table_meta::table::OPT_KEY_SNAPSHOT_LOCATION; use tracing::debug; use tracing::info; use tracing::warn; use uuid::Uuid; use crate::io::MetaWriter; use crate::io::SegmentsIO; use crate::io::TableMetaLocationGenerator; use crate::metrics::metrics_inc_commit_mutation_resolvable_conflict; use crate::metrics::metrics_inc_commit_mutation_retry; use crate::metrics::metrics_inc_commit_mutation_success; use crate::metrics::metrics_inc_commit_mutation_unresolvable_conflict; use crate::operations::commit::utils::no_side_effects_in_meta_store; use crate::operations::mutation::AbortOperation; use crate::operations::AppendOperationLogEntry; use crate::operations::TableOperationLog; use crate::statistics; use crate::statistics::merge_statistics; use crate::FuseTable; const OCC_DEFAULT_BACKOFF_INIT_DELAY_MS: Duration = Duration::from_millis(5); const OCC_DEFAULT_BACKOFF_MAX_DELAY_MS: Duration = Duration::from_millis(20 * 1000); const OCC_DEFAULT_BACKOFF_MAX_ELAPSED_MS: Duration = Duration::from_millis(120 * 1000); const MAX_RETRIES: u64 = 10; impl FuseTable { pub async fn do_commit( &self, ctx: Arc<dyn TableContext>, operation_log: TableOperationLog, copied_files: Option<UpsertTableCopiedFileReq>, overwrite: bool, ) -> Result<()> { self.commit_with_max_retry_elapsed(ctx, operation_log, copied_files, None, overwrite) .await } pub async fn commit_with_max_retry_elapsed( &self, ctx: Arc<dyn TableContext>, operation_log: TableOperationLog, copied_files: Option<UpsertTableCopiedFileReq>, max_retry_elapsed: Option<Duration>, overwrite: bool, ) -> Result<()> { let mut tbl = self; let mut latest: Arc<dyn Table>; let mut retry_times = 0; // The initial retry delay in millisecond. By default, it is 5 ms. let init_delay = OCC_DEFAULT_BACKOFF_INIT_DELAY_MS; // The maximum back off delay in millisecond, once the retry interval reaches this value, it stops increasing. // By default, it is 20 seconds. let max_delay = OCC_DEFAULT_BACKOFF_MAX_DELAY_MS; // The maximum elapsed time after the occ starts, beyond which there will be no more retries. // By default, it is 2 minutes let max_elapsed = max_retry_elapsed.unwrap_or(OCC_DEFAULT_BACKOFF_MAX_ELAPSED_MS); // TODO(xuanwo): move to backon instead. // // To simplify the settings, using fixed common values for randomization_factor and multiplier let mut backoff = ExponentialBackoffBuilder::new() .with_initial_interval(init_delay) .with_max_interval(max_delay) .with_randomization_factor(0.5) .with_multiplier(2.0) .with_max_elapsed_time(Some(max_elapsed)) .build(); let transient = self.transient(); loop { match tbl .try_commit(ctx.clone(), &operation_log, &copied_files, overwrite) .await { Ok(_) => { break { if transient { // Removes historical data, if table is transient warn!( "transient table detected, purging historical data. ({})", tbl.table_info.ident ); let latest = tbl.refresh(ctx.as_ref()).await?; tbl = FuseTable::try_from_table(latest.as_ref())?; let keep_last_snapshot = true; if let Err(e) = tbl.do_purge(&ctx, keep_last_snapshot).await { // Errors of GC, if any, are ignored, since GC task can be picked up warn!( "GC of transient table not success (this is not a permanent error). the error : {}", e ); } else { info!("GC of transient table done"); } } Ok(()) }; } Err(e) if self::utils::is_error_recoverable(&e, transient) => { match backoff.next_backoff() { Some(d) => { let name = tbl.table_info.name.clone(); debug!( "got error TableVersionMismatched, tx will be retried {} ms later. table name {}, identity {}", d.as_millis(), name.as_str(), tbl.table_info.ident ); common_base::base::tokio::time::sleep(d).await; latest = tbl.refresh(ctx.as_ref()).await?; tbl = FuseTable::try_from_table(latest.as_ref())?; retry_times += 1; continue; } None => { // Commit not fulfilled. try to abort the operations. // if it is safe to do so. if no_side_effects_in_meta_store(&e) { // if we are sure that table state inside metastore has not been // modified by this operation, abort this operation. info!("aborting operations"); let _ = utils::abort_operations(self.get_operator(), operation_log) .await; } break Err(ErrorCode::OCCRetryFailure(format!( "can not fulfill the tx after retries({} times, {} ms), aborted. table name {}, identity {}", retry_times, Instant::now() .duration_since(backoff.start_time) .as_millis(), tbl.table_info.name.as_str(), tbl.table_info.ident, ))); } } } Err(e) => { // we are not sure about if the table state has been modified or not, just propagate the error // and return, without aborting anything. break Err(e); } } } } #[inline] pub async fn try_commit<'a>( &'a self, ctx: Arc<dyn TableContext>, operation_log: &'a TableOperationLog, copied_files: &Option<UpsertTableCopiedFileReq>, overwrite: bool, ) -> Result<()> { let prev = self.read_table_snapshot().await?; let prev_version = self.snapshot_format_version().await?; let prev_timestamp = prev.as_ref().and_then(|v| v.timestamp); let prev_statistics_location = prev .as_ref() .and_then(|v| v.table_statistics_location.clone()); let schema = self.table_info.meta.schema.as_ref().clone(); let (segments, summary) = Self::merge_append_operations(operation_log)?; let progress_values = ProgressValues { rows: summary.row_count as usize, bytes: summary.uncompressed_byte_size as usize, }; ctx.get_write_progress().incr(&progress_values); let segments = segments .into_iter() .map(|loc| (loc, SegmentInfo::VERSION)) .collect(); let new_snapshot = if overwrite { TableSnapshot::new( Uuid::new_v4(), &prev_timestamp, prev.as_ref().map(|v| (v.snapshot_id, prev_version)), schema, summary, segments, self.cluster_key_meta.clone(), prev_statistics_location, ) } else { Self::merge_table_operations( self.table_info.meta.schema.as_ref(), ctx.clone(), prev, prev_version, segments, summary, self.cluster_key_meta.clone(), )? }; let mut new_table_meta = self.get_table_info().meta.clone(); // update statistics new_table_meta.statistics = TableStatistics { number_of_rows: new_snapshot.summary.row_count, data_bytes: new_snapshot.summary.uncompressed_byte_size, compressed_data_bytes: new_snapshot.summary.compressed_byte_size, index_data_bytes: new_snapshot.summary.index_size, }; FuseTable::commit_to_meta_server( ctx.as_ref(), &self.table_info, &self.meta_location_generator, new_snapshot, None, copied_files, &self.operator, ) .await } fn merge_table_operations( schema: &TableSchema, ctx: Arc<dyn TableContext>, previous: Option<Arc<TableSnapshot>>, prev_version: u64, mut new_segments: Vec<Location>, statistics: Statistics, cluster_key_meta: Option<ClusterKey>, ) -> Result<TableSnapshot> { // 1. merge stats with previous snapshot, if any let stats = if let Some(snapshot) = &previous { let mut summary = snapshot.summary.clone(); let mut fill_default_values = false; // check if need to fill default value in statistics for column_id in statistics.col_stats.keys() { if !summary.col_stats.contains_key(column_id) { fill_default_values = true; break; } } if fill_default_values { let mut default_values = Vec::with_capacity(schema.num_fields()); for field in schema.fields() { default_values.push(field_default_value(ctx.clone(), field)?); } let leaf_default_values = schema.field_leaf_default_values(&default_values); leaf_default_values .iter() .for_each(|(col_id, default_value)| { if !summary.col_stats.contains_key(col_id) { let (null_count, distinct_of_values) = if default_value.is_null() { (summary.row_count, Some(0)) } else { (0, Some(1)) }; let col_stat = ColumnStatistics { min: default_value.to_owned(), max: default_value.to_owned(), null_count, in_memory_size: 0, distinct_of_values, }; summary.col_stats.insert(*col_id, col_stat); } }); } merge_statistics(&statistics, &summary)? } else { statistics }; let prev_snapshot_id = previous.as_ref().map(|v| (v.snapshot_id, prev_version)); let prev_snapshot_timestamp = previous.as_ref().and_then(|v| v.timestamp); let prev_statistics_location = previous .as_ref() .and_then(|v| v.table_statistics_location.clone()); // 2. merge segment locations with previous snapshot, if any if let Some(snapshot) = &previous { let mut segments = snapshot.segments.clone(); new_segments.append(&mut segments) }; let new_snapshot = TableSnapshot::new( Uuid::new_v4(), &prev_snapshot_timestamp, prev_snapshot_id, schema.clone(), stats, new_segments, cluster_key_meta, prev_statistics_location, ); Ok(new_snapshot) } pub async fn commit_to_meta_server( ctx: &dyn TableContext, table_info: &TableInfo, location_generator: &TableMetaLocationGenerator, snapshot: TableSnapshot, table_statistics: Option<TableSnapshotStatistics>, copied_files: &Option<UpsertTableCopiedFileReq>, operator: &Operator, ) -> Result<()> { let snapshot_location = location_generator .snapshot_location_from_uuid(&snapshot.snapshot_id, snapshot.format_version())?; let need_to_save_statistics = snapshot.table_statistics_location.is_some() && table_statistics.is_some(); // 1. write down snapshot snapshot.write_meta(operator, &snapshot_location).await?; if need_to_save_statistics { table_statistics .clone() .unwrap() .write_meta( operator, &snapshot.table_statistics_location.clone().unwrap(), ) .await?; } // 2. prepare table meta let mut new_table_meta = table_info.meta.clone(); // 2.1 set new snapshot location new_table_meta.options.insert( OPT_KEY_SNAPSHOT_LOCATION.to_owned(), snapshot_location.clone(), ); // remove legacy options utils::remove_legacy_options(&mut new_table_meta.options); // 2.2 setup table statistics let stats = &snapshot.summary; // update statistics new_table_meta.statistics = TableStatistics { number_of_rows: stats.row_count, data_bytes: stats.uncompressed_byte_size, compressed_data_bytes: stats.compressed_byte_size, index_data_bytes: stats.index_size, }; // 3. prepare the request let catalog = ctx.get_catalog(&table_info.meta.catalog)?; let table_id = table_info.ident.table_id; let table_version = table_info.ident.seq; let req = UpdateTableMetaReq { table_id, seq: MatchSeq::Exact(table_version), new_table_meta, copied_files: copied_files.clone(), }; // 3. let's roll let reply = catalog.update_table_meta(table_info, req).await; match reply { Ok(_) => { // upsert snapshot statistics cache if let Some(snapshot_statistics) = table_statistics { if let Some(location) = &snapshot.table_statistics_location { TableSnapshotStatistics::cache() .put(location.clone(), Arc::new(snapshot_statistics)); } } TableSnapshot::cache().put(snapshot_location.clone(), Arc::new(snapshot)); // try keep a hit file of last snapshot Self::write_last_snapshot_hint(operator, location_generator, snapshot_location) .await; Ok(()) } Err(e) => { // commit snapshot to meta server failed. // figure out if the un-committed snapshot is safe to be removed. if no_side_effects_in_meta_store(&e) { // currently, only in this case (TableVersionMismatched), we are SURE about // that the table state insides meta store has NOT been changed. info!( "removing uncommitted table snapshot at location {}, of table {}, {}", snapshot_location, table_info.desc, table_info.ident ); let _ = operator.delete(&snapshot_location).await; if need_to_save_statistics { let _ = operator .delete(&snapshot.table_statistics_location.unwrap()) .await; } } Err(e) } } } pub fn merge_append_operations( append_log_entries: &[AppendOperationLogEntry], ) -> Result<(Vec<String>, Statistics)> { let iter = append_log_entries .iter() .map(|entry| (&entry.segment_location, entry.segment_info.as_ref())); FuseTable::merge_segments(iter) } pub fn merge_segments<'a, T>( mut segments: impl Iterator<Item = (&'a T, &'a SegmentInfo)>, ) -> Result<(Vec<T>, Statistics)> where T: Clone + 'a { let len_hint = segments .size_hint() .1 .unwrap_or_else(|| segments.size_hint().0); let (s, seg_locs) = segments.try_fold( (Statistics::default(), Vec::with_capacity(len_hint)), |(mut acc, mut seg_acc), (location, segment_info)| { let stats = &segment_info.summary; acc.row_count += stats.row_count; acc.block_count += stats.block_count; acc.uncompressed_byte_size += stats.uncompressed_byte_size; acc.compressed_byte_size += stats.compressed_byte_size; acc.index_size = stats.index_size; acc.col_stats = if acc.col_stats.is_empty() { stats.col_stats.clone() } else { statistics::reduce_block_statistics(&[&acc.col_stats, &stats.col_stats])? }; seg_acc.push(location.clone()); Ok::<_, ErrorCode>((acc, seg_acc)) }, )?; Ok((seg_locs, s)) } // Left a hint file which indicates the location of the latest snapshot pub async fn write_last_snapshot_hint( operator: &Operator, location_generator: &TableMetaLocationGenerator, last_snapshot_path: String, ) { // Just try our best to write down the hint file of last snapshot // - will retry in the case of temporary failure // but // - errors are ignored if writing is eventually failed // - errors (if any) will not be propagated to caller // - "data race" ignored // if multiple different versions of hints are written concurrently // it is NOT guaranteed that the latest version will be kept let hint_path = location_generator.gen_last_snapshot_hint_location(); let last_snapshot_path = { let operator_meta_data = operator.info(); let storage_prefix = operator_meta_data.root(); format!("{}{}", storage_prefix, last_snapshot_path) }; operator .write(&hint_path, last_snapshot_path) .await .unwrap_or_else(|e| { warn!("write last snapshot hint failure. {}", e); }); } // TODO refactor, it is called by segment compaction and re-cluster now pub async fn commit_mutation( &self, ctx: &Arc<dyn TableContext>, base_snapshot: Arc<TableSnapshot>, base_segments: Vec<Location>, base_summary: Statistics, abort_operation: AbortOperation, ) -> Result<()> { let mut retries = 0; let mut latest_snapshot = base_snapshot.clone(); let mut latest_table_info = &self.table_info; // holding the reference of latest table during retries let mut latest_table_ref: Arc<dyn Table>; // potentially concurrently appended segments, init it to empty let mut concurrently_appended_segment_locations: &[Location] = &[]; // Status { let status = "mutation: begin try to commit"; ctx.set_status_info(status); info!(status); } while retries < MAX_RETRIES { let mut snapshot_tobe_committed = TableSnapshot::from_previous(latest_snapshot.as_ref()); let schema = self.schema(); let (segments_tobe_committed, statistics_tobe_committed) = Self::merge_with_base( ctx.clone(), self.operator.clone(), &base_segments, &base_summary, concurrently_appended_segment_locations, schema, ) .await?; snapshot_tobe_committed.segments = segments_tobe_committed; snapshot_tobe_committed.summary = statistics_tobe_committed; match Self::commit_to_meta_server( ctx.as_ref(), latest_table_info, &self.meta_location_generator, snapshot_tobe_committed, None, &None, &self.operator, ) .await { Err(e) if e.code() == ErrorCode::TABLE_VERSION_MISMATCHED => { latest_table_ref = self.refresh(ctx.as_ref()).await?; let latest_fuse_table = FuseTable::try_from_table(latest_table_ref.as_ref())?; latest_snapshot = latest_fuse_table .read_table_snapshot() .await? .ok_or_else(|| { ErrorCode::Internal( "mutation meets empty snapshot during conflict reconciliation", ) })?; latest_table_info = &latest_fuse_table.table_info; // Check if there is only insertion during the operation. match MutatorConflictDetector::detect_conflicts( base_snapshot.as_ref(), latest_snapshot.as_ref(), ) { Conflict::Unresolvable => { abort_operation .abort(ctx.clone(), self.operator.clone()) .await?; metrics_inc_commit_mutation_unresolvable_conflict(); return Err(ErrorCode::StorageOther( "mutation conflicts, concurrent mutation detected while committing segment compaction operation", )); } Conflict::ResolvableAppend(range_of_newly_append) => { info!("resolvable conflicts detected"); metrics_inc_commit_mutation_resolvable_conflict(); concurrently_appended_segment_locations = &latest_snapshot.segments[range_of_newly_append]; } } retries += 1; metrics_inc_commit_mutation_retry(); } Err(e) => { // we are not sure about if the table state has been modified or not, just propagate the error // and return, without aborting anything. return Err(e); } Ok(_) => { return { metrics_inc_commit_mutation_success(); Ok(()) }; } } } // Commit not fulfilled. try to abort the operations. // // Note that, here the last error we have seen is TableVersionMismatched, // otherwise we should have been returned, thus it is safe to abort the operation here. abort_operation .abort(ctx.clone(), self.operator.clone()) .await?; Err(ErrorCode::StorageOther(format!( "commit mutation failed after {} retries", retries ))) } async fn merge_with_base( ctx: Arc<dyn TableContext>, operator: Operator, base_segments: &[Location], base_summary: &Statistics, concurrently_appended_segment_locations: &[Location], schema: TableSchemaRef, ) -> Result<(Vec<Location>, Statistics)> { if concurrently_appended_segment_locations.is_empty() { Ok((base_segments.to_owned(), base_summary.clone())) } else { // place the concurrently appended segments at the head of segment list let new_segments = concurrently_appended_segment_locations .iter() .chain(base_segments.iter()) .cloned() .collect(); let fuse_segment_io = SegmentsIO::create(ctx, operator, schema); let concurrent_appended_segment_infos = fuse_segment_io .read_segments(concurrently_appended_segment_locations) .await?; let mut new_statistics = base_summary.clone(); for result in concurrent_appended_segment_infos.into_iter() { let concurrent_appended_segment = result?; new_statistics = merge_statistics(&new_statistics, &concurrent_appended_segment.summary)?; } Ok((new_segments, new_statistics)) } } } pub enum Conflict { Unresolvable, // resolvable conflicts with append only operation // the range embedded is the range of segments that are appended in the latest snapshot ResolvableAppend(Range<usize>), } // wraps a namespace, to clarify the who is detecting conflict pub struct MutatorConflictDetector; impl MutatorConflictDetector { // detects conflicts, as a mutator, working on the base snapshot, with latest snapshot pub fn detect_conflicts(base: &TableSnapshot, latest: &TableSnapshot) -> Conflict { let base_segments = &base.segments; let latest_segments = &latest.segments; let base_segments_len = base_segments.len(); let latest_segments_len = latest_segments.len(); if latest_segments_len >= base_segments_len && base_segments[0..base_segments_len] == latest_segments[(latest_segments_len - base_segments_len)..latest_segments_len] { Conflict::ResolvableAppend(0..(latest_segments_len - base_segments_len)) } else { Conflict::Unresolvable } } } mod utils { use std::collections::BTreeMap; use storages_common_table_meta::table::OPT_KEY_LEGACY_SNAPSHOT_LOC; use super::*; use crate::metrics::metrics_inc_commit_mutation_aborts; #[inline] pub async fn abort_operations( operator: Operator, operation_log: TableOperationLog, ) -> Result<()> { metrics_inc_commit_mutation_aborts(); for entry in operation_log { for block in &entry.segment_info.blocks { let block_location = &block.location.0; // if deletion operation failed (after DAL retried) // we just left them there, and let the "major GC" collect them let _ = operator.delete(block_location).await; if let Some(index) = &block.bloom_filter_index_location { let _ = operator.delete(&index.0).await; } } let _ = operator.delete(&entry.segment_location).await; } Ok(()) } #[inline] pub fn is_error_recoverable(e: &ErrorCode, is_table_transient: bool) -> bool { let code = e.code(); code == ErrorCode::TABLE_VERSION_MISMATCHED || (is_table_transient && code == ErrorCode::STORAGE_NOT_FOUND) } #[inline] pub fn no_side_effects_in_meta_store(e: &ErrorCode) -> bool { // currently, the only error that we know, which indicates there are no side effects // is TABLE_VERSION_MISMATCHED e.code() == ErrorCode::TABLE_VERSION_MISMATCHED } // check if there are any fuse table legacy options pub fn remove_legacy_options(table_options: &mut BTreeMap<String, String>) { table_options.remove(OPT_KEY_LEGACY_SNAPSHOT_LOC); } }
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! 8 Planets of the Solar System mod VSOPD_87; pub mod earth; pub mod mars; pub mod jupiter; pub mod saturn; use angle; use coords; use time; /// Represents a planet pub enum Planet { /// Mercury *Helped with testing General Relativity* Mercury, /// Venus **Climate change was here** Venus, /// Earth *Pale blue dot, right?* Earth, /// Mars *Panspermia sounds nice* Mars, /// Jupiter *Oh, Europa* Jupiter, /// Saturn *62 moons, and some moonlets* Saturn, /// Uranus *Remember King George?* Uranus, /// Neptune *Oceans of liquid diamond (probably)* Neptune, } /** Computes the illuminated fraction of a planet's disk from it's phase angle # Returns * `illum_frac`: Illuminated fraction of the planet's disk # Arguments * `i`: Phase angle of the planet *| in radians* **/ #[inline] pub fn illum_frac_frm_phase_angl(i: f64) -> f64 { (1.0 + i.cos()) / 2.0 } /** Computes the illuminated fraction of a planet's disk from it's distance to the Sun and Earth # Returns * `illum_frac`: Illuminated fraction of the planet's disk # Arguments * `r` : Planet-Sun distance *| in AU* * `delta`: Planet-Earth distance *| in AU* * `R` : Sun-Earth distance *| in AU* **/ #[inline] pub fn illum_frac_frm_dist(r: f64, delta: f64, R: f64) -> f64 { let x = r + delta; (x*x - R*R) / (4.0 * r * delta) } /** Computes a planet's phase angle # Returns * `phase_angl`: Phase angle of the planet *| in radians* # Arguments * `r` : Planet-Sun distance *| in AU* * `delta`: Planet-Earth distance *| in AU* * `R` : Sun-Earth distance *| in AU* **/ #[inline] pub fn phase_angl(r: f64, delta: f64, R: f64) -> f64 { (r*r + delta*delta - R*R) / (2.0 * r * delta) } /** Computes the position angle of the bright limb of a planet # Returns * `pos_angl_of_bright_limb`: The position angle of the midpoint of the illuminated limb of a planet *| in radians* # Arguments * `sun_eq_point` : Equatorial point of the Sun *| in radians* * `planet_eq_point`: Equatorial point of the planet *| in radians* **/ pub fn pos_angle_of_bright_limb ( sun_eq_point : coords::EqPoint, planet_eq_point : coords::EqPoint ) -> f64 { let a = sun_eq_point.dec.cos(); let n = a * (sun_eq_point.asc - planet_eq_point.asc).sin(); let d = sun_eq_point.dec.sin() * planet_eq_point.dec.cos() - planet_eq_point.dec.sin() * (sun_eq_point.asc - planet_eq_point.asc).cos() * a; n.atan2(d) } /** Computes a planet's equatorial semidiameter # Returns * `semidiameter`: Equatorial semidiameter *| in radians* # Arguments * `planet` : The [Planet](./enum.Planet.html) * `planet_earth_dist`: Planet-Earth distance *| in AU* **/ pub fn semidiameter<'a> ( planet : &Planet, planet_earth_dist : f64 ) -> Result<f64, &'a str> { let s = match *planet { Planet::Mercury => angle::deg_frm_dms(0, 0, 3.360).to_radians(), Planet::Venus => angle::deg_frm_dms(0, 0, 8.410).to_radians(), Planet::Mars => angle::deg_frm_dms(0, 0, 4.680).to_radians(), Planet::Uranus => angle::deg_frm_dms(0, 0, 35.02).to_radians(), Planet::Neptune => angle::deg_frm_dms(0, 0, 33.50).to_radians(), Planet::Jupiter => jupiter::eq_semidiameter(1.0), Planet::Saturn => saturn::eq_semidiameter(1.0), Planet::Earth => { return Err("Planet::Earth was passed to the function planet::semidiameter()"); } }; Ok( s / planet_earth_dist ) } /** Computes a planet's orbital elements, referred to the mean equinox of the date # Returns `(L, a, e, i, omega, pi, M, w)` * `L`: Mean longitude *| in radians* * `a`: Semimajor axis of the orbit *| in AU* * `e`: Eccentricity of the orbit * `i`: Inclination of the plane of the orbit with the plane of the Earth's ecliptic *| in radians* * `omega`: Longitude of the ascending node *| in radians*. An undefined value is returned for `Planet::Earth`. * `pi`: Longitude of the perihelion *| in radians* * `M`: Mean anomaly *| in radians* * `w`: Argument of the perihelion *| in radians*. An undefined value is returned for `Planet::Earth`. # Arguments * `planet`: Any variant of [Planet](./enum.Planet.html) * `JD` : Julian (Ephemeris) day **/ pub fn orb_elements(planet: &Planet, JD: f64) -> (f64, f64, f64, f64, f64, f64, f64, f64) { let T = time::julian_cent(JD); let TT = T * T; let TTT = TT * T; let L; let a; let e; let i; let omega; let pi; match planet { &Planet::Mercury => { L = 252.250906 + 149474.0722491*T + 0.0003035*TT + 0.000000018*TTT; a = 0.038709831; e = 0.20563175 + 0.000020407*T - 0.0000000283*TT + 0.00000000018*TTT; i = 7.004986 + 0.0018215*T - 0.0000181*TT + 0.000000056*TTT; omega = 48.330893 + 1.1861883*T + 0.00017542*TT + 0.000000215*TTT; pi = 77.456119 + 1.5564776*T + 0.00029544*TT + 0.000000009*TTT; }, &Planet::Venus => { L = 181.979801 + 58519.2130302*T + 0.00031014*TT + 0.000000015*TTT; a = 0.72332982; e = 0.00677192 - 0.000047765*T + 0.0000000981*TTT + 0.00000000046*TTT; i = 3.394662 + 0.0010037*T - 0.00000088*TT - 0.000000007*TTT; omega = 76.67992 + 0.9011206*T + 0.00040618*TT - 0.000000093*TTT; pi = 131.563703 + 1.4022288*T - 0.00107618*TT - 0.000005678*TTT; }, &Planet::Earth => { L = 100.466457 + 36000.7698278*T + 0.00030322*TT + 0.00000002*TTT; a = 1.000001018; e = 0.01670863 - 0.000042037*T - 0.0000001267*TTT + 0.00000000014*TTT; i = 0.0; pi = 102.937348 + 1.7195366*T + 0.00045688*TT - 0.000000018*TTT; omega = 0.0 }, &Planet::Mars => { L = 355.433 + 19141.6964471*T + 0.00031052*TT + 0.000000016*TTT; a = 1.523679342; e = 0.09340065 + 0.000090484*T - 0.0000000806*TTT - 0.00000000025*TTT; i = 1.849726 - 0.0006011*T + 0.00001276*TT - 0.000000007*TTT; omega = 49.558093 + 0.7720959*T + 0.00001557*TT - 0.000002267*TTT; pi = 336.060234 + 1.8410449*T + 0.00013477*TT + 0.000000536*TTT; }, &Planet::Jupiter => { L = 34.351519 + 3036.3027748*T + 0.0002233*TT + 0.000000037*TTT; a = 5.202603209 + 0.0000001913*T; e = 0.04849793 + 0.000163225*T - 0.0000004714*TTT - 0.00000000201*TTT; i = 1.303267 - 0.0054965*T + 0.00000466*TT - 0.000000002*TTT; omega = 100.464407 + 1.0209774*T + 0.00040315*TT + 0.000000404*TTT; pi = 14.331207 + 1.6126352*T + 0.00103042*TT - 0.000004464*TTT; }, &Planet::Saturn => { L = 50.077444 + 1223.5110686*T + 0.00051908*TT - 0.00000003*TTT; a = 9.554909192 - 0.0000021390*T + 0.000000004*TT; e = 0.05554814 - 0.000346641*T - 0.0000006436*TTT + 0.0000000034*TTT; i = 2.488879 - 0.0037362*T - 0.00001519*TT + 0.000000087*TTT; omega = 113.665503 + 0.877088*T - 0.00012176*TT - 0.000002249*TTT; pi = 93.057237 + 1.9637613*T + 0.00083753*TT + 0.000004928*TTT; }, &Planet::Uranus => { L = 314.055005 + 429.8640561*T + 0.0003039*TT - 0.000000026*TTT; a = 19.218446062 - 0.0000000372*T + 0.00000000098*TT; e = 0.04638122 - 0.000027293*T + 0.0000000789*TTT + 0.00000000024*TTT; i = 0.773197 + 0.0007744*T + 0.00003749*TT - 0.000000092*TTT; omega = 74.005957 + 0.5211278*T + 0.00133947*TT + 0.000018484*TTT; pi = 173.005291 + 1.486379*T + 0.00021406*TT + 0.000000434*TTT; }, &Planet::Neptune => { L = 304.348665 + 219.8833092*T + 0.00030882*TT + 0.000000018*TTT; a = 30.110386869 - 0.0000001663*T + 0.00000000069*TT; e = 0.00945575 + 0.000006033*T - 0.00000000005*TTT; i = 1.769953 - 0.0093082*T - 0.00000708*TT + 0.000000027*TTT; omega = 131.784057 + 1.1022039*T + 0.00025952*TT - 0.000000637*TTT; pi = 48.120276 + 1.4262957*T + 0.00038434*TT + 0.00000002*TTT; }, }; ( angle::limit_to_360(L).to_radians(), a, e, angle::limit_to_360(i).to_radians(), angle::limit_to_360(omega).to_radians(), angle::limit_to_360(pi).to_radians(), angle::limit_to_360(L - pi).to_radians(), angle::limit_to_360(pi - omega).to_radians() ) } /** Computes a planet's heliocentric coordinates, referred to the mean equinox of the date # Returns `(long, lat, rad_vec)` * `long` : Heliocentric longitude *| in radians* * `lat` : Heliocentric latitude *| in radians* * `rad_vec`: Heliocentric radius vector *| in AU* # Arguments * `planet`: Any variant of [Planet](./enum.Planet.html) * `JD` : Julian (Ephemeris) day **/ pub fn heliocent_coords(planet: &Planet, JD: f64) -> (f64, f64, f64) { let VSOPD87_Terms = match planet { &Planet::Mercury => VSOPD_87::mercury::terms(), &Planet::Venus => VSOPD_87::venus::terms(), &Planet::Earth => VSOPD_87::earth::terms(), &Planet::Mars => VSOPD_87::mars::terms(), &Planet::Jupiter => VSOPD_87::jupiter::terms(), &Planet::Saturn => VSOPD_87::saturn::terms(), &Planet::Uranus => VSOPD_87::uranus::terms(), &Planet::Neptune => VSOPD_87::neptune::terms(), }; let mut L = 0.0; let mut B = 0.0; let mut R = 0.0; let JM = time::julian_mill(JD); let mut n: u8 = 1; // L, then B, then R for i in VSOPD87_Terms.iter() { // L or B or R let mut T = 1.0; let mut y = 0.0; for j in i.iter() { // T or T**2 or T**3 or ... for k in j.iter() { // add [A * cos(B + C*T)] y += k[0] * (k[1] + k[2]*JM).cos(); } if n == 1 { L += y * T; } else if n == 2 { B += y * T; } else if n == 3 { R += y * T; } y = 0.0; T *= JM; } n += 1; } L = angle::limit_to_two_PI(L); B = angle::limit_to_two_PI(B); (L, B, R) } #[inline(always)] fn light_time(dist: f64) -> f64 { 0.0057755183 * dist } /** Computes a planet's geocentric, geometric ecliptic position, uncorrected for light-time # Returns `(ecl_long, ecl_lat, rad_vec, light_time)` * `ecl_long`: Geometric longitude of the planet *| in radians* * `ecl_lat`: Geometric latitude of the planet *| in radians* * `rad_vec`: Geometric radius vector of the planet *| in AU* * `light_time`: Time taken by light to travel to the Earth from the planet's current position, in days of dynamical time The coordinates returned here refer to the true position of the planet at the time of interest, and therefore are not corrected for the effect of light-time. # Arguments * `L0`: Heliocentric longitude of the Earth *| in radians* * `B0`: Heliocentric latitude of the Earth *| in radians* * `R0`: Heliocentric radius vector of the Earth *| in radians* * `L` : Heliocentric longitude of the planet *| in radians* * `B` : Heliocentric latitude of the planet *| in radians* * `R` : Heliocentric radius vector of the planet *| in radians* **/ pub fn geocent_geomet_ecl_coords ( L0 : f64, B0 : f64, R0 : f64, L : f64, B : f64, R : f64 ) -> (f64, f64, f64, f64) { let (x, y, z) = geocent_ecl_rect_coords(L0, B0, R0, L, B, R); let (lambda, beta) = ecl_coords_frm_ecl_rect_coords(x, y, z); let planet_earth_dist = dist_frm_ecl_rect_coords(x, y, z); let light_time = light_time(planet_earth_dist); (lambda, beta, planet_earth_dist, light_time) } /** Computes a planet's geocentric ecliptic rectangular coordinates from it's heliocentric position # Returns `(X, Y, Z)` # Arguments * `L0`: Heliocentric longitude of the Earth *| in radians* * `B0`: Heliocentric latitude of the Earth *| in radians* * `R0`: Heliocentric radius vector of the Earth *| in radians* * `L` : Heliocentric longitude of the planet *| in radians* * `B` : Heliocentric latitude of the planet *| in radians* * `R` : Heliocentric radius vector of the planet *| in radians* **/ fn geocent_ecl_rect_coords ( L0 : f64, B0 : f64, R0 : f64, L : f64, B : f64, R : f64 ) -> (f64, f64, f64) { let x = R*B.cos()*L.cos() - R0*B0.cos()*L0.cos(); let y = R*B.cos()*L.sin() - R0*B0.cos()*L0.sin(); let z = R*B.sin() - R0*B0.sin(); (x, y, z) } /** Computes a planet's ecliptic coordinates, from it's geocentric ecliptic rectangular coordinates # Returns * `ecl_long`: Ecliptic longitude of the planet *| in radians* * `ecl_lat` : Ecliptic latitude of the planet *| in radians* # Arguments * `X` * `Y` * `Z` **/ #[inline] fn ecl_coords_frm_ecl_rect_coords(x: f64, y: f64, z: f64) -> (f64, f64) { ( y.atan2(x), z.atan2((x*x + y*y).sqrt()) ) } /** Computes a planet's distance to Earth, from it's geocentric ecliptic rectangular coordinates # Returns * `planet_earth_dist`: Planet-Earth distance *| in AU* # Arguments * `X` * `Y` * `Z` **/ #[inline] fn dist_frm_ecl_rect_coords(x: f64, y: f64, z: f64) -> f64 { (x*x + y*y + z*z).sqrt() } /** Computes a planet's geocentric, apparent ecliptic position, corrected for light-time # Returns `(ecl_long, ecl_lat, rad_vec)` * `planet_ecl_point`: Ecliptic point of the planet *| in radians* * `rad_vec` : Geocentric radius vector of the planet *| in AU* The coordinates returned here refer to the apparent position (from Earth) of the planet at the time of interest by correcting the true coordinates for the effect of light-time. # Arguments * `planet`: Any variant of [Planet](./enum.Planet.html) * `JD` : Julian (Ephemeris) day **/ #[allow(unused_variables)] pub fn geocent_apprnt_ecl_coords(planet: &Planet, JD: f64) -> (coords::EclPoint, f64) { let (L0, B0, R0) = heliocent_coords(&Planet::Earth, JD); let (L1, B1, R1) = heliocent_coords(&planet, JD); let (l1, b1, r1, t) = geocent_geomet_ecl_coords(L0, B0, R0, L1, B1, R1); let (L2, B2, R2) = heliocent_coords(&planet, JD - t); let (l2, b2, r2, t2) = geocent_geomet_ecl_coords(L0, B0, R0, L2, B2, R2); let ecl_point = coords::EclPoint { long:l2, lat: b2 }; (ecl_point, r2) } /** Computes a planet's geocentric ecliptic coordinates converted to the FK5 system # Returns `(ecl_long_FK5, ecl_lat_FK5)` * `ecl_long_FK5`: Ecliptic longitude of the planet, converted to the FK5 system *| in radians* * `ecl_lat_FK5` : Ecliptic latitude of the planet, converted to the FK5 system *| in radians* # Arguments * `JD` : Julian (Ephemeris) day * `ecl_long`: Ecliptic longitude of the planet on `JD` referred to the mean equinox of the date *| in radians* * `ecl_lat` : Ecliptic latitude of the planet on `JD`, referred to the mean equinox of the date *| in radians* **/ pub fn ecl_coords_to_FK5(JD: f64, ecl_long: f64, ecl_lat: f64) -> (f64, f64) { let JC = time::julian_cent(JD); let lambda1 = ecl_long - JC*(1.397 + JC*0.00031).to_radians(); let x = angle::deg_frm_dms(0, 0, 0.03916).to_radians(); let ecl_long_correction = - angle::deg_frm_dms(0, 0, 0.09033).to_radians() + x*(lambda1.cos() + lambda1.sin())*ecl_lat.tan(); ( ecl_long + ecl_long_correction, ecl_lat + x*(lambda1.cos() - lambda1.sin()) ) } pub fn geocent_eq_coords ( X : f64, Y : f64, Z : f64, i : f64, w : f64, sigma : f64, oblq_eclip : f64, v : f64, r : f64 ) -> (f64, f64, f64) { let F = sigma.cos(); let G = sigma.sin() * oblq_eclip.cos(); let H = sigma.sin() * oblq_eclip.sin(); let P = - sigma.sin() * i.cos(); let Q = sigma.cos() * i.cos() * oblq_eclip.cos() - i.sin() * oblq_eclip.sin(); let R = sigma.cos() * i.cos() * oblq_eclip.sin() + i.sin() * oblq_eclip.cos(); let A = F.atan2(P); let B = G.atan2(Q); let C = H.atan2(R); let a = (F*F + P*P).sqrt(); let b = (G*G + Q*Q).sqrt(); let c = (H*H + R*R).sqrt(); let x = r * a * (A + w + v); let y = r * b * (B + w + v); let z = r * c * (C + w + v); let xi = X + x; let nu = Y + y; let et = Z + z; let asc = angle::limit_to_two_PI( nu.atan2(xi) ); let dec = et.atan2( (xi*xi + nu*nu).sqrt() ); let dist = (x*x + y*y + z*z).sqrt(); (asc, dec, light_time(dist)) } pub fn heliocent_coords_frm_orb_elements(i: f64, sigma: f64, w: f64, v: f64, r: f64) -> (f64, f64) { let u = w + v; let x = r * (sigma.cos()*u.cos() - sigma.sin()*u.sin()*i.cos()); let y = r * (sigma.sin()*u.cos() + sigma.cos()*u.sin()*i.cos()); let z = r * i.sin() * u.sin(); (y.atan2(x), z.atan2((x*x + y*y).sqrt())) } /** Computes a planet's apparent magnitude using G. Muller's formulae # Returns * `app_mag`: Apparent magnitude of the planet # Arguments * `planet`: Any variant of [Planet](./enum.Planet.html) * `i` : Phase angle of the planet *| in radians* * `delta` : Planet-Earth distance *| in AU* * `r` : Planet-Sun distance *| in AU* **/ pub fn apprnt_mag_muller<'a> ( planet : &Planet, i : f64, delta : f64, r : f64 ) -> Result<f64, &'a str> { let x = 5.0 * (r*delta).log10(); match *planet { Planet::Mercury => Ok( x + 1.16 + (i - 50.0)*(0.02838 + (i - 50.0)*0.000102) ), Planet::Venus => Ok( x - 4.0 + i*(0.01322 + i*i*0.0000004247) ), Planet::Earth => { return Err("Planet::Earth was passed to the function planet::apprnt_mag_muller()"); }, Planet::Mars => Ok(x - 1.3 + i*0.01486), Planet::Jupiter => Ok(x - 8.93), Planet::Saturn => { return Err("Planet::Saturn was passed to the function planet::apprnt_mag_muller(). Use the function planet::saturn::apprnt_mag_muller() instead."); }, Planet::Uranus => Ok(x - 6.85), Planet::Neptune => Ok(x - 7.05), } } /** Computes a planet's apparent magnitude using the Astronomical Almanac's method adopted in 1984 # Returns * `app_mag`: Apparent magnitude of the planet # Arguments * `planet`: Any variant of [Planet](./enum.Planet.html) * `i` : Phase angle of the planet *| in radians* * `delta` : Planet-Earth distance *| in AU* * `r` : Planet-Sun distance *| in AU* **/ pub fn apprnt_mag_84<'a> ( planet : &Planet, i : f64, delta : f64, r : f64 ) -> Result<f64, &'a str> { let x = 5.0 * (r*delta).log10(); match *planet { Planet::Mercury => Ok( x - 0.42 + i*(0.0380 - i*(0.000273 - i*0.00000200)) ), Planet::Venus => Ok( x - 4.40 + i*(0.0009 + i*(0.000239 - i*0.00000065)) ), Planet::Earth => { return Err("Planet::Earth was passed to the function planet::apprnt_mag_84()"); }, Planet::Mars => Ok( x - 1.52 + i*0.016 ), Planet::Jupiter => Ok( x - 9.4 + i*0.005 ), Planet::Saturn => { return Err("Planet::Saturn was passed to the function planet::apprnt_mag_84(). Use the function planet::saturn::apprnt_mag_84() instead."); }, Planet::Uranus => Ok( x - 7.19 ), Planet::Neptune => Ok( x - 6.87 ), } }
use std::alloc::Layout; use std::borrow::Borrow; use std::env::ArgsOs; use std::mem; use std::path::Path; use std::ptr; use std::sync::OnceLock; use anyhow::anyhow; use firefly_arena::DroplessArena; use firefly_binary::{BinaryFlags, Encoding}; use firefly_rt::term::BinaryData; static ARGV: OnceLock<EnvTable> = OnceLock::new(); /// Returns all arguments this executable was invoked with pub fn argv() -> &'static [&'static BinaryData] { ARGV.get().unwrap().argv.as_slice() } /// Performs one-time initialization of the environment for the current executable. /// This is used to cache the arguments vector as constant binary values. pub fn init(mut argv: ArgsOs) -> anyhow::Result<()> { let mut table = EnvTable::with_capacity(argv.len()); let arg0 = argv.next().unwrap(); let arg0 = arg0.to_string_lossy(); // Allocate a single shared "empty" value for optionals below let empty = unsafe { table.alloc(&[]) }; unsafe { table.insert(arg0.as_bytes()); } // Register `root` flag let current_exe = std::env::current_exe()?; let root = current_exe.parent().unwrap().to_string_lossy(); unsafe { table.insert("-root".as_bytes()); table.insert(root.as_bytes()); } // Register 'progname' flag let arg0 = { let arg0: &str = arg0.borrow(); Path::new(arg0) }; let progname = arg0.file_name().unwrap().to_string_lossy(); unsafe { table.insert("-progname".as_bytes()); table.insert(progname.as_bytes()); } // Register `home` flag if let Some(home) = dirs::home_dir() { unsafe { table.insert("-home".as_bytes()); let home = home.to_string_lossy(); table.insert(home.as_bytes()); } } else { unsafe { table.insert("-home".as_bytes()); table.argv.push(empty); } } for arg in argv { let arg = arg.to_string_lossy(); unsafe { table.insert(arg.as_bytes()); } } ARGV.set(table) .map_err(|_| anyhow!("arguments were already initialized")) .unwrap(); Ok(()) } #[derive(Default)] struct EnvTable { argv: Vec<&'static BinaryData>, arena: DroplessArena, } impl EnvTable { fn with_capacity(size: usize) -> Self { Self { argv: Vec::with_capacity(size), arena: Default::default(), } } unsafe fn insert(&mut self, bytes: &[u8]) { let data = self.alloc(bytes); self.argv.push(data); } unsafe fn alloc(&mut self, bytes: &[u8]) -> &'static BinaryData { // Allocate memory for binary metadata and value let size = bytes.len(); let (layout, value_offset) = Layout::new::<BinaryFlags>() .extend(Layout::from_size_align_unchecked( size, mem::align_of::<u8>(), )) .unwrap(); let layout = layout.pad_to_align(); let ptr = self.arena.alloc_raw(layout); // Write flags let flags_ptr: *mut BinaryFlags = ptr.cast(); flags_ptr.write(BinaryFlags::new_literal(size, Encoding::detect(bytes))); // Write data let bytes_ptr: *mut u8 = (flags_ptr as *mut u8).add(value_offset); ptr::copy_nonoverlapping(bytes.as_ptr(), bytes_ptr, size); // Reify as static reference let data_ptr: *const BinaryData = ptr::from_raw_parts(ptr.cast(), size); &*data_ptr } } unsafe impl Send for EnvTable {} unsafe impl Sync for EnvTable {}
pub fn sub() { println!("math.sub") }
use rand::Rng; use std::io; macro_rules! unwrap_matches { ($e:expr, $p:pat) => { match $e { $p => (), _ => panic!(""), } }; ($e:expr, $p:pat => $body:expr) => { match $e { $p => $body, _ => panic!(""), } }; } mod game_def; fn main() { let input = std::fs::read_to_string("./data.toml").unwrap(); let root = input.parse::<toml::Value>().unwrap(); let game_def = game_def::GameDef::from_toml(&root); for encounter_id in game_def.encounter_tables.keys() { for _ in 0..10 { dbg!(generate_rng_encounter( &game_def, vec![], encounter_id.clone() )); } } } fn menu(text: String, options: Vec<String>) -> usize { loop { println!("{}", text); let mut count: u32 = 0; for option in &options { count += 1; println!("{}. {}", count, option); } let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("Failed to read input."); let input: usize = input.trim().parse().expect("Invalid input."); if input < options.len() { return input; } } } #[derive(Debug)] pub struct Mon { def: String, moves: Vec<String>, lvl: i64, exp: i64, cur_hp: i64, } #[derive(Debug)] pub struct Battle { player_team: Vec<Mon>, active_player_mons: Box<[Option<usize>]>, enemy_team: Vec<Mon>, active_enemy_mons: Box<[Option<usize>]>, } pub fn generate_rng_encounter( game_def: &game_def::GameDef, player_team: Vec<Mon>, encounter_id: String, ) -> Battle { let encounter_table = &game_def.encounter_tables[&encounter_id]; let rng_mon = || { let mon_idx = rand::thread_rng().gen_range(0..encounter_table.mons.len()); let &(min_lvl, max_lvl, ref mon_def_id) = &encounter_table.mons[mon_idx]; let lvl = rand::thread_rng().gen_range(min_lvl..=max_lvl); let mon_def = &game_def.mon_defs[mon_def_id]; let moves = mon_def.moves_at_level(lvl); Mon { def: mon_def_id.clone(), moves, lvl, exp: 0, cur_hp: mon_def.hp, } }; let enemy_team = vec![rng_mon(), rng_mon()]; let active_player_mons = player_team .iter() .enumerate() .map(|(n, _)| Some(n)) .take(2) .collect::<Box<[_]>>(); Battle { player_team, active_player_mons, enemy_team, active_enemy_mons: Box::new([Some(0), Some(1)]), } }
//! Encapsulates work of loading a texture from an image file //! Only ASCII PPMs (P3) are supported in this project. use std::io::BufReader; use web_sys::{WebGl2RenderingContext, WebGlTexture}; use png; pub type TextureId = usize; /// Represents an image texture #[derive(Debug)] pub struct Texture { pub tex: WebGlTexture, pub id: TextureId, } unsafe impl Send for Texture {} impl Texture { /// Load an image from png bytes /// Given a texture ID from the Render System pub fn init_from_image(id: TextureId, png_bytes: &[u8]) -> Self { // Set up the texture let tex = wre_gl!().create_texture(); if tex.is_none() { error_panic!("Invalid WebGl texture"); } wre_gl!().active_texture(WebGl2RenderingContext::TEXTURE0); wre_gl!() .bind_texture(WebGl2RenderingContext::TEXTURE_2D, tex.as_ref()); wre_gl!().tex_parameteri( WebGl2RenderingContext::TEXTURE_2D, WebGl2RenderingContext::TEXTURE_WRAP_S, WebGl2RenderingContext::REPEAT as i32, ); wre_gl!().tex_parameteri( WebGl2RenderingContext::TEXTURE_2D, WebGl2RenderingContext::TEXTURE_WRAP_T, WebGl2RenderingContext::REPEAT as i32, ); wre_gl!().tex_parameteri( WebGl2RenderingContext::TEXTURE_2D, WebGl2RenderingContext::TEXTURE_MIN_FILTER, WebGl2RenderingContext::NEAREST as i32, ); wre_gl!().tex_parameteri( WebGl2RenderingContext::TEXTURE_2D, WebGl2RenderingContext::TEXTURE_MAG_FILTER, WebGl2RenderingContext::NEAREST as i32, ); // Decode the png bytes let reader = BufReader::new(png_bytes); let decoder = png::Decoder::new(reader); let (png_info, mut reader) = decoder.read_info().unwrap_or_else(|err| { error_panic!("Unable to decode png: {:?}", err); }); let mut buf = vec![0; png_info.buffer_size()]; reader.next_frame(&mut buf).unwrap_or_else(|err| { error_panic!("Unable to read png: {:?}", err); }); wre_gl!().pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 1); wre_gl!(). tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_u8_array ( WebGl2RenderingContext::TEXTURE_2D, 0, WebGl2RenderingContext::RGB as i32, png_info.width as i32, png_info.height as i32, 0, WebGl2RenderingContext::RGB, WebGl2RenderingContext::UNSIGNED_BYTE, Some(&buf) ).unwrap_or_else(|err| { error_panic!("Unable to create tex_image_2d: {:?}", err); }); // unsafe { // gl::GenerateMipmap(gl::TEXTURE_2D); // } Texture { tex: tex.unwrap(), id, } } } impl Drop for Texture { fn drop(&mut self) { wre_gl!().delete_texture(Some(&self.tex)); } }
use raytracer::image::png; use raytracer::vec3::Vec3; use raytracer::scene::{Scene, sphere::Sphere, camera::Camera}; use raytracer::ray::material::{ Lambertian , Metallic}; use std::{sync::Arc, error::Error}; use core::f64::consts::PI; fn main() -> Result<(), Box<dyn Error> > { let height: usize = 400; let width: usize = 800; let samples_per_pixel : u64 = 100; let max_depth : u64 = 50; let vfov: f64 = PI/2.0; let aspect: f64 = (width as f64)/(height as f64); let look_from: Vec3 = Vec3(0.0,0.0,0.0); let look_to: Vec3 = Vec3(0.0,0.0,-1.0); let look_up: Vec3 = Vec3(0.0,1.0,0.0); let mut scene = Scene::new(Camera::new(look_from,look_to,look_up,vfov,aspect)); scene.add(Box::new(Sphere::new(Vec3(0.0,0.0,-1.0),0.5, Arc::new(Lambertian::new(Vec3(0.0,0.0,1.0)))))); scene.add(Box::new(Sphere::new(Vec3(0.0,-100.5,-1.0),100.0, Arc::new(Lambertian::new(Vec3(0.8,0.8,0.0)))))); scene.add(Box::new(Sphere::new(Vec3(1.0,0.0,-1.0),0.5, Arc::new(Metallic::new(Vec3(0.8,0.6,0.2),0.0))))); scene.add(Box::new(Sphere::new(Vec3(-1.0,0.0,-1.0),0.5, Arc::new(Metallic::new(Vec3(0.8,0.6,0.8),0.5))))); let image = scene.render(width, height, samples_per_pixel, max_depth); png::write(&image, "test.png")?; Ok(()) }
use gtk::*; use gio::{ApplicationFlags, ApplicationExt, ApplicationExtManual}; use std::{env, sync::{mpsc}}; use log::*; use common::{set_logging_panic_hook, init_simple_logger, start_thread_loop, convert_err}; use gui::build_ui; use message::{CompositeMessage, LogicMessage}; use logic::{LogicState}; use composite::CompositorState; mod message; mod gui; mod logic; mod composite; mod common; fn main() -> Result<(), String> { let path: Option<String> = match env::args().len() { 1 => None, 2 => Some(env::args().nth(1).unwrap()), _ => { println!("USAGE:\nnanomosaic [image]"); return Err(format!("Wrong parameters provided.")); } }; init_simple_logger(); set_logging_panic_hook(); start_application(path) } const APP_NAME: &str = "nanomosaic.gtk"; fn start_application(file_name: Option<String>) -> Result<(), String> { info!("Starting {}", APP_NAME); info!("Input image: {:?}", &file_name); let queue_size = 3; let app = Application::new(APP_NAME, ApplicationFlags::NON_UNIQUE) .expect("Initialization failed..."); let (logic_tx, logic_rx) = mpsc::sync_channel::<Option<LogicMessage>>(queue_size); let (composite_tx, composite_rx) = mpsc::sync_channel::<Option<CompositeMessage>>(queue_size); let state_thread = start_thread_loop(logic_rx, LogicState::new(composite_tx.clone())); let compositor_thread = start_thread_loop(composite_rx, CompositorState::new(logic_tx.clone())); let gui_logic_tx = logic_tx.clone(); let gui_composite_tx = composite_tx.clone(); app.connect_startup(move |app| build_ui( app, file_name.clone(), gui_logic_tx.clone(), gui_composite_tx.clone(), ) ); app.connect_activate(|_| {}); app.run(&vec![]); convert_err(logic_tx.send(None))?; convert_err(state_thread.join())?; debug!("Logic thread finished"); convert_err(composite_tx.send(None))?; convert_err(compositor_thread.join())?; debug!("Compositor thread finished"); Ok(()) }
use actix_files::Files; use actix_web::middleware::Logger; use actix_web::{get, web, App, HttpResponse, HttpServer, Result}; use actix_web_static_files; use listenfd::ListenFd; use log::error; use std::collections::HashMap; use music_box::{MusicLibrary, MusicSource}; // for bundling assents inside the binary with `actix_web_static_files`. include!(concat!(env!("OUT_DIR"), "/generated.rs")); // TODO: implement code passing to music_box // #[get("spotify_code")] // async fn spotify_code() -> HttpResponse { // HttpResponse::Ok().body("Not implemented!") // } #[get("/api/artists")] async fn artists(data: web::Data<AppState>) -> HttpResponse { let library = &data.library; let artists = library .get_artists() .expect("FIXME: need to return proper error HTTP response"); HttpResponse::Ok() .content_type("application/json") .json(artists) } struct AppState { library: MusicLibrary, } fn init_state() -> AppState { let spotify = MusicSource::new_spotify_client() .map_err(|err| { error!( "Got error while trying to initialize Spotify source: {}", err.to_string() ); std::io::Error::new(std::io::ErrorKind::Other, err.to_string()) }) .expect("FIXME: need to return proper error HTTP response"); let library = MusicLibrary::new(vec![spotify]); let state = AppState { library }; state } #[actix_web::main] async fn main() -> std::io::Result<()> { env_logger::init(); let mut listenfd = ListenFd::from_env(); let mut server = HttpServer::new(|| { let generated = generate(); App::new() .wrap(Logger::default()) // Set shared application data .data(init_state()) // API endpoints .service(artists) // Auto-reloaded dev static assets & main page. You can access them // under `http://localhost:8000/dev`. // FIXME: The `index.html` file reloads properly, // but css and js changes are not yet auto-reloaded. .service(Files::new("/dev", "assets/dist/").index_file("index.html")) // Bundled static assets & main page (via actix_web_static_files) .service(actix_web_static_files::ResourceFiles::new("/", generated)) }) .shutdown_timeout(5); server = if let Some(listener) = listenfd.take_tcp_listener(0).unwrap() { server.listen(listener)? } else { server.bind("127.0.0.1:8000")? }; server.run().await }
use rltk::{ColorPair, Point, RGB}; use specs::prelude::*; use crate::{Context, ParticleLifetime, Position, Renderable, RenderAura, RenderBackground}; pub const SHORT_LIFETIME: f32 = 300.; pub const MEDIUM_LIFETIME: f32 = 500.; pub const LONG_LIFETIME: f32 = 700.; pub fn cull_dead_particles(ecs: &mut World, context: &mut Context) { let mut dead_particles: Vec<Entity> = Vec::new(); { let mut particles = ecs.write_storage::<ParticleLifetime>(); let entities = ecs.entities(); for (entity, mut particle) in (&entities, &mut particles).join() { particle.lifetime_ms -= context.rltk.frame_time_ms; if particle.lifetime_ms < 0.0 { dead_particles.push(entity); } } } for dead in dead_particles.iter() { ecs.delete_entity(*dead).expect("Particle will not die"); } } //TODO figure out better naming convention enum ParticleRequestType { Entity { color: ColorPair, glyph: u8, }, Background { bg: RGB, }, Aura { fg: RGB, glyph: u8, }, } pub struct ParticleRequest { position: Point, request_type: ParticleRequestType, lifetime: f32, } pub struct ParticleBuilder { requests: Vec<ParticleRequest> } impl ParticleBuilder { pub fn new() -> ParticleBuilder { ParticleBuilder { requests: Vec::new() } } pub fn request_entity(&mut self, position: Point, lifetime: f32, color: ColorPair, glyph: u8) { self.requests.push(ParticleRequest { position, request_type: ParticleRequestType::Entity { color, glyph, }, lifetime, }); } pub fn request_background(&mut self, position: Point, lifetime: f32, bg: RGB) { self.requests.push(ParticleRequest { position, request_type: ParticleRequestType::Background { bg }, lifetime, }); } pub fn request_aura(&mut self, position: Point, lifetime: f32, fg: RGB, glyph: u8) { self.requests.push(ParticleRequest { position, request_type: ParticleRequestType::Aura { fg, glyph, }, lifetime, }); } } pub struct ParticleSpawnSystem; impl<'a> System<'a> for ParticleSpawnSystem { type SystemData = ( Entities<'a>, WriteStorage<'a, Position>, WriteStorage<'a, Renderable>, WriteStorage<'a, RenderBackground>, WriteStorage<'a, RenderAura>, WriteStorage<'a, ParticleLifetime>, WriteExpect<'a, ParticleBuilder> ); fn run(&mut self, data: Self::SystemData) { let ( entities, mut positions, mut renderables, mut render_backgrounds, mut render_auras, mut particles, mut particle_builder ) = data; for new_particle in particle_builder.requests.iter() { let particle_entity = entities.create(); positions.insert( particle_entity, Position { x: new_particle.position.x, y: new_particle.position.y, }, ).expect("Unable to insert position"); particles.insert( particle_entity, ParticleLifetime { lifetime_ms: new_particle.lifetime }, ).expect("Unable to insert lifetime"); match new_particle.request_type { ParticleRequestType::Entity { color, glyph } => { renderables.insert( particle_entity, Renderable { fg: color.fg, bg: color.bg, glyph, render_order: 0, }, ).expect("Unable to insert renderable"); } ParticleRequestType::Background { bg } => { render_backgrounds.insert( particle_entity, RenderBackground { bg }, ).expect("Unable to insert render background"); } ParticleRequestType::Aura { fg, glyph } => { render_auras.insert( particle_entity, RenderAura { fg, glyph }, ).expect("Unable to insert render background"); } } } particle_builder.requests.clear(); } }
//! Async-graphql integration with Actix-web #![forbid(unsafe_code)] #![allow(clippy::upper_case_acronyms)] #![warn(missing_docs)] mod request; mod subscription; pub use request::{GraphQLBatchRequest, GraphQLRequest, GraphQLResponse}; pub use subscription::GraphQLSubscription;
pub mod model; pub mod conv2d; pub mod dense; pub mod dropout; pub mod maxpooling; pub mod relu; pub mod sigmoid; pub mod softmax;
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to 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. // use std::any::Any; use std::collections::HashSet; use common_exception::ErrorCode; use common_expression::BlockMetaInfo; use common_expression::BlockMetaInfoDowncast; use common_expression::DataBlock; use common_expression::Scalar; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub enum MergeIntoOperation { Delete(DeletionByColumn), None, } pub type UniqueKeyDigest = u128; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct DeletionByColumn { // used in table meta level pruning pub columns_min_max: Vec<(Scalar, Scalar)>, // used in block level pub key_hashes: HashSet<UniqueKeyDigest>, } #[typetag::serde(name = "merge_into_operation_meta")] impl BlockMetaInfo for MergeIntoOperation { fn as_any(&self) -> &dyn Any { self } fn equals(&self, info: &Box<dyn BlockMetaInfo>) -> bool { match info.as_any().downcast_ref::<MergeIntoOperation>() { None => false, Some(other) => self == other, } } fn clone_self(&self) -> Box<dyn BlockMetaInfo> { Box::new(self.clone()) } } impl TryFrom<DataBlock> for MergeIntoOperation { type Error = ErrorCode; fn try_from(value: DataBlock) -> Result<Self, Self::Error> { let meta = value.get_owned_meta().ok_or_else(|| { ErrorCode::Internal( "convert MergeIntoOperation from data block failed, no block meta found", ) })?; MergeIntoOperation::downcast_from(meta).ok_or_else(|| { ErrorCode::Internal( "downcast block meta to MutationIntoOperation failed, type mismatch", ) }) } }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to 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. use std::sync::Arc; use common_exception::ErrorCode; use common_exception::Result; use common_expression::DataBlock; use common_hashtable::HashtableEntryRefLike; use common_hashtable::HashtableLike; use common_pipeline_core::processors::port::InputPort; use common_pipeline_core::processors::port::OutputPort; use common_pipeline_core::processors::processor::ProcessorPtr; use common_pipeline_transforms::processors::transforms::BlockMetaTransform; use common_pipeline_transforms::processors::transforms::BlockMetaTransformer; use crate::pipelines::processors::transforms::aggregator::aggregate_meta::AggregateMeta; use crate::pipelines::processors::transforms::aggregator::estimated_key_size; use crate::pipelines::processors::transforms::group_by::GroupColumnsBuilder; use crate::pipelines::processors::transforms::group_by::HashMethodBounds; use crate::pipelines::processors::transforms::group_by::KeysColumnIter; use crate::pipelines::processors::AggregatorParams; pub struct TransformFinalGroupBy<Method: HashMethodBounds> { method: Method, params: Arc<AggregatorParams>, } impl<Method: HashMethodBounds> TransformFinalGroupBy<Method> { pub fn try_create( input: Arc<InputPort>, output: Arc<OutputPort>, method: Method, params: Arc<AggregatorParams>, ) -> Result<ProcessorPtr> { Ok(ProcessorPtr::create(BlockMetaTransformer::create( input, output, TransformFinalGroupBy::<Method> { method, params }, ))) } } impl<Method> BlockMetaTransform<AggregateMeta<Method, ()>> for TransformFinalGroupBy<Method> where Method: HashMethodBounds { const NAME: &'static str = "TransformFinalGroupBy"; fn transform(&mut self, meta: AggregateMeta<Method, ()>) -> Result<DataBlock> { if let AggregateMeta::Partitioned { bucket, data } = meta { let mut hashtable = self.method.create_hash_table::<()>()?; 'merge_hashtable: for bucket_data in data { match bucket_data { AggregateMeta::Spilled(_) => unreachable!(), AggregateMeta::Spilling(_) => unreachable!(), AggregateMeta::Partitioned { .. } => unreachable!(), AggregateMeta::Serialized(payload) => { debug_assert!(bucket == payload.bucket); let column = payload.get_group_by_column(); let keys_iter = self.method.keys_iter_from_column(column)?; unsafe { for key in keys_iter.iter() { let _ = hashtable.insert_and_entry(key); } if let Some(limit) = self.params.limit { if hashtable.len() >= limit { break 'merge_hashtable; } } } } AggregateMeta::HashTable(payload) => unsafe { debug_assert!(bucket == payload.bucket); for key in payload.cell.hashtable.iter() { let _ = hashtable.insert_and_entry(key.key()); } if let Some(limit) = self.params.limit { if hashtable.len() >= limit { break 'merge_hashtable; } } }, } } let value_size = estimated_key_size(&hashtable); let keys_len = hashtable.len(); let mut group_columns_builder = self.method .group_columns_builder(keys_len, value_size, &self.params); for group_entity in hashtable.iter() { group_columns_builder.append_value(group_entity.key()); } return Ok(DataBlock::new_from_columns(group_columns_builder.finish()?)); } Err(ErrorCode::Internal( "TransformFinalGroupBy only recv AggregateMeta::Partitioned", )) } }
//! Messages that are sent betweeb GUI, logic and worker threads use log::*; use glib::{Sender as GlibSender}; use std::sync::mpsc::SyncSender; use nanocv::{ImgSize, ImgBuf}; use crate::common::log_err; pub type Rgba = [u8; 4]; pub type LogicSender = SyncSender<Option<LogicMessage>>; pub type CompositorSender = SyncSender<Option<CompositeMessage>>; #[derive(Clone)] pub enum LogicMessage { InitGui(GlibSender<GuiMessage>), LoadImage(String), SaveImage(String), ImageResized((ImageId, ImgSize)), MouseDown((u32, f64, f64)), CompositorFinished, ReturnBuffer(ImgBuf<Rgba>), } #[derive(Clone)] pub enum CompositeMessage { InitGui(GlibSender<GuiMessage>), CompositeMosaic((ImgBuf<Rgba>, ImgSize)), SaveMosaic((ImgBuf<Rgba>, String)), } #[derive(Clone)] pub enum GuiMessage { RenderSource(ImgBuf<Rgba>), RenderTarget(ImgBuf<Rgba>), RenderLines(SelectionLines), ShowError(String), } #[derive(Clone, Copy, Debug)] pub enum ImageId { Select, Result } pub trait MessageReceiver<T>{ fn receive(&mut self, message: T) -> Result<(), String>; } pub fn send<T>(sender: &SyncSender<Option<T>>, message: T) { log_err(sender.send(Some(message))); } pub fn send_glib<T>(sender: &Option<GlibSender<T>>, message: T) { match sender { Some(sender) => log_err(sender.send(message)), None => error!("Cannot send message, no sender available."), } } #[derive(Clone, Copy, Debug)] pub struct SelectionLines { pub x1: isize, pub x2: isize, pub y1: isize, pub y2: isize }
#[macro_use] mod common; extern crate libc; use common::util::*; static UTIL_NAME: &'static str = "link"; #[test] fn test_link_existing_file() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_link_existing_file"; let link = "test_link_existing_file_link"; at.touch(file); at.write(file, "foobar"); assert!(at.file_exists(file)); let result = ucmd.args(&[file, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.file_exists(file)); assert!(at.file_exists(link)); assert_eq!(at.read(file), at.read(link)); } #[test] fn test_link_no_circular() { let (at, mut ucmd) = testing(UTIL_NAME); let link = "test_link_no_circular"; let result = ucmd.args(&[link, link]).run(); assert_eq!(result.stderr, "link: error: No such file or directory (os error 2)\n"); assert!(!result.success); assert!(!at.file_exists(link)); } #[test] fn test_link_nonexistent_file() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_link_nonexistent_file"; let link = "test_link_nonexistent_file_link"; let result = ucmd.args(&[file, link]).run(); assert_eq!(result.stderr, "link: error: No such file or directory (os error 2)\n"); assert!(!result.success); assert!(!at.file_exists(file)); assert!(!at.file_exists(link)); }
use crate::hitable_list::HitableList; use crate::material::Material; use crate::vec3::Vec3; use std::rc::Rc; pub struct Ray { pub origin: Vec3, pub direction: Vec3, } impl Ray { pub fn new(origin: Vec3, direction: Vec3) -> Self { Ray { origin, direction } } pub fn color(ray: &Ray, world: &HitableList, depth: i64) -> Vec3 { let mut hit = Hit::new(); if world.hit(ray, 0.001, std::f64::MAX, &mut hit) { let mut scattered = Ray::new(Vec3::zero(), Vec3::zero()); let mut attenuation = Vec3::zero(); let mut clone = hit.clone(); if let Some(material) = hit.material { if depth < 50 && material.scatter(ray, &mut clone, &mut attenuation, &mut scattered) { attenuation * Ray::color(&scattered, world, depth + 1) } else { Vec3::zero() } } else { Vec3::zero() } } else { let unit_direction = ray.direction.norm(); let t = 0.5 * (unit_direction.y() + 1.0); (1.0 - t) * Vec3::one() + t * Vec3(0.5, 0.7, 1.0) } } pub fn point_at(&self, time: f64) -> Vec3 { self.origin + self.direction * time } } #[derive(Clone)] pub struct Hit { pub t: f64, pub point: Vec3, pub normal: Vec3, pub material: Option<Rc<dyn Material>>, } impl Hit { pub fn new() -> Self { Hit { t: 0.0, point: Vec3::zero(), normal: Vec3::zero(), material: None, } } } pub trait Hitable { fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, hit: &mut Hit) -> bool; }
use diesel; use diesel::prelude::*; use diesel::sqlite::SqliteConnection; pub mod schema { infer_schema!("env:DATABASE_URL"); } use self::schema::users; use self::schema::users::dsl::{ users as all_users, id as user_id, username as user_name, activated as user_activated}; #[derive(Debug, Insertable, Queryable)] #[table_name = "users"] pub struct User { pub id: Option<i32>, username: String, password: String, email: String, bio: String, activated: bool, } impl User { pub fn new() -> NewUser { NewUser::default() } pub fn all(conn: &SqliteConnection) -> Vec<User> { all_users.order(users::id.desc()) .load::<User>(conn) .unwrap() } pub fn find_by_name(name: &str, conn: &SqliteConnection) -> Vec<User> { all_users.filter(user_name.eq(name)) .order(users::id.desc()) .load::<User>(conn) .unwrap() } pub fn activated(conn: &SqliteConnection) -> Vec<User> { all_users.filter(user_activated.eq(true)) .order(users::id.desc()) .load::<User>(conn) .unwrap() } pub fn activate(&self, activated: bool, conn: &SqliteConnection) -> bool { diesel::update(all_users.filter(user_id.eq(self.id))) .set(user_activated.eq(activated)) .execute(conn) .is_ok() } pub fn store(&self, conn: &SqliteConnection) -> bool { diesel::insert(self).into(users::table) .execute(conn) .is_ok() } pub fn delete_with_id(id: i32, conn: &SqliteConnection) -> bool { diesel::delete(all_users.find(id)).execute(conn).is_ok() } } #[derive(Clone, Default)] pub struct NewUser { username: Option<String>, password: Option<String>, email: Option<String>, bio: Option<String>, } impl NewUser { pub fn username(&mut self, username: &str) -> &mut Self { self.username = Some(username.into()); self } pub fn password(&mut self, password: &str) -> &mut Self { self.password = Some(password.into()); self } pub fn email(&mut self, email: &str) -> &mut Self { self.email = Some(email.into()); self } pub fn bio(&mut self, bio: &str) -> &mut Self { self.bio = Some(bio.into()); self } pub fn done(&mut self) -> User { self.to_owned().into() } } impl Into<User> for NewUser { fn into(self) -> User { User { id: None, username: self.username.unwrap(), password: self.password.unwrap(), email: self.email.unwrap(), bio: self.bio.unwrap(), activated: false, } } }
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::state::ContractInfo; use cosmwasm_std::{to_binary, Binary, CosmosMsg, HumanAddr, StdResult, Uint128, WasmMsg}; // Instantiating an auction requires: // sell_contract: ContractInfo -- code hash and address of SNIP-20 contract of token for sale // bid_contract: ContractInfo -- code hash and address of SNIP-20 contract of bid token // sell_amount: Uint128 -- the amount you are selling // minimum_bid: Uint128 -- minimum bid you will accept // optional: // description: String -- free-form description of the auction (best to avoid double quotes). // As an example it could be the date the owner will likely finalize the // auction, or a list of other auctions for the same token, etc... #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum InitMsg { CreateAuction { sell_contract: ContractInfo, bid_contract: ContractInfo, sell_amount: Uint128, minimum_bid: Uint128, #[serde(default)] description: Option<String>, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum HandleMsg { // Receive gets called by the token contracts of the auction. If it came from the sale token, // it will consign the sent tokens. If it came from the bid token, it will place a bid. If // any other address tries to call this, it will give an error message that the calling address // is not a token in the auction. // sender: HumanAddr -- address of the token contract calling Receive // from: HumanAddr -- owner of the tokens sent to the auction // amount: Uint128 -- amount of tokens sent // msg: Option<Binary> -- not needed or used by this contract Receive { sender: HumanAddr, from: HumanAddr, amount: Uint128, #[serde(default)] msg: Option<Binary>, }, // RetractBid will retract any active bid the calling address has made and return the tokens that // are held in escrow RetractBid {}, // ViewBid will display the amount of the active bid made by the calling address and time the bid // was placed ViewBid {}, // Finalize will close the auction // only_if_bids: bool -- true if auction creator wants to keep the auction open if there are no // active bids Finalize { only_if_bids: bool, }, // If the auction holds any funds after it has closed (should never happen), this will return those // funds to their owners. Should never be needed, but included in case of unforeseen error ReturnAll {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { // Returns the contract address and TokenInfo of the token(s) to be sold, the contract address // and TokenInfo of the token(s) that would be accepted as bids, the amount of token(s) to be // sold, the minimum bid that will be accepted, an optional description of the auction, the // contract address of the auction, and the status of the auction (Accepting bids: Tokens to be // sold have(not) been consigned; Closed (will also state if there are outstanding funds after // auction closure)) AuctionInfo {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryAnswer { AuctionInfo { sell_token: Token, bid_token: Token, sell_amount: Uint128, minimum_bid: Uint128, #[serde(skip_serializing_if = "Option::is_none")] description: Option<String>, auction_address: HumanAddr, status: String, }, } // Wraps the return of a token_info query on the SNIP-20 contracts #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct TokenQuery { pub token_info: TokenInfo, } // structure of token related data used in the auction_info query #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct Token { pub contract_address: HumanAddr, pub token_info: TokenInfo, } // Speculative format for SNIP-20 Token_info calls. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema, Default)] #[serde(rename_all = "snake_case")] pub struct TokenInfo { pub name: String, pub symbol: String, pub decimals: u8, #[serde(skip_serializing_if = "Option::is_none")] pub total_supply: Option<Uint128>, } #[derive(Serialize, Deserialize, Debug, JsonSchema, PartialEq)] #[serde(rename_all = "snake_case")] pub enum ResponseStatus { Success, Failure, } // Responses from handle functions. #[derive(Serialize, Deserialize, Debug, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum HandleAnswer { Consign { status: ResponseStatus, message: String, #[serde(skip_serializing_if = "Option::is_none")] amount_consigned: Option<Uint128>, #[serde(skip_serializing_if = "Option::is_none")] amount_needed: Option<Uint128>, #[serde(skip_serializing_if = "Option::is_none")] amount_returned: Option<Uint128>, }, Bid { status: ResponseStatus, message: String, #[serde(skip_serializing_if = "Option::is_none")] previous_bid: Option<Uint128>, #[serde(skip_serializing_if = "Option::is_none")] amount_bid: Option<Uint128>, #[serde(skip_serializing_if = "Option::is_none")] amount_returned: Option<Uint128>, }, CloseAuction { status: ResponseStatus, message: String, #[serde(skip_serializing_if = "Option::is_none")] winning_bid: Option<Uint128>, #[serde(skip_serializing_if = "Option::is_none")] amount_returned: Option<Uint128>, }, RetractBid { status: ResponseStatus, message: String, #[serde(skip_serializing_if = "Option::is_none")] amount_returned: Option<Uint128>, }, Status { status: ResponseStatus, message: String, }, } // used to serialize the message to transfer tokens #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct TransferMsg { pub recipient: HumanAddr, pub amount: Uint128, pub padding: Option<String>, } impl TransferMsg { pub fn new(recipient: HumanAddr, amount: Uint128) -> Self { let padding = Some(" ".repeat(40 - amount.to_string().chars().count())); Self { recipient, amount, padding, } } /// serializes the message pub fn into_binary(self) -> StdResult<Binary> { let msg = TransferHandleMsg::Transfer(self); to_binary(&msg) } /// creates a cosmos_msg sending this struct to the named contract pub fn into_cosmos_msg( self, callback_code_hash: String, contract_addr: HumanAddr, ) -> StdResult<CosmosMsg> { let msg = self.into_binary()?; let execute = WasmMsg::Execute { msg, callback_code_hash, contract_addr, send: vec![], }; Ok(execute.into()) } } // This is just a helper to properly serialize the above message #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] #[serde(rename_all = "snake_case")] enum TransferHandleMsg { Transfer(TransferMsg), } // used to serialize the message to register a receive function with a SNIP-20 contract #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct RegisterMsg { pub code_hash: String, } impl RegisterMsg { /// serializes the message pub fn into_binary(self) -> StdResult<Binary> { let msg = RegisterHandleMsg::RegisterReceive(self); to_binary(&msg) } /// creates a cosmos_msg sending this struct to the named contract pub fn into_cosmos_msg( self, callback_code_hash: String, contract_addr: HumanAddr, ) -> StdResult<CosmosMsg> { let msg = self.into_binary()?; let execute = WasmMsg::Execute { msg, callback_code_hash, contract_addr, send: vec![], }; Ok(execute.into()) } } // This is just a helper to properly serialize the above message #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] #[serde(rename_all = "snake_case")] enum RegisterHandleMsg { RegisterReceive(RegisterMsg), } // space_pad -- pad a Vec<u8> with blanks at the end to length of multiples of block_size pub fn space_pad(block_size: usize, message: &mut Vec<u8>) -> &mut Vec<u8> { let len = message.len(); let surplus = len % block_size; if surplus == 0 { return message; } let missing = block_size - surplus; message.reserve(missing); message.extend(std::iter::repeat(b' ').take(missing)); message } // pad_log_str -- pad a String with blanks so that it has length of block_size pub fn pad_log_str(block_size: usize, response: &mut String) { response.push_str(&(" ".repeat(block_size - response.chars().count()))); }
use std::io::Read; fn main() { let mut buf = String::new(); // 標準入力から全部bufに読み込む std::io::stdin().read_to_string(&mut buf).unwrap(); let mut iter = buf.split_whitespace(); let max: u32 = iter.next().unwrap().parse().unwrap(); let start: u32 = iter.next().unwrap().parse().unwrap(); let end: u32 = iter.next().unwrap().parse().unwrap(); let mut result = 0; for num in 1..max + 1 { let sum = num .to_string() .chars() .map(|char| char.to_digit(10).unwrap()) .sum::<u32>(); if start <= sum && sum <= end { result += num; } } println!("{}", result); }
use lib::Config; use std::env; use std::process; mod lib; fn main() { //读取命令行参数 let args: Vec<String> = env::args().collect(); //println!("{:?}", args); //获取要搜索的字符串以及文件 let config = Config::new(&args).unwrap_or_else(|err| { //println!("Problem parsing argument:{}", err);//输出错误到标准流中 eprintln!("Problem parsing argument:{}", err); process::exit(1); }); //compile error //let query = config.query; //let filename = config.filename; //println!("Searching for {}", config.query); //println!("In file {}", config.filename); if let Err(e) = lib::run(config) { //处理错误 //println!("Application error:{}", e); eprintln!("Application error:{}", e); process::exit(1); }; }
use std::io; use std::io::Write; use rand; use rand::Rng; use std::collections::HashMap; pub fn solution(){ //seed random number generator for later use let mut rng = rand::thread_rng(); print!("kid list(separated by ;) > "); io::stdout().flush().unwrap(); let mut roster:String = String::new(); io::stdin().read_line(&mut roster).unwrap(); let roster:Vec<&str> = roster.trim().split(";").collect(); print!("Number of kids per list > "); io::stdout().flush().unwrap(); let mut list_size = String::new(); io::stdin().read_line(&mut list_size).unwrap(); let list_size: i32 = list_size.trim().parse().unwrap(); for kid in &roster{ //implement the lotto list as a hash map to have O(1) lookup time //for verifying a name isn't repeated let mut lotto_list: HashMap<String, bool> = HashMap::new(); for _ in 0..list_size+1{ let mut next_kid: u8 = rng.gen::<u8>() % (roster.len() as u8); while roster[next_kid as usize].to_string() == kid.to_string() || lotto_list.contains_key(&kid.to_string()){ next_kid = rng.gen::<u8>() % (roster.len() as u8); } let next_kid = roster[next_kid as usize].to_string(); lotto_list.insert(next_kid, true); } //print lotto list print!("{} > ", kid); for k in lotto_list.keys(){ print!("{}, ", k); } println!(""); } }
use crate::Result; use num::{BigInt, ToPrimitive}; // ```wl // TemplateApply[ // "cache.insert(`1`,BigInt::from(`2`));\n", // {#, Fibonacci[#]} // ]& // %/@Join[Range[0,9],PowerRange[10,100,10]] // %//StringJoin//CopyToClipboard // ``` use crate::Error::{ComplexInfinity, OverFlow}; use num::{BigUint, One}; /// TODO: Parallel Prime Swing Algorithm /// http://www.luschny.de/math/factorial/FastFactorialFunctions.htm /// http://www.luschny.de/math/factorial/SwingFactorialSagePython.html pub fn factorial_fold_u(n: usize) -> BigUint { (1..=n).fold(BigUint::one(), |a, b| a * b) } pub fn factorial_i(n: &BigInt) -> Result<BigInt> { match n.to_isize() { Some(s) => { if s < 0 { Err(ComplexInfinity) } else { Ok(BigInt::from(factorial_fold_u(s as usize))) } } None => Err(OverFlow), } } #[test] fn factorial_test() { println!("{}", factorial_i(&BigInt::from(100)).unwrap()) } pub fn factorial_mod() { unimplemented!() } pub fn factorial_digits() { unimplemented!() } pub fn factorial_tail_zero() { unimplemented!() }
//! Set the visibility of the contained widget use crate::{ data::WidgetData, geometry::{BoundingBox, MeasuredSize}, input::event::InputEvent, state::WidgetState, widgets::{ utils::{ decorator::WidgetDecorator, wrapper::{Wrapper, WrapperBindable}, }, Widget, }, Canvas, WidgetRenderer, }; pub struct Visibility<W> { pub inner: W, pub visibility: bool, pub on_state_changed: fn(&mut Self, WidgetState), } impl<W> Visibility<W> where W: Widget, { pub fn new(inner: W) -> Visibility<W> { Visibility { inner, visibility: true, on_state_changed: |_, _| (), } } } impl<W> WrapperBindable for Visibility<W> where W: Widget {} impl<W> Visibility<W> { pub fn visible(mut self, visibility: bool) -> Self { self.set_visible(visibility); self } pub fn set_visible(&mut self, visibility: bool) { self.visibility = visibility; } pub fn on_state_changed(mut self, callback: fn(&mut Self, WidgetState)) -> Self { self.on_state_changed = callback; self } } impl<W, D> Wrapper<Visibility<W>, D> where W: Widget, D: WidgetData, { pub fn visible(mut self, visibility: bool) -> Self { self.widget.set_visible(visibility); self } pub fn on_state_changed(mut self, callback: fn(&mut Visibility<W>, WidgetState)) -> Self { // TODO this should be pulled up self.widget.on_state_changed = callback; self } } impl<W> WidgetDecorator for Visibility<W> where W: Widget, { type Widget = W; fn widget(&self) -> &Self::Widget { &self.inner } fn widget_mut(&mut self) -> &mut Self::Widget { &mut self.inner } fn bounding_box(&self) -> BoundingBox { if self.visibility { self.inner.bounding_box() } else { BoundingBox { position: self.inner.bounding_box().position, size: MeasuredSize { width: 0, height: 0, }, } } } fn test_input(&mut self, event: InputEvent) -> Option<usize> { if self.visibility { // We just relay whatever the child desires self.inner.test_input(event).map(|i| i + 1) } else { None } } } impl<C, W> WidgetRenderer<C> for Visibility<W> where W: Widget + WidgetRenderer<C>, C: Canvas, { fn draw(&mut self, canvas: &mut C) -> Result<(), C::Error> { if self.visibility { self.inner.draw(canvas) } else { Ok(()) } } }
#![allow(missing_docs)] #![deny(warnings)] extern crate libc; use std::mem; use self::libc::{ c_char, int32_t, uint8_t, uint16_t, uint32_t, uint64_t }; /* the following events that user-space can register for */ //#define FAN_ACCESS 0x00000001 /* File was accessed */ ///File was accessed pub const FAN_ACCESS: uint32_t = 0x00000001; /* File was accessed */ //#define FAN_MODIFY 0x00000002 /* File was modified */ ///File was modified pub const FAN_MODIFY: uint32_t = 0x00000002; /* File was modified */ //#define FAN_CLOSE_WRITE 0x00000008 /* Writtable file closed */ ///Writtable file closed pub const FAN_CLOSE_WRITE: uint32_t = 0x00000008; /* Writtable file closed */ //#define FAN_CLOSE_NOWRITE 0x00000010 /* Unwrittable file closed */ ///Unwrittable file closed pub const FAN_CLOSE_NOWRITE: uint32_t = 0x00000010; /* Unwrittable file closed */ //#define FAN_OPEN 0x00000020 /* File was opened */ ///File was opened pub const FAN_OPEN: uint32_t = 0x00000020; /* File was opened */ //#define FAN_Q_OVERFLOW 0x00004000 /* Event queued overflowed */ ///Event queued overflowed pub const FAN_Q_OVERFLOW: uint32_t = 0x00004000; /* Event queued overflowed */ //#define FAN_OPEN_PERM 0x00010000 /* File open in perm check */ ///File open in perm check pub const FAN_OPEN_PERM: uint32_t = 0x00010000; /* File open in perm check */ //#define FAN_ACCESS_PERM 0x00020000 /* File accessed in perm check */ ///File accessed in perm check pub const FAN_ACCESS_PERM: uint32_t = 0x00020000; /* File accessed in perm check */ //#define FAN_ONDIR 0x40000000 /* event occurred against dir */ ///Event occured against dir pub const FAN_ONDIR: uint32_t = 0x40000000; /* event occurred against dir */ //#define FAN_EVENT_ON_CHILD 0x08000000 /* interested in child events */ ///Interested in child events pub const FAN_EVENT_ON_CHILD: uint32_t = 0x08000000; /* interested in child events */ /* helper events */ //#define FAN_CLOSE (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE) /* close */ ///Close pub const FAN_CLOSE: uint32_t = (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE); /* close */ /* flags used for fanotify_init() */ //#define FAN_CLOEXEC 0x00000001 ///Flag used for fanotify_init() pub const FAN_CLOEXEC: uint32_t = 0x00000001; //#define FAN_NONBLOCK 0x00000002 ///Flag used for fanotify_init() pub const FAN_NONBLOCK: uint32_t = 0x00000002; /* These are NOT bitwise flags. Both bits are used togther. */ ///These are not bitwise flags. Both bits are used together. pub const FAN_CLASS_NOTIF: uint32_t = 0x00000000; ///These are not bitwise flags. Both bits are used together. pub const FAN_CLASS_CONTENT: uint32_t = 0x00000004; ///These are not bitwise flags. Both bits are used together. pub const FAN_CLASS_PRE_CONTENT: uint32_t = 0x00000008; //#define FAN_UNLIMITED_QUEUE 0x00000010 ///These are not bitwise flags. Both bits are used together. pub const FAN_UNLIMITED_QUEUE: uint32_t = 0x00000010; //#define FAN_UNLIMITED_MARKS 0x00000020 ///These are not bitwise flags. Both bits are used together. pub const FAN_UNLIMITED_MARKS: uint32_t = 0x00000020; //#define FAN_ALL_INIT_FLAGS (FAN_CLOEXEC | FAN_NONBLOCK | pub const FAN_ALL_INIT_FLAGS: uint32_t = (FAN_CLOEXEC | FAN_NONBLOCK | FAN_ALL_CLASS_BITS | FAN_UNLIMITED_QUEUE | FAN_UNLIMITED_MARKS) /* flags used for fanotify_modify_mark() */ ///Flags used for fanotify_modify_mark() pub const FAN_MARK_ADD: uint32_t = 0x00000001; ///Flags used for fanotify_modify_mark() pub const FAN_MARK_REMOVE: uint32_t = 0x00000002; ///Flags used for fanotify_modify_mark() pub const FAN_MARK_DONT_FOLLOW: uint32_t = 0x00000004; ///Flags used for fanotify_modify_mark() pub const FAN_MARK_ONLYDIR: uint32_t = 0x00000008; ///Flags used for fanotify_modify_mark() pub const FAN_MARK_MOUNT: uint32_t = 0x00000010; ///Flags used for fanotify_modify_mark() pub const FAN_MARK_IGNORED_MASK: uint32_t = 0x00000020; ///Flags used for fanotify_modify_mark() pub const FAN_MARK_IGNORED_SURV_MODIFY: uint32_t = 0x00000040; ///Flags used for fanotify_modify_mark() pub const FAN_MARK_FLUSH: uint32_t = 0x00000080; /* * All of the events - we build the list by hand so that we can add flags in * the future and not break backward compatibility. Apps will get only the * events that they originally wanted. Be sure to add new events here! */ //#define FAN_ALL_EVENTS (FAN_ACCESS |pub const FAN_ALL_EVENTS: uint32_t = (FAN_ACCESS | FAN_MODIFY | FAN_CLOSE | FAN_OPEN) /* * All events which require a permission response from userspace */ //#define FAN_ALL_PERM_EVENTS (FAN_OPEN_PERM |pub const FAN_ALL_PERM_EVENTS: uint32_t = (FAN_OPEN_PERM | FAN_ACCESS_PERM) //#define FAN_ALL_OUTGOING_EVENTS (FAN_ALL_EVENTS |pub const FAN_ALL_OUTGOING_EVENTS: uint32_t = (FAN_ALL_EVENTS | FAN_ALL_PERM_EVENTS | FAN_Q_OVERFLOW) //#define FANOTIFY_METADATA_VERSION 3 ///placeholder pub const FANOTIFY_METADATA_VERSION: uint8_t = 3; /* struct fanotify_event_metadata { __u32 event_len; __u8 vers; __u8 reserved; __u16 metadata_len; __aligned_u64 mask; __s32 fd; __s32 pid; };*/ ///placeholder #[allow(non_camel_case_types)] #[repr(C)] #[derive(Debug,Copy,Clone)] pub struct fanotify_event_metadata { ///placeholder pub event_len: uint32_t, ///placeholder pub vers: uint8_t, ///placeholder pub reserved: uint8_t, ///placeholder pub metadata_len: uint16_t, ///placeholder pub mask: uint64_t, ///placeholder pub fd: int32_t, ///placeholder pub pid: int32_t, } pub unsafe fn fan_event_next(meta: *const fanotify_event_metadata, total_len: &mut isize) -> *const fanotify_event_metadata { *total_len -= (*meta).event_len as isize; //println!("Adding {} to {:p}",((*meta).event_len),meta); let ret = (meta as u64 + ((*meta).event_len) as u64) as *const fanotify_event_metadata; //println!("Returning {:p}",ret); return ret; } pub unsafe fn fan_event_ok(meta: *const fanotify_event_metadata, total_len: &mut isize) -> bool { //println!("len = {}, size = {}, event_len = {}",total_len, mem::size_of::<fanotify_event_metadata>(), (*meta).event_len); *total_len >= mem::size_of::<fanotify_event_metadata>() as isize && (*meta).event_len >= mem::size_of::<fanotify_event_metadata>() as u32 && (*meta).event_len <= *total_len as u32 } #[allow(non_camel_case_types)] #[repr(C)] ///placeholder pub struct fanotify_response { ///placeholder pub fd: int32_t, ///placeholder pub response: uint32_t, } /* Legit userspace responses to a _PERM event */ //#define FAN_ALLOW 0x01 ///placeholder pub const FAN_ALLOW: uint32_t = 0x01; //#define FAN_DENY 0x02 ///placeholder pub const FAN_DENY: uint32_t = 0x02; /* No fd set in event */ ///placeholder pub const FAN_NOFD: int32_t = -1; extern { /* Create and initialize fanotify group. */ pub fn fanotify_init(__flags: uint32_t, __event_f_flags: uint32_t) -> int32_t; /* Add, remove, or modify an fanotify mark on a filesystem object. */ pub fn fanotify_mark(__fanotify_fd: int32_t, __flags: uint32_t, __mask: uint64_t, __dfd: int32_t, __pathname: *const c_char) ->int32_t; } pub use self::libc::{ close, read, };
use std::io; fn main() { let mut buf = String::new(); io::stdin().read_line(&mut buf).unwrap(); let n: i64 = buf.trim().parse().unwrap(); let mut count: i64 = 0; for i in 1..n + 1 { if i % 3 != 0 && i % 5 != 0 { count += i; } } println!("{}", count); }
use std::time::Duration; use async_std::io::{timeout as tout, Error}; use async_std::net::TcpStream; pub async fn check_network(addrs: &str, timeout: Duration) -> Result<bool, Error> { match tout(timeout, TcpStream::connect(addrs)).await { Ok(_) => Ok(true), Err(e) => Err(e), } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{client, known_ess_store::KnownEssStore}; use fidl::{self, endpoints::create_proxy}; use fidl_fuchsia_wlan_common as fidl_common; use fidl_fuchsia_wlan_device_service as wlan_service; use fidl_fuchsia_wlan_service as legacy; use fidl_fuchsia_wlan_sme as fidl_sme; use fidl_fuchsia_wlan_stats as fidl_wlan_stats; use fuchsia_zircon as zx; use futures::{channel::oneshot, prelude::*}; use itertools::Itertools; use std::{ cmp::Ordering, collections::HashMap, sync::{Arc, Mutex}, }; #[derive(Clone)] pub struct Client { pub service: wlan_service::DeviceServiceProxy, pub client: client::Client, pub sme: fidl_sme::ClientSmeProxy, pub iface_id: u16, } #[derive(Clone)] pub struct ClientRef(Arc<Mutex<Option<Client>>>); impl ClientRef { pub fn new() -> Self { ClientRef(Arc::new(Mutex::new(None))) } pub fn set_if_empty(&self, client: Client) { let mut c = self.0.lock().unwrap(); if c.is_none() { *c = Some(client); } } pub fn remove_if_matching(&self, iface_id: u16) { let mut c = self.0.lock().unwrap(); let same_id = match *c { Some(ref c) => c.iface_id == iface_id, None => false, }; if same_id { *c = None; } } pub fn get(&self) -> Result<Client, legacy::Error> { self.0.lock().unwrap().clone().ok_or_else(|| legacy::Error { code: legacy::ErrCode::NotFound, description: "No wireless interface found".to_string(), }) } } const MAX_CONCURRENT_WLAN_REQUESTS: usize = 1000; pub async fn serve_legacy( requests: legacy::WlanRequestStream, client: ClientRef, ess_store: Arc<KnownEssStore>, ) -> Result<(), fidl::Error> { requests .try_for_each_concurrent(MAX_CONCURRENT_WLAN_REQUESTS, |req| { handle_request(&client, req, Arc::clone(&ess_store)) }) .await } async fn handle_request( client: &ClientRef, req: legacy::WlanRequest, ess_store: Arc<KnownEssStore>, ) -> Result<(), fidl::Error> { match req { legacy::WlanRequest::Scan { req, responder } => { let mut r = scan(client, req).await; responder.send(&mut r) } legacy::WlanRequest::Connect { req, responder } => { let mut r = connect(&client, req).await; responder.send(&mut r) } legacy::WlanRequest::Disconnect { responder } => { let mut r = disconnect(client.clone()).await; responder.send(&mut r) } legacy::WlanRequest::Status { responder } => { let mut r = status(&client).await; responder.send(&mut r) } legacy::WlanRequest::StartBss { responder, .. } => { eprintln!("StartBss() is not implemented"); responder.send(&mut not_supported()) } legacy::WlanRequest::StopBss { responder } => { eprintln!("StopBss() is not implemented"); responder.send(&mut not_supported()) } legacy::WlanRequest::Stats { responder } => { let mut r = stats(client).await; responder.send(&mut r) } legacy::WlanRequest::ClearSavedNetworks { responder } => { if let Err(e) = ess_store.clear() { eprintln!("Error clearing known ESS: {}", e); } responder.send() } } } pub fn clone_bss_info(bss: &fidl_sme::BssInfo) -> fidl_sme::BssInfo { fidl_sme::BssInfo { bssid: bss.bssid.clone(), ssid: bss.ssid.clone(), rx_dbm: bss.rx_dbm, channel: bss.channel, protection: bss.protection, compatible: bss.compatible, } } /// Compares two BSS based on /// (1) their compatibility /// (2) their security protocol /// (3) their Beacon's RSSI pub fn compare_bss(left: &fidl_sme::BssInfo, right: &fidl_sme::BssInfo) -> Ordering { left.compatible .cmp(&right.compatible) .then(left.protection.cmp(&right.protection)) .then(left.rx_dbm.cmp(&right.rx_dbm)) } /// Returns the 'best' BSS from a given BSS list. The 'best' BSS is determined by comparing /// all BSS with `compare_bss(BssDescription, BssDescription)`. pub fn get_best_bss<'a>(bss_list: &'a Vec<fidl_sme::BssInfo>) -> Option<&'a fidl_sme::BssInfo> { bss_list.iter().max_by(|x, y| compare_bss(x, y)) } async fn scan(client: &ClientRef, legacy_req: legacy::ScanRequest) -> legacy::ScanResult { let r = async move { let client = client.get()?; let scan_txn = start_scan_txn(&client, legacy_req).map_err(|e| { eprintln!("Failed to start a scan transaction: {}", e); internal_error() })?; let mut evt_stream = scan_txn.take_event_stream(); let mut aps = vec![]; let mut done = false; while let Some(event) = evt_stream.try_next().await.map_err(|e| { eprintln!("Error reading from scan transaction stream: {}", e); internal_error() })? { match event { fidl_sme::ScanTransactionEvent::OnResult { aps: new_aps } => { aps.extend(new_aps); done = false; } fidl_sme::ScanTransactionEvent::OnFinished {} => done = true, fidl_sme::ScanTransactionEvent::OnError { error } => { return Err(convert_scan_err(error)); } } } if !done { eprintln!("Failed to fetch all results before the channel was closed"); return Err(internal_error()); } let mut bss_by_ssid: HashMap<Vec<u8>, Vec<fidl_sme::BssInfo>> = HashMap::new(); for bss in aps.iter() { bss_by_ssid.entry(bss.ssid.clone()).or_insert(vec![]).push(clone_bss_info(&bss)); } Ok(bss_by_ssid .values() .filter_map(get_best_bss) .map(convert_bss_info) .sorted_by(|a, b| a.ssid.cmp(&b.ssid)) .collect()) } .await; match r { Ok(aps) => legacy::ScanResult { error: success(), aps: Some(aps) }, Err(error) => legacy::ScanResult { error, aps: None }, } } fn start_scan_txn( client: &Client, legacy_req: legacy::ScanRequest, ) -> Result<fidl_sme::ScanTransactionProxy, fidl::Error> { let (scan_txn, remote) = create_proxy()?; let mut req = fidl_sme::ScanRequest { timeout: legacy_req.timeout, scan_type: fidl_common::ScanType::Passive, }; client.sme.scan(&mut req, remote)?; Ok(scan_txn) } fn convert_scan_err(error: fidl_sme::ScanError) -> legacy::Error { legacy::Error { code: match error.code { fidl_sme::ScanErrorCode::NotSupported => legacy::ErrCode::NotSupported, fidl_sme::ScanErrorCode::InternalError => legacy::ErrCode::Internal, }, description: error.message, } } fn convert_bss_info(bss: &fidl_sme::BssInfo) -> legacy::Ap { legacy::Ap { bssid: bss.bssid.to_vec(), ssid: String::from_utf8_lossy(&bss.ssid).to_string(), rssi_dbm: bss.rx_dbm, is_secure: bss.protection != fidl_sme::Protection::Open, is_compatible: bss.compatible, chan: fidl_common::WlanChan { primary: bss.channel, secondary80: 0, cbw: fidl_common::Cbw::Cbw20, }, } } fn connect( client: &ClientRef, legacy_req: legacy::ConnectConfig, ) -> impl Future<Output = legacy::Error> { future::ready(client.get()) .and_then(move |client| { let (responder, receiver) = oneshot::channel(); let req = client::ConnectRequest { ssid: legacy_req.ssid.as_bytes().to_vec(), password: legacy_req.pass_phrase.as_bytes().to_vec(), responder, }; future::ready(client.client.connect(req).map_err(|e| { eprintln!("Failed to start a connect transaction: {}", e); internal_error() })) .and_then(move |()| { receiver.map_err(|_e| { eprintln!("Did not receive a connect result"); internal_error() }) }) }) .map_ok(convert_connect_result) .unwrap_or_else(|e| e) } async fn disconnect(client: ClientRef) -> legacy::Error { let client = match client.get() { Ok(c) => c, Err(e) => return e, }; let (responder, receiver) = oneshot::channel(); if let Err(e) = client.client.disconnect(responder) { eprintln!("Failed to enqueue a disconnect command: {}", e); return internal_error(); } match receiver.await { Ok(()) => success(), Err(_) => error_message("Request was canceled"), } } fn convert_connect_result(code: fidl_sme::ConnectResultCode) -> legacy::Error { match code { fidl_sme::ConnectResultCode::Success => success(), fidl_sme::ConnectResultCode::Canceled => error_message("Request was canceled"), fidl_sme::ConnectResultCode::BadCredentials => { error_message("Failed to join; bad credentials") } fidl_sme::ConnectResultCode::Failed => error_message("Failed to join"), } } fn status(client: &ClientRef) -> impl Future<Output = legacy::WlanStatus> { future::ready(client.get()) .and_then(|client| { client.sme.status().map_err(|e| { eprintln!("Failed to query status: {}", e); internal_error() }) }) .map(|r| match r { Ok(status) => legacy::WlanStatus { error: success(), state: convert_state(&status), current_ap: status.connected_to.map(|bss| Box::new(convert_bss_info(bss.as_ref()))), }, Err(error) => { legacy::WlanStatus { error, state: legacy::State::Unknown, current_ap: None } } }) } fn convert_state(status: &fidl_sme::ClientStatusResponse) -> legacy::State { if status.connected_to.is_some() { legacy::State::Associated } else if !status.connecting_to_ssid.is_empty() { legacy::State::Joining } else { // There is no "idle" or "disconnected" state in the legacy API legacy::State::Querying } } fn stats(client: &ClientRef) -> impl Future<Output = legacy::WlanStats> { future::ready(client.get()) .and_then(|client| { client.service.get_iface_stats(client.iface_id).map_err(|e| { eprintln!("Failed to query statistics: {}", e); internal_error() }) }) .map(|r| match r { Ok((zx::sys::ZX_OK, Some(iface_stats))) => { legacy::WlanStats { error: success(), stats: *iface_stats } } Ok((err_code, _)) => { eprintln!("GetIfaceStats returned error code {}", zx::Status::from_raw(err_code)); legacy::WlanStats { error: internal_error(), stats: empty_stats() } } Err(error) => legacy::WlanStats { error, stats: empty_stats() }, }) } fn internal_error() -> legacy::Error { legacy::Error { code: legacy::ErrCode::Internal, description: "Internal error occurred".to_string(), } } fn success() -> legacy::Error { legacy::Error { code: legacy::ErrCode::Ok, description: String::new() } } fn not_supported() -> legacy::Error { legacy::Error { code: legacy::ErrCode::NotSupported, description: "Not supported".to_string() } } fn error_message(msg: &str) -> legacy::Error { legacy::Error { code: legacy::ErrCode::Internal, description: msg.to_string() } } fn empty_stats() -> fidl_wlan_stats::IfaceStats { fidl_wlan_stats::IfaceStats { dispatcher_stats: fidl_wlan_stats::DispatcherStats { any_packet: empty_packet_counter(), mgmt_frame: empty_packet_counter(), ctrl_frame: empty_packet_counter(), data_frame: empty_packet_counter(), }, mlme_stats: None, } } fn empty_packet_counter() -> fidl_wlan_stats::PacketCounter { fidl_wlan_stats::PacketCounter { in_: empty_counter(), out: empty_counter(), drop: empty_counter(), in_bytes: empty_counter(), out_bytes: empty_counter(), drop_bytes: empty_counter(), } } fn empty_counter() -> fidl_wlan_stats::Counter { fidl_wlan_stats::Counter { count: 0, name: String::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_convert_bss_to_legacy_ap() { let bss = fidl_sme::BssInfo { bssid: [0x62, 0x73, 0x73, 0x66, 0x6f, 0x6f], ssid: b"Foo".to_vec(), rx_dbm: 20, channel: 1, protection: fidl_sme::Protection::Wpa2Personal, compatible: true, }; let ap = legacy::Ap { bssid: vec![0x62, 0x73, 0x73, 0x66, 0x6f, 0x6f], ssid: "Foo".to_string(), rssi_dbm: 20, is_secure: true, is_compatible: true, chan: fidl_common::WlanChan { primary: 1, secondary80: 0, cbw: fidl_common::Cbw::Cbw20, }, }; assert_eq!(convert_bss_info(&bss), ap); let bss = fidl_sme::BssInfo { protection: fidl_sme::Protection::Open, ..bss }; let ap = legacy::Ap { is_secure: false, ..ap }; assert_eq!(convert_bss_info(&bss), ap); } #[test] fn get_best_bss_empty_list() { assert!(get_best_bss(&vec![]).is_none()); } #[test] fn get_best_bss_compatible() { let bss2 = bss(-20, false, fidl_sme::Protection::Wpa2Wpa3Personal); let bss1 = bss(-60, true, fidl_sme::Protection::Wpa2Personal); let bss_list = vec![bss1, bss2]; assert_eq!(get_best_bss(&bss_list), Some(&bss_list[0])); //diff compatible } #[test] fn get_best_bss_protection() { let bss1 = bss(-60, true, fidl_sme::Protection::Wpa2Personal); let bss2 = bss(-40, true, fidl_sme::Protection::Wep); let bss_list = vec![bss1, bss2]; assert_eq!(get_best_bss(&bss_list), Some(&bss_list[0])); //diff protection } #[test] fn get_best_bss_rssi() { let bss1 = bss(-10, true, fidl_sme::Protection::Wpa2Personal); let bss2 = bss(-20, true, fidl_sme::Protection::Wpa2Personal); let bss_list = vec![bss1, bss2]; assert_eq!(get_best_bss(&bss_list), Some(&bss_list[0])); //diff rssi } fn bss(rx_dbm: i8, compatible: bool, protection: fidl_sme::Protection) -> fidl_sme::BssInfo { fidl_sme::BssInfo { bssid: [0x62, 0x73, 0x73, 0x66, 0x6f, 0x6f], ssid: b"Foo".to_vec(), rx_dbm, channel: 1, protection, compatible, } } }
use crate::spec::TargetOptions; pub fn opts() -> TargetOptions { TargetOptions { env: "gnu".into(), ..super::linux_base::opts() } }
#![feature(test)] extern crate test; extern crate snow; use snow::*; use snow::params::*; use snow::types::*; use snow::wrappers::crypto_wrapper::Dh25519; use snow::wrappers::rand_wrapper::RandomOs; use test::Bencher; const MSG_SIZE: usize = 4096; pub fn copy_memory(data: &[u8], out: &mut [u8]) -> usize { for count in 0..data.len() {out[count] = data[count];} data.len() } #[bench] fn bench_handshake_xx(b: &mut Bencher) { let mut static_i: Dh25519 = Default::default(); let mut static_r: Dh25519 = Default::default(); let mut rand = RandomOs::default(); static_i.generate(&mut rand); static_r.generate(&mut rand); b.bytes = MSG_SIZE as u64; b.iter(move || { let pattern: NoiseParams = "Noise_XX_25519_ChaChaPoly_BLAKE2b".parse().unwrap(); let mut h_i = NoiseBuilder::new(pattern.clone()) .local_private_key(static_i.privkey()) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::new(pattern) .local_private_key(static_r.privkey()) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_i.write_message(&[0u8;0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); }); } #[bench] fn bench_handshake_nn(b: &mut Bencher) { b.bytes = MSG_SIZE as u64; b.iter(move || { let pattern = "Noise_NN_25519_ChaChaPoly_BLAKE2b"; let mut h_i = NoiseBuilder::new(pattern.parse().unwrap()) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::new(pattern.parse().unwrap()) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); }); } #[bench] fn bench_write_throughput_aesgcm_sha256(b: &mut Bencher) { b.bytes = MSG_SIZE as u64; static PATTERN: &'static str = "Noise_NN_25519_AESGCM_SHA256"; let mut h_i = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); b.iter(move || { let _ = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); }); } #[cfg(feature = "ring-resolver")] #[bench] fn bench_read_write_throughput_aesgcm_sha256_ring(b: &mut Bencher) { b.bytes = (MSG_SIZE * 2) as u64; static PATTERN: &'static str = "Noise_NN_25519_AESGCM_SHA256"; let mut h_i = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); let mut h_r = h_r.into_transport_mode().unwrap(); b.iter(move || { let len = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); let _ = h_r.read_message(&buffer_out[..len], &mut buffer_msg).unwrap(); }); } #[cfg(feature = "ring-resolver")] #[bench] fn bench_read_write_throughput_chachapoly_blake2s_ring(b: &mut Bencher) { b.bytes = (MSG_SIZE * 2) as u64; static PATTERN: &'static str = "Noise_NN_25519_ChaChaPoly_BLAKE2s"; let mut h_i = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); let mut h_r = h_r.into_transport_mode().unwrap(); b.iter(move || { let len = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); let _ = h_r.read_message(&buffer_out[..len], &mut buffer_msg).unwrap(); }); } #[bench] fn bench_read_write_throughput_aesgcm_sha256(b: &mut Bencher) { b.bytes = (MSG_SIZE * 2) as u64; static PATTERN: &'static str = "Noise_NN_25519_AESGCM_SHA256"; let mut h_i = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); let mut h_r = h_r.into_transport_mode().unwrap(); b.iter(move || { let len = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); let _ = h_r.read_message(&buffer_out[..len], &mut buffer_msg).unwrap(); }); } #[cfg(feature = "ring-resolver")] #[bench] fn bench_write_throughput_aesgcm_sha256_ring(b: &mut Bencher) { b.bytes = MSG_SIZE as u64; static PATTERN: &'static str = "Noise_NN_25519_AESGCM_SHA256"; let mut h_i = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); b.iter(move || { let _ = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); }); } #[bench] fn bench_write_throughput_chachapoly_blake2s(b: &mut Bencher) { b.bytes = MSG_SIZE as u64; static PATTERN: &'static str = "Noise_NN_25519_ChaChaPoly_BLAKE2s"; let mut h_i = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); b.iter(move || { let _ = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); }); } #[cfg(feature = "ring-resolver")] #[bench] fn bench_write_throughput_chachapoly_blake2s_ring(b: &mut Bencher) { b.bytes = MSG_SIZE as u64; static PATTERN: &'static str = "Noise_NN_25519_ChaChaPoly_BLAKE2s"; let mut h_i = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::with_resolver(PATTERN.parse().unwrap(), Box::new(RingAcceleratedResolver::new())) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); b.iter(move || { let _ = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); }); } #[bench] fn bench_read_write_throughput_chachapoly_blake2s(b: &mut Bencher) { b.bytes = (MSG_SIZE * 2) as u64; static PATTERN: &'static str = "Noise_NN_25519_ChaChaPoly_BLAKE2s"; let mut h_i = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_initiator().unwrap(); let mut h_r = NoiseBuilder::new(PATTERN.parse().unwrap()) .build_responder().unwrap(); let mut buffer_msg = [0u8; MSG_SIZE * 2]; let mut buffer_out = [0u8; MSG_SIZE * 2]; // get the handshaking out of the way for even testing let len = h_i.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_r.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let len = h_r.write_message(&[0u8; 0], &mut buffer_msg).unwrap(); h_i.read_message(&buffer_msg[..len], &mut buffer_out).unwrap(); let mut h_i = h_i.into_transport_mode().unwrap(); let mut h_r = h_r.into_transport_mode().unwrap(); b.iter(move || { let len = h_i.write_message(&buffer_msg[..MSG_SIZE], &mut buffer_out).unwrap(); let _ = h_r.read_message(&buffer_out[..len], &mut buffer_msg).unwrap(); }); } #[bench] fn bench_builder_with_key(b: &mut Bencher) { let static_i:Dh25519 = Default::default(); let privkey = static_i.privkey(); b.iter(move || { NoiseBuilder::new("Noise_XX_25519_ChaChaPoly_SHA256".parse().unwrap()) .local_private_key(privkey) .build_initiator().unwrap(); }); } #[bench] fn bench_builder_skeleton(b: &mut Bencher) { b.iter(move || { NoiseBuilder::new("Noise_NN_25519_ChaChaPoly_SHA256".parse().unwrap()) .build_initiator().unwrap(); }); }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to 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. use std::alloc::Layout; use std::fmt; use std::sync::Arc; use common_arrow::arrow::bitmap::Bitmap; use common_exception::Result; use common_expression::types::DataType; use common_expression::Column; use common_expression::ColumnBuilder; use common_expression::Scalar; use common_io::prelude::BinaryWrite; use crate::aggregates::aggregate_function_factory::AggregateFunctionFeatures; use crate::aggregates::AggregateFunction; use crate::aggregates::AggregateFunctionRef; use crate::aggregates::StateAddr; /// OrNullAdaptor will use OrNull for aggregate functions. /// If there are no input values, return NULL or a default value, accordingly. /// Use a single additional byte of data after the nested function data: /// 0 means there was no input, 1 means there was some. pub struct AggregateFunctionOrNullAdaptor { inner: AggregateFunctionRef, size_of_data: usize, inner_nullable: bool, } impl AggregateFunctionOrNullAdaptor { pub fn create( inner: AggregateFunctionRef, features: AggregateFunctionFeatures, ) -> Result<AggregateFunctionRef> { // count/count distinct should not be nullable for empty set, just return zero let inner_return_type = inner.return_type()?; if features.returns_default_when_only_null || inner_return_type == DataType::Null { return Ok(inner); } let inner_layout = inner.state_layout(); Ok(Arc::new(AggregateFunctionOrNullAdaptor { inner, size_of_data: inner_layout.size(), inner_nullable: matches!(inner_return_type, DataType::Nullable(_)), })) } #[inline] pub fn set_flag(&self, place: StateAddr, flag: u8) { let c = place.next(self.size_of_data).get::<u8>(); *c = flag; } #[inline] pub fn get_flag(&self, place: StateAddr) -> u8 { let c = place.next(self.size_of_data).get::<u8>(); *c } } impl AggregateFunction for AggregateFunctionOrNullAdaptor { fn name(&self) -> &str { self.inner.name() } fn return_type(&self) -> Result<DataType> { Ok(self.inner.return_type()?.wrap_nullable()) } #[inline] fn init_state(&self, place: StateAddr) { let c = place.next(self.size_of_data).get::<u8>(); *c = 0; self.inner.init_state(place) } #[inline] fn state_layout(&self) -> std::alloc::Layout { let layout = self.inner.state_layout(); Layout::from_size_align(layout.size() + layout.align(), layout.align()).unwrap() } #[inline] fn accumulate( &self, place: StateAddr, columns: &[Column], validity: Option<&Bitmap>, input_rows: usize, ) -> Result<()> { if input_rows == 0 { return Ok(()); } let if_cond = self.inner.get_if_condition(columns); let validity = match (if_cond, validity) { (None, None) => None, (None, Some(b)) => Some(b.clone()), (Some(a), None) => Some(a), (Some(a), Some(b)) => Some(&a & b), }; if validity .as_ref() .map(|c| c.unset_bits() != input_rows) .unwrap_or(true) { self.set_flag(place, 1); self.inner .accumulate(place, columns, validity.as_ref(), input_rows)?; } Ok(()) } fn accumulate_keys( &self, places: &[StateAddr], offset: usize, columns: &[Column], input_rows: usize, ) -> Result<()> { self.inner .accumulate_keys(places, offset, columns, input_rows)?; let if_cond = self.inner.get_if_condition(columns); match if_cond { Some(v) if v.unset_bits() > 0 => { // all nulls if v.unset_bits() == v.len() { return Ok(()); } for (place, valid) in places.iter().zip(v.iter()) { if valid { self.set_flag(place.next(offset), 1); } } } _ => { for place in places { self.set_flag(place.next(offset), 1); } } } Ok(()) } #[inline] fn accumulate_row(&self, place: StateAddr, columns: &[Column], row: usize) -> Result<()> { self.inner.accumulate_row(place, columns, row)?; self.set_flag(place, 1); Ok(()) } #[inline] fn serialize(&self, place: StateAddr, writer: &mut Vec<u8>) -> Result<()> { self.inner.serialize(place, writer)?; writer.write_scalar(&self.get_flag(place)) } #[inline] fn deserialize(&self, place: StateAddr, reader: &mut &[u8]) -> Result<()> { let flag = reader[reader.len() - 1]; self.inner .deserialize(place, &mut &reader[..reader.len() - 1])?; self.set_flag(place, flag); Ok(()) } fn merge(&self, place: StateAddr, rhs: StateAddr) -> Result<()> { self.inner.merge(place, rhs)?; let flag = self.get_flag(place) > 0 || self.get_flag(rhs) > 0; self.set_flag(place, u8::from(flag)); Ok(()) } fn merge_result(&self, place: StateAddr, builder: &mut ColumnBuilder) -> Result<()> { match builder { ColumnBuilder::Nullable(inner_mut) => { if self.get_flag(place) == 0 { inner_mut.push_null(); } else if self.inner_nullable { self.inner.merge_result(place, builder)?; } else { self.inner.merge_result(place, &mut inner_mut.builder)?; inner_mut.validity.push(true); } } _ => unreachable!(), } Ok(()) } fn get_own_null_adaptor( &self, nested_function: AggregateFunctionRef, params: Vec<Scalar>, arguments: Vec<DataType>, ) -> Result<Option<AggregateFunctionRef>> { self.inner .get_own_null_adaptor(nested_function, params, arguments) } fn need_manual_drop_state(&self) -> bool { self.inner.need_manual_drop_state() } unsafe fn drop_state(&self, place: StateAddr) { self.inner.drop_state(place) } fn convert_const_to_full(&self) -> bool { self.inner.convert_const_to_full() } } impl fmt::Display for AggregateFunctionOrNullAdaptor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.inner) } }
#[derive(Debug)] enum List { Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } use crate::List::{Cons, Nil}; use std::rc::Rc; use std::cell::RefCell; /* A common way to use RefCell<T> is in combination with Rc<T>. Recall that Rc<T> lets you have multiple owners of some data, but it only gives immutable access to that data. If you have an Rc<T> that holds a RefCell<T>, you can get a value that can have multiple owners and that you can mutate! */ fn main() { let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); *value.borrow_mut() += 10; println!("a after = {:?}", a); println!("b after = {:?}", b); println!("c after = {:?}", c); }
pub mod attribute; pub mod instruction; pub mod read; pub mod class; pub mod field; pub mod method; pub mod constant; pub use instruction::Instruction; use crate::class_file::unvalidated::attribute::Attribute; pub use crate::class_file::unvalidated::attribute::AttributeInfo; pub use crate::class_file::unvalidated::attribute::ExceptionTableRecord; pub use crate::class_file::unvalidated::class::AccessFlags; pub use crate::class_file::unvalidated::class::ClassFile; pub use crate::class_file::unvalidated::constant::Constant; pub use crate::class_file::unvalidated::constant::ConstantIdx; pub use crate::class_file::unvalidated::field::FieldAccessFlags; pub use crate::class_file::unvalidated::field::FieldInfo; pub use crate::class_file::unvalidated::method::MethodAccessFlags; pub use crate::class_file::unvalidated::method::MethodHandle; pub use crate::class_file::unvalidated::method::MethodHandleBehavior; pub use crate::class_file::unvalidated::method::MethodInfo; #[derive(Debug)] pub enum Error { BadMagic, BadIndex, ClassFileError(&'static str), EOF, BadInstruction(u8, bool), Str(&'static str), Unsupported(&'static str), } impl From<std::io::Error> for Error { fn from(_err: std::io::Error) -> Self { // TODO handle errors that aren't _actually_ end of file? Error::EOF } }
use crate::schema::order_detail; use chrono::NaiveDateTime; use uuid::Uuid; #[derive( Clone, Debug, Serialize, Associations, Deserialize, PartialEq, Identifiable, Queryable, Insertable, )] #[table_name = "order_detail"] pub struct OrderDetail { pub id: i32, pub order_id: i32, pub shop_id: Uuid, pub state: i32, pub txt: serde_json::Value, pub req_session_id: serde_json::Value, pub created_at: NaiveDateTime, pub updated_at: Option<NaiveDateTime>, pub deleted_at: Option<NaiveDateTime>, }
extern crate rand; use std::marker::PhantomData; pub struct Cubby<C,V,T> { ents: Box<[C]>, dead: V, _pd: PhantomData<T>, } impl<C:BackendC<T>,V:BackendV,T:Send+Sync> Cubby<C,V,T> { pub fn new<F: Fn(Ent<T>) -> C, F2: Fn(Vec<usize>) -> V> (f:F,f2:F2, s:usize) -> Cubby<C,V,T> { let mut c = vec!(); for _ in (0..s) { let r = f((0,None)); c.push(r); } let mut v = vec!(); for n in (0..s).rev() { v.push(n); } Cubby { ents: c.into_boxed_slice(), dead: f2(v), _pd: PhantomData } } pub fn with<W, F: Fn(&T) -> W> (&self, e: Eid, f: F) -> Result<W,EntErr> { self.ents[e.0] .with(|r| if r.0 == e.1 { if let Some(ref r) = r.1 { Ok(f(r)) } else { Err(EntErr::NoData) } } else { Err(EntErr::Invalid) } ).unwrap() } pub fn with_mut<W, F: FnOnce(&mut T) -> W> (&self, e: Eid, f: F) -> Result<W,EntErr> { self.ents[e.0]. with_mut(|mut w| if w.0 == e.1 { if let Some(ref mut w) = w.1 { Ok(f(w)) } else { Err(EntErr::NoData) } } else { Err(EntErr::Invalid) } ).unwrap() } pub fn add (&self, i: T) -> Result<Eid,EntErr> { let d = try!(self.dead.with_mut(|mut v| v.pop())); if let Some(idx) = d { let rid = rand::random::<u64>(); self.ents[idx] .with_mut(|mut w| *w = (rid,Some(i))); Ok((idx,rid)) } else { Err(EntErr::Maxed) } } pub fn remove (&self, e:Eid) -> bool { self.ents[e.0] .with_mut(|mut w| if w.0 == e.1 { w.0 = 0; if self.dead.with_mut(|mut v| v.push(e.0)).is_ok() { true } else{false} } else { false } ).unwrap() } pub fn find<F: FnMut(&T) -> bool> (&self, mut f: F) -> Vec<Eid> { let mut v = vec!(); let mut b = false; for (i,e) in self.ents.iter().enumerate() { e.with(|rl| if rl.0 > 0 { if let Some(ref r) = rl.1 { if f(r) { v.push((i,rl.0)); } } else { b=true; } //quit at first None }); if b {break} } v } pub fn first<F: Fn(&T) -> bool> (&self, f: F) -> Option<Eid> { let mut b = false; let mut rv = None; for (i,e) in self.ents.iter().enumerate() { e.with(|r| if r.0 > 0 { if let Some(ref v) = r.1 { if f(v) { rv = Some((i,r.0));b=true; } } else { b=true; } //quit at first None }); if b {break;} } rv } // todo: consider bool, like a 'while' filter // also consider impl collection style iterator pub fn each<F: FnMut(&T) -> Option<EntErr>> (&self, mut f: F) { let mut b = false; for e in self.ents.iter() { e.with(|rl| if rl.0 > 0 { if let Some(ref r) = rl.1 { if let Some(r) = f(r) { match r { EntErr::Break => {b=true;}, //escape hatch _ => (), } } } else { b=true; } //quit at first None }); if b { break; } } } pub fn each_mut<F: FnMut(&mut T) -> Option<EntErr>> (&self, mut f: F) { let mut b = false; for e in self.ents.iter() { e.with_mut(|wl| if wl.0 > 0 { if let &mut Some(ref mut w) = &mut wl.1 { if let Some(r) = f(w) { match r { EntErr::Break => {b=true;}, //escape hatch _ => (), } } } else {b=true;} }); if b {break;} } } } #[derive(Debug)] pub enum EntErr { NoData, Invalid, Maxed, Break, //break from an 'each' call } pub type Eid = (usize,u64); pub type Ent<T> = (u64,Option<T>); pub trait BackendC<T> { fn with<W,F: FnMut(&Ent<T>) -> W> (&self,F) -> Result<W,EntErr>; fn with_mut<W,F: FnOnce(&mut Ent<T>) -> W> (&self,F) -> Result<W,EntErr>; //&mut Ent<T>; } pub trait BackendV { fn with_mut<W,F: FnOnce(&mut Vec<usize>) -> W> (&self,F) -> Result<W,EntErr>; }
#![crate_name = "locale"] #![crate_type = "rlib"] #![crate_type = "dylib"] //! Localisation is hard. //! //! Getting your program to work well in multiple languages is a world fraught with edge-cases, //! minor grammatical errors, and most importantly, subtle things that don't map over well that you //! have absolutely no idea are different in other cultures. //! //! Many people are aware of the simpler ones, such as whether to use decimal points or decimal //! commas, or that the names of the months are different in other languages. But there are also //! different ways to format dates and times, or variations on what day the week begins. It's //! perfectly possible to write your program unaware of how these things have to be changed at all, //! and that's why it's so hard. extern crate libc; use std::fmt::Display; use std::io::Result; /// Trait defining how to obtain various components of a locale. /// /// Use implementation of this trait to construct parts of the `Locale` object. /// /// There may be various methods for obtaining locale data. The lowest common denominator is /// standard C library. It is however quite limited and some systems (notably Android) don't /// actually contain the corresponding data. Many systems also provide additional configurability /// for the locale setting (Windows, KDE, etc.) that are only accessible via that system's specific /// interface. So this trait exists to allow combining the methods for obtaining the data. /// /// The implementations for individual locale categories are returned boxed, because they may need /// to be polymorphic _and_ in options to allow combining partial implementations. Creating locale /// data is not a performance critical operation, so dynamic polymrphism is used for sake of /// simplicity. /// /// All methods default to simply returning None, again so partial implementations that delegate to /// another factory are possible. See `CompositeLocaleFactory`. pub trait LocaleFactory { /// Get implementation of the Numeric locale category. fn get_numeric(&mut self) -> Option<Box<Numeric>> { None } /// Get implementation of the Time locale category. fn get_time(&mut self) -> Option<Box<Time>> { None } } /// Auxiliary class for creating composing partial implementations of locale factories. // FIXME: Create (doc) test when there actually is another implementation to substitute. #[derive(Debug, Clone)] pub struct CompositeLocaleFactory<First: LocaleFactory, Second: LocaleFactory> { first: First, second: Second, } impl<F: LocaleFactory, S: LocaleFactory> CompositeLocaleFactory<F, S> { pub fn new(first: F, second: S) -> Self { CompositeLocaleFactory::<F, S> { first: first, second: second } } } impl<F: LocaleFactory, S: LocaleFactory> LocaleFactory for CompositeLocaleFactory<F, S> { // XXX: Make a macro for this fn get_numeric(&mut self) -> Option<Box<Numeric>> { if let Some(v) = self.first.get_numeric() { Some(v) } else { self.second.get_numeric() } } fn get_time(&mut self) -> Option<Box<Time>> { if let Some(v) = self.first.get_time() { Some(v) } else { self.second.get_time() } } } /// Factory of invariant locales. /// /// Invariant locale, called "C" or "POSIX" by standard C library locale functions, is default /// locale definitions for when no information about desired locale is available or localization is /// turned off. #[derive(Debug, Clone, Default)] pub struct InvariantLocaleFactory; impl InvariantLocaleFactory { /// Constructs invariant locale factory. /// /// The signature is just so that it matches the other locale factories so the classes can be /// substituted depending on target operating system and the code using them does not have to /// care. #[allow(unused_variables)] pub fn new(locale: &str) -> Result<Self> { Ok(InvariantLocaleFactory) } } impl LocaleFactory for InvariantLocaleFactory { // NOTE: Yep, it's empty. This just returns nothing and the Locale constructor will take care // of the actual defaults. } #[cfg(target_os = "linux")] pub mod linux; #[cfg(target_os = "linux")] pub use linux::LibCLocaleFactory as SystemLocaleFactory; // FIXME: #[cfg(target_os = "macos")], but for the moment I need to test whether it compiles, don't // have MacOS box nor cross-compiler and it does not actually contain anything system-specific yet pub mod macos; #[cfg(target_os = "macos")] pub use macos::MacOSLocaleFactory as SystemLocaleFactory; #[cfg(not(any(target_os = "linux", target_os = "macos")))] pub use InvariantLocaleFactory as SystemLocaleFactory; /// Return LocaleFactory appropriate for default user locale, as far as it can be determined. /// /// The returned locale factory provides locale facets implemented using standard localization /// functionality of the underlying operating system and configured for user's default locale. // // FIXME: The global instance should simply default-initialize to default user locale with proper // fallback if it fails to construct and then we don't need this. pub fn user_locale_factory() -> SystemLocaleFactory { // FIXME: Error handling? Constructing locale with "" should never fail as far as I can tell. SystemLocaleFactory::new("").unwrap() } // ---- locale facets ---- // ---- numeric stuff ---- /// Information on how to format numbers. #[derive(Debug, Clone)] pub struct Numeric { /// The punctuation that separates the decimal part of a non-integer number. Usually a decimal /// point or a decimal comma. pub decimal_sep: String, /// The punctuation that separates groups of digits in long numbers. pub thousands_sep: String, } impl Numeric { pub fn load_user_locale() -> Result<Numeric> { if let Ok(mut factory) = SystemLocaleFactory::new("") { if let Some(numeric) = factory.get_numeric() { return Ok(*numeric); } } Ok(Numeric::english()) } pub fn english() -> Numeric { Numeric::new(".", ",") } pub fn new(decimal_sep: &str, thousands_sep: &str) -> Numeric { Numeric { decimal_sep: decimal_sep.to_string(), thousands_sep: thousands_sep.to_string(), } } pub fn format_int<I: Display>(&self, input: I) -> String { let s = input.to_string(); let mut buf = String::new(); for (i, c) in s.chars().enumerate() { buf.push(c); if (s.len() - i - 1) % 3 == 0 && i != s.len() - 1 { buf.push_str(&self.thousands_sep[..]); } } buf } pub fn format_float<F: Display>(&self, input: F, decimal_places: usize) -> String { format!("{:.*}", decimal_places, input).replace(".", &self.decimal_sep) } } // ---- time stuff --- #[derive(Debug, Clone)] pub struct Time { month_names: Vec<String>, long_month_names: Vec<String>, day_names: Vec<String>, long_day_names: Vec<String>, } impl Time { pub fn load_user_locale() -> Result<Time> { if let Ok(mut factory) = SystemLocaleFactory::new("") { if let Some(time) = factory.get_time() { return Ok(*time); } } Ok(Time::english()) } pub fn english() -> Time { Time { month_names: vec![ "Jan".to_string(), "Feb".to_string(), "Mar".to_string(), "Apr".to_string(), "May".to_string(), "Jun".to_string(), "Jul".to_string(), "Aug".to_string(), "Sep".to_string(), "Oct".to_string(), "Nov".to_string(), "Dec".to_string(), ], long_month_names: vec![ "January".to_string(), "February".to_string(), "March".to_string(), "April".to_string(), "May".to_string(), "June".to_string(), "July".to_string(), "August".to_string(), "September".to_string(), "October".to_string(), "November".to_string(), "December".to_string(), ], day_names: vec![ "Sun".to_string(), "Mon".to_string(), "Tue".to_string(), "Wed".to_string(), "Thu".to_string(), "Fri".to_string(), "Sat".to_string(), ], long_day_names: vec![ "Sunday".to_string(), "Monday".to_string(), "Tuesday".to_string(), "Wednesday".to_string(), "Thursday".to_string(), "Friday".to_string(), "Saturday".to_string(), ], } } pub fn long_month_name(&self, months_from_january: usize) -> String { self.long_month_names[months_from_january].clone() } pub fn short_month_name(&self, months_from_january: usize) -> String { self.month_names[months_from_january].clone() } pub fn long_day_name(&self, days_from_sunday: usize) -> String { self.day_names[days_from_sunday].clone() } pub fn short_day_name(&self, days_from_sunday: usize) -> String { self.day_names[days_from_sunday].clone() } } // ---- tests ---- #[cfg(test)] mod test { use super::*; #[test] fn thousands_separator() { let numeric_options = Numeric::new("/", "="); assert_eq!("1=234=567".to_string(), numeric_options.format_int(1234567)) } #[test] fn thousands_separator_2() { let numeric_options = Numeric::new("/", "="); assert_eq!("123=456".to_string(), numeric_options.format_int(123456)) } #[test] fn thousands_separator_3() { let numeric_options = Numeric::new("/", "="); assert_eq!("12=345=678".to_string(), numeric_options.format_int(12345678)) } }
extern crate hyper; use futures::sync::mpsc::{unbounded, UnboundedReceiver}; use std::thread; use args::Config; use run_info::RunInfo; use misc::split_number; use tokio_core::reactor::Core; use chrono::{Local}; use hyper::{Client, Uri}; use std::str::FromStr; use hyper::client::HttpConnector; use std::net::lookup_host; use futures::{Future, stream}; use futures::future::ok; use futures::Stream; use futures_utils::stopwatch; use request_result::RequestResult; use errors::*; /// Delegates and manages all the work. pub struct Boss { /// Number of requests successfully completed pub requests_completed: usize, /// Number of active connections pub connections: usize, num_threads: usize, } impl Boss { pub fn new(num_threads: usize) -> Self { Boss { requests_completed: 0, connections: 0, num_threads: num_threads, } } pub fn start_workforce(&self, config: &Config) -> Result<RunInfo> { let (tx, rx) = unbounded(); let desired_connections_per_worker_iter = split_number(config.num_connections, self.num_threads); // resolve dns once and for all let resolved_url = resolve_dns(&config.url)?; let start_time = Local::now(); let wanted_end_time = start_time + config.duration; let run_duration = config.duration; // start num_threads workers for desired_connections_per_worker in desired_connections_per_worker_iter { let tx = tx.clone(); let timeout = config.timeout.to_std()?; let hyper_url = resolved_url.clone(); thread::spawn(move || { // TODO: how to use error_chain on tokio-core? let mut core = Core::new().expect("Failed to create Tokio core"); let hyper_client = hyper::Client::configure() .keep_alive_timeout(Some(timeout)) .build(&core.handle()); let iterator = (0..desired_connections_per_worker).map(|_| { create_looping_worker(hyper_url.clone(), &hyper_client) .take_while(|_| ok(Local::now() < wanted_end_time)) .fold(RunInfo::new(run_duration), |mut runinfo_acc, request_result| { runinfo_acc.add_request(&request_result); ok(runinfo_acc) }) }); // create stream of requests let request_stream = stream::futures_unordered(iterator) .for_each(move |run_info| { let tx = tx.clone(); let _ = tx.send(run_info); ok(()) }); // TODO: how to use error_chain with tokio? let _ = core.run(request_stream); }); } Ok(self.collect_workers(rx, config)) } /// Collects information from all workers fn collect_workers(&self, rx: UnboundedReceiver<RunInfo>, config: &Config) -> RunInfo { rx.take(config.num_connections as u64) .fold(RunInfo::new(config.duration), |mut runinfo_acc, run_info| { runinfo_acc.merge(&run_info); ok(runinfo_acc) }) .wait() .unwrap() } } // resolves the given url to an ip fn resolve_dns(url: &str) -> Result<Uri> { let parsed_url = Uri::from_str(url)?; let host = parsed_url.host().expect("DNS lookup failed"); let host = lookup_host(&host) .expect("DNS lookup failed") .filter(|x| x.is_ipv4()) .next() .expect("DNS lookup failed"); let uri = Uri::from_str(&format!("{}://{}:{}", parsed_url.scheme().unwrap(), host.ip(), parsed_url.port().unwrap())).unwrap(); Ok(uri) } fn create_looping_worker<'a>(url: Uri, hyper_client: &'a Client<HttpConnector>) -> impl Stream<Item = RequestResult, Error = ()> + 'a { stream::unfold(0u32, move |state| { let res = send_request(url.clone(), hyper_client); let fut = res.and_then(move |req| ok::<_, _>((req, state))); Some(fut) }) } fn send_request<C>(url: Uri, hyper_client: &Client<C>) -> impl Future<Item = RequestResult, Error = ()> where C: hyper::client::Connect { stopwatch(hyper_client.get(url)) .and_then(|(_, latency)| { let request_result = RequestResult::Success { latency: latency }; Ok(request_result) }) .or_else(|_| ok(RequestResult::Failure)) }
pub struct User { pub id: String, pub name: String, pub friend_ids: Vec<String>, pub workout_plan_ids: Vec<String>, }
use std::fmt::Display; use std::iter::FromIterator; use itertools::{Itertools, zip}; use board::group_access::GroupAccess; use board::stones::grouprc::GoGroupRc; use display::display::GoDisplay; use display::goshow::GoShow; use display::range::Range2; use rust_tools::screen::dimension::Dimension; use rust_tools::screen::drawer::Drawer; use rust_tools::screen::screen::Screen; use crate::board::go_state::GoState; use graph_lib::topology::Topology; pub struct BoardMap<T> { pub(crate) width: usize, pub(crate) height: usize, pub(crate) map: Vec<Option<T>>, pub(crate) cell_size: usize, } impl BoardMap<GoGroupRc> { pub fn from_board<T>(board: &GoState, cell_size: usize) -> BoardMap<T> { // log::info!("BOARDMAP::FROM_BOARD"); let width = board.gg.goban().size; let height = board.gg.goban().size; let size = width * height; let mut res = BoardMap { width, height, map: Vec::with_capacity(size), cell_size, }; for offset in 0..size { res.map.push(None); } res } pub fn new(board: &GoState, cell_size: usize) -> BoardMap<GoGroupRc> { let mut res = BoardMap::from_board(board, cell_size); for i in 0..board.gg.goban().vertex_number() { res.map.insert(i,Some(board.gg.group_at(i).clone())); } res } } impl<T> BoardMap<T> { pub fn xy(&self, cell: usize) -> (usize, usize) { let x = cell as usize % self.width; let y = cell as usize / self.width; (x, y) } pub fn get(&self, x: usize, y: usize) -> &Option<T> { &self.map[x + y * self.width] } pub fn map<U, F: Fn(&T) -> Option<U>>(self, func: F) -> BoardMap<U> { let size = self.width * self.height; let mut res = BoardMap { width: self.width, height: self.height, map: Vec::with_capacity(size), cell_size: self.cell_size, }; for i in 0..size { res.map.push(match &self.map[i] { None => None, Some(data) => func(data), }); } res } } impl<T: Display> BoardMap<T> { pub fn init_screen(&self, range: &Range2) -> Screen { let cell_size = self.cell_size; let w = range.x().len() * cell_size + 4; let h = range.y().len() + 3; let mut screen = Screen::new(w, h); let sep = vec!['-'; cell_size]; for (x, &y) in iproduct!(range.x(), &[0, h - 2]) { screen.put_slice(screen.at(3 + cell_size * x, y), sep.as_slice()); } for (&x, y) in iproduct!(&[2, w - 1], range.y()) { screen.put(screen.at(x, y + 1), '|'); } for (&x, &y) in iproduct!(&[2, w - 1], &[0, h - 2]) { screen.put(screen.at(x, y), '+'); } for y in range.y() { screen.put_str(screen.at(0, y + 1), &GoDisplay::line(y)); } for x in range.x() { screen.put_str(screen.at(1 + cell_size + x * cell_size, h - 1), &GoDisplay::column(x)); } screen } pub(crate) fn write_screen(&self, range: &Range2) -> Screen { let cell_size = self.cell_size; let mut screen = self.init_screen(range); for (x, y) in iproduct!(range.x(), range.y()) { let y_off = y + 1; let x_off = x * cell_size + 3; match self.get(x, y) { None => { let delta = cell_size - 1; screen.put(screen.at(x_off + delta, y_off), '.'); } Some(data) => { let text = data.to_string(); if text.len() > cell_size { let delta = text.len() - cell_size; screen.put_str(screen.at(x_off + delta, y_off), &text[delta..]); } else { let delta = cell_size - text.len(); screen.put_str(screen.at(x_off + delta, y_off), &text); } } } } screen } }
//! Parsers for the different QVM and related formats. use super::{Instruction, QVM, VM_MAGIC}; use opcodes::Opcode; use super::errors::*; use nom; use nom::{le_u32, le_u8}; type Input = u8; type InputSlice<'a> = &'a [Input]; /// Creates a named parser for an instruction that only consists of an opcode macro_rules! instruction { ($name:ident, $opcode:path, $instruction:path) => { named!($name<InputSlice,Instruction>, value!($instruction, tag!([$opcode as Input])) ); } } /// Creates a named parser for an instruction that has an operand macro_rules! instruction_with_operand { ($name:ident, $opcode:path, $operand_fn:ident, $instruction:path) => { named!($name<InputSlice,Instruction>, do_parse!( tag!([$opcode as Input]) >> operand: $operand_fn >> ($instruction(operand)) ) ); } } /// Creates a named parser for an instruction with `u32` operand macro_rules! instruction_u32 { ($name:ident, $opcode:path, $instruction:path) => { instruction_with_operand!($name, $opcode, le_u32, $instruction); } } /// Creates a named parser for an instruction with `u8` operand macro_rules! instruction_u8 { ($name:ident, $opcode:path, $instruction:path) => { instruction_with_operand!($name, $opcode, le_u8, $instruction); } } instruction!(instruction_undef, Opcode::UNDEF, Instruction::UNDEF); instruction!(instruction_ignore, Opcode::IGNORE, Instruction::IGNORE); instruction!(instruction_break, Opcode::BREAK, Instruction::BREAK); instruction_u32!(instruction_enter, Opcode::ENTER, Instruction::ENTER); instruction_u32!(instruction_leave, Opcode::LEAVE, Instruction::LEAVE); instruction!(instruction_call, Opcode::CALL, Instruction::CALL); instruction!(instruction_push, Opcode::PUSH, Instruction::PUSH); instruction!(instruction_pop, Opcode::POP, Instruction::POP); instruction_u32!(instruction_const, Opcode::CONST, Instruction::CONST); instruction_u32!(instruction_local, Opcode::LOCAL, Instruction::LOCAL); instruction!(instruction_jump, Opcode::JUMP, Instruction::JUMP); instruction_u32!(instruction_eq, Opcode::EQ, Instruction::EQ); instruction_u32!(instruction_ne, Opcode::NE, Instruction::NE); instruction_u32!(instruction_lti, Opcode::LTI, Instruction::LTI); instruction_u32!(instruction_lei, Opcode::LEI, Instruction::LEI); instruction_u32!(instruction_gti, Opcode::GTI, Instruction::GTI); instruction_u32!(instruction_gei, Opcode::GEI, Instruction::GEI); instruction_u32!(instruction_ltu, Opcode::LTU, Instruction::LTU); instruction_u32!(instruction_leu, Opcode::LEU, Instruction::LEU); instruction_u32!(instruction_gtu, Opcode::GTU, Instruction::GTU); instruction_u32!(instruction_geu, Opcode::GEU, Instruction::GEU); instruction_u32!(instruction_eqf, Opcode::EQF, Instruction::EQF); instruction_u32!(instruction_nef, Opcode::NEF, Instruction::NEF); instruction_u32!(instruction_ltf, Opcode::LTF, Instruction::LTF); instruction_u32!(instruction_lef, Opcode::LEF, Instruction::LEF); instruction_u32!(instruction_gtf, Opcode::GTF, Instruction::GTF); instruction_u32!(instruction_gef, Opcode::GEF, Instruction::GEF); instruction!(instruction_load1, Opcode::LOAD1, Instruction::LOAD1); instruction!(instruction_load2, Opcode::LOAD2, Instruction::LOAD2); instruction!(instruction_load4, Opcode::LOAD4, Instruction::LOAD4); instruction!(instruction_store1, Opcode::STORE1, Instruction::STORE1); instruction!(instruction_store2, Opcode::STORE2, Instruction::STORE2); instruction!(instruction_store4, Opcode::STORE4, Instruction::STORE4); instruction_u8!(instruction_arg, Opcode::ARG, Instruction::ARG); instruction_u32!(instruction_block_copy, Opcode::BLOCK_COPY, Instruction::BLOCK_COPY); instruction!(instruction_sex8, Opcode::SEX8, Instruction::SEX8); instruction!(instruction_sex16, Opcode::SEX16, Instruction::SEX16); instruction!(instruction_negi, Opcode::NEGI, Instruction::NEGI); instruction!(instruction_add, Opcode::ADD, Instruction::ADD); instruction!(instruction_sub, Opcode::SUB, Instruction::SUB); instruction!(instruction_divi, Opcode::DIVI, Instruction::DIVI); instruction!(instruction_divu, Opcode::DIVU, Instruction::DIVU); instruction!(instruction_modi, Opcode::MODI, Instruction::MODI); instruction!(instruction_modu, Opcode::MODU, Instruction::MODU); instruction!(instruction_muli, Opcode::MULI, Instruction::MULI); instruction!(instruction_mulu, Opcode::MULU, Instruction::MULU); instruction!(instruction_band, Opcode::BAND, Instruction::BAND); instruction!(instruction_bor, Opcode::BOR, Instruction::BOR); instruction!(instruction_bxor, Opcode::BXOR, Instruction::BXOR); instruction!(instruction_bcom, Opcode::BCOM, Instruction::BCOM); instruction!(instruction_lsh, Opcode::LSH, Instruction::LSH); instruction!(instruction_rshi, Opcode::RSHI, Instruction::RSHI); instruction!(instruction_rshu, Opcode::RSHU, Instruction::RSHU); instruction!(instruction_negf, Opcode::NEGF, Instruction::NEGF); instruction!(instruction_addf, Opcode::ADDF, Instruction::ADDF); instruction!(instruction_subf, Opcode::SUBF, Instruction::SUBF); instruction!(instruction_divf, Opcode::DIVF, Instruction::DIVF); instruction!(instruction_mulf, Opcode::MULF, Instruction::MULF); instruction!(instruction_cvif, Opcode::CVIF, Instruction::CVIF); instruction!(instruction_cvfi, Opcode::CVFI, Instruction::CVFI); named!(ins<InputSlice,Instruction>, alt!(instruction_undef | instruction_ignore | instruction_break | instruction_enter | instruction_leave | instruction_call | instruction_push | instruction_pop | instruction_const | instruction_local | instruction_jump | instruction_eq | instruction_ne | instruction_lti | instruction_lei | instruction_gti | instruction_gei | instruction_ltu | instruction_leu | instruction_gtu | instruction_geu | instruction_eqf | instruction_nef | instruction_ltf | instruction_lef | instruction_gtf | instruction_gef | instruction_load1 | instruction_load2 | instruction_load4 | instruction_store1 | instruction_store2 | instruction_store4 | instruction_arg | instruction_block_copy | instruction_sex8 | instruction_sex16 | instruction_negi | instruction_add | instruction_sub | instruction_divi | instruction_divu | instruction_modi | instruction_modu | instruction_muli | instruction_mulu | instruction_band | instruction_bor | instruction_bxor | instruction_bcom | instruction_lsh | instruction_rshi | instruction_rshu | instruction_negf | instruction_addf | instruction_subf | instruction_divf | instruction_mulf | instruction_cvif | instruction_cvfi ) ); macro_rules! length_size( ($i:expr, $s:expr, $submac:ident!( $($args:tt)* )) => ( { match take!($i, $s as usize) { nom::IResult::Error(e) => nom::IResult::Error(e), nom::IResult::Incomplete(nom::Needed::Unknown) => nom::IResult::Incomplete(nom::Needed::Unknown), nom::IResult::Incomplete(nom::Needed::Size(n)) => { nom::IResult::Incomplete(nom::Needed::Size( n + nom::InputLength::input_len(&($i)) - ($s) )) }, nom::IResult::Done(i2, o2) => { match complete!(o2, $submac!($($args)*)) { nom::IResult::Error(e) => nom::IResult::Error(e), nom::IResult::Incomplete(i) => nom::IResult::Incomplete(i), nom::IResult::Done(_, o3) => nom::IResult::Done(i2, o3) } } } } ); ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => ( length_value!($i, $submac!($($args)*), call!($g)); ); ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => ( length_value!($i, call!($f), $submac!($($args)*)); ); ($i:expr, $f:expr, $g:expr) => ( length_value!($i, call!($f), call!($g)); ); ); const HEADER_LENGTH_V1: u32 = 32; named!(qvm<InputSlice, QVM>, do_parse!( tag!(VM_MAGIC) >> // magic: le_u32 >> instruction_count: le_u32 >> code_offset: le_u32 >> code_length: le_u32 >> data_offset: le_u32 >> data_length: le_u32 >> lit_length: le_u32 >> bss_length: le_u32 >> // Read padding between header and code segment take!(code_offset - HEADER_LENGTH_V1) >> code: length_size!( code_length as usize, count!(ins, instruction_count as usize) ) >> // Read padding between code and data segment take!(data_offset - code_offset - code_length) >> data: length_size!( data_length as usize, count!(le_u32, data_length as usize / 4) ) >> // lit segment is always aligned, no padding here lit: length_size!( lit_length as usize, count!(le_u8, lit_length as usize) ) >> eof!() >> ( QVM { code: code, data: data, lit: lit, bss_length: bss_length, } ) ) ); /// Tries to parse a QVM from a byte slice. pub fn parse_qvm(data: InputSlice) -> Result<QVM> { match qvm(data).to_full_result() { Ok(v) => Ok(v), Err(e) => Err(ErrorKind::Parser(e).into()), } } #[cfg(test)] mod tests { use super::{instruction_break, instruction_enter, instruction_arg, ins, qvm, parse_qvm, InputSlice}; use bytecode::Instruction; use nom::IResult; use nom; use QVM; /// q3asm reserves the stack in the BSS segment const Q3ASM_STACK_SIZE: usize = 0x10000; #[test] fn test_instruction_break_exact_match() { let data = [0x2]; let result = instruction_break(&data); assert_eq!(result, IResult::Done(&b""[..], Instruction::BREAK)); } #[test] fn test_instruction_break_tag_mismatch() { let data = [0x0]; let result = instruction_break(&data); assert_eq!(result, IResult::Error(nom::ErrorKind::Tag)); } #[test] fn test_instruction_enter_exact_match() { let data = [0x3, 0x42, 0x0, 0x0, 0x0]; let result = instruction_enter(&data); assert_eq!(result, IResult::Done(&b""[..], Instruction::ENTER(0x42))); } #[test] fn test_instruction_arg_exact_match() { let data = [0x21, 0x42]; let result = instruction_arg(&data); assert_eq!(result, IResult::Done(&b""[..], Instruction::ARG(0x42))); } #[test] fn test_ins_enter_exact_match() { let data = [0x3, 0x42, 0x0, 0x0, 0x0]; let result = ins(&data); assert_eq!(result, IResult::Done(&b""[..], Instruction::ENTER(0x42))); } #[test] fn test_qvm_file_minimal() { let data = include_bytes!("../assets/mod-minimal.qvm"); let result = qvm(data); let expected = QVM { code: vec![Instruction::ENTER(8), Instruction::CONST(4294967295), // TODO: This is actually -1, need to rethink types! Instruction::LEAVE(8), Instruction::PUSH, Instruction::LEAVE(8)], data: vec![0], lit: vec![], bss_length: Q3ASM_STACK_SIZE as u32, }; assert_eq!(result, IResult::Done(&b""[..], expected)); } #[test] fn test_qvm_file_bss() { let data = include_bytes!("../assets/mod-bss.qvm"); let result = qvm(data); let expected = QVM { code: vec![Instruction::ENTER(8), Instruction::CONST(4294967295), // TODO: This is actually -1, need to rethink types! Instruction::LEAVE(8), Instruction::PUSH, Instruction::LEAVE(8)], data: vec![0], lit: vec![], bss_length: Q3ASM_STACK_SIZE as u32 + 4, }; assert_eq!(result, IResult::Done(&b""[..], expected)); } #[test] fn test_qvm_file_data() { let data = include_bytes!("../assets/mod-data.qvm"); let result = qvm(data); let expected = QVM { code: vec![Instruction::ENTER(8), Instruction::CONST(4294967295), // TODO: This is actually -1, need to rethink types! Instruction::LEAVE(8), Instruction::PUSH, Instruction::LEAVE(8)], data: vec![ 0, // for alignment? 0xDEADBEEF, ], lit: vec![], bss_length: Q3ASM_STACK_SIZE as u32, }; assert_eq!(result, IResult::Done(&b""[..], expected)); } #[test] fn test_qvm_file_lit() { let data = include_bytes!("../assets/mod-lit.qvm"); let result = qvm(data); let expected = QVM { code: vec![Instruction::ENTER(8), Instruction::CONST(4294967295), // TODO: This is actually -1, need to rethink types! Instruction::LEAVE(8), Instruction::PUSH, Instruction::LEAVE(8)], data: vec![0], lit: vec![ '!' as u8, 0, // padding for aligment? 0, 0, ], bss_length: Q3ASM_STACK_SIZE as u32, }; assert_eq!(result, IResult::Done(&b""[..], expected)); } #[test] fn test_ins_file() { let data = include_bytes!("../assets/mod-minimal.qvm"); named!(ins5<InputSlice,Vec<Instruction>>, count!(ins, 5)); let result = ins5(&data[32..53]); let expected = vec![Instruction::ENTER(8), Instruction::CONST(4294967295), // TODO: This is actually -1, need to rethink types! Instruction::LEAVE(8), Instruction::PUSH, Instruction::LEAVE(8)]; assert_eq!(result, IResult::Done(&b""[..], expected)); } // TODO: This is more of an integration test #[test] // TODO: This test won't work due to v2 magic, which is unimplemented #[ignore] fn test_parse_qvm_ioq3_qagame() { let data = include_bytes!("../assets/ioq3/baseq3/vm/qagame.qvm"); let result = parse_qvm(data).unwrap(); // TODO: What to assert here? } }
use std::cmp::{Eq, PartialEq}; use std::ops::{Add, Div, Mul, Neg, Sub}; use crate::geometry::dq::DualQuaternion; // Equality: DualQuaternion impl PartialEq<DualQuaternion> for DualQuaternion { fn eq(&self, other: &DualQuaternion) -> bool { let q1 = self; let q2 = other; q1.p == q2.p && q1.d == q2.d } } // Equality: RHS scalar impl PartialEq<f64> for DualQuaternion { fn eq(&self, other: &f64) -> bool { let q1 = self; let q2 = DualQuaternion::new_real_quaternion(*other); q1.p == q2.p && q1.d == q2.d } } // Equality: LHS scalar impl PartialEq<DualQuaternion> for f64 { fn eq(&self, other: &DualQuaternion) -> bool { let q1 = DualQuaternion::new_real_quaternion(*self); let q2 = other; q1.p == q2.p && q1.d == q2.d } } impl Eq for DualQuaternion {} // Addition: DualQuaternion impl Add<DualQuaternion> for DualQuaternion { type Output = DualQuaternion; fn add(self, q2: DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p + q2.p; let d = q1.d + q2.d; DualQuaternion::from_parts(p, d) } } // Addition: DualQuaternion Reference impl Add<&DualQuaternion> for DualQuaternion { type Output = DualQuaternion; fn add(self, q2: &DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p + q2.p; let d = q1.d + q2.d; DualQuaternion::from_parts(p, d) } } impl Add<DualQuaternion> for &DualQuaternion { type Output = DualQuaternion; fn add(self, q2: DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p + q2.p; let d = q1.d + q2.d; DualQuaternion::from_parts(p, d) } } impl Add<&DualQuaternion> for &DualQuaternion { type Output = DualQuaternion; fn add(self, q2: &DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p + q2.p; let d = q1.d + q2.d; DualQuaternion::from_parts(p, d) } } // Addition: RHS scalar impl Add<f64> for DualQuaternion { type Output = DualQuaternion; #[inline] fn add(self, rhs: f64) -> DualQuaternion { self + DualQuaternion::new_real_quaternion(rhs) } } // Addition: LHS scalar impl Add<DualQuaternion> for f64 { type Output = DualQuaternion; #[inline] fn add(self, rhs: DualQuaternion) -> DualQuaternion { DualQuaternion::new_real_quaternion(self) + rhs } } // Subtraction: DualQuaternion impl Sub<DualQuaternion> for DualQuaternion { type Output = DualQuaternion; fn sub(self, q2: DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p - q2.p; let d = q1.d - q2.d; DualQuaternion::from_parts(p, d) } } // Subtraction: DualQuaternion Reference impl Sub<&DualQuaternion> for DualQuaternion { type Output = DualQuaternion; fn sub(self, q2: &DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p - q2.p; let d = q1.d - q2.d; DualQuaternion::from_parts(p, d) } } impl Sub<DualQuaternion> for &DualQuaternion { type Output = DualQuaternion; fn sub(self, q2: DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p - q2.p; let d = q1.d - q2.d; DualQuaternion::from_parts(p, d) } } impl Sub<&DualQuaternion> for &DualQuaternion { type Output = DualQuaternion; fn sub(self, q2: &DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p - q2.p; let d = q1.d - q2.d; DualQuaternion::from_parts(p, d) } } // Substraction: RHS scalar impl Sub<f64> for DualQuaternion { type Output = DualQuaternion; #[inline] fn sub(self, rhs: f64) -> DualQuaternion { self - DualQuaternion::new_real_quaternion(rhs) } } // Substraction: LHS scalar impl Sub<DualQuaternion> for f64 { type Output = DualQuaternion; #[inline] fn sub(self, rhs: DualQuaternion) -> DualQuaternion { DualQuaternion::new_real_quaternion(self) - rhs } } // Multiplication: DualQuaternion impl Mul<DualQuaternion> for DualQuaternion { type Output = DualQuaternion; #[inline] fn mul(self, q2: DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p * q2.p; let d = q1.p * q2.d + q1.d * q2.p; DualQuaternion::from_parts(p, d) } } // Multiplaction: DualQuaternion Reference impl Mul<&DualQuaternion> for DualQuaternion { type Output = DualQuaternion; #[inline] fn mul(self, q2: &DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p * q2.p; let d = q1.p * q2.d + q1.d * q2.p; DualQuaternion::from_parts(p, d) } } impl Mul<DualQuaternion> for &DualQuaternion { type Output = DualQuaternion; #[inline] fn mul(self, q2: DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p * q2.p; let d = q1.p * q2.d + q1.d * q2.p; DualQuaternion::from_parts(p, d) } } impl Mul<&DualQuaternion> for &DualQuaternion { type Output = DualQuaternion; #[inline] fn mul(self, q2: &DualQuaternion) -> DualQuaternion { let q1 = &self; let p = q1.p * q2.p; let d = q1.p * q2.d + q1.d * q2.p; DualQuaternion::from_parts(p, d) } } // Multiplaction: RHS scalar impl Mul<f64> for DualQuaternion { type Output = DualQuaternion; #[inline] fn mul(self, rhs: f64) -> DualQuaternion { DualQuaternion::from_parts(self.p * rhs, self.d * rhs) } } // Multiplaction: LHS scalar impl Mul<DualQuaternion> for f64 { type Output = DualQuaternion; #[inline] fn mul(self, rhs: DualQuaternion) -> DualQuaternion { DualQuaternion::from_parts(self * rhs.p, self * rhs.d) } } // Division: DualQuaternion impl Div<DualQuaternion> for DualQuaternion { type Output = DualQuaternion; #[inline] fn div(self, rhs: DualQuaternion) -> DualQuaternion { let q1 = &self; let q2 = &rhs; let a = q1.p; let b = q1.d; let c = q2.p; let d = q2.d; DualQuaternion::from_parts( a.right_div(&c).unwrap(), (b * c - a * d).right_div(&c.powf(2.)).unwrap(), ) } } // Negation: DualQuaternion impl Neg for DualQuaternion { type Output = DualQuaternion; #[inline] fn neg(self) -> DualQuaternion { let p = -self.p; let d = -self.d; DualQuaternion::from_parts(p, d) } }