text stringlengths 8 4.13M |
|---|
fn main() {
let mut a = 1;
for i in 0..=5 {
a += i;
}
println!("{}", a);
} |
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![feature(mpsc_select)]
extern crate chrono;
extern crate timer;
extern crate elevator;
use std::{thread, time};
use elevator::elevator_driver::elev_io::*;
use elevator::elevator_fsm::elevator_fsm::*;
use std::sync::mpsc::channel;
use elevator::request_handler::request_transmitter::*;
use elevator::request_handler::request_transmitter::BroadcastMessage;
use std::rc::Rc;
fn main() {
let request_transmitter: Rc<RequestTransmitter> = Rc::new(
RequestTransmitter::new()
);
let mut elevator = Elevator::new(request_transmitter.clone());
let ref peer_rx = request_transmitter.peer_receiver;
let ref request_rx = request_transmitter.bcast_receiver;
let (button_tx, button_rx) = channel::<Button>();
thread::spawn(move|| {
let io = ElevIo::new().unwrap();
let TOP_FLOOR = N_FLOORS-1;
loop {
for floor in 0..N_FLOORS {
// Buttons at current floor
let button_call_up = Button::CallUp(Floor::At(floor));
let button_call_down = Button::CallDown(Floor::At(floor));
let button_internal = Button::Internal(Floor::At(floor));
if floor != TOP_FLOOR {
if let Signal::High = io.get_button_signal(button_call_up).unwrap() {
button_tx.send(button_call_up).unwrap();
}
}
if floor != 0 {
if let Signal::High = io.get_button_signal(button_call_down).unwrap() {
button_tx.send(button_call_down).unwrap();
}
}
if let Signal::High = io.get_button_signal(button_internal).unwrap() {
button_tx.send(button_internal).unwrap();
}
}
thread::sleep(time::Duration::from_millis(20));
}
});
println!("creating");
thread::sleep(time::Duration::from_secs(1));
println!("ready!");
loop {
if let Floor::At(_) = elevator.io.get_floor_signal().unwrap() {
elevator.event_at_floor();
} else {
elevator.event_running();
}
if let Signal::High = elevator.io.get_stop_signal()
.expect("Get StopSignal failed") {
elevator.io.set_motor_dir(MotorDir::Stop)
.expect("Set MotorDir failed");
return;
}
if elevator.door_timer.timeout() {
elevator.event_doors_should_close();
}
if elevator.stuck_timer.timeout() {
elevator.event_stuck();
panic!("Elevator is stuck.");
}
let (timer_tx, timer_rx) = channel::<()>();
let timer = timer::Timer::new();
let timer_guard = timer.schedule_repeating(chrono::Duration::milliseconds(150), move|| {
timer_tx.send(());
});
timer_guard.ignore();
select! {
update_msg = peer_rx.recv() => {
let update = update_msg.unwrap();
elevator.request_handler.handle_peer_update(update);
},
bcast_msg = request_rx.recv() => {
let (message, remote_ip) = bcast_msg.unwrap();
match message {
BroadcastMessage::RequestMessage(request) => {
elevator.event_request_message(&request, remote_ip);
},
BroadcastMessage::Position(floor) => {
elevator.event_position_message(remote_ip, floor);
},
}
},
_ = timer_rx.recv() => {
request_transmitter.bcast_sender.send(BroadcastMessage::Position(elevator.current_floor));
elevator.request_handler.announce_all_requests();
},
button_msg = button_rx.recv() => {
let button = button_msg.unwrap();
elevator.event_new_floor_order(button);
}
}
}
}
|
use ash::version::EntryV1_0;
use ash::{vk, Entry, Instance};
use std::{
ffi::{CStr, CString},
os::raw::{c_char, c_void},
};
use ash::extensions::ext::DebugUtils;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
#[cfg(debug_assertions)]
pub const ENABLE_VALIDATION_LAYERS: bool = true;
#[cfg(not(debug_assertions))]
pub const ENABLE_VALIDATION_LAYERS: bool = false;
const REQUIRED_LAYERS: [&str; 1] = ["VK_LAYER_KHRONOS_validation"];
unsafe extern "system" fn vulkan_debug_utils_callback(
msg_severity: vk::DebugUtilsMessageSeverityFlagsEXT,
msg_type: vk::DebugUtilsMessageTypeFlagsEXT,
callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT,
_user_data: *mut c_void,
) -> u32 {
use vk::DebugUtilsMessageSeverityFlagsEXT as MsgSeverity;
// use vk::DebugUtilsMessageTypeFlagsEXT as MsgType;
// might be better to use the ordering like this, but i'll fix
// that later if it's worthwhile
// if msg_severity <= MsgSeverity::VERBOSE {
// } else if msg_severity <= MsgSeverity::INFO {
// } else if msg_severity <= MsgSeverity::WARNING {
// } else if msg_severity <= MsgSeverity::ERROR {
// }
let p_message_id = (*callback_data).p_message_id_name as *const c_char;
let p_message = (*callback_data).p_message as *const c_char;
let _queue_labels = {
let queue_label_count = (*callback_data).queue_label_count as usize;
let ptr = (*callback_data).p_queue_labels;
std::slice::from_raw_parts(ptr, queue_label_count)
};
let cmd_buf_labels = {
let cmd_buf_label_count = (*callback_data).cmd_buf_label_count as usize;
let ptr = (*callback_data).p_cmd_buf_labels;
std::slice::from_raw_parts(ptr, cmd_buf_label_count)
};
let objects = {
let object_count = (*callback_data).object_count as usize;
let ptr = (*callback_data).p_objects;
std::slice::from_raw_parts(ptr, object_count)
};
let p_msg_id_str = if p_message_id.is_null() {
"0".to_string()
} else {
format!("{:?}", CStr::from_ptr(p_message_id))
};
let p_msg_str = if p_message.is_null() {
"-".to_string()
} else {
format!("{:?}", CStr::from_ptr(p_message))
};
let mut message_string =
format!("{} - {:?} - {}", p_msg_id_str, msg_type, p_msg_str,);
if !cmd_buf_labels.is_empty() {
message_string.push_str("\n Command buffers: ");
for cmd_buf in cmd_buf_labels {
if !cmd_buf.p_label_name.is_null() {
message_string.push_str(&format!(
"{:?}",
CStr::from_ptr(cmd_buf.p_label_name)
));
}
}
message_string.push_str("\n");
}
if !objects.is_empty() {
let mut first = true;
for obj in objects {
if !obj.p_object_name.is_null() {
if first {
message_string.push_str("\n Objects: \n");
first = false;
}
message_string.push_str(&format!(
" {:#x} - {:?}\n",
obj.object_handle,
CStr::from_ptr(obj.p_object_name),
));
}
}
}
match msg_severity {
MsgSeverity::VERBOSE => {
debug!("{}", message_string);
}
MsgSeverity::INFO => {
info!("{}", message_string);
}
MsgSeverity::WARNING => {
warn!("{}", message_string);
}
MsgSeverity::ERROR => {
error!("{}", message_string);
}
_ => {
error!("{}", message_string);
}
}
vk::FALSE
}
/// Get the pointers to the validation layers names.
/// Also return the corresponding `CString` to avoid dangling pointers.
pub fn get_layer_names_and_pointers() -> (Vec<CString>, Vec<*const c_char>) {
let layer_names = REQUIRED_LAYERS
.iter()
.map(|name| CString::new(*name).unwrap())
.collect::<Vec<_>>();
let layer_names_ptrs = layer_names
.iter()
.map(|name| name.as_ptr())
.collect::<Vec<_>>();
(layer_names, layer_names_ptrs)
}
/// Check if the required validation set in `REQUIRED_LAYERS`
/// are supported by the Vulkan instance.
///
/// # Panics
///
/// Panic if at least one on the layer is not supported.
pub fn check_validation_layer_support(entry: &Entry) {
for required in REQUIRED_LAYERS.iter() {
let found = entry
.enumerate_instance_layer_properties()
.unwrap()
.iter()
.any(|layer| {
let name = unsafe { CStr::from_ptr(layer.layer_name.as_ptr()) };
let name =
name.to_str().expect("Failed to get layer name pointer");
required == &name
});
if !found {
panic!("Validation layer not supported: {}", required);
}
}
}
/// Setup the DebugUtils messenger if validation layers are enabled.
pub fn setup_debug_utils(
entry: &Entry,
instance: &Instance,
) -> Option<(DebugUtils, vk::DebugUtilsMessengerEXT)> {
if !ENABLE_VALIDATION_LAYERS {
return None;
}
let severity = {
use vk::DebugUtilsMessageSeverityFlagsEXT as Severity;
// TODO use the flexi_logger configuration here
Severity::all()
};
let types = {
use vk::DebugUtilsMessageTypeFlagsEXT as Type;
// TODO maybe some customization here too
Type::all()
};
let create_info = vk::DebugUtilsMessengerCreateInfoEXT::builder()
.message_severity(severity)
.message_type(types)
.pfn_user_callback(Some(vulkan_debug_utils_callback))
.build();
let debug_utils = DebugUtils::new(entry, instance);
// TODO this should probably return Result, but i need to handle
// the return at the top of this function first
let messenger = unsafe {
debug_utils
.create_debug_utils_messenger(&create_info, None)
.ok()
}?;
Some((debug_utils, messenger))
}
pub fn begin_cmd_buf_label(
utils: Option<&DebugUtils>,
cmd_buf: vk::CommandBuffer,
label: &str,
) {
if let Some(utils) = utils {
let name = CString::new(label.as_bytes()).unwrap();
let label = vk::DebugUtilsLabelEXT::builder().label_name(&name).build();
unsafe {
utils.cmd_begin_debug_utils_label(cmd_buf, &label);
}
}
}
pub fn end_cmd_buf_label(
utils: Option<&DebugUtils>,
cmd_buf: vk::CommandBuffer,
) {
if let Some(utils) = utils {
unsafe {
utils.cmd_end_debug_utils_label(cmd_buf);
}
}
}
|
use std::fmt;
/// `ResultInspector` makes it easier to examine the content of the `Result` object.
#[allow(clippy::module_name_repetitions)]
pub trait ResultInspector<T, E> {
/// Do something with `Result`'s item, passing the value on.
///
/// When using `Result`, you'll often chain several combinators together.
/// While working on such code, you might want to check out what's happening
/// at various parts in the pipeline. To do that, insert a call to inspect().
///
/// It's more common for inspect() to be used as a debugging tool than to exist
/// in your final code, but applications may find it useful in certain situations
/// when data needs to be logged before being manipulated.
/// See also `std::iter::Iterator::inspect`
///
/// `ResultInspector::inspect()` only acts on the `Ok(_)` variant of the `Result` object
/// and does nothing when it is `Err(_)`.
///
/// ```rust
/// # extern crate log;
/// # use log::info;
/// # use inspector::ResultInspector;
///
/// let env = std::env::var("XXX").inspect(|env| info!("Env var XXX is {:?}", env));
/// ```
fn inspect<F>(self, f: F) -> Result<T, E>
where
F: FnMut(&T);
/// Same as `ResultInspector::inspect()`, but only acts on `Err(_)` variant.
///
/// ```rust
/// # extern crate log;
/// # use log::error;
/// # use inspector::ResultInspector;
///
/// let env = std::env::var("XXX")
/// .inspect_err(|err| error!("Failed to get env var XXX: {:?}", err))
/// .unwrap_or_else(|_| String::new());
/// ```
fn inspect_err<F>(self, f: F) -> Result<T, E>
where
F: FnMut(&E);
/// Convenience wrapper for having a quick debug print out of your item.
/// It is equivalent to calling `inspect(|item| println!("{:?}", item))`.
///
/// ```rust
/// # use inspector::ResultInspector;
///
/// let env = std::env::var("XXX").debug();
/// ```
fn debug(self) -> Result<T, E>;
}
impl<T, E> ResultInspector<T, E> for Result<T, E>
where
T: fmt::Debug,
{
#[inline]
fn inspect<F>(self, mut f: F) -> Self
where
F: FnMut(&T),
{
if cfg!(any(debug_assertions, not(feature = "debug-only"))) {
if let Ok(ref item) = self {
f(item);
}
}
self
}
#[inline]
fn inspect_err<F>(self, mut f: F) -> Self
where
F: FnMut(&E),
{
if cfg!(any(debug_assertions, not(feature = "debug-only"))) {
if let Err(ref item) = self {
f(item);
}
}
self
}
#[inline]
fn debug(self) -> Self {
self.inspect(|item| println!("{:?}", item))
}
}
|
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// # Nombre: Daniela Guadalupe Ramirez Castillo #
// # Matricula: 170659 #
// # Carrera: ITI #
// # #
// # Descripcion: Codigo en Rust acerca de las principales operaciones con conjuntos #
// # #
// # Written: 09/13/2020 #
// # Last Update: 09/15/2020 #
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
use std::collections::HashSet;
//definimos los tres sets
fn creacion()
{
let mut A = HashSet::new();
let mut B = HashSet::new();
let mut C = HashSet::new();
A.insert(1);
A.insert(2);
A.insert(3);
A.insert(4);
A.insert(5);
B.insert(3);
B.insert(4);
B.insert(5);
B.insert(6);
B.insert(7);
C.insert(1);
C.clear();
println!("\n------Conjunto A:------");
for num in &A
{
print!("{}", num);
}
println!("\n------Conjunto B:------");
for num in &B
{
print!("{}", num);
}
println!("\n------Conjunto C:------");
for num in &C
{
print!("{}", num);
}
}
//Remueve un elemento del conjunto
fn quitar()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [3, 4, 5, 6, 7].iter().cloned().collect();
println!("\nEliminar datos del conjunto A: ");
A.remove(&2);
println!("\n------Conjunto A actualizado:------");
for num in &A
{
print!("{}", num);
}
}
fn pertenencia()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [3, 4, 5, 6, 7].iter().cloned().collect();
println!("\nPertenencia");
println!("\n1 in A:");
print!("{}", A.contains(&1));
println!("\n1 not in A:");
print!("{}", A.contains(&1));
println!("\n10 in A:");
print!("{}", A.contains(&10));
println!("\n10 not in A:");
print!("{}", A.contains(&10));
}
//Remueve todos los elementos del set
fn clearSet()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
A.clear();
println!("\n------Conjunto A actualizado:------");
for num in &A
{
print!("{}", num);
}
}
//Copia un conjunto
fn copiar()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().collect();
let mut B: HashSet<_> = A.clone();
println!("Set A = {:?} compare set B = {:?}", &A, &B);
}
//Agrega un elemento
fn agregar()
{
let mut B = HashSet::new();
B.insert(1);
B.insert(2);
B.insert(3);
B.insert(4);
B.insert(5);
B.insert(987);
println!("\n------Conjunto B actualizado:------");
for num in &B
{
print!("{}", num);
}
}
//union
fn union()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [1, 2, 3, 4, 5, 987].iter().cloned().collect();
for x in A.union(&B)
{
print!("{ }", x);
}
}
//Interseccion
fn interseccion()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [1, 2, 3, 4, 5, 987].iter().cloned().collect();
for x in A.intersection(&B)
{
print!("{}", x);
}
}
//diferencia
fn diferencia()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [1, 2, 3, 4, 5, 987].iter().cloned().collect();
for x in A.difference(&B)
{
print!("{}", x);
}
}
//Diferencia simetrica
fn simetrica()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [1, 2, 3, 4, 5, 987].iter().cloned().collect();
let mut C = HashSet::new();
C.insert(1);
C.clear();
for x in A.symmetric_difference(&B)
{
print!("{}", x);
}
for x in B.symmetric_difference(&A)
{
print!("{}", x);
}
for x in A.symmetric_difference(&C)
{
print!("{}", x);
}
for x in B.symmetric_difference(&C)
{
print!("{}", x);
}
}
//Subconjunto
fn subconjunto()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [1, 2, 3, 4, 5, 987].iter().cloned().collect();
print!("El subconjunto= ");
println!("{}",A.is_subset(&B));
print!("El subconjunto= ");
println!("{}",B.is_subset(&A));
}
//superconjunto
fn superconjunto()
{
let mut A: HashSet<_> = [1, 2, 3, 4, 5].iter().cloned().collect();
let mut B: HashSet<_> = [1, 2, 3, 4, 5, 987].iter().cloned().collect();
print!("El superconjunto= ");
println!("{}",B.is_superset(&A));
print!("El superconjunto= ");
println!("{}",A.is_superset(&B));
}
fn main() {
let mut A = HashSet::new();
let mut B = HashSet::new();
let mut C = HashSet::new();
A.insert(1);
A.insert(2);
A.insert(3);
A.insert(4);
A.insert(5);
B.insert(3);
B.insert(4);
B.insert(5);
B.insert(6);
B.insert(7);
C.insert(1);
C.clear();
println!("\n------Conjunto A:------");
for num in &A
{
print!("{}", num);
}
println!("\n------Conjunto B:------");
for num in &B
{
print!("{}", num);
}
println!("\n------Conjunto C:------");
for num in &C
{
print!("{}", num);
}
//pertenencia
println!("\nPertenencia");
println!("\n1 in A:");
print!("{}", A.contains(&1));
println!("\n1 not in A:");
print!("{}", A.contains(&1));
println!("\n10 in A:");
print!("{}", A.contains(&10));
println!("\n10 not in A:");
print!("{}", A.contains(&10));
quitar();
clearSet();
copiar();
agregar();
union();
interseccion();
diferencia();
simetrica();
subconjunto();
superconjunto();
}
|
//! Sarkara is a Post-Quantum cryptography library.
#[macro_use] extern crate arrayref;
#[macro_use] extern crate failure;
extern crate rand;
extern crate seckey;
extern crate dilithium;
extern crate kyber;
extern crate sparx_cipher;
extern crate colm;
extern crate norx;
pub mod sign;
pub mod kex;
pub mod aead;
pub mod sealedbox;
pub trait Packing: Sized {
const BYTES_LENGTH: usize;
/// TODO should be `as_bytes(&self, buf: &[u8; Self::LENGTH])`
fn read_bytes(&self, buf: &mut [u8]);
/// TODO should be `from_bytes(buf: &[u8; Self::LENGTH]) -> Self`
fn from_bytes(buf: &[u8]) -> Self;
}
|
pub use self::mat2x2::*;
pub use self::mat3x3::*;
pub use self::mat4x4::*;
pub mod mat2x2;
pub mod mat3x3;
pub mod mat4x4;
|
extern crate harust as haru;
// use haru::paper::{
// Page,
// Orientation
// };
fn main() {
let doc = haru::Document::new().ok().unwrap();
let has_doc = doc.has_handle();
println!("handle has a document: {}", has_doc);
doc.add_page();
let name = "Prova.pdf";
doc.save_to_file(&name).ok();
}
|
// pub mod ahci;
// pub mod ata;
pub mod pci;
|
use std::collections::HashMap;
use errors::*;
use ops::Op;
use Model;
use Node;
use Plan;
mod constants;
mod types;
pub mod prelude {
pub use super::types::*;
pub use super::Analyser;
use Result;
/// Attempts to unify two tensor facts into a more specialized one.
pub fn unify(x: &TensorFact, y: &TensorFact) -> Result<TensorFact> {
x.unify(y)
}
/// Attempts to unify two datatype facts.
pub fn unify_datatype(x: &TypeFact, y: &TypeFact) -> Result<TypeFact> {
x.unify(y)
}
/// Attempts to unify two shape facts.
pub fn unify_shape(x: &ShapeFact, y: &ShapeFact) -> Result<ShapeFact> {
x.unify(y)
}
/// Attempts to unify two dimension facts.
pub fn unify_dim(x: &DimFact, y: &DimFact) -> Result<DimFact> {
x.unify(y)
}
/// Attempts to unify two value facts.
pub fn unify_value(x: &ValueFact, y: &ValueFact) -> Result<ValueFact> {
x.unify(y)
}
}
pub use self::prelude::*;
#[macro_use]
pub mod macros;
#[macro_use]
pub mod helpers;
#[macro_use]
pub mod interface;
/// Tries to auto-detect the names of the input nodes.
pub fn detect_inputs(model: &Model) -> Result<Option<Vec<usize>>> {
let inputs: Vec<_> = model
.nodes()
.iter()
.filter(|n| n.op_name == "Placeholder")
.inspect(|n| info!("Autodetected input node: {} {:?}.", n.id, n.name))
.map(|n| n.id)
.collect();
if inputs.len() > 0 {
Ok(Some(inputs))
} else {
Ok(None)
}
}
/// Tries to auto-detect the name of the output node.
pub fn detect_output(model: &Model) -> Result<Option<usize>> {
// We search for the only node in the graph with no successor.
let mut succs: Vec<Vec<usize>> = vec![Vec::new(); model.nodes().len()];
for node in model.nodes() {
for &link in &node.inputs {
succs[link.0].push(node.id);
}
}
for (i, s) in succs.iter().enumerate() {
if s.len() == 0 {
info!(
"Autodetected output node: {} {:?}.",
i,
model.get_node_by_id(i)?.name
);
return Ok(Some(i));
}
}
Ok(None)
}
/// An edge of the analysed graph, annotated by a fact.
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Edge {
pub id: usize,
pub from_node: Option<usize>,
pub from_out: usize,
pub to_node: Option<usize>,
pub to_input: usize,
pub fact: TensorFact,
}
/// A graph analyser, along with its current state.
pub struct Analyser {
// The original output.
pub output: usize,
// The graph being analysed.
pub nodes: Vec<Node>,
pub edges: Vec<Edge>,
pub prev_edges: Vec<Vec<usize>>,
pub next_edges: Vec<Vec<usize>>,
// The execution plan and unused nodes.
plan: Vec<usize>,
// The current state of the algorithm.
pub current_pass: usize,
pub current_step: usize,
pub current_direction: bool,
}
impl Analyser {
/// Constructs an analyser for the given graph.
///
/// The output argument is used to infer an execution plan for the graph.
/// Changing it won't alter the correctness of the analysis, but it might
/// take much longer to complete.
pub fn new(model: Model, output: usize) -> Result<Analyser> {
let nodes = model.nodes;
let mut edges = vec![];
let mut prev_edges = vec![Vec::new(); nodes.len() + 1];
let mut next_edges = vec![Vec::new(); nodes.len() + 1];
for node in &nodes {
for (ix, input) in node.inputs.iter().enumerate() {
let id = edges.len();
edges.push(Edge {
id,
from_node: Some(input.0),
from_out: input.1.unwrap_or(0),
to_node: Some(node.id),
to_input: ix,
fact: TensorFact::new(),
});
prev_edges[node.id].push(id);
next_edges[input.0].push(id);
}
}
// Add a special output edge.
let special_edge_id = edges.len();
edges.push(Edge {
id: special_edge_id,
from_node: Some(output),
from_out: 0,
to_node: None,
to_input: 0,
fact: TensorFact::new(),
});
next_edges[output].push(special_edge_id);
// Compute an execution plan for the graph.
let plan = Plan::for_nodes(&nodes, &[output])?.order;
let current_pass = 0;
let current_step = 0;
let current_direction = true;
debug!("Using execution plan {:?}.", plan);
Ok(Analyser {
output,
nodes,
edges,
prev_edges,
next_edges,
plan,
current_pass,
current_step,
current_direction,
})
}
/// Adds an user-provided tensor fact to the analyser.
pub fn hint(&mut self, node: usize, fact: &TensorFact) -> Result<()> {
debug!("Hint for node \"{}\": {:?}", self.nodes[node].name, fact);
if node >= self.next_edges.len() {
bail!("There is no node with index {:?}.", node);
}
for &j in &self.next_edges[node] {
self.edges[j].fact = unify(fact, &self.edges[j].fact)?;
}
Ok(())
}
/// Returns a model from the analyser.
pub fn into_model(self) -> Model {
let mut nodes_by_name = HashMap::with_capacity(self.nodes.len());
self.nodes.iter().for_each(|n| {
nodes_by_name.insert(n.name.clone(), n.id);
});
Model {
nodes: self.nodes,
nodes_by_name,
}
}
/// Computes a new execution plan for the graph.
pub fn reset_plan(&mut self) -> Result<()> {
self.plan = Plan::for_nodes(&self.nodes, &[self.output])?.order;
Ok(())
}
/// Detaches the constant nodes and edges from the given graph.
pub fn propagate_constants(&mut self) -> Result<()> {
constants::propagate_constants(self)
}
/// Removes the nodes and edges which are not part of the execution plan.
/// Returns the mapping between the old and new node indexes.
pub fn prune_unused(&mut self) -> Vec<Option<usize>> {
let mut node_used = vec![false; self.nodes.len()];
let mut edge_used = vec![false; self.edges.len()];
for &i in &self.plan {
node_used[i] = true;
}
// Remove the nodes while keeping track of the new indices.
let mut deleted = 0;
let mut node_mapping = vec![None; self.nodes.len()];
for i in 0..self.nodes.len() {
if !node_used[i] {
self.nodes.remove(i - deleted);
self.prev_edges.remove(i - deleted);
self.next_edges.remove(i - deleted);
deleted += 1;
} else {
node_mapping[i] = Some(i - deleted);
self.prev_edges[i - deleted]
.iter()
.for_each(|&j| edge_used[j] = true);
self.next_edges[i - deleted]
.iter()
.for_each(|&j| edge_used[j] = true);
}
}
info!("Deleted {:?} unused nodes.", deleted);
// Update the nodes and edges to use the new indices.
for node in &mut self.nodes {
node.id = node_mapping[node.id].unwrap();
node.inputs
.iter_mut()
.for_each(|i| i.0 = node_mapping[i.0].unwrap());
}
for edge in &mut self.edges {
if let Some(i) = edge.from_node {
edge.from_node = node_mapping[i];
}
if let Some(i) = edge.to_node {
edge.to_node = node_mapping[i];
}
}
// Remove the edges while keeping track of the new indices.
let mut deleted = 0;
let mut edge_mapping = vec![None; self.edges.len()];
for i in 0..self.edges.len() {
if !edge_used[i] {
self.edges.remove(i - deleted);
deleted += 1;
} else {
edge_mapping[i] = Some(i - deleted);
}
}
info!("Deleted {:?} unused edges.", deleted);
// Update the adjacency lists to use the new indices.
for i in 0..self.nodes.len() {
self.prev_edges[i]
.iter_mut()
.for_each(|j| *j = edge_mapping[*j].unwrap());
self.next_edges[i]
.iter_mut()
.for_each(|j| *j = edge_mapping[*j].unwrap());
}
node_mapping
}
/// Runs the entire analysis at once.
pub fn run(&mut self) -> Result<()> {
self.current_pass = 0;
loop {
if !self.run_two_passes()? {
return Ok(());
}
}
}
/// Runs two passes of the analysis.
pub fn run_two_passes(&mut self) -> Result<bool> {
let mut changed = false;
info!(
"Starting pass [pass={:?}, direction={:?}].",
self.current_pass, self.current_direction,
);
// We first run a forward pass.
self.current_step = 0;
for _ in 0..self.plan.len() {
if self.run_step()? {
changed = true;
}
}
info!(
"Starting pass [pass={:?}, direction={:?}].",
self.current_pass, self.current_direction,
);
// We then run a backward pass.
self.current_step = 0;
for _ in 0..self.plan.len() {
if self.run_step()? {
changed = true;
}
}
Ok(changed)
}
/// Runs a single step of the analysis.
pub fn run_step(&mut self) -> Result<bool> {
let changed = self.try_step()?;
// Switch to the next step.
self.current_step += 1;
if self.current_step == self.plan.len() {
self.current_pass += 1;
self.current_direction = !self.current_direction;
self.current_step = 0;
}
Ok(changed)
}
/// Tries to run a single step of the analysis, and returns whether
/// there was any additional information gained during the step.
fn try_step(&mut self) -> Result<bool> {
let node = if self.current_direction {
&self.nodes[self.plan[self.current_step]]
} else {
&self.nodes[self.plan[self.plan.len() - 1 - self.current_step]]
};
debug!(
"Starting step for {} {} ({}) [pass={:?}, direction={:?}, step={:?}].",
node.id,
node.name,
node.op_name,
self.current_pass,
self.current_direction,
self.current_step,
);
let inputs: Vec<_> = self.prev_edges[node.id]
.iter()
.map(|&i| &self.edges[i])
.inspect(|edge| {
trace!(
" Input {:?} from {}/{}: {:?}",
edge.to_node.unwrap(),
edge.from_node.unwrap(),
edge.from_out,
edge.fact
);
})
.map(|edge| edge.fact.clone())
.collect();
// FIXME(liautaud): We should handle multiple output ports in the future.
let mut outputs = vec![TensorFact::new()];
for &i in &self.next_edges[node.id] {
outputs[0] = unify(&self.edges[i].fact, &outputs[0])?;
}
trace!(" Output 0: {:?}", &outputs[0]);
let inferred = node.op
.infer_and_propagate(inputs, outputs)
.map_err(|e| format!("While inferring forward for {}: {}", node.name, e))?;
let mut changed = false;
for (i, &j) in self.prev_edges[node.id].iter().enumerate() {
let fact = &inferred.0[i];
let unified = unify(fact, &self.edges[j].fact)
.map_err(|e| format!("While unifying inputs of node {:?}: {}", node.name, e))?;
if unified != self.edges[j].fact {
debug!(" Refined {} input #{} to {:?}", node.name, i, unified);
changed = true;
self.edges[j].fact = unified;
}
}
for (i, &j) in self.next_edges[node.id].iter().enumerate() {
// FIXME(liautaud): We should handle multiple output ports in the future.
if inferred.1.len() != 1 {
panic!("Inference only supports nodes with a single output port.");
}
let fact = &inferred.1[0];
let unified = unify(fact, &self.edges[j].fact)
.map_err(|e| format!("While unifying outputs of node {:?}: {}", node.name, e))?;
if unified != self.edges[j].fact {
debug!(" Refined {} output #{} to {:?}", node.name, i, unified);
changed = true;
self.edges[j].fact = unified;
}
}
Ok(changed)
}
}
#[cfg(tests)]
mod tests {
#[test]
fn unify_same_datatype() {
let dt = TypeFact::Only(DataType::DT_FLOAT);
assert_eq!(unify_datatype(&dt, &dt).unwrap(), dt);
}
#[test]
fn unify_different_datatypes_only() {
let dt1 = TypeFact::Only(DataType::DT_FLOAT);
let dt2 = TypeFact::Only(DataType::DT_DOUBLE);
assert!(unify_datatype(&dt1, &dt2).is_err());
}
#[test]
fn unify_different_datatypes_any_left() {
let dt = TypeFact::Only(DataType::DT_FLOAT);
assert_eq!(unify_datatype(&TypeFact::Any, &dt).unwrap(), dt);
}
#[test]
fn unify_different_datatypes_any_right() {
let dt = TypeFact::Only(DataType::DT_FLOAT);
assert_eq!(unify_datatype(&dt, &TypeFact::Any).unwrap(), dt);
}
#[test]
fn unify_same_shape_1() {
let s = ShapeFact::closed(vec![]);
assert_eq!(unify_shape(&s, &s).unwrap(), s);
}
#[test]
fn unify_same_shape_2() {
use super::DimFact::*;
let s = ShapeFact::closed(vec![Any]);
assert_eq!(unify_shape(&s, &s).unwrap(), s);
}
#[test]
fn unify_same_shape_3() {
use super::DimFact::*;
let s = ShapeFact::closed(vec![Only(1), Only(2)]);
assert_eq!(unify_shape(&s, &s).unwrap(), s);
}
#[test]
fn unify_different_shapes_1() {
use super::DimFact::*;
let s1 = ShapeFact::closed(vec![Only(1), Only(2)]);
let s2 = ShapeFact::closed(vec![Only(1)]);
assert!(unify_shape(&s1, &s2).is_err());
}
#[test]
fn unify_different_shapes_2() {
use super::DimFact::*;
let s1 = ShapeFact::closed(vec![Only(1), Only(2)]);
let s2 = ShapeFact::closed(vec![Any]);
assert!(unify_shape(&s1, &s2).is_err());
}
#[test]
fn unify_different_shapes_3() {
use super::DimFact::*;
let s1 = ShapeFact::open(vec![Only(1), Only(2)]);
let s2 = ShapeFact::closed(vec![Any]);
assert!(unify_shape(&s1, &s2).is_err());
}
#[test]
fn unify_different_shapes_4() {
use super::DimFact::*;
let s1 = ShapeFact::closed(vec![Any]);
let s2 = ShapeFact::closed(vec![Any]);
let sr = ShapeFact::closed(vec![Any]);
assert_eq!(unify_shape(&s1, &s2).unwrap(), sr);
}
#[test]
fn unify_different_shapes_5() {
use super::DimFact::*;
let s1 = ShapeFact::closed(vec![Any]);
let s2 = ShapeFact::closed(vec![Only(1)]);
let sr = ShapeFact::closed(vec![Only(1)]);
assert_eq!(unify_shape(&s1, &s2).unwrap(), sr);
}
#[test]
fn unify_different_shapes_6() {
use super::DimFact::*;
let s1 = ShapeFact::open(vec![]);
let s2 = ShapeFact::closed(vec![Only(1)]);
let sr = ShapeFact::closed(vec![Only(1)]);
assert_eq!(unify_shape(&s1, &s2).unwrap(), sr);
}
#[test]
fn unify_different_shapes_7() {
use super::DimFact::*;
let s1 = ShapeFact::open(vec![Any, Only(2)]);
let s2 = ShapeFact::closed(vec![Only(1), Any, Any]);
let sr = ShapeFact::closed(vec![Only(1), Only(2), Any]);
assert_eq!(unify_shape(&s1, &s2).unwrap(), sr);
}
#[test]
fn unify_same_value() {
use ndarray::prelude::*;
let dt = ValueFact::Only(Tensor::F32(ArrayD::zeros(IxDyn(&[1]))));
assert_eq!(unify_value(&dt, &dt).unwrap(), dt);
}
#[test]
fn unify_different_values_only() {
use ndarray::prelude::*;
let dt1 = ValueFact::Only(Tensor::F32(ArrayD::zeros(IxDyn(&[1]))));
let dt2 = ValueFact::Only(Tensor::F32(ArrayD::zeros(IxDyn(&[2]))));
assert!(unify_value(&dt1, &dt2).is_err());
}
#[test]
fn unify_different_values_any_left() {
use ndarray::prelude::*;
let dt = ValueFact::Only(Tensor::F32(ArrayD::zeros(IxDyn(&[1]))));
assert_eq!(unify_value(&ValueFact::Any, &dt).unwrap(), dt);
}
#[test]
fn unify_different_values_any_right() {
use ndarray::prelude::*;
let dt = ValueFact::Only(Tensor::F32(ArrayD::zeros(IxDyn(&[1]))));
assert_eq!(unify_value(&dt, &ValueFact::Any).unwrap(), dt);
}
}
|
#![allow(non_snake_case)]
#[macro_use]
extern crate lazy_static;
extern crate serde_json;
extern crate vmtests;
use serde_json::Value;
use std::collections::HashMap;
use vmtests::{load_tests, run_test};
lazy_static! {
static ref TESTS: HashMap<String, Value> = load_tests("tests/vmBitwiseLogicOperation/");
}
#[test]
fn test_and0() {
run_test(&TESTS["and0"]);
}
#[test]
fn test_and1() {
run_test(&TESTS["and1"]);
}
#[test]
fn test_and2() {
run_test(&TESTS["and2"]);
}
#[test]
fn test_and3() {
run_test(&TESTS["and3"]);
}
#[test]
fn test_and4() {
run_test(&TESTS["and4"]);
}
#[test]
fn test_and5() {
run_test(&TESTS["and5"]);
}
#[test]
fn test_byte0() {
run_test(&TESTS["byte0"]);
}
#[test]
fn test_byte10() {
run_test(&TESTS["byte10"]);
}
#[test]
fn test_byte11() {
run_test(&TESTS["byte11"]);
}
#[test]
fn test_byte1() {
run_test(&TESTS["byte1"]);
}
#[test]
fn test_byte2() {
run_test(&TESTS["byte2"]);
}
#[test]
fn test_byte3() {
run_test(&TESTS["byte3"]);
}
#[test]
fn test_byte4() {
run_test(&TESTS["byte4"]);
}
#[test]
fn test_byte5() {
run_test(&TESTS["byte5"]);
}
#[test]
fn test_byte6() {
run_test(&TESTS["byte6"]);
}
#[test]
fn test_byte7() {
run_test(&TESTS["byte7"]);
}
#[test]
fn test_byte8() {
run_test(&TESTS["byte8"]);
}
#[test]
fn test_byte9() {
run_test(&TESTS["byte9"]);
}
#[test]
fn test_byteBN() {
run_test(&TESTS["byteBN"]);
}
#[test]
fn test_eq0() {
run_test(&TESTS["eq0"]);
}
#[test]
fn test_eq1() {
run_test(&TESTS["eq1"]);
}
#[test]
fn test_eq2() {
run_test(&TESTS["eq2"]);
}
#[test]
fn test_gt0() {
run_test(&TESTS["gt0"]);
}
#[test]
fn test_gt1() {
run_test(&TESTS["gt1"]);
}
#[test]
fn test_gt2() {
run_test(&TESTS["gt2"]);
}
#[test]
fn test_gt3() {
run_test(&TESTS["gt3"]);
}
#[test]
fn test_iszeo2() {
run_test(&TESTS["iszeo2"]);
}
#[test]
fn test_iszero0() {
run_test(&TESTS["iszero0"]);
}
#[test]
fn test_iszero1() {
run_test(&TESTS["iszero1"]);
}
#[test]
fn test_lt0() {
run_test(&TESTS["lt0"]);
}
#[test]
fn test_lt1() {
run_test(&TESTS["lt1"]);
}
#[test]
fn test_lt2() {
run_test(&TESTS["lt2"]);
}
#[test]
fn test_lt3() {
run_test(&TESTS["lt3"]);
}
#[test]
fn test_not0() {
run_test(&TESTS["not0"]);
}
#[test]
fn test_not1() {
run_test(&TESTS["not1"]);
}
#[test]
fn test_not2() {
run_test(&TESTS["not2"]);
}
#[test]
fn test_not3() {
run_test(&TESTS["not3"]);
}
#[test]
fn test_not4() {
run_test(&TESTS["not4"]);
}
#[test]
fn test_not5() {
run_test(&TESTS["not5"]);
}
#[test]
fn test_or0() {
run_test(&TESTS["or0"]);
}
#[test]
fn test_or1() {
run_test(&TESTS["or1"]);
}
#[test]
fn test_or2() {
run_test(&TESTS["or2"]);
}
#[test]
fn test_or3() {
run_test(&TESTS["or3"]);
}
#[test]
fn test_or4() {
run_test(&TESTS["or4"]);
}
#[test]
fn test_or5() {
run_test(&TESTS["or5"]);
}
#[test]
fn test_sgt0() {
run_test(&TESTS["sgt0"]);
}
#[test]
fn test_sgt1() {
run_test(&TESTS["sgt1"]);
}
#[test]
fn test_sgt2() {
run_test(&TESTS["sgt2"]);
}
#[test]
fn test_sgt3() {
run_test(&TESTS["sgt3"]);
}
#[test]
fn test_sgt4() {
run_test(&TESTS["sgt4"]);
}
#[test]
fn test_slt0() {
run_test(&TESTS["slt0"]);
}
#[test]
fn test_slt1() {
run_test(&TESTS["slt1"]);
}
#[test]
fn test_slt2() {
run_test(&TESTS["slt2"]);
}
#[test]
fn test_slt3() {
run_test(&TESTS["slt3"]);
}
#[test]
fn test_slt4() {
run_test(&TESTS["slt4"]);
}
#[test]
fn test_xor0() {
run_test(&TESTS["xor0"]);
}
#[test]
fn test_xor1() {
run_test(&TESTS["xor1"]);
}
#[test]
fn test_xor2() {
run_test(&TESTS["xor2"]);
}
#[test]
fn test_xor3() {
run_test(&TESTS["xor3"]);
}
#[test]
fn test_xor4() {
run_test(&TESTS["xor4"]);
}
#[test]
fn test_xor5() {
run_test(&TESTS["xor5"]);
}
|
// El discurso de Zoe
//
// Copyright (C) 2016 GUL UC3M
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use rand::{thread_rng, Rng};
use texture::scenario::Scenario;
use state::TypeState;
pub struct Sabatini;
/// Descend
fn go_down<S: TypeState>(state: &mut Box<S>) -> Option<String> {
let current_floor = state.get_value("sabatini_floor".to_string());
if current_floor == 1 {
// Out of the building
println!("Sales del edificion.");
return Some("exterior_ir".to_string());
}
// Descend
let new_floor = current_floor - 1;
state.set_value("sabatini_floor".to_string(), new_floor);
println!("Bajas una planta.");
println!(" ");
println!("Estás en la planta {}.", new_floor);
state.reduce_time(10);
return None;
}
/// Ascend
fn go_up<S: TypeState>(state: &mut Box<S>) {
let current_floor = state.get_value("sabatini_floor".to_string());
if current_floor == 3 {
// Cannot go up
println!("No puedes subir más");
return;
}
// Ascend
let new_floor = current_floor + 1;
state.set_value("sabatini_floor".to_string(), new_floor);
println!("Subes una planta.");
println!(" ");
println!("Estás en la planta {}.", new_floor);
if new_floor == 3 {
println!("\nEsta es la planta donde están los despachos de las asociaciones,");
println!("puedes intentar ir al despacho.")
}
state.reduce_time(10);
}
/// Must flee!
fn must_flee<S: TypeState>(command: &str, state: &mut Box<S>) -> Option<String> {
match command {
"huir" => {},
_ => {
println!("Debiste huir cuando tuviste la ocasión. Te han pillado.");
return Some("game_over".to_string())
}
};
flee(state);
state.reduce_time(30);
let time = state.get_time();
let mins = time / 60;
let secs = time % 60;
println!("Has conseguido despistar al BEHTS.");
println!(" ");
println!("Estás en la esquina {} y te quedan {} minutos {} segundos.",
state.get_string("sabatini_corner".to_string()),
mins,
secs);
state.set_flag("sabatini_flee".to_string(), false);
return None;
}
/// Random direction
fn go_somewhere<S: TypeState>(direction: &str, state: &mut Box<S>) {
let corners = ["A-B", "B-C", "C-D", "D-A"];
let mut current_index = match state.get_string("sabatini_corner".to_string()).as_ref() {
"A-B" => { 0 }
"B-C" => { 1 }
"C-D" => { 2 }
_ => { 3 }
};
match direction {
"l" => {
if current_index == 0 {
// Underflow
current_index = 3;
} else {
current_index = current_index - 1;
}
},
_ => { current_index = (current_index + 1) % 4 },
};
let new_corner = corners[current_index];
println!("Avanzas por el pasillo rezando por que te lleve al lugar que deseas,");
println!("quizá tu memoria o el historial de la consola te esté jugando una mala");
println!("pasada, pero para bien o para mal llegas a la esquina {}.", new_corner);
state.reduce_time(10);
state.set_string("sabatini_corner".to_string(), new_corner.to_string());
}
/// Flee all the way
fn flee<S: TypeState>(state: &mut Box<S>) {
let mut rng = thread_rng();
let corners = match state.get_string("sabatini_corner".to_string()).as_ref() {
"A-B" => { vec!["B-C", "C-D", "D-A"] },
"B-C" => { vec!["A-B", "C-D", "D-A"] },
"C-D" => { vec!["A-B", "B-C", "D-A"] },
_ => { vec!["A-B", "B-C", "C-D"] }
};
let chosen = match rng.choose(&corners) {
Some(c) => { c.to_string() },
None => { "A-B".to_string() }
};
state.set_string("sabatini_corner".to_string(), chosen);
}
/// Random encounters
fn random_encounter<S: TypeState>(state: &mut Box<S>) {
let mut rng = thread_rng();
let perc: i32 = rng.gen_range(0, 100);
if (perc >= 0 && perc < 40) || (perc >= 50 && perc < 90) {
// BEHTS
state.set_flag("sabatini_flee".to_string(), true);
println!("\nAl avanzar te topas con un miembro del BEHTS, te ha visto y va a ir");
println!("a por ti. ¡Deber huir!");
return;
}
// No BEHTS
state.set_flag("sabatini_flee".to_string(), false);
}
impl <S: TypeState> Scenario <S> for Sabatini {
fn load(&self, _: &mut Box<S>) -> Option<String> {
println!("Acabas de entrar en el edifio 2, el Sabatini. Tienes que");
println!("encontrar el despacho del GUL y llevar el discurso de Zoe para el");
println!("programa de radio en directo a tiempo.");
println!(" ");
println!("Un escalofrio recorre tu espalda, sabes que da igual el tiempo que");
println!("lleves en esta universidad, siempre que busques un aula en este");
println!("edificio te vas a perder.");
println!(" ");
println!("Respiras hondo y te preparas para encontrar el despacho, subes las");
println!("esclaras, pues fijate que oportuno, ningún ascensor funciona.");
println!(" ");
println!("Te encuentras en la esquina C-D de la planta 1. Puedes ir al pasillo");
println!("de la derecha, al de la izquierda, subir o bajar las escaleras.");
return None;
}
fn do_action(&self, command: &str, state: &mut Box<S>) -> Option<String> {
if state.get_flag("sabatini_flee".to_string()) {
// Must flee
return must_flee(command, state);
}
match command {
"ir izquierda" | "ir a la izquierda" | "izquierda" => {
go_somewhere("l", state);
},
"ir derecha" | "ir a la derecha" | "derecha" => {
go_somewhere("l", state);
},
"subir" => {
go_up(state);
return None;
},
"bajar" => {
return go_down(state);
},
"despacho" | "ir al despacho" | "ir despacho" | "ir a despacho" => {
if state.get_value("sabatini_floor".to_string()) != 3 {
println!("Aquí no hay ningún despacho");
return None;
}
if state.get_string("sabatini_corner".to_string()) != "B-C" {
// Not correct
println!("Ninguno de los 2 despachos que hay en esta esquina es el del");
println!("GUL, además según te ven empiezan a pegar voces, se ve que los");
println!("del BEHTS les han prometido una bolsa de chuches si les");
println!("avisaban al verte. Deberias huir.");
state.reduce_time(10);
state.set_flag("sabatini_flee".to_string(), true);
}
if state.get_string("deleted".to_string()) == "none" {
// Without speech
println!("Has llegado al despacho del GUL, pero no traes lo que se te");
println!("ha pedido. Al acercarte a la puerta puedes oír a gente");
println!("hablando muy rápido. Parecen estar nerviosos.");
println!(" ");
println!("Decides que no puedes entrar así como así sin el discurso de");
println!("Zoe y te alejas.");
return None;
}
println!("¡Has llegado al despacho del GUL!");
return Some("gul".to_string());
},
_ => {
println!("Solo un poco más...");
return None;
}
};
random_encounter(state);
return None;
}
}
|
/// The representation of data, rows and columns of a [`Grid`].
///
/// [`Grid`]: crate::grid::iterable::Grid
pub trait IntoRecords {
/// A string representation of a [`Grid`] cell.
///
/// [`Grid`]: crate::grid::iterable::Grid
type Cell: AsRef<str>;
/// Cell iterator inside a row.
type IterColumns: IntoIterator<Item = Self::Cell>;
/// Rows iterator.
type IterRows: IntoIterator<Item = Self::IterColumns>;
/// Returns an iterator over rows.
fn iter_rows(self) -> Self::IterRows;
}
impl<T> IntoRecords for T
where
T: IntoIterator,
<T as IntoIterator>::Item: IntoIterator,
<<T as IntoIterator>::Item as IntoIterator>::Item: AsRef<str>,
{
type Cell = <<T as IntoIterator>::Item as IntoIterator>::Item;
type IterColumns = <T as IntoIterator>::Item;
type IterRows = <T as IntoIterator>::IntoIter;
fn iter_rows(self) -> Self::IterRows {
self.into_iter()
}
}
|
use proconio::{fastout, input};
struct UnionFind {
set: Vec<i64>,
}
impl UnionFind {
fn new(n: usize) -> Self {
let set: Vec<i64> = vec![-1; n];
Self { set }
}
fn root(&mut self, i: usize) -> usize {
if self.set[i] < 0 {
i
} else {
self.set[i] = self.root(self.set[i] as usize) as i64;
self.set[i] as usize
}
}
fn unite(&mut self, x: usize, y: usize) -> bool {
let mut x_root = self.root(x);
let mut y_root = self.root(y);
if x_root == y_root {
false
} else {
if self.set[x_root] > self.set[y_root] {
std::mem::swap(&mut x_root, &mut y_root);
}
self.set[x_root] += self.set[y_root];
self.set[y_root] = x_root as i64;
true
}
}
fn size(&mut self, i: usize) -> usize {
let par = self.root(i);
(self.set[par] * -1) as usize
}
}
#[fastout]
fn main() {
input! {
n: usize,
m: usize,
a_b_vec: [(usize, usize); m],
};
let a_b_vec: Vec<(usize, usize)> = a_b_vec.iter().map(|(a, b)| (a - 1, b - 1)).collect();
let mut set: UnionFind = UnionFind::new(n);
for a_b in a_b_vec.iter() {
set.unite(a_b.0, a_b.1);
}
let mut ans = 0;
for i in 0..n {
ans = ans.max(set.size(i));
}
println!("{}", ans);
}
|
extern crate bear_vm;
mod cli;
use bear_ass::Error;
const USAGE: &str = "bear-ass v1.0\n\
\n\
USAGE: bear-ass in out\n";
fn main() {
match cli::go() {
Ok(()) => {
std::process::exit(0);
}
Err(Error::Usage) => eprintln!("{}", USAGE),
Err(error) => eprintln!("{:?}", error),
};
std::process::exit(-2)
}
#[cfg(test)]
mod test {
use bear_ass::{assembler, parser, processor, Error};
use bear_vm::vm::{BearVM, ExecutionState};
fn print_state(state: &ExecutionState) {
eprintln!(
"ii: {}, cw: {}, lw: {}\ndata: {:?}",
state.instruction_index,
state.current_word_index,
state.loaded_word_index,
state.vm.data
);
}
fn run(program: &str) -> Result<ExecutionState, Error> {
// let mut image = Vec::new();
// let mut program = program.as_bytes();
let program = parser::Parser {}
.parse(&program)
.map_err(|e| Error::ParserError(e))?;
let processor = processor::Processor::process(program).expect("Processor error.");
let image = assembler::Assembler::assemble(processor).expect("Assembler error.");
let vm = BearVM::new(bear_vm::util::convert_slice8_to_vec32(&image));
let mut state = vm.start().map_err(|e| Error::Unknown(format!("{:?}", e)))?;
state
.run()
.map_err(|e| Error::Unknown(format!("{:?}", e)))?;
print_state(&state);
return Ok(state);
}
#[test]
fn test_sext8_neg() -> Result<(), Error> {
let state = run("
lit sext.8 halt
===
d8 -3
")?;
assert!(state.instruction_index == 2);
assert!(state.vm.data == vec![(-3).into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_sext8_pos() -> Result<(), Error> {
let state = run("
lit sext.8 halt
===
d32 1
")?;
assert!(state.instruction_index == 2);
assert!(state.vm.data == vec![1.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_sext16_neg() -> Result<(), Error> {
let state = run("
lit sext.16 halt
===
d32 (2^16)-2
")?;
assert!(state.instruction_index == 2);
assert!(state.vm.data == vec![(-2).into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_sext16_pos() -> Result<(), Error> {
let state = run("
lit sext.16 halt
===
d32 257
")?;
assert!(state.instruction_index == 2);
assert!(state.vm.data == vec![257.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_add_pos_pos() -> Result<(), Error> {
let state = run("
lit lit add halt
d32 7
d32 2
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![9.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_add_pos_neg() -> Result<(), Error> {
let state = run("
lit lit sext.8 add
d32 7
d8 -2
===
halt
")?;
assert!(state.instruction_index == 0);
assert!(state.loaded_word_index == 3);
assert!(state.current_word_index == 3);
assert!(state.vm.data == vec![5.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_add_neg_pos() -> Result<(), Error> {
let state = run("
lit lit add halt
d32 -7
d32 2
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![(-5).into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_add_neg_neg() -> Result<(), Error> {
let state = run("
lit lit add halt
d32 -7
d32 -2
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![(-9).into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_sub_pos_pos_pos() -> Result<(), Error> {
let state = run("
lit lit sub halt
d32 2
d32 7
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![5.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_sub_pos_pos_neg() -> Result<(), Error> {
let state = run("
lit lit sub halt
d32 7
d32 2
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![(-5).into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_mul_pos_pos() -> Result<(), Error> {
let state = run("
lit lit mul halt
d32 7
d32 2
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![14.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_mul_pos_neg() -> Result<(), Error> {
let state = run("
lit lit mul halt
d32 7
d32 -2
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![(-14).into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_mul_neg_pos() -> Result<(), Error> {
let state = run("
lit sext.8 lit mul
d8 -7
===
d32 2
halt
")?;
assert!(state.instruction_index == 0);
assert!(state.loaded_word_index == 3);
assert!(state.current_word_index == 3);
assert!(state.vm.data == vec![(-14).into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_mul_neg_neg() -> Result<(), Error> {
let state = run("
lit lit mul halt
d32 -2
d32 -7
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == vec![14.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_store() -> Result<(), Error> {
let state = run("
lit lit store halt
d32 $>
d32 1000
$ d32 0
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == Vec::new());
assert!(state.vm.address.len() == 0);
assert!(state.vm.image[state.vm.image.len() - 1] == 1000);
return Ok(());
}
#[test]
fn test_store_8() -> Result<(), Error> {
let state = run("
lit lit store.8 halt
d32 $>
d32 7
$ d32 0
")?;
assert!(state.instruction_index == 3);
assert!(state.vm.data == Vec::new());
assert!(state.vm.address.len() == 0);
assert!(state.vm.image[state.vm.image.len() - 1] == 7);
return Ok(());
}
#[test]
fn test_jump() -> Result<(), Error> {
let state = run("
lit jump halt nop
d32 $>
halt halt halt halt
$
lit halt nop nop
d32 7
")?;
assert!(state.instruction_index == 1);
assert!(state.loaded_word_index == 3);
assert!(state.current_word_index == 4);
assert!(state.vm.data == vec![7.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_jump_ifz_true() -> Result<(), Error> {
let state = run("
lit lit ifz:jump halt
d32 0
d32 $>
halt halt halt halt
$ lit halt nop nop
d32 7
")?;
assert!(state.instruction_index == 1);
assert!(state.loaded_word_index == 4);
assert!(state.current_word_index == 5);
assert!(state.vm.data == vec![7.into()]);
assert!(state.vm.address.len() == 0);
return Ok(());
}
#[test]
fn test_jump_ifz_false() -> Result<(), Error> {
let state = run("
lit lit ifz:jump halt
d32 $>
d32 1
halt halt halt halt
$
lit halt nop nop
d32 7
")?;
assert!(state.instruction_index == 3);
assert!(state.loaded_word_index == 0);
assert!(state.current_word_index == 2);
assert!(state.vm.data.len() == 0);
assert!(state.vm.address.len() == 0);
return Ok(());
}
}
|
use crate::events::{queue_event, Event};
use crate::timer::ToTimerID;
use crate::{
gpio::{GpioID, ToGpio},
timer::{Hertz, Timer},
};
use embedded_hal::timer::{Cancel, CountDown};
use stm32f1xx_hal::pac::{TIM1, TIM2, TIM3};
use stm32f1xx_hal::timer::CountDownTimer;
use stm32f1xx_hal::{device::interrupt, gpio};
pub type GpioOutError = core::convert::Infallible;
pub type GpioInError = core::convert::Infallible;
pub type TimerError = stm32f1xx_hal::timer::Error;
pub type Time = stm32f1xx_hal::time::Hertz;
pub(super) fn enable_interrupts() {
unsafe { cortex_m::interrupt::enable() };
}
pub(super) fn disable_interrupts() {
cortex_m::interrupt::disable();
}
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum TimerID {
Tim1,
Tim2,
Tim3,
}
impl From<Hertz> for stm32f1xx_hal::time::Hertz {
fn from(source: Hertz) -> Self {
Self(source.0)
}
}
macro_rules! implement_timer {
($timer:ty, $interrupt:ident, $id:expr) => {
impl Timer for CountDownTimer<$timer>
where
CountDownTimer<$timer>: ToTimerID,
{
#[inline]
fn start(&mut self, interval: Hertz) {
CountDown::start::<Hertz>(self, interval)
}
#[inline]
fn cancel(&mut self) -> Result<(), TimerError> {
Cancel::cancel(self)
}
#[inline]
fn wait(&mut self) -> Result<(), ()> {
CountDown::wait(self).map_err(|_| ())
}
}
impl ToTimerID for CountDownTimer<$timer> {
#[inline]
fn to_timer_id(&self) -> TimerID {
$id
}
}
#[interrupt]
fn $interrupt() {
queue_event(Event::TimerEvent($id));
}
};
}
implement_timer!(TIM1, TIM1_UP, TimerID::Tim1);
implement_timer!(TIM2, TIM2, TimerID::Tim2);
implement_timer!(TIM3, TIM3, TimerID::Tim3);
#[derive(PartialEq, Eq, Clone, Copy, Debug, PartialOrd, Ord, Hash)]
pub enum Port {
A,
B,
C,
D,
E,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, PartialOrd, Ord, Hash)]
pub enum Pin {
P00,
P01,
P02,
P03,
P04,
P05,
P06,
P07,
P08,
P09,
P10,
P11,
P12,
P13,
P14,
P15,
}
// implements conversion from a hal pin into a Gpio e.g. from stm32f1xx_hal::gpio::gpioa::PA<T>
macro_rules! implement_to_gpio {
($port:expr, $pin:expr, $hal_port:tt::$hal_pin:tt) => {
impl<T> crate::gpio::InputPin for gpio::$hal_port::$hal_pin<gpio::Input<T>> {}
impl<T> crate::gpio::OutputPin for gpio::$hal_port::$hal_pin<gpio::Output<T>> {}
impl<T> ToGpio for gpio::$hal_port::$hal_pin<T> {
#[inline]
fn to_gpio(&self) -> GpioID {
GpioID {
port: $port,
pin: $pin,
}
}
}
};
}
implement_to_gpio!(Port::A, Pin::P00, gpioa::PA0);
implement_to_gpio!(Port::A, Pin::P01, gpioa::PA1);
implement_to_gpio!(Port::A, Pin::P02, gpioa::PA2);
implement_to_gpio!(Port::A, Pin::P03, gpioa::PA3);
implement_to_gpio!(Port::A, Pin::P04, gpioa::PA4);
implement_to_gpio!(Port::A, Pin::P05, gpioa::PA5);
implement_to_gpio!(Port::A, Pin::P06, gpioa::PA6);
implement_to_gpio!(Port::A, Pin::P07, gpioa::PA7);
implement_to_gpio!(Port::A, Pin::P08, gpioa::PA8);
implement_to_gpio!(Port::A, Pin::P09, gpioa::PA9);
implement_to_gpio!(Port::A, Pin::P10, gpioa::PA10);
implement_to_gpio!(Port::A, Pin::P11, gpioa::PA11);
implement_to_gpio!(Port::A, Pin::P12, gpioa::PA12);
implement_to_gpio!(Port::A, Pin::P13, gpioa::PA13);
implement_to_gpio!(Port::A, Pin::P14, gpioa::PA14);
implement_to_gpio!(Port::A, Pin::P15, gpioa::PA15);
implement_to_gpio!(Port::B, Pin::P00, gpiob::PB0);
implement_to_gpio!(Port::B, Pin::P01, gpiob::PB1);
implement_to_gpio!(Port::B, Pin::P02, gpiob::PB2);
implement_to_gpio!(Port::B, Pin::P03, gpiob::PB3);
implement_to_gpio!(Port::B, Pin::P04, gpiob::PB4);
implement_to_gpio!(Port::B, Pin::P05, gpiob::PB5);
implement_to_gpio!(Port::B, Pin::P06, gpiob::PB6);
implement_to_gpio!(Port::B, Pin::P07, gpiob::PB7);
implement_to_gpio!(Port::B, Pin::P08, gpiob::PB8);
implement_to_gpio!(Port::B, Pin::P09, gpiob::PB9);
implement_to_gpio!(Port::B, Pin::P10, gpiob::PB10);
implement_to_gpio!(Port::B, Pin::P11, gpiob::PB11);
implement_to_gpio!(Port::B, Pin::P12, gpiob::PB12);
implement_to_gpio!(Port::B, Pin::P13, gpiob::PB13);
implement_to_gpio!(Port::B, Pin::P14, gpiob::PB14);
implement_to_gpio!(Port::B, Pin::P15, gpiob::PB15);
implement_to_gpio!(Port::C, Pin::P00, gpioc::PC0);
implement_to_gpio!(Port::C, Pin::P01, gpioc::PC1);
implement_to_gpio!(Port::C, Pin::P02, gpioc::PC2);
implement_to_gpio!(Port::C, Pin::P03, gpioc::PC3);
implement_to_gpio!(Port::C, Pin::P04, gpioc::PC4);
implement_to_gpio!(Port::C, Pin::P05, gpioc::PC5);
implement_to_gpio!(Port::C, Pin::P06, gpioc::PC6);
implement_to_gpio!(Port::C, Pin::P07, gpioc::PC7);
implement_to_gpio!(Port::C, Pin::P08, gpioc::PC8);
implement_to_gpio!(Port::C, Pin::P09, gpioc::PC9);
implement_to_gpio!(Port::C, Pin::P10, gpioc::PC10);
implement_to_gpio!(Port::C, Pin::P11, gpioc::PC11);
implement_to_gpio!(Port::C, Pin::P12, gpioc::PC12);
implement_to_gpio!(Port::C, Pin::P13, gpioc::PC13);
implement_to_gpio!(Port::C, Pin::P14, gpioc::PC14);
implement_to_gpio!(Port::C, Pin::P15, gpioc::PC15);
implement_to_gpio!(Port::D, Pin::P00, gpiod::PD0);
implement_to_gpio!(Port::D, Pin::P01, gpiod::PD1);
implement_to_gpio!(Port::D, Pin::P02, gpiod::PD2);
implement_to_gpio!(Port::D, Pin::P03, gpiod::PD3);
implement_to_gpio!(Port::D, Pin::P04, gpiod::PD4);
implement_to_gpio!(Port::D, Pin::P05, gpiod::PD5);
implement_to_gpio!(Port::D, Pin::P06, gpiod::PD6);
implement_to_gpio!(Port::D, Pin::P07, gpiod::PD7);
implement_to_gpio!(Port::D, Pin::P08, gpiod::PD8);
implement_to_gpio!(Port::D, Pin::P09, gpiod::PD9);
implement_to_gpio!(Port::D, Pin::P10, gpiod::PD10);
implement_to_gpio!(Port::D, Pin::P11, gpiod::PD11);
implement_to_gpio!(Port::D, Pin::P12, gpiod::PD12);
implement_to_gpio!(Port::D, Pin::P13, gpiod::PD13);
implement_to_gpio!(Port::D, Pin::P14, gpiod::PD14);
implement_to_gpio!(Port::D, Pin::P15, gpiod::PD15);
implement_to_gpio!(Port::E, Pin::P00, gpioe::PE0);
implement_to_gpio!(Port::E, Pin::P01, gpioe::PE1);
implement_to_gpio!(Port::E, Pin::P02, gpioe::PE2);
implement_to_gpio!(Port::E, Pin::P03, gpioe::PE3);
implement_to_gpio!(Port::E, Pin::P04, gpioe::PE4);
implement_to_gpio!(Port::E, Pin::P05, gpioe::PE5);
implement_to_gpio!(Port::E, Pin::P06, gpioe::PE6);
implement_to_gpio!(Port::E, Pin::P07, gpioe::PE7);
implement_to_gpio!(Port::E, Pin::P08, gpioe::PE8);
implement_to_gpio!(Port::E, Pin::P09, gpioe::PE9);
implement_to_gpio!(Port::E, Pin::P10, gpioe::PE10);
implement_to_gpio!(Port::E, Pin::P11, gpioe::PE11);
implement_to_gpio!(Port::E, Pin::P12, gpioe::PE12);
implement_to_gpio!(Port::E, Pin::P13, gpioe::PE13);
implement_to_gpio!(Port::E, Pin::P14, gpioe::PE14);
implement_to_gpio!(Port::E, Pin::P15, gpioe::PE15);
|
use std::fs::File;
use std::io::{Read, Write};
pub struct Form<'a> {
pub boundary: &'a str,
data: Vec<u8>,
}
impl<'a> Form<'a> {
pub fn new() -> Self {
Form {
boundary: "-------------573cf973d5228",
data: vec![],
}
}
pub fn add_text(&mut self, name: &str, text: &str) {
write!(&mut self.data, "--{}\r\n", self.boundary).unwrap();
write!(
&mut self.data,
"Content-Disposition: form-data; name=\"{}\"\r\n",
name
)
.unwrap();
write!(&mut self.data, "Content-Type: text/plain\r\n").unwrap();
write!(&mut self.data, "\r\n").unwrap();
write!(&mut self.data, "{}\r\n", text).unwrap();
}
pub fn add_file(&mut self, name: &str, cont_type: &str, filepath: &str) {
write!(&mut self.data, "--{}\r\n", self.boundary).unwrap();
write!(
&mut self.data,
"Content-Disposition: form-data; name=\"{}\" filename=\"{}\"\r\n",
name, filepath
)
.unwrap();
write!(&mut self.data, "Content-Type: {}\r\n", cont_type).unwrap();
write!(&mut self.data, "\r\n").unwrap();
let mut file = File::open(filepath).unwrap();
file.read_to_end(&mut self.data).unwrap();
write!(&mut self.data, "\r\n").unwrap();
}
pub fn get(mut self) -> Vec<u8> {
write!(&mut self.data, "--{}--\r\n", self.boundary).unwrap();
self.data
}
}
|
#![allow(unused_variables)]
#![allow(dead_code)]
fn main() {
match_intro();
match_nested_func_call();
match_with_option();
match_with_option_omit();
match_udline_placeholder();
}
fn match_intro() {
enum ZhCurrency {
YiYuan,
ShiYuan,
WuShiYuan,
YiBaiYuan,
}
fn curr_in_num(currency: ZhCurrency) -> u32 {
/*
A much better `if`
if => boolean only
match => any type (ala it's an expr)
My understanding is that it is
kinda an advanced `switch` with `break` (byDef)
*/
/*
Do keep in mind
it's just a GODDAMN simple `if`!
match ARG { // val passed in
X -> Y // if ARG == X, exec Y ( {Y} == Y )
} // Y required a val being returned
*/
match currency {
ZhCurrency::YiYuan => 1,
ZhCurrency::ShiYuan => 10,
ZhCurrency::WuShiYuan => 50,
ZhCurrency::YiBaiYuan => {
println!("Ah, you lucky dog!");
100
}
}
}
println!("{}", curr_in_num(ZhCurrency::YiBaiYuan))
}
fn match_nested_func_call() {
#[derive(Debug)]
enum UsState {
NewYork,
California,
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
// In my perspective,
// it's just a nested func call :P
fn val_in_cents(coin: Coin) -> u32 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quatr from {:?}.", state);
25
}
}
}
val_in_cents(Coin::Quarter(UsState::NewYork));
}
fn match_with_option() {
/*
If I'd use this, the reasons could be
the arg might be `None` (either none, or else)
*/
fn plus_one(arg: Option<i32>) -> Option<i32> {
/*
It's just "regular func, regular match" (sort-of)
The param being passed in must be `Option<TYPE>`.
Yet the match only got two cases
| None -> `None` (literally)
| Some -> anything but `None`
You can add multiple lines of code,
=> just like before (i.e. `{ CODE; RET_VAL }`)
*/
match arg {
None => None,
Some(i) => {
println!("Just testin the 'i'!");
Some(i + 1)
}
}
}
let four = Some(5);
let five = plus_one(four);
let none = plus_one(None);
// It's an enum (`Option`),
// so apparently you need to add ':?' for printing
println!("{:?}, {:?}, {:?}", four, five, none);
}
fn match_with_option_omit() {
fn helper(arg: Option<i32>) -> Option<i32> {
/*
Either of them MUST NOT be omitted :P
cuz it's `Option` type (which the impl requires)
*/
match arg {
None => None,
Some(i) => Some(i + 2),
}
}
}
fn match_udline_placeholder() {
let valid_wkday = 5;
// Exec started from here :P
match valid_wkday {
1 => println!("yep"),
2 => println!("yep"),
3 => println!("yep"),
4 => println!("yep"),
5 => println!("yep"),
6 => println!("yep"),
7 => println!("yep"),
_ => println!("Not valid"),
}
}
|
use crate::error::{InternalError, ValueError};
use crate::parse::BinOpKind;
use crate::scope::*;
use crate::value::*;
use crate::EvalError;
use gc::{Finalize, Gc, GcCell, Trace};
use rnix::TextRange;
use std::borrow::Borrow;
use std::collections::HashMap;
// Expressions like BinOp have the only copy of their Expr children,
// so they use ExprResultBox. Expressions like Map, which may have
// contents copied in multiple places, need ExprResultGc.
type ExprResultBox = Result<Box<Expr>, EvalError>;
type ExprResultGc = Result<Gc<Expr>, EvalError>;
/// Used to lazily calculate the value of a Expr. This should be
/// tolerant of parsing and evaluation errors from child Exprs.
///
/// We store everything that we want the user to inspect. For example,
/// the source for an attribute key-value pair includes the key so the
/// user can hover inside dynamic keys in code like
/// `{ "${toString (1+1)}" = 2; }`.
#[derive(Debug, Trace, Finalize)]
pub enum ExprSource {
// We want to share child MapAttrs between the ExprSource
// and the value map, so we use Gc.
AttrSet {
/// We use a list because the user might define the same top-level
/// attribute in multiple places via path syntax. For example:
/// ```nix
/// {
/// xyz.foo = true;
/// xyz.bar = false;
/// }
/// ```
definitions: Vec<ExprResultGc>,
},
/// See the AttrSet handling in Expr::parse for more details.
/// Note that this syntax is the exact opposite of Expr::Select.
KeyValuePair {
key: ExprResultGc,
value: ExprResultGc,
},
/// Selection of an attribute from an AttrSet. This is used for
/// multiple syntaxes, such as `inherit (xyz) foo` and `xyz.foo`.
Select {
/// We use Gc here because we need to share `from` across multiple
/// Expr nodes for syntax like `inherit (xyz) foo bar`
from: ExprResultGc,
index: ExprResultBox,
},
/// Dynamic attribute, such as the curly braces in `foo.${toString (1+1)}`
Dynamic {
inner: ExprResultBox,
},
Ident {
name: String,
},
Literal {
value: NixValue,
},
Paren {
inner: ExprResultBox,
},
BinOp {
op: BinOpKind,
left: ExprResultBox,
right: ExprResultBox,
},
BoolAnd {
left: ExprResultBox,
right: ExprResultBox,
},
BoolOr {
left: ExprResultBox,
right: ExprResultBox,
},
Implication {
left: ExprResultBox,
right: ExprResultBox,
},
UnaryInvert {
value: ExprResultBox,
},
UnaryNegate {
value: ExprResultBox,
},
}
/// Syntax node that has context and can be lazily evaluated.
#[derive(Trace, Finalize)]
pub struct Expr {
#[unsafe_ignore_trace]
pub range: Option<TextRange>,
pub value: GcCell<Option<Gc<NixValue>>>,
pub source: ExprSource,
pub scope: Gc<Scope>,
}
impl std::fmt::Debug for Expr {
// The scope can be recursive, so we don't want to print it by default
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Expr")
.field("value", &self.value)
.field("source", &self.source)
.field("range", &self.range)
.finish()
}
}
impl Expr {
/// Lazily evaluate a Expr, caching its value
pub fn eval(&self) -> Result<Gc<NixValue>, EvalError> {
let mut value_borrow = match self.value.try_borrow_mut() {
Ok(x) => x,
Err(_) => {
// We already borrow ourselves as mutable, so we called .eval() on ourself
// from an .eval(), which is probably infinite recursion.
return Err(EvalError::Internal(InternalError::Unimplemented(
"infinite recursion".to_string(),
)))
}
};
if let Some(ref value) = *value_borrow {
Ok(value.clone())
} else {
// We can later build a stack trace by wrapping errors here
let value = self.eval_uncached()?;
*value_borrow = Some(value.clone());
Ok(value)
}
}
fn eval_uncached(&self) -> Result<Gc<NixValue>, EvalError> {
match &self.source {
ExprSource::Paren { inner } => inner.as_ref()?.eval(),
ExprSource::Literal { value } => Ok(Gc::new(value.clone())),
ExprSource::BoolAnd { left, right } => {
if left.as_ref()?.eval()?.as_bool()? {
right.as_ref()?.eval()
} else {
Ok(Gc::new(NixValue::Bool(false)))
}
}
ExprSource::BoolOr { left, right } => {
if !left.as_ref()?.eval()?.as_bool()? {
right.as_ref()?.eval()
} else {
Ok(Gc::new(NixValue::Bool(true)))
}
}
ExprSource::Implication { left, right } => {
if !left.as_ref()?.eval()?.as_bool()? {
Ok(Gc::new(NixValue::Bool(true)))
} else {
right.as_ref()?.eval()
}
}
#[allow(clippy::enum_glob_use)]
#[allow(clippy::float_cmp)]
// We want to match the Nix reference implementation
ExprSource::BinOp { op, left, right } => {
use BinOpKind::*;
use NixValue::*;
// Workaround for "temporary value dropped while borrowed"
// https://doc.rust-lang.org/error-index.html#E0716
let left_tmp = left.as_ref()?.eval()?;
let left_val = left_tmp.borrow();
let right_tmp = right.as_ref()?.eval()?;
let right_val = right_tmp.borrow();
// Specially handle integer division by zero
if let (Div, Integer(_), Integer(0)) = (op, left_val, right_val) {
return Err(EvalError::Value(ValueError::DivisionByZero));
}
macro_rules! match_binops {
( arithmetic [ $( $arith_kind:pat => $arith_oper:tt, )+ ],
comparisons [ $( $comp_kind:pat => $comp_oper:tt, )+ ],
$( $pattern:pat => $expr:expr ),* ) => {
match (op, left_val, right_val) {
$(
($arith_kind, Integer(x), Integer(y)) => Integer(x $arith_oper y),
($arith_kind, Float(x), Float(y)) => Float(x $arith_oper y),
($arith_kind, Integer(x), Float(y)) => Float((*x as f64) $arith_oper y),
($arith_kind, Float(x), Integer(y)) => Float(x $arith_oper (*y as f64)),
)*
$(
($comp_kind, Integer(x), Integer(y)) => Bool(x $comp_oper y),
($comp_kind, Float(x), Float(y)) => Bool(x $comp_oper y),
($comp_kind, Integer(x), Float(y)) => Bool((*x as f64) $comp_oper *y),
($comp_kind, Float(x), Integer(y)) => Bool(*x $comp_oper (*y as f64)),
)*
$(
$pattern => $expr,
)*
}
};
}
let out = match_binops! {
arithmetic [
Add => +, Sub => -, Mul => *, Div => /,
],
comparisons [
Equal => ==, NotEqual => !=,
Greater => >, GreaterOrEq => >=,
Less => <, LessOrEq => <=,
],
_ => {
// We assume that it's our fault if an operation is unsupported.
// Over time, we can rewrite common cases into type errors.
return Err(EvalError::Internal(InternalError::Unimplemented(format!(
"{:?} {:?} {:?} unsupported",
left, op, right
))))
}
};
Ok(Gc::new(out))
}
ExprSource::UnaryInvert { value } => {
Ok(Gc::new(NixValue::Bool(!value.as_ref()?.eval()?.as_bool()?)))
}
ExprSource::UnaryNegate { value } => {
Ok(Gc::new(match value.as_ref()?.eval()?.borrow() {
NixValue::Integer(x) => NixValue::Integer(-x),
NixValue::Float(x) => NixValue::Float(-x),
_ => {
return Err(EvalError::Value(ValueError::TypeError(
"cannot negate a non-number".to_string(),
)))
}
}))
}
ExprSource::AttrSet { .. } => Err(EvalError::Internal(InternalError::Unexpected(
"eval_uncached ExprSource::Map should be unreachable, ".to_string()
+ "since the Expr::value should be initialized at creation",
))),
ExprSource::KeyValuePair { value, .. } => value.as_ref()?.eval(),
ExprSource::Dynamic { inner } => inner.as_ref()?.eval(),
ExprSource::Ident { name } => self
.scope
.get(name)
// We don't have everything implemented yet, so silently fail,
// assuming we're at fault
.ok_or(EvalError::Internal(InternalError::Unimplemented(format!(
"not found in scope: {}",
name
))))?
.eval(),
ExprSource::Select { from, index } => {
let key = index.as_ref()?.as_ident()?;
let tmp = from.as_ref()?.eval()?;
let map = tmp.as_map()?;
let val = match map.get(&key) {
Some(x) => x,
None => {
// We don't have everything implemented yet, so silently fail,
// assuming we're at fault
return Err(EvalError::Internal(InternalError::Unimplemented(format!(
"missing key: {}",
key
))));
}
};
val.eval()
}
}
}
/// Used for recursing to find the Expr at a cursor position.
/// Note that if children have overlapping `range`s, then the
/// first matching child will be used for tooling.
pub fn children(&self) -> Vec<&Expr> {
match &self.source {
ExprSource::Paren { inner } => vec![inner],
ExprSource::Literal { value: _ } => vec![],
ExprSource::BinOp { op: _, left, right } => vec![left, right],
ExprSource::BoolAnd { left, right } => vec![left, right],
ExprSource::BoolOr { left, right } => vec![left, right],
ExprSource::Implication { left, right } => vec![left, right],
ExprSource::UnaryInvert { value } => vec![value],
ExprSource::UnaryNegate { value } => vec![value],
ExprSource::AttrSet {
definitions,
} => {
let mut out = vec![];
out.extend(definitions);
// This looks similar to code at the end of the function, but
// we have Gc instead of Box, so we can't just return a vec
// like the rest of the `match` arms.
return out
.into_iter()
.map(|x| x.as_ref())
.filter_map(Result::ok)
.map(|x| x.as_ref())
.collect();
}
ExprSource::KeyValuePair { key, value } => {
let mut out = vec![];
if let Ok(x) = value {
out.push(x.as_ref());
}
if let Ok(x) = key {
if let ExprSource::Dynamic { inner: Ok(val) } = &x.source {
out.push(val.as_ref());
}
}
return out;
}
ExprSource::Dynamic { inner } => vec![inner],
ExprSource::Ident { .. } => vec![],
ExprSource::Select { from, index } => {
let mut out = vec![];
// For { .. }.x, we want hovering `x` to show the value.
// However, we still want syntax like { .. }."${toString (1+1)}"
// to allow interaction with the dynamic expression.
if let Ok(x) = index {
if let ExprSource::Dynamic { inner: Ok(val) } = &x.source {
out.push(val.as_ref());
}
}
if let Ok(x) = from {
out.push(x.as_ref());
}
return out;
}
}
.into_iter()
.map(|x| x.as_ref())
.filter_map(Result::ok)
.map(|x| x.as_ref())
.collect()
}
pub fn get_definition(&self) -> Option<Gc<Expr>> {
use ExprSource::*;
match &self.source {
Ident { name } => self.scope.get(&name),
Select { from, index } => {
let idx = index.as_ref().ok()?.as_ident().ok()?;
let out = from
.as_ref()
.ok()?
.eval()
.ok()?
.as_map()
.ok()?
.get(&idx)?
.clone();
if let ExprSource::KeyValuePair { ref key, .. } = out.source {
key.clone().ok()
} else {
Some(out)
}
}
_ => None,
}
}
/// Interpret the expression as an identifier. For example:
/// ```text
/// foo => "foo"
/// "foo" => "foo"
/// "${"foo"}" => "foo"
/// ```
pub fn as_ident(&self) -> Result<String, EvalError> {
use ExprSource::*;
match &self.source {
Ident { name } => Ok(name.clone()),
Dynamic { inner } => inner.as_ref()?.eval()?.as_str(),
Literal { value } => value.as_str(),
_ => Err(EvalError::Internal(InternalError::Unimplemented(
"unsupported identifier expression".to_string(),
))),
}
}
}
/// Used for merging sets during parsing. For example:
/// { a.b = 1; a.c = 2; } => { a = { b = 1; c = 2; }; }
///
/// Nix only allows merging several such KeyValuePairs when they correspond
/// to bare literals. Inserting a mere indirection through let or a function
/// prevents this from happening and throws an error instead:
/// ```text
/// nix-repl> :p { a = { b = 1; }; a.c = 2; }
/// { a = { b = 1; c = 2; }; }
///
/// nix-repl> :p { a = (x: x){ b = 1; }; a.c = 2; }
/// error: attribute 'a.c' already defined at (string):1:3
///
/// at «string»:1:25:
///
/// 1| { a = (x: x){ b = 1; }; a.c = 2; }
/// | ^
///
/// nix-repl> :p let y = { b = 1; }; in { a = y; a.c = 2; }
/// error: attribute 'a.c' already defined at (string):1:26
///
/// at «string»:1:33:
///
/// 1| let y = { b = 1; }; in { a = y; a.c = 2; }
/// | ^
///
/// ```
/// This function takes a and b, attempts to interpret them as literal
/// key value pairs or literal attrset values, and if it failed returns
/// such an error.
pub fn merge_set_literal(name: String, a: Gc<Expr>, b: Gc<Expr>) -> Result<Gc<Expr>, EvalError> {
// evaluate literal attr sets only, otherwise error
let eval_literal = |src: Gc<Expr>| {
let src = if let ExprSource::KeyValuePair { value, .. } = &src.source {
value.as_ref()?.clone()
} else {
src
};
match &src.source {
ExprSource::AttrSet { .. } => src.eval()?.as_map(),
ExprSource::Literal {
value: NixValue::Map(m),
..
} => Ok(m.clone()),
_ => {
// We cannot merge a literal with a non-literal. This error is
// caused by incorrect expressions such as:
// ```
// repl> let x = { y = 1; }; in { a = x; a.z = 2; }
// error: attribute 'a.z' at (string):1:33 already defined at (string):1:26
// ```
// The above would be caught because `x` is an ExprSource::Ident (as
// opposed to being an ExprSource::AttrSet literal).
Err(EvalError::Value(ValueError::AttrAlreadyDefined(
name.to_string(),
)))
}
}
};
let a = eval_literal(a)?;
let b = eval_literal(b)?;
let mut out = HashMap::new();
for (key, val) in a.iter() {
let tmp = match b.get(key) {
Some(x) => merge_set_literal(format!("{}.{}", name, key), x.clone(), val.clone())?,
None => val.clone(),
};
out.insert(key.clone(), tmp);
}
for (key, val) in b.iter() {
if !a.contains_key(key) {
out.insert(key.clone(), val.clone());
}
}
Ok(Gc::new(Expr {
range: None,
value: GcCell::new(None),
source: ExprSource::Literal {
value: NixValue::Map(out),
},
scope: Gc::new(Scope::None),
}))
}
|
use core::position::{Size, HasSize};
use core::cellbuffer::CellAccessor;
use ui::core::attributes::{HorizontalAlign, VerticalAlign};
use ui::core::frame::Frame;
/// Widgets are the foundation of UI, all frontend objects inherit the widget
/// type and are generalized through either the widget itself or a specialized
/// widget (e.g. *Button*, *Layout*).
pub trait Widget {
/// Draws the widget to the valid `CellAccessor` passed
fn draw(&mut self, parent: &mut CellAccessor);
/// Aligns the widget with the `parent` as reference
fn pack(&mut self, parent: &HasSize, halign: HorizontalAlign, valign: VerticalAlign,
margin: (usize, usize));
/// Expose the painter trait `draw_box` for all widgets, which outlines
/// the space enclosed within the widget
fn draw_box(&mut self);
/// Resize the given widget to new dimensions given by `Size`
fn resize(&mut self, new_size: Size);
/// Return a reference the renderer, `Base` in general cases
fn frame(&self) -> &Frame;
/// Return a mutable reference to the renderer, `Base` in general cases
fn frame_mut(&mut self) -> &mut Frame;
}
|
use std::fs::File;
use std::io::prelude::*;
use openssl::symm::{encrypt, decrypt, Cipher};
use rand::prelude::*;
use base64::{encode, decode};
pub fn criptografar(s: &str, chave: &[u8; 32]) -> String {
let cifra = Cipher::aes_256_ecb();
String::from_utf8_lossy(encode(&encrypt(
cifra,
chave,
None,
s.as_bytes()).unwrap()).as_bytes()).to_string()
}
pub fn des_criptografar(s: &str, chave: &[u8; 32]) -> String {
let cifra = Cipher::aes_256_ecb();
String::from_utf8_lossy(&decrypt(
cifra,
chave,
None,
&decode(s).unwrap()).unwrap()).to_string()
}
pub fn recuperar_credenciais() -> [u8; 32] {
let mut chave = [0 as u8; 32];
let mut kf = File::open("./testes/credenciais/chave.aes").unwrap();
kf.read_exact(&mut chave).unwrap();
chave
}
pub fn gerar_credendiais() -> Result<(), std::io::Error> {
let mut rng = rand::thread_rng();
let mut chave = [0 as u8; 32];
rng.fill_bytes(&mut chave);
let mut kf = File::create("./testes/credenciais/chave.aes")?;
kf.write_all(&chave)?;
Ok(())
}
|
fn main() {
println!("bkpr");
}
|
use clap::{App, Arg};
use temperature_converter::temperature_conversion::{
print_common_table, print_temperature_conversion, Temperature,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = App::new("Temperature Converter")
.version("0.1.9")
.author("Michael Berry <trismegustis@gmail.com>")
.about("Convert between Fahrenheit and Celsius")
.arg(
Arg::with_name("Fahrenheit to Celsius")
.short("f")
.long("fahrenheit-to-celsius")
.help("Convert degree Fahrenheit to Celsius")
.takes_value(true)
.allow_hyphen_values(true),
)
.arg(
Arg::with_name("Celsius to Fahrenheit")
.short("c")
.long("celsius-to-fahrenheit")
.help("Convert degree Celsius to Fahrenheit")
.takes_value(true)
.allow_hyphen_values(true),
)
.arg(
Arg::with_name("Print common table")
.short("t")
.long("table")
.help("Print a list of common conversions"),
)
.get_matches();
if cli.is_present("Fahrenheit to Celsius") {
if let Some(n) = cli.value_of("Fahrenheit to Celsius") {
match n.parse() {
Ok(n) => print_temperature_conversion(&Temperature::F(n)),
Err(e) => eprintln!("Error: {}", e),
}
};
} else if cli.is_present("Celsius to Fahrenheit") {
if let Some(n) = cli.value_of("Celsius to Fahrenheit") {
match n.parse() {
Ok(n) => print_temperature_conversion(&Temperature::C(n)),
Err(e) => eprintln!("Error: {}", e),
}
};
} else if cli.is_present("Print common table") {
print_common_table();
} else {
eprintln!("{}\n\nTry passing --help for more information", cli.usage());
}
Ok(())
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - SPI/I2S control register 1"]
pub spi2s_cr1: SPI2S_CR1,
#[doc = "0x04 - SPI control register 2"]
pub spi_cr2: SPI_CR2,
#[doc = "0x08 - Content of this register is write protected when SPI is enabled"]
pub spi_cfg1: SPI_CFG1,
#[doc = "0x0c - The content of this register is write protected when SPI is enabled or IOLOCK bit is set at SPI2S_CR1 register."]
pub spi_cfg2: SPI_CFG2,
#[doc = "0x10 - SPI/I2S interrupt enable register"]
pub spi2s_ier: SPI2S_IER,
#[doc = "0x14 - SPI/I2S status register"]
pub spi2s_sr: SPI2S_SR,
#[doc = "0x18 - SPI/I2S interrupt/status flags clear register"]
pub spi2s_ifcr: SPI2S_IFCR,
_reserved7: [u8; 0x04],
#[doc = "0x20 - SPI/I2S transmit data register"]
pub spi2s_txdr: SPI2S_TXDR,
_reserved8: [u8; 0x0c],
#[doc = "0x30 - SPI/I2S receive data register"]
pub spi2s_rxdr: SPI2S_RXDR,
_reserved9: [u8; 0x0c],
#[doc = "0x40 - SPI polynomial register"]
pub spi_crcpoly: SPI_CRCPOLY,
#[doc = "0x44 - SPI transmitter CRC register"]
pub spi_txcrc: SPI_TXCRC,
#[doc = "0x48 - SPI receiver CRC register"]
pub spi_rxcrc: SPI_RXCRC,
#[doc = "0x4c - SPI underrun data register"]
pub spi_udrdr: SPI_UDRDR,
#[doc = "0x50 - All documented bits in this register must be configured when the I2S is disabled (SPE = 0).These bits are not used in SPI mode except for I2SMOD which needs to be set to 0 in SPI mode."]
pub spi_i2scfgr: SPI_I2SCFGR,
_reserved14: [u8; 0x039c],
#[doc = "0x3f0 - SPI/I2S hardware configuration register"]
pub spi_i2s_hwcfgr: SPI_I2S_HWCFGR,
#[doc = "0x3f4 - SPI/I2S version register"]
pub spi_verr: SPI_VERR,
#[doc = "0x3f8 - SPI/I2S identification register"]
pub spi_ipidr: SPI_IPIDR,
#[doc = "0x3fc - SPI/I2S size identification register"]
pub spi_sidr: SPI_SIDR,
}
#[doc = "SPI2S_CR1 (rw) register accessor: SPI/I2S control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi2s_cr1::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 [`spi2s_cr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi2s_cr1`]
module"]
pub type SPI2S_CR1 = crate::Reg<spi2s_cr1::SPI2S_CR1_SPEC>;
#[doc = "SPI/I2S control register 1"]
pub mod spi2s_cr1;
#[doc = "SPI2S_IER (rw) register accessor: SPI/I2S interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi2s_ier::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 [`spi2s_ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi2s_ier`]
module"]
pub type SPI2S_IER = crate::Reg<spi2s_ier::SPI2S_IER_SPEC>;
#[doc = "SPI/I2S interrupt enable register"]
pub mod spi2s_ier;
#[doc = "SPI2S_SR (r) register accessor: SPI/I2S status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi2s_sr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi2s_sr`]
module"]
pub type SPI2S_SR = crate::Reg<spi2s_sr::SPI2S_SR_SPEC>;
#[doc = "SPI/I2S status register"]
pub mod spi2s_sr;
#[doc = "SPI2S_IFCR (w) register accessor: SPI/I2S interrupt/status flags clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`spi2s_ifcr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi2s_ifcr`]
module"]
pub type SPI2S_IFCR = crate::Reg<spi2s_ifcr::SPI2S_IFCR_SPEC>;
#[doc = "SPI/I2S interrupt/status flags clear register"]
pub mod spi2s_ifcr;
#[doc = "SPI2S_TXDR (w) register accessor: SPI/I2S transmit data register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`spi2s_txdr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi2s_txdr`]
module"]
pub type SPI2S_TXDR = crate::Reg<spi2s_txdr::SPI2S_TXDR_SPEC>;
#[doc = "SPI/I2S transmit data register"]
pub mod spi2s_txdr;
#[doc = "SPI2S_RXDR (r) register accessor: SPI/I2S receive data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi2s_rxdr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi2s_rxdr`]
module"]
pub type SPI2S_RXDR = crate::Reg<spi2s_rxdr::SPI2S_RXDR_SPEC>;
#[doc = "SPI/I2S receive data register"]
pub mod spi2s_rxdr;
#[doc = "SPI_CR2 (rw) register accessor: SPI control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_cr2::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 [`spi_cr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_cr2`]
module"]
pub type SPI_CR2 = crate::Reg<spi_cr2::SPI_CR2_SPEC>;
#[doc = "SPI control register 2"]
pub mod spi_cr2;
#[doc = "SPI_CFG1 (rw) register accessor: Content of this register is write protected when SPI is enabled\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_cfg1::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 [`spi_cfg1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_cfg1`]
module"]
pub type SPI_CFG1 = crate::Reg<spi_cfg1::SPI_CFG1_SPEC>;
#[doc = "Content of this register is write protected when SPI is enabled"]
pub mod spi_cfg1;
#[doc = "SPI_CFG2 (rw) register accessor: The content of this register is write protected when SPI is enabled or IOLOCK bit is set at SPI2S_CR1 register.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_cfg2::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 [`spi_cfg2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_cfg2`]
module"]
pub type SPI_CFG2 = crate::Reg<spi_cfg2::SPI_CFG2_SPEC>;
#[doc = "The content of this register is write protected when SPI is enabled or IOLOCK bit is set at SPI2S_CR1 register."]
pub mod spi_cfg2;
#[doc = "SPI_CRCPOLY (rw) register accessor: SPI polynomial register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_crcpoly::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 [`spi_crcpoly::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_crcpoly`]
module"]
pub type SPI_CRCPOLY = crate::Reg<spi_crcpoly::SPI_CRCPOLY_SPEC>;
#[doc = "SPI polynomial register"]
pub mod spi_crcpoly;
#[doc = "SPI_TXCRC (r) register accessor: SPI transmitter CRC register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_txcrc::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_txcrc`]
module"]
pub type SPI_TXCRC = crate::Reg<spi_txcrc::SPI_TXCRC_SPEC>;
#[doc = "SPI transmitter CRC register"]
pub mod spi_txcrc;
#[doc = "SPI_RXCRC (r) register accessor: SPI receiver CRC register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_rxcrc::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_rxcrc`]
module"]
pub type SPI_RXCRC = crate::Reg<spi_rxcrc::SPI_RXCRC_SPEC>;
#[doc = "SPI receiver CRC register"]
pub mod spi_rxcrc;
#[doc = "SPI_UDRDR (rw) register accessor: SPI underrun data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_udrdr::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 [`spi_udrdr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_udrdr`]
module"]
pub type SPI_UDRDR = crate::Reg<spi_udrdr::SPI_UDRDR_SPEC>;
#[doc = "SPI underrun data register"]
pub mod spi_udrdr;
#[doc = "SPI_I2SCFGR (rw) register accessor: All documented bits in this register must be configured when the I2S is disabled (SPE = 0).These bits are not used in SPI mode except for I2SMOD which needs to be set to 0 in SPI mode.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_i2scfgr::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 [`spi_i2scfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_i2scfgr`]
module"]
pub type SPI_I2SCFGR = crate::Reg<spi_i2scfgr::SPI_I2SCFGR_SPEC>;
#[doc = "All documented bits in this register must be configured when the I2S is disabled (SPE = 0).These bits are not used in SPI mode except for I2SMOD which needs to be set to 0 in SPI mode."]
pub mod spi_i2scfgr;
#[doc = "SPI_I2S_HWCFGR (r) register accessor: SPI/I2S hardware configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_i2s_hwcfgr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_i2s_hwcfgr`]
module"]
pub type SPI_I2S_HWCFGR = crate::Reg<spi_i2s_hwcfgr::SPI_I2S_HWCFGR_SPEC>;
#[doc = "SPI/I2S hardware configuration register"]
pub mod spi_i2s_hwcfgr;
#[doc = "SPI_VERR (r) register accessor: SPI/I2S version register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_verr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_verr`]
module"]
pub type SPI_VERR = crate::Reg<spi_verr::SPI_VERR_SPEC>;
#[doc = "SPI/I2S version register"]
pub mod spi_verr;
#[doc = "SPI_IPIDR (r) register accessor: SPI/I2S identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_ipidr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_ipidr`]
module"]
pub type SPI_IPIDR = crate::Reg<spi_ipidr::SPI_IPIDR_SPEC>;
#[doc = "SPI/I2S identification register"]
pub mod spi_ipidr;
#[doc = "SPI_SIDR (r) register accessor: SPI/I2S size identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi_sidr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`spi_sidr`]
module"]
pub type SPI_SIDR = crate::Reg<spi_sidr::SPI_SIDR_SPEC>;
#[doc = "SPI/I2S size identification register"]
pub mod spi_sidr;
|
// Copyright 2019, 2020 Wingchain
//
// 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.
#![feature(test)]
extern crate test;
use std::collections::HashMap;
use std::sync::Arc;
use test::{black_box, Bencher};
use crypto::hash::HashImpl;
use node_db::{DBConfig, DB};
use node_statedb::StateDB;
use primitives::DBKey;
#[bench]
fn bench_statedb_get_1(b: &mut Bencher) {
let (statedb, root) = prepare_statedb(1);
b.iter(|| black_box(statedb.get(&root, &b"abc"[..])));
}
#[bench]
fn bench_statedb_get_with_getter_1(b: &mut Bencher) {
let (statedb, root) = prepare_statedb(1);
let stmt = statedb.prepare_stmt(&root).unwrap();
let getter = StateDB::prepare_get(&stmt).unwrap();
b.iter(|| black_box(getter.get(&&b"abc"[..])));
}
#[bench]
fn bench_statedb_get_2(b: &mut Bencher) {
let (statedb, root) = prepare_statedb(2);
b.iter(|| black_box(statedb.get(&root, &b"abc"[..])));
}
#[bench]
fn bench_statedb_get_with_getter_2(b: &mut Bencher) {
let (statedb, root) = prepare_statedb(2);
let stmt = statedb.prepare_stmt(&root).unwrap();
let getter = StateDB::prepare_get(&stmt).unwrap();
b.iter(|| black_box(getter.get(&&b"abc"[..])));
}
fn prepare_statedb(records: usize) -> (StateDB, Vec<u8>) {
use tempfile::tempdir;
let path = tempdir().expect("Could not create a temp dir");
let path = path.into_path();
let db_config = DBConfig {
memory_budget: 128 * 1024 * 1024,
path,
partitions: vec![],
};
let db = Arc::new(DB::open(db_config).unwrap());
let hasher = Arc::new(HashImpl::Blake2b160);
let statedb = StateDB::new(db.clone(), node_db::columns::META_STATE, hasher).unwrap();
let root = statedb.default_root();
// update 1
let data = match records {
1 => vec![(DBKey::from_slice(b"abc"), Some(vec![1u8; 1024]))],
2 => vec![
(DBKey::from_slice(b"abc"), Some(vec![1u8; 1024])),
(DBKey::from_slice(b"abd"), Some(vec![1u8; 1024])),
],
_ => unreachable!(),
}
.into_iter()
.collect::<HashMap<_, _>>();
let (update_1_root, transaction) = statedb.prepare_update(&root, data.iter()).unwrap();
db.write(transaction).unwrap();
let result = statedb.get(&update_1_root, &b"abc"[..]).unwrap();
assert_eq!(Some(vec![1u8; 1024]), result);
// update 2
let data = vec![(DBKey::from_slice(b"abc"), Some(vec![2u8; 1024]))]
.into_iter()
.collect::<HashMap<_, _>>();
let (update_2_root, transaction) = statedb.prepare_update(&update_1_root, data.iter()).unwrap();
db.write(transaction).unwrap();
let result = statedb.get(&update_2_root, &b"abc"[..]).unwrap();
assert_eq!(Some(vec![2u8; 1024]), result);
(statedb, update_2_root)
}
|
#![warn(future_incompatible, rust_2018_compatibility, rust_2018_idioms, unused)]
#![warn(clippy::pedantic)]
// #![warn(clippy::cargo)]
#![allow(clippy::missing_errors_doc)]
#![cfg_attr(feature = "strict", deny(warnings))]
use crate::reactive::{react, Atom};
use std::{convert::TryInto, panic};
use wasm_bindgen::{prelude::*, JsCast};
use web_sys::{window, Element, HtmlInputElement};
use wee_alloc::WeeAlloc;
mod reactive;
#[global_allocator]
static ALLOC: WeeAlloc<'_> = WeeAlloc::INIT;
// TODO: get rid of derives if possible
#[derive(Clone, Eq, PartialEq)]
struct Todo {
title: String,
completed: bool,
}
#[wasm_bindgen(start)]
pub fn __start() -> Result<(), JsValue> {
panic::set_hook(Box::new(console_error_panic_hook::hook));
let new_title = Atom::new(String::new());
let todos = Atom::new(Vec::new());
let document = window().unwrap_throw().document().unwrap_throw();
let body = document.body().unwrap_throw();
let input: HtmlInputElement = document.create_element("input")?.unchecked_into();
input.add_event_listener_with_callback(
"input",
Closure::wrap(Box::new({
let new_title = new_title.clone();
let input = input.clone();
move || {
new_title.set(input.value());
}
}) as Box<dyn Fn()>)
.into_js_value()
.unchecked_ref(),
)?;
body.append_with_node_1(&input)?;
react({
let new_title = new_title.clone();
move || {
input.set_value(&new_title.get());
}
});
let add_button = document.create_element("button")?;
add_button.add_event_listener_with_callback(
"click",
Closure::wrap(Box::new({
let items = todos.clone();
move || {
items.get_mut().push(Todo {
title: new_title.get().clone(),
completed: false,
});
new_title.get_mut().clear();
}
}) as Box<dyn FnMut()>)
.into_js_value()
.unchecked_ref(),
)?;
add_button.set_text_content(Some("Add"));
body.append_with_node_1(&add_button)?;
let list = document.create_element("ul")?;
body.append_with_node_1(&list)?;
map(list, todos, move |todo| {
let li = document.create_element("li").unwrap_throw();
let label = document.create_element("label").unwrap_throw();
let check: HtmlInputElement = document
.create_element("input")
.unwrap_throw()
.unchecked_into();
check.set_type("checkbox");
check.set_checked(todo.completed);
label.append_with_node_1(&check).unwrap_throw();
label.append_with_str_2(" ", &todo.title).unwrap_throw();
li.append_with_node_1(&label).unwrap_throw();
li
});
Ok(())
}
// TODO: get rid of bounds if possible
fn map<T: Clone + Eq + 'static>(
parent: Element,
xs: Atom<Vec<T>>,
mut f: impl FnMut(&T) -> Element + 'static,
) {
let mut cache = Vec::new();
react(move || {
let xs = xs.get();
// This is the dumbest reconciler ever created
let mut mutations = Vec::new();
for index in 0..xs.len().max(cache.len()) {
match (cache.get(index), xs.get(index)) {
(None, None) => unreachable!(),
(Some(_), None) => {
mutations.push(ListMutation::Remove(index));
}
(None, Some(_)) => {
mutations.push(ListMutation::Insert(index));
}
(Some(prev), Some(next)) if prev != next => {
mutations.push(ListMutation::Remove(index));
mutations.push(ListMutation::Insert(index));
}
(Some(_), Some(_)) => {}
}
}
for mutation in &mutations {
match *mutation {
ListMutation::Remove(index) => {
cache.remove(index);
}
ListMutation::Insert(index) => {
cache.insert(index, xs[index].clone());
}
}
}
for mutation in mutations {
match mutation {
ListMutation::Remove(index) => {
parent
.children()
.item(index.try_into().unwrap())
.unwrap_throw()
.remove();
}
ListMutation::Insert(index) => {
let reference = parent.children().item(index.try_into().unwrap());
parent
.insert_before(&f(&xs[index]), reference.map(<_>::unchecked_into).as_ref())
.unwrap_throw();
}
}
}
});
}
enum ListMutation {
Remove(usize),
Insert(usize),
}
|
extern crate advent_support;
extern crate regex;
#[derive(Debug)]
struct PasswordPolicy {
min: i32,
max: i32,
letter: char,
}
#[derive(Debug)]
struct PasswordAttempt {
policy: PasswordPolicy,
password: String,
}
#[derive(Debug)]
struct PasswordAttempt2 {
positions: Vec<i32>,
letter: char,
password: String,
}
fn check_attempt(attempt: &PasswordAttempt) -> bool {
let letter = attempt.policy.letter;
let count = attempt.password.chars()
.filter(|x| *x == letter)
.count() as i32;
return count >= attempt.policy.min && count <= attempt.policy.max;
}
fn parse_attempt(re: ®ex::Regex, line: &str) -> PasswordAttempt {
match re.captures(line) {
Some(m) => {
PasswordAttempt{
policy: PasswordPolicy{
min: m.get(1).unwrap().as_str().parse().unwrap(),
max: m.get(2).unwrap().as_str().parse().unwrap(),
letter: m.get(3).unwrap().as_str().chars().next().unwrap()
},
password: String::from(m.get(4).unwrap().as_str())
}
},
None => panic!("Line '{}' did not describe password spec", line)
}
}
fn part1(lines: &Vec<String>) {
let re: regex::Regex = regex::Regex::new(r"^\s*(\d+)-(\d+)\s+([a-zA-Z0-9]):\s+([a-zA-Z0-9]+)\s*$").unwrap();
let attempts: Vec<PasswordAttempt> = lines.iter()
.filter(|x| !x.is_empty())
.map(|x| parse_attempt(&re, x))
.collect();
let num_valid = attempts.iter().filter(|x| check_attempt(x)).count();
println!("part1: {}", num_valid)
}
fn parse_attempt2(re: ®ex::Regex, line: &str) -> PasswordAttempt2 {
match re.captures(line) {
Some(m) => {
let positions: Vec<i32> = m.get(1).unwrap().as_str().split("-").map(|x| x.parse().unwrap()).collect();
PasswordAttempt2{
positions: positions,
letter: m.get(2).unwrap().as_str().chars().next().unwrap(),
password: String::from(m.get(3).unwrap().as_str()),
}
},
None => panic!("Line '{}' did not describe password spec", line)
}
}
fn check_attempt2(attempt: &PasswordAttempt2) -> bool {
let letter = attempt.letter;
let mut positions_with_letter = 0;
let mut consumed = 1; // start counting at 1
let password = &attempt.password;
let mut chars = password.chars();
for position in &attempt.positions {
let at_pos = chars.nth((position - consumed) as usize).unwrap();
// println!("letter at {} in {}: {}", position, password, at_pos);
if at_pos == letter {
positions_with_letter += 1;
}
consumed += position;
}
// println!("Password {}, occurences of {}: {} ", password, letter, positions_with_letter);
positions_with_letter == 1
}
fn part2(lines: &Vec<String>) {
let re = regex::Regex::new(r"^\s*([-0-9]+)\s+([a-zA-Z0-9]):\s+([a-zA-Z0-9]+)\s*$").unwrap();
let attempts: Vec<PasswordAttempt2> = lines.iter()
.filter(|x| !x.is_empty())
.map(|x| parse_attempt2(&re, x))
.collect();
let num_valid = attempts.iter().filter(|x| check_attempt2(x)).count();
println!("part2: {}", num_valid)
}
fn main() {
let args = advent_support::argv();
let lines = advent_support::read_lines2(&args[1]);
if args.len() == 3 && args[2] == "part2" {
part2(&lines)
} else {
part1(&lines)
}
}
|
use nix::sys::epoll::*;
use std::os::unix::io::RawFd;
use std::time::Duration;
type Result<T> = std::result::Result<T, nix::Error>;
pub struct Muxer {
epfd: RawFd,
}
pub struct MuxerEvents {
buffer: [EpollEvent; 16],
len: usize,
index: usize,
}
pub struct MuxerEvent(EpollEvent);
impl Muxer {
pub fn new() -> Result<Muxer> {
Ok(Muxer {
epfd: epoll_create()?,
})
}
pub fn watch_input(&self, fd: RawFd) -> Result<()> {
let mut epev = EpollEvent::new(EpollFlags::EPOLLIN, fd as u64);
epoll_ctl(self.epfd, EpollOp::EpollCtlAdd, fd, &mut epev)?;
Ok(())
}
pub fn wait(&self, timeout: Option<Duration>) -> Result<MuxerEvents> {
let timeout_ms = match timeout {
Some(dur) => dur.as_millis() as isize,
None => -1,
};
let mut events = MuxerEvents::default();
events.len = epoll_wait(self.epfd, &mut events.buffer, timeout_ms)?;
Ok(events)
}
}
impl Drop for Muxer {
fn drop(&mut self) {
let _ = nix::unistd::close(self.epfd);
}
}
impl Default for MuxerEvents {
fn default() -> Self {
MuxerEvents {
buffer: [EpollEvent::empty(); 16],
len: 0,
index: 0,
}
}
}
impl Iterator for MuxerEvents {
type Item = MuxerEvent;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.len {
return None
}
let i = self.index;
self.index += 1;
Some(self.buffer[i].into())
}
}
impl MuxerEvent {
pub fn fd(&self) -> RawFd {
self.0.data() as RawFd
}
pub fn readable(&self) -> bool {
self.0.events().contains(EpollFlags::EPOLLIN)
}
pub fn hungup(&self) -> bool {
self.0.events().contains(EpollFlags::EPOLLHUP)
}
}
impl From<EpollEvent> for MuxerEvent {
fn from(event: EpollEvent) -> Self {
Self(event)
}
}
|
use super::{ExtractedLexicalGrammar, ExtractedSyntaxGrammar, InternedGrammar};
use crate::generate::grammars::{ExternalToken, Variable, VariableType};
use crate::generate::rules::{MetadataParams, Rule, Symbol, SymbolType};
use anyhow::{anyhow, Result};
use std::collections::HashMap;
use std::mem;
pub(super) fn extract_tokens(
mut grammar: InternedGrammar,
) -> Result<(ExtractedSyntaxGrammar, ExtractedLexicalGrammar)> {
let mut extractor = TokenExtractor {
current_variable_name: String::new(),
current_variable_token_count: 0,
extracted_variables: Vec::new(),
extracted_usage_counts: Vec::new(),
};
for mut variable in grammar.variables.iter_mut() {
extractor.extract_tokens_in_variable(&mut variable);
}
for mut variable in grammar.external_tokens.iter_mut() {
extractor.extract_tokens_in_variable(&mut variable);
}
let mut lexical_variables = Vec::with_capacity(extractor.extracted_variables.len());
for variable in extractor.extracted_variables {
lexical_variables.push(Variable {
name: variable.name,
kind: variable.kind,
rule: variable.rule,
});
}
// If a variable's entire rule was extracted as a token and that token didn't
// appear within any other rule, then remove that variable from the syntax
// grammar, giving its name to the token in the lexical grammar. Any symbols
// that pointed to that variable will need to be updated to point to the
// variable in the lexical grammar. Symbols that pointed to later variables
// will need to have their indices decremented.
let mut variables = Vec::new();
let mut symbol_replacer = SymbolReplacer {
replacements: HashMap::new(),
};
for (i, variable) in grammar.variables.into_iter().enumerate() {
if let Rule::Symbol(Symbol {
kind: SymbolType::Terminal,
index,
}) = variable.rule
{
if i > 0 && extractor.extracted_usage_counts[index] == 1 {
let lexical_variable = &mut lexical_variables[index];
lexical_variable.kind = variable.kind;
lexical_variable.name = variable.name;
symbol_replacer.replacements.insert(i, index);
continue;
}
}
variables.push(variable);
}
for variable in variables.iter_mut() {
variable.rule = symbol_replacer.replace_symbols_in_rule(&variable.rule);
}
let expected_conflicts = grammar
.expected_conflicts
.into_iter()
.map(|conflict| {
let mut result: Vec<_> = conflict
.iter()
.map(|symbol| symbol_replacer.replace_symbol(*symbol))
.collect();
result.sort_unstable();
result.dedup();
result
})
.collect();
let supertype_symbols = grammar
.supertype_symbols
.into_iter()
.map(|symbol| symbol_replacer.replace_symbol(symbol))
.collect();
let variables_to_inline = grammar
.variables_to_inline
.into_iter()
.map(|symbol| symbol_replacer.replace_symbol(symbol))
.collect();
let mut separators = Vec::new();
let mut extra_symbols = Vec::new();
for rule in grammar.extra_symbols {
if let Rule::Symbol(symbol) = rule {
extra_symbols.push(symbol_replacer.replace_symbol(symbol));
} else {
if let Some(index) = lexical_variables.iter().position(|v| v.rule == rule) {
extra_symbols.push(Symbol::terminal(index));
} else {
separators.push(rule);
}
}
}
let mut external_tokens = Vec::new();
for external_token in grammar.external_tokens {
let rule = symbol_replacer.replace_symbols_in_rule(&external_token.rule);
if let Rule::Symbol(symbol) = rule {
if symbol.is_non_terminal() {
return Err(anyhow!(
"Rule '{}' cannot be used as both an external token and a non-terminal rule",
&variables[symbol.index].name,
));
}
if symbol.is_external() {
external_tokens.push(ExternalToken {
name: external_token.name,
kind: external_token.kind,
corresponding_internal_token: None,
})
} else {
external_tokens.push(ExternalToken {
name: lexical_variables[symbol.index].name.clone(),
kind: external_token.kind,
corresponding_internal_token: Some(symbol),
})
}
} else {
return Err(anyhow!(
"Non-symbol rules cannot be used as external tokens"
));
}
}
let mut word_token = None;
if let Some(token) = grammar.word_token {
let token = symbol_replacer.replace_symbol(token);
if token.is_non_terminal() {
return Err(anyhow!(
"Non-terminal symbol '{}' cannot be used as the word token",
&variables[token.index].name
));
}
word_token = Some(token);
}
Ok((
ExtractedSyntaxGrammar {
variables,
expected_conflicts,
extra_symbols,
variables_to_inline,
supertype_symbols,
external_tokens,
word_token,
precedence_orderings: grammar.precedence_orderings,
},
ExtractedLexicalGrammar {
variables: lexical_variables,
separators,
},
))
}
struct TokenExtractor {
current_variable_name: String,
current_variable_token_count: usize,
extracted_variables: Vec<Variable>,
extracted_usage_counts: Vec<usize>,
}
struct SymbolReplacer {
replacements: HashMap<usize, usize>,
}
impl TokenExtractor {
fn extract_tokens_in_variable(&mut self, variable: &mut Variable) {
self.current_variable_name.clear();
self.current_variable_name.push_str(&variable.name);
self.current_variable_token_count = 0;
let mut rule = Rule::Blank;
mem::swap(&mut rule, &mut variable.rule);
variable.rule = self.extract_tokens_in_rule(&rule);
}
fn extract_tokens_in_rule(&mut self, input: &Rule) -> Rule {
match input {
Rule::String(name) => self.extract_token(input, Some(name)).into(),
Rule::Pattern(..) => self.extract_token(input, None).into(),
Rule::Metadata { params, rule } => {
if params.is_token {
let mut params = params.clone();
params.is_token = false;
let mut string_value = None;
if let Rule::String(value) = rule.as_ref() {
string_value = Some(value);
}
let rule_to_extract = if params == MetadataParams::default() {
rule.as_ref()
} else {
input
};
self.extract_token(rule_to_extract, string_value).into()
} else {
Rule::Metadata {
params: params.clone(),
rule: Box::new(self.extract_tokens_in_rule(&rule)),
}
}
}
Rule::Repeat(content) => Rule::Repeat(Box::new(self.extract_tokens_in_rule(content))),
Rule::Seq(elements) => Rule::Seq(
elements
.iter()
.map(|e| self.extract_tokens_in_rule(e))
.collect(),
),
Rule::Choice(elements) => Rule::Choice(
elements
.iter()
.map(|e| self.extract_tokens_in_rule(e))
.collect(),
),
_ => input.clone(),
}
}
fn extract_token(&mut self, rule: &Rule, string_value: Option<&String>) -> Symbol {
for (i, variable) in self.extracted_variables.iter_mut().enumerate() {
if variable.rule == *rule {
self.extracted_usage_counts[i] += 1;
return Symbol::terminal(i);
}
}
let index = self.extracted_variables.len();
let variable = if let Some(string_value) = string_value {
Variable {
name: string_value.clone(),
kind: VariableType::Anonymous,
rule: rule.clone(),
}
} else {
self.current_variable_token_count += 1;
Variable {
name: format!(
"{}_token{}",
&self.current_variable_name, self.current_variable_token_count
),
kind: VariableType::Auxiliary,
rule: rule.clone(),
}
};
self.extracted_variables.push(variable);
self.extracted_usage_counts.push(1);
Symbol::terminal(index)
}
}
impl SymbolReplacer {
fn replace_symbols_in_rule(&mut self, rule: &Rule) -> Rule {
match rule {
Rule::Symbol(symbol) => self.replace_symbol(*symbol).into(),
Rule::Choice(elements) => Rule::Choice(
elements
.iter()
.map(|e| self.replace_symbols_in_rule(e))
.collect(),
),
Rule::Seq(elements) => Rule::Seq(
elements
.iter()
.map(|e| self.replace_symbols_in_rule(e))
.collect(),
),
Rule::Repeat(content) => Rule::Repeat(Box::new(self.replace_symbols_in_rule(content))),
Rule::Metadata { rule, params } => Rule::Metadata {
params: params.clone(),
rule: Box::new(self.replace_symbols_in_rule(rule)),
},
_ => rule.clone(),
}
}
fn replace_symbol(&self, symbol: Symbol) -> Symbol {
if !symbol.is_non_terminal() {
return symbol;
}
if let Some(replacement) = self.replacements.get(&symbol.index) {
return Symbol::terminal(*replacement);
}
let mut adjusted_index = symbol.index;
for (replaced_index, _) in self.replacements.iter() {
if *replaced_index < symbol.index {
adjusted_index -= 1;
}
}
return Symbol::non_terminal(adjusted_index);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::generate::grammars::VariableType;
#[test]
fn test_extraction() {
let (syntax_grammar, lexical_grammar) = extract_tokens(build_grammar(vec![
Variable::named(
"rule_0",
Rule::repeat(Rule::seq(vec![
Rule::string("a"),
Rule::pattern("b", ""),
Rule::choice(vec![
Rule::non_terminal(1),
Rule::non_terminal(2),
Rule::token(Rule::repeat(Rule::choice(vec![
Rule::string("c"),
Rule::string("d"),
]))),
]),
])),
),
Variable::named("rule_1", Rule::pattern("e", "")),
Variable::named("rule_2", Rule::pattern("b", "")),
Variable::named(
"rule_3",
Rule::seq(vec![Rule::non_terminal(2), Rule::Blank]),
),
]))
.unwrap();
assert_eq!(
syntax_grammar.variables,
vec![
Variable::named(
"rule_0",
Rule::repeat(Rule::seq(vec![
// The string "a" was replaced by a symbol referencing the lexical grammar
Rule::terminal(0),
// The pattern "b" was replaced by a symbol referencing the lexical grammar
Rule::terminal(1),
Rule::choice(vec![
// The symbol referencing `rule_1` was replaced by a symbol referencing
// the lexical grammar.
Rule::terminal(3),
// The symbol referencing `rule_2` had its index decremented because
// `rule_1` was moved to the lexical grammar.
Rule::non_terminal(1),
// The rule wrapped in `token` was replaced by a symbol referencing
// the lexical grammar.
Rule::terminal(2),
])
]))
),
// The pattern "e" was only used in once place: as the definition of `rule_1`,
// so that rule was moved to the lexical grammar. The pattern "b" appeared in
// two places, so it was not moved into the lexical grammar.
Variable::named("rule_2", Rule::terminal(1)),
Variable::named(
"rule_3",
Rule::seq(vec![Rule::non_terminal(1), Rule::Blank,])
),
]
);
assert_eq!(
lexical_grammar.variables,
vec![
Variable::anonymous("a", Rule::string("a")),
Variable::auxiliary("rule_0_token1", Rule::pattern("b", "")),
Variable::auxiliary(
"rule_0_token2",
Rule::repeat(Rule::choice(vec![Rule::string("c"), Rule::string("d"),]))
),
Variable::named("rule_1", Rule::pattern("e", "")),
]
);
}
#[test]
fn test_start_rule_is_token() {
let (syntax_grammar, lexical_grammar) =
extract_tokens(build_grammar(vec![Variable::named(
"rule_0",
Rule::string("hello"),
)]))
.unwrap();
assert_eq!(
syntax_grammar.variables,
vec![Variable::named("rule_0", Rule::terminal(0)),]
);
assert_eq!(
lexical_grammar.variables,
vec![Variable::anonymous("hello", Rule::string("hello")),]
)
}
#[test]
fn test_extracting_extra_symbols() {
let mut grammar = build_grammar(vec![
Variable::named("rule_0", Rule::string("x")),
Variable::named("comment", Rule::pattern("//.*", "")),
]);
grammar.extra_symbols = vec![Rule::string(" "), Rule::non_terminal(1)];
let (syntax_grammar, lexical_grammar) = extract_tokens(grammar).unwrap();
assert_eq!(syntax_grammar.extra_symbols, vec![Symbol::terminal(1),]);
assert_eq!(lexical_grammar.separators, vec![Rule::string(" "),]);
}
#[test]
fn test_extract_externals() {
let mut grammar = build_grammar(vec![
Variable::named(
"rule_0",
Rule::seq(vec![
Rule::external(0),
Rule::string("a"),
Rule::non_terminal(1),
Rule::non_terminal(2),
]),
),
Variable::named("rule_1", Rule::string("b")),
Variable::named("rule_2", Rule::string("c")),
]);
grammar.external_tokens = vec![
Variable::named("external_0", Rule::external(0)),
Variable::anonymous("a", Rule::string("a")),
Variable::named("rule_2", Rule::non_terminal(2)),
];
let (syntax_grammar, _) = extract_tokens(grammar).unwrap();
assert_eq!(
syntax_grammar.external_tokens,
vec![
ExternalToken {
name: "external_0".to_string(),
kind: VariableType::Named,
corresponding_internal_token: None,
},
ExternalToken {
name: "a".to_string(),
kind: VariableType::Anonymous,
corresponding_internal_token: Some(Symbol::terminal(0)),
},
ExternalToken {
name: "rule_2".to_string(),
kind: VariableType::Named,
corresponding_internal_token: Some(Symbol::terminal(2)),
},
]
);
}
#[test]
fn test_error_on_external_with_same_name_as_non_terminal() {
let mut grammar = build_grammar(vec![
Variable::named(
"rule_0",
Rule::seq(vec![Rule::non_terminal(1), Rule::non_terminal(2)]),
),
Variable::named(
"rule_1",
Rule::seq(vec![Rule::non_terminal(2), Rule::non_terminal(2)]),
),
Variable::named("rule_2", Rule::string("a")),
]);
grammar.external_tokens = vec![Variable::named("rule_1", Rule::non_terminal(1))];
match extract_tokens(grammar) {
Err(e) => {
assert_eq!(e.to_string(), "Rule 'rule_1' cannot be used as both an external token and a non-terminal rule");
}
_ => {
panic!("Expected an error but got no error");
}
}
}
fn build_grammar(variables: Vec<Variable>) -> InternedGrammar {
InternedGrammar {
variables,
..Default::default()
}
}
}
|
use std::io::{Stdout, Write};
use termion::cursor::Goto;
use termion::raw::RawTerminal;
use termion::{color, style};
use crate::models::{Board, Coordinates};
pub struct BoardView {
pub origin: Coordinates,
model: Board,
}
impl BoardView {
pub fn new(origin: Coordinates, model: Board) -> BoardView {
BoardView { origin, model }
}
pub fn update(self, model: Board) -> BoardView {
BoardView { model, ..self }
}
fn render_latitude_line(&self, stdout: &mut RawTerminal<Stdout>) {
let mut output = "+".to_string();
for _ in 0..self.model.height {
output.push_str("---+");
}
write!(
stdout,
"{}{}{}{}\n\r",
color::Fg(color::White),
color::Bg(color::Blue),
output,
style::Reset
)
.unwrap();
}
fn render_longitude_line(&self, stdout: &mut RawTerminal<Stdout>) {
let mut output = "|".to_string();
for _ in 0..self.model.width {
output.push_str(" |");
}
write!(
stdout,
"{}{}{}{}\n\r",
color::Fg(color::White),
color::Bg(color::Blue),
output,
style::Reset
)
.unwrap();
}
pub fn render(&self, stdout: &mut RawTerminal<Stdout>) {
write!(stdout, "{}", Goto(self.origin.x, self.origin.y)).unwrap();
for _ in 1..self.model.height + 1 {
self.render_latitude_line(stdout);
self.render_longitude_line(stdout);
}
self.render_latitude_line(stdout);
write!(stdout, "\n\r").unwrap();
}
}
|
use super::ziggurat_tables;
use rand::distributions::Open01;
use rand::Rng;
pub fn sample_std_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {
#[inline]
fn pdf(x: f64) -> f64 {
(-x * x / 2.0).exp()
}
#[inline]
fn zero_case<R: Rng + ?Sized>(rng: &mut R, u: f64) -> f64 {
let mut x = 1.0f64;
let mut y = 0.0f64;
while -2.0 * y < x * x {
let x_: f64 = rng.sample(Open01);
let y_: f64 = rng.sample(Open01);
x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
y = y_.ln();
}
if u < 0.0 {
x - ziggurat_tables::ZIG_NORM_R
} else {
ziggurat_tables::ZIG_NORM_R - x
}
}
ziggurat(
rng,
true,
&ziggurat_tables::ZIG_NORM_X,
&ziggurat_tables::ZIG_NORM_F,
pdf,
zero_case,
)
}
pub fn sample_exp_1<R: Rng + ?Sized>(rng: &mut R) -> f64 {
#[inline]
fn pdf(x: f64) -> f64 {
(-x).exp()
}
#[inline]
fn zero_case<R: Rng + ?Sized>(rng: &mut R, _u: f64) -> f64 {
ziggurat_tables::ZIG_EXP_R - rng.gen::<f64>().ln()
}
ziggurat(
rng,
false,
&ziggurat_tables::ZIG_EXP_X,
&ziggurat_tables::ZIG_EXP_F,
pdf,
zero_case,
)
}
// Ziggurat method for sampling a random number based on the ZIGNOR
// variant from Doornik 2005. Code borrowed from
// https://github.com/rust-lang-nursery/rand/blob/master/src/distributions/mod.
// rs#L223
#[inline(always)]
fn ziggurat<R: Rng + ?Sized, P, Z>(
rng: &mut R,
symmetric: bool,
x_tab: ziggurat_tables::ZigTable,
f_tab: ziggurat_tables::ZigTable,
mut pdf: P,
mut zero_case: Z,
) -> f64
where
P: FnMut(f64) -> f64,
Z: FnMut(&mut R, f64) -> f64,
{
const SCALE: f64 = (1u64 << 53) as f64;
loop {
let bits: u64 = rng.gen();
let i = (bits & 0xff) as usize;
let f = (bits >> 11) as f64 / SCALE;
// u is either U(-1, 1) or U(0, 1) depending on if this is a
// symmetric distribution or not.
let u = if symmetric { 2.0 * f - 1.0 } else { f };
let x = u * x_tab[i];
let test_x = if symmetric { x.abs() } else { x };
// algebraically equivalent to |u| < x_tab[i+1]/x_tab[i] (or u <
// x_tab[i+1]/x_tab[i])
if test_x < x_tab[i + 1] {
return x;
}
if i == 0 {
return zero_case(rng, u);
}
// algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1
if f_tab[i + 1] + (f_tab[i] - f_tab[i + 1]) * rng.gen::<f64>() < pdf(x) {
return x;
}
}
}
|
//! options for aurora kernel syscalls
use bitflags::bitflags;
bitflags! {
pub struct FutexOptions: u32
{
const SHARE = 1;
// only used for futex_block
const TIMEOUT = 1 << 1;
}
}
bitflags! {
pub struct ReallocOptions: u32
{
const READ = 1;
const WRITE = 1 << 1;
const EXEC = 1 << 2;
const EXACT = 1 << 4;
}
}
bitflags! {
pub struct SallocOptions: u32
{
const READ = 1;
const WRITE = 1 << 1;
const EXEC = 1 << 2;
}
}
bitflags! {
pub struct RegOptions: u32
{
const BLOCK = 1;
const DEFAULT = 1 << 1;
const GLOBAL = 1 << 2;
const PUBLIC = 1 << 3;
const REMOVE = 1 << 4;
const GROUP = 1 << 5;
}
}
bitflags! {
pub struct ConnectOptions: u32
{
const PID = 1;
}
}
bitflags! {
pub struct MsgOptions: u32
{
const PID = 1;
const BLOCK = 1 << 1;
const REPLY = 1 << 2;
const SMEM1 = 1 << 8;
const SMEM2 = 1 << 9;
const SMEM3 = 1 << 10;
const SMEM4 = 1 << 11;
const SMEM5 = 1 << 12;
const SMEM6 = 1 << 13;
const SMEM7 = 1 << 14;
const SMEM8 = 1 << 15;
}
}
|
/// An enum to represent all characters in the SupplementalMathematicalOperators block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum SupplementalMathematicalOperators {
/// \u{2a00}: '⨀'
NDashAryCircledDotOperator,
/// \u{2a01}: '⨁'
NDashAryCircledPlusOperator,
/// \u{2a02}: '⨂'
NDashAryCircledTimesOperator,
/// \u{2a03}: '⨃'
NDashAryUnionOperatorWithDot,
/// \u{2a04}: '⨄'
NDashAryUnionOperatorWithPlus,
/// \u{2a05}: '⨅'
NDashArySquareIntersectionOperator,
/// \u{2a06}: '⨆'
NDashArySquareUnionOperator,
/// \u{2a07}: '⨇'
TwoLogicalAndOperator,
/// \u{2a08}: '⨈'
TwoLogicalOrOperator,
/// \u{2a09}: '⨉'
NDashAryTimesOperator,
/// \u{2a0a}: '⨊'
ModuloTwoSum,
/// \u{2a0b}: '⨋'
SummationWithIntegral,
/// \u{2a0c}: '⨌'
QuadrupleIntegralOperator,
/// \u{2a0d}: '⨍'
FinitePartIntegral,
/// \u{2a0e}: '⨎'
IntegralWithDoubleStroke,
/// \u{2a0f}: '⨏'
IntegralAverageWithSlash,
/// \u{2a10}: '⨐'
CirculationFunction,
/// \u{2a11}: '⨑'
AnticlockwiseIntegration,
/// \u{2a12}: '⨒'
LineIntegrationWithRectangularPathAroundPole,
/// \u{2a13}: '⨓'
LineIntegrationWithSemicircularPathAroundPole,
/// \u{2a14}: '⨔'
LineIntegrationNotIncludingThePole,
/// \u{2a15}: '⨕'
IntegralAroundAPointOperator,
/// \u{2a16}: '⨖'
QuaternionIntegralOperator,
/// \u{2a17}: '⨗'
IntegralWithLeftwardsArrowWithHook,
/// \u{2a18}: '⨘'
IntegralWithTimesSign,
/// \u{2a19}: '⨙'
IntegralWithIntersection,
/// \u{2a1a}: '⨚'
IntegralWithUnion,
/// \u{2a1b}: '⨛'
IntegralWithOverbar,
/// \u{2a1c}: '⨜'
IntegralWithUnderbar,
/// \u{2a1d}: '⨝'
Join,
/// \u{2a1e}: '⨞'
LargeLeftTriangleOperator,
/// \u{2a1f}: '⨟'
ZNotationSchemaComposition,
/// \u{2a20}: '⨠'
ZNotationSchemaPiping,
/// \u{2a21}: '⨡'
ZNotationSchemaProjection,
/// \u{2a22}: '⨢'
PlusSignWithSmallCircleAbove,
/// \u{2a23}: '⨣'
PlusSignWithCircumflexAccentAbove,
/// \u{2a24}: '⨤'
PlusSignWithTildeAbove,
/// \u{2a25}: '⨥'
PlusSignWithDotBelow,
/// \u{2a26}: '⨦'
PlusSignWithTildeBelow,
/// \u{2a27}: '⨧'
PlusSignWithSubscriptTwo,
/// \u{2a28}: '⨨'
PlusSignWithBlackTriangle,
/// \u{2a29}: '⨩'
MinusSignWithCommaAbove,
/// \u{2a2a}: '⨪'
MinusSignWithDotBelow,
/// \u{2a2b}: '⨫'
MinusSignWithFallingDots,
/// \u{2a2c}: '⨬'
MinusSignWithRisingDots,
/// \u{2a2d}: '⨭'
PlusSignInLeftHalfCircle,
/// \u{2a2e}: '⨮'
PlusSignInRightHalfCircle,
/// \u{2a2f}: '⨯'
VectorOrCrossProduct,
/// \u{2a30}: '⨰'
MultiplicationSignWithDotAbove,
/// \u{2a31}: '⨱'
MultiplicationSignWithUnderbar,
/// \u{2a32}: '⨲'
SemidirectProductWithBottomClosed,
/// \u{2a33}: '⨳'
SmashProduct,
/// \u{2a34}: '⨴'
MultiplicationSignInLeftHalfCircle,
/// \u{2a35}: '⨵'
MultiplicationSignInRightHalfCircle,
/// \u{2a36}: '⨶'
CircledMultiplicationSignWithCircumflexAccent,
/// \u{2a37}: '⨷'
MultiplicationSignInDoubleCircle,
/// \u{2a38}: '⨸'
CircledDivisionSign,
/// \u{2a39}: '⨹'
PlusSignInTriangle,
/// \u{2a3a}: '⨺'
MinusSignInTriangle,
/// \u{2a3b}: '⨻'
MultiplicationSignInTriangle,
/// \u{2a3c}: '⨼'
InteriorProduct,
/// \u{2a3d}: '⨽'
RighthandInteriorProduct,
/// \u{2a3e}: '⨾'
ZNotationRelationalComposition,
/// \u{2a3f}: '⨿'
AmalgamationOrCoproduct,
/// \u{2a40}: '⩀'
IntersectionWithDot,
/// \u{2a41}: '⩁'
UnionWithMinusSign,
/// \u{2a42}: '⩂'
UnionWithOverbar,
/// \u{2a43}: '⩃'
IntersectionWithOverbar,
/// \u{2a44}: '⩄'
IntersectionWithLogicalAnd,
/// \u{2a45}: '⩅'
UnionWithLogicalOr,
/// \u{2a46}: '⩆'
UnionAboveIntersection,
/// \u{2a47}: '⩇'
IntersectionAboveUnion,
/// \u{2a48}: '⩈'
UnionAboveBarAboveIntersection,
/// \u{2a49}: '⩉'
IntersectionAboveBarAboveUnion,
/// \u{2a4a}: '⩊'
UnionBesideAndJoinedWithUnion,
/// \u{2a4b}: '⩋'
IntersectionBesideAndJoinedWithIntersection,
/// \u{2a4c}: '⩌'
ClosedUnionWithSerifs,
/// \u{2a4d}: '⩍'
ClosedIntersectionWithSerifs,
/// \u{2a4e}: '⩎'
DoubleSquareIntersection,
/// \u{2a4f}: '⩏'
DoubleSquareUnion,
/// \u{2a50}: '⩐'
ClosedUnionWithSerifsAndSmashProduct,
/// \u{2a51}: '⩑'
LogicalAndWithDotAbove,
/// \u{2a52}: '⩒'
LogicalOrWithDotAbove,
/// \u{2a53}: '⩓'
DoubleLogicalAnd,
/// \u{2a54}: '⩔'
DoubleLogicalOr,
/// \u{2a55}: '⩕'
TwoIntersectingLogicalAnd,
/// \u{2a56}: '⩖'
TwoIntersectingLogicalOr,
/// \u{2a57}: '⩗'
SlopingLargeOr,
/// \u{2a58}: '⩘'
SlopingLargeAnd,
/// \u{2a59}: '⩙'
LogicalOrOverlappingLogicalAnd,
/// \u{2a5a}: '⩚'
LogicalAndWithMiddleStem,
/// \u{2a5b}: '⩛'
LogicalOrWithMiddleStem,
/// \u{2a5c}: '⩜'
LogicalAndWithHorizontalDash,
/// \u{2a5d}: '⩝'
LogicalOrWithHorizontalDash,
/// \u{2a5e}: '⩞'
LogicalAndWithDoubleOverbar,
/// \u{2a5f}: '⩟'
LogicalAndWithUnderbar,
/// \u{2a60}: '⩠'
LogicalAndWithDoubleUnderbar,
/// \u{2a61}: '⩡'
SmallVeeWithUnderbar,
/// \u{2a62}: '⩢'
LogicalOrWithDoubleOverbar,
/// \u{2a63}: '⩣'
LogicalOrWithDoubleUnderbar,
/// \u{2a64}: '⩤'
ZNotationDomainAntirestriction,
/// \u{2a65}: '⩥'
ZNotationRangeAntirestriction,
/// \u{2a66}: '⩦'
EqualsSignWithDotBelow,
/// \u{2a67}: '⩧'
IdenticalWithDotAbove,
/// \u{2a68}: '⩨'
TripleHorizontalBarWithDoubleVerticalStroke,
/// \u{2a69}: '⩩'
TripleHorizontalBarWithTripleVerticalStroke,
/// \u{2a6a}: '⩪'
TildeOperatorWithDotAbove,
/// \u{2a6b}: '⩫'
TildeOperatorWithRisingDots,
/// \u{2a6c}: '⩬'
SimilarMinusSimilar,
/// \u{2a6d}: '⩭'
CongruentWithDotAbove,
/// \u{2a6e}: '⩮'
EqualsWithAsterisk,
/// \u{2a6f}: '⩯'
AlmostEqualToWithCircumflexAccent,
/// \u{2a70}: '⩰'
ApproximatelyEqualOrEqualTo,
/// \u{2a71}: '⩱'
EqualsSignAbovePlusSign,
/// \u{2a72}: '⩲'
PlusSignAboveEqualsSign,
/// \u{2a73}: '⩳'
EqualsSignAboveTildeOperator,
/// \u{2a74}: '⩴'
DoubleColonEqual,
/// \u{2a75}: '⩵'
TwoConsecutiveEqualsSigns,
/// \u{2a76}: '⩶'
ThreeConsecutiveEqualsSigns,
/// \u{2a77}: '⩷'
EqualsSignWithTwoDotsAboveAndTwoDotsBelow,
/// \u{2a78}: '⩸'
EquivalentWithFourDotsAbove,
/// \u{2a79}: '⩹'
LessDashThanWithCircleInside,
/// \u{2a7a}: '⩺'
GreaterDashThanWithCircleInside,
/// \u{2a7b}: '⩻'
LessDashThanWithQuestionMarkAbove,
/// \u{2a7c}: '⩼'
GreaterDashThanWithQuestionMarkAbove,
/// \u{2a7d}: '⩽'
LessDashThanOrSlantedEqualTo,
/// \u{2a7e}: '⩾'
GreaterDashThanOrSlantedEqualTo,
/// \u{2a7f}: '⩿'
LessDashThanOrSlantedEqualToWithDotInside,
/// \u{2a80}: '⪀'
GreaterDashThanOrSlantedEqualToWithDotInside,
/// \u{2a81}: '⪁'
LessDashThanOrSlantedEqualToWithDotAbove,
/// \u{2a82}: '⪂'
GreaterDashThanOrSlantedEqualToWithDotAbove,
/// \u{2a83}: '⪃'
LessDashThanOrSlantedEqualToWithDotAboveRight,
/// \u{2a84}: '⪄'
GreaterDashThanOrSlantedEqualToWithDotAboveLeft,
/// \u{2a85}: '⪅'
LessDashThanOrApproximate,
/// \u{2a86}: '⪆'
GreaterDashThanOrApproximate,
/// \u{2a87}: '⪇'
LessDashThanAndSingleDashLineNotEqualTo,
/// \u{2a88}: '⪈'
GreaterDashThanAndSingleDashLineNotEqualTo,
/// \u{2a89}: '⪉'
LessDashThanAndNotApproximate,
/// \u{2a8a}: '⪊'
GreaterDashThanAndNotApproximate,
/// \u{2a8b}: '⪋'
LessDashThanAboveDoubleDashLineEqualAboveGreaterDashThan,
/// \u{2a8c}: '⪌'
GreaterDashThanAboveDoubleDashLineEqualAboveLessDashThan,
/// \u{2a8d}: '⪍'
LessDashThanAboveSimilarOrEqual,
/// \u{2a8e}: '⪎'
GreaterDashThanAboveSimilarOrEqual,
/// \u{2a8f}: '⪏'
LessDashThanAboveSimilarAboveGreaterDashThan,
/// \u{2a90}: '⪐'
GreaterDashThanAboveSimilarAboveLessDashThan,
/// \u{2a91}: '⪑'
LessDashThanAboveGreaterDashThanAboveDoubleDashLineEqual,
/// \u{2a92}: '⪒'
GreaterDashThanAboveLessDashThanAboveDoubleDashLineEqual,
/// \u{2a93}: '⪓'
LessDashThanAboveSlantedEqualAboveGreaterDashThanAboveSlantedEqual,
/// \u{2a94}: '⪔'
GreaterDashThanAboveSlantedEqualAboveLessDashThanAboveSlantedEqual,
/// \u{2a95}: '⪕'
SlantedEqualToOrLessDashThan,
/// \u{2a96}: '⪖'
SlantedEqualToOrGreaterDashThan,
/// \u{2a97}: '⪗'
SlantedEqualToOrLessDashThanWithDotInside,
/// \u{2a98}: '⪘'
SlantedEqualToOrGreaterDashThanWithDotInside,
/// \u{2a99}: '⪙'
DoubleDashLineEqualToOrLessDashThan,
/// \u{2a9a}: '⪚'
DoubleDashLineEqualToOrGreaterDashThan,
/// \u{2a9b}: '⪛'
DoubleDashLineSlantedEqualToOrLessDashThan,
/// \u{2a9c}: '⪜'
DoubleDashLineSlantedEqualToOrGreaterDashThan,
/// \u{2a9d}: '⪝'
SimilarOrLessDashThan,
/// \u{2a9e}: '⪞'
SimilarOrGreaterDashThan,
/// \u{2a9f}: '⪟'
SimilarAboveLessDashThanAboveEqualsSign,
/// \u{2aa0}: '⪠'
SimilarAboveGreaterDashThanAboveEqualsSign,
/// \u{2aa1}: '⪡'
DoubleNestedLessDashThan,
/// \u{2aa2}: '⪢'
DoubleNestedGreaterDashThan,
/// \u{2aa3}: '⪣'
DoubleNestedLessDashThanWithUnderbar,
/// \u{2aa4}: '⪤'
GreaterDashThanOverlappingLessDashThan,
/// \u{2aa5}: '⪥'
GreaterDashThanBesideLessDashThan,
/// \u{2aa6}: '⪦'
LessDashThanClosedByCurve,
/// \u{2aa7}: '⪧'
GreaterDashThanClosedByCurve,
/// \u{2aa8}: '⪨'
LessDashThanClosedByCurveAboveSlantedEqual,
/// \u{2aa9}: '⪩'
GreaterDashThanClosedByCurveAboveSlantedEqual,
/// \u{2aaa}: '⪪'
SmallerThan,
/// \u{2aab}: '⪫'
LargerThan,
/// \u{2aac}: '⪬'
SmallerThanOrEqualTo,
/// \u{2aad}: '⪭'
LargerThanOrEqualTo,
/// \u{2aae}: '⪮'
EqualsSignWithBumpyAbove,
/// \u{2aaf}: '⪯'
PrecedesAboveSingleDashLineEqualsSign,
/// \u{2ab0}: '⪰'
SucceedsAboveSingleDashLineEqualsSign,
/// \u{2ab1}: '⪱'
PrecedesAboveSingleDashLineNotEqualTo,
/// \u{2ab2}: '⪲'
SucceedsAboveSingleDashLineNotEqualTo,
/// \u{2ab3}: '⪳'
PrecedesAboveEqualsSign,
/// \u{2ab4}: '⪴'
SucceedsAboveEqualsSign,
/// \u{2ab5}: '⪵'
PrecedesAboveNotEqualTo,
/// \u{2ab6}: '⪶'
SucceedsAboveNotEqualTo,
/// \u{2ab7}: '⪷'
PrecedesAboveAlmostEqualTo,
/// \u{2ab8}: '⪸'
SucceedsAboveAlmostEqualTo,
/// \u{2ab9}: '⪹'
PrecedesAboveNotAlmostEqualTo,
/// \u{2aba}: '⪺'
SucceedsAboveNotAlmostEqualTo,
/// \u{2abb}: '⪻'
DoublePrecedes,
/// \u{2abc}: '⪼'
DoubleSucceeds,
/// \u{2abd}: '⪽'
SubsetWithDot,
/// \u{2abe}: '⪾'
SupersetWithDot,
/// \u{2abf}: '⪿'
SubsetWithPlusSignBelow,
/// \u{2ac0}: '⫀'
SupersetWithPlusSignBelow,
/// \u{2ac1}: '⫁'
SubsetWithMultiplicationSignBelow,
/// \u{2ac2}: '⫂'
SupersetWithMultiplicationSignBelow,
/// \u{2ac3}: '⫃'
SubsetOfOrEqualToWithDotAbove,
/// \u{2ac4}: '⫄'
SupersetOfOrEqualToWithDotAbove,
/// \u{2ac5}: '⫅'
SubsetOfAboveEqualsSign,
/// \u{2ac6}: '⫆'
SupersetOfAboveEqualsSign,
/// \u{2ac7}: '⫇'
SubsetOfAboveTildeOperator,
/// \u{2ac8}: '⫈'
SupersetOfAboveTildeOperator,
/// \u{2ac9}: '⫉'
SubsetOfAboveAlmostEqualTo,
/// \u{2aca}: '⫊'
SupersetOfAboveAlmostEqualTo,
/// \u{2acb}: '⫋'
SubsetOfAboveNotEqualTo,
/// \u{2acc}: '⫌'
SupersetOfAboveNotEqualTo,
/// \u{2acd}: '⫍'
SquareLeftOpenBoxOperator,
/// \u{2ace}: '⫎'
SquareRightOpenBoxOperator,
/// \u{2acf}: '⫏'
ClosedSubset,
/// \u{2ad0}: '⫐'
ClosedSuperset,
/// \u{2ad1}: '⫑'
ClosedSubsetOrEqualTo,
/// \u{2ad2}: '⫒'
ClosedSupersetOrEqualTo,
/// \u{2ad3}: '⫓'
SubsetAboveSuperset,
/// \u{2ad4}: '⫔'
SupersetAboveSubset,
/// \u{2ad5}: '⫕'
SubsetAboveSubset,
/// \u{2ad6}: '⫖'
SupersetAboveSuperset,
/// \u{2ad7}: '⫗'
SupersetBesideSubset,
/// \u{2ad8}: '⫘'
SupersetBesideAndJoinedByDashWithSubset,
/// \u{2ad9}: '⫙'
ElementOfOpeningDownwards,
/// \u{2ada}: '⫚'
PitchforkWithTeeTop,
/// \u{2adb}: '⫛'
TransversalIntersection,
/// \u{2adc}: '⫝̸'
Forking,
/// \u{2add}: '⫝'
Nonforking,
/// \u{2ade}: '⫞'
ShortLeftTack,
/// \u{2adf}: '⫟'
ShortDownTack,
/// \u{2ae0}: '⫠'
ShortUpTack,
/// \u{2ae1}: '⫡'
PerpendicularWithS,
/// \u{2ae2}: '⫢'
VerticalBarTripleRightTurnstile,
/// \u{2ae3}: '⫣'
DoubleVerticalBarLeftTurnstile,
/// \u{2ae4}: '⫤'
VerticalBarDoubleLeftTurnstile,
/// \u{2ae5}: '⫥'
DoubleVerticalBarDoubleLeftTurnstile,
/// \u{2ae6}: '⫦'
LongDashFromLeftMemberOfDoubleVertical,
/// \u{2ae7}: '⫧'
ShortDownTackWithOverbar,
/// \u{2ae8}: '⫨'
ShortUpTackWithUnderbar,
/// \u{2ae9}: '⫩'
ShortUpTackAboveShortDownTack,
/// \u{2aea}: '⫪'
DoubleDownTack,
/// \u{2aeb}: '⫫'
DoubleUpTack,
/// \u{2aec}: '⫬'
DoubleStrokeNotSign,
/// \u{2aed}: '⫭'
ReversedDoubleStrokeNotSign,
/// \u{2aee}: '⫮'
DoesNotDivideWithReversedNegationSlash,
/// \u{2aef}: '⫯'
VerticalLineWithCircleAbove,
/// \u{2af0}: '⫰'
VerticalLineWithCircleBelow,
/// \u{2af1}: '⫱'
DownTackWithCircleBelow,
/// \u{2af2}: '⫲'
ParallelWithHorizontalStroke,
/// \u{2af3}: '⫳'
ParallelWithTildeOperator,
/// \u{2af4}: '⫴'
TripleVerticalBarBinaryRelation,
/// \u{2af5}: '⫵'
TripleVerticalBarWithHorizontalStroke,
/// \u{2af6}: '⫶'
TripleColonOperator,
/// \u{2af7}: '⫷'
TripleNestedLessDashThan,
/// \u{2af8}: '⫸'
TripleNestedGreaterDashThan,
/// \u{2af9}: '⫹'
DoubleDashLineSlantedLessDashThanOrEqualTo,
/// \u{2afa}: '⫺'
DoubleDashLineSlantedGreaterDashThanOrEqualTo,
/// \u{2afb}: '⫻'
TripleSolidusBinaryRelation,
/// \u{2afc}: '⫼'
LargeTripleVerticalBarOperator,
/// \u{2afd}: '⫽'
DoubleSolidusOperator,
/// \u{2afe}: '⫾'
WhiteVerticalBar,
}
impl Into<char> for SupplementalMathematicalOperators {
fn into(self) -> char {
match self {
SupplementalMathematicalOperators::NDashAryCircledDotOperator => '⨀',
SupplementalMathematicalOperators::NDashAryCircledPlusOperator => '⨁',
SupplementalMathematicalOperators::NDashAryCircledTimesOperator => '⨂',
SupplementalMathematicalOperators::NDashAryUnionOperatorWithDot => '⨃',
SupplementalMathematicalOperators::NDashAryUnionOperatorWithPlus => '⨄',
SupplementalMathematicalOperators::NDashArySquareIntersectionOperator => '⨅',
SupplementalMathematicalOperators::NDashArySquareUnionOperator => '⨆',
SupplementalMathematicalOperators::TwoLogicalAndOperator => '⨇',
SupplementalMathematicalOperators::TwoLogicalOrOperator => '⨈',
SupplementalMathematicalOperators::NDashAryTimesOperator => '⨉',
SupplementalMathematicalOperators::ModuloTwoSum => '⨊',
SupplementalMathematicalOperators::SummationWithIntegral => '⨋',
SupplementalMathematicalOperators::QuadrupleIntegralOperator => '⨌',
SupplementalMathematicalOperators::FinitePartIntegral => '⨍',
SupplementalMathematicalOperators::IntegralWithDoubleStroke => '⨎',
SupplementalMathematicalOperators::IntegralAverageWithSlash => '⨏',
SupplementalMathematicalOperators::CirculationFunction => '⨐',
SupplementalMathematicalOperators::AnticlockwiseIntegration => '⨑',
SupplementalMathematicalOperators::LineIntegrationWithRectangularPathAroundPole => '⨒',
SupplementalMathematicalOperators::LineIntegrationWithSemicircularPathAroundPole => '⨓',
SupplementalMathematicalOperators::LineIntegrationNotIncludingThePole => '⨔',
SupplementalMathematicalOperators::IntegralAroundAPointOperator => '⨕',
SupplementalMathematicalOperators::QuaternionIntegralOperator => '⨖',
SupplementalMathematicalOperators::IntegralWithLeftwardsArrowWithHook => '⨗',
SupplementalMathematicalOperators::IntegralWithTimesSign => '⨘',
SupplementalMathematicalOperators::IntegralWithIntersection => '⨙',
SupplementalMathematicalOperators::IntegralWithUnion => '⨚',
SupplementalMathematicalOperators::IntegralWithOverbar => '⨛',
SupplementalMathematicalOperators::IntegralWithUnderbar => '⨜',
SupplementalMathematicalOperators::Join => '⨝',
SupplementalMathematicalOperators::LargeLeftTriangleOperator => '⨞',
SupplementalMathematicalOperators::ZNotationSchemaComposition => '⨟',
SupplementalMathematicalOperators::ZNotationSchemaPiping => '⨠',
SupplementalMathematicalOperators::ZNotationSchemaProjection => '⨡',
SupplementalMathematicalOperators::PlusSignWithSmallCircleAbove => '⨢',
SupplementalMathematicalOperators::PlusSignWithCircumflexAccentAbove => '⨣',
SupplementalMathematicalOperators::PlusSignWithTildeAbove => '⨤',
SupplementalMathematicalOperators::PlusSignWithDotBelow => '⨥',
SupplementalMathematicalOperators::PlusSignWithTildeBelow => '⨦',
SupplementalMathematicalOperators::PlusSignWithSubscriptTwo => '⨧',
SupplementalMathematicalOperators::PlusSignWithBlackTriangle => '⨨',
SupplementalMathematicalOperators::MinusSignWithCommaAbove => '⨩',
SupplementalMathematicalOperators::MinusSignWithDotBelow => '⨪',
SupplementalMathematicalOperators::MinusSignWithFallingDots => '⨫',
SupplementalMathematicalOperators::MinusSignWithRisingDots => '⨬',
SupplementalMathematicalOperators::PlusSignInLeftHalfCircle => '⨭',
SupplementalMathematicalOperators::PlusSignInRightHalfCircle => '⨮',
SupplementalMathematicalOperators::VectorOrCrossProduct => '⨯',
SupplementalMathematicalOperators::MultiplicationSignWithDotAbove => '⨰',
SupplementalMathematicalOperators::MultiplicationSignWithUnderbar => '⨱',
SupplementalMathematicalOperators::SemidirectProductWithBottomClosed => '⨲',
SupplementalMathematicalOperators::SmashProduct => '⨳',
SupplementalMathematicalOperators::MultiplicationSignInLeftHalfCircle => '⨴',
SupplementalMathematicalOperators::MultiplicationSignInRightHalfCircle => '⨵',
SupplementalMathematicalOperators::CircledMultiplicationSignWithCircumflexAccent => '⨶',
SupplementalMathematicalOperators::MultiplicationSignInDoubleCircle => '⨷',
SupplementalMathematicalOperators::CircledDivisionSign => '⨸',
SupplementalMathematicalOperators::PlusSignInTriangle => '⨹',
SupplementalMathematicalOperators::MinusSignInTriangle => '⨺',
SupplementalMathematicalOperators::MultiplicationSignInTriangle => '⨻',
SupplementalMathematicalOperators::InteriorProduct => '⨼',
SupplementalMathematicalOperators::RighthandInteriorProduct => '⨽',
SupplementalMathematicalOperators::ZNotationRelationalComposition => '⨾',
SupplementalMathematicalOperators::AmalgamationOrCoproduct => '⨿',
SupplementalMathematicalOperators::IntersectionWithDot => '⩀',
SupplementalMathematicalOperators::UnionWithMinusSign => '⩁',
SupplementalMathematicalOperators::UnionWithOverbar => '⩂',
SupplementalMathematicalOperators::IntersectionWithOverbar => '⩃',
SupplementalMathematicalOperators::IntersectionWithLogicalAnd => '⩄',
SupplementalMathematicalOperators::UnionWithLogicalOr => '⩅',
SupplementalMathematicalOperators::UnionAboveIntersection => '⩆',
SupplementalMathematicalOperators::IntersectionAboveUnion => '⩇',
SupplementalMathematicalOperators::UnionAboveBarAboveIntersection => '⩈',
SupplementalMathematicalOperators::IntersectionAboveBarAboveUnion => '⩉',
SupplementalMathematicalOperators::UnionBesideAndJoinedWithUnion => '⩊',
SupplementalMathematicalOperators::IntersectionBesideAndJoinedWithIntersection => '⩋',
SupplementalMathematicalOperators::ClosedUnionWithSerifs => '⩌',
SupplementalMathematicalOperators::ClosedIntersectionWithSerifs => '⩍',
SupplementalMathematicalOperators::DoubleSquareIntersection => '⩎',
SupplementalMathematicalOperators::DoubleSquareUnion => '⩏',
SupplementalMathematicalOperators::ClosedUnionWithSerifsAndSmashProduct => '⩐',
SupplementalMathematicalOperators::LogicalAndWithDotAbove => '⩑',
SupplementalMathematicalOperators::LogicalOrWithDotAbove => '⩒',
SupplementalMathematicalOperators::DoubleLogicalAnd => '⩓',
SupplementalMathematicalOperators::DoubleLogicalOr => '⩔',
SupplementalMathematicalOperators::TwoIntersectingLogicalAnd => '⩕',
SupplementalMathematicalOperators::TwoIntersectingLogicalOr => '⩖',
SupplementalMathematicalOperators::SlopingLargeOr => '⩗',
SupplementalMathematicalOperators::SlopingLargeAnd => '⩘',
SupplementalMathematicalOperators::LogicalOrOverlappingLogicalAnd => '⩙',
SupplementalMathematicalOperators::LogicalAndWithMiddleStem => '⩚',
SupplementalMathematicalOperators::LogicalOrWithMiddleStem => '⩛',
SupplementalMathematicalOperators::LogicalAndWithHorizontalDash => '⩜',
SupplementalMathematicalOperators::LogicalOrWithHorizontalDash => '⩝',
SupplementalMathematicalOperators::LogicalAndWithDoubleOverbar => '⩞',
SupplementalMathematicalOperators::LogicalAndWithUnderbar => '⩟',
SupplementalMathematicalOperators::LogicalAndWithDoubleUnderbar => '⩠',
SupplementalMathematicalOperators::SmallVeeWithUnderbar => '⩡',
SupplementalMathematicalOperators::LogicalOrWithDoubleOverbar => '⩢',
SupplementalMathematicalOperators::LogicalOrWithDoubleUnderbar => '⩣',
SupplementalMathematicalOperators::ZNotationDomainAntirestriction => '⩤',
SupplementalMathematicalOperators::ZNotationRangeAntirestriction => '⩥',
SupplementalMathematicalOperators::EqualsSignWithDotBelow => '⩦',
SupplementalMathematicalOperators::IdenticalWithDotAbove => '⩧',
SupplementalMathematicalOperators::TripleHorizontalBarWithDoubleVerticalStroke => '⩨',
SupplementalMathematicalOperators::TripleHorizontalBarWithTripleVerticalStroke => '⩩',
SupplementalMathematicalOperators::TildeOperatorWithDotAbove => '⩪',
SupplementalMathematicalOperators::TildeOperatorWithRisingDots => '⩫',
SupplementalMathematicalOperators::SimilarMinusSimilar => '⩬',
SupplementalMathematicalOperators::CongruentWithDotAbove => '⩭',
SupplementalMathematicalOperators::EqualsWithAsterisk => '⩮',
SupplementalMathematicalOperators::AlmostEqualToWithCircumflexAccent => '⩯',
SupplementalMathematicalOperators::ApproximatelyEqualOrEqualTo => '⩰',
SupplementalMathematicalOperators::EqualsSignAbovePlusSign => '⩱',
SupplementalMathematicalOperators::PlusSignAboveEqualsSign => '⩲',
SupplementalMathematicalOperators::EqualsSignAboveTildeOperator => '⩳',
SupplementalMathematicalOperators::DoubleColonEqual => '⩴',
SupplementalMathematicalOperators::TwoConsecutiveEqualsSigns => '⩵',
SupplementalMathematicalOperators::ThreeConsecutiveEqualsSigns => '⩶',
SupplementalMathematicalOperators::EqualsSignWithTwoDotsAboveAndTwoDotsBelow => '⩷',
SupplementalMathematicalOperators::EquivalentWithFourDotsAbove => '⩸',
SupplementalMathematicalOperators::LessDashThanWithCircleInside => '⩹',
SupplementalMathematicalOperators::GreaterDashThanWithCircleInside => '⩺',
SupplementalMathematicalOperators::LessDashThanWithQuestionMarkAbove => '⩻',
SupplementalMathematicalOperators::GreaterDashThanWithQuestionMarkAbove => '⩼',
SupplementalMathematicalOperators::LessDashThanOrSlantedEqualTo => '⩽',
SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualTo => '⩾',
SupplementalMathematicalOperators::LessDashThanOrSlantedEqualToWithDotInside => '⩿',
SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualToWithDotInside => '⪀',
SupplementalMathematicalOperators::LessDashThanOrSlantedEqualToWithDotAbove => '⪁',
SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualToWithDotAbove => '⪂',
SupplementalMathematicalOperators::LessDashThanOrSlantedEqualToWithDotAboveRight => '⪃',
SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualToWithDotAboveLeft => '⪄',
SupplementalMathematicalOperators::LessDashThanOrApproximate => '⪅',
SupplementalMathematicalOperators::GreaterDashThanOrApproximate => '⪆',
SupplementalMathematicalOperators::LessDashThanAndSingleDashLineNotEqualTo => '⪇',
SupplementalMathematicalOperators::GreaterDashThanAndSingleDashLineNotEqualTo => '⪈',
SupplementalMathematicalOperators::LessDashThanAndNotApproximate => '⪉',
SupplementalMathematicalOperators::GreaterDashThanAndNotApproximate => '⪊',
SupplementalMathematicalOperators::LessDashThanAboveDoubleDashLineEqualAboveGreaterDashThan => '⪋',
SupplementalMathematicalOperators::GreaterDashThanAboveDoubleDashLineEqualAboveLessDashThan => '⪌',
SupplementalMathematicalOperators::LessDashThanAboveSimilarOrEqual => '⪍',
SupplementalMathematicalOperators::GreaterDashThanAboveSimilarOrEqual => '⪎',
SupplementalMathematicalOperators::LessDashThanAboveSimilarAboveGreaterDashThan => '⪏',
SupplementalMathematicalOperators::GreaterDashThanAboveSimilarAboveLessDashThan => '⪐',
SupplementalMathematicalOperators::LessDashThanAboveGreaterDashThanAboveDoubleDashLineEqual => '⪑',
SupplementalMathematicalOperators::GreaterDashThanAboveLessDashThanAboveDoubleDashLineEqual => '⪒',
SupplementalMathematicalOperators::LessDashThanAboveSlantedEqualAboveGreaterDashThanAboveSlantedEqual => '⪓',
SupplementalMathematicalOperators::GreaterDashThanAboveSlantedEqualAboveLessDashThanAboveSlantedEqual => '⪔',
SupplementalMathematicalOperators::SlantedEqualToOrLessDashThan => '⪕',
SupplementalMathematicalOperators::SlantedEqualToOrGreaterDashThan => '⪖',
SupplementalMathematicalOperators::SlantedEqualToOrLessDashThanWithDotInside => '⪗',
SupplementalMathematicalOperators::SlantedEqualToOrGreaterDashThanWithDotInside => '⪘',
SupplementalMathematicalOperators::DoubleDashLineEqualToOrLessDashThan => '⪙',
SupplementalMathematicalOperators::DoubleDashLineEqualToOrGreaterDashThan => '⪚',
SupplementalMathematicalOperators::DoubleDashLineSlantedEqualToOrLessDashThan => '⪛',
SupplementalMathematicalOperators::DoubleDashLineSlantedEqualToOrGreaterDashThan => '⪜',
SupplementalMathematicalOperators::SimilarOrLessDashThan => '⪝',
SupplementalMathematicalOperators::SimilarOrGreaterDashThan => '⪞',
SupplementalMathematicalOperators::SimilarAboveLessDashThanAboveEqualsSign => '⪟',
SupplementalMathematicalOperators::SimilarAboveGreaterDashThanAboveEqualsSign => '⪠',
SupplementalMathematicalOperators::DoubleNestedLessDashThan => '⪡',
SupplementalMathematicalOperators::DoubleNestedGreaterDashThan => '⪢',
SupplementalMathematicalOperators::DoubleNestedLessDashThanWithUnderbar => '⪣',
SupplementalMathematicalOperators::GreaterDashThanOverlappingLessDashThan => '⪤',
SupplementalMathematicalOperators::GreaterDashThanBesideLessDashThan => '⪥',
SupplementalMathematicalOperators::LessDashThanClosedByCurve => '⪦',
SupplementalMathematicalOperators::GreaterDashThanClosedByCurve => '⪧',
SupplementalMathematicalOperators::LessDashThanClosedByCurveAboveSlantedEqual => '⪨',
SupplementalMathematicalOperators::GreaterDashThanClosedByCurveAboveSlantedEqual => '⪩',
SupplementalMathematicalOperators::SmallerThan => '⪪',
SupplementalMathematicalOperators::LargerThan => '⪫',
SupplementalMathematicalOperators::SmallerThanOrEqualTo => '⪬',
SupplementalMathematicalOperators::LargerThanOrEqualTo => '⪭',
SupplementalMathematicalOperators::EqualsSignWithBumpyAbove => '⪮',
SupplementalMathematicalOperators::PrecedesAboveSingleDashLineEqualsSign => '⪯',
SupplementalMathematicalOperators::SucceedsAboveSingleDashLineEqualsSign => '⪰',
SupplementalMathematicalOperators::PrecedesAboveSingleDashLineNotEqualTo => '⪱',
SupplementalMathematicalOperators::SucceedsAboveSingleDashLineNotEqualTo => '⪲',
SupplementalMathematicalOperators::PrecedesAboveEqualsSign => '⪳',
SupplementalMathematicalOperators::SucceedsAboveEqualsSign => '⪴',
SupplementalMathematicalOperators::PrecedesAboveNotEqualTo => '⪵',
SupplementalMathematicalOperators::SucceedsAboveNotEqualTo => '⪶',
SupplementalMathematicalOperators::PrecedesAboveAlmostEqualTo => '⪷',
SupplementalMathematicalOperators::SucceedsAboveAlmostEqualTo => '⪸',
SupplementalMathematicalOperators::PrecedesAboveNotAlmostEqualTo => '⪹',
SupplementalMathematicalOperators::SucceedsAboveNotAlmostEqualTo => '⪺',
SupplementalMathematicalOperators::DoublePrecedes => '⪻',
SupplementalMathematicalOperators::DoubleSucceeds => '⪼',
SupplementalMathematicalOperators::SubsetWithDot => '⪽',
SupplementalMathematicalOperators::SupersetWithDot => '⪾',
SupplementalMathematicalOperators::SubsetWithPlusSignBelow => '⪿',
SupplementalMathematicalOperators::SupersetWithPlusSignBelow => '⫀',
SupplementalMathematicalOperators::SubsetWithMultiplicationSignBelow => '⫁',
SupplementalMathematicalOperators::SupersetWithMultiplicationSignBelow => '⫂',
SupplementalMathematicalOperators::SubsetOfOrEqualToWithDotAbove => '⫃',
SupplementalMathematicalOperators::SupersetOfOrEqualToWithDotAbove => '⫄',
SupplementalMathematicalOperators::SubsetOfAboveEqualsSign => '⫅',
SupplementalMathematicalOperators::SupersetOfAboveEqualsSign => '⫆',
SupplementalMathematicalOperators::SubsetOfAboveTildeOperator => '⫇',
SupplementalMathematicalOperators::SupersetOfAboveTildeOperator => '⫈',
SupplementalMathematicalOperators::SubsetOfAboveAlmostEqualTo => '⫉',
SupplementalMathematicalOperators::SupersetOfAboveAlmostEqualTo => '⫊',
SupplementalMathematicalOperators::SubsetOfAboveNotEqualTo => '⫋',
SupplementalMathematicalOperators::SupersetOfAboveNotEqualTo => '⫌',
SupplementalMathematicalOperators::SquareLeftOpenBoxOperator => '⫍',
SupplementalMathematicalOperators::SquareRightOpenBoxOperator => '⫎',
SupplementalMathematicalOperators::ClosedSubset => '⫏',
SupplementalMathematicalOperators::ClosedSuperset => '⫐',
SupplementalMathematicalOperators::ClosedSubsetOrEqualTo => '⫑',
SupplementalMathematicalOperators::ClosedSupersetOrEqualTo => '⫒',
SupplementalMathematicalOperators::SubsetAboveSuperset => '⫓',
SupplementalMathematicalOperators::SupersetAboveSubset => '⫔',
SupplementalMathematicalOperators::SubsetAboveSubset => '⫕',
SupplementalMathematicalOperators::SupersetAboveSuperset => '⫖',
SupplementalMathematicalOperators::SupersetBesideSubset => '⫗',
SupplementalMathematicalOperators::SupersetBesideAndJoinedByDashWithSubset => '⫘',
SupplementalMathematicalOperators::ElementOfOpeningDownwards => '⫙',
SupplementalMathematicalOperators::PitchforkWithTeeTop => '⫚',
SupplementalMathematicalOperators::TransversalIntersection => '⫛',
SupplementalMathematicalOperators::Forking => '⫝̸',
SupplementalMathematicalOperators::Nonforking => '⫝',
SupplementalMathematicalOperators::ShortLeftTack => '⫞',
SupplementalMathematicalOperators::ShortDownTack => '⫟',
SupplementalMathematicalOperators::ShortUpTack => '⫠',
SupplementalMathematicalOperators::PerpendicularWithS => '⫡',
SupplementalMathematicalOperators::VerticalBarTripleRightTurnstile => '⫢',
SupplementalMathematicalOperators::DoubleVerticalBarLeftTurnstile => '⫣',
SupplementalMathematicalOperators::VerticalBarDoubleLeftTurnstile => '⫤',
SupplementalMathematicalOperators::DoubleVerticalBarDoubleLeftTurnstile => '⫥',
SupplementalMathematicalOperators::LongDashFromLeftMemberOfDoubleVertical => '⫦',
SupplementalMathematicalOperators::ShortDownTackWithOverbar => '⫧',
SupplementalMathematicalOperators::ShortUpTackWithUnderbar => '⫨',
SupplementalMathematicalOperators::ShortUpTackAboveShortDownTack => '⫩',
SupplementalMathematicalOperators::DoubleDownTack => '⫪',
SupplementalMathematicalOperators::DoubleUpTack => '⫫',
SupplementalMathematicalOperators::DoubleStrokeNotSign => '⫬',
SupplementalMathematicalOperators::ReversedDoubleStrokeNotSign => '⫭',
SupplementalMathematicalOperators::DoesNotDivideWithReversedNegationSlash => '⫮',
SupplementalMathematicalOperators::VerticalLineWithCircleAbove => '⫯',
SupplementalMathematicalOperators::VerticalLineWithCircleBelow => '⫰',
SupplementalMathematicalOperators::DownTackWithCircleBelow => '⫱',
SupplementalMathematicalOperators::ParallelWithHorizontalStroke => '⫲',
SupplementalMathematicalOperators::ParallelWithTildeOperator => '⫳',
SupplementalMathematicalOperators::TripleVerticalBarBinaryRelation => '⫴',
SupplementalMathematicalOperators::TripleVerticalBarWithHorizontalStroke => '⫵',
SupplementalMathematicalOperators::TripleColonOperator => '⫶',
SupplementalMathematicalOperators::TripleNestedLessDashThan => '⫷',
SupplementalMathematicalOperators::TripleNestedGreaterDashThan => '⫸',
SupplementalMathematicalOperators::DoubleDashLineSlantedLessDashThanOrEqualTo => '⫹',
SupplementalMathematicalOperators::DoubleDashLineSlantedGreaterDashThanOrEqualTo => '⫺',
SupplementalMathematicalOperators::TripleSolidusBinaryRelation => '⫻',
SupplementalMathematicalOperators::LargeTripleVerticalBarOperator => '⫼',
SupplementalMathematicalOperators::DoubleSolidusOperator => '⫽',
SupplementalMathematicalOperators::WhiteVerticalBar => '⫾',
}
}
}
impl std::convert::TryFrom<char> for SupplementalMathematicalOperators {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'⨀' => Ok(SupplementalMathematicalOperators::NDashAryCircledDotOperator),
'⨁' => Ok(SupplementalMathematicalOperators::NDashAryCircledPlusOperator),
'⨂' => Ok(SupplementalMathematicalOperators::NDashAryCircledTimesOperator),
'⨃' => Ok(SupplementalMathematicalOperators::NDashAryUnionOperatorWithDot),
'⨄' => Ok(SupplementalMathematicalOperators::NDashAryUnionOperatorWithPlus),
'⨅' => Ok(SupplementalMathematicalOperators::NDashArySquareIntersectionOperator),
'⨆' => Ok(SupplementalMathematicalOperators::NDashArySquareUnionOperator),
'⨇' => Ok(SupplementalMathematicalOperators::TwoLogicalAndOperator),
'⨈' => Ok(SupplementalMathematicalOperators::TwoLogicalOrOperator),
'⨉' => Ok(SupplementalMathematicalOperators::NDashAryTimesOperator),
'⨊' => Ok(SupplementalMathematicalOperators::ModuloTwoSum),
'⨋' => Ok(SupplementalMathematicalOperators::SummationWithIntegral),
'⨌' => Ok(SupplementalMathematicalOperators::QuadrupleIntegralOperator),
'⨍' => Ok(SupplementalMathematicalOperators::FinitePartIntegral),
'⨎' => Ok(SupplementalMathematicalOperators::IntegralWithDoubleStroke),
'⨏' => Ok(SupplementalMathematicalOperators::IntegralAverageWithSlash),
'⨐' => Ok(SupplementalMathematicalOperators::CirculationFunction),
'⨑' => Ok(SupplementalMathematicalOperators::AnticlockwiseIntegration),
'⨒' => Ok(SupplementalMathematicalOperators::LineIntegrationWithRectangularPathAroundPole),
'⨓' => Ok(SupplementalMathematicalOperators::LineIntegrationWithSemicircularPathAroundPole),
'⨔' => Ok(SupplementalMathematicalOperators::LineIntegrationNotIncludingThePole),
'⨕' => Ok(SupplementalMathematicalOperators::IntegralAroundAPointOperator),
'⨖' => Ok(SupplementalMathematicalOperators::QuaternionIntegralOperator),
'⨗' => Ok(SupplementalMathematicalOperators::IntegralWithLeftwardsArrowWithHook),
'⨘' => Ok(SupplementalMathematicalOperators::IntegralWithTimesSign),
'⨙' => Ok(SupplementalMathematicalOperators::IntegralWithIntersection),
'⨚' => Ok(SupplementalMathematicalOperators::IntegralWithUnion),
'⨛' => Ok(SupplementalMathematicalOperators::IntegralWithOverbar),
'⨜' => Ok(SupplementalMathematicalOperators::IntegralWithUnderbar),
'⨝' => Ok(SupplementalMathematicalOperators::Join),
'⨞' => Ok(SupplementalMathematicalOperators::LargeLeftTriangleOperator),
'⨟' => Ok(SupplementalMathematicalOperators::ZNotationSchemaComposition),
'⨠' => Ok(SupplementalMathematicalOperators::ZNotationSchemaPiping),
'⨡' => Ok(SupplementalMathematicalOperators::ZNotationSchemaProjection),
'⨢' => Ok(SupplementalMathematicalOperators::PlusSignWithSmallCircleAbove),
'⨣' => Ok(SupplementalMathematicalOperators::PlusSignWithCircumflexAccentAbove),
'⨤' => Ok(SupplementalMathematicalOperators::PlusSignWithTildeAbove),
'⨥' => Ok(SupplementalMathematicalOperators::PlusSignWithDotBelow),
'⨦' => Ok(SupplementalMathematicalOperators::PlusSignWithTildeBelow),
'⨧' => Ok(SupplementalMathematicalOperators::PlusSignWithSubscriptTwo),
'⨨' => Ok(SupplementalMathematicalOperators::PlusSignWithBlackTriangle),
'⨩' => Ok(SupplementalMathematicalOperators::MinusSignWithCommaAbove),
'⨪' => Ok(SupplementalMathematicalOperators::MinusSignWithDotBelow),
'⨫' => Ok(SupplementalMathematicalOperators::MinusSignWithFallingDots),
'⨬' => Ok(SupplementalMathematicalOperators::MinusSignWithRisingDots),
'⨭' => Ok(SupplementalMathematicalOperators::PlusSignInLeftHalfCircle),
'⨮' => Ok(SupplementalMathematicalOperators::PlusSignInRightHalfCircle),
'⨯' => Ok(SupplementalMathematicalOperators::VectorOrCrossProduct),
'⨰' => Ok(SupplementalMathematicalOperators::MultiplicationSignWithDotAbove),
'⨱' => Ok(SupplementalMathematicalOperators::MultiplicationSignWithUnderbar),
'⨲' => Ok(SupplementalMathematicalOperators::SemidirectProductWithBottomClosed),
'⨳' => Ok(SupplementalMathematicalOperators::SmashProduct),
'⨴' => Ok(SupplementalMathematicalOperators::MultiplicationSignInLeftHalfCircle),
'⨵' => Ok(SupplementalMathematicalOperators::MultiplicationSignInRightHalfCircle),
'⨶' => Ok(SupplementalMathematicalOperators::CircledMultiplicationSignWithCircumflexAccent),
'⨷' => Ok(SupplementalMathematicalOperators::MultiplicationSignInDoubleCircle),
'⨸' => Ok(SupplementalMathematicalOperators::CircledDivisionSign),
'⨹' => Ok(SupplementalMathematicalOperators::PlusSignInTriangle),
'⨺' => Ok(SupplementalMathematicalOperators::MinusSignInTriangle),
'⨻' => Ok(SupplementalMathematicalOperators::MultiplicationSignInTriangle),
'⨼' => Ok(SupplementalMathematicalOperators::InteriorProduct),
'⨽' => Ok(SupplementalMathematicalOperators::RighthandInteriorProduct),
'⨾' => Ok(SupplementalMathematicalOperators::ZNotationRelationalComposition),
'⨿' => Ok(SupplementalMathematicalOperators::AmalgamationOrCoproduct),
'⩀' => Ok(SupplementalMathematicalOperators::IntersectionWithDot),
'⩁' => Ok(SupplementalMathematicalOperators::UnionWithMinusSign),
'⩂' => Ok(SupplementalMathematicalOperators::UnionWithOverbar),
'⩃' => Ok(SupplementalMathematicalOperators::IntersectionWithOverbar),
'⩄' => Ok(SupplementalMathematicalOperators::IntersectionWithLogicalAnd),
'⩅' => Ok(SupplementalMathematicalOperators::UnionWithLogicalOr),
'⩆' => Ok(SupplementalMathematicalOperators::UnionAboveIntersection),
'⩇' => Ok(SupplementalMathematicalOperators::IntersectionAboveUnion),
'⩈' => Ok(SupplementalMathematicalOperators::UnionAboveBarAboveIntersection),
'⩉' => Ok(SupplementalMathematicalOperators::IntersectionAboveBarAboveUnion),
'⩊' => Ok(SupplementalMathematicalOperators::UnionBesideAndJoinedWithUnion),
'⩋' => Ok(SupplementalMathematicalOperators::IntersectionBesideAndJoinedWithIntersection),
'⩌' => Ok(SupplementalMathematicalOperators::ClosedUnionWithSerifs),
'⩍' => Ok(SupplementalMathematicalOperators::ClosedIntersectionWithSerifs),
'⩎' => Ok(SupplementalMathematicalOperators::DoubleSquareIntersection),
'⩏' => Ok(SupplementalMathematicalOperators::DoubleSquareUnion),
'⩐' => Ok(SupplementalMathematicalOperators::ClosedUnionWithSerifsAndSmashProduct),
'⩑' => Ok(SupplementalMathematicalOperators::LogicalAndWithDotAbove),
'⩒' => Ok(SupplementalMathematicalOperators::LogicalOrWithDotAbove),
'⩓' => Ok(SupplementalMathematicalOperators::DoubleLogicalAnd),
'⩔' => Ok(SupplementalMathematicalOperators::DoubleLogicalOr),
'⩕' => Ok(SupplementalMathematicalOperators::TwoIntersectingLogicalAnd),
'⩖' => Ok(SupplementalMathematicalOperators::TwoIntersectingLogicalOr),
'⩗' => Ok(SupplementalMathematicalOperators::SlopingLargeOr),
'⩘' => Ok(SupplementalMathematicalOperators::SlopingLargeAnd),
'⩙' => Ok(SupplementalMathematicalOperators::LogicalOrOverlappingLogicalAnd),
'⩚' => Ok(SupplementalMathematicalOperators::LogicalAndWithMiddleStem),
'⩛' => Ok(SupplementalMathematicalOperators::LogicalOrWithMiddleStem),
'⩜' => Ok(SupplementalMathematicalOperators::LogicalAndWithHorizontalDash),
'⩝' => Ok(SupplementalMathematicalOperators::LogicalOrWithHorizontalDash),
'⩞' => Ok(SupplementalMathematicalOperators::LogicalAndWithDoubleOverbar),
'⩟' => Ok(SupplementalMathematicalOperators::LogicalAndWithUnderbar),
'⩠' => Ok(SupplementalMathematicalOperators::LogicalAndWithDoubleUnderbar),
'⩡' => Ok(SupplementalMathematicalOperators::SmallVeeWithUnderbar),
'⩢' => Ok(SupplementalMathematicalOperators::LogicalOrWithDoubleOverbar),
'⩣' => Ok(SupplementalMathematicalOperators::LogicalOrWithDoubleUnderbar),
'⩤' => Ok(SupplementalMathematicalOperators::ZNotationDomainAntirestriction),
'⩥' => Ok(SupplementalMathematicalOperators::ZNotationRangeAntirestriction),
'⩦' => Ok(SupplementalMathematicalOperators::EqualsSignWithDotBelow),
'⩧' => Ok(SupplementalMathematicalOperators::IdenticalWithDotAbove),
'⩨' => Ok(SupplementalMathematicalOperators::TripleHorizontalBarWithDoubleVerticalStroke),
'⩩' => Ok(SupplementalMathematicalOperators::TripleHorizontalBarWithTripleVerticalStroke),
'⩪' => Ok(SupplementalMathematicalOperators::TildeOperatorWithDotAbove),
'⩫' => Ok(SupplementalMathematicalOperators::TildeOperatorWithRisingDots),
'⩬' => Ok(SupplementalMathematicalOperators::SimilarMinusSimilar),
'⩭' => Ok(SupplementalMathematicalOperators::CongruentWithDotAbove),
'⩮' => Ok(SupplementalMathematicalOperators::EqualsWithAsterisk),
'⩯' => Ok(SupplementalMathematicalOperators::AlmostEqualToWithCircumflexAccent),
'⩰' => Ok(SupplementalMathematicalOperators::ApproximatelyEqualOrEqualTo),
'⩱' => Ok(SupplementalMathematicalOperators::EqualsSignAbovePlusSign),
'⩲' => Ok(SupplementalMathematicalOperators::PlusSignAboveEqualsSign),
'⩳' => Ok(SupplementalMathematicalOperators::EqualsSignAboveTildeOperator),
'⩴' => Ok(SupplementalMathematicalOperators::DoubleColonEqual),
'⩵' => Ok(SupplementalMathematicalOperators::TwoConsecutiveEqualsSigns),
'⩶' => Ok(SupplementalMathematicalOperators::ThreeConsecutiveEqualsSigns),
'⩷' => Ok(SupplementalMathematicalOperators::EqualsSignWithTwoDotsAboveAndTwoDotsBelow),
'⩸' => Ok(SupplementalMathematicalOperators::EquivalentWithFourDotsAbove),
'⩹' => Ok(SupplementalMathematicalOperators::LessDashThanWithCircleInside),
'⩺' => Ok(SupplementalMathematicalOperators::GreaterDashThanWithCircleInside),
'⩻' => Ok(SupplementalMathematicalOperators::LessDashThanWithQuestionMarkAbove),
'⩼' => Ok(SupplementalMathematicalOperators::GreaterDashThanWithQuestionMarkAbove),
'⩽' => Ok(SupplementalMathematicalOperators::LessDashThanOrSlantedEqualTo),
'⩾' => Ok(SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualTo),
'⩿' => Ok(SupplementalMathematicalOperators::LessDashThanOrSlantedEqualToWithDotInside),
'⪀' => Ok(SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualToWithDotInside),
'⪁' => Ok(SupplementalMathematicalOperators::LessDashThanOrSlantedEqualToWithDotAbove),
'⪂' => Ok(SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualToWithDotAbove),
'⪃' => Ok(SupplementalMathematicalOperators::LessDashThanOrSlantedEqualToWithDotAboveRight),
'⪄' => Ok(SupplementalMathematicalOperators::GreaterDashThanOrSlantedEqualToWithDotAboveLeft),
'⪅' => Ok(SupplementalMathematicalOperators::LessDashThanOrApproximate),
'⪆' => Ok(SupplementalMathematicalOperators::GreaterDashThanOrApproximate),
'⪇' => Ok(SupplementalMathematicalOperators::LessDashThanAndSingleDashLineNotEqualTo),
'⪈' => Ok(SupplementalMathematicalOperators::GreaterDashThanAndSingleDashLineNotEqualTo),
'⪉' => Ok(SupplementalMathematicalOperators::LessDashThanAndNotApproximate),
'⪊' => Ok(SupplementalMathematicalOperators::GreaterDashThanAndNotApproximate),
'⪋' => Ok(SupplementalMathematicalOperators::LessDashThanAboveDoubleDashLineEqualAboveGreaterDashThan),
'⪌' => Ok(SupplementalMathematicalOperators::GreaterDashThanAboveDoubleDashLineEqualAboveLessDashThan),
'⪍' => Ok(SupplementalMathematicalOperators::LessDashThanAboveSimilarOrEqual),
'⪎' => Ok(SupplementalMathematicalOperators::GreaterDashThanAboveSimilarOrEqual),
'⪏' => Ok(SupplementalMathematicalOperators::LessDashThanAboveSimilarAboveGreaterDashThan),
'⪐' => Ok(SupplementalMathematicalOperators::GreaterDashThanAboveSimilarAboveLessDashThan),
'⪑' => Ok(SupplementalMathematicalOperators::LessDashThanAboveGreaterDashThanAboveDoubleDashLineEqual),
'⪒' => Ok(SupplementalMathematicalOperators::GreaterDashThanAboveLessDashThanAboveDoubleDashLineEqual),
'⪓' => Ok(SupplementalMathematicalOperators::LessDashThanAboveSlantedEqualAboveGreaterDashThanAboveSlantedEqual),
'⪔' => Ok(SupplementalMathematicalOperators::GreaterDashThanAboveSlantedEqualAboveLessDashThanAboveSlantedEqual),
'⪕' => Ok(SupplementalMathematicalOperators::SlantedEqualToOrLessDashThan),
'⪖' => Ok(SupplementalMathematicalOperators::SlantedEqualToOrGreaterDashThan),
'⪗' => Ok(SupplementalMathematicalOperators::SlantedEqualToOrLessDashThanWithDotInside),
'⪘' => Ok(SupplementalMathematicalOperators::SlantedEqualToOrGreaterDashThanWithDotInside),
'⪙' => Ok(SupplementalMathematicalOperators::DoubleDashLineEqualToOrLessDashThan),
'⪚' => Ok(SupplementalMathematicalOperators::DoubleDashLineEqualToOrGreaterDashThan),
'⪛' => Ok(SupplementalMathematicalOperators::DoubleDashLineSlantedEqualToOrLessDashThan),
'⪜' => Ok(SupplementalMathematicalOperators::DoubleDashLineSlantedEqualToOrGreaterDashThan),
'⪝' => Ok(SupplementalMathematicalOperators::SimilarOrLessDashThan),
'⪞' => Ok(SupplementalMathematicalOperators::SimilarOrGreaterDashThan),
'⪟' => Ok(SupplementalMathematicalOperators::SimilarAboveLessDashThanAboveEqualsSign),
'⪠' => Ok(SupplementalMathematicalOperators::SimilarAboveGreaterDashThanAboveEqualsSign),
'⪡' => Ok(SupplementalMathematicalOperators::DoubleNestedLessDashThan),
'⪢' => Ok(SupplementalMathematicalOperators::DoubleNestedGreaterDashThan),
'⪣' => Ok(SupplementalMathematicalOperators::DoubleNestedLessDashThanWithUnderbar),
'⪤' => Ok(SupplementalMathematicalOperators::GreaterDashThanOverlappingLessDashThan),
'⪥' => Ok(SupplementalMathematicalOperators::GreaterDashThanBesideLessDashThan),
'⪦' => Ok(SupplementalMathematicalOperators::LessDashThanClosedByCurve),
'⪧' => Ok(SupplementalMathematicalOperators::GreaterDashThanClosedByCurve),
'⪨' => Ok(SupplementalMathematicalOperators::LessDashThanClosedByCurveAboveSlantedEqual),
'⪩' => Ok(SupplementalMathematicalOperators::GreaterDashThanClosedByCurveAboveSlantedEqual),
'⪪' => Ok(SupplementalMathematicalOperators::SmallerThan),
'⪫' => Ok(SupplementalMathematicalOperators::LargerThan),
'⪬' => Ok(SupplementalMathematicalOperators::SmallerThanOrEqualTo),
'⪭' => Ok(SupplementalMathematicalOperators::LargerThanOrEqualTo),
'⪮' => Ok(SupplementalMathematicalOperators::EqualsSignWithBumpyAbove),
'⪯' => Ok(SupplementalMathematicalOperators::PrecedesAboveSingleDashLineEqualsSign),
'⪰' => Ok(SupplementalMathematicalOperators::SucceedsAboveSingleDashLineEqualsSign),
'⪱' => Ok(SupplementalMathematicalOperators::PrecedesAboveSingleDashLineNotEqualTo),
'⪲' => Ok(SupplementalMathematicalOperators::SucceedsAboveSingleDashLineNotEqualTo),
'⪳' => Ok(SupplementalMathematicalOperators::PrecedesAboveEqualsSign),
'⪴' => Ok(SupplementalMathematicalOperators::SucceedsAboveEqualsSign),
'⪵' => Ok(SupplementalMathematicalOperators::PrecedesAboveNotEqualTo),
'⪶' => Ok(SupplementalMathematicalOperators::SucceedsAboveNotEqualTo),
'⪷' => Ok(SupplementalMathematicalOperators::PrecedesAboveAlmostEqualTo),
'⪸' => Ok(SupplementalMathematicalOperators::SucceedsAboveAlmostEqualTo),
'⪹' => Ok(SupplementalMathematicalOperators::PrecedesAboveNotAlmostEqualTo),
'⪺' => Ok(SupplementalMathematicalOperators::SucceedsAboveNotAlmostEqualTo),
'⪻' => Ok(SupplementalMathematicalOperators::DoublePrecedes),
'⪼' => Ok(SupplementalMathematicalOperators::DoubleSucceeds),
'⪽' => Ok(SupplementalMathematicalOperators::SubsetWithDot),
'⪾' => Ok(SupplementalMathematicalOperators::SupersetWithDot),
'⪿' => Ok(SupplementalMathematicalOperators::SubsetWithPlusSignBelow),
'⫀' => Ok(SupplementalMathematicalOperators::SupersetWithPlusSignBelow),
'⫁' => Ok(SupplementalMathematicalOperators::SubsetWithMultiplicationSignBelow),
'⫂' => Ok(SupplementalMathematicalOperators::SupersetWithMultiplicationSignBelow),
'⫃' => Ok(SupplementalMathematicalOperators::SubsetOfOrEqualToWithDotAbove),
'⫄' => Ok(SupplementalMathematicalOperators::SupersetOfOrEqualToWithDotAbove),
'⫅' => Ok(SupplementalMathematicalOperators::SubsetOfAboveEqualsSign),
'⫆' => Ok(SupplementalMathematicalOperators::SupersetOfAboveEqualsSign),
'⫇' => Ok(SupplementalMathematicalOperators::SubsetOfAboveTildeOperator),
'⫈' => Ok(SupplementalMathematicalOperators::SupersetOfAboveTildeOperator),
'⫉' => Ok(SupplementalMathematicalOperators::SubsetOfAboveAlmostEqualTo),
'⫊' => Ok(SupplementalMathematicalOperators::SupersetOfAboveAlmostEqualTo),
'⫋' => Ok(SupplementalMathematicalOperators::SubsetOfAboveNotEqualTo),
'⫌' => Ok(SupplementalMathematicalOperators::SupersetOfAboveNotEqualTo),
'⫍' => Ok(SupplementalMathematicalOperators::SquareLeftOpenBoxOperator),
'⫎' => Ok(SupplementalMathematicalOperators::SquareRightOpenBoxOperator),
'⫏' => Ok(SupplementalMathematicalOperators::ClosedSubset),
'⫐' => Ok(SupplementalMathematicalOperators::ClosedSuperset),
'⫑' => Ok(SupplementalMathematicalOperators::ClosedSubsetOrEqualTo),
'⫒' => Ok(SupplementalMathematicalOperators::ClosedSupersetOrEqualTo),
'⫓' => Ok(SupplementalMathematicalOperators::SubsetAboveSuperset),
'⫔' => Ok(SupplementalMathematicalOperators::SupersetAboveSubset),
'⫕' => Ok(SupplementalMathematicalOperators::SubsetAboveSubset),
'⫖' => Ok(SupplementalMathematicalOperators::SupersetAboveSuperset),
'⫗' => Ok(SupplementalMathematicalOperators::SupersetBesideSubset),
'⫘' => Ok(SupplementalMathematicalOperators::SupersetBesideAndJoinedByDashWithSubset),
'⫙' => Ok(SupplementalMathematicalOperators::ElementOfOpeningDownwards),
'⫚' => Ok(SupplementalMathematicalOperators::PitchforkWithTeeTop),
'⫛' => Ok(SupplementalMathematicalOperators::TransversalIntersection),
'⫝̸' => Ok(SupplementalMathematicalOperators::Forking),
'⫝' => Ok(SupplementalMathematicalOperators::Nonforking),
'⫞' => Ok(SupplementalMathematicalOperators::ShortLeftTack),
'⫟' => Ok(SupplementalMathematicalOperators::ShortDownTack),
'⫠' => Ok(SupplementalMathematicalOperators::ShortUpTack),
'⫡' => Ok(SupplementalMathematicalOperators::PerpendicularWithS),
'⫢' => Ok(SupplementalMathematicalOperators::VerticalBarTripleRightTurnstile),
'⫣' => Ok(SupplementalMathematicalOperators::DoubleVerticalBarLeftTurnstile),
'⫤' => Ok(SupplementalMathematicalOperators::VerticalBarDoubleLeftTurnstile),
'⫥' => Ok(SupplementalMathematicalOperators::DoubleVerticalBarDoubleLeftTurnstile),
'⫦' => Ok(SupplementalMathematicalOperators::LongDashFromLeftMemberOfDoubleVertical),
'⫧' => Ok(SupplementalMathematicalOperators::ShortDownTackWithOverbar),
'⫨' => Ok(SupplementalMathematicalOperators::ShortUpTackWithUnderbar),
'⫩' => Ok(SupplementalMathematicalOperators::ShortUpTackAboveShortDownTack),
'⫪' => Ok(SupplementalMathematicalOperators::DoubleDownTack),
'⫫' => Ok(SupplementalMathematicalOperators::DoubleUpTack),
'⫬' => Ok(SupplementalMathematicalOperators::DoubleStrokeNotSign),
'⫭' => Ok(SupplementalMathematicalOperators::ReversedDoubleStrokeNotSign),
'⫮' => Ok(SupplementalMathematicalOperators::DoesNotDivideWithReversedNegationSlash),
'⫯' => Ok(SupplementalMathematicalOperators::VerticalLineWithCircleAbove),
'⫰' => Ok(SupplementalMathematicalOperators::VerticalLineWithCircleBelow),
'⫱' => Ok(SupplementalMathematicalOperators::DownTackWithCircleBelow),
'⫲' => Ok(SupplementalMathematicalOperators::ParallelWithHorizontalStroke),
'⫳' => Ok(SupplementalMathematicalOperators::ParallelWithTildeOperator),
'⫴' => Ok(SupplementalMathematicalOperators::TripleVerticalBarBinaryRelation),
'⫵' => Ok(SupplementalMathematicalOperators::TripleVerticalBarWithHorizontalStroke),
'⫶' => Ok(SupplementalMathematicalOperators::TripleColonOperator),
'⫷' => Ok(SupplementalMathematicalOperators::TripleNestedLessDashThan),
'⫸' => Ok(SupplementalMathematicalOperators::TripleNestedGreaterDashThan),
'⫹' => Ok(SupplementalMathematicalOperators::DoubleDashLineSlantedLessDashThanOrEqualTo),
'⫺' => Ok(SupplementalMathematicalOperators::DoubleDashLineSlantedGreaterDashThanOrEqualTo),
'⫻' => Ok(SupplementalMathematicalOperators::TripleSolidusBinaryRelation),
'⫼' => Ok(SupplementalMathematicalOperators::LargeTripleVerticalBarOperator),
'⫽' => Ok(SupplementalMathematicalOperators::DoubleSolidusOperator),
'⫾' => Ok(SupplementalMathematicalOperators::WhiteVerticalBar),
_ => Err(()),
}
}
}
impl Into<u32> for SupplementalMathematicalOperators {
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 SupplementalMathematicalOperators {
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 SupplementalMathematicalOperators {
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 SupplementalMathematicalOperators {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
SupplementalMathematicalOperators::NDashAryCircledDotOperator
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("SupplementalMathematicalOperators{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use itertools::Itertools;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::ops::*;
pub struct Grid {
size: u32,
grid: Vec<bool>,
}
#[derive(Debug, Copy, Clone)]
struct OrderedFloat(ordered_float::OrderedFloat<f64>);
impl Hash for OrderedFloat {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.0.hash(state);
}
}
impl PartialEq for OrderedFloat {
fn eq(&self, other: &OrderedFloat) -> bool {
(self.0.into_inner() - other.0.into_inner()).abs() <= 0.001
}
}
impl Eq for OrderedFloat {}
impl Grid {
pub fn from_input(input: &str) -> Grid {
let grid: Vec<bool> = input
.lines()
.flat_map(|l| {
l.chars().map(|c| match c {
'#' => true,
'.' => false,
c => panic!("Invalid input: '{}', code {}", c, c as u32),
})
})
.collect();
let size = input.lines().nth(0).unwrap().len() as u32;
println!("size: {}", size);
Grid { grid, size }
}
#[inline]
pub fn size(&self) -> u32 {
self.size
}
#[inline]
fn at(&self, x: u32, y: u32) -> bool {
self.grid[(y * self.size + x) as usize]
}
pub fn detect_from(&self, x: u32, y: u32) -> Vec<(u32, u32)> {
let orig = (x as f64, y as f64);
let mut points: HashMap<OrderedFloat, (u32, u32)> = HashMap::new();
for ty in 0..self.size() {
for tx in (0..self.size()).filter(|&tx| self.at(tx, ty) && (tx, ty) != (x, y)) {
let t = (tx as f64, ty as f64);
let mut angle = ((t.1 - orig.1).abs() / (t.0 - orig.0).abs()).atan();
if ty < y {
angle += std::f64::consts::PI;
}
points
.entry(OrderedFloat(ordered_float::OrderedFloat(angle)))
.and_modify(|curr| {
if dist(orig, t) < dist(orig, (curr.0 as f64, curr.1 as f64)) {
*curr = (tx, ty);
}
})
.or_insert((tx, ty));
}
}
points.values().copied().collect()
}
}
#[inline]
fn dist(p1: (f64, f64), p2: (f64, f64)) -> f64 {
let dx = p1.0 - p2.0;
let dy = p1.1 - p2.1;
(dx.mul_add(dx, dy * dy)).sqrt()
}
#[aoc(day10, part1)]
pub fn day10_part1(_input: &str) -> u32 {
//let input = "#..\n.#.\n..#\n";
let input = "......#.#.\n#..#.#....\n..#######.\n.#.#.###..\n.#..#.....\n..#....#.#\n#..#....#.\n.##.#..###\n##...#..#.\n.#....####";
let grid = Grid::from_input(input);
(0u32..grid.size()).for_each(|y| {
(0..grid.size()).filter(|&x| grid.at(x, y)).for_each(|x| {
let points = grid.detect_from(x, y);
println!("({:2}, {:2}) -> points: {:?}", x, y, points.len());
})
});
0
}
|
// Find the two entries that sum to 2020; what do you get if you multiply them together?
use std::fs;
// read in the file
// loop through each value
// check if two entries give 2020
// if they do multiply them
// else continue
fn main() -> std::io::Result<()> {
let file = fs::read_to_string("data.txt")?;
let mut data : Vec<i32> = Vec::new();
for line in file.lines() {
let parse_value: i32 = line.parse().unwrap();
data.push(parse_value);
}
for i in data.iter() {
for j in data.iter() {
for k in data.iter() {
if j + i + k == 2020 {
println!("{}", j * i * k);
return Ok(());
}
}
}
}
Ok(())
}
|
use std::mem;
struct Point {
x: f64,
y: f64,
}
impl Point {
fn display(&self) -> () {
println!("Point x:{}; y:{};", self.x, self.y)
}
}
fn origin() -> Point {
Point {x: 0.0, y: 0.0}
}
pub fn run() {
println!("\n====2.12 STUCK AND HEAP====");
let p1: Point = origin();
let mut p2: Box<Point> = Box::new(origin());
println!("p1 takes up {} bytes", mem::size_of_val(&p1));
println!("p2 takes up {} bytes", mem::size_of_val(&p2));
println!("*p2 takes up {} bytes", mem::size_of_val(&*p2));
println!("p2.x {}; p2.y {}", p2.x, p2.y);
p2.x = 2.0;
p2.display();
} |
use super::{chunk_header::*, chunk_type::*, *};
use crate::error_cause::*;
use bytes::{Bytes, BytesMut};
use std::fmt;
///Operation Error (ERROR) (9)
///
///An endpoint sends this chunk to its peer endpoint to notify it of
///certain error conditions. It contains one or more error causes. An
///Operation Error is not considered fatal in and of itself, but may be
///used with an ERROR chunk to report a fatal condition. It has the
///following parameters:
/// 0 1 2 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| Type = 9 | Chunk Flags | Length |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| |
///| one or more Error Causes |
///| |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///Chunk Flags: 8 bits
/// Set to 0 on transmit and ignored on receipt.
///Length: 16 bits (unsigned integer)
/// Set to the size of the chunk in bytes, including the chunk header
/// and all the Error Cause fields present.
#[derive(Default, Debug, Clone)]
pub(crate) struct ChunkError {
pub(crate) error_causes: Vec<ErrorCause>,
}
/// makes ChunkError printable
impl fmt::Display for ChunkError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut res = vec![self.header().to_string()];
for cause in &self.error_causes {
res.push(format!(" - {}", cause.to_string()));
}
write!(f, "{}", res.join("\n"))
}
}
impl Chunk for ChunkError {
fn header(&self) -> ChunkHeader {
ChunkHeader {
typ: CT_ERROR,
flags: 0,
value_length: self.value_length() as u16,
}
}
fn unmarshal(raw: &Bytes) -> Result<Self, Error> {
let header = ChunkHeader::unmarshal(raw)?;
if header.typ != CT_ERROR {
return Err(Error::ErrChunkTypeNotCtError);
}
let mut error_causes = vec![];
let mut offset = CHUNK_HEADER_SIZE;
while offset + 4 <= raw.len() {
let e = ErrorCause::unmarshal(
&raw.slice(offset..CHUNK_HEADER_SIZE + header.value_length()),
)?;
offset += e.length();
error_causes.push(e);
}
Ok(ChunkError { error_causes })
}
fn marshal_to(&self, buf: &mut BytesMut) -> Result<usize, Error> {
self.header().marshal_to(buf)?;
for ec in &self.error_causes {
buf.extend(ec.marshal());
}
Ok(buf.len())
}
fn check(&self) -> Result<(), Error> {
Ok(())
}
fn value_length(&self) -> usize {
self.error_causes
.iter()
.fold(0, |length, ec| length + ec.length())
}
fn as_any(&self) -> &(dyn Any + Send + Sync) {
self
}
}
|
extern crate meteor_virtualize;
extern crate syn;
extern crate synom;
#[macro_use]
extern crate quote;
extern crate rustfmt_nightly as rustfmt;
use meteor_virtualize::Virtualize;
use quote::Tokens;
fn formatting(input: &str) -> String {
let string = input.to_string();
let config = rustfmt::config::Config::default();
let res = rustfmt::format_input::<Vec<u8>>(
rustfmt::Input::Text(string),
&config,
None,
);
match res {
Ok((summary, file_map, report)) => {
file_map[0].1.to_string()
}
Err(err) => {
println!("{:?}", err);
"".into()
}
}
}
fn virtualize<T>(input: &str) -> String
where
T: synom::Synom + Virtualize,
{
let mut item = match syn::parse_str::<T>(&input) {
Ok(item) => item,
Err(err) => panic!("{:?}", err),
};
let mut tokens = Tokens::new();
item.virtualize(&mut tokens);
if true {
let wrapper_tokens = quote! {
fn foo() {
let mut __tokens = ::quote::Tokens::new();
#tokens
__tokens
}
};
println!("virtualized: {}", formatting(&wrapper_tokens.to_string()));
}
tokens.to_string()
}
#[test]
fn assign_lit() {
let output = virtualize::<syn::Block>(
stringify!({ let x = 0; })
);
let reference = quote!({
__Codegen::begin_scope(&mut __codegen);
let x = {
let __args = 0;
__ExprBlock::__stmnt_local(&mut __codegen, Pat::Ident("x"), __args)
};
let __result = __ExprBlock::__expr(&mut __codegen, Expr::empty());
__Codegen::end_scope(&mut __codegen);
__result
});
assert_eq!(output, reference.to_string());
}
#[test]
fn assign_expr_sum() {
let output = virtualize::<syn::Block>(
stringify!({ let x = { 1 + 2 }; })
);
let reference = quote!({
__Codegen::begin_scope(&mut __codegen);
let x = {
let __args = {
__Codegen::begin_scope(&mut __codegen);
let __result = {
let __args = {
let __args = (1, 2);
__Add::__add(&mut __codegen, __args.0, __args.1)
};
__ExprBlock::__expr(&mut __codegen, __args)
};
__Codegen::end_scope(&mut __codegen);
__result
};
__ExprBlock::__stmnt_local(&mut __codegen, Pat::Ident("x"), __args)
};
let __result = __ExprBlock::__expr(&mut __codegen, Expr::empty());
__Codegen::end_scope(&mut __codegen);
__result
});
assert_eq!(output, reference.to_string());
}
#[test]
fn assign_expr_sum_blocks() {
let output = virtualize::<syn::Block>(
stringify!({ let x = { let a0 = 0; 1 } + { let a1 = 0; 2 }; })
);
let reference = quote!({
__Codegen::begin_scope(&mut __codegen);
let x = {
let __args = {
let __args = (
{
__Codegen::begin_scope(&mut __codegen);
let a0 = {
let __args = 0;
__ExprBlock::__stmnt_local(&mut __codegen, Pat::Ident("a0"), __args)
};
let __result = {
let __args = 1;
__ExprBlock::__expr(&mut __codegen, __args)
};
__Codegen::end_scope(&mut __codegen);
__result
},
{
__Codegen::begin_scope(&mut __codegen);
let a1 = {
let __args = 0;
__ExprBlock::__stmnt_local(&mut __codegen, Pat::Ident("a1"), __args)
};
let __result = {
let __args = 2;
__ExprBlock::__expr(&mut __codegen, __args)
};
__Codegen::end_scope(&mut __codegen);
__result
}
);
__Add::__add(&mut __codegen, __args.0, __args.1)
};
__ExprBlock::__stmnt_local(&mut __codegen, Pat::Ident("x"), __args)
};
let __result = __ExprBlock::__expr(&mut __codegen, Expr::empty());
__Codegen::end_scope(&mut __codegen);
__result
});
assert_eq!(output, reference.to_string());
}
#[test]
fn assign_expr_tuple() {
let output = virtualize::<syn::Block>(
stringify!({ let x = (1, 2); })
);
let reference = quote!({
__Codegen::begin_scope(&mut __codegen);
let x = {
let __args = {
let args = (1, 2,);
__ExprTuple::__expr(&mut __codegen, args)
};
__ExprBlock::__stmnt_local(&mut __codegen, Pat::Ident("x"), __args)
};
let __result = __ExprBlock::__expr(&mut __codegen, Expr::empty());
__Codegen::end_scope(&mut __codegen);
__result
});
assert_eq!(output, reference.to_string());
}
|
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate nuc;
use nuc::Number;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "nuc", about = "Converts numbers form one for to another")]
struct Opt {
/// Number to convert
#[structopt(help = "Input numbers")]
input: Vec<String>,
}
fn main() {
let opt = Opt::from_args();
for arg in opt.input {
let num: Number = match arg.parse() {
Ok(i) => i,
Err(e) => {
println!("Failed to parse input '{}': {}", arg, e);
std::process::exit(1);
}
};
print!("{:>8} ", num);
print!("{:>8} ", num.fmt_signed());
print!("{:>#8x} ", num);
print!("{:>#16b}", num);
println!();
}
}
|
mod arrays_slices;
mod enums;
mod pointers_ref;
mod structs;
mod tuples;
pub fn main() {
println!("------{} BEGIN------", file!());
tuples::main();
arrays_slices::main();
enums::main();
pointers_ref::main();
structs::main();
println!("------{} END------", file!());
}
|
use crate::chain::{ChainService, ForkChanges};
use crate::tests::util::gen_block;
use ckb_chain_spec::consensus::Consensus;
use ckb_core::block::Block;
use ckb_core::extras::{BlockExt, DaoStats, DEFAULT_ACCUMULATED_RATE};
use ckb_db::memorydb::MemoryKeyValueDB;
use ckb_notify::NotifyService;
use ckb_shared::shared::SharedBuilder;
use ckb_traits::ChainProvider;
use faketime::unix_time_as_millis;
use numext_fixed_uint::U256;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::sync::Arc;
// 0--1--2--3--4
// \
// \
// 1--2--3--4
#[test]
fn test_find_fork_case1() {
let builder = SharedBuilder::<MemoryKeyValueDB>::new();
let shared = builder.consensus(Consensus::default()).build().unwrap();
let notify = NotifyService::default().start::<&str>(None);
let mut chain_service = ChainService::new(shared.clone(), notify);
let genesis = shared.block_header(&shared.block_hash(0).unwrap()).unwrap();
let mut fork1: Vec<Block> = Vec::new();
let mut fork2: Vec<Block> = Vec::new();
let mut parent = genesis.clone();
for _ in 0..4 {
let new_block = gen_block(&parent, U256::from(100u64), vec![], vec![], vec![]);
fork1.push(new_block.clone());
parent = new_block.header().to_owned();
}
let mut parent = genesis.clone();
for _ in 0..3 {
let new_block = gen_block(&parent, U256::from(90u64), vec![], vec![], vec![]);
fork2.push(new_block.clone());
parent = new_block.header().to_owned();
}
// fork1 total_difficulty 400
for blk in &fork1 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
// fork2 total_difficulty 270
for blk in &fork2 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
let tip_number = { shared.lock_chain_state().tip_number() };
// fork2 total_difficulty 470
let new_block = gen_block(&parent, U256::from(200u64), vec![], vec![], vec![]);
fork2.push(new_block.clone());
let ext = BlockExt {
received_at: unix_time_as_millis(),
total_difficulty: U256::zero(),
total_uncles_count: 0,
// if txs in parent is invalid, txs in block is also invalid
txs_verified: None,
dao_stats: DaoStats {
accumulated_rate: DEFAULT_ACCUMULATED_RATE,
accumulated_capacity: 0,
},
};
let mut fork = ForkChanges::default();
chain_service.find_fork(&mut fork, tip_number, &new_block, ext);
let detached_blocks: HashSet<Block> = HashSet::from_iter(fork1.into_iter());
let attached_blocks: HashSet<Block> = HashSet::from_iter(fork2.into_iter());
assert_eq!(
detached_blocks,
HashSet::from_iter(fork.detached_blocks.iter().cloned())
);
assert_eq!(
attached_blocks,
HashSet::from_iter(fork.attached_blocks.iter().cloned())
);
}
// 0--1--2--3--4
// \
// \
// 2--3--4
#[test]
fn test_find_fork_case2() {
let builder = SharedBuilder::<MemoryKeyValueDB>::new();
let shared = builder.consensus(Consensus::default()).build().unwrap();
let notify = NotifyService::default().start::<&str>(None);
let mut chain_service = ChainService::new(shared.clone(), notify);
let genesis = shared.block_header(&shared.block_hash(0).unwrap()).unwrap();
let mut fork1: Vec<Block> = Vec::new();
let mut fork2: Vec<Block> = Vec::new();
let mut parent = genesis.clone();
for _ in 0..4 {
let new_block = gen_block(&parent, U256::from(100u64), vec![], vec![], vec![]);
fork1.push(new_block.clone());
parent = new_block.header().to_owned();
}
let mut parent = fork1[0].header().to_owned();
for _ in 0..2 {
let new_block = gen_block(&parent, U256::from(90u64), vec![], vec![], vec![]);
fork2.push(new_block.clone());
parent = new_block.header().to_owned();
}
// fork2 total_difficulty 400
for blk in &fork1 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
// fork2 total_difficulty 280
for blk in &fork2 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
let tip_number = { shared.lock_chain_state().tip_number() };
let difficulty = parent.difficulty().to_owned();
let new_block = gen_block(
&parent,
difficulty + U256::from(200u64),
vec![],
vec![],
vec![],
);
fork2.push(new_block.clone());
let ext = BlockExt {
received_at: unix_time_as_millis(),
total_difficulty: U256::zero(),
total_uncles_count: 0,
// if txs in parent is invalid, txs in block is also invalid
txs_verified: None,
dao_stats: DaoStats {
accumulated_rate: DEFAULT_ACCUMULATED_RATE,
accumulated_capacity: 0,
},
};
let mut fork = ForkChanges::default();
chain_service.find_fork(&mut fork, tip_number, &new_block, ext);
let detached_blocks: HashSet<Block> = HashSet::from_iter(fork1[1..].iter().cloned());
let attached_blocks: HashSet<Block> = HashSet::from_iter(fork2.into_iter());
assert_eq!(
detached_blocks,
HashSet::from_iter(fork.detached_blocks.iter().cloned())
);
assert_eq!(
attached_blocks,
HashSet::from_iter(fork.attached_blocks.iter().cloned())
);
}
// 0--1--2--3
// \ _ fork
// \ /
// 1--2--3--4--5--6
#[test]
fn test_find_fork_case3() {
let builder = SharedBuilder::<MemoryKeyValueDB>::new();
let shared = builder.consensus(Consensus::default()).build().unwrap();
let notify = NotifyService::default().start::<&str>(None);
let mut chain_service = ChainService::new(shared.clone(), notify);
let genesis = shared.block_header(&shared.block_hash(0).unwrap()).unwrap();
let mut fork1: Vec<Block> = Vec::new();
let mut fork2: Vec<Block> = Vec::new();
let mut parent = genesis.clone();
for _ in 0..3 {
let new_block = gen_block(&parent, U256::from(80u64), vec![], vec![], vec![]);
fork1.push(new_block.clone());
parent = new_block.header().to_owned();
}
let mut parent = genesis.clone();
for _ in 0..5 {
let new_block = gen_block(&parent, U256::from(40u64), vec![], vec![], vec![]);
fork2.push(new_block.clone());
parent = new_block.header().to_owned();
}
// fork2 total_difficulty 240
for blk in &fork1 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
// fork2 total_difficulty 200
for blk in &fork2 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
let tip_number = { shared.lock_chain_state().tip_number() };
let new_block = gen_block(&parent, U256::from(100u64), vec![], vec![], vec![]);
fork2.push(new_block.clone());
let ext = BlockExt {
received_at: unix_time_as_millis(),
total_difficulty: U256::zero(),
total_uncles_count: 0,
// if txs in parent is invalid, txs in block is also invalid
txs_verified: None,
dao_stats: DaoStats {
accumulated_rate: DEFAULT_ACCUMULATED_RATE,
accumulated_capacity: 0,
},
};
let mut fork = ForkChanges::default();
chain_service.find_fork(&mut fork, tip_number, &new_block, ext);
let detached_blocks: HashSet<Block> = HashSet::from_iter(fork1.into_iter());
let attached_blocks: HashSet<Block> = HashSet::from_iter(fork2.into_iter());
assert_eq!(
detached_blocks,
HashSet::from_iter(fork.detached_blocks.iter().cloned())
);
assert_eq!(
attached_blocks,
HashSet::from_iter(fork.attached_blocks.iter().cloned())
);
}
// 0--1--2--3--4--5
// \ _ fork
// \ /
// 1--2--3
#[test]
fn test_find_fork_case4() {
let builder = SharedBuilder::<MemoryKeyValueDB>::new();
let shared = builder.consensus(Consensus::default()).build().unwrap();
let notify = NotifyService::default().start::<&str>(None);
let mut chain_service = ChainService::new(shared.clone(), notify);
let genesis = shared.block_header(&shared.block_hash(0).unwrap()).unwrap();
let mut fork1: Vec<Block> = Vec::new();
let mut fork2: Vec<Block> = Vec::new();
let mut parent = genesis.clone();
for _ in 0..5 {
let new_block = gen_block(&parent, U256::from(40u64), vec![], vec![], vec![]);
fork1.push(new_block.clone());
parent = new_block.header().to_owned();
}
let mut parent = genesis.clone();
for _ in 0..2 {
let new_block = gen_block(&parent, U256::from(80u64), vec![], vec![], vec![]);
fork2.push(new_block.clone());
parent = new_block.header().to_owned();
}
// fork2 total_difficulty 200
for blk in &fork1 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
// fork2 total_difficulty 160
for blk in &fork2 {
chain_service
.process_block(Arc::new(blk.clone()), false)
.unwrap();
}
let tip_number = { shared.lock_chain_state().tip_number() };
let new_block = gen_block(&parent, U256::from(100u64), vec![], vec![], vec![]);
fork2.push(new_block.clone());
let ext = BlockExt {
received_at: unix_time_as_millis(),
total_difficulty: U256::zero(),
total_uncles_count: 0,
// if txs in parent is invalid, txs in block is also invalid
txs_verified: None,
dao_stats: DaoStats {
accumulated_rate: DEFAULT_ACCUMULATED_RATE,
accumulated_capacity: 0,
},
};
let mut fork = ForkChanges::default();
chain_service.find_fork(&mut fork, tip_number, &new_block, ext);
let detached_blocks: HashSet<Block> = HashSet::from_iter(fork1.into_iter());
let attached_blocks: HashSet<Block> = HashSet::from_iter(fork2.into_iter());
assert_eq!(
detached_blocks,
HashSet::from_iter(fork.detached_blocks.iter().cloned())
);
assert_eq!(
attached_blocks,
HashSet::from_iter(fork.attached_blocks.iter().cloned())
);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use crate::runtime::array::Array;
use crate::runtime::function::Result;
use crate::runtime::map::Map;
use crate::runtime::string::String as TVMString;
use crate::runtime::{external, Object, ObjectRef};
use super::expr::GlobalVar;
use super::function::BaseFunc;
use std::io::Result as IOResult;
use std::path::Path;
use tvm_macros::Object;
// TODO(@jroesch): define type
type TypeData = ObjectRef;
type GlobalTypeVar = ObjectRef;
#[repr(C)]
#[derive(Object)]
#[ref_name = "IRModule"]
#[type_key = "IRModule"]
pub struct IRModuleNode {
pub base: Object,
pub functions: Map<GlobalVar, BaseFunc>,
pub type_definitions: Map<GlobalTypeVar, TypeData>,
}
external! {
// Parser functions
#[name("parser.ParseModule")]
fn parse_module(file_name: TVMString, source: TVMString) -> IRModule;
#[name("parser.ParseExpr")]
fn parse_expression(file_name: TVMString, source: TVMString) -> IRModule;
// Module methods
#[name("ir.Module_AddDef")]
fn module_add_def(module: IRModule, type_name: GlobalTypeVar, type_data: TypeData, update: bool) -> ();
#[name("ir.Module_GetGlobalVar")]
fn module_get_global_var(module: IRModule, name: TVMString) -> GlobalVar;
#[name("ir.Module_GetGlobalVars")]
fn module_get_global_vars(module: IRModule) -> Array<GlobalVar>;
#[name("ir.Module_Lookup")]
fn module_lookup(module: IRModule, var: GlobalVar) -> BaseFunc;
#[name("ir.Module_Lookup_str")]
fn module_lookup_str(module: IRModule, name: TVMString) -> BaseFunc;
}
// TVM_REGISTER_GLOBAL("ir.Module_GetGlobalTypeVars")
// .set_body_method<IRModule>(&IRModuleNode::GetGlobalTypeVars);
// TVM_REGISTER_GLOBAL("ir.Module_ContainGlobalVar")
// .set_body_method<IRModule>(&IRModuleNode::ContainGlobalVar);
// TVM_REGISTER_GLOBAL("ir.Module_GetGlobalTypeVar")
// .set_body_method<IRModule>(&IRModuleNode::GetGlobalTypeVar);
// TVM_REGISTER_GLOBAL("ir.Module_LookupDef").set_body_typed([](IRModule mod, GlobalTypeVar var) {
// return mod->LookupTypeDef(var);
// });
// TVM_REGISTER_GLOBAL("ir.Module_LookupDef_str").set_body_typed([](IRModule mod, String var) {
// return mod->LookupTypeDef(var);
// });
// TVM_REGISTER_GLOBAL("ir.Module_LookupTag").set_body_typed([](IRModule mod, int32_t tag) {
// return mod->LookupTag(tag);
// });
// TVM_REGISTER_GLOBAL("ir.Module_FromExpr")
// .set_body_typed([](RelayExpr e, tvm::Map<GlobalVar, BaseFunc> funcs,
// tvm::Map<GlobalTypeVar, TypeData> type_defs) {
// return IRModule::FromExpr(e, funcs, type_defs);
// });
// TVM_REGISTER_GLOBAL("ir.Module_Update").set_body_typed([](IRModule mod, IRModule from) {
// mod->Update(from);
// });
// TVM_REGISTER_GLOBAL("ir.Module_UpdateFunction")
// .set_body_typed([](IRModule mod, GlobalVar gv, BaseFunc func) { mod->Update(gv, func); });
// TVM_REGISTER_GLOBAL("ir.Module_Import").set_body_typed([](IRModule mod, String path) {
// mod->Import(path);
// });
// TVM_REGISTER_GLOBAL("ir.Module_ImportFromStd").set_body_typed([](IRModule mod, String path) {
// mod->ImportFromStd(path);
// });
// TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
// .set_dispatch<IRModuleNode>([](const ObjectRef& ref, ReprPrinter* p) {
// auto* node = static_cast<const IRModuleNode*>(ref.get());
// p->stream << "IRModuleNode( " << node->functions << ")";
// });
impl IRModule {
pub fn parse<N, S>(file_name: N, source: S) -> IRModule
where
N: Into<TVMString>,
S: Into<TVMString>,
{
parse_module(file_name.into(), source.into()).expect("failed to call parser")
}
pub fn parse_file<P: 'static + AsRef<Path>>(file_path: P) -> IOResult<IRModule> {
let file_path = file_path.as_ref();
let file_path_as_str = file_path.to_str().unwrap().to_string();
let source = std::fs::read_to_string(file_path)?;
let module = IRModule::parse(file_path_as_str, source);
Ok(module)
}
pub fn add_def(
&mut self,
type_name: GlobalTypeVar,
type_data: TypeData,
update: bool,
) -> Result<()> {
module_add_def(self.clone(), type_name, type_data, update)
}
pub fn get_global_var(&self, name: TVMString) -> Result<GlobalVar> {
module_get_global_var(self.clone(), name)
}
pub fn get_global_vars(&self) -> Result<Array<GlobalVar>> {
module_get_global_vars(self.clone())
}
pub fn lookup(&self, var: GlobalVar) -> Result<BaseFunc> {
module_lookup(self.clone(), var)
}
pub fn lookup_str<S>(&self, name: S) -> Result<BaseFunc>
where
S: Into<TVMString>,
{
module_lookup_str(self.clone(), name.into())
}
}
|
//! `interactive_process` is a lightweight wrapper on [std::process] that provides
//! an interface for running a process and relaying messages to/from it as
//! newline-delimited strings over `stdin`/`stdout`.
//!
//! This behavior is provided through the [InteractiveProcess] struct, which
//! is constructed with a [std::process::Command] and a callback which is called
//! with a [std::io::Result]-wrapped [String] for each string received from the
//! child process. Upon construction, [InteractiveProcess] begins executing the
//! passed command and starts the event loop. Whilst the process is running, you
//! can send
use std::io::{BufRead, BufReader, Result, Write};
use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio};
use std::thread;
const ASCII_NEWLINE: u8 = 10;
/// Wraps a [Child] object in an interface for doing newline-dellimited string IO
/// with a child process.
///
/// Calling `send` sends a string to the process's `stdin`. A newline delimiter
/// is automatically appended. If newline characters are present in the provided
/// string, they will _not_ be escaped.
///
/// Each newline-separated string sent by the child process over `stdout` results
/// a call to the provided `line_callback` function. The line is wrapped in a
/// [std::io::Result]; it will be in the `Err` state if the line is not valid
/// UTF-8.
///
/// A callback may optionally be provided (via `new_with_exit_callback`) which is
/// invoked when the child's `stdout` stream is closed.
pub struct InteractiveProcess {
child: Child,
stdin: ChildStdin,
}
impl InteractiveProcess {
/// Attempt to start a process for the provided [Command], capturing the
/// standard in and out streams for later use. The provided callback is
/// called for every newline-terminated string written to `stdout` by the
/// process.
pub fn new<T>(command: &mut Command, line_callback: T) -> Result<Self>
where
T: Fn(Result<String>) + Send + 'static,
{
Self::new_with_exit_callback(command, line_callback, || ())
}
/// Constructor with the same semantics as `new`, except that an additional
/// no-argument closure is provided which is called when the client exits.
pub fn new_with_exit_callback<T, S>(
command: &mut Command,
line_callback: T,
exit_callback: S,
) -> std::io::Result<Self>
where
T: Fn(Result<String>) + Send + 'static,
S: Fn() + Send + 'static,
{
let mut child = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
let stdout = child
.stdout
.take()
.expect("Accessing stdout should never fail after passing Stdio::piped().");
let stdin = child
.stdin
.take()
.expect("Accessing stdin should never fail after passing Stdio::piped().");
thread::spawn(move || {
for line in BufReader::new(stdout).lines() {
line_callback(line);
}
exit_callback();
});
Ok(InteractiveProcess { stdin, child })
}
/// Send a string to the client process's `stdin` stream. A newline will be
/// appended to the string.
pub fn send(&mut self, data: &str) -> std::io::Result<()> {
self.stdin.write_all(data.as_bytes())?;
self.stdin.write_all(&[ASCII_NEWLINE])
}
/// Send a string to the client process's `stdin` stream, without appending a
/// newline.
pub fn send_unterminated(&mut self, data: &str) -> std::io::Result<()> {
self.stdin.write_all(data.as_bytes())
}
/// Consume this `InteractiveProcess` and return its child. This closes the
/// process's stdin stream, which usually kills the process. If it doesn't,
/// you can use the returned `Child` object to kill it:
///
/// proc = InteractiveProces::new(...);
/// proc.take().kill().unwrap();
pub fn close(self) -> Child {
self.child
}
/// Block the current thread on the process exiting, and return the exit code when
/// it does. This does _not_ send a signal to kill the child, so it only makes
/// sense when the child process is self-terminating.
pub fn wait(mut self) -> std::io::Result<ExitStatus> {
self.child.wait()
}
}
|
//! Time abstractions
//! To use these abstractions, first call `set_clock` with an instance of an [Clock](trait.Clock.html).
//!
mod duration;
mod instant;
mod traits;
pub use crate::executor::timer::{with_timeout, Delay, Ticker, TimeoutError, Timer};
pub use duration::Duration;
pub use instant::Instant;
pub use traits::*;
// TODO allow customizing, probably via Cargo features `tick-hz-32768` or something.
pub const TICKS_PER_SECOND: u64 = 32768;
static mut CLOCK: Option<&'static dyn Clock> = None;
/// Sets the clock used for the timing abstractions
///
/// Safety: Sets a mutable global.
pub unsafe fn set_clock(clock: &'static dyn Clock) {
CLOCK = Some(clock);
}
/// Return the current timestamp in ticks.
/// This is guaranteed to be monotonic, i.e. a call to now() will always return
/// a greater or equal value than earler calls.
pub(crate) fn now() -> u64 {
unsafe { unwrap!(CLOCK, "No clock set").now() }
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// AuthenticationValidationResponse : Represent validation endpoint responses.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AuthenticationValidationResponse {
/// Return `true` if the authentication response is valid.
#[serde(rename = "valid", skip_serializing_if = "Option::is_none")]
pub valid: Option<bool>,
}
impl AuthenticationValidationResponse {
/// Represent validation endpoint responses.
pub fn new() -> AuthenticationValidationResponse {
AuthenticationValidationResponse {
valid: None,
}
}
}
|
use modinverse::egcd;
use std::env;
use std::fs;
fn one(time: &i128, buses: &Vec<&str>) {
let buses: Vec<i128> = buses
.into_iter()
.filter_map(|bus| bus.parse::<i128>().ok())
.collect();
let res = buses
.iter()
.map(|bus_num| (bus_num, bus_num - (time % bus_num)))
.min_by(|x, y| x.1.cmp(&y.1))
.expect("Didn't get a min");
println!("best: {}, {}, result: {}", res.0, res.1, res.0 * res.1);
}
fn find_offset(pa: i128, pb: i128, phi_a: i128, phi_b: i128, lcm: i128) -> i128 {
let (gcd, s, _) = egcd(pa, pb);
let z = (phi_a - phi_b) / gcd;
let m = z * s;
((m * pa - phi_a) % lcm + lcm) % lcm
}
struct Agg {
p_a: i128, // period
phi_a: i128, // phase
count: i128,
}
fn two(buses: &Vec<&str>) {
let mut iter = buses.iter();
let first = Agg {
p_a: iter
.next()
.expect("No first value")
.parse::<i128>()
.expect("Parse first num"),
phi_a: 0,
count: 0,
};
let res: Agg = iter.fold(first, |acc: Agg, next: &&str| {
if *next == "x" {
return Agg {
count: acc.count + 1,
..acc
};
}
let next: i128 = next.parse().expect("Can't parse number");
let new_mod = num::integer::lcm(acc.p_a, next);
let new_offset = find_offset(
acc.p_a,
next,
acc.p_a - acc.phi_a,
next - (acc.count + 1),
new_mod,
);
Agg {
p_a: new_mod,
phi_a: new_offset,
count: acc.count + 1,
}
});
println!("{:?}", res.p_a - res.phi_a)
}
fn main() {
let args: Vec<String> = env::args().collect();
let file = fs::read_to_string(&args[1]).expect("Couldn't read file");
let lines: Vec<_> = file.split('\n').collect();
let time: i128 = String::from(lines[0]).parse().expect("Couldn't parse time");
let buses: Vec<&str> = lines[1].split(',').collect();
one(&time, &buses);
two(&buses);
}
|
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub(super) struct Storage {
root: PathBuf,
}
|
use crate::libs::color::color_system;
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use nusa::prelude::*;
pub struct Props {
pub variant: Variant,
}
pub enum Variant {
Dark,
Light,
}
impl std::fmt::Display for Variant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Dark => write!(f, "dark"),
Self::Light => write!(f, "light"),
}
}
}
pub enum Msg {}
pub enum On {}
pub struct LoadingCircle {
variant: Variant,
}
impl Component for LoadingCircle {
type Props = Props;
type Msg = Msg;
type Event = On;
}
impl HtmlComponent for LoadingCircle {}
impl Constructor for LoadingCircle {
fn constructor(props: Self::Props) -> Self {
Self {
variant: props.variant,
}
}
}
impl Update for LoadingCircle {
fn on_load(mut self: Pin<&mut Self>, props: Self::Props) -> Cmd<Self> {
self.variant = props.variant;
Cmd::none()
}
}
impl Render<Html> for LoadingCircle {
type Children = ();
fn render(&self, _: Self::Children) -> Html {
Self::styled(Html::span(
Attributes::new()
.class(Self::class("base"))
.class(Self::class(&format!("{}", self.variant))),
Events::new(),
vec![],
))
}
}
impl Styled for LoadingCircle {
fn style() -> Style {
style! {
".base" {
"display": "inline-block";
"padding": "0";
"margin": "0";
"width": "1.1em";
"height": "1.1em";
"border-radius": "50%";
"animation": "0.5s linear infinite rotation";
}
".dark" {
"border-top": format!("0.2em solid {}", color_system::blue(100, 6).to_string());
"border-left": format!("0.2em solid {}", color_system::blue(75, 6).to_string());
"border-bottom": format!("0.2em solid {}", color_system::blue(50, 6).to_string());
"border-right": format!("0.2em solid {}", color_system::blue(25, 6).to_string());
}
".light" {
"border-top": format!("0.2em solid {}", color_system::blue(100, 3).to_string());
"border-left": format!("0.2em solid {}", color_system::blue(75, 3).to_string());
"border-bottom": format!("0.2em solid {}", color_system::blue(50, 3).to_string());
"border-right": format!("0.2em solid {}", color_system::blue(25, 3).to_string());
}
}
}
}
|
// Taken from https://github.com/superdump/bevy-hud-pass
use bevy::{
prelude::*,
render::{
camera::{ActiveCameras, Camera, PerspectiveProjection, VisibleEntities},
pass::{
LoadOp, Operations, PassDescriptor, RenderPassDepthStencilAttachmentDescriptor,
TextureAttachment,
},
render_graph::{
base, CameraNode, PassNode, RenderGraph, RenderResourcesNode, WindowSwapChainNode,
WindowTextureNode,
},
renderer::RenderResources,
},
ui,
};
pub mod camera {
/// The name of the camera used in the HUD pass
pub const CAMERA_HUD: &str = "camera_hud";
}
pub mod node {
pub const CAMERA_HUD: &str = "camera_hud";
pub const HUD_PASS: &str = "hud_pass";
pub const HUD_MESH: &str = "hud_mesh";
}
pub const HUD_SETUP_SYSTEM: &str = "hud_setup";
/// Add a HUDPass component to an entity to have it render in the HUD pass
#[derive(Debug, Clone, Default, RenderResources)]
pub struct HUDPass;
/// Just a PerspectiveCameraBundle with `Default` providing the correct name for the
/// HUD pass
#[derive(Bundle, Debug)]
pub struct HUDCameraBundle {
pub camera: Camera,
pub perspective_projection: PerspectiveProjection,
pub visible_entities: VisibleEntities,
pub transform: Transform,
pub global_transform: GlobalTransform,
}
impl Default for HUDCameraBundle {
fn default() -> Self {
let PerspectiveCameraBundle {
camera,
perspective_projection,
visible_entities,
transform,
global_transform,
} = PerspectiveCameraBundle::with_name(&camera::CAMERA_HUD.to_string());
Self {
camera,
perspective_projection,
visible_entities,
transform,
global_transform,
}
}
}
/// Just a PbrBundle but with a HUDPass component instead of a MainPass component
/// so that the mesh is rendered by the HUD pass
#[derive(Bundle)]
pub struct HUDPbrBundle {
pub mesh: Handle<Mesh>,
pub material: Handle<StandardMaterial>,
pub hud_pass: HUDPass,
pub draw: Draw,
pub visible: Visible,
pub render_pipelines: RenderPipelines,
pub transform: Transform,
pub global_transform: GlobalTransform,
}
impl Default for HUDPbrBundle {
fn default() -> Self {
let PbrBundle {
mesh,
material,
draw,
visible,
render_pipelines,
transform,
global_transform,
..
} = PbrBundle::default();
Self {
mesh,
material,
hud_pass: HUDPass,
draw,
visible,
render_pipelines,
transform,
global_transform,
}
}
}
pub struct HUDPassPlugin;
impl Plugin for HUDPassPlugin {
fn build(&self, app: &mut AppBuilder) {
app.add_startup_system(hud_setup.system().label(HUD_SETUP_SYSTEM));
}
}
fn hud_setup(
mut graph: ResMut<RenderGraph>,
mut active_cameras: ResMut<ActiveCameras>,
msaa: Res<Msaa>,
) {
let mut hud_pass_node = PassNode::<&HUDPass>::new(PassDescriptor {
color_attachments: vec![msaa.color_attachment_descriptor(
TextureAttachment::Input("color_attachment".to_string()),
TextureAttachment::Input("color_resolve_target".to_string()),
Operations {
load: LoadOp::Load,
store: true,
},
)],
depth_stencil_attachment: Some(RenderPassDepthStencilAttachmentDescriptor {
attachment: TextureAttachment::Input("depth".to_string()),
depth_ops: Some(Operations {
// NOTE: Clearing here makes everything in this pass be drawn on top of things in the main pass
load: LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: None,
}),
sample_count: msaa.samples,
});
hud_pass_node.add_camera(node::CAMERA_HUD);
graph.add_node(node::HUD_PASS, hud_pass_node);
graph
.add_slot_edge(
base::node::PRIMARY_SWAP_CHAIN,
WindowSwapChainNode::OUT_TEXTURE,
node::HUD_PASS,
if msaa.samples > 1 {
"color_resolve_target"
} else {
"color_attachment"
},
)
.unwrap();
graph
.add_slot_edge(
base::node::MAIN_DEPTH_TEXTURE,
WindowTextureNode::OUT_TEXTURE,
node::HUD_PASS,
"depth",
)
.unwrap();
if msaa.samples > 1 {
graph
.add_slot_edge(
base::node::MAIN_SAMPLED_COLOR_ATTACHMENT,
WindowSwapChainNode::OUT_TEXTURE,
node::HUD_PASS,
"color_attachment",
)
.unwrap();
}
graph
.add_node_edge(base::node::MAIN_PASS, node::HUD_PASS)
.unwrap();
graph
.add_node_edge(node::HUD_PASS, ui::node::UI_PASS)
.unwrap();
graph.add_system_node(node::CAMERA_HUD, CameraNode::new(camera::CAMERA_HUD));
graph
.add_node_edge(node::CAMERA_HUD, node::HUD_PASS)
.unwrap();
graph.add_system_node(node::HUD_MESH, RenderResourcesNode::<HUDPass>::new(true));
graph.add_node_edge(node::HUD_MESH, node::HUD_PASS).unwrap();
active_cameras.add(camera::CAMERA_HUD);
}
|
fn main(){
//tuples, can have many different types, fixed length, can be used to return more than one var from a function
let tup : (i32, f64, u8, f32) = (500, 6.4, 1, 29.29);
let tup2 = (1500, 4.3);
println!("tup and tup2: {:?} {:?}", tup, tup2);
//get individuals vars from tuples
let(w, x, y, z) = tup;
println!("The values of w,x,y,z is : {} {} {} {}", w, x, y, z);
let five_hundred = tup.0;
let three_point_four = tup2.1;
let one = tup.2;
let twonine_29 = tup.3;
println!("From the tuples: {} {} {} {}", five_hundred, three_point_four, one, twonine_29);
} |
use anyhow::{anyhow, Result};
use async_std::fs::OpenOptions;
use async_std::prelude::*;
use async_std::net::{UdpSocket, TcpStream};
use async_std::task::block_on;
use std::path::PathBuf;
use std::net::SocketAddr;
use std::sync::{mpsc, Mutex};
use std::time::{Duration, Instant};
use super::arg::SendArg;
use super::currentfile::CurrentFile;
use super::instruction::Operation;
use super::message::{Message, self};
use super::utils;
// Store refused sockets into a black list.
lazy_static::lazy_static! {
static ref BLACK_LIST: Mutex<Vec<SocketAddr>> = Mutex::new(Vec::new());
static ref ID: Mutex<u16> = Mutex::new(1);
}
// Entry function of Sender.
// Bind on a UDP socket, listen incoming UDP connection,
// get the target TCP port.
// After expire time the whole process will be terminated.
pub async fn launch(arg: SendArg) -> Result<()> {
let udp = UdpSocket::bind(("0.0.0.0", 0)).await?;
let port = udp.local_addr()?.port();
message::send_msg(Message::Status(format!("Connection code: {}", port)));
// Start timer.
let (tx, rx) = mpsc::channel();
let expire = arg.expire.clone();
async_std::task::spawn(async move {
timer(expire, rx).await;
});
// Stop timer after getting stream.
let password = arg.password.clone();
let mut stream = listen_udp(&udp, expire, password.as_ref()).await?;
tx.send(true)?;
//message::send_msg(Message::Status(format!("Connection established\n")));
// Start sending files and messages.
start_sending(&mut stream, arg).await?;
Ok(())
}
// Listen UDP socket, until a connection comes with a valid port number,
// assume it's the TCP port of the receiver.
async fn listen_udp(udp: &UdpSocket, expire: u8, password: Option<&String>) -> Result<TcpStream>{
let mut buf = [0; 2];
let start = Instant::now();
loop {
if start.elapsed().as_secs() > (expire * 60) as u64 { break; }
let (_, addr) = udp.recv_from(&mut buf).await?;
let port = u16::from_be_bytes(buf);
let socket = SocketAddr::new(addr.ip(), port);
// If this socket already in black list, ignore it.
if BLACK_LIST.lock().unwrap().contains(&socket) {
log::debug!("Found socket in black list {}", &socket);
continue;
}
log::debug!("Connection request from {}", socket);
if let Some(stream) = try_connect_tcp(&socket, password).await? {
message::send_msg(Message::Status(format!("Connection established with {}\n", &addr)));
return Ok(stream);
}
async_std::task::sleep(Duration::from_secs(1)).await;
}
Err(anyhow!("No connection established in time"))
}
// Try to connect to the target machine after receiving its connection request.
// Only run once for a connection request.
// Needs reply from receiver to continue next step.
async fn try_connect_tcp(socket: &SocketAddr, password: Option<&String>)
-> Result<Option<TcpStream>> {
let mut stream = TcpStream::connect(socket).await?;
utils::send_ins(&mut stream, 0, Operation::Connect, password).await?;
match validate_reply(&mut stream, 0).await {
Ok((true, _)) => Ok(Some(stream)),
Ok((false, detail)) => {
message::send_msg(Message::Error(format!("Connection refused: {}", detail)));
BLACK_LIST.lock().unwrap().push(*socket);
Ok(None)
},
Err(e) => {
message::send_msg(Message::Error(format!("Error trying connecting TCP: {}", e)));
Ok(None)
}
}
}
// Wait for `expire` minutes before terminate the process.
// Can be interrupted by the signal from parent function.
async fn timer(expire: u8, rx: mpsc::Receiver<bool>) {
log::debug!("Timer in {} minutes", expire);
let start = Instant::now();
while start.elapsed().as_secs() < (expire * 60) as u64 {
// Note the type cast should come first to avoid `expire` overflow.
let t = (expire as u64 * 60) - start.elapsed().as_secs();
message::send_msg(Message::Time(t));
async_std::task::sleep(std::time::Duration::from_secs(1)).await;
if Ok(true) == rx.try_recv() {
return;
}
}
message::send_msg(Message::Fatal(format!("no connection in time")));
}
// After the connection established, start sending files and messages from here.
async fn start_sending(stream: &mut TcpStream, arg: SendArg) -> Result<()> {
if arg.files.is_some() {
send_files(stream, &arg.files.unwrap())?;
}
if arg.msg.is_some(){
send_message(stream, &arg.msg.unwrap()).await?;
}
if request_disconnect(stream).await? {
log::debug!("Ready to shutdown");
}
message::send_msg(Message::Done);
Ok(())
}
// identify files and dirs and process them accordingly.
// Remove `async` of this function to avoid async recursion.
fn send_files(stream: &mut TcpStream, files: &Vec<PathBuf>) -> Result<()> {
for file in files {
if file.is_file() {
if let Err(e) = block_on(send_single_file(stream, file)) {
message::send_msg(Message::Error(format!("Error sending file {:?} : {}", file, e)));
}
} else if file.is_dir() {
if let Err(e) = block_on(send_dir(stream, file)) {
message::send_msg(Message::Error(format!("Error sending dir {:?} : {}", file, e)));
}
} else {
return Err(anyhow!("Unknow file type"));
}
}
Ok(())
}
// 1. Check the directory name first. TODO: if overwrite strategy is overwrite, do not create the dir.
// 2. Collect all paths inside the current dir and pass them to send_files() function.
// Async function doesn't support recursion.
async fn send_dir(stream: &mut TcpStream, dir: &PathBuf) -> Result<()> {
let id = read_id();
let dir_name = dir.file_name().unwrap().to_str().unwrap().to_string();
message::send_msg(Message::Status(format!("Start sending directory: \"{}\"", &dir_name)));
utils::send_ins(stream, id, Operation::StartSendDir, Some(&dir_name)).await?;
incre_id();
// If request being refused, abort the following action.
// Message has been sent to UI through the process_reply() function.
if !process_reply(stream, id).await? {
return Ok(());
}
let mut paths = Vec::new();
for entry in dir.read_dir()? {
if let Ok(entry) = entry {
paths.push(entry.path());
}
}
// Problem unsolved: once the recursion starts, the return type is required to be `dyn Future`.
send_files(stream, &paths)?;
send_dir_end(stream).await?;
message::send_msg(Message::Status(format!("Finish sending directory: \"{}\"", &dir_name)));
Ok(())
}
async fn send_dir_end(stream: &mut TcpStream) -> Result<()> {
let id = read_id();
utils::send_ins(stream, id, Operation::EndSendDir, None).await?;
incre_id();
process_reply(stream, id).await?;
Ok(())
}
// If any error happens or receiver chooses skip, skip this file.
async fn send_single_file(stream: &mut TcpStream, file: &PathBuf) -> Result<()> {
let mut current_file = CurrentFile::from(file)?;
if !send_file_meta(stream, ¤t_file).await? {
return Ok(());
}
send_file_content(stream, &mut current_file).await?;
send_file_end(stream).await?;
Ok(())
}
// Send file name and size as metainfo to receiver.
async fn send_file_meta(stream: &mut TcpStream, file: &CurrentFile) -> Result<bool> {
let meta = file.meta_to_string();
let id = read_id();
utils::send_ins(stream, id, Operation::StartSendFile, Some(&meta)).await?;
incre_id();
process_reply(stream, id).await
}
async fn send_file_content(stream: &mut TcpStream, f: &mut CurrentFile) -> Result<()> {
log::debug!("Sending file content");
let mut file = OpenOptions::new().read(true).open(f.path.clone()).await?;
let chunk_size = 0x200000; // 2M frame size
loop {
let mut chunk = Vec::with_capacity(chunk_size);
let length = file.by_ref().take(chunk_size as u64).read_to_end(&mut chunk).await?;
if length == 0 { break; }
utils::send_ins_bytes(stream, read_id(), Operation::SendFileContent, &chunk).await?;
f.transmitted += length as u64;
message::send_msg(Message::Progress(f.get_progress()));
}
message::send_msg(Message::FileEnd);
incre_id();
Ok(())
}
async fn send_file_end(stream: &mut TcpStream) -> Result<bool> {
let id = read_id();
utils::send_ins(stream, id, Operation::EndSendFile, None).await?;
incre_id();
process_reply(stream, id).await
}
async fn send_message(stream: &mut TcpStream, msg: &String) -> Result<bool> {
let id = read_id();
utils::send_ins(stream, id, Operation::SendMsg, Some(msg)).await?;
incre_id();
process_reply(stream, id).await
}
async fn request_disconnect(stream: &mut TcpStream) -> Result<bool> {
let id = read_id();
utils::send_ins(stream, id, Operation::Disconnect, None).await?;
match validate_reply(stream, id).await? {
(true, _) => { Ok(true) },
(false, detail) => {
message::send_msg(Message::Fatal(format!("disconnection request refused: {}", detail)));
Ok(false)
}
}
}
async fn process_reply(stream: &mut TcpStream, id: u16) -> Result<bool> {
match validate_reply(stream, id).await? {
(true, _) => Ok(true),
(false, detail) => {
message::send_msg(Message::Status(detail));
Ok(false)
}
}
}
// Validate the reply id and the reply operation.
// For abnormal reply, read the details as well.
async fn validate_reply(stream: &mut TcpStream, id: u16) -> Result<(bool, String)> {
let reply = utils::recv_ins(stream).await?;
if reply.id != id {
return Err(anyhow!("wrong id in reply"));
}
let detail = if reply.buffer {
get_reply_content(stream, reply.length as usize).await?
} else {
String::new()
};
match reply.operation {
Operation::RequestSuccess => Ok((true, detail)),
Operation::RequestRefuse => Ok((false, detail)),
Operation::RequestError => Err(anyhow!(detail)),
_ => Err(anyhow!("Unknown reply")),
}
}
// Helper function to read details for validate_reply().
async fn get_reply_content(stream: &mut TcpStream, length: usize) -> Result<String> {
let detail = utils::recv_content(stream, length).await?;
Ok(String::from_utf8(detail)?)
}
// Increment ID by 1. If it reaches the boundary of U16, set it to 1.
// 0 is reservered.
fn incre_id() {
let mut id = ID.lock().unwrap();
*id = if *id < u16::MAX { *id + 1 } else {1};
}
fn read_id() -> u16 {
let id = ID.lock().unwrap();
*id
} |
use crate::data_order::DataOrder;
use std::any::type_name;
use std::fmt;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, ConnectorXError>;
pub type OutResult<T> = std::result::Result<T, ConnectorXOutError>;
#[derive(Error, Debug)]
pub enum ConnectorXOutError {
#[error("File {0} not found.")]
FileNotFoundError(String),
#[error("Source {0} not supported.")]
SourceNotSupport(String),
#[error(transparent)]
IOError(#[from] std::io::Error),
#[error(transparent)]
JsonError(#[from] serde_json::Error),
#[cfg(feature = "federation")]
#[error(transparent)]
J4RSError(#[from] j4rs::errors::J4RsError),
#[cfg(feature = "fed_exec")]
#[error(transparent)]
DataFusionError(#[from] datafusion::error::DataFusionError),
#[error(transparent)]
UrlParseError(#[from] url::ParseError),
#[error(transparent)]
ConnectorXInternalError(#[from] ConnectorXError),
#[cfg(feature = "src_postgres")]
#[error(transparent)]
PostgresSourceError(#[from] crate::sources::postgres::PostgresSourceError),
#[cfg(feature = "src_postgres")]
#[error(transparent)]
PostgresError(#[from] postgres::Error),
#[cfg(feature = "src_mysql")]
#[error(transparent)]
MySQLSourceError(#[from] crate::sources::mysql::MySQLSourceError),
#[cfg(feature = "src_mysql")]
#[error(transparent)]
MysqlError(#[from] r2d2_mysql::mysql::Error),
#[cfg(feature = "src_mssql")]
#[error(transparent)]
MsSQLSourceError(#[from] crate::sources::mssql::MsSQLSourceError),
#[cfg(feature = "src_mssql")]
#[error(transparent)]
MsSQL(#[from] tiberius::error::Error),
#[cfg(feature = "src_sqlite")]
#[error(transparent)]
SQLiteSourceError(#[from] crate::sources::sqlite::SQLiteSourceError),
#[cfg(feature = "src_sqlite")]
#[error(transparent)]
SQLiteError(#[from] rusqlite::Error),
#[cfg(feature = "src_oracle")]
#[error(transparent)]
OracleSourceError(#[from] crate::sources::oracle::OracleSourceError),
#[cfg(feature = "src_oracle")]
#[error(transparent)]
OracleError(#[from] r2d2_oracle::oracle::Error),
#[cfg(feature = "src_bigquery")]
#[error(transparent)]
BigQuerySourceError(#[from] crate::sources::bigquery::BigQuerySourceError),
#[cfg(feature = "src_bigquery")]
#[error(transparent)]
BigQueryError(#[from] gcp_bigquery_client::error::BQError),
#[cfg(feature = "dst_arrow")]
#[error(transparent)]
ArrowError(#[from] crate::destinations::arrow::ArrowDestinationError),
#[cfg(feature = "dst_arrow2")]
#[error(transparent)]
Arrow2Error(#[from] crate::destinations::arrow2::Arrow2DestinationError),
#[cfg(all(feature = "src_postgres", feature = "dst_arrow"))]
#[error(transparent)]
PostgresArrowTransportError(#[from] crate::transports::PostgresArrowTransportError),
#[cfg(all(feature = "src_postgres", feature = "dst_arrow2"))]
#[error(transparent)]
PostgresArrow2TransportError(#[from] crate::transports::PostgresArrow2TransportError),
#[cfg(all(feature = "src_mysql", feature = "dst_arrow"))]
#[error(transparent)]
MySQLArrowTransportError(#[from] crate::transports::MySQLArrowTransportError),
#[cfg(all(feature = "src_mysql", feature = "dst_arrow2"))]
#[error(transparent)]
MySQLArrow2TransportError(#[from] crate::transports::MySQLArrow2TransportError),
#[cfg(all(feature = "src_sqlite", feature = "dst_arrow"))]
#[error(transparent)]
SQLiteArrowTransportError(#[from] crate::transports::SQLiteArrowTransportError),
#[cfg(all(feature = "src_sqlite", feature = "dst_arrow2"))]
#[error(transparent)]
SQLiteArrow2TransportError(#[from] crate::transports::SQLiteArrow2TransportError),
#[cfg(all(feature = "src_mssql", feature = "dst_arrow"))]
#[error(transparent)]
MsSQLArrowTransportError(#[from] crate::transports::MsSQLArrowTransportError),
#[cfg(all(feature = "src_mssql", feature = "dst_arrow2"))]
#[error(transparent)]
MsSQLArrow2TransportError(#[from] crate::transports::MsSQLArrow2TransportError),
#[cfg(all(feature = "src_oracle", feature = "dst_arrow"))]
#[error(transparent)]
OracleArrowTransportError(#[from] crate::transports::OracleArrowTransportError),
#[cfg(all(feature = "src_oracle", feature = "dst_arrow2"))]
#[error(transparent)]
OracleArrow2TransportError(#[from] crate::transports::OracleArrow2TransportError),
#[cfg(all(feature = "src_bigquery", feature = "dst_arrow"))]
#[error(transparent)]
BigqueryArrowTransportError(#[from] crate::transports::BigQueryArrowTransportError),
#[cfg(all(feature = "src_bigquery", feature = "dst_arrow2"))]
#[error(transparent)]
BigqueryArrow2TransportError(#[from] crate::transports::BigQueryArrow2TransportError),
/// Any other errors that are too trivial to be put here explicitly.
#[error(transparent)]
Other(#[from] anyhow::Error),
}
/// Errors that can be raised from this library.
#[derive(Error, Debug)]
pub enum ConnectorXError {
/// The required type does not same as the schema defined.
#[error("Data type unexpected: {0:?} expected, {1} found.")]
TypeCheckFailed(String, &'static str),
#[error("Data order not supported {0:?}.")]
UnsupportedDataOrder(DataOrder),
#[error("Cannot resolve data order: got {0:?} from source, {1:?} from destination.")]
CannotResolveDataOrder(Vec<DataOrder>, Vec<DataOrder>),
#[error("Cannot produce a {0}, context: {1}.")]
CannotProduce(&'static str, ProduceContext),
#[error("No conversion rule from {0} to {1}.")]
NoConversionRule(String, String),
#[error("Only support single query with SELECT statement, got {0}.")]
SqlQueryNotSupported(String),
#[error("Cannot get total number of rows in advance.")]
CountError(),
#[error(transparent)]
SQLParserError(#[from] sqlparser::parser::ParserError),
#[error(transparent)]
StdIOError(#[from] std::io::Error),
#[error(transparent)]
StdVarError(#[from] std::env::VarError),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
impl ConnectorXError {
pub fn cannot_produce<T>(context: Option<String>) -> Self {
ConnectorXError::CannotProduce(type_name::<T>(), context.into())
}
}
#[derive(Debug)]
pub enum ProduceContext {
NoContext,
Context(String),
}
impl From<Option<String>> for ProduceContext {
fn from(val: Option<String>) -> Self {
match val {
Some(c) => ProduceContext::Context(c),
None => ProduceContext::NoContext,
}
}
}
impl fmt::Display for ProduceContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ProduceContext::NoContext => write!(f, "No Context"),
ProduceContext::Context(s) => write!(f, "{}", s),
}
}
}
|
use crate::nes::cpu::bus::CpuBus;
use crate::nes::cpu::registers::Registers;
use crate::nes::cpu::controller::Controller;
use crate::nes::cpu::opecode::{Command, OPECODE_MAP, AddressingMode};
pub struct Calculator;
impl Calculator {
pub fn execute<T: CpuBus>(registers: &mut Registers, bus: &mut T) -> usize {
let run_opecode = Controller::fetch(registers, bus);
let opecode_rule = OPECODE_MAP.get(&run_opecode).unwrap();
let (command, mode, cycle) = (&opecode_rule.command, &opecode_rule.mode, opecode_rule.cycle);
let opeland = Controller::fetch_opeland(registers, bus, &mode);
match *command {
Command::LDA if *mode == AddressingMode::Immediate => Calculator::LDA_immediate(registers, opeland),
Command::LDA => Calculator::LDA(registers, bus, opeland),
Command::LDX if *mode == AddressingMode::Immediate => Calculator::LDX_immediate(registers, opeland),
Command::LDX => Calculator::LDX(registers, bus, opeland),
Command::LDY if *mode == AddressingMode::Immediate => Calculator::LDY_immediate(registers, opeland),
Command::LDY => Calculator::LDY(registers, bus, opeland),
Command::STA => Calculator::STA(registers, bus, opeland),
Command::STX => Calculator::STX(registers, bus, opeland),
Command::BNE => Calculator::BNE(registers, opeland),
Command::DEX => Calculator::DEX(registers),
Command::DEY => Calculator::DEY(registers),
Command::INX => Calculator::INX(registers),
Command::JMP => Calculator::JMP(registers, opeland),
Command::JSR => Calculator::JSR(registers, bus, opeland),
Command::SEI => Calculator::SEI(registers),
Command::TXS => Calculator::TXS(registers),
Command::TYA => Calculator::TYA(registers),
Command::CLD => Calculator::CLD(registers),
Command::CPX => Calculator::CPX(registers, bus, opeland),
Command::BPL => Calculator::BPL(registers, opeland),
_ => panic!("not unimplement command: {:?}", &command),
};
cycle
}
fn LDA<T: CpuBus>(registers: &mut Registers, bus: &mut T, opeland: u16) {
Calculator::LDA_immediate(registers, bus.read(opeland) as u16);
}
fn LDA_immediate(registers: &mut Registers, opeland: u16) {
registers.A = opeland as u8;
registers.update_negative(registers.A);
registers.update_zero(registers.A);
}
fn LDX<T: CpuBus>(registers: &mut Registers, bus: &mut T, opeland: u16) {
Calculator::LDX_immediate(registers, bus.read(opeland) as u16);
}
fn LDX_immediate(registers: &mut Registers, opeland: u16) {
registers.X = opeland as u8;
registers.update_negative(registers.X);
registers.update_zero(registers.X);
}
fn LDY<T: CpuBus>(registers: &mut Registers, bus: &mut T, opeland: u16) {
Calculator::LDY_immediate(registers, bus.read(opeland) as u16);
}
fn LDY_immediate(registers: &mut Registers, opeland: u16) {
registers.Y = opeland as u8;
registers.update_negative(registers.Y);
registers.update_zero(registers.Y);
}
fn STA<T: CpuBus>(registers: &Registers, bus: &mut T, opeland: u16) {
bus.write(opeland, registers.A);
}
fn STX<T: CpuBus>(registers: &Registers, bus: &mut T, opeland: u16) {
bus.write(opeland, registers.X);
}
fn TXS(registers: &mut Registers) {
registers.S = registers.X;
}
fn BNE(registers: &mut Registers, opeland: u16) {
if !registers.P.zero {
registers.PC = opeland;
}
}
fn DEX(registers: &mut Registers) {
registers.X = registers.X.wrapping_sub(1);
registers.update_negative(registers.X);
registers.update_zero(registers.X);
}
fn DEY(registers: &mut Registers) {
registers.Y = registers.Y.wrapping_sub(1);
registers.update_negative(registers.Y);
registers.update_zero(registers.Y);
}
fn INX(registers: &mut Registers) {
registers.X = registers.X.wrapping_add(1);
registers.update_negative(registers.X);
registers.update_zero(registers.X);
}
fn JMP(registers: &mut Registers, opeland: u16) {
registers.PC = opeland;
}
fn JSR<T: CpuBus>(registers: &mut Registers, bus: &mut T, opeland: u16) {
let pc = registers.PC - 1;
Calculator::push((pc >> 8) as u8, registers, bus);
Calculator::push(pc as u8, registers, bus);
registers.PC = opeland;
}
fn SEI(registers: &mut Registers) {
registers.P.interrupt = true;
}
fn CLD(registers: &mut Registers) {
registers.P.decimal = false;
}
fn BPL(registers: &mut Registers, opeland: u16) {
if !registers.P.negative {
registers.PC = opeland;
}
}
fn TYA(registers: &mut Registers) {
registers.A = registers.Y;
registers.update_negative(registers.A);
registers.update_zero(registers.A);
}
fn CPX<T: CpuBus>(registers: &mut Registers, bus: &mut T, opeland: u16) {
let data = bus.read(opeland);
let computed = registers.X as i16 - data as i16;
registers.update_negative(computed as u8);
registers.update_zero(computed as u8);
registers.set_carry(computed >= 0)
}
fn push<T: CpuBus>(data: u8, registers: &mut Registers, bus: &mut T) {
let addr = registers.S as u16;
bus.write(addr | 0x0100, data);
registers.S -= 1;
}
}
#[cfg(test)]
mod tests;
|
use crate::utils::hash;
const BITS_PER_KEY: u8 = 10;
const K: u8 = 6; // BITS_PER_KEY * ln(2)
pub struct BloomFilter {
array: Vec<u8>,
}
impl BloomFilter {
pub fn new(n_keys: usize) -> Self {
let bits = 64.max(BITS_PER_KEY as usize * n_keys);
let bytes = (bits + 7) / 8;
Self {
array: vec![0u8; bytes],
}
}
pub fn add(&mut self, key: &[u8]) {
let bits = self.array.len() * 8;
let mut h = hash(key);
let delta = h.rotate_right(17);
for _ in 0..K {
let bitpos = (h as usize) % bits;
self.array[bitpos / 8] |= 1 << (bitpos % 8);
h = h.wrapping_add(delta);
}
}
pub fn find(&self, key: &[u8]) -> bool {
let bits = self.array.len() * 8;
let mut h = hash(key);
let delta = h.rotate_right(17);
for _ in 0..K {
let bitpos = (h as usize) % bits;
if self.array[bitpos / 8] & (1 << (bitpos % 8)) == 0 {
return false;
}
h = h.wrapping_add(delta);
}
true
}
pub fn into_vec(self) -> Vec<u8> {
self.array.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bloomfilter() {
let limit = 100000;
let mut bf = BloomFilter::new(limit / 2);
for i in (0..limit).step_by(2) {
bf.add(&i.to_string().into_bytes());
}
let mut fp = 0.0;
for i in 0..limit {
let found = bf.find(&i.to_string().into_bytes());
if i % 2 == 0 {
assert_eq!(found, i % 2 == 0);
} else {
fp += found as u8 as f32;
}
}
let fp_ratio = fp / (limit as f32);
assert!(fp_ratio < 0.008);
}
}
|
use std::fmt;
#[derive(Clone, Copy)]
pub(crate) enum Color {
Black,
White,
}
impl Color {
pub(crate) fn rev(&self) -> Color {
match self {
Color::Black => Color::White,
Color::White => Color::Black,
}
}
pub(crate) fn sym(&self) -> &str {
match self {
Color::Black => "*",
Color::White => "o",
}
}
pub(crate) fn sym_empty() -> &'static str {
"-"
}
}
impl PartialEq for Color {
fn eq(&self, other: &Color) -> bool {
use color::Color::{Black, White};
match self {
White => { match other {
White => true,
Black => false,
}},
Black => { match other {
White => false,
Black => true,
}},
}
}
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", match self {
Color::Black => "Black",
Color::White => "White",
},
self.sym()
)
}
} |
// https://github.com/elliptic-email/rust-grpc-web/blob/master/examples/yew-wasm-client/src/main.rs
mod components;
mod state;
pub mod quotes {
include!(concat!(env!("OUT_DIR"), concat!("/chat.rs")));
}
use components::app::App;
use log::Level;
use sycamore::template;
fn main() {
console_log::init_with_level(Level::Debug).expect("error initializing logger");
sycamore::render(|| {
template! {
App()
}
});
}
|
use crate::blob::blob::Blob;
use crate::xml::read_xml;
use azure_core::headers::{date_from_headers, request_id_from_headers};
use azure_core::prelude::NextMarker;
use azure_core::RequestId;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use std::convert::TryFrom;
#[derive(Debug, Clone, PartialEq)]
pub struct ListBlobsResponse {
pub prefix: Option<String>,
pub max_results: Option<u32>,
pub delimiter: Option<String>,
pub next_marker: Option<NextMarker>,
pub blobs: Blobs,
pub request_id: RequestId,
pub date: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct ListBlobsResponseInternal {
pub prefix: Option<String>,
pub max_results: Option<u32>,
pub delimiter: Option<String>,
pub next_marker: Option<String>,
pub blobs: Blobs,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Blobs {
pub blob_prefix: Option<Vec<BlobPrefix>>,
#[serde(rename = "Blob", default = "Vec::new")]
pub blobs: Vec<Blob>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BlobPrefix {
pub name: String,
}
impl TryFrom<&http::Response<Bytes>> for ListBlobsResponse {
type Error = crate::Error;
fn try_from(response: &http::Response<Bytes>) -> Result<Self, Self::Error> {
let body = response.body();
trace!("body == {:?}", body);
let list_blobs_response_internal: ListBlobsResponseInternal = read_xml(body)?;
Ok(Self {
request_id: request_id_from_headers(response.headers())?,
date: date_from_headers(response.headers())?,
prefix: list_blobs_response_internal.prefix,
max_results: list_blobs_response_internal.max_results,
delimiter: list_blobs_response_internal.delimiter,
blobs: list_blobs_response_internal.blobs,
next_marker: NextMarker::from_possibly_empty_string(
list_blobs_response_internal.next_marker,
),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserde_azure() {
const S: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<EnumerationResults ServiceEndpoint=\"https://azureskdforrust.blob.core.windows.net/\" ContainerName=\"osa2\">
<Blobs>
<Blob>
<Name>blob0.txt</Name>
<Properties>
<Creation-Time>Thu, 01 Jul 2021 10:44:59 GMT</Creation-Time>
<Last-Modified>Thu, 01 Jul 2021 10:44:59 GMT</Last-Modified>
<Etag>0x8D93C7D4629C227</Etag>
<Content-Length>8</Content-Length>
<Content-Type>text/plain</Content-Type>
<Content-Encoding />
<Content-Language />
<Content-CRC64 />
<Content-MD5>rvr3UC1SmUw7AZV2NqPN0g==</Content-MD5>
<Cache-Control />
<Content-Disposition />
<BlobType>BlockBlob</BlobType>
<AccessTier>Hot</AccessTier>
<AccessTierInferred>true</AccessTierInferred>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
<ServerEncrypted>true</ServerEncrypted>
</Properties>
<Metadata><userkey>uservalue</userkey></Metadata>
<OrMetadata />
</Blob>
<Blob>
<Name>blob1.txt</Name>
<Properties>
<Creation-Time>Thu, 01 Jul 2021 10:44:59 GMT</Creation-Time>
<Last-Modified>Thu, 01 Jul 2021 10:44:59 GMT</Last-Modified>
<Etag>0x8D93C7D463004D6</Etag>
<Content-Length>8</Content-Length>
<Content-Type>text/plain</Content-Type>
<Content-Encoding />
<Content-Language />
<Content-CRC64 />
<Content-MD5>rvr3UC1SmUw7AZV2NqPN0g==</Content-MD5>
<Cache-Control />
<Content-Disposition />
<BlobType>BlockBlob</BlobType>
<AccessTier>Hot</AccessTier>
<AccessTierInferred>true</AccessTierInferred>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
<ServerEncrypted>true</ServerEncrypted>
</Properties>
<OrMetadata />
</Blob>
<Blob>
<Name>blob2.txt</Name>
<Properties>
<Creation-Time>Thu, 01 Jul 2021 10:44:59 GMT</Creation-Time>
<Last-Modified>Thu, 01 Jul 2021 10:44:59 GMT</Last-Modified>
<Etag>0x8D93C7D4636478A</Etag>
<Content-Length>8</Content-Length>
<Content-Type>text/plain</Content-Type>
<Content-Encoding />
<Content-Language />
<Content-CRC64 />
<Content-MD5>rvr3UC1SmUw7AZV2NqPN0g==</Content-MD5>
<Cache-Control />
<Content-Disposition />
<BlobType>BlockBlob</BlobType>
<AccessTier>Hot</AccessTier>
<AccessTierInferred>true</AccessTierInferred>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
<ServerEncrypted>true</ServerEncrypted>
</Properties>
<OrMetadata />
</Blob>
</Blobs>
<NextMarker />
</EnumerationResults>";
let bytes = Bytes::from(S);
let _list_blobs_response_internal: ListBlobsResponseInternal = read_xml(&bytes).unwrap();
}
#[test]
fn deserde_azurite() {
const S: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<EnumerationResults ServiceEndpoint=\"http://127.0.0.1:10000/devstoreaccount1\" ContainerName=\"osa2\">
<Prefix/>
<Marker/>
<MaxResults>5000</MaxResults>
<Delimiter/>
<Blobs>
<Blob>
<Name>blob0.txt</Name>
<Properties>
<Creation-Time>Thu, 01 Jul 2021 10:45:02 GMT</Creation-Time>
<Last-Modified>Thu, 01 Jul 2021 10:45:02 GMT</Last-Modified>
<Etag>0x228281B5D517B20</Etag>
<Content-Length>8</Content-Length>
<Content-Type>text/plain</Content-Type>
<Content-MD5>rvr3UC1SmUw7AZV2NqPN0g==</Content-MD5>
<BlobType>BlockBlob</BlobType>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
<ServerEncrypted>true</ServerEncrypted>
<AccessTier>Hot</AccessTier>
<AccessTierInferred>true</AccessTierInferred>
<AccessTierChangeTime>Thu, 01 Jul 2021 10:45:02 GMT</AccessTierChangeTime>
</Properties>
</Blob>
<Blob>
<Name>blob1.txt</Name>
<Properties>
<Creation-Time>Thu, 01 Jul 2021 10:45:02 GMT</Creation-Time>
<Last-Modified>Thu, 01 Jul 2021 10:45:02 GMT</Last-Modified>
<Etag>0x1DD959381A8A860</Etag>
<Content-Length>8</Content-Length>
<Content-Type>text/plain</Content-Type>
<Content-MD5>rvr3UC1SmUw7AZV2NqPN0g==</Content-MD5>
<BlobType>BlockBlob</BlobType>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
<ServerEncrypted>true</ServerEncrypted>
<AccessTier>Hot</AccessTier>
<AccessTierInferred>true</AccessTierInferred>
<AccessTierChangeTime>Thu, 01 Jul 2021 10:45:02 GMT</AccessTierChangeTime>
</Properties>
</Blob>
<Blob>
<Name>blob2.txt</Name>
<Properties>
<Creation-Time>Thu, 01 Jul 2021 10:45:02 GMT</Creation-Time>
<Last-Modified>Thu, 01 Jul 2021 10:45:02 GMT</Last-Modified>
<Etag>0x1FBE9C9B0C7B650</Etag>
<Content-Length>8</Content-Length>
<Content-Type>text/plain</Content-Type>
<Content-MD5>rvr3UC1SmUw7AZV2NqPN0g==</Content-MD5>
<BlobType>BlockBlob</BlobType>
<LeaseStatus>unlocked</LeaseStatus>
<LeaseState>available</LeaseState>
<ServerEncrypted>true</ServerEncrypted>
<AccessTier>Hot</AccessTier>
<AccessTierInferred>true</AccessTierInferred>
<AccessTierChangeTime>Thu, 01 Jul 2021 10:45:02 GMT</AccessTierChangeTime>
</Properties>
</Blob>
</Blobs>
<NextMarker/>
</EnumerationResults>";
let bytes = Bytes::from(S);
let _list_blobs_response_internal: ListBlobsResponseInternal = read_xml(&bytes).unwrap();
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{Error, ResultExt},
fidl_fuchsia_bluetooth_le::{PeripheralMarker, PeripheralProxy},
fidl_fuchsia_bluetooth_test::HciEmulatorProxy,
fuchsia_async as fasync,
fuchsia_bluetooth::{
expectation::asynchronous::{ExpectableState, ExpectationHarness},
types::emulator::LegacyAdvertisingState,
},
futures::{select, Future, FutureExt},
pin_utils::pin_mut,
};
use crate::harness::{control::ActivatedFakeHost, TestHarness};
/// A snapshot of the current LE peripheral procedure states of the controller.
#[derive(Clone)]
pub struct PeripheralState {
/// Observed changes to the controller's advertising state and parameters.
pub advertising_state_changes: Vec<LegacyAdvertisingState>,
}
impl PeripheralState {
/// Resets to the default state.
pub fn reset(&mut self) {
self.advertising_state_changes.clear();
}
}
impl Default for PeripheralState {
fn default() -> PeripheralState {
PeripheralState { advertising_state_changes: Vec::new() }
}
}
pub struct PeripheralHarnessAux {
proxy: PeripheralProxy,
emulator: HciEmulatorProxy,
}
impl PeripheralHarnessAux {
fn new(proxy: PeripheralProxy, emulator: HciEmulatorProxy) -> PeripheralHarnessAux {
PeripheralHarnessAux { proxy, emulator }
}
pub fn proxy(&self) -> &PeripheralProxy {
&self.proxy
}
pub fn emulator(&self) -> &HciEmulatorProxy {
&self.emulator
}
}
pub type PeripheralHarness = ExpectationHarness<PeripheralState, PeripheralHarnessAux>;
impl TestHarness for PeripheralHarness {
fn run_with_harness<F, Fut>(test_func: F) -> Result<(), Error>
where
F: FnOnce(Self) -> Fut,
Fut: Future<Output = Result<(), Error>>,
{
let mut executor = fasync::Executor::new().context("error creating event loop")?;
executor.run_singlethreaded(run_peripheral_test_async(test_func))
}
}
async fn run_peripheral_test_async<F, Fut>(test: F) -> Result<(), Error>
where
F: FnOnce(PeripheralHarness) -> Fut,
Fut: Future<Output = Result<(), Error>>,
{
// Don't drop the ActivatedFakeHost until the end of this function.
let host = ActivatedFakeHost::new("bt-integration-le-peripheral").await?;
let proxy = fuchsia_component::client::connect_to_service::<PeripheralMarker>()
.context("Failed to connect to BLE Peripheral service")?;
let state = PeripheralHarness::new(PeripheralHarnessAux::new(proxy, host.emulator().clone()));
// Initialize the state update watcher and the test run tasks.
let watch = watch_advertising_state(state.clone());
let run_test = test(state);
// Run until one of the tasks finishes.
pin_mut!(watch);
pin_mut!(run_test);
let result = select! {
watch_result = watch.fuse() => watch_result,
test_result = run_test.fuse() => test_result,
};
host.release().await?;
result
}
async fn watch_advertising_state(harness: PeripheralHarness) -> Result<(), Error> {
loop {
let states = harness.aux().emulator().watch_legacy_advertising_states().await?;
harness
.write_state()
.advertising_state_changes
.append(&mut states.into_iter().map(|s| s.into()).collect());
harness.notify_state_changed();
}
}
|
extern crate num;
use num::*;
fn main() {
let mut x = 0.0;
let e = eventListener{parameter: &x,event: event,callback: callback };
while true {
x += 1.0;
e.check();
}
}
fn callback(){
println!("Event happened");
}
fn event<A: Float + >(val: &A) -> bool
{
match val {
f64 => val > 50.0,
i64 => val > 40,
}
}
#[derive(Debug)]
struct eventListener<'a, A>
{
parameter: &'a A,
event: fn(&'a A) -> bool,
callback: fn()
}
impl<'a,A> eventListener<'a,A>
{
fn check(&self) {
if (self.event)(self.parameter) {
(self.callback)();
}
}
}
|
use std::{
fs::File,
io::{self, Cursor, Read},
path::PathBuf,
sync::Arc,
};
use super::{
cert_resolver::CertResolver,
rustls,
untrusted,
webpki,
};
/// Not-yet-validated settings that are used for both TLS clients and TLS
/// servers.
///
/// The trust anchors are stored in PEM format because, in Kubernetes, they are
/// stored in a ConfigMap, and until very recently Kubernetes cannot store
/// binary data in ConfigMaps. Also, PEM is the most interoperable way to
/// distribute trust anchors, especially if it is desired to support multiple
/// trust anchors at once.
///
/// The end-entity certificate and private key are in DER format because they
/// are stored in the secret store where space utilization is a concern, and
/// because PEM doesn't offer any advantages.
#[derive(Debug)]
pub struct CommonSettings {
/// The trust anchors as concatenated PEM-encoded X.509 certificates.
pub trust_anchors: PathBuf,
/// The end-entity certificate as a DER-encoded X.509 certificate.
pub end_entity_cert: PathBuf,
/// The private key in DER-encoded PKCS#8 form.
pub private_key: PathBuf,
}
/// Validated configuration common between TLS clients and TLS servers.
pub struct CommonConfig {
cert_resolver: Arc<CertResolver>,
}
/// Validated configuration for TLS servers.
#[derive(Clone)]
pub struct ServerConfig(pub(super) Arc<rustls::ServerConfig>);
#[derive(Debug)]
pub enum Error {
Io(PathBuf, io::Error),
FailedToParsePrivateKey,
FailedToParseTrustAnchors(Option<webpki::Error>),
EmptyEndEntityCert,
EndEntityCertIsNotValid(webpki::Error),
InvalidPrivateKey,
TimeConversionFailed,
}
impl CommonConfig {
/// Loads a configuration from the given files and validates it. If an
/// error is returned then the caller should try again after the files are
/// updated.
///
/// In a valid configuration, all the files need to be in sync with each
/// other. For example, the private key file must contain the private
/// key for the end-entity certificate, and the end-entity certificate
/// must be issued by the CA represented by a certificate in the
/// trust anchors file. Since filesystem operations are not atomic, we
/// need to check for this consistency.
pub fn load_from_disk(settings: &CommonSettings) -> Result<Self, Error> {
let trust_anchor_certs = load_file_contents(&settings.trust_anchors)
.and_then(|file_contents|
rustls::internal::pemfile::certs(&mut Cursor::new(file_contents))
.map_err(|()| Error::FailedToParseTrustAnchors(None)))?;
let mut trust_anchors = Vec::with_capacity(trust_anchor_certs.len());
for ta in &trust_anchor_certs {
let ta = webpki::trust_anchor_util::cert_der_as_trust_anchor(
untrusted::Input::from(ta.as_ref()))
.map_err(|e| Error::FailedToParseTrustAnchors(Some(e)))?;
trust_anchors.push(ta);
}
let trust_anchors = webpki::TLSServerTrustAnchors(&trust_anchors);
let end_entity_cert = load_file_contents(&settings.end_entity_cert)?;
// XXX: Assume there are no intermediates since there is no way to load
// them yet.
let cert_chain = vec![rustls::Certificate(end_entity_cert)];
// Load the private key after we've validated the certificate.
let private_key = load_file_contents(&settings.private_key)?;
let private_key = untrusted::Input::from(&private_key);
// `CertResolver::new` is responsible for the consistency check.
let cert_resolver = CertResolver::new(&trust_anchors, cert_chain, private_key)?;
Ok(Self {
cert_resolver: Arc::new(cert_resolver),
})
}
}
impl ServerConfig {
pub fn from(common: &CommonConfig) -> Self {
let mut config = rustls::ServerConfig::new(Arc::new(rustls::NoClientAuth));
set_common_settings(&mut config.versions);
config.cert_resolver = common.cert_resolver.clone();
ServerConfig(Arc::new(config))
}
}
fn load_file_contents(path: &PathBuf) -> Result<Vec<u8>, Error> {
fn load_file(path: &PathBuf) -> Result<Vec<u8>, io::Error> {
let mut result = Vec::new();
let mut file = File::open(path)?;
loop {
match file.read_to_end(&mut result) {
Ok(_) => {
return Ok(result);
},
Err(e) => {
if e.kind() != io::ErrorKind::Interrupted {
return Err(e);
}
},
}
}
}
load_file(path)
.map(|contents| {
trace!("loaded file {:?}", path);
contents
})
.map_err(|e| Error::Io(path.clone(), e))
}
fn set_common_settings(versions: &mut Vec<rustls::ProtocolVersion>) {
// Only enable TLS 1.2 until TLS 1.3 is stable.
*versions = vec![rustls::ProtocolVersion::TLSv1_2]
}
|
use std::collections::HashMap;
use regex::Regex;
pub fn run() {
let valid_passports = count_valid_passports(include_str!("input.txt"));
println!("Day04 - Part 1: {}", valid_passports.0);
println!("Day04 - Part 2: {}", valid_passports.1);
}
fn count_valid_passports(pp_str: &str) -> (i32, i32) {
let pp_data: Vec<&str> = pp_str.split("\n\n")
.collect();
let mut valid_passports = 0;
let mut valid_and_validated = 0;
for pp in pp_data {
let passport = Passport::from_str(pp);
if passport.is_valid() {
valid_passports += 1;
}
if passport.is_valid_and_validated() {
valid_and_validated += 1;
}
}
(valid_passports, valid_and_validated)
}
struct Passport {
passport_data: HashMap<String, String>
}
impl Passport {
fn from_str (pp_str: &str) -> Self {
let mut data = HashMap::new();
let values = pp_str.trim().split(|c| c == ' ' || c == '\n');
for val in values {
let key_val: Vec<&str> = val.split(":").collect();
data.insert(String::from(key_val[0]), String::from(key_val[1]));
}
Self { passport_data: data }
}
fn is_valid(&self) -> bool {
self.passport_data.len() > 7 ||
(self.passport_data.len() > 6 && !self.passport_data.contains_key("cid"))
}
// ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
fn is_valid_ecl(&self) -> bool {
match self.passport_data.get("ecl") {
Some(ecl) => {
match ecl.as_ref() {
"amb" | "blu" | "brn" | "gry" | "grn" | "hzl" | "oth" => true,
_ => false
}
},
None => false
}
}
// hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
fn is_valid_hcl(&self) -> bool {
lazy_static! {
static ref HCL_RE: Regex = Regex::new("^#[0-9a-fA-F]{6}$").unwrap();
}
match self.passport_data.get("hcl") {
Some(hgt) => HCL_RE.is_match(hgt),
None => false
}
}
// pid (Passport ID) - a nine-digit number, including leading zeroes.
fn is_valid_pid(&self) -> bool {
lazy_static! {
static ref PID_RE: Regex = Regex::new("^[0-9]{9}$").unwrap();
}
match self.passport_data.get("pid") {
Some(hgt) => PID_RE.is_match(hgt),
None => false
}
}
// hgt (Height) - a number followed by either cm or in:
// If cm, the number must be at least 150 and at most 193.
// If in, the number must be at least 59 and at most 76.
fn is_valid_hgt(&self) -> bool {
match self.passport_data.get("hgt") {
Some(hgt) => Passport::validate_hgt(hgt),
None => false
}
}
fn validate_hgt(hgt: &str) -> bool {
let (hgt, unit) = hgt.split_at(hgt.len()-2);
let hgt: i32 = match hgt.parse() {
Ok(h) => h,
Err(_) => 0
};
match unit {
"cm" => hgt >= 150 && hgt <= 193,
"in" => hgt >= 59 && hgt <= 76,
_ => false
}
}
// byr (Birth Year) - four digits; at least 1920 and at most 2002.
fn is_valid_byr(&self) -> bool {
self.is_year_field_between("byr", 1920, 2002)
}
// iyr (Issue Year) - four digits; at least 2010 and at most 2020.
fn is_valid_iyr(&self) -> bool {
self.is_year_field_between("iyr", 2010, 2020)
}
// eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
fn is_valid_eyr(&self) -> bool {
self.is_year_field_between("eyr", 2020, 2030)
}
fn is_year_field_between(&self, field: &str, from: i32, to: i32) -> bool {
match self.passport_data.get(field) {
Some(year) => {
let y: i32 = year.parse().expect(&format!("Could not parse {}", field));
y >= from && y<= to
},
None => false
}
}
fn is_valid_and_validated(&self) -> bool {
self.is_valid_byr() &&
self.is_valid_iyr() &&
self.is_valid_eyr() &&
self.is_valid_hgt() &&
self.is_valid_ecl() &&
self.is_valid_hcl() &&
self.is_valid_pid()
}
}
#[cfg(test)]
mod tests {
use super::*;
static TEST_INPUT: &str = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in";
static VALID_PASSPORT: &str = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm";
static VALID_NORTH_POLE_CRED: &str = "hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm";
static INVALIDATED_PASSPORTS: &str = "eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007";
static VALIDATED_PASSPORTS: &str = "pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f
eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022
iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719";
#[test]
fn test_split_string_on_empty_line() {
let passports: Vec<&str> = TEST_INPUT.split("\n\n")
.collect();
assert_eq!(4, passports.len());
}
#[test]
fn test_valid_passport_from_string() {
let passport = Passport::from_str(VALID_PASSPORT);
assert!(passport.is_valid());
}
#[test]
fn test_north_pole_cred_from_string() {
let passport = Passport::from_str(VALID_NORTH_POLE_CRED);
assert!(passport.is_valid());
}
#[test]
fn test_count_valid_passports() {
let valid_passports = count_valid_passports(TEST_INPUT);
assert_eq!(2, valid_passports.0);
}
#[test]
fn test_count_invalidated_passports() {
let valid_passports = count_valid_passports(INVALIDATED_PASSPORTS);
assert_eq!(0, valid_passports.1);
}
#[test]
fn test_count_validated_passports() {
let valid_passports = count_valid_passports(VALIDATED_PASSPORTS);
assert_eq!(4, valid_passports.1);
}
#[test]
fn test_invalidated_passport_pid() {
let passport = Passport::from_str("pid:08749970004 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#62ffff");
assert_eq!(false, passport.is_valid_and_validated());
}
#[test]
fn test_invalidated_passport_hcl() {
let passport = Passport::from_str("pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2faa");
assert_eq!(false, passport.is_valid_and_validated());
}
}
|
#![allow(dead_code)]
extern crate getopts;
extern crate time;
extern crate zip;
mod appimage;
mod bootstrap;
mod util;
use getopts::Options;
use std::env;
use std::io::stdout;
fn print_help(options: &Options) {
println!("{}", options.usage("Usage: appimagezip [OPTIONS] SOURCE"));
}
fn main() {
let mut options = Options::new();
options.optflag("h", "help", "Show this help message");
options.optopt("o", "output", "Write the AppImage to FILE", "FILE");
options.optopt("", "target", "Build for the target triple", "TRIPLE");
options.optflag("D", "dump-bootstrap", "Dump the runtime bootstrap binary");
options.optflag("v", "version", "Show version info");
let args = options.parse(env::args()).unwrap();
if args.opt_present("h") {
print_help(&options);
return;
}
if args.opt_present("v") {
println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
return;
}
if args.opt_present("D") {
bootstrap::write(stdout());
return;
}
let output_file = args.opt_str("o").unwrap_or(String::from("Out.AppImage"));
let app_dir = args.free.get(1);
if let Some(app_dir) = app_dir {
let creator = appimage::Creator::new(app_dir);
match creator.write_to_file(&output_file) {
Ok(_) => {
println!("Created AppImage: {:?}", output_file);
},
Err(e) => {
println!("Error: {}", e);
},
}
}
}
|
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
//! Utilities for converting between Windows and Rust types, including strings.
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::HRESULT;
#[derive(Debug)]
pub enum Error {
Null,
Hr(HRESULT),
}
/*
pub fn as_result(hr: HRESULT) -> Result<(), Error> {
match hr {
S_OK => Ok(()),
_ => Err(Error::Hr(hr)),
}
}
*/
impl From<HRESULT> for Error {
fn from(hr: HRESULT) -> Error {
Error::Hr(hr)
}
}
pub trait ToWide {
fn to_wide_sized(&self) -> Vec<u16>;
fn to_wide(&self) -> Vec<u16>;
}
impl<T> ToWide for T where T: AsRef<OsStr> {
fn to_wide_sized(&self) -> Vec<u16> {
self.as_ref().encode_wide().collect()
}
fn to_wide(&self) -> Vec<u16> {
self.as_ref().encode_wide().chain(Some(0)).collect()
}
}
|
use std::sync::{Arc, Mutex};
use rustful::{Context};
use serde_json as json;
use files::{LoadedFiles, LoadedFile};
use serve::api;
use serve::api::ToAPIResult;
#[derive(Serialize)]
struct FileInfo {
pub id: usize,
pub filename: String,
pub language: json::Value,
}
impl FileInfo {
fn new(id: usize, f: &LoadedFile) -> FileInfo {
FileInfo {
id: id,
filename: f.filename.clone(),
language: f.parse_tree.language_json()
}
}
}
pub struct OneFile(pub Arc<Mutex<LoadedFiles>>);
impl api::Endpoint for OneFile {
type Data = FileInfo;
fn get_results(&self, context: Context) -> api::Result<Self::Data> {
let files = (&*self.0).lock().unwrap();
let id_str = context.variables.get("file").unwrap();
let id = api_try!(id_str.parse().api_result("file"));
let file = api_try!(files.find_by_id(id).api_result("file"));
api::Result::Data(FileInfo::new(id, file))
}
}
pub struct AllFiles(pub Arc<Mutex<LoadedFiles>>);
impl api::Endpoint for AllFiles {
type Data = Vec<FileInfo>;
fn get_results(&self, _context: Context) -> api::Result<Self::Data> {
let files = (&*self.0).lock().unwrap();
let file_infos = files.iter().map(|(id, f)| FileInfo::new(id, f)).collect();
api::Result::Data(file_infos)
}
}
|
/*
* 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.
*/
use bytes::BytesMut;
use crate::gdbstub::commands::*;
use crate::gdbstub::hex::*;
#[derive(PartialEq, Debug)]
pub struct X {
pub addr: u64,
pub length: usize,
pub vals: Vec<u8>,
}
impl ParseCommand for X {
fn parse(mut bytes: BytesMut) -> Option<Self> {
let mut first_colon = None;
let mut index = 0;
for &b in &bytes {
if b == b':' {
first_colon = Some(index);
break;
} else {
index += 1;
}
}
let (addr_len, vals) = bytes.split_at_mut(first_colon?);
let mut iter = addr_len.split_mut(|c| *c == b',');
let addr = iter.next().and_then(|s| decode_hex(s).ok())?;
let len = iter.next().and_then(|s| decode_hex(s).ok())?;
Some(X {
addr,
length: len,
vals: decode_binary_string(&vals[1..]).ok()?,
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn can_parse_X_special() {
// Sending packet: $X216eb0,4:,\000\000\000#ae...Packet received: OK
assert_eq!(
X::parse(BytesMut::from("216eb0,4:,\0\0\0")),
Some(X {
addr: 0x216eb0,
length: 4,
vals: vec![0x2c, 0x0, 0x0, 0x0],
})
);
// Sending packet: $X216eb0,4::\000\000\000#bc...Packet received: OK
assert_eq!(
X::parse(BytesMut::from("216eb0,4::\0\0\0")),
Some(X {
addr: 0x216eb0,
length: 4,
vals: vec![0x3a, 0x0, 0x0, 0x0],
})
);
}
}
|
use sdl2::keyboard::Keycode;
pub const fn scan_key(keycode: Keycode) -> Option<usize> {
match keycode {
// numbers
Keycode::Num1 => Some(0),
Keycode::Num2 => Some(1),
Keycode::Num3 => Some(2),
Keycode::Num4 => Some(3),
// letters
Keycode::Q => Some(4),
Keycode::W => Some(5),
Keycode::E => Some(6),
Keycode::R => Some(7),
Keycode::A => Some(8),
Keycode::S => Some(9),
Keycode::D => Some(10),
Keycode::F => Some(11),
Keycode::Z => Some(12),
Keycode::X => Some(13),
Keycode::C => Some(14),
Keycode::V => Some(15),
_ => Option::None,
}
}
|
use crate::{Bin, Boo, SBin, SStr, Str};
/// Borrowed-or-owned `Bin`.
pub type BooBin<'a> = Boo<'a, [u8], Bin>;
/// Borrowed-or-owned `SBin`.
pub type BooSBin<'a> = Boo<'a, [u8], SBin>;
/// Borrowed-or-owned `Str`.
pub type BooStr<'a> = Boo<'a, str, Str>;
/// Borrowed-or-owned `SStr`.
pub type BooSStr<'a> = Boo<'a, str, SStr>;
|
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub(super) mod mask_32;
#[cfg(target_arch = "x86_64")]
pub(super) mod mask_64;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub(super) mod vector_128;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub(super) mod vector_256;
#[allow(unused_macros)]
macro_rules! quote_classifier {
($name:ident, $core:ident, $size:literal, $mask_ty:ty) => {
pub(crate) struct $name<'i, I>
where
I: InputBlockIterator<'i, $size>,
{
iter: I,
classifier: $core,
phantom: PhantomData<&'i ()>,
}
impl<'i, I> $name<'i, I>
where
I: InputBlockIterator<'i, $size>,
{
#[inline]
#[allow(dead_code)]
pub(crate) fn new(iter: I) -> Self {
Self {
iter,
classifier: $core::new(),
phantom: PhantomData,
}
}
#[inline]
#[allow(dead_code)]
pub(crate) fn resume(
iter: I,
first_block: Option<I::Block>,
) -> (Self, Option<QuoteClassifiedBlock<I::Block, $mask_ty, $size>>) {
let mut s = Self {
iter,
classifier: $core::new(),
phantom: PhantomData,
};
let block = first_block.map(|b| {
// SAFETY: target feature invariant
let mask = unsafe { s.classifier.classify(&b) };
QuoteClassifiedBlock {
block: b,
within_quotes_mask: mask,
}
});
(s, block)
}
}
impl<'i, I> FallibleIterator for $name<'i, I>
where
I: InputBlockIterator<'i, $size>,
{
type Item = QuoteClassifiedBlock<I::Block, $mask_ty, $size>;
type Error = InputError;
fn next(&mut self) -> Result<Option<Self::Item>, Self::Error> {
match self.iter.next()? {
Some(block) => {
// SAFETY: target_feature invariant
let mask = unsafe { self.classifier.classify(&block) };
let classified_block = QuoteClassifiedBlock {
block,
within_quotes_mask: mask,
};
Ok(Some(classified_block))
}
None => Ok(None),
}
}
}
impl<'i, I> QuoteClassifiedIterator<'i, I, $mask_ty, $size> for $name<'i, I>
where
I: InputBlockIterator<'i, $size>,
{
fn get_offset(&self) -> usize {
self.iter.get_offset() - $size
}
fn offset(&mut self, count: isize) {
debug_assert!(count >= 0);
debug!("Offsetting by {count}");
if count == 0 {
return;
}
self.iter.offset(count);
}
fn flip_quotes_bit(&mut self) {
self.classifier.internal_classifier.flip_prev_quote_mask();
}
}
impl<'i, I> InnerIter<I> for $name<'i, I>
where
I: InputBlockIterator<'i, $size>,
{
fn into_inner(self) -> I {
self.iter
}
}
};
}
#[allow(unused_imports)]
pub(crate) use quote_classifier;
|
pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
let (mut m, mut n) = (nums1.len(), nums2.len());
let (mut a, mut b) = (nums1, nums2);
if m >= n {
let tmp = a;
a = b;
b = tmp;
m = a.len();
n = b.len();
}
let mut min = 0;
let mut max = m;
let half = (m + n + 1) / 2;
while min <= max {
let i = (min + max) / 2;
let j = half - i;
if i < max && b.get(j - 1) > a.get(i) {
min = i + 1; // i 太小了
} else if i > min && a.get(i - 1) > b.get(j) {
max = i - 1; // i 太大了
} else {
// i 正好是中位
let left_max = if i == 0 {
b.get(j - 1).unwrap()
} else if j == 0 {
a.get(i - 1).unwrap()
} else {
a.get(i - 1).unwrap().max(b.get(j - 1).unwrap())
};
// 如果是奇数,left_max 就是中位数
if (m + n) % 2 == 1 {
return *left_max as f64;
}
let right_min = if i == m {
b.get(j).unwrap()
} else if j == n {
a.get(i).unwrap()
} else {
b.get(j).unwrap().min(a.get(i).unwrap())
};
return (left_max + right_min) as f64 / 2.0;
}
}
0.0
}
#[cfg(test)]
mod test {
use crate::find_median_sorted_arrays::find_median_sorted_arrays;
#[test]
fn test_find_median_sorted_arrays() {
assert_eq!(find_median_sorted_arrays(vec![1, 3], vec![2]), 2.0);
assert_eq!(find_median_sorted_arrays(vec![1, 2], vec![3, 4]), 2.5);
}
}
|
mod buckets;
mod cache;
pub mod commands;
mod config;
mod context;
pub mod logging;
mod redis_cache;
mod stats;
pub use cache::{Cache, CacheMiss};
pub use commands::{Command, CommandGroup, CommandGroups, CMD_GROUPS};
pub use config::{BotConfig, CONFIG};
pub use context::{
AssignRoles, Clients, Context, ContextData, MatchLiveChannels, MatchTrackResult, Redis,
};
pub use redis_cache::{ArchivedBytes, RedisCache};
pub use stats::BotStats;
|
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy_per_link(&link_length, &hinge_mass, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_relative_helmholtz_free_energy(number_of_links: u8, link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy(&number_of_links, &link_length, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_relative_helmholtz_free_energy_per_link(link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy_per_link(&link_length, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_nondimensional_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_nondimensional_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy_per_link(&link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_nondimensional_relative_helmholtz_free_energy(number_of_links: u8, nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy(&number_of_links, &nondimensional_link_stiffness, &nondimensional_force)
}
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_legendre_nondimensional_relative_helmholtz_free_energy_per_link(nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_link_stiffness, &nondimensional_force)
} |
extern crate document;
extern crate xpath;
use std::collections::hashmap::HashMap;
use document::{Document,ToAny};
use xpath::{XPathEvaluationContext,XPathFactory};
use xpath::expression::XPathExpression;
fn main() {
let mut args = std::os::args();
let arg = match args.remove(1) {
Some(x) => x,
None => { println!("XPath required"); return; },
};
let factory = XPathFactory::new();
let expr = match factory.build(arg.as_slice()) {
Err(x) => { println!("Unable to compile XPath: {}", x); return; },
Ok(None) => { println!("Unable to compile XPath"); return; },
Ok(Some(x)) => x,
};
let d = Document::new();
let mut functions = HashMap::new();
xpath::function::register_core_functions(& mut functions);
let variables = HashMap::new();
let mut context = XPathEvaluationContext::new(d.root().to_any(),
&functions,
&variables);
context.next(d.root().to_any());
let res = expr.evaluate(&context);
println!("{}", res);
}
|
use crate::{ArgMatchesExt, Result};
use clap::{App, Arg, ArgGroup, ArgMatches};
use ronor::Sonos;
pub const NAME: &str = "skip";
pub fn build() -> App<'static, 'static> {
App::new(NAME)
.about("Go to next or previous track in the given group")
.arg(crate::household_arg())
.arg(
Arg::with_name("NEXT")
.short("n")
.long("next-track")
.help("Skip to next track")
)
.arg(
Arg::with_name("PREVIOUS")
.short("p")
.long("previous-track")
.help("Skip to previous track")
)
.group(ArgGroup::with_name("DIRECTION").args(&["NEXT", "PREVIOUS"]))
.arg(Arg::with_name("GROUP").required(true))
}
pub fn run(sonos: &mut Sonos, matches: &ArgMatches) -> Result<()> {
let household = matches.household(sonos)?;
let targets = sonos.get_groups(&household)?;
let group = matches.group(&targets.groups)?;
if matches.is_present("NEXT") {
sonos.skip_to_next_track(&group)
} else {
sonos.skip_to_previous_track(&group)
}?;
Ok(())
}
|
use super::prelude::*;
use super::schema::executor_processor_bind;
#[derive(Queryable, AsChangeset, Identifiable, Debug, Clone, Serialize, Deserialize)]
#[table_name = "executor_processor_bind"]
pub struct ExecutorProcessorBind {
id: i64,
name: String,
group_id: i64,
executor_id: i64,
weight: i16,
created_time: NaiveDateTime,
}
#[derive(Queryable, AsChangeset, Identifiable, Debug, Clone, Serialize, Deserialize)]
#[table_name = "executor_processor_bind"]
pub struct UpdateExecutorProcessorBind {
id: i64,
name: String,
group_id: i64,
executor_id: i64,
weight: i16,
}
#[derive(Queryable, AsChangeset, Identifiable, Debug, Clone, Serialize, Deserialize)]
#[table_name = "executor_processor_bind"]
pub struct BindingSelection {
id: i64,
#[serde(rename(serialize = "title"))]
name: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NewExecutorProcessorBinds {
pub(crate) name: String,
pub(crate) group_id: i64,
pub(crate) executor_ids: Vec<i64>,
pub(crate) weight: i16,
}
#[derive(Insertable, AsChangeset, Debug, Serialize, Deserialize)]
#[table_name = "executor_processor_bind"]
pub struct NewExecutorProcessorBind {
pub(crate) name: String,
pub(crate) group_id: i64,
pub(crate) executor_id: i64,
pub(crate) weight: i16,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub(crate) struct QueryParamsExecutorProcessorBind {
id: Option<i64>,
group_id: Option<i64>,
executor_id: Option<i64>,
name: Option<String>,
pub(crate) per_page: i64,
pub(crate) page: i64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ExecutorProcessorBindId {
pub(crate) executor_processor_bind_id: i64,
}
pub(crate) struct ExecutorProcessorBindQueryBuilder;
impl ExecutorProcessorBindQueryBuilder {
pub(crate) fn query_all_columns() -> executor_processor_bind::BoxedQuery<'static, Mysql> {
executor_processor_bind::table
.into_boxed()
.select(executor_processor_bind::all_columns)
}
pub(crate) fn query_binding_columns(
) -> executor_processor_bind::BoxedQuery<'static, Mysql, (sql_types::Bigint, sql_types::VarChar)>
{
executor_processor_bind::table
.into_boxed()
.select((executor_processor_bind::id, executor_processor_bind::name))
}
pub(crate) fn query_count(
) -> executor_processor_bind::BoxedQuery<'static, Mysql, diesel::sql_types::Bigint> {
executor_processor_bind::table.into_boxed().count()
}
}
impl QueryParamsExecutorProcessorBind {
pub(crate) fn query_filter<ST>(
self,
mut statement_builder: executor_processor_bind::BoxedQuery<'static, Mysql, ST>,
) -> executor_processor_bind::BoxedQuery<'static, Mysql, ST> {
if let Some(executor_processor_bind_id) = self.id {
statement_builder = statement_builder
.filter(executor_processor_bind::id.eq(executor_processor_bind_id));
}
if let Some(executor_processor_bind_group_id) = self.group_id {
statement_builder = statement_builder
.filter(executor_processor_bind::group_id.eq(executor_processor_bind_group_id));
}
if let Some(executor_processor_bind_executor_id) = self.executor_id {
statement_builder = statement_builder.filter(
executor_processor_bind::executor_id.eq(executor_processor_bind_executor_id),
);
}
if let Some(executor_processor_bind_name) = self.name {
statement_builder = statement_builder
.filter(executor_processor_bind::name.like(executor_processor_bind_name));
}
statement_builder.order(executor_processor_bind::id.desc())
}
}
|
use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult};
use crate::config::AudioFormat;
use crate::convert::Converter;
use crate::decoder::AudioPacket;
use crate::{NUM_CHANNELS, SAMPLE_RATE};
use alsa::device_name::HintIter;
use alsa::pcm::{Access, Format, Frames, HwParams, PCM};
use alsa::{Direction, ValueOr};
use std::process::exit;
use thiserror::Error;
const MAX_BUFFER: Frames = (SAMPLE_RATE / 2) as Frames;
const MIN_BUFFER: Frames = (SAMPLE_RATE / 10) as Frames;
const ZERO_FRAMES: Frames = 0;
const MAX_PERIOD_DIVISOR: Frames = 4;
const MIN_PERIOD_DIVISOR: Frames = 10;
#[derive(Debug, Error)]
enum AlsaError {
#[error("<AlsaSink> Device {device} Unsupported Format {alsa_format:?} ({format:?}), {e}")]
UnsupportedFormat {
device: String,
alsa_format: Format,
format: AudioFormat,
e: alsa::Error,
},
#[error("<AlsaSink> Device {device} Unsupported Channel Count {channel_count}, {e}")]
UnsupportedChannelCount {
device: String,
channel_count: u8,
e: alsa::Error,
},
#[error("<AlsaSink> Device {device} Unsupported Sample Rate {samplerate}, {e}")]
UnsupportedSampleRate {
device: String,
samplerate: u32,
e: alsa::Error,
},
#[error("<AlsaSink> Device {device} Unsupported Access Type RWInterleaved, {e}")]
UnsupportedAccessType { device: String, e: alsa::Error },
#[error("<AlsaSink> Device {device} May be Invalid, Busy, or Already in Use, {e}")]
PcmSetUp { device: String, e: alsa::Error },
#[error("<AlsaSink> Failed to Drain PCM Buffer, {0}")]
DrainFailure(alsa::Error),
#[error("<AlsaSink> {0}")]
OnWrite(alsa::Error),
#[error("<AlsaSink> Hardware, {0}")]
HwParams(alsa::Error),
#[error("<AlsaSink> Software, {0}")]
SwParams(alsa::Error),
#[error("<AlsaSink> PCM, {0}")]
Pcm(alsa::Error),
#[error("<AlsaSink> Could Not Parse Output Name(s) and/or Description(s), {0}")]
Parsing(alsa::Error),
#[error("<AlsaSink>")]
NotConnected,
}
impl From<AlsaError> for SinkError {
fn from(e: AlsaError) -> SinkError {
use AlsaError::*;
let es = e.to_string();
match e {
DrainFailure(_) | OnWrite(_) => SinkError::OnWrite(es),
PcmSetUp { .. } => SinkError::ConnectionRefused(es),
NotConnected => SinkError::NotConnected(es),
_ => SinkError::InvalidParams(es),
}
}
}
impl From<AudioFormat> for Format {
fn from(f: AudioFormat) -> Format {
use AudioFormat::*;
match f {
F64 => Format::float64(),
F32 => Format::float(),
S32 => Format::s32(),
S24 => Format::s24(),
S24_3 => Format::s24_3(),
S16 => Format::s16(),
}
}
}
pub struct AlsaSink {
pcm: Option<PCM>,
format: AudioFormat,
device: String,
period_buffer: Vec<u8>,
}
fn list_compatible_devices() -> SinkResult<()> {
let i = HintIter::new_str(None, "pcm").map_err(AlsaError::Parsing)?;
println!("\n\n\tCompatible alsa device(s):\n");
println!("\t------------------------------------------------------\n");
for a in i {
if let Some(Direction::Playback) = a.direction {
if let Some(name) = a.name {
if let Ok(pcm) = PCM::new(&name, Direction::Playback, false) {
if let Ok(hwp) = HwParams::any(&pcm) {
// Only show devices that support
// 2 ch 44.1 Interleaved.
if hwp.set_access(Access::RWInterleaved).is_ok()
&& hwp.set_rate(SAMPLE_RATE, ValueOr::Nearest).is_ok()
&& hwp.set_channels(NUM_CHANNELS as u32).is_ok()
{
let mut supported_formats = vec![];
for f in &[
AudioFormat::S16,
AudioFormat::S24,
AudioFormat::S24_3,
AudioFormat::S32,
AudioFormat::F32,
AudioFormat::F64,
] {
if hwp.test_format(Format::from(*f)).is_ok() {
supported_formats.push(format!("{f:?}"));
}
}
if !supported_formats.is_empty() {
println!("\tDevice:\n\n\t\t{name}\n");
println!(
"\tDescription:\n\n\t\t{}\n",
a.desc.unwrap_or_default().replace('\n', "\n\t\t")
);
println!(
"\tSupported Format(s):\n\n\t\t{}\n",
supported_formats.join(" ")
);
println!(
"\t------------------------------------------------------\n"
);
}
}
};
}
}
}
}
Ok(())
}
fn open_device(dev_name: &str, format: AudioFormat) -> SinkResult<(PCM, usize)> {
let pcm = PCM::new(dev_name, Direction::Playback, false).map_err(|e| AlsaError::PcmSetUp {
device: dev_name.to_string(),
e,
})?;
let bytes_per_period = {
let hwp = HwParams::any(&pcm).map_err(AlsaError::HwParams)?;
hwp.set_access(Access::RWInterleaved)
.map_err(|e| AlsaError::UnsupportedAccessType {
device: dev_name.to_string(),
e,
})?;
let alsa_format = Format::from(format);
hwp.set_format(alsa_format)
.map_err(|e| AlsaError::UnsupportedFormat {
device: dev_name.to_string(),
alsa_format,
format,
e,
})?;
hwp.set_rate(SAMPLE_RATE, ValueOr::Nearest).map_err(|e| {
AlsaError::UnsupportedSampleRate {
device: dev_name.to_string(),
samplerate: SAMPLE_RATE,
e,
}
})?;
hwp.set_channels(NUM_CHANNELS as u32)
.map_err(|e| AlsaError::UnsupportedChannelCount {
device: dev_name.to_string(),
channel_count: NUM_CHANNELS,
e,
})?;
// Clone the hwp while it's in
// a good working state so that
// in the event of an error setting
// the buffer and period sizes
// we can use the good working clone
// instead of the hwp that's in an
// error state.
let hwp_clone = hwp.clone();
// At a sampling rate of 44100:
// The largest buffer is 22050 Frames (500ms) with 5512 Frame periods (125ms).
// The smallest buffer is 4410 Frames (100ms) with 441 Frame periods (10ms).
// Actual values may vary.
//
// Larger buffer and period sizes are preferred as extremely small values
// will cause high CPU useage.
//
// If no buffer or period size is in those ranges or an error happens
// trying to set the buffer or period size use the device's defaults
// which may not be ideal but are *hopefully* serviceable.
let buffer_size = {
let max = match hwp.get_buffer_size_max() {
Err(e) => {
trace!("Error getting the device's max Buffer size: {}", e);
ZERO_FRAMES
}
Ok(s) => s,
};
let min = match hwp.get_buffer_size_min() {
Err(e) => {
trace!("Error getting the device's min Buffer size: {}", e);
ZERO_FRAMES
}
Ok(s) => s,
};
let buffer_size = if min < max {
match (MIN_BUFFER..=MAX_BUFFER)
.rev()
.find(|f| (min..=max).contains(f))
{
Some(size) => {
trace!("Desired Frames per Buffer: {:?}", size);
match hwp.set_buffer_size_near(size) {
Err(e) => {
trace!("Error setting the device's Buffer size: {}", e);
ZERO_FRAMES
}
Ok(s) => s,
}
}
None => {
trace!("No Desired Buffer size in range reported by the device.");
ZERO_FRAMES
}
}
} else {
trace!("The device's min reported Buffer size was greater than or equal to it's max reported Buffer size.");
ZERO_FRAMES
};
if buffer_size == ZERO_FRAMES {
trace!(
"Desired Buffer Frame range: {:?} - {:?}",
MIN_BUFFER,
MAX_BUFFER
);
trace!(
"Actual Buffer Frame range as reported by the device: {:?} - {:?}",
min,
max
);
}
buffer_size
};
let period_size = {
if buffer_size == ZERO_FRAMES {
ZERO_FRAMES
} else {
let max = match hwp.get_period_size_max() {
Err(e) => {
trace!("Error getting the device's max Period size: {}", e);
ZERO_FRAMES
}
Ok(s) => s,
};
let min = match hwp.get_period_size_min() {
Err(e) => {
trace!("Error getting the device's min Period size: {}", e);
ZERO_FRAMES
}
Ok(s) => s,
};
let max_period = buffer_size / MAX_PERIOD_DIVISOR;
let min_period = buffer_size / MIN_PERIOD_DIVISOR;
let period_size = if min < max && min_period < max_period {
match (min_period..=max_period)
.rev()
.find(|f| (min..=max).contains(f))
{
Some(size) => {
trace!("Desired Frames per Period: {:?}", size);
match hwp.set_period_size_near(size, ValueOr::Nearest) {
Err(e) => {
trace!("Error setting the device's Period size: {}", e);
ZERO_FRAMES
}
Ok(s) => s,
}
}
None => {
trace!("No Desired Period size in range reported by the device.");
ZERO_FRAMES
}
}
} else {
trace!("The device's min reported Period size was greater than or equal to it's max reported Period size,");
trace!("or the desired min Period size was greater than or equal to the desired max Period size.");
ZERO_FRAMES
};
if period_size == ZERO_FRAMES {
trace!("Buffer size: {:?}", buffer_size);
trace!(
"Desired Period Frame range: {:?} (Buffer size / {:?}) - {:?} (Buffer size / {:?})",
min_period,
MIN_PERIOD_DIVISOR,
max_period,
MAX_PERIOD_DIVISOR,
);
trace!(
"Actual Period Frame range as reported by the device: {:?} - {:?}",
min,
max
);
}
period_size
}
};
if buffer_size == ZERO_FRAMES || period_size == ZERO_FRAMES {
trace!(
"Failed to set Buffer and/or Period size, falling back to the device's defaults."
);
trace!("You may experience higher than normal CPU usage and/or audio issues.");
pcm.hw_params(&hwp_clone).map_err(AlsaError::Pcm)?;
} else {
pcm.hw_params(&hwp).map_err(AlsaError::Pcm)?;
}
let hwp = pcm.hw_params_current().map_err(AlsaError::Pcm)?;
// Don't assume we got what we wanted. Ask to make sure.
let frames_per_period = hwp.get_period_size().map_err(AlsaError::HwParams)?;
let frames_per_buffer = hwp.get_buffer_size().map_err(AlsaError::HwParams)?;
let swp = pcm.sw_params_current().map_err(AlsaError::Pcm)?;
swp.set_start_threshold(frames_per_buffer - frames_per_period)
.map_err(AlsaError::SwParams)?;
pcm.sw_params(&swp).map_err(AlsaError::Pcm)?;
trace!("Actual Frames per Buffer: {:?}", frames_per_buffer);
trace!("Actual Frames per Period: {:?}", frames_per_period);
// Let ALSA do the math for us.
pcm.frames_to_bytes(frames_per_period) as usize
};
trace!("Period Buffer size in bytes: {:?}", bytes_per_period);
Ok((pcm, bytes_per_period))
}
impl Open for AlsaSink {
fn open(device: Option<String>, format: AudioFormat) -> Self {
let name = match device.as_deref() {
Some("?") => match list_compatible_devices() {
Ok(_) => {
exit(0);
}
Err(e) => {
error!("{}", e);
exit(1);
}
},
Some(device) => device,
None => "default",
}
.to_string();
info!("Using AlsaSink with format: {:?}", format);
Self {
pcm: None,
format,
device: name,
period_buffer: vec![],
}
}
}
impl Sink for AlsaSink {
fn start(&mut self) -> SinkResult<()> {
if self.pcm.is_none() {
let (pcm, bytes_per_period) = open_device(&self.device, self.format)?;
self.pcm = Some(pcm);
if self.period_buffer.capacity() != bytes_per_period {
self.period_buffer = Vec::with_capacity(bytes_per_period);
}
// Should always match the "Period Buffer size in bytes: " trace! message.
trace!(
"Period Buffer capacity: {:?}",
self.period_buffer.capacity()
);
}
Ok(())
}
fn stop(&mut self) -> SinkResult<()> {
if self.pcm.is_some() {
// Zero fill the remainder of the period buffer and
// write any leftover data before draining the actual PCM buffer.
self.period_buffer.resize(self.period_buffer.capacity(), 0);
self.write_buf()?;
let pcm = self.pcm.take().ok_or(AlsaError::NotConnected)?;
pcm.drain().map_err(AlsaError::DrainFailure)?;
}
Ok(())
}
sink_as_bytes!();
}
impl SinkAsBytes for AlsaSink {
fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> {
let mut start_index = 0;
let data_len = data.len();
let capacity = self.period_buffer.capacity();
loop {
let data_left = data_len - start_index;
let space_left = capacity - self.period_buffer.len();
let data_to_buffer = data_left.min(space_left);
let end_index = start_index + data_to_buffer;
self.period_buffer
.extend_from_slice(&data[start_index..end_index]);
if self.period_buffer.len() == capacity {
self.write_buf()?;
}
if end_index == data_len {
break Ok(());
}
start_index = end_index;
}
}
}
impl AlsaSink {
pub const NAME: &'static str = "alsa";
fn write_buf(&mut self) -> SinkResult<()> {
if self.pcm.is_some() {
let write_result = {
let pcm = self.pcm.as_mut().ok_or(AlsaError::NotConnected)?;
match pcm.io_bytes().writei(&self.period_buffer) {
Ok(_) => Ok(()),
Err(e) => {
// Capture and log the original error as a warning, and then try to recover.
// If recovery fails then forward that error back to player.
warn!(
"Error writing from AlsaSink buffer to PCM, trying to recover, {}",
e
);
pcm.try_recover(e, false).map_err(AlsaError::OnWrite)
}
}
};
if let Err(e) = write_result {
self.pcm = None;
return Err(e.into());
}
}
self.period_buffer.clear();
Ok(())
}
}
|
use super::atom::slider;
use super::molecule::color_pallet::{self, ColorPallet};
use crate::libs::color::Pallet;
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use nusa::prelude::*;
pub struct Props {
pub default_selected: Pallet,
pub direction: Direction,
}
#[derive(Clone, Copy)]
pub enum Direction {
Left,
Right,
Bottom,
}
impl std::fmt::Display for Direction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Left => write!(f, "left"),
Self::Right => write!(f, "right"),
Self::Bottom => write!(f, "bottom"),
}
}
}
pub enum Msg {
SetIsToggled(bool),
SetSelected(Pallet),
}
pub enum On {
SelectColor(Pallet),
}
pub struct PopupColorPallet {
default_selected: Pallet,
selected: Pallet,
is_toggled: bool,
direction: Direction,
}
impl Component for PopupColorPallet {
type Props = Props;
type Msg = Msg;
type Event = On;
}
impl HtmlComponent for PopupColorPallet {}
impl Constructor for PopupColorPallet {
fn constructor(props: Props) -> Self {
Self {
default_selected: props.default_selected,
selected: props.default_selected,
is_toggled: false,
direction: props.direction,
}
}
}
impl Update for PopupColorPallet {
fn on_load(mut self: Pin<&mut Self>, props: Self::Props) -> Cmd<Self> {
self.default_selected = props.default_selected;
self.direction = props.direction;
Cmd::none()
}
fn update(mut self: Pin<&mut Self>, msg: Msg) -> Cmd<Self> {
match msg {
Msg::SetIsToggled(is_toggled) => {
self.is_toggled = is_toggled;
if self.is_toggled {
self.selected = self.default_selected;
Cmd::none()
} else {
Cmd::submit(On::SelectColor(self.selected))
}
}
Msg::SetSelected(pallet) => {
self.selected = pallet;
Cmd::none()
}
}
}
}
impl Render<Html> for PopupColorPallet {
type Children = ();
fn render(&self, _: Self::Children) -> Html {
ColorPallet::styled(());
Self::styled(Html::div(
Attributes::new().class(Self::class("base")),
Events::new(),
vec![
self.render_selected_color(),
self.render_mask(),
self.render_color_pallet(),
],
))
}
}
impl PopupColorPallet {
fn render_selected_color(&self) -> Html {
Html::div(
Attributes::new(),
Events::new().on_click(self, |_| Msg::SetIsToggled(true)),
vec![ColorPallet::render_color_base(
&slider::Theme::Light,
&self.default_selected,
)],
)
}
fn render_mask(&self) -> Html {
Html::div(
Attributes::new()
.class(Self::class("mask"))
.string("data-toggled", self.is_toggled.to_string()),
Events::new().on_click(self, |_| Msg::SetIsToggled(false)),
vec![],
)
}
fn render_color_pallet(&self) -> Html {
Html::div(
Attributes::new()
.class(Self::class("pallet"))
.class(Self::class(&format!("pallet--{}", &self.direction)))
.string("data-toggled", self.is_toggled.to_string()),
Events::new(),
vec![if self.is_toggled {
ColorPallet::new(
self,
None,
self.default_selected,
Sub::map(|sub| match sub {
color_pallet::On::SelectColor(pallet) => Msg::SetSelected(pallet),
}),
color_pallet::Props {
title: None,
theme: slider::Theme::Light,
},
)
} else {
Html::none()
}],
)
}
}
impl Styled for PopupColorPallet {
fn style() -> Style {
style! {
".base" {
"position": "relative";
"overflow": "visible";
}
".mask" {
"position": "fixed";
"top": "0";
"left": "0";
"width": "100vw";
"height": "100vh";
"z-index": super::constant::z_index::MASK;
}
".mask[data-toggled='false']" {
"display": "none";
}
".mask[data-toggled='true']" {
"display": "block";
}
".pallet" {
"position": "absolute";
"left": "calc(100% + .35rem)";
"z-index": super::constant::z_index::MASK + 1;
}
".pallet--left" {
"top": "0";
"right": "-0.35rem";
}
".pallet--right" {
"top": "0";
"left": "calc(100% + .35rem)";
}
".pallet--bottom" {
"top": "calc(100% + .35rem)";
"left": "0";
}
".pallet[data-toggled='false']" {
"display": "none";
}
".pallet[data-toggled='true']" {
"display": "block";
}
}
}
}
|
// This file was generated by `cargo dev update_lints`.
// Use that command to update this file and do not edit by hand.
// Manual edits will be overwritten.
pub(crate) static LINTS: &[&crate::LintInfo] = &[
#[cfg(feature = "internal")]
crate::utils::internal_lints::almost_standard_lint_formulation::ALMOST_STANDARD_LINT_FORMULATION_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::clippy_lints_internal::CLIPPY_LINTS_INTERNAL_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::collapsible_calls::COLLAPSIBLE_SPAN_LINT_CALLS_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::compiler_lint_functions::COMPILER_LINT_FUNCTIONS_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::if_chain_style::IF_CHAIN_STYLE_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::interning_defined_symbol::INTERNING_DEFINED_SYMBOL_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::interning_defined_symbol::UNNECESSARY_SYMBOL_STR_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::invalid_paths::INVALID_PATHS_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::lint_without_lint_pass::DEFAULT_DEPRECATION_REASON_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::lint_without_lint_pass::DEFAULT_LINT_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::lint_without_lint_pass::INVALID_CLIPPY_VERSION_ATTRIBUTE_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::lint_without_lint_pass::LINT_WITHOUT_LINT_PASS_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::lint_without_lint_pass::MISSING_CLIPPY_VERSION_ATTRIBUTE_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::msrv_attr_impl::MISSING_MSRV_ATTR_IMPL_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::outer_expn_data_pass::OUTER_EXPN_EXPN_DATA_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::produce_ice::PRODUCE_ICE_INFO,
#[cfg(feature = "internal")]
crate::utils::internal_lints::unnecessary_def_path::UNNECESSARY_DEF_PATH_INFO,
crate::absolute_paths::ABSOLUTE_PATHS_INFO,
crate::allow_attributes::ALLOW_ATTRIBUTES_INFO,
crate::almost_complete_range::ALMOST_COMPLETE_RANGE_INFO,
crate::approx_const::APPROX_CONSTANT_INFO,
crate::arc_with_non_send_sync::ARC_WITH_NON_SEND_SYNC_INFO,
crate::as_conversions::AS_CONVERSIONS_INFO,
crate::asm_syntax::INLINE_ASM_X86_ATT_SYNTAX_INFO,
crate::asm_syntax::INLINE_ASM_X86_INTEL_SYNTAX_INFO,
crate::assertions_on_constants::ASSERTIONS_ON_CONSTANTS_INFO,
crate::assertions_on_result_states::ASSERTIONS_ON_RESULT_STATES_INFO,
crate::async_yields_async::ASYNC_YIELDS_ASYNC_INFO,
crate::attrs::ALLOW_ATTRIBUTES_WITHOUT_REASON_INFO,
crate::attrs::BLANKET_CLIPPY_RESTRICTION_LINTS_INFO,
crate::attrs::DEPRECATED_CFG_ATTR_INFO,
crate::attrs::DEPRECATED_SEMVER_INFO,
crate::attrs::EMPTY_LINE_AFTER_DOC_COMMENTS_INFO,
crate::attrs::EMPTY_LINE_AFTER_OUTER_ATTR_INFO,
crate::attrs::INLINE_ALWAYS_INFO,
crate::attrs::MAYBE_MISUSED_CFG_INFO,
crate::attrs::MISMATCHED_TARGET_OS_INFO,
crate::attrs::NON_MINIMAL_CFG_INFO,
crate::attrs::USELESS_ATTRIBUTE_INFO,
crate::await_holding_invalid::AWAIT_HOLDING_INVALID_TYPE_INFO,
crate::await_holding_invalid::AWAIT_HOLDING_LOCK_INFO,
crate::await_holding_invalid::AWAIT_HOLDING_REFCELL_REF_INFO,
crate::blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS_INFO,
crate::bool_assert_comparison::BOOL_ASSERT_COMPARISON_INFO,
crate::bool_to_int_with_if::BOOL_TO_INT_WITH_IF_INFO,
crate::booleans::NONMINIMAL_BOOL_INFO,
crate::booleans::OVERLY_COMPLEX_BOOL_EXPR_INFO,
crate::borrow_deref_ref::BORROW_DEREF_REF_INFO,
crate::box_default::BOX_DEFAULT_INFO,
crate::cargo::CARGO_COMMON_METADATA_INFO,
crate::cargo::MULTIPLE_CRATE_VERSIONS_INFO,
crate::cargo::NEGATIVE_FEATURE_NAMES_INFO,
crate::cargo::REDUNDANT_FEATURE_NAMES_INFO,
crate::cargo::WILDCARD_DEPENDENCIES_INFO,
crate::casts::AS_PTR_CAST_MUT_INFO,
crate::casts::AS_UNDERSCORE_INFO,
crate::casts::BORROW_AS_PTR_INFO,
crate::casts::CAST_ABS_TO_UNSIGNED_INFO,
crate::casts::CAST_ENUM_CONSTRUCTOR_INFO,
crate::casts::CAST_ENUM_TRUNCATION_INFO,
crate::casts::CAST_LOSSLESS_INFO,
crate::casts::CAST_NAN_TO_INT_INFO,
crate::casts::CAST_POSSIBLE_TRUNCATION_INFO,
crate::casts::CAST_POSSIBLE_WRAP_INFO,
crate::casts::CAST_PRECISION_LOSS_INFO,
crate::casts::CAST_PTR_ALIGNMENT_INFO,
crate::casts::CAST_SIGN_LOSS_INFO,
crate::casts::CAST_SLICE_DIFFERENT_SIZES_INFO,
crate::casts::CAST_SLICE_FROM_RAW_PARTS_INFO,
crate::casts::CHAR_LIT_AS_U8_INFO,
crate::casts::FN_TO_NUMERIC_CAST_INFO,
crate::casts::FN_TO_NUMERIC_CAST_ANY_INFO,
crate::casts::FN_TO_NUMERIC_CAST_WITH_TRUNCATION_INFO,
crate::casts::PTR_AS_PTR_INFO,
crate::casts::PTR_CAST_CONSTNESS_INFO,
crate::casts::UNNECESSARY_CAST_INFO,
crate::checked_conversions::CHECKED_CONVERSIONS_INFO,
crate::cognitive_complexity::COGNITIVE_COMPLEXITY_INFO,
crate::collapsible_if::COLLAPSIBLE_ELSE_IF_INFO,
crate::collapsible_if::COLLAPSIBLE_IF_INFO,
crate::collection_is_never_read::COLLECTION_IS_NEVER_READ_INFO,
crate::comparison_chain::COMPARISON_CHAIN_INFO,
crate::copies::BRANCHES_SHARING_CODE_INFO,
crate::copies::IFS_SAME_COND_INFO,
crate::copies::IF_SAME_THEN_ELSE_INFO,
crate::copies::SAME_FUNCTIONS_IN_IF_CONDITION_INFO,
crate::copy_iterator::COPY_ITERATOR_INFO,
crate::crate_in_macro_def::CRATE_IN_MACRO_DEF_INFO,
crate::create_dir::CREATE_DIR_INFO,
crate::dbg_macro::DBG_MACRO_INFO,
crate::default::DEFAULT_TRAIT_ACCESS_INFO,
crate::default::FIELD_REASSIGN_WITH_DEFAULT_INFO,
crate::default_constructed_unit_structs::DEFAULT_CONSTRUCTED_UNIT_STRUCTS_INFO,
crate::default_instead_of_iter_empty::DEFAULT_INSTEAD_OF_ITER_EMPTY_INFO,
crate::default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK_INFO,
crate::default_union_representation::DEFAULT_UNION_REPRESENTATION_INFO,
crate::dereference::EXPLICIT_AUTO_DEREF_INFO,
crate::dereference::EXPLICIT_DEREF_METHODS_INFO,
crate::dereference::NEEDLESS_BORROW_INFO,
crate::dereference::REF_BINDING_TO_REFERENCE_INFO,
crate::derivable_impls::DERIVABLE_IMPLS_INFO,
crate::derive::DERIVED_HASH_WITH_MANUAL_EQ_INFO,
crate::derive::DERIVE_ORD_XOR_PARTIAL_ORD_INFO,
crate::derive::DERIVE_PARTIAL_EQ_WITHOUT_EQ_INFO,
crate::derive::EXPL_IMPL_CLONE_ON_COPY_INFO,
crate::derive::UNSAFE_DERIVE_DESERIALIZE_INFO,
crate::disallowed_macros::DISALLOWED_MACROS_INFO,
crate::disallowed_methods::DISALLOWED_METHODS_INFO,
crate::disallowed_names::DISALLOWED_NAMES_INFO,
crate::disallowed_script_idents::DISALLOWED_SCRIPT_IDENTS_INFO,
crate::disallowed_types::DISALLOWED_TYPES_INFO,
crate::doc::DOC_LINK_WITH_QUOTES_INFO,
crate::doc::DOC_MARKDOWN_INFO,
crate::doc::MISSING_ERRORS_DOC_INFO,
crate::doc::MISSING_PANICS_DOC_INFO,
crate::doc::MISSING_SAFETY_DOC_INFO,
crate::doc::NEEDLESS_DOCTEST_MAIN_INFO,
crate::doc::UNNECESSARY_SAFETY_DOC_INFO,
crate::double_parens::DOUBLE_PARENS_INFO,
crate::drop_forget_ref::DROP_NON_DROP_INFO,
crate::drop_forget_ref::FORGET_NON_DROP_INFO,
crate::drop_forget_ref::MEM_FORGET_INFO,
crate::duplicate_mod::DUPLICATE_MOD_INFO,
crate::else_if_without_else::ELSE_IF_WITHOUT_ELSE_INFO,
crate::empty_drop::EMPTY_DROP_INFO,
crate::empty_enum::EMPTY_ENUM_INFO,
crate::empty_structs_with_brackets::EMPTY_STRUCTS_WITH_BRACKETS_INFO,
crate::endian_bytes::BIG_ENDIAN_BYTES_INFO,
crate::endian_bytes::HOST_ENDIAN_BYTES_INFO,
crate::endian_bytes::LITTLE_ENDIAN_BYTES_INFO,
crate::entry::MAP_ENTRY_INFO,
crate::enum_clike::ENUM_CLIKE_UNPORTABLE_VARIANT_INFO,
crate::enum_variants::ENUM_VARIANT_NAMES_INFO,
crate::enum_variants::MODULE_INCEPTION_INFO,
crate::enum_variants::MODULE_NAME_REPETITIONS_INFO,
crate::equatable_if_let::EQUATABLE_IF_LET_INFO,
crate::error_impl_error::ERROR_IMPL_ERROR_INFO,
crate::escape::BOXED_LOCAL_INFO,
crate::eta_reduction::REDUNDANT_CLOSURE_INFO,
crate::eta_reduction::REDUNDANT_CLOSURE_FOR_METHOD_CALLS_INFO,
crate::excessive_bools::FN_PARAMS_EXCESSIVE_BOOLS_INFO,
crate::excessive_bools::STRUCT_EXCESSIVE_BOOLS_INFO,
crate::excessive_nesting::EXCESSIVE_NESTING_INFO,
crate::exhaustive_items::EXHAUSTIVE_ENUMS_INFO,
crate::exhaustive_items::EXHAUSTIVE_STRUCTS_INFO,
crate::exit::EXIT_INFO,
crate::explicit_write::EXPLICIT_WRITE_INFO,
crate::extra_unused_type_parameters::EXTRA_UNUSED_TYPE_PARAMETERS_INFO,
crate::fallible_impl_from::FALLIBLE_IMPL_FROM_INFO,
crate::float_literal::EXCESSIVE_PRECISION_INFO,
crate::float_literal::LOSSY_FLOAT_LITERAL_INFO,
crate::floating_point_arithmetic::IMPRECISE_FLOPS_INFO,
crate::floating_point_arithmetic::SUBOPTIMAL_FLOPS_INFO,
crate::format::USELESS_FORMAT_INFO,
crate::format_args::FORMAT_IN_FORMAT_ARGS_INFO,
crate::format_args::TO_STRING_IN_FORMAT_ARGS_INFO,
crate::format_args::UNINLINED_FORMAT_ARGS_INFO,
crate::format_args::UNUSED_FORMAT_SPECS_INFO,
crate::format_impl::PRINT_IN_FORMAT_IMPL_INFO,
crate::format_impl::RECURSIVE_FORMAT_IMPL_INFO,
crate::format_push_string::FORMAT_PUSH_STRING_INFO,
crate::formatting::POSSIBLE_MISSING_COMMA_INFO,
crate::formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING_INFO,
crate::formatting::SUSPICIOUS_ELSE_FORMATTING_INFO,
crate::formatting::SUSPICIOUS_UNARY_OP_FORMATTING_INFO,
crate::four_forward_slashes::FOUR_FORWARD_SLASHES_INFO,
crate::from_over_into::FROM_OVER_INTO_INFO,
crate::from_raw_with_void_ptr::FROM_RAW_WITH_VOID_PTR_INFO,
crate::from_str_radix_10::FROM_STR_RADIX_10_INFO,
crate::functions::DOUBLE_MUST_USE_INFO,
crate::functions::IMPL_TRAIT_IN_PARAMS_INFO,
crate::functions::MISNAMED_GETTERS_INFO,
crate::functions::MUST_USE_CANDIDATE_INFO,
crate::functions::MUST_USE_UNIT_INFO,
crate::functions::NOT_UNSAFE_PTR_ARG_DEREF_INFO,
crate::functions::RESULT_LARGE_ERR_INFO,
crate::functions::RESULT_UNIT_ERR_INFO,
crate::functions::TOO_MANY_ARGUMENTS_INFO,
crate::functions::TOO_MANY_LINES_INFO,
crate::future_not_send::FUTURE_NOT_SEND_INFO,
crate::if_let_mutex::IF_LET_MUTEX_INFO,
crate::if_not_else::IF_NOT_ELSE_INFO,
crate::if_then_some_else_none::IF_THEN_SOME_ELSE_NONE_INFO,
crate::ignored_unit_patterns::IGNORED_UNIT_PATTERNS_INFO,
crate::implicit_hasher::IMPLICIT_HASHER_INFO,
crate::implicit_return::IMPLICIT_RETURN_INFO,
crate::implicit_saturating_add::IMPLICIT_SATURATING_ADD_INFO,
crate::implicit_saturating_sub::IMPLICIT_SATURATING_SUB_INFO,
crate::inconsistent_struct_constructor::INCONSISTENT_STRUCT_CONSTRUCTOR_INFO,
crate::incorrect_impls::INCORRECT_CLONE_IMPL_ON_COPY_TYPE_INFO,
crate::incorrect_impls::INCORRECT_PARTIAL_ORD_IMPL_ON_ORD_TYPE_INFO,
crate::index_refutable_slice::INDEX_REFUTABLE_SLICE_INFO,
crate::indexing_slicing::INDEXING_SLICING_INFO,
crate::indexing_slicing::OUT_OF_BOUNDS_INDEXING_INFO,
crate::infinite_iter::INFINITE_ITER_INFO,
crate::infinite_iter::MAYBE_INFINITE_ITER_INFO,
crate::inherent_impl::MULTIPLE_INHERENT_IMPL_INFO,
crate::inherent_to_string::INHERENT_TO_STRING_INFO,
crate::inherent_to_string::INHERENT_TO_STRING_SHADOW_DISPLAY_INFO,
crate::init_numbered_fields::INIT_NUMBERED_FIELDS_INFO,
crate::inline_fn_without_body::INLINE_FN_WITHOUT_BODY_INFO,
crate::instant_subtraction::MANUAL_INSTANT_ELAPSED_INFO,
crate::instant_subtraction::UNCHECKED_DURATION_SUBTRACTION_INFO,
crate::int_plus_one::INT_PLUS_ONE_INFO,
crate::invalid_upcast_comparisons::INVALID_UPCAST_COMPARISONS_INFO,
crate::items_after_statements::ITEMS_AFTER_STATEMENTS_INFO,
crate::items_after_test_module::ITEMS_AFTER_TEST_MODULE_INFO,
crate::iter_not_returning_iterator::ITER_NOT_RETURNING_ITERATOR_INFO,
crate::large_const_arrays::LARGE_CONST_ARRAYS_INFO,
crate::large_enum_variant::LARGE_ENUM_VARIANT_INFO,
crate::large_futures::LARGE_FUTURES_INFO,
crate::large_include_file::LARGE_INCLUDE_FILE_INFO,
crate::large_stack_arrays::LARGE_STACK_ARRAYS_INFO,
crate::large_stack_frames::LARGE_STACK_FRAMES_INFO,
crate::len_zero::COMPARISON_TO_EMPTY_INFO,
crate::len_zero::LEN_WITHOUT_IS_EMPTY_INFO,
crate::len_zero::LEN_ZERO_INFO,
crate::let_if_seq::USELESS_LET_IF_SEQ_INFO,
crate::let_underscore::LET_UNDERSCORE_FUTURE_INFO,
crate::let_underscore::LET_UNDERSCORE_LOCK_INFO,
crate::let_underscore::LET_UNDERSCORE_MUST_USE_INFO,
crate::let_underscore::LET_UNDERSCORE_UNTYPED_INFO,
crate::let_with_type_underscore::LET_WITH_TYPE_UNDERSCORE_INFO,
crate::lifetimes::EXTRA_UNUSED_LIFETIMES_INFO,
crate::lifetimes::NEEDLESS_LIFETIMES_INFO,
crate::lines_filter_map_ok::LINES_FILTER_MAP_OK_INFO,
crate::literal_representation::DECIMAL_LITERAL_REPRESENTATION_INFO,
crate::literal_representation::INCONSISTENT_DIGIT_GROUPING_INFO,
crate::literal_representation::LARGE_DIGIT_GROUPS_INFO,
crate::literal_representation::MISTYPED_LITERAL_SUFFIXES_INFO,
crate::literal_representation::UNREADABLE_LITERAL_INFO,
crate::literal_representation::UNUSUAL_BYTE_GROUPINGS_INFO,
crate::loops::EMPTY_LOOP_INFO,
crate::loops::EXPLICIT_COUNTER_LOOP_INFO,
crate::loops::EXPLICIT_INTO_ITER_LOOP_INFO,
crate::loops::EXPLICIT_ITER_LOOP_INFO,
crate::loops::FOR_KV_MAP_INFO,
crate::loops::ITER_NEXT_LOOP_INFO,
crate::loops::MANUAL_FIND_INFO,
crate::loops::MANUAL_FLATTEN_INFO,
crate::loops::MANUAL_MEMCPY_INFO,
crate::loops::MANUAL_WHILE_LET_SOME_INFO,
crate::loops::MISSING_SPIN_LOOP_INFO,
crate::loops::MUT_RANGE_BOUND_INFO,
crate::loops::NEEDLESS_RANGE_LOOP_INFO,
crate::loops::NEVER_LOOP_INFO,
crate::loops::SAME_ITEM_PUSH_INFO,
crate::loops::SINGLE_ELEMENT_LOOP_INFO,
crate::loops::WHILE_IMMUTABLE_CONDITION_INFO,
crate::loops::WHILE_LET_LOOP_INFO,
crate::loops::WHILE_LET_ON_ITERATOR_INFO,
crate::macro_use::MACRO_USE_IMPORTS_INFO,
crate::main_recursion::MAIN_RECURSION_INFO,
crate::manual_assert::MANUAL_ASSERT_INFO,
crate::manual_async_fn::MANUAL_ASYNC_FN_INFO,
crate::manual_bits::MANUAL_BITS_INFO,
crate::manual_clamp::MANUAL_CLAMP_INFO,
crate::manual_float_methods::MANUAL_IS_FINITE_INFO,
crate::manual_float_methods::MANUAL_IS_INFINITE_INFO,
crate::manual_is_ascii_check::MANUAL_IS_ASCII_CHECK_INFO,
crate::manual_let_else::MANUAL_LET_ELSE_INFO,
crate::manual_main_separator_str::MANUAL_MAIN_SEPARATOR_STR_INFO,
crate::manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE_INFO,
crate::manual_range_patterns::MANUAL_RANGE_PATTERNS_INFO,
crate::manual_rem_euclid::MANUAL_REM_EUCLID_INFO,
crate::manual_retain::MANUAL_RETAIN_INFO,
crate::manual_slice_size_calculation::MANUAL_SLICE_SIZE_CALCULATION_INFO,
crate::manual_string_new::MANUAL_STRING_NEW_INFO,
crate::manual_strip::MANUAL_STRIP_INFO,
crate::map_unit_fn::OPTION_MAP_UNIT_FN_INFO,
crate::map_unit_fn::RESULT_MAP_UNIT_FN_INFO,
crate::match_result_ok::MATCH_RESULT_OK_INFO,
crate::matches::COLLAPSIBLE_MATCH_INFO,
crate::matches::INFALLIBLE_DESTRUCTURING_MATCH_INFO,
crate::matches::MANUAL_FILTER_INFO,
crate::matches::MANUAL_MAP_INFO,
crate::matches::MANUAL_UNWRAP_OR_INFO,
crate::matches::MATCH_AS_REF_INFO,
crate::matches::MATCH_BOOL_INFO,
crate::matches::MATCH_LIKE_MATCHES_MACRO_INFO,
crate::matches::MATCH_ON_VEC_ITEMS_INFO,
crate::matches::MATCH_OVERLAPPING_ARM_INFO,
crate::matches::MATCH_REF_PATS_INFO,
crate::matches::MATCH_SAME_ARMS_INFO,
crate::matches::MATCH_SINGLE_BINDING_INFO,
crate::matches::MATCH_STR_CASE_MISMATCH_INFO,
crate::matches::MATCH_WILDCARD_FOR_SINGLE_VARIANTS_INFO,
crate::matches::MATCH_WILD_ERR_ARM_INFO,
crate::matches::NEEDLESS_MATCH_INFO,
crate::matches::REDUNDANT_GUARDS_INFO,
crate::matches::REDUNDANT_PATTERN_MATCHING_INFO,
crate::matches::REST_PAT_IN_FULLY_BOUND_STRUCTS_INFO,
crate::matches::SIGNIFICANT_DROP_IN_SCRUTINEE_INFO,
crate::matches::SINGLE_MATCH_INFO,
crate::matches::SINGLE_MATCH_ELSE_INFO,
crate::matches::TRY_ERR_INFO,
crate::matches::WILDCARD_ENUM_MATCH_ARM_INFO,
crate::matches::WILDCARD_IN_OR_PATTERNS_INFO,
crate::mem_replace::MEM_REPLACE_OPTION_WITH_NONE_INFO,
crate::mem_replace::MEM_REPLACE_WITH_DEFAULT_INFO,
crate::mem_replace::MEM_REPLACE_WITH_UNINIT_INFO,
crate::methods::BIND_INSTEAD_OF_MAP_INFO,
crate::methods::BYTES_COUNT_TO_LEN_INFO,
crate::methods::BYTES_NTH_INFO,
crate::methods::CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS_INFO,
crate::methods::CHARS_LAST_CMP_INFO,
crate::methods::CHARS_NEXT_CMP_INFO,
crate::methods::CLEAR_WITH_DRAIN_INFO,
crate::methods::CLONED_INSTEAD_OF_COPIED_INFO,
crate::methods::CLONE_ON_COPY_INFO,
crate::methods::CLONE_ON_REF_PTR_INFO,
crate::methods::COLLAPSIBLE_STR_REPLACE_INFO,
crate::methods::DRAIN_COLLECT_INFO,
crate::methods::ERR_EXPECT_INFO,
crate::methods::EXPECT_FUN_CALL_INFO,
crate::methods::EXPECT_USED_INFO,
crate::methods::EXTEND_WITH_DRAIN_INFO,
crate::methods::FILETYPE_IS_FILE_INFO,
crate::methods::FILTER_MAP_BOOL_THEN_INFO,
crate::methods::FILTER_MAP_IDENTITY_INFO,
crate::methods::FILTER_MAP_NEXT_INFO,
crate::methods::FILTER_NEXT_INFO,
crate::methods::FLAT_MAP_IDENTITY_INFO,
crate::methods::FLAT_MAP_OPTION_INFO,
crate::methods::FORMAT_COLLECT_INFO,
crate::methods::FROM_ITER_INSTEAD_OF_COLLECT_INFO,
crate::methods::GET_FIRST_INFO,
crate::methods::GET_LAST_WITH_LEN_INFO,
crate::methods::GET_UNWRAP_INFO,
crate::methods::IMPLICIT_CLONE_INFO,
crate::methods::INEFFICIENT_TO_STRING_INFO,
crate::methods::INSPECT_FOR_EACH_INFO,
crate::methods::INTO_ITER_ON_REF_INFO,
crate::methods::IS_DIGIT_ASCII_RADIX_INFO,
crate::methods::ITERATOR_STEP_BY_ZERO_INFO,
crate::methods::ITER_CLONED_COLLECT_INFO,
crate::methods::ITER_COUNT_INFO,
crate::methods::ITER_KV_MAP_INFO,
crate::methods::ITER_NEXT_SLICE_INFO,
crate::methods::ITER_NTH_INFO,
crate::methods::ITER_NTH_ZERO_INFO,
crate::methods::ITER_ON_EMPTY_COLLECTIONS_INFO,
crate::methods::ITER_ON_SINGLE_ITEMS_INFO,
crate::methods::ITER_OVEREAGER_CLONED_INFO,
crate::methods::ITER_SKIP_NEXT_INFO,
crate::methods::ITER_SKIP_ZERO_INFO,
crate::methods::ITER_WITH_DRAIN_INFO,
crate::methods::MANUAL_FILTER_MAP_INFO,
crate::methods::MANUAL_FIND_MAP_INFO,
crate::methods::MANUAL_NEXT_BACK_INFO,
crate::methods::MANUAL_OK_OR_INFO,
crate::methods::MANUAL_SATURATING_ARITHMETIC_INFO,
crate::methods::MANUAL_SPLIT_ONCE_INFO,
crate::methods::MANUAL_STR_REPEAT_INFO,
crate::methods::MANUAL_TRY_FOLD_INFO,
crate::methods::MAP_CLONE_INFO,
crate::methods::MAP_COLLECT_RESULT_UNIT_INFO,
crate::methods::MAP_ERR_IGNORE_INFO,
crate::methods::MAP_FLATTEN_INFO,
crate::methods::MAP_IDENTITY_INFO,
crate::methods::MAP_UNWRAP_OR_INFO,
crate::methods::MUT_MUTEX_LOCK_INFO,
crate::methods::NAIVE_BYTECOUNT_INFO,
crate::methods::NEEDLESS_COLLECT_INFO,
crate::methods::NEEDLESS_OPTION_AS_DEREF_INFO,
crate::methods::NEEDLESS_OPTION_TAKE_INFO,
crate::methods::NEEDLESS_SPLITN_INFO,
crate::methods::NEW_RET_NO_SELF_INFO,
crate::methods::NONSENSICAL_OPEN_OPTIONS_INFO,
crate::methods::NO_EFFECT_REPLACE_INFO,
crate::methods::OBFUSCATED_IF_ELSE_INFO,
crate::methods::OK_EXPECT_INFO,
crate::methods::OPTION_AS_REF_DEREF_INFO,
crate::methods::OPTION_FILTER_MAP_INFO,
crate::methods::OPTION_MAP_OR_NONE_INFO,
crate::methods::OR_FUN_CALL_INFO,
crate::methods::OR_THEN_UNWRAP_INFO,
crate::methods::PATH_BUF_PUSH_OVERWRITE_INFO,
crate::methods::RANGE_ZIP_WITH_LEN_INFO,
crate::methods::READONLY_WRITE_LOCK_INFO,
crate::methods::READ_LINE_WITHOUT_TRIM_INFO,
crate::methods::REPEAT_ONCE_INFO,
crate::methods::RESULT_MAP_OR_INTO_OPTION_INFO,
crate::methods::SEARCH_IS_SOME_INFO,
crate::methods::SEEK_FROM_CURRENT_INFO,
crate::methods::SEEK_TO_START_INSTEAD_OF_REWIND_INFO,
crate::methods::SHOULD_IMPLEMENT_TRAIT_INFO,
crate::methods::SINGLE_CHAR_ADD_STR_INFO,
crate::methods::SINGLE_CHAR_PATTERN_INFO,
crate::methods::SKIP_WHILE_NEXT_INFO,
crate::methods::STABLE_SORT_PRIMITIVE_INFO,
crate::methods::STRING_EXTEND_CHARS_INFO,
crate::methods::STRING_LIT_CHARS_ANY_INFO,
crate::methods::SUSPICIOUS_COMMAND_ARG_SPACE_INFO,
crate::methods::SUSPICIOUS_MAP_INFO,
crate::methods::SUSPICIOUS_SPLITN_INFO,
crate::methods::SUSPICIOUS_TO_OWNED_INFO,
crate::methods::TYPE_ID_ON_BOX_INFO,
crate::methods::UNINIT_ASSUMED_INIT_INFO,
crate::methods::UNIT_HASH_INFO,
crate::methods::UNNECESSARY_FILTER_MAP_INFO,
crate::methods::UNNECESSARY_FIND_MAP_INFO,
crate::methods::UNNECESSARY_FOLD_INFO,
crate::methods::UNNECESSARY_JOIN_INFO,
crate::methods::UNNECESSARY_LAZY_EVALUATIONS_INFO,
crate::methods::UNNECESSARY_LITERAL_UNWRAP_INFO,
crate::methods::UNNECESSARY_SORT_BY_INFO,
crate::methods::UNNECESSARY_TO_OWNED_INFO,
crate::methods::UNWRAP_OR_DEFAULT_INFO,
crate::methods::UNWRAP_USED_INFO,
crate::methods::USELESS_ASREF_INFO,
crate::methods::VEC_RESIZE_TO_ZERO_INFO,
crate::methods::VERBOSE_FILE_READS_INFO,
crate::methods::WRONG_SELF_CONVENTION_INFO,
crate::methods::ZST_OFFSET_INFO,
crate::min_ident_chars::MIN_IDENT_CHARS_INFO,
crate::minmax::MIN_MAX_INFO,
crate::misc::SHORT_CIRCUIT_STATEMENT_INFO,
crate::misc::TOPLEVEL_REF_ARG_INFO,
crate::misc::USED_UNDERSCORE_BINDING_INFO,
crate::misc::ZERO_PTR_INFO,
crate::misc_early::BUILTIN_TYPE_SHADOW_INFO,
crate::misc_early::DOUBLE_NEG_INFO,
crate::misc_early::DUPLICATE_UNDERSCORE_ARGUMENT_INFO,
crate::misc_early::MIXED_CASE_HEX_LITERALS_INFO,
crate::misc_early::REDUNDANT_AT_REST_PATTERN_INFO,
crate::misc_early::REDUNDANT_PATTERN_INFO,
crate::misc_early::SEPARATED_LITERAL_SUFFIX_INFO,
crate::misc_early::UNNEEDED_FIELD_PATTERN_INFO,
crate::misc_early::UNNEEDED_WILDCARD_PATTERN_INFO,
crate::misc_early::UNSEPARATED_LITERAL_SUFFIX_INFO,
crate::misc_early::ZERO_PREFIXED_LITERAL_INFO,
crate::mismatching_type_param_order::MISMATCHING_TYPE_PARAM_ORDER_INFO,
crate::missing_assert_message::MISSING_ASSERT_MESSAGE_INFO,
crate::missing_const_for_fn::MISSING_CONST_FOR_FN_INFO,
crate::missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS_INFO,
crate::missing_enforced_import_rename::MISSING_ENFORCED_IMPORT_RENAMES_INFO,
crate::missing_fields_in_debug::MISSING_FIELDS_IN_DEBUG_INFO,
crate::missing_inline::MISSING_INLINE_IN_PUBLIC_ITEMS_INFO,
crate::missing_trait_methods::MISSING_TRAIT_METHODS_INFO,
crate::mixed_read_write_in_expression::DIVERGING_SUB_EXPRESSION_INFO,
crate::mixed_read_write_in_expression::MIXED_READ_WRITE_IN_EXPRESSION_INFO,
crate::module_style::MOD_MODULE_FILES_INFO,
crate::module_style::SELF_NAMED_MODULE_FILES_INFO,
crate::multi_assignments::MULTI_ASSIGNMENTS_INFO,
crate::multiple_unsafe_ops_per_block::MULTIPLE_UNSAFE_OPS_PER_BLOCK_INFO,
crate::mut_key::MUTABLE_KEY_TYPE_INFO,
crate::mut_mut::MUT_MUT_INFO,
crate::mut_reference::UNNECESSARY_MUT_PASSED_INFO,
crate::mutable_debug_assertion::DEBUG_ASSERT_WITH_MUT_CALL_INFO,
crate::mutex_atomic::MUTEX_ATOMIC_INFO,
crate::mutex_atomic::MUTEX_INTEGER_INFO,
crate::needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE_INFO,
crate::needless_bool::BOOL_COMPARISON_INFO,
crate::needless_bool::NEEDLESS_BOOL_INFO,
crate::needless_bool::NEEDLESS_BOOL_ASSIGN_INFO,
crate::needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE_INFO,
crate::needless_continue::NEEDLESS_CONTINUE_INFO,
crate::needless_else::NEEDLESS_ELSE_INFO,
crate::needless_for_each::NEEDLESS_FOR_EACH_INFO,
crate::needless_if::NEEDLESS_IF_INFO,
crate::needless_late_init::NEEDLESS_LATE_INIT_INFO,
crate::needless_parens_on_range_literals::NEEDLESS_PARENS_ON_RANGE_LITERALS_INFO,
crate::needless_pass_by_ref_mut::NEEDLESS_PASS_BY_REF_MUT_INFO,
crate::needless_pass_by_value::NEEDLESS_PASS_BY_VALUE_INFO,
crate::needless_question_mark::NEEDLESS_QUESTION_MARK_INFO,
crate::needless_update::NEEDLESS_UPDATE_INFO,
crate::neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD_INFO,
crate::neg_multiply::NEG_MULTIPLY_INFO,
crate::new_without_default::NEW_WITHOUT_DEFAULT_INFO,
crate::no_effect::NO_EFFECT_INFO,
crate::no_effect::NO_EFFECT_UNDERSCORE_BINDING_INFO,
crate::no_effect::UNNECESSARY_OPERATION_INFO,
crate::no_mangle_with_rust_abi::NO_MANGLE_WITH_RUST_ABI_INFO,
crate::non_copy_const::BORROW_INTERIOR_MUTABLE_CONST_INFO,
crate::non_copy_const::DECLARE_INTERIOR_MUTABLE_CONST_INFO,
crate::non_expressive_names::JUST_UNDERSCORES_AND_DIGITS_INFO,
crate::non_expressive_names::MANY_SINGLE_CHAR_NAMES_INFO,
crate::non_expressive_names::SIMILAR_NAMES_INFO,
crate::non_octal_unix_permissions::NON_OCTAL_UNIX_PERMISSIONS_INFO,
crate::non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY_INFO,
crate::nonstandard_macro_braces::NONSTANDARD_MACRO_BRACES_INFO,
crate::octal_escapes::OCTAL_ESCAPES_INFO,
crate::only_used_in_recursion::ONLY_USED_IN_RECURSION_INFO,
crate::operators::ABSURD_EXTREME_COMPARISONS_INFO,
crate::operators::ARITHMETIC_SIDE_EFFECTS_INFO,
crate::operators::ASSIGN_OP_PATTERN_INFO,
crate::operators::BAD_BIT_MASK_INFO,
crate::operators::CMP_OWNED_INFO,
crate::operators::DOUBLE_COMPARISONS_INFO,
crate::operators::DURATION_SUBSEC_INFO,
crate::operators::EQ_OP_INFO,
crate::operators::ERASING_OP_INFO,
crate::operators::FLOAT_ARITHMETIC_INFO,
crate::operators::FLOAT_CMP_INFO,
crate::operators::FLOAT_CMP_CONST_INFO,
crate::operators::FLOAT_EQUALITY_WITHOUT_ABS_INFO,
crate::operators::IDENTITY_OP_INFO,
crate::operators::INEFFECTIVE_BIT_MASK_INFO,
crate::operators::INTEGER_DIVISION_INFO,
crate::operators::MISREFACTORED_ASSIGN_OP_INFO,
crate::operators::MODULO_ARITHMETIC_INFO,
crate::operators::MODULO_ONE_INFO,
crate::operators::NEEDLESS_BITWISE_BOOL_INFO,
crate::operators::OP_REF_INFO,
crate::operators::PTR_EQ_INFO,
crate::operators::SELF_ASSIGNMENT_INFO,
crate::operators::VERBOSE_BIT_MASK_INFO,
crate::option_env_unwrap::OPTION_ENV_UNWRAP_INFO,
crate::option_if_let_else::OPTION_IF_LET_ELSE_INFO,
crate::overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL_INFO,
crate::panic_in_result_fn::PANIC_IN_RESULT_FN_INFO,
crate::panic_unimplemented::PANIC_INFO,
crate::panic_unimplemented::TODO_INFO,
crate::panic_unimplemented::UNIMPLEMENTED_INFO,
crate::panic_unimplemented::UNREACHABLE_INFO,
crate::partial_pub_fields::PARTIAL_PUB_FIELDS_INFO,
crate::partialeq_ne_impl::PARTIALEQ_NE_IMPL_INFO,
crate::partialeq_to_none::PARTIALEQ_TO_NONE_INFO,
crate::pass_by_ref_or_value::LARGE_TYPES_PASSED_BY_VALUE_INFO,
crate::pass_by_ref_or_value::TRIVIALLY_COPY_PASS_BY_REF_INFO,
crate::pattern_type_mismatch::PATTERN_TYPE_MISMATCH_INFO,
crate::permissions_set_readonly_false::PERMISSIONS_SET_READONLY_FALSE_INFO,
crate::precedence::PRECEDENCE_INFO,
crate::ptr::CMP_NULL_INFO,
crate::ptr::INVALID_NULL_PTR_USAGE_INFO,
crate::ptr::MUT_FROM_REF_INFO,
crate::ptr::PTR_ARG_INFO,
crate::ptr_offset_with_cast::PTR_OFFSET_WITH_CAST_INFO,
crate::pub_use::PUB_USE_INFO,
crate::question_mark::QUESTION_MARK_INFO,
crate::question_mark_used::QUESTION_MARK_USED_INFO,
crate::ranges::MANUAL_RANGE_CONTAINS_INFO,
crate::ranges::RANGE_MINUS_ONE_INFO,
crate::ranges::RANGE_PLUS_ONE_INFO,
crate::ranges::REVERSED_EMPTY_RANGES_INFO,
crate::raw_strings::NEEDLESS_RAW_STRINGS_INFO,
crate::raw_strings::NEEDLESS_RAW_STRING_HASHES_INFO,
crate::rc_clone_in_vec_init::RC_CLONE_IN_VEC_INIT_INFO,
crate::read_zero_byte_vec::READ_ZERO_BYTE_VEC_INFO,
crate::redundant_async_block::REDUNDANT_ASYNC_BLOCK_INFO,
crate::redundant_clone::REDUNDANT_CLONE_INFO,
crate::redundant_closure_call::REDUNDANT_CLOSURE_CALL_INFO,
crate::redundant_else::REDUNDANT_ELSE_INFO,
crate::redundant_field_names::REDUNDANT_FIELD_NAMES_INFO,
crate::redundant_locals::REDUNDANT_LOCALS_INFO,
crate::redundant_pub_crate::REDUNDANT_PUB_CRATE_INFO,
crate::redundant_slicing::DEREF_BY_SLICING_INFO,
crate::redundant_slicing::REDUNDANT_SLICING_INFO,
crate::redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES_INFO,
crate::redundant_type_annotations::REDUNDANT_TYPE_ANNOTATIONS_INFO,
crate::ref_option_ref::REF_OPTION_REF_INFO,
crate::ref_patterns::REF_PATTERNS_INFO,
crate::reference::DEREF_ADDROF_INFO,
crate::regex::INVALID_REGEX_INFO,
crate::regex::TRIVIAL_REGEX_INFO,
crate::return_self_not_must_use::RETURN_SELF_NOT_MUST_USE_INFO,
crate::returns::LET_AND_RETURN_INFO,
crate::returns::NEEDLESS_RETURN_INFO,
crate::returns::NEEDLESS_RETURN_WITH_QUESTION_MARK_INFO,
crate::same_name_method::SAME_NAME_METHOD_INFO,
crate::self_named_constructors::SELF_NAMED_CONSTRUCTORS_INFO,
crate::semicolon_block::SEMICOLON_INSIDE_BLOCK_INFO,
crate::semicolon_block::SEMICOLON_OUTSIDE_BLOCK_INFO,
crate::semicolon_if_nothing_returned::SEMICOLON_IF_NOTHING_RETURNED_INFO,
crate::serde_api::SERDE_API_MISUSE_INFO,
crate::shadow::SHADOW_REUSE_INFO,
crate::shadow::SHADOW_SAME_INFO,
crate::shadow::SHADOW_UNRELATED_INFO,
crate::significant_drop_tightening::SIGNIFICANT_DROP_TIGHTENING_INFO,
crate::single_call_fn::SINGLE_CALL_FN_INFO,
crate::single_char_lifetime_names::SINGLE_CHAR_LIFETIME_NAMES_INFO,
crate::single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS_INFO,
crate::single_range_in_vec_init::SINGLE_RANGE_IN_VEC_INIT_INFO,
crate::size_of_in_element_count::SIZE_OF_IN_ELEMENT_COUNT_INFO,
crate::size_of_ref::SIZE_OF_REF_INFO,
crate::slow_vector_initialization::SLOW_VECTOR_INITIALIZATION_INFO,
crate::std_instead_of_core::ALLOC_INSTEAD_OF_CORE_INFO,
crate::std_instead_of_core::STD_INSTEAD_OF_ALLOC_INFO,
crate::std_instead_of_core::STD_INSTEAD_OF_CORE_INFO,
crate::strings::STRING_ADD_INFO,
crate::strings::STRING_ADD_ASSIGN_INFO,
crate::strings::STRING_FROM_UTF8_AS_BYTES_INFO,
crate::strings::STRING_LIT_AS_BYTES_INFO,
crate::strings::STRING_SLICE_INFO,
crate::strings::STRING_TO_STRING_INFO,
crate::strings::STR_TO_STRING_INFO,
crate::strings::TRIM_SPLIT_WHITESPACE_INFO,
crate::strlen_on_c_strings::STRLEN_ON_C_STRINGS_INFO,
crate::suspicious_doc_comments::SUSPICIOUS_DOC_COMMENTS_INFO,
crate::suspicious_operation_groupings::SUSPICIOUS_OPERATION_GROUPINGS_INFO,
crate::suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL_INFO,
crate::suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL_INFO,
crate::suspicious_xor_used_as_pow::SUSPICIOUS_XOR_USED_AS_POW_INFO,
crate::swap::ALMOST_SWAPPED_INFO,
crate::swap::MANUAL_SWAP_INFO,
crate::swap_ptr_to_ref::SWAP_PTR_TO_REF_INFO,
crate::tabs_in_doc_comments::TABS_IN_DOC_COMMENTS_INFO,
crate::temporary_assignment::TEMPORARY_ASSIGNMENT_INFO,
crate::tests_outside_test_module::TESTS_OUTSIDE_TEST_MODULE_INFO,
crate::to_digit_is_some::TO_DIGIT_IS_SOME_INFO,
crate::trailing_empty_array::TRAILING_EMPTY_ARRAY_INFO,
crate::trait_bounds::TRAIT_DUPLICATION_IN_BOUNDS_INFO,
crate::trait_bounds::TYPE_REPETITION_IN_BOUNDS_INFO,
crate::transmute::CROSSPOINTER_TRANSMUTE_INFO,
crate::transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS_INFO,
crate::transmute::TRANSMUTE_BYTES_TO_STR_INFO,
crate::transmute::TRANSMUTE_FLOAT_TO_INT_INFO,
crate::transmute::TRANSMUTE_INT_TO_BOOL_INFO,
crate::transmute::TRANSMUTE_INT_TO_CHAR_INFO,
crate::transmute::TRANSMUTE_INT_TO_FLOAT_INFO,
crate::transmute::TRANSMUTE_INT_TO_NON_ZERO_INFO,
crate::transmute::TRANSMUTE_NULL_TO_FN_INFO,
crate::transmute::TRANSMUTE_NUM_TO_BYTES_INFO,
crate::transmute::TRANSMUTE_PTR_TO_PTR_INFO,
crate::transmute::TRANSMUTE_PTR_TO_REF_INFO,
crate::transmute::TRANSMUTE_UNDEFINED_REPR_INFO,
crate::transmute::TRANSMUTING_NULL_INFO,
crate::transmute::UNSOUND_COLLECTION_TRANSMUTE_INFO,
crate::transmute::USELESS_TRANSMUTE_INFO,
crate::transmute::WRONG_TRANSMUTE_INFO,
crate::tuple_array_conversions::TUPLE_ARRAY_CONVERSIONS_INFO,
crate::types::BORROWED_BOX_INFO,
crate::types::BOX_COLLECTION_INFO,
crate::types::LINKEDLIST_INFO,
crate::types::OPTION_OPTION_INFO,
crate::types::RC_BUFFER_INFO,
crate::types::RC_MUTEX_INFO,
crate::types::REDUNDANT_ALLOCATION_INFO,
crate::types::TYPE_COMPLEXITY_INFO,
crate::types::VEC_BOX_INFO,
crate::undocumented_unsafe_blocks::UNDOCUMENTED_UNSAFE_BLOCKS_INFO,
crate::undocumented_unsafe_blocks::UNNECESSARY_SAFETY_COMMENT_INFO,
crate::unicode::INVISIBLE_CHARACTERS_INFO,
crate::unicode::NON_ASCII_LITERAL_INFO,
crate::unicode::UNICODE_NOT_NFC_INFO,
crate::uninit_vec::UNINIT_VEC_INFO,
crate::unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD_INFO,
crate::unit_types::LET_UNIT_VALUE_INFO,
crate::unit_types::UNIT_ARG_INFO,
crate::unit_types::UNIT_CMP_INFO,
crate::unnamed_address::FN_ADDRESS_COMPARISONS_INFO,
crate::unnamed_address::VTABLE_ADDRESS_COMPARISONS_INFO,
crate::unnecessary_box_returns::UNNECESSARY_BOX_RETURNS_INFO,
crate::unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS_INFO,
crate::unnecessary_self_imports::UNNECESSARY_SELF_IMPORTS_INFO,
crate::unnecessary_struct_initialization::UNNECESSARY_STRUCT_INITIALIZATION_INFO,
crate::unnecessary_wraps::UNNECESSARY_WRAPS_INFO,
crate::unnested_or_patterns::UNNESTED_OR_PATTERNS_INFO,
crate::unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME_INFO,
crate::unused_async::UNUSED_ASYNC_INFO,
crate::unused_io_amount::UNUSED_IO_AMOUNT_INFO,
crate::unused_peekable::UNUSED_PEEKABLE_INFO,
crate::unused_rounding::UNUSED_ROUNDING_INFO,
crate::unused_self::UNUSED_SELF_INFO,
crate::unused_unit::UNUSED_UNIT_INFO,
crate::unwrap::PANICKING_UNWRAP_INFO,
crate::unwrap::UNNECESSARY_UNWRAP_INFO,
crate::unwrap_in_result::UNWRAP_IN_RESULT_INFO,
crate::upper_case_acronyms::UPPER_CASE_ACRONYMS_INFO,
crate::use_self::USE_SELF_INFO,
crate::useless_conversion::USELESS_CONVERSION_INFO,
crate::vec::USELESS_VEC_INFO,
crate::vec_init_then_push::VEC_INIT_THEN_PUSH_INFO,
crate::visibility::NEEDLESS_PUB_SELF_INFO,
crate::visibility::PUB_WITHOUT_SHORTHAND_INFO,
crate::visibility::PUB_WITH_SHORTHAND_INFO,
crate::wildcard_imports::ENUM_GLOB_USE_INFO,
crate::wildcard_imports::WILDCARD_IMPORTS_INFO,
crate::write::PRINTLN_EMPTY_STRING_INFO,
crate::write::PRINT_LITERAL_INFO,
crate::write::PRINT_STDERR_INFO,
crate::write::PRINT_STDOUT_INFO,
crate::write::PRINT_WITH_NEWLINE_INFO,
crate::write::USE_DEBUG_INFO,
crate::write::WRITELN_EMPTY_STRING_INFO,
crate::write::WRITE_LITERAL_INFO,
crate::write::WRITE_WITH_NEWLINE_INFO,
crate::zero_div_zero::ZERO_DIVIDED_BY_ZERO_INFO,
crate::zero_sized_map_values::ZERO_SIZED_MAP_VALUES_INFO,
];
|
use super::board;
const MAX_PLY: usize = 64;
const MATE_SCORE: i32 = 10000;
const MATE_IN_MAX_PLY: i32 = MATE_SCORE - MAX_PLY as i32;
pub struct PrincipalVariation {
moves: [Option<board::Move>; MAX_PLY],
num_moves: usize,
}
impl PrincipalVariation {
pub fn cleared() -> PrincipalVariation {
PrincipalVariation {
moves: [None; MAX_PLY],
num_moves: 0,
}
}
pub fn at(&self, index: usize) -> board::Move {
assert!(index < self.num_moves);
self.moves[index].unwrap()
}
pub fn set_moves(&mut self, first: board::Move, rest: &PrincipalVariation) {
assert!(rest.num_moves < MAX_PLY);
self.moves[0] = Some(first);
self.moves[1..=rest.num_moves].copy_from_slice(&rest.moves[0..rest.num_moves]);
self.num_moves = rest.num_moves + 1;
for i in self.num_moves..MAX_PLY {
self.moves[i] = None
}
}
}
pub fn perft(board: &board::Board, depth: u32, debug: bool) -> u64 {
let mut num_nodes = 0;
if depth == 0 {
return 1;
}
// Pseudo legal moves may leave us checked
for m in board.pseudo_legal_move_iter() {
let mut board_copy = *board;
board_copy.make_move_unverified(m);
if !board_copy.is_checked() {
board_copy.change_turn();
let num = perft(&board_copy, depth - 1, false);
if debug {
println!("{}: {}", m, num);
}
num_nodes += num;
}
}
num_nodes
}
pub fn negamax_impl(
board: &board::Board,
depth: u32,
ply: u32,
mut alpha: i32,
beta: i32,
prev_move: Option<board::Move>,
is_checked: bool,
pv: &mut PrincipalVariation,
first_moves: &[Option<board::Move>],
) -> i32 {
// Reference: https://www.chessprogramming.org/Alpha-Beta
if depth == 0 {
pv.num_moves = 0;
return board.evaluate();
}
let mut children_pv = PrincipalVariation::cleared();
let mut any_legal_moves = false;
let rest_moves = board
.pseudo_legal_move_iter()
.filter(|&m| Some(m) != first_moves[0]);
for m in first_moves[0].into_iter().chain(rest_moves) {
let mut board_copy = *board;
board_copy.make_move_unverified(m);
if !board_copy.is_checked() {
any_legal_moves = true;
board_copy.change_turn();
let is_opponent_checked = board_copy.is_checked();
let new_depth = if depth == 1
&& ((prev_move.is_some() && m.dst == prev_move.unwrap().dst)
|| is_opponent_checked)
{
// Position is not "quiet" at leaf node; extend depth to
// resolve captures and checks with a "quiescence search"
1
} else {
depth - 1
};
let score = -negamax_impl(
&board_copy,
new_depth,
ply + 1,
-beta,
-alpha,
Some(m),
is_opponent_checked,
&mut children_pv,
if Some(m) == first_moves[0] { &first_moves[1..] } else { &[None] },
);
if score > alpha {
alpha = score; // alpha acts like max in MiniMax
pv.set_moves(m, &children_pv)
}
if alpha >= beta {
break
}
}
}
if !any_legal_moves {
pv.num_moves = 0;
return if is_checked {
// Mate: add ply to prefer mate in fewer moves
-MATE_SCORE + ply as i32
} else {
// Stale mate
0
};
}
alpha
}
fn mate_in_ply(score: i32) -> Option<i32> {
if score >= MATE_IN_MAX_PLY {
Some(MATE_SCORE - score)
} else if score <= -MATE_IN_MAX_PLY {
Some(-MATE_SCORE - score)
} else {
None
}
}
pub fn negamax(
board: &board::Board,
depth: u32,
debug: bool,
first_moves: &[Option<board::Move>],
) -> (i32, PrincipalVariation) {
assert!(depth > 0);
let alpha = -MATE_SCORE;
let beta = MATE_SCORE;
let mut pv = PrincipalVariation::cleared();
let score = negamax_impl(
board,
depth,
0,
alpha,
beta,
None,
board.is_checked(),
&mut pv,
first_moves,
);
(score, pv)
}
pub fn negamax_iterative_deepening(
board: &board::Board,
time_budget: std::time::Duration,
) -> (i32, PrincipalVariation, u32) {
let start = std::time::Instant::now();
let mut depth = 1;
let mut pv = PrincipalVariation::cleared();
loop {
let iteration_start = std::time::Instant::now();
let (best_score, moves) = negamax(board, depth, false, &pv.moves);
pv = moves;
let estimated_branching_factor = board.count_pieces();
let estimated_next_iteration_time =
iteration_start.elapsed() * estimated_branching_factor;
let time = iteration_start.elapsed();
println!(
"info depth {} score {} time {} pv {}",
depth,
if let Some(ply) = mate_in_ply(best_score) {
format!("mate {}", (ply + 1) / 2)
} else {
format!("cp {}", best_score)
},
time.as_secs() * 1_000u64 + time.subsec_micros() as u64 / 1_000u64,
pv.moves
.iter()
.take(pv.num_moves)
.map(|m| format!("{}", m.unwrap()))
.collect::<Vec<String>>()
.join(" "),
);
if start.elapsed() + estimated_next_iteration_time / 2 > time_budget {
break (best_score, pv, depth);
}
depth += 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::board::Board;
// https://gist.github.com/peterellisjones/8c46c28141c162d1d8a0f0badbc9cff9
#[test]
fn perft_test_position_1() {
let board = Board::from_fen("r6r/1b2k1bq/8/8/7B/8/8/R3K2R b QK");
assert_eq!(8, board.count_moves());
assert_eq!(8, perft(&board, 1, false));
}
#[test]
fn perft_test_position_2() {
let board = Board::from_fen("8/8/8/2k5/2pP4/8/B7/4K3 b - d3");
assert_eq!(8, board.count_moves());
assert_eq!(8, perft(&board, 1, false));
}
#[test]
fn perft_test_position_3() {
let board = Board::from_fen("r1bqkbnr/pppppppp/n7/8/8/P7/1PPPPPPP/RNBQKBNR w QqKk");
assert_eq!(19, board.count_moves());
assert_eq!(19, perft(&board, 1, false));
}
#[test]
fn peft_test_position_4() {
let board = Board::from_fen("r3k2r/p1pp1pb1/bn2Qnp1/2qPN3/1p2P3/2N5/PPPBBPPP/R3K2R b QqKk");
assert_eq!(5, board.count_moves());
assert_eq!(5, perft(&board, 1, false));
}
#[test]
fn peft_test_position_5() {
let board = Board::from_fen("2kr3r/p1ppqpb1/bn2Qnp1/3PN3/1p2P3/2N5/PPPBBPPP/R3K2R b QK");
assert_eq!(44, board.count_moves());
assert_eq!(44, perft(&board, 1, false));
}
#[test]
fn peft_test_position_6() {
let board = Board::from_fen("rnb2k1r/pp1Pbppp/2p5/q7/2B5/8/PPPQNnPP/RNB1K2R w QK");
assert_eq!(39, board.count_moves());
assert_eq!(39, perft(&board, 1, false));
}
#[test]
fn peft_test_position_7() {
let board = Board::from_fen("2r5/3pk3/8/2P5/8/2K5/8/8 w -");
assert_eq!(9, board.count_moves());
assert_eq!(9, perft(&board, 1, false));
}
#[test]
fn perft_test_position_8() {
let board = Board::from_fen("rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ -");
assert_eq!(62379, perft(&board, 3, true));
}
#[test]
fn perft_test_position_9() {
let board = Board::from_fen("rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ -");
assert_eq!(62379, perft(&board, 3, true));
}
#[test]
fn perft_test_position_10() {
let board =
Board::from_fen("r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - -");
assert_eq!(89890, perft(&board, 3, true));
}
#[test]
fn perft_test_position_11() {
let board = Board::from_fen("K1k5/8/P7/8/8/8/8/8 w - -");
assert_eq!(2217, perft(&board, 6, true));
}
#[test]
fn perft_test_position_12() {
let board = Board::from_fen("8/8/2k5/5q2/5n2/8/5K2/8 b - -");
assert_eq!(23527, perft(&board, 4, true));
}
#[test]
fn perft_initial_position() {
let board = Board::initial_position();
assert_eq!(1, perft(&board, 0, false));
assert_eq!(20, perft(&board, 1, false));
assert_eq!(400, perft(&board, 2, false));
assert_eq!(8902, perft(&board, 3, false));
assert_eq!(197281, perft(&board, 4, false));
}
#[test]
fn negamax_mate_in_one() {
let board = Board::from_fen("r3k2r/Rb6/8/8/8/2b1K3/2q4B/7R b kq - 7 4");
let (score, moves) = negamax(&board, 2, true, &[None]);
assert_eq!(MATE_SCORE - 1, score);
assert_eq!("c2d2", format!("{}", moves.at(0)));
}
#[test]
fn negamax_mate_in_two() {
let board = Board::from_fen("r3k2r/Rb6/8/8/8/2b5/2q1K2B/7R w kq - 6 4");
let (score, moves) = negamax(&board, 3, true, &[None]);
assert_eq!(-(MATE_SCORE - 2), score);
assert_eq!("e2e3", format!("{}", moves.at(0)));
assert_eq!("c2d2", format!("{}", moves.at(1)));
}
#[test]
fn negamax_mate_in_three() {
let board = Board::from_fen("r3k2r/Rb5q/8/8/8/2b5/4K2B/7R b kq - 3 2");
let (score, moves) = negamax(&board, 4, true, &[None]);
assert_eq!(MATE_SCORE - 3, score);
assert_eq!("h7c2", format!("{}", moves.at(0)));
}
#[test]
fn negamax_mate_in_five_with_check_extension() {
let board = Board::from_fen("5k2/6pp/1N6/4np2/2B1n2K/1P6/P4P1P/8 b - - 0 41");
let (score, moves) = negamax(&board, 5, true, &[None]);
assert_eq!(MATE_SCORE - 5, score);
assert_eq!("e5g6", format!("{}", moves.at(0)));
assert_eq!(5, moves.num_moves);
}
#[test]
fn negamax_should_not_extend_search() {
let board = Board::from_fen("r2qkb1r/pppbpppp/3p1n2/1B6/1n6/2N1PQ2/PPPPNPPP/R1B1K2R w KQkq -");
let (score, moves) = negamax(&board, 1, true, &[None]);
assert_eq!(1, moves.num_moves);
assert!(moves.moves[1].is_none());
}
#[test]
fn negamax_mate_in_five_with_depth_6() {
let board = Board::from_fen("5k2/6pp/1N6/4np2/2B1n2K/1P6/P4P1P/8 b - - 0 41");
let (score, moves) = negamax(&board, 6, true, &[None]);
assert_eq!(MATE_SCORE - 5, score);
assert_eq!("e5g6", format!("{}", moves.at(0)));
assert_eq!(5, moves.num_moves);
}
#[test]
fn negamax_mate_in_six() {
let board = Board::from_fen("8/8/2k5/8/2K5/4q3/8/8 w - -");
let (score, moves) = negamax(&board, 7, true, &[None]);
assert_eq!(-(MATE_SCORE - 6), score);
assert_eq!("c4b4", format!("{}", moves.at(0)));
}
#[test]
fn find_shortest_path_to_mate() {
let mut board = Board::from_fen("8/2k5/8/K7/8/4q3/8/8 b - -");
let (score1, moves1) = negamax(&board, 6, true, &[None]);
assert_eq!(MATE_SCORE - 3, score1);
assert_eq!("e3b3", format!("{}", moves1.at(0)));
board.make_move("e3b3");
let (score2, moves2) = negamax(&board, 6, true, &[None]);
assert_eq!(-(MATE_SCORE - 2), score2);
assert_eq!("a5a6", format!("{}", moves2.at(0)));
board.make_move("a5a6");
// Two possible moves to mate, make sure we take one of them
let (score3, moves3) = negamax(&board, 6, true, &[None]);
assert_eq!(MATE_SCORE - 1, score3);
board.make_move(&format!("{}", moves3.at(0)));
}
#[test]
fn avoid_stale_mate_when_winning() {
let mut board = Board::from_fen("4k3/4p3/4PP2/8/1BP4P/1P6/P2P4/RN1K1B2 w - -");
let (_score, moves) = negamax(&board, 2, true, &[None]);
assert!(board.make_move(&format!("{}", moves.at(0))));
assert!(!board.is_stale_mate());
}
#[test]
fn mate_in_ply_test() {
assert_eq!(Some(0), mate_in_ply(MATE_SCORE));
assert_eq!(None, mate_in_ply(0));
assert_eq!(Some(1), mate_in_ply(MATE_SCORE - 1));
assert_eq!(Some(-1), mate_in_ply(-(MATE_SCORE - 1)));
}
} |
// Generated from vec.rs.tera template. Edit the template, not the generated file.
use crate::{f64::math, BVec2, DVec3, IVec2, UVec2, Vec2};
#[cfg(not(target_arch = "spirv"))]
use core::fmt;
use core::iter::{Product, Sum};
use core::{f32, ops::*};
/// Creates a 2-dimensional vector.
#[inline(always)]
pub const fn dvec2(x: f64, y: f64) -> DVec2 {
DVec2::new(x, y)
}
/// A 2-dimensional vector.
#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(feature = "cuda", repr(align(16)))]
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
#[cfg_attr(target_arch = "spirv", repr(simd))]
pub struct DVec2 {
pub x: f64,
pub y: f64,
}
impl DVec2 {
/// All zeroes.
pub const ZERO: Self = Self::splat(0.0);
/// All ones.
pub const ONE: Self = Self::splat(1.0);
/// All negative ones.
pub const NEG_ONE: Self = Self::splat(-1.0);
/// All `f64::MIN`.
pub const MIN: Self = Self::splat(f64::MIN);
/// All `f64::MAX`.
pub const MAX: Self = Self::splat(f64::MAX);
/// All `f64::NAN`.
pub const NAN: Self = Self::splat(f64::NAN);
/// All `f64::INFINITY`.
pub const INFINITY: Self = Self::splat(f64::INFINITY);
/// All `f64::NEG_INFINITY`.
pub const NEG_INFINITY: Self = Self::splat(f64::NEG_INFINITY);
/// A unit vector pointing along the positive X axis.
pub const X: Self = Self::new(1.0, 0.0);
/// A unit vector pointing along the positive Y axis.
pub const Y: Self = Self::new(0.0, 1.0);
/// A unit vector pointing along the negative X axis.
pub const NEG_X: Self = Self::new(-1.0, 0.0);
/// A unit vector pointing along the negative Y axis.
pub const NEG_Y: Self = Self::new(0.0, -1.0);
/// The unit axes.
pub const AXES: [Self; 2] = [Self::X, Self::Y];
/// Creates a new vector.
#[inline(always)]
pub const fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
/// Creates a vector with all elements set to `v`.
#[inline]
pub const fn splat(v: f64) -> Self {
Self { x: v, y: v }
}
/// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
/// for each element of `self`.
///
/// A true element in the mask uses the corresponding element from `if_true`, and false
/// uses the element from `if_false`.
#[inline]
pub fn select(mask: BVec2, if_true: Self, if_false: Self) -> Self {
Self {
x: if mask.x { if_true.x } else { if_false.x },
y: if mask.y { if_true.y } else { if_false.y },
}
}
/// Creates a new vector from an array.
#[inline]
pub const fn from_array(a: [f64; 2]) -> Self {
Self::new(a[0], a[1])
}
/// `[x, y]`
#[inline]
pub const fn to_array(&self) -> [f64; 2] {
[self.x, self.y]
}
/// Creates a vector from the first 2 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 2 elements long.
#[inline]
pub const fn from_slice(slice: &[f64]) -> Self {
Self::new(slice[0], slice[1])
}
/// Writes the elements of `self` to the first 2 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 2 elements long.
#[inline]
pub fn write_to_slice(self, slice: &mut [f64]) {
slice[0] = self.x;
slice[1] = self.y;
}
/// Creates a 3D vector from `self` and the given `z` value.
#[inline]
pub const fn extend(self, z: f64) -> DVec3 {
DVec3::new(self.x, self.y, z)
}
/// Computes the dot product of `self` and `rhs`.
#[inline]
pub fn dot(self, rhs: Self) -> f64 {
(self.x * rhs.x) + (self.y * rhs.y)
}
/// Returns a vector where every component is the dot product of `self` and `rhs`.
#[inline]
pub fn dot_into_vec(self, rhs: Self) -> Self {
Self::splat(self.dot(rhs))
}
/// Returns a vector containing the minimum values for each element of `self` and `rhs`.
///
/// In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`.
#[inline]
pub fn min(self, rhs: Self) -> Self {
Self {
x: self.x.min(rhs.x),
y: self.y.min(rhs.y),
}
}
/// Returns a vector containing the maximum values for each element of `self` and `rhs`.
///
/// In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`.
#[inline]
pub fn max(self, rhs: Self) -> Self {
Self {
x: self.x.max(rhs.x),
y: self.y.max(rhs.y),
}
}
/// Component-wise clamping of values, similar to [`f64::clamp`].
///
/// Each element in `min` must be less-or-equal to the corresponding element in `max`.
///
/// # Panics
///
/// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
#[inline]
pub fn clamp(self, min: Self, max: Self) -> Self {
glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
self.max(min).min(max)
}
/// Returns the horizontal minimum of `self`.
///
/// In other words this computes `min(x, y, ..)`.
#[inline]
pub fn min_element(self) -> f64 {
self.x.min(self.y)
}
/// Returns the horizontal maximum of `self`.
///
/// In other words this computes `max(x, y, ..)`.
#[inline]
pub fn max_element(self) -> f64 {
self.x.max(self.y)
}
/// Returns a vector mask containing the result of a `==` comparison for each element of
/// `self` and `rhs`.
///
/// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
/// elements.
#[inline]
pub fn cmpeq(self, rhs: Self) -> BVec2 {
BVec2::new(self.x.eq(&rhs.x), self.y.eq(&rhs.y))
}
/// Returns a vector mask containing the result of a `!=` comparison for each element of
/// `self` and `rhs`.
///
/// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
/// elements.
#[inline]
pub fn cmpne(self, rhs: Self) -> BVec2 {
BVec2::new(self.x.ne(&rhs.x), self.y.ne(&rhs.y))
}
/// Returns a vector mask containing the result of a `>=` comparison for each element of
/// `self` and `rhs`.
///
/// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
/// elements.
#[inline]
pub fn cmpge(self, rhs: Self) -> BVec2 {
BVec2::new(self.x.ge(&rhs.x), self.y.ge(&rhs.y))
}
/// Returns a vector mask containing the result of a `>` comparison for each element of
/// `self` and `rhs`.
///
/// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
/// elements.
#[inline]
pub fn cmpgt(self, rhs: Self) -> BVec2 {
BVec2::new(self.x.gt(&rhs.x), self.y.gt(&rhs.y))
}
/// Returns a vector mask containing the result of a `<=` comparison for each element of
/// `self` and `rhs`.
///
/// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
/// elements.
#[inline]
pub fn cmple(self, rhs: Self) -> BVec2 {
BVec2::new(self.x.le(&rhs.x), self.y.le(&rhs.y))
}
/// Returns a vector mask containing the result of a `<` comparison for each element of
/// `self` and `rhs`.
///
/// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
/// elements.
#[inline]
pub fn cmplt(self, rhs: Self) -> BVec2 {
BVec2::new(self.x.lt(&rhs.x), self.y.lt(&rhs.y))
}
/// Returns a vector containing the absolute value of each element of `self`.
#[inline]
pub fn abs(self) -> Self {
Self {
x: math::abs(self.x),
y: math::abs(self.y),
}
}
/// Returns a vector with elements representing the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `INFINITY`
/// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
/// - `NAN` if the number is `NAN`
#[inline]
pub fn signum(self) -> Self {
Self {
x: math::signum(self.x),
y: math::signum(self.y),
}
}
/// Returns a vector with signs of `rhs` and the magnitudes of `self`.
#[inline]
pub fn copysign(self, rhs: Self) -> Self {
Self {
x: math::copysign(self.x, rhs.x),
y: math::copysign(self.y, rhs.y),
}
}
/// Returns a bitmask with the lowest 2 bits set to the sign bits from the elements of `self`.
///
/// A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
pub fn is_negative_bitmask(self) -> u32 {
(self.x.is_sign_negative() as u32) | (self.y.is_sign_negative() as u32) << 1
}
/// Returns `true` if, and only if, all elements are finite. If any element is either
/// `NaN`, positive or negative infinity, this will return `false`.
#[inline]
pub fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
pub fn is_nan(self) -> bool {
self.x.is_nan() || self.y.is_nan()
}
/// Performs `is_nan` on each element of self, returning a vector mask of the results.
///
/// In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`.
#[inline]
pub fn is_nan_mask(self) -> BVec2 {
BVec2::new(self.x.is_nan(), self.y.is_nan())
}
/// Computes the length of `self`.
#[doc(alias = "magnitude")]
#[inline]
pub fn length(self) -> f64 {
math::sqrt(self.dot(self))
}
/// Computes the squared length of `self`.
///
/// This is faster than `length()` as it avoids a square root operation.
#[doc(alias = "magnitude2")]
#[inline]
pub fn length_squared(self) -> f64 {
self.dot(self)
}
/// Computes `1.0 / length()`.
///
/// For valid results, `self` must _not_ be of length zero.
#[inline]
pub fn length_recip(self) -> f64 {
self.length().recip()
}
/// Computes the Euclidean distance between two points in space.
#[inline]
pub fn distance(self, rhs: Self) -> f64 {
(self - rhs).length()
}
/// Compute the squared euclidean distance between two points in space.
#[inline]
pub fn distance_squared(self, rhs: Self) -> f64 {
(self - rhs).length_squared()
}
/// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
#[inline]
pub fn div_euclid(self, rhs: Self) -> Self {
Self::new(
math::div_euclid(self.x, rhs.x),
math::div_euclid(self.y, rhs.y),
)
}
/// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
///
/// [Euclidean division]: f64::rem_euclid
#[inline]
pub fn rem_euclid(self, rhs: Self) -> Self {
Self::new(
math::rem_euclid(self.x, rhs.x),
math::rem_euclid(self.y, rhs.y),
)
}
/// Returns `self` normalized to length 1.0.
///
/// For valid results, `self` must _not_ be of length zero, nor very close to zero.
///
/// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
///
/// Panics
///
/// Will panic if `self` is zero length when `glam_assert` is enabled.
#[must_use]
#[inline]
pub fn normalize(self) -> Self {
#[allow(clippy::let_and_return)]
let normalized = self.mul(self.length_recip());
glam_assert!(normalized.is_finite());
normalized
}
/// Returns `self` normalized to length 1.0 if possible, else returns `None`.
///
/// In particular, if the input is zero (or very close to zero), or non-finite,
/// the result of this operation will be `None`.
///
/// See also [`Self::normalize_or_zero()`].
#[must_use]
#[inline]
pub fn try_normalize(self) -> Option<Self> {
let rcp = self.length_recip();
if rcp.is_finite() && rcp > 0.0 {
Some(self * rcp)
} else {
None
}
}
/// Returns `self` normalized to length 1.0 if possible, else returns zero.
///
/// In particular, if the input is zero (or very close to zero), or non-finite,
/// the result of this operation will be zero.
///
/// See also [`Self::try_normalize()`].
#[must_use]
#[inline]
pub fn normalize_or_zero(self) -> Self {
let rcp = self.length_recip();
if rcp.is_finite() && rcp > 0.0 {
self * rcp
} else {
Self::ZERO
}
}
/// Returns whether `self` is length `1.0` or not.
///
/// Uses a precision threshold of `1e-6`.
#[inline]
pub fn is_normalized(self) -> bool {
// TODO: do something with epsilon
math::abs(self.length_squared() - 1.0) <= 1e-4
}
/// Returns the vector projection of `self` onto `rhs`.
///
/// `rhs` must be of non-zero length.
///
/// # Panics
///
/// Will panic if `rhs` is zero length when `glam_assert` is enabled.
#[must_use]
#[inline]
pub fn project_onto(self, rhs: Self) -> Self {
let other_len_sq_rcp = rhs.dot(rhs).recip();
glam_assert!(other_len_sq_rcp.is_finite());
rhs * self.dot(rhs) * other_len_sq_rcp
}
/// Returns the vector rejection of `self` from `rhs`.
///
/// The vector rejection is the vector perpendicular to the projection of `self` onto
/// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
///
/// `rhs` must be of non-zero length.
///
/// # Panics
///
/// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
#[must_use]
#[inline]
pub fn reject_from(self, rhs: Self) -> Self {
self - self.project_onto(rhs)
}
/// Returns the vector projection of `self` onto `rhs`.
///
/// `rhs` must be normalized.
///
/// # Panics
///
/// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
#[must_use]
#[inline]
pub fn project_onto_normalized(self, rhs: Self) -> Self {
glam_assert!(rhs.is_normalized());
rhs * self.dot(rhs)
}
/// Returns the vector rejection of `self` from `rhs`.
///
/// The vector rejection is the vector perpendicular to the projection of `self` onto
/// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
///
/// `rhs` must be normalized.
///
/// # Panics
///
/// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
#[must_use]
#[inline]
pub fn reject_from_normalized(self, rhs: Self) -> Self {
self - self.project_onto_normalized(rhs)
}
/// Returns a vector containing the nearest integer to a number for each element of `self`.
/// Round half-way cases away from 0.0.
#[inline]
pub fn round(self) -> Self {
Self {
x: math::round(self.x),
y: math::round(self.y),
}
}
/// Returns a vector containing the largest integer less than or equal to a number for each
/// element of `self`.
#[inline]
pub fn floor(self) -> Self {
Self {
x: math::floor(self.x),
y: math::floor(self.y),
}
}
/// Returns a vector containing the smallest integer greater than or equal to a number for
/// each element of `self`.
#[inline]
pub fn ceil(self) -> Self {
Self {
x: math::ceil(self.x),
y: math::ceil(self.y),
}
}
/// Returns a vector containing the integer part each element of `self`. This means numbers are
/// always truncated towards zero.
#[inline]
pub fn trunc(self) -> Self {
Self {
x: math::trunc(self.x),
y: math::trunc(self.y),
}
}
/// Returns a vector containing the fractional part of the vector, e.g. `self -
/// self.floor()`.
///
/// Note that this is fast but not precise for large numbers.
#[inline]
pub fn fract(self) -> Self {
self - self.floor()
}
/// Returns a vector containing `e^self` (the exponential function) for each element of
/// `self`.
#[inline]
pub fn exp(self) -> Self {
Self::new(math::exp(self.x), math::exp(self.y))
}
/// Returns a vector containing each element of `self` raised to the power of `n`.
#[inline]
pub fn powf(self, n: f64) -> Self {
Self::new(math::powf(self.x, n), math::powf(self.y, n))
}
/// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
#[inline]
pub fn recip(self) -> Self {
Self {
x: 1.0 / self.x,
y: 1.0 / self.y,
}
}
/// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
///
/// When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result
/// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
/// extrapolated.
#[doc(alias = "mix")]
#[inline]
pub fn lerp(self, rhs: Self, s: f64) -> Self {
self + ((rhs - self) * s)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs` is
/// less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two vectors contain similar elements. It works best when
/// comparing with a known value. The `max_abs_diff` that should be used used depends on
/// the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f64) -> bool {
self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
}
/// Returns a vector with a length no less than `min` and no more than `max`
///
/// # Panics
///
/// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
#[inline]
pub fn clamp_length(self, min: f64, max: f64) -> Self {
glam_assert!(min <= max);
let length_sq = self.length_squared();
if length_sq < min * min {
min * (self / math::sqrt(length_sq))
} else if length_sq > max * max {
max * (self / math::sqrt(length_sq))
} else {
self
}
}
/// Returns a vector with a length no more than `max`
pub fn clamp_length_max(self, max: f64) -> Self {
let length_sq = self.length_squared();
if length_sq > max * max {
max * (self / math::sqrt(length_sq))
} else {
self
}
}
/// Returns a vector with a length no less than `min`
pub fn clamp_length_min(self, min: f64) -> Self {
let length_sq = self.length_squared();
if length_sq < min * min {
min * (self / math::sqrt(length_sq))
} else {
self
}
}
/// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
/// error, yielding a more accurate result than an unfused multiply-add.
///
/// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
/// architecture has a dedicated fma CPU instruction. However, this is not always true,
/// and will be heavily dependant on designing algorithms with specific target hardware in
/// mind.
#[inline]
pub fn mul_add(self, a: Self, b: Self) -> Self {
Self::new(
math::mul_add(self.x, a.x, b.x),
math::mul_add(self.y, a.y, b.y),
)
}
/// Creates a 2D vector containing `[angle.cos(), angle.sin()]`. This can be used in
/// conjunction with the [`rotate()`][Self::rotate()] method, e.g.
/// `DVec2::from_angle(PI).rotate(DVec2::Y)` will create the vector `[-1, 0]`
/// and rotate [`DVec2::Y`] around it returning `-DVec2::Y`.
#[inline]
pub fn from_angle(angle: f64) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self { x: cos, y: sin }
}
/// Returns the angle (in radians) between `self` and `rhs` in the range `[-π, +π]`.
///
/// The inputs do not need to be unit vectors however they must be non-zero.
#[inline]
pub fn angle_between(self, rhs: Self) -> f64 {
let angle = math::acos_approx(
self.dot(rhs) / math::sqrt(self.length_squared() * rhs.length_squared()),
);
angle * math::signum(self.perp_dot(rhs))
}
/// Returns a vector that is equal to `self` rotated by 90 degrees.
#[inline]
pub fn perp(self) -> Self {
Self {
x: -self.y,
y: self.x,
}
}
/// The perpendicular dot product of `self` and `rhs`.
/// Also known as the wedge product, 2D cross product, and determinant.
#[doc(alias = "wedge")]
#[doc(alias = "cross")]
#[doc(alias = "determinant")]
#[inline]
pub fn perp_dot(self, rhs: Self) -> f64 {
(self.x * rhs.y) - (self.y * rhs.x)
}
/// Returns `rhs` rotated by the angle of `self`. If `self` is normalized,
/// then this just rotation. This is what you usually want. Otherwise,
/// it will be like a rotation with a multiplication by `self`'s length.
#[must_use]
#[inline]
pub fn rotate(self, rhs: Self) -> Self {
Self {
x: self.x * rhs.x - self.y * rhs.y,
y: self.y * rhs.x + self.x * rhs.y,
}
}
/// Casts all elements of `self` to `f32`.
#[inline]
pub fn as_vec2(&self) -> crate::Vec2 {
crate::Vec2::new(self.x as f32, self.y as f32)
}
/// Casts all elements of `self` to `i32`.
#[inline]
pub fn as_ivec2(&self) -> crate::IVec2 {
crate::IVec2::new(self.x as i32, self.y as i32)
}
/// Casts all elements of `self` to `u32`.
#[inline]
pub fn as_uvec2(&self) -> crate::UVec2 {
crate::UVec2::new(self.x as u32, self.y as u32)
}
/// Casts all elements of `self` to `i64`.
#[inline]
pub fn as_i64vec2(&self) -> crate::I64Vec2 {
crate::I64Vec2::new(self.x as i64, self.y as i64)
}
/// Casts all elements of `self` to `u64`.
#[inline]
pub fn as_u64vec2(&self) -> crate::U64Vec2 {
crate::U64Vec2::new(self.x as u64, self.y as u64)
}
}
impl Default for DVec2 {
#[inline(always)]
fn default() -> Self {
Self::ZERO
}
}
impl Div<DVec2> for DVec2 {
type Output = Self;
#[inline]
fn div(self, rhs: Self) -> Self {
Self {
x: self.x.div(rhs.x),
y: self.y.div(rhs.y),
}
}
}
impl DivAssign<DVec2> for DVec2 {
#[inline]
fn div_assign(&mut self, rhs: Self) {
self.x.div_assign(rhs.x);
self.y.div_assign(rhs.y);
}
}
impl Div<f64> for DVec2 {
type Output = Self;
#[inline]
fn div(self, rhs: f64) -> Self {
Self {
x: self.x.div(rhs),
y: self.y.div(rhs),
}
}
}
impl DivAssign<f64> for DVec2 {
#[inline]
fn div_assign(&mut self, rhs: f64) {
self.x.div_assign(rhs);
self.y.div_assign(rhs);
}
}
impl Div<DVec2> for f64 {
type Output = DVec2;
#[inline]
fn div(self, rhs: DVec2) -> DVec2 {
DVec2 {
x: self.div(rhs.x),
y: self.div(rhs.y),
}
}
}
impl Mul<DVec2> for DVec2 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self {
Self {
x: self.x.mul(rhs.x),
y: self.y.mul(rhs.y),
}
}
}
impl MulAssign<DVec2> for DVec2 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
self.x.mul_assign(rhs.x);
self.y.mul_assign(rhs.y);
}
}
impl Mul<f64> for DVec2 {
type Output = Self;
#[inline]
fn mul(self, rhs: f64) -> Self {
Self {
x: self.x.mul(rhs),
y: self.y.mul(rhs),
}
}
}
impl MulAssign<f64> for DVec2 {
#[inline]
fn mul_assign(&mut self, rhs: f64) {
self.x.mul_assign(rhs);
self.y.mul_assign(rhs);
}
}
impl Mul<DVec2> for f64 {
type Output = DVec2;
#[inline]
fn mul(self, rhs: DVec2) -> DVec2 {
DVec2 {
x: self.mul(rhs.x),
y: self.mul(rhs.y),
}
}
}
impl Add<DVec2> for DVec2 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
Self {
x: self.x.add(rhs.x),
y: self.y.add(rhs.y),
}
}
}
impl AddAssign<DVec2> for DVec2 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.x.add_assign(rhs.x);
self.y.add_assign(rhs.y);
}
}
impl Add<f64> for DVec2 {
type Output = Self;
#[inline]
fn add(self, rhs: f64) -> Self {
Self {
x: self.x.add(rhs),
y: self.y.add(rhs),
}
}
}
impl AddAssign<f64> for DVec2 {
#[inline]
fn add_assign(&mut self, rhs: f64) {
self.x.add_assign(rhs);
self.y.add_assign(rhs);
}
}
impl Add<DVec2> for f64 {
type Output = DVec2;
#[inline]
fn add(self, rhs: DVec2) -> DVec2 {
DVec2 {
x: self.add(rhs.x),
y: self.add(rhs.y),
}
}
}
impl Sub<DVec2> for DVec2 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self {
Self {
x: self.x.sub(rhs.x),
y: self.y.sub(rhs.y),
}
}
}
impl SubAssign<DVec2> for DVec2 {
#[inline]
fn sub_assign(&mut self, rhs: DVec2) {
self.x.sub_assign(rhs.x);
self.y.sub_assign(rhs.y);
}
}
impl Sub<f64> for DVec2 {
type Output = Self;
#[inline]
fn sub(self, rhs: f64) -> Self {
Self {
x: self.x.sub(rhs),
y: self.y.sub(rhs),
}
}
}
impl SubAssign<f64> for DVec2 {
#[inline]
fn sub_assign(&mut self, rhs: f64) {
self.x.sub_assign(rhs);
self.y.sub_assign(rhs);
}
}
impl Sub<DVec2> for f64 {
type Output = DVec2;
#[inline]
fn sub(self, rhs: DVec2) -> DVec2 {
DVec2 {
x: self.sub(rhs.x),
y: self.sub(rhs.y),
}
}
}
impl Rem<DVec2> for DVec2 {
type Output = Self;
#[inline]
fn rem(self, rhs: Self) -> Self {
Self {
x: self.x.rem(rhs.x),
y: self.y.rem(rhs.y),
}
}
}
impl RemAssign<DVec2> for DVec2 {
#[inline]
fn rem_assign(&mut self, rhs: Self) {
self.x.rem_assign(rhs.x);
self.y.rem_assign(rhs.y);
}
}
impl Rem<f64> for DVec2 {
type Output = Self;
#[inline]
fn rem(self, rhs: f64) -> Self {
Self {
x: self.x.rem(rhs),
y: self.y.rem(rhs),
}
}
}
impl RemAssign<f64> for DVec2 {
#[inline]
fn rem_assign(&mut self, rhs: f64) {
self.x.rem_assign(rhs);
self.y.rem_assign(rhs);
}
}
impl Rem<DVec2> for f64 {
type Output = DVec2;
#[inline]
fn rem(self, rhs: DVec2) -> DVec2 {
DVec2 {
x: self.rem(rhs.x),
y: self.rem(rhs.y),
}
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f64; 2]> for DVec2 {
#[inline]
fn as_ref(&self) -> &[f64; 2] {
unsafe { &*(self as *const DVec2 as *const [f64; 2]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f64; 2]> for DVec2 {
#[inline]
fn as_mut(&mut self) -> &mut [f64; 2] {
unsafe { &mut *(self as *mut DVec2 as *mut [f64; 2]) }
}
}
impl Sum for DVec2 {
#[inline]
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for DVec2 {
#[inline]
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for DVec2 {
#[inline]
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ONE, Self::mul)
}
}
impl<'a> Product<&'a Self> for DVec2 {
#[inline]
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
}
}
impl Neg for DVec2 {
type Output = Self;
#[inline]
fn neg(self) -> Self {
Self {
x: self.x.neg(),
y: self.y.neg(),
}
}
}
impl Index<usize> for DVec2 {
type Output = f64;
#[inline]
fn index(&self, index: usize) -> &Self::Output {
match index {
0 => &self.x,
1 => &self.y,
_ => panic!("index out of bounds"),
}
}
}
impl IndexMut<usize> for DVec2 {
#[inline]
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
match index {
0 => &mut self.x,
1 => &mut self.y,
_ => panic!("index out of bounds"),
}
}
}
#[cfg(not(target_arch = "spirv"))]
impl fmt::Display for DVec2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{}, {}]", self.x, self.y)
}
}
#[cfg(not(target_arch = "spirv"))]
impl fmt::Debug for DVec2 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple(stringify!(DVec2))
.field(&self.x)
.field(&self.y)
.finish()
}
}
impl From<[f64; 2]> for DVec2 {
#[inline]
fn from(a: [f64; 2]) -> Self {
Self::new(a[0], a[1])
}
}
impl From<DVec2> for [f64; 2] {
#[inline]
fn from(v: DVec2) -> Self {
[v.x, v.y]
}
}
impl From<(f64, f64)> for DVec2 {
#[inline]
fn from(t: (f64, f64)) -> Self {
Self::new(t.0, t.1)
}
}
impl From<DVec2> for (f64, f64) {
#[inline]
fn from(v: DVec2) -> Self {
(v.x, v.y)
}
}
impl From<Vec2> for DVec2 {
#[inline]
fn from(v: Vec2) -> Self {
Self::new(f64::from(v.x), f64::from(v.y))
}
}
impl From<IVec2> for DVec2 {
#[inline]
fn from(v: IVec2) -> Self {
Self::new(f64::from(v.x), f64::from(v.y))
}
}
impl From<UVec2> for DVec2 {
#[inline]
fn from(v: UVec2) -> Self {
Self::new(f64::from(v.x), f64::from(v.y))
}
}
|
//! BMP180 Digital pressure sensor.
//!
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::blocking::i2c::{Read, Write, WriteRead};
use num_traits::Pow;
// BMP180, BMP085 address.
const BMP180_I2CADDR: u8 = 0x77;
const BMP180_CAL_AC1: u8 = 0xAA; // R Calibration data (16 bits)
const BMP180_CAL_AC2: u8 = 0xAC; // R Calibration data (16 bits)
const BMP180_CAL_AC3: u8 = 0xAE; // R Calibration data (16 bits)
const BMP180_CAL_AC4: u8 = 0xB0; // R Calibration data (16 bits)
const BMP180_CAL_AC5: u8 = 0xB2; // R Calibration data (16 bits)
const BMP180_CAL_AC6: u8 = 0xB4; // R Calibration data (16 bits)
const BMP180_CAL_B1: u8 = 0xB6; // R Calibration data (16 bits)
const BMP180_CAL_B2: u8 = 0xB8; // R Calibration data (16 bits)
const BMP180_CAL_MB: u8 = 0xBA; // R Calibration data (16 bits)
const BMP180_CAL_MC: u8 = 0xBC; // R Calibration data (16 bits)
const BMP180_CAL_MD: u8 = 0xBE; // R Calibration data (16 bits)
const BMP180_CONTROL: u8 = 0xF4;
const BMP180_TEMPDATA: u8 = 0xF6;
const BMP180_PRESSUREDATA: u8 = 0xF6;
const BMP180_READTEMPCMD: u8 = 0x2E;
const BMP180_READPRESSURECMD: u8 = 0x34;
/// Hardware pressure sampling accuracy modes.
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum Mode {
UltraLowPower = 0,
Standard,
HighResolution,
UltraHighResolution,
}
impl Mode {
fn oversampling_settings(&self) -> u8 {
*self as u8
}
fn wait_conversion<D: DelayMs<u8>>(&self, delay: &mut D) {
let ms = match self {
Mode::UltraLowPower => 5,
Mode::Standard => 8,
Mode::HighResolution => 14,
Mode::UltraHighResolution => 26,
};
delay.delay_ms(ms);
}
}
/// BMP180, or BMP085.
pub struct BMP180<I> {
device: I,
mode: Mode,
ac1: i16,
ac2: i16,
ac3: i16,
ac4: u16,
ac5: u16,
ac6: u16,
b1: i16,
b2: i16,
mb: i16,
mc: i16,
md: i16,
}
impl<I: Write + WriteRead + Read> BMP180<I> {
/// Create device driver instance.
pub fn new(i2c: I) -> Self {
BMP180 {
device: i2c,
mode: Mode::UltraHighResolution,
ac1: 408,
ac2: -72,
ac3: -14383,
ac4: 32741,
ac5: 32757,
ac6: 23153,
b1: 6190,
b2: 4,
mb: -32767,
mc: -8711,
md: 2868,
}
}
/// Read calibration data from the EEPROM of BMP180.
pub fn init(&mut self) {
self.ac1 = self.read_i16(BMP180_CAL_AC1);
self.ac2 = self.read_i16(BMP180_CAL_AC2);
self.ac3 = self.read_i16(BMP180_CAL_AC3);
self.ac4 = self.read_u16(BMP180_CAL_AC4);
self.ac5 = self.read_u16(BMP180_CAL_AC5);
self.ac6 = self.read_u16(BMP180_CAL_AC6);
self.b1 = self.read_i16(BMP180_CAL_B1);
self.b2 = self.read_i16(BMP180_CAL_B2);
self.mb = self.read_i16(BMP180_CAL_MB);
self.mc = self.read_i16(BMP180_CAL_MC);
self.md = self.read_i16(BMP180_CAL_MD);
}
/// read uncompensated temperature value
#[inline]
fn get_ut<D: DelayMs<u8>>(&mut self, delay: &mut D) -> i32 {
self.write(&[BMP180_CONTROL, BMP180_READTEMPCMD]);
delay.delay_ms(5);
self.read_i16(BMP180_TEMPDATA) as i32
}
/// read uncompensated pressure value
#[inline]
fn get_up<D: DelayMs<u8>>(&mut self, delay: &mut D) -> i32 {
let oss = self.mode.oversampling_settings();
self.write(&[BMP180_CONTROL, BMP180_READPRESSURECMD + (oss << 6)]);
self.mode.wait_conversion(delay);
let msb = self.read_u8(BMP180_PRESSUREDATA) as i32;
let lsb = self.read_u8(BMP180_PRESSUREDATA + 1) as i32;
let xlsb = self.read_u8(BMP180_PRESSUREDATA + 2) as i32;
((msb << 16) + (lsb << 8) + xlsb) >> (8 - oss)
}
/// Calculate true temperature, resolution is 0.1C
pub fn get_temperature<D: DelayMs<u8>>(&mut self, delay: &mut D) -> f32 {
let ut = self.get_ut(delay);
let x1 = ((ut - self.ac6 as i32) * self.ac5 as i32) >> 15;
let x2 = ((self.mc as i32) << 11) / (x1 + self.md as i32);
let b5 = x1 + x2;
((b5 + 8) >> 4) as f32 / 10.0
}
/// Calculate true pressure, in Pa
pub fn get_pressure<D: DelayMs<u8>>(&mut self, delay: &mut D) -> i32 {
let oss = self.mode.oversampling_settings();
let ut = self.get_ut(delay);
let up = self.get_up(delay);
let x1 = ((ut - self.ac6 as i32) * self.ac5 as i32) >> 15;
let x2 = ((self.mc as i32) << 11) / (x1 + self.md as i32);
let b5 = x1 + x2;
let b6 = b5 - 4000;
let x1 = ((self.b2 as i32) * ((b6 * b6) >> 12)) >> 11;
let x2 = ((self.ac2 as i32) * b6) >> 11;
let x3 = x1 + x2;
// NOTE: must use i64 type
let b3: i64 = ((((self.ac1 as i64) * 4 + x3 as i64) << oss) + 2) / 4;
let x1 = ((self.ac3 as i32) * b6) >> 13;
let x2 = ((self.b1 as i32) * ((b6 * b6) >> 12)) >> 16;
let x3 = ((x1 + x2) + 2) >> 2;
let b4: u32 = (self.ac4 as u32) * ((x3 + 32768) as u32) >> 15;
let b7 = (up as i64 - b3 as i64) * (50000 >> oss);
let p = if b7 < 0x80000000 {
(b7 * 2) / (b4 as i64)
} else {
(b7 / (b4 as i64)) * 2
};
let x1 = (p >> 8) * (p >> 8);
let x1 = (x1 * 3038) >> 16;
let x2 = (-7357 * p) >> 16;
let p = p + ((x1 + x2 + 3791) >> 4);
p as i32
}
/// Calculate absolute altitude
pub fn calculate_altitude<D: DelayMs<u8>>(&mut self, delay: &mut D, sealevel_pa: f32) -> f32 {
let pa = self.get_pressure(delay) as f32;
44330.0 * (1.0 - (pa / sealevel_pa).pow(1.0 / 5.255))
}
/// Calculate pressure at sea level
pub fn calculate_sealevel_pressure<D: DelayMs<u8>>(
&mut self,
delay: &mut D,
altitude_m: f32,
) -> u32 {
let pressure = self.get_pressure(delay) as f32;
let p0 = pressure / (1.0 - altitude_m / 44330.0).pow(5.255);
p0 as u32
}
pub fn release(self) -> I {
self.device
}
fn write(&mut self, data: &[u8]) {
let _ = self.device.write(BMP180_I2CADDR, data);
}
fn read_u8(&mut self, reg: u8) -> u8 {
let mut buf = [0u8];
let _ = self.device.write_read(BMP180_I2CADDR, &[reg], &mut buf[..]);
buf[0]
}
fn read_i16(&mut self, reg: u8) -> i16 {
let mut buf = [0u8; 2];
buf[0] = self.read_u8(reg);
buf[1] = self.read_u8(reg + 1);
// let _ = self.device.write_read(BMP180_I2CADDR, &[reg], &mut buf[..]);
i16::from_be_bytes(buf)
}
fn read_u16(&mut self, reg: u8) -> u16 {
let mut buf = [0u8; 2];
buf[0] = self.read_u8(reg);
buf[1] = self.read_u8(reg + 1);
// let _ = self.device.write_read(BMP180_I2CADDR, &[reg], &mut buf[..]);
u16::from_be_bytes(buf)
}
}
|
use crate::utils::lines_from_file;
use std::{time::Instant, vec};
pub fn main() {
let start = Instant::now();
assert_eq!(part_1_test(), 820);
// println!("part_1 {:?}", part_1());
println!("part_2 {:?}", part_2());
let duration = start.elapsed();
println!("Finished after {:?}", duration);
}
fn part_2() -> u16 {
let entries = lines_from_file("src/day_05/input.txt");
let mut seats_occupied = vec![vec![false; 8]; 127];
let mut seat_id_list: Vec<u16> = vec![];
for entry in entries {
let row = compute_seat_row(entry[..7].to_string()) as usize;
let column = compute_seat_column(entry[7..].to_string()) as usize;
seats_occupied[row][column] = true;
seat_id_list.push((row as u16) * 8 + (column as u16));
}
for row in 0..127 {
for column in 0..8 {
if !seats_occupied[row][column] {
let seat_id = (row as u16) * 8 + (column as u16);
if seat_id != 0
&& seat_id_list.contains(&(seat_id - 1))
&& seat_id_list.contains(&(seat_id + 1))
{
return seat_id;
}
}
}
}
1
}
fn part_1() -> u16 {
let entries = lines_from_file("src/day_05/input.txt");
find_highest_seat_id(entries)
}
fn part_1_test() -> u16 {
let entries = lines_from_file("src/day_05/input-test.txt");
find_highest_seat_id(entries)
}
fn find_highest_seat_id(entries: Vec<String>) -> u16 {
let mut highest: u16 = 0;
for entry in entries {
let current = compute_seat_id(entry);
if current > highest {
highest = current
}
}
highest
}
fn compute_seat_id(seat_code: String) -> u16 {
let row = compute_seat_row(seat_code[..7].to_string());
let column = compute_seat_column(seat_code[7..].to_string());
(row as u16) * 8 + (column as u16)
}
fn compute_seat_row(row_code: String) -> u8 {
let mut rows: Vec<u8> = (0..=127).collect();
for i in 0..7 {
match row_code.chars().nth(i).unwrap() {
'F' => rows = rows[..(rows.len() / 2)].to_vec(),
'B' => rows = rows[(rows.len() / 2)..].to_vec(),
_ => {}
}
}
*rows.first().unwrap()
}
fn compute_seat_column(column_code: String) -> u8 {
let mut columns: Vec<u8> = (0..=7).collect();
for i in 0..3 {
match column_code.chars().nth(i).unwrap() {
'L' => columns = columns[..(columns.len() / 2)].to_vec(),
'R' => columns = columns[(columns.len() / 2)..].to_vec(),
_ => {}
}
}
*columns.first().unwrap()
}
|
use crate::crypto::hash;
use crate::math::bytes_to_int;
use crate::math::int_to_bytes;
use std::convert::TryFrom;
use std::convert::TryInto;
use typenum::marker_traits::Unsigned;
use types::beacon_state::BeaconState;
use types::config::Config;
use types::helper_functions_types::Error;
use types::primitives::{Domain, DomainType, Epoch, Slot, ValidatorIndex, Version, H256};
pub fn compute_epoch_at_slot<C: Config>(slot: Slot) -> Epoch {
slot / C::SlotsPerEpoch::to_u64()
}
pub fn compute_start_slot_at_epoch<C: Config>(epoch: Epoch) -> Slot {
epoch * C::SlotsPerEpoch::to_u64()
}
pub fn compute_activation_exit_epoch<C: Config>(epoch: Epoch) -> Epoch {
epoch + 1 + C::min_seed_lookahead()
}
pub fn compute_domain(domain_type: DomainType, fork_version: Option<&Version>) -> Domain {
let domain_type_bytes = int_to_bytes(u64::try_from(domain_type).expect(""), 4).expect("");
let mut domain_bytes = [0, 0, 0, 0, 0, 0, 0, 0];
for i in 0..4 {
domain_bytes[i] = domain_type_bytes[i];
if let Some(f) = fork_version {
domain_bytes[i + 4] = f[i];
}
}
bytes_to_int(&domain_bytes).expect("")
}
pub fn compute_shuffled_index<C: Config>(
index: ValidatorIndex,
index_count: u64,
seed: &H256,
) -> Result<ValidatorIndex, Error> {
if index > index_count {
return Err(Error::IndexOutOfRange);
}
let mut ind = index;
for current_round in 0..C::shuffle_round_count() {
// compute pivot
let seed_bytes = seed.as_bytes();
let round_bytes: Vec<u8> = int_to_bytes(current_round, 1).expect("");
let mut sum_vec: Vec<u8> = Vec::new();
let iter = seed_bytes.iter();
for i in iter {
sum_vec.push(*i);
}
sum_vec.push(round_bytes[0]);
let hashed_value = hash(sum_vec.as_mut_slice());
let mut hash_8_bytes: Vec<u8> = Vec::new();
let iter = hashed_value.iter().take(8);
for i in iter {
hash_8_bytes.push(*i);
}
let pivot = bytes_to_int(hash_8_bytes.as_mut_slice()).expect("") % index_count;
// compute flip
let flip = (pivot + index_count - ind) % index_count;
// compute position
let position = if ind > flip { ind } else { flip };
// compute source
let addition_to_sum: Vec<u8> = int_to_bytes(position / 256, 4).expect("");
let iter = addition_to_sum.iter();
for i in iter {
sum_vec.push(*i);
}
let source = hash(sum_vec.as_mut_slice());
// compute byte
let byte = source[usize::try_from((position % 256) / 8).expect("")];
// compute bit
let bit: u8 = (byte >> (position % 8)) % 2;
// flip or not?
if bit == 1 {
ind = flip;
}
}
Ok(ind)
}
pub fn compute_proposer_index<C: Config>(
state: &BeaconState<C>,
indices: &[ValidatorIndex],
seed: &H256,
) -> Result<ValidatorIndex, Error> {
if indices.is_empty() {
return Err(Error::ArrayIsEmpty);
}
let max_random_byte = 255;
let mut i = 0;
loop {
let candidate_index = indices[usize::try_from(
compute_shuffled_index::<C>(i % indices.len() as u64, indices.len() as u64, seed)
.expect(""),
)
.expect("")];
let rand_bytes = int_to_bytes(i / 32, 8).expect("");
let mut seed_and_bytes: Vec<u8> = Vec::new();
for i in 0..32 {
seed_and_bytes.push(seed[i]);
}
let iter = rand_bytes.iter().take(8);
for i in iter {
seed_and_bytes.push(*i);
}
let hashed_seed_and_bytes = hash(seed_and_bytes.as_mut_slice());
let random_byte = hashed_seed_and_bytes[usize::try_from(i % 32).expect("")];
let effective_balance =
state.validators[usize::try_from(candidate_index).expect("")].effective_balance;
if effective_balance * max_random_byte
>= C::max_effective_balance() * u64::from(random_byte)
{
return Ok(candidate_index);
}
i += 1;
}
}
pub fn compute_committee<'a, C: Config>(
indices: &'a [ValidatorIndex],
seed: &H256,
index: u64,
count: u64,
) -> Result<Vec<ValidatorIndex>, Error> {
let start = ((indices.len() as u64) * index) / count;
let end = ((indices.len() as u64) * (index + 1)) / count;
let mut committee_vec: Vec<ValidatorIndex> = Vec::new();
for i in start..end {
committee_vec.push(
indices[usize::try_from(
compute_shuffled_index::<C>(
i,
usize::try_from(indices.len())
.expect("")
.try_into()
.expect(""),
seed,
)
.expect(""),
)
.expect("")],
);
}
Ok(committee_vec)
}
#[cfg(test)]
mod tests {
use super::*;
use bls::{PublicKey, SecretKey};
use types::config::MinimalConfig;
use types::consts::FAR_FUTURE_EPOCH;
use types::types::Validator;
#[test]
fn test_epoch_at_slot() {
// Minimalconfig: SlotsPerEpoch = 8; epochs indexed from 0
assert_eq!(compute_epoch_at_slot::<MinimalConfig>(9), 1);
assert_eq!(compute_epoch_at_slot::<MinimalConfig>(8), 1);
assert_eq!(compute_epoch_at_slot::<MinimalConfig>(7), 0);
}
#[test]
fn test_start_slot_at_epoch() {
assert_eq!(compute_start_slot_at_epoch::<MinimalConfig>(1), 8);
assert_ne!(compute_start_slot_at_epoch::<MinimalConfig>(1), 7);
assert_ne!(compute_start_slot_at_epoch::<MinimalConfig>(1), 9);
}
#[test]
fn test_activation_exit_epoch() {
assert_eq!(compute_activation_exit_epoch::<MinimalConfig>(1), 3);
}
#[test]
fn test_compute_domain() {
let domain: Domain = compute_domain(1, Some(&[0, 0, 0, 1]));
assert_eq!(domain, 0x0001_0000_0001);
// 1 * 256 ^ 4 + 1 = 4294967297 = 0x0001_0000_0001
}
#[test]
fn test_compute_shuffled_index() {
let test_indices_length = 25;
for _i in 0..20 {
let shuffled_index: ValidatorIndex =
compute_shuffled_index::<MinimalConfig>(2, test_indices_length, &H256::random())
.expect("");
let in_range = if shuffled_index >= test_indices_length {
0
} else {
1
};
// if shuffled index is not one of the validators indices (0, ..., test_indices_length - 1), panic.
assert_eq!(1, in_range);
}
}
#[test]
fn test_compute_proposer_index() {
let mut state = BeaconState::<MinimalConfig>::default();
let val1: Validator = Validator {
activation_eligibility_epoch: 2,
activation_epoch: 3,
effective_balance: 0,
exit_epoch: 4,
pubkey: PublicKey::from_secret_key(&SecretKey::random()),
slashed: false,
withdrawable_epoch: 9999,
withdrawal_credentials: H256([0; 32]),
};
let val2: Validator = Validator {
activation_eligibility_epoch: 2,
activation_epoch: 3,
effective_balance: 24,
exit_epoch: FAR_FUTURE_EPOCH,
pubkey: PublicKey::from_secret_key(&SecretKey::random()),
slashed: false,
withdrawable_epoch: 9999,
withdrawal_credentials: H256([0; 32]),
};
state.validators.push(val1).expect("");
state.validators.push(val2).expect("");
let index: ValidatorIndex =
compute_proposer_index(&state, &[0, 1], &H256::random()).expect("");
let in_range = if index >= 2 { 0 } else { 1 };
assert_eq!(1, in_range);
}
#[test]
fn test_compute_committee() {
let mut test_vec: Vec<ValidatorIndex> = Vec::new();
for i in 0..100 {
test_vec.push(i);
}
let committee: Vec<ValidatorIndex> =
compute_committee::<MinimalConfig>(&test_vec, &H256::random(), 2, 20).expect("");
assert_eq!(5, committee.len());
}
}
|
use super::super::atom::{
btn::{self, Btn},
common::Common,
dropdown::{self, Dropdown},
fa,
heading::{self, Heading},
slider::{self, Slider},
text::Text,
};
use super::super::organism::{
popup_color_pallet::{self, PopupColorPallet},
room_modeless::RoomModeless,
};
use super::ShowingModal;
use crate::arena::{block, resource, BlockMut, BlockRef};
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use nusa::prelude::*;
mod description;
use description::Description;
pub struct Props {
pub character: BlockMut<block::Character>,
}
pub enum Msg {
NoOp,
Sub(On),
}
pub enum On {
OpenModal(ShowingModal),
SetDescription(String),
SetDisplayName0(String),
SetDisplayName1(String),
SetName(String),
SetColor(crate::libs::color::Pallet),
SetSize(f64),
SetZOffset(f64),
SetTexSize(f64),
SetSelectedTextureIdx(usize),
SetTextureName(usize, String),
PushTexture,
}
pub struct Tab0 {
character: BlockMut<block::Character>,
element_id: ElementId,
}
ElementId! {
input_character_display_name,
input_character_name
}
impl Component for Tab0 {
type Props = Props;
type Msg = Msg;
type Event = On;
}
impl HtmlComponent for Tab0 {}
impl Constructor for Tab0 {
fn constructor(props: Props) -> Self {
Self {
character: props.character,
element_id: ElementId::new(),
}
}
}
impl Update for Tab0 {
fn on_load(mut self: Pin<&mut Self>, props: Self::Props) -> Cmd<Self> {
self.character = props.character;
Cmd::none()
}
fn update(self: Pin<&mut Self>, msg: Self::Msg) -> Cmd<Self> {
match msg {
Msg::NoOp => Cmd::none(),
Msg::Sub(event) => Cmd::submit(event),
}
}
}
impl Render<Html> for Tab0 {
type Children = ();
fn render(&self, _: Self::Children) -> Html {
Self::styled(Html::div(
Attributes::new()
.class(RoomModeless::class("common-base"))
.class("pure-form"),
Events::new(),
vec![
self.character
.map(|data| self.render_header(data))
.unwrap_or(Common::none()),
self.character
.map(|data| self.render_main(data))
.unwrap_or(Common::none()),
],
))
}
}
impl Tab0 {
fn render_header(&self, character: &block::Character) -> Html {
Html::div(
Attributes::new().class(RoomModeless::class("common-header")),
Events::new(),
vec![
Html::label(
Attributes::new()
.class(RoomModeless::class("common-label"))
.string("for", &self.element_id.input_character_name),
Events::new(),
vec![fa::fas_i("fa-user")],
),
Html::input(
Attributes::new()
.id(&self.element_id.input_character_name)
.value(character.name()),
Events::new().on_input(self, |name| Msg::Sub(On::SetName(name))),
vec![],
),
Html::label(
Attributes::new()
.class(RoomModeless::class("common-label"))
.string("for", &self.element_id.input_character_display_name),
Events::new(),
vec![Html::text("表示名")],
),
Html::input(
Attributes::new().value(&character.display_name().1),
Events::new().on_input(self, |name| Msg::Sub(On::SetDisplayName1(name))),
vec![],
),
Text::span(""),
Html::input(
Attributes::new()
.id(&self.element_id.input_character_display_name)
.value(&character.display_name().0),
Events::new().on_input(self, |name| Msg::Sub(On::SetDisplayName0(name))),
vec![],
),
],
)
}
fn render_main(&self, character: &block::Character) -> Html {
Html::div(
Attributes::new().class(Self::class("main")),
Events::new(),
vec![
self.render_props(character),
Heading::h3(
heading::Variant::Light,
Attributes::new(),
Events::new(),
vec![Html::text("概要")],
),
Description::empty(
self,
None,
description::Props {
character: BlockMut::clone(&self.character),
},
Sub::map(|sub| match sub {
description::On::SetDescription(desc) => Msg::Sub(On::SetDescription(desc)),
}),
),
Heading::h3(
heading::Variant::Light,
Attributes::new(),
Events::new(),
vec![Html::text("立ち絵")],
),
self.render_textures(character),
],
)
}
fn render_props(&self, character: &block::Character) -> Html {
Html::div(
Attributes::new().class(Self::class("content")),
Events::new(),
vec![
Html::div(
Attributes::new().class(Common::keyvalue()),
Events::new(),
vec![
Text::span("サイズ"),
Slider::new(
self,
None,
slider::Position::Linear {
min: 0.1,
max: 10.0,
val: character.size(),
step: 0.1,
},
Sub::map(move |sub| match sub {
slider::On::Input(x) => Msg::Sub(On::SetSize(x)),
_ => Msg::NoOp,
}),
slider::Props {
range_is_editable: false,
theme: slider::Theme::Light,
},
),
Text::span("立ち絵サイズ"),
Slider::new(
self,
None,
slider::Position::Linear {
min: 0.1,
max: 10.0,
val: character.tex_size(),
step: 0.1,
},
Sub::map(move |sub| match sub {
slider::On::Input(x) => Msg::Sub(On::SetTexSize(x)),
_ => Msg::NoOp,
}),
slider::Props {
range_is_editable: false,
theme: slider::Theme::Light,
},
),
Text::span("高さ"),
Slider::new(
self,
None,
slider::Position::Linear {
min: 0.0,
max: 10.0,
val: character.z_offset(),
step: 0.1,
},
Sub::map(move |sub| match sub {
slider::On::Input(x) => {
Msg::Sub(On::SetZOffset(if x < 0.01 { 0.0 } else { x }))
}
_ => Msg::NoOp,
}),
slider::Props {
range_is_editable: false,
theme: slider::Theme::Light,
},
),
],
),
Html::div(
Attributes::new().class(Common::keyvalue()),
Events::new(),
vec![
Text::span("色"),
PopupColorPallet::empty(
self,
None,
popup_color_pallet::Props {
direction: popup_color_pallet::Direction::Bottom,
default_selected: character.color().clone(),
},
Sub::map(|sub| match sub {
popup_color_pallet::On::SelectColor(color) => {
Msg::Sub(On::SetColor(color))
}
}),
),
Text::label("立ち絵", ""),
Dropdown::new(
self,
None,
dropdown::Props {
direction: dropdown::Direction::Bottom,
variant: btn::Variant::DarkLikeMenu,
toggle_type: dropdown::ToggleType::Click,
},
Sub::none(),
(
vec![Html::text(
character
.selected_texture()
.map(|texture| texture.name().clone())
.unwrap_or(String::from("")),
)],
character
.textures()
.iter()
.enumerate()
.map(|(tex_idx, texture)| {
Btn::menu(
Attributes::new(),
Events::new().on_click(self, move |_| {
Msg::Sub(On::SetSelectedTextureIdx(tex_idx))
}),
vec![Html::text(texture.name())],
)
})
.collect(),
),
),
],
),
],
)
}
fn render_textures(&self, character: &block::Character) -> Html {
Html::div(
Attributes::new().class(Self::class("content")),
Events::new(),
vec![
Html::fragment(
character
.textures()
.iter()
.enumerate()
.map(|(tex_idx, texture)| self.render_texture(texture, tex_idx))
.collect(),
),
self.render_new_texture(),
],
)
}
fn render_texture(&self, texture: &block::character::StandingTexture, tex_idx: usize) -> Html {
Html::div(
Attributes::new().class(Self::class("texture")),
Events::new(),
vec![
Html::input(
Attributes::new().value(texture.name()),
Events::new().on_input(self, move |name| {
Msg::Sub(On::SetTextureName(tex_idx, name))
}),
vec![],
),
self.render_texture_image(texture.image(), tex_idx),
],
)
}
fn render_texture_image(
&self,
image: Option<&BlockRef<resource::ImageData>>,
tex_idx: usize,
) -> Html {
image
.and_then(|image| {
image.map(|image| {
Html::img(
Attributes::new()
.draggable("false")
.src(image.url().to_string())
.class(Common::bg_transparent()),
Events::new().on_click(self, move |_| {
Msg::Sub(On::OpenModal(ShowingModal::SelectCharacterTexture(tex_idx)))
}),
vec![],
)
})
})
.unwrap_or_else(|| {
Btn::secondary(
Attributes::new(),
Events::new().on_click(self, move |_| {
Msg::Sub(On::OpenModal(ShowingModal::SelectCharacterTexture(tex_idx)))
}),
vec![Html::text("立ち絵を選択")],
)
})
}
fn render_new_texture(&self) -> Html {
Html::div(
Attributes::new().class(Self::class("texture")),
Events::new(),
vec![Btn::secondary(
Attributes::new(),
Events::new().on_click(self, |_| Msg::Sub(On::PushTexture)),
vec![Html::text("立ち絵を追加")],
)],
)
}
}
impl Tab0 {}
impl Styled for Tab0 {
fn style() -> Style {
style! {
".dropdown" {
"overflow": "visible !important";
}
".main" {
"display": "grid";
"grid-template-columns": "1fr";
"grid-auto-rows": "max-content";
"overflow-y": "scroll";
}
".content" {
"display": "grid";
"column-gap": ".65rem";
"row-gap": ".65rem";
"align-items": "start";
"padding-left": ".65rem";
"padding-right": ".65rem";
"grid-template-columns": "repeat(auto-fit, minmax(20rem, 1fr))";
"grid-auto-rows": "max-content";
}
".content img" {
"width": "100%";
"max-height": "20rem";
"object-fit": "contain";
}
".texture" {
"display": "grid";
"align-items": "start";
"justify-items": "stretch";
"grid-template-columns": "1fr";
"grid-template-rows": "max-content max-content";
}
".textarea" {
"resize": "none";
"height": "15em";
}
}
}
}
|
use reqwest::Client;
use std::{
error::Error,
io::{stdout, BufRead, BufWriter, Lines, Write},
sync::{mpsc::channel, Arc},
thread::{sleep, spawn},
time::Duration,
};
pub struct Response {
pub name: String,
pub status: u16,
}
pub fn request_n<T, U>(
lines: &mut Lines<T>,
n: usize,
url: &str,
outfile: &mut BufWriter<U>,
) -> Result<bool, Box<Error>>
where
T: BufRead,
U: Write,
{
let cli = Arc::new(Client::new());
let (tx, rx) = channel();
let lines = lines.take(n).collect::<Result<Vec<String>, _>>()?;
let len = lines.len();
print!("{}[2K", 27 as char);
print!("fuzzing {}..{}\r", &lines[0], &lines[len - 1]);
stdout().flush()?;
for line in lines {
let fuzz_url = format!("{}/{}", url, &line);
let cli = Arc::clone(&cli);
let tx = tx.clone();
spawn(move || {
let mut counter = 0;
loop {
match cli.get(&fuzz_url).send() {
Ok(res) => {
let s = res.status().as_u16();
if s != 404 {
println!("\n{} returned {}", &line, s);
tx.send(Some(Response {
status: s,
name: line,
}))
.unwrap();
} else {
tx.send(None).unwrap();
}
break;
}
Err(e) => {
counter += 1;
println!(
"\nerror encountered while trying to fuzz {}: {}\nretrying in 1s",
&line, e
);
if counter > 5 {
println!(
"\ntoo many errors encountered trying to fuzz {}, skipped",
line
);
tx.send(Some(Response {
name: line,
status: 500,
}))
.unwrap();
break;
}
sleep(Duration::from_secs(1));
}
}
}
});
}
for _ in 0..len {
if let Some(res) = rx.recv()? {
outfile.write(&format!("{}\t{}\n", res.name, res.status).into_bytes())?;
}
}
outfile.flush()?;
Ok(n == len)
}
|
// HIGHLY INCOMPLETE!!!
use super::animation::Curve;
use util::cur::Cur;
use util::view::Viewable;
use util::fixed::fix16;
use cgmath::{Matrix4, vec3};
use nitro::Name;
use errors::Result;
use super::info_block;
/// Material animation. Does things like UV matrix animation.
pub struct MaterialAnimation {
pub name: Name,
pub num_frames: u16,
pub tracks: Vec<MaterialTrack>,
}
/// Targets one material in a model and animates it.
pub struct MaterialTrack {
pub name: Name,
pub channels: [MaterialChannel; 5],
}
/// Targets one material property for animation????
pub struct MaterialChannel {
pub num_frames: u16,
pub target: MatChannelTarget,
pub curve: Curve<f64>,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum MatChannelTarget {
TranslationU,
TranslationV,
Unknown,
}
pub fn read_mat_anim(cur: Cur, name: Name) -> Result<MaterialAnimation> {
debug!("material animation: {:?}", name);
fields!(cur, mat_anim {
_unknown: [u8; 4], // b'M\0AT' ??
num_frames: u16,
unknown: u16,
end: Cur,
});
let tracks = info_block::read::<[ChannelData; 5]>(end)?
.map(|(chans, name)| {
let c0 = read_channel(cur, chans[0], MatChannelTarget::Unknown)?;
let c1 = read_channel(cur, chans[1], MatChannelTarget::Unknown)?;
let c2 = read_channel(cur, chans[2], MatChannelTarget::Unknown)?;
let c3 = read_channel(cur, chans[3], MatChannelTarget::TranslationU)?;
let c4 = read_channel(cur, chans[4], MatChannelTarget::TranslationV)?;
let channels = [c0, c1, c2, c3, c4];
Ok(MaterialTrack { name, channels })
})
.collect::<Result<Vec<MaterialTrack>>>()?;
Ok(MaterialAnimation {
name,
num_frames,
tracks,
})
}
#[derive(Debug, Copy, Clone)]
struct ChannelData {
num_frames: u16,
flags: u8, // some sort of flags
offset: u32, // meaning appears to depend on flags
}
impl Viewable for ChannelData {
fn size() -> usize { 8 }
fn view(buf: &[u8]) -> ChannelData {
let mut cur = Cur::new(buf);
let num_frames = cur.next::<u16>().unwrap();
let _dummy = cur.next::<u8>().unwrap(); // always 0?
let flags = cur.next::<u8>().unwrap();
let offset = cur.next::<u32>().unwrap();
ChannelData { num_frames, flags, offset }
}
}
fn read_channel(base_cur: Cur, data: ChannelData, target: MatChannelTarget) -> Result<MaterialChannel> {
if !((data.flags == 16) && target != MatChannelTarget::Unknown) {
// That's the only case I understand; otherwise bail.
return Ok(MaterialChannel {
num_frames: 0,
target,
curve: Curve::None,
});
}
let values = (base_cur + data.offset)
.next_n::<u16>(data.num_frames as usize)?
.map(|n| fix16(n, 1, 10, 5))
.collect::<Vec<f64>>();
let curve = Curve::Samples {
start_frame: 0,
end_frame: data.num_frames,
values,
};
Ok(MaterialChannel {
num_frames: data.num_frames,
target,
curve,
})
}
impl MaterialTrack {
pub fn eval_uv_mat(&self, frame: u16) -> Matrix4<f64> {
let (mut u, mut v) = (0.0, 0.0);
for chan in &self.channels {
if chan.target == MatChannelTarget::TranslationU {
u = chan.curve.sample_at(u, frame);
}
if chan.target == MatChannelTarget::TranslationV {
v = chan.curve.sample_at(v, frame);
}
}
Matrix4::from_translation(vec3(u, v, 0.0))
}
}
|
//! The main Crochet interface.
use std::collections::HashMap;
use std::panic::Location;
// The unused annotations are mostly for optional async.
#[allow(unused)]
use druid::{ExtEventSink, SingleUse, Target};
#[cfg(feature = "async-std")]
use async_std::future::Future;
use crate::any_widget::DruidAppData;
#[cfg(feature = "async-std")]
use crate::app_holder::ASYNC;
use crate::id::Id;
use crate::state::State;
use crate::tree::{MutCursor, Mutation, Payload, Tree};
use crate::view::View;
pub struct Cx<'a> {
mut_cursor: MutCursor<'a>,
pub(crate) app_data: &'a mut DruidAppData,
#[allow(unused)]
resolved_futures: &'a HashMap<Id, Box<dyn State>>,
#[allow(unused)]
event_sink: &'a ExtEventSink,
}
impl<'a> Cx<'a> {
/// Only public for experimentation.
pub fn new(
tree: &'a Tree,
app_data: &'a mut DruidAppData,
resolved_futures: &'a HashMap<Id, Box<dyn State>>,
event_sink: &'a ExtEventSink,
) -> Cx<'a> {
let mut_cursor = MutCursor::new(tree);
Cx {
mut_cursor,
app_data,
resolved_futures,
event_sink,
}
}
pub fn into_mutation(self) -> Mutation {
self.mut_cursor.into_mutation()
}
pub fn end(&mut self) {
self.mut_cursor.end();
}
/// Add a view as a leaf.
///
/// This method is expected to be called mostly by the `build`
/// methods on `View` implementors.
pub fn leaf_view(&mut self, view: impl View + 'static, loc: &'static Location) -> Id {
// Note: this always boxes (for convenience), but could be written
// in terms of begin_core to avoid boxing on skip.
let view = Box::new(view);
let body = Payload::View(view);
let id = self.mut_cursor.begin_loc(body, loc);
self.mut_cursor.end();
id
}
/// Begin a view element.
///
/// This method is expected to be called mostly by the `build`
/// methods on `View` implementors.
///
/// The API may change to return a child cx.
pub fn begin_view(&mut self, view: Box<dyn View>, loc: &'static Location) -> Id {
let body = Payload::View(view);
self.mut_cursor.begin_loc(body, loc)
}
/// Traverse into a subtree only if the data has changed.
///
/// The supplied callback *must* create only one widget. This is not
/// enforced, and will probably be relaxed one way or other.
///
/// This method also traverses into the subtree if any of its action
/// queues are non-empty.
#[track_caller]
pub fn if_changed<T: PartialEq + State + 'static, U>(
&mut self,
data: T,
f: impl FnOnce(&mut Cx) -> U,
) -> Option<U> {
let key = self.mut_cursor.key_from_loc(Location::caller());
let changed = self.mut_cursor.begin_core(key, |_id, old_body| {
if let Some(Payload::State(old_data)) = old_body {
if let Some(old_data) = old_data.as_any().downcast_ref::<T>() {
if old_data == &data {
(None, false)
} else {
// Types match, data not equal
(Some(Payload::State(Box::new(data))), true)
}
} else {
// Downcast failed; this shouldn't happen
(Some(Payload::State(Box::new(data))), true)
}
} else {
// Probably inserting new state
(Some(Payload::State(Box::new(data))), true)
}
});
let actions = self.has_action();
let result = if changed || actions {
Some(f(self))
} else {
// TODO: here's a place that needs work if we relax the requirement
// of exactly one child node.
self.mut_cursor.skip_one();
None
};
self.mut_cursor.end();
result
}
/// Spawn a future when the data changes.
///
/// When the data changes (including first insert), call `future_cb` and
/// spawn the returned future. Note that if this callback needs to move
/// the data into the async callback, it should clone it first.
///
/// The value of the future is then made available to the main body
/// callback.
#[cfg(feature = "async-std")]
#[track_caller]
pub fn use_future<T, U, V, F, FC>(
&mut self,
data: &T,
future_cb: FC,
f: impl FnOnce(&mut Cx, Option<&U>) -> V,
) -> V
where
T: State + PartialEq + Clone + Sync + 'static,
FC: FnOnce(&T) -> F,
// Note: we can remove State bound
U: Send + State + 'static,
F: Future<Output = U> + Send + 'static,
{
let key = self.mut_cursor.key_from_loc(Location::caller());
let (id, f_id, changed) = self.mut_cursor.begin_core(key, |id, old_body| {
if let Some(Payload::Future(f_id, old_data)) = old_body {
if let Some(old_data) = old_data.as_any().downcast_ref::<T>() {
if old_data == data {
(None, (id, *f_id, false))
} else {
// Types match, data not equal
let f_id = Id::new();
(
Some(Payload::Future(f_id, Box::new(data.clone()))),
(id, f_id, true),
)
}
} else {
// Downcast failed; this shouldn't happen
let f_id = Id::new();
(
Some(Payload::Future(f_id, Box::new(data.clone()))),
(id, f_id, true),
)
}
} else {
// Probably inserting new state
let f_id = Id::new();
(
Some(Payload::Future(f_id, Box::new(data.clone()))),
(id, f_id, true),
)
}
});
if changed {
// Spawn the future.
let future = future_cb(data);
let sink = self.event_sink.clone();
let boxed_future = Box::pin(async move {
let result = future.await;
let boxed_result: Box<dyn State> = Box::new(result);
let payload = (id, f_id, boxed_result);
if let Err(e) = sink.submit_command(ASYNC, SingleUse::new(payload), Target::Auto) {
println!("error {:?} submitting", e);
}
});
async_std::task::spawn(boxed_future);
}
// Remove the "FutureResolved" action if it was sent.
let _ = self.app_data.dequeue_action(id);
let future_result = self
.resolved_futures
.get(&f_id)
.and_then(|result| result.as_any().downcast_ref());
let result = f(self, future_result);
self.mut_cursor.end();
result
}
/// A low-level method to skip nodes.
///
/// There must be `n` nodes in the tree to skip.
pub fn skip(&mut self, n: usize) {
for _ in 0..n {
self.mut_cursor.skip_one()
}
}
/// A low-level method to delete nodes.
///
/// There must be `n` nodes in the tree to delete.
pub fn delete(&mut self, n: usize) {
for _ in 0..n {
self.mut_cursor.delete_one()
}
}
/// A low-level method to insert a subtree.
pub fn begin_insert(&mut self) {
self.mut_cursor.begin_insert(Payload::Placeholder);
}
/// A low-level method to update a subtree.
///
/// There must be an existing placeholder node at this location in the tree.
pub fn begin_update(&mut self) {
self.mut_cursor.begin_update(Payload::Placeholder);
}
/// Report whether the current element has an action.
///
/// For the future, this should probably change to an `Option<usize>`,
/// reporting how many elements to skip before the next action.
pub fn has_action(&self) -> bool {
self.mut_cursor
.descendant_ids()
.any(|id| self.app_data.has_action(id))
}
}
|
use std::{collections::HashMap, fmt};
use serde::Serialize;
use crate::{
bson::oid::ObjectId,
client::options::ServerAddress,
sdam::{ServerInfo, TopologyType},
selection_criteria::{ReadPreference, SelectionCriteria},
};
/// A description of the most up-to-date information known about a topology. Further details can
/// be found in the [Server Discovery and Monitoring specification](https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst).
#[derive(Clone, derive_more::Display)]
#[display(fmt = "{}", description)]
pub struct TopologyDescription {
pub(crate) description: crate::sdam::TopologyDescription,
}
impl Serialize for TopologyDescription {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.description.serialize(serializer)
}
}
impl From<crate::sdam::TopologyDescription> for TopologyDescription {
fn from(description: crate::sdam::TopologyDescription) -> Self {
Self { description }
}
}
impl TopologyDescription {
/// Whether this topology has a readable server available that satisfies the specified selection
/// criteria.
pub fn has_readable_server(&self, selection_criteria: Option<SelectionCriteria>) -> bool {
match self.description.suitable_servers_in_latency_window(
&selection_criteria
.unwrap_or(SelectionCriteria::ReadPreference(ReadPreference::Primary)),
) {
Ok(servers) => !servers.is_empty(),
Err(_) => false,
}
}
/// Whether this topology has a writable server available.
pub fn has_writable_server(&self) -> bool {
match self.description.topology_type {
TopologyType::Unknown | TopologyType::ReplicaSetNoPrimary => false,
TopologyType::Single | TopologyType::Sharded => {
self.description.has_available_servers()
}
TopologyType::ReplicaSetWithPrimary | TopologyType::LoadBalanced => true,
}
}
/// Gets the type of the topology.
pub fn topology_type(&self) -> TopologyType {
self.description.topology_type
}
/// Gets the set name of the topology.
pub fn set_name(&self) -> Option<&String> {
self.description.set_name.as_ref()
}
/// Gets the max set version of the topology.
pub fn max_set_version(&self) -> Option<i32> {
self.description.max_set_version
}
/// Gets the max election ID of the topology.
pub fn max_election_id(&self) -> Option<ObjectId> {
self.description.max_election_id
}
/// Gets the compatibility error of the topology.
pub fn compatibility_error(&self) -> Option<&String> {
self.description.compatibility_error.as_ref()
}
/// Gets the servers in the topology.
pub fn servers(&self) -> HashMap<&ServerAddress, ServerInfo> {
self.description
.servers
.iter()
.map(|(address, description)| (address, ServerInfo::new_borrowed(description)))
.collect()
}
}
impl fmt::Debug for TopologyDescription {
fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> {
f.debug_struct("Topology Description")
.field("Type", &self.topology_type())
.field("Set Name", &self.set_name())
.field("Max Set Version", &self.max_set_version())
.field("Max Election ID", &self.max_election_id())
.field("Compatibility Error", &self.compatibility_error())
.field("Servers", &self.servers().values())
.finish()
}
}
|
#[doc = "Register `CRCSADDR` reader"]
pub type R = crate::R<CRCSADDR_SPEC>;
#[doc = "Register `CRCSADDR` writer"]
pub type W = crate::W<CRCSADDR_SPEC>;
#[doc = "Field `CRC_START_ADDR` reader - CRC start address on bank 1"]
pub type CRC_START_ADDR_R = crate::FieldReader<u32>;
#[doc = "Field `CRC_START_ADDR` writer - CRC start address on bank 1"]
pub type CRC_START_ADDR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - CRC start address on bank 1"]
#[inline(always)]
pub fn crc_start_addr(&self) -> CRC_START_ADDR_R {
CRC_START_ADDR_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - CRC start address on bank 1"]
#[inline(always)]
#[must_use]
pub fn crc_start_addr(&mut self) -> CRC_START_ADDR_W<CRCSADDR_SPEC, 0> {
CRC_START_ADDR_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 = "FLASH CRC start address register for bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crcsaddr::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 [`crcsaddr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CRCSADDR_SPEC;
impl crate::RegisterSpec for CRCSADDR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`crcsaddr::R`](R) reader structure"]
impl crate::Readable for CRCSADDR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`crcsaddr::W`](W) writer structure"]
impl crate::Writable for CRCSADDR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CRCSADDR to value 0"]
impl crate::Resettable for CRCSADDR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
fn main() {
let v: Vec<f64> = vec![0.0, 0.707, 1.0, 0.707];
let a: [f64; 4] = [0.0, -0.707, -1.0, -0.707];
let sv: &[f64] = &v;
let _sa: &[f64] = &a;
fn print(n: &[f64]) {
for elt in n {
print!("{} ", elt);
}
println!("");
}
print(&v); // works on vectors
print(&a); // works on arrays
print(&v[0..2]); // print the first two elements of v
print(&a[2..]); // print elements of a starting with a[2]
print(&sv[1..3]); // print v[1] and v[2]
}
|
#[doc = "Register `CCR%s` reader"]
pub type R = crate::R<CCR_SPEC>;
#[doc = "Register `CCR%s` writer"]
pub type W = crate::W<CCR_SPEC>;
#[doc = "Field `DMAREQ_ID` reader - Input DMA request line selected"]
pub type DMAREQ_ID_R = crate::FieldReader<DMAREQ_ID_A>;
#[doc = "Input DMA request line selected\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum DMAREQ_ID_A {
#[doc = "0: No signal selected as request input"]
None = 0,
#[doc = "1: Signal `dmamux2_req_gen0` selected as request input"]
Dmamux2ReqGen0 = 1,
#[doc = "2: Signal `dmamux2_req_gen1` selected as request input"]
Dmamux2ReqGen1 = 2,
#[doc = "3: Signal `dmamux2_req_gen2` selected as request input"]
Dmamux2ReqGen2 = 3,
#[doc = "4: Signal `dmamux2_req_gen3` selected as request input"]
Dmamux2ReqGen3 = 4,
#[doc = "5: Signal `dmamux2_req_gen4` selected as request input"]
Dmamux2ReqGen4 = 5,
#[doc = "6: Signal `dmamux2_req_gen5` selected as request input"]
Dmamux2ReqGen5 = 6,
#[doc = "7: Signal `dmamux2_req_gen6` selected as request input"]
Dmamux2ReqGen6 = 7,
#[doc = "8: Signal `dmamux2_req_gen7` selected as request input"]
Dmamux2ReqGen7 = 8,
#[doc = "9: Signal `lpuart1_rx_dma` selected as request input"]
Lpuart1RxDma = 9,
#[doc = "10: Signal `lpuart1_tx_dma` selected as request input"]
Lpuart1TxDma = 10,
#[doc = "11: Signal `spi6_rx_dma` selected as request input"]
Spi6RxDma = 11,
#[doc = "12: Signal `spi6_tx_dma` selected as request input"]
Spi6TxDma = 12,
#[doc = "13: Signal `i2c4_rx_dma` selected as request input"]
I2c4RxDma = 13,
#[doc = "14: Signal `i2c4_tx_dma` selected as request input"]
I2c4TxDma = 14,
#[doc = "15: Signal `sai4_a_dma` selected as request input"]
Sai4ADma = 15,
#[doc = "16: Signal `sai4_b_dma` selected as request input"]
Sai4BDma = 16,
#[doc = "17: Signal `adc3_dma` selected as request input"]
Adc3Dma = 17,
}
impl From<DMAREQ_ID_A> for u8 {
#[inline(always)]
fn from(variant: DMAREQ_ID_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for DMAREQ_ID_A {
type Ux = u8;
}
impl DMAREQ_ID_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<DMAREQ_ID_A> {
match self.bits {
0 => Some(DMAREQ_ID_A::None),
1 => Some(DMAREQ_ID_A::Dmamux2ReqGen0),
2 => Some(DMAREQ_ID_A::Dmamux2ReqGen1),
3 => Some(DMAREQ_ID_A::Dmamux2ReqGen2),
4 => Some(DMAREQ_ID_A::Dmamux2ReqGen3),
5 => Some(DMAREQ_ID_A::Dmamux2ReqGen4),
6 => Some(DMAREQ_ID_A::Dmamux2ReqGen5),
7 => Some(DMAREQ_ID_A::Dmamux2ReqGen6),
8 => Some(DMAREQ_ID_A::Dmamux2ReqGen7),
9 => Some(DMAREQ_ID_A::Lpuart1RxDma),
10 => Some(DMAREQ_ID_A::Lpuart1TxDma),
11 => Some(DMAREQ_ID_A::Spi6RxDma),
12 => Some(DMAREQ_ID_A::Spi6TxDma),
13 => Some(DMAREQ_ID_A::I2c4RxDma),
14 => Some(DMAREQ_ID_A::I2c4TxDma),
15 => Some(DMAREQ_ID_A::Sai4ADma),
16 => Some(DMAREQ_ID_A::Sai4BDma),
17 => Some(DMAREQ_ID_A::Adc3Dma),
_ => None,
}
}
#[doc = "No signal selected as request input"]
#[inline(always)]
pub fn is_none(&self) -> bool {
*self == DMAREQ_ID_A::None
}
#[doc = "Signal `dmamux2_req_gen0` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen0(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen0
}
#[doc = "Signal `dmamux2_req_gen1` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen1(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen1
}
#[doc = "Signal `dmamux2_req_gen2` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen2(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen2
}
#[doc = "Signal `dmamux2_req_gen3` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen3(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen3
}
#[doc = "Signal `dmamux2_req_gen4` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen4(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen4
}
#[doc = "Signal `dmamux2_req_gen5` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen5(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen5
}
#[doc = "Signal `dmamux2_req_gen6` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen6(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen6
}
#[doc = "Signal `dmamux2_req_gen7` selected as request input"]
#[inline(always)]
pub fn is_dmamux2_req_gen7(&self) -> bool {
*self == DMAREQ_ID_A::Dmamux2ReqGen7
}
#[doc = "Signal `lpuart1_rx_dma` selected as request input"]
#[inline(always)]
pub fn is_lpuart1_rx_dma(&self) -> bool {
*self == DMAREQ_ID_A::Lpuart1RxDma
}
#[doc = "Signal `lpuart1_tx_dma` selected as request input"]
#[inline(always)]
pub fn is_lpuart1_tx_dma(&self) -> bool {
*self == DMAREQ_ID_A::Lpuart1TxDma
}
#[doc = "Signal `spi6_rx_dma` selected as request input"]
#[inline(always)]
pub fn is_spi6_rx_dma(&self) -> bool {
*self == DMAREQ_ID_A::Spi6RxDma
}
#[doc = "Signal `spi6_tx_dma` selected as request input"]
#[inline(always)]
pub fn is_spi6_tx_dma(&self) -> bool {
*self == DMAREQ_ID_A::Spi6TxDma
}
#[doc = "Signal `i2c4_rx_dma` selected as request input"]
#[inline(always)]
pub fn is_i2c4_rx_dma(&self) -> bool {
*self == DMAREQ_ID_A::I2c4RxDma
}
#[doc = "Signal `i2c4_tx_dma` selected as request input"]
#[inline(always)]
pub fn is_i2c4_tx_dma(&self) -> bool {
*self == DMAREQ_ID_A::I2c4TxDma
}
#[doc = "Signal `sai4_a_dma` selected as request input"]
#[inline(always)]
pub fn is_sai4_a_dma(&self) -> bool {
*self == DMAREQ_ID_A::Sai4ADma
}
#[doc = "Signal `sai4_b_dma` selected as request input"]
#[inline(always)]
pub fn is_sai4_b_dma(&self) -> bool {
*self == DMAREQ_ID_A::Sai4BDma
}
#[doc = "Signal `adc3_dma` selected as request input"]
#[inline(always)]
pub fn is_adc3_dma(&self) -> bool {
*self == DMAREQ_ID_A::Adc3Dma
}
}
#[doc = "Field `DMAREQ_ID` writer - Input DMA request line selected"]
pub type DMAREQ_ID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O, DMAREQ_ID_A>;
impl<'a, REG, const O: u8> DMAREQ_ID_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "No signal selected as request input"]
#[inline(always)]
pub fn none(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::None)
}
#[doc = "Signal `dmamux2_req_gen0` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen0(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen0)
}
#[doc = "Signal `dmamux2_req_gen1` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen1(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen1)
}
#[doc = "Signal `dmamux2_req_gen2` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen2(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen2)
}
#[doc = "Signal `dmamux2_req_gen3` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen3(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen3)
}
#[doc = "Signal `dmamux2_req_gen4` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen4(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen4)
}
#[doc = "Signal `dmamux2_req_gen5` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen5(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen5)
}
#[doc = "Signal `dmamux2_req_gen6` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen6(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen6)
}
#[doc = "Signal `dmamux2_req_gen7` selected as request input"]
#[inline(always)]
pub fn dmamux2_req_gen7(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Dmamux2ReqGen7)
}
#[doc = "Signal `lpuart1_rx_dma` selected as request input"]
#[inline(always)]
pub fn lpuart1_rx_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Lpuart1RxDma)
}
#[doc = "Signal `lpuart1_tx_dma` selected as request input"]
#[inline(always)]
pub fn lpuart1_tx_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Lpuart1TxDma)
}
#[doc = "Signal `spi6_rx_dma` selected as request input"]
#[inline(always)]
pub fn spi6_rx_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Spi6RxDma)
}
#[doc = "Signal `spi6_tx_dma` selected as request input"]
#[inline(always)]
pub fn spi6_tx_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Spi6TxDma)
}
#[doc = "Signal `i2c4_rx_dma` selected as request input"]
#[inline(always)]
pub fn i2c4_rx_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::I2c4RxDma)
}
#[doc = "Signal `i2c4_tx_dma` selected as request input"]
#[inline(always)]
pub fn i2c4_tx_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::I2c4TxDma)
}
#[doc = "Signal `sai4_a_dma` selected as request input"]
#[inline(always)]
pub fn sai4_a_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Sai4ADma)
}
#[doc = "Signal `sai4_b_dma` selected as request input"]
#[inline(always)]
pub fn sai4_b_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Sai4BDma)
}
#[doc = "Signal `adc3_dma` selected as request input"]
#[inline(always)]
pub fn adc3_dma(self) -> &'a mut crate::W<REG> {
self.variant(DMAREQ_ID_A::Adc3Dma)
}
}
#[doc = "Field `SOIE` reader - Interrupt enable at synchronization event overrun"]
pub type SOIE_R = crate::BitReader<SOIE_A>;
#[doc = "Interrupt enable at synchronization event overrun\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SOIE_A {
#[doc = "0: Synchronization overrun interrupt disabled"]
Disabled = 0,
#[doc = "1: Synchronization overrun interrupt enabled"]
Enabled = 1,
}
impl From<SOIE_A> for bool {
#[inline(always)]
fn from(variant: SOIE_A) -> Self {
variant as u8 != 0
}
}
impl SOIE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SOIE_A {
match self.bits {
false => SOIE_A::Disabled,
true => SOIE_A::Enabled,
}
}
#[doc = "Synchronization overrun interrupt disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SOIE_A::Disabled
}
#[doc = "Synchronization overrun interrupt enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SOIE_A::Enabled
}
}
#[doc = "Field `SOIE` writer - Interrupt enable at synchronization event overrun"]
pub type SOIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SOIE_A>;
impl<'a, REG, const O: u8> SOIE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Synchronization overrun interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SOIE_A::Disabled)
}
#[doc = "Synchronization overrun interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SOIE_A::Enabled)
}
}
#[doc = "Field `EGE` reader - Event generation enable/disable"]
pub type EGE_R = crate::BitReader<EGE_A>;
#[doc = "Event generation enable/disable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EGE_A {
#[doc = "0: Event generation disabled"]
Disabled = 0,
#[doc = "1: Event generation enabled"]
Enabled = 1,
}
impl From<EGE_A> for bool {
#[inline(always)]
fn from(variant: EGE_A) -> Self {
variant as u8 != 0
}
}
impl EGE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EGE_A {
match self.bits {
false => EGE_A::Disabled,
true => EGE_A::Enabled,
}
}
#[doc = "Event generation disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EGE_A::Disabled
}
#[doc = "Event generation enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EGE_A::Enabled
}
}
#[doc = "Field `EGE` writer - Event generation enable/disable"]
pub type EGE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EGE_A>;
impl<'a, REG, const O: u8> EGE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Event generation disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(EGE_A::Disabled)
}
#[doc = "Event generation enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(EGE_A::Enabled)
}
}
#[doc = "Field `SE` reader - Synchronous operating mode enable/disable"]
pub type SE_R = crate::BitReader<SE_A>;
#[doc = "Synchronous operating mode enable/disable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SE_A {
#[doc = "0: Synchronization disabled"]
Disabled = 0,
#[doc = "1: Synchronization enabled"]
Enabled = 1,
}
impl From<SE_A> for bool {
#[inline(always)]
fn from(variant: SE_A) -> Self {
variant as u8 != 0
}
}
impl SE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SE_A {
match self.bits {
false => SE_A::Disabled,
true => SE_A::Enabled,
}
}
#[doc = "Synchronization disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SE_A::Disabled
}
#[doc = "Synchronization enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SE_A::Enabled
}
}
#[doc = "Field `SE` writer - Synchronous operating mode enable/disable"]
pub type SE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SE_A>;
impl<'a, REG, const O: u8> SE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Synchronization disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SE_A::Disabled)
}
#[doc = "Synchronization enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SE_A::Enabled)
}
}
#[doc = "Field `SPOL` reader - Synchronization event type selector Defines the synchronization event on the selected synchronization input:"]
pub type SPOL_R = crate::FieldReader<SPOL_A>;
#[doc = "Synchronization event type selector Defines the synchronization event on the selected synchronization input:\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SPOL_A {
#[doc = "0: No event, i.e. no synchronization nor detection"]
NoEdge = 0,
#[doc = "1: Rising edge"]
RisingEdge = 1,
#[doc = "2: Falling edge"]
FallingEdge = 2,
#[doc = "3: Rising and falling edges"]
BothEdges = 3,
}
impl From<SPOL_A> for u8 {
#[inline(always)]
fn from(variant: SPOL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for SPOL_A {
type Ux = u8;
}
impl SPOL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SPOL_A {
match self.bits {
0 => SPOL_A::NoEdge,
1 => SPOL_A::RisingEdge,
2 => SPOL_A::FallingEdge,
3 => SPOL_A::BothEdges,
_ => unreachable!(),
}
}
#[doc = "No event, i.e. no synchronization nor detection"]
#[inline(always)]
pub fn is_no_edge(&self) -> bool {
*self == SPOL_A::NoEdge
}
#[doc = "Rising edge"]
#[inline(always)]
pub fn is_rising_edge(&self) -> bool {
*self == SPOL_A::RisingEdge
}
#[doc = "Falling edge"]
#[inline(always)]
pub fn is_falling_edge(&self) -> bool {
*self == SPOL_A::FallingEdge
}
#[doc = "Rising and falling edges"]
#[inline(always)]
pub fn is_both_edges(&self) -> bool {
*self == SPOL_A::BothEdges
}
}
#[doc = "Field `SPOL` writer - Synchronization event type selector Defines the synchronization event on the selected synchronization input:"]
pub type SPOL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, SPOL_A>;
impl<'a, REG, const O: u8> SPOL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "No event, i.e. no synchronization nor detection"]
#[inline(always)]
pub fn no_edge(self) -> &'a mut crate::W<REG> {
self.variant(SPOL_A::NoEdge)
}
#[doc = "Rising edge"]
#[inline(always)]
pub fn rising_edge(self) -> &'a mut crate::W<REG> {
self.variant(SPOL_A::RisingEdge)
}
#[doc = "Falling edge"]
#[inline(always)]
pub fn falling_edge(self) -> &'a mut crate::W<REG> {
self.variant(SPOL_A::FallingEdge)
}
#[doc = "Rising and falling edges"]
#[inline(always)]
pub fn both_edges(self) -> &'a mut crate::W<REG> {
self.variant(SPOL_A::BothEdges)
}
}
#[doc = "Field `NBREQ` reader - Number of DMA requests to forward Defines the number of DMA requests forwarded before output event is generated. In synchronous mode, it also defines the number of DMA requests to forward after a synchronization event, then stop forwarding. The actual number of DMA requests forwarded is NBREQ+1. Note: This field can only be written when both SE and EGE bits are reset."]
pub type NBREQ_R = crate::FieldReader;
#[doc = "Field `NBREQ` writer - Number of DMA requests to forward Defines the number of DMA requests forwarded before output event is generated. In synchronous mode, it also defines the number of DMA requests to forward after a synchronization event, then stop forwarding. The actual number of DMA requests forwarded is NBREQ+1. Note: This field can only be written when both SE and EGE bits are reset."]
pub type NBREQ_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 5, O>;
#[doc = "Field `SYNC_ID` reader - Synchronization input selected"]
pub type SYNC_ID_R = crate::FieldReader<SYNC_ID_A>;
#[doc = "Synchronization input selected\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SYNC_ID_A {
#[doc = "0: Signal `dmamux2_evt0` selected as synchronization input"]
Dmamux2Evt0 = 0,
#[doc = "1: Signal `dmamux2_evt1` selected as synchronization input"]
Dmamux2Evt1 = 1,
#[doc = "2: Signal `dmamux2_evt2` selected as synchronization input"]
Dmamux2Evt2 = 2,
#[doc = "3: Signal `dmamux2_evt3` selected as synchronization input"]
Dmamux2Evt3 = 3,
#[doc = "4: Signal `dmamux2_evt4` selected as synchronization input"]
Dmamux2Evt4 = 4,
#[doc = "5: Signal `dmamux2_evt5` selected as synchronization input"]
Dmamux2Evt5 = 5,
#[doc = "6: Signal `lpuart1_rx_wkup` selected as synchronization input"]
Lpuart1RxWkup = 6,
#[doc = "7: Signal `lpuart1_tx_wkup` selected as synchronization input"]
Lpuart1TxWkup = 7,
#[doc = "8: Signal `lptim2_out` selected as synchronization input"]
Lptim2Out = 8,
#[doc = "9: Signal `lptim3_out` selected as synchronization input"]
Lptim3Out = 9,
#[doc = "10: Signal `i2c4_wkup` selected as synchronization input"]
I2c4Wkup = 10,
#[doc = "11: Signal `spi6_wkup` selected as synchronization input"]
Spi6Wkup = 11,
#[doc = "12: Signal `comp1_out` selected as synchronization input"]
Comp1Out = 12,
#[doc = "13: Signal `rtc_wkup` selected as synchronization input"]
RtcWkup = 13,
#[doc = "14: Signal `syscfg_exti0_mux` selected as synchronization input"]
SyscfgExti0Mux = 14,
#[doc = "15: Signal `syscfg_exti2_mux` selected as synchronization input"]
SyscfgExti2Mux = 15,
}
impl From<SYNC_ID_A> for u8 {
#[inline(always)]
fn from(variant: SYNC_ID_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for SYNC_ID_A {
type Ux = u8;
}
impl SYNC_ID_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SYNC_ID_A> {
match self.bits {
0 => Some(SYNC_ID_A::Dmamux2Evt0),
1 => Some(SYNC_ID_A::Dmamux2Evt1),
2 => Some(SYNC_ID_A::Dmamux2Evt2),
3 => Some(SYNC_ID_A::Dmamux2Evt3),
4 => Some(SYNC_ID_A::Dmamux2Evt4),
5 => Some(SYNC_ID_A::Dmamux2Evt5),
6 => Some(SYNC_ID_A::Lpuart1RxWkup),
7 => Some(SYNC_ID_A::Lpuart1TxWkup),
8 => Some(SYNC_ID_A::Lptim2Out),
9 => Some(SYNC_ID_A::Lptim3Out),
10 => Some(SYNC_ID_A::I2c4Wkup),
11 => Some(SYNC_ID_A::Spi6Wkup),
12 => Some(SYNC_ID_A::Comp1Out),
13 => Some(SYNC_ID_A::RtcWkup),
14 => Some(SYNC_ID_A::SyscfgExti0Mux),
15 => Some(SYNC_ID_A::SyscfgExti2Mux),
_ => None,
}
}
#[doc = "Signal `dmamux2_evt0` selected as synchronization input"]
#[inline(always)]
pub fn is_dmamux2_evt0(&self) -> bool {
*self == SYNC_ID_A::Dmamux2Evt0
}
#[doc = "Signal `dmamux2_evt1` selected as synchronization input"]
#[inline(always)]
pub fn is_dmamux2_evt1(&self) -> bool {
*self == SYNC_ID_A::Dmamux2Evt1
}
#[doc = "Signal `dmamux2_evt2` selected as synchronization input"]
#[inline(always)]
pub fn is_dmamux2_evt2(&self) -> bool {
*self == SYNC_ID_A::Dmamux2Evt2
}
#[doc = "Signal `dmamux2_evt3` selected as synchronization input"]
#[inline(always)]
pub fn is_dmamux2_evt3(&self) -> bool {
*self == SYNC_ID_A::Dmamux2Evt3
}
#[doc = "Signal `dmamux2_evt4` selected as synchronization input"]
#[inline(always)]
pub fn is_dmamux2_evt4(&self) -> bool {
*self == SYNC_ID_A::Dmamux2Evt4
}
#[doc = "Signal `dmamux2_evt5` selected as synchronization input"]
#[inline(always)]
pub fn is_dmamux2_evt5(&self) -> bool {
*self == SYNC_ID_A::Dmamux2Evt5
}
#[doc = "Signal `lpuart1_rx_wkup` selected as synchronization input"]
#[inline(always)]
pub fn is_lpuart1_rx_wkup(&self) -> bool {
*self == SYNC_ID_A::Lpuart1RxWkup
}
#[doc = "Signal `lpuart1_tx_wkup` selected as synchronization input"]
#[inline(always)]
pub fn is_lpuart1_tx_wkup(&self) -> bool {
*self == SYNC_ID_A::Lpuart1TxWkup
}
#[doc = "Signal `lptim2_out` selected as synchronization input"]
#[inline(always)]
pub fn is_lptim2_out(&self) -> bool {
*self == SYNC_ID_A::Lptim2Out
}
#[doc = "Signal `lptim3_out` selected as synchronization input"]
#[inline(always)]
pub fn is_lptim3_out(&self) -> bool {
*self == SYNC_ID_A::Lptim3Out
}
#[doc = "Signal `i2c4_wkup` selected as synchronization input"]
#[inline(always)]
pub fn is_i2c4_wkup(&self) -> bool {
*self == SYNC_ID_A::I2c4Wkup
}
#[doc = "Signal `spi6_wkup` selected as synchronization input"]
#[inline(always)]
pub fn is_spi6_wkup(&self) -> bool {
*self == SYNC_ID_A::Spi6Wkup
}
#[doc = "Signal `comp1_out` selected as synchronization input"]
#[inline(always)]
pub fn is_comp1_out(&self) -> bool {
*self == SYNC_ID_A::Comp1Out
}
#[doc = "Signal `rtc_wkup` selected as synchronization input"]
#[inline(always)]
pub fn is_rtc_wkup(&self) -> bool {
*self == SYNC_ID_A::RtcWkup
}
#[doc = "Signal `syscfg_exti0_mux` selected as synchronization input"]
#[inline(always)]
pub fn is_syscfg_exti0_mux(&self) -> bool {
*self == SYNC_ID_A::SyscfgExti0Mux
}
#[doc = "Signal `syscfg_exti2_mux` selected as synchronization input"]
#[inline(always)]
pub fn is_syscfg_exti2_mux(&self) -> bool {
*self == SYNC_ID_A::SyscfgExti2Mux
}
}
#[doc = "Field `SYNC_ID` writer - Synchronization input selected"]
pub type SYNC_ID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O, SYNC_ID_A>;
impl<'a, REG, const O: u8> SYNC_ID_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Signal `dmamux2_evt0` selected as synchronization input"]
#[inline(always)]
pub fn dmamux2_evt0(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Dmamux2Evt0)
}
#[doc = "Signal `dmamux2_evt1` selected as synchronization input"]
#[inline(always)]
pub fn dmamux2_evt1(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Dmamux2Evt1)
}
#[doc = "Signal `dmamux2_evt2` selected as synchronization input"]
#[inline(always)]
pub fn dmamux2_evt2(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Dmamux2Evt2)
}
#[doc = "Signal `dmamux2_evt3` selected as synchronization input"]
#[inline(always)]
pub fn dmamux2_evt3(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Dmamux2Evt3)
}
#[doc = "Signal `dmamux2_evt4` selected as synchronization input"]
#[inline(always)]
pub fn dmamux2_evt4(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Dmamux2Evt4)
}
#[doc = "Signal `dmamux2_evt5` selected as synchronization input"]
#[inline(always)]
pub fn dmamux2_evt5(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Dmamux2Evt5)
}
#[doc = "Signal `lpuart1_rx_wkup` selected as synchronization input"]
#[inline(always)]
pub fn lpuart1_rx_wkup(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Lpuart1RxWkup)
}
#[doc = "Signal `lpuart1_tx_wkup` selected as synchronization input"]
#[inline(always)]
pub fn lpuart1_tx_wkup(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Lpuart1TxWkup)
}
#[doc = "Signal `lptim2_out` selected as synchronization input"]
#[inline(always)]
pub fn lptim2_out(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Lptim2Out)
}
#[doc = "Signal `lptim3_out` selected as synchronization input"]
#[inline(always)]
pub fn lptim3_out(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Lptim3Out)
}
#[doc = "Signal `i2c4_wkup` selected as synchronization input"]
#[inline(always)]
pub fn i2c4_wkup(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::I2c4Wkup)
}
#[doc = "Signal `spi6_wkup` selected as synchronization input"]
#[inline(always)]
pub fn spi6_wkup(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Spi6Wkup)
}
#[doc = "Signal `comp1_out` selected as synchronization input"]
#[inline(always)]
pub fn comp1_out(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::Comp1Out)
}
#[doc = "Signal `rtc_wkup` selected as synchronization input"]
#[inline(always)]
pub fn rtc_wkup(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::RtcWkup)
}
#[doc = "Signal `syscfg_exti0_mux` selected as synchronization input"]
#[inline(always)]
pub fn syscfg_exti0_mux(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::SyscfgExti0Mux)
}
#[doc = "Signal `syscfg_exti2_mux` selected as synchronization input"]
#[inline(always)]
pub fn syscfg_exti2_mux(self) -> &'a mut crate::W<REG> {
self.variant(SYNC_ID_A::SyscfgExti2Mux)
}
}
impl R {
#[doc = "Bits 0:7 - Input DMA request line selected"]
#[inline(always)]
pub fn dmareq_id(&self) -> DMAREQ_ID_R {
DMAREQ_ID_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bit 8 - Interrupt enable at synchronization event overrun"]
#[inline(always)]
pub fn soie(&self) -> SOIE_R {
SOIE_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Event generation enable/disable"]
#[inline(always)]
pub fn ege(&self) -> EGE_R {
EGE_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 16 - Synchronous operating mode enable/disable"]
#[inline(always)]
pub fn se(&self) -> SE_R {
SE_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bits 17:18 - Synchronization event type selector Defines the synchronization event on the selected synchronization input:"]
#[inline(always)]
pub fn spol(&self) -> SPOL_R {
SPOL_R::new(((self.bits >> 17) & 3) as u8)
}
#[doc = "Bits 19:23 - Number of DMA requests to forward Defines the number of DMA requests forwarded before output event is generated. In synchronous mode, it also defines the number of DMA requests to forward after a synchronization event, then stop forwarding. The actual number of DMA requests forwarded is NBREQ+1. Note: This field can only be written when both SE and EGE bits are reset."]
#[inline(always)]
pub fn nbreq(&self) -> NBREQ_R {
NBREQ_R::new(((self.bits >> 19) & 0x1f) as u8)
}
#[doc = "Bits 24:28 - Synchronization input selected"]
#[inline(always)]
pub fn sync_id(&self) -> SYNC_ID_R {
SYNC_ID_R::new(((self.bits >> 24) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Input DMA request line selected"]
#[inline(always)]
#[must_use]
pub fn dmareq_id(&mut self) -> DMAREQ_ID_W<CCR_SPEC, 0> {
DMAREQ_ID_W::new(self)
}
#[doc = "Bit 8 - Interrupt enable at synchronization event overrun"]
#[inline(always)]
#[must_use]
pub fn soie(&mut self) -> SOIE_W<CCR_SPEC, 8> {
SOIE_W::new(self)
}
#[doc = "Bit 9 - Event generation enable/disable"]
#[inline(always)]
#[must_use]
pub fn ege(&mut self) -> EGE_W<CCR_SPEC, 9> {
EGE_W::new(self)
}
#[doc = "Bit 16 - Synchronous operating mode enable/disable"]
#[inline(always)]
#[must_use]
pub fn se(&mut self) -> SE_W<CCR_SPEC, 16> {
SE_W::new(self)
}
#[doc = "Bits 17:18 - Synchronization event type selector Defines the synchronization event on the selected synchronization input:"]
#[inline(always)]
#[must_use]
pub fn spol(&mut self) -> SPOL_W<CCR_SPEC, 17> {
SPOL_W::new(self)
}
#[doc = "Bits 19:23 - Number of DMA requests to forward Defines the number of DMA requests forwarded before output event is generated. In synchronous mode, it also defines the number of DMA requests to forward after a synchronization event, then stop forwarding. The actual number of DMA requests forwarded is NBREQ+1. Note: This field can only be written when both SE and EGE bits are reset."]
#[inline(always)]
#[must_use]
pub fn nbreq(&mut self) -> NBREQ_W<CCR_SPEC, 19> {
NBREQ_W::new(self)
}
#[doc = "Bits 24:28 - Synchronization input selected"]
#[inline(always)]
#[must_use]
pub fn sync_id(&mut self) -> SYNC_ID_W<CCR_SPEC, 24> {
SYNC_ID_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 = "DMAMux - DMA request line multiplexer channel x control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr::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 [`ccr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CCR_SPEC;
impl crate::RegisterSpec for CCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ccr::R`](R) reader structure"]
impl crate::Readable for CCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ccr::W`](W) writer structure"]
impl crate::Writable for CCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CCR%s to value 0"]
impl crate::Resettable for CCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
mod utils;
extern crate rand;
extern crate js_sys;
use std;
use rand::Rng;
use js_sys::{Float32Array};
use wasm_bindgen::prelude::*;
// #![feature(stdsimd)]
// #![cfg(target_feature = "simd128")]
// #![cfg(target_arch = "wasm32")]
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
extern "C" {
// Use `js_namespace` here to bind `console.log(..)` instead of just
// `log(..)`
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
// The `console.log` is quite polymorphic, so we can bind it with multiple
// signatures. Note that we need to use `js_name` to ensure we always call
// `log` in JS.
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn log_u32(a: u32);
// Multiple arguments too!
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn log_many(a: &str, b: &str);
}
#[wasm_bindgen]
pub extern fn particlesToNewPoints(particles: Float32Array) -> Vec<f32> {
let mut i = 0;
let mut points = Vec::<f32>::new();
while i < particles.length() {
points.push(particles.get_index(i));
points.push(particles.get_index(i + 1));
i = i + 4;
}
return points;
}
#[wasm_bindgen]
pub extern fn initParticles(particles: Float32Array, x:f32, y:f32) {
let mut i = 0;
let mut _rnd = rand::thread_rng();
while i < particles.length() {
particles.set_index(i, x);
particles.set_index(i + 1, y);
let d: f32 = _rnd.gen::<f32>().sqrt() * 10.0;
let ang: f32 = _rnd.gen::<f32>() * 3.14 * 20.0;
particles.set_index(i + 2, ang.cos() * d / 1000.0);
particles.set_index(i + 3, ang.sin() * d / 1000.0);
i = i + 4;
}
}
#[wasm_bindgen]
pub extern fn initParticlesWithPoints(particles: Float32Array, points: Float32Array, sub_particles: i32) {
let mut i = 0;
let mut y = 0;
let mut ptc = 0;
let mut _rnd = rand::thread_rng();
while i < particles.length() {
particles.set_index(i, points.get_index(y));
particles.set_index(i + 1, points.get_index(y + 1));
let d: f32 = _rnd.gen::<f32>().sqrt() * 10.0;
let ang: f32 = _rnd.gen::<f32>() * 3.14 * 20.0;
particles.set_index(i + 2, ang.cos() * d / 1000.0);
particles.set_index(i + 3, ang.sin() * d / 1000.0);
if ptc == sub_particles {
ptc = 0;
y = y + 2;
} else {
ptc += 1;
}
i = i + 4;
}
}
#[wasm_bindgen]
pub extern fn moveParticles(particles: &Float32Array) {
let mut i = 0;
let mut rng = rand::thread_rng();
while i < particles.length() {
particles.set_index(i, particles.get_index(i) + particles.get_index(i + 2));
particles.set_index(i + 1, particles.get_index(i + 1) + particles.get_index(i + 3));
particles.set_index(i + 3, particles.get_index(i + 3) - 0.0002);
i = i + 4;
}
}
#[wasm_bindgen]
pub extern fn getColor() -> Vec<u32> {
let mut _rnd = rand::thread_rng();
let mut result = Vec::<u32>::new();
for _ in 0..3 {
result.push((_rnd.gen::<f32>() * 255.0).round() as u32);
}
return result.clone();
}
#[wasm_bindgen]
pub extern fn getColorArray(count: u32) -> Vec<f32> {
let mut i = 0;
let mut _rnd = rand::thread_rng();
let mut result = Vec::<f32>::new();
loop {
result.push(_rnd.gen::<f32>());
result.push(_rnd.gen::<f32>());
result.push(_rnd.gen::<f32>());
i += 3;
if i == count { break; }
}
return result;
} |
use quote::quote_spanned;
use super::{
DelayType, FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints,
OperatorWriteOutput, WriteContextArgs, RANGE_0, RANGE_1,
};
/// Takes a stream as input and produces a sorted version of the stream as output.
///
/// ```hydroflow
/// source_iter(vec![2, 3, 1])
/// -> sort()
/// -> assert_eq([1, 2, 3]);
/// ```
///
/// `sort` is blocking. Only the values collected within a single tick will be sorted and
/// emitted.
pub const SORT: OperatorConstraints = OperatorConstraints {
name: "sort",
categories: &[OperatorCategory::Persistence],
hard_range_inn: RANGE_1,
soft_range_inn: RANGE_1,
hard_range_out: RANGE_1,
soft_range_out: RANGE_1,
num_args: 0,
persistence_args: RANGE_0,
type_args: RANGE_0,
is_external_input: false,
ports_inn: None,
ports_out: None,
properties: FlowProperties {
deterministic: FlowPropertyVal::Preserve,
monotonic: FlowPropertyVal::No,
inconsistency_tainted: false,
},
input_delaytype_fn: |_| Some(DelayType::Stratum),
write_fn: |&WriteContextArgs {
op_span,
ident,
inputs,
is_pull,
..
},
_| {
assert!(is_pull);
let input = &inputs[0];
let write_iterator = quote_spanned! {op_span=>
// TODO(mingwei): unneccesary extra handoff into_iter() then collect().
// Fix requires handoff specialization.
let #ident = {
let mut v = #input.collect::<::std::vec::Vec<_>>();
v.sort_unstable();
v.into_iter()
};
};
Ok(OperatorWriteOutput {
write_iterator,
..Default::default()
})
},
};
|
//! The module for the award struct.
use crate::{
auth::Auth,
client::{route::Route, Client},
error::Error,
model::{misc::AwardSubtype, misc::AwardType, misc::Params},
};
use serde::{Deserialize, Serialize};
/// The struct representing an award.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Award {
/// The ID of the award.
pub id: String,
/// If not global, which subreddit it belongs to.
pub subreddit_id: Option<String>,
/// How expensive the award is.
pub coin_price: u64,
/// The URL for the icon.
pub icon_url: String,
/// How many days of premium it gives.
pub days_of_premium: u64,
/// The height of the icon.
pub icon_height: u64,
/// The width of the icon.
pub icon_width: u64,
/// Whether the award is currently enabled.
pub is_enabled: bool,
/// The description of the award.
pub description: String,
/// How many times was this reward used on a Thing.
pub count: u64,
/// The name of the award.
pub name: String,
/// The subtype of the award.
pub award_sub_type: AwardSubtype,
/// The type of the award.
pub award_type: AwardType,
}
impl Award {
/// Brings the award to the attention of the admins.
pub async fn report<T: Auth + Send + Sync>(
&self,
client: &Client<T>,
reason: &str,
) -> Result<(), Error> {
client
.post(
Route::ReportAward,
&Params::new()
.add("award_id", self.id.as_ref())
.add("reason", reason),
)
.await
.and(Ok(()))
}
}
|
use std::cmp::min;
use std::fmt;
use std::ops;
type NumType = u32;
type InputNumType = i32;
#[derive(Clone, Copy, PartialEq, Eq)]
struct Fraction {
sign: bool,
numerator: NumType,
denominator: NumType,
}
fn xor(a: bool, b: bool) -> bool {
!(a && b) && (a || b)
}
fn sgn(a: InputNumType) -> InputNumType {
if a < 0 {
-1
} else {
1
}
}
impl Fraction {
fn _reduce(&mut self) {
if self.numerator == 0 {
self.denominator = 1;
return;
}
let mut found_one = false;
{
let top: &mut NumType = &mut self.numerator;
let bottom: &mut NumType = &mut self.denominator;
let smallest = min(*top, *bottom);
for i in 2..=smallest {
if *top % i == 0 && *bottom % i == 0 {
*top /= i;
*bottom /= i;
found_one = true;
break;
}
}
}
if found_one {
self._reduce();
}
}
fn new(top: i32, bottom: i32) -> Result<Self, String> {
if bottom == 0 {
return Err(String::from("You can't divide by zero!"));
}
let sign = !xor(top < 0, bottom < 0);
let top = (top * sgn(top)) as NumType;
let bottom = (bottom * sgn(bottom)) as NumType;
let mut out = Fraction {
sign,
numerator: top,
denominator: bottom,
};
out._reduce();
Ok(out)
}
}
impl fmt::Debug for Fraction {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let top = self.numerator;
let bottom = self.denominator;
let sign = if self.sign { "" } else { "-" };
formatter.write_fmt(format_args!("{}{} / {}", sign, top, bottom))
}
}
impl fmt::Display for Fraction {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_fmt(format_args!("{:?}", self))
}
}
impl ops::Add<Fraction> for Fraction {
type Output = Fraction;
fn add(mut self, mut rhs: Fraction) -> Fraction {
if self.denominator != rhs.denominator {
let new_denominator = self.denominator * rhs.denominator;
self.numerator *= rhs.denominator;
rhs.denominator *= self.denominator;
rhs.numerator *= self.denominator;
self.denominator = new_denominator;
}
let (sign, new_numerator) = match (self.sign, rhs.sign) {
(a, b) if a == b => (self.sign, self.numerator + rhs.numerator),
(true, false) if self.numerator >= rhs.numerator => {
(true, self.numerator - rhs.numerator)
}
(true, false) if self.numerator < rhs.numerator => {
(false, rhs.numerator - self.numerator)
}
(false, true) if self.numerator >= rhs.numerator => {
(false, self.numerator - rhs.numerator)
}
(false, true) if self.numerator < rhs.numerator => {
(true, rhs.numerator - self.numerator)
}
_ => panic!("We shouldn't have gotten here"),
};
let mut out = Fraction {
sign,
numerator: new_numerator,
denominator: self.denominator,
};
out._reduce();
out
}
}
impl ops::Add<u32> for Fraction {
type Output = Fraction;
fn add(self, rhs: u32) -> Fraction {
let r = Fraction::new(rhs as i32, 1).unwrap();
self + r
}
}
impl ops::Sub<Fraction> for Fraction {
type Output = Fraction;
fn sub(self, mut rhs: Fraction) -> Fraction {
rhs.sign = !rhs.sign;
self + rhs
}
}
impl ops::AddAssign<Fraction> for Fraction {
fn add_assign(&mut self, other: Fraction) {
let new = *self + other;
*self = new;
}
}
impl ops::Sub<u32> for Fraction {
type Output = Fraction;
fn sub(self, rhs: u32) -> Fraction {
let new_right = Fraction {
sign: false,
numerator: rhs,
denominator: 1,
};
self + new_right
}
}
fn main() {}
#[test]
fn subtract_test() {
let a = Fraction::new(5, 3).unwrap();
let b = Fraction::new(8, 3).unwrap();
let c = Fraction::new(7, 6).unwrap();
let d = Fraction::new(-7, 12).unwrap();
assert_eq!(a - a, Fraction::new(0, 1).unwrap());
assert_eq!(a - b, Fraction::new(-3, 3).unwrap());
assert_eq!(b - a, Fraction::new(3, 3).unwrap());
assert_eq!(c - d, Fraction::new(21, 12).unwrap());
}
#[test]
fn add_test() {
let a = Fraction::new(5, 3).unwrap();
let b = Fraction::new(8, 3).unwrap();
let c = Fraction::new(7, 6).unwrap();
let d = Fraction::new(-7, 12).unwrap();
assert_eq!(
a + b,
Fraction {
sign: true,
numerator: 13,
denominator: 3
}
);
assert_eq!(
b + c,
Fraction {
sign: true,
numerator: 23,
denominator: 6
}
);
assert_eq!(
c + d,
Fraction {
sign: true,
numerator: 7,
denominator: 12
}
);
assert_eq!(
d + c,
Fraction {
sign: true,
numerator: 7,
denominator: 12
}
);
assert_eq!(a + 5, Fraction::new(20, 3).unwrap());
assert_eq!(a + 0, a);
}
#[test]
fn show_test() {
let f = Fraction {
sign: true,
numerator: 5,
denominator: 4,
};
assert_eq!(format!("{:?}", f), format!("{}", f));
assert_eq!(format!("{:?}", f), "5 / 4");
let f = Fraction {
sign: false,
numerator: 5,
denominator: 4,
};
assert_eq!(format!("{:?}", f), "-5 / 4");
}
#[test]
fn new_test() {
let n = Fraction::new;
let f = n(5, 3);
assert_eq!(
f,
Ok(Fraction {
sign: true,
numerator: 5,
denominator: 3
})
);
let f = n(55, 33);
assert_eq!(
f,
Ok(Fraction {
sign: true,
numerator: 5,
denominator: 3
})
);
let f = n(-55, 33);
assert_eq!(
f,
Ok(Fraction {
sign: false,
numerator: 5,
denominator: 3
})
);
if let Ok(_) = n(55, 0) {
panic!();
}
let f = n(16384, 8192);
assert_eq!(
f,
Ok(Fraction {
sign: true,
numerator: 2,
denominator: 1
})
);
let f = n(23, 6);
assert_eq!(
f,
Ok(Fraction {
sign: true,
numerator: 23,
denominator: 6
})
);
let f = n(0, 33);
let g = n(0, 1);
assert_eq!(f, g);
}
|
/// SubmitPullReviewOptions are options to submit a pending pull review
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct SubmitPullReviewOptions {
pub body: Option<String>,
pub event: Option<String>,
}
impl SubmitPullReviewOptions {
/// Create a builder for this object.
#[inline]
pub fn builder() -> SubmitPullReviewOptionsBuilder {
SubmitPullReviewOptionsBuilder {
body: Default::default(),
}
}
#[inline]
pub fn repo_submit_pull_review() -> SubmitPullReviewOptionsPostBuilder<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingIndex, crate::generics::MissingId> {
SubmitPullReviewOptionsPostBuilder {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
_param_index: core::marker::PhantomData,
_param_id: core::marker::PhantomData,
}
}
}
impl Into<SubmitPullReviewOptions> for SubmitPullReviewOptionsBuilder {
fn into(self) -> SubmitPullReviewOptions {
self.body
}
}
impl Into<SubmitPullReviewOptions> for SubmitPullReviewOptionsPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::IndexExists, crate::generics::IdExists> {
fn into(self) -> SubmitPullReviewOptions {
self.inner.body
}
}
/// Builder for [`SubmitPullReviewOptions`](./struct.SubmitPullReviewOptions.html) object.
#[derive(Debug, Clone)]
pub struct SubmitPullReviewOptionsBuilder {
body: self::SubmitPullReviewOptions,
}
impl SubmitPullReviewOptionsBuilder {
#[inline]
pub fn body(mut self, value: impl Into<String>) -> Self {
self.body.body = Some(value.into());
self
}
#[inline]
pub fn event(mut self, value: impl Into<String>) -> Self {
self.body.event = Some(value.into());
self
}
}
/// Builder created by [`SubmitPullReviewOptions::repo_submit_pull_review`](./struct.SubmitPullReviewOptions.html#method.repo_submit_pull_review) method for a `POST` operation associated with `SubmitPullReviewOptions`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct SubmitPullReviewOptionsPostBuilder<Owner, Repo, Index, Id> {
inner: SubmitPullReviewOptionsPostBuilderContainer,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
_param_index: core::marker::PhantomData<Index>,
_param_id: core::marker::PhantomData<Id>,
}
#[derive(Debug, Default, Clone)]
struct SubmitPullReviewOptionsPostBuilderContainer {
body: self::SubmitPullReviewOptions,
param_owner: Option<String>,
param_repo: Option<String>,
param_index: Option<i64>,
param_id: Option<i64>,
}
impl<Owner, Repo, Index, Id> SubmitPullReviewOptionsPostBuilder<Owner, Repo, Index, Id> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> SubmitPullReviewOptionsPostBuilder<crate::generics::OwnerExists, Repo, Index, Id> {
self.inner.param_owner = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// name of the repo
#[inline]
pub fn repo(mut self, value: impl Into<String>) -> SubmitPullReviewOptionsPostBuilder<Owner, crate::generics::RepoExists, Index, Id> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// index of the pull request
#[inline]
pub fn index(mut self, value: impl Into<i64>) -> SubmitPullReviewOptionsPostBuilder<Owner, Repo, crate::generics::IndexExists, Id> {
self.inner.param_index = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// id of the review
#[inline]
pub fn id(mut self, value: impl Into<i64>) -> SubmitPullReviewOptionsPostBuilder<Owner, Repo, Index, crate::generics::IdExists> {
self.inner.param_id = Some(value.into());
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn body(mut self, value: impl Into<String>) -> Self {
self.inner.body.body = Some(value.into());
self
}
#[inline]
pub fn event(mut self, value: impl Into<String>) -> Self {
self.inner.body.event = Some(value.into());
self
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for SubmitPullReviewOptionsPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::IndexExists, crate::generics::IdExists> {
type Output = crate::pull_review::PullReview;
const METHOD: http::Method = http::Method::POST;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/pulls/{index}/reviews/{id}", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?"), index=self.inner.param_index.as_ref().expect("missing parameter index?"), id=self.inner.param_id.as_ref().expect("missing parameter id?")).into()
}
fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> {
use crate::client::Request;
Ok(req
.json(&self.inner.body))
}
}
impl crate::client::ResponseWrapper<crate::pull_review::PullReview, SubmitPullReviewOptionsPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::IndexExists, crate::generics::IdExists>> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
|
use std::borrow::Cow;
use std::error::Error;
use std::future::Future;
use std::io;
/// Special LogWriter that writes commands in batches.
/// Batching is both record count and timeout-based.
use std::sync::Arc;
use std::time::Duration;
use crate::storage::{self, SimpleFileWALError};
use async_trait::async_trait;
use futures_util::future::{abortable, AbortHandle};
use thiserror::Error;
use tokio::task::JoinHandle;
use tokio::{sync, time};
// TODO: pass some context for Error handling.
// Define Command trait that both provides context and
// defines data to store. Box<dyn Command>, like this.
#[derive(Error, Debug)]
pub enum BatchLogError {
#[error(transparent)]
Nested(Arc<SimpleFileWALError>),
#[error("{file}:{line} CANTHAPPEN: {msg}: {nested}")]
CantHappen {
file: &'static str,
line: u32,
msg: Cow<'static, str>,
nested: Arc<Box<dyn Error + Send + Sync + 'static>>,
},
}
struct Queue<AWAL: storage::AsyncWAL, T> {
wal: AWAL,
index_buf: Vec<AWAL::CommandPos>,
data_buf: Vec<(T, sync::oneshot::Sender<Result<T, BatchLogError>>)>,
flusher: Option<(JoinHandle<()>, AbortHandle)>,
}
impl<
AWAL: storage::AsyncWAL<Error = SimpleFileWALError> + Send + 'static,
T: Sync + Send + 'static,
> Queue<AWAL, T>
{
fn new(wal: AWAL, capacity: usize) -> Self {
Self {
wal,
index_buf: Vec::with_capacity(capacity),
data_buf: Vec::with_capacity(capacity),
flusher: None,
}
}
async fn flush(guard: &mut sync::OwnedMutexGuard<Queue<AWAL, T>>) -> Result<(), BatchLogError> {
let queue: &mut Queue<AWAL, T> = &mut *guard;
let index_buf = &mut queue.index_buf;
let wal = &mut queue.wal;
let indices_res = wal.indices(index_buf).await;
index_buf.clear();
match indices_res {
Ok(()) => {
// TODO: Possible improvement: replace Vec with new one, and
// send data in another thread. There are no fatal errors.
for (val, tx) in guard.data_buf.drain(..) {
// There is no point of handling the .send result. The
// receiver has gone? I couldn't care less.
let _ = tx.send(Ok(val));
}
Ok(())
}
Err(e) => {
let e = Arc::new(e);
for (_, tx) in guard.data_buf.drain(..) {
// There is no point of handling the .send result. The
// receiver has gone? I couldn't care less.
// TODO error context for Nested?
let _ = tx.send(Err(BatchLogError::Nested(e.clone())));
}
Err(BatchLogError::Nested(e))
}
}
}
fn get_flusher(
queue: Arc<sync::Mutex<Self>>,
flush_timeout: Duration,
) -> (JoinHandle<()>, AbortHandle) {
let delay = time::sleep(flush_timeout);
let (delay, handle) = abortable(delay);
let flusher = async move {
if delay.await.is_ok() {
let mut guard = queue.lock_owned().await;
// TODO what to do with the error? Set it somewhere.
let _ = Queue::flush(&mut guard).await;
// Dropping nor JoinHandle nor AbortHandle does not
// affect the current task.
guard.flusher = None;
}
};
(tokio::task::spawn(flusher), handle)
}
}
pub struct BatchLogConfig {
pub record_count: usize,
pub flush_timeout: Duration,
}
pub struct BatchLogWriter<AWAL: storage::AsyncWAL, T> {
/// Both WAL and CommandPos buffer.
// TODO: Vec is autoresizable. Find something not resizable, perhaps.
queue: Arc<sync::Mutex<Queue<AWAL, T>>>,
config: BatchLogConfig,
}
impl<
AWAL: storage::AsyncWAL<Error = SimpleFileWALError> + Sync + Send + 'static,
T: Sync + Send + 'static,
> BatchLogWriter<AWAL, T>
{
pub fn new(wal: AWAL, config: BatchLogConfig) -> Self {
// TODO: check record_count and fail if it is zero; or use
// max(1, record_count).
Self {
queue: Arc::new(sync::Mutex::new(Queue::new(wal, config.record_count))),
config,
}
}
}
#[async_trait]
impl<AWAL, V> storage::LogWriter<V> for BatchLogWriter<AWAL, V>
where
AWAL: storage::AsyncWAL<Error = SimpleFileWALError> + Sync + Send + 'static,
V: Sync + Send + 'static,
{
type Write = AWAL::Write;
type WriteHolder = AWAL::WriteHolder;
type Error = BatchLogError;
async fn command<I, F>(
&self, // TODO Pin? Arc?
serializer: I,
) -> Result<V, Self::Error>
where
I: FnOnce(storage::AsyncWriteWrapper<Self::Write, Self::WriteHolder>) -> F + Send + Sync,
F: Future<
Output = (
io::Result<V>,
storage::AsyncWriteWrapper<Self::Write, Self::WriteHolder>,
),
> + Send
+ Sync
+ 'async_trait,
{
let mut guard = self.queue.clone().lock_owned().await;
if guard.index_buf.len() == guard.index_buf.capacity() {
// The buffer is full and have to be flushed.
// First, remove timeout.
if let Some((_, handle)) = guard.flusher.take() {
handle.abort();
}
// Now flush and empty the buffer. Should it be done
// in a separate thread? Should timeout aligned to
// begin of flush or end of flush?
Queue::flush(&mut guard).await?;
// Reinstall timeout.
guard.flusher = Some(Queue::get_flusher(
self.queue.clone(),
self.config.flush_timeout,
));
}
// TODO: check vector is full after adding the element,
// and flush instantly. It makes benching easier. Now
// optimal number of bench request threads is capacity + 1, with
// such modification it is exactly capacity.
// TODO reconsider error handling. Send err to batched
// requests in case of io error? The requests get stuck.
// On another hand, the only possible thing is to restart?
// TODO: AsyncWAL has to rollback on failure.
// Invariant: now buffer has some space.
// TODO: on error, try to flush data and flush index got so far,
// and fail. Fail the current request too!
let (pos, val) = guard
.wal
.command(serializer)
.await
.map_err(|e| BatchLogError::Nested(Arc::new(e)))?;
let (sender, receiver) = sync::oneshot::channel();
guard.index_buf.push(pos);
guard.data_buf.push((val, sender));
if guard.flusher.is_none() {
// We have written some data, timeout has to be
// installed.
guard.flusher = Some(Queue::get_flusher(
self.queue.clone(),
self.config.flush_timeout,
));
}
drop(guard); // Explicitly
match receiver.await {
Ok(r) => r,
// Please note that this is not a fatal error, as it relates
// to single request only. But it worth knowing it anyway.
// e: tokio::sync::oneshot::error::RecvError
Err(e) => Err(BatchLogError::CantHappen {
file: file!(),
line: line!(),
msg: Cow::from("found closed oneshot::Sender in the BatchLogWriter"),
nested: Arc::new(Box::new(e)),
}),
}
}
}
|
use std::sync::Arc;
use axum::{extract::Path, Extension, Json};
use http::Response;
use hyper::Body;
use serde::Deserialize;
use svc_utils::extractors::AccountIdExtractor;
use uuid::Uuid;
use crate::{
app::{
api::v1::AppResult,
error::{Error as AppError, ErrorExt, ErrorKind},
metrics::AuthorizeMetrics,
AppContext, AuthzObject,
},
clients::tq::Priority,
};
#[derive(Debug, Deserialize)]
pub struct RestartTranscodingPayload {
priority: Priority,
}
impl Default for RestartTranscodingPayload {
fn default() -> Self {
Self {
priority: Priority::Normal,
}
}
}
pub async fn restart_transcoding(
Extension(ctx): Extension<Arc<dyn AppContext>>,
AccountIdExtractor(account_id): AccountIdExtractor,
Path(id): Path<Uuid>,
payload: Option<Json<RestartTranscodingPayload>>,
) -> AppResult {
let mut conn = ctx.get_conn().await.error(ErrorKind::InternalFailure)?;
let webinar = crate::db::class::ReadQuery::by_id(id)
.execute(&mut conn)
.await
.error(ErrorKind::InternalFailure)?
.ok_or_else(|| AppError::from(ErrorKind::ClassNotFound))?;
let object = AuthzObject::new(&["classrooms", &id.to_string()]).into();
ctx.authz()
.authorize(
webinar.audience().to_owned(),
account_id.clone(),
object,
"update".into(),
)
.await
.measure()?;
let payload = match payload {
Some(Json(payload)) => payload,
None => RestartTranscodingPayload::default(),
};
let r = crate::app::postprocessing_strategy::restart_webinar_transcoding(
ctx,
webinar,
payload.priority,
)
.await;
match r {
Ok(_) => Ok(Response::new(Body::from(""))),
Err(err) => Err(err).error(ErrorKind::InternalFailure),
}
}
|
extern crate proc_macro;
extern crate quote;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
macro_rules! span {
() => {{
Span::call_site()
}};
}
#[derive(Debug, Clone)]
struct GraphElt {
ident: syn::Ident,
node: syn::Ident,
event: syn::Ident,
}
#[derive(Debug, Clone)]
struct GraphStructure {
ident: syn::Ident,
out: GraphElt,
ins: Vec<GraphElt>,
}
fn read_typepath_ident(path: &syn::TypePath) -> syn::Ident {
path.path.segments.first().expect("One type").ident.clone()
}
fn pair_to_idents(pair: &syn::TypeTuple) -> (syn::Ident, syn::Ident) {
let pair: Vec<_> = pair
.elems
.iter()
.map(|tp| {
if let syn::Type::Path(ref tp) = tp {
tp
} else {
unimplemented!()
}
})
.collect();
if pair.len() != 2 {
panic!()
}
(read_typepath_ident(pair[0]), read_typepath_ident(pair[1]))
}
fn field_to_graph_elt(field: &syn::Field) -> GraphElt {
let ident = field.ident.clone().expect("Identifier expected");
let tuple = if let syn::Type::Tuple(ref tuple) = field.ty {
tuple
} else {
unimplemented!()
};
let (node, event) = pair_to_idents(tuple);
GraphElt { ident, node, event }
}
// TODO(vincent): check if item is a DataStruct
#[proc_macro_attribute]
pub fn crusp_lazy_graph(_attr: TokenStream, item: TokenStream) -> TokenStream {
let ast = parse_macro_input!(item as DeriveInput);
//eprintln!("{:#?}", ast);
let data = if let syn::Data::Struct(ref data) = ast.data {
data
} else {
unimplemented!()
};
// get visibility
let ident = ast.ident.clone();
let ident_builder = format!("{}Builder", ast.ident);
let graph_ident_builder = syn::Ident::new(&ident_builder, span!());
let fields = if let syn::Fields::Named(ref fields) = data.fields {
&fields.named
} else {
unimplemented!()
};
let (out, ins): (Vec<_>, Vec<_>) = fields
.iter()
.partition(|field| field.attrs[0].path.segments[0].ident == "output");
if out.len() != 1 {
panic!()
}
if ins.is_empty() {
panic!()
}
let out = out
.into_iter()
.map(|field| field_to_graph_elt(field))
.next()
.expect("Exactly one element");
let ins: Vec<_> = ins
.into_iter()
.map(|field| field_to_graph_elt(field))
.collect();
let graph = GraphStructure { ident, out, ins };
//eprintln!("{:#?}", graph);
let graph_ident = graph.ident;
let (out_ident, out_node, out_event) = (graph.out.ident, graph.out.node, graph.out.event);
let out_field = quote!(
#out_ident: ::crusp_graph::HandlerOutput<#out_node, #out_event>
);
let out_builder_field = quote!(
#out_ident: ::crusp_graph::HandlerOutputBuilder<#out_node, #out_event>
);
let in_builder_fields: Vec<_> = graph
.ins
.iter()
.map(|field| {
let (ident, node, event) =
(field.ident.clone(), field.node.clone(), field.event.clone());
quote!(
#ident: ::crusp_graph::LazyInputEventGraphBuilder<
#node,
#event,
::crusp_graph::OutCostEventLink<#out_node, #out_event>
>
)
})
.collect();
let in_rev_builder_fields: Vec<_> = graph
.ins
.iter()
.map(|field| {
let (ident, in_node, _event) =
(field.ident.clone(), field.node.clone(), field.event.clone());
let ident_name = format!("__crusp__rev_{}", ident);
let ident = syn::Ident::new(&ident_name, span!());
let out_node = out_node.clone();
quote!(
#ident: ::crusp_graph::AdjacentListGraphBuilder<
#out_node,
#in_node,
>
)
})
.collect();
let in_fields: Vec<_> = graph
.ins
.iter()
.map(|field| {
let (ident, node, event) =
(field.ident.clone(), field.node.clone(), field.event.clone());
quote!(
#ident: ::crusp_graph::LazyInputEventHandler<
#node,
#event,
::crusp_graph::OutCostEventLink<#out_node, #out_event>
>
)
})
.collect();
let in_rev_fields: Vec<_> = graph
.ins
.iter()
.map(|field| {
let (ident, in_node, _event) =
(field.ident.clone(), field.node.clone(), field.event.clone());
let ident_name = format!("__crusp__rev_{}", ident);
let ident = syn::Ident::new(&ident_name, span!());
let out_node = out_node.clone();
quote!(
#ident: ::std::rc::Rc<::crusp_graph::AdjacentListGraph<
#out_node,
#in_node,
>>
)
})
.collect();
let in_events_handler: Vec<_> = graph
.ins
.iter()
.map(|field| {
let (ident, node, event) =
(field.ident.clone(), field.node.clone(), field.event.clone());
let in_node = node;
let in_event = event;
quote!(
impl ::crusp_graph::InputEventHandler<#in_node, #in_event> for #graph_ident
{
#[allow(clippy::inline_always)]
#[inline(always)]
fn notify(&mut self, in_node: &#in_node, in_event: &#in_event) -> bool {
if self.#ident.notify(in_node, in_event) {
true
} else {
false
}
}
}
)
})
.collect();
let inout_events_handler: Vec<_> = graph.ins.iter()
.map(|field| {
let graph_ident_builder = graph_ident_builder.clone();
let (in_ident, node, event) =
(field.ident.clone(), field.node.clone(), field.event.clone());
let rev_ident = format!("__crusp__rev_{}", in_ident);
let rev_ident = syn::Ident::new(&rev_ident, span!());
let out_node = out_node.clone();
let out_event = out_event.clone();
let in_node = node;
let in_event = event;
let out_ident = out_ident.clone();
quote!(
impl ::crusp_graph::InOutEventHandlerBuilder<#out_node, #out_event, #in_node, #in_event>
for #graph_ident_builder
{
fn add_event(&mut self, out_node: &#out_node, out_event: &#out_event, in_node: &#in_node, in_event: &#in_event, cost: i64) {
let out = <::crusp_graph::OutCostEventLink<#out_node, #out_event>>::new(
*out_node,
*out_event,
cost
);
self.#in_ident.add_event(*in_node, *in_event, out);
self.#rev_ident.add_node(out_node, in_node);
self.#out_ident.add_node(*out_node);
}
}
)
})
.collect();
let graph_builder_impl = {
let graph_ident_builder = graph_ident_builder.clone();
let graph_ident = graph_ident.clone();
let out_ident = out_ident.clone();
let out_node = out_node.clone();
let out_event = out_event.clone();
let in_idents: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.ident.clone();
quote!(#field)
})
.collect();
let in_rev_idents: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.ident.clone();
let rev_field = format!("__crusp__rev_{}", field);
let rev_field = syn::Ident::new(&rev_field, span!());
quote!(#rev_field)
})
.collect();
let in_idents2 = in_idents.clone();
let in_idents3 = in_idents.clone();
let out_events: Vec<_> = std::iter::repeat(&out_event)
.clone()
.take(in_rev_idents.len())
.collect();
let out_nodes: Vec<_> = std::iter::repeat(&out_node)
.clone()
.take(in_idents.len())
.collect();
let in_nodes: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.node.clone();
quote!(#field)
})
.collect();
let in_events: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.event.clone();
quote!(#field)
})
.collect();
let in_nodes2 = in_nodes.clone();
let in_events2 = in_events.clone();
let out_events2 = out_events.clone();
let in_rev_idents2 = in_rev_idents.clone();
let in_rev_idents3 = in_rev_idents.clone();
let in_rev_nodes = in_nodes.clone();
quote!(
impl #graph_ident_builder
{
pub fn new() -> Self {
#graph_ident_builder {
#(#in_idents: <::crusp_graph::LazyInputEventHandler<#in_nodes, #in_events, ::crusp_graph::OutCostEventLink<#out_node, #out_events>>>::builder()),*,
#(#in_rev_idents: <::crusp_graph::AdjacentListGraph<#out_nodes,#in_rev_nodes>>::builder()),*,
#out_ident: <::crusp_graph::HandlerOutput<#out_node, #out_event>>::builder(),
}
}
pub fn finalize(self) -> #graph_ident {
#graph_ident {
#(#in_idents2: <::crusp_graph::LazyInputEventHandler<#in_nodes2, #in_events2, ::crusp_graph::OutCostEventLink<#out_node, #out_events2>>>::new(self.#in_idents3.finalize())),*,
#(#in_rev_idents2: ::std::rc::Rc::new(self.#in_rev_idents3.finalize())),*,
#out_ident: self.#out_ident.finalize(),
}
}
}
)
};
let graph_impl = {
let graph_ident_builder = graph_ident_builder.clone();
let graph_ident = graph_ident.clone();
let out_ident = out_ident.clone();
let out_node = out_node.clone();
let out_event = out_event.clone();
let in_idents: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.ident.clone();
quote!(#field)
})
.collect();
let out_events: Vec<_> = std::iter::repeat(&out_event)
.clone()
.take(in_idents.len())
.collect();
let in_nodes: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.node.clone();
quote!(#field)
})
.collect();
let in_events: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.event.clone();
quote!(#field)
})
.collect();
quote!(
impl #graph_ident
{
pub fn builder() -> #graph_ident_builder {
<#graph_ident_builder>::new()
}
#[allow(clippy::type_complexity)]
#[inline]
pub fn split_in_out(&mut self) -> (
&mut ::crusp_graph::HandlerOutput<#out_node, #out_event>,
#(&mut ::crusp_graph::LazyInputEventHandler<
#in_nodes, #in_events,
::crusp_graph::OutCostEventLink<#out_node, #out_events>>
),*
)
{
(
unsafe{ &mut *((&mut self.#out_ident) as *mut _)},
#(unsafe{ &mut *((&mut self.#in_idents) as *mut _)}),*
)
}
}
)
};
let impl_pop = {
let out_ident = out_ident.clone();
let out_node = out_node.clone();
let out_event = out_event.clone();
let in_idents: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.ident.clone();
quote!(#field)
})
.collect();
let in_idents2: Vec<_> = in_idents.clone();
quote!(
impl ::crusp_graph::OutputEventHandler<#out_node, #out_event> for #graph_ident
{
fn collect(&mut self, ignored: Option<OutNode>) {
let (__crusp__outs, #(#in_idents),*) = self.split_in_out();
#(#in_idents2.trigger_events(|__crusp__out| __crusp__outs.collect_out_event(__crusp__out, ignored)));*;
}
fn collect_and_pop(&mut self, ignored: Option<OutNode>) -> Option<(#out_node, #out_event)> {
self.collect(ignored);
self.#out_ident.pop()
}
})
};
let impl_pop_look = {
let out_ident = out_ident;
let out_node = out_node.clone();
let out_event = out_event;
let in_idents: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.ident.clone();
quote!(#field)
})
.collect();
let in_nodes: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.node.clone();
quote!(#field)
})
.collect();
let in_events: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.event.clone();
quote!(#field)
})
.collect();
let in_idents2: Vec<_> = in_idents.clone();
quote!(
impl <Look> ::crusp_graph::OutputEventHandlerLookup<#out_node, #out_event, Look> for #graph_ident
where
#(Look: LookEvent<#in_nodes, #in_events>),*,
{
fn collect_look(&mut self, look: &mut Look, ignored: Option<OutNode>) {
let (__crusp__outs, #(#in_idents),*) = self.split_in_out();
#(#in_idents2.trigger_look_events(|__crusp__out| __crusp__outs.collect_out_event(__crusp__out, ignored), look));*;
}
fn collect_look_and_pop(&mut self, look: &mut Look, ignored: Option<OutNode>) -> Option<(#out_node, #out_event)> {
self.collect_look(look, ignored);
self.#out_ident.pop()
}
})
};
let impl_visit_all = {
let graph_ident = graph_ident.clone();
let out_node = out_node.clone();
let in_nodes: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.node.clone();
quote!(#field)
})
.collect();
let in_rev_idents: Vec<_> = graph
.ins
.iter()
.map(|field| {
let field = field.ident.clone();
let rev_field = format!("__crusp__rev_{}", field);
let rev_field = syn::Ident::new(&rev_field, span!());
quote!(#rev_field)
})
.collect();
quote!(
impl <Visitor> ::crusp_graph::VisitAllOutputsNode<#out_node, Visitor> for #graph_ident
where
#(Visitor: VisitMut<#in_nodes>),*,
{
fn visit_all_in_nodes(&self, out_node: &#out_node, visitor: &mut Visitor)
{
#(self.#in_rev_idents.visit_in_nodes(out_node, visitor));*;
}
}
)
};
let impl_visitors: Vec<_> = graph
.ins
.iter()
.map(|field| {
let (in_ident, node, _event) =
(field.ident.clone(), field.node.clone(), field.event.clone());
let rev_ident = format!("__crusp__rev_{}", in_ident);
let rev_ident = syn::Ident::new(&rev_ident, span!());
let out_node = out_node.clone();
let in_node = node;
quote!(
impl ::crusp_graph::VisitOutputsNode<#out_node, #in_node>
for #graph_ident
{
fn visit_in_nodes<Visitor>(&self, out_node: &#out_node, visitor: &mut Visitor)
where Visitor: VisitMut<#in_node>
{
self.#rev_ident.visit_in_nodes(out_node, visitor);
}
}
)
})
.collect();
let expanded = quote!(
struct #graph_ident_builder
{
#out_builder_field,
#(#in_builder_fields),*,
#(#in_rev_builder_fields),*,
}
struct #graph_ident
{
#out_field,
#(#in_fields),*,
#(#in_rev_fields),*
}
#(#impl_visitors)*
#impl_visit_all
#(#in_events_handler)*
#(#inout_events_handler)*
#graph_builder_impl
#graph_impl
#impl_pop
#impl_pop_look
);
expanded.into()
}
|
// single tasking k-nucleotide
import io::reader_util;
use std;
import std::map;
import std::map::hashmap;
import std::sort;
// given a map, print a sorted version of it
fn sort_and_fmt(mm: hashmap<[u8], uint>, total: uint) -> str {
fn pct(xx: uint, yy: uint) -> float {
ret (xx as float) * 100f / (yy as float);
}
fn le_by_val<TT: copy, UU: copy>(kv0: (TT,UU), kv1: (TT,UU)) -> bool {
let (_, v0) = kv0;
let (_, v1) = kv1;
ret v0 >= v1;
}
fn le_by_key<TT: copy, UU: copy>(kv0: (TT,UU), kv1: (TT,UU)) -> bool {
let (k0, _) = kv0;
let (k1, _) = kv1;
ret k0 <= k1;
}
// sort by key, then by value
fn sortKV<TT: copy, UU: copy>(orig: [(TT,UU)]) -> [(TT,UU)] {
ret sort::merge_sort(le_by_val, sort::merge_sort(le_by_key, orig));
}
let mut pairs = [];
// map -> [(k,%)]
mm.each(fn&(key: [u8], val: uint) -> bool {
pairs += [(key, pct(val, total))];
ret true;
});
let pairs_sorted = sortKV(pairs);
let mut buffer = "";
pairs_sorted.each(fn&(kv: ([u8], float)) -> bool unsafe {
let (k,v) = kv;
buffer += (#fmt["%s %0.3f\n", str::to_upper(str::unsafe::from_bytes(k)), v]);
ret true;
});
ret buffer;
}
// given a map, search for the frequency of a pattern
fn find(mm: hashmap<[u8], uint>, key: str) -> uint {
alt mm.find(str::bytes(str::to_lower(key))) {
option::none { ret 0u; }
option::some(num) { ret num; }
}
}
// given a map, increment the counter for a key
fn update_freq(mm: hashmap<[u8], uint>, key: [u8]) {
alt mm.find(key) {
option::none { mm.insert(key, 1u ); }
option::some(val) { mm.insert(key, 1u + val); }
}
}
// given a [u8], for each window call a function
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry(bb: [const u8], nn: uint, it: fn(window: [u8])) -> [u8] {
let mut ii = 0u;
let len = vec::len(bb);
while ii < len - (nn - 1u) {
it(vec::slice(bb, ii, ii+nn));
ii += 1u;
}
ret vec::slice(bb, len - (nn - 1u), len);
}
fn make_sequence_processor(sz: uint, from_parent: comm::port<[u8]>, to_parent: comm::chan<str>) {
let freqs: hashmap<[u8], uint> = map::bytes_hash();
let mut carry: [u8] = [];
let mut total: uint = 0u;
let mut line: [u8];
loop {
line = comm::recv(from_parent);
if line == [] { break; }
carry = windows_with_carry(carry + line, sz, { |window|
update_freq(freqs, window);
total += 1u;
});
}
let buffer = alt sz {
1u { sort_and_fmt(freqs, total) }
2u { sort_and_fmt(freqs, total) }
3u { #fmt["%u\t%s", find(freqs, "GGT"), "GGT"] }
4u { #fmt["%u\t%s", find(freqs, "GGTA"), "GGTA"] }
6u { #fmt["%u\t%s", find(freqs, "GGTATT"), "GGTATT"] }
12u { #fmt["%u\t%s", find(freqs, "GGTATTTTAATT"), "GGTATTTTAATT"] }
18u { #fmt["%u\t%s", find(freqs, "GGTATTTTAATTTATAGT"), "GGTATTTTAATTTATAGT"] }
_ { "" }
};
//comm::send(to_parent, #fmt["yay{%u}", sz]);
comm::send(to_parent, buffer);
}
// given a FASTA file on stdin, process sequence THREE
fn main () {
// initialize each sequence sorter
let sizes = [1u,2u,3u,4u,6u,12u,18u];
let from_child = vec::map (sizes, { |_sz| comm::port() });
let to_parent = vec::mapi(sizes, { |ii, _sz| comm::chan(from_child[ii]) });
let to_child = vec::mapi(sizes, fn@(ii: uint, sz: uint) -> comm::chan<[u8]> {
ret task::spawn_listener { |from_parent|
make_sequence_processor(sz, from_parent, to_parent[ii]);
};
});
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
let rdr = io::stdin();
while !rdr.eof() {
let line: str = rdr.read_line();
if str::len(line) == 0u { cont; }
alt (line[0], proc_mode) {
// start processing if this is the one
('>' as u8, false) {
alt str::find_str_from(line, "THREE", 1u) {
option::some(_) { proc_mode = true; }
option::none { }
}
}
// break our processing
('>' as u8, true) { break; }
// process the sequence for k-mers
(_, true) {
let line_bytes = str::bytes(line);
for sizes.eachi { |ii, _sz|
let mut lb = line_bytes;
comm::send(to_child[ii], lb);
}
}
// whatever
_ { }
}
}
// finish...
for sizes.eachi { |ii, _sz|
comm::send(to_child[ii], []);
}
// now fetch and print result messages
for sizes.eachi { |ii, _sz|
io::println(comm::recv(from_child[ii]));
}
}
|
use serde::{Deserialize, Serialize};
pub use swc::config::Options;
use swc::ecmascript::ast::Program;
#[derive(Deserialize)]
pub struct ParseArguments {
pub src: String,
pub opt: Option<ParseOptions>,
}
#[derive(Deserialize)]
pub struct PrintArguments {
pub program: Program,
pub options: Options,
}
#[derive(Deserialize)]
pub struct AnalyzerArguments {
pub src: String,
pub dynamic: bool,
}
#[derive(Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ParseOptions {
#[serde(default)]
pub comments: bool,
#[serde(flatten)]
pub syntax: swc_ecma_parser::Syntax,
#[serde(default = "default_is_module")]
pub is_module: bool,
#[serde(default)]
pub target: swc_ecma_parser::JscTarget,
}
fn default_is_module() -> bool {
true
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.