text stringlengths 8 4.13M |
|---|
use js_function_promisify::Callback;
use wasm_bindgen_test::*;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn readme_example() {
let future = Callback::new(|| Ok("Hello future!".into()));
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(future.as_function().as_ref(), 500)
.unwrap();
let result = future.await; // result: Result<JsValue, JsValue>
assert_eq!(result.is_ok(), true); // Assert `Ok`
assert_eq!(result.unwrap().as_string().unwrap(), "Hello future!"); // Assert the result exactly equals the string
}
|
use crate::projections::conic;
use crate::projections::pseudoconic;
use crate::projections::cylindric;
use crate::projections::pseudocylindric;
use crate::projections::projection_types::Projection;
use crate::projections::projection_types::ProjectionType;
use crate::chart_and_js_exports::JSProjectionParams;
fn list_projections() -> Vec<Projection> {
vec![
Projection {
name: "Simple Equidistant Conic".to_string(),
projection_function: Box::new(conic::simple_equidistant_conic),
projection_type: ProjectionType::Conic,
params: JSProjectionParams::JSPointsTwoStandardPar,
},
Projection {
name: "Lambert Conformal Conic".to_string(),
projection_function: Box::new(conic::lambert_conformal_conic),
projection_type: ProjectionType::Conic,
params: JSProjectionParams::JSPointsTwoStandardPar,
},
Projection {
name: "Sinusoidal".to_string(),
projection_function: Box::new(pseudocylindric::sinusoidal),
projection_type: ProjectionType::PseudoCylindric,
params: JSProjectionParams::JSPointsOnly,
},
Projection {
name: "Loximuthal".to_string(),
projection_function: Box::new(pseudocylindric::loximuthal),
projection_type: ProjectionType::PseudoCylindric,
params: JSProjectionParams::JSPointsStandardPar,
},
Projection {
name: "Mercator".to_string(),
projection_function: Box::new(cylindric::mercator),
projection_type: ProjectionType::Cylindric,
params: JSProjectionParams::JSPointsOnly,
},
Projection {
name: "Equirectangular".to_string(),
projection_function: Box::new(cylindric::equirectangular),
projection_type: ProjectionType::Cylindric,
params: JSProjectionParams::JSPointsOnly,
},
Projection {
name: "Bonne".to_string(),
projection_function: Box::new(pseudoconic::bonne),
projection_type: ProjectionType::PseudoConic,
params: JSProjectionParams::JSPointsStandardPar,
},
]
}
pub fn use_projection(projection_name: String) -> Option<Projection> {
list_projections().into_iter().find(
|proj| proj.name == projection_name
)
}
|
use super::mem_map::{WRAM_END, WRAM_START};
pub struct Wram {
bytes: Box<[u8]>,
}
impl Wram {
pub fn new() -> Wram {
const LENGTH: usize = (WRAM_END - WRAM_START + 1) as usize;
Wram {
bytes: Box::new([0; LENGTH]),
}
}
pub fn read_byte(&self, addr: u16) -> u8 {
self.bytes[addr as usize]
}
pub fn write_byte(&mut self, addr: u16, value: u8) {
self.bytes[addr as usize] = value;
}
}
|
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use thiserror::Error;
/// Defines the Logger configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggerConfig {
// Todo: check if an enum can be used
/// The Logger level
/// Valid values: trace, debug, info, warn, error
pub level: String,
/// Determines whether the Logger should print to standard output.
/// Valid values: true, false
pub stdout_output: bool,
/// A file path in the file system; if provided, the Logger will append any output to it.
pub file_output_path: Option<String>,
// #[structopt(short = "o", long = "value_one", default_value = "10000")]
// pub module_level: HashMap<String, String>,
}
impl Default for LoggerConfig {
fn default() -> Self {
LoggerConfig { level: "info".to_owned(), stdout_output: false, file_output_path: None }
}
}
#[derive(Error, Debug)]
pub enum LoggerError {
#[error("LoggerConfigurationError: [{message}]")]
LoggerConfigurationError { message: String },
}
impl From<log::SetLoggerError> for LoggerError {
fn from(error: log::SetLoggerError) -> Self {
LoggerError::LoggerConfigurationError { message: format!("{}", error) }
}
}
impl From<std::io::Error> for LoggerError {
fn from(error: std::io::Error) -> Self {
LoggerError::LoggerConfigurationError { message: format!("{}", error) }
}
}
/// Configures the underlying logger implementation and activates it.
pub fn setup_logger(logger_config: &LoggerConfig) -> Result<(), LoggerError> {
let mut log_dispatcher = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message
))
})
.level(log::LevelFilter::from_str(&logger_config.level).map_err(|err| {
LoggerError::LoggerConfigurationError {
message: format!(
"The specified logger level is not valid: [{}]. err: {}",
&logger_config.level, err
),
}
})?);
/*
for (module, level) in logger_config.module_level.iter() {
log_dispatcher =
log_dispatcher.level_for(module.to_owned(), log::LevelFilter::from_str(level).unwrap())
}
*/
log_dispatcher = log_dispatcher
.level_for("hyper".to_owned(), log::LevelFilter::Warn)
.level_for("mio".to_owned(), log::LevelFilter::Warn)
.level_for("rants".to_owned(), log::LevelFilter::Warn)
.level_for("tokio_io".to_owned(), log::LevelFilter::Warn)
.level_for("tokio_reactor".to_owned(), log::LevelFilter::Warn)
.level_for("tokio_tcp".to_owned(), log::LevelFilter::Warn)
.level_for("tokio_uds".to_owned(), log::LevelFilter::Warn)
.level_for("tokio_util".to_owned(), log::LevelFilter::Warn);
if logger_config.stdout_output {
log_dispatcher = log_dispatcher.chain(std::io::stdout());
}
if let Some(path) = &logger_config.file_output_path {
log_dispatcher = log_dispatcher.chain(fern::log_file(&path)?)
}
log_dispatcher.apply()?;
Ok(())
}
|
use std::{
alloc::Layout,
marker::PhantomData,
mem::{align_of, size_of},
ptr::{null_mut, NonNull},
};
use libc::{
c_void, mmap, mprotect, munmap, MAP_ANONYMOUS, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE,
};
const PAGE_SIZE: usize = 4096;
const MAX_ELEMENTS: usize = usize::MAX / 2;
pub struct VirtualVec<T> {
map: usize,
cap: usize,
len: usize,
ptr: NonNull<T>,
_marker: PhantomData<T>,
}
#[cold]
#[inline(never)]
fn bounds_check_failed(index: usize, len: usize) {
panic!("index `{}` beyond VirtualVec length `{}`", index, len);
}
#[cold]
#[inline(never)]
fn capacity_overflow(len: usize) {
panic!("capacity of `{}` too large for VirtualVec", len);
}
#[cold]
#[inline(never)]
fn mapping_reserve(layout: Layout) -> *mut c_void {
unsafe {
mmap(
null_mut(),
layout.size(),
PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS,
0,
0,
)
}
}
#[cold]
#[inline(never)]
fn mapping_commit(addr: *mut c_void, len: usize) {
unsafe {
mprotect(addr, len, PROT_READ | PROT_WRITE);
}
}
impl<T> VirtualVec<T> {
#[cold]
pub fn new(map: usize) -> Self {
if size_of::<T>() == 0 {
panic!("cannot create a VirtualVec containing a ZST")
}
if align_of::<T>() > PAGE_SIZE {
panic!("alignment for type too large")
}
if map > MAX_ELEMENTS {
panic!("too many elements in map")
}
if map == 0 {
panic!("cannot create a VirtualVec without any backing storage")
}
let layout = Layout::array::<T>(map).expect("mapping too large");
let ptr = unsafe {
let mapping = mapping_reserve(layout);
let ptr = std::mem::transmute::<*mut c_void, *mut T>(mapping);
NonNull::new(ptr).expect("could not create memory mapping")
};
Self {
map,
cap: 0,
len: 0,
ptr,
_marker: PhantomData,
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn capacity(&self) -> usize {
self.cap
}
#[inline]
pub fn mapping(&self) -> usize {
self.map
}
#[inline]
pub fn as_ptr(&self) -> *const T {
self.ptr.as_ptr()
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.ptr.as_ptr()
}
pub fn truncate(&mut self, len: usize) {
unsafe {
if len >= self.len {
return;
}
let remaining_len = self.len - len;
let s = std::ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
self.len = len;
std::ptr::drop_in_place(s);
}
}
pub fn clear(&mut self) {
// SAFETY: We must adjust the length before dropping the slice in case the drop
// operation panics and leaves us with a vector pointing to invalid objects.
unsafe {
if self.len == 0 {
return;
}
let s = std::ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len());
self.len = 0;
std::ptr::drop_in_place(s);
}
}
pub fn insert(&mut self, index: usize, element: T) {
// SAFETY: ensure index is in bounds.
let len = self.len;
if index > len {
bounds_check_failed(index, len);
}
// SAFETY: ensure capacity is sufficient.
if len == self.cap {
self.reserve(1);
}
unsafe {
let ptr = self.ptr.as_ptr().add(index);
std::ptr::copy(ptr, ptr.offset(1), len - index);
std::ptr::write(ptr, element);
self.len = len + 1;
}
}
pub fn remove(&mut self, index: usize) -> T {
// SAFETY: ensure index is in bounds.
let len = self.len;
if index > len {
bounds_check_failed(index, len);
}
unsafe {
let ptr = self.ptr.as_ptr().add(index);
let ret = std::ptr::read(ptr);
std::ptr::copy(ptr.offset(1), ptr, len - index - 1);
self.len = len - 1;
ret
}
}
pub fn swap_remove(&mut self, index: usize) -> T {
// SAFETY: ensure index is in bounds.
let len = self.len;
if index > len {
bounds_check_failed(index, len);
}
// SAFETY: in the degenerate case where `len == 1` we swap with ourselves, which is fine.
unsafe {
let last = std::ptr::read(self.ptr.as_ptr().add(len - 1));
let hole = self.ptr.as_ptr().add(index);
self.len = len - 1;
std::ptr::replace(hole, last)
}
}
pub fn push(&mut self, element: T) {
if self.len == self.cap {
self.reserve(1);
}
unsafe {
let ptr = self.as_mut_ptr().add(self.len);
std::ptr::write(ptr, element);
self.len += 1;
}
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
return None;
}
unsafe {
self.len -= 1;
Some(std::ptr::read(self.ptr.as_ptr().add(self.len)))
}
}
#[inline]
fn capacity_sufficient_for(&self, additional: usize) -> bool {
// INVARIANT: `cap <= len` means subtraction can't underflow but use `wrapping_sub` to avoid
// needing to *check* for underflow in debug builds.
additional <= self.cap.wrapping_sub(self.len)
}
fn grow(&mut self, additional: usize) {
if additional > MAX_ELEMENTS {
capacity_overflow(additional)
}
// SAFETY: can't wrap, but we use wrapping add so we don't need to check.
let min_capacity = self.cap.wrapping_add(additional);
if min_capacity > self.map {
capacity_overflow(additional)
}
let growth_amount = self.map / 16;
let new_capacity = usize::max(self.cap.wrapping_add(growth_amount), min_capacity);
let new_capacity = usize::min(new_capacity, self.map);
let layout = Layout::array::<T>(new_capacity).expect("mapping too large");
mapping_commit(
unsafe { std::mem::transmute::<*mut T, *mut c_void>(self.ptr.as_ptr()) },
layout.size(),
);
self.cap = new_capacity;
}
pub fn reserve(&mut self, additional: usize) {
if self.capacity_sufficient_for(additional) {
return;
}
self.grow(additional);
}
pub fn as_slice(&self) -> &[T] {
self
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
self
}
}
impl<T> Drop for VirtualVec<T> {
fn drop(&mut self) {
let layout = Layout::array::<T>(self.map).unwrap();
unsafe {
let ptr = std::mem::transmute::<*mut T, *mut c_void>(self.ptr.as_ptr());
let ret = munmap(ptr, layout.size());
assert!(ret == 0);
}
}
}
impl<T> std::ops::Deref for VirtualVec<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe { std::slice::from_raw_parts(self.as_ptr(), self.len) }
}
}
impl<T> std::ops::DerefMut for VirtualVec<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
}
}
impl<'a, T> IntoIterator for &'a VirtualVec<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> std::slice::Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut VirtualVec<T> {
type Item = &'a mut T;
type IntoIter = std::slice::IterMut<'a, T>;
fn into_iter(self) -> std::slice::IterMut<'a, T> {
self.iter_mut()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_destroy() {
let vec = VirtualVec::<i32>::new(4096);
assert_eq!(vec.is_empty(), true);
assert_eq!(vec.mapping(), 4096);
assert_eq!(vec.capacity(), 0);
assert_eq!(vec.len(), 0);
drop(vec);
}
#[test]
fn push() {
let mut vec = VirtualVec::<i32>::new(1 << 16);
for i in 0..1 << 16 {
vec.push(i);
}
assert_eq!(vec.len(), 1 << 16);
assert_eq!(vec.capacity(), 1 << 16);
for (i, v) in vec.iter().enumerate() {
assert_eq!(i as i32, *v);
}
vec.clear();
assert_eq!(vec.len(), 0);
assert_eq!(vec.capacity(), 65536);
drop(vec);
}
}
|
use crate::rpc::kvs_service::WriteOp;
use chrono::prelude::*;
use std::{
fmt::Display,
str::FromStr,
time::{Duration, SystemTime},
};
pub enum Column {
Write,
Data,
Lock,
}
/// A Key struct used in percolator txn
#[derive(Clone)]
pub struct Key {
key: String,
ts: u64,
}
impl Key {
/// Create a new Key
pub fn new(key: String, ts: u64) -> Self {
Self { key, ts }
}
/// Get the string value of inner key
pub fn key(&self) -> &str {
self.key.as_ref()
}
/// Get the value of ts
pub fn ts(&self) -> u64 {
self.ts
}
}
impl Display for Key {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}-{:020}", self.key, self.ts)
}
}
impl FromStr for Key {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut splited = s.rsplit_terminator("-");
let ts = splited.next().unwrap().parse().unwrap();
let key = splited.collect();
Ok(Key { key, ts })
}
}
/// A DataValue struct
#[derive(Clone)]
pub struct DataValue {
value: String,
}
impl DataValue {
/// Create a new DataValue
pub fn new(value: String) -> Self {
Self { value }
}
/// Get the inner value
pub fn value(self) -> String {
self.value
}
}
impl Display for DataValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
impl FromStr for DataValue {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(DataValue {
value: s.to_string(),
})
}
}
enum LockType {
PreWrite,
Get,
RollBack,
}
/// A LockValue struct
#[derive(Clone)]
pub struct LockValue {
primary: String,
ttl: DateTime<Utc>,
op: WriteOp,
}
impl LockValue {
/// Create a new LockValue struct
pub fn new(primary: String, op: WriteOp) -> Self {
Self {
primary,
ttl: SystemTime::now().into(),
op,
}
}
/// Get the string value of primary
pub fn primary(&self) -> String {
self.primary.clone()
}
/// Get the string value of primary
pub fn op(&self) -> WriteOp {
self.op
}
/// Compute how long this key is elapsed
pub fn elapsed(&self) -> Duration {
let system_now = SystemTime::now();
let ttl: SystemTime = self.ttl.into();
system_now.duration_since(ttl).expect("Time backward!")
}
/// reset ttl
pub fn reset_ttl(&mut self) {
self.ttl = SystemTime::now().into();
}
}
impl Display for LockValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}~{}~{}", self.primary, self.ttl, self.op)
}
}
impl FromStr for LockValue {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut splited = s.rsplit_terminator("~");
let op = splited.next().unwrap().parse().unwrap();
let ttl = splited.next().unwrap().parse().unwrap();
let primary = splited.collect();
Ok(LockValue { primary, ttl, op })
}
}
impl Display for WriteOp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WriteOp::Put => write!(f, "Put"),
WriteOp::Lock => write!(f, "Lock"),
WriteOp::Delete => write!(f, "Delete"),
}
}
}
impl FromStr for WriteOp {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Put" => Ok(WriteOp::Put),
"Lock" => Ok(WriteOp::Lock),
"Delete" => Ok(WriteOp::Delete),
_ => Err(()),
}
}
}
/// A WriteValue struct
#[derive(Clone)]
pub struct WriteValue {
ts: u64,
op: WriteOp,
}
impl WriteValue {
/// Create a new WriteValue
pub fn new(ts: u64, op: WriteOp) -> Self {
Self { ts, op }
}
/// Get the value of ts
pub fn ts(&self) -> u64 {
self.ts
}
/// Get the value of write op
pub fn op(&self) -> WriteOp {
self.op
}
}
impl Display for WriteValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}-{}", self.ts, self.op)
}
}
impl FromStr for WriteValue {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut splited = s.split_terminator("-");
let ts = splited.next().unwrap();
let op = splited.next().unwrap();
Ok(WriteValue {
ts: ts.parse().unwrap(),
op: op.parse().unwrap(),
})
}
}
#[cfg(test)]
mod tests {
use std::{thread::sleep, time::Duration};
use super::*;
#[test]
fn test_lock_value() {
assert_eq!(2, 1 + 1);
let value = LockValue::new(String::from("some value"), WriteOp::Put);
let ss = value.to_string();
println!("{}", ss);
let new_value = LockValue::from_str(&ss).unwrap();
println!("{}", new_value);
sleep(Duration::from_secs(1));
println!("{:?}", new_value.elapsed());
}
}
|
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
//! Traits and structs for loading the device tree.
use vm_memory::{Bytes, GuestMemory};
use std::fmt;
use crate::configurator::{BootConfigurator, BootParams, Error as BootConfiguratorError, Result};
/// Errors specific to the device tree boot protocol configuration.
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
/// FDT does not fit in guest memory.
FDTPastRamEnd,
/// Error writing FDT in memory.
WriteFDTToMemory,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Error::*;
let desc = match self {
FDTPastRamEnd => "FDT does not fit in guest memory.",
WriteFDTToMemory => "error writing FDT in guest memory.",
};
write!(f, "Device Tree Boot Configurator: {}", desc)
}
}
impl std::error::Error for Error {}
impl From<Error> for BootConfiguratorError {
fn from(err: Error) -> Self {
BootConfiguratorError::Fdt(err)
}
}
/// Boot configurator for device tree.
pub struct FdtBootConfigurator {}
impl BootConfigurator for FdtBootConfigurator {
/// Writes the boot parameters (configured elsewhere) into guest memory.
///
/// # Arguments
///
/// * `params` - boot parameters containing the FDT.
/// * `guest_memory` - guest's physical memory.
///
/// # Examples
///
/// ```rust
/// # extern crate vm_memory;
/// # use linux_loader::configurator::{BootConfigurator, BootParams};
/// # use linux_loader::configurator::fdt::FdtBootConfigurator;
/// # use vm_memory::{Address, ByteValued, GuestMemory, GuestMemoryMmap, GuestAddress};
/// # #[derive(Clone, Copy, Default)]
/// # struct FdtPlaceholder([u8; 0x20]);
/// # unsafe impl ByteValued for FdtPlaceholder {}
/// # fn create_guest_memory() -> GuestMemoryMmap {
/// # GuestMemoryMmap::from_ranges(&[(GuestAddress(0x0), (0x100_0000 as usize))]).unwrap()
/// # }
/// # fn create_fdt(guest_memory: &GuestMemoryMmap) -> (FdtPlaceholder, GuestAddress) {
/// # let last_addr = guest_memory.last_addr().raw_value();
/// # (FdtPlaceholder([0u8; 0x20]), GuestAddress(last_addr - 0x20u64))
/// # }
/// # fn main() {
/// let guest_memory = create_guest_memory();
/// let (fdt, fdt_addr) = create_fdt(&guest_memory);
/// FdtBootConfigurator::write_bootparams::<GuestMemoryMmap>(
/// &BootParams::new::<FdtPlaceholder>(&fdt, fdt_addr),
/// &guest_memory,
/// )
/// .unwrap();
/// # }
/// ```
fn write_bootparams<M>(params: &BootParams, guest_memory: &M) -> Result<()>
where
M: GuestMemory,
{
guest_memory
.checked_offset(params.header_start, params.header.len())
.ok_or(Error::FDTPastRamEnd)?;
// The VMM has filled an FDT and passed it as a `ByteValued` object.
guest_memory
.write_slice(params.header.as_slice(), params.header_start)
.map_err(|_| Error::WriteFDTToMemory.into())
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::undocumented_unsafe_blocks)]
use super::*;
use vm_memory::{Address, ByteValued, GuestAddress, GuestMemoryMmap};
const FDT_MAX_SIZE: usize = 0x20;
const MEM_SIZE: u64 = 0x100_0000;
fn create_guest_mem() -> GuestMemoryMmap {
GuestMemoryMmap::from_ranges(&[(GuestAddress(0x0), (MEM_SIZE as usize))]).unwrap()
}
#[derive(Clone, Copy, Default)]
struct FdtPlaceholder([u8; FDT_MAX_SIZE]);
unsafe impl ByteValued for FdtPlaceholder {}
#[test]
fn test_configure_fdt_boot() {
let fdt = FdtPlaceholder([0u8; FDT_MAX_SIZE]);
let guest_memory = create_guest_mem();
// Error case: FDT doesn't fit in guest memory.
let fdt_addr = GuestAddress(guest_memory.last_addr().raw_value() - FDT_MAX_SIZE as u64 + 1);
assert_eq!(
FdtBootConfigurator::write_bootparams::<GuestMemoryMmap>(
&BootParams::new::<FdtPlaceholder>(&fdt, fdt_addr),
&guest_memory,
)
.err(),
Some(Error::FDTPastRamEnd.into())
);
let fdt_addr = GuestAddress(guest_memory.last_addr().raw_value() - FDT_MAX_SIZE as u64);
assert!(FdtBootConfigurator::write_bootparams::<GuestMemoryMmap>(
&BootParams::new::<FdtPlaceholder>(&fdt, fdt_addr),
&guest_memory,
)
.is_ok());
}
#[test]
fn test_error_messages() {
assert_eq!(
format!("{}", Error::FDTPastRamEnd),
"Device Tree Boot Configurator: FDT does not fit in guest memory."
);
assert_eq!(
format!("{}", Error::WriteFDTToMemory),
"Device Tree Boot Configurator: error writing FDT in guest memory."
);
}
}
|
/*!
```rudra-poc
[target]
crate = "obstack"
version = "0.1.3"
[test]
cargo_flags = ["--release"]
[report]
issue_url = "https://github.com/petertodd/rust-obstack/issues/4"
issue_date = 2020-09-03
rustsec_url = "https://github.com/RustSec/advisory-db/pull/373"
rustsec_id = "RUSTSEC-2020-0040"
[[bugs]]
analyzer = "Manual"
guide = "UnsafeDestructor"
bug_class = "Other"
bug_count = 2
rudra_report_locations = []
```
!*/
#![forbid(unsafe_code)]
use obstack::Obstack;
#[repr(align(256))]
#[derive(Copy, Clone)]
struct LargeAlign(u8);
fn main() {
// https://github.com/petertodd/rust-obstack/blob/e1dde0dbed709ebdea9bd1f79ec718e80c5d0bf6/src/lib.rs#L317-L337
// Line 322: Incorrect padding bytes calculation. It should be `(alignment - (start_ptr % alignment)) % alignment`.
// Line 329: Wasted memory due to `bytes_to_item()` not being applied to `padding`.
// Due to the incorrect padding calculation, the code generates unaligned reference in release mode.
let obstack = Obstack::new();
let val_ref = obstack.push_copy(LargeAlign(0));
let address = val_ref as *mut _ as usize;
println!("{:x}", address);
assert!(address % std::mem::align_of::<LargeAlign>() == 0);
}
|
// unihernandez22
// https://atcoder.jp/contests/abc174/tasks/abc174_a
// implementation
use std::io::stdin;
fn main() {
let mut x = String::new();
stdin().read_line(&mut x).unwrap();
let x: i64 = x.trim().parse().unwrap();
println!("{}",
if x >= 30 { "Yes" }
else { "No" }
);
}
|
use std::collections::HashMap;
type Line = (i32, i32, i32, i32);
fn count_overlaps(lines: &[Line], diagonals: bool) -> usize {
let mut counts = HashMap::new();
for &(x0, y0, x1, y1) in lines {
if x0 == x1 {
for y in i32::min(y0, y1)..=i32::max(y0, y1) {
*counts.entry((x0, y)).or_insert(0) += 1;
}
} else if y0 == y1 {
for x in i32::min(x0, x1)..=i32::max(x0, x1) {
*counts.entry((x, y0)).or_insert(0) += 1;
}
} else if diagonals {
let dx = if x0 > x1 { -1 } else { 1 };
let dy = if y0 > y1 { -1 } else { 1 };
let mut x = x0;
let mut y = y0;
while x != x1 + dx && y != y1 + dy {
*counts.entry((x, y)).or_insert(0) += 1;
x += dx;
y += dy;
}
}
}
counts.iter().filter(|(_, c)| **c >= 2).count()
}
fn part1(lines: &[Line]) {
println!("{}", count_overlaps(lines, false));
}
fn part2(lines: &[Line]) {
println!("{}", count_overlaps(lines, true));
}
fn main() {
let input = std::fs::read_to_string("input").unwrap();
let lines: Vec<Line> = input
.lines()
.map(|l| {
let mut coords = l
.split(" -> ")
.flat_map(|c| c.split(',').map(|n| n.parse().unwrap()));
(
coords.next().unwrap(),
coords.next().unwrap(),
coords.next().unwrap(),
coords.next().unwrap(),
)
})
.collect();
part1(&lines);
part2(&lines);
}
|
//! Frequently used imports.
// TODO: Reconsider this. Is this an anti-pattern?
pub use block::Block;
pub use cell::MoveCell;
pub use lazy_init::LazyInit;
pub use sync::Mutex;
pub use ptr::Pointer;
pub use vec::Vec;
|
use crate::Config;
use actix::clock::{interval_at, Instant};
use actix_web::{get, http::header::ContentType, web, web::Bytes, HttpResponse};
use drogue_client::{registry, Context};
use drogue_cloud_integration_common::stream::{EventStream, EventStreamConfig, IntoSseStream};
use drogue_cloud_service_api::{
auth::user::{
authz::{AuthorizationRequest, Permission},
UserInformation,
},
kafka::{KafkaConfigExt, KafkaEventType},
};
use drogue_cloud_service_common::{
client::UserAuthClient, error::ServiceError, openid::Authenticator,
};
use futures::{stream::select, StreamExt};
use openid::CustomClaims;
use serde::Deserialize;
use std::time::Duration;
use tokio_stream::wrappers::IntervalStream;
#[derive(Deserialize, Debug, Clone)]
pub struct SpyQuery {
token: String,
app: String,
}
#[get("/spy")]
pub async fn stream_events(
authenticator: web::Data<Authenticator>,
query: web::Query<SpyQuery>,
config: web::Data<Config>,
user_auth: Option<web::Data<UserAuthClient>>,
registry: web::Data<registry::v1::Client>,
) -> Result<HttpResponse, actix_web::Error> {
if let Some(user_auth) = user_auth {
let user = authenticator
.validate_token(query.token.clone())
.await
.map_err(|_| ServiceError::AuthenticationError)?;
let user_id = user.standard_claims().sub.clone();
let roles = UserInformation::Authenticated(user.into())
.roles()
.iter()
.map(ToString::to_string)
.collect();
user_auth
.authorize(
AuthorizationRequest {
application: query.app.clone(),
permission: Permission::Read,
user_id: Some(user_id),
roles,
},
Default::default(),
)
.await
.map_err(|err| ServiceError::InternalError(format!("Authorization failed: {}", err)))?
.outcome
.ensure(|| ServiceError::AuthenticationError)?;
}
let app = registry
.get_app(
&query.app,
Context {
provided_token: Some(query.token.clone()),
},
)
.await
.map_err(ServiceError::from)?
.ok_or_else(|| ServiceError::NotFound("Application".into(), query.app.clone()))?;
let cfg = EventStreamConfig {
kafka: app.kafka_config(KafkaEventType::Events, &config.kafka)?,
consumer_group: None,
};
log::debug!("Config: {:?}", cfg);
let stream = EventStream::new(cfg).map_err(|err| {
ServiceError::ServiceUnavailable(format!("Failed to connect to Kafka: {}", err))
})?;
let hb = IntervalStream::new(interval_at(Instant::now(), Duration::from_secs(5)))
.map(|_| Ok(Bytes::from("event: ping\n\n")));
let stream = select(stream.into_sse_stream(), hb);
Ok(HttpResponse::Ok()
.append_header(ContentType(mime::TEXT_EVENT_STREAM))
.streaming(stream))
}
|
use crate::{
commands::osu::SnipeOrder,
custom_client::SnipeCountryPlayer,
embeds::Footer,
util::{
constants::OSU_BASE,
numbers::{with_comma_float, with_comma_int},
osu::flag_url,
CountryCode,
},
};
use std::fmt::Write;
pub struct CountrySnipeListEmbed {
thumbnail: String,
description: String,
title: String,
footer: Footer,
}
impl CountrySnipeListEmbed {
pub fn new<'i, S>(
country: Option<&(String, CountryCode)>,
order: SnipeOrder,
players: S,
author_idx: Option<usize>,
pages: (usize, usize),
) -> Self
where
S: Iterator<Item = &'i (usize, SnipeCountryPlayer)>,
{
let order_text = match order {
SnipeOrder::Count => "#1 count",
SnipeOrder::Pp => "average pp of #1s",
SnipeOrder::Stars => "average stars of #1s",
SnipeOrder::WeightedPp => "weighted pp from #1s",
};
let (title, thumbnail) = match country {
Some((country, code)) => {
let title = format!(
"{country}{} #1 list, sorted by {order_text}",
if country.ends_with('s') { "'" } else { "'s" },
);
let thumbnail = flag_url(code.as_str());
(title, thumbnail)
}
None => (
format!("Global #1 statistics, sorted by {order_text}"),
String::new(),
),
};
let mut description = String::with_capacity(512);
for (idx, player) in players {
let _ = writeln!(
description,
"**{idx}. [{name}]({base}users/{id})**: {w}Weighted pp: {weighted}{w}\n\
{c}Count: {count}{c} ~ {p}Avg pp: {pp}{p} ~ {s}Avg stars: {stars:.2}★{s}",
idx = idx,
name = player.username,
base = OSU_BASE,
id = player.user_id,
c = if order == SnipeOrder::Count { "__" } else { "" },
p = if order == SnipeOrder::Pp { "__" } else { "" },
s = if order == SnipeOrder::Stars { "__" } else { "" },
w = if order == SnipeOrder::WeightedPp {
"__"
} else {
""
},
count = with_comma_int(player.count_first),
pp = with_comma_float(player.avg_pp),
stars = player.avg_sr,
weighted = with_comma_float(player.pp),
);
}
description.pop();
let mut footer_text = format!("Page {}/{}", pages.0, pages.1);
if let Some(idx) = author_idx {
let _ = write!(footer_text, " ~ Your position: {}", idx + 1);
}
Self {
description,
title,
thumbnail,
footer: Footer::new(footer_text),
}
}
}
impl_builder!(CountrySnipeListEmbed {
description,
footer,
thumbnail,
title,
});
|
extern crate crypto;
use self::crypto::digest::Digest;
use self::crypto::md5::Md5;
use std::collections::HashMap;
pub struct Password {
door_id: String,
}
impl Password {
pub fn new(door_id: String) -> Password {
Password { door_id: door_id }
}
pub fn val(&self) -> String {
let mut result: HashMap<u32, char> = HashMap::new();
let mut counter = 0;
loop {
if result.len() == 8 {
let mut more_result: Vec<(&u32, &char)> = result.iter().collect();
more_result.sort_by(|a, b| a.0.cmp(b.0));
let final_result: String = more_result.iter().map(|r| *r.1).collect();
println!("{:?}", more_result);
return final_result;
}
let hash = self.hashed_counter(counter);
if hash.starts_with("00000") {
match hash.chars().nth(5).unwrap().to_string().parse::<u32>() {
Ok(pos) => {
if pos < 8 {
let val = hash.chars().nth(6).unwrap();
result.entry(pos).or_insert(val);
}
}
Err(_) => {}
}
}
counter += 1;
}
}
fn hashed_counter(&self, counter: u32) -> String {
let input = format!("{}{}", self.door_id, counter);
self.hashed(input)
}
fn hashed(&self, input: String) -> String {
let mut md5 = Md5::new();
md5.input_str(&input);
md5.result_str()
}
}
#[test]
fn hashed_counter() {
let password = Password::new(String::from("abc"));
let hash = password.hashed_counter(3231929);
assert!(hash.starts_with("00000"));
}
|
#[macro_use] extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate rmp_serde;
extern crate byteorder;
extern crate futures;
extern crate indyrs as indy;
#[macro_use]
use indy::metrics;
use indy::ErrorCode;
mod utils;
#[allow(unused_imports)]
use futures::Future;
#[cfg(test)]
mod collect {
use super::*;
use std::collections::HashMap;
use serde_json::Value;
#[test]
fn collect_metrics() {
let result_metrics = metrics::collect_metrics().wait().unwrap();
let metrics_map = serde_json::from_str::<HashMap<String, Value>>(&result_metrics).unwrap();
assert!(metrics_map.contains_key("threadpool_threads_count"));
assert!(metrics_map.contains_key("wallet_count"));
let threadpool_threads_count = metrics_map
.get("threadpool_threads_count")
.unwrap()
.as_array()
.unwrap();
let wallet_count = metrics_map
.get("wallet_count")
.unwrap()
.as_array()
.unwrap();
let expected_threadpool_threads_count = [
json!({"tags":{"label":"active"},"value":0}),
json!({"tags":{"label":"queued"},"value":0}),
json!({"tags":{"label":"panic"},"value":0}),
];
let expected_wallet_count = [
json!({"tags":{"label":"opened"},"value":0}),
json!({"tags":{"label":"opened_ids"},"value":0}),
json!({"tags":{"label":"pending_for_import"},"value":0}),
json!({"tags":{"label":"pending_for_open"},"value":0}),
];
for command in &expected_threadpool_threads_count {
assert!(threadpool_threads_count.contains(&command));
}
for command in &expected_wallet_count {
assert!(wallet_count.contains(&command));
}
}
}
|
#![warn(missing_docs, clippy::pedantic)]
//! Generates strings are byte strings following rule of a regular expression.
//!
//! ```
//! # #[cfg(feature = "unicode")] {
//! use rand::{SeedableRng, Rng};
//!
//! let mut rng = rand_xorshift::XorShiftRng::from_seed(*b"The initial seed");
//!
//! // creates a generator for sampling strings
//! let gen = rand_regex::Regex::compile(r"\d{4}-\d{2}-\d{2}", 100).unwrap();
//!
//! // sample a few strings randomly
//! let samples = (&mut rng).sample_iter(&gen).take(3).collect::<Vec<String>>();
//!
//! // all Unicode characters are included when sampling
//! assert_eq!(samples, vec![
//! "꘥᥉১᪕-꧷៩-୦۱".to_string(),
//! "𞋴۰𑋸꣕-᥆꧰-෮᪑".to_string(),
//! "𑋲𐒥४౫-9႙-९౨".to_string()
//! ]);
//!
//! // you could use `regex_syntax::Hir` to include more options
//! let mut parser = regex_syntax::ParserBuilder::new().unicode(false).build();
//! let hir = parser.parse(r"\d{4}-\d{2}-\d{2}").unwrap();
//! let gen = rand_regex::Regex::with_hir(hir, 100).unwrap();
//! let samples = (&mut rng).sample_iter(&gen).take(3).collect::<Vec<String>>();
//! assert_eq!(samples, vec![
//! "8922-87-63".to_string(),
//! "3149-18-88".to_string(),
//! "5420-58-55".to_string(),
//! ]);
//! # }
//! ```
#![allow(clippy::must_use_candidate)]
use rand::{
distributions::{uniform::Uniform, Distribution},
Rng,
};
use regex_syntax::{
hir::{self, ClassBytes, ClassUnicode, Hir, HirKind, Repetition},
Parser,
};
use std::{
char,
cmp::Ordering,
error,
fmt::{self, Debug},
hash::{Hash, Hasher},
mem,
str::Utf8Error,
string::FromUtf8Error,
};
const SHORT_UNICODE_CLASS_COUNT: usize = 64;
/// Error returned by [`Regex::compile()`] and [`Regex::with_hir()`].
///
/// # Examples
///
/// ```
/// let gen = rand_regex::Regex::compile(r"^.{4}\b.{4}$", 100);
/// assert_eq!(gen.err(), Some(rand_regex::Error::Anchor));
/// ```
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Error {
/// Anchors (`^`, `$`, `\A`, `\z`) and word boundary assertions (`\b`, `\B`)
/// are not supported.
///
/// If you really need to include anchors, please consider using rejection
/// sampling e.g.
///
/// ```rust
/// # #[cfg(feature = "unicode")] {
/// use rand::Rng;
///
/// // create the generator without the anchor
/// let gen = rand_regex::Regex::compile(r".{4}.{4}", 100).unwrap();
///
/// // later filter the sampled result using a regex with the anchor
/// let filter_regex = regex::Regex::new(r"^.{4}\b.{4}$").unwrap();
/// let _sample = rand::thread_rng()
/// .sample_iter::<String, _>(&gen)
/// .filter(|s| filter_regex.is_match(s))
/// .next()
/// .unwrap();
/// # }
/// ```
Anchor,
/// The input regex has a syntax error.
///
/// # Examples
///
/// ```
/// let gen = rand_regex::Regex::compile(r"(", 100);
/// assert!(match gen {
/// Err(rand_regex::Error::Syntax(_)) => true,
/// _ => false,
/// });
/// ```
Syntax(Box<regex_syntax::Error>),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Anchor => f.write_str("anchor is not supported"),
Self::Syntax(e) => fmt::Display::fmt(e, f),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::Anchor => None,
Self::Syntax(e) => Some(e),
}
}
}
impl From<regex_syntax::Error> for Error {
fn from(e: regex_syntax::Error) -> Self {
Self::Syntax(Box::new(e))
}
}
/// String encoding.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Encoding {
/// ASCII.
Ascii = 0,
/// UTF-8.
Utf8 = 1,
/// Arbitrary bytes (no encoding).
Binary = 2,
}
/// The internal representation of [`EncodedString`], separated out to prevent
/// unchecked construction of `Es::Ascii(non_ascii_string)`.
#[derive(Debug)]
enum Es {
/// A string with ASCII content only.
Ascii(String),
/// A normal string encoded with valid UTF-8
Utf8(String),
/// A byte string which cannot be converted to UTF-8. Contains information
/// of failure.
Binary(FromUtf8Error),
}
/// A string together with its [`Encoding`].
#[derive(Debug)]
pub struct EncodedString(Es);
impl EncodedString {
/// Obtains the raw bytes of this string.
pub fn as_bytes(&self) -> &[u8] {
match &self.0 {
Es::Ascii(s) | Es::Utf8(s) => s.as_bytes(),
Es::Binary(e) => e.as_bytes(),
}
}
/// Tries to convert this instance as a UTF-8 string.
///
/// # Errors
///
/// If this instance is not compatible with UTF-8, returns an error in the
/// same manner as [`std::str::from_utf8()`].
pub fn as_str(&self) -> Result<&str, Utf8Error> {
match &self.0 {
Es::Ascii(s) | Es::Utf8(s) => Ok(s),
Es::Binary(e) => Err(e.utf8_error()),
}
}
/// Returns the encoding of this string.
pub fn encoding(&self) -> Encoding {
match self.0 {
Es::Ascii(_) => Encoding::Ascii,
Es::Utf8(_) => Encoding::Utf8,
Es::Binary(_) => Encoding::Binary,
}
}
}
impl From<EncodedString> for Vec<u8> {
fn from(es: EncodedString) -> Self {
match es.0 {
Es::Ascii(s) | Es::Utf8(s) => s.into_bytes(),
Es::Binary(e) => e.into_bytes(),
}
}
}
impl From<Vec<u8>> for EncodedString {
fn from(b: Vec<u8>) -> Self {
match String::from_utf8(b) {
Ok(s) => Self::from(s),
Err(e) => Self(Es::Binary(e)),
}
}
}
impl From<String> for EncodedString {
fn from(s: String) -> Self {
Self(if s.is_ascii() {
Es::Ascii(s)
} else {
Es::Utf8(s)
})
}
}
impl TryFrom<EncodedString> for String {
type Error = FromUtf8Error;
fn try_from(es: EncodedString) -> Result<Self, Self::Error> {
match es.0 {
Es::Ascii(s) | Es::Utf8(s) => Ok(s),
Es::Binary(e) => Err(e),
}
}
}
impl PartialEq for EncodedString {
fn eq(&self, other: &Self) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl Eq for EncodedString {}
impl PartialOrd for EncodedString {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.as_bytes().partial_cmp(other.as_bytes())
}
}
impl Ord for EncodedString {
fn cmp(&self, other: &Self) -> Ordering {
self.as_bytes().cmp(other.as_bytes())
}
}
impl Hash for EncodedString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}
/// A random distribution which generates strings matching the specified regex.
#[derive(Clone, Debug)]
pub struct Regex {
compiled: Compiled,
capacity: usize,
encoding: Encoding,
}
impl Distribution<Vec<u8>> for Regex {
/// Samples a random byte string satisfying the regex.
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<u8> {
let mut ctx = EvalCtx {
output: Vec::with_capacity(self.capacity),
rng,
};
ctx.eval(&self.compiled);
ctx.output
}
}
impl Distribution<String> for Regex {
/// Samples a random string satisfying the regex.
///
/// # Panics
///
/// If the regex produced some non-UTF-8 byte sequence, this method will
/// panic. You may want to check [`is_utf8()`](Regex::is_utf8) to ensure the
/// regex will only generate valid Unicode strings, or sample a
/// `Result<String, FromUtf8Error>` and manually handle the error.
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> String {
<Self as Distribution<Result<_, _>>>::sample(self, rng).unwrap()
}
}
impl Distribution<Result<String, FromUtf8Error>> for Regex {
/// Samples a random string satisfying the regex.
///
/// The the sampled bytes sequence is not valid UTF-8, the sampling result
/// is an Err value.
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Result<String, FromUtf8Error> {
let bytes = <Self as Distribution<Vec<u8>>>::sample(self, rng);
if self.is_utf8() {
unsafe { Ok(String::from_utf8_unchecked(bytes)) }
} else {
String::from_utf8(bytes)
}
}
}
impl Distribution<EncodedString> for Regex {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> EncodedString {
let result = <Self as Distribution<Result<_, _>>>::sample(self, rng);
EncodedString(match result {
Err(e) => Es::Binary(e),
Ok(s) => {
if self.is_ascii() || s.is_ascii() {
Es::Ascii(s)
} else {
Es::Utf8(s)
}
}
})
}
}
impl Default for Regex {
/// Creates an empty regex which generates empty strings.
///
/// # Examples
///
/// ```
/// use rand::Rng;
///
/// let gen = rand_regex::Regex::default();
/// assert_eq!(rand::thread_rng().sample::<String, _>(&gen), "");
/// ```
#[inline]
fn default() -> Self {
Self {
compiled: Compiled::default(),
capacity: 0,
encoding: Encoding::Ascii,
}
}
}
impl Regex {
/// Obtains the narrowest string encoding this regex can produce.
pub const fn encoding(&self) -> Encoding {
self.encoding
}
/// Checks if the regex can only produce ASCII strings.
///
/// # Examples
///
/// ```
/// let ascii_gen = rand_regex::Regex::compile("[0-9]+", 100).unwrap();
/// assert_eq!(ascii_gen.is_ascii(), true);
/// let non_ascii_gen = rand_regex::Regex::compile(r"\d+", 100).unwrap();
/// assert_eq!(non_ascii_gen.is_ascii(), false);
/// ```
#[inline]
pub const fn is_ascii(&self) -> bool {
// FIXME remove the `as u8` once `PartialOrd` can be used in `const fn`.
(self.encoding as u8) == (Encoding::Ascii as u8)
}
/// Checks if the regex can only produce valid Unicode strings.
///
/// Due to complexity of regex pattern, this method may have false
/// negative (returning false but still always produce valid UTF-8)
///
/// # Examples
///
/// ```
/// let utf8_hir = regex_syntax::ParserBuilder::new()
/// .unicode(false)
/// .utf8(false)
/// .build()
/// .parse(r"[\x00-\x7f]")
/// .unwrap();
/// let utf8_gen = rand_regex::Regex::with_hir(utf8_hir, 100).unwrap();
/// assert_eq!(utf8_gen.is_utf8(), true);
///
/// let non_utf8_hir = regex_syntax::ParserBuilder::new()
/// .unicode(false)
/// .utf8(false)
/// .build()
/// .parse(r"[\x00-\xff]")
/// .unwrap();
/// let non_utf8_gen = rand_regex::Regex::with_hir(non_utf8_hir, 100).unwrap();
/// assert_eq!(non_utf8_gen.is_utf8(), false);
/// ```
#[inline]
pub const fn is_utf8(&self) -> bool {
// FIXME remove the `as u8` once `PartialOrd` can be used in `const fn`.
(self.encoding as u8) <= (Encoding::Utf8 as u8)
}
/// Returns the maximum length the string this regex can generate.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "unicode")] {
/// let gen = rand_regex::Regex::compile(r"\d{4}-\d{2}-\d{2}", 100).unwrap();
/// assert_eq!(gen.capacity(), 34);
/// // each `\d` can occupy 4 bytes
/// # }
/// ```
#[inline]
pub const fn capacity(&self) -> usize {
self.capacity
}
/// Compiles a regex pattern for string generation.
///
/// If you need to supply additional flags to the pattern, please use
/// [`Regex::with_hir()`] instead.
///
/// The `max_repeat` parameter gives the maximum extra repeat counts
/// the `x*`, `x+` and `x{n,}` operators will become, e.g.
///
/// ```
/// let gen = rand_regex::Regex::compile("a{4,}", 100).unwrap();
/// // this will generate a string between 4 to 104 characters long.
/// assert_eq!(gen.capacity(), 104);
/// ```
///
/// # Errors
///
/// Returns an error if the pattern is not valid regex, or contains anchors
/// (`^`, `$`, `\A`, `\z`) or word boundary assertions (`\b`, `\B`).
pub fn compile(pattern: &str, max_repeat: u32) -> Result<Self, Error> {
let hir = Parser::new().parse(pattern)?;
Self::with_hir(hir, max_repeat)
}
/// Compiles a parsed regex pattern for string generation.
///
/// The [`Hir`] object can be obtained using [`regex_syntax::ParserBuilder`].
///
/// The `max_repeat` parameter gives the maximum extra repeat counts
/// the `x*`, `x+` and `x{n,}` operators will become.
///
/// # Errors
///
/// Returns an error if the `Hir` object contains anchors (`^`, `$`, `\A`,
/// `\z`) or word boundary assertions (`\b`, `\B`).
pub fn with_hir(hir: Hir, max_repeat: u32) -> Result<Self, Error> {
match hir.into_kind() {
HirKind::Empty => Ok(Self::default()),
HirKind::Look(_) => Err(Error::Anchor),
HirKind::Capture(hir::Capture { sub, .. }) => Self::with_hir(*sub, max_repeat),
HirKind::Literal(hir::Literal(bytes)) => Ok(Self::with_bytes_literal(bytes.into())),
HirKind::Class(hir::Class::Unicode(class)) => Ok(Self::with_unicode_class(&class)),
HirKind::Class(hir::Class::Bytes(class)) => Ok(Self::with_byte_class(&class)),
HirKind::Repetition(rep) => Self::with_repetition(rep, max_repeat),
HirKind::Concat(hirs) => Self::with_sequence(hirs, max_repeat),
HirKind::Alternation(hirs) => Self::with_choices(hirs, max_repeat),
}
}
fn with_bytes_literal(bytes: Vec<u8>) -> Self {
let es = EncodedString::from(bytes);
let encoding = es.encoding();
let bytes = Vec::from(es);
Self {
capacity: bytes.len(),
compiled: Kind::Literal(bytes).into(),
encoding,
}
}
fn with_unicode_class(class: &ClassUnicode) -> Self {
if let Some(byte_class) = class.to_byte_class() {
Self::with_byte_class(&byte_class)
} else {
Self {
compiled: compile_unicode_class(class.ranges()).into(),
capacity: class.maximum_len().unwrap_or(0),
encoding: Encoding::Utf8,
}
}
}
fn with_byte_class(class: &ClassBytes) -> Self {
Self {
compiled: Kind::ByteClass(ByteClass::compile(class.ranges())).into(),
capacity: 1,
encoding: if class.is_ascii() {
Encoding::Ascii
} else {
Encoding::Binary
},
}
}
fn with_repetition(rep: Repetition, max_repeat: u32) -> Result<Self, Error> {
let lower = rep.min;
let upper = rep.max.unwrap_or(lower + max_repeat);
// simplification: `(<any>){0}` is always empty.
if upper == 0 {
return Ok(Self::default());
}
let mut regex = Self::with_hir(*rep.sub, max_repeat)?;
regex.capacity *= upper as usize;
if lower == upper {
regex.compiled.repeat_const *= upper;
} else {
regex
.compiled
.repeat_ranges
.push(Uniform::new_inclusive(lower, upper));
}
// simplification: if the inner is an literal, replace `x{3}` by `xxx`.
if let Kind::Literal(lit) = &mut regex.compiled.kind {
if regex.compiled.repeat_const > 1 {
*lit = lit.repeat(regex.compiled.repeat_const as usize);
regex.compiled.repeat_const = 1;
}
}
Ok(regex)
}
fn with_sequence(hirs: Vec<Hir>, max_repeat: u32) -> Result<Self, Error> {
let mut seq = Vec::with_capacity(hirs.len());
let mut capacity = 0;
let mut encoding = Encoding::Ascii;
for hir in hirs {
let regex = Self::with_hir(hir, max_repeat)?;
capacity += regex.capacity;
encoding = encoding.max(regex.encoding);
let compiled = regex.compiled;
if compiled.is_single() {
// simplification: `x(yz)` = `xyz`
if let Kind::Sequence(mut s) = compiled.kind {
seq.append(&mut s);
continue;
}
}
seq.push(compiled);
}
// Further simplify by merging adjacent literals.
let mut simplified = Vec::with_capacity(seq.len());
let mut combined_lit = Vec::new();
for cur in seq {
if cur.is_single() {
if let Kind::Literal(mut lit) = cur.kind {
combined_lit.append(&mut lit);
continue;
}
}
if !combined_lit.is_empty() {
simplified.push(Kind::Literal(mem::take(&mut combined_lit)).into());
}
simplified.push(cur);
}
if !combined_lit.is_empty() {
simplified.push(Kind::Literal(combined_lit).into());
}
let compiled = match simplified.len() {
0 => return Ok(Self::default()),
1 => simplified.swap_remove(0),
_ => Kind::Sequence(simplified).into(),
};
Ok(Self {
compiled,
capacity,
encoding,
})
}
fn with_choices(hirs: Vec<Hir>, max_repeat: u32) -> Result<Self, Error> {
let mut choices = Vec::with_capacity(hirs.len());
let mut capacity = 0;
let mut encoding = Encoding::Ascii;
for hir in hirs {
let regex = Self::with_hir(hir, max_repeat)?;
if regex.capacity > capacity {
capacity = regex.capacity;
}
encoding = encoding.max(regex.encoding);
let compiled = regex.compiled;
if compiled.is_single() {
if let Kind::Any {
choices: mut sc, ..
} = compiled.kind
{
choices.append(&mut sc);
continue;
}
}
choices.push(compiled);
}
Ok(Self {
compiled: Kind::Any {
index: Uniform::new(0, choices.len()),
choices,
}
.into(),
capacity,
encoding,
})
}
}
/// Represents a compiled regex component.
#[derive(Clone, Debug)]
struct Compiled {
// Constant part of repetition.
repeat_const: u32,
// Variable parts of repetition. The repeats are multiplied together.
repeat_ranges: Vec<Uniform<u32>>,
// Kind of atomic regex component.
kind: Kind,
}
impl Default for Compiled {
fn default() -> Self {
Kind::default().into()
}
}
impl Compiled {
/// Returns whether this component has no repetition.
fn is_single(&self) -> bool {
self.repeat_const == 1 && self.repeat_ranges.is_empty()
}
}
#[derive(Clone, Debug)]
enum Kind {
Literal(Vec<u8>),
Sequence(Vec<Compiled>),
Any {
index: Uniform<usize>,
choices: Vec<Compiled>,
},
LongUnicodeClass(LongUnicodeClass),
ShortUnicodeClass(ShortUnicodeClass),
ByteClass(ByteClass),
}
impl Default for Kind {
fn default() -> Self {
Self::Literal(Vec::new())
}
}
impl From<Kind> for Compiled {
fn from(kind: Kind) -> Self {
Self {
repeat_const: 1,
repeat_ranges: Vec::new(),
kind,
}
}
}
struct EvalCtx<'a, R: ?Sized + 'a> {
output: Vec<u8>,
rng: &'a mut R,
}
impl<'a, R: Rng + ?Sized + 'a> EvalCtx<'a, R> {
fn eval(&mut self, compiled: &Compiled) {
let count = compiled
.repeat_ranges
.iter()
.fold(compiled.repeat_const, |c, u| c * u.sample(self.rng));
match &compiled.kind {
Kind::Literal(lit) => self.eval_literal(count, lit),
Kind::Sequence(seq) => self.eval_sequence(count, seq),
Kind::Any { index, choices } => self.eval_alt(count, index, choices),
Kind::LongUnicodeClass(class) => self.eval_unicode_class(count, class),
Kind::ShortUnicodeClass(class) => self.eval_unicode_class(count, class),
Kind::ByteClass(class) => self.eval_byte_class(count, class),
}
}
fn eval_literal(&mut self, count: u32, lit: &[u8]) {
for _ in 0..count {
self.output.extend_from_slice(lit);
}
}
fn eval_sequence(&mut self, count: u32, seq: &[Compiled]) {
for _ in 0..count {
for compiled in seq {
self.eval(compiled);
}
}
}
fn eval_alt(&mut self, count: u32, index: &Uniform<usize>, choices: &[Compiled]) {
for _ in 0..count {
let idx = index.sample(self.rng);
self.eval(&choices[idx]);
}
}
fn eval_unicode_class(&mut self, count: u32, class: &impl Distribution<char>) {
let mut buf = [0; 4];
for c in class.sample_iter(&mut self.rng).take(count as usize) {
let bytes = c.encode_utf8(&mut buf).as_bytes();
self.output.extend_from_slice(bytes);
}
}
fn eval_byte_class(&mut self, count: u32, class: &ByteClass) {
self.output
.extend(self.rng.sample_iter(class).take(count as usize));
}
}
/// A compiled Unicode class of more than 64 ranges.
#[derive(Clone, Debug)]
struct LongUnicodeClass {
searcher: Uniform<u32>,
ranges: Box<[(u32, u32)]>,
}
impl Distribution<char> for LongUnicodeClass {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
let normalized_index = self.searcher.sample(rng);
let entry_index = self
.ranges
.binary_search_by(|(normalized_start, _)| normalized_start.cmp(&normalized_index))
.unwrap_or_else(|e| e - 1);
let code = normalized_index + self.ranges[entry_index].1;
char::from_u32(code).expect("valid char")
}
}
/// A compiled Unicode class of less than or equals to 64 ranges.
#[derive(Clone, Debug)]
struct ShortUnicodeClass {
index: Uniform<usize>,
cases: Box<[char]>,
}
impl Distribution<char> for ShortUnicodeClass {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
self.cases[self.index.sample(rng)]
}
}
fn compile_unicode_class_with(ranges: &[hir::ClassUnicodeRange], mut push: impl FnMut(char, char)) {
for range in ranges {
let start = range.start();
let end = range.end();
if start <= '\u{d7ff}' && '\u{e000}' <= end {
push(start, '\u{d7ff}');
push('\u{e000}', end);
} else {
push(start, end);
}
}
}
fn compile_unicode_class(ranges: &[hir::ClassUnicodeRange]) -> Kind {
let mut normalized_ranges = Vec::new();
let mut normalized_len = 0;
compile_unicode_class_with(ranges, |start, end| {
let start = u32::from(start);
let end = u32::from(end);
normalized_ranges.push((normalized_len, start - normalized_len));
normalized_len += end - start + 1;
});
if normalized_len as usize > SHORT_UNICODE_CLASS_COUNT {
return Kind::LongUnicodeClass(LongUnicodeClass {
searcher: Uniform::new(0, normalized_len),
ranges: normalized_ranges.into_boxed_slice(),
});
}
// the number of cases is too small. convert into a direct search array.
let mut cases = Vec::with_capacity(normalized_len as usize);
compile_unicode_class_with(ranges, |start, end| {
for c in u32::from(start)..=u32::from(end) {
cases.push(char::from_u32(c).expect("valid char"));
}
});
Kind::ShortUnicodeClass(ShortUnicodeClass {
index: Uniform::new(0, cases.len()),
cases: cases.into_boxed_slice(),
})
}
/// A compiled byte class.
#[derive(Clone, Debug)]
struct ByteClass {
index: Uniform<usize>,
cases: Box<[u8]>,
}
impl ByteClass {
fn compile(ranges: &[hir::ClassBytesRange]) -> Self {
let mut cases = Vec::with_capacity(256);
for range in ranges {
cases.extend(range.start()..=range.end());
}
Self {
index: Uniform::new(0, cases.len()),
cases: cases.into_boxed_slice(),
}
}
}
impl Distribution<u8> for ByteClass {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u8 {
self.cases[self.index.sample(rng)]
}
}
#[cfg(test)]
mod test {
use super::*;
use rand::thread_rng;
use std::collections::HashSet;
use std::ops::RangeInclusive;
fn check_str(
pattern: &str,
encoding: Encoding,
distinct_count: RangeInclusive<usize>,
run_count: usize,
) {
let r = regex::Regex::new(pattern).unwrap();
let gen = Regex::compile(pattern, 100).unwrap();
assert!(gen.is_utf8());
assert_eq!(gen.encoding(), encoding);
let mut rng = thread_rng();
let mut gen_set = HashSet::<String>::with_capacity(run_count.min(*distinct_count.end()));
for res in (&gen).sample_iter(&mut rng).take(run_count) {
let res: String = res;
assert!(res.len() <= gen.capacity());
assert!(
r.is_match(&res),
"Wrong sample for pattern `{}`: `{}`",
pattern,
res
);
gen_set.insert(res);
}
let gen_count = gen_set.len();
assert!(
*distinct_count.start() <= gen_count && gen_count <= *distinct_count.end(),
"Distinct samples generated for pattern `{}` outside the range {:?}: {} (examples:\n{})",
pattern,
distinct_count,
gen_count,
gen_set.iter().take(10).map(|s| format!(" - {:#?}\n", s)).collect::<String>(),
);
}
fn run_count_for_distinct_count(distinct_count: usize) -> usize {
// Suppose a regex can possibly generate N distinct strings uniformly. What is the
// probability distribution of number of distinct strings R we can get by running the
// generator M times?
//
// Assuming we can afford M ≫ N ≈ R, we could find out the probability which (N - R) strings
// are still *not* generated after M iterations, which is P = (1 - (R/N)^M)^(Binomial[N,R])
// ≈ 1 - Binomial[N,R] * (R/N)^M.
//
// Here we choose the lower bound as R+1 after solving M for P > 0.999999, or:
//
// Binomial[N,R] * (R/N)^M < 10^(-6)
//
// We limit M ≤ 4096 to keep the test time short.
if distinct_count <= 1 {
return 8;
}
let n = distinct_count as f64;
((n.ln() + 6.0 * std::f64::consts::LN_10) / (n.ln() - (n - 1.0).ln())).ceil() as usize
}
#[test]
fn sanity_test_run_count() {
assert_eq!(run_count_for_distinct_count(1), 8);
assert_eq!(run_count_for_distinct_count(2), 21);
assert_eq!(run_count_for_distinct_count(3), 37);
assert_eq!(run_count_for_distinct_count(10), 153);
assert_eq!(run_count_for_distinct_count(26), 436);
assert_eq!(run_count_for_distinct_count(62), 1104);
assert_eq!(run_count_for_distinct_count(128), 2381);
assert_eq!(run_count_for_distinct_count(214), 4096);
}
fn check_str_limited(pattern: &str, encoding: Encoding, distinct_count: usize) {
let run_count = run_count_for_distinct_count(distinct_count);
check_str(
pattern,
encoding,
distinct_count..=distinct_count,
run_count,
);
}
fn check_str_unlimited(pattern: &str, encoding: Encoding, min_distinct_count: usize) {
check_str(pattern, encoding, min_distinct_count..=4096, 4096);
}
#[test]
fn test_proptest() {
check_str_limited("foo", Encoding::Ascii, 1);
check_str_limited("foo|bar|baz", Encoding::Ascii, 3);
check_str_limited("a{0,8}", Encoding::Ascii, 9);
check_str_limited("a?", Encoding::Ascii, 2);
check_str_limited("a*", Encoding::Ascii, 101);
check_str_limited("a+", Encoding::Ascii, 101);
check_str_limited("a{4,}", Encoding::Ascii, 101);
check_str_limited("(foo|bar)(xyzzy|plugh)", Encoding::Ascii, 4);
check_str_unlimited(".", Encoding::Utf8, 4075);
check_str_unlimited("(?s).", Encoding::Utf8, 4075);
}
#[test]
fn test_regex_generate() {
check_str_limited("", Encoding::Ascii, 1);
check_str_limited("aBcDe", Encoding::Ascii, 1);
check_str_limited("[a-zA-Z0-9]", Encoding::Ascii, 62);
check_str_limited("a{3,8}", Encoding::Ascii, 6);
check_str_limited("a{3}", Encoding::Ascii, 1);
check_str_limited("a{3}-a{3}", Encoding::Ascii, 1);
check_str_limited("(abcde)", Encoding::Ascii, 1);
check_str_limited("a?b?", Encoding::Ascii, 4);
}
#[test]
#[cfg(feature = "unicode")]
fn test_unicode_cases() {
check_str_limited("(?i:fOo)", Encoding::Ascii, 8);
check_str_limited("(?i:a|B)", Encoding::Ascii, 4);
check_str_unlimited(r"(\p{Greek}\P{Greek})(?:\d{3,6})", Encoding::Utf8, 4096);
}
#[test]
fn test_ascii_character_classes() {
check_str_limited("[[:alnum:]]", Encoding::Ascii, 62);
check_str_limited("[[:alpha:]]", Encoding::Ascii, 52);
check_str_limited("[[:ascii:]]", Encoding::Ascii, 128);
check_str_limited("[[:blank:]]", Encoding::Ascii, 2);
check_str_limited("[[:cntrl:]]", Encoding::Ascii, 33);
check_str_limited("[[:digit:]]", Encoding::Ascii, 10);
check_str_limited("[[:graph:]]", Encoding::Ascii, 94);
check_str_limited("[[:lower:]]", Encoding::Ascii, 26);
check_str_limited("[[:print:]]", Encoding::Ascii, 95);
check_str_limited("[[:punct:]]", Encoding::Ascii, 32);
check_str_limited("[[:space:]]", Encoding::Ascii, 6);
check_str_limited("[[:upper:]]", Encoding::Ascii, 26);
check_str_limited("[[:word:]]", Encoding::Ascii, 63);
check_str_limited("[[:xdigit:]]", Encoding::Ascii, 22);
}
#[test]
#[cfg(feature = "unicode")]
fn sanity_test_unicode_character_classes_size() {
// This test records the number of characters in each unicode class.
// If any of these test failed, please:
// 1. update the RHS of the numbers
// 2. increase the revision number of the regex-syntax dependency
// 3. update the relevant ranges in the test_unicode_* functions.
//
// (for easy reference, there are 1_112_064 assignable code points)
fn count_class_chars(pattern: &str) -> usize {
use regex_syntax::{
hir::{Class, HirKind},
parse,
};
let hir = parse(pattern).unwrap();
let HirKind::Class(Class::Unicode(cls)) = hir.into_kind() else { unreachable!() };
// we assume all positive unicode classes do not cover the surrogate range.
// otherwise `r.len()` is wrong.
cls.iter().map(|r| r.len()).sum()
}
assert_eq!(count_class_chars(r"\p{L}"), 136_104);
assert_eq!(count_class_chars(r"\p{M}"), 2_450);
assert_eq!(count_class_chars(r"\p{N}"), 1_831);
assert_eq!(count_class_chars(r"\p{P}"), 842);
assert_eq!(count_class_chars(r"\p{S}"), 7_770);
assert_eq!(count_class_chars(r"\p{Z}"), 19);
assert_eq!(count_class_chars(r"\p{C}"), 965_096);
assert_eq!(count_class_chars(r"\p{Latin}"), 1_481);
assert_eq!(count_class_chars(r"\p{Greek}"), 518);
assert_eq!(count_class_chars(r"\p{Cyrillic}"), 506);
assert_eq!(count_class_chars(r"\p{Armenian}"), 96);
assert_eq!(count_class_chars(r"\p{Hebrew}"), 134);
assert_eq!(count_class_chars(r"\p{Arabic}"), 1_368);
assert_eq!(count_class_chars(r"\p{Syriac}"), 88);
assert_eq!(count_class_chars(r"\p{Thaana}"), 50);
assert_eq!(count_class_chars(r"\p{Devanagari}"), 164);
assert_eq!(count_class_chars(r"\p{Bengali}"), 96);
assert_eq!(count_class_chars(r"\p{Gurmukhi}"), 80);
assert_eq!(count_class_chars(r"\p{Gujarati}"), 91);
assert_eq!(count_class_chars(r"\p{Oriya}"), 91);
assert_eq!(count_class_chars(r"\p{Tamil}"), 123);
assert_eq!(count_class_chars(r"\p{Hangul}"), 11_739);
assert_eq!(count_class_chars(r"\p{Hiragana}"), 381);
assert_eq!(count_class_chars(r"\p{Katakana}"), 321);
assert_eq!(count_class_chars(r"\p{Han}"), 98_408);
assert_eq!(count_class_chars(r"\p{Tagalog}"), 23);
assert_eq!(count_class_chars(r"\p{Linear_B}"), 211);
assert_eq!(count_class_chars(r"\p{Inherited}"), 657);
assert_eq!(count_class_chars(r"\d"), 680);
assert_eq!(count_class_chars(r"\s"), 25);
assert_eq!(count_class_chars(r"\w"), 139_612);
}
#[test]
#[cfg(feature = "unicode")]
fn test_unicode_character_classes() {
// The range describes the number of distinct strings we can get from the regex.
//
// Suppose the class has M members. If we randomly pick N items out of it with duplicates,
// the chance that there are K distinct members is the classical occupancy distibution[1]:
//
// Occ(K|N,M) = (S2(N,K) * M!) / ((M-K)! * M^N)
//
// where S2(N,K) are the Stirling numbers of the second kind.
//
// This distribution has mean and variance of
//
// μ = M * (1 - (1 - 1/M)^N)
// σ² = M * ((M(M-1))^N + (M-1)(M(M-2))^N - M(M-1)^(2N)) / M^(2N)
//
// which we can use to approximate as a normal distrubition and calculate the CDF to find
// out the 0.0001% percentile as the lower bound of K.
//
// (The upper bound should always be M, the 100% percentile.)
//
// The Mathematica code to compute the lower bound of K is:
//
// getInterval[m_, n_] := Block[{
// mean = m(1-(1-1/m)^n),
// var = m((m(m-1))^n+(m-1)(m(m-2))^n-m(m-1)^(2n))/m^(2n)
// }, InverseCDF[NormalDistribution[mean, Sqrt[var]], 1*^-6]
//
// (* Usage: getInterval[2450, 4096.0`32] *)
//
// [1]: https://doi.org/10.1080/00031305.2019.1699445
check_str_unlimited(r"\p{L}", Encoding::Utf8, 3999);
check_str(r"\p{M}", Encoding::Utf8, 1918..=2450, 4096);
check_str(r"\p{N}", Encoding::Utf8, 1582..=1831, 4096);
check_str(r"\p{P}", Encoding::Utf8, 824..=842, 4096);
check_str_unlimited(r"\p{S}", Encoding::Utf8, 3083);
check_str_limited(r"\p{Z}", Encoding::Utf8, 19);
check_str_unlimited(r"\p{C}", Encoding::Utf8, 4073);
check_str_unlimited(r"\P{L}", Encoding::Utf8, 4074);
check_str_unlimited(r"\P{M}", Encoding::Utf8, 4075);
check_str_unlimited(r"\P{N}", Encoding::Utf8, 4075);
check_str_unlimited(r"\P{P}", Encoding::Utf8, 4075);
check_str_unlimited(r"\P{S}", Encoding::Utf8, 4075);
check_str_unlimited(r"\P{Z}", Encoding::Utf8, 4075);
check_str_unlimited(r"\P{C}", Encoding::Utf8, 4004);
}
#[test]
#[cfg(feature = "unicode")]
fn test_unicode_script_classes() {
check_str(r"\p{Latin}", Encoding::Utf8, 1348..=1481, 4096);
check_str(r"\p{Greek}", Encoding::Utf8, 516..=518, 4096);
check_str(r"\p{Cyrillic}", Encoding::Utf8, 504..=506, 4096);
check_str_limited(r"\p{Armenian}", Encoding::Utf8, 96);
check_str_limited(r"\p{Hebrew}", Encoding::Utf8, 134);
check_str(r"\p{Arabic}", Encoding::Utf8, 1264..=1368, 4096);
check_str_limited(r"\p{Syriac}", Encoding::Utf8, 88);
check_str_limited(r"\p{Thaana}", Encoding::Utf8, 50);
check_str_limited(r"\p{Devanagari}", Encoding::Utf8, 164);
check_str_limited(r"\p{Bengali}", Encoding::Utf8, 96);
check_str_limited(r"\p{Gurmukhi}", Encoding::Utf8, 80);
check_str_limited(r"\p{Gujarati}", Encoding::Utf8, 91);
check_str_limited(r"\p{Oriya}", Encoding::Utf8, 91);
check_str_limited(r"\p{Tamil}", Encoding::Utf8, 123);
check_str_unlimited(r"\p{Hangul}", Encoding::Utf8, 3363);
check_str_limited(r"\p{Hiragana}", Encoding::Utf8, 381);
check_str_limited(r"\p{Katakana}", Encoding::Utf8, 321);
check_str_unlimited(r"\p{Han}", Encoding::Utf8, 3970);
check_str_limited(r"\p{Tagalog}", Encoding::Utf8, 23);
check_str_limited(r"\p{Linear_B}", Encoding::Utf8, 211);
check_str(r"\p{Inherited}", Encoding::Utf8, 650..=657, 4096);
}
#[test]
#[cfg(feature = "unicode")]
fn test_perl_classes() {
check_str_unlimited(r"\d+", Encoding::Utf8, 4061);
check_str_unlimited(r"\D+", Encoding::Utf8, 4096);
check_str_unlimited(r"\s+", Encoding::Utf8, 4014);
check_str_unlimited(r"\S+", Encoding::Utf8, 4096);
check_str_unlimited(r"\w+", Encoding::Utf8, 4095);
check_str_unlimited(r"\W+", Encoding::Utf8, 4096);
}
#[cfg(any())]
fn dump_categories() {
use regex_syntax::hir::*;
let categories = &[r"\p{Nd}", r"\p{Greek}"];
for cat in categories {
if let HirKind::Class(Class::Unicode(cls)) =
regex_syntax::Parser::new().parse(cat).unwrap().into_kind()
{
let s: u32 = cls
.iter()
.map(|r| u32::from(r.end()) - u32::from(r.start()) + 1)
.sum();
println!("{} => {}", cat, s);
}
}
}
#[test]
fn test_binary_generator() {
const PATTERN: &str = r"PE\x00\x00.{20}";
let r = regex::bytes::RegexBuilder::new(PATTERN)
.unicode(false)
.dot_matches_new_line(true)
.build()
.unwrap();
let hir = regex_syntax::ParserBuilder::new()
.unicode(false)
.dot_matches_new_line(true)
.utf8(false)
.build()
.parse(PATTERN)
.unwrap();
let gen = Regex::with_hir(hir, 100).unwrap();
assert_eq!(gen.capacity(), 24);
assert!(!gen.is_utf8());
assert_eq!(gen.encoding(), Encoding::Binary);
let mut rng = thread_rng();
for res in gen.sample_iter(&mut rng).take(8192) {
let res: Vec<u8> = res;
assert!(r.is_match(&res), "Wrong sample: {:?}, `{:?}`", r, res);
}
}
#[test]
fn test_encoding_generator_1() {
let hir = regex_syntax::ParserBuilder::new()
.unicode(false)
.utf8(false)
.build()
.parse(r"[\x00-\xff]{2}")
.unwrap();
let gen = Regex::with_hir(hir, 100).unwrap();
// This pattern will produce:
// - 16384 ASCII patterns (128^2)
// - 1920 UTF-8 patterns (30 * 64)
// - 47232 binary patterns (256^2 - 16384 - 1920)
let mut encoding_counts = [0; 3];
let mut rng = thread_rng();
for encoded_string in gen.sample_iter(&mut rng).take(8192) {
let encoded_string: EncodedString = encoded_string;
let bytes = encoded_string.as_bytes();
let encoding = encoded_string.encoding();
assert_eq!(bytes.len(), 2);
if bytes.is_ascii() {
assert_eq!(encoding, Encoding::Ascii);
} else if std::str::from_utf8(bytes).is_ok() {
assert_eq!(encoding, Encoding::Utf8);
} else {
assert_eq!(encoding, Encoding::Binary);
}
encoding_counts[encoding as usize] += 1;
}
// the following ranges are 99.9999% confidence intervals of the multinomial distribution.
assert!((1858..2243).contains(&encoding_counts[Encoding::Ascii as usize]));
assert!((169..319).contains(&encoding_counts[Encoding::Utf8 as usize]));
assert!((5704..6102).contains(&encoding_counts[Encoding::Binary as usize]));
}
#[test]
fn test_encoding_generator_2() {
let gen = Regex::compile(r"[\u{0}-\u{b5}]{2}", 100).unwrap();
// This pattern will produce 32761 distinct outputs, with:
// - 16384 ASCII patterns
// - 16377 UTF-8 patterns
let mut encoding_counts = [0; 2];
let mut rng = thread_rng();
for encoded_string in gen.sample_iter(&mut rng).take(8192) {
let encoded_string: EncodedString = encoded_string;
let encoding = encoded_string.encoding();
let string = encoded_string.as_str().unwrap();
assert_eq!(string.chars().count(), 2);
if string.is_ascii() {
assert_eq!(encoding, Encoding::Ascii);
assert_eq!(string.len(), 2);
} else {
assert_eq!(encoding, Encoding::Utf8);
}
encoding_counts[encoding as usize] += 1;
}
// the following ranges are 99.9999% confidence intervals of the multinomial distribution.
assert!((3876..4319).contains(&encoding_counts[Encoding::Ascii as usize]));
assert!((3874..4317).contains(&encoding_counts[Encoding::Utf8 as usize]));
}
#[test]
fn test_encoding_generator_3() {
let gen = Regex::compile(r"[\u{0}-\u{7f}]{2}", 100).unwrap();
let mut rng = thread_rng();
for encoded_string in gen.sample_iter(&mut rng).take(8192) {
let encoded_string: EncodedString = encoded_string;
assert_eq!(encoded_string.encoding(), Encoding::Ascii);
assert_eq!(String::try_from(encoded_string).unwrap().len(), 2);
}
}
#[test]
#[should_panic(expected = "FromUtf8Error")]
fn test_generating_non_utf8_string() {
let hir = regex_syntax::ParserBuilder::new()
.unicode(false)
.utf8(false)
.build()
.parse(r"\x88")
.unwrap();
let gen = Regex::with_hir(hir, 100).unwrap();
assert!(!gen.is_utf8());
assert_eq!(gen.encoding(), Encoding::Binary);
let mut rng = thread_rng();
let _: String = rng.sample(&gen);
}
}
|
use crate::io::*;
use crate::layers::loss_layer::SoftMaxWithLoss;
use crate::model::*;
use crate::optimizer::{AdaGrad, Adam, Optimizer, SGD};
use crate::trainer::*;
use crate::types::*;
use crate::util::*;
extern crate ndarray;
use ndarray::{Array, Axis, Slice};
pub fn train2() {
const PRINT_ITER_NUM: usize = 10;
const HIDDEN_SIZE: usize = 10;
const BATCH_SIZE: usize = 30;
const MAX_EPOCH: usize = 300;
let data = csv_to_array::<f32>("./data/spiral/x.csv").expect("cannot read data csv");
let target = csv_to_array::<f32>("./data/spiral/t.csv").expect("cannot read target csv");
let data_len = data.shape()[0];
assert_eq!(data_len, target.shape()[0]);
println!("{:?}", target);
println!("{:?}, {:?}", data.dim(), target.dim());
let mut model = TwoLayerNet::<SoftMaxWithLoss>::new(2, HIDDEN_SIZE, 3);
// let mut optimizer = SGD { lr: 1.0 };
// let mut optimizer = AdaGrad::new(1.0);
let mut optimizer = Adam::new(0.001, 0.9, 0.999);
let mut trainer = Trainer::new(model, optimizer);
trainer.fit(
data,
target,
MAX_EPOCH,
BATCH_SIZE,
None,
Some(PRINT_ITER_NUM),
);
trainer.show_loss();
}
pub fn train() {
const INPUT_DIM: usize = 2;
const TARGET_SIZE: usize = 3;
const PRINT_ITER_NUM: usize = 10;
let hidden_size = 10;
let batch_size = 30;
let max_epoch = 300;
let data = read_csv::<[f32; INPUT_DIM]>("./data/spiral/x.csv").expect("cannot read data csv");
let data = Array::from_shape_fn((data.len(), INPUT_DIM), |(i, j)| data[i][j]);
let target =
read_csv::<[f32; TARGET_SIZE]>("./data/spiral/t.csv").expect("cannot read target csv");
let target = Array::from_shape_fn((target.len(), TARGET_SIZE), |(i, j)| target[i][j]);
let data_len = data.shape()[0];
assert_eq!(data_len, target.shape()[0]);
let mut model = TwoLayerNet::<SoftMaxWithLoss>::new(2, hidden_size, 3);
// let mut optimizer = SGD { lr: 1.0 };
let mut optimizer = AdaGrad::new(1.0);
let max_iters = data_len / batch_size;
let mut loss_list = Vec::<f32>::new();
for epoch in 1..=max_epoch {
let idx = random_index(data_len);
// 一定回数イテレーションするたびに平均の損失を記録する
let mut total_loss: f32 = 0.0;
let mut loss_count: i32 = 0;
for iters in 1..=max_iters {
let batch_idx = &idx[(iters - 1) * batch_size..iters * batch_size];
// こういう事したいのだが...。
// data.slice_axis(Axis(0), batch_idx);
let batch_data =
Array::from_shape_fn((batch_size, INPUT_DIM), |(i, j)| data[[batch_idx[i], j]]);
let batch_target = Array::from_shape_fn((batch_size, TARGET_SIZE), |(i, j)| {
target[[batch_idx[i], j]]
});
let loss = model.forward(batch_data, &batch_target);
model.backward(batch_size);
// moedl.params1dArr1del.grads1dは片方が&mut self, もう片方が&selfでArr1d
// 実際はselfの中の別々のもArr2dスしているので、問題はないはずだが、Arr2d
// コンパイラとしてはそれらのselfの同一フィールドにアクセスしている可能性がある
// つまり結局同一のフィール度に参照と可変参照の両方でアクセスする可能性があるので
// エラーとしているのか...。
// optimizer.update1d(model.params1d(), model.grads1d());
//
// let grads1d: Vec<Arr1d> = model.grads1d().into_iter().map(Arr1d::clone).collect();
// let grads2d: Vec<Arr2d> = model.grads2d().into_iter().map(Arr2d::clone).collect();
// optimizer.update1d(model.params1d(), grads1d);
// // optimizer.update2d(model.params2d(), grads2d);
// optimizer.update1d(model.params1d(), model.grads1d());
// optimizer.update2d(model.params2d(), model.grads2d());
total_loss += loss; // 1バッチごとに損失を加算していく
loss_count += 1; // バッチ回数を記録
if iters % PRINT_ITER_NUM == 0 {
let avg_loss = total_loss / loss_count as f32;
println!(
"|epoch {}| iter {}/{} | loss {}",
epoch, iters, max_iters, avg_loss
);
loss_list.push(avg_loss);
total_loss = 0.0;
loss_count = 0;
}
}
}
println!("hello?");
putsl!(data);
putsl!(target);
putsl!(loss_list);
}
#[test]
fn ch01_train() {
train2();
}
|
fn is_multiple_of(n: u64) -> impl Fn(&u64) -> bool {
move |m: &u64| *m % n == 0
}
pub fn is_multiple_of_5_or_3(n: &u64) -> bool {
is_multiple_of(5)(n) || is_multiple_of(3)(n)
}
pub fn solve(max: u64) -> u64 {
(1..max).into_iter().filter(is_multiple_of_5_or_3).sum()
}
|
//! ### Reverse Complement Problem
//!
//! Find the reverse complement of a DNA string.
//!
//! **Given:** A DNA string Pattern.
//!
//! **Return:** Pattern, the reverse complement of Pattern.
extern crate bio_algorithms as bio;
use std::fs::File;
use std::io::prelude::*;
use bio::bio_types::DNA_Sequence;
fn main() {
let mut f = File::open("test_files/1c.txt").expect("Coudln't open file");
let mut file_text = String::new();
f.read_to_string(&mut file_text)
.expect("Couldn't read file");
let lines: Vec<&str> = file_text.split('\n').collect();
let pattern_string = lines[0];
let mut dna_pattern = DNA_Sequence::from_string(pattern_string);
println!("{}", dna_pattern.reverse_complement())
}
|
#[doc = "Register `DFSDM_FLT3AWHTR` reader"]
pub type R = crate::R<DFSDM_FLT3AWHTR_SPEC>;
#[doc = "Register `DFSDM_FLT3AWHTR` writer"]
pub type W = crate::W<DFSDM_FLT3AWHTR_SPEC>;
#[doc = "Field `BKAWH` reader - Break signal assignment to analog watchdog high threshold event"]
pub type BKAWH_R = crate::FieldReader;
#[doc = "Field `BKAWH` writer - Break signal assignment to analog watchdog high threshold event"]
pub type BKAWH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `AWHT` reader - Analog watchdog high threshold"]
pub type AWHT_R = crate::FieldReader<u32>;
#[doc = "Field `AWHT` writer - Analog watchdog high threshold"]
pub type AWHT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 24, O, u32>;
impl R {
#[doc = "Bits 0:3 - Break signal assignment to analog watchdog high threshold event"]
#[inline(always)]
pub fn bkawh(&self) -> BKAWH_R {
BKAWH_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:31 - Analog watchdog high threshold"]
#[inline(always)]
pub fn awht(&self) -> AWHT_R {
AWHT_R::new((self.bits >> 8) & 0x00ff_ffff)
}
}
impl W {
#[doc = "Bits 0:3 - Break signal assignment to analog watchdog high threshold event"]
#[inline(always)]
#[must_use]
pub fn bkawh(&mut self) -> BKAWH_W<DFSDM_FLT3AWHTR_SPEC, 0> {
BKAWH_W::new(self)
}
#[doc = "Bits 8:31 - Analog watchdog high threshold"]
#[inline(always)]
#[must_use]
pub fn awht(&mut self) -> AWHT_W<DFSDM_FLT3AWHTR_SPEC, 8> {
AWHT_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "analog watchdog high threshold register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dfsdm_flt3awhtr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dfsdm_flt3awhtr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DFSDM_FLT3AWHTR_SPEC;
impl crate::RegisterSpec for DFSDM_FLT3AWHTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dfsdm_flt3awhtr::R`](R) reader structure"]
impl crate::Readable for DFSDM_FLT3AWHTR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dfsdm_flt3awhtr::W`](W) writer structure"]
impl crate::Writable for DFSDM_FLT3AWHTR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DFSDM_FLT3AWHTR to value 0"]
impl crate::Resettable for DFSDM_FLT3AWHTR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! This example demonstrates creating a [`CompactTable`] `from()` a
//! multidimensional array.
//!
//! * Note how [`CompactTable::from()`] inherits the lengths of the nested arrays
//! as typed definitions through [const generics](https://practice.rs/generics-traits/const-generics.html).
use tabled::{settings::Style, tables::CompactTable};
fn main() {
let data = [
["Debian", "1.1.1.1", "true"],
["Arch", "127.1.1.1", "true"],
["Manjaro", "Arch", "true"],
];
let _table = CompactTable::from(data).with(Style::psql());
#[cfg(feature = "std")]
println!("{}", _table.to_string());
}
|
extern crate algorithm;
use algorithm::genetic;
#[test]
fn test1() {
assert_eq!(2, genetic::test());
}
|
mod stm32f1xx;
#[cfg(feature = "stm32f1xx")]
use stm32f1xx as dev;
pub type GpioOutError = dev::GpioOutError;
pub type GpioInError = dev::GpioInError;
pub type TimerError = dev::TimerError;
pub type Pin = dev::Pin;
pub type Port = dev::Port;
pub type TimerID = dev::TimerID;
pub type Time = dev::Time;
#[inline]
pub(crate) fn disable_interrupts() {
dev::disable_interrupts()
}
#[inline]
pub(crate) fn enable_interrupts() {
dev::enable_interrupts()
}
|
use chrono::{DateTime, Utc};
use eyre::Report;
use hashbrown::HashMap;
use rosu_v2::model::GameMode;
use serde_json::Value;
use sqlx::{types::Json, ColumnIndex, Decode, Error, FromRow, Row, Type};
use std::collections::HashMap as StdHashMap;
use twilight_model::id::{marker::ChannelMarker, Id};
#[derive(Debug)]
pub struct TrackingUser {
pub user_id: u32,
pub mode: GameMode,
pub last_top_score: DateTime<Utc>,
pub channels: HashMap<Id<ChannelMarker>, usize>,
}
impl TrackingUser {
pub fn new(
user_id: u32,
mode: GameMode,
last_top_score: DateTime<Utc>,
channel: Id<ChannelMarker>,
limit: usize,
) -> Self {
let mut channels = HashMap::new();
channels.insert(channel, limit);
Self {
user_id,
mode,
last_top_score,
channels,
}
}
pub fn remove_channel(&mut self, channel: Id<ChannelMarker>) -> bool {
self.channels.remove(&channel).is_some()
}
}
impl<'r, R> FromRow<'r, R> for TrackingUser
where
R: Row,
usize: ColumnIndex<R>,
i8: Type<<R as Row>::Database>,
i8: Decode<'r, <R as Row>::Database>,
u32: Type<<R as Row>::Database>,
u32: Decode<'r, <R as Row>::Database>,
DateTime<Utc>: Type<<R as Row>::Database>,
DateTime<Utc>: Decode<'r, <R as Row>::Database>,
Json<Value>: Type<<R as Row>::Database>,
Json<Value>: Decode<'r, <R as Row>::Database>,
{
fn from_row(row: &'r R) -> Result<Self, Error> {
let user_id: u32 = row.try_get(0)?;
let mode: i8 = row.try_get(1)?;
let mode = GameMode::from(mode as u8);
let last_top_score: DateTime<Utc> = row.try_get(2)?;
let channels = match serde_json::from_value::<StdHashMap<String, usize>>(row.try_get(3)?) {
Ok(channels) => channels
.into_iter()
.map(|(id, limit)| (Id::new(id.parse().unwrap()), limit))
.collect(),
Err(why) => {
let wrap =
format!("failed to deserialize tracking channels value for ({user_id},{mode})");
let report = Report::new(why).wrap_err(wrap);
warn!("{:?}", report);
HashMap::new()
}
};
Ok(Self {
user_id,
mode,
last_top_score,
channels,
})
}
}
|
use serde::{Deserialize, Serialize};
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub(in super::super) struct SqlStateClass {
pub(in super::super) class: String,
pub(in super::super) class_text: String,
}
impl SqlStateClass {
pub(in super::super) fn new(class: &str, class_text: &str) -> Self {
Self {
class: class.to_string(),
class_text: class_text.to_string(),
}
}
}
|
use renderer::{ Model, VertexFormat, VertexAttribute };
pub fn make_plane() -> Model {
let mut verts = [
0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0,
1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,
];
let inds = [
1, 0, 3, 3, 2, 1
];
let fmt = VertexFormat::new(&[
VertexAttribute::new(3, false),
VertexAttribute::new(3, false),
VertexAttribute::new(2, false)
]);
Model::from(&verts, &inds, fmt)
} |
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about conversions from one type to
//! another. They follow the standard Rust conventions of `as`/`into`/`from`.
//!
//! Like many traits, these are often used as bounds for generic functions, to support arguments of
//! multiple types.
//!
//! See each trait for usage examples.
#![stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
/// A cheap, reference-to-reference conversion.
///
/// # Examples
///
/// Both `String` and `&str` implement `AsRef<str>`:
///
/// ```
/// fn is_hello<T: AsRef<str>>(s: T) {
/// assert_eq!("hello", s.as_ref());
/// }
///
/// let s = "hello";
/// is_hello(s);
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_ref(&self) -> &T;
}
/// A cheap, mutable reference-to-mutable reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_mut(&mut self) -> &mut T;
}
/// A conversion that consumes `self`, which may or may not be expensive.
///
/// # Examples
///
/// `String` implements `Into<Vec<u8>>`:
///
/// ```
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
/// let bytes = b"hello".to_vec();
/// assert_eq!(bytes, s.into());
/// }
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn into(self) -> T;
}
/// Construct `Self` via a conversion.
///
/// # Examples
///
/// `String` implements `From<&str>`:
///
/// ```
/// let s = "hello";
/// let string = "hello".to_string();
///
/// let other_string: String = From::from(s);
///
/// assert_eq!(string, other_string);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn from(T) -> Self;
}
////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////
// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
// fn as_ref(&self) -> &U {
// self.deref().as_ref()
// }
// }
// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
fn as_mut(&mut self) -> &mut U {
(*self).as_mut()
}
}
// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
// fn as_mut(&mut self) -> &mut U {
// self.deref_mut().as_mut()
// }
// }
// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
fn into(self) -> U {
U::from(self)
}
}
// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
fn from(t: T) -> T { t }
}
////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
fn as_ref(&self) -> &[T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
fn as_mut(&mut self) -> &mut [T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
fn as_ref(&self) -> &str {
self
}
}
|
use std::env;
use std::fs;
fn main(){
let args : Vec<String> = env::args().collect();
if args.len() < 2 {
return;
}
let lines = fs::read_to_string(&args[1]).unwrap();
let linelength = lines.split('\n').collect::<Vec<&str>>()[0].len();
let mut map : Vec<Vec<i32>> = Vec::new();
for _ in 0..linelength {
map.push(Vec::<i32>::new());
for _ in 0..26 {
map.last_mut().unwrap().push(0);
}
}
for line in lines.split('\n') {
if line == "" {
continue;
}
for i in 0..linelength {
let c = line.chars().nth(i).unwrap();
map[i][(c as usize) - ('a' as usize)] += 1;
}
}
for submap in map {
let maxcount = submap.iter().max().unwrap();
for i in 0..26 {
if submap[i] == *maxcount {
print!("{}", (i + 'a' as usize) as u8 as char);
break;
}
}
}
println!();
}
|
fn main() {
println!("Hello, world!");
case_string_test();
create_a_new_string();
update_a_string();
concat_with_plus();
indexing_into_string();
}
fn case_string_test() {
let s = "Hello World";
let a = &s[0..1];
println!("{}", a);
let s = String::from("Hello World");
let a: &str = &s[..];
println!("{}", a);
}
fn create_a_new_string() {
// creating a new empty string.
let mut s = String::new();
let data = "initial contents";
let s = data.to_string();
let s: String = "initial contents".to_string();
let s: String = String::from("initial content");
let hello = String::from("안녕하세요");
let hello = "안녕하세요".to_string();
}
fn update_a_string() {
let mut s = String::from("foo");
s.push_str("bar");
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(&s2);
println!("s1 is {}", s1);
println!("s2 is {}", s2);
let mut s = String::from("lo");
s.push('l');
println!("s is {}", s);
}
fn concat_with_plus() {
// let s1 = "Hello ";
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // String.add(self, s : &str) -> String
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = s1 + "-" + &s2 + "-" + &s3;
println!("{}", s);
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{}-{}-{}", s1,s2, s3);
println!("{}", s);
}
fn indexing_into_string() {
let s = String::from("hello");
// let h = s1[0]; // error!
// inner representation
let len = String::from("Hola").len();
println!("length 'Hola' => {}", len); // 4
let len = String::from("안녕하세요").len();
println!("length '안녕하세요' => {}", len); // 4
let s = "안녕하세요";
println!("{}", &s[0..3]);
for c in s.chars() {
println!("char => {}", c);
}
for b in s.bytes() {
println!("byte => {}", b);
}
}
|
mod dedup;
mod manager;
mod page;
mod state_block;
|
#[doc = "Register `APB1LENR` reader"]
pub type R = crate::R<APB1LENR_SPEC>;
#[doc = "Register `APB1LENR` writer"]
pub type W = crate::W<APB1LENR_SPEC>;
#[doc = "Field `TIM2EN` reader - TIM2 peripheral clock enable Set and reset by software."]
pub type TIM2EN_R = crate::BitReader<TIM2EN_A>;
#[doc = "TIM2 peripheral clock enable Set and reset by software.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TIM2EN_A {
#[doc = "0: The selected clock is disabled"]
Disabled = 0,
#[doc = "1: The selected clock is enabled"]
Enabled = 1,
}
impl From<TIM2EN_A> for bool {
#[inline(always)]
fn from(variant: TIM2EN_A) -> Self {
variant as u8 != 0
}
}
impl TIM2EN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIM2EN_A {
match self.bits {
false => TIM2EN_A::Disabled,
true => TIM2EN_A::Enabled,
}
}
#[doc = "The selected clock is disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == TIM2EN_A::Disabled
}
#[doc = "The selected clock is enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == TIM2EN_A::Enabled
}
}
#[doc = "Field `TIM2EN` writer - TIM2 peripheral clock enable Set and reset by software."]
pub type TIM2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIM2EN_A>;
impl<'a, REG, const O: u8> TIM2EN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "The selected clock is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(TIM2EN_A::Disabled)
}
#[doc = "The selected clock is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(TIM2EN_A::Enabled)
}
}
#[doc = "Field `TIM3EN` reader - TIM3 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM3EN_R;
#[doc = "Field `TIM4EN` reader - TIM4 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM4EN_R;
#[doc = "Field `TIM5EN` reader - TIM5 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM5EN_R;
#[doc = "Field `TIM6EN` reader - TIM6 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM6EN_R;
#[doc = "Field `TIM7EN` reader - TIM7 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM7EN_R;
#[doc = "Field `TIM12EN` reader - TIM12 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM12EN_R;
#[doc = "Field `TIM13EN` reader - TIM13 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM13EN_R;
#[doc = "Field `TIM14EN` reader - TIM14 peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as TIM14EN_R;
#[doc = "Field `LPTIM1EN` reader - LPTIM1 peripheral clocks enable Set and reset by software. The peripheral clocks of the LPTIM1 are the kernel clock selected by LPTIM1SEL and provided to lptim_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as LPTIM1EN_R;
#[doc = "Field `SPI2EN` reader - SPI2 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI2 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as SPI2EN_R;
#[doc = "Field `SPI3EN` reader - SPI3 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI3 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as SPI3EN_R;
#[doc = "Field `SPDIFRXEN` reader - SPDIFRX peripheral clocks enable Set and reset by software. The peripheral clocks of the SPDIFRX are the kernel clock selected by SPDIFRXSEL and provided to spdifrx_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as SPDIFRXEN_R;
#[doc = "Field `USART2EN` reader - USART2peripheral clocks enable Set and reset by software. The peripheral clocks of the USART2 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as USART2EN_R;
#[doc = "Field `USART3EN` reader - USART3 peripheral clocks enable Set and reset by software. The peripheral clocks of the USART3 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as USART3EN_R;
#[doc = "Field `UART4EN` reader - UART4 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART4 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as UART4EN_R;
#[doc = "Field `UART5EN` reader - UART5 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART5 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as UART5EN_R;
#[doc = "Field `I2C1EN` reader - I2C1 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C1 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as I2C1EN_R;
#[doc = "Field `I2C2EN` reader - I2C2 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C2 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as I2C2EN_R;
#[doc = "Field `I2C3EN` reader - I2C3 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C3 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as I2C3EN_R;
#[doc = "Field `CECEN` reader - HDMI-CEC peripheral clock enable Set and reset by software. The peripheral clocks of the HDMI-CEC are the kernel clock selected by CECSEL and provided to cec_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as CECEN_R;
#[doc = "Field `DAC1EN` reader - DAC1 (containing two converters) peripheral clock enable Set and reset by software."]
pub use TIM2EN_R as DAC1EN_R;
#[doc = "Field `UART7EN` reader - UART7 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART7 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as UART7EN_R;
#[doc = "Field `UART8EN` reader - UART8 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART8 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_R as UART8EN_R;
#[doc = "Field `TIM3EN` writer - TIM3 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM3EN_W;
#[doc = "Field `TIM4EN` writer - TIM4 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM4EN_W;
#[doc = "Field `TIM5EN` writer - TIM5 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM5EN_W;
#[doc = "Field `TIM6EN` writer - TIM6 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM6EN_W;
#[doc = "Field `TIM7EN` writer - TIM7 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM7EN_W;
#[doc = "Field `TIM12EN` writer - TIM12 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM12EN_W;
#[doc = "Field `TIM13EN` writer - TIM13 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM13EN_W;
#[doc = "Field `TIM14EN` writer - TIM14 peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as TIM14EN_W;
#[doc = "Field `LPTIM1EN` writer - LPTIM1 peripheral clocks enable Set and reset by software. The peripheral clocks of the LPTIM1 are the kernel clock selected by LPTIM1SEL and provided to lptim_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as LPTIM1EN_W;
#[doc = "Field `SPI2EN` writer - SPI2 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI2 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as SPI2EN_W;
#[doc = "Field `SPI3EN` writer - SPI3 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI3 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as SPI3EN_W;
#[doc = "Field `SPDIFRXEN` writer - SPDIFRX peripheral clocks enable Set and reset by software. The peripheral clocks of the SPDIFRX are the kernel clock selected by SPDIFRXSEL and provided to spdifrx_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as SPDIFRXEN_W;
#[doc = "Field `USART2EN` writer - USART2peripheral clocks enable Set and reset by software. The peripheral clocks of the USART2 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as USART2EN_W;
#[doc = "Field `USART3EN` writer - USART3 peripheral clocks enable Set and reset by software. The peripheral clocks of the USART3 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as USART3EN_W;
#[doc = "Field `UART4EN` writer - UART4 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART4 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as UART4EN_W;
#[doc = "Field `UART5EN` writer - UART5 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART5 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as UART5EN_W;
#[doc = "Field `I2C1EN` writer - I2C1 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C1 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as I2C1EN_W;
#[doc = "Field `I2C2EN` writer - I2C2 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C2 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as I2C2EN_W;
#[doc = "Field `I2C3EN` writer - I2C3 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C3 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as I2C3EN_W;
#[doc = "Field `CECEN` writer - HDMI-CEC peripheral clock enable Set and reset by software. The peripheral clocks of the HDMI-CEC are the kernel clock selected by CECSEL and provided to cec_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as CECEN_W;
#[doc = "Field `DAC1EN` writer - DAC1 (containing two converters) peripheral clock enable Set and reset by software."]
pub use TIM2EN_W as DAC1EN_W;
#[doc = "Field `UART7EN` writer - UART7 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART7 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as UART7EN_W;
#[doc = "Field `UART8EN` writer - UART8 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART8 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
pub use TIM2EN_W as UART8EN_W;
impl R {
#[doc = "Bit 0 - TIM2 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim2en(&self) -> TIM2EN_R {
TIM2EN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - TIM3 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim3en(&self) -> TIM3EN_R {
TIM3EN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - TIM4 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim4en(&self) -> TIM4EN_R {
TIM4EN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - TIM5 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim5en(&self) -> TIM5EN_R {
TIM5EN_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - TIM6 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim6en(&self) -> TIM6EN_R {
TIM6EN_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - TIM7 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim7en(&self) -> TIM7EN_R {
TIM7EN_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - TIM12 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim12en(&self) -> TIM12EN_R {
TIM12EN_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - TIM13 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim13en(&self) -> TIM13EN_R {
TIM13EN_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - TIM14 peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn tim14en(&self) -> TIM14EN_R {
TIM14EN_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - LPTIM1 peripheral clocks enable Set and reset by software. The peripheral clocks of the LPTIM1 are the kernel clock selected by LPTIM1SEL and provided to lptim_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn lptim1en(&self) -> LPTIM1EN_R {
LPTIM1EN_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 14 - SPI2 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI2 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn spi2en(&self) -> SPI2EN_R {
SPI2EN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - SPI3 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI3 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn spi3en(&self) -> SPI3EN_R {
SPI3EN_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - SPDIFRX peripheral clocks enable Set and reset by software. The peripheral clocks of the SPDIFRX are the kernel clock selected by SPDIFRXSEL and provided to spdifrx_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn spdifrxen(&self) -> SPDIFRXEN_R {
SPDIFRXEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - USART2peripheral clocks enable Set and reset by software. The peripheral clocks of the USART2 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn usart2en(&self) -> USART2EN_R {
USART2EN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - USART3 peripheral clocks enable Set and reset by software. The peripheral clocks of the USART3 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn usart3en(&self) -> USART3EN_R {
USART3EN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - UART4 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART4 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn uart4en(&self) -> UART4EN_R {
UART4EN_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - UART5 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART5 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn uart5en(&self) -> UART5EN_R {
UART5EN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - I2C1 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C1 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn i2c1en(&self) -> I2C1EN_R {
I2C1EN_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - I2C2 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C2 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn i2c2en(&self) -> I2C2EN_R {
I2C2EN_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - I2C3 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C3 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn i2c3en(&self) -> I2C3EN_R {
I2C3EN_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 27 - HDMI-CEC peripheral clock enable Set and reset by software. The peripheral clocks of the HDMI-CEC are the kernel clock selected by CECSEL and provided to cec_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn cecen(&self) -> CECEN_R {
CECEN_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 29 - DAC1 (containing two converters) peripheral clock enable Set and reset by software."]
#[inline(always)]
pub fn dac1en(&self) -> DAC1EN_R {
DAC1EN_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - UART7 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART7 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn uart7en(&self) -> UART7EN_R {
UART7EN_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - UART8 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART8 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
pub fn uart8en(&self) -> UART8EN_R {
UART8EN_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM2 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim2en(&mut self) -> TIM2EN_W<APB1LENR_SPEC, 0> {
TIM2EN_W::new(self)
}
#[doc = "Bit 1 - TIM3 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim3en(&mut self) -> TIM3EN_W<APB1LENR_SPEC, 1> {
TIM3EN_W::new(self)
}
#[doc = "Bit 2 - TIM4 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim4en(&mut self) -> TIM4EN_W<APB1LENR_SPEC, 2> {
TIM4EN_W::new(self)
}
#[doc = "Bit 3 - TIM5 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim5en(&mut self) -> TIM5EN_W<APB1LENR_SPEC, 3> {
TIM5EN_W::new(self)
}
#[doc = "Bit 4 - TIM6 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim6en(&mut self) -> TIM6EN_W<APB1LENR_SPEC, 4> {
TIM6EN_W::new(self)
}
#[doc = "Bit 5 - TIM7 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim7en(&mut self) -> TIM7EN_W<APB1LENR_SPEC, 5> {
TIM7EN_W::new(self)
}
#[doc = "Bit 6 - TIM12 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim12en(&mut self) -> TIM12EN_W<APB1LENR_SPEC, 6> {
TIM12EN_W::new(self)
}
#[doc = "Bit 7 - TIM13 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim13en(&mut self) -> TIM13EN_W<APB1LENR_SPEC, 7> {
TIM13EN_W::new(self)
}
#[doc = "Bit 8 - TIM14 peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn tim14en(&mut self) -> TIM14EN_W<APB1LENR_SPEC, 8> {
TIM14EN_W::new(self)
}
#[doc = "Bit 9 - LPTIM1 peripheral clocks enable Set and reset by software. The peripheral clocks of the LPTIM1 are the kernel clock selected by LPTIM1SEL and provided to lptim_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn lptim1en(&mut self) -> LPTIM1EN_W<APB1LENR_SPEC, 9> {
LPTIM1EN_W::new(self)
}
#[doc = "Bit 14 - SPI2 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI2 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn spi2en(&mut self) -> SPI2EN_W<APB1LENR_SPEC, 14> {
SPI2EN_W::new(self)
}
#[doc = "Bit 15 - SPI3 peripheral clocks enable Set and reset by software. The peripheral clocks of the SPI3 are the kernel clock selected by I2S123SRC and provided to spi_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn spi3en(&mut self) -> SPI3EN_W<APB1LENR_SPEC, 15> {
SPI3EN_W::new(self)
}
#[doc = "Bit 16 - SPDIFRX peripheral clocks enable Set and reset by software. The peripheral clocks of the SPDIFRX are the kernel clock selected by SPDIFRXSEL and provided to spdifrx_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn spdifrxen(&mut self) -> SPDIFRXEN_W<APB1LENR_SPEC, 16> {
SPDIFRXEN_W::new(self)
}
#[doc = "Bit 17 - USART2peripheral clocks enable Set and reset by software. The peripheral clocks of the USART2 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn usart2en(&mut self) -> USART2EN_W<APB1LENR_SPEC, 17> {
USART2EN_W::new(self)
}
#[doc = "Bit 18 - USART3 peripheral clocks enable Set and reset by software. The peripheral clocks of the USART3 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn usart3en(&mut self) -> USART3EN_W<APB1LENR_SPEC, 18> {
USART3EN_W::new(self)
}
#[doc = "Bit 19 - UART4 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART4 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn uart4en(&mut self) -> UART4EN_W<APB1LENR_SPEC, 19> {
UART4EN_W::new(self)
}
#[doc = "Bit 20 - UART5 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART5 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn uart5en(&mut self) -> UART5EN_W<APB1LENR_SPEC, 20> {
UART5EN_W::new(self)
}
#[doc = "Bit 21 - I2C1 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C1 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn i2c1en(&mut self) -> I2C1EN_W<APB1LENR_SPEC, 21> {
I2C1EN_W::new(self)
}
#[doc = "Bit 22 - I2C2 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C2 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn i2c2en(&mut self) -> I2C2EN_W<APB1LENR_SPEC, 22> {
I2C2EN_W::new(self)
}
#[doc = "Bit 23 - I2C3 peripheral clocks enable Set and reset by software. The peripheral clocks of the I2C3 are the kernel clock selected by I2C123SEL and provided to i2C_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn i2c3en(&mut self) -> I2C3EN_W<APB1LENR_SPEC, 23> {
I2C3EN_W::new(self)
}
#[doc = "Bit 27 - HDMI-CEC peripheral clock enable Set and reset by software. The peripheral clocks of the HDMI-CEC are the kernel clock selected by CECSEL and provided to cec_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn cecen(&mut self) -> CECEN_W<APB1LENR_SPEC, 27> {
CECEN_W::new(self)
}
#[doc = "Bit 29 - DAC1 (containing two converters) peripheral clock enable Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn dac1en(&mut self) -> DAC1EN_W<APB1LENR_SPEC, 29> {
DAC1EN_W::new(self)
}
#[doc = "Bit 30 - UART7 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART7 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn uart7en(&mut self) -> UART7EN_W<APB1LENR_SPEC, 30> {
UART7EN_W::new(self)
}
#[doc = "Bit 31 - UART8 peripheral clocks enable Set and reset by software. The peripheral clocks of the UART8 are the kernel clock selected by USART234578SEL and provided to usart_ker_ck input, and the rcc_pclk1 bus interface clock."]
#[inline(always)]
#[must_use]
pub fn uart8en(&mut self) -> UART8EN_W<APB1LENR_SPEC, 31> {
UART8EN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1lenr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1lenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB1LENR_SPEC;
impl crate::RegisterSpec for APB1LENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb1lenr::R`](R) reader structure"]
impl crate::Readable for APB1LENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb1lenr::W`](W) writer structure"]
impl crate::Writable for APB1LENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB1LENR to value 0"]
impl crate::Resettable for APB1LENR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[test]
fn test_all() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/surface_*.rs");
}
|
use crate::functions::*;
use crate::layers::*;
use crate::math::Derivative;
use crate::params::*;
use crate::types::*;
use itertools::izip;
use ndarray::{s, Array1, Axis, Dimension, Ix2, Ix3, RemoveAxis};
#[derive(Default)]
struct Cache {
x: Arr2d,
h_prev: Arr2d,
h_next: Arr2d,
}
/// 外部入力 x: (b, c), wx: (c, h)
/// 相互入出力 h: (b, h), wh: (h, h)
/// 上位のTimeRNNではこれがtime_size個存在する
struct RNN<'a> {
wx: &'a P1<Arr2d>,
wh: &'a P1<Arr2d>,
b: &'a P1<Arr1d>,
cache: Cache,
}
impl<'a> RNN<'a> {
pub fn forward(&mut self, x: Arr2d, h_prev: Arr2d) -> Arr2d {
let t = h_prev.dot(&*self.wh.p()) + x.dot(&*self.wx.p()) + &*self.b.p();
let h_next = t.mapv(f32::tanh);
self.cache = Cache {
x,
h_prev,
h_next: h_next.clone(),
};
h_next
}
/// dx: (b, c)とdh_prev: (b, h)を返す
pub fn backward(&mut self, dh_next: Arr2d) -> (Arr2d, Arr2d) {
let dt = dh_next * self.cache.h_next.mapv(|y| 1.0 - y * y);
let dh_prev = dt.dot(&self.wh.p().t());
let dx = dt.dot(&self.wx.p().t());
self.b.store(dt.sum_axis(Axis(0)));
self.wh.store(self.cache.h_prev.t().dot(&dt));
self.wx.store(self.cache.x.t().dot(&dt));
(dx, dh_prev)
}
}
/// (b,c)の外部入力と、(b,h)の内部相互入力を受け、(b,h)を出力する
/// time_sizeはlayerの数
pub struct TimeRNN<'a> {
h: Arr2d,
dh: Arr2d,
stateful: bool,
time_size: usize,
channel_size: usize,
hidden_size: usize,
layers: Vec<RNN<'a>>,
}
impl<'a> TimeRNN<'a> {
pub fn new(wx: &'a P1<Arr2d>, wh: &'a P1<Arr2d>, b: &'a P1<Arr1d>, time_size: usize) -> Self {
let (channel_size, hidden_size) = wx.p().dim();
let layers: Vec<_> = (0..time_size)
.map(|_| RNN {
wx: wx,
wh: wh,
b: b,
cache: Default::default(),
})
.collect();
Self {
layers,
h: Default::default(),
dh: Default::default(),
time_size,
channel_size,
hidden_size,
stateful: true,
}
}
pub fn forward(&mut self, xs: Arr3d) -> Arr3d {
let batch_size = xs.dim().0;
let mut hs = Arr3d::zeros((batch_size, self.time_size, self.hidden_size));
if !self.stateful || self.h.len() == 0 {
self.h = Arr2d::zeros((batch_size, self.hidden_size));
}
for (t, layer) in self.layers.iter_mut().enumerate() {
self.h = layer.forward(xs.index_axis(Axis(1), t).to_owned(), self.h.clone());
hs.index_axis_mut(Axis(1), t).assign(&self.h);
}
hs
}
pub fn backward<D: Dimension>(&mut self, dhs: Array<f32, D>) -> Arr3d {
let batch_size = dhs.len() / (self.time_size * self.hidden_size);
let dhs = dhs
.into_shape((batch_size, self.time_size, self.hidden_size))
.unwrap();
let mut dxs = Arr3d::zeros((batch_size, self.time_size, self.channel_size));
/// 一番端っこのRNNではhはゼロ?
let mut dh = Arr2d::zeros((batch_size, self.hidden_size));
for (t, layer) in self.layers.iter_mut().enumerate().rev() {
let (_dx, _dh) = layer.backward(dhs.index_axis(Axis(1), t).to_owned() + dh);
dh = _dh;
dxs.index_axis_mut(Axis(1), t).assign(&_dx);
}
self.dh = dh;
dxs
}
pub fn set_state(&mut self, h: Arr2d) {
self.h = h;
}
pub fn reset_state(&mut self) {
self.h = Default::default();
}
}
pub struct TimeEmbedding<'a> {
w: &'a Param<Arr2d>, // <- グローバルパラメータ(更新、学習が必要なもの)
idx: Array2<usize>, // <- ローカルパラメータ(直接保持する)
}
impl<'a> TimeEmbedding<'a> {
pub fn new(w: &'a Param<Arr2d>) -> Self {
Self {
w,
idx: Default::default(),
}
}
pub fn forward(&mut self, idx: Array2<usize>) -> Arr3d {
let (batch_size, time_size) = idx.dim();
let channel_num = self.w.p().dim().1;
let mut out: Arr3d = Array3::zeros((batch_size, time_size, channel_num));
for (mut _o, _x) in out.outer_iter_mut().zip(idx.outer_iter()) {
_o.assign(&pickup1(&self.w.p(), Axis(0), _x));
}
self.idx = idx;
out
}
pub fn backward(&mut self, dout: Arr3d) {
let mut dw = Array2::zeros(self.w.p().dim());
// バッチ方向に回す
for (_o, _x) in dout.outer_iter().zip(self.idx.outer_iter()) {
for (__o, __x) in _o.outer_iter().zip(_x.iter()) {
let mut row = dw.index_axis_mut(Axis(0), *__x);
row += &__o;
}
}
self.w.store(dw);
}
}
pub struct TimeAffine<'a> {
w: &'a Param<Arr2d>,
b: &'a P1<Arr1d>,
x: Arr2d,
}
impl<'a> TimeAffine<'a> {
pub fn new(w: &'a Param<Arr2d>, b: &'a P1<Arr1d>) -> Self {
Self {
w,
b,
x: Default::default(),
}
}
pub fn forward(&mut self, x: Arr2d) -> Arr2d {
self.x = x;
// dot(&self.x, &self.w.p) + &self.b.p
self.x.dot(&*self.w.p()) + &*self.b.p()
}
pub fn backward(&mut self, dout: Arr2d) -> Arr2d {
// let (b, t, c_out) = dout.dim(); // batch, time, channel
// let c_in = self.x.dim().2;
// let dout = dout.into_shape((b * t, c_out)).unwrap();
// let rx = self
// .x
// .clone()
// .into_shape((b * t, c_in))
// .expect("self.x and dout must have same dimention!");
self.b.store(dout.sum_axis(Axis(0)));
self.w.store(self.x.t().dot(&dout));
dout.dot(&self.w.p().t())
}
}
/// SoftMaxWithLossと全く同じになりそうなので、とりあえずはあとで
pub struct TimeSoftmaxWithLoss {
pred: Arr2d,
target: Array1<usize>,
}
impl TimeSoftmaxWithLoss {
fn forward(&mut self, xs: Arr2d, ts: Array1<usize>) -> f32 {
self.pred = softmax(xs);
self.target = ts;
// 本ではもう少しごちゃごちゃやっているmaskがなんとか
cross_entropy_error_target(&self.pred, &self.target)
}
fn backward(&mut self) -> Arr2d {
unimplemented!();
}
}
#[derive(Default, Clone)]
struct CacheLSTM {
x: Arr2d,
h_prev: Arr2d,
c_prev: Arr2d,
i: Arr2d,
f: Arr2d,
g: Arr2d,
o: Arr2d,
c_next: Arr2d,
}
struct LSTM<'a> {
/// (channel, 4*hidden)
wx: &'a P1<Arr2d>,
/// (hidden, 4*hidden)
wh: &'a P1<Arr2d>,
/// (4*hidden, )
b: &'a P1<Arr1d>,
cache: CacheLSTM,
}
impl<'a> LSTM<'a> {
/// x: (batch, channel), h_prev: (batch, hidden), c_prev: (batch, hidden)
pub fn forward(&mut self, x: Arr2d, h_prev: Arr2d, c_prev: Arr2d) -> (Arr2d, Arr2d) {
let (batch_size, hidden_size) = h_prev.dim();
// (batch, 4*hidden)
let a = x.dot(&*self.wx.p()) + h_prev.dot(&*self.wh.p()) + &*self.b.p();
let mut chunks = a.axis_chunks_iter(Axis(1), hidden_size);
let mut yielder = |f: fn(f32) -> f32| chunks.next().unwrap().mapv(f);
// それぞれ (batch, hidden)
let sigmoid = |x: f32| 1.0 / (1.0 + (-x).exp());
let f = yielder(sigmoid); // forget
let g = yielder(f32::tanh); // gain new info
let i = yielder(sigmoid); // input
let o = yielder(sigmoid); // output
let c_next = &f * &c_prev + &g * &i; // c_prevを割合fで忘却し、gを割合iで追加する
let h_next = &o * &c_next.mapv(f32::tanh); // c_nextをtanhして、割合oで出力する
self.cache = CacheLSTM {
x,
h_prev,
c_prev,
i,
f,
g,
o,
c_next: c_next.clone(),
};
(h_next, c_next)
}
/// dh: (batch, hidden), dc: (battch, hidden)
/// 返り値は(dx, dh_prev, dc_prev)
pub fn backward(&mut self, dh_next: Arr2d, dc_next: Arr2d) -> (Arr2d, Arr2d, Arr2d) {
let cache = self.cache.clone();
let c_next_tanh = cache.c_next.mapv(f32::tanh); // すでにforwardで行った計算だが、cacheしてないので、復活させる
let ds = dc_next + &dh_next * &cache.o * c_next_tanh.dtanh();
let dc_prev = &ds * &cache.f;
// dAを準備
let (batch_size, hidden_size) = dh_next.dim();
let mut dA = Arr2d::zeros((batch_size, hidden_size * 4));
let mut chunk = dA.axis_chunks_iter_mut(Axis(1), hidden_size);
let mut assign = |d| chunk.next().unwrap().assign(&d);
// df, dg, di, doの順に格納していく
assign(&ds * &cache.c_prev * cache.f.dsigmoid());
assign(&ds * &cache.i * cache.g.dtanh());
assign(&ds * &cache.g * cache.i.dsigmoid());
assign(&dh_next * &c_next_tanh * cache.o.dsigmoid());
// dAから、wh, wx, bの勾配を計算し格納
self.wh.store(cache.h_prev.t().dot(&dA));
self.wx.store(cache.x.t().dot(&dA));
self.b.store(dA.sum_axis(Axis(0))); // <= batch方向に潰す
let dx = dA.dot(&self.wx.p().t());
let dh_prev = dA.dot(&self.wh.p().t());
(dx, dh_prev, dc_prev)
}
}
pub struct TimeLSTM<'a> {
h: Arr2d, // 順伝播の時は、前回のhを用いる
c: Arr2d, // 同様にcも用いる
/// dxとは別で、内部LSTMの相互入出力によるもの!
pub dh: Arr2d, // 誤差逆伝播では基本的に勾配を渡すことはない(したがって1回のbackward関数内で保持すれば良い)のだが、encoder-decoderの時は、decoderからencoderに渡す必要がある。
stateful: bool, // 前回のhを保持するかどうか
pub time_size: usize,
channel_size: usize,
hidden_size: usize,
layers: Vec<LSTM<'a>>,
}
impl<'a> TimeLSTM<'a> {
pub fn new(
wx: &'a P1<Arr2d>,
wh: &'a P1<Arr2d>,
b: &'a P1<Arr1d>,
time_size: usize,
stateful: bool,
) -> Self {
let (channel_size, mut hidden_size) = wx.p().dim();
hidden_size /= 4; // wxは(channel, 4*hidden)
let layers: Vec<_> = (0..time_size)
.map(|_| LSTM {
wx: wx,
wh: wh,
b: b,
cache: Default::default(),
})
.collect();
Self {
layers,
h: Default::default(),
c: Default::default(),
dh: Default::default(),
time_size,
channel_size,
hidden_size,
stateful,
}
}
pub fn forward(&mut self, xs: Arr3d) -> Arr3d {
let batch_size = xs.dim().0;
let mut hs = Arr3d::zeros((batch_size, self.time_size, self.hidden_size));
// 前回のhを保持しない設定、またはそもそも持っていな時
// h, c共に初期化する
if !self.stateful || self.h.len() == 0 {
self.h = Arr2d::zeros((batch_size, self.hidden_size));
}
if !self.stateful || self.c.len() == 0 {
self.c = Arr2d::zeros((batch_size, self.hidden_size));
}
for (layer, xst, mut hst) in izip!(
self.layers.iter_mut(),
xs.axis_iter(Axis(1)),
hs.axis_iter_mut(Axis(1))
) {
let (_h, _c) = layer.forward(xst.to_owned(), self.h.clone(), self.c.clone());
hst.assign(&_h);
self.h = _h;
self.c = _c;
}
hs
}
/// xs: (batch=1, time=1, hidden) -> (batch=1, hidden)
pub fn forward_piece(&mut self, xs: Arr2d) -> Arr2d {
// time_size = 1で進める
// 事前にself.hをセットしておく(self.set_state)
let batch_size = xs.dim().0;
// let mut hs = Arr2d::zeros((batch_size, self.hidden_size));
assert_eq!(
batch_size,
self.h.dim().0,
"you have to set the right state h"
);
if !self.stateful || self.h.len() == 0 {
self.h = Arr2d::zeros((batch_size, self.hidden_size));
}
if !self.stateful || self.c.len() == 0 {
self.c = Arr2d::zeros((batch_size, self.hidden_size));
}
let (_h, _c) = self.layers[0].forward(xs, self.h.clone(), self.c.clone());
// hs.assign(&_h);
self.h = _h;
self.c = _c;
self.h.clone()
}
pub fn backward(&mut self, dhs: Arr3d) -> Arr3d {
let batch_size = dhs.len() / (self.time_size * self.hidden_size);
let mut dxs = Arr3d::zeros((batch_size, self.time_size, self.channel_size));
/// 誤差逆伝播については、dh, dcはゼロから始める
/// 順伝播についてはstateful=trueの場合は一つ前のiter(その場合は自分で保存)や隣のencoderから受け取って初期化していた
let mut dh = Arr2d::zeros((batch_size, self.hidden_size));
let mut dc = dh.clone();
for (layer, mut dxt, dht) in (izip!(
self.layers.iter_mut(),
dxs.axis_iter_mut(Axis(1)),
dhs.axis_iter(Axis(1))
))
.rev()
{
/// 上流からのdhtと、横からのdh(先頭ではゼロ)を加算する
let (_dx, _dh, _dc) = layer.backward(dht.to_owned() + dh, dc);
dh = _dh;
dc = _dc;
dxt.assign(&_dx);
}
self.dh = dh;
dxs
}
/// (batch*time, hidden) -> (batch, time, hidden)
pub fn conv_2d_3d(&self, x: Arr2d) -> Arr3d {
let (batch_time, hidden_size) = x.dim();
let batch_size = batch_time / self.time_size;
x.into_shape((batch_size, self.time_size, hidden_size))
.unwrap()
}
pub fn reset_state(&mut self) {
self.h = Default::default();
self.c = Default::default();
}
pub fn set_state(&mut self, h: Option<Arr2d>, c: Option<Arr2d>) {
self.h = h.unwrap_or_default();
self.c = c.unwrap_or_default();
}
}
#[derive(Default)]
/// パラメタ持たない。
pub struct TimeAttention {
softmax: SoftMaxD<Ix3>,
/// swapaxis: (false, false)と、swapaxis: (false, true)
matmul: [MatMul3D; 2],
/// (batch, dec_t, enc_t)
attention: Arr3d,
}
impl TimeAttention {
pub fn new() -> Self {
Self {
matmul: [Default::default(), MatMul3D::new(false, true)],
..Default::default()
}
}
/// 入力 : (batch, enct, hidden), (batch, dect, hidden)
pub fn forward(&mut self, enc_hs: Arr3d, dec_hs: Arr3d) -> Arr3d {
// (batch, dect, hidden)@(batch, enct, hidden) -> (batch, dect, enct)
// dec_hsはここで消費される。つまり、dec_hsはattentionを作ることにしか使われないのだが、そんなもんかな
let mut attention = self.matmul[0].forward((dec_hs, enc_hs.clone()));
// いわゆるAttention (SoftMaxに入れることで0~1に正規化される。)
attention = self.softmax.forward(attention);
// (batch, dect, enct)@(batch, enct, hidden; swap) -> (batch, dect, hidden)
self.matmul[1].forward((attention, enc_hs))
}
/// generateの際にattentionを保存したい場合は、attention_idx = Some(decoder time 方向のインデックス)とする
pub fn forward_piece(
&mut self,
enc_hs: Arr3d,
dec_h: Arr2d,
attention_idx: Option<usize>,
) -> Arr2d {
let (batch_size, enc_t, hidden_size) = enc_hs.dim();
// const dec_t = 1
// (batch, hidden) @ (batch, enct, hidden) -> (batch, enct)
let mut out = Arr2d::from_shape_fn((batch_size, enc_t), |(b, e)| {
dec_h.slice(s![b, ..]).dot(&enc_hs.slice(s![b, e, ..]))
});
// いわゆるAttention (SoftMaxに入れることで0~1に正規化される。)
out = softmax(out);
// attentionがない場合は事前に作っておく必要がある
if self.attention.len() != 0 {
attention_idx.map(|i| self.attention.slice_mut(s![0..1, i, ..]).assign(&out));
}
// (batch, enct) @ (batch, enct, hidden) -> (batch, hidden)
// enc_hsをattentionで重み付けする。
Arr2d::from_shape_fn((batch_size, hidden_size), |(b, h)| {
out.slice(s![b, ..]).dot(&enc_hs.slice(s![b, .., h]))
})
}
/// dhs -> denc_hs, dout
pub fn backward(&mut self, mut dhs: Arr3d) -> (Arr3d, Arr3d) {
let (dattention, dhs_enc1) = self.matmul[1].backward(dhs);
let dhs_dec = self.softmax.backward(dattention);
let (dout, dhs_enc2) = self.matmul[0].backward(dhs_dec);
(dhs_enc1 + dhs_enc2, dout)
}
pub fn get_attention(&self) -> Arr2d {
self.attention.slice(s![0, .., ..]).to_owned()
}
pub fn set_attention_box(&mut self, enc_t: usize, dec_t: usize) {
self.attention = Arr3d::zeros((1, dec_t, enc_t));
}
}
|
//! This crate was inspired by Python's input function. It allows easy reading of data from the terminal.
//!
//! A simple example of its use is:
//! ```
//! extern crate reader;
//! use reader::input;
//!
//! let name = input("Enter your name: ");
//! println!("Your name is: {}", name);
//! ```
use std::io::Write;
use std::num::{ParseIntError, ParseFloatError};
/// Read a String.
///
/// This function works in a similar way to the python "input" function,
/// that receives as an argument a sentence that will be displayed on the screen
/// and returns a String.
///
/// # Examples
///
/// Basic usage
/// ```
/// extern crate reader;
/// use reader::input;
///
/// let name = input("Enter your name: ");
/// println!("Your name is: {}", name);
/// ```
pub fn input(text: &'static str) -> String {
let mut string = String::new();
print!("{}", text);
std::io::stdout().flush().unwrap();
std::io::stdin()
.read_line(&mut string)
.expect("Failed to read line");
string.truncate(string.len() - 1); // Removes the '\n', important to avoid line skipping.
return string;
}
/// Convert a String to integer (i64)
///
/// # Examples
///
/// Basic usage
/// ```
/// extern crate reader;
/// use reader::{input, int};
///
/// Reading a integer (i64)
///
/// let age = int(input("Enter your age: ")).unwrap();
/// println!("Your age is: {}", age);
///
/// Reading a integer (i32)
///
/// let age = int(input("Enter your age: ")).unwrap() as i32;
/// println!("Your age is: {}", age);
///
/// Reading a integer (i16)
///
/// let age = int(input("Enter your age: ")).unwrap() as i16;
/// println!("Your age is: {}", age);
///
/// Reading a integer (i8)
///
/// let age = int(input("Enter your age: ")).unwrap() as i8;
/// println!("Your age is: {}", age);
/// ```
pub fn int(string: String) -> Result<i64, ParseIntError> {
return match string.trim().parse::<i64>() {
Ok(integer) => Ok(integer),
Err(e) => Err(e)
}
}
/// Convert a String to float (f64)
///
/// # Examples
///
/// Basic usage
/// ```
/// extern crate reader;
/// use reader::{input, float};
///
/// Reading a float (f64)
///
/// let salary = float(input("Enter your salary: ")).unwrap();
/// println!("Your salary is: {}", salary);
///
/// Reading a float (f32)
///
/// let salary = float(input("Enter your salary: ")).unwrap() as f32;
/// println!("Your salary is: {}", salary);
/// ```
pub fn float(string: String) -> Result<f64, ParseFloatError> {
return match string.trim().parse::<f64>() {
Ok(float) => Ok(float),
Err(e) => Err(e)
}
}
|
use crate::{DomainId, OperatorId, OperatorPublicKey, StakeWeight};
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_core::crypto::{VrfPublic, Wraps};
use sp_core::sr25519::vrf::{VrfOutput, VrfSignature, VrfTranscript};
use sp_std::vec::Vec;
use subspace_core_primitives::Blake2b256Hash;
const VRF_TRANSCRIPT_LABEL: &[u8] = b"bundle_producer_election";
/// Generates a domain-specific vrf transcript from given global_challenge.
pub fn make_transcript(domain_id: DomainId, global_challenge: &Blake2b256Hash) -> VrfTranscript {
VrfTranscript::new(
VRF_TRANSCRIPT_LABEL,
&[
(b"domain", &domain_id.to_le_bytes()),
(b"global_challenge", global_challenge.as_ref()),
],
)
}
/// Returns the election threshold based on the operator stake proportion and slot probability.
pub fn calculate_threshold(
operator_stake: StakeWeight,
total_domain_stake: StakeWeight,
bundle_slot_probability: (u64, u64),
) -> u128 {
// The calculation is written for not causing the overflow, which might be harder to
// understand, the formula in a readable form is as followes:
//
// bundle_slot_probability.0 operator_stake
// threshold = ------------------------- * --------------------- * u128::MAX
// bundle_slot_probability.1 total_domain_stake
//
// TODO: better to have more audits on this calculation.
u128::MAX / u128::from(bundle_slot_probability.1) * u128::from(bundle_slot_probability.0)
/ total_domain_stake
* operator_stake
}
pub fn is_below_threshold(vrf_output: &VrfOutput, threshold: u128) -> bool {
let vrf_output = u128::from_le_bytes(
vrf_output
.0
.to_bytes()
.split_at(core::mem::size_of::<u128>())
.0
.try_into()
.expect("Slice splitted from VrfOutput must fit into u128; qed"),
);
vrf_output < threshold
}
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct BundleProducerElectionParams<Balance> {
pub current_operators: Vec<OperatorId>,
pub total_domain_stake: Balance,
pub bundle_slot_probability: (u64, u64),
}
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub enum VrfProofError {
/// Invalid vrf proof.
BadProof,
}
/// Verify the vrf proof generated in the bundle election.
pub(crate) fn verify_vrf_signature(
domain_id: DomainId,
public_key: &OperatorPublicKey,
vrf_signature: &VrfSignature,
global_challenge: &Blake2b256Hash,
) -> Result<(), VrfProofError> {
if !public_key.as_inner_ref().vrf_verify(
&make_transcript(domain_id, global_challenge).into(),
vrf_signature,
) {
return Err(VrfProofError::BadProof);
}
Ok(())
}
|
use std::{error, io, io::Write, path::Path, process};
pub fn run(args: &str) -> Result<(String, String, process::ExitStatus), Box<dyn error::Error>> {
let output = fake_tty::bash_command(&format!("{}; echo \"\n$PWD\"", args)).output()?;
let stdout = String::from_utf8(output.stdout)?;
let stderr = String::from_utf8(output.stderr)?;
let status = output.status;
let stdout = stdout.trim_end();
let lb = stdout.rfind(|c| matches!(c, '\n' | '\r')).unwrap();
let (mut output, cwd) = stdout.split_at(lb);
let cwd = cwd.trim_start();
if !cmp_paths(std::env::current_dir()?, cwd) {
std::env::set_current_dir(cwd)?;
}
if output.ends_with('\r') {
output = &output[..output.len() - 1];
}
Ok((output.to_string(), stderr, status))
}
fn cmp_paths(p1: impl AsRef<Path>, p2: impl AsRef<Path>) -> bool {
p1.as_ref() == p2.as_ref()
}
pub fn input(mut child: process::Child, input: impl AsRef<str>) -> io::Result<process::Child> {
child
.stdin
.as_mut()
.unwrap()
.write_all(input.as_ref().as_bytes())?;
Ok(child)
}
|
pub enum ArchKeyboardAction
{
ArchKeyDown(u8),
ArchKeyUp(u8)
}
pub fn get_key() -> ArchKeyboardAction
{
let raw = unsafe { ::platform::io::inport(0x60) };
let key = raw & 0x7F;
match raw & 0x80
{
0 => ArchKeyDown(key),
_ => ArchKeyUp(key),
}
}
|
// Copyright 2020 The MWC Developers
//
// 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 super::types::{Address, Publisher, Subscriber, SubscriptionHandler};
use crate::adapters::types::MWCMQSAddress;
use crate::error::{Error, ErrorKind};
use crate::libwallet::proof::crypto;
use crate::libwallet::proof::crypto::Hex;
use crate::util::Mutex;
use crate::core::core::amount_to_hr_string;
use crate::util::RwLock;
use crate::SlateSender;
use crate::SwapMessageSender;
use ed25519_dalek::{PublicKey as DalekPublicKey, SecretKey as DalekSecretKey};
use grin_wallet_libwallet::proof::message::EncryptedMessage;
use grin_wallet_libwallet::proof::proofaddress::ProvableAddress;
use grin_wallet_libwallet::proof::tx_proof::{push_proof_for_slate, TxProof};
use grin_wallet_libwallet::slatepack::SlatePurpose;
use grin_wallet_libwallet::swap::message::Message;
use grin_wallet_libwallet::swap::message::SwapMessage;
use grin_wallet_libwallet::{Slate, SlateVersion, VersionedSlate};
use grin_wallet_util::grin_util::secp::key::SecretKey;
use regex::Regex;
use std::collections::HashMap;
use std::io::Read;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::time::Duration;
use std::{thread, time};
extern crate nanoid;
const TIMEOUT_ERROR_REGEX: &str = r"timed out";
// MQS enforced to have a single instance. And different compoments migth manage
// instances separatlly.
// Also all dependent components want to use MQS and they need interface.
// Since instance is single, interface will be global
lazy_static! {
static ref MWCMQS_BROKER: RwLock<Option<(MWCMQPublisher, MWCMQSubscriber)>> = RwLock::new(None);
}
/// Init mwc mqs objects for the access.
pub fn init_mwcmqs_access_data(publisher: MWCMQPublisher, subscriber: MWCMQSubscriber) {
MWCMQS_BROKER.write().replace((publisher, subscriber));
}
/// Init mwc mqs objects for the access.
pub fn get_mwcmqs_brocker() -> Option<(MWCMQPublisher, MWCMQSubscriber)> {
MWCMQS_BROKER.read().clone()
}
/// Reset Broker (listener is stopped)
pub fn reset_mwcmqs_brocker() {
MWCMQS_BROKER.write().take();
}
pub struct MwcMqsChannel {
des_address: String,
}
impl MwcMqsChannel {
pub fn new(des_address: String) -> Self {
Self {
des_address: des_address,
}
}
fn send_tx_to_mqs(
&self,
slate: &Slate,
mwcmqs_publisher: MWCMQPublisher,
rx_slate: Receiver<Slate>,
) -> Result<Slate, Error> {
let des_address = MWCMQSAddress::from_str(self.des_address.as_ref()).map_err(|e| {
ErrorKind::MqsGenericError(format!("Invalid destination address, {}", e))
})?;
mwcmqs_publisher
.post_slate(&slate, &des_address)
.map_err(|e| {
ErrorKind::MqsGenericError(format!(
"MQS unable to transfer slate {} to the worker, {}",
slate.id, e
))
})?;
println!(
"slate [{}] for [{}] MWCs sent to [{}]",
slate.id.to_string(),
amount_to_hr_string(slate.amount, false),
des_address,
);
//expect to get slate back.
let slate_returned = rx_slate
.recv_timeout(Duration::from_secs(120))
.map_err(|e| {
ErrorKind::MqsGenericError(format!(
"MQS unable to process slate {}, {}",
slate.id, e
))
})?;
return Ok(slate_returned);
}
fn send_swap_to_mqs(
&self,
swap_message: &Message,
mwcmqs_publisher: MWCMQPublisher,
_rs_message: Receiver<Message>,
) -> Result<(), Error> {
let des_address = MWCMQSAddress::from_str(self.des_address.as_ref()).map_err(|e| {
ErrorKind::MqsGenericError(format!("Invalid destination address, {}", e))
})?;
mwcmqs_publisher
.post_take(swap_message, &des_address)
.map_err(|e| {
ErrorKind::MqsGenericError(format!(
"MQS unable to transfer swap message {} to the worker, {}",
swap_message.id, e
))
})?;
Ok(())
}
}
impl SlateSender for MwcMqsChannel {
fn check_other_wallet_version(
&self,
_destination_address: &String,
) -> Result<Option<(SlateVersion, Option<String>)>, Error> {
Ok(None)
}
// MQS doesn't do encryption because of backward compability. In any case it is not critical, the whole slate is encrypted and the size of slate is not important
fn send_tx(
&self,
slate: &Slate,
_slate_content: SlatePurpose,
_slatepack_secret: &DalekSecretKey,
_recipients: Option<DalekPublicKey>,
_other_wallet_version: Option<(SlateVersion, Option<String>)>,
) -> Result<Slate, Error> {
if let Some((mwcmqs_publisher, mwcmqs_subscriber)) = get_mwcmqs_brocker() {
// Creating channels for notification
let (tx_slate, rx_slate) = channel(); //this chaneel is used for listener thread to send message to other thread
mwcmqs_subscriber.set_notification_channels(&slate.id, tx_slate);
let res = self.send_tx_to_mqs(slate, mwcmqs_publisher, rx_slate);
mwcmqs_subscriber.reset_notification_channels(&slate.id);
res
} else {
return Err(ErrorKind::MqsGenericError(format!(
"MQS is not started, not able to send the slate {}",
slate.id
))
.into());
}
}
}
impl SwapMessageSender for MwcMqsChannel {
/// Send a swap message. Return true is message delivery acknowledge can be set (message was delivered and procesed)
fn send_swap_message(&self, message: &Message) -> Result<bool, Error> {
if let Some((mwcmqs_publisher, _mwcmqs_subscriber)) = get_mwcmqs_brocker() {
let (_ts_message, rs_message) = channel();
self.send_swap_to_mqs(message, mwcmqs_publisher, rs_message)?;
// MQS is async protocol, message might never be delivered, so no ack can be granted.
Ok(false)
} else {
return Err(ErrorKind::MqsGenericError(format!(
"MQS is not started, not able to send the swap message {}",
message.id
))
.into());
}
}
}
#[derive(Clone)]
pub struct MWCMQPublisher {
address: MWCMQSAddress,
broker: MWCMQSBroker,
secret_key: SecretKey,
}
impl MWCMQPublisher {
// Note, Publisher must initialize controller with self
pub fn new(
address: MWCMQSAddress,
secret_key: &SecretKey,
mwcmqs_domain: String,
mwcmqs_port: u16,
print_to_log: bool,
handler: Box<dyn SubscriptionHandler + Send>,
) -> Self {
Self {
address,
broker: MWCMQSBroker::new(mwcmqs_domain, mwcmqs_port, print_to_log, handler),
secret_key: secret_key.clone(),
}
}
}
impl Publisher for MWCMQPublisher {
fn post_slate(&self, slate: &Slate, to: &dyn Address) -> Result<(), Error> {
let to_address_raw = format!("mwcmqs://{}", to.get_stripped());
let to_address = MWCMQSAddress::from_str(&to_address_raw)?;
self.broker
.post_slate(slate, &to_address, &self.address, &self.secret_key)?;
Ok(())
}
fn encrypt_slate(&self, slate: &Slate, to: &dyn Address) -> Result<String, Error> {
let to_address_raw = format!("mwcmqs://{}", to.get_stripped());
let to_address = MWCMQSAddress::from_str(&to_address_raw)?;
self.broker
.encrypt_slate(slate, &to_address, &self.address, &self.secret_key)
}
fn decrypt_slate(
&self,
from: String,
mapmessage: String,
signature: String,
source_address: &ProvableAddress,
) -> Result<String, Error> {
let r1 = str::replace(&mapmessage, "%22", "\"");
let r2 = str::replace(&r1, "%7B", "{");
let r3 = str::replace(&r2, "%7D", "}");
let r4 = str::replace(&r3, "%3A", ":");
let r5 = str::replace(&r4, "%2C", ",");
let r5 = r5.trim().to_string();
let from = MWCMQSAddress::from_str(&from)?;
let (slate, _tx_proof) = TxProof::from_response(
&from.address,
r5.clone(),
"".to_string(),
signature.clone(),
&self.secret_key,
&source_address,
)
.map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable to build txproof from the payload, {}", e))
})?;
let slate = serde_json::to_string(&slate).map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable convert Slate to Json, {}", e))
})?;
Ok(slate)
}
fn post_take(&self, message: &Message, to: &dyn Address) -> Result<(), Error> {
let to_address_raw = format!("mwcmqs://{}", to.get_stripped());
let to_address = MWCMQSAddress::from_str(&to_address_raw)?;
self.broker
.post_take(message, &to_address, &self.address, &self.secret_key)?;
Ok(())
}
// Address of this publisher (from address)
fn get_publisher_address(&self) -> Result<Box<dyn Address>, Error> {
Ok(Box::new(self.address.clone()))
}
}
#[derive(Clone)]
pub struct MWCMQSubscriber {
address: MWCMQSAddress,
broker: MWCMQSBroker,
secret_key: SecretKey,
}
impl MWCMQSubscriber {
pub fn new(publisher: &MWCMQPublisher) -> Self {
Self {
address: publisher.address.clone(),
broker: publisher.broker.clone(),
secret_key: publisher.secret_key.clone(),
}
}
}
impl Subscriber for MWCMQSubscriber {
fn start(&mut self) -> Result<(), Error> {
self.broker
.subscribe(&self.address.address, &self.secret_key);
Ok(())
}
fn stop(&mut self) -> bool {
if let Ok(client) = reqwest::Client::builder()
.timeout(Duration::from_secs(60))
.build()
{
let mut params = HashMap::new();
params.insert("mapmessage", "nil");
let response = client
.post(&format!(
"https://{}:{}/sender?address={}",
self.broker.mwcmqs_domain,
self.broker.mwcmqs_port,
str::replace(&self.address.get_stripped(), "@", "%40")
))
.form(¶ms)
.send();
let response_status = response.is_ok();
self.broker.stop();
reset_mwcmqs_brocker();
response_status
} else {
error!("Unable to stop mwcmqs threads");
false
}
}
fn is_running(&self) -> bool {
self.broker.is_running()
}
fn set_notification_channels(&self, slate_id: &uuid::Uuid, slate_send_channel: Sender<Slate>) {
self.broker
.handler
.lock()
.set_notification_channels(slate_id, slate_send_channel);
}
fn reset_notification_channels(&self, slate_id: &uuid::Uuid) {
self.broker
.handler
.lock()
.reset_notification_channels(slate_id);
}
}
#[derive(Clone)]
struct MWCMQSBroker {
running: Arc<AtomicBool>,
pub mwcmqs_domain: String,
pub mwcmqs_port: u16,
pub print_to_log: bool,
pub handler: Arc<Mutex<Box<dyn SubscriptionHandler + Send>>>,
}
impl MWCMQSBroker {
fn new(
mwcmqs_domain: String,
mwcmqs_port: u16,
print_to_log: bool,
handler: Box<dyn SubscriptionHandler + Send>,
) -> Self {
Self {
running: Arc::new(AtomicBool::new(false)),
mwcmqs_domain,
mwcmqs_port,
print_to_log,
handler: Arc::new(Mutex::new(handler)),
}
}
fn encrypt_slate(
&self,
slate: &Slate,
to: &MWCMQSAddress,
from: &MWCMQSAddress,
secret_key: &SecretKey,
) -> Result<String, Error> {
let pkey = to.address.public_key()?;
let skey = secret_key.clone();
let version = slate.lowest_version();
let slate = VersionedSlate::into_version_plain(slate.clone(), version)?;
let serde_json = serde_json::to_string(&slate).map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable convert Slate to Json, {}", e))
})?;
let message = EncryptedMessage::new(serde_json, &to.address, &pkey, &skey)
.map_err(|e| ErrorKind::GenericError(format!("Unable encrypt slate, {}", e)))?;
let message_ser = &serde_json::to_string(&message).map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable convert Message to Json, {}", e))
})?;
let mut challenge = String::new();
challenge.push_str(&message_ser);
let signature = crypto::sign_challenge(&challenge, secret_key)?;
let signature = signature.to_hex();
let mser: &str = &message_ser;
let mser: &str = &str::replace(mser, "{", "%7B");
let mser: &str = &str::replace(mser, "}", "%7D");
let mser: &str = &str::replace(mser, ":", "%3A");
let mser: &str = &str::replace(mser, ",", "%2C");
let mser: &str = &str::replace(mser, "\"", "%22");
let mser: &str = &mser.trim().to_string();
let fromstripped = from.get_stripped();
Ok(format!(
"mapmessage={}&from={}&signature={}",
mser, &fromstripped, &signature
))
}
fn post_slate(
&self,
slate: &Slate,
to: &MWCMQSAddress,
from: &MWCMQSAddress,
secret_key: &SecretKey,
) -> Result<(), Error> {
if !self.is_running() {
return Err(ErrorKind::ClosedListener("mwcmqs".to_string()).into());
}
let pkey = to.address.public_key()?;
let skey = secret_key.clone();
let version = slate.lowest_version();
let slate = VersionedSlate::into_version_plain(slate.clone(), version)?;
let message = EncryptedMessage::new(
serde_json::to_string(&slate).map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable convert Slate to Json, {}", e))
})?,
&to.address,
&pkey,
&skey,
)
.map_err(|e| ErrorKind::GenericError(format!("Unable encrypt slate, {}", e)))?;
let message_ser = &serde_json::to_string(&message).map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable convert Message to Json, {}", e))
})?;
let mut challenge = String::new();
challenge.push_str(&message_ser);
let signature = crypto::sign_challenge(&challenge, secret_key)?;
let signature = signature.to_hex();
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(120))
.build()
.map_err(|e| ErrorKind::GenericError(format!("Failed to build a client, {}", e)))?;
let mser: &str = &message_ser;
let fromstripped = from.get_stripped();
let mut params = HashMap::new();
params.insert("mapmessage", mser);
params.insert("from", &fromstripped);
params.insert("signature", &signature);
let url = format!(
"https://{}:{}/sender?address={}",
self.mwcmqs_domain,
self.mwcmqs_port,
&str::replace(&to.get_stripped(), "@", "%40")
);
let response = client.post(&url).form(¶ms).send();
if !response.is_ok() {
return Err(ErrorKind::MqsInvalidRespose("mwcmqs connection error".to_string()).into());
} else {
let mut response = response.unwrap();
let mut resp_str = "".to_string();
let read_resp = response.read_to_string(&mut resp_str);
if !read_resp.is_ok() {
return Err(ErrorKind::MqsInvalidRespose("mwcmqs i/o error".to_string()).into());
} else {
let data: Vec<&str> = resp_str.split(" ").collect();
if data.len() <= 1 {
return Err(ErrorKind::MqsInvalidRespose("mwcmqs".to_string()).into());
} else {
let last_seen = data[1].parse::<i64>();
if !last_seen.is_ok() {
return Err(ErrorKind::MqsInvalidRespose("mwcmqs".to_string()).into());
} else {
let last_seen = last_seen.unwrap();
if last_seen > 10000000000 {
self.do_log_warn(format!("\nWARNING: [{}] has not been connected to mwcmqs recently. This user might not receive the slate.",
to.get_stripped()));
} else if last_seen > 150000 {
let seconds = last_seen / 1000;
self.do_log_warn(format!("\nWARNING: [{}] has not been connected to mwcmqs for {} seconds. This user might not receive the slate.",
to.get_stripped(), seconds));
}
}
}
}
}
Ok(())
}
fn post_take(
&self,
swapmessage: &Message,
to: &MWCMQSAddress,
from: &MWCMQSAddress,
secret_key: &SecretKey,
) -> Result<(), Error> {
if !self.is_running() {
return Err(ErrorKind::ClosedListener("mwcmqs".to_string()).into());
}
let pkey = to.address.public_key()?;
let skey = secret_key.clone();
let message = EncryptedMessage::new(
serde_json::to_string(&swapmessage).map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable convert Slate to Json, {}", e))
})?,
&to.address,
&pkey,
&skey,
)
.map_err(|e| ErrorKind::GenericError(format!("Unable encrypt slate, {}", e)))?;
let message_ser = &serde_json::to_string(&message).map_err(|e| {
ErrorKind::MqsGenericError(format!("Unable to convert Swap Message to Json, {}", e))
})?;
let mut challenge = String::new();
challenge.push_str(&message_ser);
let signature = crypto::sign_challenge(&challenge, secret_key);
let signature = signature.unwrap().to_hex();
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(60))
.build()
.map_err(|e| {
ErrorKind::GenericError(format!("Failed to build a client for post_take, {}", e))
})?;
let mser: &str = &message_ser;
let fromstripped = from.get_stripped();
let mut params = HashMap::new();
params.insert("swapmessage", mser);
params.insert("from", &fromstripped);
params.insert("signature", &signature);
let url = format!(
"https://{}:{}/sender?address={}",
self.mwcmqs_domain,
self.mwcmqs_port,
&str::replace(&to.get_stripped(), "@", "%40")
);
let response = client.post(&url).form(¶ms).send();
if !response.is_ok() {
return Err(ErrorKind::MqsInvalidRespose(format!(
"mwcmqs connection error, {:?}",
response
))
.into());
} else {
let mut response = response.unwrap();
let mut resp_str = "".to_string();
let read_resp = response.read_to_string(&mut resp_str);
if !read_resp.is_ok() {
return Err(ErrorKind::MqsInvalidRespose("mwcmqs i/o error".to_string()).into());
} else {
let data: Vec<&str> = resp_str.split(" ").collect();
if data.len() <= 1 {
return Err(ErrorKind::MqsInvalidRespose("mwcmqs".to_string()).into());
} else {
let last_seen = data[1].parse::<i64>();
if !last_seen.is_ok() {
return Err(ErrorKind::MqsInvalidRespose("mwcmqs".to_string()).into());
} else {
let last_seen = last_seen.unwrap();
if last_seen > 10000000000 {
println!("\nWARNING: [{}] has not been connected to mwcmqs recently. This user might not receive the swap message.",
to.get_stripped());
} else if last_seen > 150000 {
let seconds = last_seen / 1000;
println!("\nWARNING: [{}] has not been connected to mwcmqs for {} seconds. This user might not receive the swap message.",
to.get_stripped(), seconds);
}
}
}
}
}
Ok(())
}
fn print_error(&mut self, messages: Vec<&str>, error: &str, code: i16) {
self.do_log_error(format!(
"ERROR: messages=[{:?}] produced error: {} (code={})",
messages, error, code
));
}
fn do_log_info(&self, message: String) {
if self.print_to_log {
info!("{}", message);
} else {
println!("{}", message);
}
}
fn do_log_warn(&self, message: String) {
if self.print_to_log {
warn!("{}", message);
} else {
println!("{}", message);
}
}
fn do_log_error(&self, message: String) {
if self.print_to_log {
error!("{}", message);
} else {
println!("{}", message);
}
}
fn subscribe(&mut self, source_address: &ProvableAddress, secret_key: &SecretKey) -> () {
let address = MWCMQSAddress::new(
source_address.clone(),
Some(self.mwcmqs_domain.clone()),
Some(self.mwcmqs_port),
);
let nanoid = nanoid::simple();
self.running.store(true, Ordering::SeqCst);
let mut resp_str = "".to_string();
let secret_key = secret_key.clone();
let cloned_address = address.clone();
let cloned_running = self.running.clone();
let mut count = 0;
let mut connected = false;
let mut isnginxerror = false;
let mut delcount = 0;
let mut is_in_warning = false;
// get time from server
let mut time_now = "";
let mut is_error = false;
let secs = 30;
let cl = reqwest::Client::builder()
.timeout(Duration::from_secs(secs))
.build();
if cl.is_ok() {
let client = cl.unwrap();
let resp_result = client
.get(&format!(
"https://{}:{}/timenow?address={}",
self.mwcmqs_domain,
self.mwcmqs_port,
str::replace(&cloned_address.get_stripped(), "@", "%40"),
))
.send();
if !resp_result.is_ok() {
is_error = true;
} else {
let mut resp = resp_result.unwrap();
let read_resp = resp.read_to_string(&mut resp_str);
if !read_resp.is_ok() {
is_error = true;
} else {
time_now = &resp_str;
}
}
} else {
is_error = true;
}
let mut time_now_signature = String::new();
if let Ok(time_now_sign) = crypto::sign_challenge(&format!("{}", time_now), &secret_key) {
let time_now_sign = str::replace(&format!("{:?}", time_now_sign), "Signature(", "");
let time_now_sign = str::replace(&time_now_sign, ")", "");
time_now_signature = time_now_sign;
}
if time_now_signature.is_empty() {
is_error = true;
}
let mut url = String::from(&format!(
"https://{}:{}/listener?address={}&delTo={}&time_now={}&signature={}",
self.mwcmqs_domain,
self.mwcmqs_port,
str::replace(&cloned_address.get_stripped(), "@", "%40"),
"nil".to_string(),
time_now,
time_now_signature
));
let first_url = String::from(&format!(
"https://{}:{}/listener?address={}&delTo={}&time_now={}&signature={}&first=true",
self.mwcmqs_domain,
self.mwcmqs_port,
str::replace(&cloned_address.get_stripped(), "@", "%40"),
"nil".to_string(),
time_now,
time_now_signature
));
if is_error {
print!(
"ERROR: Failed to start mwcmqs subscriber. Error connecting to {}:{}",
self.mwcmqs_domain, self.mwcmqs_port
);
} else {
let mut is_error = false;
let mut loop_count = 0;
loop {
loop_count = loop_count + 1;
if is_error {
break;
}
let mut resp_str = "".to_string();
count = count + 1;
let cloned_cloned_address = cloned_address.clone();
if !cloned_running.load(Ordering::SeqCst) {
break;
}
let secs = if !connected { 2 } else { 120 };
let cl = reqwest::Client::builder()
.timeout(Duration::from_secs(secs))
.build();
let client = if cl.is_ok() {
cl.unwrap()
} else {
self.print_error([].to_vec(), "couldn't instantiate client", -101);
is_error = true;
continue;
};
let mut first_response = true;
let resp_result = if loop_count == 1 {
client.get(&*first_url).send()
} else {
client.get(&*url).send()
};
if !resp_result.is_ok() {
let err_message = format!("{:?}", resp_result);
let re = Regex::new(TIMEOUT_ERROR_REGEX).unwrap();
let captures = re.captures(&err_message);
if captures.is_none() {
// This was not a timeout. Sleep first.
if connected {
is_in_warning = true;
self.do_log_warn(format!("\nWARNING: mwcmqs listener [{}] lost connection. Will try to restore in the background. tid=[{}]",
cloned_cloned_address.get_stripped(), nanoid ));
}
let second = time::Duration::from_millis(5000);
thread::sleep(second);
connected = false;
} else if count == 1 {
delcount = 0;
self.do_log_warn(format!(
"\nmwcmqs listener started for [{}] tid=[{}]",
cloned_cloned_address.get_stripped(),
nanoid
));
connected = true;
} else {
delcount = 0;
if !connected {
if is_in_warning {
self.do_log_info(format!(
"INFO: mwcmqs listener [{}] reestablished connection. tid=[{}]",
cloned_cloned_address.get_stripped(),
nanoid
));
is_in_warning = false;
isnginxerror = false;
}
}
connected = true;
}
} else {
if count == 1 {
self.do_log_warn(format!(
"\nmwcmqs listener started for [{}] tid=[{}]",
cloned_cloned_address.get_stripped(),
nanoid
));
} else if !connected && !isnginxerror {
if is_in_warning {
self.do_log_info(format!(
"INFO: listener [{}] reestablished connection.",
cloned_cloned_address.get_stripped()
));
is_in_warning = false;
isnginxerror = false;
}
connected = true;
} else if !isnginxerror {
connected = true;
}
let mut resp = resp_result.unwrap();
let read_resp = resp.read_to_string(&mut resp_str);
if !read_resp.is_ok() {
// read error occured. Sleep and try again in 5 seconds
self.do_log_info(format!("io error occured while trying to connect to {}. Will sleep for 5 second and will reconnect.",
&format!("https://{}:{}", self.mwcmqs_domain, self.mwcmqs_port)));
self.do_log_error(format!("Error: {:?}", read_resp));
let second = time::Duration::from_millis(5000);
thread::sleep(second);
continue;
}
let mut break_out = false;
let msgvec: Vec<&str> = if resp_str.starts_with("messagelist: ") {
let mut ret: Vec<&str> = Vec::new();
let lines: Vec<&str> = resp_str.split("\n").collect();
for i in 1..lines.len() {
let params: Vec<&str> = lines[i].split(" ").collect();
if params.len() >= 2 {
let index = params[1].find(';');
if index.is_some() {
// new format
let index = index.unwrap();
let mut last_message_id = ¶ms[1][0..index];
let start = last_message_id.find(' ');
if start.is_some() {
last_message_id = &last_message_id[1 + start.unwrap()..];
}
url = String::from(format!(
"https://{}:{}/listener?address={}&delTo={}&time_now={}&signature={}",
self.mwcmqs_domain,
self.mwcmqs_port,
str::replace(&cloned_address.get_stripped(), "@", "%40"),
&last_message_id,
time_now,
time_now_signature
));
ret.push(¶ms[1][index + 1..]);
} else if params[1] == "closenewlogin" {
if cloned_running.load(Ordering::SeqCst) {
self.do_log_error(format!(
"\nERROR: new login detected. mwcmqs listener will stop!"
));
}
break; // stop listener
} else {
self.print_error([].to_vec(), "message id expected", -103);
is_error = true;
continue;
}
}
}
ret
} else {
let index = resp_str.find(';');
if index.is_some() {
// new format
let index = index.unwrap();
let mut last_message_id = &resp_str[0..index];
let start = last_message_id.find(' ');
if start.is_some() {
last_message_id = &last_message_id[1 + start.unwrap()..];
}
url = String::from(format!(
"https://{}:{}/listener?address={}&delTo={}&time_now={}&signature={}",
self.mwcmqs_domain,
self.mwcmqs_port,
str::replace(&cloned_address.get_stripped(), "@", "%40"),
&last_message_id,
time_now,
time_now_signature
));
vec![&resp_str[index + 1..]]
} else {
if resp_str.find("nginx").is_some() {
// this is common for nginx to return if the server is down.
// so we don't print. We also add a small sleep here.
connected = false;
if !isnginxerror {
is_in_warning = true;
self.do_log_warn(format!("\nWARNING: mwcmqs listener [{}] lost connection. Will try to restore in the background. tid=[{}]",
cloned_cloned_address.get_stripped(),
nanoid));
}
isnginxerror = true;
let second = time::Duration::from_millis(5000);
thread::sleep(second);
continue;
} else {
if resp_str == "message: closenewlogin\n" {
if cloned_running.load(Ordering::SeqCst) {
self.do_log_error(format!(
"\nERROR: new login detected. mwcmqs listener will stop!",
));
}
break; // stop listener
} else if resp_str == "message: mapmessage=nil" {
// our connection message
continue;
} else {
self.print_error([].to_vec(), "message id expected", -102);
is_error = true;
continue;
}
}
}
};
for itt in 0..msgvec.len() {
if break_out {
break;
}
if msgvec[itt] == "message: closenewlogin\n"
|| msgvec[itt] == "closenewlogin"
{
if cloned_running.load(Ordering::SeqCst) {
print!("\nERROR: new login detected. mwcmqs listener will stop!",);
}
break_out = true;
break; // stop listener
} else if msgvec[itt] == "message: mapmessage=nil\n"
|| msgvec[itt] == "mapmessage=nil"
|| msgvec[itt] == "mapmessage=nil\n"
{
if first_response {
delcount = 1;
first_response = false;
} else {
delcount = delcount + 1;
}
// this is our exit message. Just ignore.
continue;
}
let split = msgvec[itt].split(" ");
let vec: Vec<&str> = split.collect();
let splitx = if vec.len() == 1 {
vec[0].split("&")
} else if vec.len() >= 2 {
vec[1].split("&")
} else {
self.print_error(msgvec.clone(), "too many spaced messages", -1);
is_error = true;
continue;
};
let splitxvec: Vec<&str> = splitx.collect();
let splitxveclen = splitxvec.len();
if splitxveclen != 3 {
if msgvec[itt].find("nginx").is_some() {
// this is common for nginx to return if the server is down.
// so we don't print. We also add a small sleep here.
connected = false;
if !isnginxerror {
is_in_warning = true;
self.do_log_warn(format!("\nWARNING: mwcmqs listener [{}] lost connection. Will try to restore in the background. tid=[{}]",
cloned_cloned_address.get_stripped(),
nanoid));
}
isnginxerror = true;
let second = time::Duration::from_millis(5000);
thread::sleep(second);
} else {
self.print_error(msgvec.clone(), "splitxveclen != 3", -2);
is_error = true;
}
continue;
} else if isnginxerror {
isnginxerror = false;
connected = true;
}
let mut from = "".to_string();
for i in 0..3 {
if splitxvec[i].starts_with("from=") {
let vec: Vec<&str> = splitxvec[i].split("=").collect();
if vec.len() <= 1 {
self.print_error(msgvec.clone(), "vec.len <= 1", -3);
is_error = true;
continue;
}
from = str::replace(
&vec[1].to_string().trim().to_string(),
"%40",
"@",
);
}
}
let mut signature = "".to_string();
for i in 0..3 {
if splitxvec[i].starts_with("signature=") {
let vec: Vec<&str> = splitxvec[i].split("=").collect();
if vec.len() <= 1 {
self.print_error(msgvec.clone(), "vec.len <= 1", -4);
is_error = true;
continue;
}
signature = vec[1].to_string().trim().to_string();
}
}
for i in 0..3 {
if splitxvec[i].starts_with("mapmessage=")
|| splitxvec[i].starts_with("swapmessage=")
{
let slate_or_swap = if splitxvec[i].starts_with("mapmessage") {
"slate"
} else {
"swap"
};
let split2 = splitxvec[i].split("=");
let vec2: Vec<&str> = split2.collect();
if vec2.len() <= 1 {
self.print_error(msgvec.clone(), "vec2.len <= 1", -5);
is_error = true;
continue;
}
let r1 = str::replace(vec2[1], "%22", "\"");
let r2 = str::replace(&r1, "%7B", "{");
let r3 = str::replace(&r2, "%7D", "}");
let r4 = str::replace(&r3, "%3A", ":");
let r5 = str::replace(&r4, "%2C", ",");
let r5 = r5.trim().to_string();
if first_response {
delcount = 1;
first_response = false;
} else {
delcount = delcount + 1;
}
let from = MWCMQSAddress::from_str(&from);
let from = if !from.is_ok() {
self.print_error(msgvec.clone(), "error parsing from", -12);
is_error = true;
continue;
} else {
from.unwrap()
};
if slate_or_swap == "slate" {
let (mut slate, tx_proof) = match TxProof::from_response(
&from.address,
r5.clone(),
"".to_string(),
signature.clone(),
&secret_key,
&source_address,
) {
Ok(x) => x,
Err(err) => {
self.do_log_error(format!("{}", err));
continue;
}
};
push_proof_for_slate(&slate.id, tx_proof);
self.handler.lock().on_slate(&from, &mut slate);
} else if slate_or_swap == "swap" {
let swap_message = match SwapMessage::from_received(
&from.address,
r5.clone(),
"".to_string(),
signature.clone(),
&secret_key,
) {
Ok(x) => x,
Err(err) => {
self.do_log_error(format!("{}", err));
continue;
}
};
let ack_message =
self.handler.lock().on_swap_message(swap_message);
if let Some(ack_message) = ack_message {
let mqs_cannel = MwcMqsChannel::new(from.to_string());
if let Err(e) = mqs_cannel.send_swap_message(&ack_message) {
self.do_log_error(format!(
"Unable to send back ack message, {}",
e
));
}
}
}
break;
}
}
}
if break_out {
break;
}
}
}
}
if !is_error {
self.do_log_info(format!(
"\nmwcmqs listener [{}] stopped. tid=[{}]",
address.get_stripped(),
nanoid
));
}
cloned_running.store(false, Ordering::SeqCst);
reset_mwcmqs_brocker();
}
fn stop(&self) {
self.running.store(false, Ordering::SeqCst);
}
fn is_running(&self) -> bool {
self.running.load(Ordering::SeqCst)
}
}
|
use std::fs::File;
use std::io::{BufWriter, Write};
use clap::{App, Arg};
fn main() -> std::io::Result<()> {
let args = App::new("json-sorter")
.version("0.1")
.about("sorts keys alphabetically in a JSON file")
.arg(Arg::with_name("input_file")
.help("The JSON file to sort keys in")
.takes_value(true)
.required(true))
.get_matches();
let input_file_name = args.value_of("input_file").unwrap();
let json: serde_json::Value = serde_json::from_reader(File::open(input_file_name)
.expect("file should open read only"))
.expect("file should be proper JSON");
BufWriter::new(
File::create("sorted_".to_string() + input_file_name)
.expect("Unable to create file [{}]"))
.write_all(json.to_string().as_bytes())
.expect("Unable to write data");
Ok(())
} |
fn is_prime(n: i64) -> bool {
if n == 1 {
return false;
}
let mut i = 2;
while i * i <= n {
if n % i == 0 {
return false;
}
i += 1;
}
return true;
}
#[test]
fn test_is_prime() {
assert!(!is_prime(1));
assert!(is_prime(2));
assert!(is_prime(3));
assert!(is_prime(47));
assert!(!is_prime(48));
}
fn prime_factors(n: i64) -> Vec<(i64, i64)> {
if n == 1 {
return vec![(1, 1)];
}
let mut x = n;
let mut i = 2;
let mut res = vec![];
while i * i <= n {
let mut cnt = 0;
while x % i == 0 {
cnt += 1;
x /= i;
}
if cnt > 0 {
res.push((i, cnt));
}
i += 1;
}
if x != 1 {
res.push((x, 1));
}
return res;
}
#[test]
fn test_prime_factors() {
assert_eq!(vec![(2, 4)], prime_factors(16));
assert_eq!(vec![(47, 1)], prime_factors(47));
assert_eq!(vec![(3, 1), (5, 1), (43, 1)], prime_factors(645));
}
fn main() {
let mut ans = 1;
while prime_factors(ans).len() != 4
|| prime_factors(ans + 1).len() != 4
|| prime_factors(ans + 2).len() != 4
|| prime_factors(ans + 3).len() != 4
{
ans += 1;
}
println!("{}", ans);
}
|
#[doc = "Register `STGENR_PIDR6` reader"]
pub type R = crate::R<STGENR_PIDR6_SPEC>;
#[doc = "Field `PIDR6` reader - PIDR6"]
pub type PIDR6_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - PIDR6"]
#[inline(always)]
pub fn pidr6(&self) -> PIDR6_R {
PIDR6_R::new(self.bits)
}
}
#[doc = "STGENR peripheral ID6 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`stgenr_pidr6::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct STGENR_PIDR6_SPEC;
impl crate::RegisterSpec for STGENR_PIDR6_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`stgenr_pidr6::R`](R) reader structure"]
impl crate::Readable for STGENR_PIDR6_SPEC {}
#[doc = "`reset()` method sets STGENR_PIDR6 to value 0"]
impl crate::Resettable for STGENR_PIDR6_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Reader of register MMMS_RX_PKT_CNTR"]
pub type R = crate::R<u32, super::MMMS_RX_PKT_CNTR>;
#[doc = "Reader of field `MMMS_RX_PKT_CNT`"]
pub type MMMS_RX_PKT_CNT_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:5 - Count of all packets in the RX FIFO in MMMS mode"]
#[inline(always)]
pub fn mmms_rx_pkt_cnt(&self) -> MMMS_RX_PKT_CNT_R {
MMMS_RX_PKT_CNT_R::new((self.bits & 0x3f) as u8)
}
}
|
//! `fitsio` - a thin wrapper around the [`cfitsio`][1] C library.
//!
//! * [HDU access](#hdu-access)
//! * [Header keys](#header-keys)
//! * [Reading file data](#reading-file-data)
//! * [Images](#images)
//! * [Tables](#tables)
//!
//! This library wraps the low level `cfitsio` bindings: [`fitsio-sys`][2] and provides a more
//! native experience for rust users.
//!
//! The main interface to a fits file is [`FitsFile`](struct.FitsFile.html). All file manipulation
//! and reading starts with this class.
//!
//! Opening a file:
//!
//! ```rust
//! # fn main() {
//! # let filename = "../testdata/full_example.fits";
//! use fitsio::FitsFile;
//!
//! // let filename = ...;
//! let fptr = FitsFile::open(filename).unwrap();
//! # }
//! ```
//!
//! Alternatively a new file can be created on disk with the companion method
//! [`create`](struct.FitsFile.html#method.create):
//!
//! ```rust
//! # extern crate tempdir;
//! # extern crate fitsio;
//! # use fitsio::FitsFile;
//! # fn main() {
//! # let tdir = tempdir::TempDir::new("fitsio-").unwrap();
//! # let tdir_path = tdir.path();
//! # let _filename = tdir_path.join("test.fits");
//! # let filename = _filename.to_str().unwrap();
//! use fitsio::FitsFile;
//!
//! // let filename = ...;
//! let fptr = FitsFile::create(filename).unwrap();
//! # }
//! ```
//!
//! From this point, the current HDU can be queried and changed, or fits header cards can be read
//! or file contents can be read.
//!
//! ## HDU access
//!
//! Information about the current HDU can be fetched with various functions, for example getting
//! the current HDU type:
//!
//! ```rust
//! # extern crate fitsio;
//! # extern crate fitsio_sys;
//! # use fitsio::FitsFile;
//! #
//! # fn main() {
//! # let filename = "../testdata/full_example.fits";
//! # let fptr = FitsFile::open(filename).unwrap();
//! use fitsio_sys::HduType;
//!
//! match fptr.hdu_type() {
//! Ok(HduType::IMAGE_HDU) => println!("Found image"),
//! Ok(HduType::BINARY_TBL) => println!("Found table"),
//! _ => {},
//! }
//! # }
//! ```
//!
//! or fetching metadata about the current HDU:
//!
//! ```rust
//! # extern crate fitsio;
//! # extern crate fitsio_sys;
//! # use fitsio::{FitsFile, HduInfo};
//! #
//! # fn main() {
//! # let filename = "../testdata/full_example.fits";
//! # let fptr = FitsFile::open(filename).unwrap();
//! // image HDU
//! if let Ok(HduInfo::ImageInfo { dimensions, shape }) = fptr.fetch_hdu_info() {
//! println!("Image is {}-dimensional", dimensions);
//! println!("Found image with shape {:?}", shape);
//! }
//! # fptr.change_hdu("TESTEXT").unwrap();
//!
//! // tables
//! if let Ok(HduInfo::TableInfo { column_names, num_rows, .. }) = fptr.fetch_hdu_info() {
//! println!("Table contains {} rows", num_rows);
//! println!("Table has {} columns", column_names.len());
//! }
//! # }
//! ```
//!
//! The current HDU can be selected either by absolute number (0-indexed) or string-like:
//!
//! ```rust
//! # extern crate fitsio;
//! #
//! # fn main() {
//! # let filename = "../testdata/full_example.fits";
//! # let fptr = fitsio::FitsFile::open(filename).unwrap();
//! fptr.change_hdu(1).unwrap();
//! assert_eq!(fptr.hdu_number(), 1);
//!
//! # fptr.change_hdu(0).unwrap();
//! fptr.change_hdu("TESTEXT").unwrap();
//! assert_eq!(fptr.hdu_number(), 1);
//! # }
//! ```
//!
//! ## Header keys
//!
//! Header keys are read through the [`read_key`](struct.FitsFile.html#method.read_key) function,
//! and is generic over types that implement the [`ReadsKey`](trait.ReadsKey.html) trait:
//!
//! ```rust
//! # extern crate fitsio;
//! #
//! # fn main() {
//! # let filename = "../testdata/full_example.fits";
//! # let fptr = fitsio::FitsFile::open(filename).unwrap();
//! # {
//! let int_value: i64 = fptr.read_key("INTTEST").unwrap();
//! # }
//!
//! // Alternatively
//! # {
//! let int_value = fptr.read_key::<i64>("INTTEST").unwrap();
//! # }
//!
//! // Or let the compiler infer the types (if possible)
//! # }
//! ```
//!
//! Header cards can be written through the method
//! [`write_key`](struct.FitsFile.html#method.write_key). It takes a key name and value. See [the
//! `WritesKey`](trait.WritesKey.html) trait for supported data types.
//!
//! ```rust
//! # extern crate tempdir;
//! # extern crate fitsio;
//! # let tdir = tempdir::TempDir::new("fitsio-").unwrap();
//! # let tdir_path = tdir.path();
//! # let filename = tdir_path.join("test.fits");
//! # {
//! # let fptr = fitsio::FitsFile::create(filename.to_str().unwrap()).unwrap();
//! fptr.write_key("foo", 1i64).unwrap();
//! assert_eq!(fptr.read_key::<i64>("foo").unwrap(), 1i64);
//! # }
//! ```
//!
//! ## Reading file data
//!
//! ### Images
//!
//! Image data can be read through either
//! [`read_section`](struct.FitsFile.html#method.read_section) which reads contiguous pixels
//! between a start index and end index, or
//! [`read_region`](struct.FitsFile.html#method.read_region) which reads rectangular chunks from
//! the image.
//!
//! ```rust
//! # extern crate fitsio;
//! #
//! # fn main() {
//! # let filename = "../testdata/full_example.fits";
//! # let fptr = fitsio::FitsFile::open(filename).unwrap();
//! // Read the first 100 pixels
//! let first_row: Vec<i32> = fptr.read_section(0, 100).unwrap();
//!
//! // Read a square section of the image
//! use fitsio::positional::Coordinate;
//!
//! let lower_left = Coordinate { x: 0, y: 0 };
//! let upper_right = Coordinate { x: 10, y: 10 };
//! let chunk: Vec<i32> = fptr.read_region(&lower_left, &upper_right).unwrap();
//! # }
//! ```
//!
//! ### Tables
//!
//! Columns can be read using the [`read_col`](struct.FitsFile.html#method.read_col) function,
//! which can convert data types on the fly. See the [`ReadsCol`](trait.ReadsCol.html) trait for
//! supported data types.
//!
//! ```rust
//! # extern crate fitsio;
//! #
//! # fn main() {
//! # let filename = "../testdata/full_example.fits";
//! # let fptr = fitsio::FitsFile::open(filename).unwrap();
//! # fptr.change_hdu(1).unwrap();
//! let integer_data: Vec<i32> = fptr.read_col("intcol").unwrap();
//! # }
//! ```
//!
//! The [`columns`](struct.FitsFile.html#method.columns) method returns an iterator over all of the
//! columns in a table.
//!
//! [1]: http://heasarc.gsfc.nasa.gov/fitsio/fitsio.html
//! [2]: https://crates.io/crates/fitsio-sys
mod stringutils;
pub mod positional;
extern crate fitsio_sys as sys;
extern crate libc;
use std::ptr;
use std::ffi;
use positional::Coordinate;
/// Error type
///
/// `cfitsio` passes errors through integer status codes. This struct wraps this and its associated
/// error message.
#[derive(Debug, PartialEq, Eq)]
pub struct FitsError {
status: i32,
message: String,
}
/// Macro for returning a FITS error type
macro_rules! fits_try {
($status: ident, $e: expr) => {
match $status {
0 => Ok($e),
_ => {
Err(FitsError {
status: $status,
message: stringutils::status_to_string($status).unwrap(),
})
}
}
}
}
/// FITS specific result type
///
/// This is a shortcut for a result with `FitsError` as the error type
pub type Result<T> = std::result::Result<T, FitsError>;
/// Hdu description type
///
/// Any way of describing a HDU - number or string which either
/// changes the hdu by absolute number, or by name.
pub trait DescribesHdu {
fn change_hdu(&self, fptr: &FitsFile) -> Result<()>;
}
impl DescribesHdu for usize {
fn change_hdu(&self, f: &FitsFile) -> Result<()> {
let mut _hdu_type = 0;
let mut status = 0;
unsafe {
sys::ffmahd(f.fptr, (*self + 1) as i32, &mut _hdu_type, &mut status);
}
fits_try!(status, ())
}
}
impl<'a> DescribesHdu for &'a str {
fn change_hdu(&self, f: &FitsFile) -> Result<()> {
let mut _hdu_type = 0;
let mut status = 0;
let c_hdu_name = ffi::CString::new(*self).unwrap();
unsafe {
sys::ffmnhd(f.fptr,
sys::HduType::ANY_HDU.into(),
c_hdu_name.into_raw(),
0,
&mut status);
}
fits_try!(status, ())
}
}
/// Trait applied to types which can be read from a FITS header
///
/// This is currently:
///
/// * i32
/// * i64
/// * f32
/// * f64
/// * String
pub trait ReadsKey {
fn read_key(f: &FitsFile, name: &str) -> Result<Self> where Self: Sized;
}
macro_rules! reads_key_impl {
($t:ty, $func:ident) => (
impl ReadsKey for $t {
fn read_key(f: &FitsFile, name: &str) -> Result<Self> {
let c_name = ffi::CString::new(name).unwrap();
let mut status = 0;
let mut value: Self = Self::default();
unsafe {
sys::$func(f.fptr,
c_name.into_raw(),
&mut value,
ptr::null_mut(),
&mut status);
}
fits_try!(status, value)
}
}
)
}
reads_key_impl!(i32, ffgkyl);
reads_key_impl!(i64, ffgkyj);
reads_key_impl!(f32, ffgkye);
reads_key_impl!(f64, ffgkyd);
impl ReadsKey for String {
fn read_key(f: &FitsFile, name: &str) -> Result<Self> {
let c_name = ffi::CString::new(name).unwrap();
let mut status = 0;
let mut value: Vec<libc::c_char> = vec![0; sys::MAX_VALUE_LENGTH];
unsafe {
sys::ffgkys(f.fptr,
c_name.into_raw(),
value.as_mut_ptr(),
ptr::null_mut(),
&mut status);
}
fits_try!(status, {
let value: Vec<u8> = value.iter()
.map(|&x| x as u8)
.filter(|&x| x != 0)
.collect();
String::from_utf8(value).unwrap()
})
}
}
/// Writing a fits keyword
pub trait WritesKey {
fn write_key(f: &FitsFile, name: &str, value: Self) -> Result<()>;
}
macro_rules! writes_key_impl_flt {
($t:ty, $func:ident) => (
impl WritesKey for $t {
fn write_key(f: &FitsFile, name: &str, value: Self) -> Result<()> {
let c_name = ffi::CString::new(name).unwrap();
let mut status = 0;
unsafe {
sys::$func(f.fptr,
c_name.into_raw(),
value,
9,
ptr::null_mut(),
&mut status);
}
fits_try!(status, ())
}
}
)
}
impl WritesKey for i64 {
fn write_key(f: &FitsFile, name: &str, value: Self) -> Result<()> {
let c_name = ffi::CString::new(name).unwrap();
let mut status = 0;
unsafe {
sys::ffpkyj(f.fptr,
c_name.into_raw(),
value,
ptr::null_mut(),
&mut status);
}
fits_try!(status, ())
}
}
writes_key_impl_flt!(f32, ffpkye);
writes_key_impl_flt!(f64, ffpkyd);
impl WritesKey for String {
fn write_key(f: &FitsFile, name: &str, value: Self) -> Result<()> {
let c_name = ffi::CString::new(name).unwrap();
let mut status = 0;
unsafe {
sys::ffpkys(f.fptr,
c_name.into_raw(),
ffi::CString::new(value).unwrap().into_raw(),
ptr::null_mut(),
&mut status);
}
fits_try!(status, ())
}
}
/// Trait for reading a fits column
pub trait ReadsCol {
fn read_col(fits_file: &FitsFile, name: &str) -> Result<Vec<Self>> where Self: Sized;
}
macro_rules! reads_col_impl {
($t: ty, $func: ident, $nullval: expr) => (
impl ReadsCol for $t {
fn read_col(fits_file: &FitsFile, name: &str) -> Result<Vec<Self>> {
match fits_file.fetch_hdu_info() {
Ok(HduInfo::TableInfo {
column_names, num_rows, ..
}) => {
let mut out = vec![$nullval; num_rows];
assert_eq!(out.len(), num_rows);
let column_number = column_names.iter().position(|ref colname| {
colname.as_str() == name
}).unwrap();
let mut status = 0;
unsafe {
sys::$func(fits_file.fptr,
(column_number + 1) as i32,
1,
1,
num_rows as i64,
$nullval,
out.as_mut_ptr(),
ptr::null_mut(),
&mut status);
}
fits_try!(status, out)
},
Err(e) => Err(e),
_ => panic!("Unknown error occurred"),
}
}
}
)
}
reads_col_impl!(i32, ffgcvk, 0);
reads_col_impl!(u32, ffgcvuk, 0);
reads_col_impl!(i64, ffgcvj, 0);
reads_col_impl!(u64, ffgcvuj, 0);
reads_col_impl!(f32, ffgcve, 0.0);
reads_col_impl!(f64, ffgcvd, 0.0);
// TODO: impl for string
/// Reading fits images
pub trait ReadsImage {
fn read_section(fits_file: &FitsFile, start: usize, end: usize) -> Result<Vec<Self>>
where Self: Sized;
/// Read a square region from the chip.
///
/// Lower left indicates the starting point of the square, and the upper
/// right defines the pixel _beyond_ the end. The range of pixels included
/// is inclusive of the lower end, and *exclusive* of the upper end.
fn read_region(fits_file: &FitsFile,
lower_left: &Coordinate,
upper_right: &Coordinate)
-> Result<Vec<Self>>
where Self: Sized;
}
macro_rules! reads_image_impl {
($t: ty, $data_type: expr) => (
impl ReadsImage for $t {
fn read_section(fits_file: &FitsFile, start: usize, end: usize) -> Result<Vec<Self>> {
match fits_file.fetch_hdu_info() {
Ok(HduInfo::ImageInfo { dimensions: _dimensions, shape: _shape }) => {
let nelements = end - start;
let mut out = vec![0 as $t; nelements];
let mut status = 0;
unsafe {
sys::ffgpv(fits_file.fptr,
$data_type.into(),
(start + 1) as i64,
nelements as i64,
ptr::null_mut(),
out.as_mut_ptr() as *mut libc::c_void,
ptr::null_mut(),
&mut status);
}
fits_try!(status, out)
}
Err(e) => Err(e),
_ => panic!("Unknown error occurred"),
}
}
fn read_region( fits_file: &FitsFile, lower_left: &Coordinate, upper_right: &Coordinate)
-> Result<Vec<Self>> {
match fits_file.fetch_hdu_info() {
Ok(HduInfo::ImageInfo { dimensions: _dimensions, shape: _shape }) => {
// TODO: check dimensions
// These have to be mutable because of the C-api
let mut fpixel = [ (lower_left.x + 1) as _, (lower_left.y + 1) as _ ];
let mut lpixel = [ (upper_right.x + 1) as _, (upper_right.y + 1) as _ ];
let mut inc = [ 1, 1 ];
let nelements =
((upper_right.y - lower_left.y) + 1) *
((upper_right.x - lower_left.x) + 1);
let mut out = vec![0 as $t; nelements as usize];
let mut status = 0;
unsafe {
sys::ffgsv(
fits_file.fptr,
$data_type.into(),
fpixel.as_mut_ptr(),
lpixel.as_mut_ptr(),
inc.as_mut_ptr(),
ptr::null_mut(),
out.as_mut_ptr() as *mut libc::c_void,
ptr::null_mut(),
&mut status);
}
fits_try!(status, out)
}
Err(e) => Err(e),
_ => panic!("Unknown error occurred"),
}
}
}
)
}
reads_image_impl!(i8, sys::DataType::TSHORT);
reads_image_impl!(i32, sys::DataType::TINT);
reads_image_impl!(i64, sys::DataType::TLONG);
reads_image_impl!(u8, sys::DataType::TUSHORT);
reads_image_impl!(u32, sys::DataType::TUINT);
reads_image_impl!(u64, sys::DataType::TULONG);
reads_image_impl!(f32, sys::DataType::TFLOAT);
reads_image_impl!(f64, sys::DataType::TDOUBLE);
/// Description of the current HDU
///
/// If the current HDU is an image, then
/// [`fetch_hdu_info`](struct.FitsFile.html#method.fetch_hdu_info) returns `HduInfo::ImageInfo`.
/// Otherwise the variant is `HduInfo::TableInfo`.
#[derive(PartialEq, Eq, Debug)]
pub enum HduInfo {
ImageInfo {
dimensions: usize,
shape: Vec<usize>,
},
TableInfo {
column_names: Vec<String>,
column_types: Vec<sys::DataType>,
num_rows: usize,
},
}
/// Main entry point to the FITS file format
///
///
pub struct FitsFile {
fptr: *mut sys::fitsfile,
pub filename: String,
}
impl Clone for FitsFile {
fn clone(&self) -> Self {
FitsFile::open(&self.filename).unwrap()
}
}
fn typechar_to_data_type<T: Into<String>>(typechar: T) -> sys::DataType {
match typechar.into().as_str() {
"X" => sys::DataType::TBIT,
"B" => sys::DataType::TBYTE,
"L" => sys::DataType::TLOGICAL,
"A" => sys::DataType::TSTRING,
"I" => sys::DataType::TSHORT,
"J" => sys::DataType::TLONG,
"E" => sys::DataType::TFLOAT,
"D" => sys::DataType::TDOUBLE,
"C" => sys::DataType::TCOMPLEX,
"M" => sys::DataType::TDBLCOMPLEX,
"K" => sys::DataType::TLONGLONG,
other => panic!("Unhandled case: {}", other),
}
}
unsafe fn fetch_hdu_info(fptr: *mut sys::fitsfile) -> Result<HduInfo> {
let mut status = 0;
let mut hdu_type = 0;
sys::ffghdt(fptr, &mut hdu_type, &mut status);
let hdu_type = match hdu_type {
0 => {
let mut dimensions = 0;
sys::ffgidm(fptr, &mut dimensions, &mut status);
let mut shape = vec![0; dimensions as usize];
sys::ffgisz(fptr, dimensions, shape.as_mut_ptr(), &mut status);
HduInfo::ImageInfo {
dimensions: dimensions as usize,
shape: shape.iter().map(|v| *v as usize).collect(),
}
}
1 | 2 => {
let mut num_rows = 0;
sys::ffgnrw(fptr, &mut num_rows, &mut status);
let mut num_cols = 0;
sys::ffgncl(fptr, &mut num_cols, &mut status);
let mut column_names = Vec::with_capacity(num_cols as usize);
let mut column_types = Vec::with_capacity(num_cols as usize);
for i in 0..num_cols {
let mut name_buffer: Vec<libc::c_char> = vec![0; 71];
let mut type_buffer: Vec<libc::c_char> = vec![0; 71];
sys::ffgbcl(fptr,
(i + 1) as i32,
name_buffer.as_mut_ptr(),
ptr::null_mut(),
type_buffer.as_mut_ptr(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
&mut status);
column_names.push(stringutils::buf_to_string(&name_buffer).unwrap());
column_types.push(typechar_to_data_type(stringutils::buf_to_string(&type_buffer)
.unwrap()));
}
HduInfo::TableInfo {
column_names: column_names,
column_types: column_types,
num_rows: num_rows as usize,
}
}
_ => panic!("Invalid hdu type found"),
};
fits_try!(status, hdu_type)
}
pub enum Column {
Int32 {
name: String,
data: Vec<i32>,
},
Int64 {
name: String,
data: Vec<i64>,
},
Float {
name: String,
data: Vec<f32>,
},
Double {
name: String,
data: Vec<f64>,
},
}
pub struct ColumnIterator<'a> {
current: usize,
column_names: Vec<String>,
column_types: Vec<sys::DataType>,
fits_file: &'a FitsFile,
}
impl<'a> ColumnIterator<'a> {
fn new(fits_file: &'a FitsFile) -> Self {
match fits_file.fetch_hdu_info() {
Ok(HduInfo::TableInfo { column_names, column_types, num_rows: _num_rows }) => {
ColumnIterator {
current: 0,
column_names: column_names,
column_types: column_types,
fits_file: fits_file,
}
}
Err(e) => panic!("{:?}", e),
_ => panic!("Unknown error occurred"),
}
}
}
impl<'a> Iterator for ColumnIterator<'a> {
type Item = Column;
fn next(&mut self) -> Option<Self::Item> {
let ncols = self.column_names.len();
if self.current < ncols {
let current_name = &self.column_names[self.current];
let current_type = &self.column_types[self.current];
let retval = match *current_type {
sys::DataType::TSHORT => {
i32::read_col(self.fits_file, current_name)
.map(|data| {
Some(Column::Int32 {
name: current_name.to_string(),
data: data,
})
})
.unwrap()
}
sys::DataType::TLONG => {
i64::read_col(self.fits_file, current_name)
.map(|data| {
Some(Column::Int64 {
name: current_name.to_string(),
data: data,
})
})
.unwrap()
}
sys::DataType::TFLOAT => {
f32::read_col(self.fits_file, current_name)
.map(|data| {
Some(Column::Float {
name: current_name.to_string(),
data: data,
})
})
.unwrap()
}
sys::DataType::TDOUBLE => {
f64::read_col(self.fits_file, current_name)
.map(|data| {
Some(Column::Double {
name: current_name.to_string(),
data: data,
})
})
.unwrap()
}
_ => unimplemented!(),
};
self.current += 1;
retval
} else {
None
}
}
}
impl FitsFile {
/// Open a fits file from disk
///
/// # Examples
///
/// ```
/// use fitsio::FitsFile;
///
/// let f = FitsFile::open("../testdata/full_example.fits").unwrap();
///
/// // Continue to use `f` afterwards
/// ```
pub fn open(filename: &str) -> Result<Self> {
let mut fptr = ptr::null_mut();
let mut status = 0;
let c_filename = ffi::CString::new(filename).unwrap();
unsafe {
sys::ffopen(&mut fptr as *mut *mut sys::fitsfile,
c_filename.as_ptr(),
sys::FileOpenMode::READONLY as libc::c_int,
&mut status);
}
fits_try!(status,
FitsFile {
fptr: fptr,
filename: filename.to_string(),
})
}
/// Create a new fits file on disk
pub fn create(path: &str) -> Result<Self> {
let mut fptr = ptr::null_mut();
let mut status = 0;
let c_filename = ffi::CString::new(path).unwrap();
unsafe {
sys::ffinit(&mut fptr as *mut *mut sys::fitsfile,
c_filename.as_ptr(),
&mut status);
}
fits_try!(status, {
let f = FitsFile {
fptr: fptr,
filename: path.to_string(),
};
try!(f.add_empty_primary());
f
})
}
fn add_empty_primary(&self) -> Result<()> {
let mut status = 0;
unsafe {
sys::ffphps(self.fptr, 8, 0, ptr::null_mut(), &mut status);
}
fits_try!(status, ())
}
/// Change the current HDU
pub fn change_hdu<T: DescribesHdu>(&self, hdu_description: T) -> Result<()> {
hdu_description.change_hdu(self)
}
/// Get the current HDU type
pub fn hdu_type(&self) -> Result<sys::HduType> {
let mut status = 0;
let mut hdu_type = 0;
unsafe {
sys::ffghdt(self.fptr, &mut hdu_type, &mut status);
}
fits_try!(status, {
match hdu_type {
0 => sys::HduType::IMAGE_HDU,
2 => sys::HduType::BINARY_TBL,
_ => unimplemented!(),
}
})
}
pub fn hdu_number(&self) -> usize {
let mut hdu_num = 0;
unsafe {
sys::ffghdn(self.fptr, &mut hdu_num);
}
(hdu_num - 1) as usize
}
/// Read header key
pub fn read_key<T: ReadsKey>(&self, name: &str) -> Result<T> {
T::read_key(self, name)
}
/// Write header key
pub fn write_key<T: WritesKey>(&self, name: &str, value: T) -> Result<()> {
T::write_key(self, name, value)
}
/// Read a binary table column
pub fn read_col<T: ReadsCol>(&self, name: &str) -> Result<Vec<T>> {
T::read_col(self, name)
}
/// Read an image between pixel a and pixel b into a `Vec`
pub fn read_section<T: ReadsImage>(&self, start: usize, end: usize) -> Result<Vec<T>> {
T::read_section(self, start, end)
}
/// Read a square region into a `Vec`
pub fn read_region<T: ReadsImage>(&self,
lower_left: &Coordinate,
upper_right: &Coordinate)
-> Result<Vec<T>> {
T::read_region(self, lower_left, upper_right)
}
pub fn columns(&self) -> ColumnIterator {
ColumnIterator::new(self)
}
/// Get the current hdu info
pub fn fetch_hdu_info(&self) -> Result<HduInfo> {
unsafe { fetch_hdu_info(self.fptr) }
}
}
impl Drop for FitsFile {
fn drop(&mut self) {
let mut status = 0;
unsafe {
sys::ffclos(self.fptr, &mut status);
}
}
}
#[cfg(test)]
mod test {
extern crate tempdir;
use super::*;
use sys;
use super::typechar_to_data_type;
#[test]
fn typechar_conversions() {
let input = vec![
"X",
"B",
"L",
"A",
"I",
"J",
"E",
"D",
"C",
"M",
];
let expected = vec![
sys::DataType::TBIT,
sys::DataType::TBYTE,
sys::DataType::TLOGICAL,
sys::DataType::TSTRING,
sys::DataType::TSHORT,
sys::DataType::TLONG,
sys::DataType::TFLOAT,
sys::DataType::TDOUBLE,
sys::DataType::TCOMPLEX,
sys::DataType::TDBLCOMPLEX,
];
input.iter()
.zip(expected)
.map(|(&i, e)| {
assert_eq!(typechar_to_data_type(i), e);
})
.collect::<Vec<_>>();
}
#[test]
fn opening_an_existing_file() {
match FitsFile::open("../testdata/full_example.fits") {
Ok(_) => {}
Err(e) => panic!("{:?}", e),
}
}
#[test]
fn creating_a_new_file() {
let tdir = tempdir::TempDir::new("fitsio-").unwrap();
let tdir_path = tdir.path();
let filename = tdir_path.join("test.fits");
assert!(!filename.exists());
FitsFile::create(filename.to_str().unwrap())
.map(|f| {
assert!(filename.exists());
// Ensure the empty primary has been written
let naxis: i64 = f.read_key("NAXIS").unwrap();
assert_eq!(naxis, 0);
})
.unwrap();
}
#[test]
fn fetching_a_hdu() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
for i in 0..2 {
f.change_hdu(i).unwrap();
assert_eq!(f.hdu_number(), i);
}
match f.change_hdu(2) {
Err(e) => assert_eq!(e.status, 107),
_ => panic!("Error checking for failure"),
}
f.change_hdu("TESTEXT").unwrap();
assert_eq!(f.hdu_number(), 1);
}
#[test]
fn reading_header_keys() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
match f.read_key::<i64>("INTTEST") {
Ok(value) => assert_eq!(value, 42),
Err(e) => panic!("Error reading key: {:?}", e),
}
match f.read_key::<f64>("DBLTEST") {
Ok(value) => assert_eq!(value, 0.09375),
Err(e) => panic!("Error reading key: {:?}", e),
}
match f.read_key::<String>("TEST") {
Ok(value) => assert_eq!(value, "value"),
Err(e) => panic!("Error reading key: {:?}", e),
}
}
#[test]
fn getting_hdu_type() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
assert_eq!(f.hdu_type().unwrap(), sys::HduType::IMAGE_HDU);
f.change_hdu("TESTEXT").unwrap();
assert_eq!(f.hdu_type().unwrap(), sys::HduType::BINARY_TBL);
}
#[test]
fn fetching_hdu_info() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
match f.fetch_hdu_info() {
Ok(HduInfo::ImageInfo { dimensions, shape }) => {
assert_eq!(dimensions, 2);
assert_eq!(shape, vec![100, 100]);
}
Err(e) => panic!("Error fetching hdu info {:?}", e),
_ => panic!("Unknown error"),
}
f.change_hdu(1).unwrap();
match f.fetch_hdu_info() {
Ok(HduInfo::TableInfo { column_names, column_types, num_rows }) => {
assert_eq!(num_rows, 50);
assert_eq!(column_names,
vec![
"intcol".to_string(),
"floatcol".to_string(),
"doublecol".to_string(),
]);
assert_eq!(column_types,
vec![
sys::DataType::TLONG,
sys::DataType::TFLOAT,
sys::DataType::TDOUBLE,
]);
}
Err(e) => panic!("Error fetching hdu info {:?}", e),
_ => panic!("Unknown error"),
}
}
#[test]
fn read_columns() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
f.change_hdu(1).unwrap();
let intcol_data: Vec<i32> = f.read_col("intcol").unwrap();
assert_eq!(intcol_data[0], 18);
assert_eq!(intcol_data[15], 10);
assert_eq!(intcol_data[49], 12);
let floatcol_data: Vec<f32> = f.read_col("floatcol").unwrap();
assert_eq!(floatcol_data[0], 17.496801);
assert_eq!(floatcol_data[15], 19.570272);
assert_eq!(floatcol_data[49], 10.217053);
let doublecol_data: Vec<f64> = f.read_col("doublecol").unwrap();
assert_eq!(doublecol_data[0], 16.959972808730814);
assert_eq!(doublecol_data[15], 19.013522579233065);
assert_eq!(doublecol_data[49], 16.61153656123406);
}
#[test]
fn read_image_data() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
let first_row: Vec<i32> = f.read_section(0, 100).unwrap();
assert_eq!(first_row.len(), 100);
assert_eq!(first_row[0], 108);
assert_eq!(first_row[49], 176);
let second_row: Vec<i32> = f.read_section(100, 200).unwrap();
assert_eq!(second_row.len(), 100);
assert_eq!(second_row[0], 177);
assert_eq!(second_row[49], 168);
}
#[test]
fn read_image_slice() {
use super::positional::Coordinate;
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
let lower_left = Coordinate { x: 0, y: 0 };
let upper_right = Coordinate { x: 10, y: 10 };
let chunk: Vec<i32> = f.read_region(&lower_left, &upper_right).unwrap();
assert_eq!(chunk.len(), 11 * 11);
assert_eq!(chunk[0], 108);
assert_eq!(chunk[11], 177);
assert_eq!(chunk[chunk.len() - 1], 160);
}
#[test]
fn cloning() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
let f2 = f.clone();
assert!(f.fptr != f2.fptr);
f.change_hdu(1).unwrap();
assert!(f.hdu_number() != f2.hdu_number());
}
#[test]
fn test_fits_try() {
use super::stringutils;
let status = 0;
assert_eq!(fits_try!(status, 10), Ok(10));
let status = 105;
assert_eq!(fits_try!(status, 10),
Err(FitsError {
status: status,
message: stringutils::status_to_string(status).unwrap(),
}));
}
#[test]
fn column_iterator() {
let f = FitsFile::open("../testdata/full_example.fits").unwrap();
f.change_hdu(1).unwrap();
let column_names: Vec<String> = f.columns()
.map(|col| {
match col {
Column::Int32 { name, data: _data } => name,
Column::Int64 { name, data: _data } => name,
Column::Float { name, data: _data } => name,
Column::Double { name, data: _data } => name,
}
})
.collect();
assert_eq!(column_names,
vec!["intcol".to_string(), "floatcol".to_string(), "doublecol".to_string()]);
}
// Writing data
#[test]
fn writing_header_keywords() {
let tdir = tempdir::TempDir::new("fitsio-").unwrap();
let tdir_path = tdir.path();
let filename = tdir_path.join("test.fits");
// Closure ensures file is closed properly
{
let f = FitsFile::create(filename.to_str().unwrap()).unwrap();
f.write_key("FOO", 1i64).unwrap();
f.write_key("BAR", "baz".to_string()).unwrap();
}
FitsFile::open(filename.to_str().unwrap())
.map(|f| {
assert_eq!(f.read_key::<i64>("FOO").unwrap(), 1);
assert_eq!(f.read_key::<String>("BAR").unwrap(), "baz".to_string());
})
.unwrap();
}
}
|
pub fn wiggle_sort(nums: &mut Vec<i32>) {
nums.sort();
let n = nums.len();
let mut result = vec![0; n];
if n % 2 == 0 {
for i in 0..n / 2 {
result[n - 2 - 2 * i] = nums[i];
result[n - 1 - 2 * i] = nums[n / 2 + i];
}
} else {
for i in 0..n / 2 {
result[n - 1 - 2 * i] = nums[i];
result[n - 2 - 2 * i] = nums[n / 2 + i + 1];
}
result[0] = nums[n / 2];
}
for i in 0..n {
nums[i] = result[i];
}
} |
use sdl2::render::{Texture, TextureCreator, Canvas};
use sdl2::video::{WindowContext, Window};
use sdl2::pixels::{PixelFormatEnum};
use crate::nes::nes::NES;
use crate::gfx::render;
use super::window::RenderableWindow;
use crate::ppu::ppu;
use crate::ppu::ppu::{FRAMEBUFFER_WIDTH, FRAMEBUFFER_HEIGHT};
use crate::gfx::palette;
pub struct FramebufferWindow<'a> {
width: u32,
height: u32,
texture: Texture<'a>,
}
impl<'a> FramebufferWindow<'a> {
pub fn new(texture_creator: &'a TextureCreator<WindowContext>,
width: u32,
height: u32) -> FramebufferWindow {
let texture = texture_creator
.create_texture_streaming(PixelFormatEnum::RGB24,
ppu::FRAMEBUFFER_WIDTH as u32,
ppu::FRAMEBUFFER_HEIGHT as u32).unwrap();
FramebufferWindow { width, height, texture }
}
fn _update_texture(&mut self, nes: &NES) -> Result<(), String> {
let pixel_data = nes.get_ppu().get_framebuffer();
let mut texture_rgb_data = [0 as u8; (FRAMEBUFFER_WIDTH * FRAMEBUFFER_HEIGHT * 3) as usize];
for (i, val) in pixel_data.iter().enumerate() {
let (r, g, b) = palette::NTSC_2C02[*val as usize];
texture_rgb_data[i * 3] = r;
texture_rgb_data[i * 3 + 1] = g;
texture_rgb_data[i * 3 + 2] = b;
}
self.texture.update(None, &texture_rgb_data, (FRAMEBUFFER_WIDTH * 3) as usize).map_err(|e| e.to_string())?;
Ok(())
}
}
impl<'a> RenderableWindow for FramebufferWindow<'a> {
fn render(&mut self,
canvas: &mut Canvas<Window>,
x: i32,
y: i32,
nes: &NES) -> Result<(), String> {
self._update_texture(nes);
render::textured_window(canvas, x, y, self.width, self.height, &self.texture)?;
Ok(())
}
}
|
use crate::utils::asserts::meta::assert_meta;
use crate::utils::asserts::peer::{assert_peer_data, test_peer_array};
use crate::utils::mockito_helpers::{mock_client, mock_http_request};
use arkecosystem_client::api::models::peer::Peer;
use arkecosystem_client::api::models::shared::Response;
use arkecosystem_client::Connection;
use serde_json::{from_str, Value};
use std::borrow::Borrow;
#[tokio::test]
async fn test_all() {
let (_mock, body) = mock_http_request("peers");
{
let mut client = mock_client();
let actual = client.peers.all().await.unwrap();
let expected: Value = from_str(&body).unwrap();
assert_meta(actual.meta.unwrap(), expected["meta"].borrow());
test_peer_array(actual.data, expected);
}
}
#[tokio::test]
async fn test_all_params() {
// TODO use a different fixture to check that uses query strings
let (_mock, body) = mock_http_request("peers");
{
let mut client = mock_client();
let params = [("limit", "20")].iter();
let actual = client.peers.all_params(params).await.unwrap();
let expected: Value = from_str(&body).unwrap();
assert_meta(actual.meta.unwrap(), expected["meta"].borrow());
test_peer_array(actual.data, expected);
}
}
#[tokio::test]
async fn test_show() {
let (_mock, body) = mock_http_request("peers/dummy");
{
let mut client: Connection = mock_client();
let actual: Response<Peer> = client.peers.show("dummy").await.unwrap();
let expected: Value = from_str(&body).unwrap();
assert_peer_data(&actual.data, &expected["data"]);
}
}
|
use std::cell::RefCell;
use std::rc::Rc;
pub trait Wrap<T> {
fn wrap(t: T) -> Self;
}
pub type SharedMut<T> = Rc<RefCell<T>>;
impl<T> Wrap<T> for SharedMut<T> {
fn wrap(t: T) -> Self {
Rc::new(RefCell::new(t))
}
}
pub use std::f64::consts::PI;
pub use std::ops;
pub type Time = f32;
/// A type alias for internal floating point precision.
pub type Float = f64;
#[derive(Debug, Clone, Copy, PartialEq)]
/// A tuple struct that represents a single stereo frame.
pub struct Stereo(pub Float, pub Float);
/// Overload addition for `Stereo` frame.
impl ops::Add<Stereo> for Stereo {
type Output = Stereo;
fn add(self, rhs: Stereo) -> Self {
Stereo(self.0 + rhs.0, self.1 + rhs.1)
}
}
impl ops::Add<Float> for Stereo {
type Output = Stereo;
fn add(self, rhs: Float) -> Self {
Stereo(self.0 + rhs, self.1 + rhs)
}
}
impl ops::AddAssign<Stereo> for Stereo {
fn add_assign(&mut self, rhs: Stereo) {
self.0 += rhs.0;
self.1 += rhs.1;
}
}
/// Overload subtraction for `Stereo` frame.
impl ops::Sub<Stereo> for Stereo {
type Output = Stereo;
fn sub(self, rhs: Stereo) -> Self {
Stereo(self.0 - rhs.0, self.1 - rhs.1)
}
}
impl ops::Sub<Float> for Stereo {
type Output = Stereo;
fn sub(self, rhs: Float) -> Self {
Stereo(self.0 - rhs, self.1 - rhs)
}
}
impl ops::SubAssign<Stereo> for Stereo {
fn sub_assign(&mut self, rhs: Stereo) {
self.0 -= rhs.0;
self.1 -= rhs.1;
}
}
/// Overload multiplication for `Stereo` frame.
impl ops::Mul<Stereo> for Stereo {
type Output = Stereo;
fn mul(self, rhs: Stereo) -> Self {
Stereo(self.0 * rhs.0, self.1 * rhs.1)
}
}
impl ops::MulAssign<Stereo> for Stereo {
fn mul_assign(&mut self, rhs: Stereo) {
self.0 *= rhs.0;
self.1 *= rhs.1;
}
}
/// Overload multiplication for `Stereo` frame with scalar.
impl ops::Mul<Float> for Stereo {
type Output = Stereo;
fn mul(self, rhs: Float) -> Self {
Stereo(self.0 * rhs, self.1 * rhs)
}
}
impl ops::MulAssign<Float> for Stereo {
fn mul_assign(&mut self, rhs: Float) {
self.0 *= rhs;
self.1 *= rhs;
}
}
impl ops::Div<Float> for Stereo {
type Output = Stereo;
fn div(self, rhs: Float) -> Self {
Stereo(self.0 / rhs, self.1 / rhs)
}
}
impl ops::Div<Stereo> for Stereo {
type Output = Stereo;
fn div(self, rhs: Stereo) -> Self {
Stereo(self.0 / rhs.0, self.1 / rhs.1)
}
}
impl Default for Stereo {
fn default() -> Self {
Stereo(0.0, 0.0)
}
}
#[test]
fn test_stereo() {
// It would be better to make a relative equality check with some error epsilon. But
// therefore `Sub` and `abs()` had to be implemented for `Stereo`.
let (a, b) = (Stereo(1.0, 2.0), Stereo(2.0, 4.0));
assert_eq!(a + b, Stereo(3.0, 6.0));
assert_eq!(a - b, Stereo(-1.0, -2.0));
assert_eq!(b - a, Stereo(1.0, 2.0));
assert_eq!(a * b, Stereo(2.0, 8.0));
assert_eq!(a * 3.0, Stereo(3.0, 6.0));
let mut x = Stereo::default();
x += Stereo(5.0, 10.0);
assert_eq!(x, Stereo(5.0, 10.0));
x *= 0.1;
assert_eq!(x, Stereo(0.5, 1.0));
}
pub const MINUS_THREE_DB: Float = 0.7079457843841379;
/// Defines conversion methods from a plain `1/x` power ratio into db and vice versa.
pub trait Db {
/// Returns the ratio in dB.
///
/// Example:
/// `assert!(Db::to_rb(0.0001), -80.0)`
fn to_db(ratio: Float) -> Float;
/// Returns the `1/x` ratio from the given dB value.
fn from_db(db: Float) -> Float;
}
impl Db for Float {
fn to_db(ratio: Float) -> Float {
20.0 * ratio.log10()
}
fn from_db(db: Float) -> Float {
let ten: Float = 10.0;
ten.powf(db / 20.0)
}
}
#[test]
fn test_conversion() {
assert_relative_eq!(-80.0, Float::to_db(0.0001));
assert_relative_eq!(0.0, Float::to_db(1.0));
assert_relative_eq!(6.0, Float::to_db(2.0), epsilon = 0.03);
assert_relative_eq!(MINUS_THREE_DB * MINUS_THREE_DB, Float::from_db(-6.0));
assert_relative_eq!(MINUS_THREE_DB, Float::from_db(-3.0));
}
|
pub mod autotransport;
mod serversenteventstransport;
mod longpollingtransport;
pub mod clienttransport;
pub mod httpbasedtransport;
|
/// An enum to represent all characters in the DevanagariExtended block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum DevanagariExtended {
/// \u{a8e0}: '꣠'
CombiningDevanagariDigitZero,
/// \u{a8e1}: '꣡'
CombiningDevanagariDigitOne,
/// \u{a8e2}: '꣢'
CombiningDevanagariDigitTwo,
/// \u{a8e3}: '꣣'
CombiningDevanagariDigitThree,
/// \u{a8e4}: '꣤'
CombiningDevanagariDigitFour,
/// \u{a8e5}: '꣥'
CombiningDevanagariDigitFive,
/// \u{a8e6}: '꣦'
CombiningDevanagariDigitSix,
/// \u{a8e7}: '꣧'
CombiningDevanagariDigitSeven,
/// \u{a8e8}: '꣨'
CombiningDevanagariDigitEight,
/// \u{a8e9}: '꣩'
CombiningDevanagariDigitNine,
/// \u{a8ea}: '꣪'
CombiningDevanagariLetterA,
/// \u{a8eb}: '꣫'
CombiningDevanagariLetterU,
/// \u{a8ec}: '꣬'
CombiningDevanagariLetterKa,
/// \u{a8ed}: '꣭'
CombiningDevanagariLetterNa,
/// \u{a8ee}: '꣮'
CombiningDevanagariLetterPa,
/// \u{a8ef}: '꣯'
CombiningDevanagariLetterRa,
/// \u{a8f0}: '꣰'
CombiningDevanagariLetterVi,
/// \u{a8f1}: '꣱'
CombiningDevanagariSignAvagraha,
/// \u{a8f2}: 'ꣲ'
DevanagariSignSpacingCandrabindu,
/// \u{a8f3}: 'ꣳ'
DevanagariSignCandrabinduVirama,
/// \u{a8f4}: 'ꣴ'
DevanagariSignDoubleCandrabinduVirama,
/// \u{a8f5}: 'ꣵ'
DevanagariSignCandrabinduTwo,
/// \u{a8f6}: 'ꣶ'
DevanagariSignCandrabinduThree,
/// \u{a8f7}: 'ꣷ'
DevanagariSignCandrabinduAvagraha,
/// \u{a8f8}: '꣸'
DevanagariSignPushpika,
/// \u{a8f9}: '꣹'
DevanagariGapFiller,
/// \u{a8fa}: '꣺'
DevanagariCaret,
/// \u{a8fb}: 'ꣻ'
DevanagariHeadstroke,
/// \u{a8fc}: '꣼'
DevanagariSignSiddham,
/// \u{a8fd}: 'ꣽ'
DevanagariJainOm,
/// \u{a8fe}: 'ꣾ'
DevanagariLetterAy,
}
impl Into<char> for DevanagariExtended {
fn into(self) -> char {
match self {
DevanagariExtended::CombiningDevanagariDigitZero => '꣠',
DevanagariExtended::CombiningDevanagariDigitOne => '꣡',
DevanagariExtended::CombiningDevanagariDigitTwo => '꣢',
DevanagariExtended::CombiningDevanagariDigitThree => '꣣',
DevanagariExtended::CombiningDevanagariDigitFour => '꣤',
DevanagariExtended::CombiningDevanagariDigitFive => '꣥',
DevanagariExtended::CombiningDevanagariDigitSix => '꣦',
DevanagariExtended::CombiningDevanagariDigitSeven => '꣧',
DevanagariExtended::CombiningDevanagariDigitEight => '꣨',
DevanagariExtended::CombiningDevanagariDigitNine => '꣩',
DevanagariExtended::CombiningDevanagariLetterA => '꣪',
DevanagariExtended::CombiningDevanagariLetterU => '꣫',
DevanagariExtended::CombiningDevanagariLetterKa => '꣬',
DevanagariExtended::CombiningDevanagariLetterNa => '꣭',
DevanagariExtended::CombiningDevanagariLetterPa => '꣮',
DevanagariExtended::CombiningDevanagariLetterRa => '꣯',
DevanagariExtended::CombiningDevanagariLetterVi => '꣰',
DevanagariExtended::CombiningDevanagariSignAvagraha => '꣱',
DevanagariExtended::DevanagariSignSpacingCandrabindu => 'ꣲ',
DevanagariExtended::DevanagariSignCandrabinduVirama => 'ꣳ',
DevanagariExtended::DevanagariSignDoubleCandrabinduVirama => 'ꣴ',
DevanagariExtended::DevanagariSignCandrabinduTwo => 'ꣵ',
DevanagariExtended::DevanagariSignCandrabinduThree => 'ꣶ',
DevanagariExtended::DevanagariSignCandrabinduAvagraha => 'ꣷ',
DevanagariExtended::DevanagariSignPushpika => '꣸',
DevanagariExtended::DevanagariGapFiller => '꣹',
DevanagariExtended::DevanagariCaret => '꣺',
DevanagariExtended::DevanagariHeadstroke => 'ꣻ',
DevanagariExtended::DevanagariSignSiddham => '꣼',
DevanagariExtended::DevanagariJainOm => 'ꣽ',
DevanagariExtended::DevanagariLetterAy => 'ꣾ',
}
}
}
impl std::convert::TryFrom<char> for DevanagariExtended {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'꣠' => Ok(DevanagariExtended::CombiningDevanagariDigitZero),
'꣡' => Ok(DevanagariExtended::CombiningDevanagariDigitOne),
'꣢' => Ok(DevanagariExtended::CombiningDevanagariDigitTwo),
'꣣' => Ok(DevanagariExtended::CombiningDevanagariDigitThree),
'꣤' => Ok(DevanagariExtended::CombiningDevanagariDigitFour),
'꣥' => Ok(DevanagariExtended::CombiningDevanagariDigitFive),
'꣦' => Ok(DevanagariExtended::CombiningDevanagariDigitSix),
'꣧' => Ok(DevanagariExtended::CombiningDevanagariDigitSeven),
'꣨' => Ok(DevanagariExtended::CombiningDevanagariDigitEight),
'꣩' => Ok(DevanagariExtended::CombiningDevanagariDigitNine),
'꣪' => Ok(DevanagariExtended::CombiningDevanagariLetterA),
'꣫' => Ok(DevanagariExtended::CombiningDevanagariLetterU),
'꣬' => Ok(DevanagariExtended::CombiningDevanagariLetterKa),
'꣭' => Ok(DevanagariExtended::CombiningDevanagariLetterNa),
'꣮' => Ok(DevanagariExtended::CombiningDevanagariLetterPa),
'꣯' => Ok(DevanagariExtended::CombiningDevanagariLetterRa),
'꣰' => Ok(DevanagariExtended::CombiningDevanagariLetterVi),
'꣱' => Ok(DevanagariExtended::CombiningDevanagariSignAvagraha),
'ꣲ' => Ok(DevanagariExtended::DevanagariSignSpacingCandrabindu),
'ꣳ' => Ok(DevanagariExtended::DevanagariSignCandrabinduVirama),
'ꣴ' => Ok(DevanagariExtended::DevanagariSignDoubleCandrabinduVirama),
'ꣵ' => Ok(DevanagariExtended::DevanagariSignCandrabinduTwo),
'ꣶ' => Ok(DevanagariExtended::DevanagariSignCandrabinduThree),
'ꣷ' => Ok(DevanagariExtended::DevanagariSignCandrabinduAvagraha),
'꣸' => Ok(DevanagariExtended::DevanagariSignPushpika),
'꣹' => Ok(DevanagariExtended::DevanagariGapFiller),
'꣺' => Ok(DevanagariExtended::DevanagariCaret),
'ꣻ' => Ok(DevanagariExtended::DevanagariHeadstroke),
'꣼' => Ok(DevanagariExtended::DevanagariSignSiddham),
'ꣽ' => Ok(DevanagariExtended::DevanagariJainOm),
'ꣾ' => Ok(DevanagariExtended::DevanagariLetterAy),
_ => Err(()),
}
}
}
impl Into<u32> for DevanagariExtended {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for DevanagariExtended {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for DevanagariExtended {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl DevanagariExtended {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
DevanagariExtended::CombiningDevanagariDigitZero
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("DevanagariExtended{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
// The heart of the Multi-sig orchestrator. All messages will be sent, received, and
// all actions triggered via event-driven methods within this module.
// SO FAR:
// Most of this is copy and pasted from the guide: https://ws-rs.org/guide
use ws::{listen, Handler, Sender, Result, Message, Handshake, CloseCode, Error};
use std::rc::Rc;
use std::cell::Cell;
struct Server {
out: Sender,
}
type Xdr = String;
type Account_ID = String;
#[derive(Debug)]
struct TxObj {
xdr: Xdr,
req_sigs: u8,
cur_sigs: u8,
req_weight: u8,
cur_weight: u8,
}
#[derive(Debug)]
enum SocketMessageData {
ACCOUNT_ID(Account_ID),
TX_OBJ(TxObj),
XDR(Xdr),
TX_OBJ_ARRAY(Vec<TxObj>),
}
#[derive(Debug)]
enum SocketMessageHeader {
CONN,
RE_INIT,
DISCONN,
NEW_TX,
SIG_TX,
}
#[derive(Debug)]
struct SocketMessage {
header: SocketMessageHeader,
data: SocketMessageData,
}
fn parse_message(msg: &str) {
}
#[cfg(test)]
mod test_parse_message {
#[test]
fn it_parses_a_message() {
assert_eq!(2 + 2, 4);
}
}
impl Handler for Server {
fn on_open(&mut self, _: Handshake) -> Result<()> {
// We have a new connection, so we increment the connection counter
println!("New connection");
Ok(())
}
/*
* Message format
*
* [MESSAGE_HEADER]: DATA
*
*/
fn on_message(&mut self, msg: Message) -> Result<()> {
// Print out the received message
println!("Message: {}", msg);
// Parse message
// TODO: catch errors on unexpected messages that don't unwrap
parse_message(msg.as_text().unwrap());
// Act on parsed message
// Echo the message back
self.out.send(msg)
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
match code {
CloseCode::Normal => println!("The client is done with the connection."),
CloseCode::Away => println!("The client is leaving the site."),
CloseCode::Abnormal => println!(
"Closing handshake failed! Unable to obtain closing status from client."),
_ => println!("The client encountered an error: {}", reason),
}
}
fn on_error(&mut self, err: Error) {
println!("The server encountered an error: {:?}", err);
}
}
pub fn start() {
// listen on port 3012 for new messages
listen("127.0.0.1:3012", |out| { Server { out: out } }).unwrap()
} |
use std::time::Duration;
use std::io::Write;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use super::super::config::{Tokens, Config, ClientRef};
use super::super::results::{BearerResult, BearerError};
use super::oauth2client;
fn url_encode(to_encode: &str) -> String {
to_encode.as_bytes().iter().fold(String::new(), |mut out, &b| {
match b as char {
// unreserved:
'A'...'Z' | 'a'...'z' | '0'...'9' | '-' | '.' | '_' | '~' => out.push(b as char),
' ' => out.push('+'),
ch => out.push_str(format!("%{:02X}", ch as usize).as_str()),
};
out
})
}
struct Http<'a> {
port: usize,
client: ClientRef<'a>,
tokens: Option<BearerResult<Tokens>>,
}
impl<'a> Http<'a> {
pub fn new(config: &'a Config, port: usize) -> Self {
Http {
port: port,
client: config.client(),
tokens: None,
}
}
pub fn fetch_tokens(&mut self) -> BearerResult<Tokens> {
let listener = TcpListener::bind(self.addr().as_str()).unwrap();
while self.tokens.is_none() {
let stream = listener.incoming().next().unwrap();
let mut stream = stream.unwrap();
self.handle_client(&mut stream);
}
let tokens = self.tokens.as_ref().unwrap();
match tokens.as_ref() {
Ok(tokens) => Ok(tokens.clone()),
Err(err) => Err(err.clone()),
}
}
fn handle_client(&mut self, stream: &mut TcpStream) {
stream.set_read_timeout(Some(Duration::new(15, 0))).unwrap();
let mut buffer = [0; 4096];
stream.read(&mut buffer[..]).unwrap();
let httpquery = String::from_utf8_lossy(&buffer);
// debug!("{}", string);
// We don't bother the header
let httpquery = httpquery.lines().next().unwrap();
// debug!("{}", httpquery);
let mut httpquery = httpquery.split_whitespace();
let verb = httpquery.next().unwrap();
if verb != "GET" {
self.handle_405(stream);
return;
}
let path = httpquery.next().unwrap();
let mut path = path.split("?");
let pathinfo = path.next().unwrap();
if pathinfo != "/callback" {
self.handle_404(stream);
return;
}
let querystring = path.next();
if querystring.is_none() {
self.handle_302(stream);
return;
}
let querystring = querystring.unwrap().split("&");
for param in querystring {
let mut param = param.split("=");
let key = param.next();
let value = param.next().unwrap();
match key {
Some("error") => self.handle_200_error(stream, value),
Some("code") => self.handle_200_code(stream, value),
_ => {}
}
}
}
fn handle_404(&mut self, stream: &mut TcpStream) {
stream.write(b"HTTP/1.1 404 Not Found
Connection: close
Server: bearer-rs
Content-Type: text/plain;charset=UTF-8
Content-Length: 10
Not Found
")
.unwrap();
}
fn handle_405(&mut self, stream: &mut TcpStream) {
stream.write(b"HTTP/1.1 405 Method Not Allowed
Connection: close
Server: bearer-rs
Content-Type: text/plain;charset=UTF-8
Content-Length: 19
Method Not Allowed
")
.unwrap();
}
fn handle_302(&mut self, stream: &mut TcpStream) {
let mut location = format!("{}?response_type=code&client_id={}&redirect_uri={}",
self.client.authorize_url,
url_encode(self.client.client_id),
url_encode(self.redirect_uri().as_ref()));
if let Some(scope) = self.client.scope {
location.push_str("&scope=");
location.push_str(scope);
}
debug!("Redirecting to {}", location);
let resp = format!("HTTP/1.1 302 Moved Temporarily
Connection: close
Server: bearer-rs
Location: {}
",
location);
stream.write(resp.as_bytes()).unwrap();
}
fn handle_200_code(&mut self, stream: &mut TcpStream, code: &str) {
debug!("OAuth2.0 Authorization Code received, fetching tokens");
let tokens = oauth2client::from_authcode(&self.client, code, self.redirect_uri().as_str());
let content = match tokens {
Ok(res) => {
self.tokens = Some(Ok(res));
"Token received".to_string()
}
Err(err) => format!("Error while fetching token: {:?}", err),
};
let resp = format!("HTTP/1.1 200 Ok
Connection: close
Server: bearer-rs
Content-Type: text/plain;charset=UTF-8
Content-Length: {}
{}",
content.len(),
content);
stream.write(resp.as_bytes()).unwrap();
}
fn handle_200_error(&mut self, stream: &mut TcpStream, error: &str) {
let content = format!("No Tokens returns. OAuth2.0 Authorization Server Error: {}",
error);
let resp = format!("HTTP/1.1 200 Ok
Connection: close
Server: bearer-rs
Content-Type: text/plain;charset=UTF-8
Content-Length: {}
{}",
content.len(),
content);
stream.write(resp.as_bytes()).unwrap();
self.tokens = Some(Err(BearerError::OAuth2Error(content)));
}
fn addr(&self) -> String {
return format!("localhost:{}", self.port);
}
fn redirect_uri(&self) -> String {
return format!("http://localhost:{}/callback", self.port);
}
}
pub fn get_tokens<'a>(config: &'a Config, port: usize) -> BearerResult<Tokens> {
let mut server: Http<'a> = Http::new(config, port);
let token = server.fetch_tokens()?;
Ok(token)
}
#[cfg(test)]
mod tests {
use std::thread;
use std::time;
use std::net::TcpStream;
use rand::{thread_rng, Rng};
use super::*;
use super::super::super::results::BearerError;
#[test]
fn test_url_encode() {
assert_eq!(url_encode("The éêè !"), "The+%C3%A9%C3%AA%C3%A8+%21")
}
#[test]
fn test_get_tokens_ok() {
let mut rng = thread_rng();
let authorization_server_port: usize = rng.gen_range(3000, 9000);
let client_port: usize = rng.gen_range(3000, 9000);
let httphandler = thread::spawn(move || {
let authorize = format!("http://127.0.0.1:{}/authorize", authorization_server_port);
let token = format!("http://127.0.0.1:{}/token", authorization_server_port);
let conf = Config::new("/tmp",
"client_name",
"provider",
authorize.as_str(),
token.as_str(),
"12e26",
"secret",
None)
.unwrap();
let tokens = get_tokens(&conf, client_port);
assert_eq!(tokens.is_ok(), true);
let tokens = tokens.unwrap();
assert_eq!(tokens.access_token, "atok");
assert_eq!(tokens.refresh_token.unwrap(), "rtok");
// assert_eq!(tokens.expires_at, "TIME DEPENDANT VALUE");
});
let dur = time::Duration::from_millis(700);
thread::sleep(dur);
let mut client_addr = format!("127.0.0.1:{}", client_port);
let client = TcpStream::connect(client_addr.as_str());
let mut client = if client.is_err() {
client_addr = format!("[::1]:{}", client_port);
let client = TcpStream::connect(client_addr.as_str());
client.unwrap()
}
else {
client.unwrap()
};
client.write_all(b"GET /callback HTTP/1.1\r\n\r\n").unwrap();
let mut response = String::new();
client.read_to_string(&mut response).unwrap();
assert_eq!(response, format!(r#"HTTP/1.1 302 Moved Temporarily
Connection: close
Server: bearer-rs
Location: http://127.0.0.1:{}/authorize?response_type=code&client_id=12e26&redirect_uri=http%3A%2F%2Flocalhost%3A{}%2Fcallback
"#, authorization_server_port, client_port));
let authservhandler = thread::spawn(move || {
let authorization_server =
TcpListener::bind(format!("127.0.0.1:{}", authorization_server_port)).unwrap();
let stream = authorization_server.incoming().next().unwrap();
let mut stream = stream.unwrap();
let tokens = r#"{"access_token": "atok",
"expires_in": 42,
"refresh_token": "rtok"}"#;
let content_len = format!("Content-Length: {}", tokens.len());
let resp = vec!["HTTP/1.0 200 Ok",
"Content-Type: application/json",
content_len.as_str(),
"",
tokens];
let resp = resp.join("\r\n");
stream.write(resp.as_bytes()).unwrap();
});
let dur = time::Duration::from_millis(700);
thread::sleep(dur);
let mut client = TcpStream::connect(client_addr).unwrap();
client.write_all(b"GET /callback?code=abc HTTP/1.1\r\n\r\n").unwrap();
let mut response = String::new();
client.read_to_string(&mut response).unwrap();
assert_eq!(response,
r#"HTTP/1.1 200 Ok
Connection: close
Server: bearer-rs
Content-Type: text/plain;charset=UTF-8
Content-Length: 14
Token received"#);
// ensure threads are terminated
httphandler.join().unwrap();
authservhandler.join().unwrap();
}
#[test]
fn test_get_tokens_error() {
let mut rng = thread_rng();
let client_port: usize = rng.gen_range(3000, 9000);
let httphandler = thread::spawn(move || {
let conf = Config::from_file("src/tests/conf", "dummy").unwrap();
let tokens = get_tokens(&conf, client_port);
assert_eq!(tokens.is_err(), true);
let err = tokens.unwrap_err();
assert_eq!(err, BearerError::OAuth2Error("".to_string()));
});
let dur = time::Duration::from_millis(700);
thread::sleep(dur);
let client_addr = format!("127.0.0.1:{}", client_port);
let client = TcpStream::connect(client_addr.as_str());
let mut client = if client.is_err() {
let client_addr = format!("[::1]:{}", client_port);
let client = TcpStream::connect(client_addr.as_str());
client.unwrap()
}
else {
client.unwrap()
};
client.write_all(b"GET /callback?error=server_error&error_description=internal+server+error HTTP/1.1\r\n\r\n").unwrap();
let mut response = String::new();
client.read_to_string(&mut response).unwrap();
assert_eq!(response,
r#"HTTP/1.1 200 Ok
Connection: close
Server: bearer-rs
Content-Type: text/plain;charset=UTF-8
Content-Length: 68
No Tokens returns. OAuth2.0 Authorization Server Error: server_error"#);
// ensure threads are terminated
httphandler.join().unwrap();
}
}
|
use std::fs;
use std::collections::HashMap;
fn main() {
let lines : Vec<String> = fs::read_to_string("./in.in").expect("Smth went wrong smh").split("\n").map(|s| s.to_owned()).collect();
part1(lines.clone());
part2(lines);
}
fn part1(n : Vec<String>) {
let mut valid : u32 = 0;
for i in n {
let parts : Vec<String> = i.split(": ").map(|s| s.to_owned()).collect();
let letter : char = parts[0].split(" ").collect::<Vec<&str>>()[1].to_owned().chars().collect::<Vec<char>>()[0];
let policy : Vec<u32> = parts[0].split(" ").collect::<Vec<&str>>()[0].split("-").map(|s| s.parse().unwrap()).collect();
let mut count : u32 = 0;
for c in parts[1].chars().collect::<Vec<char>>() {
if c == letter { count += 1}
}
if count >= policy[0] && count <= policy[1] {
valid += 1;
}
}
println!("{}", valid);
}
fn part2(n : Vec<String>) {
let mut valid : u32 = 0;
for i in n {
let parts : Vec<String> = i.split(": ").map(|s| s.to_owned()).collect();
let letter : char = parts[0].split(" ").collect::<Vec<&str>>()[1].to_owned().chars().collect::<Vec<char>>()[0];
let policy : Vec<u32> = parts[0].split(" ").collect::<Vec<&str>>()[0].split("-").map(|s| s.parse().unwrap()).collect();
let chars = parts[1].chars().collect::<Vec<char>>();
let mut pol_1 : bool = false;
let mut pol_2 : bool = false;
for i in 0..chars.len() {
if policy[0] - 1 == i as u32 && chars[i] == letter {
pol_1 = true;
} else if policy[1] - 1 == i as u32 && chars[i] == letter {
pol_2 = true;
}
}
if pol_1 && pol_2 {
} else if pol_1 {
valid += 1;
} else if pol_2 {
valid += 1;
}
}
println!("{}", valid);
}
|
use graphics::textures::TextureId;
#[derive(Copy, Clone)]
pub struct Sprite {
pub sprite: TextureId,
pub center: [f32; 2],
pub uv_rect: [f32; 4],
pub layer: f32,
pub flip_x: bool,
}
impl Sprite {
pub fn new(sprite: TextureId) -> Self {
Sprite {
sprite,
center: [0.5, 0.5],
uv_rect: [0.0, 0.0, 1.0, 1.0],
layer: 2.0,
flip_x: false,
}
}
}
|
use super::*;
/**
Wraps a reference to a `String` representation of some type
The `String` can be accessed as if it were the type.
An `Adapter` can be made for any type that implements `FromStr` and `Display`.
An `Adapter` must be dropped before the `String` can be accessed again.
# Example
```
use kai::*;
// A `Vec` of number strings
let mut nums: Vec<String> = vec![
"4".into(),
"1".into(),
"-1".into(),
];
// Iterate over `Adapters` that wrap the number strings
// The `Adapter`s can be modified as if they are numbers
for mut n in nums.iter_mut().filter_map(|s| Adapter::<i32>::from(s).ok()) {
*n += 2;
*n *= 2;
}
assert_eq!(
vec!["12".to_string(), "6".into(), "2".into()],
nums,
);
```
*/
pub struct Adapter<'a, T>
where
T: FromStr + Display,
{
string: &'a mut String,
temp: T,
}
impl<'a, T> Adapter<'a, T>
where
T: FromStr + Display,
{
/// Create a new `Adapter` from a `String`
pub fn from(string: &'a mut String) -> Result<Adapter<'a, T>, T::Err> {
string.parse().map(move |temp| Adapter { string, temp })
}
/**
Force a drop, returning ownership to the string
This function only needs to be called if you want access to the string
before the `Adapter` would normally be dropped.
*/
pub fn finish(self) {}
}
impl<'a, T> Deref for Adapter<'a, T>
where
T: FromStr + Display,
{
type Target = T;
fn deref(&self) -> &Self::Target {
&self.temp
}
}
impl<'a, T> DerefMut for Adapter<'a, T>
where
T: FromStr + Display,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.temp
}
}
impl<'a, T> Drop for Adapter<'a, T>
where
T: FromStr + Display,
{
fn drop(&mut self) {
*self.string = self.temp.to_string()
}
}
impl<'a, T> Debug for Adapter<'a, T>
where
T: FromStr + Display + Debug,
{
fn fmt(&self, f: &mut Formatter) -> FmtResult {
<T as Debug>::fmt(&self.temp, f)
}
}
impl<'a, T> Display for Adapter<'a, T>
where
T: FromStr + Display,
{
fn fmt(&self, f: &mut Formatter) -> FmtResult {
<T as Display>::fmt(&self.temp, f)
}
}
impl<'a, T> AsRef<T> for Adapter<'a, T>
where
T: FromStr + Display,
{
fn as_ref(&self) -> &T {
&self.temp
}
}
impl<'a, T> std::borrow::Borrow<T> for Adapter<'a, T>
where
T: FromStr + Display,
{
fn borrow(&self) -> &T {
&self.temp
}
}
|
/// Convenience wrapper for making simple get calls.
macro_rules! cci_get_call {
($function:ident($($arg0:expr,)+ _: $type:ty $(, $arg1:expr)*$(,)*)) => ({
let mut value: $type = unsafe { ::std::mem::uninitialized() };
let error = unsafe { $function($($arg0,)* &mut value, $($arg1),* ) };
if error == ErrorCode::OK { Ok(value) } else { Err(error) }
})
}
/// Convenience wrapper for making simple get calls, ignoring the ErrorCode.
macro_rules! cci_get_only {
($function:ident($($arg0:expr,)+ _: $type:ty $(, $arg1:expr)*$(,)*)) => ({
let mut value: $type = Default::default();
unsafe { $function($($arg0,)* &mut value, $($arg1,)*) };
value
})
}
macro_rules! impl_binary_fmt {
($type:ty) => {
impl ::std::fmt::Binary for $type {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
impl ::std::fmt::Octal for $type {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
impl ::std::fmt::LowerHex for $type {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
impl ::std::fmt::UpperHex for $type {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
};
}
|
/*=======================================
* @FileName: 18四数之和.rs
* @Description:
* @Author: TonyLaw
* @Date: 2021-09-01 23:10:39 Wednesday
* @Copyright: © 2021 TonyLaw. All Rights Reserved.
=========================================*/
/*=======================================
(题目难度:中等)
给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] :
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
提示:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
=========================================*/
struct Solution;
impl Solution {
pub fn four_sum(mut nums: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
let len = nums.len();
if len < 4 {return vec![]};
let mut ret = vec![];
nums.sort_unstable();
for i in 0..len - 3 {
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target { break; } //剪枝
if nums[i] + nums[len - 3] + nums[len - 2] + nums[len - 1] < target { continue; } // 剪枝
if i > 0 && nums[i] == nums[i - 1] { continue; } // 剪枝
for j in i+1..len-2 {
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target { break; } // 剪枝
if nums[i] + nums[j] + nums[len - 2] + nums[len - 1] < target { continue; } // 剪枝
if j > i + 1 && nums[j] == nums[j - 1] {continue; } // 剪枝
let (mut k, mut q) = (j + 1, len - 1);
loop {
if k >= q { break; }
if nums[i] + nums[j] + nums[k] + nums[k + 1] > target { break; } // 剪枝
if nums[i] + nums[j] + nums[q - 1] + nums[q] < target { break; } // 剪枝
if k > j + 1 && nums[k] == nums[k - 1] { k += 1; continue; } // 剪枝
if q > len - 1 && nums[q] == nums[k + 1] { q -= 1; continue; } // 剪枝
let sum = nums[i] + nums[j] + nums[k] + nums[q];
if sum == target {
ret.push(vec![nums[i], nums[j], nums[k], nums[q]]);
k += 1;
} else if sum > target {
q -= 1;
} else {
k += 1;
}
}
}
}
return ret
}
}
fn main() {
let l1 = vec![1, 0, -1, 0, -2, 2];
let n1 = 0;
let result = Solution::four_sum(l1, n1);
println!("{:?}", result);
} |
//! Various methods of executing over Falcon IL
use error::*;
use il;
/// Swaps the bytes of an expression (swaps endianness)
pub fn swap_bytes(expr: &il::Expression) -> Result<il::Expression> {
match expr.bits() {
8 => Ok(expr.clone()),
16 => {
// isolate bytes
let b0 = il::Expression::trun(8, expr.clone())?;
let b1 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(8, 16))?)?;
// move to swapped locations
let b0 = il::Expression::shl(
il::Expression::zext(16, b0)?,
il::expr_const(8, 16)
)?;
let b1 = il::Expression::zext(16, b1)?;
Ok(il::Expression::or(b0, b1)?)
}
32 => {
// isolate bytes
let b0 = il::Expression::trun(8, expr.clone())?;
let b1 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(8, 32))?)?;
let b2 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(16, 32))?)?;
let b3 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(24, 32))?)?;
// move to swapped locations
let b0 = il::Expression::shl(
il::Expression::zext(32, b0)?,
il::expr_const(24, 32)
)?;
let b1 = il::Expression::shl(
il::Expression::zext(32, b1)?,
il::expr_const(16, 32)
)?;
let b2 = il::Expression::shl(
il::Expression::zext(32, b2)?,
il::expr_const(8, 32)
)?;
let b3 = il::Expression::zext(32, b3)?;
Ok(il::Expression::or(
il::Expression::or(b0, b1)?,
il::Expression::or(b2, b3)?
)?)
}
64 => {
// isolate bytes
let b0 = il::Expression::trun(8, expr.clone())?;
let b1 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(8, 64))?)?;
let b2 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(16, 64))?)?;
let b3 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(24, 64))?)?;
let b4 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(32, 64))?)?;
let b5 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(40, 64))?)?;
let b6 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(48, 64))?)?;
let b7 = il::Expression::trun(8,
il::Expression::shr(expr.clone(), il::expr_const(56, 64))?)?;
// move to swapped locations
let b0 = il::Expression::shl(
il::Expression::zext(64, b0)?,
il::expr_const(56, 64)
)?;
let b1 = il::Expression::shl(
il::Expression::zext(64, b1)?,
il::expr_const(48, 64)
)?;
let b2 = il::Expression::shl(
il::Expression::zext(64, b2)?,
il::expr_const(40, 64)
)?;
let b3 = il::Expression::shl(
il::Expression::zext(64, b3)?,
il::expr_const(32, 64)
)?;
let b4 = il::Expression::shl(
il::Expression::zext(64, b4)?,
il::expr_const(24, 64)
)?;
let b5 = il::Expression::shl(
il::Expression::zext(64, b5)?,
il::expr_const(16, 64)
)?;
let b6 = il::Expression::shl(
il::Expression::zext(64, b6)?,
il::expr_const(8, 64)
)?;
let b7 = il::Expression::zext(64, b7)?;
Ok(il::Expression::or(
il::Expression::or(
il::Expression::or(b0, b1)?,
il::Expression::or(b2, b3)?
)?,
il::Expression::or(
il::Expression::or(b4, b5)?,
il::Expression::or(b6, b7)?
)?
)?)
},
_ => bail!("invalid bit-length {} for byte_swap", expr.bits())
}
}
/// Takes an `il::Expression` where all terminals are `il::Constants`, and
/// returns an `il::Constant` with the result of the expression.
pub fn constants_expression(expr: &il::Expression) -> Result<il::Constant> {
// shorthand for this function, for internal recursive use
fn ece(expr: &il::Expression) -> Result<il::Constant> {
constants_expression(expr)
}
match *expr {
il::Expression::Scalar(_) => {
bail!("constants_expression called with Scalar terminal")
},
il::Expression::Constant(ref constant) => Ok(constant.clone()),
il::Expression::Add(ref lhs, ref rhs) => {
let r = ece(lhs)?.value() + ece(rhs)?.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Sub(ref lhs, ref rhs) => {
let r = ece(lhs)?.value().wrapping_sub(ece(rhs)?.value());
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Mul(ref lhs, ref rhs) => {
let r = ece(lhs)?.value() * ece(rhs)?.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Divu(ref lhs, ref rhs) => {
let rhs = ece(rhs)?;
if rhs.value() == 0 {
return Err(ErrorKind::Arithmetic("Division by zero".to_string()).into());
}
let r = ece(lhs)?.value() / rhs.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Modu(ref lhs, ref rhs) => {
let rhs = ece(rhs)?;
if rhs.value() == 0 {
return Err(ErrorKind::Arithmetic("Division by zero".to_string()).into());
}
let r = ece(lhs)?.value() % rhs.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Divs(ref lhs, ref rhs) => {
let rhs = ece(rhs)?;
if rhs.value() == 0 {
return Err(ErrorKind::Arithmetic("Division by zero".to_string()).into());
}
let r = (ece(lhs)?.value() as i64) / (rhs.value() as i64);
Ok(il::Constant::new(r as u64, lhs.bits()))
},
il::Expression::Mods(ref lhs, ref rhs) => {
let rhs = ece(rhs)?;
if rhs.value() == 0 {
return Err(ErrorKind::Arithmetic("Division by zero".to_string()).into());
}
let r = (ece(lhs)?.value() as i64) % (rhs.value() as i64);
Ok(il::Constant::new(r as u64, lhs.bits()))
},
il::Expression::And(ref lhs, ref rhs) => {
let r = ece(lhs)?.value() & ece(rhs)?.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Or(ref lhs, ref rhs) => {
let r = ece(lhs)?.value() | ece(rhs)?.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Xor(ref lhs, ref rhs) => {
let r = ece(lhs)?.value() ^ ece(rhs)?.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Shl(ref lhs, ref rhs) => {
let r = ece(lhs)?.value() << ece(rhs)?.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Shr(ref lhs, ref rhs) => {
let r = ece(lhs)?.value() >> ece(rhs)?.value();
Ok(il::Constant::new(r, lhs.bits()))
},
il::Expression::Cmpeq(ref lhs, ref rhs) => {
if ece(lhs)?.value() == ece(rhs)?.value() {
Ok(il::Constant::new(1, 1))
}
else {
Ok(il::Constant::new(0, 1))
}
},
il::Expression::Cmpneq(ref lhs, ref rhs) => {
if ece(lhs)?.value() != ece(rhs)?.value() {
Ok(il::Constant::new(1, 1))
}
else {
Ok(il::Constant::new(0, 1))
}
},
il::Expression::Cmplts(ref lhs, ref rhs) => {
if (ece(lhs)?.value() as i64) < (ece(rhs)?.value() as i64) {
Ok(il::Constant::new(1, 1))
}
else {
Ok(il::Constant::new(0, 1))
}
},
il::Expression::Cmpltu(ref lhs, ref rhs) => {
if ece(lhs)?.value() < ece(rhs)?.value() {
Ok(il::Constant::new(1, 1))
}
else {
Ok(il::Constant::new(0, 1))
}
},
il::Expression::Zext(bits, ref rhs) |
il::Expression::Trun(bits, ref rhs) => {
Ok(il::Constant::new(ece(rhs)?.value(), bits))
},
il::Expression::Sext(bits, ref rhs) => {
let rhs = ece(rhs)?;
if rhs.value() >> (rhs.bits() - 1) == 1 {
let mask = !((1 << rhs.bits()) - 1);
Ok(il::Constant::new(rhs.value() | mask, bits))
}
else {
Ok(il::Constant::new(rhs.value(), bits))
}
}
}
} |
#[doc = "Register `SDCR1` reader"]
pub type R = crate::R<SDCR1_SPEC>;
#[doc = "Register `SDCR1` writer"]
pub type W = crate::W<SDCR1_SPEC>;
#[doc = "Field `NC` reader - Number of column address bits These bits define the number of bits of a column address."]
pub type NC_R = crate::FieldReader;
#[doc = "Field `NC` writer - Number of column address bits These bits define the number of bits of a column address."]
pub type NC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `NR` reader - Number of row address bits These bits define the number of bits of a row address."]
pub type NR_R = crate::FieldReader;
#[doc = "Field `NR` writer - Number of row address bits These bits define the number of bits of a row address."]
pub type NR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `MWID` reader - Memory data bus width. These bits define the memory device width."]
pub type MWID_R = crate::FieldReader;
#[doc = "Field `MWID` writer - Memory data bus width. These bits define the memory device width."]
pub type MWID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `NB` reader - Number of internal banks This bit sets the number of internal banks."]
pub type NB_R = crate::BitReader;
#[doc = "Field `NB` writer - Number of internal banks This bit sets the number of internal banks."]
pub type NB_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CAS` reader - CAS Latency This bits sets the SDRAM CAS latency in number of memory clock cycles"]
pub type CAS_R = crate::FieldReader;
#[doc = "Field `CAS` writer - CAS Latency This bits sets the SDRAM CAS latency in number of memory clock cycles"]
pub type CAS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `WP` reader - Write protection This bit enables write mode access to the SDRAM bank."]
pub type WP_R = crate::BitReader;
#[doc = "Field `WP` writer - Write protection This bit enables write mode access to the SDRAM bank."]
pub type WP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SDCLK` reader - SDRAM clock configuration These bits define the SDRAM clock period for both SDRAM banks and allow disabling the clock before changing the frequency. In this case the SDRAM must be re-initialized. Note: The corresponding bits in the FMC_SDCR2 register are don’t care."]
pub type SDCLK_R = crate::FieldReader;
#[doc = "Field `SDCLK` writer - SDRAM clock configuration These bits define the SDRAM clock period for both SDRAM banks and allow disabling the clock before changing the frequency. In this case the SDRAM must be re-initialized. Note: The corresponding bits in the FMC_SDCR2 register are don’t care."]
pub type SDCLK_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `RBURST` reader - Burst read This bit enables Burst read mode. The SDRAM controller anticipates the next read commands during the CAS latency and stores data in the Read FIFO. Note: The corresponding bit in the FMC_SDCR2 register is don’t care."]
pub type RBURST_R = crate::BitReader;
#[doc = "Field `RBURST` writer - Burst read This bit enables Burst read mode. The SDRAM controller anticipates the next read commands during the CAS latency and stores data in the Read FIFO. Note: The corresponding bit in the FMC_SDCR2 register is don’t care."]
pub type RBURST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RPIPE` reader - Read pipe These bits define the delay, in clock cycles, for reading data after CAS latency. Note: The corresponding bits in the FMC_SDCR2 register is read only."]
pub type RPIPE_R = crate::FieldReader;
#[doc = "Field `RPIPE` writer - Read pipe These bits define the delay, in clock cycles, for reading data after CAS latency. Note: The corresponding bits in the FMC_SDCR2 register is read only."]
pub type RPIPE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bits 0:1 - Number of column address bits These bits define the number of bits of a column address."]
#[inline(always)]
pub fn nc(&self) -> NC_R {
NC_R::new((self.bits & 3) as u8)
}
#[doc = "Bits 2:3 - Number of row address bits These bits define the number of bits of a row address."]
#[inline(always)]
pub fn nr(&self) -> NR_R {
NR_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:5 - Memory data bus width. These bits define the memory device width."]
#[inline(always)]
pub fn mwid(&self) -> MWID_R {
MWID_R::new(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bit 6 - Number of internal banks This bit sets the number of internal banks."]
#[inline(always)]
pub fn nb(&self) -> NB_R {
NB_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bits 7:8 - CAS Latency This bits sets the SDRAM CAS latency in number of memory clock cycles"]
#[inline(always)]
pub fn cas(&self) -> CAS_R {
CAS_R::new(((self.bits >> 7) & 3) as u8)
}
#[doc = "Bit 9 - Write protection This bit enables write mode access to the SDRAM bank."]
#[inline(always)]
pub fn wp(&self) -> WP_R {
WP_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bits 10:11 - SDRAM clock configuration These bits define the SDRAM clock period for both SDRAM banks and allow disabling the clock before changing the frequency. In this case the SDRAM must be re-initialized. Note: The corresponding bits in the FMC_SDCR2 register are don’t care."]
#[inline(always)]
pub fn sdclk(&self) -> SDCLK_R {
SDCLK_R::new(((self.bits >> 10) & 3) as u8)
}
#[doc = "Bit 12 - Burst read This bit enables Burst read mode. The SDRAM controller anticipates the next read commands during the CAS latency and stores data in the Read FIFO. Note: The corresponding bit in the FMC_SDCR2 register is don’t care."]
#[inline(always)]
pub fn rburst(&self) -> RBURST_R {
RBURST_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bits 13:14 - Read pipe These bits define the delay, in clock cycles, for reading data after CAS latency. Note: The corresponding bits in the FMC_SDCR2 register is read only."]
#[inline(always)]
pub fn rpipe(&self) -> RPIPE_R {
RPIPE_R::new(((self.bits >> 13) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - Number of column address bits These bits define the number of bits of a column address."]
#[inline(always)]
#[must_use]
pub fn nc(&mut self) -> NC_W<SDCR1_SPEC, 0> {
NC_W::new(self)
}
#[doc = "Bits 2:3 - Number of row address bits These bits define the number of bits of a row address."]
#[inline(always)]
#[must_use]
pub fn nr(&mut self) -> NR_W<SDCR1_SPEC, 2> {
NR_W::new(self)
}
#[doc = "Bits 4:5 - Memory data bus width. These bits define the memory device width."]
#[inline(always)]
#[must_use]
pub fn mwid(&mut self) -> MWID_W<SDCR1_SPEC, 4> {
MWID_W::new(self)
}
#[doc = "Bit 6 - Number of internal banks This bit sets the number of internal banks."]
#[inline(always)]
#[must_use]
pub fn nb(&mut self) -> NB_W<SDCR1_SPEC, 6> {
NB_W::new(self)
}
#[doc = "Bits 7:8 - CAS Latency This bits sets the SDRAM CAS latency in number of memory clock cycles"]
#[inline(always)]
#[must_use]
pub fn cas(&mut self) -> CAS_W<SDCR1_SPEC, 7> {
CAS_W::new(self)
}
#[doc = "Bit 9 - Write protection This bit enables write mode access to the SDRAM bank."]
#[inline(always)]
#[must_use]
pub fn wp(&mut self) -> WP_W<SDCR1_SPEC, 9> {
WP_W::new(self)
}
#[doc = "Bits 10:11 - SDRAM clock configuration These bits define the SDRAM clock period for both SDRAM banks and allow disabling the clock before changing the frequency. In this case the SDRAM must be re-initialized. Note: The corresponding bits in the FMC_SDCR2 register are don’t care."]
#[inline(always)]
#[must_use]
pub fn sdclk(&mut self) -> SDCLK_W<SDCR1_SPEC, 10> {
SDCLK_W::new(self)
}
#[doc = "Bit 12 - Burst read This bit enables Burst read mode. The SDRAM controller anticipates the next read commands during the CAS latency and stores data in the Read FIFO. Note: The corresponding bit in the FMC_SDCR2 register is don’t care."]
#[inline(always)]
#[must_use]
pub fn rburst(&mut self) -> RBURST_W<SDCR1_SPEC, 12> {
RBURST_W::new(self)
}
#[doc = "Bits 13:14 - Read pipe These bits define the delay, in clock cycles, for reading data after CAS latency. Note: The corresponding bits in the FMC_SDCR2 register is read only."]
#[inline(always)]
#[must_use]
pub fn rpipe(&mut self) -> RPIPE_W<SDCR1_SPEC, 13> {
RPIPE_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "SDRAM control registers 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sdcr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sdcr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SDCR1_SPEC;
impl crate::RegisterSpec for SDCR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`sdcr1::R`](R) reader structure"]
impl crate::Readable for SDCR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`sdcr1::W`](W) writer structure"]
impl crate::Writable for SDCR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SDCR1 to value 0x02d0"]
impl crate::Resettable for SDCR1_SPEC {
const RESET_VALUE: Self::Ux = 0x02d0;
}
|
extern crate libc;
use self::libc::*;
#[link(name = "opus")]
extern "C" {
pub fn opus_strerror(error: c_int) -> *const c_char;
pub fn opus_get_version_string() -> *const c_char;
pub fn opus_encoder_create(Fs: i32, channels: c_int,
application: c_int,
error: *mut c_int) -> *const c_void;
pub fn opus_encoder_ctl(st: *const c_void,
request: c_int, ...) -> c_int;
pub fn opus_encode(st: *const c_void, pcm: *const i16,
frame_size: c_int, data: *mut c_uchar,
max_data_bytes: i32) -> i32;
pub fn opus_encoder_destroy(st: *const c_void) -> ();
pub fn opus_decoder_create(Fs: i32, channels: c_int,
error: *mut c_int) -> *const c_void;
pub fn opus_decoder_ctl(st: *const c_void,
request: c_int, ...) -> c_int;
pub fn opus_decoder_destroy(st: *const c_void) -> ();
}
|
//! Terminal handling.
use crate::error::Result;
use libc::{c_int, c_void, sigaction, sighandler_t, siginfo_t, termios, winsize};
use libc::{SA_SIGINFO, SIGWINCH, STDIN_FILENO, STDOUT_FILENO, TCSADRAIN, TIOCGWINSZ, VMIN, VTIME};
use std::io::{self, Bytes, Read, Stdin};
use std::mem::MaybeUninit;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
/// A terminal in raw mode.
pub struct Terminal {
tty: Bytes<Stdin>,
prior_term: termios,
}
/// Terminal size as the number of *rows* and *columns*.
pub struct TerminalSize {
pub rows: u32,
pub cols: u32,
}
impl Terminal {
/// Puts the terminal into raw mode.
///
/// The terminal mode is changed such that raw bytes are read from standard input without
/// buffering, returning an instance of [`Terminal`] that, when dropped, will restore the
/// terminal to its prior mode.
///
/// Raw mode is configured such that reads do not block indefinitely when no bytes are
/// available. In this case, the underlying driver waits `1/10` second before returning with
/// nothing.
///
/// # Errors
///
/// Returns [`Err`] if an I/O error occurred while enabling raw mode.
pub fn new() -> Result<Terminal> {
register_winsize_handler();
let prior_term = unsafe {
let mut prior_term = MaybeUninit::<termios>::uninit();
os_result(libc::tcgetattr(STDIN_FILENO, prior_term.as_mut_ptr()))?;
prior_term.assume_init()
};
let mut raw_term = prior_term.clone();
unsafe {
libc::cfmakeraw(&mut raw_term);
raw_term.c_cc[VMIN] = 0;
raw_term.c_cc[VTIME] = 1;
os_result(libc::tcsetattr(STDIN_FILENO, TCSADRAIN, &raw_term))?;
};
Ok(Terminal {
tty: io::stdin().bytes(),
prior_term,
})
}
/// Reads the next byte if available.
///
/// If a byte is available, this function immediately returns with [`Some<u8>`]. Otherwise, it
/// will block for `1/10` second, waiting for input, before returning [`None`].
///
/// # Errors
///
/// Returns `Err` if an I/O error occurred while fetching the next byte.
pub fn read(&mut self) -> Result<Option<u8>> {
Ok(self.tty.next().transpose()?)
}
fn restore(&mut self) -> Result<()> {
unsafe { os_result(libc::tcsetattr(STDIN_FILENO, TCSADRAIN, &self.prior_term)) }
}
}
impl Drop for Terminal {
fn drop(&mut self) {
self.restore()
.expect("terminal settings should have been restored");
}
}
/// Returns the size of the terminal.
///
/// Calls to this function always query the underlying driver, as the terminal size may have
/// changed since the prior request.
///
/// # Errors
///
/// Returns [`Err`] if an I/O error occurred.
pub fn size() -> Result<TerminalSize> {
let win = unsafe {
let mut win = MaybeUninit::<winsize>::uninit();
os_result(libc::ioctl(STDOUT_FILENO, TIOCGWINSZ, win.as_mut_ptr()))?;
win.assume_init()
};
Ok(TerminalSize {
rows: win.ws_row as u32,
cols: win.ws_col as u32,
})
}
/// Returns `true` if the terminal size changed.
///
/// If this function returns `true`, all subsequent calls will return `false` until the terminal
/// size once again changes.
pub fn size_changed() -> bool {
WINSIZE_CHANGED.swap(false, Ordering::Relaxed)
}
fn os_result(err: c_int) -> Result<()> {
if err < 0 {
Err(io::Error::last_os_error().into())
} else {
Ok(())
}
}
/// Ensures that signal handler is registered at most once.
static WINSIZE_HANDLER: OnceLock<()> = OnceLock::new();
/// Used by signal handler to convey that the terminal size changed.
static WINSIZE_CHANGED: AtomicBool = AtomicBool::new(false);
/// Signal handler that gets invoked when the terminal size changes.
extern "C" fn winsize_handler(_: c_int, _: *mut siginfo_t, _: *mut c_void) {
WINSIZE_CHANGED.store(true, Ordering::Relaxed);
}
/// Registers the signal handler to capture changes in terminal size.
fn register_winsize_handler() {
WINSIZE_HANDLER.get_or_init(|| unsafe {
let mut sigact = MaybeUninit::<sigaction>::uninit();
let sigact_ptr = sigact.as_mut_ptr();
os_result(libc::sigemptyset(&mut (*sigact_ptr).sa_mask)).expect("register signal handler");
(*sigact_ptr).sa_flags = SA_SIGINFO;
(*sigact_ptr).sa_sigaction = winsize_handler as sighandler_t;
os_result(libc::sigaction(SIGWINCH, sigact_ptr, ptr::null_mut()))
.expect("register signal handler");
});
}
|
#[doc = "Register `RCC_PLL4CFGR1` reader"]
pub type R = crate::R<RCC_PLL4CFGR1_SPEC>;
#[doc = "Register `RCC_PLL4CFGR1` writer"]
pub type W = crate::W<RCC_PLL4CFGR1_SPEC>;
#[doc = "Field `DIVN` reader - DIVN"]
pub type DIVN_R = crate::FieldReader<u16>;
#[doc = "Field `DIVN` writer - DIVN"]
pub type DIVN_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 9, O, u16>;
#[doc = "Field `DIVM4` reader - DIVM4"]
pub type DIVM4_R = crate::FieldReader;
#[doc = "Field `DIVM4` writer - DIVM4"]
pub type DIVM4_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>;
#[doc = "Field `IFRGE` reader - IFRGE"]
pub type IFRGE_R = crate::FieldReader;
#[doc = "Field `IFRGE` writer - IFRGE"]
pub type IFRGE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bits 0:8 - DIVN"]
#[inline(always)]
pub fn divn(&self) -> DIVN_R {
DIVN_R::new((self.bits & 0x01ff) as u16)
}
#[doc = "Bits 16:21 - DIVM4"]
#[inline(always)]
pub fn divm4(&self) -> DIVM4_R {
DIVM4_R::new(((self.bits >> 16) & 0x3f) as u8)
}
#[doc = "Bits 24:25 - IFRGE"]
#[inline(always)]
pub fn ifrge(&self) -> IFRGE_R {
IFRGE_R::new(((self.bits >> 24) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:8 - DIVN"]
#[inline(always)]
#[must_use]
pub fn divn(&mut self) -> DIVN_W<RCC_PLL4CFGR1_SPEC, 0> {
DIVN_W::new(self)
}
#[doc = "Bits 16:21 - DIVM4"]
#[inline(always)]
#[must_use]
pub fn divm4(&mut self) -> DIVM4_W<RCC_PLL4CFGR1_SPEC, 16> {
DIVM4_W::new(self)
}
#[doc = "Bits 24:25 - IFRGE"]
#[inline(always)]
#[must_use]
pub fn ifrge(&mut self) -> IFRGE_W<RCC_PLL4CFGR1_SPEC, 24> {
IFRGE_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "This register is used to configure the PLL4.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_pll4cfgr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_pll4cfgr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RCC_PLL4CFGR1_SPEC;
impl crate::RegisterSpec for RCC_PLL4CFGR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rcc_pll4cfgr1::R`](R) reader structure"]
impl crate::Readable for RCC_PLL4CFGR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rcc_pll4cfgr1::W`](W) writer structure"]
impl crate::Writable for RCC_PLL4CFGR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RCC_PLL4CFGR1 to value 0x0001_0031"]
impl crate::Resettable for RCC_PLL4CFGR1_SPEC {
const RESET_VALUE: Self::Ux = 0x0001_0031;
}
|
/*
use pymemprofile_api::oom::get_cgroup_available_memory;
use std::time::Instant;
*/
fn main() {
/*
let now = Instant::now();
for _ in 1..1_000 {
get_cgroup_available_memory();
}
let elapsed_secs = (now.elapsed().as_millis() as f64) / 1000.0;
println!("Calls/sec: {}", 1000.0 * (1.0 / elapsed_secs));
*/
}
|
use crate::ast;
use crate::{Parse, ParseError, ParseErrorKind, Parser, Peek, Spanned, ToTokens};
/// The unit literal `()`.
#[derive(Debug, Clone, ToTokens, Spanned)]
pub struct LitBool {
/// The token of the literal.
pub token: ast::Token,
/// The value of the literal.
#[rune(skip)]
pub value: bool,
}
/// Parsing a unit literal
///
/// # Examples
///
/// ```rust
/// use rune::{parse_all, ast};
///
/// parse_all::<ast::LitBool>("true").unwrap();
/// parse_all::<ast::LitBool>("false").unwrap();
/// ```
impl Parse for LitBool {
fn parse(parser: &mut Parser) -> Result<Self, ParseError> {
let token = parser.token_next()?;
let value = match token.kind {
ast::Kind::True => true,
ast::Kind::False => false,
_ => {
return Err(ParseError::new(
token,
ParseErrorKind::ExpectedBool { actual: token.kind },
));
}
};
Ok(Self { value, token })
}
}
impl Peek for LitBool {
fn peek(p1: Option<ast::Token>, _: Option<ast::Token>) -> bool {
matches!(peek!(p1).kind, ast::Kind::True | ast::Kind::False)
}
}
|
use super::*;
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct Affine<T> {
pub m: Matrix2<T>,
pub t: Vector2<T>,
}
impl<T: BaseFloat> Default for Affine<T> {
#[inline]
fn default() -> Self {
Self::one()
}
}
impl<S: BaseFloat> Transform<Point2<S>> for Affine<S> {
#[inline]
fn one() -> Self {
Self {
m: Matrix2::one(),
t: Vector2::zero(),
}
}
#[inline]
fn look_at(_eye: Point2<S>, _center: Point2<S>, _up: Vector2<S>) -> Self {
unimplemented!();
//let dir = center - eye;
//Matrix3::from(Matrix2::look_at(dir, up))
}
#[inline]
fn transform_vector(&self, vec: Vector2<S>) -> Vector2<S> {
self.m * vec + self.t
}
#[inline]
fn transform_point(&self, _point: Point2<S>) -> Point2<S> {
unimplemented!();
//Point2::from_vec((self * Point3::new(point.x, point.y, S::one()).to_vec()).truncate())
//Point2::from_vec(self.m * Point2::new(point.x, point.y) + self.t)
}
#[inline]
fn concat(&self, other: &Self) -> Self {
Self {
m: other.m * self.m,
t: other.m * self.t + other.t,
}
}
#[inline]
fn inverse_transform(&self) -> Option<Self> {
let a = self.a();
let b = self.b();
let c = self.c();
let d = self.d();
let tx = self.t.x;
let ty = self.t.y;
let n = (a * d) - (b * c);
let m = Matrix2::new(
d / n,
-b / n,
-c / n,
a / n,
);
let t = Vector2::new(
(c * ty - d * tx) / n,
-(a * ty - b * tx) / n,
);
// FIXME:
Some(Self { m, t })
}
}
// transposed:
// mm00
// mm00
// tt10
// 0000
// non trnsposed
// mmt0
// mmt0
// 0010
// 0000
impl<T: BaseFloat> Into<[[T; 4]; 4]> for Affine<T> {
#[inline]
fn into(self) -> [[T; 4]; 4] {
let o = T::one();
let z = T::zero();
[
[self.a(), self.b(), o, o],
[self.c(), self.d(), o, o],
[self.t.x, self.t.y, z, o],
[o, o, o, o],
]
}
}
impl<T: BaseFloat> Into<Matrix4<T>> for Affine<T> {
#[inline]
fn into(self) -> Matrix4<T> {
let o = T::one();
let z = T::zero();
Matrix4::new(
self.a(), self.b(), o, o,
self.c(), self.d(), o, o,
self.t.x, self.t.y, z, o,
o, o, o, o,
)
}
}
impl<T: BaseFloat> Affine<T> {
#[inline] fn a(&self) -> T { self.m.x.x }
#[inline] fn b(&self) -> T { self.m.x.y }
#[inline] fn c(&self) -> T { self.m.y.x }
#[inline] fn d(&self) -> T { self.m.y.y }
#[inline]
pub fn projection(w: T, h: T) -> Self {
let two = T::one() + T::one();
let t = Vector2::new(-T::one(), -T::one());
let m = Matrix2::new(
T::one() / w * two,
T::zero(),
T::zero(),
T::one() / h * two,
);
Self { m, t }
}
#[inline]
pub fn apply_inv(&self, v: Vector2<T>) -> Vector2<T> {
let a = self.a();
let b = self.b();
let c = self.c();
let d = self.d();
let tx = self.t.x;
let ty = self.t.y;
let id = T::one() / (a * d + c * (-b));
let Vector2 { x, y } = v;
Vector2::new(
(d * id * x) + (-c * id * y) + ( ty * c - tx * d) * id,
(a * id * y) + (-b * id * x) + (-ty * a + tx * b) * id,
)
}
#[inline]
pub fn translate(&mut self, x: T, y: T) {
self.t.x += x;
self.t.y += y;
}
#[inline]
pub fn scale(&mut self, x: T, y: T) {
self.m.x.x *= x;
self.m.x.y *= y;
self.m.y.x *= x;
self.m.y.y *= y;
self.t.x *= x;
self.t.y *= y;
}
#[inline]
pub fn rotate(&mut self, angle: T) {
let (sin, cos) = angle.sin_cos();
let a = self.a();
let c = self.c();
let tx = self.t.x;
self.m.x.x = (a * cos) - (self.m.x.y * sin);
self.m.x.y = (a * sin) + (self.m.x.y * cos);
self.m.y.x = (c * cos) - (self.m.y.y * sin);
self.m.y.y = (c * sin) + (self.m.y.y * cos);
self.t.x = (tx * cos) - (self.t.y * sin);
self.t.y = (tx * sin) + (self.t.y * cos);
}
#[inline]
pub fn set_identity(&mut self) {
self.m = Matrix2::one();
self.t = Vector2::zero();
}
#[inline]
pub fn compose(pos: Vector2<T>, pivot: Vector2<T>, scale: Vector2<T>, rotation: T, skew: Vector2<T>) -> Self {
let (sr, cr) = rotation.sin_cos();
let (sy, cy) = skew.y.sin_cos();
let nsx = -skew.x.sin();
let cx = skew.x.cos();
let a = cr * scale.x;
let b = sr * scale.x;
let c = -sr * scale.y;
let d = cr * scale.y;
let m = Matrix2::new(
( cy * a) + (sy * c),
( cy * b) + (sy * d),
(nsx * a) + (cx * c),
(nsx * b) + (cx * d),
);
let t = Vector2::new(
pos.x + (pivot.x * a + pivot.y * c),
pos.y + (pivot.x * b + pivot.y * d),
);
Self { m, t }
}
}
|
// This file is part of lock-free-multi-producer-single-consumer-ring-buffer. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/lock-free-multi-producer-single-consumer-ring-buffer/master/COPYRIGHT. No part of lock-free-multi-producer-single-consumer-ring-buffer, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 - 2019 The developers of lock-free-multi-producer-single-consumer-ring-buffer. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/lock-free-multi-producer-single-consumer-ring-buffer/master/COPYRIGHT.
/// A ring buffer consumer for receiving lock-less bursts of messages.
///
/// Not particularly cheap to consume from (as it walks all producers) so try to use as few producers as possible and consume as much as possible with each call.
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct RingBufferConsumer<T: Sized>(RingBuffer<T>);
impl<T: Sized> RingBufferConsumer<T>
{
/// Get a contiguous range which is ready to be consumed.
///
/// Only call this on one thread at a time.
///
/// Not particularly cheap (as it walks all producers) so try to take as much as possible.
#[inline(always)]
pub fn consume<'a>(&'a self) -> RingBufferConsumerGuard<'a, T>
{
let (count, offset) = self.reference().consume();
RingBufferConsumerGuard
{
buffer_slice: self.reference().buffer_consumer_slice_reference(count, offset),
release_count: count,
consumer: self,
}
}
#[inline(always)]
pub(crate) fn release(&self, count: usize)
{
self.reference().release(count)
}
#[inline(always)]
fn reference(&self) -> &RingBufferInner<T>
{
self.0.reference()
}
}
|
#[doc = "Register `DCKCFGR2` reader"]
pub type R = crate::R<DCKCFGR2_SPEC>;
#[doc = "Register `DCKCFGR2` writer"]
pub type W = crate::W<DCKCFGR2_SPEC>;
#[doc = "Field `FMPI2C1SEL` reader - I2C4 kernel clock source selection"]
pub type FMPI2C1SEL_R = crate::FieldReader<FMPI2C1SEL_A>;
#[doc = "I2C4 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum FMPI2C1SEL_A {
#[doc = "0: APB clock selected as I2C clock"]
Apb = 0,
#[doc = "1: System clock selected as I2C clock"]
Sysclk = 1,
#[doc = "2: HSI clock selected as I2C clock"]
Hsi = 2,
}
impl From<FMPI2C1SEL_A> for u8 {
#[inline(always)]
fn from(variant: FMPI2C1SEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for FMPI2C1SEL_A {
type Ux = u8;
}
impl FMPI2C1SEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<FMPI2C1SEL_A> {
match self.bits {
0 => Some(FMPI2C1SEL_A::Apb),
1 => Some(FMPI2C1SEL_A::Sysclk),
2 => Some(FMPI2C1SEL_A::Hsi),
_ => None,
}
}
#[doc = "APB clock selected as I2C clock"]
#[inline(always)]
pub fn is_apb(&self) -> bool {
*self == FMPI2C1SEL_A::Apb
}
#[doc = "System clock selected as I2C clock"]
#[inline(always)]
pub fn is_sysclk(&self) -> bool {
*self == FMPI2C1SEL_A::Sysclk
}
#[doc = "HSI clock selected as I2C clock"]
#[inline(always)]
pub fn is_hsi(&self) -> bool {
*self == FMPI2C1SEL_A::Hsi
}
}
#[doc = "Field `FMPI2C1SEL` writer - I2C4 kernel clock source selection"]
pub type FMPI2C1SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, FMPI2C1SEL_A>;
impl<'a, REG, const O: u8> FMPI2C1SEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "APB clock selected as I2C clock"]
#[inline(always)]
pub fn apb(self) -> &'a mut crate::W<REG> {
self.variant(FMPI2C1SEL_A::Apb)
}
#[doc = "System clock selected as I2C clock"]
#[inline(always)]
pub fn sysclk(self) -> &'a mut crate::W<REG> {
self.variant(FMPI2C1SEL_A::Sysclk)
}
#[doc = "HSI clock selected as I2C clock"]
#[inline(always)]
pub fn hsi(self) -> &'a mut crate::W<REG> {
self.variant(FMPI2C1SEL_A::Hsi)
}
}
#[doc = "Field `CECSEL` reader - HDMI CEC clock source selection"]
pub type CECSEL_R = crate::BitReader<CECSEL_A>;
#[doc = "HDMI CEC clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CECSEL_A {
#[doc = "0: LSE clock is selected as HDMI-CEC clock"]
Lse = 0,
#[doc = "1: HSI divided by 488 clock is selected as HDMI-CEC clock"]
HsiDiv488 = 1,
}
impl From<CECSEL_A> for bool {
#[inline(always)]
fn from(variant: CECSEL_A) -> Self {
variant as u8 != 0
}
}
impl CECSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CECSEL_A {
match self.bits {
false => CECSEL_A::Lse,
true => CECSEL_A::HsiDiv488,
}
}
#[doc = "LSE clock is selected as HDMI-CEC clock"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == CECSEL_A::Lse
}
#[doc = "HSI divided by 488 clock is selected as HDMI-CEC clock"]
#[inline(always)]
pub fn is_hsi_div488(&self) -> bool {
*self == CECSEL_A::HsiDiv488
}
}
#[doc = "Field `CECSEL` writer - HDMI CEC clock source selection"]
pub type CECSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CECSEL_A>;
impl<'a, REG, const O: u8> CECSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "LSE clock is selected as HDMI-CEC clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut crate::W<REG> {
self.variant(CECSEL_A::Lse)
}
#[doc = "HSI divided by 488 clock is selected as HDMI-CEC clock"]
#[inline(always)]
pub fn hsi_div488(self) -> &'a mut crate::W<REG> {
self.variant(CECSEL_A::HsiDiv488)
}
}
#[doc = "Field `CK48MSEL` reader - SDIO/USBFS/HS clock selection"]
pub type CK48MSEL_R = crate::BitReader<CK48MSEL_A>;
#[doc = "SDIO/USBFS/HS clock selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CK48MSEL_A {
#[doc = "0: 48MHz clock from PLL is selected"]
Pll = 0,
#[doc = "1: 48MHz clock from PLLSAI is selected"]
Pllsai = 1,
}
impl From<CK48MSEL_A> for bool {
#[inline(always)]
fn from(variant: CK48MSEL_A) -> Self {
variant as u8 != 0
}
}
impl CK48MSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CK48MSEL_A {
match self.bits {
false => CK48MSEL_A::Pll,
true => CK48MSEL_A::Pllsai,
}
}
#[doc = "48MHz clock from PLL is selected"]
#[inline(always)]
pub fn is_pll(&self) -> bool {
*self == CK48MSEL_A::Pll
}
#[doc = "48MHz clock from PLLSAI is selected"]
#[inline(always)]
pub fn is_pllsai(&self) -> bool {
*self == CK48MSEL_A::Pllsai
}
}
#[doc = "Field `CK48MSEL` writer - SDIO/USBFS/HS clock selection"]
pub type CK48MSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CK48MSEL_A>;
impl<'a, REG, const O: u8> CK48MSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "48MHz clock from PLL is selected"]
#[inline(always)]
pub fn pll(self) -> &'a mut crate::W<REG> {
self.variant(CK48MSEL_A::Pll)
}
#[doc = "48MHz clock from PLLSAI is selected"]
#[inline(always)]
pub fn pllsai(self) -> &'a mut crate::W<REG> {
self.variant(CK48MSEL_A::Pllsai)
}
}
#[doc = "Field `SDIOSEL` reader - SDIO clock selection"]
pub type SDIOSEL_R = crate::BitReader<SDIOSEL_A>;
#[doc = "SDIO clock selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SDIOSEL_A {
#[doc = "0: 48 MHz clock is selected as SD clock"]
Ck48m = 0,
#[doc = "1: System clock is selected as SD clock"]
Sysclk = 1,
}
impl From<SDIOSEL_A> for bool {
#[inline(always)]
fn from(variant: SDIOSEL_A) -> Self {
variant as u8 != 0
}
}
impl SDIOSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SDIOSEL_A {
match self.bits {
false => SDIOSEL_A::Ck48m,
true => SDIOSEL_A::Sysclk,
}
}
#[doc = "48 MHz clock is selected as SD clock"]
#[inline(always)]
pub fn is_ck48m(&self) -> bool {
*self == SDIOSEL_A::Ck48m
}
#[doc = "System clock is selected as SD clock"]
#[inline(always)]
pub fn is_sysclk(&self) -> bool {
*self == SDIOSEL_A::Sysclk
}
}
#[doc = "Field `SDIOSEL` writer - SDIO clock selection"]
pub type SDIOSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SDIOSEL_A>;
impl<'a, REG, const O: u8> SDIOSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "48 MHz clock is selected as SD clock"]
#[inline(always)]
pub fn ck48m(self) -> &'a mut crate::W<REG> {
self.variant(SDIOSEL_A::Ck48m)
}
#[doc = "System clock is selected as SD clock"]
#[inline(always)]
pub fn sysclk(self) -> &'a mut crate::W<REG> {
self.variant(SDIOSEL_A::Sysclk)
}
}
#[doc = "Field `SPDIFRXSEL` reader - SPDIF clock selection"]
pub type SPDIFRXSEL_R = crate::BitReader<SPDIFRXSEL_A>;
#[doc = "SPDIF clock selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SPDIFRXSEL_A {
#[doc = "0: SPDIF-Rx clock from PLL is selected"]
Pll = 0,
#[doc = "1: SPDIF-Rx clock from PLLI2S is selected"]
Plli2s = 1,
}
impl From<SPDIFRXSEL_A> for bool {
#[inline(always)]
fn from(variant: SPDIFRXSEL_A) -> Self {
variant as u8 != 0
}
}
impl SPDIFRXSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SPDIFRXSEL_A {
match self.bits {
false => SPDIFRXSEL_A::Pll,
true => SPDIFRXSEL_A::Plli2s,
}
}
#[doc = "SPDIF-Rx clock from PLL is selected"]
#[inline(always)]
pub fn is_pll(&self) -> bool {
*self == SPDIFRXSEL_A::Pll
}
#[doc = "SPDIF-Rx clock from PLLI2S is selected"]
#[inline(always)]
pub fn is_plli2s(&self) -> bool {
*self == SPDIFRXSEL_A::Plli2s
}
}
#[doc = "Field `SPDIFRXSEL` writer - SPDIF clock selection"]
pub type SPDIFRXSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SPDIFRXSEL_A>;
impl<'a, REG, const O: u8> SPDIFRXSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "SPDIF-Rx clock from PLL is selected"]
#[inline(always)]
pub fn pll(self) -> &'a mut crate::W<REG> {
self.variant(SPDIFRXSEL_A::Pll)
}
#[doc = "SPDIF-Rx clock from PLLI2S is selected"]
#[inline(always)]
pub fn plli2s(self) -> &'a mut crate::W<REG> {
self.variant(SPDIFRXSEL_A::Plli2s)
}
}
impl R {
#[doc = "Bits 22:23 - I2C4 kernel clock source selection"]
#[inline(always)]
pub fn fmpi2c1sel(&self) -> FMPI2C1SEL_R {
FMPI2C1SEL_R::new(((self.bits >> 22) & 3) as u8)
}
#[doc = "Bit 26 - HDMI CEC clock source selection"]
#[inline(always)]
pub fn cecsel(&self) -> CECSEL_R {
CECSEL_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - SDIO/USBFS/HS clock selection"]
#[inline(always)]
pub fn ck48msel(&self) -> CK48MSEL_R {
CK48MSEL_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - SDIO clock selection"]
#[inline(always)]
pub fn sdiosel(&self) -> SDIOSEL_R {
SDIOSEL_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - SPDIF clock selection"]
#[inline(always)]
pub fn spdifrxsel(&self) -> SPDIFRXSEL_R {
SPDIFRXSEL_R::new(((self.bits >> 29) & 1) != 0)
}
}
impl W {
#[doc = "Bits 22:23 - I2C4 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn fmpi2c1sel(&mut self) -> FMPI2C1SEL_W<DCKCFGR2_SPEC, 22> {
FMPI2C1SEL_W::new(self)
}
#[doc = "Bit 26 - HDMI CEC clock source selection"]
#[inline(always)]
#[must_use]
pub fn cecsel(&mut self) -> CECSEL_W<DCKCFGR2_SPEC, 26> {
CECSEL_W::new(self)
}
#[doc = "Bit 27 - SDIO/USBFS/HS clock selection"]
#[inline(always)]
#[must_use]
pub fn ck48msel(&mut self) -> CK48MSEL_W<DCKCFGR2_SPEC, 27> {
CK48MSEL_W::new(self)
}
#[doc = "Bit 28 - SDIO clock selection"]
#[inline(always)]
#[must_use]
pub fn sdiosel(&mut self) -> SDIOSEL_W<DCKCFGR2_SPEC, 28> {
SDIOSEL_W::new(self)
}
#[doc = "Bit 29 - SPDIF clock selection"]
#[inline(always)]
#[must_use]
pub fn spdifrxsel(&mut self) -> SPDIFRXSEL_W<DCKCFGR2_SPEC, 29> {
SPDIFRXSEL_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "dedicated clocks configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dckcfgr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dckcfgr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DCKCFGR2_SPEC;
impl crate::RegisterSpec for DCKCFGR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dckcfgr2::R`](R) reader structure"]
impl crate::Readable for DCKCFGR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dckcfgr2::W`](W) writer structure"]
impl crate::Writable for DCKCFGR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DCKCFGR2 to value 0"]
impl crate::Resettable for DCKCFGR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub const DBMS_MIN_REVISION_WITH_QUOTA_KEY_IN_CLIENT_INFO: u64 = 54060;
pub const DBMS_MIN_REVISION_WITH_SETTINGS_SERIALIZED_AS_STRINGS: u64 = 54429;
pub const CLIENT_HELLO: u64 = 0;
pub const CLIENT_QUERY: u64 = 1;
pub const CLIENT_DATA: u64 = 2;
pub const CLIENT_CANCEL: u64 = 3;
pub const CLIENT_PING: u64 = 4;
pub const COMPRESS_ENABLE: u64 = 1;
pub const COMPRESS_DISABLE: u64 = 0;
pub const STATE_COMPLETE: u64 = 2;
pub const SERVER_HELLO: u64 = 0;
pub const SERVER_DATA: u64 = 1;
pub const SERVER_EXCEPTION: u64 = 2;
pub const SERVER_PROGRESS: u64 = 3;
pub const SERVER_PONG: u64 = 4;
pub const SERVER_END_OF_STREAM: u64 = 5;
pub const SERVER_PROFILE_INFO: u64 = 6;
pub const SERVER_TOTALS: u64 = 7;
pub const SERVER_EXTREMES: u64 = 8;
|
#![allow(incomplete_features)]
#![feature(generic_associated_types, const_generics)]
pub mod app;
pub mod fields;
pub mod kinds;
pub mod lens;
pub mod message;
pub mod mutation;
mod pane_zone;
mod panes;
pub mod stores;
mod theme;
pub use app::App;
pub use iced::{Sandbox, Settings};
pub use kinds::{Field, Key, Kind};
pub use message::Message;
pub use stores::ObjectStore;
pub use theme::Theme;
|
use bindgen;
use cc;
use std::env;
use std::path::PathBuf;
use std::process::Command;
fn main() {
let v8_dir = match env::var("CUSTOM_V8") {
Ok(custom_v8_dir) => {
let custom_v8_dir = PathBuf::from(custom_v8_dir);
assert!(custom_v8_dir.exists());
custom_v8_dir
}
Err(_) => panic!("Must use CUSTOM_V8 env_var"),
};
#[cfg(target_env = "msvc")] {
compile_wrappers_windows(v8_dir.clone());
generate_bindings_windows(v8_dir.clone());
}
#[cfg(not(target_env = "msvc"))] {
compile_wrappers_not_windows(v8_dir.clone());
generate_bindings_not_windows(v8_dir);
}
}
fn compile_wrappers_not_windows(v8_dir: PathBuf) {
let include_dir = v8_dir.join("include");
println!("cargo:rerun-if-changed=src/wrapper.cpp");
cc::Build::new()
.cpp(true)
.warnings(false)
.flag("--std=c++14")
.include(include_dir)
.file("src/wrapper.cpp")
.compile("libwrapper.a");
}
fn generate_bindings_not_windows(v8_dir: PathBuf) {
println!("cargo:rustc-link-lib=v8_libbase");
println!("cargo:rustc-link-lib=v8_libplatform");
println!("cargo:rustc-link-lib=v8_monolith");
println!("cargo:rustc-link-lib=c++");
println!(
"cargo:rustc-link-search={}/out.gn/x64.release/obj",
v8_dir.to_str().unwrap()
);
println!(
"cargo:rustc-link-search={}/out.gn/x64.release/obj/third_party/icu",
v8_dir.to_str().unwrap()
);
let bindings = bindgen::Builder::default()
.generate_comments(true)
.header("src/wrapper.cpp")
.rust_target(bindgen::RustTarget::Nightly)
.clang_arg("-x")
.clang_arg("c++")
.clang_arg("--std=c++14")
.clang_arg(format!("-I{}", v8_dir.join("include").to_str().unwrap()))
// Because there are some layout problems with these
.opaque_type("std::.*")
.whitelist_type("std::unique_ptr\\<v8::Platform\\>")
.whitelist_type("v8::.*")
.blacklist_type("std::basic_string.*")
.whitelist_function("v8::.*")
.whitelist_function("osgood::.*")
.whitelist_var("v8::.*")
// Re-structure the modules a bit and hide the "root" module
.raw_line("#[doc(hidden)]")
// .generate_inline_functions(true)
.enable_cxx_namespaces()
.derive_debug(true)
.derive_hash(true)
.derive_eq(true)
.derive_partialeq(true)
.rustfmt_bindings(true) // comment this for a slightly faster build
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
fn compile_wrappers_windows(v8_dir: PathBuf) {
let include_dir = v8_dir.join("include");
println!("cargo:rerun-if-changed=src/wrapper.cpp");
cc::Build::new()
.flag("/EHsc")
.warnings_into_errors(false)
.warnings(false)
.flag("/std:c++14")
.cpp(true)
.include(include_dir)
.file("src/wrapper.cpp")
.compile("wrapper");
}
fn generate_bindings_windows(v8_dir: PathBuf) {
println!("cargo:rustc-link-lib=DbgHelp");
println!("cargo:rustc-link-lib=Winmm");
println!("cargo:rustc-link-lib=Shlwapi");
println!("cargo:rustc-link-lib=v8_init");
println!("cargo:rustc-link-lib=v8_initializers");
println!("cargo:rustc-link-lib=v8_libbase");
println!("cargo:rustc-link-lib=v8_nosnapshot");
println!("cargo:rustc-link-lib=v8_libplatform");
println!("cargo:rustc-link-lib=v8_monolith");
println!("cargo:rustc-link-lib=icui18n");
println!("cargo:rustc-link-lib=icuuc");
println!(
"cargo:rustc-link-search={}/lib",
v8_dir.to_str().unwrap()
);
println!(
"cargo:rustc-link-search={}/lib/third_party/icu",
v8_dir.to_str().unwrap()
);
println!(
"cargo:rustc-link-search={}/out.gn/x64.release/obj",
v8_dir.to_str().unwrap()
);
println!(
"cargo:rustc-link-search={}/out.gn/x64.release/obj/third_party/icu",
v8_dir.to_str().unwrap()
);
let bindings = bindgen::Builder::default()
.generate_comments(true)
.header("src/wrapper.cpp")
.rust_target(bindgen::RustTarget::Nightly)
.clang_arg("-x")
.clang_arg("c++")
.clang_arg("--std=c++14")
.clang_arg(format!("-I{}", v8_dir.join("include").to_str().unwrap()))
// Because there are some layout problems with these
.opaque_type("std::.*")
.whitelist_type("std::unique_ptr\\<v8::Platform\\>")
.whitelist_type("v8::.*")
.blacklist_type("std::basic_string.*")
.whitelist_function("v8::.*")
.whitelist_function("osgood::.*")
.whitelist_var("v8::.*")
// Re-structure the modules a bit and hide the "root" module
.raw_line("#[doc(hidden)]")
// .generate_inline_functions(true)
.enable_cxx_namespaces()
.derive_debug(true)
.derive_hash(true)
.derive_eq(true)
.derive_partialeq(true)
.rustfmt_bindings(true) // comment this for a slightly faster build
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
|
use utils::vec3;
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct Ray {
pub a: vec3::Vec3,
pub b: vec3::Vec3,
time: f32,
}
#[allow(dead_code)]
impl Ray {
pub fn new(a: &vec3::Vec3, b: &vec3::Vec3, ti: f32) -> Self {
Self {
a: a.clone(),
b: b.clone(),
time: ti,
}
}
pub fn origin(&self) -> &vec3::Vec3 {
&self.a
}
pub fn direction(&self) -> &vec3::Vec3 {
&self.b
}
pub fn time(self) -> f32 {
self.time
}
pub fn point_at_parameter(&self, t: f32) -> vec3::Vec3 {
let z: vec3::Vec3 = self.a.clone() + self.b.clone() * t;
z
}
}
|
#[doc = "Reader of register BSEC_OTP_CONFIG"]
pub type R = crate::R<u32, super::BSEC_OTP_CONFIG>;
#[doc = "Writer for register BSEC_OTP_CONFIG"]
pub type W = crate::W<u32, super::BSEC_OTP_CONFIG>;
#[doc = "Register BSEC_OTP_CONFIG `reset()`'s with value 0x0e"]
impl crate::ResetValue for super::BSEC_OTP_CONFIG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0e
}
}
#[doc = "Reader of field `PWRUP`"]
pub type PWRUP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PWRUP`"]
pub struct PWRUP_W<'a> {
w: &'a mut W,
}
impl<'a> PWRUP_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 `FRC`"]
pub type FRC_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `FRC`"]
pub struct FRC_W<'a> {
w: &'a mut W,
}
impl<'a> FRC_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 << 1)) | (((value as u32) & 0x03) << 1);
self.w
}
}
#[doc = "Reader of field `PRGWIDTH`"]
pub type PRGWIDTH_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PRGWIDTH`"]
pub struct PRGWIDTH_W<'a> {
w: &'a mut W,
}
impl<'a> PRGWIDTH_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 3)) | (((value as u32) & 0x0f) << 3);
self.w
}
}
#[doc = "Reader of field `TREAD`"]
pub type TREAD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TREAD`"]
pub struct TREAD_W<'a> {
w: &'a mut W,
}
impl<'a> TREAD_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 << 7)) | (((value as u32) & 0x03) << 7);
self.w
}
}
impl R {
#[doc = "Bit 0 - PWRUP"]
#[inline(always)]
pub fn pwrup(&self) -> PWRUP_R {
PWRUP_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 1:2 - FRC"]
#[inline(always)]
pub fn frc(&self) -> FRC_R {
FRC_R::new(((self.bits >> 1) & 0x03) as u8)
}
#[doc = "Bits 3:6 - PRGWIDTH"]
#[inline(always)]
pub fn prgwidth(&self) -> PRGWIDTH_R {
PRGWIDTH_R::new(((self.bits >> 3) & 0x0f) as u8)
}
#[doc = "Bits 7:8 - TREAD"]
#[inline(always)]
pub fn tread(&self) -> TREAD_R {
TREAD_R::new(((self.bits >> 7) & 0x03) as u8)
}
}
impl W {
#[doc = "Bit 0 - PWRUP"]
#[inline(always)]
pub fn pwrup(&mut self) -> PWRUP_W {
PWRUP_W { w: self }
}
#[doc = "Bits 1:2 - FRC"]
#[inline(always)]
pub fn frc(&mut self) -> FRC_W {
FRC_W { w: self }
}
#[doc = "Bits 3:6 - PRGWIDTH"]
#[inline(always)]
pub fn prgwidth(&mut self) -> PRGWIDTH_W {
PRGWIDTH_W { w: self }
}
#[doc = "Bits 7:8 - TREAD"]
#[inline(always)]
pub fn tread(&mut self) -> TREAD_W {
TREAD_W { w: self }
}
}
|
#[doc = "Reader of register DSI_VMCCR"]
pub type R = crate::R<u32, super::DSI_VMCCR>;
#[doc = "Reader of field `VMT`"]
pub type VMT_R = crate::R<u8, u8>;
#[doc = "Reader of field `LPVSAE`"]
pub type LPVSAE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPVBPE`"]
pub type LPVBPE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPVFPE`"]
pub type LPVFPE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPVAE`"]
pub type LPVAE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPHBPE`"]
pub type LPHBPE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPHFE`"]
pub type LPHFE_R = crate::R<bool, bool>;
#[doc = "Reader of field `FBTAAE`"]
pub type FBTAAE_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPCE`"]
pub type LPCE_R = crate::R<bool, bool>;
impl R {
#[doc = "Bits 0:1 - VMT"]
#[inline(always)]
pub fn vmt(&self) -> VMT_R {
VMT_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bit 2 - LPVSAE"]
#[inline(always)]
pub fn lpvsae(&self) -> LPVSAE_R {
LPVSAE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - LPVBPE"]
#[inline(always)]
pub fn lpvbpe(&self) -> LPVBPE_R {
LPVBPE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - LPVFPE"]
#[inline(always)]
pub fn lpvfpe(&self) -> LPVFPE_R {
LPVFPE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - LPVAE"]
#[inline(always)]
pub fn lpvae(&self) -> LPVAE_R {
LPVAE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - LPHBPE"]
#[inline(always)]
pub fn lphbpe(&self) -> LPHBPE_R {
LPHBPE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - LPHFE"]
#[inline(always)]
pub fn lphfe(&self) -> LPHFE_R {
LPHFE_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - FBTAAE"]
#[inline(always)]
pub fn fbtaae(&self) -> FBTAAE_R {
FBTAAE_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - LPCE"]
#[inline(always)]
pub fn lpce(&self) -> LPCE_R {
LPCE_R::new(((self.bits >> 9) & 0x01) != 0)
}
}
|
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! Generic implementation of a block header.
use crate::codec::{Codec, Decode, Encode, EncodeAsRef, Error, HasCompact, Input, Output};
use crate::generic::Digest;
use crate::traits::{
self, AtLeast32BitUnsigned, Hash as HashT, MaybeDisplay, MaybeMallocSizeOf, MaybeSerialize,
MaybeSerializeDeserialize, Member, SimpleBitOps,
};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_core::U256;
use sp_std::{convert::TryFrom, fmt::Debug};
/// Abstraction over a block header for a substrate chain.
#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
pub struct Header<Number: Copy + Into<U256> + TryFrom<U256>, Hash: HashT> {
/// The parent hash.
pub parent_hash: Hash::Output,
/// The block number.
#[cfg_attr(
feature = "std",
serde(serialize_with = "serialize_number", deserialize_with = "deserialize_number")
)]
pub number: Number,
/// The state trie merkle root
pub state_root: Hash::Output,
/// The merkle root of the extrinsics.
pub extrinsics_root: Hash::Output,
/// A chain-specific digest of data useful for light clients or referencing auxiliary data.
pub digest: Digest<Hash::Output>,
}
#[cfg(feature = "std")]
impl<Number, Hash> parity_util_mem::MallocSizeOf for Header<Number, Hash>
where
Number: Copy + Into<U256> + TryFrom<U256> + parity_util_mem::MallocSizeOf,
Hash: HashT,
Hash::Output: parity_util_mem::MallocSizeOf,
{
fn size_of(&self, ops: &mut parity_util_mem::MallocSizeOfOps) -> usize {
self.parent_hash.size_of(ops) +
self.number.size_of(ops) +
self.state_root.size_of(ops) +
self.extrinsics_root.size_of(ops) +
self.digest.size_of(ops)
}
}
#[cfg(feature = "std")]
pub fn serialize_number<S, T: Copy + Into<U256> + TryFrom<U256>>(
val: &T,
s: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let u256: U256 = (*val).into();
serde::Serialize::serialize(&u256, s)
}
#[cfg(feature = "std")]
pub fn deserialize_number<'a, D, T: Copy + Into<U256> + TryFrom<U256>>(d: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'a>,
{
let u256: U256 = serde::Deserialize::deserialize(d)?;
TryFrom::try_from(u256).map_err(|_| serde::de::Error::custom("Try from failed"))
}
impl<Number, Hash> Decode for Header<Number, Hash>
where
Number: HasCompact + Copy + Into<U256> + TryFrom<U256>,
Hash: HashT,
Hash::Output: Decode,
{
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
Ok(Header {
parent_hash: Decode::decode(input)?,
number: <<Number as HasCompact>::Type>::decode(input)?.into(),
state_root: Decode::decode(input)?,
extrinsics_root: Decode::decode(input)?,
digest: Decode::decode(input)?,
})
}
}
impl<Number, Hash> Encode for Header<Number, Hash>
where
Number: HasCompact + Copy + Into<U256> + TryFrom<U256>,
Hash: HashT,
Hash::Output: Encode,
{
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.parent_hash);
dest.push(&<<<Number as HasCompact>::Type as EncodeAsRef<_>>::RefType>::from(&self.number));
dest.push(&self.state_root);
dest.push(&self.extrinsics_root);
dest.push(&self.digest);
}
}
impl<Number, Hash> codec::EncodeLike for Header<Number, Hash>
where
Number: HasCompact + Copy + Into<U256> + TryFrom<U256>,
Hash: HashT,
Hash::Output: Encode,
{
}
impl<Number, Hash> traits::Header for Header<Number, Hash>
where
Number: Member
+ MaybeSerializeDeserialize
+ Debug
+ sp_std::hash::Hash
+ MaybeDisplay
+ AtLeast32BitUnsigned
+ Codec
+ Copy
+ Into<U256>
+ TryFrom<U256>
+ sp_std::str::FromStr
+ MaybeMallocSizeOf,
Hash: HashT,
Hash::Output: Default
+ sp_std::hash::Hash
+ Copy
+ Member
+ Ord
+ MaybeSerialize
+ Debug
+ MaybeDisplay
+ SimpleBitOps
+ Codec
+ MaybeMallocSizeOf,
{
type Number = Number;
type Hash = <Hash as HashT>::Output;
type Hashing = Hash;
fn number(&self) -> &Self::Number {
&self.number
}
fn set_number(&mut self, num: Self::Number) {
self.number = num
}
fn extrinsics_root(&self) -> &Self::Hash {
&self.extrinsics_root
}
fn set_extrinsics_root(&mut self, root: Self::Hash) {
self.extrinsics_root = root
}
fn state_root(&self) -> &Self::Hash {
&self.state_root
}
fn set_state_root(&mut self, root: Self::Hash) {
self.state_root = root
}
fn parent_hash(&self) -> &Self::Hash {
&self.parent_hash
}
fn set_parent_hash(&mut self, hash: Self::Hash) {
self.parent_hash = hash
}
fn digest(&self) -> &Digest<Self::Hash> {
&self.digest
}
fn digest_mut(&mut self) -> &mut Digest<Self::Hash> {
#[cfg(feature = "std")]
log::debug!(target: "header", "Retrieving mutable reference to digest");
&mut self.digest
}
fn new(
number: Self::Number,
extrinsics_root: Self::Hash,
state_root: Self::Hash,
parent_hash: Self::Hash,
digest: Digest<Self::Hash>,
) -> Self {
Header { number, extrinsics_root, state_root, parent_hash, digest }
}
}
impl<Number, Hash> Header<Number, Hash>
where
Number: Member
+ sp_std::hash::Hash
+ Copy
+ MaybeDisplay
+ AtLeast32BitUnsigned
+ Codec
+ Into<U256>
+ TryFrom<U256>,
Hash: HashT,
Hash::Output:
Default + sp_std::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Codec,
{
/// Convenience helper for computing the hash of the header without having
/// to import the trait.
pub fn hash(&self) -> Hash::Output {
Hash::hash_of(self)
}
}
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
#[test]
fn should_serialize_numbers() {
fn serialize(num: u128) -> String {
let mut v = vec![];
{
let mut ser = serde_json::Serializer::new(std::io::Cursor::new(&mut v));
serialize_number(&num, &mut ser).unwrap();
}
String::from_utf8(v).unwrap()
}
assert_eq!(serialize(0), "\"0x0\"".to_owned());
assert_eq!(serialize(1), "\"0x1\"".to_owned());
assert_eq!(serialize(u64::max_value() as u128), "\"0xffffffffffffffff\"".to_owned());
assert_eq!(serialize(u64::max_value() as u128 + 1), "\"0x10000000000000000\"".to_owned());
}
#[test]
fn should_deserialize_number() {
fn deserialize(num: &str) -> u128 {
let mut der = serde_json::Deserializer::new(serde_json::de::StrRead::new(num));
deserialize_number(&mut der).unwrap()
}
assert_eq!(deserialize("\"0x0\""), 0);
assert_eq!(deserialize("\"0x1\""), 1);
assert_eq!(deserialize("\"0xffffffffffffffff\""), u64::max_value() as u128);
assert_eq!(deserialize("\"0x10000000000000000\""), u64::max_value() as u128 + 1);
}
}
|
#![no_std]
#![feature(lang_items, core_intrinsics)]
use core::intrinsics;
use core::panic::PanicInfo;
use core::alloc::{GlobalAlloc, Layout};
use core::fmt;
use core::fmt::Write;
extern {
fn malloc(size: usize) -> *mut u8;
fn free(ptr: *mut u8);
fn write(file: isize, buffer: *const u8, count: usize) -> usize;
}
struct LibcAllocator;
unsafe impl GlobalAlloc for LibcAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if layout.align() > 8 {
panic!("Unsupported alignment")
}
malloc(layout.size())
}
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
free(ptr)
}
}
struct Stdout;
impl fmt::Write for Stdout {
fn write_str(&mut self, s: &str) -> fmt::Result {
unsafe {
let buffer = s.as_bytes();
if write(0, buffer.as_ptr(), buffer.len()) > 0 {
Ok(())
} else {
Err(()).map_err(|_| fmt::Error)
}
}
}
}
fn stdout() -> Stdout {
Stdout
}
fn print_str(s: &str) -> Result<(), ()> {
stdout().write_str(s).map_err(drop)
}
fn print_fmt(args: fmt::Arguments) -> Result<(), ()> {
stdout().write_fmt(args).map_err(drop)
}
#[global_allocator]
static A: LibcAllocator = LibcAllocator;
#[no_mangle]
pub extern fn rust_main() {
print_str("Hello from Rust!\n");
print_fmt(format_args!("Hello formatted from {}\n", "Rust"));
}
#[lang = "panic_impl"]
#[no_mangle]
pub extern fn rust_begin_panic(_info: &PanicInfo) -> ! {
unsafe { intrinsics::abort() }
}
|
// -*- mode: rust; -*-
//
// To the extent possible under law, the authors have waived all copyright and
// related or neighboring rights to curve25519-dalek, using the Creative
// Commons "CC0" public domain dedication. See
// <http://creativecommons.org/publicdomain/zero/.0/> for full details.
//
// Authors:
// - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
//! An implementation of Mike Hamburg's Decaf cofactor-eliminating
//! point-compression scheme, providing a prime-order group on top of
//! a non-prime-order elliptic curve.
//!
//! Note: this code is currently feature-gated with the `yolocrypto`
//! feature flag, because our implementation is still unfinished.
// We allow non snake_case names because coordinates in projective space are
// traditionally denoted by the capitalisation of their respective
// counterparts in affine space. Yeah, you heard me, rustc, I'm gonna have my
// affine and projective cakes and eat both of them too.
#![allow(non_snake_case)]
use core::fmt::Debug;
use constants;
use field::FieldElement;
use subtle::CTAssignable;
use subtle::CTNegatable;
use core::ops::{Add, Sub, Neg};
use curve::ExtendedPoint;
use curve::BasepointMult;
use curve::ScalarMult;
use curve::Identity;
use scalar::Scalar;
// ------------------------------------------------------------------------
// Compressed points
// ------------------------------------------------------------------------
/// A point serialized using Mike Hamburg's Decaf scheme.
///
/// XXX think about how this API should work
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct CompressedDecaf(pub [u8; 32]);
/// The result of compressing a `DecafPoint`.
impl CompressedDecaf {
/// View this `CompressedDecaf` as an array of bytes.
pub fn to_bytes(&self) -> [u8;32] {
self.0
}
/// Attempt to decompress to an `DecafPoint`.
pub fn decompress(&self) -> Option<DecafPoint> {
// XXX should decoding be CT ?
// XXX need to check that xy is nonnegative and reject otherwise
let s = FieldElement::from_bytes(&self.0);
// Check that s = |s| and reject otherwise.
let mut abs_s = s;
let neg = abs_s.is_negative_decaf();
abs_s.conditional_negate(neg);
if abs_s != s { return None; }
let ss = s.square();
let X = &s + &s; // X = 2s
let Z = &FieldElement::one() - &ss; // Z = 1+as^2
let u = &(&Z * &Z) - &(&constants::d4 * &ss); // u = Z^2 - 4ds^2
let uss = &u * &ss;
let mut v = match uss.invsqrt() {
Some(v) => v,
None => return None,
};
// Now v = 1/sqrt(us^2) if us^2 is a nonzero square, 0 if us^2 is zero.
let uv = &v * &u;
if uv.is_negative_decaf() == 1u8 {
v.negate();
}
let mut two_minus_Z = -&Z; two_minus_Z[0] += 2;
let mut w = &v * &(&s * &two_minus_Z);
w.conditional_assign(&FieldElement::one(), s.is_zero());
let Y = &w * &Z;
let T = &w * &X;
// "To decode the point, one must decode it to affine form
// instead of projective, and check that xy is non-negative."
//
// XXX can we merge this inversion with the one above?
let xy = &T * &Z.invert();
if (Y.is_nonzero() & xy.is_nonnegative_decaf()) == 1u8 {
Some(DecafPoint(ExtendedPoint{ X: X, Y: Y, Z: Z, T: T }))
} else {
None
}
}
}
impl Identity for CompressedDecaf {
fn identity() -> CompressedDecaf {
CompressedDecaf([0u8;32])
}
}
/// A point in a prime-order group.
///
/// XXX think about how this API should work
#[derive(Copy, Clone)]
pub struct DecafPoint(pub ExtendedPoint);
impl DecafPoint {
/// Compress in Decaf format.
pub fn compress(&self) -> CompressedDecaf {
// Q: Do we want to encode twisted or untwisted?
//
// Notes:
// Recall that the twisted Edwards curve E_{a,d} is of the form
//
// ax^2 + y^2 = 1 + dx^2y^2.
//
// Internally, we operate on the curve with a = -1, d =
// -121665/121666, a.k.a., the twist. But maybe we would like
// to use Decaf on the untwisted curve with a = 1, d =
// 121665/121666. (why? interop?)
//
// Fix i, a square root of -1 (mod p).
//
// The map x -> ix is an isomorphism from E_{a,d} to E_{-a,-d}.
// Its inverse is x -> -ix.
// let untwisted_X = &self.X * &constants::MSQRT_M1;
// etc.
// Step 0: pre-rotation, needed for Decaf with E[8] = Z/8
let mut X = self.0.X;
let mut Y = self.0.Y;
let mut T = self.0.T;
// If y nonzero and xy nonnegative, continue.
// Otherwise, add Q_6 = (i,0) = constants::EIGHT_TORSION[6]
// (x,y) + Q_6 = (iy,ix)
// (X:Y:Z:T) + Q_6 = (iY:iX:Z:-T)
// XXX it should be possible to avoid this inversion, but
// let's make sure the code is correct first
let xy = &T * &self.0.Z.invert();
let is_neg_mask = 1u8 & !(Y.is_nonzero() & xy.is_nonnegative_decaf());
let iX = &X * &constants::SQRT_M1;
let iY = &Y * &constants::SQRT_M1;
X.conditional_assign(&iY, is_neg_mask);
Y.conditional_assign(&iX, is_neg_mask);
T.conditional_negate(is_neg_mask);
// Step 1: Compute r = 1/sqrt((a-d)(Z+Y)(Z-Y))
let Z_plus_Y = &self.0.Z + &Y;
let Z_minus_Y = &self.0.Z - &Y;
let t = &constants::a_minus_d * &(&Z_plus_Y * &Z_minus_Y);
// t should always be square (why?)
// XXX is it safe to use option types here?
let mut r = t.invsqrt().unwrap();
// Step 2: Compute u = (a-d)r
let u = &constants::a_minus_d * &r;
// Step 3: Negate r if -2uZ is negative.
let uZ = &u * &self.0.Z;
let m2uZ = -&(&uZ + &uZ);
r.conditional_negate(m2uZ.is_negative_decaf());
// Step 4: Compute s = | u(r(aZX - dYT)+Y)/a|
// = |u(r(-ZX - dYT)+Y)| since a = -1
let minus_ZX = -&(&self.0.Z * &X);
let dYT = &constants::d * &(&Y * &T);
// Compute s = u(r(aZX - dYT)+Y) and cnegate for abs
let mut s = &u * &(&(&r * &(&minus_ZX - &dYT)) + &Y);
let neg = s.is_negative_decaf();
s.conditional_negate(neg);
CompressedDecaf(s.to_bytes())
}
/// Return the coset self + E[4], for debugging.
fn coset4(&self) -> [ExtendedPoint; 4] {
[ self.0
, &self.0 + &constants::EIGHT_TORSION[2]
, &self.0 + &constants::EIGHT_TORSION[4]
, &self.0 + &constants::EIGHT_TORSION[6]
]
}
}
impl Identity for DecafPoint {
fn identity() -> DecafPoint {
DecafPoint(ExtendedPoint::identity())
}
}
// ------------------------------------------------------------------------
// Equality
// ------------------------------------------------------------------------
/// XXX check whether there's a simple way to do equality checking
/// with cofactor 8, not just cofactor 4, and add a CT equality function?
impl PartialEq for DecafPoint {
fn eq(&self, other: &DecafPoint) -> bool {
let self_compressed = self.compress();
let other_compressed = other.compress();
self_compressed == other_compressed
}
}
impl Eq for DecafPoint {}
// ------------------------------------------------------------------------
// Arithmetic
// ------------------------------------------------------------------------
impl<'a, 'b> Add<&'b DecafPoint> for &'a DecafPoint {
type Output = DecafPoint;
fn add(self, other: &'b DecafPoint) -> DecafPoint {
DecafPoint(&self.0 + &other.0)
}
}
impl<'a, 'b> Sub<&'b DecafPoint> for &'a DecafPoint {
type Output = DecafPoint;
fn sub(self, other: &'b DecafPoint) -> DecafPoint {
DecafPoint(&self.0 - &other.0)
}
}
impl<'a> Neg for &'a DecafPoint {
type Output = DecafPoint;
fn neg(self) -> DecafPoint {
DecafPoint(-&self.0)
}
}
impl ScalarMult<Scalar> for DecafPoint {
fn scalar_mult(&self, scalar: &Scalar) -> DecafPoint {
DecafPoint(self.0.scalar_mult(scalar))
}
}
impl BasepointMult<Scalar> for DecafPoint {
// XXX is this actually in the image of the isogeny,
// or do we need a different basepoint?
fn basepoint() -> DecafPoint {
DecafPoint(constants::BASEPOINT)
}
fn basepoint_mult(scalar: &Scalar) -> DecafPoint {
DecafPoint(ExtendedPoint::basepoint_mult(scalar))
}
}
// ------------------------------------------------------------------------
// Debug traits
// ------------------------------------------------------------------------
impl Debug for CompressedDecaf {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "CompressedDecaf: {:?}", &self.0[..])
}
}
impl Debug for DecafPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let coset = self.coset4();
write!(f, "DecafPoint: coset \n{:?}\n{:?}\n{:?}\n{:?}",
coset[0], coset[1], coset[2], coset[3])
}
}
// ------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------
#[cfg(test)]
mod test {
use rand::OsRng;
use scalar::Scalar;
use constants;
use constants::BASE_CMPRSSD;
use curve::CompressedEdwardsY;
use curve::ExtendedPoint;
use curve::BasepointMult;
use curve::Identity;
use super::*;
#[test]
#[should_panic]
fn test_decaf_decompress_negative_s_fails() {
// constants::d is neg, so decompression should fail as |d| != d.
let bad_compressed = CompressedDecaf(constants::d.to_bytes());
bad_compressed.decompress().unwrap();
}
#[test]
fn test_decaf_decompress_id() {
let compressed_id = CompressedDecaf::identity();
let id = compressed_id.decompress().unwrap();
// This should compress (as ed25519) to the following:
let mut bytes = [0u8; 32]; bytes[0] = 1;
assert_eq!(id.0.compress(), CompressedEdwardsY(bytes));
}
#[test]
fn test_decaf_compress_id() {
let id = DecafPoint::identity();
assert_eq!(id.compress(), CompressedDecaf::identity());
}
#[test]
fn test_decaf_basepoint_roundtrip() {
let bp_compressed_decaf = DecafPoint::basepoint().compress();
let bp_recaf = bp_compressed_decaf.decompress().unwrap().0;
// Check that bp_recaf differs from bp by a point of order 4
let diff = &ExtendedPoint::basepoint() - &bp_recaf;
let diff4 = diff.mult_by_pow_2(4);
assert_eq!(diff4.compress(), ExtendedPoint::identity().compress());
}
#[test]
fn test_decaf_four_torsion_basepoint() {
let bp = DecafPoint::basepoint();
let bp_coset = bp.coset4();
for i in 0..4 {
assert_eq!(bp, DecafPoint(bp_coset[i]));
}
}
#[test]
fn test_decaf_four_torsion_random() {
let mut rng = OsRng::new().unwrap();
let s = Scalar::random(&mut rng);
let P = DecafPoint::basepoint_mult(&s);
let P_coset = P.coset4();
for i in 0..4 {
assert_eq!(P, DecafPoint(P_coset[i]));
}
}
#[test]
fn test_decaf_random_roundtrip() {
let mut rng = OsRng::new().unwrap();
for j in 0..100 {
let s = Scalar::random(&mut rng);
let P = DecafPoint::basepoint_mult(&s);
let compressed_P = P.compress();
let Q = compressed_P.decompress().unwrap();
for i in 0..4 {
assert_eq!(P, Q);
}
}
}
}
#[cfg(test)]
mod bench {
use rand::OsRng;
use test::Bencher;
use super::*;
#[bench]
fn decompression(b: &mut Bencher) {
let mut rng = OsRng::new().unwrap();
let s = Scalar::random(&mut rng);
let P = DecafPoint::basepoint_mult(&s);
let P_compressed = P.compress();
b.iter(|| P_compressed.decompress().unwrap());
}
#[bench]
fn compression(b: &mut Bencher) {
let mut rng = OsRng::new().unwrap();
let s = Scalar::random(&mut rng);
let P = DecafPoint::basepoint_mult(&s);
b.iter(|| P.compress());
}
}
|
use crate::category::Category;
use crate::error::Error;
use crate::image::Image;
use crate::location::Location;
use crate::rating::Rating;
use crate::schema::TABLES;
use rusqlite::{params, Connection};
use std::path::Path;
#[derive(Debug)]
pub struct Store {
con: Connection,
}
impl Store {
pub fn create(path: &Path) -> Result<Self, Error> {
let con = Connection::open(path)?;
for item in TABLES {
let _ = con.execute(item, params![])?;
}
Ok(Store { con })
}
pub fn open(path: &Path) -> Result<Self, Error> {
if !path.is_file() {
return Err(Error::NotAFile(path.to_path_buf()));
}
let con = Connection::open(path)?;
Ok(Store { con })
}
pub fn put_image(&self, hash: &str, path: &Path) -> Result<Image, Error> {
let sql = r#"
INSERT INTO image (hash, path)
VALUES (?1, ?2)
"#;
if hash.is_empty() {
return Err(Error::EmptyHash);
}
if !path.is_file() {
return Err(Error::NotAFile(path.to_path_buf()));
}
let path_str_rep = path.to_str().ok_or(Error::PathConversion)?;
let _ = self.con.execute(sql, params![hash, path_str_rep])?;
let id = self.con.last_insert_rowid();
let sql = r#"
SELECT id, hash, path
FROM image
WHERE id = ?1
"#;
let result = self.con.query_row(sql, params![id], |row| {
let path_as_string: String = row.get(2)?;
Ok(Image {
id: row.get(0)?,
hash: row.get(1)?,
path: Path::new(&path_as_string).to_path_buf(),
})
});
match result {
Ok(image) => Ok(image),
Err(e) => Err(Error::Rusqlite(e)),
}
}
pub fn put_image_location(
&self,
name: &str,
latitude: f32,
longitude: f32,
) -> Result<Location, Error> {
let sql = r#"
INSERT INTO image_location (name, latitude, longitude)
VALUES (?1, ?2, ?3)
"#;
if name.is_empty() {
return Err(Error::EmptyLocationName);
}
if latitude < -90.0 || latitude > 90.0 {
return Err(Error::InvalidLatitude(latitude));
}
if longitude < -180.0 || longitude > 180.0 {
return Err(Error::InvalidLongitude(longitude));
}
let _ = self.con.execute(sql, params![name, latitude, longitude])?;
let id = self.con.last_insert_rowid();
let sql = r#"
SELECT id, name, latitude, longitude
FROM image_location
WHERE id = ?1
"#;
let result = self.con.query_row(sql, params![id], |row| {
Ok(Location {
id: row.get(0)?,
name: row.get(1)?,
latitude: row.get(2)?,
longitude: row.get(3)?,
})
});
match result {
Ok(location) => Ok(location),
Err(e) => Err(Error::Rusqlite(e)),
}
}
pub fn put_image_rating_value(&self, rating: i64) -> Result<Rating, Error> {
let sql = r#"
INSERT INTO image_rating_value (value)
VALUES (?1)
"#;
let _ = self.con.execute(sql, params![rating])?;
let value = self.con.last_insert_rowid();
Ok(Rating { value })
}
pub fn put_image_category_value(&self, value: &str) -> Result<Category, Error> {
let sql = r#"
INSERT INTO image_category_value (value)
VALUES (?1)
"#;
if value.is_empty() {
return Err(Error::EmptyCategory);
}
let _ = self.con.execute(sql, params![value])?;
let sql = r#"
SELECT value
FROM image_category_value
WHERE value = ?1
"#;
let result = self.con.query_row(sql, params![value], |row| {
Ok(Category { value: row.get(0)? })
});
match result {
Ok(category) => Ok(category),
Err(e) => Err(Error::Rusqlite(e)),
}
}
pub fn put_image_locations(&self, image: &Image, location: &Location) -> Result<i64, Error> {
let sql = r#"
INSERT INTO image_locations (image_id, image_location_id)
VALUES (?1, ?2)
"#;
let _ = self.con.execute(sql, params![image.id, location.id])?;
let id = self.con.last_insert_rowid();
Ok(id)
}
pub fn put_image_ratings(&self, image: &Image, rating: &Rating) -> Result<i64, Error> {
let sql = r#"
INSERT INTO image_ratings (image_id, image_rating_value_value)
VALUES (?1, ?2)
"#;
let _ = self.con.execute(sql, params![image.id, rating.value])?;
let id = self.con.last_insert_rowid();
Ok(id)
}
pub fn put_image_categories(&self, image: &Image, category: &Category) -> Result<i64, Error> {
let sql = r#"
INSERT INTO image_categories (image_id, image_category_value_value)
VALUES (?1, ?2)
"#;
let _ = self.con.execute(sql, params![image.id, category.value])?;
let id = self.con.last_insert_rowid();
Ok(id)
}
pub fn select_image(&self) -> Result<Option<Vec<Image>>, Error> {
let sql = r#"
SELECT id, hash, path
FROM image
"#;
let mut statement = self.con.prepare(sql)?;
let iter = statement.query_map(params![], |row| {
let path_rep: String = row.get(2)?;
Ok(Image {
id: row.get(0)?,
hash: row.get(1)?,
path: Path::new(&path_rep).to_path_buf(),
})
})?;
let mut images: Vec<Image> = Vec::new();
for image in iter {
images.push(image?);
}
if images.is_empty() {
return Ok(None);
}
Ok(Some(images))
}
pub fn select_image_path_like(&self, like: &str) -> Result<Option<Vec<Image>>, Error> {
let sql = r#"
SELECT id, hash, path
FROM image
WHERE LIKE(?1, path)
"#;
let mut statement = self.con.prepare(sql)?;
let hack = format!("%{}%", like);
let iter = statement.query_map(params![&hack], |row| {
let path_rep: String = row.get(2)?;
Ok(Image {
id: row.get(0)?,
hash: row.get(1)?,
path: Path::new(&path_rep).to_path_buf(),
})
})?;
let mut images: Vec<Image> = Vec::new();
for image in iter {
images.push(image?);
}
if images.is_empty() {
return Ok(None);
}
Ok(Some(images))
}
}
|
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
use crate::{
core::set::{from_timestamp, SetObject},
Get, Set,
};
use super::VacationResponse;
impl VacationResponse<Set> {
pub fn is_enabled(&mut self, is_enabled: bool) -> &mut Self {
self.is_enabled = Some(is_enabled);
self
}
pub fn from_date(&mut self, from_date: Option<i64>) -> &mut Self {
self.from_date = from_date.map(from_timestamp);
self
}
pub fn to_date(&mut self, to_date: Option<i64>) -> &mut Self {
self.to_date = to_date.map(from_timestamp);
self
}
pub fn subject(&mut self, subject: Option<impl Into<String>>) -> &mut Self {
self.subject = subject.map(|s| s.into());
self
}
pub fn text_body(&mut self, text_body: Option<impl Into<String>>) -> &mut Self {
self.text_body = text_body.map(|s| s.into());
self
}
pub fn html_body(&mut self, html_body: Option<impl Into<String>>) -> &mut Self {
self.html_body = html_body.map(|s| s.into());
self
}
}
impl SetObject for VacationResponse<Set> {
type SetArguments = ();
fn new(_create_id: Option<usize>) -> Self {
VacationResponse {
_create_id,
_state: Default::default(),
id: None,
is_enabled: None,
from_date: from_timestamp(0).into(),
to_date: from_timestamp(0).into(),
subject: "".to_string().into(),
text_body: "".to_string().into(),
html_body: "".to_string().into(),
}
}
fn create_id(&self) -> Option<String> {
self._create_id.map(|id| format!("c{}", id))
}
}
impl SetObject for VacationResponse<Get> {
type SetArguments = ();
fn new(_create_id: Option<usize>) -> Self {
unimplemented!()
}
fn create_id(&self) -> Option<String> {
None
}
}
|
use flux::semantic::walk::Node as WalkNode;
use lspower::lsp;
pub struct ExperimentalDiagnosticVisitor {
namespaces: Vec<String>,
pub diagnostics: Vec<(Option<String>, lsp::Diagnostic)>,
}
impl Default for ExperimentalDiagnosticVisitor {
fn default() -> Self {
Self {
diagnostics: vec![],
namespaces: vec!["experimental".into()],
}
}
}
impl<'a> flux::semantic::walk::Visitor<'a>
for ExperimentalDiagnosticVisitor
{
fn visit(&mut self, node: WalkNode<'a>) -> bool {
match node {
WalkNode::Package(pkg) => {
// Is there an experimental import in this package? If not,
// don't keep going. There's nothing to check here.
let mut imports_experimental = false;
pkg.files.iter().for_each(|file| {
file.imports.iter().for_each(|import| {
if import.path.value.starts_with("experimental") {
imports_experimental = true;
if let Some(alias) = &import.alias {
self.namespaces
.push(format!("{}", alias.name));
} else {
let split: Vec<&str> = import
.path
.value
.split('/')
.collect();
if split.len() > 1 {
if let Some(namespace) = split.last() {
self.namespaces.push(namespace.to_string());
}
}
}
}
})
});
return imports_experimental;
},
WalkNode::CallExpr(expr) => {
match &expr.callee {
flux::semantic::nodes::Expression::Identifier(id) => {
if self.namespaces.contains(&format!("{}", id.name)) {
self.diagnostics.push((expr.loc.file.clone(), lsp::Diagnostic {
range: expr.loc.clone().into(),
severity: Some(lsp::DiagnosticSeverity::HINT),
message: "experimental features can change often or be deleted/moved. Use with caution.".into(),
..lsp::Diagnostic::default()
}));
}
}
flux::semantic::nodes::Expression::Member(member) => {
if let flux::semantic::nodes::Expression::Identifier(id) = &member.object {
if self.namespaces.contains(&format!("{}", id.name)) {
self.diagnostics.push((expr.loc.file.clone(), lsp::Diagnostic {
range: expr.loc.clone().into(),
severity: Some(lsp::DiagnosticSeverity::HINT),
message: "experimental features can change often or be deleted/moved. Use with caution.".into(),
..lsp::Diagnostic::default()
}));
}
}
}
_ => {}
}
}
_ => {},
}
true
}
}
#[derive(Default)]
pub struct ContribDiagnosticVisitor {
namespaces: Vec<String>,
pub diagnostics: Vec<(Option<String>, lsp::Diagnostic)>,
}
impl<'a> flux::semantic::walk::Visitor<'a>
for ContribDiagnosticVisitor
{
fn visit(&mut self, node: WalkNode<'a>) -> bool {
match node {
WalkNode::Package(pkg) => {
// Is there a contrib import in this package? If not,
// don't keep going. There's nothing to check here.
let mut imports_from_contrib = false;
pkg.files.iter().for_each(|file| {
file.imports.iter().for_each(|import| {
if import.path.value.starts_with("contrib") {
imports_from_contrib = true;
if let Some(alias) = &import.alias {
self.namespaces
.push(format!("{}", alias.name));
} else {
let split: Vec<&str> = import
.path
.value
.split('/')
.collect();
if split.len() > 1 {
if let Some(namespace) = split.last()
{
self.namespaces
.push(namespace.to_string());
}
}
}
}
})
});
return imports_from_contrib;
},
WalkNode::CallExpr(expr) => {
match &expr.callee {
flux::semantic::nodes::Expression::Identifier(id) => {
if self.namespaces.contains(&format!("{}", id.name)) {
self.diagnostics.push((id.loc.file.clone(), lsp::Diagnostic {
range: expr.loc.clone().into(),
severity: Some(lsp::DiagnosticSeverity::HINT),
message: "contrib packages are user-contributed, and do not carry with them the same compatibility guarantees as the standard library. Use with caution.".into(),
..lsp::Diagnostic::default()
}));
}
}
flux::semantic::nodes::Expression::Member(member) => {
if let flux::semantic::nodes::Expression::Identifier(id) = &member.object {
if self.namespaces.contains(&id.name.to_string()) {
self.diagnostics.push((id.loc.file.clone(), lsp::Diagnostic {
range: expr.loc.clone().into(),
severity: Some(lsp::DiagnosticSeverity::HINT),
message: "contrib packages are user-contributed, and do not carry with them the same compatibility guarantees as the standard library. Use with caution.".into(),
..lsp::Diagnostic::default()
}));
}
}
}
_ => {}
}
}
_ => {},
}
true
}
}
pub struct InfluxDBIdentifierDiagnosticVisitor {
names: Vec<String>,
pub diagnostics: Vec<(Option<String>, lsp::Diagnostic)>,
}
impl Default for InfluxDBIdentifierDiagnosticVisitor {
fn default() -> Self {
Self {
diagnostics: vec![],
names: vec!["v".into(), "task".into(), "params".into()],
}
}
}
impl<'a> flux::semantic::walk::Visitor<'a>
for InfluxDBIdentifierDiagnosticVisitor
{
fn visit(&mut self, node: WalkNode<'a>) -> bool {
if let WalkNode::VariableAssgn(assign) = node {
if self.names.contains(&assign.id.name.to_string()) {
self.diagnostics.push((assign.loc.file.clone(), lsp::Diagnostic {
range: assign.id.loc.clone().into(),
severity: Some(lsp::DiagnosticSeverity::WARNING),
message: format!("Avoid using `{}` as an identifier name. In some InfluxDB contexts, it may be provided at runtime.", assign.id.name),
..lsp::Diagnostic::default()
}));
}
}
true
}
}
|
//! A simple Driver for the Waveshare E-Ink Displays via SPI
//!
//! This driver was built using [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal/~0.1
//!
//! # Requirements
//!
//! ### SPI
//!
//! - MISO is not connected/available
//! - SPI_MODE_0 is used (CPHL = 0, CPOL = 0)
//! - 8 bits per word, MSB first
//! - Max. Speed tested by myself was 8Mhz but more should be possible (Ben Krasnow used 18Mhz with his implemenation)
//!
//! ### Other....
//!
//! - Buffersize: Wherever a buffer is used it always needs to be of the size: `width / 8 * length`,
//! where width and length being either the full e-ink size or the partial update window size
//!
//! # Examples
//!
//! ```ignore
//! use eink-waveshare-rs::epd4in2::EPD4in2;
//!
//! let mut epd4in2 = EPD4in2::new(spi, cs, busy, dc, rst, delay).unwrap();
//!
//! let mut buffer = [0u8, epd4in2.get_width() / 8 * epd4in2.get_height()];
//!
//! // draw something into the buffer
//!
//! epd4in2.display_and_transfer_buffer(buffer, None);
//!
//! // wait and look at the image
//!
//! epd4in2.clear_frame(None);
//!
//! epd4in2.sleep();
//! ```
//!
//!
#![no_std]
#[cfg(feature = "graphics")]
extern crate embedded_graphics;
#[cfg(feature = "graphics")]
pub mod graphics;
mod traits;
pub mod color;
/// Interface for the physical connection between display and the controlling device
mod interface;
#[cfg(feature = "epd4in2")]
pub mod epd4in2;
#[cfg(feature = "epd1in54")]
pub mod epd1in54;
#[cfg(feature = "epd2in9")]
pub mod epd2in9;
#[cfg(any(feature = "epd1in54", feature = "epd2in9"))]
pub(crate) mod type_a;
pub mod prelude {
pub use color::Color;
pub use traits::{RefreshLUT, WaveshareDisplay};
pub use SPI_MODE;
}
extern crate embedded_hal as hal;
use hal::spi::{Mode, Phase, Polarity};
/// SPI mode -
/// For more infos see [Requirements: SPI](index.html#spi)
pub const SPI_MODE: Mode = Mode {
phase: Phase::CaptureOnFirstTransition,
polarity: Polarity::IdleLow,
};
|
struct Solution();
impl Solution {
pub fn climb_stairs(n: i32) -> i32 {
if n == 1{
return 1;
}
let n = n as usize;
let mut stairs=vec![1;n];
stairs[1]=2;
for i in 2..n{
stairs[i]=stairs[i-1]+stairs[i-2];
}
stairs[n-1]
}
}
fn main(){
println!("{}",Solution::climb_stairs(2));
println!("{}",Solution::climb_stairs(3));
println!("{}",Solution::climb_stairs(1));
} |
#![feature(concat_idents)]
mod app;
use app::{App, Status};
use log::{debug, warn};
use std::path::{Path, PathBuf};
use std::io::{self, Read, Write};
use std::sync::{Arc, RwLock, Mutex};
use std::thread;
use std::sync::mpsc;
use tui::{ backend::{CrosstermBackend, Backend}, Terminal };
use fern::colors::{Color, ColoredLevelConfig};
use crossterm::{
event::{self, Event as CEvent, KeyEvent, MouseEvent, KeyCode, KeyModifiers, MouseButton},
execute,
ExecutableCommand,
cursor,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum Event {
Tick,
CharKey(char),
CtrlKey(char),
Up,
Down,
Left,
Right,
ScrollUp(u16, u16),
ScrollDown(u16, u16),
Press(u16, u16),
Enter,
Backspace,
Esc,
Unsupported(String),
}
impl From<CEvent> for Event {
fn from(event: CEvent) -> Self {
match event {
CEvent::Key(KeyEvent { code: KeyCode::Char(c), modifiers: KeyModifiers::NONE }) => Self::CharKey(c),
CEvent::Key(KeyEvent { code: KeyCode::Char(c), modifiers: KeyModifiers::SHIFT }) => Self::CharKey(c),
CEvent::Key(KeyEvent { code: KeyCode::Char(c), modifiers: KeyModifiers::CONTROL }) => Self::CtrlKey(c),
CEvent::Key(KeyEvent { code: KeyCode::Up, modifiers: _ }) => Self::Up,
CEvent::Key(KeyEvent { code: KeyCode::Down, modifiers: _ }) => Self::Down,
CEvent::Key(KeyEvent { code: KeyCode::Left, modifiers: _ }) => Self::Left,
CEvent::Key(KeyEvent { code: KeyCode::Right, modifiers: _ }) => Self::Right,
CEvent::Key(KeyEvent { code: KeyCode::Enter, modifiers: _ }) => Self::Enter,
CEvent::Key(KeyEvent { code: KeyCode::Backspace, modifiers: _ }) => Self::Backspace,
CEvent::Key(KeyEvent { code: KeyCode::Esc, modifiers: _ }) => Self::Esc,
CEvent::Mouse(MouseEvent::Down(MouseButton::Left, xpos, ypos, KeyModifiers::NONE)) =>
Self::Press(xpos, ypos),
CEvent::Mouse(MouseEvent::ScrollDown(xpos, ypos, KeyModifiers::NONE)) =>
Self::ScrollDown(xpos, ypos),
CEvent::Mouse(MouseEvent::ScrollUp(xpos, ypos, KeyModifiers::NONE)) =>
Self::ScrollUp(xpos, ypos),
e =>
Self::Unsupported(format!("{:?}", e)),
}
}
}
pub struct Events {
rx: mpsc::Receiver<Event>,
}
impl Events {
pub fn new(tick_rate: std::time::Duration) -> Self {
assert!(tick_rate >= std::time::Duration::from_millis(100), "tick_rate to small");
let (tx, rx) = mpsc::channel();
{
let tx = tx.clone();
thread::spawn(move || {
let mut last_tick = std::time::Instant::now();
loop {
if event::poll(tick_rate-last_tick.elapsed()).unwrap() {
if let Ok(event) = event::read() {
tx.send(event.into()).unwrap();
}
}
if last_tick.elapsed() >= tick_rate {
let _ = tx.send(Event::Tick);
last_tick = std::time::Instant::now();
}
}
})
};
Self { rx }
}
pub fn next(&self) -> Result<Event, mpsc::RecvError> {
self.rx.recv()
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
dotenv::dotenv()?;
let level: log::LevelFilter = std::env::var("RUST_LOG").unwrap_or("debug".to_string()).parse()?;
//let colors = ColoredLevelConfig::new().info(Color::Green);
let (tx, rx) = mpsc::channel();
fern::Dispatch::new()
.level(level)
// .chain(
// fern::Dispatch::new()
// .format(move |out, message, record| {
// out.finish(format_args!(
// "[{} {:<5} {}] {}",
// chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S.%3f"),
// colors.color(record.level()),
// record.target(),
// message
// ))
// })
// .chain(std::io::stdout())
// )
.chain(
fern::Dispatch::new()
.format(move |out, message, record| {
out.finish(format_args!(
"[{} {:<5} {}] {}",
chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S"),
record.level(),
record.target(),
message
))
})
.chain(fern::log_file("output.log")?)
.chain(tx)
)
.apply()?;
enable_raw_mode()?;
let backend = CrosstermBackend::new(io::stdout());
let mut terminal = Terminal::new(backend)?;
terminal.backend_mut().execute(EnterAlternateScreen)?;
terminal.backend_mut().execute(event::EnableMouseCapture)?;
terminal.clear()?;
terminal.hide_cursor()?;
let events = Events::new(std::time::Duration::from_millis(250));
let mut app = App::new(rx); let mut cursor_show = false; let mut app_state_insert = false;
loop {
terminal.draw(|f| app.draw(f))?;
match events.next()? {
Event::CharKey('q') if !app_state_insert => {
disable_raw_mode()?;
terminal.backend_mut().execute(LeaveAlternateScreen)?;
terminal.backend_mut().execute(event::DisableMouseCapture)?;
terminal.show_cursor()?;
break;
}
e => app.on_event(e),
}
match app.status {
Status::Insert(ref m) => {
if !app_state_insert {
app_state_insert = true;
}
let rect = terminal.backend_mut().size()?;
if !cursor_show {
terminal.backend_mut().execute(cursor::Show)?;
cursor_show = true;
}
terminal.backend_mut().execute(cursor::MoveTo(m.len() as u16 + 1, rect.height))?;
},
_ => {
if app_state_insert {
app_state_insert = false;
}
if cursor_show {
terminal.backend_mut().execute(cursor::Hide)?;
}
}
}
}
Ok(())
}
|
impl Solution {
pub fn sum_odd_length_subarrays(mut arr: Vec<i32>) -> i32 {
let mut a = vec![0;1];
a.append(&mut arr);
let n = a.len();
for i in 1..n{
a[i] += a[i - 1];
}
let mut res = 0;
for i in 1..n{
for j in i..n{
if (j - i + 1) & 1 == 1{
res += a[j] - a[i - 1];
}
}
}
res
}
} |
use gdk::{
ModifierType,
keyval_to_unicode,
CONTROL_MASK,
META_MASK,
SHIFT_MASK,
SUPER_MASK,
};
use servo::msg::constellation_msg::{ALT, CONTROL, SHIFT, SUPER};
use gdk::enums::key as gdk_key;
use gdk_sys::{GDK_BUTTON_MIDDLE, GDK_BUTTON_PRIMARY, GDK_BUTTON_SECONDARY};
use servo::msg::constellation_msg::{Key, KeyModifiers};
use servo::script_traits::MouseButton;
pub fn modifiers(modifiers: ModifierType) -> KeyModifiers {
let mut result = KeyModifiers::empty();
if modifiers.contains(META_MASK) {
result.insert(ALT);
}
if modifiers.contains(SUPER_MASK) {
result.insert(SUPER);
}
if modifiers.contains(CONTROL_MASK) {
result.insert(CONTROL);
}
if modifiers.contains(SHIFT_MASK) {
result.insert(SHIFT);
}
result
}
pub fn mouse_button(gtk_button: u32) -> MouseButton {
match gtk_button as i32 {
GDK_BUTTON_MIDDLE => MouseButton::Middle,
GDK_BUTTON_PRIMARY => MouseButton::Left,
GDK_BUTTON_SECONDARY => MouseButton::Right,
_ => panic!("unexpected value for gtk_button"),
}
}
pub fn key(gdk_key: gdk_key::Key) -> (Option<char>, Option<Key>) {
let unicode =
keyval_to_unicode(gdk_key)
.and_then(|char|
if char.is_control() {
None
}
else {
Some(char)
}
);
let key =
match gdk_key {
gdk_key::space => Key::Space,
gdk_key::apostrophe => Key::Apostrophe,
gdk_key::comma => Key::Comma,
gdk_key::minus => Key::Minus,
gdk_key::period => Key::Period,
gdk_key::slash => Key::Slash,
gdk_key::_0 => Key::Num0,
gdk_key::_1 => Key::Num1,
gdk_key::_2 => Key::Num2,
gdk_key::_3 => Key::Num3,
gdk_key::_4 => Key::Num4,
gdk_key::_5 => Key::Num5,
gdk_key::_6 => Key::Num6,
gdk_key::_7 => Key::Num7,
gdk_key::_8 => Key::Num8,
gdk_key::_9 => Key::Num9,
gdk_key::semicolon => Key::Semicolon,
gdk_key::equal => Key::Equal,
gdk_key::A | gdk_key::a => Key::A,
gdk_key::B | gdk_key::b => Key::B,
gdk_key::C | gdk_key::c => Key::C,
gdk_key::D | gdk_key::d => Key::D,
gdk_key::E | gdk_key::e => Key::E,
gdk_key::F | gdk_key::f => Key::F,
gdk_key::G | gdk_key::g => Key::G,
gdk_key::H | gdk_key::h => Key::H,
gdk_key::I | gdk_key::i => Key::I,
gdk_key::J | gdk_key::j => Key::J,
gdk_key::K | gdk_key::k => Key::K,
gdk_key::L | gdk_key::l => Key::L,
gdk_key::M | gdk_key::m => Key::M,
gdk_key::N | gdk_key::n => Key::N,
gdk_key::O | gdk_key::o => Key::O,
gdk_key::P | gdk_key::p => Key::P,
gdk_key::Q | gdk_key::q => Key::Q,
gdk_key::R | gdk_key::r => Key::R,
gdk_key::S | gdk_key::s => Key::S,
gdk_key::T | gdk_key::t => Key::T,
gdk_key::U | gdk_key::u => Key::U,
gdk_key::V | gdk_key::v => Key::V,
gdk_key::W | gdk_key::w => Key::W,
gdk_key::X | gdk_key::x => Key::X,
gdk_key::Y | gdk_key::y => Key::Y,
gdk_key::Z | gdk_key::z => Key::Z,
gdk_key::bracketleft => Key::LeftBracket,
gdk_key::backslash => Key::Backslash,
gdk_key::bracketright => Key::RightBracket,
gdk_key::dead_grave => Key::GraveAccent,
//gdk_key:: => Key::World1, // TODO
//gdk_key:: => Key::World2,
gdk_key::Escape => Key::Escape,
gdk_key::Return => Key::Enter,
gdk_key::Tab => Key::Tab,
gdk_key::BackSpace => Key::Backspace,
gdk_key::Insert => Key::Insert,
gdk_key::Delete => Key::Delete,
gdk_key::Right => Key::Right,
gdk_key::Left => Key::Left,
gdk_key::Down => Key::Down,
gdk_key::Up => Key::Up,
gdk_key::Page_Up => Key::PageUp,
gdk_key::Page_Down => Key::PageDown,
gdk_key::Home => Key::Home,
gdk_key::End => Key::End,
gdk_key::Caps_Lock => Key::CapsLock,
gdk_key::Scroll_Lock => Key::ScrollLock,
gdk_key::Num_Lock => Key::NumLock,
gdk_key::_3270_PrintScreen => Key::PrintScreen, // TODO: tes)t
gdk_key::Pause => Key::Pause,
gdk_key::F1 => Key::F1,
gdk_key::F2 => Key::F2,
gdk_key::F3 => Key::F3,
gdk_key::F4 => Key::F4,
gdk_key::F5 => Key::F5,
gdk_key::F6 => Key::F6,
gdk_key::F7 => Key::F7,
gdk_key::F8 => Key::F8,
gdk_key::F9 => Key::F9,
gdk_key::F10 => Key::F10,
gdk_key::F11 => Key::F11,
gdk_key::F12 => Key::F12,
gdk_key::F13 => Key::F13,
gdk_key::F14 => Key::F14,
gdk_key::F15 => Key::F15,
gdk_key::F16 => Key::F16,
gdk_key::F17 => Key::F17,
gdk_key::F18 => Key::F18,
gdk_key::F19 => Key::F19,
gdk_key::F20 => Key::F20,
gdk_key::F21 => Key::F21,
gdk_key::F22 => Key::F22,
gdk_key::F23 => Key::F23,
gdk_key::F24 => Key::F24,
gdk_key::F25 => Key::F25,
gdk_key::KP_0 => Key::Kp0,
gdk_key::KP_1 => Key::Kp1,
gdk_key::KP_2 => Key::Kp2,
gdk_key::KP_3 => Key::Kp3,
gdk_key::KP_4 => Key::Kp4,
gdk_key::KP_5 => Key::Kp5,
gdk_key::KP_6 => Key::Kp6,
gdk_key::KP_7 => Key::Kp7,
gdk_key::KP_8 => Key::Kp8,
gdk_key::KP_9 => Key::Kp9,
gdk_key::KP_Decimal => Key::KpDecimal,
gdk_key::KP_Divide => Key::KpDivide,
gdk_key::KP_Multiply => Key::KpMultiply,
gdk_key::KP_Subtract => Key::KpSubtract,
gdk_key::KP_Add => Key::KpAdd,
gdk_key::KP_Enter => Key::KpEnter,
gdk_key::KP_Equal => Key::KpEqual,
gdk_key::Shift_L => Key::LeftShift,
gdk_key::Control_L => Key::LeftControl,
gdk_key::Alt_L => Key::LeftAlt,
gdk_key::Super_L => Key::LeftSuper,
gdk_key::Shift_R => Key::RightShift,
gdk_key::Control_R => Key::RightControl,
gdk_key::Alt_R => Key::RightAlt,
gdk_key::Super_R => Key::RightSuper,
gdk_key::Menu => Key::Menu,
//gdk_key:: => Key::NavigateBackward, // TODO
//gdk_key:: => Key::NavigateForward,
_ => return
if let Some(key) = unicode {
(Some(key), Some(Key::A)) // FIXME: don't send A.
}
else {
(None, None)
}
};
(unicode, Some(key))
}
|
fn main() {
proconio::input! {
n: usize,
a: [i32; n],
b: [i32; n],
}
let mut min = 100000000;
let mut max = 0;
for i in 0..n {
if min > b[i] {
min = b[i];
}
}
for i in 0..n {
if max < a[i] {
max = a[i];
}
}
// println!("{} {}", min, max);
if min - max >= 0 {
println!("{}", min - max + 1);
}else{
println!("0");
}
}
|
use anyhow::{anyhow, bail};
use bikecleats_testsuite::{BatchTestCase, CheckerShell, ExpectedOutput};
use futures_util::{select, FutureExt as _};
use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle};
use std::{
cmp,
collections::BTreeMap,
env,
ffi::{OsStr, OsString},
future::Future,
io, iter,
path::{Path, PathBuf},
process::{ExitStatus, Output, Stdio},
sync::Arc,
time::{Duration, Instant},
};
use termcolor::{Color, WriteColor};
use tokio::io::AsyncWriteExt as _;
use unicode_width::UnicodeWidthStr as _;
macro_rules! color_spec {
($($tt:tt)*) => {
_color_spec_inner!(@acc(::termcolor::ColorSpec::new().set_reset(false)), @rest($($tt)*))
};
}
macro_rules! _color_spec_inner {
(@acc($acc:expr), @rest()) => {
$acc
};
(@acc($acc:expr), @rest(, $($rest:tt)*)) => {
_color_spec_inner!(@acc($acc), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Fg($color:expr) $($rest:tt)*)) => {
_color_spec_inner!(@acc($acc.set_fg(::std::option::Option::Some($color))), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Bg($color:expr) $($rest:tt)*)) => {
_color_spec_inner!(@acc($acc.set_bg(::std::option::Option::Some($color))), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Bold $($rest:tt)*)) => {
_color_spec_inner!(@acc($acc.set_bold(true)), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Italic $($rest:tt)*)) => {
_color_spec_inner!(@acc($acc.set_italic(true)), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Underline $($rest:tt)*)) => {
_color_spec_inner!(@acc($acc.set_underline(true)), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Intense $($rest:tt)*)) => {
_color_spec_inner!(@acc($acc.set_intense(true)), @rest($($rest)*))
};
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct JudgeOutcome {
pub verdicts: Vec<Verdict>,
}
impl JudgeOutcome {
pub fn print_pretty<W: WriteColor>(
&self,
mut wtr: W,
display_limit: Option<usize>,
) -> io::Result<()> {
for (i, verdict) in self.verdicts.iter().enumerate() {
if i > 0 {
writeln!(wtr)?;
}
write!(
wtr,
"{}/{} ({:?}) ",
i + 1,
self.verdicts.len(),
verdict.test_case_name().unwrap_or(""),
)?;
wtr.set_color(color_spec!(Bold, Fg(verdict.summary_color())))?;
writeln!(wtr, "{}", verdict.summary())?;
wtr.reset()?;
let mut write_text =
|header: &str, text: &str, highlight_numbers: bool| -> io::Result<()> {
wtr.set_color(color_spec!(Bold, Fg(Color::Magenta)))?;
writeln!(wtr, "{}", header)?;
wtr.reset()?;
if text.is_empty() {
wtr.set_color(color_spec!(Bold, Fg(Color::Yellow)))?;
writeln!(wtr, "EMPTY")?;
return wtr.reset();
}
if matches!(display_limit, Some(l) if l < text.len()) {
wtr.set_color(color_spec!(Bold, Fg(Color::Yellow)))?;
writeln!(wtr, "{} B", text.len())?;
return wtr.reset();
}
for token in parse_to_tokens(text, highlight_numbers) {
match token {
Token::SpcLf(s) | Token::Plain(s) => wtr.write_all(s.as_ref())?,
Token::Cr(n) => {
wtr.set_color(color_spec!(Fg(Color::Yellow)))?;
(0..n).try_for_each(|_| wtr.write_all(b"\\r"))?;
wtr.reset()?;
}
Token::Tab(n) => {
wtr.set_color(color_spec!(Fg(Color::Yellow)))?;
(0..n).try_for_each(|_| wtr.write_all(b"\\t"))?;
wtr.reset()?;
}
Token::OtherWhitespaceControl(s) => {
wtr.set_color(color_spec!(Fg(Color::Yellow)))?;
write!(wtr, "{}", s.escape_unicode())?;
wtr.reset()?;
}
Token::HighlightedNumber(s) => {
wtr.set_color(color_spec!(Fg(Color::Cyan)))?;
wtr.write_all(s.as_ref())?;
wtr.reset()?;
}
}
}
if !text.ends_with('\n') {
wtr.set_color(color_spec!(Fg(Color::Yellow)))?;
writeln!(wtr, "⏎")?;
wtr.reset()?;
}
Ok(())
};
write_text("stdin:", verdict.stdin(), false)?;
if let Some(expected) = verdict.expected().expected_stdout() {
write_text("expected:", expected, verdict.expected().is_float())?;
} else if let Some(example) = verdict.expected().example() {
write_text("example:", example, verdict.expected().is_float())?;
}
if let Some(stdout) = verdict.stdout() {
write_text("actual:", stdout, verdict.expected().is_float())?;
}
if let Some(stderr) = verdict.stderr().filter(|s| !s.is_empty()) {
write_text("stderr:", stderr, verdict.expected().is_float())?;
}
if let Some(checker_stdout) = verdict.checker_stdout().filter(|s| !s.is_empty()) {
write_text("checker stdout: ", checker_stdout, false)?;
}
if let Some(checker_stderr) = verdict.checker_stderr().filter(|s| !s.is_empty()) {
write_text("checker stderr: ", checker_stderr, false)?;
}
if let Some(wrong_answer_note) = verdict.wrong_answer_note() {
write_text("note: ", &(wrong_answer_note.to_string() + "\n"), false)?;
}
}
return wtr.flush();
#[derive(Debug)]
enum Token<'a> {
SpcLf(&'a str),
Cr(usize),
Tab(usize),
OtherWhitespaceControl(&'a str),
HighlightedNumber(&'a str),
Plain(&'a str),
}
fn parse_to_tokens(text: &str, highlight_numbers: bool) -> Vec<Token<'_>> {
use nom::branch::alt;
use nom::bytes::complete::take_while1;
use nom::character::complete::char;
use nom::combinator::recognize;
use nom::multi::{many0, many1};
use nom::number::complete::recognize_float;
use nom::IResult;
let (_, tokens) = many0(alt((
spc_lf,
cr,
tab,
other_whitespace_control,
highlighted_number_or_plain(highlight_numbers),
)))(text)
.unwrap();
return tokens;
fn spc_lf(input: &str) -> IResult<&str, Token<'_>> {
let (rest, target) = take_while1(|c| [' ', '\n'].contains(&c))(input)?;
Ok((rest, Token::SpcLf(target)))
}
fn cr(input: &str) -> IResult<&str, Token<'_>> {
let (rest, target) = recognize(many1(char('\r')))(input)?;
Ok((rest, Token::Cr(target.len())))
}
fn tab(input: &str) -> IResult<&str, Token<'_>> {
let (rest, target) = recognize(many1(char('\t')))(input)?;
Ok((rest, Token::Tab(target.len())))
}
fn other_whitespace_control(input: &str) -> IResult<&str, Token<'_>> {
let (rest, target) =
take_while1(|c: char| c.is_whitespace() || c.is_control())(input)?;
Ok((rest, Token::OtherWhitespaceControl(target)))
}
fn highlighted_number_or_plain(
highlight_numbers: bool,
) -> fn(&str) -> IResult<&str, Token<'_>> {
return if highlight_numbers {
|input| highlighted_number(input).or_else(|_| plain(input))
} else {
plain
};
fn highlighted_number(input: &str) -> IResult<&str, Token<'_>> {
let (rest, target) = recognize_float(input)?;
Ok((rest, Token::HighlightedNumber(target)))
}
fn plain(input: &str) -> IResult<&str, Token<'_>> {
let (rest, target) =
take_while1(|c: char| !(c.is_whitespace() || c.is_control()))(input)?;
Ok((rest, Token::Plain(target)))
}
}
}
}
pub fn error_on_fail(&self) -> anyhow::Result<()> {
let fails = self
.verdicts
.iter()
.filter(|v| !matches!(v, Verdict::Accepted { .. }))
.count();
if fails > 0 {
bail!(
"{}/{} test{} failed",
fails,
self.verdicts.len(),
if fails == 0 { "" } else { "s" }
);
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub enum Verdict {
Accepted {
test_case_name: Option<String>,
elapsed: Duration,
stdin: Arc<str>,
stdout: Arc<str>,
stderr: Arc<str>,
expected: ExpectedOutput,
},
WrongAnswer {
test_case_name: Option<String>,
elapsed: Duration,
stdin: Arc<str>,
stdout: Arc<str>,
stderr: Arc<str>,
checker_stdout: Arc<str>,
checker_stderr: Arc<str>,
expected: ExpectedOutput,
note: Option<WrongAnswerNote>,
},
RuntimeError {
test_case_name: Option<String>,
elapsed: Duration,
stdin: Arc<str>,
stdout: Arc<str>,
stderr: Arc<str>,
expected: ExpectedOutput,
status: ExitStatus,
},
TimelimitExceeded {
test_case_name: Option<String>,
timelimit: Duration,
stdin: Arc<str>,
expected: ExpectedOutput,
},
}
impl Verdict {
fn test_case_name(&self) -> Option<&str> {
match self {
Verdict::Accepted { test_case_name, .. }
| Verdict::WrongAnswer { test_case_name, .. }
| Verdict::RuntimeError { test_case_name, .. }
| Verdict::TimelimitExceeded { test_case_name, .. } => test_case_name.as_deref(),
}
}
fn stdin(&self) -> &str {
match self {
Verdict::Accepted { stdin, .. }
| Verdict::WrongAnswer { stdin, .. }
| Verdict::RuntimeError { stdin, .. }
| Verdict::TimelimitExceeded { stdin, .. } => stdin,
}
}
fn stdout(&self) -> Option<&str> {
match self {
Verdict::Accepted { stdout, .. }
| Verdict::WrongAnswer { stdout, .. }
| Verdict::RuntimeError { stdout, .. } => Some(stdout),
Verdict::TimelimitExceeded { .. } => None,
}
}
fn stderr(&self) -> Option<&str> {
match self {
Verdict::Accepted { stderr, .. }
| Verdict::WrongAnswer { stderr, .. }
| Verdict::RuntimeError { stderr, .. } => Some(stderr),
Verdict::TimelimitExceeded { .. } => None,
}
}
fn expected(&self) -> &ExpectedOutput {
match self {
Verdict::Accepted { expected, .. }
| Verdict::WrongAnswer { expected, .. }
| Verdict::RuntimeError { expected, .. }
| Verdict::TimelimitExceeded { expected, .. } => expected,
}
}
fn checker_stdout(&self) -> Option<&str> {
match self {
Verdict::WrongAnswer { checker_stdout, .. } => Some(checker_stdout),
_ => None,
}
}
fn checker_stderr(&self) -> Option<&str> {
match self {
Verdict::WrongAnswer { checker_stderr, .. } => Some(checker_stderr),
_ => None,
}
}
fn wrong_answer_note(&self) -> Option<WrongAnswerNote> {
match *self {
Self::WrongAnswer { note, .. } => note,
_ => None,
}
}
fn summary(&self) -> String {
match self {
Self::Accepted { elapsed, .. } => format!("Accepted ({} ms)", elapsed.as_millis()),
Self::TimelimitExceeded { timelimit, .. } => {
format!("Timelimit Exceeded ({} ms)", timelimit.as_millis())
}
Self::WrongAnswer { elapsed, .. } => {
format!("Wrong Answer ({} ms)", elapsed.as_millis())
}
Self::RuntimeError {
elapsed, status, ..
} => format!("Runtime Error ({} ms, {})", elapsed.as_millis(), status),
}
}
fn summary_color(&self) -> Color {
match self {
Self::Accepted { .. } => Color::Green,
Self::TimelimitExceeded { .. } => Color::Red,
Self::WrongAnswer { .. } | Self::RuntimeError { .. } => Color::Yellow,
}
}
fn summary_style(&self) -> &'static str {
match self {
Self::Accepted { .. } => ".bold.green",
Self::TimelimitExceeded { .. } => ".bold.red",
Self::WrongAnswer { .. } | Self::RuntimeError { .. } => ".bold.yellow",
}
}
}
#[derive(Copy, Clone, Debug, derive_more::Display)]
pub enum WrongAnswerNote {
#[display(
fmt = "whitespace-separated words matched. try setting `match` to `SplitWhitespace`"
)]
WordsMatched,
}
#[derive(Debug, Clone)]
pub struct CommandExpression {
pub program: OsString,
pub args: Vec<OsString>,
pub cwd: PathBuf,
pub env: BTreeMap<OsString, OsString>,
}
impl CommandExpression {
async fn build(
&self,
stdin: Option<&Path>,
stdout: &Path,
stderr: &Path,
) -> io::Result<tokio::process::Command> {
let mut cmd = tokio::process::Command::new(&self.program);
let stdin = if let Some(stdin) = stdin {
tokio::fs::File::open(stdin).await?.into_std().await.into()
} else {
Stdio::piped()
};
let stdout = tokio::fs::File::create(stdout).await?.into_std().await;
let stderr = tokio::fs::File::create(stderr).await?.into_std().await;
cmd.args(&self.args)
.current_dir(&self.cwd)
.envs(&self.env)
.stdin(stdin)
.stdout(stdout)
.stderr(stderr);
Ok(cmd)
}
}
pub fn judge<C: 'static + Future<Output = tokio::io::Result<()>> + Send>(
draw_target: ProgressDrawTarget,
ctrl_c: fn() -> C,
cmd: &CommandExpression,
test_cases: &[BatchTestCase],
) -> anyhow::Result<JudgeOutcome> {
let cmd = Arc::new(cmd.clone());
let num_test_cases = test_cases.len();
let quoted_name_width = test_cases
.iter()
.flat_map(|BatchTestCase { name, .. }| name.as_ref())
.map(|s| format!("{:?}", s).width())
.max()
.unwrap_or(0);
let bash_exe = {
static GIT_BASH: &str = r"C:\Program Files\Git\bin\bash.exe";
let bash_exe = if cfg!(windows) && Path::new(GIT_BASH).exists() {
GIT_BASH
} else {
"bash"
};
which::which_in(bash_exe, env::var_os("PATH"), &cmd.cwd)
.map_err(|_| anyhow!("`{}` not found", bash_exe))?
};
let tempdir = tempfile::Builder::new()
.prefix("snowchains-core-juding-")
.tempdir()?;
let tempdir_path = tempdir.path().to_owned();
let mp = MultiProgress::with_draw_target(draw_target);
let mut targets = vec![];
for (i, test_case) in test_cases.iter().enumerate() {
let pb = mp.add(ProgressBar::new_spinner());
pb.set_style(progress_style("{prefix}{spinner} {msg:bold}"));
pb.set_prefix(&format!(
"{}/{} ({} ",
align_right(&(i + 1).to_string(), num_test_cases.to_string().len()),
num_test_cases,
align_left(
&format!("{:?})", test_case.name.as_deref().unwrap_or("")),
quoted_name_width + 1,
),
));
pb.set_message("Judging...");
pb.enable_steady_tick(50);
targets.push((test_case.clone(), pb));
}
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_io()
.enable_time()
.build()?;
let outcome = rt.spawn(async move {
let num_targets = targets.len();
let (ctrl_c_tx, ctrl_c_rx) = tokio::sync::broadcast::channel(cmp::max(1, num_targets));
let mut ctrl_c_rxs = iter::once(ctrl_c_rx)
.chain(iter::repeat_with(|| ctrl_c_tx.subscribe()))
.take(num_targets)
.collect::<Vec<_>>();
tokio::task::spawn(async move {
let err_msg = match ctrl_c().await {
Ok(()) => "Recieved Ctrl-c".to_owned(),
Err(err) => err.to_string(),
};
ctrl_c_tx.send(err_msg).unwrap();
});
let (job_start_tx, mut job_start_rx) = tokio::sync::mpsc::channel(num_cpus::get());
for _ in 0..num_cpus::get() {
job_start_tx.send(()).await?;
}
let mut results = vec![];
for (i, (test_case, pb)) in targets.into_iter().enumerate() {
let cmd = cmd.clone();
let stdin_path = tempdir_path.join(format!("{}-stdin", i));
let actual_stdout_path = tempdir_path.join(format!("{}-actual-stdout", i));
let expected_stdout_path = tempdir_path.join(format!("{}-expected-stdout", i));
let stderr_path = tempdir_path.join(format!("{}-stderr", i));
let bash_exe = bash_exe.clone();
job_start_rx.recv().await;
let job_start_tx = job_start_tx.clone();
let mut ctrl_c_rx = ctrl_c_rxs.pop().expect("should have enough length");
let pb_clone = pb.clone();
results.push(tokio::task::spawn(async move {
let result = tokio::task::spawn(async move {
tokio::fs::write(&stdin_path, test_case.input.as_ref()).await?;
let test_case_name = test_case.name.clone();
let timelimit = test_case.timelimit;
let stdin = test_case.input.clone();
let expected = test_case.output.clone();
let cwd = &cmd.cwd;
let cmd = cmd
.build(
(stdin.len() >= 10 * 1024).then(|| &*stdin_path),
&actual_stdout_path,
&stderr_path,
)
.await?;
let started = Instant::now();
let mut child = { cmd }.spawn()?;
if let Some(mut child_stdin) = child.stdin.take() {
child_stdin.write_all((*stdin).as_ref()).await?;
}
macro_rules! with_ctrl_c {
($future:expr) => {
select! {
__output = $future => __output,
err_msg = ctrl_c_rx.recv().fuse() => {
let _ = child.kill();
bail!("{}", err_msg?);
},
}
};
}
let status = if let Some(timelimit) = timelimit {
let timeout = timelimit + Duration::from_millis(100);
if let Ok(status) =
with_ctrl_c!(tokio::time::timeout(timeout, child.wait()).fuse())
{
status?
} else {
let _ = child.kill().await;
let verdict = Verdict::TimelimitExceeded {
test_case_name,
timelimit,
stdin,
expected,
};
tokio::task::block_in_place(|| {
pb_clone.set_style(progress_style(&format!(
"{{prefix}}{{msg:{}}}",
verdict.summary_style(),
)));
pb_clone.finish_with_message(&verdict.summary());
});
return Ok(verdict);
}
} else {
with_ctrl_c!(child.wait().fuse())?
};
let elapsed = Instant::now() - started;
let stdout = utf8(tokio::fs::read(&actual_stdout_path).await?)?;
let stderr = utf8(tokio::fs::read(&stderr_path).await?)?;
if matches!(timelimit, Some(t) if t < elapsed) {
Ok(Verdict::TimelimitExceeded {
test_case_name,
timelimit: timelimit.unwrap(),
stdin,
expected,
})
} else if !status.success() {
Ok(Verdict::RuntimeError {
test_case_name,
elapsed,
stdin,
stdout,
stderr,
expected,
status,
})
} else if let Err((checker_stdout, checker_stderr, note)) = check(
&test_case.output,
&stdout,
cwd,
&stdin_path,
&actual_stdout_path,
&expected_stdout_path,
&bash_exe,
)
.await?
{
Ok(Verdict::WrongAnswer {
test_case_name,
elapsed,
stdin,
stdout,
stderr,
checker_stdout,
checker_stderr,
expected,
note,
})
} else {
Ok(Verdict::Accepted {
test_case_name,
elapsed,
stdin,
stdout,
stderr,
expected,
})
}
})
.await
.unwrap();
match &result {
Ok(verdict) => {
tokio::task::block_in_place(|| {
pb.set_style(progress_style(&format!(
"{{prefix}}{{msg:{}}}",
verdict.summary_style(),
)));
pb.finish_with_message(&verdict.summary());
});
}
Err(err) => {
tokio::task::block_in_place(|| {
pb.set_style(progress_style("{prefix}{msg}"));
pb.finish_with_message(&format!("{:?}", err));
});
}
}
job_start_tx.send(()).await?;
let verdict = result?;
Ok::<_, anyhow::Error>((i, verdict))
}));
}
let mut verdicts = vec![None; num_targets];
for result in results {
let (i, element) = result.await??;
verdicts[i] = Some(element);
}
let verdicts = verdicts.into_iter().map(Option::unwrap).collect();
Ok::<_, anyhow::Error>(JudgeOutcome { verdicts })
});
mp.join()?;
let outcome = rt.block_on(outcome)??;
tempdir.close()?;
return Ok(outcome);
fn progress_style(template: impl AsRef<str>) -> ProgressStyle {
ProgressStyle::default_spinner().template(template.as_ref())
}
fn align_left(s: &str, n: usize) -> String {
let spaces = n.saturating_sub(s.width());
s.chars().chain(itertools::repeat_n(' ', spaces)).collect()
}
fn align_right(s: &str, n: usize) -> String {
let spaces = n.saturating_sub(s.width());
itertools::repeat_n(' ', spaces).chain(s.chars()).collect()
}
}
async fn check(
expected: &ExpectedOutput,
actual: &str,
cwd: &Path,
stdin_path: &Path,
actual_stdout_path: &Path,
expected_stdout_path: &Path,
bash_exe: &Path,
) -> anyhow::Result<Result<(), (Arc<str>, Arc<str>, Option<WrongAnswerNote>)>> {
match expected {
ExpectedOutput::Deterministic(expected) => Ok(if expected.accepts(actual) {
Ok(())
} else {
let note = expected
.expected_stdout()
.filter(|expected| expected.split_whitespace().eq(actual.split_whitespace()))
.map(|_| WrongAnswerNote::WordsMatched);
Err((Arc::from(""), Arc::from(""), note))
}),
ExpectedOutput::Checker { text, cmd, shell } => {
let (program, args) = match shell {
CheckerShell::Bash => (bash_exe, [OsStr::new("-c"), OsStr::new(cmd)]),
};
let mut env_vars = vec![("INPUT", stdin_path), ("ACTUAL_OUTPUT", actual_stdout_path)];
if let Some(text) = text {
tokio::fs::write(expected_stdout_path, text.as_ref()).await?;
env_vars.push(("EXPECTED_OUTPUT", expected_stdout_path));
}
let Output {
status,
stdout,
stderr,
} = tokio::process::Command::new(program)
.args(&args)
.envs(env_vars)
.current_dir(cwd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.output()
.await?;
let (stdout, stderr) = (utf8(stdout)?, utf8(stderr)?);
Ok(if status.success() {
Ok(())
} else {
Err((stdout, stderr, None))
})
}
}
}
fn utf8(bytes: Vec<u8>) -> anyhow::Result<Arc<str>> {
String::from_utf8(bytes)
.map(Into::into)
.map_err(|_| anyhow!("the output was not a valid UTF-8 string"))
}
|
use std::thread;
use std::time::Duration;
use anyhow::Result;
use rand;
use rand::Rng;
use super::{SensorId, Sensors};
use crate::{Global, drop::DropJoin};
pub fn poll_tmp_probes() -> Result<DropJoin<()>> {
let handle = thread::Builder::new()
.name("temp-sensor".into())
.stack_size(32 * 1024)
.spawn(move || {
let mut rng = rand::thread_rng();
let sensors = Sensors::global();
loop {
sensors.set(&SensorId::Tmp0, rng.gen_range(18.0..30.0));
sensors.set(&SensorId::Tmp1, rng.gen_range(18.0..30.0));
sensors.set(&SensorId::Tmp2, rng.gen_range(18.0..30.0));
sensors.set(&SensorId::Tmp3, rng.gen_range(18.0..30.0));
thread::sleep(Duration::from_secs(1));
}
})?;
Ok(DropJoin::new(handle))
}
pub fn poll_rpi_tmp() -> Result<DropJoin<()>> {
let handle = thread::Builder::new()
.name("rpi-sensor".into())
.stack_size(32 * 1024)
.spawn(move || {
let mut rng = rand::thread_rng();
let sensors = Sensors::global();
loop {
sensors.set(&SensorId::RPi, rng.gen_range(20.0..50.0));
thread::sleep(Duration::from_secs(3));
}
})?;
Ok(DropJoin::new(handle))
}
pub fn poll_rpm() -> Result<DropJoin<()>> {
let handle = thread::Builder::new()
.name("rpm-counter".into())
.stack_size(32 * 1024)
.spawn(move || {
let mut rng = rand::thread_rng();
let sensors = Sensors::global();
loop {
sensors.set(&SensorId::RPM0, rng.gen_range(900.0..2400.0));
sensors.set(&SensorId::RPM1, rng.gen_range(900.0..2400.0));
thread::sleep(Duration::from_secs(5));
}
})?;
Ok(DropJoin::new(handle))
}
|
mod tests{
use num_cpus; // 1.13.0
use std::time;
use threadpool::ThreadPool; // 1.8.0 // 0.7.2
use crossbeam; // 0.7.3
use futures::executor; // 0.3.4
use futures::Future;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::delay_for;
use tokio::runtime::Runtime;
#[test]
fn s_1_3_sync_threads_with_crossbeam_messages() {
let pool = ThreadPool::new(num_cpus::get());
let (tx, rx) = crossbeam::unbounded();
let tx_c = tx.clone();
pool.execute(move || {
println!("[Thread a] Spawned thread");
time::Duration::from_millis(2000);
tx_c.send("continue").unwrap();
println!("[Thread a] End");
});
pool.execute(move || {
println!("[Thread b] Spawned thread");
while let Ok(message) = rx.recv() {
println!("[Thread b] Message : {:?}", message);
if message == "continue" {
println!("[Thread b] continue exectution {:?}", message);
break;
}
println!("[Thread b] End");
}
});
pool.join();
}
#[test]
fn s_1_3_sync_futures_with_crossbeam_messages_driver () {
async fn sync_futures_with_crossbeam_messages() {
let (tx, rx) = crossbeam::unbounded();
let future_1 = async {
println!("[Future 1] started");
time::Duration::from_millis(2000);
tx.send(1).unwrap();
println!("[Future 1] End");
};
future_1.await;
let future_2 = async {
println!("[Future 2] started");
time::Duration::from_millis(2000);
while let Ok(message) = rx.recv() {
println!("[Future 2] Message : {:?}", message);
if message == 1 {
println!("[Future 2] continue exectution -> {:?}", message);
break;
}
println!("[Future 2] End");
}
};
future_2.await;
}
let fut = async {
sync_futures_with_crossbeam_messages().await;
};
executor::block_on(fut);
}
#[test]
fn s_1_5_1_concurrent_updates_futures_to_arc_mutex() {
async fn concurrent_updates_futures_to_arc_mutex() {
let s = Arc::new(Mutex::new(1_u128));
let i = s.clone();
let j = s.clone();
let future_1 = tokio::spawn(async move {
println!("[Future 1] started");
for _item in 0..30 {
tokio::time::delay_for(Duration::from_secs(1)).await;
{
let mut i_shared = i.lock().unwrap();
println!("[Future 1] {:?}", i_shared);
*i_shared = *i_shared * 3;
}
}
println!("[Future 1] End -> i = {:?}", i);
});
let future_2 = tokio::spawn(async move {
println!("[Future 2] started");
for _item in 0..30 {
tokio::time::delay_for(Duration::from_secs(1)).await;
{
let mut i_shared = j.lock().unwrap();
println!("[Future 2] {:?}", i_shared);
*i_shared = *i_shared * 2;
}
}
println!("[Future 2] End -> i = {:?}", j);
});
tokio::join!(future_1, future_2);
println!("Final i = {:?}", s);
}
let fut = async {
concurrent_updates_futures_to_arc_mutex().await;
};
let mut rt = Runtime::new().unwrap();
rt.block_on(fut);
}
}
use num_cpus; // 1.13.0
use std::time;
use threadpool::ThreadPool; // 1.8.0 // 0.7.2
fn main() {
}
|
use std::cell::RefCell;
use std::ops::RangeFrom;
// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------
///
/// A Step counter will simply return an increasing integer (`u32`) value, nothing fancy.
///
#[derive(Debug)]
pub struct StepCounter(RefCell<RangeFrom<u32>>);
// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------
impl Default for StepCounter {
fn default() -> Self {
Self::from_one()
}
}
impl StepCounter {
/// Create a step counter that starts from `0`.
pub fn from_zero() -> Self {
Self::from(0)
}
/// Create a step counter that starts from `1`.
pub fn from_one() -> Self {
Self::from(1)
}
/// Create a step counter that starts from an arbitrary value.
pub fn from(start: u32) -> Self {
Self(RefCell::from(start..))
}
/// Return the current step number, and increment.
pub fn step(&self) -> u32 {
self.0.borrow_mut().next().unwrap()
}
/// Skip a number of steps and return the step number at that point.
pub fn steps(&self, skip: u32) -> Option<u32> {
if skip == 0 {
None
} else {
Some(self.0.borrow_mut().nth((skip - 1) as usize).unwrap())
}
}
}
// ------------------------------------------------------------------------------------------------
// Unit Tests
// ------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_start_at_zero() {
let counter = StepCounter::from_zero();
assert_eq!(counter.step(), 0);
}
#[test]
fn test_start_at_one() {
let counter = StepCounter::from_one();
assert_eq!(counter.step(), 1);
}
#[test]
fn test_start_at_ninety_nine() {
let counter = StepCounter::from(99);
assert_eq!(counter.step(), 99);
}
#[test]
fn test_just_steps() {
let counter = StepCounter::from_zero();
assert_eq!(counter.step(), 0);
assert_eq!(counter.step(), 1);
assert_eq!(counter.step(), 2);
assert_eq!(counter.step(), 3);
assert_eq!(counter.step(), 4);
assert_eq!(counter.step(), 5);
assert_eq!(counter.step(), 6);
assert_eq!(counter.step(), 7);
assert_eq!(counter.step(), 8);
assert_eq!(counter.step(), 9);
}
#[test]
fn test_skip_steps() {
let counter = StepCounter::from_zero();
assert_eq!(counter.step(), 0);
assert_eq!(counter.step(), 1);
assert_eq!(counter.steps(5), Some(6));
assert_eq!(counter.step(), 7);
assert_eq!(counter.step(), 8);
assert_eq!(counter.steps(10), Some(18));
assert_eq!(counter.step(), 19);
assert_eq!(counter.steps(0), None);
assert_eq!(counter.step(), 20);
assert_eq!(counter.step(), 21);
}
}
|
use nom::bytes::complete::{is_a, take, take_while, take_while_m_n};
use nom::character::complete::anychar;
use nom::combinator::{map, map_res, opt, verify};
use nom::error::context;
mod parse;
#[derive(Debug, PartialEq)]
pub struct Genre<'s>(&'s str);
#[derive(Debug, PartialEq)]
pub struct Second(f64);
#[derive(Debug, PartialEq)]
pub struct Third<'s> {
has_dot: bool,
body: &'s str,
}
#[derive(Debug, PartialEq)]
pub struct Year {
year: u16,
suffix: Option<char>,
}
#[derive(Debug, PartialEq)]
pub struct Note<'s>(&'s str);
#[derive(Debug, PartialEq)]
pub struct LC<'s> {
genre: Genre<'s>,
second: Second,
third: Third<'s>,
fourth: Option<Third<'s>>,
year: Option<Year>,
note: Option<Note<'s>>, // Note bits at the end
}
use std::fmt;
impl<'s> fmt::Display for LC<'s> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.genre.0)?;
write!(f, " {}", self.second.0)?;
write!(f, " ")?;
write!(f, "{}", self.third)?;
if let Some(ref fourth) = self.fourth {
write!(f, " ")?;
write!(f, "{}", fourth)?;
}
if let Some(Year { ref year, ref suffix }) = self.year {
write!(f, " ")?;
write!(f, "{}", year)?;
if let Some(ref suffix) = suffix {
write!(f, "{}", suffix)?;
}
}
Ok(())
}
}
impl<'s> fmt::Display for Third<'s> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.has_dot {
write!(f, ".")?;
}
write!(f, "{}", self.body)?;
Ok(())
}
}
impl<'a> Genre<'a> {
fn parse(i: &'a str) -> parse::Result<'a, Self> {
context(
"Genre",
map(take_while_m_n(1, 2, nom::AsChar::is_alpha), Genre),
)(i)
}
}
impl Second {
fn parse(i: parse::Input) -> parse::Result<Self> {
let mut seen_dot = false;
let mut prev = None;
let mut end = None;
for (ind, c) in i.chars().enumerate() {
match c {
'.' => if seen_dot {
end = Some(ind);
break;
} else {
seen_dot = true;
},
'A'..='Z' => if prev == Some('.') {
end = Some(ind - 1);
break;
} else {
end = Some(ind);
break;
}
_ => (),
}
prev = Some(c);
}
let end = end.ok_or_else(|| nom::Err::Error(parse::Error { errors: vec![(i, nom::error::ErrorKind::Eof)], }))?;
let after = &i[end..];
let second = &i[..end];
let second = second.replace(" ", "").parse().unwrap();
Ok((after, Second(second)))
}
}
impl<'s> Third<'s> {
fn parse(i: parse::Input<'s>) -> parse::Result<'s, Self> {
let (i, _) = opt(is_a(" "))(i)?;
let (i, has_dot) = map(opt(nom::character::complete::char('.')), |dot| {
dot.is_some()
})(i)?;
let (i, _) = opt(is_a(" "))(i)?;
let (i, body) = context(
"Third",
verify(take_while(|c: char| c.is_alphanumeric()), |s: &str| {
s.chars().next().map(|c| c.is_alphabetic()).unwrap_or(false)
}),
)(i)?;
Ok((i, Third { has_dot, body }))
}
}
impl Year {
fn parse(i: parse::Input) -> parse::Result<Self> {
let (i, _) = opt(is_a(" "))(i)?;
let (i, year) = map_res(take(4usize), str::parse)(i)?;
let (i, suffix) = opt(verify(anychar, |c| c.is_alphabetic()))(i)?;
Ok((i, Year { year, suffix }))
}
}
impl<'s> Note<'s> {
// Implement note pieces here. Read whole string at the end and hold data
fn last_but_not_least(i: parse::Input<'s>) -> parse::Result<'s, Self> {
if i.is_empty() {
Err(nom::Err::Error(parse::Error { errors: vec![(i, nom::error::ErrorKind::Eof)], }))
} else {
let note = Note(i);
Ok((i, note))
}
}
}
impl<'a> LC<'a> {
pub fn maybe_parse(i: &'a str) -> Result<Option<LC<'a>>,
nom::Err<parse::Error<&'a str>>> {
if i.is_empty() { // Finds empty sets and handles them
// If you want to see empty LCCs
let (_, lc) = LC::parse(i)?;
Ok(Some(lc))
// If you don't want to see empty LCCs
// Ok(None)
// Don't use ';' here as it gets angry.
} else { // Shows fixed LC otherwise
let (_, lc) = LC::parse(i)?;
Ok(Some(lc))
}
}
pub fn parse(i: parse::Input<'a>) -> parse::Result<'a, Self> {
// For debug purposes
// let (i, genre) = dbg!(Genre::parse(i)?);
// let (i, second) = dbg!(Second::parse(i)?);
// let (i, third) = dbg!(Third::parse(i)?);
// let (i, fourth) = dbg!(opt(Third::parse)(i))?;
// let (i, year) = dbg!(opt(Year::parse)(i))?;
// let (i, note) = dbg!(opt(Note::last_but_not_least)(i))?;
// Fully functioning
let (i, genre) = Genre::parse(i)?;
let (i, second) = Second::parse(i)?;
let (i, third) = Third::parse(i)?;
let (i, fourth) = opt(Third::parse)(i)?;
let (i, year) = opt(Year::parse)(i)?;
let (i, note) = opt(Note::last_but_not_least)(i)?;
//this OK is a tuple and expects 2 types
Ok((
i,
Self {
genre,
second,
third,
fourth,
year,
note,
},
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_full() {
let lc = "TD 224 .C3 C3723 2009";
let expected = LC {
genre: Genre("TD"),
second: Second(224.0),
third: Third {
has_dot: true,
body: "C3",
},
fourth: Some(Third {
has_dot: false,
body: "C3723",
}),
year: Some(Year {
year: 2009,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
#[test]
fn test_first() {
let lc = "GB 658 .C43 2005";
let expected = LC {
genre: Genre("GB"),
second: Second(658.0),
third: Third {
has_dot: true,
body: "C43",
},
fourth: None,
year: Some(Year {
year: 2005,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
#[test]
fn test_suffix() {
let lc = "GC 21.5 .S56 1988b";
let expected = LC {
genre: Genre("GC"),
second: Second(21.5),
third: Third {
has_dot: true,
body: "S56",
},
fourth: None,
year: Some(Year {
year: 1988,
suffix: Some('b'),
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
#[test]
fn test_optspace() {
let lc = "TD224.C3 C3723 2004";
let expected = LC {
genre: Genre("TD"),
second: Second(224.0),
third: Third {
has_dot: true,
body: "C3",
},
fourth: Some(Third {
has_dot: false,
body: "C3723",
}),
year: Some(Year {
year: 2004,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
#[test]
fn extra_space() {
let lc = "QC 920 .Z38 2009 ";
let expected = LC {
genre: Genre("QC"),
second: Second(920.0),
third: Third {
has_dot: true,
body: "Z38",
},
fourth: None,
year: Some(Year {
year: 2009,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
// Row { lc: "QC 183 .G675" }
#[test]
fn missing_year() {
let lc = "QC 183 .G675";
let expected = LC {
genre: Genre("QC"),
second: Second(183.0),
third: Third {
has_dot: true,
body: "G675",
},
fourth: None,
year: None,
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
// Row { lc: "HD 1695 .K55 .V5 2010" }
#[test]
fn double_dot() {
let lc = "HD 1695 .K55 .V5 2010";
let expected = LC {
genre: Genre("HD"),
second: Second(1695.0),
third: Third {
has_dot: true,
body: "K55",
},
fourth: Some(Third {
has_dot: true,
body: "V5",
}),
year: Some(Year {
year: 2010,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
// Row { lc: "HD 1695 .55 .K55 .V5 2010" }
#[test]
fn space_in_float() {
let lc = "HD 1695 .55 .K55 .V5 2010";
let expected = LC {
genre: Genre("HD"),
second: Second(1695.55),
third: Third {
has_dot: true,
body: "K55",
},
fourth: Some(Third {
has_dot: true,
body: "V5",
}),
year: Some(Year {
year: 2010,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
#[test]
fn offset_dots() {
let lc = "HD 1695 .55. K55. V5 2010";
let expected = LC {
genre: Genre("HD"),
second: Second(1695.55),
third: Third {
has_dot: true,
body: "K55",
},
fourth: Some(Third {
has_dot: true,
body: "V5",
}),
year: Some(Year {
year: 2010,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
#[test]
fn round_trip() {
let lc = "HD 1695 .55. K55. V5 2010";
let expected = "HD 1695.55 .K55 .V5 2010";
let lc = LC::maybe_parse(lc).unwrap().unwrap().to_string();
assert_eq!(expected, lc);
}
#[test]
fn round_trip_no_float() {
let lc = "HD 1695 .K55 .V5 2010";
let expected = "HD 1695 .K55 .V5 2010";
let lc = LC::maybe_parse(lc).unwrap().unwrap().to_string();
assert_eq!(expected, lc);
}
// Row { lc: "TD 225 .S25 H26x 2002" }
#[test]
fn trailing_char() {
let lc = "TD 225 .S25 H26x 2002";
dbg!(lc);
let expected = LC {
genre: Genre("TD"),
second: Second(225.0),
third: Third {
has_dot: true,
body: "S25",
},
fourth: Some(Third {
has_dot: false,
body: "H26x",
}),
year: Some(Year {
year: 2002,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
// Row { lc: "G 4364 .R6 .S6C3 2006" }
#[test]
fn midstring_char() {
let lc = "G 4364 .R6 .S6C3 2006";
dbg!(lc);
let expected = LC {
genre: Genre("G"),
second: Second(4364.0),
third: Third {
has_dot: true,
body: "R6",
},
fourth: Some(Third {
has_dot: true,
body: "S6C3",
}),
year: Some(Year {
year: 2006,
suffix: None,
}),
note: None,
};
let (_, lc) = LC::parse(lc).unwrap();
assert_eq!(expected, dbg!(lc));
}
// Test case no longer necessary
// #[test]
// //Row "Circ. desk"
// fn only_text() {
// let lc = "Circ. desk";
// dbg!(lc);
// let expected = LC {
// genre: Genre(None),
// second: Second(None),
// third: Third(None),
// fourth: None,
// year: None,
// note: "Circ. desk",
// };
// let (_, lc) = LC::parse(lc).unwrap();
// assert_eq!(expected,dbg!(lc));
// }
}
|
use bevy::prelude::*;
use crate::{asset_loader, player, camera, level_collision, enemy, AppState, GameState,
follow_text, Kid, level_collision::CollisionShape, cutscene, cutscene::CutsceneSegment };
pub struct LevelReady(pub bool);
pub struct TheaterOutsidePlugin;
impl Plugin for TheaterOutsidePlugin {
fn build(&self, app: &mut AppBuilder) {
app
.insert_resource(LevelReady(false))
.init_resource::<TheaterMeshes>()
.add_plugin(enemy::EnemyPlugin)
.add_plugin(cutscene::CutscenePlugin)
//.insert_resource(PathFinder::new())
//.init_resource::<crate::pause::PauseButtonMaterials>()
//.add_plugin(AudioPlugin)
//.add_event::<holdable::LiftHoldableEvent>()
.add_system_set(
SystemSet::on_enter(crate::AppState::Loading)
.with_system(player::load_assets.system())
.with_system(load_assets.system())
)
.add_system_set(
SystemSet::on_enter(crate::AppState::InGame)
.with_system(load_level.system().label("loading_level"))
.with_system(crate::camera::create_camera.system().after("loading_level"))
.with_system(set_clear_color.system().after("loading_level"))
.with_system(follow_text::create_follow_text.system().after("loading_level"))
.with_system(enemy::spawn_enemies.system().after("loading_level"))
)
.add_system_set(
SystemSet::on_exit(crate::AppState::InGame)
.with_system(cleanup_environment.system())
)
.add_system_set(
SystemSet::on_update(crate::AppState::ResetLevel)
.with_system(reset_level.system())
)
.add_system_set(
SystemSet::on_update(crate::AppState::InGame)
.with_system(player::player_input.system())
.with_system(check_for_level_exit.system())
.with_system(player::player_movement_update.system())
.with_system(listen_for_level_reset.system())
//.with_system(holdable::lift_holdable.system().label("handle_lift_events"))
);
}
}
#[derive(Default)]
pub struct TheaterMeshes {
pub outside: Handle<Mesh>,
pub outside_material: Handle<StandardMaterial>,
pub lobby: Handle<Mesh>,
pub lobby_railing: Handle<Mesh>,
pub lobby_concession: Handle<Mesh>,
pub lobby_desk: Handle<Mesh>,
pub lobby_material: Handle<StandardMaterial>,
pub railing_material: Handle<StandardMaterial>,
pub movie: Handle<Mesh>,
pub movie_material: Handle<StandardMaterial>,
pub legs: Handle<Mesh>,
pub torso: Handle<Mesh>,
pub headhand: Handle<Mesh>,
pub hairone: Handle<Mesh>,
pub hairtwo: Handle<Mesh>,
pub hat: Handle<Mesh>,
pub face: Handle<Mesh>,
pub face_material: Handle<StandardMaterial>,
pub talk_material: Handle<StandardMaterial>,
pub kid_legs: Handle<Mesh>,
pub kid_torso: Handle<Mesh>,
pub kid_headhand: Handle<Mesh>,
pub kid_hairone: Handle<Mesh>,
pub kid_hairtwo: Handle<Mesh>,
pub kid_face: Handle<Mesh>,
}
pub fn check_for_level_exit(
player: Query<(&Transform, &player::Player)>,
level_info_assets: Res<Assets<asset_loader::LevelInfo>>,
level_info_state: Res<asset_loader::LevelInfoState>,
mut current_cutscene: ResMut<cutscene::CurrentCutscene>,
game_state: Res<GameState>,
mut state: ResMut<State<AppState>>,
) {
if game_state.has_seen_half_of_movie {
current_cutscene.trigger(
vec!(
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::A, cutscene::Position::Left),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::B, cutscene::Position::Center_Left),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::C, cutscene::Position::Center_Right),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::D, cutscene::Position::Right),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::D),
cutscene::CutsceneSegment::Textbox("We did it!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::C),
cutscene::CutsceneSegment::Textbox("That part where Ferris wrote a macro from scratch was amazing!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::A),
cutscene::CutsceneSegment::Textbox("Not as amazing as when Ferris used the 'unsafe' keyword!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::B),
cutscene::CutsceneSegment::Textbox("I can't believe that movie was rated PG!".to_string()),
cutscene::CutsceneSegment::NoTalking,
cutscene::CutsceneSegment::Textbox("HEY!".to_string()),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::A, cutscene::Position::Clear),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::B, cutscene::Position::Clear),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::C, cutscene::Position::Clear),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::D, cutscene::Position::Clear),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::Mom, cutscene::Position::Center),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::Mom),
cutscene::CutsceneSegment::Textbox("Just where do you think you're going?".to_string()),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::A, cutscene::Position::Left),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::A),
cutscene::CutsceneSegment::Textbox("Oh no! We've been caught!".to_string()),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::D, cutscene::Position::Right),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::D),
cutscene::CutsceneSegment::Textbox("Umm... sorry everyone".to_string()),
cutscene::CutsceneSegment::Textbox("This is...".to_string()),
cutscene::CutsceneSegment::Textbox("This is... my mom".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::A),
cutscene::CutsceneSegment::Textbox("WHAT!?".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::Mom),
cutscene::CutsceneSegment::Textbox("That's right! And you were going to leave without saying good bye?".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::A),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::B, cutscene::Position::Center_Left),
cutscene::CutsceneSegment::CharacterPosition(cutscene::Character::C, cutscene::Position::Center_Right),
cutscene::CutsceneSegment::Textbox("I don't understand.. ".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::D),
cutscene::CutsceneSegment::Textbox("I guess I should have mentioned that".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::Mom),
cutscene::CutsceneSegment::Textbox("You kids cracked us up, pretending to sneak around".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::C),
cutscene::CutsceneSegment::Textbox("You saw us!?".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::Mom),
cutscene::CutsceneSegment::Textbox("Of course we did!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::C),
cutscene::CutsceneSegment::Textbox("Oh no, we're in trouble now!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::Mom),
cutscene::CutsceneSegment::Textbox("Ha ha, don't you know you four can watch movies for free here?".to_string()),
cutscene::CutsceneSegment::Textbox("All of the staff knows".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::A),
cutscene::CutsceneSegment::Textbox("Why didn't you tell us??".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::D),
cutscene::CutsceneSegment::Textbox("Because you all were so excited to sneak in!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::A),
cutscene::CutsceneSegment::Textbox("Wow, so... this whole thing was just an Illusion of Security!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::B),
cutscene::CutsceneSegment::Textbox("That's the theme of the jam!".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::A),
cutscene::CutsceneSegment::Textbox("what?".to_string()),
cutscene::CutsceneSegment::SetTalking(cutscene::Character::B),
cutscene::CutsceneSegment::Textbox("what??".to_string()),
cutscene::CutsceneSegment::NoTalking,
cutscene::CutsceneSegment::Textbox("AND THAT'S THE END OF THE GAME".to_string()),
cutscene::CutsceneSegment::Textbox("YOU DID IT, THANK YOU FOR PLAYING".to_string()),
cutscene::CutsceneSegment::Textbox("THE GAME CRASHES NOW, BYE!".to_string()),
cutscene::CutsceneSegment::Crash,
),
cutscene::Level::Movie
);
state.push(AppState::Cutscene).unwrap();
return;
}
let levels_asset = level_info_assets.get(&level_info_state.handle);
if let Some(level_asset) = levels_asset {
for (transform, player) in player.iter() {
if player.kid == game_state.controlling {
for (level, shape) in level_asset.collision_info.shapes.iter() {
if *level == game_state.current_level {
match shape {
CollisionShape::LevelSwitch((r, _)) => {
if transform.translation.x >= r.bottom_x
&& transform.translation.x <= r.top_x
&& transform.translation.z <= r.right_z
&& transform.translation.z >= r.left_z {
println!("Level switch triggered!");
current_cutscene.trigger(
vec!(
CutsceneSegment::CameraPosition(8.684685, 1.7965136, -0.079336877,
-0.020942269, -0.9995644, -0.020797854,1.5643123 , 1.0),
CutsceneSegment::LevelSwitch(cutscene::Level::Lobby),
),
cutscene::Level::Outside
);
state.push(AppState::Cutscene).unwrap();
}
}
_ => ()
}
}
}
}
}
}
}
fn load_assets(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut theater_meshes: ResMut<TheaterMeshes>,
mut level_info_state: ResMut<asset_loader::LevelInfoState>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut loading: ResMut<asset_loader::AssetsLoading>,
) {
println!("Adding theater assets");
theater_meshes.outside = asset_server.load("models/theater_outside.glb#Mesh0/Primitive0");
theater_meshes.lobby = asset_server.load("models/lobby.glb#Mesh0/Primitive0");
theater_meshes.lobby_railing = asset_server.load("models/lobby.glb#Mesh1/Primitive0");
theater_meshes.lobby_concession = asset_server.load("models/lobby.glb#Mesh2/Primitive0");
theater_meshes.lobby_desk = asset_server.load("models/lobby.glb#Mesh3/Primitive0");
theater_meshes.movie = asset_server.load("models/movie.glb#Mesh0/Primitive0");
theater_meshes.legs = asset_server.load("models/person.glb#Mesh0/Primitive0");
theater_meshes.torso = asset_server.load("models/person.glb#Mesh1/Primitive0");
theater_meshes.headhand = asset_server.load("models/person.glb#Mesh2/Primitive0");
theater_meshes.hairone = asset_server.load("models/person.glb#Mesh3/Primitive0");
theater_meshes.hat = asset_server.load("models/person.glb#Mesh4/Primitive0");
theater_meshes.face = asset_server.load("models/person.glb#Mesh5/Primitive0");
theater_meshes.kid_face = asset_server.load("models/person.glb#Mesh6/Primitive0");
theater_meshes.kid_hairone = asset_server.load("models/person.glb#Mesh7/Primitive0");
theater_meshes.kid_hairtwo = asset_server.load("models/person.glb#Mesh8/Primitive0");
theater_meshes.kid_headhand = asset_server.load("models/person.glb#Mesh9/Primitive0");
theater_meshes.kid_legs = asset_server.load("models/person.glb#Mesh10/Primitive0");
theater_meshes.kid_torso = asset_server.load("models/person.glb#Mesh11/Primitive0");
theater_meshes.hairtwo = asset_server.load("models/person.glb#Mesh12/Primitive0");
let texture_handle = asset_server.load("models/theater_outside.png");
theater_meshes.outside_material = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
..Default::default()
});
let texture_handle = asset_server.load("models/lobby.png");
theater_meshes.lobby_material = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
..Default::default()
});
let texture_handle = asset_server.load("models/railing.png");
theater_meshes.railing_material = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
..Default::default()
});
let texture_handle = asset_server.load("models/movie.png");
theater_meshes.movie_material = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
..Default::default()
});
let texture_handle = asset_server.load("models/Eyes.png");
theater_meshes.face_material = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
..Default::default()
});
let texture_handle = asset_server.load("models/Mouth.png");
theater_meshes.talk_material = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
..Default::default()
});
loading.asset_handles.push(theater_meshes.outside.clone_untyped());
loading.asset_handles.push(theater_meshes.lobby.clone_untyped());
loading.asset_handles.push(theater_meshes.lobby_railing.clone_untyped());
loading.asset_handles.push(theater_meshes.lobby_concession.clone_untyped());
loading.asset_handles.push(theater_meshes.lobby_desk.clone_untyped());
loading.asset_handles.push(theater_meshes.movie.clone_untyped());
loading.asset_handles.push(theater_meshes.legs.clone_untyped());
loading.asset_handles.push(theater_meshes.torso.clone_untyped());
loading.asset_handles.push(theater_meshes.headhand.clone_untyped());
loading.asset_handles.push(theater_meshes.hairone.clone_untyped());
loading.asset_handles.push(theater_meshes.hairtwo.clone_untyped());
loading.asset_handles.push(theater_meshes.hat.clone_untyped());
loading.asset_handles.push(theater_meshes.face.clone_untyped());
loading.asset_handles.push(theater_meshes.kid_legs.clone_untyped());
loading.asset_handles.push(theater_meshes.kid_torso.clone_untyped());
loading.asset_handles.push(theater_meshes.kid_headhand.clone_untyped());
loading.asset_handles.push(theater_meshes.kid_hairone.clone_untyped());
loading.asset_handles.push(theater_meshes.kid_hairtwo.clone_untyped());
loading.asset_handles.push(theater_meshes.kid_face.clone_untyped());
level_info_state.handle = asset_server.load("data/outside.lvl");
asset_server.watch_for_changes().unwrap();
}
fn listen_for_level_reset(
mut state: ResMut<State<crate::AppState>>,
keyboard_input: Res<Input<KeyCode>>,
) {
if keyboard_input.just_pressed(KeyCode::R) {
state.set(crate::AppState::ResetLevel).unwrap();
}
}
fn reset_level(
mut state: ResMut<State<crate::AppState>>,
mut timer: Local<f32>,
time: Res<Time>,
) {
*timer += time.delta_seconds();
if *timer > 1.0 {
state.set(crate::AppState::InGame).unwrap();
*timer = 0.0;
}
}
fn cleanup_environment(
mut commands: Commands,
level_mesh: Query<Entity, With<TheaterOutside>>,
player: Query<Entity, With<player::Player>>,
enemy: Query<Entity, With<enemy::Enemy>>,
camera: Query<Entity, With<camera::MainCamera>>,
collision_meshes: Query<Entity, With<level_collision::DebugLevelCollisionMesh>>,
) {
for entity in level_mesh.iter() {
commands.entity(entity).despawn_recursive();
}
for entity in player.iter() {
commands.entity(entity).despawn_recursive();
}
for entity in enemy.iter() {
commands.entity(entity).despawn_recursive();
}
for entity in camera.iter() {
commands.entity(entity).despawn_recursive();
}
for entity in collision_meshes.iter() {
commands.entity(entity).despawn_recursive();
}
}
struct TheaterOutside { }
fn load_level(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut level_ready: ResMut<LevelReady>,
mut theater_meshes: ResMut<TheaterMeshes>,
enemy_meshes: Res<enemy::EnemyMeshes>,
person_meshes: Res<player::PersonMeshes>,
asset_server: Res<AssetServer>,
mut level_info_state: ResMut<asset_loader::LevelInfoState>,
level_info_assets: ResMut<Assets<asset_loader::LevelInfo>>,
mut game_state: ResMut<GameState>,
mut state: ResMut<State<crate::AppState>>,
) {
println!("loading level");
println!("Starting to load level...");
let levels_asset = level_info_assets.get(&level_info_state.handle);
if let Some(level_asset) = levels_asset {
println!("Level loaded");
} else {
// try again later?
println!("failed to load level");
state.set(crate::AppState::Loading).unwrap();
return;
}
game_state.current_level = cutscene::Level::Outside;
let color = Color::hex("072AC8").unwrap();
let mut transform = Transform::identity();
// transform.apply_non_uniform_scale(Vec3::new(SCALE, SCALE, SCALE));
// transform.rotate(Quat::from_axis_angle(Vec3::new(0.0, 1.0, 0.0), std::f32::consts::PI));
commands.spawn_bundle(PbrBundle {
transform,
..Default::default()
})
.insert(TheaterOutside {})
.with_children(|parent| {
parent.spawn_bundle(PbrBundle {
mesh: theater_meshes.outside.clone(),
material: theater_meshes.outside_material.clone(),
transform: {
let mut t = Transform::default();
t.rotate(Quat::from_axis_angle(Vec3::new(0.0, 1.0, 0.0), std::f32::consts::PI));
t
},
..Default::default()
});
}).id();
game_state.last_positions = [
(Kid::A, Some(Vec3::new(0.0, 0.0, 0.0))),
(Kid::B, Some(Vec3::new(0.0, 0.0, -1.0))),
(Kid::C, Some(Vec3::new(0.0, 0.0, 0.5))),
(Kid::D, Some(Vec3::new(0.0, 0.0, -0.5))),
].iter().cloned().collect();
player::spawn_player(&mut commands, &mut materials, &mut meshes,
&person_meshes, &theater_meshes, &game_state);
level_ready.0 = true;
}
fn set_clear_color(
mut clear_color: ResMut<ClearColor>,
) {
clear_color.0 = Color::hex("555555").unwrap();
}
|
// Copyright 2018 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
use rocksdb::{ColumnFamilyOptions, DBCompressionType, DBOptions, DB};
use super::tempdir_with_prefix;
#[test]
// Make sure all compression types are supported.
fn test_compression() {
let path = tempdir_with_prefix("_rust_rocksdb_test_metadata");
let compression_types = [
DBCompressionType::Snappy,
DBCompressionType::Zlib,
DBCompressionType::Bz2,
DBCompressionType::Lz4,
DBCompressionType::Lz4hc,
DBCompressionType::Zstd,
];
for compression_type in compression_types.iter() {
let mut opts = DBOptions::new();
opts.create_if_missing(true);
let mut cf_opts = ColumnFamilyOptions::new();
cf_opts.compression(*compression_type);
// DB open will fail if compression type is not supported.
DB::open_cf(
opts,
path.path().to_str().unwrap(),
vec![("default", cf_opts)],
)
.unwrap();
}
}
|
// Copyright 2015 The Gfx-rs Developers.
//
// 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.
//! Various helper macros.
mod pso;
mod structure;
#[macro_export]
macro_rules! gfx_format {
($name:ident : $surface:ident = $container:ident<$channel:ident>) => {
impl $crate::format::Formatted for $name {
type Surface = $crate::format::$surface;
type Channel = $crate::format::$channel;
type View = $crate::format::$container<
<$crate::format::$channel as $crate::format::ChannelTyped>::ShaderType
>;
}
}
}
|
use serde::Deserialize;
// fn deserialize_number_from_string<'de, D: Deserializer<'de>>(deserializer: D) -> Result<usize, D::Error> {
// use serde::de::Error;
// if let Ok(x) = usize::deserialize(deserializer) {
// return Ok(x);
// }
// let string = deserializer.deserialize_str()?;
// string.parse().map_err(|e| D::Error::unexpected(serde::de::Unexpected::Str(string), "unsigned integer"))
// }
use crate::parse::hacks::deserialize_through_str;
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
pub struct Device {
#[serde(rename = "_title")]
name: String,
#[serde(rename = "fs-device-type")]
device_type: String,
#[serde(rename = "fs-free-space")]
#[serde(deserialize_with = "deserialize_through_str")]
free_space: usize,
#[serde(rename = "fs-total-space")]
#[serde(deserialize_with = "deserialize_through_str")]
total_space: usize,
#[serde(rename = "fs-enabled")]
#[serde(deserialize_with = "deserialize_through_str")]
enabled: bool,
#[serde(rename = "fs-readonly")]
#[serde(deserialize_with = "deserialize_through_str")]
read_only: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
pub struct Directory {
#[serde(rename = "_title")]
name: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
pub struct File {
#[serde(rename = "_title")]
name: String,
#[serde(rename = "fs-cdate")]
cdate: String,
#[serde(rename = "fs-mdate")]
mdate: String,
#[serde(rename = "fs-size")]
#[serde(deserialize_with = "deserialize_through_str")]
size: usize,
#[serde(rename = "fs-readonly")]
#[serde(deserialize_with = "deserialize_through_str")]
read_only: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
#[serde(tag = "_type")]
pub enum DirEntry {
#[serde(rename = "fs-dir")]
Directory(Directory),
#[serde(rename = "fs-file")]
File(File),
#[serde(rename = "fs-device")]
Device(Device),
}
pub fn parse_directory_listing(data: &[u8]) -> Result<Vec<DirEntry>, serde_json::Error> {
super::parse_vec::<DirEntry>(data)
}
|
use reqwest::Client;
use roxmltree::Document;
use sqlx::PgPool;
use tracing::{
field::{display, Empty},
Span,
};
use warp::{http::StatusCode, Rejection};
use crate::error::Error;
use crate::requests::{upload_file, youtube_streams, youtube_thumbnail};
use crate::vtubers::VTUBERS;
pub async fn publish_content(
body: String,
pool: PgPool,
client: Client,
) -> Result<StatusCode, Rejection> {
let span = tracing::debug_span!("pubsub_publish", vtuber_id = Empty, video_id = Empty);
tracing::debug!(parent: &span, body = ?body);
let doc = match Document::parse(&body) {
Ok(doc) => doc,
Err(_) => return Ok(StatusCode::BAD_REQUEST),
};
if let Some((vtuber_id, video_id, title)) = parse_modification(&doc) {
span.record("vtuber_id", &display(vtuber_id));
span.record("video_id", &display(video_id));
let streams = youtube_streams(&client, &[&video_id]).await?;
tracing::debug!(parent: &span, streams = ?streams);
if streams.is_empty() {
return Ok(StatusCode::BAD_REQUEST);
}
let thumbnail_url = upload_thumbnail(&streams[0].id, &span, &client)
.await
.map(|filename| format!("https://holo.poi.cat/thumbnail/{}", filename));
let _ = sqlx::query!(
r#"
insert into youtube_streams (stream_id, vtuber_id, title, status, thumbnail_url, schedule_time, start_time, end_time)
values ($1, $2, $3, $4::text::stream_status, $5, $6, $7, $8)
on conflict (stream_id) do update
set (title, status, thumbnail_url, schedule_time, start_time, end_time)
= ($3, $4::text::stream_status, coalesce($5, youtube_streams.thumbnail_url), $6, $7, $8)
"#,
streams[0].id,
vtuber_id,
title,
streams[0].status.as_str(),
thumbnail_url,
streams[0].schedule_time,
streams[0].start_time,
streams[0].end_time,
)
.execute(&pool)
.await
.map_err(Error::Database)?;
return Ok(StatusCode::OK);
}
if let Some((video_id, vtuber_id)) = parse_deletion(&doc) {
span.record("vtuber_id", &display(vtuber_id));
span.record("video_id", &display(video_id));
let _ = sqlx::query!(
r#"
delete from youtube_streams
where stream_id = $1
and vtuber_id = $2
and status = 'scheduled'::stream_status
"#,
video_id,
vtuber_id,
)
.execute(&pool)
.await
.map_err(Error::Database)?;
return Ok(StatusCode::OK);
}
Ok(StatusCode::BAD_REQUEST)
}
async fn upload_thumbnail(stream_id: &str, span: &Span, client: &Client) -> Option<String> {
// TODO: versioning filename using md5
let filename = format!("{}.jpg", stream_id);
let data = match youtube_thumbnail(stream_id, &client).await {
Ok(x) => x,
Err(e) => {
tracing::warn!(parent: span, err = ?e, "failed to upload thumbnail");
return None;
}
};
match upload_file(&filename, data, "image/jpg", &client).await {
Ok(_) => {
tracing::debug!(parent: span, "thumbnail uploaded");
Some(filename)
}
Err(e) => {
tracing::warn!(parent: span, err = ?e, "failed to upload thumbnail");
None
}
}
}
pub fn parse_modification<'a>(doc: &'a Document) -> Option<(&'a str, &'a str, &'a str)> {
let video_id = doc
.descendants()
.find(|n| n.tag_name().name() == "videoId")
.and_then(|n| n.text())?;
// skip the frist title element
let title = doc
.descendants()
.filter(|n| n.tag_name().name() == "title")
.nth(1)
.and_then(|n| n.text())?;
let channel_id = doc
.descendants()
.find(|n| n.tag_name().name() == "channelId")
.and_then(|n| n.text())?;
let vtuber_id = VTUBERS
.iter()
.find(|v| v.youtube == Some(channel_id))
.map(|v| v.id)?;
Some((vtuber_id, video_id, title))
}
pub fn parse_deletion<'a>(doc: &'a Document) -> Option<(&'a str, &'a str)> {
let stream_id = doc
.descendants()
.find(|n| n.tag_name().name() == "deleted-entry")
.and_then(|n| n.attribute("ref"))
.and_then(|r| r.get("yt:video:".len()..))?;
let channel_id = doc
.descendants()
.find(|n| n.tag_name().name() == "uri")
.and_then(|n| n.text())
.and_then(|n| n.get("https://www.youtube.com/channel/".len()..))?;
let vtuber_id = VTUBERS
.iter()
.find(|v| v.youtube == Some(channel_id))
.map(|v| v.id)?;
Some((stream_id, vtuber_id))
}
|
use List::*;
enum List {
//Cons: Tuple struct that wraps an element and a pointer to the next node
Cons(u32, Box<List>),
// Nil: signifies the the end of the list
Nil,
}
//Methods can be attached to an enum
impl List {
//Create a new List
fn new() -> List {
//Nil has the type list
Nil
}
// Add a new element to the given list
fn prepend(self, elem: u32) -> List {
// Cons has the type list
Cons(elem, Box::new(self))
}
//return the length of this list
fn len(&self) -> u32 {
match *self {
//Base case when list is empty, len is zero
Nil => 0,
// get the reference to the tail
Cons(_,ref tail) => 1 + tail.len()
}
}
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
//format! is similar to println! macro but returns
// a heap allocated string instead of printing it
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!{"Nil"}
},
}
}
}
fn main() {
// Create an empty linked list
let mut list = List::new();
// Prepend some elements
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Show the final state of the list
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}
|
#[derive(Debug, Clone)]
pub struct Token {
pub token_type: TokenType,
pub lexeme: String,
pub literal: Option<Literal>,
pub line: u32,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TokenType {
// Single-character tokens.
LeftParen, RightParen, LeftBrace, RightBrace,
Comma, Dot, Minus, Plus, SemiColon, Slash, Star,
// One or two character tokens.
Bang, BangEqual,
Equal, EqualEqual,
Greater, GreaterEqual,
Less, LessEqual,
// Literals.
Identifier, String, Number,
// Keywords.
And, Class, Else, False, Fun, For, If, Nil, Or,
Print, Return, Super, This, True, Var, While,
Eof
}
impl ToString for Token {
fn to_string(&self) -> String {
format!("{:?} {} {:?}", self.token_type, self.lexeme, self.literal)
}
}
impl Token {
pub fn new(token_type: TokenType, lexeme: String, literal: Option<Literal>, line: u32) -> Self {
Token {
token_type,
lexeme,
literal,
line,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
Bool(bool),
Number(f64),
String(String),
Nil,
} |
pub fn experiments() {
let rule_1: &str = "
Each object can used exactly once.
Once you use an object it is moved to the new location
and is no longer usable in the old.
";
println!("Rule 1: {}", rule_1);
// So the deeper question is what constitutes "using"
struct A;
let a = A;
let b = a;
// won't compile
// let c = a;
let c = b;
// This is such a small concept, but I somehow never got it,
// and had so many problems around it, I need to go back,
// and tackle a lot of areas I used to be struggling with.
//
// and thats just from reading a sentence!
// Note to self: Tell new Rustaceans this
}
|
use lib::load_file;
use lib::setup::quick_setup::{initialize_demo, quick_demo};
use lib::types::buffer::ebo::EBO;
use lib::types::buffer::vao_builder::VAOBuilder;
use lib::types::buffer::vbo::VBO;
use lib::types::data::data_layout::DataLayout;
use lib::types::linalg::dimension::Dimension;
use lib::types::linalg::matrix::Matrix;
use lib::types::shader::shader::Shader;
use lib::types::shader::shader_program::ShaderProgram;
use std::time::SystemTime;
pub const SIERPINSKI_DEPTH: usize = 9;
pub fn main() {
let demo = initialize_demo("Sierpinski GPU", Dimension::new(900, 700));
let vertex_shader = Shader::from_source(
load_file("./shaders/sierpinski_gpu_vertex.glsl"),
gl::VERTEX_SHADER,
)
.unwrap();
let fragment_shader = Shader::from_source(
load_file("./shaders/sierpinski_gpu_fragment.glsl"),
gl::FRAGMENT_SHADER,
)
.unwrap();
let shader_program = ShaderProgram::link(&[&vertex_shader, &fragment_shader]).unwrap();
let iterations = shader_program.uniform_from_str("iterations").unwrap();
let rotate = shader_program.uniform_from_str("rotationMatrix").unwrap();
let noise = shader_program.uniform_from_str("noise").unwrap();
let mut vertices = Vec::new();
let mut indices = Vec::new();
sierpinski_triangle(
&mut vertices,
&mut indices,
SIERPINSKI_DEPTH,
Matrix::<f32>::from_data(vec![-1.0, -1.0], Dimension::new(2, 1)),
Matrix::<f32>::from_data(vec![1.0, -1.0], Dimension::new(2, 1)),
Matrix::<f32>::from_data(vec![0., 1.0], Dimension::new(2, 1)),
);
let data_layout =
DataLayout::infer_from_f32slice(&vertices, &[], gl::FALSE, vertices.len() / 2);
let (vao, _vbo, _ebo) =
VAOBuilder::from_vbo(VBO::default(), &vertices, gl::STATIC_DRAW, data_layout)
.add_ebo(EBO::default(), &indices, gl::STATIC_DRAW)
.compile();
let now = SystemTime::now();
let mut curr_time = SystemTime::now();
quick_demo(
demo,
|| {
let elapsed_time = now.elapsed().unwrap().as_secs_f32();
let rotation_matrix = Matrix::<f32>::identity4().rotate4(0.0, 1.0, 0.0, elapsed_time);
unsafe {
gl::ClearColor(0.2, 0.3, 0.3, 1.0);
gl::Clear(gl::COLOR_BUFFER_BIT);
shader_program.gl_use();
shader_program.uniform_matrix4fv(&rotate, &rotation_matrix);
shader_program.uniform1f(&noise, elapsed_time);
shader_program.uniform1i(&iterations, SIERPINSKI_DEPTH as i32);
vao.bind();
gl::DrawElements(
gl::TRIANGLES,
indices.len() as i32,
gl::UNSIGNED_INT,
std::ptr::null(),
);
}
println!(
"Current frame took: {}",
curr_time.elapsed().unwrap().as_millis()
);
curr_time = SystemTime::now();
},
|_| {},
);
}
pub fn sierpinski_triangle(
vertices: &mut Vec<f32>,
indices: &mut Vec<u32>,
depth: usize,
bottom_left: Matrix<f32>,
bottom_right: Matrix<f32>,
top: Matrix<f32>,
) {
if depth == 0 {
return;
}
let new_bottom = (&bottom_left + &bottom_right) * 0.5;
let new_left = (&bottom_left + &top) * 0.5;
let new_right = (&top + &bottom_right) * 0.5;
sierpinski_triangle(
vertices,
indices,
depth - 1,
bottom_left,
new_bottom.clone(),
new_left.clone(),
);
sierpinski_triangle(
vertices,
indices,
depth - 1,
new_left.clone(),
new_right.clone(),
top,
);
sierpinski_triangle(
vertices,
indices,
depth - 1,
new_bottom.clone(),
bottom_right,
new_right.clone(),
);
let len = indices.len() as u32;
vertices.extend_from_slice(&new_right.data[0..2]);
vertices.extend_from_slice(&new_bottom.data[0..2]);
vertices.extend_from_slice(&new_left.data[0..2]);
indices.push(len);
indices.push(len + 1);
indices.push(len + 2);
}
|
extern crate rs_munge;
use rs_munge::{encode, decode};
fn main() {
let orig_payload = b"abc";
let message = decode(&encode(Some(orig_payload)).unwrap()).unwrap();
let payload = message.payload().unwrap();
assert_eq!(payload, orig_payload);
assert!(message.uid() > 0);
assert!(message.gid() > 0);
println!("{:?}", message);
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Tests surrounding exit logic.
use std::sync::Mutex;
use reverie::syscalls;
use reverie::syscalls::Syscall;
use reverie::syscalls::SyscallInfo;
use reverie::syscalls::Sysno;
use reverie::Error;
use reverie::ExitStatus;
use reverie::GlobalRPC;
use reverie::GlobalTool;
use reverie::Guest;
use reverie::Pid;
use reverie::Tool;
#[derive(Debug, Default)]
struct GlobalState {
// FIXME: Can't use (Pid, ExitStatus) types here since they don't implement
// Serialize/Deserialize.
exited: Mutex<Vec<(i32, ExitStatus)>>,
}
#[reverie::global_tool]
impl GlobalTool for GlobalState {
type Request = ExitStatus;
type Response = ();
type Config = ();
async fn receive_rpc(&self, from: Pid, exit_status: ExitStatus) -> Self::Response {
self.exited
.lock()
.unwrap()
.push((from.as_raw(), exit_status));
}
}
#[derive(Debug, Default, Clone)]
struct InjectExitTool {}
#[reverie::tool]
impl Tool for InjectExitTool {
type GlobalState = GlobalState;
type ThreadState = ();
async fn on_exit_process<G: GlobalRPC<Self::GlobalState>>(
self,
_pid: Pid,
global_state: &G,
exit_status: ExitStatus,
) -> Result<(), Error> {
global_state.send_rpc(exit_status).await;
Ok(())
}
async fn handle_syscall_event<T: Guest<Self>>(
&self,
guest: &mut T,
syscall: Syscall,
) -> Result<i64, Error> {
if syscall.number() == Sysno::getpid {
guest
.tail_inject(syscalls::ExitGroup::new().with_status(42))
.await
} else {
guest.tail_inject(syscall).await
}
}
}
#[cfg(not(sanitized))]
#[test]
fn smoke() {
use reverie_ptrace::testing::test_fn;
let (output, state) = test_fn::<InjectExitTool, _>(|| unsafe {
let _ = libc::getpid();
libc::syscall(libc::SYS_exit_group, 0);
})
.unwrap();
assert_eq!(output.status, ExitStatus::Exited(42));
let mut mg = state.exited.lock().unwrap();
assert_eq!(mg.pop().map(|x| x.1), Some(ExitStatus::Exited(42)));
assert!(mg.is_empty());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.