text stringlengths 8 4.13M |
|---|
mod model;
mod context;
mod hook;
use self::context::{CommandError, JobContext};
pub(crate) use self::model::*;
use self::hook::{Hook, Hooks};
use crate::config::{Config, Project};
use crate::fs::{get_job_archive_file, get_telegram_chat_id};
use crate::status;
use crate::time::now;
use std::fmt;
use std::io;
use std::io::Write;
use std::slice::SliceConcatExt;
use toml;
pub(crate) type JobResult = Result<(), Error>;
#[derive(Debug)]
pub(crate) enum Error {
Context(io::Error),
Command(CommandError),
Archive(io::Error),
Log(io::Error),
}
#[derive(Debug)]
struct JobRunner<'a> {
job: &'a Job,
project: &'a Project,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Context(ref err) => write!(f, "Unable to create context: {}", err),
Error::Command(ref err) => write!(f, "{}", err),
Error::Archive(ref err) => write!(f, "Unable to archive job: {}", err),
Error::Log(ref err) => write!(f, "Unable write job log: {}", err),
}
}
}
impl<'a> JobRunner<'a> {
fn new(job: &'a Job, project: &'a Project) -> Self {
JobRunner { job, project }
}
fn run(&self) -> JobResult {
let started_at = now();
let project_name = &self.job.project;
status!(
"Starting job #{} for {}, triggered by {}",
self.job.id,
project_name,
self.job.trigger
);
let result = self.run_scripts();
self.archive_job(started_at, result.is_ok())?;
result
}
fn run_scripts(&self) -> JobResult {
let mut context = JobContext::new(self.job, self.project).map_err(Error::Context)?;
println!("{}", context);
for script in &self.project.scripts {
let command = &script.command;
status!("Running command: {}", command.join(" "));
let status = context.run_command(command);
if let Err(ref err) = status {
let result = writeln!(context.log_file(), "[toby] {}", err);
result.map_err(Error::Log)?;
}
status.map_err(Error::Command).or_else(|err| {
if script.allow_failure {
Ok(())
} else {
Err(err)
}
})?;
}
Ok(())
}
fn archive_job(&self, started_at: u64, successful: bool) -> JobResult {
let job = &self.job;
let file = get_job_archive_file(&job.project, job.id).map_err(Error::Archive)?;
let mut buf_writer = io::BufWriter::new(file);
let archived_job = self.job.archive(started_at, successful);
let archived_job_str = toml::to_string(&archived_job).expect("unable to serialize job");
buf_writer
.write_all(archived_job_str.as_bytes())
.map_err(Error::Archive)?;
Ok(())
}
}
pub(crate) fn start_worker(config: &Config, receiver: &WorkerReceiver) {
let projects = &config.projects;
let telegram_chat_id = get_telegram_chat_id().expect("Unable to read telegram chat id");
let hooks = Hooks::from_config(config, telegram_chat_id);
for job in receiver {
let project_name = &job.project;
match projects.get(project_name) {
Some(project) => {
let runner = JobRunner::new(&job, project);
hooks.before_job(&job);
let job_result = runner.run();
match job_result {
Ok(_) => status!("Job finished successfully"),
Err(ref err) => status!("{}", err),
};
hooks.after_job(&job, &job_result);
}
None => status!("Project {} does not exist", project_name),
}
}
}
|
use darling::{util::Flag, FromDeriveInput, FromField, FromVariant};
use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::{DeriveInput, Ident, Index, Member, Path};
use crate::generators::{self as gen, CodedVariant};
#[derive(FromDeriveInput)]
#[darling(supports(enum_any), attributes(sdk_error))]
struct Error {
ident: Ident,
data: darling::ast::Data<ErrorVariant, darling::util::Ignored>,
/// The path to a const set to the module name.
#[darling(default)]
module_name: Option<syn::Path>,
/// Whether to sequentially autonumber the error codes.
/// This option exists as a convenience for runtimes that
/// only append errors or release only breaking changes.
#[darling(default, rename = "autonumber")]
autonumber: Flag,
}
#[derive(FromVariant)]
#[darling(attributes(sdk_error))]
struct ErrorVariant {
ident: Ident,
fields: darling::ast::Fields<ErrorField>,
/// The explicit ID of the error code. Overrides any autonumber set on the error enum.
#[darling(default, rename = "code")]
code: Option<u32>,
#[darling(default, rename = "transparent")]
transparent: Flag,
#[darling(default, rename = "abort")]
abort: Flag,
}
impl CodedVariant for ErrorVariant {
const FIELD_NAME: &'static str = "code";
fn ident(&self) -> &Ident {
&self.ident
}
fn code(&self) -> Option<u32> {
self.code
}
}
#[derive(FromField)]
#[darling(forward_attrs(source, from))]
struct ErrorField {
ident: Option<Ident>,
attrs: Vec<syn::Attribute>,
}
pub fn derive_error(input: DeriveInput) -> TokenStream {
let error = match Error::from_derive_input(&input) {
Ok(error) => error,
Err(e) => return e.write_errors(),
};
let error_ty_ident = &error.ident;
let module_name = error
.module_name
.unwrap_or_else(|| syn::parse_quote!(MODULE_NAME));
let (module_name_body, code_body, abort_body) = convert_variants(
&format_ident!("self"),
module_name,
&error.data.as_ref().take_enum().unwrap(),
error.autonumber.is_some(),
);
let sdk_crate = gen::sdk_crate_path();
gen::wrap_in_const(quote! {
use #sdk_crate::{self as __sdk, error::Error as _};
#[automatically_derived]
impl __sdk::error::Error for #error_ty_ident {
fn module_name(&self) -> &str {
#module_name_body
}
fn code(&self) -> u32 {
#code_body
}
fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
#abort_body
}
}
#[automatically_derived]
impl From<#error_ty_ident> for __sdk::error::RuntimeError {
fn from(err: #error_ty_ident) -> Self {
Self::new(err.module_name(), err.code(), &err.to_string())
}
}
})
}
fn convert_variants(
enum_binding: &Ident,
module_name: Path,
variants: &[&ErrorVariant],
autonumber: bool,
) -> (TokenStream, TokenStream, TokenStream) {
if variants.is_empty() {
return (quote!(#module_name), quote!(0), quote!(Err(#enum_binding)));
}
let mut next_autonumber = 0u32;
let mut reserved_numbers = std::collections::BTreeSet::new();
let abort_variants: Vec<_> = variants
.iter()
.filter_map(|variant| {
if variant.abort.is_none() {
return None;
}
let variant_ident = &variant.ident;
Some(quote! {
match #enum_binding {
Self::#variant_ident(err) => Ok(err),
_ => Err(#enum_binding),
}
})
})
.collect();
let abort_variant = match abort_variants.len() {
0 => quote!(Err(#enum_binding)),
1 => abort_variants.into_iter().next().unwrap(),
_ => {
enum_binding
.span()
.unwrap()
.error("multiple abort variants specified")
.emit();
return (quote!(), quote!(), quote!());
}
};
let (module_name_matches, code_matches): (Vec<_>, Vec<_>) = variants
.iter()
.map(|variant| {
let variant_ident = &variant.ident;
if variant.transparent.is_some() {
// Transparently forward everything to the source.
let mut maybe_sources = variant
.fields
.iter()
.enumerate()
.filter_map(|(i, f)| (!f.attrs.is_empty()).then(|| (i, f.ident.clone())));
let source = maybe_sources.next();
if maybe_sources.count() != 0 {
variant_ident
.span()
.unwrap()
.error("multiple error sources specified for variant")
.emit();
return (quote!(), quote!());
}
if source.is_none() {
variant_ident
.span()
.unwrap()
.error("no source error specified for variant")
.emit();
return (quote!(), quote!());
}
let (field_index, field_ident) = source.unwrap();
let field = match field_ident {
Some(ident) => Member::Named(ident),
None => Member::Unnamed(Index {
index: field_index as u32,
span: variant_ident.span(),
}),
};
let source = quote!(source);
let module_name = quote_spanned!(variant_ident.span()=> #source.module_name());
let code = quote_spanned!(variant_ident.span()=> #source.code());
(
quote! {
Self::#variant_ident { #field: #source, .. } => #module_name,
},
quote! {
Self::#variant_ident { #field: #source, .. } => #code,
},
)
} else {
// Regular case without forwarding.
let code = match variant.code {
Some(code) => {
if reserved_numbers.contains(&code) {
variant_ident
.span()
.unwrap()
.error(format!("code {} already used", code))
.emit();
return (quote!(), quote!());
}
reserved_numbers.insert(code);
code
}
None if autonumber => {
let mut reserved_successors = reserved_numbers.range(next_autonumber..);
while reserved_successors.next() == Some(&next_autonumber) {
next_autonumber += 1;
}
let code = next_autonumber;
reserved_numbers.insert(code);
next_autonumber += 1;
code
}
None => {
variant_ident
.span()
.unwrap()
.error("missing `code` for variant")
.emit();
return (quote!(), quote!());
}
};
(
quote! {
Self::#variant_ident { .. } => #module_name,
},
quote! {
Self::#variant_ident { .. } => #code,
},
)
}
})
.unzip();
(
quote! {
match #enum_binding {
#(#module_name_matches)*
}
},
quote! {
match #enum_binding {
#(#code_matches)*
}
},
abort_variant,
)
}
#[cfg(test)]
mod tests {
#[test]
fn generate_error_impl_auto_abort() {
let expected: syn::Stmt = syn::parse_quote!(
const _: () = {
use oasis_runtime_sdk::{self as __sdk, error::Error as _};
#[automatically_derived]
impl __sdk::error::Error for Error {
fn module_name(&self) -> &str {
match self {
Self::Error0 { .. } => MODULE_NAME,
Self::Error2 { .. } => MODULE_NAME,
Self::Error1 { .. } => MODULE_NAME,
Self::Error3 { .. } => MODULE_NAME,
Self::ErrorAbort { .. } => MODULE_NAME,
}
}
fn code(&self) -> u32 {
match self {
Self::Error0 { .. } => 0u32,
Self::Error2 { .. } => 2u32,
Self::Error1 { .. } => 1u32,
Self::Error3 { .. } => 3u32,
Self::ErrorAbort { .. } => 4u32,
}
}
fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
match self {
Self::ErrorAbort(err) => Ok(err),
_ => Err(self),
}
}
}
#[automatically_derived]
impl From<Error> for __sdk::error::RuntimeError {
fn from(err: Error) -> Self {
Self::new(err.module_name(), err.code(), &err.to_string())
}
}
};
);
let input: syn::DeriveInput = syn::parse_quote!(
#[derive(Error)]
#[sdk_error(autonumber)]
pub enum Error {
Error0,
#[sdk_error(code = 2)]
Error2 {
payload: Vec<u8>,
},
Error1(String),
Error3,
#[sdk_error(abort)]
ErrorAbort(sdk::dispatcher::Error),
}
);
let error_derivation = super::derive_error(input);
let actual: syn::Stmt = syn::parse2(error_derivation).unwrap();
crate::assert_empty_diff!(actual, expected);
}
#[test]
fn generate_error_impl_manual() {
let expected: syn::Stmt = syn::parse_quote!(
const _: () = {
use oasis_runtime_sdk::{self as __sdk, error::Error as _};
#[automatically_derived]
impl __sdk::error::Error for Error {
fn module_name(&self) -> &str {
THE_MODULE_NAME
}
fn code(&self) -> u32 {
0
}
fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
Err(self)
}
}
#[automatically_derived]
impl From<Error> for __sdk::error::RuntimeError {
fn from(err: Error) -> Self {
Self::new(err.module_name(), err.code(), &err.to_string())
}
}
};
);
let input: syn::DeriveInput = syn::parse_quote!(
#[derive(Error)]
#[sdk_error(autonumber, module_name = "THE_MODULE_NAME")]
pub enum Error {}
);
let error_derivation = super::derive_error(input);
let actual: syn::Stmt = syn::parse2(error_derivation).unwrap();
crate::assert_empty_diff!(actual, expected);
}
#[test]
fn generate_error_impl_from() {
let expected: syn::Stmt = syn::parse_quote!(
const _: () = {
use oasis_runtime_sdk::{self as __sdk, error::Error as _};
#[automatically_derived]
impl __sdk::error::Error for Error {
fn module_name(&self) -> &str {
match self {
Self::Foo { 0: source, .. } => source.module_name(),
}
}
fn code(&self) -> u32 {
match self {
Self::Foo { 0: source, .. } => source.code(),
}
}
fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
Err(self)
}
}
#[automatically_derived]
impl From<Error> for __sdk::error::RuntimeError {
fn from(err: Error) -> Self {
Self::new(err.module_name(), err.code(), &err.to_string())
}
}
};
);
let input: syn::DeriveInput = syn::parse_quote!(
#[derive(Error)]
#[sdk_error(module_name = "THE_MODULE_NAME")]
pub enum Error {
#[sdk_error(transparent)]
Foo(#[from] AnotherError),
}
);
let error_derivation = super::derive_error(input);
let actual: syn::Stmt = syn::parse2(error_derivation).unwrap();
crate::assert_empty_diff!(actual, expected);
}
}
|
use chamomile::prelude::SendMessage;
use smol::channel::{SendError, Sender};
use tdn_types::{
group::GroupId,
message::{ReceiveMessage, RecvType, SendType},
primitive::{DeliveryType, PeerAddr, Result, StreamType},
};
#[inline]
pub(crate) async fn layer_handle_send(
fgid: GroupId,
tgid: GroupId,
p2p_send: &Sender<SendMessage>,
msg: SendType,
) -> std::result::Result<(), SendError<SendMessage>> {
// fgid, tgid serialize data to msg data.
let mut bytes = fgid.0.to_vec();
bytes.extend(&tgid.0);
match msg {
SendType::Connect(tid, peer_addr, _domain, addr, data) => {
bytes.extend(data);
p2p_send
.send(SendMessage::StableConnect(tid, peer_addr, addr, bytes))
.await
}
SendType::Disconnect(peer_addr) => {
p2p_send
.send(SendMessage::StableDisconnect(peer_addr))
.await
}
SendType::Result(tid, peer_addr, is_ok, is_force, data) => {
bytes.extend(data);
p2p_send
.send(SendMessage::StableResult(
tid, peer_addr, is_ok, is_force, bytes,
))
.await
}
SendType::Event(tid, peer_addr, data) => {
bytes.extend(data);
p2p_send
.send(SendMessage::Data(tid, peer_addr, bytes))
.await
}
SendType::Stream(id, stream, data) => {
bytes.extend(data);
p2p_send.send(SendMessage::Stream(id, stream, bytes)).await
}
}
}
#[inline]
pub(crate) async fn layer_handle_connect(
fgid: GroupId,
_tgid: GroupId,
out_send: &Sender<ReceiveMessage>,
peer_addr: PeerAddr,
data: Vec<u8>,
) -> Result<()> {
let gmsg = RecvType::Connect(peer_addr, data);
#[cfg(any(feature = "single", feature = "std"))]
let msg = ReceiveMessage::Layer(fgid, gmsg);
#[cfg(any(feature = "multiple", feature = "full"))]
let msg = ReceiveMessage::Layer(fgid, _tgid, gmsg);
out_send
.send(msg)
.await
.map_err(|e| error!("Outside channel: {:?}", e))
.expect("Outside channel closed");
Ok(())
}
#[inline]
pub(crate) async fn layer_handle_result_connect(
fgid: GroupId,
_tgid: GroupId,
out_send: &Sender<ReceiveMessage>,
peer_addr: PeerAddr,
data: Vec<u8>,
) -> Result<()> {
let gmsg = RecvType::ResultConnect(peer_addr, data);
#[cfg(any(feature = "single", feature = "std"))]
let msg = ReceiveMessage::Layer(fgid, gmsg);
#[cfg(any(feature = "multiple", feature = "full"))]
let msg = ReceiveMessage::Layer(fgid, _tgid, gmsg);
out_send
.send(msg)
.await
.map_err(|e| error!("Outside channel: {:?}", e))
.expect("Outside channel closed");
Ok(())
}
#[inline]
pub(crate) async fn layer_handle_result(
fgid: GroupId,
_tgid: GroupId,
out_send: &Sender<ReceiveMessage>,
peer_addr: PeerAddr,
is_ok: bool,
data: Vec<u8>,
) -> Result<()> {
let gmsg = RecvType::Result(peer_addr, is_ok, data);
#[cfg(any(feature = "single", feature = "std"))]
let msg = ReceiveMessage::Layer(fgid, gmsg);
#[cfg(any(feature = "multiple", feature = "full"))]
let msg = ReceiveMessage::Layer(fgid, _tgid, gmsg);
out_send
.send(msg)
.await
.map_err(|e| error!("Outside channel: {:?}", e))
.expect("Outside channel closed");
Ok(())
}
#[inline]
pub(crate) async fn layer_handle_leave(
fgid: GroupId,
out_send: &Sender<ReceiveMessage>,
peer_addr: PeerAddr,
) -> Result<()> {
let gmsg = RecvType::Leave(peer_addr);
#[cfg(any(feature = "single", feature = "std"))]
let msg = ReceiveMessage::Layer(fgid, gmsg);
#[cfg(any(feature = "multiple", feature = "full"))]
let msg = ReceiveMessage::Layer(fgid, fgid, gmsg);
out_send
.send(msg)
.await
.map_err(|e| error!("Outside channel: {:?}", e))
.expect("Outside channel closed");
Ok(())
}
#[inline]
pub(crate) async fn layer_handle_data(
fgid: GroupId,
_tgid: GroupId,
out_send: &Sender<ReceiveMessage>,
peer_addr: PeerAddr,
data: Vec<u8>,
) -> Result<()> {
let gmsg = RecvType::Event(peer_addr, data);
#[cfg(any(feature = "single", feature = "std"))]
let msg = ReceiveMessage::Layer(fgid, gmsg);
#[cfg(any(feature = "multiple", feature = "full"))]
let msg = ReceiveMessage::Layer(fgid, _tgid, gmsg);
out_send
.send(msg)
.await
.map_err(|e| error!("Outside channel: {:?}", e))
.expect("Outside channel closed");
Ok(())
}
#[inline]
pub(crate) async fn layer_handle_stream(
fgid: GroupId,
_tgid: GroupId,
out_send: &Sender<ReceiveMessage>,
uid: u32,
stream_type: StreamType,
data: Vec<u8>,
) -> Result<()> {
let gmsg = RecvType::Stream(uid, stream_type, data);
#[cfg(any(feature = "single", feature = "std"))]
let msg = ReceiveMessage::Layer(fgid, gmsg);
#[cfg(any(feature = "multiple", feature = "full"))]
let msg = ReceiveMessage::Layer(fgid, _tgid, gmsg);
out_send
.send(msg)
.await
.map_err(|e| error!("Outside channel: {:?}", e))
.expect("Outside channel closed");
Ok(())
}
#[inline]
pub(crate) async fn layer_handle_delivery(
fgid: GroupId,
_tgid: GroupId,
out_send: &Sender<ReceiveMessage>,
delivery_type: DeliveryType,
tid: u64,
is_sended: bool,
) -> Result<()> {
let gmsg = RecvType::Delivery(delivery_type, tid, is_sended);
#[cfg(any(feature = "single", feature = "std"))]
let msg = ReceiveMessage::Layer(fgid, gmsg);
#[cfg(any(feature = "multiple", feature = "full"))]
let msg = ReceiveMessage::Layer(fgid, _tgid, gmsg);
out_send
.send(msg)
.await
.map_err(|e| error!("Outside channel: {:?}", e))
.expect("Outside channel closed");
Ok(())
}
|
use super::*;
use super::BinaryTree;
#[test]
fn test_len() {
let vec: Vec<i32> = vec![8; 8];
assert!(vec.len() == 8);
}
#[test]
fn test_sequential_search() {
let vec = vec![1, 2, 5, 6, 7, 9, 20];
let assert_value = Some(2);
let search_value = 5;
let result_value = vec.sequential_search(search_value);
assert_eq!(result_value, assert_value, "result is {}", result_value.unwrap());
}
#[test]
fn test_binary_search() {
let vec = vec![1, 2, 5, 6, 7, 9, 20];
let assert_value = Some(2);
let search_value = 5;
let result_value = vec.binary_search(search_value, 0, vec.len() as i32 - 1);
assert_eq!(result_value, assert_value, "result is {}", result_value.unwrap());
}
#[test]
fn test_interpolation_search() {
let vec = vec![1, 2, 5, 6, 7, 9, 20];
let assert_value = Some(2);
let search_value = 5;
let result_value = vec.interpolation_search(search_value, 0, vec.len() as i32 - 1);
assert_eq!(result_value, assert_value, "result is {}", result_value.unwrap());
}
#[test]
fn test_sequential_search_none() {
let vec = vec![1, 2, 5, 6, 7, 9, 20];
let search_value = 3;
let result_value = vec.sequential_search(search_value);
assert!(result_value.is_none(), "result is {}", result_value.unwrap());
}
#[test]
fn test_binary_search_none() {
let vec = vec![1, 2, 5, 6, 7, 9, 20];
let search_value = 3;
let result_value = vec.binary_search(search_value, 0, vec.len() as i32 - 1);
assert!(result_value.is_none(), "result is {}", result_value.unwrap());
}
#[test]
fn test_interpolation_search_none() {
let vec = vec![1, 2, 5, 6, 7, 9, 20];
let search_value = 3;
let result_value = vec.interpolation_search(search_value, 0, vec.len() as i32 - 1);
assert!(result_value.is_none(), "result is {}", result_value.unwrap());
}
#[test]
fn test_is_empty() {
let tree = BinaryTree::new();
assert!(tree.is_empty());
}
#[test]
fn test_is_not_empty() {
let mut tree = BinaryTree::new();
tree.insert(5);
assert!(!tree.is_empty());
}
#[test]
fn test_find() {
let mut tree = BinaryTree::new();
tree.insert(5);
tree.insert(4);
tree.insert(3);
let search_value = 4;
println!("{:?}", tree.search(search_value));
assert!(tree.search(search_value).unwrap().value == search_value);
}
#[test]
fn test_find_none() {
let mut tree = BinaryTree::new();
tree.insert(5);
tree.insert(4);
tree.insert(3);
let search_value = 2;
assert!(tree.search(search_value).is_none());
}
#[test]
fn test_min() {
let mut tree = BinaryTree::new();
tree.insert(5);
tree.insert(6);
tree.insert(7);
tree.insert(4);
tree.insert(3);
let index = 4;
assert_eq!(tree.min(4), 6);
}
|
// Temporary
//#![allow(dead_code)]
use crate::credentials::generate_mqtt_hash;
use crate::mqtt_broker_manager::{QOS, TOPICS, NEUTRONCOMMUNICATOR_TOPIC, REGISTERED_TOPIC};
use crate::nodes::{Node, Element};
use crate::settings::{NeutronCommunicator, SettingsDatabase, SettingsWebInterface};
use crate::external_interface::structs::{ElementsFiltered, NodeFiltered, NodeInfoEdit};
use crate::{BLACKBOX_MQTT_USERNAME, INTERFACE_MQTT_USERNAME};
use postgres::{Config, tls::NoTls};
use r2d2::Pool;
use r2d2_postgres::{PostgresConnectionManager};
const MQTT_USERNAME_UNREGISTERED: &str = "unregistered_node";
const TABLE_BLACKBOX_UNREGISTERED: &str = "blackbox_unregistered";
const TABLE_BLACKBOX_NODES: &str = "blackbox_nodes";
const TABLE_BLACKBOX_ELEMENTS: &str = "blackbox_elements";
const TABLE_MQTT_USERS: &str = "mqtt_users";
const TABLE_MQTT_ACL: &str = "mqtt_acl";
const MQTT_READ_WRITE: i32 = 3;
const MQTT_WRITE_ONLY: i32 = 2;
const MQTT_SUBSCRIBE_ONLY: i32 = 4;
const MQTT_READ_ONLY: i32 = 1;
/**
* Checks if the db contains necessary tables for operation.
* If it doesn't, it creates them.
*
* This function creates a db connection and returns it.
*
* If the mosquitto broker and BlackBox are using the same db server,
* and BlackBox creates tables for authentication,
* the new password for BlackBox is returned.
* ```
* Touple.0 - Database connection pool
* Touple.1 - New mqtt password(if empty, then ignore)
* ```
*/
pub fn init(
bb_mqtt_same_db: bool,
db_settings: &SettingsDatabase,
mqtt_blackbox_pass: &str,
web_interface: &SettingsWebInterface,
neutron_communicators: &[NeutronCommunicator],
) -> Result<Pool<PostgresConnectionManager<NoTls>>, i8> {
let mut builder = Config::new();
builder.host(&db_settings.db_ip)
.port(db_settings.db_port.parse::<u16>().unwrap())
.dbname(&db_settings.db_name)
.user(
&db_settings.db_username
)
.password(
if !db_settings.db_password.is_empty() {
&db_settings.db_password
} else {
""
}
);
let manager = PostgresConnectionManager::new(builder.clone(), NoTls);
let manager_return = PostgresConnectionManager::new(builder, NoTls);
let _pool = Pool::new(manager);
match _pool {
Ok(db) => {
info!("Database connection successful.");
// Check which table exists
if !table_exists(TABLE_BLACKBOX_NODES, db.clone()) {
info!("Creating BlackBox Nodes table.");
if !create_table_nodes(db.clone()) {
return Err(1);
}
}
if !table_exists(TABLE_BLACKBOX_ELEMENTS, db.clone()) {
info!("Creating BlackBox Elements table.");
if !create_table_elements(db.clone()) {
return Err(1);
}
}
// Unregistered table is not supposed to be here on startup so we remove it if it exists
if table_exists(TABLE_BLACKBOX_UNREGISTERED, db.clone()) {
set_discovery_mode(false, "", db.clone(), None);
}
// If we're on the same db then create the tables, generate the mosquitto config and credentials
if bb_mqtt_same_db {
if !table_exists(TABLE_MQTT_USERS, db.clone()) {
info!("Creating MQTT Users table.");
if !create_table_mqtt_users(db.clone()) {
return Err(1);
}
}
if !table_exists(TABLE_MQTT_ACL, db.clone()) {
info!("Creating MQTT ACL table.");
if !create_table_mqtt_acl(db.clone()) {
return Err(1);
}
}
if !check_mqtt_user_exists(db.clone(), BLACKBOX_MQTT_USERNAME) {
info!("BlackBox MQTT credentials not found. Generating...");
if !set_mqtt_bb_creds(db.clone(), bb_mqtt_same_db, mqtt_blackbox_pass) {
return Err(1);
}
}
if !check_mqtt_user_exists(db.clone(), &INTERFACE_MQTT_USERNAME) {
info!("Interface MQTT credentials not found. Generating...");
if !set_external_interface_creds(
db.clone(),
bb_mqtt_same_db,
&web_interface.mqtt_password,
) {
return Err(1);
}
}
for neutron_communicator in neutron_communicators {
if !neutron_communicator.mqtt_password.is_empty()
&& !neutron_communicator.mqtt_username.is_empty()
&& !check_mqtt_user_exists(db.clone(), &neutron_communicator.mqtt_username)
{
if let false = set_neutron_communicator_creds(
db.clone(),
&neutron_communicator.mqtt_username,
&neutron_communicator.mqtt_password,
) {
return Err(1);
}
}
}
} else {
info!("Running BlackBox and MQTT broker on different databases.");
}
// Set all node states to 0
edit_node_state_global(false, db);
}
Err(e) => error!("Database connection failed. {}", e),
}
info!("Database initialization complete.");
match Pool::new(manager_return) {
Ok(pool) => Ok(pool),
Err(e) => {
error!("Could not create PostgreSQL pool, {}", e);
Err(1)
}
}
}
/**
* Queries the database to check if a table exists.
* Returns a boolean true if found.
*/
fn table_exists(table_name: &str, db_conn: Pool<PostgresConnectionManager<NoTls>>) -> bool {
let mut _conn = db_conn.get().unwrap();
let comm = format!("SELECT 1 FROM {} LIMIT 1;", table_name);
let query = _conn.execute(comm.as_str(), &[]);
query.is_ok()
}
/**
* Generates <TABLE_BLACKBOX_NODES>.
*/
fn create_table_nodes(db_conn: Pool<PostgresConnectionManager<NoTls>>) -> bool {
let mut _conn = db_conn.get().unwrap();
let comm = format!(
r"CREATE TABLE {} (
id SERIAL PRIMARY KEY,
identifier TEXT NOT NULL,
name TEXT NOT NULL,
state BOOLEAN NOT NULL
);",
TABLE_BLACKBOX_NODES
);
let query = _conn.execute(comm.as_str(), &[]);
match query {
Ok(_) => true,
Err(e) => {
error!("Failed to create table {}. {}", TABLE_BLACKBOX_NODES, e);
false
}
}
}
/**
* Generates <TABLE_BLACKBOX_ELEMENTS>.
*/
fn create_table_elements(db_conn: Pool<PostgresConnectionManager<NoTls>>) -> bool {
let mut _conn = db_conn.get().unwrap();
let comm = format!(
r"CREATE TABLE {} (
node_identifier TEXT NOT NULL,
address TEXT NOT NULL,
name TEXT NOT NULL,
element_type TEXT NOT NULL,
zone TEXT NOT NULL,
data TEXT NOT NULL
);",
TABLE_BLACKBOX_ELEMENTS
);
let query = _conn.execute(comm.as_str(), &[]);
match query {
Ok(_) => true,
Err(e) => {
error!("Failed to create table {}. {}", TABLE_BLACKBOX_ELEMENTS, e);
false
}
}
}
/**
* Generates <MYSQL_MQTT_USERS_TABLE>.
*/
fn create_table_mqtt_users(db_conn: Pool<PostgresConnectionManager<NoTls>>) -> bool {
let mut _conn = db_conn.get().unwrap();
let comm = format!(
r"CREATE TABLE {} (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL,
password TEXT NOT NULL,
superuser BOOLEAN NOT NULL DEFAULT FALSE
);",
TABLE_MQTT_USERS
);
let query = _conn.execute(comm.as_str(), &[]);
match query {
Ok(_) => true,
Err(e) => {
error!("Failed to create table {}. {}", TABLE_MQTT_USERS, e);
false
}
}
}
/**
* Generates <MYSQL_MQTT_ACL_TABLE>.
*/
fn create_table_mqtt_acl(db_conn: Pool<PostgresConnectionManager<NoTls>>) -> bool {
let mut _conn = db_conn.get().unwrap();
let comm = format!(
r"CREATE TABLE {} (
username TEXT NOT NULL,
topic TEXT NOT NULL,
rw INTEGER NOT NULL
);",
TABLE_MQTT_ACL
);
let query = _conn.execute(comm.as_str(), &[]);
match query {
Ok(_) => true,
Err(e) => {
error!("Failed to create table {}. {}", TABLE_MQTT_ACL, e);
false
}
}
}
/**
* Checks if user exist in <MYSQL_MQTT_USERS_TABLE> table, searching by username. \
* Returns false if user isn't found. \
* Panics if the query wasn't able to run.
*/
fn check_mqtt_user_exists(db_conn: Pool<PostgresConnectionManager<NoTls>>, username: &str) -> bool {
let mut _conn = db_conn.get().unwrap();
let comm = format!(
"SELECT 1 FROM {} WHERE USERNAME='{}' LIMIT 1;",
TABLE_MQTT_USERS, username
);
let res = _conn.query(comm.as_str(), &[]);
match res {
Ok(rows) => {
!rows.is_empty()
}
Err(e) => panic!("Could not check existance of mqtt user. {}", e),
}
}
/**
* TODO: Update the comment
*
* Generates hash from provided password.
* If using_same_db boolean is true, then it gets saved into the shared db(table <MYSQL_MQTT_USERS_TABLE>)
* between BlackBox and Mosquitto.
* Displays Hash and WebInterface MQTT username if we're not on the same db.
* The External Interface account can read-only 'registered' topic and can r/w 'web_interface/#' topic.
* Returns true if successful.
* Handles self error messages.
*/
pub fn set_external_interface_creds(
db_conn: Pool<PostgresConnectionManager<NoTls>>,
using_same_db: bool,
web_interface_mqtt_password: &str,
) -> bool {
let mut _conn = db_conn.get().unwrap();
let hash = generate_mqtt_hash(web_interface_mqtt_password);
if using_same_db {
let query;
if let Ok(q) = _conn.prepare(&format!("INSERT INTO {} (username, topic, rw) VALUES ($1, $2, $3);", &TABLE_MQTT_ACL)) {
query = q;
} else {
error!("Could not prepare WI ACL query.");
return false;
}
// Add external_interface credentials to the users table
if !add_node_to_mqtt_users(db_conn, &INTERFACE_MQTT_USERNAME, &hash) {
return false;
}
// Subscribe r/w to "external_interface/#"
//TODO: Replace this var with a const
let topic_self = "external_interface/#";
if let Err(e) = _conn.query(&query, &[&INTERFACE_MQTT_USERNAME, &topic_self, &MQTT_READ_WRITE]) {
error!("Could not add an ACL entry (self) for external_interface. {}", e);
return false;
}
// For registering to global topic (read/sub)
if let Err(e) = _conn.query(&query, &[&INTERFACE_MQTT_USERNAME, ®ISTERED_TOPIC, &MQTT_READ_ONLY]) {
error!("Could not add an ACL entry (global) for external_interface. {}", e);
return false;
}
if let Err(e) = _conn.query(&query, &[&INTERFACE_MQTT_USERNAME, ®ISTERED_TOPIC, &MQTT_SUBSCRIBE_ONLY]) {
error!("Could not add an ACL entry (global) for external_interface. {}", e);
return false;
}
// For registering to the NECO topic (write)
if let Err(e) = _conn.query(&query, &[&INTERFACE_MQTT_USERNAME, &NEUTRONCOMMUNICATOR_TOPIC, &MQTT_WRITE_ONLY]) {
error!("Could not add an ACL entry (NECO) for external_interface. {}", e);
return false;
}
// For registering to the NECO ids topic (write)
if let Err(e) = _conn.query(&query, &[&INTERFACE_MQTT_USERNAME, &[NEUTRONCOMMUNICATOR_TOPIC, "/#"].concat(), &MQTT_WRITE_ONLY]) {
error!("Could not add an ACL entry (NECO) for external_interface. {}", e);
return false;
}
} else {
warn!(
"External interface Credentials: Hash: {} | Username: {}",
hash, INTERFACE_MQTT_USERNAME
);
}
true
}
/**
* Generates hash from provided password.
* If using_same_db boolean is true, then it gets saved into the shared db(table <MYSQL_MQTT_USERS_TABLE>)
* between BlackBox and Mosquitto.
* Displays Hash and BlackBox MQTT username if we're not on the same db.
* Returns true if successful.
* Handles self error messages.
*/
pub fn set_mqtt_bb_creds(
db_conn: Pool<PostgresConnectionManager<NoTls>>,
using_same_db: bool,
bb_mqtt_password: &str,
) -> bool {
let mut _conn = db_conn.get().unwrap();
let hash = generate_mqtt_hash(bb_mqtt_password);
if using_same_db {
let query1 = format!(
"DELETE FROM mqtt_users WHERE USERNAME='{}';",
BLACKBOX_MQTT_USERNAME
);
match _conn.execute(query1.as_str(), &[]) {
Ok(_) => {}
Err(e) => {
error!(
"Couldn't make sure that there is only one user for BlackBox. {}",
e
);
return false;
}
}
let query2 = format!(
"INSERT INTO {} (username, password, superuser)
VALUES ($1, $2, $3);",
&TABLE_MQTT_USERS,
);
match _conn.execute(query2.as_str(), &[&BLACKBOX_MQTT_USERNAME, &hash, &true]) {
Ok(_) => {
debug!(
"BlackBox MQTT user credentials inserted. Hashed: {} Length: {}",
&hash,
&hash.len()
);
}
Err(e) => {
error!(
"Could not add BlackBox credentials to table: {}. {}",
&TABLE_MQTT_USERS, e
);
return false;
}
}
} else {
warn!(
"MQTT Credentials for BlackBox: Hash: {} | Username: {}",
hash, BLACKBOX_MQTT_USERNAME
);
}
true
}
/**
* Adds the neutron communicator credentials to the mqtt_users and mqtt_acl tables.
*/
pub fn set_neutron_communicator_creds(
db_conn: Pool<PostgresConnectionManager<NoTls>>,
username: &str,
password: &str,
) -> bool {
let mut _conn = db_conn.get().unwrap();
let query;
if let Ok(q) = _conn.prepare(&format!("INSERT INTO {} (username, topic, rw) VALUES ($1, $2, $3);", TABLE_MQTT_ACL)) {
query = q;
} else {
error!("Could not prepare NECO ACL query.");
return false;
}
let hash = generate_mqtt_hash(password);
// Add external_interface credentials to the users table
if !add_node_to_mqtt_users(db_conn, username, &hash) {
return false;
}
// Subscribe r/w to "neutron_communicators/[username]"
let topic_self = "neutron_communicators/%u";
if let Err(e) = _conn.query(&query, &[&username, &topic_self, &MQTT_READ_WRITE]) {
error!("Could not add an ACL entry for NECO. Topic: {} Error: {}", topic_self, e);
return false;
}
// Subscribe r-only to "neutron_communicators"
if let Err(e) = _conn.query(&query, &[&username, &NEUTRONCOMMUNICATOR_TOPIC, &MQTT_READ_ONLY]) {
error!("Could not add an ACL entry for NECO. Topic: {} Error: {}", NEUTRONCOMMUNICATOR_TOPIC, e);
return false;
}
if let Err(e) = _conn.query(&query, &[&username, &NEUTRONCOMMUNICATOR_TOPIC, &MQTT_SUBSCRIBE_ONLY]) {
error!("Could not add an ACL entry for NECO. Topic: {} Error: {}", NEUTRONCOMMUNICATOR_TOPIC, e);
return false;
}
// Subscribe write-only to "external_interface"
if let Err(e) = _conn.query(&query, &[&username, &INTERFACE_MQTT_USERNAME, &MQTT_WRITE_ONLY]) {
error!("Could not add an ACL entry for NECO. Topic: {} Error: {}", INTERFACE_MQTT_USERNAME, e);
return false;
}
true
}
/**
* Should be called with enable_discovery = false on BlackBox startup!
* Adds or removes unregistered nodes MQTT credentials and ACL entries.
* Generates a table <TABLE_BLACKBOX_UNREGISTERED> used for saving unregistered node information(client_id, element_summary).
* Returns true is successful.
*/
pub fn set_discovery_mode(
enable_discovery: bool,
mqtt_unregistered_pass: &str,
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
mqtt_cli: Option<&crate::mqtt::AsyncClient>,
) -> bool {
if enable_discovery {
if let Some(cli) = mqtt_cli {
cli.subscribe(TOPICS[1], QOS[1]);
}
let mqtt_users = add_node_to_mqtt_users(
conn_pool.clone(),
MQTT_USERNAME_UNREGISTERED,
&generate_mqtt_hash(mqtt_unregistered_pass),
);
let mqtt_acl = add_node_to_mqtt_acl(conn_pool.clone(), true, MQTT_USERNAME_UNREGISTERED);
if mqtt_users && mqtt_acl {
// Try to drop the table just in case
let query = format!(
"SET client_min_messages = ERROR; DROP TABLE IF EXISTS {};",
TABLE_BLACKBOX_UNREGISTERED
);
let mut conn = conn_pool.get().unwrap();
conn.batch_execute(&query).unwrap();
// Create a new table for unregistered nodes
let mut _conn = conn_pool.get().unwrap();
let query = format!(
r"CREATE TABLE {} (
client_id TEXT PRIMARY KEY NOT NULL,
elements_summary TEXT NOT NULL
);",
TABLE_BLACKBOX_UNREGISTERED
);
let res = _conn.execute(query.as_str(), &[]);
match res {
Ok(_) => {}
Err(e) => error!("Failed to create unregistered node table. {}", e),
}
warn!("DISCOVERY ENABLED.");
} else {
error!("Could not enable discovery.");
if !mqtt_users {
error!("Unable to add unregistered credentials.");
}
if !mqtt_acl {
error!("Unable to add unregistered ACL entries.");
}
return false;
}
} else {
if let Some(cli) = mqtt_cli {
cli.unsubscribe(TOPICS[1]);
}
let mqtt_users = remove_from_mqtt_users(conn_pool.clone(), MQTT_USERNAME_UNREGISTERED);
let mqtt_acl = remove_node_from_mqtt_acl(conn_pool.clone(), MQTT_USERNAME_UNREGISTERED);
if mqtt_users && mqtt_acl {
// Drop the <TABLE_BLACKBOX_UNREGISTERED>
let query = format!(
"SET client_min_messages = ERROR; DROP TABLE IF EXISTS {};",
TABLE_BLACKBOX_UNREGISTERED
);
let mut conn = conn_pool.get().unwrap();
conn.batch_execute(&query).unwrap();
info!("DISCOVERY DISABLED.");
}
}
true
}
/**
* Adds an entry to the <TABLE_BLACKBOX_UNREGISTERED>.
* If a row already exists with the same client_id, a new one isn't added.
* Returns true if successful.
*/
pub fn add_to_unregistered_table(
client_id: &str,
elements_summary: &str,
db_pool: Pool<PostgresConnectionManager<NoTls>>,
) -> bool {
let mut conn = db_pool.get().unwrap();
let query = format!(
"INSERT INTO {} (client_id, elements_summary)
VALUES ($1, $2) ON CONFLICT (client_id) DO NOTHING;",
&TABLE_BLACKBOX_UNREGISTERED
);
let res = conn.execute(query.as_str(), &[&client_id, &elements_summary]);
match res {
Ok(res) => {
if res > 0 {
debug!(
"Unregistered node listed. Client_id: {} Elements_Summary: {}",
&client_id, &elements_summary
);
} else {
debug!("Unregistered node probably exists. {}", &client_id);
return false;
}
}
Err(e) => {
error!("Could not list unregistered node to table. {}", e);
return false;
}
}
true
}
/**
* Removes rows matching client_id from <TABLE_BLACKBOX_UNREGISTERED>.
* Returns true if successful.
*/
pub fn remove_from_unregistered_table(
client_id: &str,
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!(
"DELETE FROM {} WHERE CLIENT_ID = $1;",
&TABLE_BLACKBOX_UNREGISTERED
);
let res = conn.execute(query.as_str(), &[&client_id]);
match res {
Ok(res) => {
if res > 0 {
debug!("Unregistered node removed. Client_ID: {}.", &client_id);
} else {
debug!("Unregistered not removed. Client_ID: {}.", &client_id);
return false;
}
}
Err(_) => {
/*error!(
"Could not remove listing of unregistered node from table. Node_ID: {}. {}",
&client_id, e
);*/
return false;
}
}
true
}
// /**
// * Returns The contents of <TABLE_BLACKBOX_UNREGISTERED> as Result.
// * If empty, returns 1.
// */
// pub fn get_unregistered_table(
// conn_pool: Pool<PostgresConnectionManager<NoTls>>,
// ) -> Result<Vec<UnregisteredNodeItem>, i8> {
// let mut conn = conn_pool.get().unwrap();
// let query = format!("SELECT * FROM {};", TABLE_BLACKBOX_UNREGISTERED);
// let res = conn.query(&query, &[]);
// /*let result: Vec<UnregisteredNodeItem> = query.map(|result| {
// result
// .map(|x| x.unwrap())
// .map(|row| {
// unimplemented!();
// /*let (client_id, elements_summary) = postgres::Result(row);
// UnregisteredNodeItem {
// client_id,
// elements_summary,
// }*/
// }).collect()
// })?;*/
// let mut result: Vec<UnregisteredNodeItem> = Vec::new();
// for row in res.unwrap().iter() {
// result.push(UnregisteredNodeItem {
// client_id: row.get("client_id"),
// elements_summary: row.get("elements_summary"),
// });
// }
// if result.is_empty() {
// return Err(1);
// }
// Ok(result)
// }
/**
* Creates a new MQTT user entry for <username> with <hash> and adds to the <TABLE_MQTT_USERS>. \
* Returns true if no error was encountered.
*/
pub fn add_node_to_mqtt_users(
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
username: &str,
hash: &str,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!(
"INSERT INTO {} (username, password, superuser)
VALUES ($1, $2, $3);",
&TABLE_MQTT_USERS
);
let res = conn.execute(query.as_str(), &[&username, &hash, &false]);
match res {
Ok(res) => {
if res > 0 {
debug!(
"MQTT user inserted. Hashed: {} Length: {}",
&hash,
&hash.len()
);
} else {
debug!(
"MQTT user was not inserted. Affected rows: 0. Username: {}",
&username
);
}
}
Err(e) => {
error!("Could not add credentials to mqtt_users. {}", e);
return false;
}
}
true
}
/**
* Removes MQTT USERS entry from the <TABLE_MQTT_USERS> with the provided username. \
* Returns true if successful.
*/
pub fn remove_from_mqtt_users(conn_pool: Pool<PostgresConnectionManager<NoTls>>, username: &str) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!("DELETE FROM {} WHERE USERNAME = $1;", &TABLE_MQTT_USERS);
let res = conn.execute(query.as_str(), &[&username]);
match res {
Ok(res) => {
if res > 0 {
debug!("MQTT account removed. Node Username: {}.", &username);
} else {
debug!(
"MQTT account removal was unsuccessful. Rows affected: 0. Username: {}",
&username
);
}
}
Err(e) => {
error!(
"Could not remove MQTT account. Node Username: {}. {}",
&username, e
);
return false;
}
}
true
}
/**
* Creates new MQTT ACL entries for <username> to table <TABLE_MQTT_ACL>. \
* ```unregistered - if the entry is for an unregistered or a registered node```. \
* Returns true if a row was successfully inserted.
*/
pub fn add_node_to_mqtt_acl(
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
unregistered: bool,
username: &str,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let mut _conn = conn_pool.get().unwrap();
// Allows the node to subscribe and publish to "registered/<username> || unregistered/<client_id>"
let topic_self = if unregistered {
"unregistered/%c"
} else {
"registered/%u"
};
// And to only subscribe to "registered" || "unregistered"
let topic_global = if unregistered {
"unregistered"
} else {
"registered"
};
// For registering to self topic (read/write)
let query = format!(
"INSERT INTO {} (username, topic, rw)
VALUES ($1, $2, $3);",
&TABLE_MQTT_ACL
);
let res = conn.execute(query.as_str(), &[&username, &topic_self, &MQTT_READ_WRITE]);
match res {
Ok(res) => {
if res > 0 {
debug!("New ACL entry (self). Node Username: {}.", &username);
} else {
debug!(
"New ACL entry (self) unsuccessful. Rows affected: 0. Node Username: {} ",
&username
);
return false;
}
}
Err(e) => {
error!(
"Could not add a new ACL entry (self). Node Username: {}. {}",
&username, e
);
return false;
}
}
//
// For registering to global(listen only)
let query = format!(
"INSERT INTO {} (username, topic, rw)
VALUES ($1, $2, $3);",
&TABLE_MQTT_ACL
);
let _res = _conn.execute(query.as_str(), &[&username, &topic_global, &MQTT_SUBSCRIBE_ONLY]);
let res = _conn.execute(query.as_str(), &[&username, &topic_global, &MQTT_READ_ONLY]);
match res {
Ok(res) => {
if res > 0 {
debug!("New ACL entry (global). Node Username: {}.", &username);
} else {
debug!(
"New ACL entry (global) unsuccessful. Rows affected: 0. Node Username: {} ",
&username
);
return false;
}
}
Err(e) => {
error!(
"Could not add a new ACL entry (global). Node Username: {}. {}",
&username, e
);
return false;
}
}
true
}
/**
* Removes ACL entries from the <TABLE_MQTT_ACL> with the provided username.
* Returns true if succeded.
*/
pub fn remove_node_from_mqtt_acl(
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
username: &str,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!("DELETE FROM {} WHERE USERNAME = $1;", &TABLE_MQTT_ACL);
let res = conn.execute(query.as_str(), &[&username]);
match res {
Ok(res) => {
if res > 0 {
debug!("ACL entries removed. Node Username: {}.", &username);
} else {
debug!(
"ACL entry removal unsuccessful. Rows affected: 0. Node Username: {}.",
&username
);
}
}
Err(e) => {
error!(
"Could not remove ACL entries. Node Username: {}. {}",
&username, e
);
return false;
}
}
true
}
/**
* Creates a new registered node entry to the <TABLE_BLACKBOX_NODES>.
* Returns true if a row was successfully inserted.
*/
pub fn add_node_to_node_table(conn_pool: Pool<PostgresConnectionManager<NoTls>>, node: Node) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!(
"INSERT INTO {} (identifier, name, state)
VALUES ($1, $2, $3);",
&TABLE_BLACKBOX_NODES
);
let res = conn.execute(
query.as_str(),
&[
&node.identifier,
&node.name,
&node.state,
],
);
match res {
Ok(res) => {
if res > 0 {
debug!(
"Added a new node to node_table. Node_ID: {}.",
&node.identifier
);
} else {
debug!(
"Adding a new node to node_table unsuccessful. Rows affected: 0. Node_ID: {}.",
&node.identifier
);
return false;
}
}
Err(e) => {
error!(
"Could not add a new entry to node_table. Node_ID: {}. {}",
&node.identifier, e
);
return false;
}
}
true
}
/**
* Removes Node from the <TABLE_BLACKBOX_NODES> with the provided node_identifier.
* Returns true if succeded.
*/
pub fn remove_node_from_node_table(
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
node_identifier: &str,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!(
"DELETE FROM {} WHERE identifier = $1;",
&TABLE_BLACKBOX_NODES
);
let res = conn.execute(query.as_str(), &[&node_identifier]);
match res {
Ok(res) => {
if res > 0 {
debug!(
"Node removed from database table: {}. Node_ID: {}.",
&TABLE_BLACKBOX_NODES, &node_identifier
);
} else {
debug!("Node removal from database table unsuccessful. Rows affected: 0. Table: {}. Node_ID: {}.",
&TABLE_BLACKBOX_NODES, &node_identifier
);
}
}
Err(e) => {
error!("Could not remove Node_ID: {}. {}", &node_identifier, e);
return false;
}
}
true
}
// /**
// * Returns Node from <TABLE_BLACKBOX_NODES> with the provided node_identifier (the first one it finds).
// * If no nodes found, returns 1.
// */
// pub fn get_node_from_node_table(
// node_identifier: &str,
// conn_pool: Pool<PostgresConnectionManager<NoTls>>,
// ) -> Result<Node, i8> {
// let mut conn = conn_pool.get().unwrap();
// let query = format!(
// "SELECT * FROM {} WHERE identifier = $1;",
// TABLE_BLACKBOX_NODES
// );
// let res = conn.query(&query, &[&node_identifier]);
// /*let result: Vec<Node> = query.map(|result| {
// result
// .map(|x| x.unwrap())
// .map(|row| {
// unimplemented!();
// let (id, identifier, name, category, elements_summary, state) =
// postgres::from_row(row);
// Node {
// id,
// identifier,
// name,
// category,
// elements_summary,
// state,
// }
// }).collect()
// })?;*/
// let mut result: Node = Node {
// id: 0,
// identifier: "".to_string(),
// name: "".to_string(),
// category: "".to_string(),
// elements_summary: "".to_string(),
// state: false,
// };
// let mut num: i8 = 0;
// for row in res.unwrap().iter() {
// num = 1;
// result = Node {
// id: row.get("id"),
// identifier: row.get("identifier"),
// name: row.get("name"),
// category: row.get("category"),
// elements_summary: row.get("elements_summary"),
// state: row.get("state"),
// };
// // We only need one so break loop if we have it
// break;
// }
// if num == 0 {
// return Err(1);
// }
// Ok(result)
// }
/**
* Fetching Node/Element list for sending to External Interface
*
* Consists of two queries to two tables, then it combines them into one struct and is then returned as an Option
*/
pub fn get_node_element_list(
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
) -> Option<Vec<NodeFiltered>> {
let mut conn = conn_pool.get().unwrap();
let query_nodes = format!(
"SELECT identifier, name, state FROM {};",
TABLE_BLACKBOX_NODES
);
let query_result_nodes = conn.query(query_nodes.as_str(), &[]);
let query_elements = format!(
"SELECT node_identifier, address, name, element_type, zone, data FROM {};",
TABLE_BLACKBOX_ELEMENTS
);
let query_result_elements = conn.query(query_elements.as_str(), &[]);
let mut element_filtered_list: Vec<ElementsFiltered> = Vec::new();
match query_result_elements {
Ok(rows) => {
for row in rows.iter() {
element_filtered_list.push(ElementsFiltered {
node_identifier: row.get("node_identifier"),
address: row.get("address"),
name: row.get("name"),
element_type: row.get("element_type"),
zone: row.get("zone"),
data: row.get("data")
})
}
}
Err(e) => warn!("Could not get element list from database. {}", e),
}
let mut node_filtered_list: Vec<NodeFiltered> = Vec::new();
match query_result_nodes {
Ok(rows_nodes) => {
for row_node in rows_nodes.iter() {
let node_identifier: String = row_node.get("identifier");
let mut _elements: Vec<ElementsFiltered> = Vec::new();
for elem in element_filtered_list.clone().iter() {
if elem.node_identifier == node_identifier {
_elements.push(elem.clone());
}
}
node_filtered_list.push(NodeFiltered {
identifier: node_identifier,
name: row_node.get("name"),
state: row_node.get("state"),
elements: _elements,
})
}
Some(node_filtered_list)
}
Err(e) => {
warn!("Could not get node list from database. {}", e);
None
}
}
}
/**
* Returns a list of Nodes from <TABLE_BLACKBOX_NODES> with their identifiers and state.
* If no entries found, returns 1.
*/
// pub fn get_states_from_node_table(
// conn_pool: Pool<PostgresConnectionManager<NoTls>>,
// ) -> Result<Vec<NodeState>, i8> {
// let mut conn = conn_pool.get().unwrap();
// let query = format!("SELECT identifier, state FROM {};", TABLE_BLACKBOX_NODES);
// let res = conn.query(&query, &[]);
// /*let result: Vec<NodeState> = query.map(|result| {
// result
// .map(|x| x.unwrap())
// .map(|row| {
// unimplemented!();
// /*
// let (identifier, state) = postgres::from_row(row);
// NodeState {
// identifier,
// state,
// }*/
// }).collect()
// })?;
// if result.is_empty() {
// return Err(postgres::Error::IoError(io::Error::new(
// io::ErrorKind::Other,
// "No items to return",
// )));
// }*/
// let mut result: Vec<NodeState> = Vec::new();
// for row in res.unwrap().iter() {
// result.push(NodeState {
// identifier: row.get("identifier"),
// state: row.get("state"),
// });
// }
// if result.is_empty() {
// return Err(1);
// }
// Ok(result)
// }
/**
* Sets the state column in the <TABLE_BLACKBOX_NODES> with the provided new_state to row matching node_identifier.
* Returns true if successful.
*/
pub fn edit_node_state(
node_identifier: &str,
new_state: bool,
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!(
"UPDATE {} SET state = $1 WHERE identifier = $2;",
TABLE_BLACKBOX_NODES
);
let res = conn.execute(query.as_str(), &[&new_state, &node_identifier]);
match res {
Ok(res) => {
if res > 0 {
debug!(
"Node state changed to: {}. Node_ID: {}.",
&new_state, &node_identifier
);
} else {
debug!(
"Node state was not changed. Rows affected: 0. Node_ID: {}.",
&node_identifier
);
return false;
}
}
Err(e) => {
error!(
"Could not change state. Node_ID: {} state. {}",
node_identifier, e
);
return false;
}
}
true
}
/**
* Sets the state column for each row in the <TABLE_BLACKBOX_NODES> with the provided new_state.
* Returns true if query was successful.
*/
pub fn edit_node_state_global(new_state: bool, conn_pool: Pool<PostgresConnectionManager<NoTls>>) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!("UPDATE {} SET state = $1;", TABLE_BLACKBOX_NODES);
let res = conn.execute(query.as_str(), &[&new_state]);
match res {
Ok(res) => {
if res > 0 {
debug!("Node states changed globally to: {}.", new_state);
} else {
debug!("Node states was not changed globally. Rows affected: 0");
return false;
}
}
Err(e) => {
error!("Could not change global node state. {}", e);
return false;
}
}
true
}
/**
* Using the provided information from ```node``` parameter
*
* Updates the name column of the row matching the node identifier and address in the <TABLE_BLACKBOX_ELEMENTS>.
*
* Returns true if successful.
*/
pub fn edit_node_info(node: NodeInfoEdit, conn_pool: Pool<PostgresConnectionManager<NoTls>>) -> bool {
let mut conn = conn_pool.get().unwrap();
let mut successful = true;
let query = format!(
"UPDATE {} SET NAME = $1 WHERE identifier = $2;",
TABLE_BLACKBOX_NODES
);
let res = conn.execute(query.as_str(), &[&node.name, &node.identifier]);
for element in node.elements {
let query = format!(
"UPDATE {} SET NAME = $1, ZONE = $2 WHERE (node_identifier = $3 AND address = $4);",
TABLE_BLACKBOX_ELEMENTS
);
let res = conn.execute(query.as_str(), &[&element.name, &element.zone, &node.identifier, &element.address]);
match res {
Ok(res) => {
if res > 0 {
debug!(
"Element info changed. Node_ID: {}. Element address: {}",
node.identifier, element.address
);
} else {
debug!("Element info was not updated. Rows affected: 0. Node_ID: {}. Element address: {}", node.identifier, element.address);
}
}
Err(e) => {
error!(
"Could not change element info. Node_ID: {}. Element address: {}. {}",
node.identifier, element.address, e
);
successful = false;
}
}
}
match res {
Ok(res) => {
if res > 0 {
debug!("Node info changed. Node_ID: {}.", node.identifier);
} else {
debug!(
"Node info was not updated. Rows affected: 0. Node_ID: {}.",
node.identifier
);
}
}
Err(e) => {
error!(
"Could not change node info. Node_ID: {}. {}",
node.identifier, e
);
successful = false;
}
}
successful
}
/**
* Goes through a list of Elements and adds each to <TABLE_BLACKBOX_ELEMENTS>.
*/
pub fn add_elements_to_element_table(
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
elements: Vec<Element>,
) -> bool {
let mut conn = conn_pool.get().unwrap();
for element in elements {
let query = format!(
"INSERT INTO {} (node_identifier, address, name, element_type, zone, data)
VALUES ($1, $2, $3, $4, $5, $6);",
&TABLE_BLACKBOX_ELEMENTS
);
let res = conn.execute(
query.as_str(),
&[
&element.node_identifier,
&element.address,
&element.name,
&element.element_type.to_string(),
&element.zone,
&element.data,
],
);
match res {
Ok(res) => {
if res > 0 {
debug!(
"Added a new element from Node_ID: {:?} to database table. Element type: {}.",
&element.node_identifier,
&element.element_type.to_string()
);
}
}
Err(e) => {
error!(
"Could not add element from Node_ID: {:?} to database table. {}",
&element.node_identifier, e
);
return false;
}
}
}
true
}
/**
* Removes all elements from <TABLE_BLACKBOX_ELEMENTS> matching node_id.
*/
pub fn remove_elements_from_elements_table(
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
node_id: &str,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!(
"DELETE FROM {} WHERE node_identifier = $1;",
TABLE_BLACKBOX_ELEMENTS
);
let res = conn.execute(query.as_str(), &[&node_id]);
match res {
Ok(res) => {
if res > 0 {
debug!("Elements removed. Node_ID: {}.", &node_id);
}
}
Err(e) => {
error!("Could not remove Elements. Node_ID: {}. {}", &node_id, e);
return false;
}
}
true
}
/**
* Edits element data of the specified row matching element_address and node_identifier. In <TABLE_BLACKBOX_ELEMENTS>.
*/
pub fn edit_element_data_from_element_table(
node_identifier: &str,
element_address: &str,
data: &str,
conn_pool: Pool<PostgresConnectionManager<NoTls>>,
) -> bool {
let mut conn = conn_pool.get().unwrap();
let query = format!(
"UPDATE {} SET DATA = $1 WHERE node_identifier = $2 AND ADDRESS = $3;",
TABLE_BLACKBOX_ELEMENTS
);
let res = conn.execute(query.as_str(), &[&data, &node_identifier, &element_address]);
match res {
Ok(res) => {
if res > 0 {
debug!(
"Element data changed to: {}. Node_ID: {} Address: {}.",
&data, &node_identifier, &element_address
);
}
}
Err(e) => {
error!(
"Could not change Node_ID: {} Address: {} data. {}",
&node_identifier, &element_address, e
);
return false;
}
}
true
}
// /**
// * Removes any tables that BlackBox uses.
// */
// pub fn sanitize_db_from_blackbox(db_pool: Pool<PostgresConnectionManager<NoTls>>) {
// let mut conn = db_pool.get().unwrap();
// let query = format!(
// "DROP TABLE IF EXISTS {}, {}, {};",
// TABLE_BLACKBOX_UNREGISTERED, TABLE_BLACKBOX_NODES, TABLE_BLACKBOX_ELEMENTS
// );
// conn.execute(query.as_str(), &[]).unwrap();
// }
// /**
// * Removes any tables that were made for Mosquitto.
// */
// pub fn sanitize_db_from_mosquitto(db_pool: Pool<PostgresConnectionManager<NoTls>>) {
// let mut conn = db_pool.get().unwrap();
// let query = format!(
// "DROP TABLE IF EXISTS {}, {};",
// TABLE_MQTT_USERS, TABLE_MQTT_ACL
// );
// conn.execute(query.as_str(), &[]).unwrap();
// }
|
#[macro_use]
extern crate rbatis_macro_driver;
use std::os::raw::c_char;
use async_std::task::block_on;
use rbatis::rbatis::Rbatis;
use rbatis::crud::{CRUD, CRUDTable};
use chrono::NaiveDateTime;
use rbatis_core::value::DateTimeNow;
use std::ops::Add;
use serde::{Deserialize, Serialize};
use shared::to_str;
#[derive(CRUDTable, Serialize, Deserialize, Clone, Debug)]
pub struct BizActivity {
pub id: Option<String>,
pub name: Option<String>,
pub pc_link: Option<String>,
pub h5_link: Option<String>,
pub pc_banner_img: Option<String>,
pub h5_banner_img: Option<String>,
pub sort: Option<String>,
pub status: Option<i32>,
pub remark: Option<String>,
pub create_time: Option<NaiveDateTime>,
pub version: Option<i32>,
pub delete_flag: Option<i32>,
}
async fn init_rbatis(db_file_name: &str) -> Rbatis {
log::info!("init_rbatis");
if std::fs::metadata(db_file_name).is_err() {
let file = std::fs::File::create(db_file_name);
if file.is_err() {
log::info!("{:?}",file.err().unwrap());
}
}
let rb = Rbatis::new();
let url = "sqlite://".to_owned().add(db_file_name);
log::info!("{:?}",url);
let r = rb.link(url.as_str()).await;
if r.is_err() {
log::info!("{:?}",r.err().unwrap());
}
return rb;
}
#[no_mangle]
pub extern "C" fn tryRbatis(name: *mut c_char) {
#[cfg(target_os = "android")]shared::init_logger_once();
log::info!("start");
let rb = block_on(init_rbatis(to_str(name)));
let sql = "\
CREATE TABLE `biz_activity` (
`id` varchar(50) NOT NULL DEFAULT '',
`name` varchar(255) NOT NULL,
`pc_link` varchar(255) DEFAULT NULL,
`h5_link` varchar(255) DEFAULT NULL,
`sort` varchar(255) NOT NULL ,
`status` int(11) NOT NULL ,
`version` int(11) NOT NULL,
`remark` varchar(255) DEFAULT NULL,
`create_time` datetime NOT NULL,
`delete_flag` int(1) NOT NULL,
`pc_banner_img` varchar(255) DEFAULT NULL,
`h5_banner_img` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`) ) ;";
let r = block_on(rb.exec("", sql));
if r.is_err() {
log::info!("{:?}",r.err().unwrap());
}
let activity = BizActivity {
id: Some("12312".to_string()),
name: Some("123".to_string()),
pc_link: None,
h5_link: None,
pc_banner_img: None,
h5_banner_img: None,
sort: Some("1".to_string()),
status: Some(1),
remark: None,
create_time: Some(NaiveDateTime::now()),
version: Some(1),
delete_flag: Some(1),
};
let r = block_on(rb.save("", &activity));
if r.is_err() {
log::info!("{:?}",r.err().unwrap());
}
let sql = "select count(*) from biz_activity";
let r = block_on(rb.exec("", sql));
match r {
Ok(a) => {
log::info!("{:?}",a);
}
Err(e) => {
log::info!("{:?}",e);
}
}
}
#[cfg(test)]
mod tests {
use crate::tryRbatis;
#[test]
fn rbatis_test() {
let url = shared::to_c_char("orm_rbatis.db");
tryRbatis(url);
shared::Str_free(url);
}
}
|
/*
* Given an integer, write a function to determine if it is a power of two.
*
* Examples:
* ----------
* Input: 1
* Output: true
*
* Input: 16
* Output: true
*
* Input: 218
* Output: false
*/
pub fn is_power_of_two(n: i32) -> bool {
if n <= 0 {
return false
}
return (n & (n-1)) == 0
}
#[cfg(test)]
mod test {
use super::is_power_of_two;
#[test]
fn example1() {
let input = 1;
assert_eq!(is_power_of_two(input), true);
}
#[test]
fn example2() {
let input = 16;
assert_eq!(is_power_of_two(input), true);
}
#[test]
fn example3() {
let input = 3;
assert_eq!(is_power_of_two(input), false);
}
#[test]
fn example4() {
let input = 218;
assert_eq!(is_power_of_two(input), false);
}
#[test]
fn example5() {
let input = 32;
assert_eq!(is_power_of_two(input), true);
}
#[test]
fn example6() {
let input = 100000;
assert_eq!(is_power_of_two(input), false);
}
#[test]
fn example7() {
let input = 2048;
assert_eq!(is_power_of_two(input), true);
}
#[test]
fn example8() {
let input = 6;
assert_eq!(is_power_of_two(input), false);
}
#[test]
fn example9() {
let input = 9;
assert_eq!(is_power_of_two(input), false);
}
#[test]
fn example10() {
let input = 64;
assert_eq!(is_power_of_two(input), true);
}
#[test]
fn example11() {
let input = 48;
assert_eq!(is_power_of_two(input), false);
}
#[test]
fn example12() {
let input = 256;
assert_eq!(is_power_of_two(input), true);
}
#[test]
fn example13() {
let input = -16;
assert_eq!(is_power_of_two(input), false);
}
}
|
extern crate specs;
use specs::{Component, VecStorage};
#[derive(Debug)]
struct Position {
x: f32,
y: f32
}
impl Component for Position {
type Storage = VecStorage<Self>;
}
#[macro_use]
extern crate specs_derive;
#[derive(Debug, Component)]
#[component(VecStorage)]
struct Velocity {
x: f32,
y: f32,
}
use specs::{System, Join, WriteStorage, ReadStorage, Entities};
struct PhysicsSystem;
impl<'a> System<'a> for PhysicsSystem {
type SystemData = (WriteStorage<'a, Position>, ReadStorage<'a, Velocity>);
fn run(&mut self, (mut positions, velocities): Self::SystemData) {
for (position, velocity) in (&mut positions, &velocities).join() {
position.x += velocity.x;
position.y += velocity.y;
}
}
}
struct RenderSystem;
impl<'a> System<'a> for RenderSystem {
type SystemData = (Entities<'a>, ReadStorage<'a, Position>);
fn run(&mut self, (entities, positions): Self::SystemData) {
for (entity, position) in (&*entities, &positions).join() {
println!("Entity {e} at ({x}, {y})", e = entity.id(), x = position.x, y = position.y);
}
}
}
use specs::{DispatcherBuilder, World};
fn main() {
let mut world = World::new();
world.register::<Position>();
world.register::<Velocity>();
world.create_entity()
.with(Position { x: 0., y: 0. })
.build();
world.create_entity()
.with(Position { x: 1., y: 0. })
.with(Velocity { x: 0.1, y: 0.1 })
.build();
let mut dispatcher = DispatcherBuilder::new()
.add(PhysicsSystem, "physics", &[])
.add(RenderSystem, "render", &["physics"])
.build();
loop {
dispatcher.dispatch(&mut world.res);
}
}
|
use bigneon_db::dev::TestProject;
use bigneon_db::models::{
DisplayTicket, EventEditableAttributes, Order, RedeemResults, TicketInstance, Wallet,
};
use chrono::prelude::*;
use chrono::NaiveDateTime;
use diesel;
use diesel::result::Error;
use diesel::sql_types;
use diesel::Connection;
use diesel::RunQueryDsl;
use time::Duration;
use uuid::Uuid;
#[test]
pub fn find_for_user_for_display() {
let project = TestProject::new();
let connection = project.get_connection();
let organization = project
.create_organization()
.with_fee_schedule(&project.create_fee_schedule().finish())
.finish();
let event = project
.create_event()
.with_organization(&organization)
.with_event_start(&NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11))
.with_tickets()
.with_ticket_pricing()
.finish();
let event2 = project
.create_event()
.with_organization(&organization)
.with_event_start(&NaiveDate::from_ymd(2017, 7, 8).and_hms(9, 10, 11))
.with_tickets()
.with_ticket_pricing()
.finish();
let user = project.create_user().finish();
let mut cart = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type = &event.ticket_types(connection).unwrap()[0];
let ticket_type2 = &event2.ticket_types(connection).unwrap()[0];
let mut ticket_ids: Vec<Uuid> = cart
.add_tickets(ticket_type.id, 2, connection)
.unwrap()
.into_iter()
.map(|t| t.id)
.collect();
ticket_ids.sort();
let mut ticket_ids2: Vec<Uuid> = cart
.add_tickets(ticket_type2.id, 2, connection)
.unwrap()
.into_iter()
.map(|t| t.id)
.collect();
ticket_ids2.sort();
// Order is not paid so tickets are not accessible
assert!(
TicketInstance::find_for_user_for_display(user.id, Some(event.id), None, None, connection)
.unwrap()
.is_empty()
);
// Order is paid, tickets returned
let total = cart.calculate_total(connection).unwrap();
cart.add_external_payment("test".to_string(), user.id, total, connection)
.unwrap();
let mut found_ticket_ids: Vec<Uuid> =
TicketInstance::find_for_user_for_display(user.id, Some(event.id), None, None, connection)
.unwrap()
.iter()
.flat_map(move |(_, tickets)| tickets.iter())
.map(|t| t.id)
.collect();
found_ticket_ids.sort();
assert_eq!(found_ticket_ids, ticket_ids);
// other event
let mut found_ticket_ids: Vec<Uuid> =
TicketInstance::find_for_user_for_display(user.id, Some(event2.id), None, None, connection)
.unwrap()
.iter()
.flat_map(move |(_, tickets)| tickets.iter())
.map(|t| t.id)
.collect();
found_ticket_ids.sort();
assert_eq!(found_ticket_ids, ticket_ids2);
// no event specified
let mut all_ticket_ids = ticket_ids.clone();
all_ticket_ids.append(&mut ticket_ids2.clone());
all_ticket_ids.sort();
let mut found_ticket_ids: Vec<Uuid> =
TicketInstance::find_for_user_for_display(user.id, None, None, None, connection)
.unwrap()
.iter()
.flat_map(move |(_, tickets)| tickets.iter())
.map(|t| t.id)
.collect();
found_ticket_ids.sort();
assert_eq!(found_ticket_ids, all_ticket_ids);
// start date prior to both event starts
let mut found_ticket_ids: Vec<Uuid> = TicketInstance::find_for_user_for_display(
user.id,
None,
Some(NaiveDate::from_ymd(2015, 7, 8).and_hms(9, 0, 11)),
None,
connection,
).unwrap()
.iter()
.flat_map(move |(_, tickets)| tickets.iter())
.map(|t| t.id)
.collect();
found_ticket_ids.sort();
assert_eq!(found_ticket_ids, all_ticket_ids);
// start date filters out event
let mut found_ticket_ids: Vec<Uuid> = TicketInstance::find_for_user_for_display(
user.id,
None,
Some(NaiveDate::from_ymd(2017, 7, 8).and_hms(9, 0, 11)),
None,
connection,
).unwrap()
.iter()
.flat_map(move |(_, tickets)| tickets.iter())
.map(|t| t.id)
.collect();
found_ticket_ids.sort();
assert_eq!(found_ticket_ids, ticket_ids2);
// end date filters out event
let mut found_ticket_ids: Vec<Uuid> = TicketInstance::find_for_user_for_display(
user.id,
None,
None,
Some(NaiveDate::from_ymd(2017, 7, 8).and_hms(9, 0, 11)),
connection,
).unwrap()
.iter()
.flat_map(move |(_, tickets)| tickets.iter())
.map(|t| t.id)
.collect();
found_ticket_ids.sort();
assert_eq!(found_ticket_ids, ticket_ids);
}
#[test]
pub fn find() {
let project = TestProject::new();
let connection = project.get_connection();
let organization = project
.create_organization()
.with_fee_schedule(&project.create_fee_schedule().finish())
.finish();
let event = project
.create_event()
.with_organization(&organization)
.with_tickets()
.with_ticket_pricing()
.finish();
let user = project.create_user().finish();
//let _d_user: DisplayUser = user.into();
let cart = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type = &event.ticket_types(connection).unwrap()[0];
let display_event = event.for_display(connection).unwrap();
let ticket = cart
.add_tickets(ticket_type.id, 1, connection)
.unwrap()
.remove(0);
let expected_ticket = DisplayTicket {
id: ticket.id,
ticket_type_name: ticket_type.name.clone(),
status: "Reserved".to_string(),
};
assert_eq!(
(display_event, None, expected_ticket),
TicketInstance::find_for_display(ticket.id, connection).unwrap()
);
assert!(TicketInstance::find(Uuid::new_v4(), connection).is_err());
}
#[test]
pub fn find_for_user() {
let project = TestProject::new();
let connection = project.get_connection();
let organization = project
.create_organization()
.with_fee_schedule(&project.create_fee_schedule().finish())
.finish();
let event = project
.create_event()
.with_organization(&organization)
.with_tickets()
.with_ticket_pricing()
.finish();
let user = project.create_user().finish();
let mut cart = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type = &event.ticket_types(connection).unwrap()[0];
cart.add_tickets(ticket_type.id, 5, connection)
.unwrap()
.remove(0);
let total = cart.calculate_total(connection).unwrap();
cart.add_external_payment("test".to_string(), user.id, total, connection)
.unwrap();
let tickets = TicketInstance::find_for_user(user.id, connection).unwrap();
assert_eq!(tickets.len(), 5);
assert!(TicketInstance::find(Uuid::new_v4(), connection).is_err());
}
#[test]
pub fn reserve_tickets() {
let db = TestProject::new();
let connection = db.get_connection();
let organization = db
.create_organization()
.with_fee_schedule(&db.create_fee_schedule().finish())
.finish();
let event = db
.create_event()
.with_organization(&organization)
.with_ticket_pricing()
.finish();
let user = db.create_user().finish();
let order = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type_id = event.ticket_types(connection).unwrap()[0].id;
let expires = NaiveDateTime::from(Utc::now().naive_utc() + Duration::days(2));
order.add_tickets(ticket_type_id, 0, connection).unwrap();
let order_item = order.items(connection).unwrap().remove(0);
let reserved_tickets = TicketInstance::reserve_tickets(
&order_item,
&expires,
ticket_type_id,
None,
10,
connection,
).unwrap();
let order_item = order.items(connection).unwrap().remove(0);
assert_eq!(reserved_tickets.len(), 10);
assert!(
reserved_tickets
.iter()
.filter(|&ticket| ticket.order_item_id != Some(order_item.id))
.collect::<Vec<&TicketInstance>>()
.is_empty()
);
assert!(
reserved_tickets
.iter()
.filter(|&ticket| ticket.reserved_until.is_none())
.collect::<Vec<&TicketInstance>>()
.is_empty()
);
}
#[test]
pub fn release_tickets() {
let project = TestProject::new();
let connection = project.get_connection();
let event = project.create_event().with_ticket_pricing().finish();
let user = project.create_user().finish();
let order = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type_id = event.ticket_types(connection).unwrap()[0].id;
order.add_tickets(ticket_type_id, 10, connection).unwrap();
let order_item = order.items(connection).unwrap().remove(0);
// Release tickets
let released_tickets =
TicketInstance::release_tickets(&order_item, Some(4), connection).unwrap();
assert_eq!(released_tickets.len(), 4);
assert!(
released_tickets
.iter()
.filter(|&ticket| ticket.order_item_id == Some(order_item.id))
.collect::<Vec<&TicketInstance>>()
.is_empty()
);
assert!(
released_tickets
.iter()
.filter(|&ticket| ticket.reserved_until.is_some())
.collect::<Vec<&TicketInstance>>()
.is_empty()
);
project
.get_connection()
.transaction::<Vec<TicketInstance>, Error, _>(|| {
// Release requesting too many tickets
let released_tickets =
TicketInstance::release_tickets(&order_item, Some(7), connection);
assert_eq!(
released_tickets.unwrap_err().cause.unwrap(),
"Could not release the correct amount of tickets",
);
Err(Error::RollbackTransaction)
}).unwrap_err();
// Release remaining tickets (no quantity specified)
let released_tickets = TicketInstance::release_tickets(&order_item, None, connection).unwrap();
assert_eq!(released_tickets.len(), 6);
assert!(
released_tickets
.iter()
.filter(|&ticket| ticket.order_item_id.is_some())
.collect::<Vec<&TicketInstance>>()
.is_empty()
);
assert!(
released_tickets
.iter()
.filter(|&ticket| ticket.reserved_until.is_some())
.collect::<Vec<&TicketInstance>>()
.is_empty()
);
}
#[test]
fn redeem_ticket() {
let project = TestProject::new();
let connection = project.get_connection();
let organization = project
.create_organization()
.with_fee_schedule(&project.create_fee_schedule().finish())
.finish();
let event = project
.create_event()
.with_organization(&organization)
.with_ticket_pricing()
.finish();
let user = project.create_user().finish();
let mut cart = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type = &event.ticket_types(connection).unwrap()[0];
let ticket = cart
.add_tickets(ticket_type.id, 1, connection)
.unwrap()
.remove(0);
let total = cart.calculate_total(connection).unwrap();
cart.add_external_payment("test".to_string(), user.id, total, connection)
.unwrap();
let ticket = TicketInstance::find(ticket.id, connection).unwrap();
let result1 =
TicketInstance::redeem_ticket(ticket.id, "WrongKey".to_string(), connection).unwrap();
assert_eq!(result1, RedeemResults::TicketInvalid);
let result2 =
TicketInstance::redeem_ticket(ticket.id, ticket.redeem_key.unwrap(), connection).unwrap();
assert_eq!(result2, RedeemResults::TicketRedeemSuccess);
}
#[test]
fn show_redeemable_ticket() {
let project = TestProject::new();
let connection = project.get_connection();
let organization = project
.create_organization()
.with_fee_schedule(&project.create_fee_schedule().finish())
.finish();
let venue = project.create_venue().finish();
let event = project
.create_event()
.with_organization(&organization)
.with_ticket_pricing()
.with_venue(&venue)
.finish();
let user = project.create_user().finish();
let mut cart = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type = &event.ticket_types(connection).unwrap()[0];
let ticket = cart
.add_tickets(ticket_type.id, 1, connection)
.unwrap()
.remove(0);
let total = cart.calculate_total(connection).unwrap();
cart.add_external_payment("test".to_string(), user.id, total, connection)
.unwrap();
let ticket = TicketInstance::find(ticket.id, connection).unwrap();
//make redeem date in the future
let new_event_redeem_date = EventEditableAttributes {
redeem_date: Some(NaiveDateTime::from(
Utc::now().naive_utc() + Duration::days(2),
)),
..Default::default()
};
event.update(new_event_redeem_date, connection).unwrap();
let result = TicketInstance::show_redeemable_ticket(ticket.id, connection).unwrap();
assert!(result.redeem_key.is_none());
//make redeem date in the past
let new_event_redeem_date = EventEditableAttributes {
redeem_date: Some(NaiveDateTime::from(
Utc::now().naive_utc() - Duration::days(2),
)),
..Default::default()
};
event.update(new_event_redeem_date, connection).unwrap();
let result = TicketInstance::show_redeemable_ticket(ticket.id, connection).unwrap();
assert!(result.redeem_key.is_some());
}
#[test]
pub fn authorize_ticket_transfer() {
let project = TestProject::new();
let connection = project.get_connection();
let organization = project
.create_organization()
.with_fee_schedule(&project.create_fee_schedule().finish())
.finish();
let event = project
.create_event()
.with_organization(&organization)
.with_tickets()
.with_ticket_pricing()
.finish();
let user = project.create_user().finish();
let mut cart = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type = &event.ticket_types(connection).unwrap()[0];
cart.add_tickets(ticket_type.id, 5, connection)
.unwrap()
.remove(0);
let total = cart.calculate_total(connection).unwrap();
cart.add_external_payment("test".to_string(), user.id, total, connection)
.unwrap();
let tickets = TicketInstance::find_for_user(user.id, connection).unwrap();
assert_eq!(tickets.len(), 5);
//try with a ticket that does not exist in the list
let tickets = TicketInstance::find_for_user(user.id, connection).unwrap();
let mut ticket_ids: Vec<Uuid> = tickets.iter().map(|t| t.id).collect();
ticket_ids.push(Uuid::new_v4());
let transfer_auth2 =
TicketInstance::authorize_ticket_transfer(user.id, ticket_ids, 24, connection);
assert!(transfer_auth2.is_err());
//Now try with tickets that the user does own
let ticket_ids: Vec<Uuid> = tickets.iter().map(|t| t.id).collect();
let transfer_auth3 =
TicketInstance::authorize_ticket_transfer(user.id, ticket_ids, 24, connection).unwrap();
assert_eq!(transfer_auth3.sender_user_id, user.id);
}
#[test]
pub fn receive_ticket_transfer() {
let project = TestProject::new();
let connection = project.get_connection();
let organization = project
.create_organization()
.with_fee_schedule(&project.create_fee_schedule().finish())
.finish();
let event = project
.create_event()
.with_organization(&organization)
.with_tickets()
.with_ticket_pricing()
.finish();
let user = project.create_user().finish();
let mut cart = Order::find_or_create_cart(&user, connection).unwrap();
let ticket_type = &event.ticket_types(connection).unwrap()[0];
cart.add_tickets(ticket_type.id, 5, connection)
.unwrap()
.remove(0);
let total = cart.calculate_total(connection).unwrap();
cart.add_external_payment("test".to_string(), user.id, total, connection)
.unwrap();
let tickets = TicketInstance::find_for_user(user.id, connection).unwrap();
let ticket_ids: Vec<Uuid> = tickets.iter().map(|t| t.id).collect();
let user2 = project.create_user().finish();
//try receive ones that are expired
let transfer_auth =
TicketInstance::authorize_ticket_transfer(user.id, ticket_ids.clone(), 0, connection)
.unwrap();
let _q: Vec<TicketInstance> = diesel::sql_query(
r#"
UPDATE ticket_instances
SET transfer_expiry_date = '2018-06-06 09:49:09.643207'
WHERE id = $1;
"#,
).bind::<sql_types::Uuid, _>(ticket_ids[0])
.get_results(connection)
.unwrap();
let sender_wallet =
Wallet::find_default_for_user(transfer_auth.sender_user_id, connection).unwrap();
let receiver_wallet = Wallet::find_default_for_user(user2.id, connection).unwrap();
let receive_auth2 = TicketInstance::receive_ticket_transfer(
transfer_auth,
&sender_wallet,
&receiver_wallet.id,
connection,
);
assert!(receive_auth2.is_err());
//try receive the wrong number of tickets (too few)
let transfer_auth =
TicketInstance::authorize_ticket_transfer(user.id, ticket_ids.clone(), 3600, connection)
.unwrap();
let mut wrong_auth = transfer_auth.clone();
wrong_auth.num_tickets = 4;
let receive_auth1 = TicketInstance::receive_ticket_transfer(
wrong_auth,
&sender_wallet,
&receiver_wallet.id,
connection,
);
assert!(receive_auth1.is_err());
//legit receive tickets
let _receive_auth3 = TicketInstance::receive_ticket_transfer(
transfer_auth,
&sender_wallet,
&receiver_wallet.id,
connection,
);
//Look if one of the tickets does have the new wallet_id
let receive_wallet = Wallet::find_default_for_user(user2.id, connection).unwrap();
let received_ticket = TicketInstance::find(ticket_ids[0], connection).unwrap();
assert_eq!(receive_wallet.id, received_ticket.wallet_id);
}
|
use std::io::Cursor;
use std::sync::Arc;
use lightning::ln::msgs::NetAddress;
use lightning::util::ser::Writeable;
use lightning::{
routing::gossip::{NodeId, NodeInfo},
util::ser::Readable,
};
use serde::Deserialize;
use tokio::runtime::Handle;
use crate::{error::Error, hex_utils, node::NetworkGraph};
use super::router::RemoteSenseiInfo;
pub enum NodeInfoLookup {
Local(Arc<NetworkGraph>),
Remote(RemoteNetworkGraph),
}
// TODO: probably want a cache in front of the remote lookup?
// these things don't change very often and the request is expensive
// perhaps even notifications from remote? like some kind of "spv network graph"
// where I can register node_ids I care about and get notified of changes
// could be whenever I make a request for one it counts as notification registration
// is this even worth it? maybe we just keep a graph in sync :eyeroll:
// or I guess a shared database/cache (redis?) could be used?
// that's probably not better then a long-lived connection with the remote node
// since they keep the graph in memory.
impl NodeInfoLookup {
pub fn new_local(network_graph: Arc<NetworkGraph>) -> Self {
NodeInfoLookup::Local(network_graph)
}
pub fn new_remote(host: String, token: String, tokio_handle: Handle) -> Self {
NodeInfoLookup::Remote(RemoteNetworkGraph::new(host, token, tokio_handle))
}
pub fn get_node_info(&self, node_id: NodeId) -> Result<Option<NodeInfo>, Error> {
match self {
NodeInfoLookup::Local(network_graph) => {
let network_graph = network_graph.read_only();
Ok(network_graph.nodes().get(&node_id).cloned())
}
NodeInfoLookup::Remote(remote_graph) => remote_graph.get_node_info_sync(node_id),
}
}
pub fn get_alias(&self, node_id: NodeId) -> Result<Option<String>, Error> {
Ok(self
.get_node_info(node_id)?
.and_then(|node_info| node_info.announcement_info.map(|ann_info| ann_info.alias))
.map(|node_alias| node_alias.to_string()))
}
pub fn get_addresses(&self, node_id: NodeId) -> Result<Vec<NetAddress>, Error> {
Ok(self
.get_node_info(node_id)?
.and_then(|info| {
info.announcement_info
.as_ref()
.map(|info| info.addresses.clone())
})
.unwrap_or_default())
}
}
pub struct RemoteNetworkGraph {
remote_sensei: RemoteSenseiInfo,
tokio_handle: Handle,
}
#[derive(Deserialize)]
struct GetInfoResponse {
node_info: Option<String>,
}
impl RemoteNetworkGraph {
pub fn new(host: String, token: String, tokio_handle: Handle) -> Self {
Self {
remote_sensei: RemoteSenseiInfo { host, token },
tokio_handle,
}
}
fn get_node_info_route(&self) -> String {
format!("{}/v1/ldk/network/node_info", self.remote_sensei.host)
}
fn get_node_info_sync(&self, node_id: NodeId) -> Result<Option<NodeInfo>, Error> {
tokio::task::block_in_place(move || {
self.tokio_handle
.clone()
.block_on(async move { self.get_node_info(node_id).await })
})
}
async fn get_node_info(&self, node_id: NodeId) -> Result<Option<NodeInfo>, Error> {
let client = reqwest::Client::new();
let response = client
.post(self.get_node_info_route())
.header("token", self.remote_sensei.token.clone())
.json(&serde_json::json!({
"node_id_hex": hex_utils::hex_str(&node_id.encode())
}))
.send()
.await;
match response {
Ok(response) => {
let get_info_response: GetInfoResponse = response.json().await.unwrap();
Ok(get_info_response.node_info.map(|node_info| {
let mut readable_node_info =
Cursor::new(hex_utils::to_vec(&node_info).unwrap());
NodeInfo::read(&mut readable_node_info).unwrap()
}))
}
Err(e) => Err(Error::Generic(e.to_string())),
}
}
}
|
#![allow(unused_imports)]
use legion::{system, systems::CommandBuffer, Entity};
#[system(par_for_each)]
fn for_each(_: &Entity, _: &mut CommandBuffer) {}
fn main() {}
|
#[allow(unused_imports)]
use proconio::{
input, fastout,
};
fn solve(a: i64, b: i64, c: i64, d: i64) -> usize {
if a == c && b == d {
0
} else if a + b == c + d
|| a - b == c - d
|| (a - c).abs() + (b - d).abs() <= 3
{
1
} else if (a + b + c + d) % 2 == 0
|| (a - c).abs() + (b - d).abs() <= 6
|| (a + b - c - d).abs() <= 3
|| (a - b - c + d).abs() <= 3
{
2
} else {
3
}
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
input! {
r1: (i64, i64), r2: (i64, i64),
}
println!("{}", solve(r1.0, r1.1, r2.0, r2.1));
Ok(())
}
fn main() {
match run() {
Err(err) => panic!("{}", err),
_ => (),
}
}
|
use super::{vertex, Vertex};
use super::opengl::{VertexArray, BufferUsage, Buffer, VertexBuffer, ElementBuffer, PrimitiveType};
use crate::error::{GameError, GameResult};
use glow::Context;
use std::rc::Rc;
pub struct Renderer {
vertex_array: VertexArray,
vertex_buffer: VertexBuffer,
vertex_size: usize,
element_buffer: Option<ElementBuffer>,
element_size: Option<usize>,
}
impl Renderer {
pub fn init_vertex_size(&mut self, usage: BufferUsage, size: usize) {
self.vertex_buffer.bind();
self.vertex_buffer.init_size(usage, vertex::ATTRIBUTE_STRIDE * size);
init_vertex_attribute_pointer(&self.vertex_buffer);
self.vertex_buffer.unbind();
self.vertex_size = size;
}
pub fn init_with_vertices(&mut self, usage: BufferUsage, vertices: &[Vertex]) {
self.vertex_buffer.bind();
self.vertex_buffer.init_with_data(usage, &convert_vertices_to_data(vertices));
init_vertex_attribute_pointer(&self.vertex_buffer);
self.vertex_buffer.unbind();
self.vertex_size = vertices.len();
}
pub fn update_vertices(&self, offset: usize, vertices: &[Vertex]) {
self.vertex_buffer.bind();
self.vertex_buffer.sub_data(offset, &convert_vertices_to_data(vertices));
self.vertex_buffer.unbind();
}
pub fn vertex_size(&self) -> usize {
self.vertex_size
}
fn element_buffer(&self) -> GameResult<&ElementBuffer> {
self.element_buffer.as_ref().ok_or_else(|| GameError::StateError("not setup element buffer".into()))
}
pub fn init_element_size(&mut self, usage: BufferUsage, size: usize) -> GameResult {
let element_buffer = self.element_buffer()?;
element_buffer.bind();
element_buffer.init_size(usage, size);
element_buffer.unbind();
self.element_size = Some(size);
Ok(())
}
pub fn init_with_elements(&mut self, usage: BufferUsage, elements: &[u32]) -> GameResult {
let element_buffer = self.element_buffer()?;
element_buffer.bind();
element_buffer.init_with_data(usage, elements);
element_buffer.unbind();
self.element_size = Some(elements.len());
Ok(())
}
pub fn update_elements(&self, offset: usize, elements: &[u32]) -> GameResult {
let element_buffer = self.element_buffer()?;
element_buffer.bind();
element_buffer.sub_data(offset, elements);
element_buffer.unbind();
Ok(())
}
pub fn element_size(&self) -> Option<usize> {
self.element_size
}
pub fn draw_arrays(&self, primitive: PrimitiveType, first: usize, count: usize) {
self.vertex_array.bind();
self.vertex_array.draw_arrays(primitive, first, count);
self.vertex_array.unbind();
}
pub fn draw_elements(&self, primitive: PrimitiveType, count: usize, offset: usize) {
self.vertex_array.bind();
self.vertex_array.draw_elements(primitive, count, offset);
self.vertex_array.unbind();
}
}
pub struct RendererBuilder {
gl: Rc<Context>,
vertex_array: VertexArray,
vertex_buffer: Option<VertexBuffer>,
vertex_size: Option<usize>,
element_buffer: Option<ElementBuffer>,
element_size: Option<usize>,
}
impl RendererBuilder {
pub fn new(gl: Rc<Context>) -> GameResult<Self> {
let vertex_array = VertexArray::new(gl.clone())
.map_err(|error| GameError::InitError(error.into()))?;
vertex_array.bind();
Ok(Self {
gl,
vertex_array,
vertex_buffer: None,
vertex_size: None,
element_buffer: None,
element_size: None,
})
}
fn assert_vertex_buffer_not_init(&self) {
assert!(self.vertex_buffer.is_none(), "vertex buffer has been setup");
}
pub fn init_vertex_size(mut self, usage: BufferUsage, size: usize) -> Self {
self.assert_vertex_buffer_not_init();
let vertex_buffer = Buffer::new_vertex(self.gl.clone()).unwrap();
vertex_buffer.bind();
vertex_buffer.init_size(usage, vertex::ATTRIBUTE_STRIDE * size);
init_vertex_attribute_pointer(&vertex_buffer);
self.vertex_buffer = Some(vertex_buffer);
self.vertex_size = Some(size);
self
}
pub fn init_with_vertices(mut self, usage: BufferUsage, vertices: &[Vertex]) -> Self {
self.assert_vertex_buffer_not_init();
let vertex_buffer = Buffer::new_vertex(self.gl.clone()).unwrap();
vertex_buffer.bind();
vertex_buffer.init_with_data(usage, &convert_vertices_to_data(vertices));
init_vertex_attribute_pointer(&vertex_buffer);
self.vertex_buffer = Some(vertex_buffer);
self.vertex_size = Some(vertices.len());
self
}
fn assert_element_buffer_not_init(&self) {
assert!(self.element_buffer.is_none(), "element buffer has been setup");
}
pub fn init_element_size(mut self, usage: BufferUsage, size: usize) -> Self {
self.assert_element_buffer_not_init();
let element_buffer = Buffer::new_element(self.gl.clone()).unwrap();
element_buffer.bind();
element_buffer.init_size(usage, size);
self.element_buffer = Some(element_buffer);
self.element_size = Some(size);
self
}
pub fn init_with_elements(mut self, usage: BufferUsage, elements: &[u32]) -> Self {
self.assert_element_buffer_not_init();
let element_buffer = Buffer::new_element(self.gl.clone()).unwrap();
element_buffer.bind();
element_buffer.init_with_data(usage, elements);
self.element_buffer = Some(element_buffer);
self.element_size = Some(elements.len());
self
}
pub fn build(self) -> GameResult<Renderer> {
let vertex_array = self.vertex_array;
let vertex_buffer = self.vertex_buffer
.ok_or_else(|| GameError::InitError("must setup vertex buffer".into()))?;
let vertex_size = self.vertex_size
.ok_or_else(|| GameError::InitError("must setup vertex buffer".into()))?;
let element_buffer = self.element_buffer;
let element_size = self.element_size;
vertex_array.unbind();
vertex_buffer.unbind();
if let Some(element_buffer) = element_buffer.as_ref() {
element_buffer.unbind();
}
Ok(Renderer {
vertex_array,
vertex_buffer,
vertex_size,
element_buffer,
element_size,
})
}
}
fn init_vertex_attribute_pointer(vertex_buffer: &VertexBuffer) {
vertex_buffer.set_attrib_pointer_f32(0, vertex::ATTRIBUTE_POSITION_SIZE, vertex::ATTRIBUTE_STRIDE, vertex::ATTRIBUTE_OFFSET_0);
vertex_buffer.set_attrib_pointer_f32(1, vertex::ATTRIBUTE_UV_SIZE, vertex::ATTRIBUTE_STRIDE, vertex::ATTRIBUTE_OFFSET_1);
vertex_buffer.set_attrib_pointer_f32(2, vertex::ATTRIBUTE_COLOR_SIZE, vertex::ATTRIBUTE_STRIDE, vertex::ATTRIBUTE_OFFSET_2);
}
fn convert_vertices_to_data(vertices: &[Vertex]) -> Vec<f32> {
let mut data = Vec::with_capacity(vertex::ATTRIBUTE_STRIDE * vertices.len());
for vertex in vertices {
data.push(vertex.position.x);
data.push(vertex.position.y);
data.push(vertex.uv.x);
data.push(vertex.uv.y);
data.push(vertex.color.red);
data.push(vertex.color.green);
data.push(vertex.color.blue);
data.push(vertex.color.alpha);
}
data
}
|
pub struct ProconReader<R: std::io::Read> {
reader: R,
}
impl<R: std::io::Read> ProconReader<R> {
pub fn new(reader: R) -> Self {
Self { reader }
}
pub fn get<T: std::str::FromStr>(&mut self) -> T {
use std::io::Read;
let buf = self
.reader
.by_ref()
.bytes()
.map(|b| b.unwrap())
.skip_while(|&byte| byte == b' ' || byte == b'\n' || byte == b'\r')
.take_while(|&byte| byte != b' ' && byte != b'\n' && byte != b'\r')
.collect::<Vec<_>>();
std::str::from_utf8(&buf)
.unwrap()
.parse()
.ok()
.expect("Parse Error.")
}
}
mod rolling_hash {
const M: u64 = 1_000_000_000 + 9;
const B: u64 = 999999937;
pub struct RollingHash {
h: Vec<u64>,
p: Vec<u64>,
}
impl RollingHash {
pub fn new(s: &[u64]) -> Self {
let n = s.len();
let mut h = vec![0; n + 1];
let mut p = vec![0; n + 1];
p[0] = 1;
for i in 0..n {
h[i + 1] = (h[i] * B + s[i]) % M;
p[i + 1] = p[i] * B % M;
}
Self { h, p }
}
pub fn get(&self, range: std::ops::Range<usize>) -> u64 {
let l = range.start;
let r = range.end;
(self.h[r] + M - self.h[l] * self.p[r - l] % M) % M
}
}
}
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
use rolling_hash::RollingHash;
let n: usize = rd.get();
let s: String = rd.get();
let t = s.chars().map(|c| c as u64).collect::<Vec<_>>();
let rh = RollingHash::new(&t);
let mut ans = 0;
for i in 0..n {
for j in (i + 1)..n {
let mut ok = 0;
let mut ng = std::cmp::min(j - i, n - j) + 1;
while ng - ok > 1 {
let m = (ng + ok) / 2;
if rh.get(i..(i + m)) == rh.get(j..(j + m)) {
ok = m;
} else {
ng = m;
}
}
ans = std::cmp::max(ans, ok);
}
}
println!("{}", ans);
}
|
///
/// Creates a retina map that can be used to simulate glaucoma.
///
/// # Arguments
///
/// - `res` - resolution of the returned retina map
/// - `severity` - the severity of the disease, value between 0 and 100
///
pub fn generate_simple(
res: (u32, u32),
severity: u8,
) -> image::ImageBuffer<image::Rgba<u8>, Vec<u8>> {
if severity > 98 {
generate_blindness(res)
} else {
let radius = ((((res.0 / 2) as i32).pow(2) + ((res.1 / 2) as i32).pow(2)) as f64).sqrt();
generate(res, radius, severity)
}
}
///
/// Creates a retina map that can be used to simulate glaucoma.
///
/// # Arguments
///
/// - `res` - resolution of the returned retina map
/// - `radius` - radius of the affected area
/// - `factor` - intensity of the effect, value between 0 and 1
///
fn generate(
res: (u32, u32),
radius: f64,
severity: u8,
) -> image::ImageBuffer<image::Rgba<u8>, Vec<u8>> {
let severity = severity as f64;
let border_width = if severity >= 80.0 {
10.0 * (100.0 - severity)
} else if severity < 20.0 {
10.0 * severity
} else {
200.0
};
let mut mapbuffer = image::ImageBuffer::new(res.0, res.1);
for (x, y, pixel) in mapbuffer.enumerate_pixels_mut() {
let distance_from_center = ((((res.0 / 2) as i32 - x as i32).pow(2)
+ ((res.1 / 2) as i32 - y as i32).pow(2)) as f64)
.sqrt();
let factor = 1.0 - (severity / 100.0);
let mut is_healthy = true;
if distance_from_center > radius * factor {
is_healthy = false;
}
let mut cells = 255;
if !is_healthy {
cells = 0;
// partly affected cells just outside the healthy circle
cells += (255.0 / border_width) as u8
* (border_width - (distance_from_center - radius * factor))
.min(border_width)
.max(0.0) as u8;
}
let cells = calculate_scotoma(res, (x, y), severity, cells);
*pixel = image::Rgba([cells, cells, cells, cells]);
}
mapbuffer
}
#[allow(unused_variables)]
fn calculate_scotoma(res: (u32, u32), pos: (u32, u32), severity: f64, cells: u8) -> u8 {
cells
}
///
/// Creates a retina map that can be used to simulate absolute blindness.
///
/// # Arguments
///
/// - `res` - resolution of the returned retina map
///
pub fn generate_blindness(res: (u32, u32)) -> image::ImageBuffer<image::Rgba<u8>, Vec<u8>> {
let mut mapbuffer = image::ImageBuffer::new(res.0, res.1);
for (_, _, pixel) in mapbuffer.enumerate_pixels_mut() {
*pixel = image::Rgba([0, 0, 0, 0]);
}
mapbuffer
}
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Regression test for #18060: match arms were matching in the wrong order.
fn main() {
assert_eq!(2, match (1, 3) { (0, 2..=5) => 1, (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 });
assert_eq!(2, match (1, 3) { (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 });
assert_eq!(2, match (1, 7) { (0, 2..=5) => 1, (1, 7) => 2, (_, 2..=5) => 3, (_, _) => 4 });
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u16,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u16,
}
impl super::RXIE {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u16 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIE_EP1R {
bits: bool,
}
impl USB_RXIE_EP1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIE_EP1W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIE_EP1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u16) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIE_EP2R {
bits: bool,
}
impl USB_RXIE_EP2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIE_EP2W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIE_EP2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u16) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIE_EP3R {
bits: bool,
}
impl USB_RXIE_EP3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIE_EP3W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIE_EP3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u16) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIE_EP4R {
bits: bool,
}
impl USB_RXIE_EP4R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIE_EP4W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIE_EP4W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 4);
self.w.bits |= ((value as u16) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIE_EP5R {
bits: bool,
}
impl USB_RXIE_EP5R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIE_EP5W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIE_EP5W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u16) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIE_EP6R {
bits: bool,
}
impl USB_RXIE_EP6R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIE_EP6W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIE_EP6W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u16) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIE_EP7R {
bits: bool,
}
impl USB_RXIE_EP7R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIE_EP7W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIE_EP7W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u16) & 1) << 7;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u16 {
self.bits
}
#[doc = "Bit 1 - RX Endpoint 1 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep1(&self) -> USB_RXIE_EP1R {
let bits = ((self.bits >> 1) & 1) != 0;
USB_RXIE_EP1R { bits }
}
#[doc = "Bit 2 - RX Endpoint 2 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep2(&self) -> USB_RXIE_EP2R {
let bits = ((self.bits >> 2) & 1) != 0;
USB_RXIE_EP2R { bits }
}
#[doc = "Bit 3 - RX Endpoint 3 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep3(&self) -> USB_RXIE_EP3R {
let bits = ((self.bits >> 3) & 1) != 0;
USB_RXIE_EP3R { bits }
}
#[doc = "Bit 4 - RX Endpoint 4 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep4(&self) -> USB_RXIE_EP4R {
let bits = ((self.bits >> 4) & 1) != 0;
USB_RXIE_EP4R { bits }
}
#[doc = "Bit 5 - RX Endpoint 5 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep5(&self) -> USB_RXIE_EP5R {
let bits = ((self.bits >> 5) & 1) != 0;
USB_RXIE_EP5R { bits }
}
#[doc = "Bit 6 - RX Endpoint 6 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep6(&self) -> USB_RXIE_EP6R {
let bits = ((self.bits >> 6) & 1) != 0;
USB_RXIE_EP6R { bits }
}
#[doc = "Bit 7 - RX Endpoint 7 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep7(&self) -> USB_RXIE_EP7R {
let bits = ((self.bits >> 7) & 1) != 0;
USB_RXIE_EP7R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u16) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 1 - RX Endpoint 1 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep1(&mut self) -> _USB_RXIE_EP1W {
_USB_RXIE_EP1W { w: self }
}
#[doc = "Bit 2 - RX Endpoint 2 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep2(&mut self) -> _USB_RXIE_EP2W {
_USB_RXIE_EP2W { w: self }
}
#[doc = "Bit 3 - RX Endpoint 3 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep3(&mut self) -> _USB_RXIE_EP3W {
_USB_RXIE_EP3W { w: self }
}
#[doc = "Bit 4 - RX Endpoint 4 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep4(&mut self) -> _USB_RXIE_EP4W {
_USB_RXIE_EP4W { w: self }
}
#[doc = "Bit 5 - RX Endpoint 5 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep5(&mut self) -> _USB_RXIE_EP5W {
_USB_RXIE_EP5W { w: self }
}
#[doc = "Bit 6 - RX Endpoint 6 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep6(&mut self) -> _USB_RXIE_EP6W {
_USB_RXIE_EP6W { w: self }
}
#[doc = "Bit 7 - RX Endpoint 7 Interrupt Enable"]
#[inline(always)]
pub fn usb_rxie_ep7(&mut self) -> _USB_RXIE_EP7W {
_USB_RXIE_EP7W { w: self }
}
}
|
use mysql::{PooledConn, Pool};
use mysql::prelude::*;
use mysql::params;
use csv::Reader;
use serde::{Deserialize, Serialize};
use serde_json::{Result};
use std::fs::{OpenOptions};
use std::io::Write;
#[derive(Debug, Deserialize, Serialize)]
struct Example {
name: String
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct ExampleRead {
id: i32,
name: String
}
fn read_csv() -> Vec<Example> {
let mut records = Vec::new();
let mut reader = Reader::from_path("/data/example.csv").unwrap();
let iter = reader.records();
// It didn't like deserializing StringRecord and applying it to a struct with an Option<i32>
// DOn't know why 'yet', to get around this a seperate struct was created in order to read in the files.
for result in iter {
let record = result.unwrap();
let row: Example = record.deserialize(None).unwrap();
records.push(row)
}
return records
}
fn connect_to_db() -> PooledConn {
let url = "mysql://codetest:swordfish@database:3306/codetest";
let pool = Pool::new(url).expect("can't create pool ");
let conn = pool.get_conn().expect("can't create connection");
return conn
}
fn write_to_json(selected_records: Vec<ExampleRead>) -> std::result::Result<(), serde_json::Error> {
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open("/data/example-rust.json")
.expect("Could not open/create file");
let iter = selected_records.iter();
let iter_length = iter.len();
let mut count = 0;
file.write_all("[\n".as_bytes()).expect("write failed");
for record in iter {
count = count + 1;
// Serialize it to a JSON string
let record_json = serde_json::to_string(&record)?;
file.write_all(record_json.as_bytes()).expect("writing record failed");
if iter_length == count {
} else {
file.write_all(",\n".as_bytes()).expect("writing comma failed");
}
}
file.write_all("\n]".as_bytes()).expect("write failed");
println!("Successfully wrote a file");
Ok(())
}
fn main() -> Result<()> {
let mut conn = connect_to_db();
let records = read_csv();
conn.exec_batch(
r"INSERT INTO examples (name)
VALUES (:name)",
records.iter().map(|record| params! {
"name" => &record.name,
})
).unwrap();
let selected_records = conn
.query_map(
"SELECT id, name from examples",
|(id, name)| {
ExampleRead { id, name }
},
).unwrap();
write_to_json(selected_records)?;
println!("Script Completed!");
Ok(())
}
|
use std::convert::TryFrom;
use super::component_prelude::*;
use crate::level_manager::Level;
#[derive(Default, Clone, PartialEq, Eq, Hash, Deserialize)]
pub struct MenuSelection(pub Level);
impl MenuSelection {
#[rustfmt::skip]
pub fn next(&mut self) {
self.0 = match self.0 {
Level::VeryEasy => Level::Easy,
Level::Easy => Level::Normal,
Level::Normal => Level::Hard,
Level::Hard => Level::Absurd,
Level::Absurd => Level::VeryEasy,
};
}
#[rustfmt::skip]
pub fn prev(&mut self) {
self.0 = match self.0 {
Level::VeryEasy => Level::Absurd,
Level::Easy => Level::VeryEasy,
Level::Normal => Level::Easy,
Level::Hard => Level::Normal,
Level::Absurd => Level::Hard,
};
}
pub fn level(&self) -> Level {
self.0.clone()
}
}
impl TryFrom<&str> for MenuSelection {
type Error = ();
#[rustfmt::skip]
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value.to_string().as_str() {
"selection_very_easy" | "button_start_very_easy" => {
Ok(Self(Level::VeryEasy))
}
"selection_easy" | "button_start_easy" => {
Ok(Self(Level::Easy))
},
"selection_normal" | "button_start_normal" => {
Ok(Self(Level::Normal))
}
"selection_hard" | "button_start_hard" => {
Ok(Self(Level::Hard))
},
"selection_absurd" | "button_start_absurd" => {
Ok(Self(Level::Absurd))
}
_ => Err(()),
}
}
}
#[derive(Default)]
pub struct MenuSelector {
pub selection: MenuSelection,
}
impl MenuSelector {
pub fn next(&mut self) {
self.selection.next();
}
pub fn prev(&mut self) {
self.selection.prev();
}
pub fn set(&mut self, selection: MenuSelection) {
self.selection = selection;
}
}
impl Component for MenuSelector {
type Storage = HashMapStorage<Self>;
}
|
#[macro_use]
extern crate log;
extern crate lapin;
extern crate tokio;
extern crate tokio_amqp;
use dotenv::dotenv;
use std::env;
use lapin::{Connection, ConnectionProperties, BasicProperties, types::FieldTable};
use lapin::options::{QueueDeclareOptions, BasicConsumeOptions, BasicPublishOptions, BasicAckOptions};
use tokio_amqp::*;
use tokio::runtime::Runtime;
use std::{thread, time};
use std::sync::Arc;
use futures_lite::StreamExt;
fn main() {
env_logger::init();
let rt = Arc::new(Runtime::new().expect("failed to create runtime"));
rt.block_on(init_consumer(rt.clone()));
loop {
rt.spawn(publish(rt.clone()));
let ten_millis = time::Duration::from_secs(10);
thread::sleep(ten_millis);
}
}
async fn init_consumer(rt: Arc<Runtime>) {
let conn = Connection::connect("amqp://rmq:rmq@127.0.0.1:5672/%2f", ConnectionProperties::default().with_tokio()).await.expect("Error when connecting to RabbitMQ");
if let Ok(channel) = conn.create_channel().await {
if let Ok(queue) = channel.queue_declare(
"TEST_MESSAGE",
QueueDeclareOptions::default(),
FieldTable::default()).await {
info!("Declared queue {:?}", queue);
if let Ok(mut consumer) = channel.basic_consume(
"TEST_MESSAGE",
"test_message_consumer",
BasicConsumeOptions::default(),
FieldTable::default(),
).await {
rt.spawn(async move {
info!("Will consume");
while let Some(delivery) = consumer.next().await {
info!("Message received.");
let (_, delivery) = delivery.expect("error in mail consumer");
let body = String::from_utf8_lossy(&*delivery.data);
println!("Received [{}]", body);
delivery
.ack(BasicAckOptions::default())
.await
.expect("ack");
}
info!("Stopped consume");
});
}
}
}
}
async fn publish(rt: Arc<Runtime>) {
let conn = Connection::connect("amqp://rmq:rmq@127.0.0.1:5672/%2f", ConnectionProperties::default().with_tokio()).await.expect("Error when connecting to RabbitMQ");
if let Ok(channel) = conn.create_channel().await {
match channel
.basic_publish(
"",
"TEST_MESSAGE",
BasicPublishOptions::default(),
Vec::from(String::from("Test...")),
BasicProperties::default(),
)
.await {
Ok(pub_conf) => {
match pub_conf.await {
Ok(_) => {
info!("PubConf OK");
}
Err(e) => {
error!("Error when publising: {}", e);
}
}
}
Err(e) => {
error!("Error when publising: {}", e);
}
}
info!("OK -> notify complete");
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Display;
use std::fmt::Formatter;
use num_traits::FromPrimitive;
use crate::txn_condition::Target;
use crate::txn_op;
use crate::txn_op::Request;
use crate::txn_op_response::Response;
use crate::ConditionResult;
use crate::TxnCondition;
use crate::TxnDeleteByPrefixRequest;
use crate::TxnDeleteByPrefixResponse;
use crate::TxnDeleteRequest;
use crate::TxnDeleteResponse;
use crate::TxnGetRequest;
use crate::TxnGetResponse;
use crate::TxnOp;
use crate::TxnOpResponse;
use crate::TxnPutRequest;
use crate::TxnPutResponse;
use crate::TxnReply;
use crate::TxnRequest;
struct OptionDisplay<'a, T: Display> {
t: &'a Option<T>,
}
impl<'a, T: Display> Display for OptionDisplay<'a, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.t {
None => {
write!(f, "None")
}
Some(x) => x.fmt(f),
}
}
}
struct VecDisplay<'a, T: Display> {
vec: &'a Vec<T>,
}
impl<'a, T: Display> Display for VecDisplay<'a, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "[")?;
for (i, t) in self.vec.iter().enumerate() {
if i > 0 {
write!(f, ",")?;
}
write!(f, "{}", t)?;
}
write!(f, "]")
}
}
impl Display for TxnRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"TxnRequest{{ if:{} then:{} else:{} }}",
VecDisplay {
vec: &self.condition
},
VecDisplay { vec: &self.if_then },
VecDisplay {
vec: &self.else_then
},
)
}
}
impl Display for TxnCondition {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let expect: ConditionResult = FromPrimitive::from_i32(self.expected).unwrap();
write!(f, "{} {} {}", self.key, expect, OptionDisplay {
t: &self.target
})
}
}
impl Display for ConditionResult {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let x = match self {
ConditionResult::Eq => "==",
ConditionResult::Gt => ">",
ConditionResult::Ge => ">=",
ConditionResult::Lt => "<",
ConditionResult::Le => "<=",
ConditionResult::Ne => "!=",
};
write!(f, "{}", x)
}
}
impl Display for TxnOp {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", OptionDisplay { t: &self.request })
}
}
impl Display for txn_op::Request {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Request::Get(r) => {
write!(f, "Get({})", r)
}
Request::Put(r) => {
write!(f, "Put({})", r)
}
Request::Delete(r) => {
write!(f, "Delete({})", r)
}
Request::DeleteByPrefix(r) => {
write!(f, "DeleteByPrefix({})", r)
}
}
}
}
impl Display for TxnGetRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Get key={}", self.key)
}
}
impl Display for TxnPutRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Put key={}, need prev_value: {}",
self.key, self.prev_value
)?;
if let Some(expire_at) = self.expire_at {
write!(f, " expire at: {}", expire_at)?;
}
Ok(())
}
}
impl Display for TxnDeleteRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Delete key={}", self.key)
}
}
impl Display for TxnDeleteByPrefixRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "TxnDeleteByPrefixRequest prefix={}", self.prefix)
}
}
impl Display for Target {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Target::Value(_) => {
write!(f, "value(...)",)
}
Target::Seq(seq) => {
write!(f, "seq({})", seq)
}
}
}
}
impl Display for TxnReply {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"TxnReply{{ success: {}, responses: {}, error: {}}}",
self.success,
VecDisplay {
vec: &self.responses
},
self.error
)
}
}
impl Display for TxnOpResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "TxnOpResponse: {}", OptionDisplay { t: &self.response })
}
}
impl Display for Response {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Response::Get(r) => {
write!(f, "Get: {}", r)
}
Response::Put(r) => {
write!(f, "Put: {}", r)
}
Response::Delete(r) => {
write!(f, "Delete: {}", r)
}
Response::DeleteByPrefix(r) => {
write!(f, "DeleteByPrefix: {}", r)
}
}
}
}
impl Display for TxnGetResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Get-resp: key={}, prev_seq={:?}",
self.key,
self.value.as_ref().map(|x| x.seq)
)
}
}
impl Display for TxnPutResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Put-resp: key={}, prev_seq={:?}",
self.key,
self.prev_value.as_ref().map(|x| x.seq)
)
}
}
impl Display for TxnDeleteResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Delete-resp: success: {}, key={}, prev_seq={:?}",
self.success,
self.key,
self.prev_value.as_ref().map(|x| x.seq)
)
}
}
impl Display for TxnDeleteByPrefixResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"TxnDeleteByPrefixResponse prefix={},count={}",
self.prefix, self.count
)
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub const FACILITY_PINT_STATUS_CODE: u32 = 240u32;
pub const FACILITY_RTC_INTERFACE: u32 = 238u32;
pub const FACILITY_SIP_STATUS_CODE: u32 = 239u32;
pub type INetworkTransportSettings = *mut ::core::ffi::c_void;
pub type INotificationTransportSync = *mut ::core::ffi::c_void;
pub type IRTCBuddy = *mut ::core::ffi::c_void;
pub type IRTCBuddy2 = *mut ::core::ffi::c_void;
pub type IRTCBuddyEvent = *mut ::core::ffi::c_void;
pub type IRTCBuddyEvent2 = *mut ::core::ffi::c_void;
pub type IRTCBuddyGroup = *mut ::core::ffi::c_void;
pub type IRTCBuddyGroupEvent = *mut ::core::ffi::c_void;
pub type IRTCClient = *mut ::core::ffi::c_void;
pub type IRTCClient2 = *mut ::core::ffi::c_void;
pub type IRTCClientEvent = *mut ::core::ffi::c_void;
pub type IRTCClientPortManagement = *mut ::core::ffi::c_void;
pub type IRTCClientPresence = *mut ::core::ffi::c_void;
pub type IRTCClientPresence2 = *mut ::core::ffi::c_void;
pub type IRTCClientProvisioning = *mut ::core::ffi::c_void;
pub type IRTCClientProvisioning2 = *mut ::core::ffi::c_void;
pub type IRTCCollection = *mut ::core::ffi::c_void;
pub type IRTCDispatchEventNotification = *mut ::core::ffi::c_void;
pub type IRTCEnumBuddies = *mut ::core::ffi::c_void;
pub type IRTCEnumGroups = *mut ::core::ffi::c_void;
pub type IRTCEnumParticipants = *mut ::core::ffi::c_void;
pub type IRTCEnumPresenceDevices = *mut ::core::ffi::c_void;
pub type IRTCEnumProfiles = *mut ::core::ffi::c_void;
pub type IRTCEnumUserSearchResults = *mut ::core::ffi::c_void;
pub type IRTCEnumWatchers = *mut ::core::ffi::c_void;
pub type IRTCEventNotification = *mut ::core::ffi::c_void;
pub type IRTCInfoEvent = *mut ::core::ffi::c_void;
pub type IRTCIntensityEvent = *mut ::core::ffi::c_void;
pub type IRTCMediaEvent = *mut ::core::ffi::c_void;
pub type IRTCMediaRequestEvent = *mut ::core::ffi::c_void;
pub type IRTCMessagingEvent = *mut ::core::ffi::c_void;
pub type IRTCParticipant = *mut ::core::ffi::c_void;
pub type IRTCParticipantStateChangeEvent = *mut ::core::ffi::c_void;
pub type IRTCPortManager = *mut ::core::ffi::c_void;
pub type IRTCPresenceContact = *mut ::core::ffi::c_void;
pub type IRTCPresenceDataEvent = *mut ::core::ffi::c_void;
pub type IRTCPresenceDevice = *mut ::core::ffi::c_void;
pub type IRTCPresencePropertyEvent = *mut ::core::ffi::c_void;
pub type IRTCPresenceStatusEvent = *mut ::core::ffi::c_void;
pub type IRTCProfile = *mut ::core::ffi::c_void;
pub type IRTCProfile2 = *mut ::core::ffi::c_void;
pub type IRTCProfileEvent = *mut ::core::ffi::c_void;
pub type IRTCProfileEvent2 = *mut ::core::ffi::c_void;
pub type IRTCReInviteEvent = *mut ::core::ffi::c_void;
pub type IRTCRegistrationStateChangeEvent = *mut ::core::ffi::c_void;
pub type IRTCRoamingEvent = *mut ::core::ffi::c_void;
pub type IRTCSession = *mut ::core::ffi::c_void;
pub type IRTCSession2 = *mut ::core::ffi::c_void;
pub type IRTCSessionCallControl = *mut ::core::ffi::c_void;
pub type IRTCSessionDescriptionManager = *mut ::core::ffi::c_void;
pub type IRTCSessionOperationCompleteEvent = *mut ::core::ffi::c_void;
pub type IRTCSessionOperationCompleteEvent2 = *mut ::core::ffi::c_void;
pub type IRTCSessionPortManagement = *mut ::core::ffi::c_void;
pub type IRTCSessionReferStatusEvent = *mut ::core::ffi::c_void;
pub type IRTCSessionReferredEvent = *mut ::core::ffi::c_void;
pub type IRTCSessionStateChangeEvent = *mut ::core::ffi::c_void;
pub type IRTCSessionStateChangeEvent2 = *mut ::core::ffi::c_void;
pub type IRTCUserSearch = *mut ::core::ffi::c_void;
pub type IRTCUserSearchQuery = *mut ::core::ffi::c_void;
pub type IRTCUserSearchResult = *mut ::core::ffi::c_void;
pub type IRTCUserSearchResultsEvent = *mut ::core::ffi::c_void;
pub type IRTCWatcher = *mut ::core::ffi::c_void;
pub type IRTCWatcher2 = *mut ::core::ffi::c_void;
pub type IRTCWatcherEvent = *mut ::core::ffi::c_void;
pub type IRTCWatcherEvent2 = *mut ::core::ffi::c_void;
pub type ITransportSettingsInternal = *mut ::core::ffi::c_void;
pub const RTCAU_BASIC: u32 = 1u32;
pub const RTCAU_DIGEST: u32 = 2u32;
pub const RTCAU_KERBEROS: u32 = 8u32;
pub const RTCAU_NTLM: u32 = 4u32;
pub const RTCAU_USE_LOGON_CRED: u32 = 65536u32;
pub const RTCCS_FAIL_ON_REDIRECT: u32 = 2u32;
pub const RTCCS_FORCE_PROFILE: u32 = 1u32;
pub const RTCClient: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2051205673,
data2: 41655,
data3: 16580,
data4: [176, 145, 246, 240, 36, 170, 137, 190],
};
pub const RTCEF_ALL: u32 = 33554431u32;
pub const RTCEF_BUDDY: u32 = 256u32;
pub const RTCEF_BUDDY2: u32 = 262144u32;
pub const RTCEF_CLIENT: u32 = 1u32;
pub const RTCEF_GROUP: u32 = 8192u32;
pub const RTCEF_INFO: u32 = 4096u32;
pub const RTCEF_INTENSITY: u32 = 64u32;
pub const RTCEF_MEDIA: u32 = 32u32;
pub const RTCEF_MEDIA_REQUEST: u32 = 16384u32;
pub const RTCEF_MESSAGING: u32 = 128u32;
pub const RTCEF_PARTICIPANT_STATE_CHANGE: u32 = 16u32;
pub const RTCEF_PRESENCE_DATA: u32 = 8388608u32;
pub const RTCEF_PRESENCE_PROPERTY: u32 = 131072u32;
pub const RTCEF_PRESENCE_STATUS: u32 = 16777216u32;
pub const RTCEF_PROFILE: u32 = 1024u32;
pub const RTCEF_REGISTRATION_STATE_CHANGE: u32 = 2u32;
pub const RTCEF_REINVITE: u32 = 4194304u32;
pub const RTCEF_ROAMING: u32 = 65536u32;
pub const RTCEF_SESSION_OPERATION_COMPLETE: u32 = 8u32;
pub const RTCEF_SESSION_REFERRED: u32 = 2097152u32;
pub const RTCEF_SESSION_REFER_STATUS: u32 = 1048576u32;
pub const RTCEF_SESSION_STATE_CHANGE: u32 = 4u32;
pub const RTCEF_USERSEARCH: u32 = 2048u32;
pub const RTCEF_WATCHER: u32 = 512u32;
pub const RTCEF_WATCHER2: u32 = 524288u32;
pub const RTCIF_DISABLE_MEDIA: u32 = 1u32;
pub const RTCIF_DISABLE_STRICT_DNS: u32 = 8u32;
pub const RTCIF_DISABLE_UPNP: u32 = 2u32;
pub const RTCIF_ENABLE_SERVER_CLASS: u32 = 4u32;
pub const RTCMT_AUDIO_RECEIVE: u32 = 2u32;
pub const RTCMT_AUDIO_SEND: u32 = 1u32;
pub const RTCMT_T120_SENDRECV: u32 = 16u32;
pub const RTCMT_VIDEO_RECEIVE: u32 = 8u32;
pub const RTCMT_VIDEO_SEND: u32 = 4u32;
pub const RTCRF_REGISTER_ALL: u32 = 15u32;
pub const RTCRF_REGISTER_INVITE_SESSIONS: u32 = 1u32;
pub const RTCRF_REGISTER_MESSAGE_SESSIONS: u32 = 2u32;
pub const RTCRF_REGISTER_NOTIFY: u32 = 8u32;
pub const RTCRF_REGISTER_PRESENCE: u32 = 4u32;
pub const RTCRMF_ALL_ROAMING: u32 = 15u32;
pub const RTCRMF_BUDDY_ROAMING: u32 = 1u32;
pub const RTCRMF_PRESENCE_ROAMING: u32 = 4u32;
pub const RTCRMF_PROFILE_ROAMING: u32 = 8u32;
pub const RTCRMF_WATCHER_ROAMING: u32 = 2u32;
pub const RTCSI_APPLICATION: u32 = 32u32;
pub const RTCSI_IM: u32 = 8u32;
pub const RTCSI_MULTIPARTY_IM: u32 = 16u32;
pub const RTCSI_PC_TO_PC: u32 = 1u32;
pub const RTCSI_PC_TO_PHONE: u32 = 2u32;
pub const RTCSI_PHONE_TO_PHONE: u32 = 4u32;
pub const RTCTR_TCP: u32 = 2u32;
pub const RTCTR_TLS: u32 = 4u32;
pub const RTCTR_UDP: u32 = 1u32;
pub type RTC_ACE_SCOPE = i32;
pub const RTCAS_SCOPE_USER: RTC_ACE_SCOPE = 0i32;
pub const RTCAS_SCOPE_DOMAIN: RTC_ACE_SCOPE = 1i32;
pub const RTCAS_SCOPE_ALL: RTC_ACE_SCOPE = 2i32;
pub type RTC_ANSWER_MODE = i32;
pub const RTCAM_OFFER_SESSION_EVENT: RTC_ANSWER_MODE = 0i32;
pub const RTCAM_AUTOMATICALLY_ACCEPT: RTC_ANSWER_MODE = 1i32;
pub const RTCAM_AUTOMATICALLY_REJECT: RTC_ANSWER_MODE = 2i32;
pub const RTCAM_NOT_SUPPORTED: RTC_ANSWER_MODE = 3i32;
pub type RTC_AUDIO_DEVICE = i32;
pub const RTCAD_SPEAKER: RTC_AUDIO_DEVICE = 0i32;
pub const RTCAD_MICROPHONE: RTC_AUDIO_DEVICE = 1i32;
pub type RTC_BUDDY_EVENT_TYPE = i32;
pub const RTCBET_BUDDY_ADD: RTC_BUDDY_EVENT_TYPE = 0i32;
pub const RTCBET_BUDDY_REMOVE: RTC_BUDDY_EVENT_TYPE = 1i32;
pub const RTCBET_BUDDY_UPDATE: RTC_BUDDY_EVENT_TYPE = 2i32;
pub const RTCBET_BUDDY_STATE_CHANGE: RTC_BUDDY_EVENT_TYPE = 3i32;
pub const RTCBET_BUDDY_ROAMED: RTC_BUDDY_EVENT_TYPE = 4i32;
pub const RTCBET_BUDDY_SUBSCRIBED: RTC_BUDDY_EVENT_TYPE = 5i32;
pub type RTC_BUDDY_SUBSCRIPTION_TYPE = i32;
pub const RTCBT_SUBSCRIBED: RTC_BUDDY_SUBSCRIPTION_TYPE = 0i32;
pub const RTCBT_ALWAYS_OFFLINE: RTC_BUDDY_SUBSCRIPTION_TYPE = 1i32;
pub const RTCBT_ALWAYS_ONLINE: RTC_BUDDY_SUBSCRIPTION_TYPE = 2i32;
pub const RTCBT_POLL: RTC_BUDDY_SUBSCRIPTION_TYPE = 3i32;
pub type RTC_CLIENT_EVENT_TYPE = i32;
pub const RTCCET_VOLUME_CHANGE: RTC_CLIENT_EVENT_TYPE = 0i32;
pub const RTCCET_DEVICE_CHANGE: RTC_CLIENT_EVENT_TYPE = 1i32;
pub const RTCCET_NETWORK_QUALITY_CHANGE: RTC_CLIENT_EVENT_TYPE = 2i32;
pub const RTCCET_ASYNC_CLEANUP_DONE: RTC_CLIENT_EVENT_TYPE = 3i32;
pub type RTC_DTMF = i32;
pub const RTC_DTMF_0: RTC_DTMF = 0i32;
pub const RTC_DTMF_1: RTC_DTMF = 1i32;
pub const RTC_DTMF_2: RTC_DTMF = 2i32;
pub const RTC_DTMF_3: RTC_DTMF = 3i32;
pub const RTC_DTMF_4: RTC_DTMF = 4i32;
pub const RTC_DTMF_5: RTC_DTMF = 5i32;
pub const RTC_DTMF_6: RTC_DTMF = 6i32;
pub const RTC_DTMF_7: RTC_DTMF = 7i32;
pub const RTC_DTMF_8: RTC_DTMF = 8i32;
pub const RTC_DTMF_9: RTC_DTMF = 9i32;
pub const RTC_DTMF_STAR: RTC_DTMF = 10i32;
pub const RTC_DTMF_POUND: RTC_DTMF = 11i32;
pub const RTC_DTMF_A: RTC_DTMF = 12i32;
pub const RTC_DTMF_B: RTC_DTMF = 13i32;
pub const RTC_DTMF_C: RTC_DTMF = 14i32;
pub const RTC_DTMF_D: RTC_DTMF = 15i32;
pub const RTC_DTMF_FLASH: RTC_DTMF = 16i32;
pub type RTC_EVENT = i32;
pub const RTCE_CLIENT: RTC_EVENT = 0i32;
pub const RTCE_REGISTRATION_STATE_CHANGE: RTC_EVENT = 1i32;
pub const RTCE_SESSION_STATE_CHANGE: RTC_EVENT = 2i32;
pub const RTCE_SESSION_OPERATION_COMPLETE: RTC_EVENT = 3i32;
pub const RTCE_PARTICIPANT_STATE_CHANGE: RTC_EVENT = 4i32;
pub const RTCE_MEDIA: RTC_EVENT = 5i32;
pub const RTCE_INTENSITY: RTC_EVENT = 6i32;
pub const RTCE_MESSAGING: RTC_EVENT = 7i32;
pub const RTCE_BUDDY: RTC_EVENT = 8i32;
pub const RTCE_WATCHER: RTC_EVENT = 9i32;
pub const RTCE_PROFILE: RTC_EVENT = 10i32;
pub const RTCE_USERSEARCH: RTC_EVENT = 11i32;
pub const RTCE_INFO: RTC_EVENT = 12i32;
pub const RTCE_GROUP: RTC_EVENT = 13i32;
pub const RTCE_MEDIA_REQUEST: RTC_EVENT = 14i32;
pub const RTCE_ROAMING: RTC_EVENT = 15i32;
pub const RTCE_PRESENCE_PROPERTY: RTC_EVENT = 16i32;
pub const RTCE_PRESENCE_DATA: RTC_EVENT = 17i32;
pub const RTCE_PRESENCE_STATUS: RTC_EVENT = 18i32;
pub const RTCE_SESSION_REFER_STATUS: RTC_EVENT = 19i32;
pub const RTCE_SESSION_REFERRED: RTC_EVENT = 20i32;
pub const RTCE_REINVITE: RTC_EVENT = 21i32;
pub const RTC_E_ANOTHER_MEDIA_SESSION_ACTIVE: ::windows_sys::core::HRESULT = -2131885961i32;
pub const RTC_E_BASIC_AUTH_SET_TLS: ::windows_sys::core::HRESULT = -2131886017i32;
pub const RTC_E_CLIENT_ALREADY_INITIALIZED: ::windows_sys::core::HRESULT = -2131886042i32;
pub const RTC_E_CLIENT_ALREADY_SHUT_DOWN: ::windows_sys::core::HRESULT = -2131886041i32;
pub const RTC_E_CLIENT_NOT_INITIALIZED: ::windows_sys::core::HRESULT = -2131886043i32;
pub const RTC_E_DESTINATION_ADDRESS_LOCAL: ::windows_sys::core::HRESULT = -2131886061i32;
pub const RTC_E_DESTINATION_ADDRESS_MULTICAST: ::windows_sys::core::HRESULT = -2131886059i32;
pub const RTC_E_DUPLICATE_BUDDY: ::windows_sys::core::HRESULT = -2131886006i32;
pub const RTC_E_DUPLICATE_GROUP: ::windows_sys::core::HRESULT = -2131885998i32;
pub const RTC_E_DUPLICATE_REALM: ::windows_sys::core::HRESULT = -2131886013i32;
pub const RTC_E_DUPLICATE_WATCHER: ::windows_sys::core::HRESULT = -2131886005i32;
pub const RTC_E_INVALID_ACL_LIST: ::windows_sys::core::HRESULT = -2131886000i32;
pub const RTC_E_INVALID_ADDRESS_LOCAL: ::windows_sys::core::HRESULT = -2131886060i32;
pub const RTC_E_INVALID_BUDDY_LIST: ::windows_sys::core::HRESULT = -2131886001i32;
pub const RTC_E_INVALID_LISTEN_SOCKET: ::windows_sys::core::HRESULT = -2131885957i32;
pub const RTC_E_INVALID_OBJECT_STATE: ::windows_sys::core::HRESULT = -2131885983i32;
pub const RTC_E_INVALID_PORTRANGE: ::windows_sys::core::HRESULT = -2131885988i32;
pub const RTC_E_INVALID_PREFERENCE_LIST: ::windows_sys::core::HRESULT = -2131885991i32;
pub const RTC_E_INVALID_PROFILE: ::windows_sys::core::HRESULT = -2131886034i32;
pub const RTC_E_INVALID_PROXY_ADDRESS: ::windows_sys::core::HRESULT = -2131886058i32;
pub const RTC_E_INVALID_REGISTRATION_STATE: ::windows_sys::core::HRESULT = -2131885971i32;
pub const RTC_E_INVALID_SESSION_STATE: ::windows_sys::core::HRESULT = -2131886038i32;
pub const RTC_E_INVALID_SESSION_TYPE: ::windows_sys::core::HRESULT = -2131886039i32;
pub const RTC_E_INVALID_SIP_URL: ::windows_sys::core::HRESULT = -2131886062i32;
pub const RTC_E_LISTENING_SOCKET_NOT_EXIST: ::windows_sys::core::HRESULT = -2131885958i32;
pub const RTC_E_LOCAL_PHONE_NEEDED: ::windows_sys::core::HRESULT = -2131886036i32;
pub const RTC_E_MALFORMED_XML: ::windows_sys::core::HRESULT = -2131886004i32;
pub const RTC_E_MAX_PENDING_OPERATIONS: ::windows_sys::core::HRESULT = -2131885990i32;
pub const RTC_E_MAX_REDIRECTS: ::windows_sys::core::HRESULT = -2131885960i32;
pub const RTC_E_MEDIA_AEC: ::windows_sys::core::HRESULT = -2131886044i32;
pub const RTC_E_MEDIA_AUDIO_DEVICE_NOT_AVAILABLE: ::windows_sys::core::HRESULT = -2131886047i32;
pub const RTC_E_MEDIA_CONTROLLER_STATE: ::windows_sys::core::HRESULT = -2131886049i32;
pub const RTC_E_MEDIA_DISABLED: ::windows_sys::core::HRESULT = -2131885970i32;
pub const RTC_E_MEDIA_ENABLED: ::windows_sys::core::HRESULT = -2131885969i32;
pub const RTC_E_MEDIA_NEED_TERMINAL: ::windows_sys::core::HRESULT = -2131886048i32;
pub const RTC_E_MEDIA_SESSION_IN_HOLD: ::windows_sys::core::HRESULT = -2131885962i32;
pub const RTC_E_MEDIA_SESSION_NOT_EXIST: ::windows_sys::core::HRESULT = -2131885963i32;
pub const RTC_E_MEDIA_VIDEO_DEVICE_NOT_AVAILABLE: ::windows_sys::core::HRESULT = -2131886046i32;
pub const RTC_E_NOT_ALLOWED: ::windows_sys::core::HRESULT = -2131885950i32;
pub const RTC_E_NOT_EXIST: ::windows_sys::core::HRESULT = -2131885992i32;
pub const RTC_E_NOT_PRESENCE_PROFILE: ::windows_sys::core::HRESULT = -2131885974i32;
pub const RTC_E_NO_BUDDY: ::windows_sys::core::HRESULT = -2131885996i32;
pub const RTC_E_NO_DEVICE: ::windows_sys::core::HRESULT = -2131886035i32;
pub const RTC_E_NO_GROUP: ::windows_sys::core::HRESULT = -2131885999i32;
pub const RTC_E_NO_PROFILE: ::windows_sys::core::HRESULT = -2131886037i32;
pub const RTC_E_NO_REALM: ::windows_sys::core::HRESULT = -2131885994i32;
pub const RTC_E_NO_TRANSPORT: ::windows_sys::core::HRESULT = -2131885993i32;
pub const RTC_E_NO_WATCHER: ::windows_sys::core::HRESULT = -2131885995i32;
pub const RTC_E_OPERATION_WITH_TOO_MANY_PARTICIPANTS: ::windows_sys::core::HRESULT = -2131886018i32;
pub const RTC_E_PINT_STATUS_REJECTED_ALL_BUSY: ::windows_sys::core::HRESULT = -2131755001i32;
pub const RTC_E_PINT_STATUS_REJECTED_BADNUMBER: ::windows_sys::core::HRESULT = -2131754997i32;
pub const RTC_E_PINT_STATUS_REJECTED_BUSY: ::windows_sys::core::HRESULT = -2131755003i32;
pub const RTC_E_PINT_STATUS_REJECTED_CANCELLED: ::windows_sys::core::HRESULT = -2131754998i32;
pub const RTC_E_PINT_STATUS_REJECTED_NO_ANSWER: ::windows_sys::core::HRESULT = -2131755002i32;
pub const RTC_E_PINT_STATUS_REJECTED_PL_FAILED: ::windows_sys::core::HRESULT = -2131755000i32;
pub const RTC_E_PINT_STATUS_REJECTED_SW_FAILED: ::windows_sys::core::HRESULT = -2131754999i32;
pub const RTC_E_PLATFORM_NOT_SUPPORTED: ::windows_sys::core::HRESULT = -2131885952i32;
pub const RTC_E_POLICY_NOT_ALLOW: ::windows_sys::core::HRESULT = -2131886012i32;
pub const RTC_E_PORT_MANAGER_ALREADY_SET: ::windows_sys::core::HRESULT = -2131885956i32;
pub const RTC_E_PORT_MAPPING_FAILED: ::windows_sys::core::HRESULT = -2131886010i32;
pub const RTC_E_PORT_MAPPING_UNAVAILABLE: ::windows_sys::core::HRESULT = -2131886011i32;
pub const RTC_E_PRESENCE_ENABLED: ::windows_sys::core::HRESULT = -2131885982i32;
pub const RTC_E_PRESENCE_NOT_ENABLED: ::windows_sys::core::HRESULT = -2131886040i32;
pub const RTC_E_PROFILE_INVALID_SERVER_AUTHMETHOD: ::windows_sys::core::HRESULT = -2131886024i32;
pub const RTC_E_PROFILE_INVALID_SERVER_PROTOCOL: ::windows_sys::core::HRESULT = -2131886025i32;
pub const RTC_E_PROFILE_INVALID_SERVER_ROLE: ::windows_sys::core::HRESULT = -2131886023i32;
pub const RTC_E_PROFILE_INVALID_SESSION: ::windows_sys::core::HRESULT = -2131886021i32;
pub const RTC_E_PROFILE_INVALID_SESSION_PARTY: ::windows_sys::core::HRESULT = -2131886020i32;
pub const RTC_E_PROFILE_INVALID_SESSION_TYPE: ::windows_sys::core::HRESULT = -2131886019i32;
pub const RTC_E_PROFILE_MULTIPLE_REGISTRARS: ::windows_sys::core::HRESULT = -2131886022i32;
pub const RTC_E_PROFILE_NO_KEY: ::windows_sys::core::HRESULT = -2131886032i32;
pub const RTC_E_PROFILE_NO_NAME: ::windows_sys::core::HRESULT = -2131886031i32;
pub const RTC_E_PROFILE_NO_PROVISION: ::windows_sys::core::HRESULT = -2131886033i32;
pub const RTC_E_PROFILE_NO_SERVER: ::windows_sys::core::HRESULT = -2131886028i32;
pub const RTC_E_PROFILE_NO_SERVER_ADDRESS: ::windows_sys::core::HRESULT = -2131886027i32;
pub const RTC_E_PROFILE_NO_SERVER_PROTOCOL: ::windows_sys::core::HRESULT = -2131886026i32;
pub const RTC_E_PROFILE_NO_USER: ::windows_sys::core::HRESULT = -2131886030i32;
pub const RTC_E_PROFILE_NO_USER_URI: ::windows_sys::core::HRESULT = -2131886029i32;
pub const RTC_E_PROFILE_SERVER_UNAUTHORIZED: ::windows_sys::core::HRESULT = -2131886014i32;
pub const RTC_E_REDIRECT_PROCESSING_FAILED: ::windows_sys::core::HRESULT = -2131885959i32;
pub const RTC_E_REFER_NOT_ACCEPTED: ::windows_sys::core::HRESULT = -2131885968i32;
pub const RTC_E_REFER_NOT_ALLOWED: ::windows_sys::core::HRESULT = -2131885967i32;
pub const RTC_E_REFER_NOT_EXIST: ::windows_sys::core::HRESULT = -2131885966i32;
pub const RTC_E_REGISTRATION_DEACTIVATED: ::windows_sys::core::HRESULT = -2131885949i32;
pub const RTC_E_REGISTRATION_REJECTED: ::windows_sys::core::HRESULT = -2131885948i32;
pub const RTC_E_REGISTRATION_UNREGISTERED: ::windows_sys::core::HRESULT = -2131885947i32;
pub const RTC_E_ROAMING_ENABLED: ::windows_sys::core::HRESULT = -2131885981i32;
pub const RTC_E_ROAMING_FAILED: ::windows_sys::core::HRESULT = -2131886002i32;
pub const RTC_E_ROAMING_OPERATION_INTERRUPTED: ::windows_sys::core::HRESULT = -2131886003i32;
pub const RTC_E_SDP_CONNECTION_ADDR: ::windows_sys::core::HRESULT = -2131886070i32;
pub const RTC_E_SDP_FAILED_TO_BUILD: ::windows_sys::core::HRESULT = -2131886067i32;
pub const RTC_E_SDP_MULTICAST: ::windows_sys::core::HRESULT = -2131886071i32;
pub const RTC_E_SDP_NOT_PRESENT: ::windows_sys::core::HRESULT = -2131886074i32;
pub const RTC_E_SDP_NO_MEDIA: ::windows_sys::core::HRESULT = -2131886069i32;
pub const RTC_E_SDP_PARSE_FAILED: ::windows_sys::core::HRESULT = -2131886073i32;
pub const RTC_E_SDP_UPDATE_FAILED: ::windows_sys::core::HRESULT = -2131886072i32;
pub const RTC_E_SECURITY_LEVEL_ALREADY_SET: ::windows_sys::core::HRESULT = -2131885955i32;
pub const RTC_E_SECURITY_LEVEL_NOT_COMPATIBLE: ::windows_sys::core::HRESULT = -2131886009i32;
pub const RTC_E_SECURITY_LEVEL_NOT_DEFINED: ::windows_sys::core::HRESULT = -2131886008i32;
pub const RTC_E_SECURITY_LEVEL_NOT_SUPPORTED_BY_PARTICIPANT: ::windows_sys::core::HRESULT = -2131886007i32;
pub const RTC_E_SIP_ADDITIONAL_PARTY_IN_TWO_PARTY_SESSION: ::windows_sys::core::HRESULT = -2131885986i32;
pub const RTC_E_SIP_AUTH_FAILED: ::windows_sys::core::HRESULT = -2131886063i32;
pub const RTC_E_SIP_AUTH_HEADER_SENT: ::windows_sys::core::HRESULT = -2131886065i32;
pub const RTC_E_SIP_AUTH_TIME_SKEW: ::windows_sys::core::HRESULT = -2131885972i32;
pub const RTC_E_SIP_AUTH_TYPE_NOT_SUPPORTED: ::windows_sys::core::HRESULT = -2131886064i32;
pub const RTC_E_SIP_CALL_CONNECTION_NOT_ESTABLISHED: ::windows_sys::core::HRESULT = -2131885987i32;
pub const RTC_E_SIP_CALL_DISCONNECTED: ::windows_sys::core::HRESULT = -2131886055i32;
pub const RTC_E_SIP_CODECS_DO_NOT_MATCH: ::windows_sys::core::HRESULT = -2131886080i32;
pub const RTC_E_SIP_DNS_FAIL: ::windows_sys::core::HRESULT = -2131885978i32;
pub const RTC_E_SIP_HEADER_NOT_PRESENT: ::windows_sys::core::HRESULT = -2131886075i32;
pub const RTC_E_SIP_HIGH_SECURITY_SET_TLS: ::windows_sys::core::HRESULT = -2131886016i32;
pub const RTC_E_SIP_HOLD_OPERATION_PENDING: ::windows_sys::core::HRESULT = -2131885965i32;
pub const RTC_E_SIP_INVALID_CERTIFICATE: ::windows_sys::core::HRESULT = -2131885979i32;
pub const RTC_E_SIP_INVITEE_PARTY_TIMEOUT: ::windows_sys::core::HRESULT = -2131885973i32;
pub const RTC_E_SIP_INVITE_TRANSACTION_PENDING: ::windows_sys::core::HRESULT = -2131886066i32;
pub const RTC_E_SIP_NEED_MORE_DATA: ::windows_sys::core::HRESULT = -2131886056i32;
pub const RTC_E_SIP_NO_STREAM: ::windows_sys::core::HRESULT = -2131886077i32;
pub const RTC_E_SIP_OTHER_PARTY_JOIN_IN_PROGRESS: ::windows_sys::core::HRESULT = -2131885984i32;
pub const RTC_E_SIP_PARSE_FAILED: ::windows_sys::core::HRESULT = -2131886076i32;
pub const RTC_E_SIP_PARTY_ALREADY_IN_SESSION: ::windows_sys::core::HRESULT = -2131885985i32;
pub const RTC_E_SIP_PEER_PARTICIPANT_IN_MULTIPARTY_SESSION: ::windows_sys::core::HRESULT = -2131885951i32;
pub const RTC_E_SIP_REFER_OPERATION_PENDING: ::windows_sys::core::HRESULT = -2131885953i32;
pub const RTC_E_SIP_REQUEST_DESTINATION_ADDR_NOT_PRESENT: ::windows_sys::core::HRESULT = -2131886054i32;
pub const RTC_E_SIP_SSL_NEGOTIATION_TIMEOUT: ::windows_sys::core::HRESULT = -2131886051i32;
pub const RTC_E_SIP_SSL_TUNNEL_FAILED: ::windows_sys::core::HRESULT = -2131886052i32;
pub const RTC_E_SIP_STACK_SHUTDOWN: ::windows_sys::core::HRESULT = -2131886050i32;
pub const RTC_E_SIP_STREAM_NOT_PRESENT: ::windows_sys::core::HRESULT = -2131886078i32;
pub const RTC_E_SIP_STREAM_PRESENT: ::windows_sys::core::HRESULT = -2131886079i32;
pub const RTC_E_SIP_TCP_FAIL: ::windows_sys::core::HRESULT = -2131885977i32;
pub const RTC_E_SIP_TIMEOUT: ::windows_sys::core::HRESULT = -2131886068i32;
pub const RTC_E_SIP_TLS_FAIL: ::windows_sys::core::HRESULT = -2131885975i32;
pub const RTC_E_SIP_TLS_INCOMPATIBLE_ENCRYPTION: ::windows_sys::core::HRESULT = -2131885980i32;
pub const RTC_E_SIP_TRANSPORT_NOT_SUPPORTED: ::windows_sys::core::HRESULT = -2131886057i32;
pub const RTC_E_SIP_UDP_SIZE_EXCEEDED: ::windows_sys::core::HRESULT = -2131886053i32;
pub const RTC_E_SIP_UNHOLD_OPERATION_PENDING: ::windows_sys::core::HRESULT = -2131885964i32;
pub const RTC_E_START_STREAM: ::windows_sys::core::HRESULT = -2131886045i32;
pub const RTC_E_STATUS_CLIENT_ADDRESS_INCOMPLETE: ::windows_sys::core::HRESULT = -2131820060i32;
pub const RTC_E_STATUS_CLIENT_AMBIGUOUS: ::windows_sys::core::HRESULT = -2131820059i32;
pub const RTC_E_STATUS_CLIENT_BAD_EXTENSION: ::windows_sys::core::HRESULT = -2131820124i32;
pub const RTC_E_STATUS_CLIENT_BAD_REQUEST: ::windows_sys::core::HRESULT = -2131820144i32;
pub const RTC_E_STATUS_CLIENT_BUSY_HERE: ::windows_sys::core::HRESULT = -2131820058i32;
pub const RTC_E_STATUS_CLIENT_CONFLICT: ::windows_sys::core::HRESULT = -2131820135i32;
pub const RTC_E_STATUS_CLIENT_FORBIDDEN: ::windows_sys::core::HRESULT = -2131820141i32;
pub const RTC_E_STATUS_CLIENT_GONE: ::windows_sys::core::HRESULT = -2131820134i32;
pub const RTC_E_STATUS_CLIENT_LENGTH_REQUIRED: ::windows_sys::core::HRESULT = -2131820133i32;
pub const RTC_E_STATUS_CLIENT_LOOP_DETECTED: ::windows_sys::core::HRESULT = -2131820062i32;
pub const RTC_E_STATUS_CLIENT_METHOD_NOT_ALLOWED: ::windows_sys::core::HRESULT = -2131820139i32;
pub const RTC_E_STATUS_CLIENT_NOT_ACCEPTABLE: ::windows_sys::core::HRESULT = -2131820138i32;
pub const RTC_E_STATUS_CLIENT_NOT_FOUND: ::windows_sys::core::HRESULT = -2131820140i32;
pub const RTC_E_STATUS_CLIENT_PAYMENT_REQUIRED: ::windows_sys::core::HRESULT = -2131820142i32;
pub const RTC_E_STATUS_CLIENT_PROXY_AUTHENTICATION_REQUIRED: ::windows_sys::core::HRESULT = -2131820137i32;
pub const RTC_E_STATUS_CLIENT_REQUEST_ENTITY_TOO_LARGE: ::windows_sys::core::HRESULT = -2131820131i32;
pub const RTC_E_STATUS_CLIENT_REQUEST_TIMEOUT: ::windows_sys::core::HRESULT = -2131820136i32;
pub const RTC_E_STATUS_CLIENT_REQUEST_URI_TOO_LARGE: ::windows_sys::core::HRESULT = -2131820130i32;
pub const RTC_E_STATUS_CLIENT_TEMPORARILY_NOT_AVAILABLE: ::windows_sys::core::HRESULT = -2131820064i32;
pub const RTC_E_STATUS_CLIENT_TOO_MANY_HOPS: ::windows_sys::core::HRESULT = -2131820061i32;
pub const RTC_E_STATUS_CLIENT_TRANSACTION_DOES_NOT_EXIST: ::windows_sys::core::HRESULT = -2131820063i32;
pub const RTC_E_STATUS_CLIENT_UNAUTHORIZED: ::windows_sys::core::HRESULT = -2131820143i32;
pub const RTC_E_STATUS_CLIENT_UNSUPPORTED_MEDIA_TYPE: ::windows_sys::core::HRESULT = -2131820129i32;
pub const RTC_E_STATUS_GLOBAL_BUSY_EVERYWHERE: ::windows_sys::core::HRESULT = -2131819944i32;
pub const RTC_E_STATUS_GLOBAL_DECLINE: ::windows_sys::core::HRESULT = -2131819941i32;
pub const RTC_E_STATUS_GLOBAL_DOES_NOT_EXIST_ANYWHERE: ::windows_sys::core::HRESULT = -2131819940i32;
pub const RTC_E_STATUS_GLOBAL_NOT_ACCEPTABLE: ::windows_sys::core::HRESULT = -2131819938i32;
pub const RTC_E_STATUS_INFO_CALL_FORWARDING: ::windows_sys::core::HRESULT = 15663285i32;
pub const RTC_E_STATUS_INFO_QUEUED: ::windows_sys::core::HRESULT = 15663286i32;
pub const RTC_E_STATUS_INFO_RINGING: ::windows_sys::core::HRESULT = 15663284i32;
pub const RTC_E_STATUS_INFO_TRYING: ::windows_sys::core::HRESULT = 15663204i32;
pub const RTC_E_STATUS_NOT_ACCEPTABLE_HERE: ::windows_sys::core::HRESULT = -2131820056i32;
pub const RTC_E_STATUS_REDIRECT_ALTERNATIVE_SERVICE: ::windows_sys::core::HRESULT = -2131820164i32;
pub const RTC_E_STATUS_REDIRECT_MOVED_PERMANENTLY: ::windows_sys::core::HRESULT = -2131820243i32;
pub const RTC_E_STATUS_REDIRECT_MOVED_TEMPORARILY: ::windows_sys::core::HRESULT = -2131820242i32;
pub const RTC_E_STATUS_REDIRECT_MULTIPLE_CHOICES: ::windows_sys::core::HRESULT = -2131820244i32;
pub const RTC_E_STATUS_REDIRECT_SEE_OTHER: ::windows_sys::core::HRESULT = -2131820241i32;
pub const RTC_E_STATUS_REDIRECT_USE_PROXY: ::windows_sys::core::HRESULT = -2131820239i32;
pub const RTC_E_STATUS_REQUEST_TERMINATED: ::windows_sys::core::HRESULT = -2131820057i32;
pub const RTC_E_STATUS_SERVER_BAD_GATEWAY: ::windows_sys::core::HRESULT = -2131820042i32;
pub const RTC_E_STATUS_SERVER_INTERNAL_ERROR: ::windows_sys::core::HRESULT = -2131820044i32;
pub const RTC_E_STATUS_SERVER_NOT_IMPLEMENTED: ::windows_sys::core::HRESULT = -2131820043i32;
pub const RTC_E_STATUS_SERVER_SERVER_TIMEOUT: ::windows_sys::core::HRESULT = -2131820040i32;
pub const RTC_E_STATUS_SERVER_SERVICE_UNAVAILABLE: ::windows_sys::core::HRESULT = -2131820041i32;
pub const RTC_E_STATUS_SERVER_VERSION_NOT_SUPPORTED: ::windows_sys::core::HRESULT = -2131820039i32;
pub const RTC_E_STATUS_SESSION_PROGRESS: ::windows_sys::core::HRESULT = 15663287i32;
pub const RTC_E_STATUS_SUCCESS: ::windows_sys::core::HRESULT = 15663304i32;
pub const RTC_E_TOO_MANY_GROUPS: ::windows_sys::core::HRESULT = -2131885997i32;
pub const RTC_E_TOO_MANY_RETRIES: ::windows_sys::core::HRESULT = -2131885989i32;
pub const RTC_E_TOO_SMALL_EXPIRES_VALUE: ::windows_sys::core::HRESULT = -2131885976i32;
pub const RTC_E_UDP_NOT_SUPPORTED: ::windows_sys::core::HRESULT = -2131885954i32;
pub type RTC_GROUP_EVENT_TYPE = i32;
pub const RTCGET_GROUP_ADD: RTC_GROUP_EVENT_TYPE = 0i32;
pub const RTCGET_GROUP_REMOVE: RTC_GROUP_EVENT_TYPE = 1i32;
pub const RTCGET_GROUP_UPDATE: RTC_GROUP_EVENT_TYPE = 2i32;
pub const RTCGET_GROUP_BUDDY_ADD: RTC_GROUP_EVENT_TYPE = 3i32;
pub const RTCGET_GROUP_BUDDY_REMOVE: RTC_GROUP_EVENT_TYPE = 4i32;
pub const RTCGET_GROUP_ROAMED: RTC_GROUP_EVENT_TYPE = 5i32;
pub type RTC_LISTEN_MODE = i32;
pub const RTCLM_NONE: RTC_LISTEN_MODE = 0i32;
pub const RTCLM_DYNAMIC: RTC_LISTEN_MODE = 1i32;
pub const RTCLM_BOTH: RTC_LISTEN_MODE = 2i32;
pub type RTC_MEDIA_EVENT_REASON = i32;
pub const RTCMER_NORMAL: RTC_MEDIA_EVENT_REASON = 0i32;
pub const RTCMER_HOLD: RTC_MEDIA_EVENT_REASON = 1i32;
pub const RTCMER_TIMEOUT: RTC_MEDIA_EVENT_REASON = 2i32;
pub const RTCMER_BAD_DEVICE: RTC_MEDIA_EVENT_REASON = 3i32;
pub const RTCMER_NO_PORT: RTC_MEDIA_EVENT_REASON = 4i32;
pub const RTCMER_PORT_MAPPING_FAILED: RTC_MEDIA_EVENT_REASON = 5i32;
pub const RTCMER_REMOTE_REQUEST: RTC_MEDIA_EVENT_REASON = 6i32;
pub type RTC_MEDIA_EVENT_TYPE = i32;
pub const RTCMET_STOPPED: RTC_MEDIA_EVENT_TYPE = 0i32;
pub const RTCMET_STARTED: RTC_MEDIA_EVENT_TYPE = 1i32;
pub const RTCMET_FAILED: RTC_MEDIA_EVENT_TYPE = 2i32;
pub type RTC_MESSAGING_EVENT_TYPE = i32;
pub const RTCMSET_MESSAGE: RTC_MESSAGING_EVENT_TYPE = 0i32;
pub const RTCMSET_STATUS: RTC_MESSAGING_EVENT_TYPE = 1i32;
pub type RTC_MESSAGING_USER_STATUS = i32;
pub const RTCMUS_IDLE: RTC_MESSAGING_USER_STATUS = 0i32;
pub const RTCMUS_TYPING: RTC_MESSAGING_USER_STATUS = 1i32;
pub type RTC_OFFER_WATCHER_MODE = i32;
pub const RTCOWM_OFFER_WATCHER_EVENT: RTC_OFFER_WATCHER_MODE = 0i32;
pub const RTCOWM_AUTOMATICALLY_ADD_WATCHER: RTC_OFFER_WATCHER_MODE = 1i32;
pub type RTC_PARTICIPANT_STATE = i32;
pub const RTCPS_IDLE: RTC_PARTICIPANT_STATE = 0i32;
pub const RTCPS_PENDING: RTC_PARTICIPANT_STATE = 1i32;
pub const RTCPS_INCOMING: RTC_PARTICIPANT_STATE = 2i32;
pub const RTCPS_ANSWERING: RTC_PARTICIPANT_STATE = 3i32;
pub const RTCPS_INPROGRESS: RTC_PARTICIPANT_STATE = 4i32;
pub const RTCPS_ALERTING: RTC_PARTICIPANT_STATE = 5i32;
pub const RTCPS_CONNECTED: RTC_PARTICIPANT_STATE = 6i32;
pub const RTCPS_DISCONNECTING: RTC_PARTICIPANT_STATE = 7i32;
pub const RTCPS_DISCONNECTED: RTC_PARTICIPANT_STATE = 8i32;
pub type RTC_PORT_TYPE = i32;
pub const RTCPT_AUDIO_RTP: RTC_PORT_TYPE = 0i32;
pub const RTCPT_AUDIO_RTCP: RTC_PORT_TYPE = 1i32;
pub const RTCPT_VIDEO_RTP: RTC_PORT_TYPE = 2i32;
pub const RTCPT_VIDEO_RTCP: RTC_PORT_TYPE = 3i32;
pub const RTCPT_SIP: RTC_PORT_TYPE = 4i32;
pub type RTC_PRESENCE_PROPERTY = i32;
pub const RTCPP_PHONENUMBER: RTC_PRESENCE_PROPERTY = 0i32;
pub const RTCPP_DISPLAYNAME: RTC_PRESENCE_PROPERTY = 1i32;
pub const RTCPP_EMAIL: RTC_PRESENCE_PROPERTY = 2i32;
pub const RTCPP_DEVICE_NAME: RTC_PRESENCE_PROPERTY = 3i32;
pub const RTCPP_MULTIPLE: RTC_PRESENCE_PROPERTY = 4i32;
pub type RTC_PRESENCE_STATUS = i32;
pub const RTCXS_PRESENCE_OFFLINE: RTC_PRESENCE_STATUS = 0i32;
pub const RTCXS_PRESENCE_ONLINE: RTC_PRESENCE_STATUS = 1i32;
pub const RTCXS_PRESENCE_AWAY: RTC_PRESENCE_STATUS = 2i32;
pub const RTCXS_PRESENCE_IDLE: RTC_PRESENCE_STATUS = 3i32;
pub const RTCXS_PRESENCE_BUSY: RTC_PRESENCE_STATUS = 4i32;
pub const RTCXS_PRESENCE_BE_RIGHT_BACK: RTC_PRESENCE_STATUS = 5i32;
pub const RTCXS_PRESENCE_ON_THE_PHONE: RTC_PRESENCE_STATUS = 6i32;
pub const RTCXS_PRESENCE_OUT_TO_LUNCH: RTC_PRESENCE_STATUS = 7i32;
pub type RTC_PRIVACY_MODE = i32;
pub const RTCPM_BLOCK_LIST_EXCLUDED: RTC_PRIVACY_MODE = 0i32;
pub const RTCPM_ALLOW_LIST_ONLY: RTC_PRIVACY_MODE = 1i32;
pub type RTC_PROFILE_EVENT_TYPE = i32;
pub const RTCPFET_PROFILE_GET: RTC_PROFILE_EVENT_TYPE = 0i32;
pub const RTCPFET_PROFILE_UPDATE: RTC_PROFILE_EVENT_TYPE = 1i32;
pub type RTC_PROVIDER_URI = i32;
pub const RTCPU_URIHOMEPAGE: RTC_PROVIDER_URI = 0i32;
pub const RTCPU_URIHELPDESK: RTC_PROVIDER_URI = 1i32;
pub const RTCPU_URIPERSONALACCOUNT: RTC_PROVIDER_URI = 2i32;
pub const RTCPU_URIDISPLAYDURINGCALL: RTC_PROVIDER_URI = 3i32;
pub const RTCPU_URIDISPLAYDURINGIDLE: RTC_PROVIDER_URI = 4i32;
pub type RTC_REGISTRATION_STATE = i32;
pub const RTCRS_NOT_REGISTERED: RTC_REGISTRATION_STATE = 0i32;
pub const RTCRS_REGISTERING: RTC_REGISTRATION_STATE = 1i32;
pub const RTCRS_REGISTERED: RTC_REGISTRATION_STATE = 2i32;
pub const RTCRS_REJECTED: RTC_REGISTRATION_STATE = 3i32;
pub const RTCRS_UNREGISTERING: RTC_REGISTRATION_STATE = 4i32;
pub const RTCRS_ERROR: RTC_REGISTRATION_STATE = 5i32;
pub const RTCRS_LOGGED_OFF: RTC_REGISTRATION_STATE = 6i32;
pub const RTCRS_LOCAL_PA_LOGGED_OFF: RTC_REGISTRATION_STATE = 7i32;
pub const RTCRS_REMOTE_PA_LOGGED_OFF: RTC_REGISTRATION_STATE = 8i32;
pub type RTC_REINVITE_STATE = i32;
pub const RTCRIN_INCOMING: RTC_REINVITE_STATE = 0i32;
pub const RTCRIN_SUCCEEDED: RTC_REINVITE_STATE = 1i32;
pub const RTCRIN_FAIL: RTC_REINVITE_STATE = 2i32;
pub type RTC_RING_TYPE = i32;
pub const RTCRT_PHONE: RTC_RING_TYPE = 0i32;
pub const RTCRT_MESSAGE: RTC_RING_TYPE = 1i32;
pub const RTCRT_RINGBACK: RTC_RING_TYPE = 2i32;
pub type RTC_ROAMING_EVENT_TYPE = i32;
pub const RTCRET_BUDDY_ROAMING: RTC_ROAMING_EVENT_TYPE = 0i32;
pub const RTCRET_WATCHER_ROAMING: RTC_ROAMING_EVENT_TYPE = 1i32;
pub const RTCRET_PRESENCE_ROAMING: RTC_ROAMING_EVENT_TYPE = 2i32;
pub const RTCRET_PROFILE_ROAMING: RTC_ROAMING_EVENT_TYPE = 3i32;
pub const RTCRET_WPENDING_ROAMING: RTC_ROAMING_EVENT_TYPE = 4i32;
pub type RTC_SECURITY_LEVEL = i32;
pub const RTCSECL_UNSUPPORTED: RTC_SECURITY_LEVEL = 1i32;
pub const RTCSECL_SUPPORTED: RTC_SECURITY_LEVEL = 2i32;
pub const RTCSECL_REQUIRED: RTC_SECURITY_LEVEL = 3i32;
pub type RTC_SECURITY_TYPE = i32;
pub const RTCSECT_AUDIO_VIDEO_MEDIA_ENCRYPTION: RTC_SECURITY_TYPE = 0i32;
pub const RTCSECT_T120_MEDIA_ENCRYPTION: RTC_SECURITY_TYPE = 1i32;
pub type RTC_SESSION_REFER_STATUS = i32;
pub const RTCSRS_REFERRING: RTC_SESSION_REFER_STATUS = 0i32;
pub const RTCSRS_ACCEPTED: RTC_SESSION_REFER_STATUS = 1i32;
pub const RTCSRS_ERROR: RTC_SESSION_REFER_STATUS = 2i32;
pub const RTCSRS_REJECTED: RTC_SESSION_REFER_STATUS = 3i32;
pub const RTCSRS_DROPPED: RTC_SESSION_REFER_STATUS = 4i32;
pub const RTCSRS_DONE: RTC_SESSION_REFER_STATUS = 5i32;
pub type RTC_SESSION_STATE = i32;
pub const RTCSS_IDLE: RTC_SESSION_STATE = 0i32;
pub const RTCSS_INCOMING: RTC_SESSION_STATE = 1i32;
pub const RTCSS_ANSWERING: RTC_SESSION_STATE = 2i32;
pub const RTCSS_INPROGRESS: RTC_SESSION_STATE = 3i32;
pub const RTCSS_CONNECTED: RTC_SESSION_STATE = 4i32;
pub const RTCSS_DISCONNECTED: RTC_SESSION_STATE = 5i32;
pub const RTCSS_HOLD: RTC_SESSION_STATE = 6i32;
pub const RTCSS_REFER: RTC_SESSION_STATE = 7i32;
pub type RTC_SESSION_TYPE = i32;
pub const RTCST_PC_TO_PC: RTC_SESSION_TYPE = 0i32;
pub const RTCST_PC_TO_PHONE: RTC_SESSION_TYPE = 1i32;
pub const RTCST_PHONE_TO_PHONE: RTC_SESSION_TYPE = 2i32;
pub const RTCST_IM: RTC_SESSION_TYPE = 3i32;
pub const RTCST_MULTIPARTY_IM: RTC_SESSION_TYPE = 4i32;
pub const RTCST_APPLICATION: RTC_SESSION_TYPE = 5i32;
pub const RTC_S_ROAMING_NOT_SUPPORTED: ::windows_sys::core::HRESULT = 15597633i32;
pub type RTC_T120_APPLET = i32;
pub const RTCTA_WHITEBOARD: RTC_T120_APPLET = 0i32;
pub const RTCTA_APPSHARING: RTC_T120_APPLET = 1i32;
pub type RTC_TERMINATE_REASON = i32;
pub const RTCTR_NORMAL: RTC_TERMINATE_REASON = 0i32;
pub const RTCTR_DND: RTC_TERMINATE_REASON = 1i32;
pub const RTCTR_BUSY: RTC_TERMINATE_REASON = 2i32;
pub const RTCTR_REJECT: RTC_TERMINATE_REASON = 3i32;
pub const RTCTR_TIMEOUT: RTC_TERMINATE_REASON = 4i32;
pub const RTCTR_SHUTDOWN: RTC_TERMINATE_REASON = 5i32;
pub const RTCTR_INSUFFICIENT_SECURITY_LEVEL: RTC_TERMINATE_REASON = 6i32;
pub const RTCTR_NOT_SUPPORTED: RTC_TERMINATE_REASON = 7i32;
pub type RTC_USER_SEARCH_COLUMN = i32;
pub const RTCUSC_URI: RTC_USER_SEARCH_COLUMN = 0i32;
pub const RTCUSC_DISPLAYNAME: RTC_USER_SEARCH_COLUMN = 1i32;
pub const RTCUSC_TITLE: RTC_USER_SEARCH_COLUMN = 2i32;
pub const RTCUSC_OFFICE: RTC_USER_SEARCH_COLUMN = 3i32;
pub const RTCUSC_PHONE: RTC_USER_SEARCH_COLUMN = 4i32;
pub const RTCUSC_COMPANY: RTC_USER_SEARCH_COLUMN = 5i32;
pub const RTCUSC_CITY: RTC_USER_SEARCH_COLUMN = 6i32;
pub const RTCUSC_STATE: RTC_USER_SEARCH_COLUMN = 7i32;
pub const RTCUSC_COUNTRY: RTC_USER_SEARCH_COLUMN = 8i32;
pub const RTCUSC_EMAIL: RTC_USER_SEARCH_COLUMN = 9i32;
pub type RTC_USER_SEARCH_PREFERENCE = i32;
pub const RTCUSP_MAX_MATCHES: RTC_USER_SEARCH_PREFERENCE = 0i32;
pub const RTCUSP_TIME_LIMIT: RTC_USER_SEARCH_PREFERENCE = 1i32;
pub type RTC_VIDEO_DEVICE = i32;
pub const RTCVD_RECEIVE: RTC_VIDEO_DEVICE = 0i32;
pub const RTCVD_PREVIEW: RTC_VIDEO_DEVICE = 1i32;
pub type RTC_WATCHER_EVENT_TYPE = i32;
pub const RTCWET_WATCHER_ADD: RTC_WATCHER_EVENT_TYPE = 0i32;
pub const RTCWET_WATCHER_REMOVE: RTC_WATCHER_EVENT_TYPE = 1i32;
pub const RTCWET_WATCHER_UPDATE: RTC_WATCHER_EVENT_TYPE = 2i32;
pub const RTCWET_WATCHER_OFFERING: RTC_WATCHER_EVENT_TYPE = 3i32;
pub const RTCWET_WATCHER_ROAMED: RTC_WATCHER_EVENT_TYPE = 4i32;
pub type RTC_WATCHER_MATCH_MODE = i32;
pub const RTCWMM_EXACT_MATCH: RTC_WATCHER_MATCH_MODE = 0i32;
pub const RTCWMM_BEST_ACE_MATCH: RTC_WATCHER_MATCH_MODE = 1i32;
pub type RTC_WATCHER_STATE = i32;
pub const RTCWS_UNKNOWN: RTC_WATCHER_STATE = 0i32;
pub const RTCWS_OFFERING: RTC_WATCHER_STATE = 1i32;
pub const RTCWS_ALLOWED: RTC_WATCHER_STATE = 2i32;
pub const RTCWS_BLOCKED: RTC_WATCHER_STATE = 3i32;
pub const RTCWS_DENIED: RTC_WATCHER_STATE = 4i32;
pub const RTCWS_PROMPT: RTC_WATCHER_STATE = 5i32;
pub const STATUS_SEVERITY_RTC_ERROR: u32 = 2u32;
#[repr(C)]
#[cfg(feature = "Win32_Networking_WinSock")]
pub struct TRANSPORT_SETTING {
pub SettingId: super::super::Networking::WinSock::TRANSPORT_SETTING_ID,
pub Length: *mut u32,
pub Value: *mut u8,
}
#[cfg(feature = "Win32_Networking_WinSock")]
impl ::core::marker::Copy for TRANSPORT_SETTING {}
#[cfg(feature = "Win32_Networking_WinSock")]
impl ::core::clone::Clone for TRANSPORT_SETTING {
fn clone(&self) -> Self {
*self
}
}
|
use criterion::{criterion_group, criterion_main, Benchmark, Criterion, Throughput};
use futures::compat::Future01CompatExt;
use rand::{distributions::Alphanumeric, rngs::SmallRng, thread_rng, Rng, SeedableRng};
use tempfile::tempdir;
use vector::test_util::{
next_addr, runtime, send_lines, shutdown_on_idle, wait_for_tcp, CountReceiver,
};
use vector::{
buffers::BufferConfig,
sinks, sources,
topology::{self, config},
};
fn benchmark_buffers(c: &mut Criterion) {
let num_lines: usize = 100_000;
let line_size: usize = 100;
let in_addr = next_addr();
let out_addr = next_addr();
let data_dir = tempdir().unwrap();
let data_dir = data_dir.path().to_path_buf();
let data_dir2 = data_dir.clone();
c.bench(
"buffers",
Benchmark::new("in-memory", move |b| {
b.iter_with_setup(
|| {
let mut config = config::Config::empty();
config.add_source(
"in",
sources::socket::SocketConfig::make_tcp_config(in_addr),
);
config.add_sink(
"out",
&["in"],
sinks::socket::SocketSinkConfig::make_basic_tcp_config(
out_addr.to_string(),
),
);
config.sinks["out"].buffer = BufferConfig::Memory {
max_events: 100,
when_full: Default::default(),
};
let mut rt = runtime();
let (output_lines, topology) = rt.block_on_std(async move {
let output_lines = CountReceiver::receive_lines(out_addr);
let (topology, _crash) = topology::start(config, false).await.unwrap();
(output_lines, topology)
});
wait_for_tcp(in_addr);
(rt, topology, output_lines)
},
|(mut rt, topology, output_lines)| {
rt.block_on_std(async move {
let lines = random_lines(line_size).take(num_lines);
send_lines(in_addr, lines).await.unwrap();
topology.stop().compat().await.unwrap();
assert_eq!(num_lines, output_lines.wait().await.len());
});
shutdown_on_idle(rt);
},
);
})
.with_function("on-disk", move |b| {
b.iter_with_setup(
|| {
let mut config = config::Config::empty();
config.add_source(
"in",
sources::socket::SocketConfig::make_tcp_config(in_addr),
);
config.add_sink(
"out",
&["in"],
sinks::socket::SocketSinkConfig::make_basic_tcp_config(
out_addr.to_string(),
),
);
config.sinks["out"].buffer = BufferConfig::Disk {
max_size: 1_000_000,
when_full: Default::default(),
};
config.global.data_dir = Some(data_dir.clone());
let mut rt = runtime();
let (output_lines, topology) = rt.block_on_std(async move {
let output_lines = CountReceiver::receive_lines(out_addr);
let (topology, _crash) = topology::start(config, false).await.unwrap();
(output_lines, topology)
});
wait_for_tcp(in_addr);
(rt, topology, output_lines)
},
|(mut rt, topology, output_lines)| {
rt.block_on_std(async move {
let lines = random_lines(line_size).take(num_lines);
send_lines(in_addr, lines).await.unwrap();
tokio::time::delay_for(std::time::Duration::from_secs(100)).await;
topology.stop().compat().await.unwrap();
assert_eq!(num_lines, output_lines.wait().await.len());
});
shutdown_on_idle(rt);
},
);
})
.with_function("low-limit-on-disk", move |b| {
b.iter_with_setup(
|| {
let mut config = config::Config::empty();
config.add_source(
"in",
sources::socket::SocketConfig::make_tcp_config(in_addr),
);
config.add_sink(
"out",
&["in"],
sinks::socket::SocketSinkConfig::make_basic_tcp_config(
out_addr.to_string(),
),
);
config.sinks["out"].buffer = BufferConfig::Disk {
max_size: 10_000,
when_full: Default::default(),
};
config.global.data_dir = Some(data_dir2.clone());
let mut rt = runtime();
let (output_lines, topology) = rt.block_on_std(async move {
let output_lines = CountReceiver::receive_lines(out_addr);
let (topology, _crash) = topology::start(config, false).await.unwrap();
(output_lines, topology)
});
wait_for_tcp(in_addr);
(rt, topology, output_lines)
},
|(mut rt, topology, output_lines)| {
rt.block_on_std(async move {
let lines = random_lines(line_size).take(num_lines);
send_lines(in_addr, lines).await.unwrap();
tokio::time::delay_for(std::time::Duration::from_secs(100)).await;
topology.stop().compat().await.unwrap();
assert_eq!(num_lines, output_lines.wait().await.len());
});
shutdown_on_idle(rt);
},
);
})
.sample_size(10)
.noise_threshold(0.05)
.throughput(Throughput::Bytes((num_lines * line_size) as u64)),
);
}
criterion_group!(buffers, benchmark_buffers);
criterion_main!(buffers);
fn random_lines(size: usize) -> impl Iterator<Item = String> {
let mut rng = SmallRng::from_rng(thread_rng()).unwrap();
std::iter::repeat(()).map(move |_| {
rng.sample_iter(&Alphanumeric)
.take(size)
.collect::<String>()
})
}
|
use crate::decode::Decode;
use crate::encode::Encode;
use crate::postgres::protocol::TypeId;
use crate::postgres::{PgData, PgRawBuffer, PgTypeInfo, PgValue, Postgres};
use crate::types::Type;
impl Type<Postgres> for bool {
fn type_info() -> PgTypeInfo {
PgTypeInfo::new(TypeId::BOOL, "BOOL")
}
}
impl Type<Postgres> for [bool] {
fn type_info() -> PgTypeInfo {
PgTypeInfo::new(TypeId::ARRAY_BOOL, "BOOL[]")
}
}
impl Type<Postgres> for Vec<bool> {
fn type_info() -> PgTypeInfo {
<[bool] as Type<Postgres>>::type_info()
}
}
impl Encode<Postgres> for bool {
fn encode(&self, buf: &mut PgRawBuffer) {
buf.push(*self as u8);
}
}
impl<'de> Decode<'de, Postgres> for bool {
fn decode(value: PgValue<'de>) -> crate::Result<Self> {
match value.try_get()? {
PgData::Binary(buf) => Ok(buf.get(0).map(|&b| b != 0).unwrap_or_default()),
PgData::Text("t") => Ok(true),
PgData::Text("f") => Ok(false),
PgData::Text(s) => Err(decode_err!("unexpected value {:?} for boolean", s)),
}
}
}
|
mod client;
mod pipe;
mod server;
mod session;
mod traits;
pub use tokio;
pub use tokio_rustls::rustls;
pub use tokio_rustls::webpki;
pub use client::Client;
pub use server::Server;
|
use super::class;
use super::name;
use super::network;
use super::qtype;
pub struct Question {
pub RawName: Vec<u8>,
pub name: String,
pub qtype: qtype::Type,
pub class: class::Class,
}
impl std::fmt::Display for Question {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
writeln!(fmt, "name:{}", self.name).unwrap();
write!(fmt, "qtype:{}\nclass:{}", self.qtype, self.class)
}
}
pub fn unpack(message: &Vec<u8>, offset: usize) -> Option<(Question, usize)> {
let (raw, o) = match name::unpack(message, offset) {
Some(n) => n,
None => return None,
};
let name = network::CombineName(&raw);
return Some((
Question {
RawName: message[offset..o].to_vec(),
name,
qtype: qtype::unpack(((message[o + 0] as u16) << 8) | (message[o + 1] as u16)),
class: class::unpack(((message[o + 2] as u16) << 8) | (message[o + 3] as u16)),
},
o + 4,
));
}
|
extern crate lazy_static;
extern crate rhai;
extern crate serde;
extern crate serde_json;
use lazy_static::lazy_static;
use regex::{Captures, Match, Regex};
use serde::Serialize;
use std::cmp::{max, min, PartialEq};
use std::str;
const BOM: &str = "\u{FEFF}";
const NO_INDENT: &str = "expected indent regext to be initialized already";
const CANNOT_HOLD_VALUE: &str = "tried to assign value to an invalid token";
const CANNOT_SET_MODE: &str = "tried to set mode of invalid token";
const NO_END_BRACKET: &str = "End of line was reached with no closing bracket for interpolation.";
#[derive(Clone, Serialize)]
struct Position {
line: usize,
column: usize,
}
#[derive(Clone, Serialize)]
struct Loc {
start: Option<Position>,
filename: Option<String>,
end: Option<Position>,
}
#[derive(PartialEq, Debug, Clone, Serialize)]
pub enum AttributeValue {
StringValue(String),
BooleanValue(bool),
}
#[derive(PartialEq, Debug, Clone, Serialize)]
pub enum BlockMode {
Replace,
Prepend,
Append,
}
#[derive(PartialEq, Debug, Clone, Serialize)]
pub enum LexToken {
Colon,
AndAttributes,
Attribute {
name: String,
val: AttributeValue,
must_escape: bool,
},
Block {
val: Option<String>,
mode: BlockMode,
},
Blockcode,
Call {
val: Option<String>,
args: String,
},
Case {
val: Option<String>,
},
Class {
val: Option<String>,
},
Code {
must_escape: bool,
buffer: bool,
val: Option<String>,
},
Comment {
val: Option<String>,
buffer: bool,
},
Default,
Doctype {
val: Option<String>,
},
Dot,
Each {
val: Option<String>,
key: Option<String>,
code: String,
},
EachOf {
val: Option<String>,
value: String,
code: String,
},
ElseIf {
val: Option<String>,
},
Else {
val: Option<String>,
},
EndAttributes,
EndPipelessText,
EndPugInterpolation,
EOS,
Extends,
Filter {
val: Option<String>,
},
ID {
val: Option<String>,
},
If {
val: Option<String>,
},
Include,
Indent {
val: usize,
},
InterpolatedCode {
must_escape: bool,
buffer: bool,
val: Option<String>,
},
Interpolation {
val: Option<String>,
},
MixinBlock,
Mixin {
val: Option<String>,
args: Option<String>,
},
Newline,
Outdent,
Path {
val: Option<String>,
},
Slash,
StartAttributes,
StartPipelessText,
StartPugInterpolation,
Tag {
val: Option<String>,
},
TextHTML {
val: Option<String>,
},
Text {
val: Option<String>,
},
When {
val: Option<String>,
},
While {
val: Option<String>,
},
Yield,
}
impl LexToken {
fn empty_text() -> Self {
Self::Text { val: None }
}
fn has_val(&self) -> bool {
match self {
Self::Block { val, .. }
| Self::Call { val, .. }
| Self::Class { val, .. }
| Self::Code { val, .. }
| Self::Comment { val, .. }
| Self::Each { val, .. }
| Self::EachOf { val, .. }
| Self::ElseIf { val, .. }
| Self::Else { val, .. }
| Self::Filter { val, .. }
| Self::ID { val, .. }
| Self::If { val, .. }
| Self::InterpolatedCode { val, .. }
| Self::Interpolation { val, .. }
| Self::Mixin { val, .. }
| Self::Tag { val, .. }
| Self::TextHTML { val, .. }
| Self::Text { val, .. }
| Self::When { val, .. }
| Self::While { val, .. } => val.is_some(),
_ => false,
}
}
fn set_mode(&mut self, mode: BlockMode) {
let mut new = match self {
Self::Block { val, .. } => Self::Block {
mode,
val: val.take(),
},
_ => std::panic::panic_any(CANNOT_SET_MODE),
};
std::mem::swap(self, &mut new);
}
fn indent_val(val: usize) -> Self {
Self::Indent { val }
}
fn get_str_val(&self) -> Option<&String> {
match self {
Self::Block { val, .. }
| Self::Call { val, .. }
| Self::Class { val, .. }
| Self::Code { val, .. }
| Self::Comment { val, .. }
| Self::Each { val, .. }
| Self::EachOf { val, .. }
| Self::ElseIf { val, .. }
| Self::Else { val, .. }
| Self::Filter { val, .. }
| Self::ID { val, .. }
| Self::If { val, .. }
| Self::InterpolatedCode { val, .. }
| Self::Interpolation { val, .. }
| Self::Mixin { val, .. }
| Self::Tag { val, .. }
| Self::TextHTML { val, .. }
| Self::Text { val, .. }
| Self::When { val, .. }
| Self::While { val, .. } => val.as_ref(),
_ => std::panic::panic_any("cannot get string val"),
}
}
fn with_val(self, _val: String) -> Self {
if self.has_val() {
return self;
}
let val = Some(_val.clone());
match self {
Self::Attribute {
must_escape, name, ..
} => Self::Attribute {
must_escape,
name,
val: AttributeValue::StringValue(_val),
},
Self::Block { mode, .. } => Self::Block { mode, val },
Self::Call { args, .. } => Self::Call { args, val },
Self::Class { .. } => Self::Class { val },
Self::Code {
must_escape,
buffer,
..
} => Self::Code {
must_escape,
buffer,
val,
},
Self::Comment { buffer, .. } => Self::Comment { buffer, val },
Self::Each { key, code, .. } => Self::Each { key, code, val },
Self::EachOf { value, code, .. } => Self::EachOf { value, code, val },
Self::ElseIf { .. } => Self::ElseIf { val },
Self::Else { .. } => Self::Else { val },
Self::Filter { .. } => Self::Filter { val },
Self::ID { .. } => Self::ID { val },
Self::If { .. } => Self::If { val },
//Self::Indent {..} => Self::Indent{val},
Self::InterpolatedCode {
must_escape,
buffer,
..
} => Self::InterpolatedCode {
must_escape,
buffer,
val,
},
Self::Interpolation { .. } => Self::Interpolation { val },
Self::Mixin { args, .. } => Self::Mixin { args, val },
Self::Tag { .. } => Self::Tag { val },
Self::TextHTML { .. } => Self::TextHTML { val },
Self::Text { .. } => Self::Text { val },
Self::When { .. } => Self::When { val },
Self::While { .. } => Self::While { val },
_ => std::panic::panic_any(CANNOT_HOLD_VALUE),
}
}
}
//type Tokenizer = fn(&mut Lexer) -> bool;
mod tokenizers {
use super::*;
fn match_to_len(m: Match) -> usize {
m.as_str().len()
}
pub(super) fn blank(lexer: &mut Lexer) -> bool {
//println!("--blank");
let search = BLANK_LINE_RE.find(&lexer.input).map(match_to_len);
if let Some(_match) = search {
lexer.consume(max(_match, 1) - 1);
lexer.increment_line(1);
return true;
}
false
}
pub(super) fn eos(lexer: &mut Lexer) -> bool {
//println!("--eos");
if lexer.input.len() > 0 {
return false;
}
if lexer.interpolated {
std::panic::panic_any(NO_END_BRACKET);
}
for i in &lexer.indent_stack {
if *i == 0 {
break;
}
lexer
.tokens
.push(lexer.tokend(lexer.tok(LexToken::Outdent)))
}
lexer.tokens.push(lexer.tokend(lexer.tok(LexToken::EOS)));
lexer.ended = true;
return true;
}
pub(super) fn end_interpolation(lexer: &mut Lexer) -> bool {
//println!("--end_interpolation");
if lexer.interpolated && lexer.input.starts_with(']') {
lexer.input.replace_range(0..1, "");
lexer.ended = true;
return true;
}
return false;
}
pub(super) fn doctype(lexer: &mut Lexer) -> bool {
//println!("--doctype");
let tok = lexer.scan_eol(&DOCTYPE_RE, LexToken::Doctype { val: None });
if let Some(tok) = tok {
lexer.tokens.push(lexer.tokend(tok));
return true;
}
false
}
/*
pub(super) fn interpolation(lexer: &mut Lexer) -> bool {
let _match = lexer.scan_eol(&DOCTYPE_RE, LexToken::Doctype { val: None });
}
*/
pub(super) fn case(lexer: &mut Lexer) -> bool {
//println!("--case");
let tok = lexer.scan_eol(&CASE_RE, LexToken::Case { val: None });
if let Some(tok) = tok {
lexer.tokens.push(lexer.tokend(tok));
return true;
}
// TODO negative case
false
}
/*
pub(super) fn when(lexer: &mut Lexer) -> bool {
let tok = lexer.scan_eol(&WHEN_RE, LexToken::When { val: None });
if let Some(tok) = tok {
lexer.tokens.push(lexer.tokend(tok));
return true;
}
false
}
*/
pub(super) fn default(lexer: &mut Lexer) -> bool {
//println!("--default");
let tok = lexer.scan_eol(&DEFAULT_RE, LexToken::Default);
if let Some(tok) = tok {
lexer.tokens.push(lexer.tokend(tok));
return true;
}
//TODO negative case
false
}
pub(super) fn block(lexer: &mut Lexer) -> bool {
//println!("--block");
let captures = BLOCK_NEWLINE_RE.captures(&lexer.input);
if let Some(captures) = captures {
let mut name = captures
.get(1)
.map(|m| m.as_str().trim())
.unwrap_or_default()
.to_string();
let mut comment = String::with_capacity(0);
if name.find("//").is_some() {
comment = format!(
"//{}",
name.split("//").skip(1).collect::<Vec<&str>>().join("//")
);
name = name
.split("//")
.next()
.map(|s| s.trim())
.unwrap_or_default()
.to_string();
}
if name.len() == 0 {
return false;
}
let val = Some(name);
let mut tok = lexer.tok(LexToken::Block {
val,
mode: BlockMode::Replace,
});
let captures_0_len = captures
.get(0)
.map(|m| m.as_str().len())
.unwrap_or_default();
let mut length = min(comment.len(), captures_0_len) - comment.len();
while {
let c = lexer.input.chars().nth(length - 1).unwrap();
c == '\n' || c == '\t' || c == ' '
} {
length -= 1
}
lexer.increment_column(length);
lexer.tokens.push(lexer.tokend(tok));
lexer.consume(min(comment.len(), captures_0_len) - comment.len());
lexer.increment_column(
min(comment.len() + length, captures_0_len) - comment.len() - length,
);
return true;
}
false
}
pub(super) fn mixin_block(lexer: &mut Lexer) -> bool {
//println!("--mixin_block");
let tok = lexer.scan_eol(&BLOCK_RE, LexToken::MixinBlock);
if let Some(tok) = tok {
lexer.tokens.push(lexer.tokend(tok));
true
} else {
false
}
}
pub(super) fn include(lexer: &mut Lexer) -> bool {
//println!("--include");
let tok = lexer.scan(&INCLUDE_RE, LexToken::Include);
if let Some(tok) = tok {
lexer.tokens.push(lexer.tokend(tok));
//TODO filters
let is_path = path(lexer);
/*
if ! is_path {
TODO error
}
*/
return true;
}
false
}
pub(super) fn path(lexer: &mut Lexer) -> bool {
//println!("--path");
let mut tok = lexer.scan_eol(&PATH_RE, LexToken::Path { val: None });
if let Some(mut tok) = tok {
tok.lex_token = match tok.lex_token {
LexToken::Path { val: Some(val) } => LexToken::Path {
val: Some(val.trim().to_string()),
},
_ => tok.lex_token,
};
lexer.tokens.push(lexer.tokend(tok));
return true;
}
false
}
pub(super) fn tag(lexer: &mut Lexer) -> bool {
//println!("--tag");
if let Some(captures) = &TAG_RE.captures(&lexer.input) {
let name = captures.get(1).map(|m| m.as_str().to_string());
let captures_0_len = captures
.get(0)
.map(|m| m.as_str().len())
.unwrap_or_default();
lexer.consume(captures_0_len);
let tok = lexer.tok(LexToken::Tag { val: name });
lexer.increment_column(captures_0_len);
lexer.tokens.push(lexer.tokend(tok));
return true;
}
false
}
pub(super) fn id(lexer: &mut Lexer) -> bool {
//println!("--id");
let tok = lexer.scan(&ID_RE, LexToken::ID { val: None });
if let Some(tok) = tok {
// no idea why I have to clone here to get the length
if let Some(length) = tok.lex_token.get_str_val().clone().map(|s| s.len()) {
lexer.increment_column(length);
}
lexer.tokens.push(lexer.tokend(tok));
return true;
}
// TODO negative case
false
}
pub(super) fn class_name(lexer: &mut Lexer) -> bool {
//println!("--class_name");
let tok = lexer.scan(&CLASSNAME_RE, LexToken::Class { val: None });
if let Some(tok) = tok {
lexer.increment_column(
tok.lex_token
.get_str_val()
.map(|s| s.len())
.unwrap_or_default(),
);
lexer.tokens.push(lexer.tokend(tok));
return true;
}
false
}
pub(super) fn _yield(lexer: &mut Lexer) -> bool {
//println!("--yield");
let tok = lexer.scan_eol(&YIELD_RE, LexToken::Yield);
if let Some(tok) = tok {
lexer.tokens.push(lexer.tokend(tok));
true
} else {
false
}
}
pub(super) fn comment(lexer: &mut Lexer) -> bool {
//println!("--comment");
//let search = COMMENT_RE.find(&lexer.input).map(match_to_len);
let mut val = String::with_capacity(0);
let mut buffer = false;
let mut consume: usize = 0;
let mut result = false;
{
let captures = COMMENT_RE.captures(&lexer.input);
if let Some(captures) = captures {
//println!("captures = {:?}", captures);
val = captures
.get(2)
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
buffer = if let Some(_match) = captures.get(1) {
_match.as_str() != "-"
} else {
true
};
//consume = captures[0].len();
consume = captures
.get(0)
.map(|m| m.as_str().len())
.unwrap_or_default();
result = true
}
}
if result {
let val = Some(val);
lexer.consume(consume);
let tok = lexer.tok(LexToken::Comment { val, buffer });
lexer.increment_column(consume);
lexer.tokens.push(lexer.tokend(tok));
lexer.pipeless_text(0);
}
return result;
}
pub(super) fn indent(lexer: &mut Lexer) -> bool {
//println!("--indent");
let captures = lexer.scan_indentation();
if let Some(captures) = captures.as_ref() {
//println!("captures {:?}", captures)
} else {
//println!("no captures")
}
if let Some(captures) = captures {
let indents = captures.get(1).map(|m| m.as_str().len()).unwrap_or(0);
lexer.increment_line(1);
lexer.consume(indents + 1);
//TODO INVALID_INDENTATION
if lexer.input.starts_with('\n') {
lexer.interpolation_allowed = true;
//return lexer.tokend(lexer.tok(LexToken::Newline));
return true;
}
if indents < *lexer.indent_stack.get(0).unwrap_or(&0usize) {
let mut outdent_count = 0;
while *lexer.indent_stack.get(0).unwrap_or(&0usize) > indents {
//TODO INCONSISTENT_INDENTATION
outdent_count += 1;
lexer.indent_stack.remove(0);
}
while outdent_count > 0 {
outdent_count -= 1;
lexer.colno = 1;
let tok = lexer.tok(LexToken::Outdent);
lexer.colno = *lexer.indent_stack.get(0).unwrap_or(&0usize) + 1;
lexer.tokens.push(lexer.tokend(tok));
}
} else if indents != 0 && indents != *lexer.indent_stack.get(0).unwrap_or(&0usize) {
let tok = lexer.tok(LexToken::indent_val(indents));
lexer.colno = 1 + indents;
lexer.tokens.push(lexer.tokend(tok));
lexer.indent_stack.insert(0, indents);
} else {
let tok = lexer.tok(LexToken::Newline);
lexer.colno = 1 + min(lexer.indent_stack.get(0).unwrap_or(&0), &indents);
lexer.tokens.push(lexer.tokend(tok));
}
lexer.interpolation_allowed = true;
return true;
}
false
}
pub(super) fn text(lexer: &mut Lexer) -> bool {
//println!("--text");
let tok = lexer
.scan(&TEXT_RE_1, LexToken::Text { val: None })
.or_else(|| lexer.scan(&TEXT_RE_2, LexToken::Text { val: None }))
.or_else(|| lexer.scan(&TEXT_RE_3, LexToken::Text { val: None }));
if let Some(tok) = tok {
let val = tok
.lex_token
.get_str_val()
.map(|s| s.clone())
.unwrap_or_default();
lexer.add_text(tok.lex_token, val, None, 0);
true
} else {
false
}
}
pub(super) fn text_html(lexer: &mut Lexer) -> bool {
//println!("--text_html");
let tok = lexer.scan(&TEXT_HTML_RE, LexToken::TextHTML { val: None });
if let Some(tok) = tok {
let val = tok
.lex_token
.get_str_val()
.map(|s| s.clone())
.unwrap_or_default();
lexer.add_text(tok.lex_token, val, None, 0);
true
} else {
false
}
}
}
#[derive(Clone, Serialize)]
pub struct Token {
lex_token: LexToken,
loc: Loc,
}
pub struct LexerOptions {
pub filename: Option<String>,
pub interpolated: bool,
pub starting_line: usize,
pub starting_column: usize,
}
lazy_static! {
static ref CARRIAGE_RETURN: Regex = Regex::new(r"\r\n|\r").unwrap();
static ref BLANK_LINE_RE: Regex = Regex::new(r"^\n[ \t]*\n").unwrap();
static ref COMMENT_RE: Regex = Regex::new(r"^//(-)?([^\n]*)").unwrap();
static ref TABS_RE: Regex = Regex::new(r"^\n(\t*) *").unwrap();
static ref SPACES_RE: Regex = Regex::new(r"^\n( *)").unwrap();
static ref STRING_INTERP_RE: Regex = Regex::new(r"(\\)?([#!])\{((?:.|\n)*)$").unwrap();
static ref SCAN_EOL_WHITESPACE_RE: Regex = Regex::new(r"^([ ]+)([^ ]*)").unwrap();
static ref SCAN_EOL_1_RE: Regex = Regex::new(r"^[ \t]*(\n|$)").unwrap();
static ref SCAN_EOL_2_RE: Regex = Regex::new(r"^[ \t]*").unwrap();
static ref YIELD_RE: Regex = Regex::new(r"^yield").unwrap();
static ref BLOCK_RE: Regex = Regex::new(r"^block").unwrap();
static ref BLOCK_NEWLINE_RE: Regex = Regex::new(r"^block +([^\n]+)").unwrap();
static ref EXTENDS_RE: Regex = Regex::new(r"^extends?(?= |$|\n)").unwrap();
static ref DOT_RE: Regex = Regex::new(r"^\.").unwrap();
static ref TEXT_HTML_RE: Regex = Regex::new(r"^(<[^\n]*)").unwrap();
static ref TEXT_RE_1: Regex = Regex::new(r"^(?:\| ?| )([^\n]+)").unwrap();
static ref TEXT_RE_2: Regex = Regex::new(r"^( )").unwrap();
static ref TEXT_RE_3: Regex = Regex::new(r"^\|( ?)").unwrap();
static ref CLASSNAME_RE: Regex =
Regex::new(r"(?i)^\.([_a-z0-9\-]*[_a-z][_a-z0-9\-]*)").unwrap();
static ref ID_RE: Regex = Regex::new(r"^#([\w-]+)").unwrap();
static ref INVALID_ID_RE: Regex = Regex::new(r"^#").unwrap();
static ref INVALID_ID_CAPTURE: Regex = Regex::new(r".[^ \t\(\#\.\:]*").unwrap();
static ref DOCTYPE_RE: Regex = Regex::new(r"^doctype *([^\n]*)").unwrap();
static ref FILTER_RE: Regex = Regex::new(r"^:([\w\-]+)").unwrap();
static ref TAG_RE: Regex = Regex::new(r"^(\w(?:[-:\w]*\w)?)").unwrap();
static ref INTERPOLATION_RE: Regex = Regex::new(r"^#\{").unwrap();
static ref CASE_RE: Regex = Regex::new(r"^case +([^\n]+)").unwrap();
static ref CASE_NEGATIVE_RE: Regex = Regex::new(r"^case\b").unwrap();
static ref WHEN_RE: Regex = Regex::new(r"^when +([^:\n]+)").unwrap();
static ref WHEN_NEGATIVE_RE: Regex = Regex::new(r"^when\b").unwrap();
static ref DEFAULT_RE: Regex = Regex::new(r"^default").unwrap();
static ref DEFAULT_NEGATIVE_RE: Regex = Regex::new(r"^default\b").unwrap();
static ref INCLUDE_RE: Regex = Regex::new(r"^include(?=:| |$|\n)").unwrap();
static ref INCLUDE_NEGATIVE_RE: Regex = Regex::new(r"^include\b").unwrap();
static ref PATH_RE: Regex = Regex::new(r"^ ([^\n]+)").unwrap();
}
fn remove_bom(str: &str) -> String {
if str.starts_with(BOM) {
String::from(str::from_utf8(&str.as_bytes()[3..]).unwrap())
} else {
str.to_string()
}
}
fn normalize_line_endings(str: &str) -> String {
CARRIAGE_RETURN.replace_all(str, "\n").into()
}
struct Lexer {
input: String,
original_input: String,
filename: Option<String>,
interpolated: bool,
lineno: usize,
colno: usize,
indent_stack: Vec<usize>,
indent_re: Option<Regex>,
interpolation_allowed: bool,
whitespace_re: Option<Regex>,
tokens: Vec<Token>,
ended: bool,
}
impl Lexer {
fn new(source: &str, options: LexerOptions) -> Self {
let source = remove_bom(source);
let input = normalize_line_endings(&source);
let original_input = input.clone();
let filename = options.filename;
let interpolated = options.interpolated; // || false?
let lineno = min(options.starting_line, 1);
let colno = min(options.starting_column, 1);
let indent_stack = Vec::with_capacity(4);
let indent_re = None;
let interpolation_allowed = true;
let whitespace_re = Some(Regex::new(r"[ \n\t]").unwrap());
let tokens = Vec::new();
let ended = false;
return Lexer {
input,
original_input,
filename,
interpolated,
lineno,
colno,
indent_stack,
indent_re,
interpolation_allowed,
whitespace_re,
tokens,
ended,
};
}
fn fail(&self) -> bool {
std::panic::panic_any(format!("unexpected text '{}'", &self.input[0..5]));
}
fn bracket_expression(skip: usize) -> usize {
// TODO assert open bracket here
0
}
fn tok(&self, lex_token: LexToken) -> Token {
Token {
lex_token,
loc: Loc {
start: Some(Position {
line: self.lineno,
column: self.colno,
}),
end: None,
filename: self.filename.clone(),
},
}
}
fn tokend(&self, token: Token) -> Token {
let mut token = token;
token.loc.end = Some(Position {
line: self.lineno,
column: self.colno,
});
token
}
fn increment_line(&mut self, increment: usize) {
self.lineno += increment;
if increment != 0 {
self.colno = 1;
}
}
fn increment_column(&mut self, increment: usize) {
self.colno += increment
}
fn consume(&mut self, len: usize) {
//println!("consuming {}", len);
self.input.replace_range(0..len, "");
//println!("input = {:?}", self.input);
}
fn pipeless_text(&mut self, indents: usize) -> bool {
//println!("pipeless_text indents {}", indents);
while tokenizers::blank(self) {}
let captures = self.scan_indentation();
let mut indents = indents;
if indents == 0 {
if let Some(captures) = captures {
//println!("captures = {:?}", captures);
indents = captures[1].len()
}
}
if indents
> if self.indent_stack.len() == 0 {
0
} else {
self.indent_stack[0]
}
{
//println!("start-pipeless-text");
self.tokens
.push(self.tokend(self.tok(LexToken::StartPipelessText)));
let mut tokens = Vec::new();
let mut token_indent = Vec::new();
let mut stringptr = 0;
while {
let nl_index = if let Some(i) = self.input[(stringptr + 1)..].find("\n") {
i
} else {
self.input.len() - stringptr - 1
};
// possibly different because of substr
let mut begin = stringptr + 1;
let end = min(begin + nl_index, self.input.len() - 1);
begin = min(begin, end);
let buffer = &self.input[begin..end];
let line_targets = format!("\n{}", buffer);
let line_captures = self
.indent_re
.as_ref()
.expect(NO_INDENT)
.captures(&line_targets);
let line_indents = line_captures
.as_ref()
.map(|captures| captures[1].len())
.unwrap_or_default();
let mut is_match = line_indents >= indents;
token_indent.push(is_match);
is_match = is_match || buffer.trim().len() == 0;
if is_match {
stringptr += buffer.len() + 1;
let begin = if buffer.len() == 0 {
0
} else {
min(buffer.len() - 1, indents)
};
tokens.push(String::from(&buffer[begin..]))
} else if line_indents > *self.indent_stack.get(0).unwrap_or(&0usize) {
self.tokens.pop();
return self.pipeless_text(line_captures.unwrap()[1].len());
}
(self.input.len() - stringptr != 0) && is_match
} {}
self.consume(stringptr);
//println!("n tokens = {}", tokens.len());
while self.input.len() == 0 && tokens[tokens.len() - 1] == "" {
tokens.pop();
}
for (i, token) in tokens.into_iter().enumerate() {
//println!("token {}, i {}", token, i);
self.increment_line(1);
let mut tok = None;
if i != 0 {
tok = Some(self.tok(LexToken::Newline))
}
if token_indent[i] {
self.increment_column(indents)
}
if let Some(tok) = tok {
self.tokens.push(self.tokend(tok))
}
self.add_text(LexToken::empty_text(), token, None, 0);
}
//println!("end-pipeless-text");
self.tokens
.push(self.tokend(self.tok(LexToken::EndPipelessText)));
return true;
}
false
}
fn add_text(
&mut self,
lex_token: LexToken,
value: String,
prefix: Option<String>,
escaped: usize,
) {
/*println!(
"addText lex_token {:?}; value {}; prefix {:?}; escaped {}",
lex_token, value, prefix, escaped
);*/
// let mut tok = None;
//
let is_prefixed = prefix.is_some();
let mut prefix = prefix.unwrap_or(String::with_capacity(0));
let mut value = value;
if is_prefixed && value.len() + prefix.len() == 0 {
return;
}
let index_end = if self.interpolated {
value.find(']')
} else {
None
}
.unwrap_or(usize::MAX);
let index_start = if self.interpolation_allowed {
value.find("#[")
} else {
None
}
.unwrap_or(usize::MAX);
let index_escaped = if self.interpolation_allowed {
value.find("\\#[")
} else {
None
}
.unwrap_or(usize::MAX);
let string_interp_match = STRING_INTERP_RE.find(&value);
let string_interp_index = if self.interpolation_allowed {
string_interp_match.map(|m| m.start())
} else {
None
}
.unwrap_or(usize::MAX);
if index_escaped != usize::MAX
&& index_escaped < index_end
&& index_escaped < index_start
&& index_escaped < string_interp_index
{
//println!("break1");
prefix.push_str(&value[0..index_escaped]);
prefix.push_str("#[");
value.replace_range(0..index_escaped + 3, "");
return self.add_text(lex_token, value, Some(prefix), escaped + 1);
}
if index_start != usize::MAX
&& index_start < index_end
&& index_start < index_escaped
&& index_start < string_interp_index
{
//println!("break2");
let tok = self.tok(lex_token.clone().with_val(format!(
"{}{}",
prefix,
&value[0..index_start]
)));
self.increment_column(prefix.len() + index_start + escaped);
self.tokens.push(self.tokend(tok));
let tok = self.tok(LexToken::StartPugInterpolation);
self.increment_column(2);
self.tokens.push(self.tokend(tok));
let mut child = Lexer::new(
&value[index_start + 2..],
LexerOptions {
filename: self.filename.clone(),
interpolated: true,
starting_line: self.lineno,
starting_column: self.colno, // plugins
},
);
let mut interpolated = child.get_tokens();
self.colno = child.colno;
self.tokens.append(&mut interpolated);
let tok = self.tok(LexToken::EndPugInterpolation);
self.increment_column(1);
self.tokens.push(self.tokend(tok));
self.add_text(lex_token, child.input, None, 0);
return;
}
if index_end != usize::MAX
&& index_end < index_start
&& index_end < index_escaped
&& index_end < string_interp_index
{
//println!("path1");
let value_slice = &value[0..index_end];
if prefix.len() + value_slice.len() != 0 {
self.add_text(lex_token, String::from(value_slice), Some(prefix), 0);
}
self.ended = true;
let mut temp = String::with_capacity(0);
std::mem::swap(&mut self.input, &mut temp);
self.input = String::from(
&value[if let Some(i) = value.find(']') {
i + 1usize
} else {
0
}..],
);
self.input.push_str(&temp);
return;
}
// TODO extra crap goes here
//println!("path2");
value = if prefix.len() > 0 {
let mut p = prefix;
p.push_str(&value);
p
} else {
value
};
let value_len = value.len();
let tok = self.tok(lex_token.with_val(value));
self.increment_column(value_len + escaped);
self.tokens.push(self.tokend(tok))
}
fn scan_indentation(&mut self) -> Option<Captures> {
//println!("scan_indentation");
//TODO can this be find instead of captures?
if let Some(ref indent_re) = self.indent_re {
indent_re.captures(&self.input)
} else {
if let Some(captures) = TABS_RE.captures(&self.input) {
self.indent_re = Some(Regex::new(r"^\n(\t*) *").unwrap());
if captures
.get(1)
.map(|m| m.as_str().len())
.unwrap_or_default()
== 0
{
self.indent_re = Some(Regex::new(r"^\n( *)").unwrap());
SPACES_RE.captures(&self.input)
} else {
Some(captures)
}
} else {
None
}
}
}
fn scan(&mut self, regexp: &Regex, lex_token: LexToken) -> Option<Token> {
let captures = regexp.captures(&self.input);
if let Some(captures) = captures {
let captures_0_len = captures
.get(0)
.map(|m| m.as_str().len())
.unwrap_or_default();
let val = captures.get(1).map(|m| m.as_str());
let diff = captures_0_len - val.map(|v| v.len()).unwrap_or_default();
let tok = self.tok(if let Some(val) = val {
lex_token.with_val(val.to_string())
} else {
lex_token
});
self.consume(captures_0_len);
self.increment_column(diff);
return Some(tok);
}
None
}
fn scan_eol(&mut self, regexp: &Regex, lex_token: LexToken) -> Option<Token> {
let captures = regexp.captures(&self.input);
if let Some(captures) = captures {
let mut whitespace_len = 0;
let mut captures_0_len = 0;
let mut captures_1 = String::with_capacity(0);
{
let captures_0 = captures.get(0).map(|m| m.as_str()).unwrap_or_default();
captures_1 = captures
.get(1)
.map(|m| m.as_str())
.unwrap_or_default()
.to_string();
captures_0_len = captures_0.len();
let whitespace = SCAN_EOL_WHITESPACE_RE.captures(captures_0);
if let Some(whitespace) = whitespace {
whitespace_len = whitespace
.get(1)
.map(|m| m.as_str().len())
.unwrap_or_default();
self.increment_column(whitespace_len);
}
}
let new_input = &self.input[captures_0_len..];
if new_input.starts_with(':') {
self.input = new_input.to_string();
let tok = self.tok(lex_token.with_val(captures_1));
self.increment_column(captures_0_len - whitespace_len);
return Some(tok);
}
if SCAN_EOL_1_RE.is_match(new_input) {
let begin = SCAN_EOL_2_RE
.find(new_input)
.map(|m| m.as_str().len())
.unwrap_or_default();
self.input = new_input[begin..].to_string();
let tok = self.tok(lex_token.with_val(captures_1));
self.increment_column(captures_0_len - whitespace_len);
return Some(tok);
}
}
None
}
fn advance(&mut self) {
//println!("advance");
tokenizers::blank(self)
|| tokenizers::eos(self)
|| tokenizers::end_interpolation(self)
|| tokenizers::_yield(self)
|| tokenizers::doctype(self)
//|| tokenizers::interpolation(self)
|| tokenizers::case(self)
//|| tokenizers::when(self)
|| tokenizers::default(self)
//|| tokenizers::extends(self)
//|| tokenizers::append(self)
//|| tokenizers::prepend(self)
|| tokenizers::block(self)
|| tokenizers::mixin_block(self)
//|| tokenizers::include(self)
//|| tokenizers::mixin(self)
//|| tokenizers::call(self)
//|| tokenizers::conditional(self)
//|| tokenizers::each_of(self)
//|| tokenizers::each(self)
//|| tokenizers::while(self)
|| tokenizers::tag(self)
//|| tokenizers::filter(self)
//|| tokenizers::block_code(self)
//|| tokenizers::code(self)
|| tokenizers::id(self)
//|| tokenizers::dot(self)
|| tokenizers::class_name(self)
//|| tokenizers::attrs(self)
//|| tokenizers::attributes_block(self)
|| tokenizers::indent(self)
|| tokenizers::text(self)
|| tokenizers::text_html(self)
|| tokenizers::comment(self)
//|| tokenizers::slash(self)
//|| tokenizers::colon(self)
|| self.fail();
}
fn get_tokens(&mut self) -> Vec<Token> {
while !self.ended {
self.advance()
}
let tokens = std::mem::take(&mut self.tokens);
tokens
}
}
pub fn lex(source: String, options: LexerOptions) -> Vec<Token> {
let mut lexer = Lexer::new(&source, options);
lexer.get_tokens()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_remove_bom() {
assert_eq!(remove_bom("\u{FEFF}hello world"), "hello world".to_string());
}
#[test]
fn test_set_mode() {
let mut blocktok = LexToken::Block {
val: Some(String::from("smth")),
mode: BlockMode::Prepend,
};
blocktok.set_mode(BlockMode::Replace);
assert_eq!(
LexToken::Block {
val: Some(String::from("smth")),
mode: BlockMode::Replace
},
blocktok
)
}
#[test]
fn test_regex() {
let captures = SPACES_RE
.captures("\n // bar\n li one\n // baz\n li two\n\n//\n ul\n")
.unwrap();
assert_eq!(&captures[1], " ");
assert_eq!(&captures[0], "\n ");
}
}
|
mod utilities;
mod logger;
mod mazo;
mod jugador;
mod juego;
mod sinc;
use std::thread;
use std::sync::{Arc, Barrier};
use std::sync::mpsc::{channel, Receiver, Sender};
use rand::prelude::*;
fn main() {
let config = utilities::parse_parameters(std::env::args().collect());
let n_jugadores = config.player_count as usize;
let log = logger::crear_log();
let mut jugador_suspendido = 0;
let coordinador_sinc = juego::iniciar_juego(&log, n_jugadores);
let mut puntajes = Vec::new();
// Inicializo los puntakes
for _i in 0..n_jugadores {
puntajes.push(0.);
}
let mut numero_ronda = 1;
loop {
logger::log(&log, format!("Iniciando ronda {}.\n", numero_ronda));
let resumen = juego::iniciar_ronda(&log, &coordinador_sinc, jugador_suspendido);
for p in resumen.jugadores_puntos {
puntajes[p.0 - 1] += p.1;
logger::log(&log, format!("Jugador {}: sacó {:.2} puntos \n", p.0, p.1));
}
jugador_suspendido = resumen.jugador_suspendido;
logger::log(&log, "-- Termino ronda --\n".to_string());
if resumen.ultima_ronda {
juego::terminar_juego(&log, &coordinador_sinc);
break;
}
numero_ronda += 1;
}
for jugador in coordinador_sinc.jugadores_handler {
let _ = jugador.join();
}
logger::log(&log, "Finalizó el juego, puntajes: \n".to_string());
for i in 0..n_jugadores {
logger::log(&log, format!("Jugador {} con {:.2} puntos\n", i+1, puntajes[i]))
}
}
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(test)]
extern crate test;
use std::f64::{NAN, NEG_INFINITY, INFINITY, MAX};
use std::mem::size_of;
use test::black_box;
// Ensure the const-eval result and runtime result of float comparison are equivalent.
macro_rules! compare {
($op:tt) => {
compare!(
[NEG_INFINITY, -MAX, -1.0, -0.0, 0.0, 1.0, MAX, INFINITY, NAN],
$op
);
};
([$($lhs:expr),+], $op:tt) => {
$(compare!(
$lhs,
$op,
[NEG_INFINITY, -MAX, -1.0, -0.0, 0.0, 1.0, MAX, INFINITY, NAN]
);)+
};
($lhs:expr, $op:tt, [$($rhs:expr),+]) => {
$({
// Wrap the check in its own function to reduce time needed to borrowck.
fn check() {
static CONST_EVAL: bool = $lhs $op $rhs;
let runtime_eval = black_box($lhs) $op black_box($rhs);
assert_eq!(CONST_EVAL, runtime_eval, stringify!($lhs $op $rhs));
assert_eq!(
size_of::<[u8; ($lhs $op $rhs) as usize]>(),
runtime_eval as usize,
stringify!($lhs $op $rhs (forced const eval))
);
}
check();
})+
};
}
fn main() {
assert_eq!(0.0/0.0 < 0.0/0.0, false);
assert_eq!(0.0/0.0 > 0.0/0.0, false);
assert_eq!(NAN < NAN, false);
assert_eq!(NAN > NAN, false);
compare!(==);
compare!(!=);
compare!(<);
compare!(<=);
compare!(>);
compare!(>=);
}
|
/* Core
* The core module provides functionality that will be common to the server
* and client. This will include color, cards, and mana.
*/
pub mod color;
pub mod mana;
|
use crate::{cvars::Config, physics::*, render::GameGraphics};
use ::resources::Resources;
use gvfs::filesystem::Filesystem;
use hecs::World;
pub mod components;
mod main;
pub mod physics;
pub mod systems;
pub struct GameState {
pub world: World,
pub resources: Resources,
pub filesystem: Filesystem,
pub config: Config,
context: gfx2d::Gfx2dContext,
graphics: GameGraphics,
}
impl GameState {
pub(crate) fn new(
context: gfx2d::Gfx2dContext,
world: World,
resources: Resources,
filesystem: Filesystem,
config: Config,
) -> Self {
GameState {
context,
graphics: GameGraphics::new(),
world,
resources,
filesystem,
config,
}
}
pub fn config_update(&self) {
// let app_events = self.resources.get::<AppEventsQueue>().unwrap();
// if app_events
// .iter()
// .any(|event| matches!(event, AppEvent::CvarsChanged))
// {
// let dt = self
// .resources
// .get::<Config>()
// .unwrap()
// .net
// .orb
// .read()
// .unwrap()
// .timestep_seconds as f32;
// }
}
fn step_physics(&mut self, delta: f64) {
use crate::physics::*;
let gravity = vector![0.0, 9.81];
// let configuration = resources.get::<RapierConfiguration>().unwrap();
let mut integration_parameters = self.resources.get_mut::<IntegrationParameters>().unwrap();
integration_parameters.dt = delta as f32;
let mut modifs_tracker = self.resources.get_mut::<ModificationTracker>().unwrap();
let mut physics_pipeline = self.resources.get_mut::<PhysicsPipeline>().unwrap();
// let mut query_pipeline = self.resources.get_mut::<QueryPipeline>().unwrap();
let mut island_manager = self.resources.get_mut::<IslandManager>().unwrap();
let mut broad_phase = self.resources.get_mut::<BroadPhase>().unwrap();
let mut narrow_phase = self.resources.get_mut::<NarrowPhase>().unwrap();
let mut ccd_solver = self.resources.get_mut::<CCDSolver>().unwrap();
let mut joint_set = self.resources.get_mut::<JointSet>().unwrap();
let mut joints_entity_map = self.resources.get_mut::<JointsEntityMap>().unwrap();
const PHYSICS_HOOKS: physics::SameParentFilter = physics::SameParentFilter {};
let event_handler = self
.resources
.get::<physics::PhysicsEventHandler>()
.unwrap();
// TODO: make all preparations before looping necessary number of steps
attach_bodies_and_colliders(&mut self.world);
create_joints(&mut self.world, &mut joint_set, &mut joints_entity_map);
finalize_collider_attach_to_bodies(&mut self.world, &mut modifs_tracker);
prepare_step(&mut self.world, &mut modifs_tracker);
step_world(
&mut self.world,
&gravity,
&integration_parameters,
&mut physics_pipeline,
&mut modifs_tracker,
&mut island_manager,
&mut broad_phase,
&mut narrow_phase,
&mut joint_set,
&mut joints_entity_map,
&mut ccd_solver,
&PHYSICS_HOOKS,
&*event_handler,
);
despawn_outliers(&mut self.world, 2500., self.config.phys.scale);
collect_removals(&mut self.world, &mut modifs_tracker);
}
}
|
use glam::Vec3;
use serde::{Serialize, Deserialize};
use crate::structure::*;
use crate::triangle::Triangle;
#[derive(Default, Serialize, Deserialize, Clone, Copy)]
pub struct Bbox {
min: Vec3,
max: Vec3,
}
impl Bbox {
pub fn expand(&mut self, triangle: &Triangle) {
self.min = self.min.min(triangle.a.min(triangle.b.min(triangle.c)));
self.max = self.max.max(triangle.a.max(triangle.b.max(triangle.c)));
}
pub fn intersect(&self, ray: &Ray) -> bool {
let mut t1 = (self.min.x() - ray.origin.x()) * (1.0 / ray.direction.x());
let mut t2 = (self.max.x() - ray.origin.x()) * (1.0 / ray.direction.x());
let mut tmin = t1.min(t2);
let mut tmax = t1.max(t2);
for i in 1..3 {
t1 = (self.min[i] - ray.origin[i]) * (1.0 / ray.direction[i]);
t2 = (self.max[i] - ray.origin[i]) * (1.0 / ray.direction[i]);
tmin = tmin.max(t1.min(t2));
tmax = tmax.min(t1.max(t2));
}
tmax > tmin.max(0.0)
}
pub fn centroid(&self) -> Vec3 {
(self.min + self.max) / 2.0
}
pub fn merge(&self, another_box: &Self) -> Self {
Self {
min: self.min.min(another_box.min),
max: self.max.max(another_box.max)
}
}
}
|
#![feature(unboxed_closures)]
#![feature(fn_traits)]
mod operator;
mod closure;
mod arena;
|
//! Network Sockets example.
//!
//! This example showcases the use of network sockets via the `Soc` service and the standard library's implementations.
use ctru::prelude::*;
use std::io::{self, Read, Write};
use std::net::{Shutdown, TcpListener};
use std::time::Duration;
fn main() {
ctru::use_panic_handler();
let gfx = Gfx::new().unwrap();
let mut hid = Hid::new().unwrap();
let apt = Apt::new().unwrap();
// Owning a living handle to the `Soc` service is required to use network functionalities.
let soc = Soc::new().unwrap();
// Listen on the standard HTTP port (80).
let server = TcpListener::bind("0.0.0.0:80").unwrap();
server.set_nonblocking(true).unwrap();
let _bottom_console = Console::new(gfx.bottom_screen.borrow_mut());
println!("Point your browser at:\nhttp://{}/\n", soc.host_address());
println!("\x1b[29;12HPress Start to exit");
let _top_console = Console::new(gfx.top_screen.borrow_mut());
while apt.main_loop() {
hid.scan_input();
if hid.keys_down().contains(KeyPad::START) {
break;
};
// Receive any incoming connections.
match server.accept() {
Ok((mut stream, socket_addr)) => {
println!("Got connection from {socket_addr}");
// Print the HTTP request sent by the client (most likely, a web browser).
let mut buf = [0u8; 4096];
match stream.read(&mut buf) {
Ok(_) => {
let req_str = String::from_utf8_lossy(&buf);
println!("{req_str}");
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
println!("Note: Reading the connection returned ErrorKind::WouldBlock.")
} else {
println!("Unable to read stream: {e}")
}
}
}
// Return a HTML page with a simple "Hello World!".
let response = b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n<html><body>Hello world</body></html>\r\n";
if let Err(e) = stream.write(response) {
println!("Error writing http response: {e}");
}
// Shutdown the stream (depending on the web browser used to view the page, this might cause some issues).
stream.shutdown(Shutdown::Both).unwrap();
}
Err(e) => match e.kind() {
// If the TCP socket would block execution, just try again.
std::io::ErrorKind::WouldBlock => {}
_ => {
println!("Error accepting connection: {e}");
std::thread::sleep(Duration::from_secs(2));
}
},
}
gfx.wait_for_vblank();
}
}
|
extern crate core;
use std::collections::HashMap;
use std::str::FromStr;
fn part1(input: &str) -> String {
let (instructions, mut stacks) = get_stacks_and_instructions(input);
parse_command_and_execute(perform_action_part1, instructions, &mut stacks);
calculate_output(stacks)
}
fn part2(input: &str) -> String {
let (instructions, mut stacks) = get_stacks_and_instructions(input);
parse_command_and_execute(perform_action_part2, instructions, &mut stacks);
calculate_output(stacks)
}
fn get_stacks_and_instructions(input: &str) -> (&str, HashMap<usize, Vec<String>>) {
let mut parts = input.trim_end().split("\n\n");
let starting_stack = parts.next().unwrap();
let instructions = parts.next().unwrap();
let stacks = build_stacks(starting_stack);
(instructions, stacks)
}
fn parse_command_and_execute(
command: fn(&mut HashMap<usize, Vec<String>>, u64, &usize, &usize),
instructions: &str,
stacks: &mut HashMap<usize, Vec<String>>,
) {
instructions.split('\n').for_each(|line| {
let (amount, origin, destination) = parse_instruction(line);
command(stacks, amount, &origin, &destination);
});
}
fn calculate_output(mut stacks: HashMap<usize, Vec<String>>) -> String {
let mut output = String::new();
for index in 1..stacks.len() + 1 {
output.push_str(stacks.get_mut(&index).unwrap().pop().unwrap().as_str());
}
output
}
fn parse_instruction(line: &str) -> (u64, usize, usize) {
let instruction: Vec<&str> = line.split(' ').skip(1).step_by(2).collect();
let amount = u64::from_str(instruction[0]).unwrap();
let origin = instruction[1].parse::<usize>().unwrap();
let destination = instruction[2].parse::<usize>().unwrap();
(amount, origin, destination)
}
fn build_stacks(starting_stack: &str) -> HashMap<usize, Vec<String>> {
let mut stack_spec: Vec<&str> = starting_stack.split('\n').collect();
stack_spec.reverse();
let mut stacks: HashMap<usize, Vec<String>> = HashMap::new();
for (index, line) in stack_spec.iter().enumerate() {
if index == 0 {
line.chars().skip(1).step_by(4).for_each(|char| {
stacks.insert(char::to_digit(char, 10).unwrap() as usize, Vec::new());
});
} else {
line.chars()
.skip(1)
.step_by(4)
.enumerate()
.for_each(|(index2, char)| {
if char != ' ' {
stacks
.get_mut(&(&index2 + 1))
.unwrap()
.push(String::from(char))
}
});
}
}
stacks
}
fn perform_action_part2(
stacks: &mut HashMap<usize, Vec<String>>,
amount: u64,
origin: &usize,
destination: &usize,
) {
let value = stacks.get_mut(origin).unwrap();
let to_move_stack = value.split_off(value.len() - amount as usize);
stacks.get_mut(destination).unwrap().extend(to_move_stack);
}
fn perform_action_part1(
stacks: &mut HashMap<usize, Vec<String>>,
amount: u64,
origin: &usize,
destination: &usize,
) {
for _ in 0..amount {
let value = stacks.get_mut(origin).unwrap();
let value = value.pop().unwrap();
stacks.get_mut(destination).unwrap().push(value);
}
}
fn main() {
let example = include_str!(r"../../resources/day5-example.txt");
let input = include_str!(r"../../resources/day5-input.txt");
rustaoc2022::run_matrix(part1, part2, example, input);
}
#[cfg(test)]
mod day5 {
use crate::{part1, part2};
#[test]
fn test_example() {
let input = include_str!(r"../../resources/day5-example.txt");
assert_eq!("CMZ", part1(input));
assert_eq!("MCD", part2(input));
}
#[test]
fn test_input() {
let input = include_str!(r"../../resources/day5-input.txt");
assert_eq!("LBLVVTVLP", part1(input));
assert_eq!("TPFFBDRJD", part2(input));
}
}
|
mod basic_literal;
mod identifier;
mod binary_op;
mod func_call;
mod func_literal;
mod symbol_bound_literal;
pub use self::basic_literal::BasicLiteral;
pub use self::binary_op::BinaryOp;
pub use self::func_call::{FuncCall, FuncParam};
pub use self::identifier::Identifier;
pub use self::symbol_bound_literal::SymbolBoundLiteral;
pub use self::func_literal::{FuncLiteral, ParamDecl, ParamDeclStmt, ReturnSpecifier};
use atoms::Location;
use std::fmt;
use traits::HasLocation;
///
/// An Expression is one of the basic building blocks in a program.
/// By itself, it doesn't mean much, but it is one of the building
/// blocks used in various statements.
///
/// Expressions represent values, operations, and calls to functions
/// that are used in statements.
///
#[derive(Debug)]
pub enum Expression {
BasicLiteral(BasicLiteral),
BinaryOp(Box<BinaryOp>),
CharLiteral(SymbolBoundLiteral),
FuncCall(Box<FuncCall>),
Identifier(Identifier),
StringLiteral(SymbolBoundLiteral),
FunctionLiteral(Box<FuncLiteral>),
}
impl Expression {
///
/// Returns true if this expression would require a
/// semicolon after it if it is in a declaration statement.
///
pub fn requires_semicolon(&self) -> bool {
match *self {
Expression::FunctionLiteral(_) => false,
_ => true,
}
}
}
impl HasLocation for Expression {
fn start(&self) -> Location {
match *self {
Expression::BasicLiteral(ref l) => l.start(),
Expression::BinaryOp(ref op) => op.start(),
Expression::FuncCall(ref call) => call.start(),
Expression::Identifier(ref i) => i.start(),
Expression::CharLiteral(ref c) => c.start(),
Expression::StringLiteral(ref s) => s.start(),
Expression::FunctionLiteral(ref fl) => fl.start(),
}
}
}
impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let name = match *self {
Expression::BasicLiteral(_) => "Basic Literal",
Expression::BinaryOp(_) => "Binary Operation",
Expression::FuncCall(_) => "Function Call",
Expression::Identifier(_) => "Identifier",
Expression::CharLiteral(_) => "Character Literal",
Expression::StringLiteral(_) => "String Literal",
Expression::FunctionLiteral(_) => "Function Literal",
};
write!(f, "{}", name)
}
}
|
type SigmoidFunc = fn(f64) -> f64;
#[derive(Debug, Clone)]
pub struct Sigmoid {
upper_bound: f64,
lower_bound: f64,
function: SigmoidFunc,
derivative: SigmoidFunc, // derivative function
}
impl Sigmoid {
#[allow(dead_code)]
pub fn log() -> Sigmoid {
Sigmoid {
upper_bound: 1.0,
lower_bound: 0.0,
function: log_sigmoid,
derivative: derivative_log,
}
}
pub fn tan() -> Sigmoid {
Sigmoid {
upper_bound: 1.0,
lower_bound: -1.0,
function: tan_sigmoid,
derivative: derivative_tan,
}
}
pub fn get_upper(&self) -> f64 {
self.upper_bound
}
pub fn get_lower(&self) -> f64 {
self.lower_bound
}
pub fn func(&self, x: f64) -> f64 {
(self.function)(x)
}
pub fn deriv(&self, x: f64) -> f64 {
(self.derivative)(x)
}
}
// log-S型激活函数
#[allow(dead_code)]
fn log_sigmoid(x: f64) -> f64 {
1.0 / (1.0 + (-x).exp())
}
// log-S型激活函数的导数
#[allow(dead_code)]
fn derivative_log(x: f64) -> f64 {
let y = log_sigmoid(x);
y * (1.0 - y)
}
// tan-S型激活函数
fn tan_sigmoid(x: f64) -> f64 {
let a1 = x.exp();
let a2 = (-x).exp();
(a1 - a2) / (a1 + a2)
}
// tan-S型激活函数的导数
fn derivative_tan(x: f64) -> f64 {
let y = tan_sigmoid(x);
1.0 - y * y
}
|
//! Equijoin expression plan.
use timely::dataflow::scopes::child::Iterative;
use timely::dataflow::Scope;
use timely::order::Product;
use timely::progress::Timestamp;
use differential_dataflow::lattice::Lattice;
use differential_dataflow::operators::arrange::{Arrange, Arranged};
use differential_dataflow::operators::JoinCore;
use crate::binding::{AsBinding, Binding};
use crate::domain::Domain;
use crate::plan::{Dependencies, Implementable};
use crate::timestamp::Rewind;
use crate::{AsAid, Value, Var};
use crate::{
AttributeBinding, CollectionRelation, Implemented, Relation, ShutdownHandle, TraceValHandle,
VariableMap,
};
/// A plan stage joining two source relations on the specified
/// variables. Throws if any of the join variables isn't bound by both
/// sources.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub struct Join<P1: Implementable, P2: Implementable> {
/// TODO
pub variables: Vec<Var>,
/// Plan for the left input.
pub left_plan: Box<P1>,
/// Plan for the right input.
pub right_plan: Box<P2>,
}
fn attribute_attribute<'b, A, S>(
nested: &mut Iterative<'b, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
target: Var,
left: AttributeBinding<A>,
right: AttributeBinding<A>,
) -> (Implemented<'b, A, S>, ShutdownHandle)
where
A: AsAid,
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind,
{
let mut variables = Vec::with_capacity(3);
variables.push(target);
let (left_arranged, shutdown_left) = {
let (index, shutdown_button) = if target == left.variables.0 {
variables.push(left.variables.1);
domain
.forward_propose(&left.source_attribute)
.expect("forward propose trace does not exist")
.import_frontier(
&nested.parent,
&format!("Propose({:?})", left.source_attribute),
)
} else if target == left.variables.1 {
variables.push(left.variables.0);
domain
.reverse_propose(&left.source_attribute)
.expect("reverse propose trace does not exist")
.import_frontier(
&nested.parent,
&format!("_Propose({:?})", left.source_attribute),
)
} else {
panic!("Unbound target variable in Attribute<->Attribute join.");
};
(index.enter(nested), shutdown_button)
};
let (right_arranged, shutdown_right) = {
let (index, shutdown_button) = if target == right.variables.0 {
variables.push(right.variables.1);
domain
.forward_propose(&right.source_attribute)
.expect("forward propose trace does not exist")
.import_frontier(
&nested.parent,
&format!("Propose({:?})", right.source_attribute),
)
} else if target == right.variables.1 {
variables.push(right.variables.0);
domain
.reverse_propose(&right.source_attribute)
.expect("reverse propose trace does not exist")
.import_frontier(
&nested.parent,
&format!("_Propose({:?})", right.source_attribute),
)
} else {
panic!("Unbound target variable in Attribute<->Attribute join.");
};
(index.enter(nested), shutdown_button)
};
let tuples = left_arranged.join_core(&right_arranged, move |key: &Value, v1, v2| {
let mut out = Vec::with_capacity(3);
out.push(key.clone());
out.push(v1.clone());
out.push(v2.clone());
Some(out)
});
let mut shutdown_handle = ShutdownHandle::from_button(shutdown_left);
shutdown_handle.add_button(shutdown_right);
let relation = CollectionRelation { variables, tuples };
(Implemented::Collection(relation), shutdown_handle)
}
fn collection_collection<'b, A, S>(
nested: &mut Iterative<'b, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
target_variables: &[Var],
left: CollectionRelation<'b, S>,
right: CollectionRelation<'b, S>,
) -> (Implemented<'b, A, S>, ShutdownHandle)
where
A: AsAid,
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind,
{
let mut shutdown_handle = ShutdownHandle::empty();
let variables = target_variables
.iter()
.cloned()
.chain(
left.variables()
.drain(..)
.filter(|x| !target_variables.contains(x)),
)
.chain(
right
.variables()
.drain(..)
.filter(|x| !target_variables.contains(x)),
)
.collect();
let left_arranged: Arranged<
Iterative<'b, S, u64>,
TraceValHandle<Vec<Value>, Vec<Value>, Product<S::Timestamp, u64>, isize>,
> = {
let (arranged, shutdown) = left.tuples_by_variables(nested, domain, &target_variables);
shutdown_handle.merge_with(shutdown);
arranged.arrange()
};
let right_arranged: Arranged<
Iterative<'b, S, u64>,
TraceValHandle<Vec<Value>, Vec<Value>, Product<S::Timestamp, u64>, isize>,
> = {
let (arranged, shutdown) = right.tuples_by_variables(nested, domain, &target_variables);
shutdown_handle.merge_with(shutdown);
arranged.arrange()
};
let tuples = left_arranged.join_core(&right_arranged, |key: &Vec<Value>, v1, v2| {
Some(
key.iter()
.cloned()
.chain(v1.iter().cloned())
.chain(v2.iter().cloned())
.collect(),
)
});
let relation = CollectionRelation { variables, tuples };
(Implemented::Collection(relation), shutdown_handle)
}
fn collection_attribute<'b, A, S>(
nested: &mut Iterative<'b, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
target_variables: &[Var],
left: CollectionRelation<'b, S>,
right: AttributeBinding<A>,
) -> (Implemented<'b, A, S>, ShutdownHandle)
where
A: AsAid,
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind,
{
// @TODO specialized implementation
let (tuples, shutdown_propose) = match domain.forward_propose(&right.source_attribute) {
None => panic!("attribute {:?} does not exist", &right.source_attribute),
Some(propose_trace) => {
let (propose, shutdown_propose) = propose_trace.import_frontier(
&nested.parent,
&format!("Propose({:?})", right.source_attribute),
);
let tuples = propose
.enter(nested)
.as_collection(|e, v| vec![e.clone(), v.clone()]);
(tuples, shutdown_propose)
}
};
let right_collected = CollectionRelation {
variables: vec![right.variables.0, right.variables.1],
tuples,
};
let (implemented, mut shutdown_handle) =
collection_collection(nested, domain, target_variables, left, right_collected);
shutdown_handle.add_button(shutdown_propose);
(implemented, shutdown_handle)
}
// Some(var) => {
// assert!(*var == self.variables.1);
// let (index, shutdown_button) = domain
// .forward_validate(&self.source_attribute)
// .unwrap()
// .import_core(&scope.parent, &self.source_attribute);
// let frontier = index.trace.advance_frontier().to_vec();
// let forwarded = index.enter_at(scope, move |_, _, time| {
// let mut forwarded = time.clone();
// forwarded.advance_by(&frontier);
// Product::new(forwarded, 0)
// });
// (forwarded, ShutdownHandle::from_button(shutdown_button))
// }
// Some(var) => {
// assert!(*var == self.variables.0);
// let (index, shutdown_button) = domain
// .reverse_validate(&self.source_attribute)
// .unwrap()
// .import_core(&scope.parent, &self.source_attribute);
// let frontier = index.trace.advance_frontier().to_vec();
// let forwarded = index.enter_at(scope, move |_, _, time| {
// let mut forwarded = time.clone();
// forwarded.advance_by(&frontier);
// Product::new(forwarded, 0)
// });
// (forwarded, ShutdownHandle::from_button(shutdown_button))
// }
impl<P1: Implementable, P2: Implementable<A = P1::A>> Implementable for Join<P1, P2> {
type A = P1::A;
fn dependencies(&self) -> Dependencies<Self::A> {
self.left_plan.dependencies() + self.right_plan.dependencies()
}
fn into_bindings(&self) -> Vec<Binding<Self::A>> {
let mut left_bindings = self.left_plan.into_bindings();
let mut right_bindings = self.right_plan.into_bindings();
let mut bindings = Vec::with_capacity(left_bindings.len() + right_bindings.len());
bindings.append(&mut left_bindings);
bindings.append(&mut right_bindings);
bindings
}
fn implement<'b, S>(
&self,
nested: &mut Iterative<'b, S, u64>,
domain: &mut Domain<Self::A, S::Timestamp>,
local_arrangements: &VariableMap<Self::A, Iterative<'b, S, u64>>,
) -> (Implemented<'b, Self::A, S>, ShutdownHandle)
where
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind,
{
assert!(!self.variables.is_empty());
let (left, shutdown_left) = self.left_plan.implement(nested, domain, local_arrangements);
let (right, shutdown_right) = self
.right_plan
.implement(nested, domain, local_arrangements);
let (implemented, mut shutdown_handle) = match left {
Implemented::Attribute(left) => {
match right {
Implemented::Attribute(right) => {
if self.variables.len() == 1 {
attribute_attribute(nested, domain, self.variables[0], left, right)
} else if self.variables.len() == 2 {
unimplemented!();
// intersect_attributes(domain, self.variables, left, right)
} else {
panic!(
"Attribute<->Attribute joins can't target more than two variables."
);
}
}
Implemented::Collection(right) => {
collection_attribute(nested, domain, &self.variables, right, left)
}
}
}
Implemented::Collection(left) => match right {
Implemented::Attribute(right) => {
collection_attribute(nested, domain, &self.variables, left, right)
}
Implemented::Collection(right) => {
collection_collection(nested, domain, &self.variables, left, right)
}
},
};
shutdown_handle.merge_with(shutdown_left);
shutdown_handle.merge_with(shutdown_right);
(implemented, shutdown_handle)
}
}
|
#![feature(plugin, decl_macro, custom_attribute, proc_macro_hygiene)]
#![recursion_limit="256"]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate diesel;
extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate regex;
extern crate bcrypt;
extern crate frank_jwt;
extern crate rocket_cors;
extern crate chrono;
pub mod routes;
pub mod db;
pub mod models;
pub mod schema;
pub mod woltlab_auth_helper;
pub mod auth_guard;
pub mod config;
pub mod cors_fairing;
pub mod accounts;
pub mod organizations; |
extern crate rocket;
use rocket::Rocket;
pub mod model;
pub mod dao;
pub mod service;
pub mod route;
pub fn init() -> Rocket {
rocket::ignite()
.mount("/client", route::client_route::routes())
.mount("/user", route::user_route::routes())
} |
use super::expf;
/* k is such that k*ln2 has minimal relative error and x - kln2 > log(FLT_MIN) */
const K: i32 = 235;
/* expf(x)/2 for x >= log(FLT_MAX), slightly better than 0.5f*expf(x/2)*expf(x/2) */
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub(crate) fn k_expo2f(x: f32) -> f32 {
let k_ln2 = f32::from_bits(0x4322e3bc);
/* note that k is odd and scale*scale overflows */
let scale = f32::from_bits(((0x7f + K / 2) as u32) << 23);
/* exp(x - k ln2) * 2**(k-1) */
expf(x - k_ln2) * scale * scale
}
|
fn main() {
println!("{} days", 3);
println!("{0}, this {1}. {1}, this is {0}", "Alice", "Bob");
println!("{subject} {verb} {object}",
object="t-shirt",
subject="people",
verb="using");
println!("{} dari {:b} orang tahu angka biner, setengahnya tidak tahu", 1, 2);
println!("{number:>width$}", number=1, width=6);
println!("{number:>0width$}", number=1, width=6);
println!("My name is {0}, {1} {0}", "Bond", "James");
#[allow(dead_code)]
struct Structure(i32);
// println!("struk ini `{}` tidak akan dicetak...", Structure(3));
} |
use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_then};
use clippy_utils::source::{first_line_of_span, indent_of, reindent_multiline, snippet, snippet_opt};
use clippy_utils::{
both, count_eq, eq_expr_value, get_enclosing_block, get_parent_expr, if_sequence, is_else_clause, is_lint_allowed,
search_same, ContainsName, SpanlessEq, SpanlessHash,
};
use if_chain::if_chain;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{Block, Expr, ExprKind, HirId};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::hir::map::Map;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{source_map::Span, symbol::Symbol, BytePos};
use std::borrow::Cow;
declare_clippy_lint! {
/// ### What it does
/// Checks for consecutive `if`s with the same condition.
///
/// ### Why is this bad?
/// This is probably a copy & paste error.
///
/// ### Example
/// ```ignore
/// if a == b {
/// …
/// } else if a == b {
/// …
/// }
/// ```
///
/// Note that this lint ignores all conditions with a function call as it could
/// have side effects:
///
/// ```ignore
/// if foo() {
/// …
/// } else if foo() { // not linted
/// …
/// }
/// ```
#[clippy::version = "pre 1.29.0"]
pub IFS_SAME_COND,
correctness,
"consecutive `if`s with the same condition"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for consecutive `if`s with the same function call.
///
/// ### Why is this bad?
/// This is probably a copy & paste error.
/// Despite the fact that function can have side effects and `if` works as
/// intended, such an approach is implicit and can be considered a "code smell".
///
/// ### Example
/// ```ignore
/// if foo() == bar {
/// …
/// } else if foo() == bar {
/// …
/// }
/// ```
///
/// This probably should be:
/// ```ignore
/// if foo() == bar {
/// …
/// } else if foo() == baz {
/// …
/// }
/// ```
///
/// or if the original code was not a typo and called function mutates a state,
/// consider move the mutation out of the `if` condition to avoid similarity to
/// a copy & paste error:
///
/// ```ignore
/// let first = foo();
/// if first == bar {
/// …
/// } else {
/// let second = foo();
/// if second == bar {
/// …
/// }
/// }
/// ```
#[clippy::version = "1.41.0"]
pub SAME_FUNCTIONS_IN_IF_CONDITION,
pedantic,
"consecutive `if`s with the same function call"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for `if/else` with the same body as the *then* part
/// and the *else* part.
///
/// ### Why is this bad?
/// This is probably a copy & paste error.
///
/// ### Example
/// ```ignore
/// let foo = if … {
/// 42
/// } else {
/// 42
/// };
/// ```
#[clippy::version = "pre 1.29.0"]
pub IF_SAME_THEN_ELSE,
correctness,
"`if` with the same `then` and `else` blocks"
}
declare_clippy_lint! {
/// ### What it does
/// Checks if the `if` and `else` block contain shared code that can be
/// moved out of the blocks.
///
/// ### Why is this bad?
/// Duplicate code is less maintainable.
///
/// ### Known problems
/// * The lint doesn't check if the moved expressions modify values that are beeing used in
/// the if condition. The suggestion can in that case modify the behavior of the program.
/// See [rust-clippy#7452](https://github.com/rust-lang/rust-clippy/issues/7452)
///
/// ### Example
/// ```ignore
/// let foo = if … {
/// println!("Hello World");
/// 13
/// } else {
/// println!("Hello World");
/// 42
/// };
/// ```
///
/// Could be written as:
/// ```ignore
/// println!("Hello World");
/// let foo = if … {
/// 13
/// } else {
/// 42
/// };
/// ```
#[clippy::version = "1.53.0"]
pub BRANCHES_SHARING_CODE,
nursery,
"`if` statement with shared code in all blocks"
}
declare_lint_pass!(CopyAndPaste => [
IFS_SAME_COND,
SAME_FUNCTIONS_IN_IF_CONDITION,
IF_SAME_THEN_ELSE,
BRANCHES_SHARING_CODE
]);
impl<'tcx> LateLintPass<'tcx> for CopyAndPaste {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if !expr.span.from_expansion() {
if let ExprKind::If(_, _, _) = expr.kind {
// skip ifs directly in else, it will be checked in the parent if
if let Some(&Expr {
kind: ExprKind::If(_, _, Some(else_expr)),
..
}) = get_parent_expr(cx, expr)
{
if else_expr.hir_id == expr.hir_id {
return;
}
}
let (conds, blocks) = if_sequence(expr);
// Conditions
lint_same_cond(cx, &conds);
lint_same_fns_in_if_cond(cx, &conds);
// Block duplication
lint_same_then_else(cx, &blocks, conds.len() == blocks.len(), expr);
}
}
}
}
/// Implementation of `BRANCHES_SHARING_CODE` and `IF_SAME_THEN_ELSE` if the blocks are equal.
fn lint_same_then_else<'tcx>(
cx: &LateContext<'tcx>,
blocks: &[&Block<'tcx>],
has_conditional_else: bool,
expr: &'tcx Expr<'_>,
) {
// We only lint ifs with multiple blocks
if blocks.len() < 2 || is_else_clause(cx.tcx, expr) {
return;
}
// Check if each block has shared code
let has_expr = blocks[0].expr.is_some();
let (start_eq, mut end_eq, expr_eq) = if let Some(block_eq) = scan_block_for_eq(cx, blocks) {
(block_eq.start_eq, block_eq.end_eq, block_eq.expr_eq)
} else {
return;
};
// BRANCHES_SHARING_CODE prerequisites
if has_conditional_else || (start_eq == 0 && end_eq == 0 && (has_expr && !expr_eq)) {
return;
}
// Only the start is the same
if start_eq != 0 && end_eq == 0 && (!has_expr || !expr_eq) {
let block = blocks[0];
let start_stmts = block.stmts.split_at(start_eq).0;
let mut start_walker = UsedValueFinderVisitor::new(cx);
for stmt in start_stmts {
intravisit::walk_stmt(&mut start_walker, stmt);
}
emit_branches_sharing_code_lint(
cx,
start_eq,
0,
false,
check_for_warn_of_moved_symbol(cx, &start_walker.def_symbols, expr),
blocks,
expr,
);
} else if end_eq != 0 || (has_expr && expr_eq) {
let block = blocks[blocks.len() - 1];
let (start_stmts, block_stmts) = block.stmts.split_at(start_eq);
let (block_stmts, end_stmts) = block_stmts.split_at(block_stmts.len() - end_eq);
// Scan start
let mut start_walker = UsedValueFinderVisitor::new(cx);
for stmt in start_stmts {
intravisit::walk_stmt(&mut start_walker, stmt);
}
let mut moved_syms = start_walker.def_symbols;
// Scan block
let mut block_walker = UsedValueFinderVisitor::new(cx);
for stmt in block_stmts {
intravisit::walk_stmt(&mut block_walker, stmt);
}
let mut block_defs = block_walker.defs;
// Scan moved stmts
let mut moved_start: Option<usize> = None;
let mut end_walker = UsedValueFinderVisitor::new(cx);
for (index, stmt) in end_stmts.iter().enumerate() {
intravisit::walk_stmt(&mut end_walker, stmt);
for value in &end_walker.uses {
// Well we can't move this and all prev statements. So reset
if block_defs.contains(value) {
moved_start = Some(index + 1);
end_walker.defs.drain().for_each(|x| {
block_defs.insert(x);
});
end_walker.def_symbols.clear();
}
}
end_walker.uses.clear();
}
if let Some(moved_start) = moved_start {
end_eq -= moved_start;
}
let end_linable = block.expr.map_or_else(
|| end_eq != 0,
|expr| {
intravisit::walk_expr(&mut end_walker, expr);
end_walker.uses.iter().any(|x| !block_defs.contains(x))
},
);
if end_linable {
end_walker.def_symbols.drain().for_each(|x| {
moved_syms.insert(x);
});
}
emit_branches_sharing_code_lint(
cx,
start_eq,
end_eq,
end_linable,
check_for_warn_of_moved_symbol(cx, &moved_syms, expr),
blocks,
expr,
);
}
}
struct BlockEqual {
/// The amount statements that are equal from the start
start_eq: usize,
/// The amount statements that are equal from the end
end_eq: usize,
/// An indication if the block expressions are the same. This will also be true if both are
/// `None`
expr_eq: bool,
}
/// This function can also trigger the `IF_SAME_THEN_ELSE` in which case it'll return `None` to
/// abort any further processing and avoid duplicate lint triggers.
fn scan_block_for_eq(cx: &LateContext<'tcx>, blocks: &[&Block<'tcx>]) -> Option<BlockEqual> {
let mut start_eq = usize::MAX;
let mut end_eq = usize::MAX;
let mut expr_eq = true;
let mut iter = blocks.windows(2);
while let Some(&[win0, win1]) = iter.next() {
let l_stmts = win0.stmts;
let r_stmts = win1.stmts;
// `SpanlessEq` now keeps track of the locals and is therefore context sensitive clippy#6752.
// The comparison therefore needs to be done in a way that builds the correct context.
let mut evaluator = SpanlessEq::new(cx);
let mut evaluator = evaluator.inter_expr();
let current_start_eq = count_eq(&mut l_stmts.iter(), &mut r_stmts.iter(), |l, r| evaluator.eq_stmt(l, r));
let current_end_eq = {
// We skip the middle statements which can't be equal
let end_comparison_count = l_stmts.len().min(r_stmts.len()) - current_start_eq;
let it1 = l_stmts.iter().skip(l_stmts.len() - end_comparison_count);
let it2 = r_stmts.iter().skip(r_stmts.len() - end_comparison_count);
it1.zip(it2)
.fold(0, |acc, (l, r)| if evaluator.eq_stmt(l, r) { acc + 1 } else { 0 })
};
let block_expr_eq = both(&win0.expr, &win1.expr, |l, r| evaluator.eq_expr(l, r));
// IF_SAME_THEN_ELSE
if_chain! {
if block_expr_eq;
if l_stmts.len() == r_stmts.len();
if l_stmts.len() == current_start_eq;
if !is_lint_allowed(cx, IF_SAME_THEN_ELSE, win0.hir_id);
if !is_lint_allowed(cx, IF_SAME_THEN_ELSE, win1.hir_id);
then {
span_lint_and_note(
cx,
IF_SAME_THEN_ELSE,
win0.span,
"this `if` has identical blocks",
Some(win1.span),
"same as this",
);
return None;
}
}
start_eq = start_eq.min(current_start_eq);
end_eq = end_eq.min(current_end_eq);
expr_eq &= block_expr_eq;
}
if !expr_eq {
end_eq = 0;
}
// Check if the regions are overlapping. Set `end_eq` to prevent the overlap
let min_block_size = blocks.iter().map(|x| x.stmts.len()).min().unwrap();
if (start_eq + end_eq) > min_block_size {
end_eq = min_block_size - start_eq;
}
Some(BlockEqual {
start_eq,
end_eq,
expr_eq,
})
}
fn check_for_warn_of_moved_symbol(
cx: &LateContext<'tcx>,
symbols: &FxHashSet<Symbol>,
if_expr: &'tcx Expr<'_>,
) -> bool {
get_enclosing_block(cx, if_expr.hir_id).map_or(false, |block| {
let ignore_span = block.span.shrink_to_lo().to(if_expr.span);
symbols
.iter()
.filter(|sym| !sym.as_str().starts_with('_'))
.any(move |sym| {
let mut walker = ContainsName {
name: *sym,
result: false,
};
// Scan block
block
.stmts
.iter()
.filter(|stmt| !ignore_span.overlaps(stmt.span))
.for_each(|stmt| intravisit::walk_stmt(&mut walker, stmt));
if let Some(expr) = block.expr {
intravisit::walk_expr(&mut walker, expr);
}
walker.result
})
})
}
fn emit_branches_sharing_code_lint(
cx: &LateContext<'tcx>,
start_stmts: usize,
end_stmts: usize,
lint_end: bool,
warn_about_moved_symbol: bool,
blocks: &[&Block<'tcx>],
if_expr: &'tcx Expr<'_>,
) {
if start_stmts == 0 && !lint_end {
return;
}
// (help, span, suggestion)
let mut suggestions: Vec<(&str, Span, String)> = vec![];
let mut add_expr_note = false;
// Construct suggestions
let sm = cx.sess().source_map();
if start_stmts > 0 {
let block = blocks[0];
let span_start = first_line_of_span(cx, if_expr.span).shrink_to_lo();
let span_end = sm.stmt_span(block.stmts[start_stmts - 1].span, block.span);
let cond_span = first_line_of_span(cx, if_expr.span).until(block.span);
let cond_snippet = reindent_multiline(snippet(cx, cond_span, "_"), false, None);
let cond_indent = indent_of(cx, cond_span);
let moved_span = block.stmts[0].span.source_callsite().to(span_end);
let moved_snippet = reindent_multiline(snippet(cx, moved_span, "_"), true, None);
let suggestion = moved_snippet.to_string() + "\n" + &cond_snippet + "{";
let suggestion = reindent_multiline(Cow::Borrowed(&suggestion), true, cond_indent);
let span = span_start.to(span_end);
suggestions.push(("start", span, suggestion.to_string()));
}
if lint_end {
let block = blocks[blocks.len() - 1];
let span_end = block.span.shrink_to_hi();
let moved_start = if end_stmts == 0 && block.expr.is_some() {
block.expr.unwrap().span.source_callsite()
} else {
sm.stmt_span(block.stmts[block.stmts.len() - end_stmts].span, block.span)
};
let moved_end = block.expr.map_or_else(
|| sm.stmt_span(block.stmts[block.stmts.len() - 1].span, block.span),
|expr| expr.span.source_callsite(),
);
let moved_span = moved_start.to(moved_end);
let moved_snipped = reindent_multiline(snippet(cx, moved_span, "_"), true, None);
let indent = indent_of(cx, if_expr.span.shrink_to_hi());
let suggestion = "}\n".to_string() + &moved_snipped;
let suggestion = reindent_multiline(Cow::Borrowed(&suggestion), true, indent);
let mut span = moved_start.to(span_end);
// Improve formatting if the inner block has indention (i.e. normal Rust formatting)
let test_span = Span::new(span.lo() - BytePos(4), span.lo(), span.ctxt(), span.parent());
if snippet_opt(cx, test_span)
.map(|snip| snip == " ")
.unwrap_or_default()
{
span = span.with_lo(test_span.lo());
}
suggestions.push(("end", span, suggestion.to_string()));
add_expr_note = !cx.typeck_results().expr_ty(if_expr).is_unit();
}
let add_optional_msgs = |diag: &mut DiagnosticBuilder<'_>| {
if add_expr_note {
diag.note("The end suggestion probably needs some adjustments to use the expression result correctly");
}
if warn_about_moved_symbol {
diag.warn("Some moved values might need to be renamed to avoid wrong references");
}
};
// Emit lint
if suggestions.len() == 1 {
let (place_str, span, sugg) = suggestions.pop().unwrap();
let msg = format!("all if blocks contain the same code at the {}", place_str);
let help = format!("consider moving the {} statements out like this", place_str);
span_lint_and_then(cx, BRANCHES_SHARING_CODE, span, msg.as_str(), |diag| {
diag.span_suggestion(span, help.as_str(), sugg, Applicability::Unspecified);
add_optional_msgs(diag);
});
} else if suggestions.len() == 2 {
let (_, end_span, end_sugg) = suggestions.pop().unwrap();
let (_, start_span, start_sugg) = suggestions.pop().unwrap();
span_lint_and_then(
cx,
BRANCHES_SHARING_CODE,
start_span,
"all if blocks contain the same code at the start and the end. Here at the start",
move |diag| {
diag.span_note(end_span, "and here at the end");
diag.span_suggestion(
start_span,
"consider moving the start statements out like this",
start_sugg,
Applicability::Unspecified,
);
diag.span_suggestion(
end_span,
"and consider moving the end statements out like this",
end_sugg,
Applicability::Unspecified,
);
add_optional_msgs(diag);
},
);
}
}
/// This visitor collects `HirId`s and Symbols of defined symbols and `HirId`s of used values.
struct UsedValueFinderVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
/// The `HirId`s of defined values in the scanned statements
defs: FxHashSet<HirId>,
/// The Symbols of the defined symbols in the scanned statements
def_symbols: FxHashSet<Symbol>,
/// The `HirId`s of the used values
uses: FxHashSet<HirId>,
}
impl<'a, 'tcx> UsedValueFinderVisitor<'a, 'tcx> {
fn new(cx: &'a LateContext<'tcx>) -> Self {
UsedValueFinderVisitor {
cx,
defs: FxHashSet::default(),
def_symbols: FxHashSet::default(),
uses: FxHashSet::default(),
}
}
}
impl<'a, 'tcx> Visitor<'tcx> for UsedValueFinderVisitor<'a, 'tcx> {
type Map = Map<'tcx>;
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::All(self.cx.tcx.hir())
}
fn visit_local(&mut self, l: &'tcx rustc_hir::Local<'tcx>) {
let local_id = l.pat.hir_id;
self.defs.insert(local_id);
if let Some(sym) = l.pat.simple_ident() {
self.def_symbols.insert(sym.name);
}
if let Some(expr) = l.init {
intravisit::walk_expr(self, expr);
}
}
fn visit_qpath(&mut self, qpath: &'tcx rustc_hir::QPath<'tcx>, id: HirId, _span: rustc_span::Span) {
if let rustc_hir::QPath::Resolved(_, path) = *qpath {
if path.segments.len() == 1 {
if let rustc_hir::def::Res::Local(var) = self.cx.qpath_res(qpath, id) {
self.uses.insert(var);
}
}
}
}
}
/// Implementation of `IFS_SAME_COND`.
fn lint_same_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
let mut h = SpanlessHash::new(cx);
h.hash_expr(expr);
h.finish()
};
let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool { eq_expr_value(cx, lhs, rhs) };
for (i, j) in search_same(conds, hash, eq) {
span_lint_and_note(
cx,
IFS_SAME_COND,
j.span,
"this `if` has the same condition as a previous `if`",
Some(i.span),
"same as this",
);
}
}
/// Implementation of `SAME_FUNCTIONS_IN_IF_CONDITION`.
fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
let mut h = SpanlessHash::new(cx);
h.hash_expr(expr);
h.finish()
};
let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool {
// Do not lint if any expr originates from a macro
if lhs.span.from_expansion() || rhs.span.from_expansion() {
return false;
}
// Do not spawn warning if `IFS_SAME_COND` already produced it.
if eq_expr_value(cx, lhs, rhs) {
return false;
}
SpanlessEq::new(cx).eq_expr(lhs, rhs)
};
for (i, j) in search_same(conds, hash, eq) {
span_lint_and_note(
cx,
SAME_FUNCTIONS_IN_IF_CONDITION,
j.span,
"this `if` has the same function call as a previous `if`",
Some(i.span),
"same as this",
);
}
}
|
#[derive(Debug)]
pub enum Error {
FixnumParsing,
BooleanParsing,
UnknownToken,
EmptyValues,
MismatchedTypes
}
|
//! Utilities for parsing from byte streams
mod buffer;
mod parser;
pub(crate) use self::buffer::Buffer;
pub(crate) use self::parser::Parser;
use std::io;
use thiserror::Error;
use crate::object::ParseIdError;
#[derive(Debug, Error)]
pub(crate) enum Error {
#[error("unexpected end of file")]
UnexpectedEof,
#[error("the file length is invalid")]
InvalidLength,
#[error("an object id is malformed")]
InvalidId(
#[source]
#[from]
ParseIdError,
),
#[error("io error while parsing")]
Io(
#[source]
#[from]
io::Error,
),
}
|
extern crate websocket;
extern crate mount;
extern crate staticfile;
extern crate iron;
mod server;
mod page;
mod board;
fn main() {
server::start();
page::serve();
} |
#[test]
fn test_basic_closure() {
let plus_one = |x: i32| x + 1;
assert_eq!(2, plus_one(1));
}
#[test]
fn test_longer_closure() {
let plus_two = |x| {
let mut result: i32 = x;
result += 1;
result += 1;
result
};
assert_eq!(4, plus_two(2));
}
#[test]
fn test_basic_closure_with_annotations() {
let plus_one = |x: i32| -> i32 { x + 1 };
assert_eq!(2, plus_one(1));
}
fn plus_one_v1 (x: i32) -> i32 { x + 1 }
#[test]
fn test_closure_syntax() {
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32| x + 1 ;
}
#[test]
fn test_binding_scope() {
let num = 5;
let plus_num = |x: i32| x + num;
assert_eq!(10, plus_num(5));
}
// won't compile. can't take a mutable borrown on num
// becuase the closure is already borrowing it
//#[test]
//fn test_failing_borrow() {
// let mut num = 5;
// let plus_num = |x: i32| x + num;
// let y = &mut num;
//}
#[test]
fn test_borrow() {
let mut num = 5;
{
let plus_num = |x: i32| x + num;
}
let y = &mut num; // borrow is valid here becuase closure is out of scope
}
// won't compile. ownership was passed to the closure, the same as if nums
// was passed to a function call
//#[test]
//fn test_failing_move() {
// let nums = vec![1, 2, 3];
// let takes_nums = || nums;
// println!("{:?}", nums);
//}
#[test]
fn test_move() {
let num = 5;
let owns_num = move |x: i32| x + num;
}
#[test]
fn test_move_mutable_borrow() {
let mut num = 5;
{
// closure gets a mutable borrow of num
let mut add_num = |x: i32| num += x;
add_num(5);
}
assert_eq!(10, num);
}
#[test]
fn test_move_closure() {
let mut num = 5;
{
// closure gets a copy of num
// moving a closure effective gives the closure it's own stack frame
let mut add_num = move |x: i32| num += x;
add_num(5);
}
assert_eq!(5, num);
}
// closure is statically dispatched due to the Fn trait
fn call_with_one_static_dispatch<F>(some_closure: F) -> i32
where F : Fn(i32) -> i32 {
some_closure(1)
}
#[test]
fn test_pass_closure_as_arg_static_dispatch() {
let answer = call_with_one_static_dispatch(|x| x + 2);
assert_eq!(3, answer);
}
fn call_with_one_dynamic_dispatch(some_closure: &Fn(i32) -> i32) -> i32 {
some_closure(1)
}
#[test]
fn test_pass_closure_as_arg_dynamic_dispatch() {
let answer = call_with_one_dynamic_dispatch(&|x| x + 2);
assert_eq!(3, answer);
}
fn add_one(i: i32) -> i32 {
i + 1
}
#[test]
fn test_function_instead_of_closure() {
let f = add_one;
let answer = call_with_one_dynamic_dispatch(&f);
assert_eq!(2, answer);
}
#[test]
fn test_functioin_instead_of_closure_2() {
let answer = call_with_one_dynamic_dispatch(&add_one);
assert_eq!(2, answer);
}
// won't compile. In order to return, Rust must know it's size.
// Fn is a trait, so it could be any size, hence the error
//fn factory() -> (Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
//}
// won't compile. No lifetime specified for returned reference
//fn factory() -> &(Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
//}
// won't compile. Mismatched types
// return value is actually [closure@closures.rs:151:5: 151:16 num:_]
//fn factory() -> &'static (Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
//}
// won't compile.
// closure may outlive the current function, but it borrows `num`,
// which is owned by the current function
//fn factory() -> Box<Fn(i32) -> i32> {
// let num = 5;
// Box::new(|x| x + num)
//}
// By making the inner closure a move Fn, we create a new stack frame for
// our closure. By Boxing it up, we've given it a known size, and allowing it
// to escape out stack frame
fn factory() -> Box<Fn(i32) -> i32> {
let num = 5;
Box::new(move |x| x + num)
}
#[test]
fn test_function_returning_function() {
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
}
|
use crate::Counter;
use num_traits::Zero;
use std::collections::HashMap;
use std::hash::Hash;
impl<T, N> Counter<T, N>
where
T: Hash + Eq,
N: Zero,
{
/// Create a new, empty `Counter`
pub fn new() -> Self {
Counter {
map: HashMap::new(),
zero: N::zero(),
}
}
}
impl<T, N> Default for Counter<T, N>
where
T: Hash + Eq,
N: Default,
{
fn default() -> Self {
Self {
map: Default::default(),
zero: Default::default(),
}
}
}
|
use std::{env, path::PathBuf};
fn main() {
let config_src = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
.join("mc_randomx")
.join("MerosConfiguration")
.join("configuration.h");
let config_dst = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
.join("RandomX")
.join("src")
.join("configuration.h");
if !config_src.exists() || !config_dst.exists() {
panic!("RandomX configuration doesn't exist. Did you checkout the git submodules?")
}
std::fs::copy(config_src, config_dst).unwrap();
let dst = cmake::Config::new("RandomX")
.define("ARCH", "native")
.build_target("randomx")
.profile("Release")
.build();
println!("cargo:rustc-link-search=native={}/build", dst.display());
println!("cargo:rustc-link-lib=static=randomx");
println!("cargo:rerun-if-changed=RandomX/src/randomx.h");
println!("cargo:rerun-if-changed=mc_randomx/MerosConfiguration/configuration.h");
let bindings = bindgen::Builder::default()
.header("RandomX/src/randomx.h")
.whitelist_function("randomx_.*")
.whitelist_type("randomx_.*")
.whitelist_var("randomx_.*")
.whitelist_var("RANDOMX_.*")
.size_t_is_usize(true)
.prepend_enum_name(false)
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
.generate()
.expect("Failed to generate RandomX bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Failed to write RandomX bindings");
}
|
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{
parse::{Parse, ParseStream, Result},
Ident, LitInt, Token,
};
struct BoundedInt {
name: Ident,
lower: LitInt,
upper: LitInt,
}
impl Parse for BoundedInt {
fn parse(input: ParseStream) -> Result<Self> {
let name: Ident = input.parse()?;
input.parse::<Token!(,)>()?;
let lower: LitInt = input.parse()?;
input.parse::<Token!(,)>()?;
let upper: LitInt = input.parse()?;
Ok(BoundedInt { name, lower, upper })
}
}
#[proc_macro]
pub fn bound_int_types(input: TokenStream) -> TokenStream {
let BoundedInt { name, lower, upper } = syn::parse_macro_input!(input);
let lower = lower.value();
let upper = upper.value();
// Define the trait, which is the general type for the bounded integer.
let mut out = quote! {
trait #name: std::fmt::Debug {
fn get() -> Self;
fn value(&self) -> u64;
}
};
for i in lower..=upper {
let name_i = format!("{}_{}", name, i);
let struct_name = format!("__{}_struct", name_i);
let plus_name = format!("__{}_plus", name_i);
let minus_name = format!("__{}_minus", name_i);
let name_i_ident = Ident::new(&name_i, Span::call_site());
let struct_name_ident = Ident::new(&struct_name, Span::call_site());
let plus_name_ident = Ident::new(&plus_name, Span::call_site());
let minus_name_ident = Ident::new(&minus_name, Span::call_site());
out.extend(quote! {
// Define the type for the specific value.
#[derive(Copy, Clone, Debug, PartialEq)]
struct #struct_name_ident {}
impl #struct_name_ident {
fn plus<T: #plus_name_ident>(&self, other: T) -> T::Result {
other.sum()
}
fn minus<T: #minus_name_ident>(&self, other: T) -> T::Result {
other.difference()
}
}
// Define a constant for external usage of the value.
const #name_i_ident: #struct_name_ident = #struct_name_ident {};
// Implement the general trait on the struct.
impl #name for #struct_name_ident {
fn get() -> Self {
#name_i_ident
}
fn value(&self) -> u64 {
#i
}
}
// Define a trait for values which can be added to this value.
trait #plus_name_ident: #name {
type Result: #name;
fn sum(&self) -> Self::Result {
Self::Result::get()
}
}
// Define a trait for values which can be subtracted from this value.
trait #minus_name_ident: #name {
type Result: #name;
fn difference(&self) -> Self::Result {
Self::Result::get()
}
}
});
// Implement the "plus" traits for the value which won't overflow.
//
// For example, if `lower` is 1, `upper` is `10`, and `i` is `6`, then the numbers that can
// be added to `6` are `1` through `4`.
for plus in lower..=upper - i {
let plus_impl = format!("__{}_{}_plus", name, plus);
let result = format!("__{}_{}_struct", name, plus + i);
let plus_impl_ident = Ident::new(&plus_impl, Span::call_site());
let result_ident = Ident::new(&result, Span::call_site());
out.extend(quote!{
impl #plus_impl_ident for #struct_name_ident {
type Result = #result_ident;
}
});
}
// Implement the "minus" trait for the values which won't underflow.
//
// For example, if `lower` is 2, `upper` is `10`, and `i` is `6`, then the numbers that can
// be subtracted from `6` are `2` through `4`.
for minus in lower..=i - lower {
let minus_impl = format!("__{}_{}_minus", name, i);
let result = format!("__{}_{}_struct", name, i - minus);
let minus_concrete = format!("__{}_{}_struct", name, minus);
let minus_impl_ident = Ident::new(&minus_impl, Span::call_site());
let result_ident = Ident::new(&result, Span::call_site());
let minus_concrete_ident = Ident::new(&minus_concrete, Span::call_site());
out.extend(quote!{
impl #minus_impl_ident for #minus_concrete_ident {
type Result = #result_ident;
}
});
}
}
TokenStream::from(out)
}
|
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
use std::fmt;
#[cfg(not(feature = "std"))]
use core::fmt;
use embedded_hal::blocking::i2c;
/// A wrapper around an embedded_hal bus peripheral that traces each
/// read and write call and prints the raw bytes that were sent or
/// received. It will also pretty-print the error result if the
/// underlying request failed.
///
/// Currently, this requires that the error type of the underlying peripheral
/// implements std::fmt::Debug, which most of them seem to do.
pub struct BusLogger<W : fmt::Write,T> (
W, T
);
impl<W: fmt::Write, T> BusLogger<W,T> {
pub fn new(w : W, t : T) -> BusLogger<W,T> {
BusLogger(w,t)
}
}
impl <W : fmt::Write, T : i2c::Read> i2c::Read for BusLogger<W,T> where
<T as i2c::Read>::Error : fmt::Debug
{
type Error = T::Error;
fn read(&mut self, address: u8, buffer: &mut[u8]) -> Result<(), Self::Error> {
write!(self.0, "a[{:02x}] ", address).ok();
let result = self.1.read(address,buffer);
match result {
Err(e) => { writeln!(self.0, "{:?}\r", e).ok(); Err(e)}
_ => {writeln!(self.0, "r{:02x?}\r", buffer).ok(); Ok(())}
}
}
}
impl <W : fmt::Write, T : i2c::Write> i2c::Write for BusLogger<W,T> where
<T as i2c::Write>::Error : fmt::Debug
{
type Error = T::Error;
fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> {
write!(self.0, "a[{:02x}] ", addr).ok();
write!(self.0, "w{:02x?} ", bytes).ok();
let result = self.1.write(addr,bytes);
match result {
Err(e) => { writeln!(self.0, "{:?}\r", e).ok(); Err(e)}
_ => {writeln!(self.0, "\r").ok(); Ok(())}
}
}
}
impl <W : fmt::Write, T : i2c::WriteRead> i2c::WriteRead for BusLogger<W,T> where
<T as i2c::WriteRead>::Error : fmt::Debug
{
type Error = T::Error;
fn write_read(&mut self, address: u8, bytes: &[u8], buffer: &mut [u8]) -> Result<(), Self::Error> {
write!(self.0, "a[{:02x}] ", address).ok();
write!(self.0, "w{:02x?} ", bytes).ok();
let result = self.1.write_read(address,bytes,buffer);
match result {
Err(e) => { writeln!(self.0, "{:?}\r", e).ok(); Err(e)}
_ => {writeln!(self.0, "r{:02x?}\r",buffer).ok(); Ok(())}
}
}
}
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
blocks::{blockheader::BlockHeaderValidationError, BlockValidationError},
transactions::transaction::TransactionError,
};
use derive_error::Error;
#[derive(Clone, Debug, PartialEq, Error)]
pub enum ValidationError {
BlockHeaderError(BlockHeaderValidationError),
BlockError(BlockValidationError),
// Contains kernels or inputs that are not yet spendable
MaturityError,
// Contains unknown inputs
UnknownInputs,
// The transaction has some transaction error
TransactionError(TransactionError),
/// Custom error with string message
#[error(no_from, non_std, msg_embedded)]
CustomError(String),
/// A database instance must be set for this validator
NoDatabaseConfigured,
// The total expected supply plus the total accumulated (offset) excess does not equal the sum of all UTXO
// commitments.
InvalidAccountingBalance,
// Transaction contains already spent inputs
ContainsSTxO,
// The recorded chain accumulated difficulty was stronger
WeakerAccumulatedDifficulty,
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: clone :: Clone)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct CMD_ENTRY {
pub pwszCmdToken: super::super::Foundation::PWSTR,
pub pfnCmdHandler: ::core::option::Option<PFN_HANDLE_CMD>,
pub dwShortCmdHelpToken: u32,
pub dwCmdHlpToken: u32,
pub dwFlags: u32,
pub pOsVersionCheck: ::core::option::Option<PNS_OSVERSIONCHECK>,
}
#[cfg(feature = "Win32_Foundation")]
impl CMD_ENTRY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for CMD_ENTRY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for CMD_ENTRY {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("CMD_ENTRY").field("pwszCmdToken", &self.pwszCmdToken).field("dwShortCmdHelpToken", &self.dwShortCmdHelpToken).field("dwCmdHlpToken", &self.dwCmdHlpToken).field("dwFlags", &self.dwFlags).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for CMD_ENTRY {
fn eq(&self, other: &Self) -> bool {
self.pwszCmdToken == other.pwszCmdToken && self.pfnCmdHandler.map(|f| f as usize) == other.pfnCmdHandler.map(|f| f as usize) && self.dwShortCmdHelpToken == other.dwShortCmdHelpToken && self.dwCmdHlpToken == other.dwCmdHlpToken && self.dwFlags == other.dwFlags && self.pOsVersionCheck.map(|f| f as usize) == other.pOsVersionCheck.map(|f| f as usize)
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for CMD_ENTRY {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for CMD_ENTRY {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[derive(:: core :: clone :: Clone)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct CMD_GROUP_ENTRY {
pub pwszCmdGroupToken: super::super::Foundation::PWSTR,
pub dwShortCmdHelpToken: u32,
pub ulCmdGroupSize: u32,
pub dwFlags: u32,
pub pCmdGroup: *mut CMD_ENTRY,
pub pOsVersionCheck: ::core::option::Option<PNS_OSVERSIONCHECK>,
}
#[cfg(feature = "Win32_Foundation")]
impl CMD_GROUP_ENTRY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for CMD_GROUP_ENTRY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for CMD_GROUP_ENTRY {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("CMD_GROUP_ENTRY").field("pwszCmdGroupToken", &self.pwszCmdGroupToken).field("dwShortCmdHelpToken", &self.dwShortCmdHelpToken).field("ulCmdGroupSize", &self.ulCmdGroupSize).field("dwFlags", &self.dwFlags).field("pCmdGroup", &self.pCmdGroup).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for CMD_GROUP_ENTRY {
fn eq(&self, other: &Self) -> bool {
self.pwszCmdGroupToken == other.pwszCmdGroupToken && self.dwShortCmdHelpToken == other.dwShortCmdHelpToken && self.ulCmdGroupSize == other.ulCmdGroupSize && self.dwFlags == other.dwFlags && self.pCmdGroup == other.pCmdGroup && self.pOsVersionCheck.map(|f| f as usize) == other.pOsVersionCheck.map(|f| f as usize)
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for CMD_GROUP_ENTRY {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for CMD_GROUP_ENTRY {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
pub const DEFAULT_CONTEXT_PRIORITY: u32 = 100u32;
pub const ERROR_CMD_NOT_FOUND: u32 = 15004u32;
pub const ERROR_CONTEXT_ALREADY_REGISTERED: u32 = 15019u32;
pub const ERROR_CONTINUE_IN_PARENT_CONTEXT: u32 = 15016u32;
pub const ERROR_DLL_LOAD_FAILED: u32 = 15006u32;
pub const ERROR_ENTRY_PT_NOT_FOUND: u32 = 15005u32;
pub const ERROR_HELPER_ALREADY_REGISTERED: u32 = 15018u32;
pub const ERROR_INIT_DISPLAY: u32 = 15007u32;
pub const ERROR_INVALID_OPTION_TAG: u32 = 15009u32;
pub const ERROR_INVALID_OPTION_VALUE: u32 = 15014u32;
pub const ERROR_INVALID_SYNTAX: u32 = 15001u32;
pub const ERROR_MISSING_OPTION: u32 = 15011u32;
pub const ERROR_NO_CHANGE: u32 = 15003u32;
pub const ERROR_NO_ENTRIES: u32 = 15000u32;
pub const ERROR_NO_TAG: u32 = 15010u32;
pub const ERROR_OKAY: u32 = 15015u32;
pub const ERROR_PARSING_FAILURE: u32 = 15020u32;
pub const ERROR_PROTOCOL_NOT_IN_TRANSPORT: u32 = 15002u32;
pub const ERROR_SHOW_USAGE: u32 = 15013u32;
pub const ERROR_SUPPRESS_OUTPUT: u32 = 15017u32;
pub const ERROR_TAG_ALREADY_PRESENT: u32 = 15008u32;
pub const ERROR_TRANSPORT_NOT_PRESENT: u32 = 15012u32;
pub const MAX_NAME_LEN: u32 = 48u32;
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn MatchEnumTag<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(hmodule: Param0, pwcarg: Param1, dwnumarg: u32, penumtable: *const TOKEN_VALUE, pdwvalue: *mut u32) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn MatchEnumTag(hmodule: super::super::Foundation::HANDLE, pwcarg: super::super::Foundation::PWSTR, dwnumarg: u32, penumtable: *const TOKEN_VALUE, pdwvalue: *mut u32) -> u32;
}
::core::mem::transmute(MatchEnumTag(hmodule.into_param().abi(), pwcarg.into_param().abi(), ::core::mem::transmute(dwnumarg), ::core::mem::transmute(penumtable), ::core::mem::transmute(pdwvalue)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn MatchToken<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(pwszusertoken: Param0, pwszcmdtoken: Param1) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn MatchToken(pwszusertoken: super::super::Foundation::PWSTR, pwszcmdtoken: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(MatchToken(pwszusertoken.into_param().abi(), pwszcmdtoken.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
pub const NETSH_ERROR_BASE: u32 = 15000u32;
pub const NETSH_ERROR_END: u32 = 15019u32;
pub const NETSH_MAX_CMD_TOKEN_LENGTH: u32 = 128u32;
pub const NETSH_MAX_TOKEN_LENGTH: u32 = 64u32;
pub const NETSH_VERSION_50: u32 = 20480u32;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct NS_CMD_FLAGS(pub i32);
pub const CMD_FLAG_PRIVATE: NS_CMD_FLAGS = NS_CMD_FLAGS(1i32);
pub const CMD_FLAG_INTERACTIVE: NS_CMD_FLAGS = NS_CMD_FLAGS(2i32);
pub const CMD_FLAG_LOCAL: NS_CMD_FLAGS = NS_CMD_FLAGS(8i32);
pub const CMD_FLAG_ONLINE: NS_CMD_FLAGS = NS_CMD_FLAGS(16i32);
pub const CMD_FLAG_HIDDEN: NS_CMD_FLAGS = NS_CMD_FLAGS(32i32);
pub const CMD_FLAG_LIMIT_MASK: NS_CMD_FLAGS = NS_CMD_FLAGS(65535i32);
pub const CMD_FLAG_PRIORITY: NS_CMD_FLAGS = NS_CMD_FLAGS(-2147483648i32);
impl ::core::convert::From<i32> for NS_CMD_FLAGS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NS_CMD_FLAGS {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for NS_CONTEXT_ATTRIBUTES {
fn clone(&self) -> Self {
unimplemented!()
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct NS_CONTEXT_ATTRIBUTES {
pub Anonymous: NS_CONTEXT_ATTRIBUTES_0,
pub pwszContext: super::super::Foundation::PWSTR,
pub guidHelper: ::windows::core::GUID,
pub dwFlags: u32,
pub ulPriority: u32,
pub ulNumTopCmds: u32,
pub pTopCmds: *mut CMD_ENTRY,
pub ulNumGroups: u32,
pub pCmdGroups: *mut CMD_GROUP_ENTRY,
pub pfnCommitFn: ::core::option::Option<PNS_CONTEXT_COMMIT_FN>,
pub pfnDumpFn: ::core::option::Option<PNS_CONTEXT_DUMP_FN>,
pub pfnConnectFn: ::core::option::Option<PNS_CONTEXT_CONNECT_FN>,
pub pReserved: *mut ::core::ffi::c_void,
pub pfnOsVersionCheck: ::core::option::Option<PNS_OSVERSIONCHECK>,
}
#[cfg(feature = "Win32_Foundation")]
impl NS_CONTEXT_ATTRIBUTES {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for NS_CONTEXT_ATTRIBUTES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for NS_CONTEXT_ATTRIBUTES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for NS_CONTEXT_ATTRIBUTES {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for NS_CONTEXT_ATTRIBUTES {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union NS_CONTEXT_ATTRIBUTES_0 {
pub Anonymous: NS_CONTEXT_ATTRIBUTES_0_0,
pub _ullAlign: u64,
}
#[cfg(feature = "Win32_Foundation")]
impl NS_CONTEXT_ATTRIBUTES_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for NS_CONTEXT_ATTRIBUTES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for NS_CONTEXT_ATTRIBUTES_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for NS_CONTEXT_ATTRIBUTES_0 {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for NS_CONTEXT_ATTRIBUTES_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct NS_CONTEXT_ATTRIBUTES_0_0 {
pub dwVersion: u32,
pub dwReserved: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl NS_CONTEXT_ATTRIBUTES_0_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for NS_CONTEXT_ATTRIBUTES_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for NS_CONTEXT_ATTRIBUTES_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("dwVersion", &self.dwVersion).field("dwReserved", &self.dwReserved).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for NS_CONTEXT_ATTRIBUTES_0_0 {
fn eq(&self, other: &Self) -> bool {
self.dwVersion == other.dwVersion && self.dwReserved == other.dwReserved
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for NS_CONTEXT_ATTRIBUTES_0_0 {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for NS_CONTEXT_ATTRIBUTES_0_0 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct NS_EVENTS(pub i32);
pub const NS_EVENT_LOOP: NS_EVENTS = NS_EVENTS(65536i32);
pub const NS_EVENT_LAST_N: NS_EVENTS = NS_EVENTS(1i32);
pub const NS_EVENT_LAST_SECS: NS_EVENTS = NS_EVENTS(2i32);
pub const NS_EVENT_FROM_N: NS_EVENTS = NS_EVENTS(4i32);
pub const NS_EVENT_FROM_START: NS_EVENTS = NS_EVENTS(8i32);
impl ::core::convert::From<i32> for NS_EVENTS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NS_EVENTS {
type Abi = Self;
}
impl ::core::clone::Clone for NS_HELPER_ATTRIBUTES {
fn clone(&self) -> Self {
unimplemented!()
}
}
#[repr(C)]
pub struct NS_HELPER_ATTRIBUTES {
pub Anonymous: NS_HELPER_ATTRIBUTES_0,
pub guidHelper: ::windows::core::GUID,
pub pfnStart: ::core::option::Option<PNS_HELPER_START_FN>,
pub pfnStop: ::core::option::Option<PNS_HELPER_STOP_FN>,
}
impl NS_HELPER_ATTRIBUTES {}
impl ::core::default::Default for NS_HELPER_ATTRIBUTES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for NS_HELPER_ATTRIBUTES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for NS_HELPER_ATTRIBUTES {}
unsafe impl ::windows::core::Abi for NS_HELPER_ATTRIBUTES {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union NS_HELPER_ATTRIBUTES_0 {
pub Anonymous: NS_HELPER_ATTRIBUTES_0_0,
pub _ullAlign: u64,
}
impl NS_HELPER_ATTRIBUTES_0 {}
impl ::core::default::Default for NS_HELPER_ATTRIBUTES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for NS_HELPER_ATTRIBUTES_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for NS_HELPER_ATTRIBUTES_0 {}
unsafe impl ::windows::core::Abi for NS_HELPER_ATTRIBUTES_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct NS_HELPER_ATTRIBUTES_0_0 {
pub dwVersion: u32,
pub dwReserved: u32,
}
impl NS_HELPER_ATTRIBUTES_0_0 {}
impl ::core::default::Default for NS_HELPER_ATTRIBUTES_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for NS_HELPER_ATTRIBUTES_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("dwVersion", &self.dwVersion).field("dwReserved", &self.dwReserved).finish()
}
}
impl ::core::cmp::PartialEq for NS_HELPER_ATTRIBUTES_0_0 {
fn eq(&self, other: &Self) -> bool {
self.dwVersion == other.dwVersion && self.dwReserved == other.dwReserved
}
}
impl ::core::cmp::Eq for NS_HELPER_ATTRIBUTES_0_0 {}
unsafe impl ::windows::core::Abi for NS_HELPER_ATTRIBUTES_0_0 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct NS_MODE_CHANGE(pub i32);
pub const NETSH_COMMIT: NS_MODE_CHANGE = NS_MODE_CHANGE(0i32);
pub const NETSH_UNCOMMIT: NS_MODE_CHANGE = NS_MODE_CHANGE(1i32);
pub const NETSH_FLUSH: NS_MODE_CHANGE = NS_MODE_CHANGE(2i32);
pub const NETSH_COMMIT_STATE: NS_MODE_CHANGE = NS_MODE_CHANGE(3i32);
pub const NETSH_SAVE: NS_MODE_CHANGE = NS_MODE_CHANGE(4i32);
impl ::core::convert::From<i32> for NS_MODE_CHANGE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NS_MODE_CHANGE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct NS_REQS(pub i32);
pub const NS_REQ_ZERO: NS_REQS = NS_REQS(0i32);
pub const NS_REQ_PRESENT: NS_REQS = NS_REQS(1i32);
pub const NS_REQ_ALLOW_MULTIPLE: NS_REQS = NS_REQS(2i32);
pub const NS_REQ_ONE_OR_MORE: NS_REQS = NS_REQS(3i32);
impl ::core::convert::From<i32> for NS_REQS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NS_REQS {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
pub type PFN_HANDLE_CMD = unsafe extern "system" fn(pwszmachine: super::super::Foundation::PWSTR, ppwcarguments: *mut super::super::Foundation::PWSTR, dwcurrentindex: u32, dwargcount: u32, dwflags: u32, pvdata: *const ::core::ffi::c_void, pbdone: *mut super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub type PGET_RESOURCE_STRING_FN = unsafe extern "system" fn(dwmsgid: u32, lpbuffer: super::super::Foundation::PWSTR, nbuffermax: u32) -> u32;
pub type PNS_CONTEXT_COMMIT_FN = unsafe extern "system" fn(dwaction: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub type PNS_CONTEXT_CONNECT_FN = unsafe extern "system" fn(pwszmachine: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub type PNS_CONTEXT_DUMP_FN = unsafe extern "system" fn(pwszrouter: super::super::Foundation::PWSTR, ppwcarguments: *const super::super::Foundation::PWSTR, dwargcount: u32, pvdata: *const ::core::ffi::c_void) -> u32;
pub type PNS_DLL_INIT_FN = unsafe extern "system" fn(dwnetshversion: u32, preserved: *mut ::core::ffi::c_void) -> u32;
pub type PNS_DLL_STOP_FN = unsafe extern "system" fn(dwreserved: u32) -> u32;
pub type PNS_HELPER_START_FN = unsafe extern "system" fn(pguidparent: *const ::windows::core::GUID, dwversion: u32) -> u32;
pub type PNS_HELPER_STOP_FN = unsafe extern "system" fn(dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub type PNS_OSVERSIONCHECK = unsafe extern "system" fn(cimostype: u32, cimosproductsuite: u32, cimosversion: super::super::Foundation::PWSTR, cimosbuildnumber: super::super::Foundation::PWSTR, cimservicepackmajorversion: super::super::Foundation::PWSTR, cimservicepackminorversion: super::super::Foundation::PWSTR, uireserved: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn PreprocessCommand<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hmodule: Param0, ppwcarguments: *mut super::super::Foundation::PWSTR, dwcurrentindex: u32, dwargcount: u32, ptttags: *mut TAG_TYPE, dwtagcount: u32, dwminargs: u32, dwmaxargs: u32, pdwtagtype: *mut u32) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PreprocessCommand(hmodule: super::super::Foundation::HANDLE, ppwcarguments: *mut super::super::Foundation::PWSTR, dwcurrentindex: u32, dwargcount: u32, ptttags: *mut TAG_TYPE, dwtagcount: u32, dwminargs: u32, dwmaxargs: u32, pdwtagtype: *mut u32) -> u32;
}
::core::mem::transmute(PreprocessCommand(
hmodule.into_param().abi(),
::core::mem::transmute(ppwcarguments),
::core::mem::transmute(dwcurrentindex),
::core::mem::transmute(dwargcount),
::core::mem::transmute(ptttags),
::core::mem::transmute(dwtagcount),
::core::mem::transmute(dwminargs),
::core::mem::transmute(dwmaxargs),
::core::mem::transmute(pdwtagtype),
))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn PrintError<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hmodule: Param0, dwerrid: u32) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PrintError(hmodule: super::super::Foundation::HANDLE, dwerrid: u32) -> u32;
}
::core::mem::transmute(PrintError(hmodule.into_param().abi(), ::core::mem::transmute(dwerrid)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn PrintMessage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(pwszformat: Param0) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PrintMessage(pwszformat: super::super::Foundation::PWSTR) -> u32;
}
::core::mem::transmute(PrintMessage(pwszformat.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn PrintMessageFromModule<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hmodule: Param0, dwmsgid: u32) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PrintMessageFromModule(hmodule: super::super::Foundation::HANDLE, dwmsgid: u32) -> u32;
}
::core::mem::transmute(PrintMessageFromModule(hmodule.into_param().abi(), ::core::mem::transmute(dwmsgid)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn RegisterContext(pchildcontext: *const NS_CONTEXT_ATTRIBUTES) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn RegisterContext(pchildcontext: *const ::core::mem::ManuallyDrop<NS_CONTEXT_ATTRIBUTES>) -> u32;
}
::core::mem::transmute(RegisterContext(::core::mem::transmute(pchildcontext)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn RegisterHelper(pguidparentcontext: *const ::windows::core::GUID, pfnregistersubcontext: *const NS_HELPER_ATTRIBUTES) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn RegisterHelper(pguidparentcontext: *const ::windows::core::GUID, pfnregistersubcontext: *const ::core::mem::ManuallyDrop<NS_HELPER_ATTRIBUTES>) -> u32;
}
::core::mem::transmute(RegisterHelper(::core::mem::transmute(pguidparentcontext), ::core::mem::transmute(pfnregistersubcontext)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct TAG_TYPE {
pub pwszTag: super::super::Foundation::PWSTR,
pub dwRequired: u32,
pub bPresent: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl TAG_TYPE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for TAG_TYPE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for TAG_TYPE {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("TAG_TYPE").field("pwszTag", &self.pwszTag).field("dwRequired", &self.dwRequired).field("bPresent", &self.bPresent).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for TAG_TYPE {
fn eq(&self, other: &Self) -> bool {
self.pwszTag == other.pwszTag && self.dwRequired == other.dwRequired && self.bPresent == other.bPresent
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for TAG_TYPE {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for TAG_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct TOKEN_VALUE {
pub pwszToken: super::super::Foundation::PWSTR,
pub dwValue: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl TOKEN_VALUE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for TOKEN_VALUE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for TOKEN_VALUE {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("TOKEN_VALUE").field("pwszToken", &self.pwszToken).field("dwValue", &self.dwValue).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for TOKEN_VALUE {
fn eq(&self, other: &Self) -> bool {
self.pwszToken == other.pwszToken && self.dwValue == other.dwValue
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for TOKEN_VALUE {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for TOKEN_VALUE {
type Abi = Self;
}
|
// 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 {
crate::model::addable_directory::AddableDirectory,
crate::model::*,
cm_rust::{CapabilityPath, ComponentDecl, ExposeDecl, UseDecl, UseStorageDecl},
directory_broker::{DirectoryBroker, RoutingFn},
fuchsia_vfs_pseudo_fs::directory,
std::collections::HashMap,
};
/// Represents the directory hierarchy of the exposed directory, not including the nodes for the
/// capabilities themselves.
pub struct DirTree {
directory_nodes: HashMap<String, Box<DirTree>>,
broker_nodes: HashMap<String, RoutingFn>,
}
impl DirTree {
/// Builds a directory hierarchy from a component's `uses` declarations.
/// `routing_factory` is a closure that generates the routing function that will be called
/// when a leaf node is opened.
pub fn build_from_uses(
routing_factory: impl Fn(AbsoluteMoniker, UseDecl) -> RoutingFn,
abs_moniker: &AbsoluteMoniker,
decl: ComponentDecl,
) -> Result<Self, ModelError> {
let mut tree = DirTree { directory_nodes: HashMap::new(), broker_nodes: HashMap::new() };
for use_ in decl.uses {
tree.add_use_capability(&routing_factory, abs_moniker, &use_)?;
}
Ok(tree)
}
/// Builds a directory hierarchy from a component's `exposes` declarations.
/// `routing_factory` is a closure that generates the routing function that will be called
/// when a leaf node is opened.
pub fn build_from_exposes(
routing_factory: impl Fn(AbsoluteMoniker, ExposeDecl) -> RoutingFn,
abs_moniker: &AbsoluteMoniker,
decl: ComponentDecl,
) -> Self {
let mut tree = DirTree { directory_nodes: HashMap::new(), broker_nodes: HashMap::new() };
for expose in decl.exposes {
tree.add_expose_capability(&routing_factory, abs_moniker, &expose);
}
tree
}
/// Installs the directory tree into `root_dir`.
pub fn install<'entries>(
self,
abs_moniker: &AbsoluteMoniker,
root_dir: &mut impl AddableDirectory<'entries>,
) -> Result<(), ModelError> {
for (name, subtree) in self.directory_nodes {
let mut subdir = directory::simple::empty();
subtree.install(abs_moniker, &mut subdir)?;
root_dir.add_node(&name, subdir, abs_moniker)?;
}
for (name, route_fn) in self.broker_nodes {
let node = DirectoryBroker::new(route_fn);
root_dir.add_node(&name, node, abs_moniker)?;
}
Ok(())
}
fn add_use_capability(
&mut self,
routing_factory: &impl Fn(AbsoluteMoniker, UseDecl) -> RoutingFn,
abs_moniker: &AbsoluteMoniker,
use_: &UseDecl,
) -> Result<(), ModelError> {
let path = match use_ {
cm_rust::UseDecl::Service(d) => &d.target_path,
cm_rust::UseDecl::LegacyService(d) => &d.target_path,
cm_rust::UseDecl::Directory(d) => &d.target_path,
cm_rust::UseDecl::Storage(UseStorageDecl::Data(p)) => &p,
cm_rust::UseDecl::Storage(UseStorageDecl::Cache(p)) => &p,
cm_rust::UseDecl::Storage(UseStorageDecl::Meta) | cm_rust::UseDecl::Runner(_) => {
// Meta storage and runners don't show up in the namespace; nothing to do.
return Ok(());
}
};
let tree = self.to_directory_node(path);
let routing_fn = routing_factory(abs_moniker.clone(), use_.clone());
tree.broker_nodes.insert(path.basename.to_string(), routing_fn);
Ok(())
}
fn add_expose_capability(
&mut self,
routing_factory: &impl Fn(AbsoluteMoniker, ExposeDecl) -> RoutingFn,
abs_moniker: &AbsoluteMoniker,
expose: &ExposeDecl,
) {
let path = match expose {
cm_rust::ExposeDecl::Service(d) => &d.target_path,
cm_rust::ExposeDecl::LegacyService(d) => &d.target_path,
cm_rust::ExposeDecl::Directory(d) => &d.target_path,
cm_rust::ExposeDecl::Runner(_) => {
// Runners do not add directory entries.
return;
}
};
let tree = self.to_directory_node(path);
let routing_fn = routing_factory(abs_moniker.clone(), expose.clone());
tree.broker_nodes.insert(path.basename.to_string(), routing_fn);
}
fn to_directory_node(&mut self, path: &CapabilityPath) -> &mut DirTree {
let components = path.dirname.split("/");
let mut tree = self;
for component in components {
if !component.is_empty() {
tree = tree.directory_nodes.entry(component.to_string()).or_insert(Box::new(
DirTree { directory_nodes: HashMap::new(), broker_nodes: HashMap::new() },
));
}
}
tree
}
}
#[cfg(test)]
mod tests {
use {
super::*,
crate::model::testing::{mocks, test_helpers, test_helpers::*},
cm_rust::{
CapabilityName, CapabilityPath, ExposeDecl, ExposeDirectoryDecl,
ExposeLegacyServiceDecl, ExposeRunnerDecl, ExposeSource, ExposeTarget, UseDecl,
UseDirectoryDecl, UseLegacyServiceDecl, UseRunnerDecl, UseSource, UseStorageDecl,
},
fidl::endpoints::{ClientEnd, ServerEnd},
fidl_fuchsia_io::MODE_TYPE_DIRECTORY,
fidl_fuchsia_io::{DirectoryMarker, NodeMarker, OPEN_RIGHT_READABLE, OPEN_RIGHT_WRITABLE},
fuchsia_async as fasync,
fuchsia_vfs_pseudo_fs::directory::{self, entry::DirectoryEntry},
fuchsia_zircon as zx,
std::{convert::TryFrom, iter},
};
#[fuchsia_async::run_singlethreaded(test)]
async fn build_from_uses() {
// Call `build_from_uses` with a routing factory that routes to a mock directory or service,
// and a `ComponentDecl` with `use` declarations.
let routing_factory = mocks::proxy_use_routing_factory();
let decl = ComponentDecl {
uses: vec![
UseDecl::Directory(UseDirectoryDecl {
source: UseSource::Realm,
source_path: CapabilityPath::try_from("/data/baz").unwrap(),
target_path: CapabilityPath::try_from("/in/data/hippo").unwrap(),
}),
UseDecl::LegacyService(UseLegacyServiceDecl {
source: UseSource::Realm,
source_path: CapabilityPath::try_from("/svc/baz").unwrap(),
target_path: CapabilityPath::try_from("/in/svc/hippo").unwrap(),
}),
UseDecl::Storage(UseStorageDecl::Data(
CapabilityPath::try_from("/in/data/persistent").unwrap(),
)),
UseDecl::Storage(UseStorageDecl::Cache(
CapabilityPath::try_from("/in/data/cache").unwrap(),
)),
UseDecl::Storage(UseStorageDecl::Meta),
UseDecl::Runner(UseRunnerDecl { source_name: CapabilityName::from("elf") }),
],
..default_component_decl()
};
let abs_moniker = AbsoluteMoniker::root();
let tree = DirTree::build_from_uses(routing_factory, &abs_moniker, decl.clone())
.expect("Unable to build 'uses' directory");
// Convert the tree to a directory.
let mut in_dir = directory::simple::empty();
tree.install(&abs_moniker, &mut in_dir).expect("Unable to build pseudodirectory");
let (in_dir_client, in_dir_server) = zx::Channel::create().unwrap();
in_dir.open(
OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE,
MODE_TYPE_DIRECTORY,
&mut iter::empty(),
ServerEnd::<NodeMarker>::new(in_dir_server.into()),
);
fasync::spawn(async move {
let _ = in_dir.await;
});
let in_dir_proxy = ClientEnd::<DirectoryMarker>::new(in_dir_client)
.into_proxy()
.expect("failed to create directory proxy");
assert_eq!(
vec!["in/data/cache", "in/data/hippo", "in/data/persistent", "in/svc/hippo"],
test_helpers::list_directory_recursive(&in_dir_proxy).await
);
// Expect that calls on the directory nodes reach the mock directory/service.
assert_eq!("friend", test_helpers::read_file(&in_dir_proxy, "in/data/hippo/hello").await);
assert_eq!(
"friend",
test_helpers::read_file(&in_dir_proxy, "in/data/persistent/hello").await
);
assert_eq!("friend", test_helpers::read_file(&in_dir_proxy, "in/data/cache/hello").await);
assert_eq!(
"hippos".to_string(),
test_helpers::call_echo(&in_dir_proxy, "in/svc/hippo").await
);
}
#[fuchsia_async::run_singlethreaded(test)]
async fn build_from_exposes() {
// Call `build_from_exposes` with a routing factory that routes to a mock directory or
// service, and a `ComponentDecl` with `expose` declarations.
let routing_factory = mocks::proxy_expose_routing_factory();
let decl = ComponentDecl {
exposes: vec![
ExposeDecl::Directory(ExposeDirectoryDecl {
source: ExposeSource::Self_,
source_path: CapabilityPath::try_from("/data/baz").unwrap(),
target_path: CapabilityPath::try_from("/in/data/hippo").unwrap(),
target: ExposeTarget::Realm,
}),
ExposeDecl::Directory(ExposeDirectoryDecl {
source: ExposeSource::Self_,
source_path: CapabilityPath::try_from("/data/foo").unwrap(),
target_path: CapabilityPath::try_from("/in/data/bar").unwrap(),
target: ExposeTarget::Realm,
}),
ExposeDecl::LegacyService(ExposeLegacyServiceDecl {
source: ExposeSource::Self_,
source_path: CapabilityPath::try_from("/svc/baz").unwrap(),
target_path: CapabilityPath::try_from("/in/svc/hippo").unwrap(),
target: ExposeTarget::Realm,
}),
ExposeDecl::Runner(ExposeRunnerDecl {
source: ExposeSource::Self_,
source_name: CapabilityName::from("elf"),
target: ExposeTarget::Realm,
target_name: CapabilityName::from("elf"),
}),
],
..default_component_decl()
};
let abs_moniker = AbsoluteMoniker::root();
let tree = DirTree::build_from_exposes(routing_factory, &abs_moniker, decl.clone());
// Convert the tree to a directory.
let mut expose_dir = directory::simple::empty();
tree.install(&abs_moniker, &mut expose_dir).expect("Unable to build pseudodirectory");
let (expose_dir_client, expose_dir_server) = zx::Channel::create().unwrap();
expose_dir.open(
OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE,
MODE_TYPE_DIRECTORY,
&mut iter::empty(),
ServerEnd::<NodeMarker>::new(expose_dir_server.into()),
);
fasync::spawn(async move {
let _ = expose_dir.await;
});
let expose_dir_proxy = ClientEnd::<DirectoryMarker>::new(expose_dir_client)
.into_proxy()
.expect("failed to create directory proxy");
assert_eq!(
vec!["in/data/bar", "in/data/hippo", "in/svc/hippo"],
test_helpers::list_directory_recursive(&expose_dir_proxy).await
);
// Expect that calls on the directory nodes reach the mock directory/service.
assert_eq!("friend", test_helpers::read_file(&expose_dir_proxy, "in/data/bar/hello").await);
assert_eq!(
"friend",
test_helpers::read_file(&expose_dir_proxy, "in/data/hippo/hello").await
);
assert_eq!(
"hippos".to_string(),
test_helpers::call_echo(&expose_dir_proxy, "in/svc/hippo").await
);
}
}
|
use crate::headers::{Error, Header, HeaderName, HeaderValue};
use hyper::http::header;
use std::fmt;
use std::iter;
use std::str::FromStr;
const BASIC_REALM_PREAMBLE: &str = "Basic realm=";
static WWW_AUTHENTICATE: &HeaderName = &header::WWW_AUTHENTICATE;
#[derive(Clone, Debug, PartialEq)]
pub struct WWWAuthenticate(BasicRealm);
impl WWWAuthenticate {
pub fn basic_realm(realm: &str) -> Self {
WWWAuthenticate(BasicRealm(realm.to_owned()))
}
}
impl Header for WWWAuthenticate {
fn name() -> &'static HeaderName {
WWW_AUTHENTICATE
}
fn decode<'i, I>(values: &mut I) -> Result<Self, Error>
where
Self: Sized,
I: Iterator<Item = &'i HeaderValue>,
{
values
.next()
.and_then(|v| v.to_str().ok()?.parse().ok())
.map(WWWAuthenticate)
.ok_or_else(Error::invalid)
}
fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
values.extend(iter::once((&self.0).into()))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct BasicRealm(String);
impl From<&BasicRealm> for HeaderValue {
fn from(realm: &BasicRealm) -> Self {
format!("{}", realm).parse().unwrap()
}
}
impl fmt::Display for BasicRealm {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(BASIC_REALM_PREAMBLE)?;
f.write_str("\"")?;
f.write_str(&self.0)?;
f.write_str("\"")?;
Ok(())
}
}
impl FromStr for BasicRealm {
type Err = Error;
fn from_str(s: &str) -> Result<BasicRealm, Error> {
if s.starts_with(BASIC_REALM_PREAMBLE) {
Ok(BasicRealm(
s[BASIC_REALM_PREAMBLE.len() + 1..s.len() - 1].to_owned(),
))
} else {
Err(Error::invalid())
}
}
}
#[cfg(test)]
mod test {
use super::{BasicRealm, WWWAuthenticate};
use crate::headers::{Header, HeaderMapExt};
use crate::test::headers::encode;
use hyper::http::HeaderMap;
#[test]
fn test_encode_basic_realm() {
assert_eq!(
format!("{}", BasicRealm(String::from("Test Realm"))),
"Basic realm=\"Test Realm\""
)
}
#[test]
fn test_parse_basic_realm() {
assert_eq!(
"Basic realm=\"Test Realm\"".parse::<BasicRealm>().unwrap(),
BasicRealm(String::from("Test Realm")),
)
}
#[test]
fn test_parse_err_basic_realm() {
assert!("Missing realm=\"Test Realm\""
.parse::<BasicRealm>()
.is_err())
}
#[test]
fn test_encode_www_authenticate() {
assert_eq!(
encode(WWWAuthenticate::basic_realm("Test Realm"))
.to_str()
.unwrap(),
"Basic realm=\"Test Realm\""
)
}
#[test]
fn test_decode_www_authenticate() {
let mut headers = HeaderMap::new();
headers.insert(
WWWAuthenticate::name(),
"Basic realm=\"Test Realm\"".parse().unwrap(),
);
let header = headers.typed_get::<WWWAuthenticate>().unwrap();
assert_eq!(header, WWWAuthenticate::basic_realm("Test Realm"))
}
#[test]
fn test_decode_www_authenticate_invalid() {
let mut headers = HeaderMap::new();
headers.insert(
WWWAuthenticate::name(),
"Missing realm=\"Test Realm\"".parse().unwrap(),
);
let header = headers.typed_try_get::<WWWAuthenticate>();
assert!(header.is_err())
}
}
|
use ggez::graphics::*;
use ggez::*;
use tiled;
use sprite::*;
use util;
#[derive(Debug)]
pub struct Map {
// pixel location of top left of map
pub(crate) pos: Point2,
pub(crate) camera: Rect,
// layer index to use
pub(crate) layer_index: usize,
// tileset to use
pub(crate) tile_set: usize,
// gid of tileset with blocking layer
pub(crate) blocking_tile: u32,
pub(crate) map_def: tiled::Map,
}
impl Map {
pub fn new(map_def: tiled::Map) -> Self {
let mut blocking_tile = 0;
let mut found_blocking = false;
for tileset in map_def.tilesets.iter() {
if tileset.name.contains("collision") {
blocking_tile = tileset.first_gid;
found_blocking = true;
break;
}
}
if !found_blocking {
panic!("No collision tile found");
}
Map {
pos: Point2::new(0.0, 0.0),
camera: Rect::new(
0.0,
0.0,
// 43.0 * 16.0,
// 15.0 * 16.0,
(map_def.width * map_def.tile_width) as f32,
(map_def.width * map_def.tile_height) as f32,
),
layer_index: 0,
tile_set: 0,
blocking_tile,
map_def,
}
}
/// Getters
pub fn dimensions(&self) -> (u32, u32) {
let m = &self.map_def;
return (m.width, m.height);
}
pub fn tile_dimensions(&self) -> (u32, u32) {
let m = &self.map_def;
return (m.tile_width, m.tile_height);
}
pub fn pixel_dimensions(&self) -> (u32, u32) {
let m = &self.map_def;
return (m.tile_width * m.width, m.height * m.tile_height);
}
/// Advance Getters/ Setters
pub fn get_tile(&self, x: usize, y: usize, layer: usize) -> u32 {
self.map_def.layers[layer].tiles[y][x]
}
pub fn write_tile(&mut self, x: usize, y: usize, layer: usize, tile: u32) {
self.map_def.layers[layer].tiles[y][x] = tile;
}
pub fn in_bounds(&mut self, x: usize, y: usize, layer: usize) -> bool {
let y_bounds = self.map_def.layers[layer].tiles.len();
let x_bounds = self.map_def.layers[layer].tiles[y].len();
x < x_bounds && y < y_bounds
}
// is blocking
pub fn is_blocking(&self, x: usize, y: usize, layer: usize) -> bool {
let collision_layer = layer + 2;
let tile = self.get_tile(x, y, collision_layer);
self.blocking_tile == tile
}
pub fn set_blocking(&mut self, x: usize, y: usize, layer: usize, blocking: bool) {
if blocking {
let bt = self.blocking_tile;
self.write_tile(x, y, layer + 2, bt);
} else {
self.write_tile(x, y, layer + 2, 0);
}
}
/// converts world pixel coordinates to tile in map
pub fn point_to_tile(&self, x: f32, y: f32) -> (usize, usize) {
let (w, h) = self.pixel_dimensions();
let (tw, th) = self.tile_dimensions();
let x = util::clamp(x, self.pos.x, self.pos.y + w as f32 - 1.0);
let y = util::clamp(y, self.pos.y, self.pos.y + h as f32 - 1.0);
let tile_x = ((x - self.pos.x) / tw as f32).floor();
let tile_y = ((y - self.pos.y) / th as f32).floor();
(tile_x as usize, tile_y as usize)
}
pub fn get_tile_foot(&self, x: usize, y: usize) -> graphics::Point2 {
let tile_dimensions = self.tile_dimensions();
let x = self.pos.x + (tile_dimensions.0 as f32 * x as f32) + tile_dimensions.0 as f32 / 2.0;
let y = self.pos.y + (tile_dimensions.1 as f32 * y as f32) + tile_dimensions.1 as f32;
Point2::new(x, y)
}
pub fn get_tile_top(&self, x: usize, y: usize) -> graphics::Point2 {
let tile_dimensions = self.tile_dimensions();
let x = self.pos.x + (tile_dimensions.0 as f32 * x as f32) + tile_dimensions.0 as f32 / 2.0;
let y = self.pos.y + (tile_dimensions.1 as f32 * y as f32);
Point2::new(x, y)
}
/// redner helpers
pub fn tile_draw_params(
&self,
uvs: &Vec<Rect>,
tile_x: usize,
tile_y: usize,
tile: u32,
) -> graphics::DrawParam {
let (tw, th) = self.tile_dimensions();
let x: f32 = self.pos.x + tw as f32 * tile_x as f32;
let y: f32 = self.pos.y + th as f32 * tile_y as f32;
// subtract 1 because tiled indexes by 1
let uv = uvs[(tile - 1) as usize];
// println!("wh: {} {}", uv.left() * self.map_pixel_width, uv.right() * self.map_pixel_width);
let mut params = graphics::DrawParam::default();
params.src = uv;
params.dest = Point2::new(-self.camera.left() + x, -self.camera.top() + y);
// TODO: Figure out reason for this hack
// have to scale otherwise it looks like tearing
params.scale = Point2::new(1.1, 1.1);
params
}
}
impl SpriteComponent for Map {
fn setup_sprite(&self, sprite: &mut Sprite) {
// layers are made of 3 sections
// want the index to point to a given section
let layer_index = self.layer_index * 3;
let (tile_left, tile_top) = self.point_to_tile(self.camera.left(), self.camera.top());
let (tile_right, tile_bottom) =
self.point_to_tile(self.camera.right(), self.camera.bottom());
sprite.sprite_batch.clear();
for j in tile_top..=(tile_bottom) {
for i in tile_left..=(tile_right) {
// Get actual tile layer
let tile = self.get_tile(i, j, layer_index);
if tile > 0 {
sprite
.sprite_batch
.add(self.tile_draw_params(&sprite.uvs, i, j, tile));
}
// Get decoration layer tiles
let tile = self.get_tile(i, j, layer_index + 1);
if tile > 0 {
sprite
.sprite_batch
.add(self.tile_draw_params(&sprite.uvs, i, j, tile));
}
}
}
}
/// Where to draw the sprite map at
fn draw_sprite_at(&self) -> graphics::Point2 {
self.pos.clone()
}
}
pub fn load_tile_map(ctx: &mut Context, tilemap_src: &str) -> GameResult<tiled::Map> {
let tilemap_file = ctx.filesystem.open(tilemap_src)?;
match tiled::parse(tilemap_file) {
Ok(map) => Ok(map),
Err(_) => Err(GameError::from(String::from("tiled error"))),
}
}
|
// Install:
//
// cargo install --git https://github.com/BurntSushi/dotfiles find-invalid-utf8
//
// Usage:
//
// find-invalid-utf8
// find-invalid-utf8 path/to/directory-or-file
//
// To parallelize, use 'xargs':
//
// find ./ -print0 | xargs -0 -n1 -P8 find-invalid-utf8
use std::{ffi::OsString, fs::File, io::BufRead, path::Path};
use anyhow::Context;
use bstr::{io::BufReadExt, ByteSlice};
use termcolor::{Color, ColorChoice, ColorSpec, WriteColor};
fn main() -> anyhow::Result<()> {
let mut args: Vec<OsString> = std::env::args_os().skip(1).collect();
let dir = match args.pop() {
None => OsString::from("."),
Some(dir) => {
anyhow::ensure!(
args.is_empty(),
"Usage: find-invalid-utf8 [<dir>]"
);
dir
}
};
// Basically just iterate over every line in every file in a directory
// tree, and if a line contains invalid UTF-8, print it. Invalid UTF-8
// bytes are colorized and printed in their hexadecimal format.
//
// As a heuristic, files containing a NUL byte are assumed to be binary
// and are skipped.
let wtr = termcolor::BufferWriter::stdout(ColorChoice::Auto);
let mut buf = termcolor::Buffer::ansi();
for result in walkdir::WalkDir::new(dir) {
let dent = result?;
if !dent.file_type().is_file() {
continue;
}
let file = File::open(dent.path())
.with_context(|| format!("{}", dent.path().display()))?;
let rdr = std::io::BufReader::new(file);
buf.clear();
let is_binary = print_utf8_errors(dent.path(), rdr, &mut buf)
.with_context(|| format!("{}", dent.path().display()))?;
if !is_binary {
wtr.print(&buf)?;
}
}
Ok(())
}
/// Print lines that contain bytes that aren't valid UTF-8. Bytes that aren't
/// valid UTF-8 are printed in hexadecimal format.
///
/// This returns true if the reader is suspected of being a binary file. In
/// that case, printing to `wtr` is stopped and `true` is returned.
fn print_utf8_errors<R: BufRead, W: WriteColor>(
path: &Path,
mut rdr: R,
mut wtr: W,
) -> anyhow::Result<bool> {
let mut is_binary = false;
let (mut lineno, mut offset) = (1, 0);
rdr.for_byte_line_with_terminator(|line| {
if line.find_byte(b'\x00').is_some() {
is_binary = true;
return Ok(false);
}
let (cur_lineno, cur_offset) = (lineno, offset);
lineno += 1;
offset += line.len();
if line.is_utf8() {
return Ok(true);
}
write!(wtr, "{}:{}:{}:", path.display(), cur_lineno, cur_offset)?;
for chunk in line.utf8_chunks() {
if !chunk.valid().is_empty() {
write!(wtr, "{}", chunk.valid())?;
}
if !chunk.invalid().is_empty() {
let mut color = ColorSpec::new();
color.set_fg(Some(Color::Red)).set_bold(true);
wtr.set_color(&color)?;
for &b in chunk.invalid().iter() {
write!(wtr, r"\x{:X}", b)?;
}
wtr.reset()?;
}
}
Ok(true)
})?;
Ok(is_binary)
}
|
pub fn raindrops(num: usize) -> String {
let factors = rain_factors(num);
let mut rain = String::new();
for factor in factors {
match factor {
3 => rain.push_str("Pling"),
5 => rain.push_str("Plang"),
7 => rain.push_str("Plong"),
_ => continue,
};
}
if rain.is_empty() {
rain = format!("{}", num);
}
rain
}
fn rain_factors(num: usize) -> Vec<usize> {
let mut factors = Vec::new();
let candidates = vec![3, 5, 7];
for cand in candidates {
if num % cand == 0 {
factors.push(cand);
}
}
factors
}
|
#![feature(phase)]
#[phase(plugin)]
extern crate rustful_macros;
extern crate rustful;
use std::sync::RWLock;
use rustful::{Server, TreeRouter, Request, Response, RequestPlugin, ResponsePlugin};
use rustful::RequestAction;
use rustful::RequestAction::Continue;
use rustful::{ResponseAction, ResponseData};
use rustful::Method::Get;
use rustful::StatusCode;
use rustful::header::Headers;
fn say_hello(request: Request, _cache: &(), response: Response) {
let person = match request.variables.get(&"person".into_string()) {
Some(name) => name.as_slice(),
None => "stranger"
};
try_send!(response.into_writer(), format!("{{\"message\": \"Hello, {}!\"}}", person));
}
fn main() {
println!("Visit http://localhost:8080 or http://localhost:8080/Peter (if your name is Peter) to try this example.");
let routes = routes!{
"print" => {
Get: say_hello,
":person" => Get: say_hello
}
};
let server_result = Server::new()
.handlers(TreeRouter::from_routes(&routes))
.port(8080)
//Log path, change path, log again
.with_request_plugin(RequestLogger::new())
.with_request_plugin(PathPrefix::new("print"))
.with_request_plugin(RequestLogger::new())
.with_response_plugin(Jsonp::new("setMessage"))
.run();
match server_result {
Ok(_server) => {},
Err(e) => println!("could not start server: {}", e)
}
}
struct RequestLogger {
counter: RWLock<uint>
}
impl RequestLogger {
pub fn new() -> RequestLogger {
RequestLogger {
counter: RWLock::new(0)
}
}
}
impl RequestPlugin for RequestLogger {
///Count requests and log the path.
fn modify(&self, request: &mut Request) -> RequestAction {
*self.counter.write() += 1;
println!("Request #{} is to '{}'", *self.counter.read(), request.path);
Continue
}
}
struct PathPrefix {
prefix: &'static str
}
impl PathPrefix {
pub fn new(prefix: &'static str) -> PathPrefix {
PathPrefix {
prefix: prefix
}
}
}
impl RequestPlugin for PathPrefix {
///Append the prefix to the path
fn modify(&self, request: &mut Request) -> RequestAction {
request.path = format!("/{}{}", self.prefix.trim_chars('/'), request.path);
Continue
}
}
struct Jsonp {
function: &'static str
}
impl Jsonp {
pub fn new(function: &'static str) -> Jsonp {
Jsonp {
function: function
}
}
}
impl ResponsePlugin for Jsonp {
fn begin(&self, status: StatusCode, headers: Headers) -> (StatusCode, Headers, ResponseAction) {
let action = ResponseAction::write(Some(format!("{}(", self.function)));
(status, headers, action)
}
fn write<'a>(&'a self, bytes: Option<ResponseData<'a>>) -> ResponseAction {
ResponseAction::write(bytes)
}
fn end(&self) -> ResponseAction {
ResponseAction::write(Some(");"))
}
} |
use std;
#[test]
fn test() { let x = std::option::some[int](10); } |
mod models;
mod views;
mod controllers;
mod tests;
|
use std::collections::HashMap;
use std::fs;
use colored::*;
use log::*;
use serde::Deserialize;
use serde_json::Value;
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum AWSService {
Lambda {
runtime: String,
handler: String,
#[serde(default)]
env_file: String,
#[serde(default)]
env_vars: HashMap<String, String>,
function_name: String,
files: Vec<String>,
function_path: String,
},
Apigateway {
api_name: String,
path_part: String,
http_method: String,
authorization_type: String,
integration_type: String,
integration_http_method: String,
uri: String,
},
Dynamo {
table_name: String,
schema: Value,
#[serde(default)]
recreate: bool,
},
Kinesis {
stream_name: String,
#[serde(default)]
shard_count: u32,
},
S3 {
bucket: String,
#[serde(default)]
recreate: bool,
#[serde(default)]
files: Vec<String>,
},
SNS {
topic: String,
},
SQS {
queue: String,
},
}
#[derive(Deserialize, Debug)]
pub struct Dep {
#[serde(default)]
pub services: Vec<String>,
pub location: String,
#[serde(default)]
pub stackfile: String,
}
#[derive(Deserialize, Debug)]
pub struct Service {
#[serde(flatten)]
pub variant: AWSService,
#[serde(default)]
pub deps: HashMap<String, Dep>,
}
#[derive(Deserialize, Debug)]
pub struct LocalstackConfig {
pub version: String,
pub services: Vec<String>,
pub docker_host: String,
#[serde(default)]
pub lambda_executer: String,
#[serde(default)]
pub data_dir: String,
#[serde(default)]
pub port_web_ui: String,
#[serde(default)]
pub debug: String,
#[serde(default)]
pub kinesis_error_probability: u32,
#[serde(default)]
pub recreate: bool,
}
#[derive(Deserialize, Debug)]
pub struct Stack {
pub localstack_config: LocalstackConfig,
pub services: HashMap<String, Service>,
}
pub fn parse(stackfile: &str, format: &str) -> Option<Stack> {
let data = fs::read_to_string(&stackfile).expect("failed reading stackfile");
match format.as_ref() {
"json" => serde_json::from_str(&data).unwrap(),
"yaml" => serde_yaml::from_str(&data).unwrap(),
_ => {
error!(
"don't know how to parse '{}', not supported stackfile format",
stackfile.yellow()
);
return None;
}
}
}
|
// Copyright 2019 The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::support::utils::{make_input, random_string};
use rand::rngs::OsRng;
use std::{sync::Arc, time::Duration};
use tari_comms::{
multiaddr::Multiaddr,
peer_manager::{NodeId, NodeIdentity, Peer, PeerFeatures, PeerFlags},
types::CommsPublicKey,
};
use tari_comms_dht::DhtConfig;
use tari_core::transactions::{tari_amount::MicroTari, types::CryptoFactories};
use tari_crypto::keys::PublicKey;
use tari_p2p::initialization::CommsConfig;
use tari_test_utils::paths::with_temp_dir;
use crate::support::comms_and_services::get_next_memory_address;
use futures::{FutureExt, StreamExt};
use std::path::Path;
use tari_core::transactions::{tari_amount::uT, transaction::UnblindedOutput, types::PrivateKey};
use tari_p2p::transport::TransportType;
use tari_wallet::{
contacts_service::storage::{database::Contact, memory_db::ContactsServiceMemoryDatabase},
output_manager_service::storage::memory_db::OutputManagerMemoryDatabase,
storage::memory_db::WalletMemoryDatabase,
transaction_service::{handle::TransactionEvent, storage::memory_db::TransactionMemoryDatabase},
wallet::WalletConfig,
Wallet,
};
use tempdir::TempDir;
use tokio::{runtime::Runtime, time::delay_for};
fn create_peer(public_key: CommsPublicKey, net_address: Multiaddr) -> Peer {
Peer::new(
public_key.clone(),
NodeId::from_key(&public_key).unwrap(),
net_address.into(),
PeerFlags::empty(),
PeerFeatures::COMMUNICATION_NODE,
&[],
)
}
fn create_wallet(
node_identity: NodeIdentity,
data_path: &Path,
factories: CryptoFactories,
) -> Wallet<WalletMemoryDatabase, TransactionMemoryDatabase, OutputManagerMemoryDatabase, ContactsServiceMemoryDatabase>
{
let comms_config = CommsConfig {
node_identity: Arc::new(node_identity.clone()),
transport_type: TransportType::Memory {
listener_address: node_identity.public_address(),
},
datastore_path: data_path.to_path_buf(),
peer_database_name: random_string(8),
max_concurrent_inbound_tasks: 100,
outbound_buffer_size: 100,
dht: DhtConfig {
discovery_request_timeout: Duration::from_secs(1),
..Default::default()
},
allow_test_addresses: true,
listener_liveness_whitelist_cidrs: Vec::new(),
listener_liveness_max_sessions: 0,
};
let config = WalletConfig {
comms_config,
factories,
transaction_service_config: None,
};
let runtime_node = Runtime::new().unwrap();
let wallet = Wallet::new(
config,
runtime_node,
WalletMemoryDatabase::new(),
TransactionMemoryDatabase::new(),
OutputManagerMemoryDatabase::new(),
ContactsServiceMemoryDatabase::new(),
)
.unwrap();
wallet
}
#[test]
fn test_wallet() {
with_temp_dir(|dir_path| {
let mut runtime = Runtime::new().unwrap();
let factories = CryptoFactories::default();
let alice_identity =
NodeIdentity::random(&mut OsRng, get_next_memory_address(), PeerFeatures::COMMUNICATION_NODE).unwrap();
let bob_identity =
NodeIdentity::random(&mut OsRng, get_next_memory_address(), PeerFeatures::COMMUNICATION_NODE).unwrap();
let base_node_identity =
NodeIdentity::random(&mut OsRng, get_next_memory_address(), PeerFeatures::COMMUNICATION_NODE).unwrap();
let mut alice_wallet = create_wallet(alice_identity.clone(), dir_path, factories.clone());
let mut bob_wallet = create_wallet(bob_identity.clone(), dir_path, factories.clone());
alice_wallet
.runtime
.block_on(alice_wallet.comms.peer_manager().add_peer(create_peer(
bob_identity.public_key().clone(),
bob_identity.public_address(),
)))
.unwrap();
bob_wallet
.runtime
.block_on(bob_wallet.comms.peer_manager().add_peer(create_peer(
alice_identity.public_key().clone(),
alice_identity.public_address(),
)))
.unwrap();
alice_wallet
.set_base_node_peer(
(*base_node_identity.public_key()).clone(),
get_next_memory_address().to_string(),
)
.unwrap();
let mut alice_event_stream = alice_wallet.transaction_service.get_event_stream_fused();
let value = MicroTari::from(1000);
let (_utxo, uo1) = make_input(&mut OsRng, MicroTari(2500), &factories.commitment);
runtime
.block_on(alice_wallet.output_manager_service.add_output(uo1))
.unwrap();
runtime
.block_on(alice_wallet.transaction_service.send_transaction(
bob_identity.public_key().clone(),
value,
MicroTari::from(20),
"".to_string(),
))
.unwrap();
runtime.block_on(async {
let mut delay = delay_for(Duration::from_secs(60)).fuse();
let mut reply_count = false;
loop {
futures::select! {
event = alice_event_stream.select_next_some() => match &*event.unwrap() {
TransactionEvent::ReceivedTransactionReply(_) => {
reply_count = true;
break;
},
_ => (),
},
() = delay => {
break;
},
}
}
assert!(reply_count);
});
let mut contacts = Vec::new();
for i in 0..2 {
let (_secret_key, public_key) = PublicKey::random_keypair(&mut OsRng);
contacts.push(Contact {
alias: random_string(8),
public_key,
});
runtime
.block_on(alice_wallet.contacts_service.upsert_contact(contacts[i].clone()))
.unwrap();
}
let got_contacts = runtime.block_on(alice_wallet.contacts_service.get_contacts()).unwrap();
assert_eq!(contacts, got_contacts);
});
}
#[test]
fn test_store_and_forward_send_tx() {
let factories = CryptoFactories::default();
let db_tempdir = TempDir::new(random_string(8).as_str()).unwrap();
let alice_identity =
NodeIdentity::random(&mut OsRng, get_next_memory_address(), PeerFeatures::COMMUNICATION_NODE).unwrap();
let bob_identity =
NodeIdentity::random(&mut OsRng, get_next_memory_address(), PeerFeatures::COMMUNICATION_NODE).unwrap();
let carol_identity =
NodeIdentity::random(&mut OsRng, get_next_memory_address(), PeerFeatures::COMMUNICATION_NODE).unwrap();
let mut alice_wallet = create_wallet(alice_identity.clone(), &db_tempdir.path(), factories.clone());
let mut bob_wallet = create_wallet(bob_identity.clone(), &db_tempdir.path(), factories.clone());
let mut alice_event_stream = alice_wallet.transaction_service.get_event_stream_fused();
alice_wallet
.runtime
.block_on(alice_wallet.comms.peer_manager().add_peer(create_peer(
bob_identity.public_key().clone(),
bob_identity.public_address(),
)))
.unwrap();
bob_wallet
.runtime
.block_on(bob_wallet.comms.peer_manager().add_peer(create_peer(
alice_identity.public_key().clone(),
alice_identity.public_address(),
)))
.unwrap();
bob_wallet
.runtime
.block_on(bob_wallet.comms.peer_manager().add_peer(create_peer(
carol_identity.public_key().clone(),
carol_identity.public_address(),
)))
.unwrap();
let value = MicroTari::from(1000);
let (_utxo, uo1) = make_input(&mut OsRng, MicroTari(2500), &factories.commitment);
alice_wallet
.runtime
.block_on(alice_wallet.output_manager_service.add_output(uo1))
.unwrap();
alice_wallet
.runtime
.block_on(alice_wallet.transaction_service.send_transaction(
carol_identity.public_key().clone(),
value,
MicroTari::from(20),
"Store and Forward!".to_string(),
))
.unwrap();
// Waiting here for a while to make sure the discovery retry is over
alice_wallet
.runtime
.block_on(async { delay_for(Duration::from_secs(10)).await });
let mut carol_wallet = create_wallet(carol_identity.clone(), &db_tempdir.path(), factories.clone());
carol_wallet
.runtime
.block_on(carol_wallet.comms.peer_manager().add_peer(create_peer(
bob_identity.public_key().clone(),
bob_identity.public_address(),
)))
.unwrap();
alice_wallet.runtime.block_on(async {
let mut delay = delay_for(Duration::from_secs(60)).fuse();
let mut tx_reply = 0;
loop {
futures::select! {
event = alice_event_stream.select_next_some() => {
match &*event.unwrap() {
TransactionEvent::ReceivedTransactionReply(_) => tx_reply+=1,
_ => (),
}
if tx_reply == 1 {
break;
}
},
() = delay => {
break;
},
}
}
assert_eq!(tx_reply, 1, "Must have received a reply from Carol");
});
alice_wallet.shutdown();
bob_wallet.shutdown();
carol_wallet.shutdown();
}
#[test]
fn test_import_utxo() {
let factories = CryptoFactories::default();
let alice_identity = NodeIdentity::random(
&mut OsRng,
"/ip4/127.0.0.1/tcp/24521".parse().unwrap(),
PeerFeatures::COMMUNICATION_NODE,
)
.unwrap();
let base_node_identity = NodeIdentity::random(
&mut OsRng,
"/ip4/127.0.0.1/tcp/24522".parse().unwrap(),
PeerFeatures::COMMUNICATION_NODE,
)
.unwrap();
let temp_dir = TempDir::new(random_string(8).as_str()).unwrap();
let comms_config = CommsConfig {
node_identity: Arc::new(alice_identity.clone()),
transport_type: TransportType::Tcp {
listener_address: "/ip4/127.0.0.1/tcp/0".parse().unwrap(),
tor_socks_config: None,
},
datastore_path: temp_dir.path().to_path_buf(),
peer_database_name: random_string(8),
max_concurrent_inbound_tasks: 100,
outbound_buffer_size: 100,
dht: Default::default(),
allow_test_addresses: true,
listener_liveness_whitelist_cidrs: Vec::new(),
listener_liveness_max_sessions: 0,
};
let config = WalletConfig {
comms_config,
factories: factories.clone(),
transaction_service_config: None,
};
let runtime_node = Runtime::new().unwrap();
let mut alice_wallet = Wallet::new(
config,
runtime_node,
WalletMemoryDatabase::new(),
TransactionMemoryDatabase::new(),
OutputManagerMemoryDatabase::new(),
ContactsServiceMemoryDatabase::new(),
)
.unwrap();
let utxo = UnblindedOutput::new(20000 * uT, PrivateKey::default(), None);
let tx_id = alice_wallet
.import_utxo(
utxo.value,
&utxo.spending_key,
base_node_identity.public_key(),
"Testing".to_string(),
)
.unwrap();
let balance = alice_wallet
.runtime
.block_on(alice_wallet.output_manager_service.get_balance())
.unwrap();
assert_eq!(balance.available_balance, 20000 * uT);
let completed_tx = alice_wallet
.runtime
.block_on(alice_wallet.transaction_service.get_completed_transactions())
.unwrap()
.remove(&tx_id)
.expect("Tx should be in collection");
assert_eq!(completed_tx.amount, 20000 * uT);
}
#[cfg(feature = "test_harness")]
#[test]
fn test_data_generation() {
use tari_wallet::testnet_utils::generate_wallet_test_data;
let runtime = Runtime::new().unwrap();
let factories = CryptoFactories::default();
let node_id =
NodeIdentity::random(&mut OsRng, get_next_memory_address(), PeerFeatures::COMMUNICATION_NODE).unwrap();
let temp_dir = TempDir::new(random_string(8).as_str()).unwrap();
let comms_config = CommsConfig {
node_identity: Arc::new(node_id.clone()),
transport_type: TransportType::Memory {
listener_address: "/memory/0".parse().unwrap(),
},
datastore_path: temp_dir.path().to_path_buf(),
peer_database_name: random_string(8),
max_concurrent_inbound_tasks: 100,
outbound_buffer_size: 100,
dht: DhtConfig {
discovery_request_timeout: Duration::from_millis(500),
..Default::default()
},
allow_test_addresses: true,
listener_liveness_whitelist_cidrs: Vec::new(),
listener_liveness_max_sessions: 0,
};
let config = WalletConfig {
comms_config,
factories,
transaction_service_config: None,
};
let transaction_backend = TransactionMemoryDatabase::new();
let mut wallet = Wallet::new(
config,
runtime,
WalletMemoryDatabase::new(),
transaction_backend.clone(),
OutputManagerMemoryDatabase::new(),
ContactsServiceMemoryDatabase::new(),
)
.unwrap();
generate_wallet_test_data(&mut wallet, temp_dir.path(), transaction_backend).unwrap();
let contacts = wallet.runtime.block_on(wallet.contacts_service.get_contacts()).unwrap();
assert!(contacts.len() > 0);
let balance = wallet
.runtime
.block_on(wallet.output_manager_service.get_balance())
.unwrap();
assert!(balance.available_balance > MicroTari::from(0));
// TODO Put this back when the new comms goes in and we use the new Event bus
// let outbound_tx = wallet
// .runtime
// .block_on(wallet.transaction_service.get_pending_outbound_transactions())
// .unwrap();
// assert!(outbound_tx.len() > 0);
let completed_tx = wallet
.runtime
.block_on(wallet.transaction_service.get_completed_transactions())
.unwrap();
assert!(completed_tx.len() > 0);
wallet.shutdown();
}
|
#[test]
fn repr_rust_struct() {
use std::mem::size_of;
struct MyStructRust {
_a: usize,
_b: String,
}
assert_eq!(
size_of::<usize>() + size_of::<String>(),
size_of::<MyStructRust>()
);
}
#[test]
fn repr_c_struct() {
use std::mem::size_of;
#[repr(C)]
struct MyStructC {
_a: usize,
_b: *const u8,
}
assert_eq!(
size_of::<usize>() + size_of::<*const u8>(),
std::mem::size_of::<MyStructC>()
);
}
|
//! A library for interacting with audio devices.
//!
//! The sole aim of this crate is to provide idiomatic *low level* audio
//! interface drivers that can be used independently. If all you need is WASAPI
//! or ALSA, then that is all you pay for and you should have a decent
//! Rust-idiomatic programming experience.
//!
//! This is part of the [audio ecosystem] and makes use of core traits provided
//! by the [audio-core] crate.
//!
//! # Examples
//!
//! * [ALSA blocking playback][alsa-blocking].
//! * [ALSA async playback][alsa-async].
//! * [WASAPI blocking playback][wasapi-blocking].
//! * [WASAPI async playback][wasapi-async].
//!
//! # Support
//!
//! Supported tier 1 platforms and systems are the following:
//!
//! | Platform | System | Blocking | Async |
//! |----------|--------|----------|---------|
//! | Windows | WASAPI | **wip** | **wip** |
//! | Linux | ALSA | **wip** | **wip** |
//!
//! [audio ecosystem]: https://docs.rs/audio
//! [alsa-blocking]: https://github.com/udoprog/audio/blob/main/audio-device/examples/alsa.rs
//! [alsa-async]: https://github.com/udoprog/audio/blob/main/audio-device/examples/alsa-async.rs
//! [audio-core]: https://docs.rs/audio-core
//! [wasapi-async]: https://github.com/udoprog/audio/blob/main/audio-device/examples/wasapi-async.rs
//! [wasapi-blocking]: https://github.com/udoprog/audio/blob/main/audio-device/examples/wasapi.rs
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
pub(crate) mod loom;
#[macro_use]
#[doc(hidden)]
mod macros;
cfg_unix! {
#[macro_use]
pub mod unix;
}
cfg_wasapi! {
pub mod wasapi;
}
cfg_windows! {
pub mod windows;
}
cfg_libc! {
pub mod libc;
}
cfg_alsa! {
pub mod alsa;
}
cfg_pulse! {
pub mod pulse;
}
cfg_pipewire! {
pub mod pipewire;
}
pub mod runtime;
mod error;
pub use self::error::{Error, Result};
|
use clap::Clap;
use nlprule::{rules::Rules, tokenizer::Tokenizer};
#[derive(Clap)]
#[clap(
version = "1.0",
author = "Benjamin Minixhofer <bminixhofer@gmail.com>"
)]
struct Opts {
text: String,
#[clap(long, short)]
tokenizer: String,
#[clap(long, short)]
rules: String,
}
fn main() {
env_logger::init();
let opts = Opts::parse();
let tokenizer = Tokenizer::new(opts.tokenizer).unwrap();
let rules = Rules::new(opts.rules).unwrap();
let tokens = tokenizer.pipe(&opts.text);
println!("Tokens: {:#?}", tokens);
println!("Suggestions: {:#?}", rules.suggest(&opts.text, &tokenizer));
}
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#[allow(dead_code)]
mod helpers;
use helpers::{
block_builders::chain_block,
pow_blockchain::{append_to_pow_blockchain, create_test_pow_blockchain},
};
use tari_core::{
chain_storage::{fetch_headers, BlockchainBackend},
consensus::{ConsensusManagerBuilder, Network},
helpers::create_mem_db,
proof_of_work::{get_median_timestamp, PowAlgorithm},
};
use tari_crypto::tari_utilities::epoch_time::EpochTime;
pub fn get_header_timestamps<B: BlockchainBackend>(db: &B, height: u64, timestamp_count: u64) -> Vec<EpochTime> {
let min_height = height.checked_sub(timestamp_count).unwrap_or(0);
let block_nums = (min_height..=height).collect();
fetch_headers(db, block_nums)
.unwrap()
.iter()
.map(|h| h.timestamp)
.collect::<Vec<_>>()
}
#[test]
fn test_median_timestamp_with_height() {
let network = Network::LocalNet;
let consensus_manager = ConsensusManagerBuilder::new(network).build();
let store = create_mem_db(&consensus_manager);
let pow_algos = vec![
PowAlgorithm::Blake, // GB default
PowAlgorithm::Monero,
PowAlgorithm::Blake,
PowAlgorithm::Monero,
PowAlgorithm::Blake,
];
create_test_pow_blockchain(&store, pow_algos, &consensus_manager);
let timestamp_count = 10;
let header0_timestamp = store.fetch_header(0).unwrap().timestamp;
let header1_timestamp = store.fetch_header(1).unwrap().timestamp;
let header2_timestamp = store.fetch_header(2).unwrap().timestamp;
let db = &*store.db_read_access().unwrap();
let median_timestamp =
get_median_timestamp(get_header_timestamps(db, 0, timestamp_count)).expect("median returned an error");
assert_eq!(median_timestamp, header0_timestamp);
let median_timestamp =
get_median_timestamp(get_header_timestamps(db, 3, timestamp_count)).expect("median returned an error");
assert_eq!(median_timestamp, (header1_timestamp + header2_timestamp) / 2);
let median_timestamp =
get_median_timestamp(get_header_timestamps(db, 2, timestamp_count)).expect("median returned an error");
assert_eq!(median_timestamp, header1_timestamp);
let median_timestamp =
get_median_timestamp(get_header_timestamps(db, 4, timestamp_count)).expect("median returned an error");
assert_eq!(median_timestamp, header2_timestamp);
}
#[test]
fn test_median_timestamp_odd_order() {
let network = Network::LocalNet;
let consensus_manager = ConsensusManagerBuilder::new(network).build();
let timestamp_count = consensus_manager.consensus_constants().get_median_timestamp_count() as u64;
let store = create_mem_db(&consensus_manager);
let pow_algos = vec![PowAlgorithm::Blake]; // GB default
create_test_pow_blockchain(&store, pow_algos, &consensus_manager);
let mut timestamps = vec![store.fetch_block(0).unwrap().block().header.timestamp.clone()];
let height = store.get_metadata().unwrap().height_of_longest_chain.unwrap();
let mut median_timestamp = get_median_timestamp(get_header_timestamps(
&*store.db_read_access().unwrap(),
height,
timestamp_count,
))
.expect("median returned an error");
assert_eq!(median_timestamp, timestamps[0]);
let pow_algos = vec![PowAlgorithm::Blake];
// lets add 1
let tip = store.fetch_block(store.get_height().unwrap().unwrap()).unwrap().block;
append_to_pow_blockchain(&store, tip, pow_algos.clone(), &consensus_manager);
timestamps.push(timestamps[0].increase(consensus_manager.consensus_constants().get_target_block_interval()));
let height = store.get_metadata().unwrap().height_of_longest_chain.unwrap();
median_timestamp = get_median_timestamp(get_header_timestamps(
&*store.db_read_access().unwrap(),
height,
timestamp_count,
))
.expect("median returned an error");
assert_eq!(median_timestamp, (timestamps[0] + timestamps[1]) / 2);
// lets add 1 that's further back then
let append_height = store.get_height().unwrap().unwrap();
let prev_block = store.fetch_block(append_height).unwrap().block().clone();
let new_block = chain_block(&prev_block, Vec::new(), &consensus_manager.consensus_constants());
let mut new_block = store.calculate_mmr_roots(new_block).unwrap();
timestamps.push(timestamps[0].increase(&consensus_manager.consensus_constants().get_target_block_interval() / 2));
new_block.header.timestamp = timestamps[2];
new_block.header.pow.pow_algo = PowAlgorithm::Blake;
store.add_block(new_block).unwrap();
timestamps.push(timestamps[2].increase(consensus_manager.consensus_constants().get_target_block_interval() / 2));
let height = store.get_metadata().unwrap().height_of_longest_chain.unwrap();
median_timestamp = get_median_timestamp(get_header_timestamps(
&*store.db_read_access().unwrap(),
height,
timestamp_count,
))
.expect("median returned an error");
// Median timestamp should be block 3 and not block 2
assert_eq!(median_timestamp, timestamps[2]);
}
|
use std::io::{Read};
use serde::de::{Deserialize};
use serde_json::Number;
fn number_to_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let n: Number = Deserialize::deserialize(d)?;
Ok(n.to_string())
}
#[derive(Deserialize)]
pub struct Config {
pub name: String,
pub password: String,
pub iccid: String,
}
impl Config {
pub fn open(path: &str) -> Result<Self, Box<std::error::Error>> {
let mut file = std::fs::File::open(path)?;
let mut config_data = String::new();
file.read_to_string(&mut config_data)?;
Ok(serde_json::from_str::<Self>(&config_data)?)
}
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Debug)]
pub struct Step
{
pub code: String,
speed_number: String,
// todo: show this fields in `yota status`
// speed_string: String,
// amount_number: String,
// amount_string: String,
// remain_number: String,
// remain_string: String,
}
#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Debug)]
pub struct Product {
#[serde(deserialize_with = "number_to_string")]
pub product_id: String,
pub steps: Vec<Step>,
}
impl Product {
pub fn get_step(&self, speed: &str) -> Option<&Step> {
self.steps
.iter()
.skip_while(|s| { s.speed_number != *speed })
.next()
}
}
#[derive(Deserialize, Debug)]
pub struct Devices {
#[serde(flatten)]
pub mapped: std::collections::HashMap<String, Product>
}
impl Devices {
pub fn from_str(s: &str) -> serde_json::Result<Self> {
serde_json::from_str::<Self>(s)
}
pub fn get_product(&self, product: &str) -> Option<&Product> {
self.mapped.get(product)
}
}
|
mod common;
mod matrix;
use common::get_rng;
use failure::Error;
use matrix::{Cell, Matrix};
use rand::prelude::*;
use sdl2::event::Event;
use sdl2::gfx::framerate::FPSManager;
use sdl2::gfx::primitives::DrawRenderer;
use sdl2::pixels::Color;
use std::f64;
use std::sync::{Arc, RwLock};
use std::thread;
use structopt::StructOpt;
const WHITE: Color = Color {
r: 255,
g: 255,
b: 255,
a: 255,
};
const BLACK: Color = Color {
r: 0,
g: 0,
b: 0,
a: 255,
};
#[derive(Debug, StructOpt)]
struct Opt {
dimension: Dimension,
#[structopt(short = "t", default_value = "0.01")]
initial_temperature: f64,
#[structopt(short = "c", default_value = "0.999999")]
temperature_coefficient: f64,
}
#[derive(Debug)]
struct Dimension {
width: usize,
height: usize,
}
impl std::str::FromStr for Dimension {
type Err = Error;
fn from_str(s: &str) -> Result<Dimension, Error> {
let i = s.find('x').ok_or_else(|| failure::err_msg("NoneError"))?;
let (width, height) = s.split_at(i);
let width = width.parse()?;
let height = height[1..].parse()?;
Ok(Dimension { width, height })
}
}
#[derive(Debug)]
struct State {
matrix: Matrix,
temperature: f64,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let opt = Opt::from_args();
let state = Arc::new(RwLock::new(State {
matrix: Matrix::random(opt.dimension.width, opt.dimension.height),
temperature: opt.initial_temperature,
}));
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("shakashakagen", 0, 0)
.resizable()
.build()?;
let mut canvas = window.into_canvas().build()?;
let mut event_pump = sdl_context.event_pump()?;
let mut fps_manager = FPSManager::new();
{
let state = Arc::clone(&state);
thread::spawn(move || worker(opt.temperature_coefficient, state));
}
'main_loop: loop {
canvas.set_draw_color(WHITE);
canvas.clear();
for (y, row) in state.read().unwrap().matrix.rows().enumerate() {
for (x, cell) in row.iter().enumerate() {
draw_cell(&mut canvas, cell, x, y)?;
}
}
{
let state = state.read().unwrap();
println!(
"score: {:.4} temperature: {:1.4e}",
state.matrix.score(),
state.temperature
);
}
for event in event_pump.poll_iter() {
if let Event::Quit { .. } = event {
break 'main_loop;
}
}
canvas.present();
fps_manager.delay();
}
Ok(())
}
fn draw_cell<T>(canvas: &mut T, cell: &Cell, x: usize, y: usize) -> Result<(), String>
where
T: DrawRenderer,
{
let x = x as i16;
let y = y as i16;
let cell_size = 16; // TODO adjust to fit with window size
let top = y * cell_size;
let bottom = top + cell_size;
let left = x * cell_size;
let right = left + cell_size;
match cell {
Cell::Empty => (),
Cell::Filled => canvas.box_(left, top, right, bottom, BLACK)?,
Cell::TopRight => canvas.filled_trigon(left, top, right, top, right, bottom, BLACK)?,
Cell::BottomRight => {
canvas.filled_trigon(right, top, right, bottom, left, bottom, BLACK)?
}
Cell::BottomLeft => canvas.filled_trigon(right, bottom, left, bottom, left, top, BLACK)?,
Cell::TopLeft => canvas.filled_trigon(left, bottom, left, top, right, top, BLACK)?,
}
Ok(())
}
fn worker(temperature_coefficient: f64, state: Arc<RwLock<State>>) {
let mut rng = get_rng();
loop {
let next_matrix;
let current_score;
let next_score;
let temperature;
{
let state = state.read().unwrap();
temperature = state.temperature;
current_score = state.matrix.score();
next_matrix = state.matrix.random_neighbor();
next_score = next_matrix.score();
}
{
let mut state = state.write().unwrap();
if rng.gen_range(0.0, 1.0)
< acceptance_probability(current_score, next_score, temperature)
{
state.matrix = next_matrix;
}
state.temperature *= temperature_coefficient;
}
}
}
fn acceptance_probability(current_energy: f64, next_energy: f64, temperature: f64) -> f64 {
if next_energy < current_energy {
1.0
} else {
f64::exp(-(next_energy - current_energy) / temperature)
}
}
|
//! # Rights Management Pallet
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use core::result::Result;
use frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch, ensure,
sp_std::prelude::*};
use frame_system::ensure_signed;
pub use sp_std::vec::Vec;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
// General constraints to limit data size
pub const SRC_ID_MAX_LENGTH: usize = 36;
pub const SONG_ID_MAX_LENGTH: usize = 36;
pub const SONG_NAME_MAX_LENGTH: usize = 20;
pub const ARTIST_NAME_MAX_LENGTH: usize = 20;
pub const COMPOSER_MAX_LENGTH: usize = 20;
pub const LYRICIST_MAX_LENGTH: usize = 20;
pub const YOR_MAX_LENGTH: usize = 4;
pub const SONG_MAX_PROPS: usize = 6;
pub trait Config: frame_system::Config + timestamp::Config {
type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;
}
// Custom types
pub type SrcId = Vec<u8>;
pub type SongId = Vec<u8>;
pub type SongName = Vec<u8>;
pub type AlbumTitle = Vec<u8>;
pub type ArtistName = Vec<u8>;
pub type Composer = Vec<u8>;
pub type Lyricist = Vec<u8>;
pub type YOR = Vec<u8>;
pub type Alias = Vec<u8>;
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct MusicData<AccountId, Moment> {
// music file hash
src_id: SrcId,
// This is account that represents the ownership of the music created.
owner: AccountId,
// The song ID would typically be a ISRC code (International Standard Recording Code),
// or ISWC code (International Standard Musical Work Code), or similar.
song_id: Option<SongId>,
// Timestamp (approximate) at which the music was registered on-chain.
registered: Moment,
// This is a series of properties describing the music test data.
props: Option<Vec<TestData>>,
// album: Option<Vec<Album<Moment>>>,
// track: Option<Vec<Track>>,
// artist_alias: Option<Vec<ArtistAlias>>,
// comp: Option<Vec<Comp>>,
// distributions_comp: Option<Vec<DistributionsComp>>,
// distributions_master: Option<Vec<DistributionsMaster>>,
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct TestData {
name: SongName,
artist: ArtistName,
composer: Composer,
lyricist: Lyricist,
year: YOR,
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct ArtistAlias {
artist: ArtistName,
aliases: Alias
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct Album<Moment> {
album_artist: ArtistName,
album_producer: Vec<u16>,
album_title: Vec<u16>,
album_type: Vec<u16>,
c_line: Vec<u16>,
country_of_origin: Vec<u8>,
display_label_name: Vec<u16>,
explicit_: bool,
genre_1: u32,
master_label_name: Vec<u16>,
p_line: Vec<u16>,
part_of_album: bool,
release_date: Moment,
sales_start_date: Vec<u16>,
upc_or_ean: bool
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct Track {
track_no: u32,
track_producer: Vec<u8>,
track_title: Vec<u8>,
track_volume: u32,
track_duration: Vec<u32>,
genre_1: Vec<u8>,
genre_2: Vec<u8>,
p_line: Vec<u8>,
samples: bool,
track_artists: Vec<ArtistName>,
zero: ArtistAlias,
one: ArtistAlias,
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct Comp<Moment> {
pro: Vec<u16>,
composition_title: Vec<u16>,
publishers: Vec<Vec<u16>>,
third_party_publishers: bool,
writers: Vec<Vec<u16>>,
created: Moment,
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct DistributionsMaster {
payee: ArtistName,
bp: u32,
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct DistributionsComp {
payee: Composer,
bp: u32,
}
impl TestData {
pub fn new(name: &[u8], artist: &[u8], composer: &[u8], lyricist: &[u8], year: &[u8]) -> Self {
Self {
name: name.to_vec(),
artist: artist.to_vec(),
composer: composer.to_vec(),
lyricist: lyricist.to_vec(),
year: year.to_vec(),
}
}
pub fn name(&self) -> &[u8] {
self.name.as_ref()
}
pub fn artist(&self) -> &[u8] {
self.artist.as_ref()
}
pub fn composer(&self) -> &[u8] {
self.composer.as_ref()
}
pub fn lyricist(&self) -> &[u8] {
self.lyricist.as_ref()
}
pub fn year(&self) -> &[u8] {
self.year.as_ref()
}
}
// The pallet's runtime storage items.
// https://substrate.dev/docs/en/knowledgebase/runtime/storage
decl_storage! {
trait Store for Module<T: Config> as RightsMgmtPallet {
pub MusicCollections get(fn music_by_src_id): map hasher(blake2_128_concat) SrcId => Option<MusicData<T::AccountId, T::Moment>>;
pub SrcCollections get(fn products_of_org): map hasher(blake2_128_concat) T::AccountId => Vec<SrcId>;
pub OwnerOf get(fn owner_of): map hasher(blake2_128_concat) SrcId => Option<T::AccountId>;
}
}
// Pallets use events to inform users when important changes are made.
// https://substrate.dev/docs/en/knowledgebase/runtime/events
decl_event!(
pub enum Event<T> where AccountId = <T as frame_system::Config>::AccountId {
/// Event documentation should end with an array that provides descriptive names for event
SrcCreated(AccountId, SrcId, SongId, AccountId),
}
);
// Errors inform users that something went wrong.
decl_error! {
pub enum Error for Module<T: Config> {
SrcIdMissing,
SrcIdTooLong,
SrcIdExists,
SongIdMissing,
SongIdTooLong,
SongIdExists,
SongTooManyProps,
SongInvalidSongName,
SongInvalidArtistName,
SongInvalidComposer,
SongInvalidLyricist,
SongInvalidYOR
}
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
type Error = Error<T>;
fn deposit_event() = default;
#[weight = 10_000]
pub fn register_music(origin, src_id: SrcId, song_id: SongId, owner: T::AccountId, props: Option<Vec<TestData>>) -> dispatch::DispatchResult {
let who = ensure_signed(origin)?;
// Validate music file hash
Self::validate_src_id(&src_id)?;
// Validate song ID
Self::validate_song_id(&song_id)?;
// Validate song props
Self::validate_song_props(&props)?;
// Check SRC doesn't exist yet (1 DB read)
Self::validate_new_src_id(&src_id)?;
// Create a song instance
let song = Self::new_song()
.verified_by(src_id.clone())
.identified_by(Some(song_id.clone()))
.owned_by(owner.clone())
.registered_on(<timestamp::Module<T>>::get())
.with_props(props)
.build();
<MusicCollections<T>>::insert(&src_id, song);
<SrcCollections<T>>::append(&owner, &src_id);
<OwnerOf<T>>::insert(&src_id, &owner);
Self::deposit_event(RawEvent::SrcCreated(who, src_id, song_id, owner));
Ok(())
}
}
}
impl<T: Config> Module<T> {
fn new_song() -> SongBuilder<T::AccountId, T::Moment> {
SongBuilder::<T::AccountId, T::Moment>::default()
}
pub fn validate_src_id(src_id: &[u8]) -> Result<(), Error<T>> {
// File Hash validation
ensure!(!src_id.is_empty(), Error::<T>::SrcIdMissing);
ensure!(
src_id.len() <= SRC_ID_MAX_LENGTH,
Error::<T>::SrcIdTooLong
);
Ok(())
}
pub fn validate_song_id(song_id: &[u8]) -> Result<(), Error<T>> {
// Basic song ID validation
ensure!(!song_id.is_empty(), Error::<T>::SongIdMissing);
ensure!(
song_id.len() <= SONG_ID_MAX_LENGTH,
Error::<T>::SongIdTooLong
);
Ok(())
}
pub fn validate_new_src_id(src_id: &[u8]) -> Result<(), Error<T>> {
// SRC existence check
ensure!(
!<MusicCollections<T>>::contains_key(src_id),
Error::<T>::SrcIdExists
);
Ok(())
}
pub fn validate_song_props(props: &Option<Vec<TestData>>) -> Result<(), Error<T>> {
if let Some(props) = props {
ensure!(
props.len() <= SONG_MAX_PROPS,
Error::<T>::SongTooManyProps,
);
for prop in props {
ensure!(
prop.name().len() <= SONG_NAME_MAX_LENGTH,
Error::<T>::SongInvalidSongName
);
ensure!(
prop.artist().len() <= ARTIST_NAME_MAX_LENGTH,
Error::<T>::SongInvalidArtistName
);
ensure!(
prop.composer().len() <= COMPOSER_MAX_LENGTH,
Error::<T>::SongInvalidComposer
);
ensure!(
prop.lyricist().len() <= LYRICIST_MAX_LENGTH,
Error::<T>::SongInvalidLyricist
);
ensure!(
prop.year().len() <= YOR_MAX_LENGTH,
Error::<T>::SongInvalidYOR
);
}
}
Ok(())
}
}
#[derive(Default)]
pub struct SongBuilder<AccountId, Moment>
where
AccountId: Default,
Moment: Default,
{
src_id: SrcId,
song_id: Option<SongId>,
owner: AccountId,
props: Option<Vec<TestData>>,
// album: Option<Vec<Album<Moment>>>,
// track: Option<Vec<Track>>,
registered: Moment,
}
impl<AccountId, Moment> SongBuilder<AccountId, Moment>
where
AccountId: Default,
Moment: Default,
{
pub fn verified_by(mut self, src_id: SrcId) -> Self {
self.src_id = src_id;
self
}
pub fn identified_by(mut self, song_id: Option<SongId>) -> Self {
self.song_id = song_id;
self
}
pub fn owned_by(mut self, owner: AccountId) -> Self {
self.owner = owner;
self
}
pub fn with_props(mut self, props: Option<Vec<TestData>>) -> Self {
self.props = props;
self
}
// pub fn with_album(mut self, album: Option<Vec<Album<Moment>>>) -> Self {
// self.album = album;
// self
// }
// pub fn with_track(mut self, track: Option<Vec<Track>>) -> Self {
// self.track = track;
// self
// }
pub fn registered_on(mut self, registered: Moment) -> Self {
self.registered = registered;
self
}
pub fn build(self) -> MusicData<AccountId, Moment> {
MusicData::<AccountId, Moment> {
song_id: self.song_id,
src_id: self.src_id,
owner: self.owner,
props: self.props,
// album: self.album,
// track: self.track,
registered: self.registered,
}
}
}
|
//! ```elixir
//! case Lumen.Web.HTMLFormElement.element(html_form_element, "input-name") do
//! {:ok, html_input_element} -> ...
//! :error -> ...
//! end
//! ```
use wasm_bindgen::JsCast;
use web_sys::HtmlInputElement;
use liblumen_alloc::atom;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::html_form_element;
use crate::runtime::binary_to_string::binary_to_string;
#[native_implemented::function(Elixir.Lumen.Web.HTMLFormElement:element/2)]
fn result(process: &Process, html_form_element_term: Term, name: Term) -> exception::Result<Term> {
let html_form_element_term = html_form_element::from_term(html_form_element_term)?;
let name_string: String = binary_to_string(name)?;
let object = html_form_element_term.get_with_name(&name_string).unwrap();
let result_html_input_element: Result<HtmlInputElement, _> = object.dyn_into();
let final_term = match result_html_input_element {
Ok(html_input_element) => {
let html_input_element_resource_reference = process.resource(html_input_element);
process.tuple_from_slice(&[atom!("ok"), html_input_element_resource_reference])
}
Err(_) => atom!("error"),
};
Ok(final_term)
}
|
/// Tokens from the textual representation of constraints.
use crate::ir;
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
ValueIdent(String),
ChoiceIdent(String),
Var(String),
Doc(String),
CmpOp(ir::CmpOp),
Code(String),
CounterKind(ir::CounterKind),
Bool(bool),
CounterVisibility(ir::CounterVisibility),
And,
Trigger,
When,
Alias,
Counter,
Define,
Enum,
Equal,
Forall,
In,
Is,
Not,
Require,
Requires,
Value,
End,
Symmetric,
AntiSymmetric,
Arrow,
Colon,
Comma,
LParen,
RParen,
BitOr,
Or,
SetDefKey(ir::SetDefKey),
Set,
SubsetOf,
SetIdent(String),
Base,
Disjoint,
Quotient,
Of,
Divide,
Integer,
}
|
fn sample1() {
fn a1() -> fn(i32) -> i32 {
|x| x * 2
}
println!("a1 = {}", a1()(11));
fn b1() -> impl Fn(i32) -> i32 {
|x| x * 2
}
println!("b1 = {}", b1()(12));
fn c1() -> Box<dyn Fn(i32) -> i32> {
Box::new(|x| x * 2)
}
println!("c1 = {}", c1()(13));
}
fn sample2() {
/* コンパイルエラー: closures can only be coerced to `fn` types if they do not capture any variables
fn a2(y: i32) -> fn(i32) -> i32 {
move |x| x * y
}
println!("a2 = {}", a2(2)(21));
*/
fn b2(y: i32) -> impl Fn(i32) -> i32 {
move |x| x * y
}
println!("b2 = {}", b2(2)(22));
fn c2(y: i32) -> Box<dyn Fn(i32) -> i32> {
Box::new(move |x| x * y)
}
println!("c2 = {}", c2(2)(23));
}
fn sample3() {
fn bc() -> impl Fn(i32) -> Box<dyn Fn(i32) -> i32> {
|x| Box::new(move |y| x * y)
}
println!("bc = {}", bc()(3)(32));
/* コンパイルエラー: `impl Trait` only allowed in function and inherent method return types, not in `Fn` trait return
fn bb() -> impl Fn(i32) -> impl Fn(i32) -> i32 {
|x| move |y| x * y
}
*/
fn cc() -> Box<dyn Fn(i32) -> Box<dyn Fn(i32) -> i32>> {
Box::new(|x| Box::new(move |y| x * y))
}
println!("cc = {}", cc()(3)(33));
fn ba() -> impl Fn(i32) -> fn(i32) -> i32 {
|_x||y| y
}
println!("ba = {}", ba()(3)(31));
}
fn sample4() {
fn bcc(d: i32) -> impl Fn(i32) -> Box<dyn Fn(i32) -> Box<dyn Fn(i32) -> i32>> {
move |a| Box::new(move |b| Box::new(move |c| a * b * c + d))
}
println!("bcc = {}", bcc(2)(3)(4)(5));
}
fn main() {
sample1();
sample2();
sample3();
sample4();
let c = |x: i32| move |y: i32| x * y;
println!("c = {}", c(10)(20));
}
|
use ::Access;
use na::{BaseFloat, Norm, Vector3};
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
use std::convert::Into;
/// East North Up vector
///
/// This struct represents a vector in the ENU coordinate system.
/// See: [ENU](https://en.wikipedia.org/wiki/Axes_conventions) for a general
/// description.
///
/// # Note
/// ENU implements `Into` on all operations. This means that any vector that
/// can be converted to ENU with a `From` implementation will automatically
/// be able to work with ENU at the cost of the `Into` conversion.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ENU<N>(Vector3<N>);
impl<N> ENU<N> {
/// Crate a new ENU vector
pub fn new(e: N, n: N, u: N) -> ENU<N> {
ENU(Vector3::new(e, n, u))
}
}
impl<N: Copy> ENU<N> {
/// Get the East component of this vector
pub fn east(&self) -> N {
self.0.x
}
/// Get the North component of this vector
pub fn north(&self) -> N {
self.0.y
}
/// Get the Up component of this vector
pub fn up(&self) -> N {
self.0.z
}
}
impl<N: Copy + Add<N, Output = N>, T: Into<ENU<N>>> Add<T> for ENU<N> {
type Output = ENU<N>;
fn add(self, right: T) -> Self::Output {
ENU(self.0 + right.into().0)
}
}
impl<N: Copy + AddAssign<N>, T: Into<ENU<N>>> AddAssign<T> for ENU<N> {
fn add_assign(&mut self, right: T) {
self.0 += right.into().0
}
}
impl<N: Copy + Sub<N, Output = N>, T: Into<ENU<N>>> Sub<T> for ENU<N> {
type Output = ENU<N>;
fn sub(self, right: T) -> Self::Output {
ENU(self.0 - right.into().0)
}
}
impl<N: Copy + SubAssign<N>, T: Into<ENU<N>>> SubAssign<T> for ENU<N> {
fn sub_assign(&mut self, right: T) {
self.0 -= right.into().0
}
}
impl<N: Copy + Mul<N, Output = N>> Mul<N> for ENU<N> {
type Output = ENU<N>;
fn mul(self, right: N) -> Self::Output {
ENU(self.0 * right)
}
}
impl<N: Copy + MulAssign<N>> MulAssign<N> for ENU<N> {
fn mul_assign(&mut self, right: N) {
self.0 *= right
}
}
impl<N: Copy + Div<N, Output = N>> Div<N> for ENU<N> {
type Output = ENU<N>;
fn div(self, right: N) -> Self::Output {
ENU(self.0 / right)
}
}
impl<N: Copy + DivAssign<N>> DivAssign<N> for ENU<N> {
fn div_assign(&mut self, right: N) {
self.0 /= right
}
}
impl<N: BaseFloat> Norm for ENU<N> {
type NormType = N;
fn norm_squared(&self) -> N {
self.0.norm_squared()
}
fn normalize(&self) -> Self {
ENU(self.0.normalize())
}
fn normalize_mut(&mut self) -> N {
self.0.normalize_mut()
}
fn try_normalize(&self, min_norm: Self::NormType) -> Option<Self> {
self.0.try_normalize(min_norm).map(ENU)
}
fn try_normalize_mut(&mut self, min_norm: Self::NormType) -> Option<Self::NormType> {
self.0.try_normalize_mut(min_norm)
}
}
impl<N> Access<Vector3<N>> for ENU<N> {
fn access(self) -> Vector3<N> {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use ::ned::NED;
quickcheck! {
fn create_enu(e: f32, n: f32, u: f32) -> () {
ENU::new(e, n, u);
}
fn get_components(e: f32, n: f32, u: f32) -> () {
let vec = ENU::new(e, n, u);
assert_eq!(vec.east(), e);
assert_eq!(vec.north(), n);
assert_eq!(vec.up(), u);
}
fn from_ned(n: f32, e: f32, d: f32) -> () {
let ned = NED::new(n, e, d);
let enu = ENU::from(ned);
assert_eq!(enu.east(), e);
assert_eq!(enu.north(), n);
assert_eq!(enu.up(), -d);
}
}
}
|
pub mod data;
use std::collections::{BTreeMap, HashMap, HashSet, LinkedList};
// TODO: try doing recursively
//
fn path(node: &str, target: &str, children: &HashMap<String, Vec<String>>) -> Option<LinkedList<String>> {
if node == target {
let mut l = LinkedList::new();
l.push_back(target.to_string());
return Some(l)
}
for child in children.get(node).unwrap_or(&Vec::new()) {
if let Some(mut l) = path(child, target, children) {
l.push_back(node.to_string());
return Some(l)
}
}
None
}
fn path_length(a: &LinkedList<String>, b: &LinkedList<String>) -> usize {
let prefix_length =
a.iter().rev()
.zip(b.iter().rev())
.take_while(|(a,b)|a == b)
.count();
a.len() + b.len() - 2 * prefix_length - 2
}
fn main() {
let mut orbits = {
let mut v = data::data();
v.sort_unstable();
let mut os: HashMap<String, Vec<String>> = HashMap::new();
let mut values = Vec::new();
let mut key = v[0].base.clone();
for orbit in &v {
if orbit.base != key {
let mut tmp = Vec::new();
std::mem::swap(&mut values, &mut tmp);
os.insert(key, tmp);
key = orbit.base.clone();
}
values.push(orbit.orbiter.clone())
}
os.insert(key, values);
os
};
match std::env::args().nth(1).as_deref() {
Some("A") | Some("a") => {
let mut sum = 0;
let mut working_set = {
let mut ws = BTreeMap::new();
let mut root_set = HashSet::new();
root_set.insert("COM".to_string());
ws.insert(1, root_set);
ws
};
while let Some(item) = working_set.iter().next() {
let depth = *item.0;
let bases = working_set.remove(&depth).unwrap();
for base in bases {
if let Some(orbiters) = orbits.remove(&base) {
sum += depth * orbiters.len();
working_set.entry(depth+1).or_default().extend(orbiters.into_iter());
}
}
}
println!("(A) Total orbits = {}", sum);
},
Some("B") | Some("b") => {
if let Some(p) = path("COM", "SAN", &orbits) {
if let Some(q) = path("COM", "YOU", &orbits) {
println!("(B) Minimum orbit transfers = {}", path_length(&p, &q));
}
}
},
Some(_) | None => {
eprint!("Invalid input: provide A or B");
}
};
}
|
use amethyst::input::BindingTypes;
#[derive(Debug, PartialEq, Eq, Hash, Default)]
pub struct IngameBindings;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum IngameAxisBinding {
None,
PlayerX,
PlayerY,
PlayerAltX,
PlayerAltY,
}
impl Default for IngameAxisBinding {
fn default() -> Self {
IngameAxisBinding::None
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum IngameActionBinding {
None,
Quit,
PlayerJump,
PlayerRun,
TogglePause,
ToMainMenu,
}
impl Default for IngameActionBinding {
fn default() -> Self {
IngameActionBinding::None
}
}
impl BindingTypes for IngameBindings {
type Axis = IngameAxisBinding;
type Action = IngameActionBinding;
}
|
//!
//! ms.rs
//!
//! Created by Mitchell Nordine at 08:22PM on November 02, 2014.
//!
//!
use num::{FromPrimitive, ToPrimitive};
use std::ops::{Add, Sub, Mul, Div, Rem, Neg,
AddAssign, SubAssign, MulAssign, DivAssign, RemAssign};
use super::calc;
use super::{
Bars,
Beats,
Bpm,
Ppqn,
SampleHz,
Samples,
Ticks,
TimeSig,
samples_from_ms,
ticks_from_ms,
};
/// Time representation in the form of Milliseconds.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Ms(pub calc::Ms);
impl Ms {
/// Return the unit value of Ms.
#[inline]
pub fn ms(&self) -> calc::Ms { let Ms(ms) = *self; ms }
/// Convert to the equivalent duration in Bars.
#[inline]
pub fn bars(&self, bpm: Bpm, ts: TimeSig) -> f64 {
self.ms() as f64 / Bars(1).ms(bpm, ts) as f64
}
/// Convert to the equivalent duration in Beats.
#[inline]
pub fn beats(&self, bpm: Bpm) -> f64 {
self.ms() as f64 / Beats(1).ms(bpm) as f64
}
/// Convert to unit value of `Samples`.
#[inline]
pub fn samples(&self, sample_hz: SampleHz) -> calc::Samples {
samples_from_ms(self.ms(), sample_hz)
}
/// Convert to `Samples`.
#[inline]
pub fn to_samples(&self, sample_hz: SampleHz) -> Samples {
Samples(self.samples(sample_hz))
}
/// Convert to unit value of `Ticks`.
#[inline]
pub fn ticks(&self, bpm: Bpm, ppqn: Ppqn) -> calc::Ticks {
ticks_from_ms(self.ms(), bpm, ppqn)
}
/// Convert to `Ticks`.
#[inline]
pub fn to_ticks(&self, bpm: Bpm, ppqn: Ppqn) -> Ticks {
Ticks(self.ticks(bpm, ppqn))
}
}
impl From<calc::Ms> for Ms {
#[inline]
fn from(ms: calc::Ms) -> Self {
Ms(ms)
}
}
impl Add for Ms {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
Self(self.ms() + rhs.ms())
}
}
impl Sub for Ms {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self {
Self(self.ms() - rhs.ms())
}
}
impl Mul for Ms {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self {
Self(self.ms() * rhs.ms())
}
}
impl Div for Ms {
type Output = Self;
#[inline]
fn div(self, rhs: Self) -> Self {
Self(self.ms() / rhs.ms())
}
}
impl Rem for Ms {
type Output = Self;
#[inline]
fn rem(self, rhs: Self) -> Self {
Self(self.ms() % rhs.ms())
}
}
impl Neg for Ms {
type Output = Self;
#[inline]
fn neg(self) -> Self {
Self(-self.ms())
}
}
impl AddAssign for Ms {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs;
}
}
impl SubAssign for Ms {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs;
}
}
impl MulAssign for Ms {
fn mul_assign(&mut self, rhs: Self) {
*self = *self * rhs;
}
}
impl DivAssign for Ms {
fn div_assign(&mut self, rhs: Self) {
*self = *self / rhs;
}
}
impl RemAssign for Ms {
fn rem_assign(&mut self, rhs: Self) {
*self = *self % rhs;
}
}
impl ToPrimitive for Ms {
fn to_u64(&self) -> Option<u64> {
self.ms().to_u64()
}
fn to_i64(&self) -> Option<i64> {
self.ms().to_i64()
}
}
impl FromPrimitive for Ms {
fn from_u64(n: u64) -> Option<Ms> {
Some(Ms(n as calc::Ms))
}
fn from_i64(n: i64) -> Option<Ms> {
Some(Ms(n as calc::Ms))
}
}
|
use {
core::fmt,
log::{self, Level, LevelFilter, Log, Metadata, Record},
};
pub fn init(level: &str) {
static LOGGER: SimpleLogger = SimpleLogger;
log::set_logger(&LOGGER).unwrap();
log::set_max_level(match level {
"error" => LevelFilter::Error,
"warn" => LevelFilter::Warn,
"info" => LevelFilter::Info,
"debug" => LevelFilter::Debug,
"trace" => LevelFilter::Trace,
_ => LevelFilter::Off,
});
}
#[macro_export]
macro_rules! print {
($($arg:tt)*) => ({
$crate::logging::print(format_args!($($arg)*));
});
}
#[macro_export]
macro_rules! println {
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
/// Add escape sequence to print with color in Linux console
macro_rules! with_color {
($args: ident, $color_code: ident) => {{
format_args!("\u{1B}[{}m{}\u{1B}[0m", $color_code as u8, $args)
}};
}
fn print_in_color(args: fmt::Arguments, color_code: u8) {
kernel_hal_bare::arch::putfmt(with_color!(args, color_code));
}
#[allow(dead_code)]
pub fn print(args: fmt::Arguments) {
kernel_hal_bare::arch::putfmt(args);
}
struct SimpleLogger;
impl Log for SimpleLogger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
if !self.enabled(record.metadata()) {
return;
}
let (tid, pid) = kernel_hal_bare::Thread::get_tid();
print_in_color(
format_args!(
"[{:?} {:>5} {} {}:{}] {}\n",
kernel_hal_bare::timer_now(),
record.level(),
kernel_hal_bare::apic_local_id(),
pid,
tid,
record.args()
),
level_to_color_code(record.level()),
);
}
fn flush(&self) {}
}
fn level_to_color_code(level: Level) -> u8 {
match level {
Level::Error => 31, // Red
Level::Warn => 93, // BrightYellow
Level::Info => 34, // Blue
Level::Debug => 32, // Green
Level::Trace => 90, // BrightBlack
}
}
|
//! # kdtree-na
//!
//! K-dimensional tree for Rust (bucket point-region implementation)
//!
//! ## Usage
//!
//! ```
//! extern crate nalgebra;
//!
//! use nalgebra::{vector, Vector2};
//! use kdtree_na::{norm::EuclideanNormSquared, KdTree};
//!
//! let a: (Vector2<f64>, usize) = (vector![0f64, 0f64], 0);
//! let b: (Vector2<f64>, usize) = (vector![1f64, 1f64], 1);
//! let c: (Vector2<f64>, usize) = (vector![2f64, 2f64], 2);
//! let d: (Vector2<f64>, usize) = (vector![3f64, 3f64], 3);
//!
//! let mut kdtree = KdTree::new_static();
//!
//! kdtree.add(&a.0, a.1).unwrap();
//! kdtree.add(&b.0, b.1).unwrap();
//! kdtree.add(&c.0, c.1).unwrap();
//! kdtree.add(&d.0, d.1).unwrap();
//!
//! assert_eq!(kdtree.size(), 4);
//! assert_eq!(
//! kdtree.nearest(&a.0, 0, &EuclideanNormSquared).unwrap(),
//! vec![]
//! );
//! assert_eq!(
//! kdtree.nearest(&a.0, 1, &EuclideanNormSquared).unwrap(),
//! vec![(0f64, &0)]
//! );
//! assert_eq!(
//! kdtree.nearest(&a.0, 2, &EuclideanNormSquared).unwrap(),
//! vec![(0f64, &0), (2f64, &1)]
//! );
//! assert_eq!(
//! kdtree.nearest(&a.0, 3, &EuclideanNormSquared).unwrap(),
//! vec![(0f64, &0), (2f64, &1), (8f64, &2)]
//! );
//! assert_eq!(
//! kdtree.nearest(&a.0, 4, &EuclideanNormSquared).unwrap(),
//! vec![(0f64, &0), (2f64, &1), (8f64, &2), (18f64, &3)]
//! );
//! assert_eq!(
//! kdtree.nearest(&a.0, 5, &EuclideanNormSquared).unwrap(),
//! vec![(0f64, &0), (2f64, &1), (8f64, &2), (18f64, &3)]
//! );
//! assert_eq!(
//! kdtree.nearest(&b.0, 4, &EuclideanNormSquared).unwrap(),
//! vec![(0f64, &1), (2f64, &0), (2f64, &2), (8f64, &3)]
//! );
//! ```
extern crate nalgebra;
extern crate num_traits;
#[cfg(feature = "serialize")]
extern crate serde;
mod heap_element;
pub mod kdtree;
pub mod norm;
mod util;
pub use crate::kdtree::ErrorKind;
pub use crate::kdtree::KdTree;
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_expression::types::number::*;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::types::StringType;
use common_expression::BlockEntry;
use common_expression::Column;
use common_expression::DataBlock;
use common_expression::FromData;
use common_expression::Value;
use goldenfile::Mint;
use crate::common::*;
#[test]
pub fn test_pass() {
let mut mint = Mint::new("tests/it/testdata");
let mut file = mint.new_goldenfile("kernel-pass.txt").unwrap();
run_filter(
&mut file,
vec![true, false, false, false, true],
&new_block(&[
Int32Type::from_data(vec![0i32, 1, 2, 3, -4]),
UInt8Type::from_data_with_validity(vec![10u8, 11, 12, 13, 14], vec![
false, true, false, false, false,
]),
Column::Null { len: 5 },
StringType::from_data_with_validity(vec!["x", "y", "z", "a", "b"], vec![
false, true, true, false, false,
]),
]),
);
run_concat(&mut file, &[
new_block(&[
Int32Type::from_data(vec![0i32, 1, 2, 3, -4]),
UInt8Type::from_data_with_validity(vec![10u8, 11, 12, 13, 14], vec![
false, true, false, false, false,
]),
Column::Null { len: 5 },
Column::EmptyArray { len: 5 },
StringType::from_data_with_validity(vec!["x", "y", "z", "a", "b"], vec![
false, true, true, false, false,
]),
]),
new_block(&[
Int32Type::from_data(vec![5i32, 6]),
UInt8Type::from_data_with_validity(vec![15u8, 16], vec![false, true]),
Column::Null { len: 2 },
Column::EmptyArray { len: 2 },
StringType::from_data_with_validity(vec!["x", "y"], vec![false, true]),
]),
]);
run_take(
&mut file,
&[0, 3, 1],
&new_block(&[
Int32Type::from_data(vec![0i32, 1, 2, 3, -4]),
UInt8Type::from_data_with_validity(vec![10u8, 11, 12, 13, 14], vec![
false, true, false, false, false,
]),
Column::Null { len: 5 },
StringType::from_data_with_validity(vec!["x", "y", "z", "a", "b"], vec![
false, true, true, false, false,
]),
]),
);
{
let mut blocks = Vec::with_capacity(3);
let indices = vec![
(0, 0, 1),
(1, 0, 1),
(2, 0, 1),
(0, 1, 1),
(1, 1, 1),
(2, 1, 1),
(0, 2, 1),
(1, 2, 1),
(2, 2, 1),
(0, 3, 1),
(1, 3, 1),
(2, 3, 1),
// repeat 3
(0, 0, 3),
];
for i in 0..3 {
let mut columns = Vec::with_capacity(3);
columns.push(BlockEntry {
data_type: DataType::Number(NumberDataType::UInt8),
value: Value::Column(UInt8Type::from_data(vec![(i + 10) as u8; 4])),
});
columns.push(BlockEntry {
data_type: DataType::Nullable(Box::new(DataType::Number(NumberDataType::UInt8))),
value: Value::Column(UInt8Type::from_data_with_validity(
vec![(i + 10) as u8; 4],
vec![true, true, false, false],
)),
});
blocks.push(DataBlock::new(columns, 4))
}
run_take_block(&mut file, &indices, &blocks);
}
{
let mut blocks = Vec::with_capacity(3);
let indices = vec![
(0, 0, 2),
(1, 0, 3),
(2, 0, 1),
(2, 1, 1),
(0, 2, 1),
(2, 2, 1),
(0, 3, 1),
(2, 3, 1),
];
for i in 0..3 {
let mut columns = Vec::with_capacity(3);
columns.push(BlockEntry {
data_type: DataType::Number(NumberDataType::UInt8),
value: Value::Column(UInt8Type::from_data(vec![(i + 10) as u8; 4])),
});
columns.push(BlockEntry {
data_type: DataType::Nullable(Box::new(DataType::Number(NumberDataType::UInt8))),
value: Value::Column(UInt8Type::from_data_with_validity(
vec![(i + 10) as u8; 4],
vec![true, true, false, false],
)),
});
blocks.push(DataBlock::new(columns, 4))
}
run_take_block_by_slices_with_limit(&mut file, &indices, &blocks, None);
run_take_block_by_slices_with_limit(&mut file, &indices, &blocks, Some(4));
}
run_take_by_slice_limit(
&mut file,
&new_block(&[
Int32Type::from_data(vec![0i32, 1, 2, 3, -4]),
UInt8Type::from_data_with_validity(vec![10u8, 11, 12, 13, 14], vec![
false, true, false, false, false,
]),
Column::Null { len: 5 },
StringType::from_data_with_validity(vec!["x", "y", "z", "a", "b"], vec![
false, true, true, false, false,
]),
]),
(2, 3),
None,
);
run_take_by_slice_limit(
&mut file,
&new_block(&[
Int32Type::from_data(vec![0i32, 1, 2, 3, -4]),
UInt8Type::from_data_with_validity(vec![10u8, 11, 12, 13, 14], vec![
false, true, false, false, false,
]),
Column::Null { len: 5 },
StringType::from_data_with_validity(vec!["x", "y", "z", "a", "b"], vec![
false, true, true, false, false,
]),
]),
(2, 3),
Some(2),
);
run_scatter(
&mut file,
&new_block(&[
Int32Type::from_data(vec![0i32, 1, 2, 3, -4]),
UInt8Type::from_data_with_validity(vec![10u8, 11, 12, 13, 14], vec![
false, true, false, false, false,
]),
Column::Null { len: 5 },
StringType::from_data_with_validity(vec!["x", "y", "z", "a", "b"], vec![
false, true, true, false, false,
]),
]),
&[0, 0, 1, 2, 1],
3,
);
}
|
mod websocket;
use lazy_static::lazy_static;
use parking_lot::RwLock;
use rayon::{ThreadPool, ThreadPoolBuilder};
use serde::Serialize;
use std::sync::{
atomic::{AtomicBool, AtomicU32, Ordering},
Arc, Weak,
};
use crate::dprintln;
use self::websocket::{TransactionMessage, TransactionServer};
lazy_static! {
static ref TRANSACTIONS: Transactions = Transactions::init();
static ref TRANSACTIONS_SLAVE: ThreadPool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
}
pub struct Transactions {
inner: RwLock<Vec<TransactionRef>>,
id: AtomicU32,
websocket: Option<TransactionServer>,
}
impl std::ops::Deref for Transactions {
type Target = RwLock<Vec<TransactionRef>>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl Transactions {
fn init() -> Transactions {
Transactions {
inner: RwLock::new(Vec::new()),
id: AtomicU32::new(0),
websocket: TransactionServer::init().ok(),
}
}
pub fn find(&self, transaction_id: u32) -> Option<Transaction> {
let transactions = self.inner.read();
if let Ok(pos) = transactions.binary_search_by_key(&transaction_id, |transaction| transaction.id) {
let transaction = transactions.get(pos).unwrap().upgrade();
if transaction.is_some() {
return transaction;
} else {
#[cfg(debug_assertions)]
panic!("Stale transaction found in transactions list");
}
}
None
}
}
pub struct TransactionRef {
pub id: u32,
ptr: Weak<TransactionInner>,
}
impl std::ops::Deref for TransactionRef {
type Target = Weak<TransactionInner>;
fn deref(&self) -> &Self::Target {
&self.ptr
}
}
impl PartialOrd for TransactionRef {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.id.partial_cmp(&other.id)
}
}
impl Ord for TransactionRef {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.id.cmp(&other.id)
}
}
impl PartialEq for TransactionRef {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for TransactionRef {}
#[inline(always)]
fn progress_as_int(progress: f64) -> u16 {
u16::min((progress * 10000.) as u16, 10000)
}
pub type Transaction = Arc<TransactionInner>;
#[derive(Debug)]
pub struct TransactionInner {
pub id: u32,
aborted: AtomicBool,
}
impl TransactionInner {
fn emit(&self, message: TransactionMessage) {
if let Some(ref websocket) = TRANSACTIONS.websocket {
websocket.send(message);
} else {
TransactionServer::send_tauri_event(message);
}
}
fn abort(&self) {
self.aborted.store(true, Ordering::Release);
let id = self.id;
TRANSACTIONS_SLAVE.spawn(move || {
let mut transactions = TRANSACTIONS.write();
if let Ok(pos) = transactions.binary_search_by_key(&id, |transaction| transaction.id) {
transactions.remove(pos);
}
});
}
pub fn data<D: Serialize + Send + 'static>(&self, data: D) {
self.emit(TransactionMessage::Data(self.id, json!(data)));
}
pub fn status<S: Into<String>>(&self, status: S) {
self.emit(TransactionMessage::Status(self.id, status.into()))
}
pub fn progress(&self, progress: f64) {
if self.aborted() {
dprintln!("Tried to progress an aborted transaction!");
} else {
self.emit(TransactionMessage::Progress(self.id, progress_as_int(progress)));
}
}
pub fn progress_incr(&self, progress: f64) {
if self.aborted() {
dprintln!("Tried to progress an aborted transaction!");
} else {
self.emit(TransactionMessage::IncrProgress(self.id, progress_as_int(progress)));
}
}
pub fn error<S: Into<String>, D: Serialize + Send + 'static>(&self, msg: S, data: D) {
self.abort();
self.emit(TransactionMessage::Error(self.id, msg.into(), json!(data)));
}
pub fn finished<D: Serialize + Send + 'static>(&self, data: D) {
debug_assert!(!self.aborted(), "Tried to finish an aborted transaction!");
self.abort();
self.emit(TransactionMessage::Finished(self.id, json!(data)));
}
pub fn cancel(&self) {
self.abort();
}
pub fn aborted(&self) -> bool {
self.aborted.load(Ordering::Acquire)
}
}
impl Drop for TransactionInner {
fn drop(&mut self) {
if !self.aborted() {
self.error("ERR_UNKNOWN", turbonone!());
self.abort();
#[cfg(debug_assertions)]
println!("{:#?}", backtrace::Backtrace::new());
}
}
}
impl serde::Serialize for TransactionInner {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u64(self.id as u64)
}
}
pub fn init() {
lazy_static::initialize(&TRANSACTIONS);
}
pub fn new() -> Transaction {
let transaction = Arc::new(TransactionInner {
id: TRANSACTIONS.id.fetch_add(1, Ordering::SeqCst),
aborted: AtomicBool::new(false),
});
{
let mut transactions = TRANSACTIONS.write();
transactions.push(TransactionRef {
id: transaction.id,
ptr: Arc::downgrade(&transaction),
});
transactions.reserve(1);
}
transaction
}
#[macro_export]
macro_rules! transaction {
() => {
crate::transactions::new()
};
}
#[tauri::command]
fn cancel_transaction(id: u32) {
if let Some(transaction) = TRANSACTIONS.find(id) {
transaction.cancel();
}
}
#[tauri::command]
fn websocket() -> Option<u16> {
TRANSACTIONS.websocket.as_ref().map(|socket| socket.port)
}
|
use crate::*;
use crate::{
composite_collections::{SmallCompositeVec as CompositeVec, SmallStartLen as StartLen},
impl_interfacetype::impl_interfacetype_tokenizer,
lifetimes::LifetimeIndex,
literals_constructors::{rslice_tokenizer, rstr_tokenizer},
};
use as_derive_utils::{
datastructure::{DataStructure, DataVariant},
gen_params_in::{GenParamsIn, InWhat},
return_spanned_err, return_syn_err, to_stream,
to_token_fn::ToTokenFnMut,
};
use syn::Ident;
use proc_macro2::{Span, TokenStream as TokenStream2};
use core_extensions::{IteratorExt, SelfOps};
#[doc(hidden)]
pub mod reflection;
mod attribute_parsing;
mod common_tokens;
mod generic_params;
mod nonexhaustive;
mod prefix_types;
mod repr_attrs;
mod tl_function;
mod tl_field;
mod tl_multi_tl;
mod shared_vars;
#[cfg(test)]
mod tests;
use self::{
attribute_parsing::{
parse_attrs_for_stable_abi, ASTypeParamBound, ConstIdents, LayoutConstructor,
StabilityKind, StableAbiOptions,
},
common_tokens::CommonTokens,
nonexhaustive::{tokenize_enum_info, tokenize_nonexhaustive_items},
prefix_types::{prefix_type_tokenizer, PrefixTypeTokens},
reflection::ModReflMode,
shared_vars::SharedVars,
tl_field::CompTLField,
tl_function::{CompTLFunction, VisitedFieldMap},
tl_multi_tl::TypeLayoutRange,
};
pub(crate) fn derive(mut data: DeriveInput) -> Result<TokenStream2, syn::Error> {
data.generics.make_where_clause();
// println!("\nderiving for {}",data.ident);
let arenas = Arenas::default();
let arenas = &arenas;
let ctokens = CommonTokens::new(arenas);
let ctokens = &ctokens;
let ds = &DataStructure::new(&data);
let config = &parse_attrs_for_stable_abi(ds.attrs, ds, arenas)?;
let shared_vars = &mut SharedVars::new(arenas, &config.const_idents, ctokens);
let generics = ds.generics;
let name = ds.name;
let doc_hidden_attr = config.doc_hidden_attr;
// This has to come before the `VisitedFieldMap`.
let generic_params_tokens =
generic_params::GenericParams::new(ds, shared_vars, config, ctokens);
if generics.lifetimes().count() > LifetimeIndex::MAX_LIFETIME_PARAM + 1 {
return_syn_err!(
Span::call_site(),
"Cannot have more than {} lifetime parameter.",
LifetimeIndex::MAX_LIFETIME_PARAM + 1
);
}
let visited_fields = &VisitedFieldMap::new(ds, config, shared_vars, ctokens);
shared_vars.extract_errs()?;
let mono_type_layout = &Ident::new(&format!("_MONO_LAYOUT_{}", name), Span::call_site());
let (_, _, where_clause) = generics.split_for_impl();
let where_clause = (&where_clause.expect("BUG").predicates).into_iter();
let where_clause_b = where_clause.clone();
let ty_generics = GenParamsIn::new(generics, InWhat::ItemUse);
let impld_stable_abi_trait = match &config.kind {
StabilityKind::Value {
impl_prefix_stable_abi: false,
}
| StabilityKind::NonExhaustive { .. } => Ident::new("StableAbi", Span::call_site()),
StabilityKind::Value {
impl_prefix_stable_abi: true,
}
| StabilityKind::Prefix { .. } => Ident::new("PrefixStableAbi", Span::call_site()),
};
// The type that implements StableAbi
let impl_ty = match &config.kind {
StabilityKind::Value { .. } => quote!(#name <#ty_generics> ),
StabilityKind::Prefix(prefix) => {
let n = &prefix.prefix_fields_struct;
quote!(#n <#ty_generics> )
}
StabilityKind::NonExhaustive(nonexhaustive) => {
let marker = nonexhaustive.nonexhaustive_marker;
quote!(#marker < #name <#ty_generics> , __Storage > )
}
};
let mut prefix_type_trait_bound = None;
let mut prefix_bounds: &[_] = &[];
// The type whose size and alignment that is stored in the type layout.
let size_align_for = match &config.kind {
StabilityKind::NonExhaustive(_) => {
quote!(__Storage)
}
StabilityKind::Prefix(prefix) => {
let prefix_fields_struct = prefix.prefix_fields_struct;
prefix_type_trait_bound = Some(quote!(
#name <#ty_generics>:__sabi_re::PrefixTypeTrait,
));
prefix_bounds = &prefix.prefix_bounds;
quote!( #prefix_fields_struct <#ty_generics> )
}
StabilityKind::Value { .. } => quote!(Self),
};
let repr = config.repr;
let is_transparent = config.repr.is_repr_transparent();
let is_enum = ds.data_variant == DataVariant::Enum;
let prefix = match &config.kind {
StabilityKind::Prefix(prefix) => Some(prefix),
_ => None,
};
let nonexh_opt = match &config.kind {
StabilityKind::NonExhaustive(nonexhaustive) => Some(nonexhaustive),
_ => None,
};
let tags_const;
let tags_arg;
// tokenizes the `Tag` data structure associated with this type.
match &config.tags {
Some(tag) => {
tags_const = quote!( const __SABI_TAG: &'static __sabi_re::Tag = &#tag; );
tags_arg = quote!(Some(Self::__SABI_TAG));
}
None => {
tags_const = TokenStream2::new();
tags_arg = quote!(None);
}
}
let extra_checks_const;
let extra_checks_arg;
match &config.extra_checks {
Some(extra_checks) => {
extra_checks_const = quote!(
const __SABI_EXTRA_CHECKS:
&'static ::std::mem::ManuallyDrop<__sabi_re::StoredExtraChecks>
=
&std::mem::ManuallyDrop::new(
__sabi_re::StoredExtraChecks::from_const(
&#extra_checks,
__sabi_re::TD_Opaque,
)
);
);
extra_checks_arg = quote!(Some(Self::__SABI_EXTRA_CHECKS));
}
None => {
extra_checks_const = TokenStream2::new();
extra_checks_arg = quote!(None);
}
};
let variant_names_start_len = if is_enum {
let mut variant_names = String::new();
for variant in &ds.variants {
use std::fmt::Write;
let _ = write!(variant_names, "{};", variant.name);
}
shared_vars.push_str(&variant_names, None)
} else {
StartLen::EMPTY
};
// tokenizes the items for nonexhaustive enums outside of the module this generates.
let nonexhaustive_items = tokenize_nonexhaustive_items(ds, config, ctokens);
// tokenizes the items for nonexhaustive enums inside of the module this generates.
let nonexhaustive_tokens = tokenize_enum_info(ds, variant_names_start_len, config, ctokens)?;
let is_nonzero = if is_transparent && !visited_fields.map.is_empty() {
let visited_field = &visited_fields.map[0];
let is_opaque_field = visited_field.layout_ctor.is_opaque();
if visited_field.comp_field.is_function() {
quote!(__sabi_re::True)
} else if is_opaque_field {
quote!(__sabi_re::False)
} else {
let ty = visited_field.comp_field.type_(shared_vars);
quote!( <#ty as __StableAbi>::IsNonZeroType )
}
} else {
quote!(__sabi_re::False)
};
let ct = ctokens;
// The tokens for the MonoTLData stored in the TypeLayout
let mono_tl_data;
// The tokens for the GenericTLData stored in the TypeLayout
let generic_tl_data;
match (is_enum, prefix) {
(false, None) => {
mono_tl_data = {
let fields = fields_tokenizer(ds, visited_fields, ct);
match ds.data_variant {
DataVariant::Struct => quote!( __sabi_re::MonoTLData::derive_struct(#fields) ),
DataVariant::Union => quote!( __sabi_re::MonoTLData::derive_union(#fields) ),
DataVariant::Enum => unreachable!(),
}
};
generic_tl_data = {
match ds.data_variant {
DataVariant::Struct => quote!(__sabi_re::GenericTLData::Struct),
DataVariant::Union => quote!(__sabi_re::GenericTLData::Union),
DataVariant::Enum => unreachable!(),
}
};
}
(true, None) => {
let vn_sl = variant_names_start_len;
mono_tl_data = {
let mono_enum_tokenizer =
tokenize_mono_enum(ds, vn_sl, nonexh_opt, config, visited_fields, shared_vars);
quote!( __sabi_re::MonoTLData::Enum(#mono_enum_tokenizer) )
};
generic_tl_data = {
let generic_enum_tokenizer =
tokenize_generic_enum(ds, vn_sl, nonexh_opt, config, visited_fields, ct);
quote!( __sabi_re::GenericTLData::Enum(#generic_enum_tokenizer) )
};
}
(false, Some(prefix)) => {
if is_transparent {
return_spanned_err!(name, "repr(transparent) prefix types not supported")
}
mono_tl_data = {
let first_suffix_field = prefix.first_suffix_field.field_pos;
let fields = fields_tokenizer(ds, visited_fields, ct);
let prefix_field_conditionality_mask = prefix.prefix_field_conditionality_mask;
quote!(
__sabi_re::MonoTLData::prefix_type_derive(
#first_suffix_field,
#prefix_field_conditionality_mask,
#fields
)
)
};
generic_tl_data = {
quote!(
__sabi_re::GenericTLData::prefix_type_derive(
<#name <#ty_generics> as
__sabi_re::PrefixTypeTrait
>::PT_FIELD_ACCESSIBILITY,
)
)
};
}
(true, Some(_)) => {
return_spanned_err!(name, "enum prefix types not supported");
}
};
let lifetimes = &generics
.lifetimes()
.map(|x| &x.lifetime)
.collect::<Vec<_>>();
let type_params = &generics.type_params().map(|x| &x.ident).collect::<Vec<_>>();
let const_params = &generics
.const_params()
.map(|x| &x.ident)
.collect::<Vec<_>>();
// For `type StaticEquivalent= ... ;`
let lifetimes_s = lifetimes.iter().map(|_| &ctokens.static_lt);
let type_params_s = ToTokenFnMut::new(|ts| {
let ct = ctokens;
for (ty_param, bounds) in config.type_param_bounds.iter() {
match bounds {
ASTypeParamBound::NoBound => {
ct.empty_tuple.to_tokens(ts);
}
ASTypeParamBound::GetStaticEquivalent | ASTypeParamBound::StableAbi => {
to_stream!(ts; ct.static_equivalent, ct.lt, ty_param, ct.gt);
}
}
ct.comma.to_tokens(ts);
}
});
let const_params_s = &const_params;
// The name of the struct this generates,
// to use as the `GetStaticEquivalent_::StaticEquivalent` associated type.
let static_struct_name = Ident::new(&format!("_static_{}", name), Span::call_site());
let item_info_const = Ident::new(&format!("_item_info_const_{}", name), Span::call_site());
let static_struct_decl = {
let const_param_name = generics.const_params().map(|c| &c.ident);
let const_param_type = generics.const_params().map(|c| &c.ty);
let lifetimes_a = lifetimes;
let type_params_a = type_params;
quote! {
#doc_hidden_attr
pub struct #static_struct_name<
#(#lifetimes_a,)*
#(#type_params_a:?Sized,)*
#(const #const_param_name:#const_param_type,)*
>(
#(& #lifetimes_a (),)*
extern "C" fn(#(&#type_params_a,)*)
);
}
};
// if the `#[sabi(impl_InterfaceType())]` attribute was used:
// tokenizes the implementation of `InterfaceType` for `#name #ty_params`
let interfacetype_tokenizer =
impl_interfacetype_tokenizer(ds.name, ds.generics, config.impl_interfacetype.as_ref());
let stringified_name = rstr_tokenizer(name.to_string());
let mut stable_abi_bounded = Vec::new();
let mut static_equiv_bounded = Vec::new();
for (ident, bounds) in config.type_param_bounds.iter() {
let list = match bounds {
ASTypeParamBound::NoBound => None,
ASTypeParamBound::GetStaticEquivalent => Some(&mut static_equiv_bounded),
ASTypeParamBound::StableAbi => Some(&mut stable_abi_bounded),
};
if let Some(list) = list {
list.push(ident);
}
}
let stable_abi_bounded = &stable_abi_bounded;
let static_equiv_bounded = &static_equiv_bounded;
let extra_bounds = &config.extra_bounds;
let PrefixTypeTokens {
prefixref_types,
prefixref_impls,
} = prefix_type_tokenizer(mono_type_layout, ds, config, ctokens)?;
let mod_refl_mode = match config.mod_refl_mode {
ModReflMode::Module => quote!(__ModReflMode::Module),
ModReflMode::Opaque => quote!(__ModReflMode::Opaque),
ModReflMode::DelegateDeref(field_index) => {
quote!(
__ModReflMode::DelegateDeref{
phantom_field_index:#field_index
}
)
}
};
let phantom_field_tys = config.phantom_fields.iter().map(|x| x.1);
// This has to be collected into a Vec ahead of time,
// so that the names and types are stored in SharedVars.
let phantom_fields = config
.phantom_fields
.iter()
.map(|(name, ty)| {
CompTLField::from_expanded_std_field(
name,
std::iter::empty(),
shared_vars.push_type(LayoutConstructor::Regular, ty),
shared_vars,
)
})
.collect::<Vec<CompTLField>>();
let phantom_fields = rslice_tokenizer(&phantom_fields);
// The storage type parameter that is added if this is a nonexhaustive enum.
let storage_opt = nonexh_opt.map(|_| &ctokens.und_storage);
let generics_header =
GenParamsIn::with_after_types(ds.generics, InWhat::ImplHeader, storage_opt);
shared_vars.extract_errs()?;
let mono_shared_vars_tokenizer = shared_vars.mono_shared_vars_tokenizer();
let strings_const = &config.const_idents.strings;
let strings = shared_vars.strings().piped(rstr_tokenizer);
let shared_vars_tokenizer = shared_vars.shared_vars_tokenizer(mono_type_layout);
// drop(_measure_time0);
let shared_where_preds = quote!(
#(#where_clause_b,)*
#(#stable_abi_bounded:__StableAbi,)*
#(#static_equiv_bounded:__GetStaticEquivalent_,)*
#(#extra_bounds,)*
#(#prefix_bounds,)*
#prefix_type_trait_bound
);
let stable_abi_where_preds = shared_where_preds.clone().mutated(|ts| {
ts.extend(quote!(
#(#phantom_field_tys:__StableAbi,)*
))
});
let prefix_ref_impls = if let StabilityKind::Prefix(prefix) = &config.kind {
let prefix_ref = &prefix.prefix_ref;
let prefix_fields_struct = &prefix.prefix_fields_struct;
let lifetimes_s = lifetimes_s.clone();
quote!(
unsafe impl<#generics_header> __sabi_re::GetStaticEquivalent_
for #prefix_ref <#ty_generics>
where
#shared_where_preds
{
type StaticEquivalent =
__sabi_re::PrefixRef<
#static_struct_name <
#(#lifetimes_s,)*
#type_params_s
#({#const_params_s}),*
>
>;
}
unsafe impl<#generics_header> __sabi_re::StableAbi for #prefix_ref <#ty_generics>
where
#stable_abi_where_preds
{
type IsNonZeroType = __sabi_re::True;
const LAYOUT: &'static __sabi_re::TypeLayout =
<__sabi_re::PrefixRef<#prefix_fields_struct <#ty_generics>>
as __sabi_re::StableAbi
>::LAYOUT;
}
)
} else {
TokenStream2::new()
};
quote!(
#prefixref_types
#nonexhaustive_items
const _: () = {
use ::abi_stable;
#[allow(unused_imports)]
use ::abi_stable::pmr::{
self as __sabi_re,
renamed::*,
};
#prefixref_impls
const #item_info_const: abi_stable::type_layout::ItemInfo=
abi_stable::make_item_info!();
const #strings_const: ::abi_stable::std_types::RStr<'static>=#strings;
#static_struct_decl
#nonexhaustive_tokens
#interfacetype_tokenizer
#prefix_ref_impls
unsafe impl <#generics_header> __GetStaticEquivalent_ for #impl_ty
where
#shared_where_preds
{
type StaticEquivalent=#static_struct_name <
#(#lifetimes_s,)*
#type_params_s
#({#const_params_s}),*
>;
}
#[doc(hidden)]
const #mono_type_layout:&'static __sabi_re::MonoTypeLayout=
&__sabi_re::MonoTypeLayout::from_derive(
__sabi_re::_private_MonoTypeLayoutDerive{
name: #stringified_name,
item_info: #item_info_const,
data: #mono_tl_data,
generics: #generic_params_tokens,
mod_refl_mode:#mod_refl_mode,
repr_attr:#repr,
phantom_fields:#phantom_fields,
shared_vars: #mono_shared_vars_tokenizer,
}
);
impl <#generics_header> #impl_ty
where
#stable_abi_where_preds
{
#shared_vars_tokenizer
#extra_checks_const
#tags_const
}
unsafe impl <#generics_header> __sabi_re::#impld_stable_abi_trait for #impl_ty
where
#stable_abi_where_preds
{
type IsNonZeroType=#is_nonzero;
const LAYOUT: &'static __sabi_re::TypeLayout = {
&__sabi_re::TypeLayout::from_derive::<#size_align_for>(
__sabi_re::_private_TypeLayoutDerive {
shared_vars: Self::__SABI_SHARED_VARS,
mono:#mono_type_layout,
abi_consts: Self::ABI_CONSTS,
data:#generic_tl_data,
tag: #tags_arg,
extra_checks: #extra_checks_arg,
}
)
};
}
};
)
.observe(|tokens| {
// drop(_measure_time1);
if config.debug_print {
panic!("\n\n\n{}\n\n\n", tokens);
}
})
.piped(Ok)
}
// Tokenizes a `MonoTLEnum{ .. }`
fn tokenize_mono_enum<'a>(
ds: &'a DataStructure<'a>,
variant_names_start_len: StartLen,
_nonexhaustive_opt: Option<&'a nonexhaustive::NonExhaustive<'a>>,
_config: &'a StableAbiOptions<'a>,
visited_fields: &'a VisitedFieldMap<'a>,
shared_vars: &mut SharedVars<'a>,
) -> impl ToTokens + 'a {
let ct = shared_vars.ctokens();
ToTokenFnMut::new(move |ts| {
let variant_names_start_len = variant_names_start_len.tokenizer(ct.as_ref());
let variant_lengths = ds.variants.iter().map(|x| {
assert!(
x.fields.len() < 256,
"variant '{}' has more than 255 fields.",
x.name
);
x.fields.len() as u8
});
let fields = fields_tokenizer(ds, visited_fields, ct);
quote!(
__sabi_re::MonoTLEnum::new(
#variant_names_start_len,
abi_stable::rslice![#( #variant_lengths ),*],
#fields,
)
)
.to_tokens(ts);
})
}
// Tokenizes a `GenericTLEnum{ .. }`
fn tokenize_generic_enum<'a>(
ds: &'a DataStructure<'a>,
_variant_names_start_len: StartLen,
nonexhaustive_opt: Option<&'a nonexhaustive::NonExhaustive<'a>>,
config: &'a StableAbiOptions<'a>,
_visited_fields: &'a VisitedFieldMap<'a>,
ct: &'a CommonTokens<'a>,
) -> impl ToTokens + 'a {
ToTokenFnMut::new(move |ts| {
let is_exhaustive = match nonexhaustive_opt {
Some(_) => {
let name = ds.name;
let ty_generics = GenParamsIn::new(ds.generics, InWhat::ItemUse);
// let (_, ty_generics,_) = ds.generics.split_for_impl();
quote!(nonexhaustive(
&__sabi_re::MakeTLNonExhaustive::< #name <#ty_generics> >::NEW
))
}
None => quote!(exhaustive()),
};
let discriminants = ds.variants.iter().map(|x| x.discriminant);
let discriminants = config.repr.tokenize_discriminant_exprs(discriminants, ct);
quote!(
__sabi_re::GenericTLEnum::new(
__IsExhaustive::#is_exhaustive,
#discriminants,
)
)
.to_tokens(ts);
})
}
/// Tokenizes a TLFields,
fn fields_tokenizer<'a>(
ds: &'a DataStructure<'a>,
visited_fields: &'a VisitedFieldMap<'a>,
ctokens: &'a CommonTokens<'a>,
) -> impl ToTokens + 'a {
ToTokenFnMut::new(move |ts| {
to_stream!(ts;ctokens.comp_tl_fields,ctokens.colon2,ctokens.new);
ctokens.paren.surround(ts, |ts| {
fields_tokenizer_inner(ds, visited_fields, ctokens, ts);
});
})
}
fn fields_tokenizer_inner<'a>(
ds: &'a DataStructure<'a>,
visited_fields: &'a VisitedFieldMap<'a>,
ct: &'a CommonTokens<'a>,
ts: &mut TokenStream2,
) {
let iter = visited_fields.map.iter().map(|field| field.comp_field);
rslice_tokenizer(iter).to_tokens(ts);
ct.comma.to_tokens(ts);
if visited_fields.fn_ptr_count == 0 {
ct.none.to_tokens(ts);
} else {
to_stream!(ts;ct.some);
ct.paren.surround(ts, |ts| {
ct.and_.to_tokens(ts);
tokenize_tl_functions(ds, visited_fields, ct, ts);
});
}
to_stream! {ts; ct.comma };
}
/// Tokenizes a TLFunctions
fn tokenize_tl_functions<'a>(
ds: &'a DataStructure<'a>,
visited_fields: &'a VisitedFieldMap<'a>,
_ct: &'a CommonTokens<'a>,
ts: &mut TokenStream2,
) {
let mut functions =
CompositeVec::<&'a CompTLFunction>::with_capacity(visited_fields.fn_ptr_count);
let mut field_fn_ranges = Vec::<StartLen>::with_capacity(ds.field_count);
visited_fields
.map
.iter()
.map(|field| functions.extend(&field.functions))
.extending(&mut field_fn_ranges);
let functions = functions.into_inner();
let field_fn_ranges = field_fn_ranges.into_iter().map(|sl| sl.to_u32());
quote!({
const TLF_A: &[__CompTLFunction] = &[#(#functions),*];
const TLF_B: __TLFunctions = __TLFunctions::new(
__sabi_re::RSlice::from_slice(TLF_A),
abi_stable::rslice![#(#field_fn_ranges),*],
);
TLF_B
})
.to_tokens(ts);
}
|
use crate::Span;
/// A comment.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(
feature = "serde-1",
derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
pub struct Comment<'input> {
/// The comment itself.
pub value: &'input str,
/// Where the comment is located in the original string.
pub span: Span,
}
|
use crate::ast;
use crate::error::{GraphError, Result};
use crate::graph::{ToValues, Values, Variables};
use inflector::Inflector;
#[derive(Clone, Default, Debug)]
pub struct Vars {
pub inner: Variables,
}
#[derive(Clone)]
pub struct Query<'a> {
pub name: &'a str,
pub description: &'a str,
pub ty: ast::LetType,
// order: value -> fn_value
pub value: Option<String>,
pub fn_value: Option<fn() -> Option<String>>,
}
pub const QUERY_SPLIT_1: &str = "\x01";
impl From<Variables> for Vars {
fn from(inner: Variables) -> Self {
Self { inner }
}
}
impl Vars {
pub fn from_variables(inner: Variables) -> Self {
Self::from(inner)
}
pub fn load(query: Vec<Query>) -> Result<Self> {
Ok(Self {
inner: query
.into_iter()
.map(|x| {
let name = x.name.to_string();
let desc = x.description.to_string();
let ty = x.ty;
let fn_value = x.fn_value;
let value = x
.value
.or_else(|| fn_value.map(|f| f()).flatten())
.map(|v| Self::encode(&name, v, Some(&ty)))
.transpose()?;
let mut var = ast::Variable::with_name_value(name.clone(), value);
var.id = Some(0);
var.id_old = Some(0);
var.description = Some(desc);
var.ty = Some(ty);
Ok((name, var.into()))
})
.collect::<Result<_>>()?,
})
}
pub fn get(&self, name: &str) -> Result<&ast::RefVariable> {
self.inner.get(name).ok_or_else(|| {
GraphError::NoSuchVariable {
name: name.to_string(),
candidates: self.inner.keys().cloned().collect(),
}
.into()
})
}
pub fn try_get_checked(
&self,
name: &str,
expected: ast::LetType,
) -> Result<Option<&ast::RefVariable>> {
match self.inner.get(name) {
Some(var) => {
let var_ref = var.borrow();
if let Some(value) = var_ref.value.as_ref() {
let value_ty = value.ty();
if value_ty.as_ref() == Some(&expected) {
Ok(Some(var))
} else {
GraphError::MismatchedType {
name: name.to_string(),
expected,
given: value_ty,
}
.into()
}
} else {
GraphError::EmptyValue {
name: name.to_string(),
expected,
}
.into()
}
}
None => Ok(None),
}
}
pub fn get_node_name(&self, name: &str, ty: ast::LetNodeType) -> Result<String> {
self.get_and_cast(name, ast::LetType::Node(Some(ty)), |x| {
x.unwrap_node_name().map(|x| x.to_string())
})
}
pub fn get_string(&self, name: &str) -> Result<String> {
self.get_and_cast(name, ast::LetType::String, |x| {
x.unwrap_string().map(|x| x.to_string())
})
}
pub fn get_string_list(&self, name: &str) -> Result<Vec<String>> {
self.get_and_cast_list(name, ast::LetType::String, |x| {
x.unwrap_string().map(|x| x.to_string())
})
}
fn get_and_cast<T>(
&self,
name: &str,
expected: ast::LetType,
f: impl Fn(&ast::Value) -> Option<T>,
) -> Result<T> {
match self.get(name)?.borrow().value.as_ref() {
Some(value) => f(value).ok_or_else(|| {
GraphError::MismatchedType {
name: name.to_string(),
expected,
given: value.ty(),
}
.into()
}),
None => GraphError::EmptyValue {
name: name.to_string(),
expected,
}
.into(),
}
}
fn get_and_cast_list<T>(
&self,
name: &str,
expected: ast::LetType,
f: impl Fn(&ast::Value) -> Option<T>,
) -> Result<Vec<T>> {
self.get_and_cast(name, ast::LetType::List(Box::new(expected)), |x| {
x.unwrap_list()
.map(|x| x.iter().map(|x| f(x)).flatten().collect())
})
}
pub fn set(&self, name: &str, value: &str) -> Result<()> {
let mut var = self.get(name)?.borrow_mut();
var.value = Some(Self::encode(name, value.to_string(), var.ty.as_ref())?);
Ok(())
}
pub fn set_as_value(&self, name: &str, value: impl Into<ast::Value>) -> Result<()> {
let value = value.into();
let mut var = self.get(name)?.borrow_mut();
let expected = &var.ty;
let given = &value.ty();
if expected != given {
return GraphError::MismatchedType {
name: name.to_string(),
expected: expected.clone().unwrap(),
given: given.clone(),
}
.into();
}
var.value = Some(value);
Ok(())
}
fn encode(name: &str, value: String, ty: Option<&ast::LetType>) -> Result<ast::Value> {
match ty {
Some(ast::LetType::List(ty)) => Ok(ast::Value::List(
value
.split(QUERY_SPLIT_1)
.filter(|x| !x.is_empty())
.map(|x| Self::encode(name, x.to_string(), Some(ty)))
.collect::<Result<_>>()?,
)),
_ => Self::encode_atomic(name, value, ty),
}
}
fn encode_atomic(name: &str, value: String, ty: Option<&ast::LetType>) -> Result<ast::Value> {
match ty {
Some(ast::LetType::Bool) => match value.to_lowercase().as_str() {
"yes" | "true" | "1" => Ok(true.into()),
"no" | "false" | "0" => Ok(false.into()),
_ => unparsable_string(name, value, ty),
},
Some(ast::LetType::UInt) => match value.parse::<u64>() {
Ok(value) => Ok(value.into()),
Err(_) => unparsable_string(name, value, ty),
},
Some(ast::LetType::Int) => match value.parse::<i64>() {
Ok(value) => Ok(value.into()),
Err(_) => unparsable_string(name, value, ty),
},
Some(ast::LetType::Real) => match value.parse::<f64>() {
Ok(value) => Ok(value.into()),
Err(_) => unparsable_string(name, value, ty),
},
Some(ast::LetType::String) => Ok(ast::Value::String(value)),
Some(ast::LetType::Node(_)) => Ok(ast::Value::Node(value.to_pascal_case())),
_ => unparsable_string(name, value, ty),
}
}
pub fn to_variables(&self) -> Self {
self.inner
.iter()
.map(|(k, v)| (k.to_snake_case(), v.clone()))
.collect::<Variables>()
.into()
}
}
impl ToValues for Vars {
fn to_values(&self) -> Values {
self.inner.to_values()
}
}
fn unparsable_string<T>(name: &str, value: String, ty: Option<&ast::LetType>) -> Result<T> {
GraphError::UnparsableString {
name: name.to_string(),
value,
ty: ty.cloned(),
}
.into()
}
|
use serde::{Deserialize, Serialize};
/// Describes the scores that the two players have. Players each begin with 20 points, and loses when all the points are lost.
/// /両プレイヤーが持つ得点を表す型。双方20点スタートであり、点が0点になると敗北。
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Scores {
ia: i32,
a: i32,
}
/// Describes who won the game. If `Victor(None)`, the game is a tie.
/// /どちらが勝利したのかを表現する型。 `Victor(None)` であれば引き分け。
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Victor(Option<cetkaik_core::absolute::Side>);
use cetkaik_core::absolute;
impl Default for Scores {
fn default() -> Self {
Self::new()
}
}
impl Scores {
#[must_use]
pub const fn new() -> Self {
Self { ia: 20, a: 20 }
}
#[must_use]
pub const fn ia(self) -> i32 {
self.ia
}
#[must_use]
pub const fn a(self) -> i32 {
self.a
}
pub fn edit(
self,
raw_score: i32,
whose_turn: cetkaik_core::absolute::Side,
rate: super::Rate,
) -> Result<Self, Victor> {
let increment_in_ia_owner_s_score = match whose_turn {
absolute::Side::IASide => 1,
absolute::Side::ASide => -1,
} * rate.num()
* raw_score;
let new_ia_owner_s_score = 0.max(40.min(self.ia + increment_in_ia_owner_s_score));
if new_ia_owner_s_score == 40 {
Err(Victor(Some(absolute::Side::IASide)))
} else if new_ia_owner_s_score == 0 {
Err(Victor(Some(absolute::Side::ASide)))
} else {
Ok(Self {
ia: new_ia_owner_s_score,
a: 40 - new_ia_owner_s_score,
})
}
}
#[must_use]
pub fn which_side_is_winning(self) -> Victor {
match self.ia.cmp(&(40 - self.ia)) {
std::cmp::Ordering::Greater => Victor(Some(absolute::Side::IASide)),
std::cmp::Ordering::Less => Victor(Some(absolute::Side::ASide)),
std::cmp::Ordering::Equal => Victor(None),
}
}
}
|
#![allow(non_snake_case)]
use core::convert::TryInto;
use test_winrt_signatures::*;
use windows::core::*;
use Component::Signatures::*;
#[implement(Component::Signatures::ITestSingle)]
struct RustTest();
impl RustTest {
fn SignatureSingle(&self, a: f32, b: &mut f32) -> Result<f32> {
*b = a;
Ok(a)
}
fn ArraySignatureSingle(&self, a: &[f32], b: &mut [f32], c: &mut Array<f32>) -> Result<Array<f32>> {
assert!(a.len() == b.len());
assert!(c.is_empty());
b.copy_from_slice(a);
*c = Array::from_slice(a);
Ok(Array::from_slice(a))
}
fn CallSignatureSingle(&self, handler: &Option<SignatureSingle>) -> Result<()> {
let a = 123.0;
let mut b = 0.0;
// TODO: this seems rather verbose...
let c = handler.as_ref().unwrap().Invoke(a, &mut b)?;
assert!(a == b);
assert!(a == c);
Ok(())
}
fn CallArraySignatureSingle(&self, handler: &Option<ArraySignatureSingle>) -> Result<()> {
let a = [1.0, 2.0, 3.0];
let mut b = [0.0; 3];
let mut c = Array::new();
let d = handler.as_ref().unwrap().Invoke(&a, &mut b, &mut c)?;
assert!(a == b);
// TODO: should `a == c` be sufficient? Does that work for Vec?
assert!(a == c[..]);
assert!(a == d[..]);
Ok(())
}
}
fn test_interface(test: &ITestSingle) -> Result<()> {
let a = 123.0;
let mut b = 0.0;
let c = test.SignatureSingle(a, &mut b)?;
assert!(a == b);
assert!(a == c);
test.CallSignatureSingle(SignatureSingle::new(|a, b| {
*b = a;
Ok(a)
}))?;
let a = [4.0, 5.0, 6.0];
let mut b = [0.0; 3];
let mut c = Array::new();
let d = test.ArraySignatureSingle(&a, &mut b, &mut c)?;
assert!(a == b);
assert!(a == c[..]);
assert!(a == d[..]);
test.CallArraySignatureSingle(ArraySignatureSingle::new(|a, b, c| {
assert!(a.len() == b.len());
assert!(c.is_empty());
b.copy_from_slice(a);
*c = Array::from_slice(a);
Ok(Array::from_slice(a))
}))?;
Ok(())
}
#[test]
fn test() -> Result<()> {
test_interface(&Test::new()?.try_into()?)?;
test_interface(&RustTest().into())?;
Ok(())
}
|
use crate::{AsReg, Reg};
use failure::{bail, Error};
use hashbrown::HashSet;
use std::fmt;
#[derive(Debug, Default)]
pub struct Registers {
registers: [Reg; 6],
/// Written to registers.
written: HashSet<usize>,
/// Read from registers.
read: HashSet<usize>,
/// Last instruction that was executed.
pub last_ip: Option<usize>,
/// Which register contains the current instruction.
pub ip: usize,
}
impl Registers {
/// Test if the given registry has been written to.
pub fn is_written(&self, reg: impl AsReg) -> bool {
self.written.contains(®.as_reg())
}
/// Test if the given registry has been read from.
pub fn is_read(&self, reg: impl AsReg) -> bool {
self.read.contains(®.as_reg())
}
/// Access the given register immutably.
pub fn reg(&mut self, reg: impl AsReg) -> Result<Reg, Error> {
let index = reg.as_reg();
self.read.insert(index);
match self.registers.get(index).cloned() {
Some(reg) => Ok(reg),
None => bail!("no such register: {}", index),
}
}
/// Access the given register mutably.
pub fn reg_mut(&mut self, reg: impl AsReg) -> Result<&mut i64, Error> {
let index = reg.as_reg();
self.written.insert(index);
match self.registers.get_mut(index) {
Some(reg) => Ok(reg),
None => bail!("no such register: {}", index),
}
}
pub fn ip(&self) -> Result<usize, Error> {
match self.registers.get(self.ip) {
Some(reg) => Ok(*reg as usize),
None => bail!("no ip register: {}", self.ip),
}
}
pub fn ip_mut(&mut self) -> Result<&mut Reg, Error> {
match self.registers.get_mut(self.ip) {
Some(reg) => Ok(reg),
None => bail!("no ip register: {}", self.ip),
}
}
/// Iterate over all registers.
pub fn iter(&self) -> impl Iterator<Item = Reg> + '_ {
self.registers.iter().cloned()
}
/// Clear all state for the device.
pub fn clear(&mut self) {
self.written.clear();
self.read.clear();
}
pub fn reset(&mut self) {
self.written.clear();
self.read.clear();
self.last_ip = None;
for r in self.registers.iter_mut() {
*r = Default::default();
}
}
pub fn name(&self, reg: impl AsReg) -> RegName {
let reg = reg.as_reg();
let special = if reg == self.ip { Some("ip") } else { None };
RegName {
special,
name: ['a', 'b', 'c', 'd', 'e', 'f'].get(reg).cloned(),
}
}
}
pub struct RegName {
special: Option<&'static str>,
name: Option<char>,
}
impl fmt::Display for RegName {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(special) = self.special.as_ref() {
return special.fmt(fmt);
}
if let Some(name) = self.name {
return name.fmt(fmt);
}
"?".fmt(fmt)
}
}
|
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Req {
verb: String
} |
//! Services and MakeServices
//!
//! - A [`Service`](service::Service) is a trait representing an asynchronous
//! function of a request to a response. It's similar to
//! `async fn(Request) -> Result<Response, Error>`.
//! - A [`MakeService`](service::MakeService) is a trait creating specific
//! instances of a `Service`.
//!
//! These types are conceptually similar to those in
//! [tower](https://crates.io/crates/tower), while being specific to hyper.
//!
//! # Service
//!
//! In hyper, especially in the server setting, a `Service` is usually bound
//! to a single connection. It defines how to respond to **all** requests that
//! connection will receive.
//!
//! While it's possible to implement `Service` for a type manually, the helpers
//! [`service_fn`](service::service_fn) and
//! [`service_fn_ok`](service::service_fn_ok) should be sufficient for most
//! cases.
//!
//! # MakeService
//!
//! Since a `Service` is bound to a single connection, a [`Server`](::Server)
//! needs a way to make them as it accepts connections. This is what a
//! `MakeService` does.
//!
//! Resources that need to be shared by all `Service`s can be put into a
//! `MakeService`, and then passed to individual `Service`s when `make_service`
//! is called.
mod make_service;
mod new_service;
mod service;
pub use self::make_service::{make_service_fn, MakeService, MakeServiceRef};
// NewService is soft-deprecated.
#[doc(hidden)]
pub use self::new_service::NewService;
pub use self::service::{service_fn, service_fn_ok, Service};
|
//! Task notification
cfg_target_has_atomic! {
#[cfg(feature = "alloc")]
mod arc_wake;
#[cfg(feature = "alloc")]
pub use self::arc_wake::ArcWake;
#[cfg(feature = "alloc")]
mod waker;
#[cfg(feature = "alloc")]
pub use self::waker::waker;
#[cfg(feature = "alloc")]
mod waker_ref;
#[cfg(feature = "alloc")]
pub use self::waker_ref::{waker_ref, WakerRef};
pub use futures_core::task::__internal::AtomicWaker;
}
mod noop_waker;
pub use self::noop_waker::noop_waker;
#[cfg(feature = "std")]
pub use self::noop_waker::noop_waker_ref;
mod spawn;
pub use self::spawn::{SpawnExt, LocalSpawnExt};
pub use futures_core::task::{Context, Poll, Waker, RawWaker, RawWakerVTable};
|
#![deny(
clippy::all,
clippy::pedantic,
clippy::nursery,
// TODO(thlorenz): prepare toml to publish
// clippy::cargo
)]
// clippy::restriction,
#![deny(
clippy::as_conversions,
clippy::clone_on_ref_ptr,
clippy::create_dir,
clippy::dbg_macro,
clippy::decimal_literal_representation,
clippy::else_if_without_else,
clippy::exit,
clippy::expect_used,
clippy::filetype_is_file,
clippy::float_cmp_const,
clippy::get_unwrap,
clippy::indexing_slicing,
clippy::inline_asm_x86_att_syntax,
clippy::inline_asm_x86_intel_syntax,
clippy::integer_arithmetic,
clippy::integer_division,
clippy::let_underscore_must_use,
clippy::lossy_float_literal,
clippy::map_err_ignore,
clippy::mem_forget,
clippy::panic_in_result_fn,
clippy::print_stdout,
clippy::rc_buffer,
clippy::rest_pat_in_fully_bound_structs,
clippy::shadow_same,
clippy::string_add,
clippy::todo,
clippy::unimplemented,
clippy::unneeded_field_pattern,
clippy::unreachable,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::use_debug,
clippy::verbose_file_reads,
clippy::wildcard_enum_match_arm,
clippy::wrong_pub_self_convention
)]
#![allow(
// TODO(thlorenz): add docs
clippy::cargo_common_metadata,
clippy::erasing_op,
clippy::module_name_repetitions,
clippy::must_use_candidate,
clippy::similar_names,
missing_crate_level_docs,
missing_doc_code_examples,
)]
#[cfg(feature = "plot")]
mod test_utils;
#[cfg(feature = "plot")]
pub use test_utils::*;
mod angle;
mod beam;
mod beam_iter;
mod grid;
mod position;
mod ray;
mod ray_iter;
mod rays;
mod tile_raycaster;
mod util;
pub use angle::AngleRad;
pub use beam::BeamIntersect;
pub use grid::Grid;
pub use position::TilePosition;
pub use tile_raycaster::{Crossing, TileRaycaster};
|
use std::collections::HashSet;
use ocl::{self, builders::KernelBuilder};
use crate::{Push, filter::Filter};
/// Filter that doesn't change picture. Used as a placeholder.
#[derive(Default)]
pub struct IdentityFilter {}
impl IdentityFilter {
pub fn new() -> Self {
Self {}
}
}
impl Filter for IdentityFilter {
fn inst_name() -> String {
"identity_filter".to_string()
}
fn source(_: &mut HashSet<u64>) -> String {
"#include <clay_core/filter/identity.h>".to_string()
}
}
impl Push for IdentityFilter {
fn args_count() -> usize {
1
}
fn args_def(kb: &mut KernelBuilder) {
kb.arg(&0i32);
}
fn args_set(&mut self, i: usize, k: &mut ocl::Kernel) -> crate::Result<()> {
k.set_arg(i, &0i32).map_err(|e| e.into())
}
}
|
use super::{Dispatch, NodeId, QueryId, ShardId, State};
use crate::{NodeQueue, NodeQueueEntry, NodeStatus, NodeThreadPool};
use std::cell::RefCell;
use std::collections::HashSet;
use rand_chacha::{rand_core::SeedableRng, ChaChaRng};
use simrs::{Key, QueueId};
/// Always selects the node with the fewer requests in the queue.
pub struct ShortestQueueDispatch {
node_queues: Vec<QueueId<NodeQueue<NodeQueueEntry>>>,
node_weights: Vec<f32>,
shards: Vec<Vec<NodeId>>,
disabled_nodes: HashSet<NodeId>,
thread_pools: Vec<Key<NodeThreadPool>>,
rng: RefCell<ChaChaRng>,
include_running: bool,
}
impl ShortestQueueDispatch {
/// Constructs a new dispatcher.
#[must_use]
pub fn new(
nodes: &[Vec<usize>],
node_queues: Vec<QueueId<NodeQueue<NodeQueueEntry>>>,
thread_pools: Vec<Key<NodeThreadPool>>,
include_running: bool,
) -> Self {
let node_weights = vec![1.0; node_queues.len()];
Self {
shards: super::invert_nodes_to_shards(nodes),
disabled_nodes: HashSet::new(),
node_queues,
thread_pools,
node_weights,
rng: RefCell::new(ChaChaRng::from_entropy()),
include_running,
}
}
fn calc_length(&self, state: &State, node_id: NodeId) -> usize {
let queue_len = state.len(self.node_queues[node_id.0]);
let active = if self.include_running {
state
.get(self.thread_pools[node_id.0])
.expect("unknown thread pool ID")
.num_active()
} else {
0
};
queue_len + active
}
fn calc_loads(&self, state: &State) -> Vec<f32> {
(0..self.num_nodes())
.map(NodeId)
.zip(&self.node_weights)
.map(|(node_id, weight)| {
if !self.disabled_nodes.contains(&node_id) {
self.calc_length(state, node_id) as f32 * *weight
} else {
f32::MAX
}
})
.collect()
}
fn select_node(&self, shard_id: ShardId, loads: &[f32]) -> NodeId {
use rand::Rng;
let mut min_load = f32::MAX;
let mut min_node = NodeId(0);
let mut min_count = 0;
let nodes = &self.shards[shard_id.0];
if nodes.len() == 1 {
return nodes[0];
}
for &node_id in nodes.iter().filter(|n| !self.disabled_nodes.contains(n)) {
let load = loads[node_id.0];
if load < min_load {
min_load = load;
min_node = node_id;
min_count = 1;
} else if load == min_load {
min_count += 1;
}
}
if min_count == 1 {
min_node
} else {
let selected: usize = self.rng.borrow_mut().gen_range(0..min_count);
self.shards[shard_id.0]
.iter()
.copied()
.filter(|n| loads[n.0] == min_load)
.nth(selected)
.unwrap()
}
}
}
impl Dispatch for ShortestQueueDispatch {
fn dispatch(&self, _: QueryId, shards: &[ShardId], state: &State) -> Vec<(ShardId, NodeId)> {
let mut selection = shards
.iter()
.copied()
.map(|sid| (sid, NodeId(0)))
.collect::<Vec<_>>();
let mut loads = self.calc_loads(state);
for (shard_id, node_id) in &mut selection {
*node_id = self.select_node(*shard_id, &loads);
loads[node_id.0] += self.node_weights[node_id.0];
}
selection
}
fn num_shards(&self) -> usize {
self.shards.len()
}
fn num_nodes(&self) -> usize {
self.node_queues.len()
}
fn disable_node(&mut self, node_id: NodeId) -> eyre::Result<bool> {
Ok(self.disabled_nodes.insert(node_id))
}
fn enable_node(&mut self, node_id: NodeId) -> bool {
self.disabled_nodes.remove(&node_id)
}
fn recompute(&mut self, node_statuses: &[Key<NodeStatus>], state: &State) {
self.node_weights = node_statuses
.iter()
.copied()
.map(|key| match state.get(key).expect("missing node status") {
NodeStatus::Healthy => 1.0,
NodeStatus::Injured(i) => {
assert!(*i > 1.0);
*i
}
NodeStatus::Unresponsive => 0.0,
})
.collect();
}
}
|
#[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "sum";
#[test]
fn test_bsd_single_file() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.arg("lorem_ipsum.txt").run();
assert_empty_stderr!(result);
assert!(result.success);
assert_eq!(result.stdout, at.read("bsd_single_file.expected"));
}
#[test]
fn test_bsd_multiple_files() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.arg("lorem_ipsum.txt")
.arg("alice_in_wonderland.txt")
.run();
assert_empty_stderr!(result);
assert!(result.success);
assert_eq!(result.stdout, at.read("bsd_multiple_files.expected"));
}
#[test]
fn test_bsd_stdin() {
let (at, mut ucmd) = testing(UTIL_NAME);
let input = at.read("lorem_ipsum.txt");
let result = ucmd.run_piped_stdin(input);
assert_empty_stderr!(result);
assert!(result.success);
assert_eq!(result.stdout, at.read("bsd_stdin.expected"));
}
#[test]
fn test_sysv_single_file() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.arg("-s").arg("lorem_ipsum.txt").run();
assert_empty_stderr!(result);
assert!(result.success);
assert_eq!(result.stdout, at.read("sysv_single_file.expected"));
}
#[test]
fn test_sysv_multiple_files() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.arg("-s")
.arg("lorem_ipsum.txt")
.arg("alice_in_wonderland.txt")
.run();
assert_empty_stderr!(result);
assert!(result.success);
assert_eq!(result.stdout, at.read("sysv_multiple_files.expected"));
}
#[test]
fn test_sysv_stdin() {
let (at, mut ucmd) = testing(UTIL_NAME);
let input = at.read("lorem_ipsum.txt");
let result = ucmd.arg("-s").run_piped_stdin(input);
assert_empty_stderr!(result);
assert!(result.success);
assert_eq!(result.stdout, at.read("sysv_stdin.expected"));
}
|
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let (n, m) = scan!((usize, usize));
let ss = scan!(String; n);
let tt = scan!(String; m);
use std::collections::HashSet;
let tt: HashSet<String> = tt.into_iter().collect();
for s in ss {
if tt.contains(&s) {
println!("Yes");
} else {
println!("No");
}
}
}
|
#[path = "with_atom_module/with_atom_function.rs"]
mod with_atom_function;
// `without_atom_function_errors_badarg` in unit tests
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u16,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u16,
}
impl super::DMACTL3 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u16 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct USB_DMACTL3_ENABLER {
bits: bool,
}
impl USB_DMACTL3_ENABLER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_DMACTL3_ENABLEW<'a> {
w: &'a mut W,
}
impl<'a> _USB_DMACTL3_ENABLEW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u16) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_DMACTL3_DIRR {
bits: bool,
}
impl USB_DMACTL3_DIRR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_DMACTL3_DIRW<'a> {
w: &'a mut W,
}
impl<'a> _USB_DMACTL3_DIRW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u16) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_DMACTL3_MODER {
bits: bool,
}
impl USB_DMACTL3_MODER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_DMACTL3_MODEW<'a> {
w: &'a mut W,
}
impl<'a> _USB_DMACTL3_MODEW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u16) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_DMACTL3_IER {
bits: bool,
}
impl USB_DMACTL3_IER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_DMACTL3_IEW<'a> {
w: &'a mut W,
}
impl<'a> _USB_DMACTL3_IEW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u16) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_DMACTL3_EPR {
bits: u8,
}
impl USB_DMACTL3_EPR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _USB_DMACTL3_EPW<'a> {
w: &'a mut W,
}
impl<'a> _USB_DMACTL3_EPW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 4);
self.w.bits |= ((value as u16) & 15) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_DMACTL3_ERRR {
bits: bool,
}
impl USB_DMACTL3_ERRR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_DMACTL3_ERRW<'a> {
w: &'a mut W,
}
impl<'a> _USB_DMACTL3_ERRW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 8);
self.w.bits |= ((value as u16) & 1) << 8;
self.w
}
}
#[doc = "Possible values of the field `USB_DMACTL3_BRSTM`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_DMACTL3_BRSTMR {
#[doc = "Bursts of unspecified length"]
USB_DMACTL3_BRSTM_ANY,
#[doc = "INCR4 or unspecified length"]
USB_DMACTL3_BRSTM_INC4,
#[doc = "INCR8, INCR4 or unspecified length"]
USB_DMACTL3_BRSTM_INC8,
#[doc = "INCR16, INCR8, INCR4 or unspecified length"]
USB_DMACTL3_BRSTM_INC16,
}
impl USB_DMACTL3_BRSTMR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_ANY => 0,
USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC4 => 1,
USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC8 => 2,
USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC16 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> USB_DMACTL3_BRSTMR {
match value {
0 => USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_ANY,
1 => USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC4,
2 => USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC8,
3 => USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC16,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `USB_DMACTL3_BRSTM_ANY`"]
#[inline(always)]
pub fn is_usb_dmactl3_brstm_any(&self) -> bool {
*self == USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_ANY
}
#[doc = "Checks if the value of the field is `USB_DMACTL3_BRSTM_INC4`"]
#[inline(always)]
pub fn is_usb_dmactl3_brstm_inc4(&self) -> bool {
*self == USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC4
}
#[doc = "Checks if the value of the field is `USB_DMACTL3_BRSTM_INC8`"]
#[inline(always)]
pub fn is_usb_dmactl3_brstm_inc8(&self) -> bool {
*self == USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC8
}
#[doc = "Checks if the value of the field is `USB_DMACTL3_BRSTM_INC16`"]
#[inline(always)]
pub fn is_usb_dmactl3_brstm_inc16(&self) -> bool {
*self == USB_DMACTL3_BRSTMR::USB_DMACTL3_BRSTM_INC16
}
}
#[doc = "Values that can be written to the field `USB_DMACTL3_BRSTM`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_DMACTL3_BRSTMW {
#[doc = "Bursts of unspecified length"]
USB_DMACTL3_BRSTM_ANY,
#[doc = "INCR4 or unspecified length"]
USB_DMACTL3_BRSTM_INC4,
#[doc = "INCR8, INCR4 or unspecified length"]
USB_DMACTL3_BRSTM_INC8,
#[doc = "INCR16, INCR8, INCR4 or unspecified length"]
USB_DMACTL3_BRSTM_INC16,
}
impl USB_DMACTL3_BRSTMW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_ANY => 0,
USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_INC4 => 1,
USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_INC8 => 2,
USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_INC16 => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _USB_DMACTL3_BRSTMW<'a> {
w: &'a mut W,
}
impl<'a> _USB_DMACTL3_BRSTMW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USB_DMACTL3_BRSTMW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Bursts of unspecified length"]
#[inline(always)]
pub fn usb_dmactl3_brstm_any(self) -> &'a mut W {
self.variant(USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_ANY)
}
#[doc = "INCR4 or unspecified length"]
#[inline(always)]
pub fn usb_dmactl3_brstm_inc4(self) -> &'a mut W {
self.variant(USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_INC4)
}
#[doc = "INCR8, INCR4 or unspecified length"]
#[inline(always)]
pub fn usb_dmactl3_brstm_inc8(self) -> &'a mut W {
self.variant(USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_INC8)
}
#[doc = "INCR16, INCR8, INCR4 or unspecified length"]
#[inline(always)]
pub fn usb_dmactl3_brstm_inc16(self) -> &'a mut W {
self.variant(USB_DMACTL3_BRSTMW::USB_DMACTL3_BRSTM_INC16)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 9);
self.w.bits |= ((value as u16) & 3) << 9;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u16 {
self.bits
}
#[doc = "Bit 0 - DMA Transfer Enable"]
#[inline(always)]
pub fn usb_dmactl3_enable(&self) -> USB_DMACTL3_ENABLER {
let bits = ((self.bits >> 0) & 1) != 0;
USB_DMACTL3_ENABLER { bits }
}
#[doc = "Bit 1 - DMA Direction"]
#[inline(always)]
pub fn usb_dmactl3_dir(&self) -> USB_DMACTL3_DIRR {
let bits = ((self.bits >> 1) & 1) != 0;
USB_DMACTL3_DIRR { bits }
}
#[doc = "Bit 2 - DMA Transfer Mode"]
#[inline(always)]
pub fn usb_dmactl3_mode(&self) -> USB_DMACTL3_MODER {
let bits = ((self.bits >> 2) & 1) != 0;
USB_DMACTL3_MODER { bits }
}
#[doc = "Bit 3 - DMA Interrupt Enable"]
#[inline(always)]
pub fn usb_dmactl3_ie(&self) -> USB_DMACTL3_IER {
let bits = ((self.bits >> 3) & 1) != 0;
USB_DMACTL3_IER { bits }
}
#[doc = "Bits 4:7 - Endpoint number"]
#[inline(always)]
pub fn usb_dmactl3_ep(&self) -> USB_DMACTL3_EPR {
let bits = ((self.bits >> 4) & 15) as u8;
USB_DMACTL3_EPR { bits }
}
#[doc = "Bit 8 - Bus Error Bit"]
#[inline(always)]
pub fn usb_dmactl3_err(&self) -> USB_DMACTL3_ERRR {
let bits = ((self.bits >> 8) & 1) != 0;
USB_DMACTL3_ERRR { bits }
}
#[doc = "Bits 9:10 - Burst Mode"]
#[inline(always)]
pub fn usb_dmactl3_brstm(&self) -> USB_DMACTL3_BRSTMR {
USB_DMACTL3_BRSTMR::_from(((self.bits >> 9) & 3) as u8)
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u16) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - DMA Transfer Enable"]
#[inline(always)]
pub fn usb_dmactl3_enable(&mut self) -> _USB_DMACTL3_ENABLEW {
_USB_DMACTL3_ENABLEW { w: self }
}
#[doc = "Bit 1 - DMA Direction"]
#[inline(always)]
pub fn usb_dmactl3_dir(&mut self) -> _USB_DMACTL3_DIRW {
_USB_DMACTL3_DIRW { w: self }
}
#[doc = "Bit 2 - DMA Transfer Mode"]
#[inline(always)]
pub fn usb_dmactl3_mode(&mut self) -> _USB_DMACTL3_MODEW {
_USB_DMACTL3_MODEW { w: self }
}
#[doc = "Bit 3 - DMA Interrupt Enable"]
#[inline(always)]
pub fn usb_dmactl3_ie(&mut self) -> _USB_DMACTL3_IEW {
_USB_DMACTL3_IEW { w: self }
}
#[doc = "Bits 4:7 - Endpoint number"]
#[inline(always)]
pub fn usb_dmactl3_ep(&mut self) -> _USB_DMACTL3_EPW {
_USB_DMACTL3_EPW { w: self }
}
#[doc = "Bit 8 - Bus Error Bit"]
#[inline(always)]
pub fn usb_dmactl3_err(&mut self) -> _USB_DMACTL3_ERRW {
_USB_DMACTL3_ERRW { w: self }
}
#[doc = "Bits 9:10 - Burst Mode"]
#[inline(always)]
pub fn usb_dmactl3_brstm(&mut self) -> _USB_DMACTL3_BRSTMW {
_USB_DMACTL3_BRSTMW { w: self }
}
}
|
use bigdecimal::BigDecimal;
use crate::decode::Decode;
use crate::encode::Encode;
use crate::io::Buf;
use crate::mysql::protocol::TypeId;
use crate::mysql::{MySql, MySqlData, MySqlTypeInfo, MySqlValue};
use crate::types::Type;
use crate::Error;
use std::str::FromStr;
impl Type<MySql> for BigDecimal {
fn type_info() -> MySqlTypeInfo {
MySqlTypeInfo::new(TypeId::NEWDECIMAL)
}
}
impl Encode<MySql> for BigDecimal {
fn encode(&self, buf: &mut Vec<u8>) {
let size = Encode::<MySql>::size_hint(self) - 1;
assert!(size <= std::u8::MAX as usize, "Too large size");
buf.push(size as u8);
let s = self.to_string();
buf.extend_from_slice(s.as_bytes());
}
fn size_hint(&self) -> usize {
let s = self.to_string();
s.as_bytes().len() + 1
}
}
impl Decode<'_, MySql> for BigDecimal {
fn decode(value: MySqlValue) -> crate::Result<Self> {
match value.try_get()? {
MySqlData::Binary(mut binary) => {
let _len = binary.get_u8()?;
let s = std::str::from_utf8(binary).map_err(Error::decode)?;
Ok(BigDecimal::from_str(s).map_err(Error::decode)?)
}
MySqlData::Text(s) => {
let s = std::str::from_utf8(s).map_err(Error::decode)?;
Ok(BigDecimal::from_str(s).map_err(Error::decode)?)
}
}
}
}
#[test]
fn test_encode_decimal() {
let v: BigDecimal = BigDecimal::from_str("-1.05").unwrap();
let mut buf: Vec<u8> = vec![];
<BigDecimal as Encode<MySql>>::encode(&v, &mut buf);
assert_eq!(buf, vec![0x05, b'-', b'1', b'.', b'0', b'5']);
let v: BigDecimal = BigDecimal::from_str("-105000").unwrap();
let mut buf: Vec<u8> = vec![];
<BigDecimal as Encode<MySql>>::encode(&v, &mut buf);
assert_eq!(buf, vec![0x07, b'-', b'1', b'0', b'5', b'0', b'0', b'0']);
let v: BigDecimal = BigDecimal::from_str("0.00105").unwrap();
let mut buf: Vec<u8> = vec![];
<BigDecimal as Encode<MySql>>::encode(&v, &mut buf);
assert_eq!(buf, vec![0x07, b'0', b'.', b'0', b'0', b'1', b'0', b'5']);
}
#[test]
fn test_decode_decimal() {
let buf: Vec<u8> = vec![0x05, b'-', b'1', b'.', b'0', b'5'];
let v = <BigDecimal as Decode<'_, MySql>>::decode(MySqlValue::binary(
MySqlTypeInfo::new(TypeId::NEWDECIMAL),
buf.as_slice(),
))
.unwrap();
assert_eq!(v.to_string(), "-1.05");
let buf: Vec<u8> = vec![0x04, b'0', b'.', b'0', b'5'];
let v = <BigDecimal as Decode<'_, MySql>>::decode(MySqlValue::binary(
MySqlTypeInfo::new(TypeId::NEWDECIMAL),
buf.as_slice(),
))
.unwrap();
assert_eq!(v.to_string(), "0.05");
let buf: Vec<u8> = vec![0x06, b'-', b'9', b'0', b'0', b'0', b'0'];
let v = <BigDecimal as Decode<'_, MySql>>::decode(MySqlValue::binary(
MySqlTypeInfo::new(TypeId::NEWDECIMAL),
buf.as_slice(),
))
.unwrap();
assert_eq!(v.to_string(), "-90000");
}
|
/// Implement the trait IntoTab
///
use core::Core;
pub trait IntoTab {
fn into_tab(&self) -> Vec<Vec<Core>>;
}
impl IntoTab for Vec<Core> {
fn into_tab(&self) -> Vec<Vec<Core>> {
let mut res = Vec::new();
res.push(self.to_vec());
res
}
}
impl IntoTab for Vec<Vec<Core>> {
fn into_tab(&self) -> Vec<Vec<Core>> {
self.to_vec()
}
}
|
use shipyard::*;
use derive_deref::{Deref, DerefMut};
use shipyard_scenegraph::prelude::*;
use crate::mainloop::UpdateTick;
use nalgebra::{Unit, UnitQuaternion, Vector3};
#[derive(Component, Clone, Deref, DerefMut)]
pub struct Spin(pub f64);
pub fn spin_sys(
tick: UniqueView<UpdateTick>,
mut rotations: ViewMut<Rotation>,
mut spins: ViewMut<Spin>,
) {
let UpdateTick {delta} = *tick;
(&mut spins, &mut rotations)
.iter()
.for_each(|(mut spin, mut rotation)| {
let mut value = spin.0 + (delta * 0.1);
if value > 360.0 {
value -= 360.0;
}
spin.0 = value;
let axis = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));
let coords = UnitQuaternion::from_axis_angle(&axis, value.to_radians()).coords;
rotation.coords = coords;
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.