text stringlengths 8 4.13M |
|---|
use std::hashmap::{HashMap, HashSet};
use statemachine::{StateMachine, StateId, Epsilon, StateSet, ToDfaResult, Partitioning};
use regex::{Regex};
struct ScannerDefinition<TokenType> {
prioritized_rules: ~[(Regex, TokenType)]
}
impl<TokenType: Pod+IterBytes+Eq+Clone> ScannerDefinition<TokenType> {
pub fn to_state_machine(&self) -> (StateMachine, StateId, HashMap<StateId, TokenType>) {
// Generate NFA from definition
let (nfa, nfa_start_state, nfa_end_state_to_token_map) = self.to_nfa();
let nfa_end_states = nfa_end_state_to_token_map.keys().map(|x| *x).collect::<StateSet>();
// Generate DFA from NFA
let ToDfaResult { dfa,
start_state: dfa_start_state,
end_state_map: dfa_end_state_map } = nfa.to_dfa(nfa_start_state,
&nfa_end_states);
// Find out which DFA states map to which token
let dfa_end_state_to_token_map = {
// Build an ordering for tokens from the order they appear in the rule set
let token_priority = self.prioritized_rules
.iter()
.enumerate()
.map(|(i, &(_, token))| (token, i))
.collect::<HashMap<TokenType, uint>>();
let mut dfa_end_state_to_token_map = HashMap::<StateId, TokenType>::new();
for (&dfa_end_state, nfa_end_states) in dfa_end_state_map.iter() {
assert!(nfa_end_states.len() >= 1);
let token = nfa_end_states
.iter()
.map(|s_ref| nfa_end_state_to_token_map.get_copy(s_ref))
.min_by(|t_ref| token_priority.get_copy(t_ref))
.unwrap()
.clone();
dfa_end_state_to_token_map.insert(dfa_end_state, token);
}
dfa_end_state_to_token_map
};
// Minimize DFA
let initial_partitioning = {
// Group end states by the token they signify
let token_to_dfa_end_state_map = {
let mut token_to_dfa_end_state_map = HashMap::new();
for (dfa_end_state, token) in dfa_end_state_to_token_map.iter() {
let state_set = token_to_dfa_end_state_map.find_or_insert_with(token,
|_| HashSet::new());
state_set.insert(*dfa_end_state);
}
token_to_dfa_end_state_map
};
// Collect the rest of the state machines states
let non_accepting_states = {
let mut non_accepting_states = dfa.states();
for state_set in token_to_dfa_end_state_map.values() {
for state_id in state_set.iter() {
assert!(non_accepting_states.contains(state_id));
non_accepting_states.remove(state_id);
}
}
non_accepting_states
};
Partitioning(token_to_dfa_end_state_map.values().map(|x| x.clone()).to_owned_vec() +
~[non_accepting_states])
};
// Create minimal DFA
let (minimal_dfa, dfa_to_minimal_dfa_state_map) = dfa.to_minimal(&initial_partitioning);
// Map minimal DFA end states to tokens
let minimal_dfa_end_state_to_token_map = {
let mut minimal_dfa_end_state_to_token_map = HashMap::new();
for dfa_end_state in dfa_end_state_map.keys() {
let minimal_dfa_end_state = dfa_to_minimal_dfa_state_map.get_copy(dfa_end_state);
let token = dfa_end_state_to_token_map.get_copy(dfa_end_state);
minimal_dfa_end_state_to_token_map.insert(minimal_dfa_end_state, token);
}
minimal_dfa_end_state_to_token_map
};
let minimal_dfa_start_state = dfa_to_minimal_dfa_state_map.get_copy(&dfa_start_state);
return (minimal_dfa, minimal_dfa_start_state, minimal_dfa_end_state_to_token_map);
}
fn to_nfa(&self) -> (StateMachine, StateId, HashMap<StateId, TokenType>) {
let mut end_state_to_token = HashMap::new();
let mut nfa = StateMachine::new();
let nfa_start_state = nfa.add_state();
for &(ref regex, token_type) in self.prioritized_rules.iter() {
let (regex_sm, regex_start_state, regex_end_state) = regex.to_state_machine();
end_state_to_token.insert(regex_end_state, token_type);
nfa.consume(regex_sm);
nfa.add_transition(nfa_start_state, regex_start_state, Epsilon);
}
(nfa, nfa_start_state, end_state_to_token)
}
}
struct SlowScanner<TokenType> {
dfa: StateMachine,
start_state: StateId,
end_state_to_token_map: HashMap<StateId, TokenType>,
}
impl<TokenType: Pod+IterBytes+Eq+Clone> SlowScanner<TokenType> {
pub fn new(sd: &ScannerDefinition<TokenType>) -> SlowScanner<TokenType> {
let (dfa, start, end_states) = sd.to_state_machine();
SlowScanner {
dfa: dfa,
start_state: start,
end_state_to_token_map: end_states
}
}
pub fn scan(&self, input: &str) -> Option<TokenType> {
let mut current_state = self.start_state;
let mut state_history = ~[current_state];
for c in input.chars() {
match self.dfa.get_successor_state(current_state, c) {
Some(successor_state) => {
current_state = successor_state;
state_history.push(current_state);
}
None => break
};
}
for state_id in state_history.rev_iter() {
match self.end_state_to_token_map.find_copy(state_id) {
Some(token) => {
return Some(token);
}
None => { /* do nothing */ }
}
}
return None;
}
}
#[cfg(test)]
mod tests {
use super::{ScannerDefinition, SlowScanner};
use regex::{Leaf, Seq, Union};
#[deriving(Eq, IterBytes, Clone)]
enum Token {
A,
B,
C,
}
#[test]
pub fn test_simple() {
let rules = ~[(Leaf('a'), A), (Leaf('b'), B), (Leaf('c'), C)];
let sd = ScannerDefinition {
prioritized_rules: rules
};
let slow_scanner = SlowScanner::new(&sd);
assert_eq!(slow_scanner.scan("a"), Some(A));
assert_eq!(slow_scanner.scan("b"), Some(B));
assert_eq!(slow_scanner.scan("c"), Some(C));
assert_eq!(slow_scanner.scan(""), None);
assert_eq!(slow_scanner.scan("d"), None);
assert_eq!(slow_scanner.scan("0"), None);
assert_eq!(slow_scanner.scan("ab"), Some(A));
assert_eq!(slow_scanner.scan("bc"), Some(B));
assert_eq!(slow_scanner.scan("ca"), Some(C));
}
#[test]
pub fn test_longest_match() {
let rules = ~[(Leaf('a'), A),
(Seq(~Leaf('a'), ~Leaf('a')), B),
(Seq(~Leaf('a'), ~Seq(~Leaf('a'), ~Leaf('a'))), C)];
let sd = ScannerDefinition {
prioritized_rules: rules
};
let slow_scanner = SlowScanner::new(&sd);
assert_eq!(slow_scanner.scan(""), None);
assert_eq!(slow_scanner.scan("a"), Some(A));
assert_eq!(slow_scanner.scan("aa"), Some(B));
assert_eq!(slow_scanner.scan("aaa"), Some(C));
assert_eq!(slow_scanner.scan("aaaa"), Some(C));
assert_eq!(slow_scanner.scan("aaaaaa"), Some(C));
}
#[test]
pub fn test_priority() {
{
let rules = ~[(Leaf('a'), A),
(Union(~Leaf('a'), ~Leaf('b')), B)];
let sd = ScannerDefinition {
prioritized_rules: rules
};
let slow_scanner = SlowScanner::new(&sd);
assert_eq!(slow_scanner.scan(""), None);
assert_eq!(slow_scanner.scan("a"), Some(A));
assert_eq!(slow_scanner.scan("b"), Some(B));
}
{
// Reversed priority
let rules = ~[(Union(~Leaf('a'), ~Leaf('b')), B),
(Leaf('a'), A)];
let sd = ScannerDefinition {
prioritized_rules: rules
};
let slow_scanner = SlowScanner::new(&sd);
assert_eq!(slow_scanner.scan(""), None);
assert_eq!(slow_scanner.scan("a"), Some(B));
assert_eq!(slow_scanner.scan("b"), Some(B));
}
}
} |
use crate::post::Post;
use async_trait::async_trait;
use mockall::predicate::*;
use mockall::*;
#[automock]
#[async_trait]
pub trait PostDb {
async fn get_post_by_id(&self, post_id: i32) -> DomainResult<Option<Post>>;
async fn get_posts(&self, show_all: bool) -> DomainResult<Vec<Post>>;
async fn create_post(&self, title: String, body: String) -> DomainResult<Post>;
async fn post_set_published(&self, post_id: i32, published: bool)
-> DomainResult<Option<Post>>;
}
#[derive(Debug)]
pub struct DomainError {
message: String,
}
pub type DomainResult<T> = Result<T, DomainError>;
impl DomainError {
pub fn new(message: String) -> Self {
Self { message }
}
}
|
use std::error::Error;
use std::sync::mpsc;
use log::{error, info};
use neovim_lib::neovim::Neovim;
use neovim_lib::session::Session;
use simplelog::{Config, Level, LevelFilter, WriteLogger};
pub mod event;
pub mod event_handlers;
pub mod handler;
use crate::event::Event;
use crate::event_handlers::search::search;
use crate::handler::NeovimHandler;
fn main() {
use std::process;
init_logging().expect("scorched earth: unable to initialize logger.");
match start_program() {
Ok(_) => {
info!("exiting");
process::exit(0);
}
Err(msg) => {
error!("{}", msg);
process::exit(1);
}
};
}
fn init_logging() -> Result<(), Box<Error>> {
use std::env;
use std::fs::File;
let _log_level_filter = match env::var("LOG_LEVEL")
.unwrap_or(String::from("trace"))
.to_lowercase()
.as_ref()
{
"debug" => LevelFilter::Debug,
"error" => LevelFilter::Error,
"info" => LevelFilter::Info,
"off" => LevelFilter::Off,
"trace" => LevelFilter::Trace,
"warn" => LevelFilter::Warn,
_ => LevelFilter::Off,
};
let log_level_filter = LevelFilter::Debug;
let config = Config {
time: Some(Level::Error),
level: Some(Level::Error),
target: Some(Level::Error),
location: Some(Level::Error),
time_format: None,
};
let filepath = "./ctrlp.log";
let log_file = File::create(filepath)?;
WriteLogger::init(log_level_filter, config, log_file).unwrap();
Ok(())
}
fn start_program() -> Result<(), Box<Error>> {
info!("Connection to neovim");
let (sender, receiver) = mpsc::channel();
let mut session = Session::new_parent()?;
session.start_event_loop_handler(NeovimHandler(sender));
let nvim = Neovim::new(session);
start_event_loop(receiver, nvim);
Ok(())
}
fn start_event_loop(receiver: mpsc::Receiver<Event>, mut nvim: Neovim) {
info!("Starting event loop");
loop {
info!("Waiting");
let payload = receiver.recv();
match payload {
Ok(Event::Shutdown) => {
info!("Shutting down");
break;
}
Ok(Event::Search) => {
search(Event::Shutdown, &nvim);
}
_ => info!("unhandled event"),
}
}
}
|
use super::status;
use actix_web::{HttpMessage, HttpRequest, HttpResponse, dev::HttpResponseBuilder, State, Json, AsyncResponder, FutureResponse};
use futures::Future;
use share::state::AppState;
use model::user::{SignupUser, SigninUser};
pub fn signup((signup_user, state): (Json<SignupUser>, State<AppState>)) -> FutureResponse<HttpResponse> {
state.db.send(SignupUser{
username: signup_user.username.clone(),
email: signup_user.email.clone(),
password: signup_user.password.clone(),
confirm_password: signup_user.confirm_password.clone(),
})
.from_err()
.and_then(|res| {
match res {
Ok(signup_msg) => Ok(status(&signup_msg.status).json(signup_msg)),
Err(_) => Ok(HttpResponse::InternalServerError().into())
}
}).responder()
}
pub fn signin((signin_user, state): (Json<SigninUser>, State<AppState>)) -> FutureResponse<HttpResponse> {
state.db.send(SigninUser{
username: signin_user.username.clone(),
password: signin_user.password.clone(),
}).from_err()
.and_then(|res| {
match res {
Ok(signin_msg) => Ok(status(&signin_msg.status).json(signin_msg)),
Err(_) => Ok(HttpResponse::InternalServerError().into())
}
}).responder()
}
|
#[doc = "Reader of register CFGR"]
pub type R = crate::R<u32, super::CFGR>;
#[doc = "Writer for register CFGR"]
pub type W = crate::W<u32, super::CFGR>;
#[doc = "Register CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `MCOPRE`"]
pub type MCOPRE_R = crate::R<u8, u8>;
#[doc = "Reader of field `MCOSEL`"]
pub type MCOSEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `MCOSEL`"]
pub struct MCOSEL_W<'a> {
w: &'a mut W,
}
impl<'a> MCOSEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 24)) | (((value as u32) & 0x07) << 24);
self.w
}
}
#[doc = "Reader of field `PPRE`"]
pub type PPRE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PPRE`"]
pub struct PPRE_W<'a> {
w: &'a mut W,
}
impl<'a> PPRE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12);
self.w
}
}
#[doc = "Reader of field `HPRE`"]
pub type HPRE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `HPRE`"]
pub struct HPRE_W<'a> {
w: &'a mut W,
}
impl<'a> HPRE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Reader of field `SWS`"]
pub type SWS_R = crate::R<u8, u8>;
#[doc = "Reader of field `SW`"]
pub type SW_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SW`"]
pub struct SW_W<'a> {
w: &'a mut W,
}
impl<'a> SW_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
impl R {
#[doc = "Bits 28:30 - Microcontroller clock output prescaler"]
#[inline(always)]
pub fn mcopre(&self) -> MCOPRE_R {
MCOPRE_R::new(((self.bits >> 28) & 0x07) as u8)
}
#[doc = "Bits 24:26 - Microcontroller clock output"]
#[inline(always)]
pub fn mcosel(&self) -> MCOSEL_R {
MCOSEL_R::new(((self.bits >> 24) & 0x07) as u8)
}
#[doc = "Bits 12:14 - APB prescaler"]
#[inline(always)]
pub fn ppre(&self) -> PPRE_R {
PPRE_R::new(((self.bits >> 12) & 0x07) as u8)
}
#[doc = "Bits 8:11 - AHB prescaler"]
#[inline(always)]
pub fn hpre(&self) -> HPRE_R {
HPRE_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 3:5 - System clock switch status"]
#[inline(always)]
pub fn sws(&self) -> SWS_R {
SWS_R::new(((self.bits >> 3) & 0x07) as u8)
}
#[doc = "Bits 0:2 - System clock switch"]
#[inline(always)]
pub fn sw(&self) -> SW_R {
SW_R::new((self.bits & 0x07) as u8)
}
}
impl W {
#[doc = "Bits 24:26 - Microcontroller clock output"]
#[inline(always)]
pub fn mcosel(&mut self) -> MCOSEL_W {
MCOSEL_W { w: self }
}
#[doc = "Bits 12:14 - APB prescaler"]
#[inline(always)]
pub fn ppre(&mut self) -> PPRE_W {
PPRE_W { w: self }
}
#[doc = "Bits 8:11 - AHB prescaler"]
#[inline(always)]
pub fn hpre(&mut self) -> HPRE_W {
HPRE_W { w: self }
}
#[doc = "Bits 0:2 - System clock switch"]
#[inline(always)]
pub fn sw(&mut self) -> SW_W {
SW_W { w: self }
}
}
|
use yew::prelude::*;
use yew_router::components::RouterAnchor;
use crate::app::AppRoute;
use super::applications::SocialApplications;
use super::tab_settings::TabSettings;
pub enum Content {
Settings,
Applications
}
pub struct SocialSettings {
content: Content,
link: ComponentLink<Self>
}
pub enum Msg {
ChangeContent(Content)
}
impl Component for SocialSettings {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
SocialSettings {
content: Content::Settings,
link
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeContent(content) => {
self.content = content;
true
}
}
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
type Anchor = RouterAnchor<AppRoute>;
html! {
<div
class="py-5 px-4 m-auto"
style="max-width: 1048px; font-size:14px;"
>
<Anchor
route=AppRoute::SocialHome
classes="text-decoration-none domain-link-dark"
>
<i class="bi bi-arrow-left me-2"></i>
{"Social Connections"}
</Anchor>
<div
class="d-flex mb-5 mt-3"
>
<div
style="flex: 0 0 auto; width: 64px; height: 64px;"
class="d-flex justify-content-center align-items-center rounded me-4 border"
>
<img
src="/assets/icons/google-avatar.png"
class="w-50"
/>
</div>
<div
class="d-flex flex-column"
>
<h2>{"google-oauth2"}</h2>
<div
class="text-muted"
>
<span
class="me-4"
>
{"Google / Gmail"}
</span>
<span>
{"Identifier"}
</span>
<span
class="rounded ms-2"
style="
background-color: #eff0f2;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
font-size: 14px;
padding: 2px 6px;
font-family: 'Roboto Mono', monospace;
"
>
{"con_qgZPycWvQ4BBRzcY"}
</span>
</div>
</div>
</div>
<div
class="mb-4"
>
<ul class="nav nav-tabs">
<li
onclick=self.link.callback(|_| Msg::ChangeContent(Content::Settings))
class="nav-item"
>
<a
// class="nav-link active"
class={
match self.content {
Content::Settings => "nav-link active",
_ => "nav-link"
}
}
aria-current="page"
href="#"
>
{"Settings"}</a>
</li>
<li
onclick=self.link.callback(|_| Msg::ChangeContent(Content::Applications))
class="nav-item">
<a
// class="nav-link"
class={
match self.content {
Content::Applications => "nav-link active",
_ => "nav-link"
}
}
href="#">{"Applications"}</a>
</li>
</ul>
</div>
// <Quickstart/>
// <TabSettings/>
{
match self.content {
Content::Applications => html! { <SocialApplications/> },
Content::Settings => html! { <TabSettings/> }
}
}
</div>
}
}
}
|
mod requests;
fn main() {
// grab the top posts
let arr = requests::top();
// then iterate `up to a limit` and grab links
println!("this is my first post {}\n\n", *arr.get(0).unwrap());
let post_id: u64;
post_id = arr[0].as_u64().unwrap();
requests::call_item(post_id);
}
|
extern crate clonedir_lib;
use self::clonedir_lib::clonedir;
use flate2::read::GzDecoder;
use reqwest;
use serde_json;
use std::fs;
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
use tar::Archive;
pub fn extract_tarball<P: AsRef<Path>, Q: AsRef<Path>>(url: &str, cache: P, to: Q) {
extract_tarball_raw(&url, &cache);
clonedir(&cache, &to).unwrap();
}
fn extract_tarball_raw<P: AsRef<Path>>(url: &str, to: P) {
fn get_real_path(parent: &Path, child: &Path) -> PathBuf {
let child = if child.starts_with("package") {
child.strip_prefix("package").unwrap()
} else {
child
};
let path = parent.join(child);
if !path.starts_with(parent) {
panic!("invalid tarball");
}
path
}
println!("fetching {:?}", url);
let response = reqwest::get(url).unwrap();
let ungzip = GzDecoder::new(response);
let mut archive = Archive::new(ungzip);
for file in archive.entries().unwrap() {
let mut file = file.unwrap();
let kind = file.header().entry_type();
let path = file.path().unwrap().into_owned();
if kind.is_pax_global_extensions() {
break;
}
let path = get_real_path(to.as_ref(), &path);
debug!("{:?} {:?}", kind, path);
if kind.is_dir() {
fs::create_dir_all(path).unwrap();
} else if kind.is_file() {
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut output = File::create(&path).unwrap();
io::copy(&mut file, &mut output).unwrap();
}
}
create_integrity(&to);
}
fn create_integrity<P: AsRef<Path>>(path: P) {
let integrity = Integrity {
method: String::from("sha256"),
hash: String::from("foo"),
};
let f = File::create(path.as_ref().join(".nd-integrity")).unwrap();
serde_json::to_writer(f, &integrity).unwrap();
}
#[derive(Serialize, Deserialize)]
struct Integrity {
method: String,
hash: String,
}
#[cfg(test)]
mod tests {
use super::*;
fn setup<P: AsRef<Path>>(p: P) {
fs::remove_dir_all(p).unwrap_or(());
}
fn teardown<P: AsRef<Path>>(p: P) {
fs::remove_dir_all(p).unwrap_or(());
}
#[test]
fn extracts_package() {
let p = PathBuf::from("tmp/refresh/1");
setup(&p);
extract_tarball(
"https://registry.npmjs.org/edon-test-c/-/edon-test-c-1.0.0.tgz",
p.join("cache"),
p.join("output"),
);
fs::read_to_string(p.join("output").join("package.json")).unwrap();
fs::read_to_string(p.join("cache").join("package.json")).unwrap();
teardown(&p);
}
}
|
// 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.
//! Test tools for serving TUF repositories.
use {
crate::repo::{get, Repository},
failure::Error,
fidl_fuchsia_pkg_ext::RepositoryConfig,
fuchsia_async::{self as fasync, net::TcpListener, EHandle},
fuchsia_url::pkg_url::RepoUrl,
futures::{
compat::Future01CompatExt,
future::{ready, BoxFuture, RemoteHandle},
prelude::*,
task::SpawnExt,
},
hyper::{header, service::service_fn, Body, Method, Request, Response, Server, StatusCode},
std::{
net::{Ipv4Addr, SocketAddr},
path::{Path, PathBuf},
sync::Arc,
},
};
/// A builder to construct a test repository server.
pub struct ServedRepositoryBuilder {
repo: Arc<Repository>,
uri_path_override_handler: Option<Arc<dyn UriPathHandler>>,
}
/// Override how a `ServedRepository` responds to GET requests on valid URI paths.
/// Useful for injecting failures.
pub trait UriPathHandler: 'static + Send + Sync {
/// `response` is what the server would have responded with.
fn handle(&self, uri_path: &Path, response: Response<Body>) -> BoxFuture<Response<Body>>;
}
struct PassThroughUriPathHandler;
impl UriPathHandler for PassThroughUriPathHandler {
fn handle(&self, _uri_path: &Path, response: Response<Body>) -> BoxFuture<Response<Body>> {
ready(response).boxed()
}
}
impl ServedRepositoryBuilder {
pub(crate) fn new(repo: Arc<Repository>) -> Self {
ServedRepositoryBuilder { repo, uri_path_override_handler: None }
}
/// Override how the `ServedRepositoryBuilder` responds to some URI paths.
pub fn uri_path_override_handler(mut self, handler: impl UriPathHandler) -> Self {
self.uri_path_override_handler = Some(Arc::new(handler));
self
}
/// Spawn the server on the current executor, returning a handle to manage the server.
pub fn start(self) -> Result<ServedRepository, Error> {
let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0);
let (connections, addr) = {
let listener = TcpListener::bind(&addr)?;
let local_addr = listener.local_addr()?;
(listener.accept_stream().map_ok(|(conn, _addr)| conn.compat()), local_addr)
};
let root = self.repo.path();
let uri_path_override_handler =
self.uri_path_override_handler.unwrap_or(Arc::new(PassThroughUriPathHandler));
let service = move || {
let root = root.clone();
let uri_path_override_handler = uri_path_override_handler.clone();
service_fn(move |req| {
ServedRepository::handle_tuf_repo_request(
root.clone(),
uri_path_override_handler.clone(),
req,
)
.boxed()
.compat()
})
};
let (stop, rx_stop) = futures::channel::oneshot::channel();
let (server, wait_stop) = Server::builder(connections.compat())
.executor(EHandle::local().compat())
.serve(service)
.with_graceful_shutdown(rx_stop.compat())
.compat()
.unwrap_or_else(|e| panic!("error serving repo over http: {}", e))
.remote_handle();
fasync::spawn(server);
Ok(ServedRepository { repo: self.repo, stop, wait_stop, addr })
}
}
/// A [`Repository`] being served over HTTP.
pub struct ServedRepository {
repo: Arc<Repository>,
stop: futures::channel::oneshot::Sender<()>,
wait_stop: RemoteHandle<()>,
addr: SocketAddr,
}
impl ServedRepository {
/// Request the given path served by the repository over HTTP.
pub async fn get(&self, path: impl AsRef<str>) -> Result<Vec<u8>, Error> {
let url = format!("http://127.0.0.1:{}/{}", self.addr.port(), path.as_ref());
get(url).await
}
/// Returns the URL that can be used to connect to this repository from this device.
pub fn local_url(&self) -> String {
format!("http://127.0.0.1:{}", self.addr.port())
}
/// Generate a [`RepositoryConfig`] suitable for configuring a package resolver to use this
/// served repository.
pub fn make_repo_config(&self, url: RepoUrl) -> RepositoryConfig {
self.repo.make_repo_config(url, self.local_url())
}
/// Gracefully signal the server to stop and returns a future that resolves when it terminates.
pub fn stop(self) -> RemoteHandle<()> {
self.stop.send(()).expect("remote end to still be open");
self.wait_stop
}
async fn handle_tuf_repo_request(
repo: PathBuf,
uri_path_override_handler: Arc<dyn UriPathHandler>,
req: Request<Body>,
) -> Result<Response<Body>, hyper::Error> {
let fail =
|status: StatusCode| Response::builder().status(status).body(Body::empty()).unwrap();
if *req.method() != Method::GET {
return Ok(fail(StatusCode::NOT_FOUND));
} else if req.uri().query().is_some() {
return Ok(fail(StatusCode::BAD_REQUEST));
}
let uri_path = Path::new(req.uri().path());
// don't let queries escape the repo root.
if uri_path.components().any(|component| component == std::path::Component::ParentDir) {
return Ok(fail(StatusCode::NOT_FOUND));
}
let fs_path = repo.join(uri_path.strip_prefix("/").unwrap_or(uri_path));
// FIXME synchronous IO in an async context.
let data = match std::fs::read(fs_path) {
Ok(data) => data,
Err(ref err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(fail(StatusCode::NOT_FOUND));
}
Err(err) => {
eprintln!("error reading repo file: {}", err);
return Ok(fail(StatusCode::INTERNAL_SERVER_ERROR));
}
};
Ok(uri_path_override_handler
.handle(
uri_path,
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_LENGTH, data.len())
.body(Body::from(data))
.unwrap(),
)
.await)
}
}
#[cfg(test)]
mod tests {
use {super::*, crate::repo::RepositoryBuilder, matches::assert_matches};
#[fuchsia_async::run_singlethreaded(test)]
async fn test_serve_empty() -> Result<(), Error> {
let repo = Arc::new(RepositoryBuilder::new().build().await?);
let served_repo = repo.build_server().start()?;
// no '..' allowed.
assert_matches!(served_repo.get("blobs/../root.json").await, Err(_));
// getting a known file fetches something.
let bytes = served_repo.get("targets.json").await?;
assert_ne!(bytes, Vec::<u8>::new());
// even if it doesn't go through the helper function.
let url = format!("{}/targets.json", served_repo.local_url());
let also_bytes = get(&url).await?;
assert_eq!(bytes, also_bytes);
// requests fail after stopping the server
served_repo.stop().await;
assert_matches!(get(url).await, Err(_));
Ok(())
}
}
|
#![feature(async_await)]
use lambda::lambda;
type Err = Box<dyn std::error::Error + Send + Sync + 'static>;
#[lambda]
#[runtime::main]
async fn main(s: String) -> Result<String, Err> {
Ok(s)
}
|
#![feature(lang_items)] // required for defining the panic handler
#![no_std] // don't link the Rust standard library
#![no_main] // disable all Rust-level entry points
#![feature(try_trait)]
#![feature(asm)]
#![feature(const_fn)]
#![feature(global_asm)]
#[macro_use]
extern crate bitflags;
extern crate x86_64;
extern crate uefi;
use core::ptr;
#[macro_use]
mod macros;
pub mod panic;
pub mod kmain;
mod display;
mod console;
#[path="../../share/uefi_proto.rs"]
mod kernel_proto;
#[path="../../share/color.rs"]
mod color;
global_asm!(include_str!("entry.s"));
#[no_mangle]
pub extern "C" fn memcpy(dst: *mut u8, src: *const u8, count: usize) {
unsafe {
asm!("rep movsb" : : "{rcx}" (count), "{rdi}" (dst), "{rsi}" (src) : "rcx", "rsi", "rdi" : "volatile");
}
}
#[no_mangle]
pub extern "C" fn memset(dst: *mut u8, val: u8, count: usize) {
unsafe {
asm!("rep stosb" : : "{rcx}" (count), "{rdi}" (dst), "{al}" (val) : "rcx", "rdi" : "volatile");
}
}
#[no_mangle]
pub extern "C" fn memcmp(dst: *mut u8, src: *const u8, count: usize) -> isize {
unsafe {
let rv: isize;
asm!("repnz cmpsb ; movq $$0, $0 ; ja 1f; jb 2f; jmp 3f; 1: inc $0 ; jmp 3f; 2: dec $0; 3:" : "=r" (rv) : "{rcx}" (count), "{rdi}" (dst), "{rsi}" (src) : "rcx", "rsi", "rdi" : "volatile");
rv
}
} |
// 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.
// This test makes sure that we don't run into a linker error because of the
// middle::reachable pass missing trait methods with default impls.
// aux-build:issue_38226_aux.rs
// Need -Cno-prepopulate-passes to really disable inlining, otherwise the faulty
// code gets optimized out:
// compile-flags: -Cno-prepopulate-passes -Cpasses=name-anon-globals
extern crate issue_38226_aux;
fn main() {
issue_38226_aux::foo::<()>();
}
|
#[doc = "channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"]
pub type CR = crate::Reg<u32, _CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CR;
#[doc = "`read()` method returns [cr::R](cr::R) reader structure"]
impl crate::Readable for CR {}
#[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"]
impl crate::Writable for CR {}
#[doc = "channel x configuration register"]
pub mod cr;
#[doc = "channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ndtr](ndtr) module"]
pub type NDTR = crate::Reg<u32, _NDTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _NDTR;
#[doc = "`read()` method returns [ndtr::R](ndtr::R) reader structure"]
impl crate::Readable for NDTR {}
#[doc = "`write(|w| ..)` method takes [ndtr::W](ndtr::W) writer structure"]
impl crate::Writable for NDTR {}
#[doc = "channel x number of data register"]
pub mod ndtr;
#[doc = "channel x peripheral address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [par](par) module"]
pub type PAR = crate::Reg<u32, _PAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PAR;
#[doc = "`read()` method returns [par::R](par::R) reader structure"]
impl crate::Readable for PAR {}
#[doc = "`write(|w| ..)` method takes [par::W](par::W) writer structure"]
impl crate::Writable for PAR {}
#[doc = "channel x peripheral address register"]
pub mod par;
#[doc = "channel x memory address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mar](mar) module"]
pub type MAR = crate::Reg<u32, _MAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MAR;
#[doc = "`read()` method returns [mar::R](mar::R) reader structure"]
impl crate::Readable for MAR {}
#[doc = "`write(|w| ..)` method takes [mar::W](mar::W) writer structure"]
impl crate::Writable for MAR {}
#[doc = "channel x memory address register"]
pub mod mar;
|
use quote::ToTokens;
use syn::{
visit_mut::{self, VisitMut},
*,
};
use crate::utils::*;
pub(super) fn collect_impl_trait(args: &mut Vec<Path>, ty: &mut Type) {
fn to_trimed_string(path: &Path) -> String {
path.to_token_stream().to_string().replace(" ", "")
}
let mut traits = Vec::new();
CollectImplTrait::new(&mut traits).visit_type_mut(ty);
traits.into_iter().for_each(|t| {
if !args.contains(&t) && TRAITS.contains(&&*to_trimed_string(&t)) {
args.push(t);
}
});
}
struct CollectImplTrait<'a> {
traits: &'a mut Vec<Path>,
}
impl<'a> CollectImplTrait<'a> {
fn new(traits: &'a mut Vec<Path>) -> Self {
Self { traits }
}
}
impl VisitMut for CollectImplTrait<'_> {
fn visit_type_impl_trait_mut(&mut self, node: &mut TypeImplTrait) {
visit_mut::visit_type_impl_trait_mut(self, node);
node.bounds.iter().for_each(|ty| {
if let TypeParamBound::Trait(ty) = ty {
self.traits.push(path(ty.path.segments.iter().map(|ty| ty.ident.clone().into())));
}
});
}
}
const TRAITS: &[&str] = &[
"Clone",
"Copy",
"PartialEq",
"Eq",
"PartialOrd",
"Ord",
"Hash",
// core
"AsRef",
"AsMut",
"Debug",
"fmt::Debug",
"Display",
"fmt::Display",
"fmt::Binary",
"fmt::LowerExp",
"fmt::LowerHex",
"fmt::Octal",
"fmt::Pointer",
"fmt::UpperExp",
"fmt::UpperHex",
"fmt::Write",
"Iterator",
"DoubleEndedIterator",
"ExactSizeIterator",
"FusedIterator",
"TrustedLen",
"Extend",
"Deref",
"DerefMut",
"Index",
"IndexMut",
"RangeBounds",
"Fn",
"FnMut",
"FnOnce",
"Generator",
"Future",
// std
"Read",
"io::Read",
"BufRead",
"io::BufRead",
"Write",
"io::Write",
"Seek",
"io::Seek",
"Error",
"error::Error",
];
|
mod string_decode;
mod string_encode;
mod wire_decode;
mod wire_encode;
pub use string_decode::*;
pub use string_encode::*;
pub use wire_decode::*;
pub use wire_encode::*;
|
use std;
use na::*;
use math::*;
use renderer::*;
use alga::general::*;
use std::rc::Rc;
use std::cell::RefCell;
use num::PrimInt;
use std::collections::HashMap;
use qef_bindings::*;
//uniform manifold dual contouring is a modification to dual marching cubes (hermite extension to dual marching cubes)
//dual marching cubes (modification, by Nielson, to original marching cubes)
//taken from:
//https://stackoverflow.com/questions/16638711/dual-marching-cubes-table
//original work:
//https://vis.computer.org/vis2004/DVD/vis/papers/nielson2.pdf
//256 x 16
pub fn edge_table() -> Vec< Vec< isize > >{
vec![
vec![-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 8, 3, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 8, 3, -1, 1, 2, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![9, 0, 2, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![10, 2, 3, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 8, 11, 2, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 9, 0, -1, 2, 3, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![8, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 7, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 8, 4, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 7, 9, -2, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 8, 4, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 0, 3, 7, 4, -2, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 10, 9, -1, 8, 7, 4, -2, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 7, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![8, 4, 7, -1, 3, 11, 2, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 4, 7, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![9, 0, 1, -1, 8, 4, 7, -1, 2, 3, 11, -2, -1, -1, -1, -1],
vec![1, 2, 4, 7, 9, 11, -2, -1, -1, -1, -1, -1-1, -1, -1, -1, -1],
vec![3, 11, 10, 1, -1, 8, 7, 4, -2, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 7, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 7, 8, -1, 0, 3, 11, 10, 9, -2, -1, -1, -1, -1, -1, -1],
vec![4, 7, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![9, 5, 4, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![9, 5, 4, -1, 0, 8, 3, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 5, 4, 1, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 5, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 9, 5, 4, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 0, 8, -1, 1, 2, 10, -1, 4, 9, 5, -2, -1, -1, -1, -1],
vec![0, 2, 4, 5, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 5, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![9, 5, 4, -1, 2, 3, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![9, 4, 5, -1, 0, 2, 11, 8, -2, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -1, 0, 4, 5, 1, -2, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 5, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 10, 1, -1, 9, 4, 5, -2, -1, -1, -1, -1, -1, -1, -1],
vec![4, 9, 5, -1, 0, 1, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 5, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 4, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 7, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 5, 7, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 5, 7, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 5, 3, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 8, 7, 5, 9, -2, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 0, 3, 7, 5, 9, -2, -1, -1, -1, -1, -1, -1],
vec![0, 2, 5, 7, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 5, 7, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 11, -1, 5, 7, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 5, 7, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 11, -1, 0, 1, 5, 7, 8, -2, -1, -1, -1, -1, -1, -1],
vec![1, 2, 5, 7, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 10, 1, -1, 8, 7, 5, 9, -2, -1, -1, -1, -1, -1, -1],
vec![0, 1, 5, 7, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 5, 7, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 7, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 6, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 8, -1, 10, 5, 6, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 10, 5, 6, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![10, 5, 6, -1, 3, 8, 9, 1, -2, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 5, 6, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 8, -1, 1, 2, 6, 5, -2, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 5, 6, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 5, 6, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -1, 10, 6, 5, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![10, 5, 6, -1, 0, 8, 2, 11, -2, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -1, 0, 1, 9, -1, 10, 5, 6, -2, -1, -1, -1, -1],
vec![10, 5, 6, -1, 11, 2, 8, 9, 1, -2, -1, -1, -1, -1, -1, -1],
vec![1, 3, 5, 6, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 5, 6, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 5, 6, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 6, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![8, 7, 4, -1, 5, 6, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 6, 10, -1, 0, 3, 4, 7, -2, -1, -1, -1, -1, -1, -1, -1],
vec![10, 5, 6, -1, 1, 9, 0, -1, 8, 7, 4, -2, -1, -1, -1, -1],
vec![10, 5, 6, -1, 7, 4, 9, 1, 3, -2, -1, -1, -1, -1, -1, -1],
vec![8, 7, 4, -1, 1, 2, 6, 5, -2, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 7, 4, -1, 1, 2, 6, 5, -2, -1, -1, -1, -1, -1, -1],
vec![8, 7, 4, -1, 0, 9, 2, 5, 6, -2, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 5, 6, 7, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -1, 5, 6, 10, -1, 8, 7, 4, -2, -1, -1, -1, -1],
vec![10, 5, 6, -1, 0, 2, 11, 7, 4, -2, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -1, 0, 1, 9, -1, 10, 5, 6, -1, 8, 7, 4, -2],
vec![10, 5, 6, -1, 7, 4, 11, 2, 1, 9, -2, -1, -1, -1, -1, -1],
vec![8, 7, 4, -1, 3, 11, 6, 5, 1, -2, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 5, 6, 7, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![8, 7, 4, -1, 6, 5, 9, 0, 11, 3, -2, -1, -1, -1, -1, -1],
vec![4, 5, 6, 7, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 6, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 8, -1, 9, 10, 6, 4, -2, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 6, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 6, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 6, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 8, -1, 1, 2, 4, 6, 9, -2, -1, -1, -1, -1, -1, -1],
vec![0, 2, 4, 6, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 6, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![11, 2, 3, -1, 9, 4, 10, 6, -2, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 11, 8, -1, 9, 4, 6, 10, -2, -1, -1, -1, -1, -1, -1],
vec![2, 3, 11, -1, 0, 1, 4, 6, 10, -2, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 6, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 6, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 6, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 6, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 6, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![6, 7, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 6, 7, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 6, 7, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 6, 7, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 6, 7, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 2, 3, 6, 7, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 6, 7, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 6, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -1, 10, 6, 9, 7, 8, -2, -1, -1, -1, -1, -1, -1],
vec![0, 2, 6, 7, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![3, 11, 2, -1, 8, 7, 0, 1, 10, 6, -2, -1, -1, -1, -1, -1],
vec![1, 2, 6, 7, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 6, 7, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 6, 7, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 6, 7, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![6, 7, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 0, 3, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 0, 9, 1, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 1, 3, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 1, 2, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 1, 2, 10, -1, 0, 3, 8, -2, -1, -1, -1, -1],
vec![11, 7, 6, -1, 0, 9, 10, 2, -2, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 2, 3, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1],
vec![2, 3, 6, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 6, 7, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 3, 2, 6, 7, -2, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 6, 7, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 6, 7, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 6, 7, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 6, 7, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![6, 7, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 6, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 6, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 8, 4, 11, 6, -2, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 6, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 8, 4, 6, 11, -2, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 0, 3, 11, 6, 4, -2, -1, -1, -1, -1, -1, -1],
vec![0, 9, 10, 2, -1, 8, 4, 11, 6, -2, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 6, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 6, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 4, 6, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 2, 3, 8, 4, 6, -2, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 6, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 6, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 6, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 6, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 6, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![6, 7, 11, -1, 4, 5, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![6, 7, 11, -1, 4, 5, 9, -1, 0, 3, 8, -2, -1, -1, -1, -1],
vec![11, 7, 6, -1, 1, 0, 5, 4, -2, -1, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 8, 3, 1, 5, 4, -2, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 4, 5, 9, -1, 1, 2, 10, -2, -1, -1, -1, -1],
vec![11, 7, 6, -1, 4, 5, 9, -1, 1, 2, 10, -1, 0, 3, 8, -2],
vec![11, 7, 6, -1, 0, 2, 10, 5, 4, -2, -1, -1, -1, -1, -1, -1],
vec![11, 7, 6, -1, 8, 3, 2, 10, 5, 4, -2, -1, -1, -1, -1, -1],
vec![4, 5, 9, -1, 3, 2, 6, 7, -2, -1, -1, -1, -1, -1, -1, -1],
vec![4, 5, 9, -1, 2, 0, 8, 7, 6, -2, -1, -1, -1, -1, -1, -1],
vec![3, 2, 6, 7, -1, 0, 1, 5, 4, -2, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 5, 6, 7, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![9, 4, 5, -1, 1, 10, 6, 7, 3, -2, -1, -1, -1, -1, -1, -1],
vec![9, 4, 5, -1, 6, 10, 1, 0, 8, 7, -2, -1, -1, -1, -1, -1],
vec![0, 3, 4, 5, 6, 7, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 5, 6, 7, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 6, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 5, 6, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 5, 6, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 5, 6, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 9, 5, 6, 11, 8, -2, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -1, 9, 0, 3, 11, 6, 5, -2, -1, -1, -1, -1, -1],
vec![0, 2, 5, 6, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 5, 6, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 5, 6, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 5, 6, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 2, 3, 5, 6, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 5, 6, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 5, 6, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 5, 6, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 5, 6, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 6, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 7, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 7, 10, 11, -1, 0, 3, 8, -2, -1, -1, -1, -1, -1, -1, -1],
vec![5, 7, 10, 11, -1, 0, 1, 9, -2, -1, -1, -1, -1, -1, -1, -1],
vec![5, 7, 10, 11, -1, 3, 8, 9, 1, -2, -1, -1, -1, -1, -1, -1],
vec![1, 2, 5, 7, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 5, 7, 11, -1, 0, 3, 8, -2, -1, -1, -1, -1, -1, -1],
vec![0, 2, 5, 7, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 5, 7, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 5, 7, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 5, 7, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 7, 3, 2, 10, 5, -2, -1, -1, -1, -1, -1, -1],
vec![1, 2, 5, 7, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 5, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 5, 7, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 5, 7, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![5, 7, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 5, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 5, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 8, 11, 10, 4, 5, -2, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 5, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 5, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 2, 3, 4, 5, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 4, 5, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 5, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 5, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 4, 5, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -1, 8, 3, 2, 10, 5, 4, -2, -1, -1, -1, -1, -1],
vec![1, 2, 4, 5, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 5, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 5, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 5, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 5, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 7, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 8, -1, 10, 9, 4, 7, 11, -2, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 7, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 7, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 7, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 7, 9, 11, -1, 0, 3, 8, -2, -1, -1, -1, -1, -1],
vec![0, 2, 4, 7, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 7, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 4, 7, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 4, 7, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 2, 3, 4, 7, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 4, 7, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 4, 7, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 4, 7, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 4, 7, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![4, 7, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![8, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 9, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 8, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 10, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 8, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 2, 3, 9, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 8, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 11, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![2, 3, 8, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 2, 9, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 2, 3, 8, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 2, 10, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![1, 3, 8, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 1, 9, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![0, 3, 8, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
vec![-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
]
}
pub fn vertex_num_table() -> Vec<usize>{
vec![
0, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1,
1, 1, 2, 1, 2, 2, 2, 1, 2, 1, 3, 1, 2, 1, 2, 1,
1, 2, 1, 1, 2, 3, 1, 1, 2, 2, 2, 1, 2, 2, 1, 1,
1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 2, 1, 2, 1, 1, 1,
1, 2, 2, 2, 1, 2, 1, 1, 2, 2, 3, 2, 1, 1, 1, 1,
2, 2, 3, 2, 2, 2, 2, 1, 3, 2, 4, 2, 2, 1, 2, 1,
1, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1,
1, 2, 2, 2, 2, 3, 2, 2, 1, 1, 2, 1, 1, 1, 1, 1,
1, 1, 2, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1,
2, 3, 2, 2, 3, 4, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1,
1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 2, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1,
1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1,
1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0
]
}
pub fn corner_points() -> Vec< Vector3<f32> >{
vec![
Vector3::new(0.0,0.0,0.0),
Vector3::new(1.0,0.0,0.0),
Vector3::new(1.0,0.0,1.0), //clockwise starting from zero y min
Vector3::new(0.0,0.0,1.0),
Vector3::new(0.0,1.0,0.0),
Vector3::new(1.0,1.0,0.0), //y max
Vector3::new(1.0,1.0,1.0),
Vector3::new(0.0,1.0,1.0)
]
}
pub fn edge_pairs() -> Vec < Vector2<usize> >{
vec![
Vector2::new(0,1),
Vector2::new(1,2),
Vector2::new(3,2),
Vector2::new(0,3),
Vector2::new(4,5),
Vector2::new(5,6), //5
Vector2::new(7,6), //6
Vector2::new(4,7),
Vector2::new(4,0),
Vector2::new(1,5),
Vector2::new(2,6), //10
Vector2::new(3,7)
]
}
#[derive(Clone, Debug)]
pub struct Cell<T : Real>{
pub densities : [T;8], //sampled densities at each corner, `i` element corresponds to `i` corner vector of `corner_points` fn.
pub hermite_data : HashMap<usize, Plane<T>>, //binding between index of a particular edge of the cell and intersection point and normal for that edge
pub config : usize, //identifier of this particular cell configuration, used in dual marching cubes table
}
#[derive(Clone, Debug)]
pub struct HermiteGrid<T : Real>{
pub a : T,//length of one edge of a cubic cell
pub size : usize, //number of cells along each axis
pub cells : Vec<Option<Cell<T>>>, // length is size^3
//after filling the grid each cell must be initialized (set to Some)
}
impl<T : Real + SupersetOf<f32>> HermiteGrid<T>{
pub fn new(a : T, size : usize) -> HermiteGrid<T>{
let cells = vec![None;(size + 1) * (size + 1) * (size + 1)];
HermiteGrid{a,size,cells}
}
//cell is assumed to be initialized
pub fn get(&self, x : usize, y : usize, z : usize) -> &Cell<T>{
self.cells[z * self.size * self.size + y * self.size + x].as_ref().unwrap()
}
pub fn set(&mut self, x : usize, y : usize, z : usize, value : Cell<T>){
let v = self.size;
self.cells[z * v * v + y * v + x] = Some(value);
}
pub fn get_point(&self, x : usize, y : usize, z : usize) -> Vector3<T>{
Vector3::new(self.a * convert::<f32, T>(x as f32), self.a * convert::<f32, T>(y as f32), self.a * convert::<f32, T>(z as f32))
}
//bounding box of the cell
pub fn cube(&self, x : usize, y : usize, z : usize, offset : Vector3<T>) -> Square3<T>{
Square3{center : offset + Vector3::new(convert::<f32,T>(x as f32 + 0.5) * self.a, convert::<f32,T>(y as f32 + 0.5) * self.a, convert::<f32,T>(z as f32 + 0.5) * self.a), extent: self.a / convert(2.0)}
}
}
//it is assumed that surface is smooth in the area along the line and density at the ends of the line have different signs
//TODO handle multiple intersections per edge ???
fn sample_surface_intersection(line : &Line3<f32>, n : usize, f : &DenFn3<f32>) -> Vector3<f32>{
let ext = line.end - line.start;
let norm = ext.norm();
let dir = ext / norm;
//let mut best_abs = std::f32::MAX;
//let mut best_point : Option<Vector3<f32>> = None;
let mut center = line.start + ext * 0.5;
let mut cur_ext = norm * 0.25;
for _ in 0..n {
let point1 = center - dir * cur_ext;
let point2 = center + dir * cur_ext;
let den1 = f(point1).abs();
let den2 = f(point2).abs();
if den1 <= den2 {
center = point1;
}else{
center = point2;
}
cur_ext *= 0.5;
}
center
}
pub fn sample_normal(point : &Vector3<f32>, eps : f32, f : &DenFn3<f32>) -> Vector3<f32>{
Vector3::new( f(Vector3::new(point.x + eps, point.y, point.z)) - f(Vector3::new(point.x, point.y, point.z)),
f(Vector3::new(point.x, point.y + eps, point.z)) - f(Vector3::new(point.x, point.y, point.z)),
f(Vector3::new(point.x, point.y, point.z + eps)) - f(Vector3::new(point.x, point.y, point.z)) ).normalize()
}
fn is_const_sign(a : f32, b : f32) -> bool {
if a > 0.0 { b > 0.0} else {b <= 0.0}
}
//outer list corresponds to each vertex to be placed inside the cell
//inner list binds edges according to the EMCT to that vertex
pub fn which_edges_are_signed(table : &Vec< Vec<isize> >, config : usize) -> Vec<Vec<usize>>{
let entry = &table[config];
if entry[0] == -2 {return Vec::with_capacity(0)}
let mut result = Vec::new();
let mut cur_vertex = Vec::new();
for i in 0..entry.len(){ //entry.len() is always 16
let k = entry[i];
if k >= 0 {cur_vertex.push(k as usize)}
else if k == -2 {result.push(cur_vertex);return result}
else { //k == -1
result.push(cur_vertex);
cur_vertex = Vec::new();
}
}
result
}
fn calc_qef(point : &Vector3<f32>, planes : &Vec<Plane<f32>>) -> f32{
let mut qef : f32 = 0.0;
for plane in planes{
let dist_signed = plane.normal.dot(&(point - plane.point));
qef += dist_signed * dist_signed;
}
qef
}
//works bad
//try delta approuch
//start from the center then find a direction in which qef increases most and move a bit along it
fn solve_qef_iterative(square : &Square3<f32>, threshold : f32, planes : &Vec<Plane<f32>>) -> Vector3<f32>{
let mut vertex = square.center;
let mut next_iter = vertex;
while threshold < calc_qef(&vertex, planes){
let mut qef : f32 = 0.0; //TODO
for plane in planes{
let dist_signed = plane.normal.dot(&(vertex - plane.point));
qef += dist_signed * dist_signed;
next_iter += plane.normal * dist_signed;
}
vertex = next_iter / (planes.len() as f32) * 0.7;
next_iter = vertex;
}
vertex
}
//works but the error is too great
fn solve_qef_analically_ATA_ATb(planes : &Vec<Plane<f32>>) -> Option<Vector3<f32>>{
let normals : Vec<f32> = planes.iter().flat_map(|x| x.normal.as_slice().to_owned()).collect();
let mut Abs = Vec::with_capacity(normals.len() * 4 / 3);
//let intersections : Vec<f32> = planes.iter().flat_map(|x| x.point.as_slice().to_owned()).collect();
let product : Vec<f32> = planes.iter().map(|x| x.normal.dot(&x.point)).collect();
for i in 0..product.len(){
Abs.push(normals[3 * i]);
Abs.push(normals[3 * i + 1]);
Abs.push(normals[3 * i + 2]);
Abs.push(product[i]);
}
let A = DMatrix::from_row_slice(normals.len() / 3, 3, normals.as_slice());
let ATA = (&A).transpose() * &A;
let b = DMatrix::from_row_slice(product.len(), 1, product.as_slice());
let ATb = (&A).transpose() * &b;
let Ab = DMatrix::from_row_slice(planes.len(), 4, Abs.as_slice());
let bTb = (&b).transpose() * (&b);
let mag = bTb.norm();
let qr = ATA.qr();
let solved = qr.solve(&ATb);
if solved.is_some(){
Some(Vector3::new(solved.as_ref().unwrap()[0], solved.as_ref().unwrap()[1], solved.as_ref().unwrap()[2]))
}else{
None
}
}
fn solve_qef_analically_qr(planes : &Vec<Plane<f32>>, bounds : &Square3<f32>) -> Vector3<f32>{
let mut masspoint = Vector4::zeros();
let normals : Vec<f32> = planes.iter().flat_map(|x| {
masspoint += Vector4::new(x.point.x, x.point.y, x.point.z, 1.0);
x.normal.as_slice().to_owned()
}).collect();
let mut Abs = Vec::with_capacity(normals.len() * 4 / 3);
//let intersections : Vec<f32> = planes.iter().flat_map(|x| x.point.as_slice().to_owned()).collect();
let product : Vec<f32> = planes.iter().map(|x| x.normal.dot(&x.point)).collect();
for i in 0..product.len(){
Abs.push(normals[3 * i]);
Abs.push(normals[3 * i + 1]);
Abs.push(normals[3 * i + 2]);
Abs.push(product[i]);
}
let Ab = DMatrix::from_row_slice(planes.len(), 4, Abs.as_slice());
let qr1 = Ab.qr();
let R = qr1.r();
//println!("R : {}", &R);
let A1 = R.slice((0,0), (3,3));
let b1 = R.slice((0,3), (3,1));
let a1 = A1.fixed_slice::<U3,U3>(0,0);
//println!("A1 : {}", &A1);
//println!("b1 : {}", &b1);
let qr2 = A1.qr();
//println!("{}", a1.determinant().abs());
//let det = a1.determinant().abs();
let try = qr2.solve(&Vector3::new(b1[0], b1[1], b1[2]));
let solution =
match try{
Some(min) => {
if point3_inside_sphere_inclusive(&min, Sphere{center : bounds.center, rad : 3.0.sqrt() * bounds.extent * 2.0}){
min
}else{
let temp = (masspoint / masspoint.w);
Vector3::new(temp.x, temp.y, temp.z)
}
},
None => {
let temp = (masspoint / masspoint.w);
Vector3::new(temp.x, temp.y, temp.z)
}
};
//let mut r = unsafe{R.get_unchecked(3,3)};
//let svd = A1.svd(true,true);
//let sol = svd.solve(&b1,0.0); //does not want to work
//Some(Vector3::new(sol[0], sol[1], sol[2]))
solution
}
//minimizer + error
fn solve_qef_via_bindings(planes : &Vec<Plane<f32>>) -> (Vector3<f32>,f32) {
let mut ATA = Matrix3::zeros();
let mut ATb = Vector3::zeros();
let mut accum = Vector4::zeros();
for plane in planes{
qef_add_r(plane.normal, plane.point, &mut ATA, &mut ATb, &mut accum);
}
let mut res = Vector3::zeros();
//println!("{}", &ATb);
//println!("{}", &ATA);
//println!("accum {}", &accum);
let err = qef_solve_r(ATA, ATb, accum, &mut res);
//println!("result is {}", &res);
(res, err)
}
fn sample_qef_brute(square : &Square3<f32>, n : usize, planes : &Vec<Plane<f32>>) -> Vector3<f32> {
let ext = Vector3::new(square.extent, square.extent, square.extent);
let min = square.center - ext;
let mut best_qef = std::f32::MAX;
let mut best_point = min;
for i in 0..n{
for j in 0..n{
for k in 0..n{
let point = min + Vector3::new(ext.x * (2.0 * (i as f32) + 1.0) / (n as f32),
ext.y * (2.0 * (j as f32) + 1.0) / (n as f32),
ext.z * (2.0 * (k as f32) + 1.0) / (n as f32));
let qef = calc_qef(&point, &planes);
if qef < best_qef{
best_qef = qef;
best_point = point;
}
}
}
}
best_point
}
//constructs grid: calculates hermite data and configuration for each cell
//TODO generating triangles write in this function would benefit performance (no extra looping through cells)
pub fn construct_grid<'f>(f : &'f DenFn3<f32>, offset : Vector3<f32>, a : f32, size : usize, accuracy : usize, render_tr_light : &mut RendererVertFragDef, render_debug_lines : &mut RendererVertFragDef) -> HermiteGrid<f32>{
let corners = corner_points();
let edge_pairs = edge_pairs();
let edge_table = edge_table();
//bindings between edge and vertex for each cell
let mut cache : Vec< Option< HashMap<usize, Vector3<f32> > > > = vec![None;size * size * size];
let mut load_cell = |grid : &mut HermiteGrid<f32>, x : usize, y : usize, z : usize, cache : &mut Vec<Option<HashMap<usize,Vector3<f32>>>>|{
let cell_min = offset + Vector3::new(x as f32 * a, y as f32 * a, z as f32 * a);
let bounds = grid.cube(x,y,z,offset);
let mut densities = [0.0;8];
let mut config = 0;
let mut corner_vertex_count = 0;
for i in 0..8{
let p = cell_min + corners[i] * a;
densities[i] = f(p);
if densities[i] < 0.0{
config |= 1 << i;
corner_vertex_count += 1;
}
}
let vertices = which_edges_are_signed(&edge_table, config);
let mut hermite_data = HashMap::new();
let mut cached_cell = HashMap::new();
if vertices.len() >= 1 { //render cells that contain more than 1 vertex
//add_square3_bounds_color(render_debug_lines, bounds.clone(), Vector3::new(1.0,0.0,0.0));
}
for vertex in vertices{
let mut cur_planes = Vec::with_capacity(vertex.len());
for edge_id in &vertex{
let pair = edge_pairs[edge_id.clone()];
let v1 = corners[pair.x];
let v2 = corners[pair.y];
let edge = Line3{start : cell_min + v1 * a, end : cell_min + v2 * a};
let intersection = sample_surface_intersection(&edge, accuracy, f);
let normal = sample_normal(&intersection, 1e-5, f);
let plane = Plane{point : intersection, normal};
hermite_data.insert(edge_id.clone(), plane);
cur_planes.push(plane); //for current vertex QEF processing
}
let is_valid_qef_estimation = |minimizer : &Vector3<f32>| -> bool{
point3_inside_sphere_inclusive(minimizer, Sphere{center : bounds.center, rad : 3.0.sqrt() * bounds.extent * 3.1})
};
//let minimizer_opt = solve_qef_analically_ATA_ATb(&cur_planes);
//let minimizer = if minimizer_opt.is_some() {minimizer_opt.unwrap()} else {bounds.center};
//let minimizer = sample_qef_brute(&bounds, 32, &cur_planes);
// let minimizer = if(corner_vertex_count > 1){
// let try = solve_qef_via_bindings(&cur_planes);
// let minimizer =
// if !is_valid_qef_estimation(&try.0){
// println!("bad minimizer {}", &try.0);
// use rand;
// use rand::Rng;
// use rand::distributions::{Sample, Range};
// let mut rng = rand::thread_rng();
// let mut between = Range::new(0.0, 1.0);
// let r = between.sample(&mut rng);
// let g = between.sample(&mut rng);
// let b = between.sample(&mut rng);
// add_square3_bounds_color(render_debug_lines, bounds.clone(), Vector3::new(r,g,b));
// add_square3_bounds_color(render_debug_lines, Square3{center : try.0, extent : 0.075/4.0}, Vector3::new(r,g,b));
// add_line3_color(render_debug_lines, Line3{start : bounds.center, end : try.0}, Vector3::new(r,g,b));
// for plane in &cur_planes{
// add_square3_bounds_color(render_debug_lines, Square3{center : plane.point, extent : 0.075/4.0}, Vector3::new(r,g,b));
// add_line3_color(render_debug_lines, Line3{start : plane.point, end : plane.point + plane.normal * (0.075)}, Vector3::new(r,g,b));
// }
// try.0
// }else{
// try.0
// };
// minimizer
// }else{
// println!("sampled");
// sample_qef_brute(&bounds, 32, &cur_planes)
// };
let minimizer = solve_qef_analically_qr(&cur_planes, &bounds);
// if !is_valid_qef_estimation(&minimizer){
// println!("bad minimizer {}, det {}, err {}", &minimizer, try.1, calc_qef(&minimizer, &cur_planes));
// use rand;
// use rand::Rng;
// use rand::distributions::{Sample, Range};
// let mut rng = rand::thread_rng();
// let mut between = Range::new(0.0, 1.0);
// let r = between.sample(&mut rng);
// let g = between.sample(&mut rng);
// let b = between.sample(&mut rng);
// add_square3_bounds_color(render_debug_lines, bounds.clone(), Vector3::new(r,g,b));
// add_square3_bounds_color(render_debug_lines, Square3{center : minimizer, extent : 0.075/4.0}, Vector3::new(r,g,b));
// add_line3_color(render_debug_lines, Line3{start : bounds.center, end : minimizer}, Vector3::new(r,g,b));
// for plane in &cur_planes{
// add_square3_bounds_color(render_debug_lines, Square3{center : plane.point, extent : 0.075/4.0}, Vector3::new(r,g,b));
// add_line3_color(render_debug_lines, Line3{start : plane.point, end : plane.point + plane.normal * (0.075)}, Vector3::new(r,g,b));
// }
// }
//add_square3_bounds_color(render_debug_lines, Square3{center : minimizer, extent : 0.075/4.0}, Vector3::new(1.0,1.0,0.0));
for edge_id in &vertex {
cached_cell.insert(edge_id.clone(), minimizer);//duplicates are not possible
}
}
let t = z * size * size + y * size + x;
cache[t] = Some(cached_cell);
let cell = Cell{densities, hermite_data, config};
grid.set(x, y, z, cell);
};
let mut load_cell_cached = |grid : &mut HermiteGrid<f32>, x : usize, y : usize, z : usize, cache : &mut Vec<Option<HashMap<usize,Vector3<f32>>>>|{
let t = z * size * size + y * size + x;
let mut load = false;
{
let cached = cache[t].as_ref();
match cached{
None => load = true,
Some(_) => (),
}
}
let cached = {
if load{
load_cell(grid, x, y, z, cache);
};
cache[t].as_ref().unwrap()
};
cached.clone() //TODO cloning is bad here
};
let mut grid = HermiteGrid::new(a, size);
for y in 0..size-1{
for z in 0..size-1{
for x in 0..size-1{
let cell = load_cell_cached(&mut grid, x,y,z, &mut cache);
for (edge_id, minimizer) in &cell{
let t = minimizer.clone();
match edge_id.clone(){ //TODO add triangle vertex only once, use indexing + culling (decide direction by normal)
5 => {
let r = load_cell_cached(&mut grid, x+1,y,z, &mut cache).get(&7).unwrap().clone();
let ru = load_cell_cached(&mut grid, x+1,y+1,z, &mut cache).get(&3).unwrap().clone();
let u = load_cell_cached(&mut grid, x,y+1,z, &mut cache).get(&1).unwrap().clone();
let normal = &grid.get(x,y,z).hermite_data.get(&5).unwrap().normal;
add_triangle_color_normal(render_tr_light, &Triangle3{p1 : t, p2 : r, p3 : ru}, &Vector3::new(1.0, 1.0, 0.0), normal);
add_triangle_color_normal(render_tr_light, &Triangle3{p1 : t, p2 : ru, p3 : u}, &Vector3::new(1.0, 1.0, 0.0), normal);
},
6 => {
let f = load_cell_cached(&mut grid, x,y,z+1, &mut cache).get(&4).unwrap().clone();
let fu_ = load_cell_cached(&mut grid, x,y+1,z+1, &mut cache);
// let config = grid.get(x,y+1,z+1).config;
// println!("vertex count {:?}, edges: {:?}, map : {:?}", vertex_num_table()[config], edge_table[config], &fu_);
let fu = fu_.get(&0).unwrap().clone();
let u = load_cell_cached(&mut grid, x,y+1,z, &mut cache).get(&2).unwrap().clone();
let normal = &grid.get(x,y,z).hermite_data.get(&6).unwrap().normal;
add_triangle_color_normal(render_tr_light, &Triangle3{p1 : t, p2 : f, p3 : fu}, &Vector3::new(1.0, 1.0, 0.0), normal);
add_triangle_color_normal(render_tr_light, &Triangle3{p1 : t, p2 : fu, p3 : u}, &Vector3::new(1.0, 1.0, 0.0), normal);
},
10 => {
let r_ = load_cell_cached(&mut grid, x+1,y,z, &mut cache);
//let config = grid.get(x+1,y,z).config;
//let config_this = grid.get(x,y,z).config;
//println!("this {:?}, errored {:?}", &edge_table[config_this], &edge_table[config]);
let r = r_.get(&11).unwrap().clone();
let rf = load_cell_cached(&mut grid, x+1,y,z+1, &mut cache).get(&8).unwrap().clone();
let f = load_cell_cached(&mut grid, x,y,z+1, &mut cache).get(&9).unwrap().clone();
let normal = &grid.get(x,y,z).hermite_data.get(&10).unwrap().normal;
add_triangle_color_normal(render_tr_light, &Triangle3{p1 : t, p2 : rf, p3 : r}, &Vector3::new(1.0, 1.0, 0.0), normal);
add_triangle_color_normal(render_tr_light, &Triangle3{p1 : t, p2 : f, p3 : rf}, &Vector3::new(1.0, 1.0, 0.0), normal);
},
_ => ()
}
}
}
}
}
grid
} |
use proconio::input;
fn gcd(x: u32, y: u32) -> u32 {
if y == 0 {
x
} else {
gcd(y, x % y)
}
}
fn main() {
input! {
n: usize,
mut a: [u32; n],
};
a.sort();
let mut g = 0;
for w in a.windows(2) {
g = gcd(g, w[1] - w[0]);
}
if g == 1 {
println!("2");
} else {
println!("1");
}
}
|
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
//
use sha1::Sha1;
use gltf::json::texture;
use gltf::json::Mesh;
use gltf::json::{material::NormalTexture, material::OcclusionTexture};
use gltf::json::{texture::Sampler, Image, Index, Material, Texture};
use crate::{MeldKey, Result, WorkAsset};
/// A trait implemented on glTF objects for which we need a `MeldKey`.
///
/// Please consult [the `MeldKey` documentation](../meld_keys/type.MeldKey.html) for an overview.
pub trait HasKeyForVariants {
/// Computes and returns the `MeldKey` for this object.
///
/// See individual implementations for details.
fn build_meld_key(&self, work_asset: &WorkAsset) -> Result<MeldKey>;
}
impl HasKeyForVariants for Image {
/// The `MeldKey` of an `Image` is a stringified SHA1-hash of the underlying bytes.
///
/// Example: "`daf12297c5c549fa199b85adbe77d626edc93184`"
fn build_meld_key(&self, work_asset: &WorkAsset) -> Result<MeldKey> {
let image_bytes = work_asset.read_image_bytes(self)?;
Ok(Sha1::from(image_bytes).digest().to_string())
}
}
impl HasKeyForVariants for Texture {
/// The `MeldKey` of an `Texture` combines a `Sampler` and an `Image` `MeldKey`.
///
/// Example: "`[sampler=,source=daf12297c5c549fa199b85adbe77d626edc93184]`"
fn build_meld_key(&self, work_asset: &WorkAsset) -> Result<MeldKey> {
Ok(format!(
"[sampler={},source={}]",
key_or_empty(work_asset.sampler_keys(), self.sampler),
key(work_asset.image_keys(), self.source),
))
}
}
impl HasKeyForVariants for Sampler {
/// The `MeldKey` of a `Sampler` is a stringification of simple JSON attributes.
///
/// Example: "`[mag_filter=None,min_filter=None,wrap_s=Repeat,wrap_t=Repeat]`"
fn build_meld_key(&self, _work_asset: &WorkAsset) -> Result<MeldKey> {
Ok(format!(
"[mag_filter={:?},min_filter={:?},wrap_s={:?},wrap_t={:?}]",
self.mag_filter, self.min_filter, self.wrap_s, self.wrap_t
))
}
}
impl HasKeyForVariants for Material {
/// The `MeldKey` of a `Material` combines `Texture` keys with its own many JSON attributes.
///
/// Example: "`[[pbr=[bcf=[1.0, 1.0, 1.0, 1.0], bct=[tc=0,src=[sampler=,source=49ff16b74ed7beabc95d49ef8a0f7615db949851]], mf=0.4, rf=0.6, mrt=[]], nt=[], ot=[], et=[], ef=[0.0, 0.0, 0.0], am=Opaque, ac=0.5, ds=false]`"
fn build_meld_key(&self, work_asset: &WorkAsset) -> Result<MeldKey> {
let pbr = &self.pbr_metallic_roughness;
Ok(format!(
"[[pbr=[bcf={:?}, bct={}, mf={:?}, rf={:?}, mrt={}], nt={}, ot={}, et={}, ef={:?}, am={:?}, ac={:?}, ds={}]",
pbr.base_color_factor,
key_for_texinfo(work_asset, &pbr.base_color_texture),
pbr.metallic_factor,
pbr.roughness_factor,
key_for_texinfo(work_asset, &pbr.metallic_roughness_texture),
key_for_normal_texinfo(work_asset, &self.normal_texture),
key_for_occlusion_texinfo(work_asset, &self.occlusion_texture),
key_for_texinfo(work_asset, &self.emissive_texture),
self.emissive_factor,
self.alpha_mode,
self.alpha_cutoff,
self.double_sided,
))
}
}
impl HasKeyForVariants for Mesh {
/// The `MeldKey` of a `Mesh` is simply its name. This is probably a temporary solution.
///
/// Example: "`polySurface12`"
///
/// Note: It'd be very, very convenient if we can match up meshes by name, because comparing
/// them numerically is kind of a nightmare of fuzzy computational geometry. The question is if
/// the tool can require users to control the glTF level name to the extend necessary.
fn build_meld_key(&self, _work_asset: &WorkAsset) -> Result<MeldKey> {
self.name
.as_ref()
.map(String::from)
.ok_or_else(|| format!("Mesh with no name! Eee."))
}
}
fn key_for_texinfo(work_asset: &WorkAsset, texinfo: &Option<texture::Info>) -> MeldKey {
if let Some(texinfo) = &texinfo {
format!(
"[tc={},src={}]",
texinfo.tex_coord,
key(work_asset.texture_keys(), texinfo.index),
)
} else {
String::from("[]")
}
}
fn key_for_normal_texinfo(work_asset: &WorkAsset, texinfo: &Option<NormalTexture>) -> MeldKey {
if let Some(texinfo) = &texinfo {
format!(
"[s={},tc={},src={}]",
texinfo.scale,
texinfo.tex_coord,
key(work_asset.texture_keys(), texinfo.index),
)
} else {
String::from("[]")
}
}
fn key_for_occlusion_texinfo(
work_asset: &WorkAsset,
texinfo: &Option<OcclusionTexture>,
) -> MeldKey {
if let Some(texinfo) = &texinfo {
format!(
"[s={:?},tc={},src={}]",
texinfo.strength,
texinfo.tex_coord,
key(work_asset.texture_keys(), texinfo.index),
)
} else {
String::from("[]")
}
}
fn key_or_empty<T>(keys: &Vec<MeldKey>, ix: Option<Index<T>>) -> MeldKey {
match ix {
Some(ix) => key(keys, ix),
None => String::new(),
}
}
fn key<T>(keys: &Vec<MeldKey>, ix: Index<T>) -> MeldKey {
keys[ix.value()].to_owned()
}
|
use crate::particles::VectorField;
use crate::{FieldProvider, GPUFieldProvider, State};
#[cfg(target_arch = "wasm32")]
use std::path::PathBuf;
#[cfg(target_arch = "wasm32")]
use stdweb::*;
pub enum FileResult {
OptionsFile(reparser::Options),
VectorField((FieldProvider, GPUFieldProvider)),
}
pub fn reload_file(state: &State) -> Result<FileResult, String> {
let ext = get_ext(state)?;
let data = get_data(state)?;
handle_file_ext(&ext, &data, state)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn get_data(state: &State) -> Result<Vec<u8>, String> {
use std::{fs::File, io::Read};
let path = state
.file_path
.as_ref()
.ok_or_else(|| "No file path saved.".to_owned())?;
let mut file = File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
let mut content = Vec::new();
file.read_to_end(&mut content)
.map_err(|e| format!("Failed to read file: {}", e))?;
Ok(content)
}
#[cfg(target_arch = "wasm32")]
pub fn get_data(_state: &State) -> Result<Vec<u8>, String> {
// Get file extension
let content = js!(return getData();)
.into_string()
.ok_or_else(|| "Failed to get data from JS.".to_owned())?;
let pos = content.find(",").map(|i| i + 1).unwrap_or(0);
let b64 = content.split_at(pos).1;
base64::decode(b64).map_err(|e| format!("Failed to decode base64 content: {}", e))
}
#[cfg(not(target_arch = "wasm32"))]
fn get_ext(state: &State) -> Result<String, String> {
state
.file_path
.as_ref()
.ok_or_else(|| "No file path saved.".to_owned())?
.extension()
.ok_or_else(|| "No file extension.".to_owned())
.map(|s| s.to_string_lossy().into_owned())
}
#[cfg(target_arch = "wasm32")]
fn get_ext(_state: &State) -> Result<String, String> {
let path_str = js!(return getPath();)
.into_string()
.ok_or_else(|| "Failed to get path from JS.".to_owned())?;
let mut path = PathBuf::new();
path.push(path_str);
path.extension()
.ok_or_else(|| "No file extension.".to_owned())
.map(|s| s.to_string_lossy().into_owned())
}
fn handle_file_ext(file_ext: &str, data: &[u8], state: &State) -> Result<FileResult, String> {
match file_ext {
"bincode" => {
let vector_field =
bincode::deserialize(data).map_err(|e| format!("Failed to parse data: {}", e))?;
create_providers(vector_field)
}
"nhdr" => {
let string_rep =
std::str::from_utf8(data).map_err(|e| format!("Parse error: {}", e))?;
Ok(FileResult::OptionsFile(
reparser::Options::from_header_file(string_rep.lines()),
))
}
"raw" => {
let options = state
.options_file
.as_ref()
.ok_or_else(|| "No options file loaded.".to_owned())?;
let data = reparser::load_data_bytes_from_opt(&options, data)?;
let vector_field =
bincode::deserialize(&data).map_err(|e| format!("Failed to parse data: {}", e))?;
create_providers(vector_field)
}
_ => Err("Unknown file extension".to_owned()),
}
}
fn create_providers(vectorfield: VectorField) -> Result<FileResult, String> {
let gpu_field_provider = GPUFieldProvider::new(&vectorfield);
let field_provider = FieldProvider::new(vectorfield);
Ok(FileResult::VectorField((
field_provider,
gpu_field_provider,
)))
}
|
use termion::color;
use termion::cursor;
use termion::style;
use std::collections::HashSet;
use std::fmt;
use std::fmt::Write;
use std::ops::Index;
pub mod square;
pub use self::square::Square;
pub mod generator;
const BORDER_COLOR: color::Fg<color::Rgb> = color::Fg(color::Rgb(220, 220, 220));
const BORDER_TOP: &'static str = "┏━━━┯━━━┯━━━┳━━━┯━━━┯━━━┳━━━┯━━━┯━━━┓";
const BORDER_BOTTOM: &'static str = "┗━━━┷━━━┷━━━┻━━━┷━━━┷━━━┻━━━┷━━━┷━━━┛";
const BORDER_HORIZONTAL_THIN: &'static str = "┠───┼───┼───╂───┼───┼───╂───┼───┼───┨";
const BORDER_HORIZONTAL_THICK: &'static str = "┣━━━┿━━━┿━━━╋━━━┿━━━┿━━━╋━━━┿━━━┿━━━┫";
const BORDER_VERTICAL_THICK: &'static str = "┃";
const BORDER_VERTICAL_THIN: &'static str = "│";
#[derive(Debug, Clone)]
struct GridState {
squares: [[Square; 9]; 9],
current: (usize, usize),
}
#[derive(Debug, Clone)]
pub struct Grid {
state: GridState,
past: Vec<GridState>,
future: Vec<GridState>,
}
impl Grid {
pub fn new(values: [[u8; 9]; 9]) -> Self {
Grid {
state: GridState::new(values),
past: vec![],
future: vec![],
}
}
pub fn from_csv(csv: &str) -> Self {
Grid {
state: GridState::from_csv(csv),
past: vec![],
future: vec![],
}
}
pub fn move_cursor(&mut self, dir: Direction) {
self.past.push(self.state.clone());
self.state.move_cursor(dir);
self.future = vec![];
}
pub fn update_current(&mut self, d: usize) {
self.past.push(self.state.clone());
self.state.update_current(d);
self.future = vec![];
}
pub fn freeze(&mut self) {
self.state.freeze();
}
pub fn permute(&mut self, permutation: Vec<u8>) {
self.state.permute(permutation);
}
pub fn flip_horizontally(&mut self) {
self.state.flip_horizontally();
}
pub fn flip_vertically(&mut self) {
self.state.flip_vertically();
}
pub fn row(&self, row: usize) -> Vec<Square> {
self.state.row(row)
}
pub fn col(&self, col: usize) -> Vec<Square> {
self.state.col(col)
}
pub fn block(&self, y: usize, x: usize) -> Vec<Square> {
self.state.block(y, x)
}
pub fn remove_filled(&mut self) {
self.past.push(self.state.clone());
self.state.remove_filled();
self.future = vec![];
}
pub fn undo(&mut self) {
if let Some(state) = self.past.pop() {
self.future.push(self.state.clone());
self.state = state;
}
}
pub fn redo(&mut self) {
if let Some(state) = self.future.pop() {
self.past.push(self.state.clone());
self.state = state;
}
}
pub fn is_solved(&self) -> bool {
self.state.is_solved()
}
/// Check the grid for inaccuracies
/// and return the problem square locations
pub fn find_invalid_squares(&self) -> HashSet<(usize, usize)> {
self.state.find_invalid_squares()
}
}
impl GridState {
pub fn new(values: [[u8; 9]; 9]) -> Self {
let mut squares = [[Square::Empty; 9]; 9];
for i in 0..9 {
for j in 0..9 {
if values[i][j] == 0 {
squares[i][j] = Square::Empty;
} else {
squares[i][j] = Square::initial(values[i][j]);
}
}
}
GridState {
squares,
current: (0, 0),
}
}
pub fn from_csv(csv: &str) -> Self {
let mut values = [[0; 9]; 9];
let mut i = 0;
let mut j = 0;
for c in csv.chars() {
if c == ',' {
j += 1;
} else if c == '\n' {
i += 1;
j = 0;
} else if c.is_digit(10) {
values[i][j] = c as u8 - b'0';
} else {
panic!("Unknown character in csv: {}", c);
}
}
GridState::new(values)
}
pub fn move_cursor(&mut self, dir: Direction) {
let (i, j) = dir.coords();
let (ci, cj) = self.current;
self.current = ((ci + i) % 9, (cj + j) % 9);
}
pub fn update_current(&mut self, d: usize) {
let (i, j) = self.current;
let sq = &mut self.squares[i][j];
if !sq.is_initial() {
*sq = Square::from_value(d as u8);
}
}
pub fn freeze(&mut self) {
for i in 0..9 {
for j in 0..9 {
self.squares[i][j] = Square::initial(self.squares[i][j].value());
}
}
}
pub fn permute(&mut self, permutation: Vec<u8>) {
assert_eq!(permutation.len(), 9);
assert!((1..10).all(|n| permutation.contains(&n)));
for i in 0..9 {
for j in 0..9 {
if !self.squares[i][j].is_empty() {
let value = self.squares[i][j].value();
self.squares[i][j] = Square::initial(permutation[(value - 1) as usize]);
}
}
}
}
pub fn flip_horizontally(&mut self) {
for i in 0..9 {
self.squares[i].reverse();
}
}
pub fn flip_vertically(&mut self) {
self.squares.reverse();
}
pub fn row(&self, row: usize) -> Vec<Square> {
self.squares[row].to_vec()
}
pub fn col(&self, col: usize) -> Vec<Square> {
let mut column = vec![];
for i in 0..9 {
column.push(self.squares[i][col]);
}
column
}
pub fn block(&self, y: usize, x: usize) -> Vec<Square> {
let mut block = vec![];
for i in y * 3..(y + 1) * 3 {
for j in x * 3..(x + 1) * 3 {
block.push(self.squares[i][j])
}
}
block
}
pub fn remove_filled(&mut self) {
for i in 0..9 {
for j in 0..9 {
if !self.squares[i][j].is_initial() {
self.squares[i][j] = Square::Empty;
}
}
}
}
pub fn is_solved(&self) -> bool {
for i in 0..9 {
for j in 0..9 {
if self.squares[i][j].is_empty() {
return false;
}
}
}
self.find_invalid_squares().is_empty()
}
/// Check the grid for inaccuracies
/// and return the problem square locations
pub fn find_invalid_squares(&self) -> HashSet<(usize, usize)> {
let mut set = HashSet::new();
for i in 0..9 {
for j in 0..9 {
let value = self.squares[i][j].value();
if value != 0 {
// Check the column
for i2 in i + 1..9 {
if self.squares[i2][j].value() == value {
set.insert((i, j));
set.insert((i2, j));
}
}
// Check the row
for j2 in j + 1..9 {
if self.squares[i][j2].value() == value {
set.insert((i, j));
set.insert((i, j2));
}
}
// Check the square
for i2 in prev_multiple(3, i)..next_multiple(3, i) {
for j2 in prev_multiple(3, j)..next_multiple(3, j) {
if i2 == i && j2 == j {
continue;
};
if self.squares[i2][j2].value() == value {
set.insert((i, j));
set.insert((i2, j2));
}
}
}
}
}
}
set
}
}
impl Index<usize> for Grid {
type Output = [Square; 9];
fn index(&self, idx: usize) -> &[Square; 9] {
self.state.index(idx)
}
}
impl Index<usize> for GridState {
type Output = [Square; 9];
fn index(&self, idx: usize) -> &[Square; 9] {
&self.squares[idx]
}
}
impl fmt::Display for Grid {
fn fmt(&self, ff: &mut fmt::Formatter) -> fmt::Result {
self.state.fmt(ff)
}
}
impl fmt::Display for GridState {
fn fmt(&self, ff: &mut fmt::Formatter) -> fmt::Result {
let mistakes = self.find_invalid_squares();
let mut f = "".to_string();
write!(f, "{}{}", BORDER_COLOR, BORDER_TOP)?;
write!(f, "{}{}", cursor::Down(1), cursor::Left(37))?;
for i in 0..9 {
write!(f, "{}{}", BORDER_COLOR, BORDER_VERTICAL_THICK)?;
for j in 0..9 {
let st = if (i, j) == self.current {
format!("{}", style::Invert)
} else {
String::new()
};
let nt = if (i, j) == self.current {
format!("{}", style::NoInvert)
} else {
String::new()
};
let fg = if mistakes.contains(&(i, j)) {
format!("{}", color::Fg(color::Red))
} else if self.squares[i][j].is_initial() {
format!("{}", color::Fg(color::Cyan))
} else {
format!("{}", color::Fg(color::White))
};
write!(f, " {}{}{}{} ", st, fg, self.squares[i][j], nt)?;
write!(f, "{}", BORDER_COLOR)?;
if j % 3 == 2 {
write!(f, "{}", BORDER_VERTICAL_THICK)?;
} else {
write!(f, "{}", BORDER_VERTICAL_THIN)?;
}
}
write!(f, "{}{}", cursor::Down(1), cursor::Left(37))?;
write!(f, "{}", BORDER_COLOR)?;
if i == 8 {
write!(f, "{}", BORDER_BOTTOM)?;
} else if i % 3 == 2 {
write!(f, "{}", BORDER_HORIZONTAL_THICK)?;
} else {
write!(f, "{}", BORDER_HORIZONTAL_THIN)?;
}
write!(f, "{}{}", cursor::Down(1), cursor::Left(37))?;
}
write!(ff, "{}", f)
}
}
fn prev_multiple(a: usize, b: usize) -> usize {
b - (b % a)
}
fn next_multiple(a: usize, b: usize) -> usize {
b + a - (b % a)
}
pub enum Direction {
Right,
Left,
Up,
Down,
}
impl Direction {
pub fn coords(&self) -> (usize, usize) {
match *self {
Direction::Right => (0, 1),
Direction::Left => (0, 8),
Direction::Up => (8, 0),
Direction::Down => (1, 0),
}
}
}
|
extern crate olin;
use log::{error, info};
use olin::env;
use std::str;
/// This tests for https://github.com/CommonWA/cwa-spec/blob/master/ns/env.md
pub extern "C" fn test() -> Result<(), i32> {
info!("running ns::env tests");
info!("env[\"MAGIC_CONCH\"] = \"yes\"");
let envvar_name = "MAGIC_CONCH";
let mut envvar_val = [0u8; 64];
let envvar_val = env::get_buf(envvar_name.as_bytes(), &mut envvar_val)
.map(|s| str::from_utf8(s).expect("envvar wasn't UTF-8"))
.map_err(|e| {
error!("couldn't get: {:?}", e);
1
})?;
if envvar_val != "yes" {
error!("wanted yes, got: {}", envvar_val);
return Err(1);
}
info!("passed");
info!("look for variable that does not exist");
match env::get("DOES_NOT_EXIST") {
Err(env::Error::NotFound) => info!("this does not exist! :D"),
Ok(_) => {
error!("DOES_NOT_EXIST exists");
return Err(1);
}
_ => {
error!("other error");
return Err(2);
}
}
info!("ns::env tests passed");
Ok(())
}
|
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
pub fn say() {
println!("Hi!");
#[cfg(feature = "gpu")]
println!("Hi! feature: gpu");
#[cfg(feature = "opencl")]
println!("Hi! feature: opencl");
}
|
use std::num::Float;
#[derive(Clone)]
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
#[derive(Clone)]
pub struct Point {
pub x: f32,
pub y: f32,
}
#[derive(Clone)]
pub struct Line {
pub start: Point,
pub end: Point,
}
pub struct Circle {
pub center: Point,
pub radius: f32,
pub velocity: Vec2,
}
impl Vec2 {
pub fn between(a: &Point, b: &Point) -> Vec2 {
Vec2 { x: b.x - a.x, y: b.y - a.y }
}
pub fn magnitude(&self) -> f32 {
(self.x * self.x + self.y * self.y).sqrt()
}
pub fn to_unit(&self) -> Vec2 {
let len = self.magnitude();
Vec2 { x: self.x / len, y: self.y / len }
}
pub fn scale(&self, scale: f32) -> Vec2 {
Vec2 { x: self.x * scale, y: self.y * scale }
}
}
impl Line {
pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Line {
Line {
start: Point { x: x1, y: y1 },
end: Point { x: x2, y: y2 },
}
}
pub fn to_unit_vector(&self) -> Vec2 {
Vec2::between(&self.start, &self.end).to_unit()
}
pub fn len(&self) -> f32 {
distance(&self.start, &self.end)
}
}
pub fn dot_product(a: &Vec2, b: &Vec2) -> f32 {
a.x * b.x + a.y * b.y
}
pub fn distance(a: &Point, b: &Point) -> f32 {
let x = a.x - b.x;
let y = a.y - b.y;
(x * x + y * y).sqrt()
}
pub fn closest_point(circle: &Circle, line: &Line) -> Point {
let line_vec = line.to_unit_vector();
let line_end_to_circle = Vec2::between(&line.start, &circle.center);
let dot = dot_product(&line_end_to_circle, &line_vec);
if dot <= 0.0 {
line.start.clone()
} else if dot >= line.len() {
line.end.clone()
} else {
Point {
x: line.start.x + line_vec.x * dot,
y: line.start.y + line_vec.y * dot,
}
}
}
impl Circle {
pub fn new(x: f32, y: f32, r: f32) -> Circle {
Circle {
center: Point { x: x, y: y },
radius: r,
velocity: Vec2 { x: 0.0, y: 0.0 }
}
}
pub fn approx(&self) -> Vec<Line> {
let x = self.center.x;
let y = self.center.y;
let r = self.radius;
let c = 0.7071; // sin(45) = cos(45) = 1/sqrt(2)
vec![
Line::new(x, y+r, x+r*c, y+r*c),
Line::new(x+r*c, y+r*c, x+r, y),
Line::new(x+r, y, x+r*c, y-r*c),
Line::new(x+r*c, y-r*c, x, y-r),
Line::new(x, y-r, x-r*c, y-r*c),
Line::new(x-r*c, y-r*c, x-r, y),
Line::new(x-r, y, x-r*c, y+r*c),
Line::new(x-r*c, y+r*c, x, y+r),
]
}
pub fn distance(&self, line: &Line) -> f32 {
let closest = closest_point(self, line);
distance(&self.center, &closest)
}
pub fn is_intersecting(&self, line: &Line) -> bool {
self.distance(line) < self.radius
}
fn bounce_vector(&self, line: &Line) -> Vec2 {
Vec2::between(&closest_point(self, line), &self.center)
}
pub fn bounce_circle(&mut self, line: &Line) {
let bounce = self.bounce_vector(line);
let bounce_normal = bounce.to_unit();
let dot = dot_product(&self.velocity, &bounce_normal);
let mut len = bounce.magnitude();
if dot >= 0.0 {
len += self.radius;
} else {
len -= self.radius;
}
let displacement = bounce_normal.scale(len);
self.center.x -= 2.0 * displacement.x;
self.center.y -= 2.0 * displacement.y;
self.velocity.x -= 2.0 * dot * bounce_normal.x;
self.velocity.y -= 2.0 * dot * bounce_normal.y;
}
}
|
extern crate basics;
extern crate networking;
extern crate iterator_example;
fn main() {
// run function in basics
//basics::read_file::run().unwrap();
//basics::little_endian_int::run().unwrap();
//basics::random_numbers::run_basic().unwrap();
//basics::random_numbers::run_with_a_range();
//basics::random_numbers::run_with_a_range_independent();
//basics::random_numbers::run_with_given_distribution();
//basics::random_numbers::run_range_for_a_type();
//basics::run_command::run().unwrap();
//basics::multi_regular_expression::run().unwrap();
//basics::lazystatic::run_lazy_static();
//basics::lazystatic::run_lazy_mutable().unwrap();
//basics::regex_text::run_email();
//basics::regex_text::run_hashtags();
//basics::regex_text::run_replace();
//basics::regex_text::run_phone_number().unwrap();
//basics::file_sha_256::run().unwrap();
//basics::operate_bitfield::run();
//basics::memmap_file::run().unwrap();
networking::run();
println!("======================");
iterator_example::run();
}
|
use crate::codec::{Decode, Encode};
use crate::spacecenter::Part;
use crate::{remote_type, RemoteObject};
remote_type!(
/// Represents a servo.
object InfernalRobotics.Servo {
properties: {
{
Name {
/// Returns the name of the servo.
///
/// **Game Scenes**: Flight
get: name -> String,
/// Sets the name of the servo.
///
/// **Game Scenes**: Flight
set: set_name(&str)
}
}
{
Part {
/// Returns the part containing the servo.
///
/// **Game Scenes**: Flight
get: part -> Part
}
}
{
Position {
/// Returns the position of the servo.
///
/// **Game Scenes**: Flight
get: position -> f32
}
}
{
MinConfigPosition {
/// Returns the minimum position of the servo, specified by the part configuration.
///
/// **Game Scenes**: Flight
get: min_config_position -> f32
}
}
{
MaxConfigPosition {
/// Returns the maximum position of the servo, specified by the part configuration.
///
/// **Game Scenes**: Flight
get: max_config_position -> f32
}
}
{
MinPosition {
/// Returns the minimum position of the servo, specified by the in-game tweak menu.
///
/// **Game Scenes**: Flight
get: min_position -> f32,
/// Sets the minimum position of the servo, specified by the in-game tweak menu.
///
/// **Game Scenes**: Flight
set: set_min_position(f32)
}
}
{
MaxPosition {
/// Returns the maximum position of the servo, specified by the in-game tweak menu.
///
/// **Game Scenes**: Flight
get: max_position -> f32,
/// Sets the maximum position of the servo, specified by the in-game tweak menu.
///
/// **Game Scenes**: Flight
set: set_max_position(f32)
}
}
{
ConfigSpeed {
/// Returns the speed multiplier of the servo, specified by the part configuration.
///
/// **Game Scenes**: Flight
get: config_speed -> f32
}
}
{
Speed {
/// Returns the speed multiplier of the servo, specified by the in-game tweak menu.
///
/// **Game Scenes**: Flight
get: speed -> f32,
/// Sets the speed multiplier of the servo, specified by the in-game tweak menu.
///
/// **Game Scenes**: Flight
set: set_speed(f32)
}
}
{
CurrentSpeed {
/// Returns the current speed at which the servo is moving.
///
/// **Game Scenes**: Flight
get: current_speed -> f32,
/// Sets the current speed at which the servo is moving.
///
/// **Game Scenes**: Flight
set: set_current_speed(f32)
}
}
{
Acceleration {
/// Returns the acceleration of the servo.
///
/// **Game Scenes**: Flight
get: acceleration -> f32,
/// Sets the acceleration of the servo.
///
/// **Game Scenes**: Flight
set: set_acceleration(f32)
}
}
{
IsMoving {
/// Returns whether the servo is moving.
///
/// **Game Scenes**: Flight
get: is_moving -> bool
}
}
{
IsFreeMoving {
/// Returns whether the servo is freely moving.
///
/// **Game Scenes**: Flight
get: is_free_moving -> bool
}
}
{
IsLocked {
/// Returns whether the servo is locked.
///
/// **Game Scenes**: Flight
get: is_locked -> bool,
/// Sets whether the servo is locked.
///
/// **Game Scenes**: Flight
set: set_locked(bool)
}
}
{
IsAxisInverted {
/// Returns whether the servos axis is inverted.
///
/// **Game Scenes**: Flight
get: is_axis_inverted -> bool,
/// Sets whether the servos axis is inverted.
///
/// **Game Scenes**: Flight
set: set_axis_inverted(bool)
}
}
}
methods: {
{
/// Moves the servo to the right.
///
/// **Game Scenes**: Flight
fn move_right() {
MoveRight()
}
}
{
/// Moves the servo to the left.
///
/// **Game Scenes**: Flight
fn move_left() {
MoveLeft()
}
}
{
/// Moves the servo to the center.
///
/// **Game Scenes**: Flight
fn move_center() {
MoveCenter()
}
}
{
/// Moves the servo to the next preset.
///
/// **Game Scenes**: Flight
fn move_next_preset() {
MoveNextPreset()
}
}
{
/// Moves the servo to the previous preset.
///
/// **Game Scenes**: Flight
fn move_prev_preset() {
MovePrevPreset()
}
}
{
/// Moves the servo to position and sets the speed multiplier to speed.
///
/// **Game Scenes**: Flight
///
/// # Arguments
/// * `position` - The position to move the servo to.
/// * `speed` - Speed multiplier for the movement.
fn move_to(position: f32, speed: f32) {
MoveTo(position, speed)
}
}
{
/// Stops the servo.
///
/// **Game Scenes**: Flight
fn stop() {
Stop()
}
}
{
/// Sets whether the servo should be highlighted in-game.
///
/// **Game Scenes**: Flight
fn set_highlight(highlight: bool) {
set_Highlight(highlight)
}
}
}
});
|
use super::*;
#[test]
fn part_one_discussion() {
let prog = vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50];
let m = one_off_machine(&prog, None);
assert_eq!(m.read_addr(3), 70);
assert_eq!(m.read_addr(0), 3500);
}
#[test]
fn part_one_example_one() {
let prog = vec![1, 0, 0, 0, 99];
let m = one_off_machine(&prog, None);
assert_eq!(m.read_addr(0), 2);
}
#[test]
fn part_one_example_two() {
let prog = vec![2, 3, 0, 3, 99];
let m = one_off_machine(&prog, None);
assert_eq!(m.read_addr(3), 6);
}
#[test]
fn part_one_example_three() {
let prog = vec![2, 4, 4, 5, 99, 0];
let m = one_off_machine(&prog, None);
assert_eq!(m.read_addr(5), 9801);
}
#[test]
fn part_one_example_four() {
let prog = vec![1, 1, 1, 4, 99, 5, 6, 0, 99];
let m = one_off_machine(&prog, None);
assert_eq!(m.read_addr(0), 30);
assert_eq!(m.read_addr(4), 2);
}
#[test]
fn basic_io() {
let prog = vec![3, 0, 4, 0, 99];
let (m, output) = one_off(&prog, Some(vec![42, 1, 2, 3]));
assert_eq!(m.read_addr(0), 42); // the temp storage
assert_eq!(output, vec![42]); // wrote it out
}
#[test]
fn parameter_modes() {
let prog = vec![1002, 4, 3, 4, 33];
let m = one_off_machine(&prog, None);
assert_eq!(m.read_addr(4), 99);
}
#[test]
fn equals_position() {
let prog = vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8];
let output = one_off_output(&prog, Some(vec![4]));
assert_eq!(output, vec![0]);
let output = one_off_output(&prog, Some(vec![8]));
assert_eq!(output, vec![1]);
let output = one_off_output(&prog, Some(vec![12]));
assert_eq!(output, vec![0]);
}
#[test]
fn equals_immediate() {
let prog = vec![3, 3, 1108, -1, 8, 3, 4, 3, 99];
let output = one_off_output(&prog, Some(vec![4]));
assert_eq!(output, vec![0]);
let output = one_off_output(&prog, Some(vec![8]));
assert_eq!(output, vec![1]);
let output = one_off_output(&prog, Some(vec![12]));
assert_eq!(output, vec![0]);
}
#[test]
fn quine() {
let prog = vec![
109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99,
];
let output = one_off_output(&prog, None);
assert_eq!(prog, output)
}
#[test]
fn compute_16_digit_number() {
let prog = vec![1102, 34915192, 34915192, 7, 4, 7, 99, 0];
let output = one_off_output(&prog, None);
assert_eq!(output[0].to_string().len(), 16)
}
#[test]
fn output_huge_number() {
let n = 1125899906842624;
let prog = vec![104, n, 99];
let output = one_off_output(&prog, None);
assert_eq!(output[0], n)
}
|
mod ingame_bindings;
mod menu_bindings;
pub mod prelude {
pub use super::ingame_bindings::{
IngameActionBinding,
IngameAxisBinding,
IngameBindings,
};
pub use super::menu_bindings::{
MenuActionBinding,
MenuAxisBinding,
MenuBindings,
};
}
pub use ingame_bindings::IngameBindings;
pub use menu_bindings::MenuBindings;
use amethyst::input::InputBundle;
use crate::helpers::resource;
pub fn ingame_input_bundle() -> InputBundle<ingame_bindings::IngameBindings> {
InputBundle::<ingame_bindings::IngameBindings>::new()
.with_bindings_from_file(resource("config/ingame_bindings.ron"))
.unwrap()
}
pub fn menu_input_bundle() -> InputBundle<menu_bindings::MenuBindings> {
InputBundle::<menu_bindings::MenuBindings>::new()
.with_bindings_from_file(resource("config/menu_bindings.ron"))
.unwrap()
}
|
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
type V3 = [f64; 3];
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct Camera {
pub pos: V3,
pub look_at: V3,
pub up: V3,
pub focus_distance: Option<f64>,
#[serde(default = "default_aperture")]
pub aperture: f64,
#[serde(default = "default_fov")]
pub fov: f64,
}
const fn default_aperture() -> f64 {
0.1
}
const fn default_fov() -> f64 {
60.0
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ColorInput {
Color { color: V3 },
Texture { filename: PathBuf },
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Material {
Holdout {
albedo: ColorInput,
},
Lambert {
albedo: ColorInput,
},
Metal {
albedo: ColorInput,
#[serde(default = "default_fuzz")]
fuzz: f64,
},
Dielectric {
albedo: ColorInput,
ior: f64,
},
}
const fn default_fuzz() -> f64 {
0.01
}
#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize)]
pub struct Positioned<T> {
pub(crate) pos: V3,
#[serde(flatten)]
pub(crate) value: T,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SDF {
Sphere {
radius: f64,
},
Plane {
normal: V3,
},
Box {
size: V3,
},
Rounding {
sdf: Box<SDF>,
amount: f64,
},
Union {
left: Positioned<Box<SDF>>,
right: Positioned<Box<SDF>>,
smooth: f64,
},
Intersection {
left: Positioned<Box<SDF>>,
right: Positioned<Box<SDF>>,
smooth: f64,
},
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Object {
Sphere {
pos: V3,
radius: f64,
material: Material,
},
Plane {
pos: V3,
normal: V3,
material: Material,
},
SDF {
pos: V3,
material: Material,
sdf: SDF,
},
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct Scene<W> {
#[serde(default = "default_bounces")]
pub bounces: u32,
#[serde(default = "default_samples")]
pub samples: u32,
pub camera: Camera,
pub world: W,
}
const fn default_samples() -> u32 {
100
}
const fn default_bounces() -> u32 {
100
}
|
use crate::Counter;
use num_traits::Zero;
use std::hash::Hash;
use std::ops::{Sub, SubAssign};
impl<T, N> Sub for Counter<T, N>
where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
{
type Output = Counter<T, N>;
/// Subtract (keeping only positive values).
///
/// `out = c - d;` -> `out[x] == c[x] - d[x]` for all `x`,
/// keeping only items with a value greater than [`N::zero()`].
///
/// [`N::zero()`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// let e = c - d;
///
/// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(e.into_map(), expect);
/// ```
fn sub(mut self, rhs: Counter<T, N>) -> Self::Output {
self -= rhs;
self
}
}
impl<T, N> SubAssign for Counter<T, N>
where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
{
/// Subtract (keeping only positive values).
///
/// `c -= d;` -> `c[x] -= d[x]` for all `x`,
/// keeping only items with a value greater than [`N::zero()`].
///
/// [`N::zero()`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// c -= d;
///
/// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(c.into_map(), expect);
/// ```
fn sub_assign(&mut self, rhs: Self) {
for (key, value) in rhs.map {
let mut remove = false;
if let Some(entry) = self.map.get_mut(&key) {
if *entry >= value {
*entry -= value;
} else {
remove = true;
}
if *entry == N::zero() {
remove = true;
}
}
if remove {
self.map.remove(&key);
}
}
}
}
|
pub use {chunk_render_mesher::*, chunk_render_mesher_system::*, chunk_render_mesher_worker::*};
mod chunk_render_mesher;
mod chunk_render_mesher_system;
mod chunk_render_mesher_worker;
|
// Copyright 2017 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.
// run-pass
// Issue 33903:
// Built-in indexing should be used even when the index is not
// trivially an integer
// Only built-in indexing can be used in constant expressions
const FOO: i32 = [12, 34][0 + 1];
fn main() {}
|
#[doc = "Reader of register SR"]
pub type R = crate::R<u32, super::SR>;
#[doc = "Reader of field `CTEF`"]
pub type CTEF_R = crate::R<bool, bool>;
#[doc = "Reader of field `CTCF`"]
pub type CTCF_R = crate::R<bool, bool>;
#[doc = "Reader of field `CSMF`"]
pub type CSMF_R = crate::R<bool, bool>;
#[doc = "Reader of field `CTOF`"]
pub type CTOF_R = crate::R<bool, bool>;
#[doc = "Reader of field `FTF`"]
pub type FTF_R = crate::R<bool, bool>;
#[doc = "Reader of field `BUSY`"]
pub type BUSY_R = crate::R<bool, bool>;
#[doc = "Reader of field `FLEVEL`"]
pub type FLEVEL_R = crate::R<u8, u8>;
impl R {
#[doc = "Bit 0 - Clear transfer error flag"]
#[inline(always)]
pub fn ctef(&self) -> CTEF_R {
CTEF_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Clear transfer complete flag"]
#[inline(always)]
pub fn ctcf(&self) -> CTCF_R {
CTCF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 3 - Clear status match flag"]
#[inline(always)]
pub fn csmf(&self) -> CSMF_R {
CSMF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Clear timeout flag"]
#[inline(always)]
pub fn ctof(&self) -> CTOF_R {
CTOF_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 2 - FIFO threshold flag"]
#[inline(always)]
pub fn ftf(&self) -> FTF_R {
FTF_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 5 - Busy"]
#[inline(always)]
pub fn busy(&self) -> BUSY_R {
BUSY_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bits 8:13 - FIFO level"]
#[inline(always)]
pub fn flevel(&self) -> FLEVEL_R {
FLEVEL_R::new(((self.bits >> 8) & 0x3f) as u8)
}
}
|
use std::convert::TryFrom;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UbloxRawMsg {
class: u8,
id: u8,
payload: Vec<u8>,
checksum: [u8; 2],
}
impl UbloxRawMsg {
pub fn new(class: u8, id: u8, payload: Vec<u8>) -> Self {
let checksum = Self::calc_checksum(class, id, &payload);
UbloxRawMsg {
class,
id,
payload,
checksum,
}
}
pub fn class(&self) -> u8 {
self.class
}
pub fn id(&self) -> u8 {
self.id
}
pub fn take_payload(self) -> Vec<u8> {
self.payload
}
pub fn checksum(&self) -> [u8; 2] {
self.checksum
}
fn calc_checksum(class: u8, id: u8, payload: &[u8]) -> [u8; 2] {
let mut ck_a = 0u8;
let mut ck_b = 0u8;
let mut consume_byte = |byte| {
ck_a = ck_a.wrapping_add(byte);
ck_b = ck_b.wrapping_add(ck_a);
};
consume_byte(class);
consume_byte(id);
let [l0, l1] = (payload.len() as u16).to_le_bytes();
consume_byte(l0);
consume_byte(l1);
for byte in payload {
consume_byte(*byte);
}
[ck_a, ck_b]
}
}
impl TryFrom<Vec<u8>> for UbloxRawMsg {
type Error = String;
fn try_from(bytes: Vec<u8>) -> Result<Self, String> {
if &bytes[0..2] != &[0xb5, 0x62] {
return Err(format!(
"wrong header: expected [181, 98], got {:?}",
&bytes[0..2]
));
}
if bytes.len() < 8 {
return Err(format!(
"message too short: expected at least 8 bytes, got {}",
bytes.len()
));
}
let class = bytes[2];
let id = bytes[3];
let length = u16::from_le_bytes([bytes[4], bytes[5]]) as usize;
if bytes.len() < 8 + length {
return Err(format!(
"message too short: expected {} bytes, got {}",
8 + length,
bytes.len()
));
}
let payload = bytes[6..6 + length].to_vec();
Ok(Self::new(class, id, payload))
}
}
impl From<UbloxRawMsg> for Vec<u8> {
fn from(msg: UbloxRawMsg) -> Vec<u8> {
let [l0, l1] = (msg.payload.len() as u16).to_le_bytes();
let mut result = vec![0xb5, 0x62, msg.class, msg.id, l0, l1];
result.extend(&msg.payload);
result.extend(&msg.checksum[..]);
result
}
}
#[cfg(test)]
mod test {
use std::convert::TryInto;
use super::UbloxRawMsg;
#[test]
fn simple_test_from_vec() {
let bytes = vec![
0xb5, 0x62, 0x01, 0x02, 0x04, 0x00, b't', b'e', b's', b't', 0xc7, 0x87,
];
let msg: Result<UbloxRawMsg, _> = bytes.try_into();
assert_eq!(
msg,
Ok(UbloxRawMsg {
class: 0x01,
id: 0x02,
payload: vec![b't', b'e', b's', b't'],
checksum: [0xc7, 0x87],
})
);
}
#[test]
fn simple_test_to_vec() {
let payload = vec![b't', b'e', b's', b't'];
let msg = UbloxRawMsg::new(0x01, 0x02, payload);
let bytes: Vec<u8> = msg.into();
assert_eq!(
bytes,
vec![0xb5, 0x62, 0x01, 0x02, 0x04, 0x00, b't', b'e', b's', b't', 0xc7, 0x87]
);
}
}
|
use core::fmt;
use core::str::FromStr;
use crate::term::Atom;
use super::FunctionSymbol;
/// This struct is a subset of `FunctionSymbol` that is used to more
/// generally represent module/function/arity information for any function
/// whether defined or not.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ModuleFunctionArity {
pub module: Atom,
pub function: Atom,
pub arity: u8,
}
impl ModuleFunctionArity {
pub fn new(module: Atom, function: Atom, arity: usize) -> Self {
Self {
module,
function,
arity: arity.try_into().unwrap(),
}
}
}
impl From<FunctionSymbol> for ModuleFunctionArity {
#[inline]
fn from(sym: FunctionSymbol) -> Self {
Self {
module: sym.module,
function: sym.function,
arity: sym.arity,
}
}
}
impl FromStr for ModuleFunctionArity {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let Some((module, rest)) = s.split_once(':') else { return Err(()); };
let Some((function, arity)) = rest.split_once('/') else { return Err(()); };
let module = Atom::try_from(module).unwrap();
let function = Atom::try_from(function).unwrap();
let Ok(arity) = arity.parse::<u8>() else { return Err(()); };
Ok(Self {
module,
function,
arity,
})
}
}
impl fmt::Debug for ModuleFunctionArity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl fmt::Display for ModuleFunctionArity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}/{}", self.module, self.function, self.arity)
}
}
|
extern crate oxygengine_animation as anims;
extern crate oxygengine_core as core;
extern crate oxygengine_utils as utils;
pub mod component;
pub mod composite_renderer;
pub mod font_asset_protocol;
pub mod font_face_asset_protocol;
pub mod jpg_image_asset_protocol;
pub mod map_asset_protocol;
pub mod math;
pub mod mesh_animation_asset_protocol;
pub mod mesh_asset_protocol;
pub mod png_image_asset_protocol;
pub mod resource;
pub mod sprite_sheet_asset_protocol;
pub mod svg_image_asset_protocol;
pub mod system;
pub mod tileset_asset_protocol;
pub mod ui_theme_asset_protocol;
pub mod prelude {
pub use crate::{
component::*, composite_renderer::*, font_asset_protocol::*, font_face_asset_protocol::*,
jpg_image_asset_protocol::*, map_asset_protocol::*, math::*,
mesh_animation_asset_protocol::*, mesh_asset_protocol::*, png_image_asset_protocol::*,
resource::*, sprite_sheet_asset_protocol::*, svg_image_asset_protocol::*, system::*,
tileset_asset_protocol::*, ui_theme_asset_protocol::*,
};
}
use crate::{
component::*,
composite_renderer::CompositeRenderer,
system::{
CompositeCameraCacheSystem, CompositeMapSystem, CompositeMeshAnimationSystem,
CompositeMeshSystem, CompositeRendererSystem, CompositeSpriteAnimationSystem,
CompositeSpriteSheetSystem, CompositeSurfaceCacheSystem, CompositeTilemapAnimationSystem,
CompositeTilemapSystem, CompositeTransformSystem, CompositeUiSystem,
},
};
use core::{
app::AppBuilder, assets::database::AssetsDatabase, ignite_proxy, prefab::PrefabManager,
};
ignite_proxy! {
struct Grid2d<T> {}
}
pub fn bundle_installer<CR>(builder: &mut AppBuilder, data: CR)
where
CR: CompositeRenderer + 'static,
{
builder.install_resource(data);
builder.install_system(CompositeTransformSystem, "transform", &[]);
builder.install_system(CompositeSpriteAnimationSystem, "sprite_animation", &[]);
builder.install_system(CompositeTilemapAnimationSystem, "tilemap_animation", &[]);
builder.install_system(
CompositeMeshAnimationSystem::default(),
"mesh_animation",
&[],
);
builder.install_system(
CompositeSpriteSheetSystem::default(),
"sprite_sheet",
&["sprite_animation"],
);
builder.install_system(
CompositeTilemapSystem::default(),
"tilemap",
&["tilemap_animation"],
);
builder.install_system(CompositeMeshSystem::default(), "mesh", &["mesh_animation"]);
builder.install_system(CompositeMapSystem::default(), "map", &[]);
builder.install_thread_local_system(CompositeUiSystem::<CR>::default());
builder.install_thread_local_system(CompositeCameraCacheSystem::<CR>::default());
builder.install_thread_local_system(CompositeSurfaceCacheSystem::<CR>::default());
builder.install_thread_local_system(CompositeRendererSystem::<CR>::default());
}
pub fn protocols_installer(database: &mut AssetsDatabase) {
database.register(png_image_asset_protocol::PngImageAssetProtocol);
database.register(jpg_image_asset_protocol::JpgImageAssetProtocol);
database.register(svg_image_asset_protocol::SvgImageAssetProtocol);
database.register(sprite_sheet_asset_protocol::SpriteSheetAssetProtocol);
database.register(tileset_asset_protocol::TilesetAssetProtocol);
database.register(map_asset_protocol::MapAssetProtocol);
database.register(ui_theme_asset_protocol::UiThemeAssetProtocol);
database.register(font_asset_protocol::FontAssetProtocol);
database.register(font_face_asset_protocol::FontFaceAssetProtocol);
database.register(mesh_asset_protocol::MeshAssetProtocol);
database.register(mesh_animation_asset_protocol::MeshAnimationAssetProtocol);
}
pub fn prefabs_installer(prefabs: &mut PrefabManager) {
prefabs.register_component_factory::<CompositeVisibility>("CompositeVisibility");
prefabs.register_component_factory::<CompositeSurfaceCache>("CompositeSurfaceCache");
prefabs.register_component_factory::<CompositeRenderable>("CompositeRenderable");
prefabs.register_component_factory::<CompositeRenderableStroke>("CompositeRenderableStroke");
prefabs.register_component_factory::<CompositeTransform>("CompositeTransform");
prefabs.register_component_factory::<CompositeRenderLayer>("CompositeRenderLayer");
prefabs.register_component_factory::<CompositeRenderDepth>("CompositeRenderDepth");
prefabs.register_component_factory::<CompositeRenderAlpha>("CompositeRenderAlpha");
prefabs.register_component_factory::<CompositeCameraAlignment>("CompositeCameraAlignment");
prefabs.register_component_factory::<CompositeEffect>("CompositeEffect");
prefabs.register_component_factory::<CompositeCamera>("CompositeCamera");
prefabs.register_component_factory::<CompositeSprite>("CompositeSprite");
prefabs.register_component_factory::<CompositeSpriteAnimation>("CompositeSpriteAnimation");
prefabs.register_component_factory::<CompositeTilemap>("CompositeTilemap");
prefabs.register_component_factory::<CompositeTilemapAnimation>("CompositeTilemapAnimation");
prefabs.register_component_factory::<CompositeMapChunk>("CompositeMapChunk");
prefabs.register_component_factory::<CompositeMesh>("CompositeMesh");
prefabs.register_component_factory::<CompositeMeshAnimation>("CompositeMeshAnimation");
prefabs.register_component_factory::<CompositeUiElement>("CompositeUiElement");
}
|
use std::collections::HashMap;
fn interpret_with(expr: &str, env: &HashMap<String, i32>) -> i32 {
let mut stack: Vec<i32> = Vec::new();
let tokens: Vec<i32> = expr.split(" ").map(|t|
match t {
"+" => {
let l = stack.pop().expect("To few variables");
let r = stack.pop().expect("To few variables");
let sub = l + r;
stack.push(sub);
sub
}
"-" => {
let r = stack.pop().expect("To few variables");
let l = stack.pop().expect("To few variables");
let sub = l - r;
stack.push(sub);
sub
}
_ => {
let n = *(env.get(t).expect("Unresolved variable binding"));
stack.push(n);
n
}
}
).collect();
//invariant for proper input expression
if 1 != stack.len() {
panic!("non parsable RPN expression, too many variables");
}
*(tokens.last().expect("Empty result"))
}
pub fn run() {
println!("-------------------- {} --------------------", file!());
let expr = "a x - z +";
let vars: HashMap<String, i32> = [
("a".to_string(), 2),
("x".to_string(), 3),
("z".to_string(), 5)
].iter().cloned().collect();
println!("Expected 4 actual {}", interpret_with(expr, &vars));
let expr = "a x z - +";
let vars: HashMap<String, i32> = [
("a".to_string(), 5),
("x".to_string(), 10),
("z".to_string(), 42)
].iter().cloned().collect();
println!("Expected -27 actual {}", interpret_with(expr, &vars));
let expr = "a b c - +";
let vars: HashMap<String, i32> = [
("a".to_string(), 5),
("b".to_string(), 5),
("c".to_string(), 10),
].iter().cloned().collect();
println!("Expected 0 actual {}", interpret_with(expr, &vars));
} |
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
fn hex_safe(n: u8) -> char {
let n = if n <= 9 { b'0' + n } else { b'A' + n - 10 };
n as char
}
pub fn escape_string(s: &str) -> String {
let chars = s.chars().peekable();
let mut s = String::new();
for c in chars {
match c {
'\t' => s.push_str("\\t"),
'\r' => s.push_str("\\r"),
'\n' => s.push_str("\\n"),
'\'' => s.push_str("\\\'"),
'"' => s.push_str("\\\""),
'\\' => s.push_str("\\\\"),
'\x00'..='\x1F' => {
s.push('\\');
s.push('x');
s.push(hex_safe(c as u8 / 16));
s.push(hex_safe(c as u8 % 16));
}
_ => s.push(c),
}
}
s
}
|
use crate::component_registry::ComponentRegistry;
use crate::SpatialComponent;
use hibitset::{BitSet, BitSetAnd, BitSetLike};
use spatialos_sdk::worker::component::Component as WorkerComponent;
use spatialos_sdk::worker::Authority;
use specs::join::BitAnd;
use specs::prelude::{
Component, Entity, Join, Read, ReadStorage, Resources, SystemData, WriteStorage,
};
use specs::shred::{Fetch, ResourceId};
use specs::storage::{DistinctStorage, MaskedStorage, UnprotectedStorage};
use specs::world::Index;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
/// A wrapper around the read storage of a SpatialOS component.
///
/// Analagous to `ReadStorage`.
pub type SpatialReadStorage<'a, T> = ReadStorage<'a, SpatialComponent<T>>;
/// Retrieves write access to any component of this type which this worker has
/// authority over.
///
/// Analagous to `WriteStorage`.
pub struct SpatialWriteStorage<'a, T: 'static + WorkerComponent> {
data: WriteStorage<'a, SpatialComponent<T>>,
authority: Fetch<'a, AuthorityBitSet<T>>,
}
impl<'a, T: 'static + WorkerComponent> SpatialWriteStorage<'a, T> {
pub(crate) fn try_fetch_component_storage(
res: &'a Resources,
) -> Option<WriteStorage<'a, SpatialComponent<T>>> {
if res.has_value::<MaskedStorage<SpatialComponent<T>>>() {
Some(WriteStorage::<SpatialComponent<T>>::fetch(res))
} else {
None
}
}
}
impl<'a, T: 'static + WorkerComponent> Deref for SpatialWriteStorage<'a, T> {
type Target = WriteStorage<'a, SpatialComponent<T>>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<'a, T: 'static + WorkerComponent> DerefMut for SpatialWriteStorage<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.data
}
}
impl<'a, T: 'static + WorkerComponent> SystemData<'a> for SpatialWriteStorage<'a, T>
where
T: 'static + WorkerComponent,
{
fn setup(res: &mut Resources) {
Read::<AuthorityBitSet<T>>::setup(res);
WriteStorage::<SpatialComponent<T>>::setup(res);
}
fn fetch(res: &'a Resources) -> Self {
SpatialWriteStorage {
data: WriteStorage::<SpatialComponent<T>>::fetch(res),
authority: res.fetch(),
}
}
fn reads() -> Vec<ResourceId> {
vec![ResourceId::new::<AuthorityBitSet<T>>()]
}
fn writes() -> Vec<ResourceId> {
WriteStorage::<SpatialComponent<T>>::writes()
}
}
impl<'a, 'e, T> Join for &'a mut SpatialWriteStorage<'e, T>
where
T: 'static + WorkerComponent,
{
type Mask = BitSetAnd<&'a BitSet, &'a BitSet>;
type Type = &'a mut SpatialComponent<T>;
type Value = &'a mut <SpatialComponent<T> as Component>::Storage;
unsafe fn open(self) -> (Self::Mask, Self::Value) {
let storage = &mut self.data;
let (mask, value) = storage.open();
((&self.authority.mask, mask).and(), value)
}
unsafe fn get(v: &mut Self::Value, i: Index) -> &'a mut SpatialComponent<T> {
<&'a mut WriteStorage<'a, SpatialComponent<T>> as Join>::get(v, i)
}
}
#[cfg(feature = "parallel")]
unsafe impl<'a, 'e, T> ParJoin for &'a mut SpatialWriteStorage<'e, T>
where
T: 'static + WorkerComponent,
D: DerefMut<Target = MaskedStorage<T>>,
WriteStorage<'a, SpatialComponent<T>>: ParJoin,
<SpatialComponent<T> as Component>::Storage: Sync + DistinctStorage,
{
}
/// A wrapper around an arbitrary `UnprotectedStorage` which registers
/// the SpatialOS component in the `ComponentRegistry`.
#[doc(hidden)]
pub struct SpatialUnprotectedStorage<T, C, U>(U, PhantomData<T>, PhantomData<C>)
where
T: 'static + WorkerComponent,
U: UnprotectedStorage<C> + Default;
impl<T, C, U> UnprotectedStorage<C> for SpatialUnprotectedStorage<T, C, U>
where
T: 'static + WorkerComponent,
U: UnprotectedStorage<C> + Default,
{
unsafe fn clean<B>(&mut self, has: B)
where
B: BitSetLike,
{
self.0.clean(has);
}
unsafe fn get(&self, id: Index) -> &C {
self.0.get(id)
}
unsafe fn get_mut(&mut self, id: Index) -> &mut C {
self.0.get_mut(id)
}
unsafe fn insert(&mut self, id: Index, v: C) {
self.0.insert(id, v);
}
unsafe fn remove(&mut self, id: Index) -> C {
self.0.remove(id)
}
}
unsafe impl<T, C, U> DistinctStorage for SpatialUnprotectedStorage<T, C, U>
where
T: 'static + WorkerComponent,
U: UnprotectedStorage<C> + Default + DistinctStorage,
{
}
impl<T, C, U> Default for SpatialUnprotectedStorage<T, C, U>
where
T: 'static + WorkerComponent,
U: UnprotectedStorage<C> + Default,
{
fn default() -> Self {
ComponentRegistry::register_component::<T>();
SpatialUnprotectedStorage(Default::default(), PhantomData, PhantomData)
}
}
pub(crate) struct AuthorityBitSet<T: WorkerComponent> {
mask: BitSet,
_phantom: PhantomData<T>,
}
impl<T: WorkerComponent> AuthorityBitSet<T> {
pub(crate) fn set_authority(&mut self, e: Entity, authority: Authority) {
if authority == Authority::NotAuthoritative {
self.mask.remove(e.id());
} else {
self.mask.add(e.id());
}
}
}
impl<T: WorkerComponent> Default for AuthorityBitSet<T> {
fn default() -> Self {
AuthorityBitSet {
mask: BitSet::new(),
_phantom: PhantomData,
}
}
}
#[test]
fn component_registers_successfully_on_read() {
use crate::generated_test::*;
use specs::prelude::World;
let mut world = World::new();
SpatialReadStorage::<Position>::setup(&mut world.res);
assert!(ComponentRegistry::get_interface(Position::ID).is_some());
}
#[test]
fn component_registers_successfully_on_write() {
use crate::generated_test::*;
use specs::prelude::World;
let mut world = World::new();
SpatialWriteStorage::<Position>::setup(&mut world.res);
assert!(ComponentRegistry::get_interface(Position::ID).is_some());
}
#[test]
fn should_only_join_authority() {
use crate::entities::SpatialEntitiesRes;
use crate::generated_test::*;
use crate::*;
use spatialos_sdk::worker::EntityId as WorkerEntityId;
use specs::prelude::*;
let mut world = World::new();
Entities::setup(&mut world.res);
EntityIds::setup(&mut world.res);
SpatialReadStorage::<Position>::setup(&mut world.res);
SpatialWriteStorage::<Position>::setup(&mut world.res);
let entity_id = EntityId(WorkerEntityId::new(5));
let data = Position {
coords: Coordinates {
x: 1.0,
y: 2.0,
z: 3.0,
},
};
{
world
.res
.fetch_mut::<SpatialEntitiesRes>()
.got_new_entity(&world.res, entity_id);
}
let entity = {
world
.res
.fetch::<SpatialEntitiesRes>()
.get_entity(entity_id)
.unwrap()
};
{
assert!((&SpatialReadStorage::<Position>::fetch(&world.res))
.join()
.next()
.is_none());
}
{
let mut storage = SpatialWriteStorage::<Position>::fetch(&world.res);
storage.insert(entity, SpatialComponent::new(data)).unwrap();
}
{
let mut storage = SpatialReadStorage::<Position>::fetch(&world.res);
assert!((&mut storage).join().next().is_some());
}
{
let mut storage = SpatialWriteStorage::<Position>::fetch(&world.res);
assert!(
(&mut storage).join().next().is_none(),
"WriteStorage should be empty as the worker is not authoritative."
);
}
{
world
.res
.fetch_mut::<AuthorityBitSet<Position>>()
.set_authority(entity, Authority::Authoritative);
}
{
let mut storage = SpatialReadStorage::<Position>::fetch(&world.res);
assert!((&mut storage).join().next().is_some());
}
{
let mut storage = SpatialWriteStorage::<Position>::fetch(&world.res);
assert!(
(&mut storage).join().next().is_some(),
"WriteStorage should be non-empty as the worker is authoritative."
);
}
}
|
use crate::enums::{TypeHolder, Types};
use crate::types_structs::{Enum, ItemInfo, Struct, Trait, TYPE_CASE};
use crate::{Language, TypeCases};
use derive_new::new;
use std::collections::{HashMap, VecDeque};
use std::fs::{DirEntry, File};
use std::io::Write;
use std::path::PathBuf;
use std::rc::Rc;
use syn::__private::ToTokens;
use syn::{PathArguments, ReturnType, Type};
use std::time::Instant;
//constants
pub const F_CLASS: &str = "foreign_class!";
pub const F_CALLBACK: &str = "foreign_callback!";
pub const F_ENUM: &str = "foreign_enum!";
//errors
const UNABLE_TO_READ: &str = "Unable to read file: ";
//helper macros
#[derive(new, Debug)]
struct AttrCheck {
is_attribute: bool,
is_constructor: bool,
}
macro_rules! has_gen_attr {
($expr:expr) => {
has_gen_attr!($expr, false)
};
($expr:expr,$check_for_constructor:expr) => {{
let mut is_attribute = false;
let mut is_constructor = false;
$expr.attrs.iter().any(|it| {
is_attribute = it
.path
.segments
.iter()
.any(|it| it.ident == "generate_interface");
if is_attribute && $check_for_constructor {
is_constructor = it.tokens.to_string().contains("constructor");
}
is_attribute
});
AttrCheck::new(is_attribute, is_constructor)
}};
}
//to use with Structs only
macro_rules! has_doc_gen_attr {
($expr:expr) => {
$expr.attrs.iter().any(|it| {
it.path
.segments
.iter()
.any(|it| &it.ident.to_string() == "generate_interface_doc")
})
};
}
macro_rules! get_doc {
($expr:expr) => {
$expr
.attrs
.iter()
.filter_map(|it| {
//segments usually contain an item but just in case
let doc = it
.path
.segments
.iter()
.map(|it| it.ident.to_string())
.filter(|it| it == "doc")
.next();
//
if let Some(_) = doc {
Some(it.to_token_stream().to_string())
} else {
None
}
})
.collect::<Vec<String>>()
};
}
macro_rules! correct_string {
($string:expr) => {{
let sign = $string.rfind("<");
if let Some(sign) = sign {
//means it's something like Box<Kofi>
// find the other >
let other = $string.find(">").unwrap();
let new_string = &$string[sign + 1..other];
new_string.trim().to_string()
} else {
$string.trim().into()
}
}};
}
macro_rules! types_in_method {
($expr:expr) => {{
let result = (&$expr)
.sig
.inputs
.iter()
.filter_map(|it| {
match it {
syn::FnArg::Receiver(_) => None, //something like (&self)
syn::FnArg::Typed(typ) => {
let _type = typ.ty.to_token_stream().to_string().replace(" dyn ", "");
////println!("type {}", _type);
Some(correct_string!(_type))
}
}
})
.collect::<Vec<_>>();
result
}};
}
macro_rules! return_types {
($expr:expr) => {{
let mut return_types: Vec<String> = Vec::new();
match &$expr.sig.output {
ReturnType::Type(_, val) => match &**val {
Type::Path(val) => {
//let result = vec![];
val.path.segments.iter().for_each(|it| {
return_types.push((&it.ident).to_string());
match &it.arguments {
PathArguments::AngleBracketed(val) => {
val.args.iter().for_each(|it| {
let str = it.to_token_stream().to_string();
return_types.push(str);
});
}
_ => {}
}
});
}
_ => {}
},
_ => {}
}
return_types
}};
}
macro_rules! function_signature {
($expr:expr) => {{
{
let signature = &$expr.sig;
let mut iter = signature.to_token_stream().into_iter();
//it could start with maybe unsafe fn or fn
iter.find(|it| it.to_string() == "fn");
let mut result = String::with_capacity(32);
while let Some(val) = iter.next() {
let val = val.to_string();
if val == "'" {
//lifetimes cause problems
result.push_str(&val); // push the lifetime param
result.push_str(&iter.next().unwrap().to_string());
result.push(' ');
} else {
result.push_str(&val)
}
}
result
}
}};
}
/// First all enums would be placed at the start of the file to make things simpler
///
/// so now to the traits and structs
///
/// assuming we have struct A and struct B
/// struct A has a method which depends on struct B but not vice versa
/// struct A is first added
/// so now it's time to add struct B
/// struct B should be placed in front of struct A in vec deque
struct ItemsHolder {
list: HashMap<Rc<String>, TypeHolder>,
enums_list: Vec<Enum>,
final_list: VecDeque<Rc<String>>,
}
impl ItemsHolder {
fn new(capacity: usize) -> ItemsHolder {
ItemsHolder {
list: HashMap::with_capacity(capacity),
enums_list: Vec::new(),
final_list: VecDeque::with_capacity(capacity),
}
}
/*fn ensure_new(&self, name: Rc<String>) {
assert!(
!self.list.contains_key(&name),
"A struct with a similar name already exists. struct {}",
&name
);
}*/
fn add_items(&mut self, name: Rc<String>, item: TypeHolder) {
self.list.insert(name, item);
}
fn sort_items(&mut self) {
/* So now it's a 2 way something
Given 3 types: North, South, East
If North has a method that depends on East, but North is added first, when East is added, it should
be placed before North and not after it
*/
//supposed We have F, N, M, O, T
// F is added first but F has a method which depends on N
//N has a method which depends on O
// So in effect the list should be [O, N, F, ...] even though F was added first
if self.list.is_empty() {
eprintln!("Annotate methods and enums to use module rust_interface_file_generator");
return;
}
self.list.keys().next().unwrap().to_string();
let mut values = self
.list
.keys()
.map(|it| (it.clone(), None))
.collect::<HashMap<Rc<String>, Option<()>>>();
//TODO optimise it
fn analyse_item(
item: &TypeHolder,
values: &mut HashMap<Rc<String>, Option<()>>,
map: &HashMap<Rc<String>, TypeHolder>,
out: &mut VecDeque<Rc<String>>,
) {
let types = item.types();
//println!("types {:?} name {}", types, item.name());
let item_name = item.name().to_string();
values.remove(&item_name);
let item_name = Rc::new(item_name);
out.iter().position(|it| it == &item_name).and_then(|it| {
//println!("and then {}", item_name);
Some(out.remove(it))
});
out.push_front(item_name);
for _type in types {
//println!("type {}", _type);
if let Some(val) = map.get(_type) {
if val.name() == item.name() {
//Since classes with constructors have `self` as type
continue;
}
//println!("val {} item {}", val.name(), item.name());
//println!("for ilist {:?}", out);
analyse_item(val, values, map, out);
}
}
//values.remove(&item.name().to_string());
////println!("list {:?}", out);
//panic!();
}
//let mut times = 0;
while !values.is_empty() {
/*println!(
"while {:?} start {}",
values.keys().collect::<Vec<&Rc<String>>>(),
values.iter().next().unwrap().0.to_string()
);*/
analyse_item(
self.list
.get(&values.iter().next().unwrap().0.to_string())
.unwrap(),
&mut values,
&self.list,
&mut self.final_list,
);
//println!("panic {:?}", values.keys().collect::<Vec<&Rc<String>>>());
/*times += 1;
if times == 5 {
panic!()
}*/
//panic!()
}
////println!("out {}",)
}
fn add_enum(&mut self, data: Enum) {
//self.list.insert(Rc::new(data.name.to_string()),TypeHolder::Enum(data));
self.enums_list.push(data)
}
fn generate_interface(mut self, language: Language, out_file: &PathBuf) {
//println!("final {:?}", self.final_list);
let mut file = File::create(out_file).expect("Unable to write to disk");
file.write(b"//Automatically generated by rifgen\nuse crate::*;\n")
.unwrap();
if matches!(language, Language::Java) {
file.write_all(b"use jni_sys::*;\n").unwrap();
}
//first add enums since enums "can't" depend on other data structures
self.sort_items();
for mut enums in self.enums_list {
file.write_all(enums.generate_interface().as_ref())
.expect("Unable to write to disk");
}
/*assert_eq!(
self.final_list,
vec![
Rc::new("OTH".into()),
Rc::new("Kofi".into()),
Rc::new("Noth".into()),
Rc::new("Finalise".into()),
Rc::new("ImDone".into())
]
);*/
//println!("tested");
for name in self.final_list {
file.write_all(
self.list
.get_mut(&*name)
.unwrap()
.generate_interface()
.as_ref(),
)
.expect("Unable to write to disk");
}
}
}
// one possible implementation of walking a directory only visiting files
fn visit_dirs(dir: &PathBuf, cb: &mut dyn FnMut(&std::fs::DirEntry)) -> std::io::Result<()> {
if dir.is_dir() {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_dirs(&path, cb)?;
} else {
cb(&entry);
}
}
}
Ok(())
}
pub struct FileGenerator {
interface_file_path: PathBuf,
starting_point: PathBuf,
}
impl FileGenerator {
pub fn new(
type_case: TypeCases,
interface_file_path: PathBuf,
starting_point: PathBuf,
) -> FileGenerator {
unsafe { TYPE_CASE = type_case }
FileGenerator {
interface_file_path,
starting_point,
}
}
pub fn build(&self, language: Language) {
let start = Instant::now();
//the closure to be applied to each file
let mut file_data: HashMap<Rc<String>, TypeHolder> = HashMap::new();
let mut closure = |file: &DirEntry| {
let file_path = file.path();
let file_contents = std::fs::read_to_string(&file_path).expect(&format!(
"{}{}",
UNABLE_TO_READ,
file_path.to_str().unwrap()
));
let compiled_file = syn::parse_file(&file_contents).expect("Invalid rust file");
for item in &compiled_file.items {
//
match item {
syn::Item::Struct(item) => {
//check if it has the doc attribute
if has_doc_gen_attr!(item) {
let name = Rc::new((&item).ident.to_string());
//assert!(!file_data.contains_key(&name.clone()));
//the impl block may come (ie if it's in a different file) before the struct definition
if let Some(val) = file_data.get_mut(&name) {
match val {
TypeHolder::Struct(val) => {
val.docs.append(&mut get_doc!(item));
}
_ => {
panic!("Expected {} to be a struct", name)
}
}
} else {
file_data.insert(
name.clone(),
TypeHolder::Struct(Struct::new(
name.to_string(),
Types::Struct,
get_doc!(item),
vec![],
)),
);
}
}
}
syn::Item::Fn(val) => {
// function not in impl block
let name = val.sig.ident.to_string();
if has_gen_attr!(val).is_attribute {
panic!(
"interface functions should be declared in impl blocks.\nName of function {}",
name
)
}
}
syn::Item::Impl(val) => {
//TODO let it work with enums
FileGenerator::impl_data(&mut file_data, val);
}
syn::Item::Enum(val) => {
if has_gen_attr!(val).is_attribute {
let name = Rc::new((&val).ident.to_string());
assert!(
!file_data.contains_key(&name),
"Multiple definitions of {}",
&name
); // make sure no other struct has the same name
let variants = val
.variants
.iter()
.map(|it| ItemInfo::new_enum(it.ident.to_string(), get_doc!(it)))
.collect();
file_data.insert(
name.clone(),
TypeHolder::Enum(Enum::new(
name.to_string(),
Types::Enum,
get_doc!(val),
variants,
)),
);
}
}
syn::Item::Trait(val) => {
if !has_gen_attr!(val).is_attribute {
continue;
}
//println!("trait");
let name = Rc::new((&val).ident.to_string());
let mut trait_data: Trait = Trait::new(
name.to_string(),
Types::Trait,
get_doc!(val),
Vec::with_capacity(val.items.len()),
);
for item in &val.items {
if let syn::TraitItem::Method(method) = item {
let method_name = (&method).sig.ident.to_string();
trait_data.extras.push(ItemInfo::new_method(
function_signature!(method),
get_doc!(method),
method_name,
false,
types_in_method!(method),
return_types!(method),
));
}
}
assert!(
!file_data.contains_key(&name),
"Multiple definitions of {}",
&name
); // make sure no other struct has the same name
file_data.insert(name.clone(), TypeHolder::Trait(trait_data));
}
_ => {
//todo
}
}
}
};
visit_dirs(&self.starting_point, &mut closure).expect("Unable to read directory");
//create interface file
let mut holder = ItemsHolder::new(file_data.len());
//file_data.iter().for_each(|it| println!("it {:?}", it));
for (name, type_holder) in file_data {
match type_holder {
TypeHolder::Struct(_) | TypeHolder::Trait(_) => {
holder.add_items(name, type_holder);
}
TypeHolder::Enum(val) => holder.add_enum(val),
}
}
holder.generate_interface(language, &self.interface_file_path);
println!("Total Time Taken To Generate File {:?}", start.elapsed());
}
fn impl_data(map: &mut HashMap<Rc<String>, TypeHolder>, item: &syn::ItemImpl) {
let self_type = &*item.self_ty;
if let syn::Type::Path(type_path) = self_type {
let name = type_path
.path
.segments
.iter()
.next()
.and_then(|it| Some(it.ident.to_string()));
if let Some(name) = name {
//name of struct or enum
for item in item.items.iter() {
match item {
syn::ImplItem::Method(method) => {
let method_info: AttrCheck = has_gen_attr!(method, true);
//not supporting enums for now
if !method_info.is_attribute {
continue;
}
let method_name = (&method).sig.ident.to_string();
let data = map.get_mut(&name);
let item_info = ItemInfo::new_method(
function_signature!(method),
get_doc!(method),
method_name,
method_info.is_constructor,
types_in_method!(method),
return_types!(method),
);
if let Some(data) = data {
match data {
TypeHolder::Struct(val) => {
val.extras.push(item_info);
}
_ => {
unimplemented!("Impl function may only be used for structs")
}
}
} else {
//impl block came before struct definition (properly due to the order in which the files
// were read)
//we're assuming the impl method is for a struct
//if it's for an enum, it would crash in the enum function
let data = Struct::new(
name.to_string(),
Types::Struct,
vec![],
vec![item_info],
);
map.insert(Rc::new(name.clone()), TypeHolder::Struct(data));
}
}
_ => {}
}
}
}
};
}
}
/*
todo!()
#[cfg(test)]
mod tests {
use crate::generator_lib::AttrCheck;
use syn::__private::ToTokens;
use syn::{Item, PathArguments, ReturnType, Type};
#[test]
fn test_syn() {
let item = syn::parse_str::<syn::Item>(
"
#[generate_interface_doc]
#[derive(Debug)]
///struct us good
///
struct Kofi {
kkkk: i64,
}
",
)
.unwrap();
////println!("{:#?}", item);
let item = syn::parse_str::<syn::Item>(
"#[generate_interface(here)]
///nice docs
fn not() {
unimplemented!()
}",
)
.unwrap();
//println!("{:#?}", item);
if let syn::Item::Fn(val) = item {
let y = val
.attrs
.iter()
.map(|it| it.tokens.to_string())
//.filter(|it| it.contains("constructor"))
.collect::<Vec<String>>();
val.attrs.iter().any(|it| {
let is_attribute = it
.path
.segments
.iter()
.any(|it| it.ident == "generate_interface");
//println!("any {}", is_attribute);
is_attribute
});
for attribute in val.attrs.iter() {
let is_attribute = attribute
.path
.segments
.iter()
.any(|it| it.ident == "generate_interface");
//println!("is {}", is_attribute);
}
//println!("vec {:?} has {:?}", y, has_gen_attr!(val, true));
}
panic!()
}
#[test]
fn test_types_in_method() {
let item = syn::parse_str::<Item>("fn others(h: Box<Box<i64,FOK>>, j: OTH) {}").unwrap();
let item1 = syn::parse_str::<Item>(
"unsafe fn new(kkkk: i64, k: Trial) -> HashMap<i64,Kofi> {
Kofi { kkkk }
}",
)
.unwrap();
let item2 = syn::parse_str::<Item>(
"unsafe fn new(kkkk: i64, k: Trial) -> Kofi {
Kofi { kkkk }
}",
)
.unwrap();
if let syn::Item::Fn(val) = item1 {
let vecs = types_in_method!(val);
////println!("types in {:?} {:?}", vecs, return_types!(val));
match val.sig.output {
ReturnType::Default => {}
ReturnType::Type(_, val) => match &*val {
Type::Path(val) => {
//let result = vec![];
val.path.segments.iter().for_each(|it| {
//println!("ident {}", &it.ident);
match &it.arguments {
PathArguments::None => {}
PathArguments::AngleBracketed(val) => {
let str = val.args.to_token_stream().to_string();
val.args.iter().for_each(|it| {
let str = it.to_token_stream().to_string();
//println!("str {}", str);
});
}
PathArguments::Parenthesized(_) => {}
}
});
}
_ => {}
},
}
}
}
}
*/ |
use anchor_lang::prelude::*;
use yta_token::{YTAToken,Increase};
#[program]
pub mod yta_demo {
use super::*;
pub fn initialize(ctx: Context<Initialize>,total:u64,authority:Pubkey) -> ProgramResult {
let yta_config = &mut ctx.accounts.yta_config;
yta_config.authority = authority;
yta_config.total = total;
Ok(())
}
pub fn Reward(ctx: Context<Reward>,amount:u64)->ProgramResult{
let yta_config = &mut ctx.accounts.yta_config;
if yta_config.total - amount >=0 {
yta_config.total-=amount;
let cpi_program = ctx.accounts.yta_config.clone();
let cpi_accounts = Increase{
yta_account:ctx.accounts.receiver.clone().into(),
authority:ctx.accounts.authority.clone(),
};
let cpi_ctx = CpiContext::new(cpi_program,cpi_accounts);
yta_token::cpi::increase(cpi_ctx,amount);
}
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(init)]
pub yta_config:ProgramAccount<'info,YTAConfig>,
pub rent:Sysvar<'info,Rent>
}
#[derive(Accounts)]
pub struct Reward<'info>{
#[account(mut)]
pub yta_config:ProgramAccount<'info,YTAConfig>,
pub receiver:CpiAccount<'info,YTAToken>,
pub authority:AccountInfo<'info>,
}
#[account]
pub struct YTAConfig{
pub total:u64,
pub authority:Pubkey,
} |
use ast::{self, AsStatement, Program};
use lexer::Lexer;
use token::{self, Token};
struct Parser<'a> {
l: &'a mut Lexer,
cur_token: Token,
peek_token: Token,
}
impl<'a> Parser<'a> {
fn new(l: &'a mut Lexer) -> Self {
let tok1 = l.next_token().clone();
let tok2 = l.next_token().clone();
Parser {
l: l,
cur_token: tok1,
peek_token: tok2,
}
}
fn next_token(&mut self) {
let tok = self.peek_token.clone();
let next = self.l.next_token();
self.cur_token = tok;
self.peek_token = next;
}
fn parse_program(&mut self) -> Option<Program> {
let mut program = ast::Program::new();
while self.cur_token.typ != token::TokenType::EOF {
println!("cur_token: {:?}", self.cur_token);
if let Some(stmt) = self.parse_statement() {
program.statements.push(stmt);
}
self.next_token();
}
Some(program)
}
fn parse_statement(&mut self) -> Option<Box<ast::Statement>> {
match self.cur_token.typ {
token::TokenType::LET => self.parse_let_statement().map(|x| x.as_box_statement()),
_ => None,
}
}
fn parse_let_statement(&mut self) -> Option<ast::LetStatement> {
let let_token = self.cur_token.clone();
if !self.expect_peek(token::TokenType::IDENT) {
return None;
}
let ident = ast::Identifier {
token: self.cur_token.clone(),
value: self.cur_token.literal.clone(),
};
let stmt = ast::LetStatement {
token: let_token,
name: ident,
//value: None,
};
if !self.expect_peek(token::TokenType::ASSIGN) {
return None;
}
while !self.cur_token_is(token::TokenType::SEMICOLON) {
self.next_token();
}
Some(stmt)
}
fn cur_token_is(&self, t: token::TokenType) -> bool {
self.cur_token.typ == t
}
fn peek_token_is(&self, t: token::TokenType) -> bool {
self.peek_token.typ == t
}
fn expect_peek(&mut self, t: token::TokenType) -> bool {
if self.peek_token_is(t) {
self.next_token();
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ast::*;
use std::any::Any;
fn print_if_string(s: &Any) {
if let Some(string) = s.downcast_ref::<String>() {
println!("It's a string({}): '{}'", string.len(), string);
} else {
println!("Not a string...");
}
}
#[test]
fn let_statements() {
let input = r#"
let x = 5;
let y = 10;
let foobar = 838383;"#;
let mut l = Lexer::new(String::from(input));
let mut p = Parser::new(&mut l);
let program = p.parse_program().expect("parse_program() failed");
assert_eq!(program.statements.len(), 3);
for (i, ident) in vec!["x", "y", "foobar"].iter().enumerate() {
let stmt = &program.statements[i];
assert_let_statement(stmt, &ident);
}
}
fn assert_let_statement(s: &Box<Statement>, name: &str) {
assert_eq!(s.token_literal(), "let");
let stmt = s
.downcast_ref::<ast::LetStatement>()
.expect("downcast as LetStatement");
assert_eq!(stmt.name.value, name);
assert_eq!(stmt.name.token_literal(), name);
}
}
|
#[doc = "Reader of register COMP_ID_2"]
pub type R = crate::R<u32, super::COMP_ID_2>;
#[doc = "Reader of field `PREAMBLE`"]
pub type PREAMBLE_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - Preamble bits 12 to 19"]
#[inline(always)]
pub fn preamble(&self) -> PREAMBLE_R {
PREAMBLE_R::new((self.bits & 0xff) as u8)
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn AllJoynAcceptBusConnection(serverbushandle: super::super::Foundation::HANDLE, abortevent: super::super::Foundation::HANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AllJoynCloseBusHandle(bushandle: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn AllJoynConnectToBus(connectionspec: super::super::Foundation::PWSTR) -> super::super::Foundation::HANDLE;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
pub fn AllJoynCreateBus(outbuffersize: u32, inbuffersize: u32, lpsecurityattributes: *const super::super::Security::SECURITY_ATTRIBUTES) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn AllJoynEnumEvents(connectedbushandle: super::super::Foundation::HANDLE, eventtoreset: super::super::Foundation::HANDLE, eventtypes: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn AllJoynEventSelect(connectedbushandle: super::super::Foundation::HANDLE, eventhandle: super::super::Foundation::HANDLE, eventtypes: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn AllJoynReceiveFromBus(connectedbushandle: super::super::Foundation::HANDLE, buffer: *mut ::core::ffi::c_void, bytestoread: u32, bytestransferred: *mut u32, reserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn AllJoynSendToBus(connectedbushandle: super::super::Foundation::HANDLE, buffer: *const ::core::ffi::c_void, bytestowrite: u32, bytestransferred: *mut u32, reserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn QCC_StatusText(status: QStatus) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_create(defaultlanguage: super::super::Foundation::PSTR) -> alljoyn_aboutdata;
pub fn alljoyn_aboutdata_create_empty() -> alljoyn_aboutdata;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_create_full(arg: alljoyn_msgarg, language: super::super::Foundation::PSTR) -> alljoyn_aboutdata;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_createfrommsgarg(data: alljoyn_aboutdata, arg: alljoyn_msgarg, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_createfromxml(data: alljoyn_aboutdata, aboutdataxml: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_aboutdata_destroy(data: alljoyn_aboutdata);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_getaboutdata(data: alljoyn_aboutdata, msgarg: alljoyn_msgarg, language: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_aboutdata_getajsoftwareversion(data: alljoyn_aboutdata, ajsoftwareversion: *mut *mut i8) -> QStatus;
pub fn alljoyn_aboutdata_getannouncedaboutdata(data: alljoyn_aboutdata, msgarg: alljoyn_msgarg) -> QStatus;
pub fn alljoyn_aboutdata_getappid(data: alljoyn_aboutdata, appid: *mut *mut u8, num: *mut usize) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_getappname(data: alljoyn_aboutdata, appname: *mut *mut i8, language: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_aboutdata_getdateofmanufacture(data: alljoyn_aboutdata, dateofmanufacture: *mut *mut i8) -> QStatus;
pub fn alljoyn_aboutdata_getdefaultlanguage(data: alljoyn_aboutdata, defaultlanguage: *mut *mut i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_getdescription(data: alljoyn_aboutdata, description: *mut *mut i8, language: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_aboutdata_getdeviceid(data: alljoyn_aboutdata, deviceid: *mut *mut i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_getdevicename(data: alljoyn_aboutdata, devicename: *mut *mut i8, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_getfield(data: alljoyn_aboutdata, name: super::super::Foundation::PSTR, value: *mut alljoyn_msgarg, language: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_aboutdata_getfields(data: alljoyn_aboutdata, fields: *const *const i8, num_fields: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_getfieldsignature(data: alljoyn_aboutdata, fieldname: super::super::Foundation::PSTR) -> super::super::Foundation::PSTR;
pub fn alljoyn_aboutdata_gethardwareversion(data: alljoyn_aboutdata, hardwareversion: *mut *mut i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_getmanufacturer(data: alljoyn_aboutdata, manufacturer: *mut *mut i8, language: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_aboutdata_getmodelnumber(data: alljoyn_aboutdata, modelnumber: *mut *mut i8) -> QStatus;
pub fn alljoyn_aboutdata_getsoftwareversion(data: alljoyn_aboutdata, softwareversion: *mut *mut i8) -> QStatus;
pub fn alljoyn_aboutdata_getsupportedlanguages(data: alljoyn_aboutdata, languagetags: *const *const i8, num: usize) -> usize;
pub fn alljoyn_aboutdata_getsupporturl(data: alljoyn_aboutdata, supporturl: *mut *mut i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_isfieldannounced(data: alljoyn_aboutdata, fieldname: super::super::Foundation::PSTR) -> u8;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_isfieldlocalized(data: alljoyn_aboutdata, fieldname: super::super::Foundation::PSTR) -> u8;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_isfieldrequired(data: alljoyn_aboutdata, fieldname: super::super::Foundation::PSTR) -> u8;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_isvalid(data: alljoyn_aboutdata, language: super::super::Foundation::PSTR) -> u8;
pub fn alljoyn_aboutdata_setappid(data: alljoyn_aboutdata, appid: *const u8, num: usize) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setappid_fromstring(data: alljoyn_aboutdata, appid: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setappname(data: alljoyn_aboutdata, appname: super::super::Foundation::PSTR, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setdateofmanufacture(data: alljoyn_aboutdata, dateofmanufacture: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setdefaultlanguage(data: alljoyn_aboutdata, defaultlanguage: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setdescription(data: alljoyn_aboutdata, description: super::super::Foundation::PSTR, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setdeviceid(data: alljoyn_aboutdata, deviceid: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setdevicename(data: alljoyn_aboutdata, devicename: super::super::Foundation::PSTR, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setfield(data: alljoyn_aboutdata, name: super::super::Foundation::PSTR, value: alljoyn_msgarg, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_sethardwareversion(data: alljoyn_aboutdata, hardwareversion: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setmanufacturer(data: alljoyn_aboutdata, manufacturer: super::super::Foundation::PSTR, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setmodelnumber(data: alljoyn_aboutdata, modelnumber: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setsoftwareversion(data: alljoyn_aboutdata, softwareversion: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setsupportedlanguage(data: alljoyn_aboutdata, language: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdata_setsupporturl(data: alljoyn_aboutdata, supporturl: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutdatalistener_create(callbacks: *const alljoyn_aboutdatalistener_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_aboutdatalistener;
pub fn alljoyn_aboutdatalistener_destroy(listener: alljoyn_aboutdatalistener);
pub fn alljoyn_abouticon_clear(icon: *mut _alljoyn_abouticon_handle);
pub fn alljoyn_abouticon_create() -> *mut _alljoyn_abouticon_handle;
pub fn alljoyn_abouticon_destroy(icon: *mut _alljoyn_abouticon_handle);
pub fn alljoyn_abouticon_getcontent(icon: *mut _alljoyn_abouticon_handle, data: *const *const u8, size: *mut usize);
pub fn alljoyn_abouticon_geturl(icon: *mut _alljoyn_abouticon_handle, r#type: *const *const i8, url: *const *const i8);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_abouticon_setcontent(icon: *mut _alljoyn_abouticon_handle, r#type: super::super::Foundation::PSTR, data: *mut u8, csize: usize, ownsdata: u8) -> QStatus;
pub fn alljoyn_abouticon_setcontent_frommsgarg(icon: *mut _alljoyn_abouticon_handle, arg: alljoyn_msgarg) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_abouticon_seturl(icon: *mut _alljoyn_abouticon_handle, r#type: super::super::Foundation::PSTR, url: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_abouticonobj_create(bus: alljoyn_busattachment, icon: *mut _alljoyn_abouticon_handle) -> *mut _alljoyn_abouticonobj_handle;
pub fn alljoyn_abouticonobj_destroy(icon: *mut _alljoyn_abouticonobj_handle);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_abouticonproxy_create(bus: alljoyn_busattachment, busname: super::super::Foundation::PSTR, sessionid: u32) -> *mut _alljoyn_abouticonproxy_handle;
pub fn alljoyn_abouticonproxy_destroy(proxy: *mut _alljoyn_abouticonproxy_handle);
pub fn alljoyn_abouticonproxy_geticon(proxy: *mut _alljoyn_abouticonproxy_handle, icon: *mut _alljoyn_abouticon_handle) -> QStatus;
pub fn alljoyn_abouticonproxy_getversion(proxy: *mut _alljoyn_abouticonproxy_handle, version: *mut u16) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutlistener_create(callback: *const alljoyn_aboutlistener_callback, context: *const ::core::ffi::c_void) -> alljoyn_aboutlistener;
pub fn alljoyn_aboutlistener_destroy(listener: alljoyn_aboutlistener);
pub fn alljoyn_aboutobj_announce(obj: alljoyn_aboutobj, sessionport: u16, aboutdata: alljoyn_aboutdata) -> QStatus;
pub fn alljoyn_aboutobj_announce_using_datalistener(obj: alljoyn_aboutobj, sessionport: u16, aboutlistener: alljoyn_aboutdatalistener) -> QStatus;
pub fn alljoyn_aboutobj_create(bus: alljoyn_busattachment, isannounced: alljoyn_about_announceflag) -> alljoyn_aboutobj;
pub fn alljoyn_aboutobj_destroy(obj: alljoyn_aboutobj);
pub fn alljoyn_aboutobj_unannounce(obj: alljoyn_aboutobj) -> QStatus;
pub fn alljoyn_aboutobjectdescription_clear(description: alljoyn_aboutobjectdescription);
pub fn alljoyn_aboutobjectdescription_create() -> alljoyn_aboutobjectdescription;
pub fn alljoyn_aboutobjectdescription_create_full(arg: alljoyn_msgarg) -> alljoyn_aboutobjectdescription;
pub fn alljoyn_aboutobjectdescription_createfrommsgarg(description: alljoyn_aboutobjectdescription, arg: alljoyn_msgarg) -> QStatus;
pub fn alljoyn_aboutobjectdescription_destroy(description: alljoyn_aboutobjectdescription);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutobjectdescription_getinterfacepaths(description: alljoyn_aboutobjectdescription, interfacename: super::super::Foundation::PSTR, paths: *const *const i8, numpaths: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutobjectdescription_getinterfaces(description: alljoyn_aboutobjectdescription, path: super::super::Foundation::PSTR, interfaces: *const *const i8, numinterfaces: usize) -> usize;
pub fn alljoyn_aboutobjectdescription_getmsgarg(description: alljoyn_aboutobjectdescription, msgarg: alljoyn_msgarg) -> QStatus;
pub fn alljoyn_aboutobjectdescription_getpaths(description: alljoyn_aboutobjectdescription, paths: *const *const i8, numpaths: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutobjectdescription_hasinterface(description: alljoyn_aboutobjectdescription, interfacename: super::super::Foundation::PSTR) -> u8;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutobjectdescription_hasinterfaceatpath(description: alljoyn_aboutobjectdescription, path: super::super::Foundation::PSTR, interfacename: super::super::Foundation::PSTR) -> u8;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutobjectdescription_haspath(description: alljoyn_aboutobjectdescription, path: super::super::Foundation::PSTR) -> u8;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutproxy_create(bus: alljoyn_busattachment, busname: super::super::Foundation::PSTR, sessionid: u32) -> alljoyn_aboutproxy;
pub fn alljoyn_aboutproxy_destroy(proxy: alljoyn_aboutproxy);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_aboutproxy_getaboutdata(proxy: alljoyn_aboutproxy, language: super::super::Foundation::PSTR, data: alljoyn_msgarg) -> QStatus;
pub fn alljoyn_aboutproxy_getobjectdescription(proxy: alljoyn_aboutproxy, objectdesc: alljoyn_msgarg) -> QStatus;
pub fn alljoyn_aboutproxy_getversion(proxy: alljoyn_aboutproxy, version: *mut u16) -> QStatus;
pub fn alljoyn_applicationstatelistener_create(callbacks: *const alljoyn_applicationstatelistener_callbacks, context: *mut ::core::ffi::c_void) -> alljoyn_applicationstatelistener;
pub fn alljoyn_applicationstatelistener_destroy(listener: alljoyn_applicationstatelistener);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_authlistener_create(callbacks: *const alljoyn_authlistener_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_authlistener;
pub fn alljoyn_authlistener_destroy(listener: alljoyn_authlistener);
pub fn alljoyn_authlistener_requestcredentialsresponse(listener: alljoyn_authlistener, authcontext: *mut ::core::ffi::c_void, accept: i32, credentials: alljoyn_credentials) -> QStatus;
pub fn alljoyn_authlistener_setsharedsecret(listener: alljoyn_authlistener, sharedsecret: *const u8, sharedsecretsize: usize) -> QStatus;
pub fn alljoyn_authlistener_verifycredentialsresponse(listener: alljoyn_authlistener, authcontext: *mut ::core::ffi::c_void, accept: i32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_authlistenerasync_create(callbacks: *const alljoyn_authlistenerasync_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_authlistener;
pub fn alljoyn_authlistenerasync_destroy(listener: alljoyn_authlistener);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_autopinger_adddestination(autopinger: alljoyn_autopinger, group: super::super::Foundation::PSTR, destination: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_autopinger_addpinggroup(autopinger: alljoyn_autopinger, group: super::super::Foundation::PSTR, listener: alljoyn_pinglistener, pinginterval: u32);
pub fn alljoyn_autopinger_create(bus: alljoyn_busattachment) -> alljoyn_autopinger;
pub fn alljoyn_autopinger_destroy(autopinger: alljoyn_autopinger);
pub fn alljoyn_autopinger_pause(autopinger: alljoyn_autopinger);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_autopinger_removedestination(autopinger: alljoyn_autopinger, group: super::super::Foundation::PSTR, destination: super::super::Foundation::PSTR, removeall: i32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_autopinger_removepinggroup(autopinger: alljoyn_autopinger, group: super::super::Foundation::PSTR);
pub fn alljoyn_autopinger_resume(autopinger: alljoyn_autopinger);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_autopinger_setpinginterval(autopinger: alljoyn_autopinger, group: super::super::Foundation::PSTR, pinginterval: u32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_addlogonentry(bus: alljoyn_busattachment, authmechanism: super::super::Foundation::PSTR, username: super::super::Foundation::PSTR, password: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_addmatch(bus: alljoyn_busattachment, rule: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_advertisename(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, transports: u16) -> QStatus;
pub fn alljoyn_busattachment_bindsessionport(bus: alljoyn_busattachment, sessionport: *mut u16, opts: alljoyn_sessionopts, listener: alljoyn_sessionportlistener) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_canceladvertisename(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, transports: u16) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_cancelfindadvertisedname(bus: alljoyn_busattachment, nameprefix: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_cancelfindadvertisednamebytransport(bus: alljoyn_busattachment, nameprefix: super::super::Foundation::PSTR, transports: u16) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_cancelwhoimplements_interface(bus: alljoyn_busattachment, implementsinterface: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_busattachment_cancelwhoimplements_interfaces(bus: alljoyn_busattachment, implementsinterfaces: *const *const i8, numberinterfaces: usize) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_clearkeys(bus: alljoyn_busattachment, guid: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_busattachment_clearkeystore(bus: alljoyn_busattachment);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_connect(bus: alljoyn_busattachment, connectspec: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_create(applicationname: super::super::Foundation::PSTR, allowremotemessages: i32) -> alljoyn_busattachment;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_create_concurrency(applicationname: super::super::Foundation::PSTR, allowremotemessages: i32, concurrency: u32) -> alljoyn_busattachment;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_createinterface(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, iface: *mut alljoyn_interfacedescription) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_createinterface_secure(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, iface: *mut alljoyn_interfacedescription, secpolicy: alljoyn_interfacedescription_securitypolicy) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_createinterfacesfromxml(bus: alljoyn_busattachment, xml: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_deletedefaultkeystore(applicationname: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_busattachment_deleteinterface(bus: alljoyn_busattachment, iface: alljoyn_interfacedescription) -> QStatus;
pub fn alljoyn_busattachment_destroy(bus: alljoyn_busattachment);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_disconnect(bus: alljoyn_busattachment, unused: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_busattachment_enableconcurrentcallbacks(bus: alljoyn_busattachment);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_enablepeersecurity(bus: alljoyn_busattachment, authmechanisms: super::super::Foundation::PSTR, listener: alljoyn_authlistener, keystorefilename: super::super::Foundation::PSTR, isshared: i32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_enablepeersecuritywithpermissionconfigurationlistener(bus: alljoyn_busattachment, authmechanisms: super::super::Foundation::PSTR, authlistener: alljoyn_authlistener, keystorefilename: super::super::Foundation::PSTR, isshared: i32, permissionconfigurationlistener: alljoyn_permissionconfigurationlistener) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_findadvertisedname(bus: alljoyn_busattachment, nameprefix: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_findadvertisednamebytransport(bus: alljoyn_busattachment, nameprefix: super::super::Foundation::PSTR, transports: u16) -> QStatus;
pub fn alljoyn_busattachment_getalljoyndebugobj(bus: alljoyn_busattachment) -> alljoyn_proxybusobject;
pub fn alljoyn_busattachment_getalljoynproxyobj(bus: alljoyn_busattachment) -> alljoyn_proxybusobject;
pub fn alljoyn_busattachment_getconcurrency(bus: alljoyn_busattachment) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_getconnectspec(bus: alljoyn_busattachment) -> super::super::Foundation::PSTR;
pub fn alljoyn_busattachment_getdbusproxyobj(bus: alljoyn_busattachment) -> alljoyn_proxybusobject;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_getglobalguidstring(bus: alljoyn_busattachment) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_getinterface(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR) -> alljoyn_interfacedescription;
pub fn alljoyn_busattachment_getinterfaces(bus: alljoyn_busattachment, ifaces: *const alljoyn_interfacedescription, numifaces: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_getkeyexpiration(bus: alljoyn_busattachment, guid: super::super::Foundation::PSTR, timeout: *mut u32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_getpeerguid(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, guid: super::super::Foundation::PSTR, guidsz: *mut usize) -> QStatus;
pub fn alljoyn_busattachment_getpermissionconfigurator(bus: alljoyn_busattachment) -> alljoyn_permissionconfigurator;
pub fn alljoyn_busattachment_gettimestamp() -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_getuniquename(bus: alljoyn_busattachment) -> super::super::Foundation::PSTR;
pub fn alljoyn_busattachment_isconnected(bus: alljoyn_busattachment) -> i32;
pub fn alljoyn_busattachment_ispeersecurityenabled(bus: alljoyn_busattachment) -> i32;
pub fn alljoyn_busattachment_isstarted(bus: alljoyn_busattachment) -> i32;
pub fn alljoyn_busattachment_isstopping(bus: alljoyn_busattachment) -> i32;
pub fn alljoyn_busattachment_join(bus: alljoyn_busattachment) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_joinsession(bus: alljoyn_busattachment, sessionhost: super::super::Foundation::PSTR, sessionport: u16, listener: alljoyn_sessionlistener, sessionid: *mut u32, opts: alljoyn_sessionopts) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_joinsessionasync(bus: alljoyn_busattachment, sessionhost: super::super::Foundation::PSTR, sessionport: u16, listener: alljoyn_sessionlistener, opts: alljoyn_sessionopts, callback: alljoyn_busattachment_joinsessioncb_ptr, context: *mut ::core::ffi::c_void) -> QStatus;
pub fn alljoyn_busattachment_leavesession(bus: alljoyn_busattachment, sessionid: u32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_namehasowner(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, hasowner: *mut i32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_ping(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, timeout: u32) -> QStatus;
pub fn alljoyn_busattachment_registeraboutlistener(bus: alljoyn_busattachment, aboutlistener: alljoyn_aboutlistener);
pub fn alljoyn_busattachment_registerapplicationstatelistener(bus: alljoyn_busattachment, listener: alljoyn_applicationstatelistener) -> QStatus;
pub fn alljoyn_busattachment_registerbuslistener(bus: alljoyn_busattachment, listener: alljoyn_buslistener);
pub fn alljoyn_busattachment_registerbusobject(bus: alljoyn_busattachment, obj: alljoyn_busobject) -> QStatus;
pub fn alljoyn_busattachment_registerbusobject_secure(bus: alljoyn_busattachment, obj: alljoyn_busobject) -> QStatus;
pub fn alljoyn_busattachment_registerkeystorelistener(bus: alljoyn_busattachment, listener: alljoyn_keystorelistener) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_registersignalhandler(bus: alljoyn_busattachment, signal_handler: alljoyn_messagereceiver_signalhandler_ptr, member: alljoyn_interfacedescription_member, srcpath: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_registersignalhandlerwithrule(bus: alljoyn_busattachment, signal_handler: alljoyn_messagereceiver_signalhandler_ptr, member: alljoyn_interfacedescription_member, matchrule: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_releasename(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_busattachment_reloadkeystore(bus: alljoyn_busattachment) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_removematch(bus: alljoyn_busattachment, rule: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_removesessionmember(bus: alljoyn_busattachment, sessionid: u32, membername: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_requestname(bus: alljoyn_busattachment, requestedname: super::super::Foundation::PSTR, flags: u32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_secureconnection(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, forceauth: i32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_secureconnectionasync(bus: alljoyn_busattachment, name: super::super::Foundation::PSTR, forceauth: i32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_setdaemondebug(bus: alljoyn_busattachment, module: super::super::Foundation::PSTR, level: u32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_setkeyexpiration(bus: alljoyn_busattachment, guid: super::super::Foundation::PSTR, timeout: u32) -> QStatus;
pub fn alljoyn_busattachment_setlinktimeout(bus: alljoyn_busattachment, sessionid: u32, linktimeout: *mut u32) -> QStatus;
pub fn alljoyn_busattachment_setlinktimeoutasync(bus: alljoyn_busattachment, sessionid: u32, linktimeout: u32, callback: alljoyn_busattachment_setlinktimeoutcb_ptr, context: *mut ::core::ffi::c_void) -> QStatus;
pub fn alljoyn_busattachment_setsessionlistener(bus: alljoyn_busattachment, sessionid: u32, listener: alljoyn_sessionlistener) -> QStatus;
pub fn alljoyn_busattachment_start(bus: alljoyn_busattachment) -> QStatus;
pub fn alljoyn_busattachment_stop(bus: alljoyn_busattachment) -> QStatus;
pub fn alljoyn_busattachment_unbindsessionport(bus: alljoyn_busattachment, sessionport: u16) -> QStatus;
pub fn alljoyn_busattachment_unregisteraboutlistener(bus: alljoyn_busattachment, aboutlistener: alljoyn_aboutlistener);
pub fn alljoyn_busattachment_unregisterallaboutlisteners(bus: alljoyn_busattachment);
pub fn alljoyn_busattachment_unregisterallhandlers(bus: alljoyn_busattachment) -> QStatus;
pub fn alljoyn_busattachment_unregisterapplicationstatelistener(bus: alljoyn_busattachment, listener: alljoyn_applicationstatelistener) -> QStatus;
pub fn alljoyn_busattachment_unregisterbuslistener(bus: alljoyn_busattachment, listener: alljoyn_buslistener);
pub fn alljoyn_busattachment_unregisterbusobject(bus: alljoyn_busattachment, object: alljoyn_busobject);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_unregistersignalhandler(bus: alljoyn_busattachment, signal_handler: alljoyn_messagereceiver_signalhandler_ptr, member: alljoyn_interfacedescription_member, srcpath: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_unregistersignalhandlerwithrule(bus: alljoyn_busattachment, signal_handler: alljoyn_messagereceiver_signalhandler_ptr, member: alljoyn_interfacedescription_member, matchrule: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busattachment_whoimplements_interface(bus: alljoyn_busattachment, implementsinterface: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_busattachment_whoimplements_interfaces(bus: alljoyn_busattachment, implementsinterfaces: *const *const i8, numberinterfaces: usize) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_buslistener_create(callbacks: *const alljoyn_buslistener_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_buslistener;
pub fn alljoyn_buslistener_destroy(listener: alljoyn_buslistener);
pub fn alljoyn_busobject_addinterface(bus: alljoyn_busobject, iface: alljoyn_interfacedescription) -> QStatus;
pub fn alljoyn_busobject_addinterface_announced(bus: alljoyn_busobject, iface: alljoyn_interfacedescription) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_addmethodhandler(bus: alljoyn_busobject, member: alljoyn_interfacedescription_member, handler: alljoyn_messagereceiver_methodhandler_ptr, context: *mut ::core::ffi::c_void) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_addmethodhandlers(bus: alljoyn_busobject, entries: *const alljoyn_busobject_methodentry, numentries: usize) -> QStatus;
pub fn alljoyn_busobject_cancelsessionlessmessage(bus: alljoyn_busobject, msg: alljoyn_message) -> QStatus;
pub fn alljoyn_busobject_cancelsessionlessmessage_serial(bus: alljoyn_busobject, serialnumber: u32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_create(path: super::super::Foundation::PSTR, isplaceholder: i32, callbacks_in: *const alljoyn_busobject_callbacks, context_in: *const ::core::ffi::c_void) -> alljoyn_busobject;
pub fn alljoyn_busobject_destroy(bus: alljoyn_busobject);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_emitpropertieschanged(bus: alljoyn_busobject, ifcname: super::super::Foundation::PSTR, propnames: *const *const i8, numprops: usize, id: u32);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_emitpropertychanged(bus: alljoyn_busobject, ifcname: super::super::Foundation::PSTR, propname: super::super::Foundation::PSTR, val: alljoyn_msgarg, id: u32);
pub fn alljoyn_busobject_getannouncedinterfacenames(bus: alljoyn_busobject, interfaces: *const *const i8, numinterfaces: usize) -> usize;
pub fn alljoyn_busobject_getbusattachment(bus: alljoyn_busobject) -> alljoyn_busattachment;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_getname(bus: alljoyn_busobject, buffer: super::super::Foundation::PSTR, buffersz: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_getpath(bus: alljoyn_busobject) -> super::super::Foundation::PSTR;
pub fn alljoyn_busobject_issecure(bus: alljoyn_busobject) -> i32;
pub fn alljoyn_busobject_methodreply_args(bus: alljoyn_busobject, msg: alljoyn_message, args: alljoyn_msgarg, numargs: usize) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_methodreply_err(bus: alljoyn_busobject, msg: alljoyn_message, error: super::super::Foundation::PSTR, errormessage: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_busobject_methodreply_status(bus: alljoyn_busobject, msg: alljoyn_message, status: QStatus) -> QStatus;
pub fn alljoyn_busobject_setannounceflag(bus: alljoyn_busobject, iface: alljoyn_interfacedescription, isannounced: alljoyn_about_announceflag) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_busobject_signal(bus: alljoyn_busobject, destination: super::super::Foundation::PSTR, sessionid: u32, signal: alljoyn_interfacedescription_member, args: alljoyn_msgarg, numargs: usize, timetolive: u16, flags: u8, msg: alljoyn_message) -> QStatus;
pub fn alljoyn_credentials_clear(cred: alljoyn_credentials);
pub fn alljoyn_credentials_create() -> alljoyn_credentials;
pub fn alljoyn_credentials_destroy(cred: alljoyn_credentials);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_getcertchain(cred: alljoyn_credentials) -> super::super::Foundation::PSTR;
pub fn alljoyn_credentials_getexpiration(cred: alljoyn_credentials) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_getlogonentry(cred: alljoyn_credentials) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_getpassword(cred: alljoyn_credentials) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_getprivateKey(cred: alljoyn_credentials) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_getusername(cred: alljoyn_credentials) -> super::super::Foundation::PSTR;
pub fn alljoyn_credentials_isset(cred: alljoyn_credentials, creds: u16) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_setcertchain(cred: alljoyn_credentials, certchain: super::super::Foundation::PSTR);
pub fn alljoyn_credentials_setexpiration(cred: alljoyn_credentials, expiration: u32);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_setlogonentry(cred: alljoyn_credentials, logonentry: super::super::Foundation::PSTR);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_setpassword(cred: alljoyn_credentials, pwd: super::super::Foundation::PSTR);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_setprivatekey(cred: alljoyn_credentials, pk: super::super::Foundation::PSTR);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_credentials_setusername(cred: alljoyn_credentials, username: super::super::Foundation::PSTR);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_getbuildinfo() -> super::super::Foundation::PSTR;
pub fn alljoyn_getnumericversion() -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_getversion() -> super::super::Foundation::PSTR;
pub fn alljoyn_init() -> QStatus;
pub fn alljoyn_interfacedescription_activate(iface: alljoyn_interfacedescription);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addannotation(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addargannotation(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, argname: super::super::Foundation::PSTR, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addmember(iface: alljoyn_interfacedescription, r#type: alljoyn_messagetype, name: super::super::Foundation::PSTR, inputsig: super::super::Foundation::PSTR, outsig: super::super::Foundation::PSTR, argnames: super::super::Foundation::PSTR, annotation: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addmemberannotation(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addmethod(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, inputsig: super::super::Foundation::PSTR, outsig: super::super::Foundation::PSTR, argnames: super::super::Foundation::PSTR, annotation: u8, accessperms: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addproperty(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, signature: super::super::Foundation::PSTR, access: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addpropertyannotation(iface: alljoyn_interfacedescription, property: super::super::Foundation::PSTR, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_addsignal(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, sig: super::super::Foundation::PSTR, argnames: super::super::Foundation::PSTR, annotation: u8, accessperms: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_interfacedescription_eql(one: alljoyn_interfacedescription, other: alljoyn_interfacedescription) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getannotation(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR, value_size: *mut usize) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getannotationatindex(iface: alljoyn_interfacedescription, index: usize, name: super::super::Foundation::PSTR, name_size: *mut usize, value: super::super::Foundation::PSTR, value_size: *mut usize);
pub fn alljoyn_interfacedescription_getannotationscount(iface: alljoyn_interfacedescription) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getargdescriptionforlanguage(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, arg: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR, maxlanguagelength: usize, languagetag: super::super::Foundation::PSTR) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getdescriptionforlanguage(iface: alljoyn_interfacedescription, description: super::super::Foundation::PSTR, maxlanguagelength: usize, languagetag: super::super::Foundation::PSTR) -> usize;
pub fn alljoyn_interfacedescription_getdescriptionlanguages(iface: alljoyn_interfacedescription, languages: *const *const i8, size: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getdescriptionlanguages2(iface: alljoyn_interfacedescription, languages: super::super::Foundation::PSTR, languagessize: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getdescriptiontranslationcallback(iface: alljoyn_interfacedescription) -> alljoyn_interfacedescription_translation_callback_ptr;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getmember(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, member: *mut alljoyn_interfacedescription_member) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getmemberannotation(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR, value_size: *mut usize) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getmemberargannotation(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, argname: super::super::Foundation::PSTR, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR, value_size: *mut usize) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getmemberdescriptionforlanguage(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR, maxlanguagelength: usize, languagetag: super::super::Foundation::PSTR) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getmembers(iface: alljoyn_interfacedescription, members: *mut alljoyn_interfacedescription_member, nummembers: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getmethod(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, member: *mut alljoyn_interfacedescription_member) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getname(iface: alljoyn_interfacedescription) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getproperties(iface: alljoyn_interfacedescription, props: *mut alljoyn_interfacedescription_property, numprops: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getproperty(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, property: *mut alljoyn_interfacedescription_property) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getpropertyannotation(iface: alljoyn_interfacedescription, property: super::super::Foundation::PSTR, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR, str_size: *mut usize) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getpropertydescriptionforlanguage(iface: alljoyn_interfacedescription, property: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR, maxlanguagelength: usize, languagetag: super::super::Foundation::PSTR) -> usize;
pub fn alljoyn_interfacedescription_getsecuritypolicy(iface: alljoyn_interfacedescription) -> alljoyn_interfacedescription_securitypolicy;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_getsignal(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, member: *mut alljoyn_interfacedescription_member) -> i32;
pub fn alljoyn_interfacedescription_hasdescription(iface: alljoyn_interfacedescription) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_hasmember(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, insig: super::super::Foundation::PSTR, outsig: super::super::Foundation::PSTR) -> i32;
pub fn alljoyn_interfacedescription_hasproperties(iface: alljoyn_interfacedescription) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_hasproperty(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_introspect(iface: alljoyn_interfacedescription, str: super::super::Foundation::PSTR, buf: usize, indent: usize) -> usize;
pub fn alljoyn_interfacedescription_issecure(iface: alljoyn_interfacedescription) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_member_eql(one: alljoyn_interfacedescription_member, other: alljoyn_interfacedescription_member) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_member_getannotation(member: alljoyn_interfacedescription_member, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR, value_size: *mut usize) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_member_getannotationatindex(member: alljoyn_interfacedescription_member, index: usize, name: super::super::Foundation::PSTR, name_size: *mut usize, value: super::super::Foundation::PSTR, value_size: *mut usize);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_member_getannotationscount(member: alljoyn_interfacedescription_member) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_member_getargannotation(member: alljoyn_interfacedescription_member, argname: super::super::Foundation::PSTR, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR, value_size: *mut usize) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_member_getargannotationatindex(member: alljoyn_interfacedescription_member, argname: super::super::Foundation::PSTR, index: usize, name: super::super::Foundation::PSTR, name_size: *mut usize, value: super::super::Foundation::PSTR, value_size: *mut usize);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_member_getargannotationscount(member: alljoyn_interfacedescription_member, argname: super::super::Foundation::PSTR) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_property_eql(one: alljoyn_interfacedescription_property, other: alljoyn_interfacedescription_property) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_property_getannotation(property: alljoyn_interfacedescription_property, name: super::super::Foundation::PSTR, value: super::super::Foundation::PSTR, value_size: *mut usize) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_property_getannotationatindex(property: alljoyn_interfacedescription_property, index: usize, name: super::super::Foundation::PSTR, name_size: *mut usize, value: super::super::Foundation::PSTR, value_size: *mut usize);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_property_getannotationscount(property: alljoyn_interfacedescription_property) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setargdescription(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, argname: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setargdescriptionforlanguage(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, arg: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR, languagetag: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setdescription(iface: alljoyn_interfacedescription, description: super::super::Foundation::PSTR);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setdescriptionforlanguage(iface: alljoyn_interfacedescription, description: super::super::Foundation::PSTR, languagetag: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setdescriptionlanguage(iface: alljoyn_interfacedescription, language: super::super::Foundation::PSTR);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setdescriptiontranslationcallback(iface: alljoyn_interfacedescription, translationcallback: alljoyn_interfacedescription_translation_callback_ptr);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setmemberdescription(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setmemberdescriptionforlanguage(iface: alljoyn_interfacedescription, member: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR, languagetag: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setpropertydescription(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_interfacedescription_setpropertydescriptionforlanguage(iface: alljoyn_interfacedescription, name: super::super::Foundation::PSTR, description: super::super::Foundation::PSTR, languagetag: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_keystorelistener_create(callbacks: *const alljoyn_keystorelistener_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_keystorelistener;
pub fn alljoyn_keystorelistener_destroy(listener: alljoyn_keystorelistener);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_keystorelistener_getkeys(listener: alljoyn_keystorelistener, keystore: alljoyn_keystore, sink: super::super::Foundation::PSTR, sink_sz: *mut usize) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_keystorelistener_putkeys(listener: alljoyn_keystorelistener, keystore: alljoyn_keystore, source: super::super::Foundation::PSTR, password: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_keystorelistener_with_synchronization_create(callbacks: *const alljoyn_keystorelistener_with_synchronization_callbacks, context: *mut ::core::ffi::c_void) -> alljoyn_keystorelistener;
pub fn alljoyn_message_create(bus: alljoyn_busattachment) -> alljoyn_message;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_description(msg: alljoyn_message, str: super::super::Foundation::PSTR, buf: usize) -> usize;
pub fn alljoyn_message_destroy(msg: alljoyn_message);
pub fn alljoyn_message_eql(one: alljoyn_message, other: alljoyn_message) -> i32;
pub fn alljoyn_message_getarg(msg: alljoyn_message, argn: usize) -> alljoyn_msgarg;
pub fn alljoyn_message_getargs(msg: alljoyn_message, numargs: *mut usize, args: *mut alljoyn_msgarg);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getauthmechanism(msg: alljoyn_message) -> super::super::Foundation::PSTR;
pub fn alljoyn_message_getcallserial(msg: alljoyn_message) -> u32;
pub fn alljoyn_message_getcompressiontoken(msg: alljoyn_message) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getdestination(msg: alljoyn_message) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_geterrorname(msg: alljoyn_message, errormessage: super::super::Foundation::PSTR, errormessage_size: *mut usize) -> super::super::Foundation::PSTR;
pub fn alljoyn_message_getflags(msg: alljoyn_message) -> u8;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getinterface(msg: alljoyn_message) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getmembername(msg: alljoyn_message) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getobjectpath(msg: alljoyn_message) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getreceiveendpointname(msg: alljoyn_message) -> super::super::Foundation::PSTR;
pub fn alljoyn_message_getreplyserial(msg: alljoyn_message) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getsender(msg: alljoyn_message) -> super::super::Foundation::PSTR;
pub fn alljoyn_message_getsessionid(msg: alljoyn_message) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_getsignature(msg: alljoyn_message) -> super::super::Foundation::PSTR;
pub fn alljoyn_message_gettimestamp(msg: alljoyn_message) -> u32;
pub fn alljoyn_message_gettype(msg: alljoyn_message) -> alljoyn_messagetype;
pub fn alljoyn_message_isbroadcastsignal(msg: alljoyn_message) -> i32;
pub fn alljoyn_message_isencrypted(msg: alljoyn_message) -> i32;
pub fn alljoyn_message_isexpired(msg: alljoyn_message, tillexpirems: *mut u32) -> i32;
pub fn alljoyn_message_isglobalbroadcast(msg: alljoyn_message) -> i32;
pub fn alljoyn_message_issessionless(msg: alljoyn_message) -> i32;
pub fn alljoyn_message_isunreliable(msg: alljoyn_message) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_parseargs(msg: alljoyn_message, signature: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_message_setendianess(endian: i8);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_message_tostring(msg: alljoyn_message, str: super::super::Foundation::PSTR, buf: usize) -> usize;
pub fn alljoyn_msgarg_array_create(size: usize) -> alljoyn_msgarg;
pub fn alljoyn_msgarg_array_element(arg: alljoyn_msgarg, index: usize) -> alljoyn_msgarg;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_array_get(args: alljoyn_msgarg, numargs: usize, signature: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_array_set(args: alljoyn_msgarg, numargs: *mut usize, signature: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_array_set_offset(args: alljoyn_msgarg, argoffset: usize, numargs: *mut usize, signature: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_array_signature(values: alljoyn_msgarg, numvalues: usize, str: super::super::Foundation::PSTR, buf: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_array_tostring(args: alljoyn_msgarg, numargs: usize, str: super::super::Foundation::PSTR, buf: usize, indent: usize) -> usize;
pub fn alljoyn_msgarg_clear(arg: alljoyn_msgarg);
pub fn alljoyn_msgarg_clone(destination: alljoyn_msgarg, source: alljoyn_msgarg);
pub fn alljoyn_msgarg_copy(source: alljoyn_msgarg) -> alljoyn_msgarg;
pub fn alljoyn_msgarg_create() -> alljoyn_msgarg;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_create_and_set(signature: super::super::Foundation::PSTR) -> alljoyn_msgarg;
pub fn alljoyn_msgarg_destroy(arg: alljoyn_msgarg);
pub fn alljoyn_msgarg_equal(lhv: alljoyn_msgarg, rhv: alljoyn_msgarg) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_get(arg: alljoyn_msgarg, signature: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_msgarg_get_array_element(arg: alljoyn_msgarg, index: usize, element: *mut alljoyn_msgarg);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_get_array_elementsignature(arg: alljoyn_msgarg, index: usize) -> super::super::Foundation::PSTR;
pub fn alljoyn_msgarg_get_array_numberofelements(arg: alljoyn_msgarg) -> usize;
pub fn alljoyn_msgarg_get_bool(arg: alljoyn_msgarg, b: *mut i32) -> QStatus;
pub fn alljoyn_msgarg_get_bool_array(arg: alljoyn_msgarg, length: *mut usize, ab: *mut i32) -> QStatus;
pub fn alljoyn_msgarg_get_double(arg: alljoyn_msgarg, d: *mut f64) -> QStatus;
pub fn alljoyn_msgarg_get_double_array(arg: alljoyn_msgarg, length: *mut usize, ad: *mut f64) -> QStatus;
pub fn alljoyn_msgarg_get_int16(arg: alljoyn_msgarg, n: *mut i16) -> QStatus;
pub fn alljoyn_msgarg_get_int16_array(arg: alljoyn_msgarg, length: *mut usize, an: *mut i16) -> QStatus;
pub fn alljoyn_msgarg_get_int32(arg: alljoyn_msgarg, i: *mut i32) -> QStatus;
pub fn alljoyn_msgarg_get_int32_array(arg: alljoyn_msgarg, length: *mut usize, ai: *mut i32) -> QStatus;
pub fn alljoyn_msgarg_get_int64(arg: alljoyn_msgarg, x: *mut i64) -> QStatus;
pub fn alljoyn_msgarg_get_int64_array(arg: alljoyn_msgarg, length: *mut usize, ax: *mut i64) -> QStatus;
pub fn alljoyn_msgarg_get_objectpath(arg: alljoyn_msgarg, o: *mut *mut i8) -> QStatus;
pub fn alljoyn_msgarg_get_signature(arg: alljoyn_msgarg, g: *mut *mut i8) -> QStatus;
pub fn alljoyn_msgarg_get_string(arg: alljoyn_msgarg, s: *mut *mut i8) -> QStatus;
pub fn alljoyn_msgarg_get_uint16(arg: alljoyn_msgarg, q: *mut u16) -> QStatus;
pub fn alljoyn_msgarg_get_uint16_array(arg: alljoyn_msgarg, length: *mut usize, aq: *mut u16) -> QStatus;
pub fn alljoyn_msgarg_get_uint32(arg: alljoyn_msgarg, u: *mut u32) -> QStatus;
pub fn alljoyn_msgarg_get_uint32_array(arg: alljoyn_msgarg, length: *mut usize, au: *mut u32) -> QStatus;
pub fn alljoyn_msgarg_get_uint64(arg: alljoyn_msgarg, t: *mut u64) -> QStatus;
pub fn alljoyn_msgarg_get_uint64_array(arg: alljoyn_msgarg, length: *mut usize, at: *mut u64) -> QStatus;
pub fn alljoyn_msgarg_get_uint8(arg: alljoyn_msgarg, y: *mut u8) -> QStatus;
pub fn alljoyn_msgarg_get_uint8_array(arg: alljoyn_msgarg, length: *mut usize, ay: *mut u8) -> QStatus;
pub fn alljoyn_msgarg_get_variant(arg: alljoyn_msgarg, v: alljoyn_msgarg) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_get_variant_array(arg: alljoyn_msgarg, signature: super::super::Foundation::PSTR, length: *mut usize, av: *mut alljoyn_msgarg) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_getdictelement(arg: alljoyn_msgarg, elemsig: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_msgarg_getkey(arg: alljoyn_msgarg) -> alljoyn_msgarg;
pub fn alljoyn_msgarg_getmember(arg: alljoyn_msgarg, index: usize) -> alljoyn_msgarg;
pub fn alljoyn_msgarg_getnummembers(arg: alljoyn_msgarg) -> usize;
pub fn alljoyn_msgarg_gettype(arg: alljoyn_msgarg) -> alljoyn_typeid;
pub fn alljoyn_msgarg_getvalue(arg: alljoyn_msgarg) -> alljoyn_msgarg;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_hassignature(arg: alljoyn_msgarg, signature: super::super::Foundation::PSTR) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_set(arg: alljoyn_msgarg, signature: super::super::Foundation::PSTR) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_set_and_stabilize(arg: alljoyn_msgarg, signature: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_msgarg_set_bool(arg: alljoyn_msgarg, b: i32) -> QStatus;
pub fn alljoyn_msgarg_set_bool_array(arg: alljoyn_msgarg, length: usize, ab: *mut i32) -> QStatus;
pub fn alljoyn_msgarg_set_double(arg: alljoyn_msgarg, d: f64) -> QStatus;
pub fn alljoyn_msgarg_set_double_array(arg: alljoyn_msgarg, length: usize, ad: *mut f64) -> QStatus;
pub fn alljoyn_msgarg_set_int16(arg: alljoyn_msgarg, n: i16) -> QStatus;
pub fn alljoyn_msgarg_set_int16_array(arg: alljoyn_msgarg, length: usize, an: *mut i16) -> QStatus;
pub fn alljoyn_msgarg_set_int32(arg: alljoyn_msgarg, i: i32) -> QStatus;
pub fn alljoyn_msgarg_set_int32_array(arg: alljoyn_msgarg, length: usize, ai: *mut i32) -> QStatus;
pub fn alljoyn_msgarg_set_int64(arg: alljoyn_msgarg, x: i64) -> QStatus;
pub fn alljoyn_msgarg_set_int64_array(arg: alljoyn_msgarg, length: usize, ax: *mut i64) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_set_objectpath(arg: alljoyn_msgarg, o: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_msgarg_set_objectpath_array(arg: alljoyn_msgarg, length: usize, ao: *const *const i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_set_signature(arg: alljoyn_msgarg, g: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_msgarg_set_signature_array(arg: alljoyn_msgarg, length: usize, ag: *const *const i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_set_string(arg: alljoyn_msgarg, s: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_msgarg_set_string_array(arg: alljoyn_msgarg, length: usize, r#as: *const *const i8) -> QStatus;
pub fn alljoyn_msgarg_set_uint16(arg: alljoyn_msgarg, q: u16) -> QStatus;
pub fn alljoyn_msgarg_set_uint16_array(arg: alljoyn_msgarg, length: usize, aq: *mut u16) -> QStatus;
pub fn alljoyn_msgarg_set_uint32(arg: alljoyn_msgarg, u: u32) -> QStatus;
pub fn alljoyn_msgarg_set_uint32_array(arg: alljoyn_msgarg, length: usize, au: *mut u32) -> QStatus;
pub fn alljoyn_msgarg_set_uint64(arg: alljoyn_msgarg, t: u64) -> QStatus;
pub fn alljoyn_msgarg_set_uint64_array(arg: alljoyn_msgarg, length: usize, at: *mut u64) -> QStatus;
pub fn alljoyn_msgarg_set_uint8(arg: alljoyn_msgarg, y: u8) -> QStatus;
pub fn alljoyn_msgarg_set_uint8_array(arg: alljoyn_msgarg, length: usize, ay: *mut u8) -> QStatus;
pub fn alljoyn_msgarg_setdictentry(arg: alljoyn_msgarg, key: alljoyn_msgarg, value: alljoyn_msgarg) -> QStatus;
pub fn alljoyn_msgarg_setstruct(arg: alljoyn_msgarg, struct_members: alljoyn_msgarg, num_members: usize) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_signature(arg: alljoyn_msgarg, str: super::super::Foundation::PSTR, buf: usize) -> usize;
pub fn alljoyn_msgarg_stabilize(arg: alljoyn_msgarg);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_msgarg_tostring(arg: alljoyn_msgarg, str: super::super::Foundation::PSTR, buf: usize, indent: usize) -> usize;
pub fn alljoyn_observer_create(bus: alljoyn_busattachment, mandatoryinterfaces: *const *const i8, nummandatoryinterfaces: usize) -> alljoyn_observer;
pub fn alljoyn_observer_destroy(observer: alljoyn_observer);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_observer_get(observer: alljoyn_observer, uniquebusname: super::super::Foundation::PSTR, objectpath: super::super::Foundation::PSTR) -> alljoyn_proxybusobject_ref;
pub fn alljoyn_observer_getfirst(observer: alljoyn_observer) -> alljoyn_proxybusobject_ref;
pub fn alljoyn_observer_getnext(observer: alljoyn_observer, proxyref: alljoyn_proxybusobject_ref) -> alljoyn_proxybusobject_ref;
pub fn alljoyn_observer_registerlistener(observer: alljoyn_observer, listener: alljoyn_observerlistener, triggeronexisting: i32);
pub fn alljoyn_observer_unregisteralllisteners(observer: alljoyn_observer);
pub fn alljoyn_observer_unregisterlistener(observer: alljoyn_observer, listener: alljoyn_observerlistener);
pub fn alljoyn_observerlistener_create(callback: *const alljoyn_observerlistener_callback, context: *const ::core::ffi::c_void) -> alljoyn_observerlistener;
pub fn alljoyn_observerlistener_destroy(listener: alljoyn_observerlistener);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_passwordmanager_setcredentials(authmechanism: super::super::Foundation::PSTR, password: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_permissionconfigurationlistener_create(callbacks: *const alljoyn_permissionconfigurationlistener_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_permissionconfigurationlistener;
pub fn alljoyn_permissionconfigurationlistener_destroy(listener: alljoyn_permissionconfigurationlistener);
pub fn alljoyn_permissionconfigurator_certificatechain_destroy(certificatechain: *mut i8);
pub fn alljoyn_permissionconfigurator_certificateid_cleanup(certificateid: *mut alljoyn_certificateid);
pub fn alljoyn_permissionconfigurator_certificateidarray_cleanup(certificateidarray: *mut alljoyn_certificateidarray);
pub fn alljoyn_permissionconfigurator_claim(configurator: alljoyn_permissionconfigurator, cakey: *mut i8, identitycertificatechain: *mut i8, groupid: *const u8, groupsize: usize, groupauthority: *mut i8, manifestsxmls: *mut *mut i8, manifestscount: usize) -> QStatus;
pub fn alljoyn_permissionconfigurator_endmanagement(configurator: alljoyn_permissionconfigurator) -> QStatus;
pub fn alljoyn_permissionconfigurator_getapplicationstate(configurator: alljoyn_permissionconfigurator, state: *mut alljoyn_applicationstate) -> QStatus;
pub fn alljoyn_permissionconfigurator_getclaimcapabilities(configurator: alljoyn_permissionconfigurator, claimcapabilities: *mut u16) -> QStatus;
pub fn alljoyn_permissionconfigurator_getclaimcapabilitiesadditionalinfo(configurator: alljoyn_permissionconfigurator, additionalinfo: *mut u16) -> QStatus;
pub fn alljoyn_permissionconfigurator_getdefaultclaimcapabilities() -> u16;
pub fn alljoyn_permissionconfigurator_getdefaultpolicy(configurator: alljoyn_permissionconfigurator, policyxml: *mut *mut i8) -> QStatus;
pub fn alljoyn_permissionconfigurator_getidentity(configurator: alljoyn_permissionconfigurator, identitycertificatechain: *mut *mut i8) -> QStatus;
pub fn alljoyn_permissionconfigurator_getidentitycertificateid(configurator: alljoyn_permissionconfigurator, certificateid: *mut alljoyn_certificateid) -> QStatus;
pub fn alljoyn_permissionconfigurator_getmanifests(configurator: alljoyn_permissionconfigurator, manifestarray: *mut alljoyn_manifestarray) -> QStatus;
pub fn alljoyn_permissionconfigurator_getmanifesttemplate(configurator: alljoyn_permissionconfigurator, manifesttemplatexml: *mut *mut i8) -> QStatus;
pub fn alljoyn_permissionconfigurator_getmembershipsummaries(configurator: alljoyn_permissionconfigurator, certificateids: *mut alljoyn_certificateidarray) -> QStatus;
pub fn alljoyn_permissionconfigurator_getpolicy(configurator: alljoyn_permissionconfigurator, policyxml: *mut *mut i8) -> QStatus;
pub fn alljoyn_permissionconfigurator_getpublickey(configurator: alljoyn_permissionconfigurator, publickey: *mut *mut i8) -> QStatus;
pub fn alljoyn_permissionconfigurator_installmanifests(configurator: alljoyn_permissionconfigurator, manifestsxmls: *mut *mut i8, manifestscount: usize, append: i32) -> QStatus;
pub fn alljoyn_permissionconfigurator_installmembership(configurator: alljoyn_permissionconfigurator, membershipcertificatechain: *mut i8) -> QStatus;
pub fn alljoyn_permissionconfigurator_manifestarray_cleanup(manifestarray: *mut alljoyn_manifestarray);
pub fn alljoyn_permissionconfigurator_manifesttemplate_destroy(manifesttemplatexml: *mut i8);
pub fn alljoyn_permissionconfigurator_policy_destroy(policyxml: *mut i8);
pub fn alljoyn_permissionconfigurator_publickey_destroy(publickey: *mut i8);
pub fn alljoyn_permissionconfigurator_removemembership(configurator: alljoyn_permissionconfigurator, serial: *const u8, seriallen: usize, issuerpublickey: *mut i8, issueraki: *const u8, issuerakilen: usize) -> QStatus;
pub fn alljoyn_permissionconfigurator_reset(configurator: alljoyn_permissionconfigurator) -> QStatus;
pub fn alljoyn_permissionconfigurator_resetpolicy(configurator: alljoyn_permissionconfigurator) -> QStatus;
pub fn alljoyn_permissionconfigurator_setapplicationstate(configurator: alljoyn_permissionconfigurator, state: alljoyn_applicationstate) -> QStatus;
pub fn alljoyn_permissionconfigurator_setclaimcapabilities(configurator: alljoyn_permissionconfigurator, claimcapabilities: u16) -> QStatus;
pub fn alljoyn_permissionconfigurator_setclaimcapabilitiesadditionalinfo(configurator: alljoyn_permissionconfigurator, additionalinfo: u16) -> QStatus;
pub fn alljoyn_permissionconfigurator_setmanifesttemplatefromxml(configurator: alljoyn_permissionconfigurator, manifesttemplatexml: *mut i8) -> QStatus;
pub fn alljoyn_permissionconfigurator_startmanagement(configurator: alljoyn_permissionconfigurator) -> QStatus;
pub fn alljoyn_permissionconfigurator_updateidentity(configurator: alljoyn_permissionconfigurator, identitycertificatechain: *mut i8, manifestsxmls: *mut *mut i8, manifestscount: usize) -> QStatus;
pub fn alljoyn_permissionconfigurator_updatepolicy(configurator: alljoyn_permissionconfigurator, policyxml: *mut i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_pinglistener_create(callback: *const alljoyn_pinglistener_callback, context: *const ::core::ffi::c_void) -> alljoyn_pinglistener;
pub fn alljoyn_pinglistener_destroy(listener: alljoyn_pinglistener);
pub fn alljoyn_proxybusobject_addchild(proxyobj: alljoyn_proxybusobject, child: alljoyn_proxybusobject) -> QStatus;
pub fn alljoyn_proxybusobject_addinterface(proxyobj: alljoyn_proxybusobject, iface: alljoyn_interfacedescription) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_addinterface_by_name(proxyobj: alljoyn_proxybusobject, name: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_proxybusobject_copy(source: alljoyn_proxybusobject) -> alljoyn_proxybusobject;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_create(bus: alljoyn_busattachment, service: super::super::Foundation::PSTR, path: super::super::Foundation::PSTR, sessionid: u32) -> alljoyn_proxybusobject;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_create_secure(bus: alljoyn_busattachment, service: super::super::Foundation::PSTR, path: super::super::Foundation::PSTR, sessionid: u32) -> alljoyn_proxybusobject;
pub fn alljoyn_proxybusobject_destroy(proxyobj: alljoyn_proxybusobject);
pub fn alljoyn_proxybusobject_enablepropertycaching(proxyobj: alljoyn_proxybusobject);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getallproperties(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, values: alljoyn_msgarg) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getallpropertiesasync(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, callback: alljoyn_proxybusobject_listener_getallpropertiescb_ptr, timeout: u32, context: *mut ::core::ffi::c_void) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getchild(proxyobj: alljoyn_proxybusobject, path: super::super::Foundation::PSTR) -> alljoyn_proxybusobject;
pub fn alljoyn_proxybusobject_getchildren(proxyobj: alljoyn_proxybusobject, children: *mut alljoyn_proxybusobject, numchildren: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getinterface(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR) -> alljoyn_interfacedescription;
pub fn alljoyn_proxybusobject_getinterfaces(proxyobj: alljoyn_proxybusobject, ifaces: *const alljoyn_interfacedescription, numifaces: usize) -> usize;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getpath(proxyobj: alljoyn_proxybusobject) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getproperty(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, property: super::super::Foundation::PSTR, value: alljoyn_msgarg) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getpropertyasync(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, property: super::super::Foundation::PSTR, callback: alljoyn_proxybusobject_listener_getpropertycb_ptr, timeout: u32, context: *mut ::core::ffi::c_void) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getservicename(proxyobj: alljoyn_proxybusobject) -> super::super::Foundation::PSTR;
pub fn alljoyn_proxybusobject_getsessionid(proxyobj: alljoyn_proxybusobject) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_getuniquename(proxyobj: alljoyn_proxybusobject) -> super::super::Foundation::PSTR;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_implementsinterface(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR) -> i32;
pub fn alljoyn_proxybusobject_introspectremoteobject(proxyobj: alljoyn_proxybusobject) -> QStatus;
pub fn alljoyn_proxybusobject_introspectremoteobjectasync(proxyobj: alljoyn_proxybusobject, callback: alljoyn_proxybusobject_listener_introspectcb_ptr, context: *mut ::core::ffi::c_void) -> QStatus;
pub fn alljoyn_proxybusobject_issecure(proxyobj: alljoyn_proxybusobject) -> i32;
pub fn alljoyn_proxybusobject_isvalid(proxyobj: alljoyn_proxybusobject) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_methodcall(proxyobj: alljoyn_proxybusobject, ifacename: super::super::Foundation::PSTR, methodname: super::super::Foundation::PSTR, args: alljoyn_msgarg, numargs: usize, replymsg: alljoyn_message, timeout: u32, flags: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_methodcall_member(proxyobj: alljoyn_proxybusobject, method: alljoyn_interfacedescription_member, args: alljoyn_msgarg, numargs: usize, replymsg: alljoyn_message, timeout: u32, flags: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_methodcall_member_noreply(proxyobj: alljoyn_proxybusobject, method: alljoyn_interfacedescription_member, args: alljoyn_msgarg, numargs: usize, flags: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_methodcall_noreply(proxyobj: alljoyn_proxybusobject, ifacename: super::super::Foundation::PSTR, methodname: super::super::Foundation::PSTR, args: alljoyn_msgarg, numargs: usize, flags: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_methodcallasync(proxyobj: alljoyn_proxybusobject, ifacename: super::super::Foundation::PSTR, methodname: super::super::Foundation::PSTR, replyfunc: alljoyn_messagereceiver_replyhandler_ptr, args: alljoyn_msgarg, numargs: usize, context: *mut ::core::ffi::c_void, timeout: u32, flags: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_methodcallasync_member(proxyobj: alljoyn_proxybusobject, method: alljoyn_interfacedescription_member, replyfunc: alljoyn_messagereceiver_replyhandler_ptr, args: alljoyn_msgarg, numargs: usize, context: *mut ::core::ffi::c_void, timeout: u32, flags: u8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_parsexml(proxyobj: alljoyn_proxybusobject, xml: super::super::Foundation::PSTR, identifier: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_proxybusobject_ref_create(proxy: alljoyn_proxybusobject) -> alljoyn_proxybusobject_ref;
pub fn alljoyn_proxybusobject_ref_decref(r#ref: alljoyn_proxybusobject_ref);
pub fn alljoyn_proxybusobject_ref_get(r#ref: alljoyn_proxybusobject_ref) -> alljoyn_proxybusobject;
pub fn alljoyn_proxybusobject_ref_incref(r#ref: alljoyn_proxybusobject_ref);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_registerpropertieschangedlistener(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, properties: *const *const i8, numproperties: usize, callback: alljoyn_proxybusobject_listener_propertieschanged_ptr, context: *mut ::core::ffi::c_void) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_removechild(proxyobj: alljoyn_proxybusobject, path: super::super::Foundation::PSTR) -> QStatus;
pub fn alljoyn_proxybusobject_secureconnection(proxyobj: alljoyn_proxybusobject, forceauth: i32) -> QStatus;
pub fn alljoyn_proxybusobject_secureconnectionasync(proxyobj: alljoyn_proxybusobject, forceauth: i32) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_setproperty(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, property: super::super::Foundation::PSTR, value: alljoyn_msgarg) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_setpropertyasync(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, property: super::super::Foundation::PSTR, value: alljoyn_msgarg, callback: alljoyn_proxybusobject_listener_setpropertycb_ptr, timeout: u32, context: *mut ::core::ffi::c_void) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_proxybusobject_unregisterpropertieschangedlistener(proxyobj: alljoyn_proxybusobject, iface: super::super::Foundation::PSTR, callback: alljoyn_proxybusobject_listener_propertieschanged_ptr) -> QStatus;
pub fn alljoyn_routerinit() -> QStatus;
pub fn alljoyn_routerinitwithconfig(configxml: *mut i8) -> QStatus;
pub fn alljoyn_routershutdown() -> QStatus;
pub fn alljoyn_securityapplicationproxy_claim(proxy: alljoyn_securityapplicationproxy, cakey: *mut i8, identitycertificatechain: *mut i8, groupid: *const u8, groupsize: usize, groupauthority: *mut i8, manifestsxmls: *mut *mut i8, manifestscount: usize) -> QStatus;
pub fn alljoyn_securityapplicationproxy_computemanifestdigest(unsignedmanifestxml: *mut i8, identitycertificatepem: *mut i8, digest: *mut *mut u8, digestsize: *mut usize) -> QStatus;
pub fn alljoyn_securityapplicationproxy_create(bus: alljoyn_busattachment, appbusname: *mut i8, sessionid: u32) -> alljoyn_securityapplicationproxy;
pub fn alljoyn_securityapplicationproxy_destroy(proxy: alljoyn_securityapplicationproxy);
pub fn alljoyn_securityapplicationproxy_digest_destroy(digest: *mut u8);
pub fn alljoyn_securityapplicationproxy_eccpublickey_destroy(eccpublickey: *mut i8);
pub fn alljoyn_securityapplicationproxy_endmanagement(proxy: alljoyn_securityapplicationproxy) -> QStatus;
pub fn alljoyn_securityapplicationproxy_getapplicationstate(proxy: alljoyn_securityapplicationproxy, applicationstate: *mut alljoyn_applicationstate) -> QStatus;
pub fn alljoyn_securityapplicationproxy_getclaimcapabilities(proxy: alljoyn_securityapplicationproxy, capabilities: *mut u16) -> QStatus;
pub fn alljoyn_securityapplicationproxy_getclaimcapabilitiesadditionalinfo(proxy: alljoyn_securityapplicationproxy, additionalinfo: *mut u16) -> QStatus;
pub fn alljoyn_securityapplicationproxy_getdefaultpolicy(proxy: alljoyn_securityapplicationproxy, policyxml: *mut *mut i8) -> QStatus;
pub fn alljoyn_securityapplicationproxy_geteccpublickey(proxy: alljoyn_securityapplicationproxy, eccpublickey: *mut *mut i8) -> QStatus;
pub fn alljoyn_securityapplicationproxy_getmanifesttemplate(proxy: alljoyn_securityapplicationproxy, manifesttemplatexml: *mut *mut i8) -> QStatus;
pub fn alljoyn_securityapplicationproxy_getpermissionmanagementsessionport() -> u16;
pub fn alljoyn_securityapplicationproxy_getpolicy(proxy: alljoyn_securityapplicationproxy, policyxml: *mut *mut i8) -> QStatus;
pub fn alljoyn_securityapplicationproxy_installmembership(proxy: alljoyn_securityapplicationproxy, membershipcertificatechain: *mut i8) -> QStatus;
pub fn alljoyn_securityapplicationproxy_manifest_destroy(signedmanifestxml: *mut i8);
pub fn alljoyn_securityapplicationproxy_manifesttemplate_destroy(manifesttemplatexml: *mut i8);
pub fn alljoyn_securityapplicationproxy_policy_destroy(policyxml: *mut i8);
pub fn alljoyn_securityapplicationproxy_reset(proxy: alljoyn_securityapplicationproxy) -> QStatus;
pub fn alljoyn_securityapplicationproxy_resetpolicy(proxy: alljoyn_securityapplicationproxy) -> QStatus;
pub fn alljoyn_securityapplicationproxy_setmanifestsignature(unsignedmanifestxml: *mut i8, identitycertificatepem: *mut i8, signature: *const u8, signaturesize: usize, signedmanifestxml: *mut *mut i8) -> QStatus;
pub fn alljoyn_securityapplicationproxy_signmanifest(unsignedmanifestxml: *mut i8, identitycertificatepem: *mut i8, signingprivatekeypem: *mut i8, signedmanifestxml: *mut *mut i8) -> QStatus;
pub fn alljoyn_securityapplicationproxy_startmanagement(proxy: alljoyn_securityapplicationproxy) -> QStatus;
pub fn alljoyn_securityapplicationproxy_updateidentity(proxy: alljoyn_securityapplicationproxy, identitycertificatechain: *mut i8, manifestsxmls: *mut *mut i8, manifestscount: usize) -> QStatus;
pub fn alljoyn_securityapplicationproxy_updatepolicy(proxy: alljoyn_securityapplicationproxy, policyxml: *mut i8) -> QStatus;
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_sessionlistener_create(callbacks: *const alljoyn_sessionlistener_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_sessionlistener;
pub fn alljoyn_sessionlistener_destroy(listener: alljoyn_sessionlistener);
pub fn alljoyn_sessionopts_cmp(one: alljoyn_sessionopts, other: alljoyn_sessionopts) -> i32;
pub fn alljoyn_sessionopts_create(traffic: u8, ismultipoint: i32, proximity: u8, transports: u16) -> alljoyn_sessionopts;
pub fn alljoyn_sessionopts_destroy(opts: alljoyn_sessionopts);
pub fn alljoyn_sessionopts_get_multipoint(opts: alljoyn_sessionopts) -> i32;
pub fn alljoyn_sessionopts_get_proximity(opts: alljoyn_sessionopts) -> u8;
pub fn alljoyn_sessionopts_get_traffic(opts: alljoyn_sessionopts) -> u8;
pub fn alljoyn_sessionopts_get_transports(opts: alljoyn_sessionopts) -> u16;
pub fn alljoyn_sessionopts_iscompatible(one: alljoyn_sessionopts, other: alljoyn_sessionopts) -> i32;
pub fn alljoyn_sessionopts_set_multipoint(opts: alljoyn_sessionopts, ismultipoint: i32);
pub fn alljoyn_sessionopts_set_proximity(opts: alljoyn_sessionopts, proximity: u8);
pub fn alljoyn_sessionopts_set_traffic(opts: alljoyn_sessionopts, traffic: u8);
pub fn alljoyn_sessionopts_set_transports(opts: alljoyn_sessionopts, transports: u16);
#[cfg(feature = "Win32_Foundation")]
pub fn alljoyn_sessionportlistener_create(callbacks: *const alljoyn_sessionportlistener_callbacks, context: *const ::core::ffi::c_void) -> alljoyn_sessionportlistener;
pub fn alljoyn_sessionportlistener_destroy(listener: alljoyn_sessionportlistener);
pub fn alljoyn_shutdown() -> QStatus;
pub fn alljoyn_unity_deferred_callbacks_process() -> i32;
pub fn alljoyn_unity_set_deferred_callback_mainthread_only(mainthread_only: i32);
}
pub const ALLJOYN_BIG_ENDIAN: u8 = 66u8;
pub const ALLJOYN_CRED_CERT_CHAIN: u16 = 4u16;
pub const ALLJOYN_CRED_EXPIRATION: u16 = 32u16;
pub const ALLJOYN_CRED_LOGON_ENTRY: u16 = 16u16;
pub const ALLJOYN_CRED_NEW_PASSWORD: u16 = 4097u16;
pub const ALLJOYN_CRED_ONE_TIME_PWD: u16 = 8193u16;
pub const ALLJOYN_CRED_PASSWORD: u16 = 1u16;
pub const ALLJOYN_CRED_PRIVATE_KEY: u16 = 8u16;
pub const ALLJOYN_CRED_USER_NAME: u16 = 2u16;
pub const ALLJOYN_DISCONNECTED: u32 = 4u32;
pub const ALLJOYN_LITTLE_ENDIAN: u8 = 108u8;
pub const ALLJOYN_MEMBER_ANNOTATE_DEPRECATED: u8 = 2u8;
pub const ALLJOYN_MEMBER_ANNOTATE_GLOBAL_BROADCAST: u8 = 32u8;
pub const ALLJOYN_MEMBER_ANNOTATE_NO_REPLY: u8 = 1u8;
pub const ALLJOYN_MEMBER_ANNOTATE_SESSIONCAST: u8 = 4u8;
pub const ALLJOYN_MEMBER_ANNOTATE_SESSIONLESS: u8 = 8u8;
pub const ALLJOYN_MEMBER_ANNOTATE_UNICAST: u8 = 16u8;
pub const ALLJOYN_MESSAGE_DEFAULT_TIMEOUT: u32 = 25000u32;
pub const ALLJOYN_MESSAGE_FLAG_ALLOW_REMOTE_MSG: u32 = 4u32;
pub const ALLJOYN_MESSAGE_FLAG_AUTO_START: u32 = 2u32;
pub const ALLJOYN_MESSAGE_FLAG_ENCRYPTED: u32 = 128u32;
pub const ALLJOYN_MESSAGE_FLAG_GLOBAL_BROADCAST: u32 = 32u32;
pub const ALLJOYN_MESSAGE_FLAG_NO_REPLY_EXPECTED: u32 = 1u32;
pub const ALLJOYN_MESSAGE_FLAG_SESSIONLESS: u32 = 16u32;
pub const ALLJOYN_PROP_ACCESS_READ: u8 = 1u8;
pub const ALLJOYN_PROP_ACCESS_RW: u8 = 3u8;
pub const ALLJOYN_PROP_ACCESS_WRITE: u8 = 2u8;
pub const ALLJOYN_PROXIMITY_ANY: u32 = 255u32;
pub const ALLJOYN_PROXIMITY_NETWORK: u32 = 2u32;
pub const ALLJOYN_PROXIMITY_PHYSICAL: u32 = 1u32;
pub const ALLJOYN_READ_READY: u32 = 1u32;
pub const ALLJOYN_TRAFFIC_TYPE_MESSAGES: u32 = 1u32;
pub const ALLJOYN_TRAFFIC_TYPE_RAW_RELIABLE: u32 = 4u32;
pub const ALLJOYN_TRAFFIC_TYPE_RAW_UNRELIABLE: u32 = 2u32;
pub const ALLJOYN_WRITE_READY: u32 = 2u32;
pub const QCC_FALSE: u32 = 0u32;
pub const QCC_TRUE: u32 = 1u32;
pub type QStatus = i32;
pub const ER_OK: QStatus = 0i32;
pub const ER_FAIL: QStatus = 1i32;
pub const ER_UTF_CONVERSION_FAILED: QStatus = 2i32;
pub const ER_BUFFER_TOO_SMALL: QStatus = 3i32;
pub const ER_OS_ERROR: QStatus = 4i32;
pub const ER_OUT_OF_MEMORY: QStatus = 5i32;
pub const ER_SOCKET_BIND_ERROR: QStatus = 6i32;
pub const ER_INIT_FAILED: QStatus = 7i32;
pub const ER_WOULDBLOCK: QStatus = 8i32;
pub const ER_NOT_IMPLEMENTED: QStatus = 9i32;
pub const ER_TIMEOUT: QStatus = 10i32;
pub const ER_SOCK_OTHER_END_CLOSED: QStatus = 11i32;
pub const ER_BAD_ARG_1: QStatus = 12i32;
pub const ER_BAD_ARG_2: QStatus = 13i32;
pub const ER_BAD_ARG_3: QStatus = 14i32;
pub const ER_BAD_ARG_4: QStatus = 15i32;
pub const ER_BAD_ARG_5: QStatus = 16i32;
pub const ER_BAD_ARG_6: QStatus = 17i32;
pub const ER_BAD_ARG_7: QStatus = 18i32;
pub const ER_BAD_ARG_8: QStatus = 19i32;
pub const ER_INVALID_ADDRESS: QStatus = 20i32;
pub const ER_INVALID_DATA: QStatus = 21i32;
pub const ER_READ_ERROR: QStatus = 22i32;
pub const ER_WRITE_ERROR: QStatus = 23i32;
pub const ER_OPEN_FAILED: QStatus = 24i32;
pub const ER_PARSE_ERROR: QStatus = 25i32;
pub const ER_END_OF_DATA: QStatus = 26i32;
pub const ER_CONN_REFUSED: QStatus = 27i32;
pub const ER_BAD_ARG_COUNT: QStatus = 28i32;
pub const ER_WARNING: QStatus = 29i32;
pub const ER_EOF: QStatus = 30i32;
pub const ER_DEADLOCK: QStatus = 31i32;
pub const ER_COMMON_ERRORS: QStatus = 4096i32;
pub const ER_STOPPING_THREAD: QStatus = 4097i32;
pub const ER_ALERTED_THREAD: QStatus = 4098i32;
pub const ER_XML_MALFORMED: QStatus = 4099i32;
pub const ER_AUTH_FAIL: QStatus = 4100i32;
pub const ER_AUTH_USER_REJECT: QStatus = 4101i32;
pub const ER_NO_SUCH_ALARM: QStatus = 4102i32;
pub const ER_TIMER_FALLBEHIND: QStatus = 4103i32;
pub const ER_SSL_ERRORS: QStatus = 4104i32;
pub const ER_SSL_INIT: QStatus = 4105i32;
pub const ER_SSL_CONNECT: QStatus = 4106i32;
pub const ER_SSL_VERIFY: QStatus = 4107i32;
pub const ER_EXTERNAL_THREAD: QStatus = 4108i32;
pub const ER_CRYPTO_ERROR: QStatus = 4109i32;
pub const ER_CRYPTO_TRUNCATED: QStatus = 4110i32;
pub const ER_CRYPTO_KEY_UNAVAILABLE: QStatus = 4111i32;
pub const ER_BAD_HOSTNAME: QStatus = 4112i32;
pub const ER_CRYPTO_KEY_UNUSABLE: QStatus = 4113i32;
pub const ER_EMPTY_KEY_BLOB: QStatus = 4114i32;
pub const ER_CORRUPT_KEYBLOB: QStatus = 4115i32;
pub const ER_INVALID_KEY_ENCODING: QStatus = 4116i32;
pub const ER_DEAD_THREAD: QStatus = 4117i32;
pub const ER_THREAD_RUNNING: QStatus = 4118i32;
pub const ER_THREAD_STOPPING: QStatus = 4119i32;
pub const ER_BAD_STRING_ENCODING: QStatus = 4120i32;
pub const ER_CRYPTO_INSUFFICIENT_SECURITY: QStatus = 4121i32;
pub const ER_CRYPTO_ILLEGAL_PARAMETERS: QStatus = 4122i32;
pub const ER_CRYPTO_HASH_UNINITIALIZED: QStatus = 4123i32;
pub const ER_THREAD_NO_WAIT: QStatus = 4124i32;
pub const ER_TIMER_EXITING: QStatus = 4125i32;
pub const ER_INVALID_GUID: QStatus = 4126i32;
pub const ER_THREADPOOL_EXHAUSTED: QStatus = 4127i32;
pub const ER_THREADPOOL_STOPPING: QStatus = 4128i32;
pub const ER_INVALID_STREAM: QStatus = 4129i32;
pub const ER_TIMER_FULL: QStatus = 4130i32;
pub const ER_IODISPATCH_STOPPING: QStatus = 4131i32;
pub const ER_SLAP_INVALID_PACKET_LEN: QStatus = 4132i32;
pub const ER_SLAP_HDR_CHECKSUM_ERROR: QStatus = 4133i32;
pub const ER_SLAP_INVALID_PACKET_TYPE: QStatus = 4134i32;
pub const ER_SLAP_LEN_MISMATCH: QStatus = 4135i32;
pub const ER_SLAP_PACKET_TYPE_MISMATCH: QStatus = 4136i32;
pub const ER_SLAP_CRC_ERROR: QStatus = 4137i32;
pub const ER_SLAP_ERROR: QStatus = 4138i32;
pub const ER_SLAP_OTHER_END_CLOSED: QStatus = 4139i32;
pub const ER_TIMER_NOT_ALLOWED: QStatus = 4140i32;
pub const ER_NOT_CONN: QStatus = 4141i32;
pub const ER_XML_CONVERTER_ERROR: QStatus = 8192i32;
pub const ER_XML_INVALID_RULES_COUNT: QStatus = 8193i32;
pub const ER_XML_INTERFACE_MEMBERS_MISSING: QStatus = 8194i32;
pub const ER_XML_INVALID_MEMBER_TYPE: QStatus = 8195i32;
pub const ER_XML_INVALID_MEMBER_ACTION: QStatus = 8196i32;
pub const ER_XML_MEMBER_DENY_ACTION_WITH_OTHER: QStatus = 8197i32;
pub const ER_XML_INVALID_ANNOTATIONS_COUNT: QStatus = 8198i32;
pub const ER_XML_INVALID_ELEMENT_NAME: QStatus = 8199i32;
pub const ER_XML_INVALID_ATTRIBUTE_VALUE: QStatus = 8200i32;
pub const ER_XML_INVALID_SECURITY_LEVEL_ANNOTATION_VALUE: QStatus = 8201i32;
pub const ER_XML_INVALID_ELEMENT_CHILDREN_COUNT: QStatus = 8202i32;
pub const ER_XML_INVALID_POLICY_VERSION: QStatus = 8203i32;
pub const ER_XML_INVALID_POLICY_SERIAL_NUMBER: QStatus = 8204i32;
pub const ER_XML_INVALID_ACL_PEER_TYPE: QStatus = 8205i32;
pub const ER_XML_INVALID_ACL_PEER_CHILDREN_COUNT: QStatus = 8206i32;
pub const ER_XML_ACL_ALL_TYPE_PEER_WITH_OTHERS: QStatus = 8207i32;
pub const ER_XML_INVALID_ACL_PEER_PUBLIC_KEY: QStatus = 8208i32;
pub const ER_XML_ACL_PEER_NOT_UNIQUE: QStatus = 8209i32;
pub const ER_XML_ACL_PEER_PUBLIC_KEY_SET: QStatus = 8210i32;
pub const ER_XML_ACLS_MISSING: QStatus = 8211i32;
pub const ER_XML_ACL_PEERS_MISSING: QStatus = 8212i32;
pub const ER_XML_INVALID_OBJECT_PATH: QStatus = 8213i32;
pub const ER_XML_INVALID_INTERFACE_NAME: QStatus = 8214i32;
pub const ER_XML_INVALID_MEMBER_NAME: QStatus = 8215i32;
pub const ER_XML_INVALID_MANIFEST_VERSION: QStatus = 8216i32;
pub const ER_XML_INVALID_OID: QStatus = 8217i32;
pub const ER_XML_INVALID_BASE64: QStatus = 8218i32;
pub const ER_XML_INTERFACE_NAME_NOT_UNIQUE: QStatus = 8219i32;
pub const ER_XML_MEMBER_NAME_NOT_UNIQUE: QStatus = 8220i32;
pub const ER_XML_OBJECT_PATH_NOT_UNIQUE: QStatus = 8221i32;
pub const ER_XML_ANNOTATION_NOT_UNIQUE: QStatus = 8222i32;
pub const ER_NONE: QStatus = 65535i32;
pub const ER_BUS_ERRORS: QStatus = 36864i32;
pub const ER_BUS_READ_ERROR: QStatus = 36865i32;
pub const ER_BUS_WRITE_ERROR: QStatus = 36866i32;
pub const ER_BUS_BAD_VALUE_TYPE: QStatus = 36867i32;
pub const ER_BUS_BAD_HEADER_FIELD: QStatus = 36868i32;
pub const ER_BUS_BAD_SIGNATURE: QStatus = 36869i32;
pub const ER_BUS_BAD_OBJ_PATH: QStatus = 36870i32;
pub const ER_BUS_BAD_MEMBER_NAME: QStatus = 36871i32;
pub const ER_BUS_BAD_INTERFACE_NAME: QStatus = 36872i32;
pub const ER_BUS_BAD_ERROR_NAME: QStatus = 36873i32;
pub const ER_BUS_BAD_BUS_NAME: QStatus = 36874i32;
pub const ER_BUS_NAME_TOO_LONG: QStatus = 36875i32;
pub const ER_BUS_BAD_LENGTH: QStatus = 36876i32;
pub const ER_BUS_BAD_VALUE: QStatus = 36877i32;
pub const ER_BUS_BAD_HDR_FLAGS: QStatus = 36878i32;
pub const ER_BUS_BAD_BODY_LEN: QStatus = 36879i32;
pub const ER_BUS_BAD_HEADER_LEN: QStatus = 36880i32;
pub const ER_BUS_UNKNOWN_SERIAL: QStatus = 36881i32;
pub const ER_BUS_UNKNOWN_PATH: QStatus = 36882i32;
pub const ER_BUS_UNKNOWN_INTERFACE: QStatus = 36883i32;
pub const ER_BUS_ESTABLISH_FAILED: QStatus = 36884i32;
pub const ER_BUS_UNEXPECTED_SIGNATURE: QStatus = 36885i32;
pub const ER_BUS_INTERFACE_MISSING: QStatus = 36886i32;
pub const ER_BUS_PATH_MISSING: QStatus = 36887i32;
pub const ER_BUS_MEMBER_MISSING: QStatus = 36888i32;
pub const ER_BUS_REPLY_SERIAL_MISSING: QStatus = 36889i32;
pub const ER_BUS_ERROR_NAME_MISSING: QStatus = 36890i32;
pub const ER_BUS_INTERFACE_NO_SUCH_MEMBER: QStatus = 36891i32;
pub const ER_BUS_NO_SUCH_OBJECT: QStatus = 36892i32;
pub const ER_BUS_OBJECT_NO_SUCH_MEMBER: QStatus = 36893i32;
pub const ER_BUS_OBJECT_NO_SUCH_INTERFACE: QStatus = 36894i32;
pub const ER_BUS_NO_SUCH_INTERFACE: QStatus = 36895i32;
pub const ER_BUS_MEMBER_NO_SUCH_SIGNATURE: QStatus = 36896i32;
pub const ER_BUS_NOT_NUL_TERMINATED: QStatus = 36897i32;
pub const ER_BUS_NO_SUCH_PROPERTY: QStatus = 36898i32;
pub const ER_BUS_SET_WRONG_SIGNATURE: QStatus = 36899i32;
pub const ER_BUS_PROPERTY_VALUE_NOT_SET: QStatus = 36900i32;
pub const ER_BUS_PROPERTY_ACCESS_DENIED: QStatus = 36901i32;
pub const ER_BUS_NO_TRANSPORTS: QStatus = 36902i32;
pub const ER_BUS_BAD_TRANSPORT_ARGS: QStatus = 36903i32;
pub const ER_BUS_NO_ROUTE: QStatus = 36904i32;
pub const ER_BUS_NO_ENDPOINT: QStatus = 36905i32;
pub const ER_BUS_BAD_SEND_PARAMETER: QStatus = 36906i32;
pub const ER_BUS_UNMATCHED_REPLY_SERIAL: QStatus = 36907i32;
pub const ER_BUS_BAD_SENDER_ID: QStatus = 36908i32;
pub const ER_BUS_TRANSPORT_NOT_STARTED: QStatus = 36909i32;
pub const ER_BUS_EMPTY_MESSAGE: QStatus = 36910i32;
pub const ER_BUS_NOT_OWNER: QStatus = 36911i32;
pub const ER_BUS_SET_PROPERTY_REJECTED: QStatus = 36912i32;
pub const ER_BUS_CONNECT_FAILED: QStatus = 36913i32;
pub const ER_BUS_REPLY_IS_ERROR_MESSAGE: QStatus = 36914i32;
pub const ER_BUS_NOT_AUTHENTICATING: QStatus = 36915i32;
pub const ER_BUS_NO_LISTENER: QStatus = 36916i32;
pub const ER_BUS_NOT_ALLOWED: QStatus = 36918i32;
pub const ER_BUS_WRITE_QUEUE_FULL: QStatus = 36919i32;
pub const ER_BUS_ENDPOINT_CLOSING: QStatus = 36920i32;
pub const ER_BUS_INTERFACE_MISMATCH: QStatus = 36921i32;
pub const ER_BUS_MEMBER_ALREADY_EXISTS: QStatus = 36922i32;
pub const ER_BUS_PROPERTY_ALREADY_EXISTS: QStatus = 36923i32;
pub const ER_BUS_IFACE_ALREADY_EXISTS: QStatus = 36924i32;
pub const ER_BUS_ERROR_RESPONSE: QStatus = 36925i32;
pub const ER_BUS_BAD_XML: QStatus = 36926i32;
pub const ER_BUS_BAD_CHILD_PATH: QStatus = 36927i32;
pub const ER_BUS_OBJ_ALREADY_EXISTS: QStatus = 36928i32;
pub const ER_BUS_OBJ_NOT_FOUND: QStatus = 36929i32;
pub const ER_BUS_CANNOT_EXPAND_MESSAGE: QStatus = 36930i32;
pub const ER_BUS_NOT_COMPRESSED: QStatus = 36931i32;
pub const ER_BUS_ALREADY_CONNECTED: QStatus = 36932i32;
pub const ER_BUS_NOT_CONNECTED: QStatus = 36933i32;
pub const ER_BUS_ALREADY_LISTENING: QStatus = 36934i32;
pub const ER_BUS_KEY_UNAVAILABLE: QStatus = 36935i32;
pub const ER_BUS_TRUNCATED: QStatus = 36936i32;
pub const ER_BUS_KEY_STORE_NOT_LOADED: QStatus = 36937i32;
pub const ER_BUS_NO_AUTHENTICATION_MECHANISM: QStatus = 36938i32;
pub const ER_BUS_BUS_ALREADY_STARTED: QStatus = 36939i32;
pub const ER_BUS_BUS_NOT_STARTED: QStatus = 36940i32;
pub const ER_BUS_KEYBLOB_OP_INVALID: QStatus = 36941i32;
pub const ER_BUS_INVALID_HEADER_CHECKSUM: QStatus = 36942i32;
pub const ER_BUS_MESSAGE_NOT_ENCRYPTED: QStatus = 36943i32;
pub const ER_BUS_INVALID_HEADER_SERIAL: QStatus = 36944i32;
pub const ER_BUS_TIME_TO_LIVE_EXPIRED: QStatus = 36945i32;
pub const ER_BUS_HDR_EXPANSION_INVALID: QStatus = 36946i32;
pub const ER_BUS_MISSING_COMPRESSION_TOKEN: QStatus = 36947i32;
pub const ER_BUS_NO_PEER_GUID: QStatus = 36948i32;
pub const ER_BUS_MESSAGE_DECRYPTION_FAILED: QStatus = 36949i32;
pub const ER_BUS_SECURITY_FATAL: QStatus = 36950i32;
pub const ER_BUS_KEY_EXPIRED: QStatus = 36951i32;
pub const ER_BUS_CORRUPT_KEYSTORE: QStatus = 36952i32;
pub const ER_BUS_NO_CALL_FOR_REPLY: QStatus = 36953i32;
pub const ER_BUS_NOT_A_COMPLETE_TYPE: QStatus = 36954i32;
pub const ER_BUS_POLICY_VIOLATION: QStatus = 36955i32;
pub const ER_BUS_NO_SUCH_SERVICE: QStatus = 36956i32;
pub const ER_BUS_TRANSPORT_NOT_AVAILABLE: QStatus = 36957i32;
pub const ER_BUS_INVALID_AUTH_MECHANISM: QStatus = 36958i32;
pub const ER_BUS_KEYSTORE_VERSION_MISMATCH: QStatus = 36959i32;
pub const ER_BUS_BLOCKING_CALL_NOT_ALLOWED: QStatus = 36960i32;
pub const ER_BUS_SIGNATURE_MISMATCH: QStatus = 36961i32;
pub const ER_BUS_STOPPING: QStatus = 36962i32;
pub const ER_BUS_METHOD_CALL_ABORTED: QStatus = 36963i32;
pub const ER_BUS_CANNOT_ADD_INTERFACE: QStatus = 36964i32;
pub const ER_BUS_CANNOT_ADD_HANDLER: QStatus = 36965i32;
pub const ER_BUS_KEYSTORE_NOT_LOADED: QStatus = 36966i32;
pub const ER_BUS_NO_SUCH_HANDLE: QStatus = 36971i32;
pub const ER_BUS_HANDLES_NOT_ENABLED: QStatus = 36972i32;
pub const ER_BUS_HANDLES_MISMATCH: QStatus = 36973i32;
pub const ER_BUS_NO_SESSION: QStatus = 36975i32;
pub const ER_BUS_ELEMENT_NOT_FOUND: QStatus = 36976i32;
pub const ER_BUS_NOT_A_DICTIONARY: QStatus = 36977i32;
pub const ER_BUS_WAIT_FAILED: QStatus = 36978i32;
pub const ER_BUS_BAD_SESSION_OPTS: QStatus = 36980i32;
pub const ER_BUS_CONNECTION_REJECTED: QStatus = 36981i32;
pub const ER_DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: QStatus = 36982i32;
pub const ER_DBUS_REQUEST_NAME_REPLY_IN_QUEUE: QStatus = 36983i32;
pub const ER_DBUS_REQUEST_NAME_REPLY_EXISTS: QStatus = 36984i32;
pub const ER_DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER: QStatus = 36985i32;
pub const ER_DBUS_RELEASE_NAME_REPLY_RELEASED: QStatus = 36986i32;
pub const ER_DBUS_RELEASE_NAME_REPLY_NON_EXISTENT: QStatus = 36987i32;
pub const ER_DBUS_RELEASE_NAME_REPLY_NOT_OWNER: QStatus = 36988i32;
pub const ER_DBUS_START_REPLY_ALREADY_RUNNING: QStatus = 36990i32;
pub const ER_ALLJOYN_BINDSESSIONPORT_REPLY_ALREADY_EXISTS: QStatus = 36992i32;
pub const ER_ALLJOYN_BINDSESSIONPORT_REPLY_FAILED: QStatus = 36993i32;
pub const ER_ALLJOYN_JOINSESSION_REPLY_NO_SESSION: QStatus = 36995i32;
pub const ER_ALLJOYN_JOINSESSION_REPLY_UNREACHABLE: QStatus = 36996i32;
pub const ER_ALLJOYN_JOINSESSION_REPLY_CONNECT_FAILED: QStatus = 36997i32;
pub const ER_ALLJOYN_JOINSESSION_REPLY_REJECTED: QStatus = 36998i32;
pub const ER_ALLJOYN_JOINSESSION_REPLY_BAD_SESSION_OPTS: QStatus = 36999i32;
pub const ER_ALLJOYN_JOINSESSION_REPLY_FAILED: QStatus = 37000i32;
pub const ER_ALLJOYN_LEAVESESSION_REPLY_NO_SESSION: QStatus = 37002i32;
pub const ER_ALLJOYN_LEAVESESSION_REPLY_FAILED: QStatus = 37003i32;
pub const ER_ALLJOYN_ADVERTISENAME_REPLY_TRANSPORT_NOT_AVAILABLE: QStatus = 37004i32;
pub const ER_ALLJOYN_ADVERTISENAME_REPLY_ALREADY_ADVERTISING: QStatus = 37005i32;
pub const ER_ALLJOYN_ADVERTISENAME_REPLY_FAILED: QStatus = 37006i32;
pub const ER_ALLJOYN_CANCELADVERTISENAME_REPLY_FAILED: QStatus = 37008i32;
pub const ER_ALLJOYN_FINDADVERTISEDNAME_REPLY_TRANSPORT_NOT_AVAILABLE: QStatus = 37009i32;
pub const ER_ALLJOYN_FINDADVERTISEDNAME_REPLY_ALREADY_DISCOVERING: QStatus = 37010i32;
pub const ER_ALLJOYN_FINDADVERTISEDNAME_REPLY_FAILED: QStatus = 37011i32;
pub const ER_ALLJOYN_CANCELFINDADVERTISEDNAME_REPLY_FAILED: QStatus = 37013i32;
pub const ER_BUS_UNEXPECTED_DISPOSITION: QStatus = 37014i32;
pub const ER_BUS_INTERFACE_ACTIVATED: QStatus = 37015i32;
pub const ER_ALLJOYN_UNBINDSESSIONPORT_REPLY_BAD_PORT: QStatus = 37016i32;
pub const ER_ALLJOYN_UNBINDSESSIONPORT_REPLY_FAILED: QStatus = 37017i32;
pub const ER_ALLJOYN_BINDSESSIONPORT_REPLY_INVALID_OPTS: QStatus = 37018i32;
pub const ER_ALLJOYN_JOINSESSION_REPLY_ALREADY_JOINED: QStatus = 37019i32;
pub const ER_BUS_SELF_CONNECT: QStatus = 37020i32;
pub const ER_BUS_SECURITY_NOT_ENABLED: QStatus = 37021i32;
pub const ER_BUS_LISTENER_ALREADY_SET: QStatus = 37022i32;
pub const ER_BUS_PEER_AUTH_VERSION_MISMATCH: QStatus = 37023i32;
pub const ER_ALLJOYN_SETLINKTIMEOUT_REPLY_NOT_SUPPORTED: QStatus = 37024i32;
pub const ER_ALLJOYN_SETLINKTIMEOUT_REPLY_NO_DEST_SUPPORT: QStatus = 37025i32;
pub const ER_ALLJOYN_SETLINKTIMEOUT_REPLY_FAILED: QStatus = 37026i32;
pub const ER_ALLJOYN_ACCESS_PERMISSION_WARNING: QStatus = 37027i32;
pub const ER_ALLJOYN_ACCESS_PERMISSION_ERROR: QStatus = 37028i32;
pub const ER_BUS_DESTINATION_NOT_AUTHENTICATED: QStatus = 37029i32;
pub const ER_BUS_ENDPOINT_REDIRECTED: QStatus = 37030i32;
pub const ER_BUS_AUTHENTICATION_PENDING: QStatus = 37031i32;
pub const ER_BUS_NOT_AUTHORIZED: QStatus = 37032i32;
pub const ER_PACKET_BUS_NO_SUCH_CHANNEL: QStatus = 37033i32;
pub const ER_PACKET_BAD_FORMAT: QStatus = 37034i32;
pub const ER_PACKET_CONNECT_TIMEOUT: QStatus = 37035i32;
pub const ER_PACKET_CHANNEL_FAIL: QStatus = 37036i32;
pub const ER_PACKET_TOO_LARGE: QStatus = 37037i32;
pub const ER_PACKET_BAD_PARAMETER: QStatus = 37038i32;
pub const ER_PACKET_BAD_CRC: QStatus = 37039i32;
pub const ER_RENDEZVOUS_SERVER_DEACTIVATED_USER: QStatus = 37067i32;
pub const ER_RENDEZVOUS_SERVER_UNKNOWN_USER: QStatus = 37068i32;
pub const ER_UNABLE_TO_CONNECT_TO_RENDEZVOUS_SERVER: QStatus = 37069i32;
pub const ER_NOT_CONNECTED_TO_RENDEZVOUS_SERVER: QStatus = 37070i32;
pub const ER_UNABLE_TO_SEND_MESSAGE_TO_RENDEZVOUS_SERVER: QStatus = 37071i32;
pub const ER_INVALID_RENDEZVOUS_SERVER_INTERFACE_MESSAGE: QStatus = 37072i32;
pub const ER_INVALID_PERSISTENT_CONNECTION_MESSAGE_RESPONSE: QStatus = 37073i32;
pub const ER_INVALID_ON_DEMAND_CONNECTION_MESSAGE_RESPONSE: QStatus = 37074i32;
pub const ER_INVALID_HTTP_METHOD_USED_FOR_RENDEZVOUS_SERVER_INTERFACE_MESSAGE: QStatus = 37075i32;
pub const ER_RENDEZVOUS_SERVER_ERR500_INTERNAL_ERROR: QStatus = 37076i32;
pub const ER_RENDEZVOUS_SERVER_ERR503_STATUS_UNAVAILABLE: QStatus = 37077i32;
pub const ER_RENDEZVOUS_SERVER_ERR401_UNAUTHORIZED_REQUEST: QStatus = 37078i32;
pub const ER_RENDEZVOUS_SERVER_UNRECOVERABLE_ERROR: QStatus = 37079i32;
pub const ER_RENDEZVOUS_SERVER_ROOT_CERTIFICATE_UNINITIALIZED: QStatus = 37080i32;
pub const ER_BUS_NO_SUCH_ANNOTATION: QStatus = 37081i32;
pub const ER_BUS_ANNOTATION_ALREADY_EXISTS: QStatus = 37082i32;
pub const ER_SOCK_CLOSING: QStatus = 37083i32;
pub const ER_NO_SUCH_DEVICE: QStatus = 37084i32;
pub const ER_P2P: QStatus = 37085i32;
pub const ER_P2P_TIMEOUT: QStatus = 37086i32;
pub const ER_P2P_NOT_CONNECTED: QStatus = 37087i32;
pub const ER_BAD_TRANSPORT_MASK: QStatus = 37088i32;
pub const ER_PROXIMITY_CONNECTION_ESTABLISH_FAIL: QStatus = 37089i32;
pub const ER_PROXIMITY_NO_PEERS_FOUND: QStatus = 37090i32;
pub const ER_BUS_OBJECT_NOT_REGISTERED: QStatus = 37091i32;
pub const ER_P2P_DISABLED: QStatus = 37092i32;
pub const ER_P2P_BUSY: QStatus = 37093i32;
pub const ER_BUS_INCOMPATIBLE_DAEMON: QStatus = 37094i32;
pub const ER_P2P_NO_GO: QStatus = 37095i32;
pub const ER_P2P_NO_STA: QStatus = 37096i32;
pub const ER_P2P_FORBIDDEN: QStatus = 37097i32;
pub const ER_ALLJOYN_ONAPPSUSPEND_REPLY_FAILED: QStatus = 37098i32;
pub const ER_ALLJOYN_ONAPPSUSPEND_REPLY_UNSUPPORTED: QStatus = 37099i32;
pub const ER_ALLJOYN_ONAPPRESUME_REPLY_FAILED: QStatus = 37100i32;
pub const ER_ALLJOYN_ONAPPRESUME_REPLY_UNSUPPORTED: QStatus = 37101i32;
pub const ER_BUS_NO_SUCH_MESSAGE: QStatus = 37102i32;
pub const ER_ALLJOYN_REMOVESESSIONMEMBER_REPLY_NO_SESSION: QStatus = 37103i32;
pub const ER_ALLJOYN_REMOVESESSIONMEMBER_NOT_BINDER: QStatus = 37104i32;
pub const ER_ALLJOYN_REMOVESESSIONMEMBER_NOT_MULTIPOINT: QStatus = 37105i32;
pub const ER_ALLJOYN_REMOVESESSIONMEMBER_NOT_FOUND: QStatus = 37106i32;
pub const ER_ALLJOYN_REMOVESESSIONMEMBER_INCOMPATIBLE_REMOTE_DAEMON: QStatus = 37107i32;
pub const ER_ALLJOYN_REMOVESESSIONMEMBER_REPLY_FAILED: QStatus = 37108i32;
pub const ER_BUS_REMOVED_BY_BINDER: QStatus = 37109i32;
pub const ER_BUS_MATCH_RULE_NOT_FOUND: QStatus = 37110i32;
pub const ER_ALLJOYN_PING_FAILED: QStatus = 37111i32;
pub const ER_ALLJOYN_PING_REPLY_UNREACHABLE: QStatus = 37112i32;
pub const ER_UDP_MSG_TOO_LONG: QStatus = 37113i32;
pub const ER_UDP_DEMUX_NO_ENDPOINT: QStatus = 37114i32;
pub const ER_UDP_NO_NETWORK: QStatus = 37115i32;
pub const ER_UDP_UNEXPECTED_LENGTH: QStatus = 37116i32;
pub const ER_UDP_UNEXPECTED_FLOW: QStatus = 37117i32;
pub const ER_UDP_DISCONNECT: QStatus = 37118i32;
pub const ER_UDP_NOT_IMPLEMENTED: QStatus = 37119i32;
pub const ER_UDP_NO_LISTENER: QStatus = 37120i32;
pub const ER_UDP_STOPPING: QStatus = 37121i32;
pub const ER_ARDP_BACKPRESSURE: QStatus = 37122i32;
pub const ER_UDP_BACKPRESSURE: QStatus = 37123i32;
pub const ER_ARDP_INVALID_STATE: QStatus = 37124i32;
pub const ER_ARDP_TTL_EXPIRED: QStatus = 37125i32;
pub const ER_ARDP_PERSIST_TIMEOUT: QStatus = 37126i32;
pub const ER_ARDP_PROBE_TIMEOUT: QStatus = 37127i32;
pub const ER_ARDP_REMOTE_CONNECTION_RESET: QStatus = 37128i32;
pub const ER_UDP_BUSHELLO: QStatus = 37129i32;
pub const ER_UDP_MESSAGE: QStatus = 37130i32;
pub const ER_UDP_INVALID: QStatus = 37131i32;
pub const ER_UDP_UNSUPPORTED: QStatus = 37132i32;
pub const ER_UDP_ENDPOINT_STALLED: QStatus = 37133i32;
pub const ER_ARDP_INVALID_RESPONSE: QStatus = 37134i32;
pub const ER_ARDP_INVALID_CONNECTION: QStatus = 37135i32;
pub const ER_UDP_LOCAL_DISCONNECT: QStatus = 37136i32;
pub const ER_UDP_EARLY_EXIT: QStatus = 37137i32;
pub const ER_UDP_LOCAL_DISCONNECT_FAIL: QStatus = 37138i32;
pub const ER_ARDP_DISCONNECTING: QStatus = 37139i32;
pub const ER_ALLJOYN_PING_REPLY_INCOMPATIBLE_REMOTE_ROUTING_NODE: QStatus = 37140i32;
pub const ER_ALLJOYN_PING_REPLY_TIMEOUT: QStatus = 37141i32;
pub const ER_ALLJOYN_PING_REPLY_UNKNOWN_NAME: QStatus = 37142i32;
pub const ER_ALLJOYN_PING_REPLY_FAILED: QStatus = 37143i32;
pub const ER_TCP_MAX_UNTRUSTED: QStatus = 37144i32;
pub const ER_ALLJOYN_PING_REPLY_IN_PROGRESS: QStatus = 37145i32;
pub const ER_LANGUAGE_NOT_SUPPORTED: QStatus = 37146i32;
pub const ER_ABOUT_FIELD_ALREADY_SPECIFIED: QStatus = 37147i32;
pub const ER_UDP_NOT_DISCONNECTED: QStatus = 37148i32;
pub const ER_UDP_ENDPOINT_NOT_STARTED: QStatus = 37149i32;
pub const ER_UDP_ENDPOINT_REMOVED: QStatus = 37150i32;
pub const ER_ARDP_VERSION_NOT_SUPPORTED: QStatus = 37151i32;
pub const ER_CONNECTION_LIMIT_EXCEEDED: QStatus = 37152i32;
pub const ER_ARDP_WRITE_BLOCKED: QStatus = 37153i32;
pub const ER_PERMISSION_DENIED: QStatus = 37154i32;
pub const ER_ABOUT_DEFAULT_LANGUAGE_NOT_SPECIFIED: QStatus = 37155i32;
pub const ER_ABOUT_SESSIONPORT_NOT_BOUND: QStatus = 37156i32;
pub const ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD: QStatus = 37157i32;
pub const ER_ABOUT_INVALID_ABOUTDATA_LISTENER: QStatus = 37158i32;
pub const ER_BUS_PING_GROUP_NOT_FOUND: QStatus = 37159i32;
pub const ER_BUS_REMOVED_BY_BINDER_SELF: QStatus = 37160i32;
pub const ER_INVALID_CONFIG: QStatus = 37161i32;
pub const ER_ABOUT_INVALID_ABOUTDATA_FIELD_VALUE: QStatus = 37162i32;
pub const ER_ABOUT_INVALID_ABOUTDATA_FIELD_APPID_SIZE: QStatus = 37163i32;
pub const ER_BUS_TRANSPORT_ACCESS_DENIED: QStatus = 37164i32;
pub const ER_INVALID_CERTIFICATE: QStatus = 37165i32;
pub const ER_CERTIFICATE_NOT_FOUND: QStatus = 37166i32;
pub const ER_DUPLICATE_CERTIFICATE: QStatus = 37167i32;
pub const ER_UNKNOWN_CERTIFICATE: QStatus = 37168i32;
pub const ER_MISSING_DIGEST_IN_CERTIFICATE: QStatus = 37169i32;
pub const ER_DIGEST_MISMATCH: QStatus = 37170i32;
pub const ER_DUPLICATE_KEY: QStatus = 37171i32;
pub const ER_NO_COMMON_TRUST: QStatus = 37172i32;
pub const ER_MANIFEST_NOT_FOUND: QStatus = 37173i32;
pub const ER_INVALID_CERT_CHAIN: QStatus = 37174i32;
pub const ER_NO_TRUST_ANCHOR: QStatus = 37175i32;
pub const ER_INVALID_APPLICATION_STATE: QStatus = 37176i32;
pub const ER_FEATURE_NOT_AVAILABLE: QStatus = 37177i32;
pub const ER_KEY_STORE_ALREADY_INITIALIZED: QStatus = 37178i32;
pub const ER_KEY_STORE_ID_NOT_YET_SET: QStatus = 37179i32;
pub const ER_POLICY_NOT_NEWER: QStatus = 37180i32;
pub const ER_MANIFEST_REJECTED: QStatus = 37181i32;
pub const ER_INVALID_CERTIFICATE_USAGE: QStatus = 37182i32;
pub const ER_INVALID_SIGNAL_EMISSION_TYPE: QStatus = 37183i32;
pub const ER_APPLICATION_STATE_LISTENER_ALREADY_EXISTS: QStatus = 37184i32;
pub const ER_APPLICATION_STATE_LISTENER_NO_SUCH_LISTENER: QStatus = 37185i32;
pub const ER_MANAGEMENT_ALREADY_STARTED: QStatus = 37186i32;
pub const ER_MANAGEMENT_NOT_STARTED: QStatus = 37187i32;
pub const ER_BUS_DESCRIPTION_ALREADY_EXISTS: QStatus = 37188i32;
#[repr(C)]
pub struct _alljoyn_abouticon_handle(pub u8);
#[repr(C)]
pub struct _alljoyn_abouticonobj_handle(pub u8);
#[repr(C)]
pub struct _alljoyn_abouticonproxy_handle(pub u8);
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_about_announced_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, busname: super::super::Foundation::PSTR, version: u16, port: u16, objectdescriptionarg: alljoyn_msgarg, aboutdataarg: alljoyn_msgarg)>;
pub type alljoyn_about_announceflag = i32;
pub const UNANNOUNCED: alljoyn_about_announceflag = 0i32;
pub const ANNOUNCED: alljoyn_about_announceflag = 1i32;
pub type alljoyn_aboutdata = isize;
pub type alljoyn_aboutdatalistener = isize;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_aboutdatalistener_callbacks {
pub about_datalistener_getaboutdata: alljoyn_aboutdatalistener_getaboutdata_ptr,
pub about_datalistener_getannouncedaboutdata: alljoyn_aboutdatalistener_getannouncedaboutdata_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_aboutdatalistener_callbacks {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_aboutdatalistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_aboutdatalistener_getaboutdata_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, msgarg: alljoyn_msgarg, language: super::super::Foundation::PSTR) -> QStatus>;
pub type alljoyn_aboutdatalistener_getannouncedaboutdata_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, msgarg: alljoyn_msgarg) -> QStatus>;
pub type alljoyn_aboutlistener = isize;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_aboutlistener_callback {
pub about_listener_announced: alljoyn_about_announced_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_aboutlistener_callback {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_aboutlistener_callback {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_aboutobj = isize;
pub type alljoyn_aboutobjectdescription = isize;
pub type alljoyn_aboutproxy = isize;
pub type alljoyn_applicationstate = i32;
pub const NOT_CLAIMABLE: alljoyn_applicationstate = 0i32;
pub const CLAIMABLE: alljoyn_applicationstate = 1i32;
pub const CLAIMED: alljoyn_applicationstate = 2i32;
pub const NEED_UPDATE: alljoyn_applicationstate = 3i32;
pub type alljoyn_applicationstatelistener = isize;
#[repr(C)]
pub struct alljoyn_applicationstatelistener_callbacks {
pub state: alljoyn_applicationstatelistener_state_ptr,
}
impl ::core::marker::Copy for alljoyn_applicationstatelistener_callbacks {}
impl ::core::clone::Clone for alljoyn_applicationstatelistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_applicationstatelistener_state_ptr = ::core::option::Option<unsafe extern "system" fn(busname: *mut i8, publickey: *mut i8, applicationstate: alljoyn_applicationstate, context: *mut ::core::ffi::c_void)>;
pub type alljoyn_authlistener = isize;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_authlistener_authenticationcomplete_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, authmechanism: super::super::Foundation::PSTR, peername: super::super::Foundation::PSTR, success: i32)>;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_authlistener_callbacks {
pub request_credentials: alljoyn_authlistener_requestcredentials_ptr,
pub verify_credentials: alljoyn_authlistener_verifycredentials_ptr,
pub security_violation: alljoyn_authlistener_securityviolation_ptr,
pub authentication_complete: alljoyn_authlistener_authenticationcomplete_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_authlistener_callbacks {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_authlistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_authlistener_requestcredentials_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, authmechanism: super::super::Foundation::PSTR, peername: super::super::Foundation::PSTR, authcount: u16, username: super::super::Foundation::PSTR, credmask: u16, credentials: alljoyn_credentials) -> i32>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_authlistener_requestcredentialsasync_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, listener: alljoyn_authlistener, authmechanism: super::super::Foundation::PSTR, peername: super::super::Foundation::PSTR, authcount: u16, username: super::super::Foundation::PSTR, credmask: u16, authcontext: *mut ::core::ffi::c_void) -> QStatus>;
pub type alljoyn_authlistener_securityviolation_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, status: QStatus, msg: alljoyn_message)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_authlistener_verifycredentials_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, authmechanism: super::super::Foundation::PSTR, peername: super::super::Foundation::PSTR, credentials: alljoyn_credentials) -> i32>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_authlistener_verifycredentialsasync_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, listener: alljoyn_authlistener, authmechanism: super::super::Foundation::PSTR, peername: super::super::Foundation::PSTR, credentials: alljoyn_credentials, authcontext: *mut ::core::ffi::c_void) -> QStatus>;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_authlistenerasync_callbacks {
pub request_credentials: alljoyn_authlistener_requestcredentialsasync_ptr,
pub verify_credentials: alljoyn_authlistener_verifycredentialsasync_ptr,
pub security_violation: alljoyn_authlistener_securityviolation_ptr,
pub authentication_complete: alljoyn_authlistener_authenticationcomplete_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_authlistenerasync_callbacks {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_authlistenerasync_callbacks {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_autopinger = isize;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_autopinger_destination_found_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, group: super::super::Foundation::PSTR, destination: super::super::Foundation::PSTR)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_autopinger_destination_lost_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, group: super::super::Foundation::PSTR, destination: super::super::Foundation::PSTR)>;
pub type alljoyn_busattachment = isize;
pub type alljoyn_busattachment_joinsessioncb_ptr = ::core::option::Option<unsafe extern "system" fn(status: QStatus, sessionid: u32, opts: alljoyn_sessionopts, context: *mut ::core::ffi::c_void)>;
pub type alljoyn_busattachment_setlinktimeoutcb_ptr = ::core::option::Option<unsafe extern "system" fn(status: QStatus, timeout: u32, context: *mut ::core::ffi::c_void)>;
pub type alljoyn_buslistener = isize;
pub type alljoyn_buslistener_bus_disconnected_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_buslistener_bus_prop_changed_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, prop_name: super::super::Foundation::PSTR, prop_value: alljoyn_msgarg)>;
pub type alljoyn_buslistener_bus_stopping_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void)>;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_buslistener_callbacks {
pub listener_registered: alljoyn_buslistener_listener_registered_ptr,
pub listener_unregistered: alljoyn_buslistener_listener_unregistered_ptr,
pub found_advertised_name: alljoyn_buslistener_found_advertised_name_ptr,
pub lost_advertised_name: alljoyn_buslistener_lost_advertised_name_ptr,
pub name_owner_changed: alljoyn_buslistener_name_owner_changed_ptr,
pub bus_stopping: alljoyn_buslistener_bus_stopping_ptr,
pub bus_disconnected: alljoyn_buslistener_bus_disconnected_ptr,
pub property_changed: alljoyn_buslistener_bus_prop_changed_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_buslistener_callbacks {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_buslistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_buslistener_found_advertised_name_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, name: super::super::Foundation::PSTR, transport: u16, nameprefix: super::super::Foundation::PSTR)>;
pub type alljoyn_buslistener_listener_registered_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, bus: alljoyn_busattachment)>;
pub type alljoyn_buslistener_listener_unregistered_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_buslistener_lost_advertised_name_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, name: super::super::Foundation::PSTR, transport: u16, nameprefix: super::super::Foundation::PSTR)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_buslistener_name_owner_changed_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, busname: super::super::Foundation::PSTR, previousowner: super::super::Foundation::PSTR, newowner: super::super::Foundation::PSTR)>;
pub type alljoyn_busobject = isize;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_busobject_callbacks {
pub property_get: alljoyn_busobject_prop_get_ptr,
pub property_set: alljoyn_busobject_prop_set_ptr,
pub object_registered: alljoyn_busobject_object_registration_ptr,
pub object_unregistered: alljoyn_busobject_object_registration_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_busobject_callbacks {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_busobject_callbacks {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_busobject_methodentry {
pub member: *mut alljoyn_interfacedescription_member,
pub method_handler: alljoyn_messagereceiver_methodhandler_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_busobject_methodentry {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_busobject_methodentry {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_busobject_object_registration_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_busobject_prop_get_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, ifcname: super::super::Foundation::PSTR, propname: super::super::Foundation::PSTR, val: alljoyn_msgarg) -> QStatus>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_busobject_prop_set_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, ifcname: super::super::Foundation::PSTR, propname: super::super::Foundation::PSTR, val: alljoyn_msgarg) -> QStatus>;
#[repr(C)]
pub struct alljoyn_certificateid {
pub serial: *mut u8,
pub serialLen: usize,
pub issuerPublicKey: *mut i8,
pub issuerAki: *mut u8,
pub issuerAkiLen: usize,
}
impl ::core::marker::Copy for alljoyn_certificateid {}
impl ::core::clone::Clone for alljoyn_certificateid {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct alljoyn_certificateidarray {
pub count: usize,
pub ids: *mut alljoyn_certificateid,
}
impl ::core::marker::Copy for alljoyn_certificateidarray {}
impl ::core::clone::Clone for alljoyn_certificateidarray {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_claimcapability_masks = i32;
pub const CAPABLE_ECDHE_NULL: alljoyn_claimcapability_masks = 1i32;
pub const CAPABLE_ECDHE_ECDSA: alljoyn_claimcapability_masks = 4i32;
pub const CAPABLE_ECDHE_SPEKE: alljoyn_claimcapability_masks = 8i32;
pub type alljoyn_claimcapabilityadditionalinfo_masks = i32;
pub const PASSWORD_GENERATED_BY_SECURITY_MANAGER: alljoyn_claimcapabilityadditionalinfo_masks = 1i32;
pub const PASSWORD_GENERATED_BY_APPLICATION: alljoyn_claimcapabilityadditionalinfo_masks = 2i32;
pub type alljoyn_credentials = isize;
pub type alljoyn_interfacedescription = isize;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_interfacedescription_member {
pub iface: alljoyn_interfacedescription,
pub memberType: alljoyn_messagetype,
pub name: super::super::Foundation::PSTR,
pub signature: super::super::Foundation::PSTR,
pub returnSignature: super::super::Foundation::PSTR,
pub argNames: super::super::Foundation::PSTR,
pub internal_member: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_interfacedescription_member {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_interfacedescription_member {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_interfacedescription_property {
pub name: super::super::Foundation::PSTR,
pub signature: super::super::Foundation::PSTR,
pub access: u8,
pub internal_property: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_interfacedescription_property {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_interfacedescription_property {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_interfacedescription_securitypolicy = i32;
pub const AJ_IFC_SECURITY_INHERIT: alljoyn_interfacedescription_securitypolicy = 0i32;
pub const AJ_IFC_SECURITY_REQUIRED: alljoyn_interfacedescription_securitypolicy = 1i32;
pub const AJ_IFC_SECURITY_OFF: alljoyn_interfacedescription_securitypolicy = 2i32;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_interfacedescription_translation_callback_ptr = ::core::option::Option<unsafe extern "system" fn(sourcelanguage: super::super::Foundation::PSTR, targetlanguage: super::super::Foundation::PSTR, sourcetext: super::super::Foundation::PSTR) -> super::super::Foundation::PSTR>;
pub type alljoyn_keystore = isize;
pub type alljoyn_keystorelistener = isize;
pub type alljoyn_keystorelistener_acquireexclusivelock_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, listener: alljoyn_keystorelistener) -> QStatus>;
#[repr(C)]
pub struct alljoyn_keystorelistener_callbacks {
pub load_request: alljoyn_keystorelistener_loadrequest_ptr,
pub store_request: alljoyn_keystorelistener_storerequest_ptr,
}
impl ::core::marker::Copy for alljoyn_keystorelistener_callbacks {}
impl ::core::clone::Clone for alljoyn_keystorelistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_keystorelistener_loadrequest_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, listener: alljoyn_keystorelistener, keystore: alljoyn_keystore) -> QStatus>;
pub type alljoyn_keystorelistener_releaseexclusivelock_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, listener: alljoyn_keystorelistener)>;
pub type alljoyn_keystorelistener_storerequest_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, listener: alljoyn_keystorelistener, keystore: alljoyn_keystore) -> QStatus>;
#[repr(C)]
pub struct alljoyn_keystorelistener_with_synchronization_callbacks {
pub load_request: alljoyn_keystorelistener_loadrequest_ptr,
pub store_request: alljoyn_keystorelistener_storerequest_ptr,
pub acquire_exclusive_lock: alljoyn_keystorelistener_acquireexclusivelock_ptr,
pub release_exclusive_lock: alljoyn_keystorelistener_releaseexclusivelock_ptr,
}
impl ::core::marker::Copy for alljoyn_keystorelistener_with_synchronization_callbacks {}
impl ::core::clone::Clone for alljoyn_keystorelistener_with_synchronization_callbacks {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct alljoyn_manifestarray {
pub count: usize,
pub xmls: *mut *mut i8,
}
impl ::core::marker::Copy for alljoyn_manifestarray {}
impl ::core::clone::Clone for alljoyn_manifestarray {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_message = isize;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_messagereceiver_methodhandler_ptr = ::core::option::Option<unsafe extern "system" fn(bus: alljoyn_busobject, member: *const alljoyn_interfacedescription_member, message: alljoyn_message)>;
pub type alljoyn_messagereceiver_replyhandler_ptr = ::core::option::Option<unsafe extern "system" fn(message: alljoyn_message, context: *mut ::core::ffi::c_void)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_messagereceiver_signalhandler_ptr = ::core::option::Option<unsafe extern "system" fn(member: *const alljoyn_interfacedescription_member, srcpath: super::super::Foundation::PSTR, message: alljoyn_message)>;
pub type alljoyn_messagetype = i32;
pub const ALLJOYN_MESSAGE_INVALID: alljoyn_messagetype = 0i32;
pub const ALLJOYN_MESSAGE_METHOD_CALL: alljoyn_messagetype = 1i32;
pub const ALLJOYN_MESSAGE_METHOD_RET: alljoyn_messagetype = 2i32;
pub const ALLJOYN_MESSAGE_ERROR: alljoyn_messagetype = 3i32;
pub const ALLJOYN_MESSAGE_SIGNAL: alljoyn_messagetype = 4i32;
pub type alljoyn_msgarg = isize;
pub type alljoyn_observer = isize;
pub type alljoyn_observer_object_discovered_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, proxyref: alljoyn_proxybusobject_ref)>;
pub type alljoyn_observer_object_lost_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, proxyref: alljoyn_proxybusobject_ref)>;
pub type alljoyn_observerlistener = isize;
#[repr(C)]
pub struct alljoyn_observerlistener_callback {
pub object_discovered: alljoyn_observer_object_discovered_ptr,
pub object_lost: alljoyn_observer_object_lost_ptr,
}
impl ::core::marker::Copy for alljoyn_observerlistener_callback {}
impl ::core::clone::Clone for alljoyn_observerlistener_callback {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_permissionconfigurationlistener = isize;
#[repr(C)]
pub struct alljoyn_permissionconfigurationlistener_callbacks {
pub factory_reset: alljoyn_permissionconfigurationlistener_factoryreset_ptr,
pub policy_changed: alljoyn_permissionconfigurationlistener_policychanged_ptr,
pub start_management: alljoyn_permissionconfigurationlistener_startmanagement_ptr,
pub end_management: alljoyn_permissionconfigurationlistener_endmanagement_ptr,
}
impl ::core::marker::Copy for alljoyn_permissionconfigurationlistener_callbacks {}
impl ::core::clone::Clone for alljoyn_permissionconfigurationlistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_permissionconfigurationlistener_endmanagement_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void)>;
pub type alljoyn_permissionconfigurationlistener_factoryreset_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void) -> QStatus>;
pub type alljoyn_permissionconfigurationlistener_policychanged_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void)>;
pub type alljoyn_permissionconfigurationlistener_startmanagement_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void)>;
pub type alljoyn_permissionconfigurator = isize;
pub type alljoyn_pinglistener = isize;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_pinglistener_callback {
pub destination_found: alljoyn_autopinger_destination_found_ptr,
pub destination_lost: alljoyn_autopinger_destination_lost_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_pinglistener_callback {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_pinglistener_callback {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_proxybusobject = isize;
pub type alljoyn_proxybusobject_listener_getallpropertiescb_ptr = ::core::option::Option<unsafe extern "system" fn(status: QStatus, obj: alljoyn_proxybusobject, values: alljoyn_msgarg, context: *mut ::core::ffi::c_void)>;
pub type alljoyn_proxybusobject_listener_getpropertycb_ptr = ::core::option::Option<unsafe extern "system" fn(status: QStatus, obj: alljoyn_proxybusobject, value: alljoyn_msgarg, context: *mut ::core::ffi::c_void)>;
pub type alljoyn_proxybusobject_listener_introspectcb_ptr = ::core::option::Option<unsafe extern "system" fn(status: QStatus, obj: alljoyn_proxybusobject, context: *mut ::core::ffi::c_void)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_proxybusobject_listener_propertieschanged_ptr = ::core::option::Option<unsafe extern "system" fn(obj: alljoyn_proxybusobject, ifacename: super::super::Foundation::PSTR, changed: alljoyn_msgarg, invalidated: alljoyn_msgarg, context: *mut ::core::ffi::c_void)>;
pub type alljoyn_proxybusobject_listener_setpropertycb_ptr = ::core::option::Option<unsafe extern "system" fn(status: QStatus, obj: alljoyn_proxybusobject, context: *mut ::core::ffi::c_void)>;
pub type alljoyn_proxybusobject_ref = isize;
pub type alljoyn_securityapplicationproxy = isize;
pub type alljoyn_sessionlistener = isize;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_sessionlistener_callbacks {
pub session_lost: alljoyn_sessionlistener_sessionlost_ptr,
pub session_member_added: alljoyn_sessionlistener_sessionmemberadded_ptr,
pub session_member_removed: alljoyn_sessionlistener_sessionmemberremoved_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_sessionlistener_callbacks {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_sessionlistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
pub type alljoyn_sessionlistener_sessionlost_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, sessionid: u32, reason: alljoyn_sessionlostreason)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_sessionlistener_sessionmemberadded_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, sessionid: u32, uniquename: super::super::Foundation::PSTR)>;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_sessionlistener_sessionmemberremoved_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, sessionid: u32, uniquename: super::super::Foundation::PSTR)>;
pub type alljoyn_sessionlostreason = i32;
pub const ALLJOYN_SESSIONLOST_INVALID: alljoyn_sessionlostreason = 0i32;
pub const ALLJOYN_SESSIONLOST_REMOTE_END_LEFT_SESSION: alljoyn_sessionlostreason = 1i32;
pub const ALLJOYN_SESSIONLOST_REMOTE_END_CLOSED_ABRUPTLY: alljoyn_sessionlostreason = 2i32;
pub const ALLJOYN_SESSIONLOST_REMOVED_BY_BINDER: alljoyn_sessionlostreason = 3i32;
pub const ALLJOYN_SESSIONLOST_LINK_TIMEOUT: alljoyn_sessionlostreason = 4i32;
pub const ALLJOYN_SESSIONLOST_REASON_OTHER: alljoyn_sessionlostreason = 5i32;
pub type alljoyn_sessionopts = isize;
pub type alljoyn_sessionportlistener = isize;
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_sessionportlistener_acceptsessionjoiner_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, sessionport: u16, joiner: super::super::Foundation::PSTR, opts: alljoyn_sessionopts) -> i32>;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct alljoyn_sessionportlistener_callbacks {
pub accept_session_joiner: alljoyn_sessionportlistener_acceptsessionjoiner_ptr,
pub session_joined: alljoyn_sessionportlistener_sessionjoined_ptr,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for alljoyn_sessionportlistener_callbacks {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for alljoyn_sessionportlistener_callbacks {
fn clone(&self) -> Self {
*self
}
}
#[cfg(feature = "Win32_Foundation")]
pub type alljoyn_sessionportlistener_sessionjoined_ptr = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void, sessionport: u16, id: u32, joiner: super::super::Foundation::PSTR)>;
pub type alljoyn_typeid = i32;
pub const ALLJOYN_INVALID: alljoyn_typeid = 0i32;
pub const ALLJOYN_ARRAY: alljoyn_typeid = 97i32;
pub const ALLJOYN_BOOLEAN: alljoyn_typeid = 98i32;
pub const ALLJOYN_DOUBLE: alljoyn_typeid = 100i32;
pub const ALLJOYN_DICT_ENTRY: alljoyn_typeid = 101i32;
pub const ALLJOYN_SIGNATURE: alljoyn_typeid = 103i32;
pub const ALLJOYN_HANDLE: alljoyn_typeid = 104i32;
pub const ALLJOYN_INT32: alljoyn_typeid = 105i32;
pub const ALLJOYN_INT16: alljoyn_typeid = 110i32;
pub const ALLJOYN_OBJECT_PATH: alljoyn_typeid = 111i32;
pub const ALLJOYN_UINT16: alljoyn_typeid = 113i32;
pub const ALLJOYN_STRUCT: alljoyn_typeid = 114i32;
pub const ALLJOYN_STRING: alljoyn_typeid = 115i32;
pub const ALLJOYN_UINT64: alljoyn_typeid = 116i32;
pub const ALLJOYN_UINT32: alljoyn_typeid = 117i32;
pub const ALLJOYN_VARIANT: alljoyn_typeid = 118i32;
pub const ALLJOYN_INT64: alljoyn_typeid = 120i32;
pub const ALLJOYN_BYTE: alljoyn_typeid = 121i32;
pub const ALLJOYN_STRUCT_OPEN: alljoyn_typeid = 40i32;
pub const ALLJOYN_STRUCT_CLOSE: alljoyn_typeid = 41i32;
pub const ALLJOYN_DICT_ENTRY_OPEN: alljoyn_typeid = 123i32;
pub const ALLJOYN_DICT_ENTRY_CLOSE: alljoyn_typeid = 125i32;
pub const ALLJOYN_BOOLEAN_ARRAY: alljoyn_typeid = 25185i32;
pub const ALLJOYN_DOUBLE_ARRAY: alljoyn_typeid = 25697i32;
pub const ALLJOYN_INT32_ARRAY: alljoyn_typeid = 26977i32;
pub const ALLJOYN_INT16_ARRAY: alljoyn_typeid = 28257i32;
pub const ALLJOYN_UINT16_ARRAY: alljoyn_typeid = 29025i32;
pub const ALLJOYN_UINT64_ARRAY: alljoyn_typeid = 29793i32;
pub const ALLJOYN_UINT32_ARRAY: alljoyn_typeid = 30049i32;
pub const ALLJOYN_INT64_ARRAY: alljoyn_typeid = 30817i32;
pub const ALLJOYN_BYTE_ARRAY: alljoyn_typeid = 31073i32;
pub const ALLJOYN_WILDCARD: alljoyn_typeid = 42i32;
|
use chrono::prelude::*;
use diesel::sql_types::{Nullable, Text, Timestamp, Uuid as dUuid};
use uuid::Uuid;
#[derive(Queryable, QueryableByName, Serialize, Deserialize)]
pub struct RedeemableTicket {
#[sql_type = "dUuid"]
pub id: Uuid,
#[sql_type = "Text"]
pub ticket_type: String,
#[sql_type = "dUuid"]
pub user_id: Uuid,
#[sql_type = "Text"]
pub first_name: String,
#[sql_type = "Text"]
pub last_name: String,
#[sql_type = "Nullable<Text>"]
pub email: Option<String>,
#[sql_type = "Nullable<Text>"]
pub phone: Option<String>,
#[sql_type = "Nullable<Text>"]
pub redeem_key: Option<String>,
#[sql_type = "Nullable<Timestamp>"]
pub redeem_date: Option<NaiveDateTime>,
#[sql_type = "Text"]
pub status: String,
#[sql_type = "dUuid"]
pub event_id: Uuid,
#[sql_type = "Text"]
pub event_name: String,
#[sql_type = "Nullable<Timestamp>"]
pub door_time: Option<NaiveDateTime>,
#[sql_type = "Nullable<Timestamp>"]
pub event_start: Option<NaiveDateTime>,
#[sql_type = "Nullable<dUuid>"]
pub venue_id: Option<Uuid>,
#[sql_type = "Text"]
pub venue_name: String,
}
|
#[doc = "Reader of register RAM0CTRL"]
pub type R = crate::R<u32, super::RAM0CTRL>;
#[doc = "Writer for register RAM0CTRL"]
pub type W = crate::W<u32, super::RAM0CTRL>;
#[doc = "Register RAM0CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::RAM0CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "RAM0 Blockset Power-down\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RAMPOWERDOWN_A {
#[doc = "0: None of the RAM blocks powered down"]
NONE = 0,
#[doc = "8: Power down RAM blocks 4 and above"]
BLK4 = 8,
#[doc = "12: Power down RAM blocks 3 and above"]
BLK3TO4 = 12,
#[doc = "14: Power down RAM blocks 2 and above"]
BLK2TO4 = 14,
#[doc = "15: Power down RAM blocks 1 and above"]
BLK1TO4 = 15,
}
impl From<RAMPOWERDOWN_A> for u8 {
#[inline(always)]
fn from(variant: RAMPOWERDOWN_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `RAMPOWERDOWN`"]
pub type RAMPOWERDOWN_R = crate::R<u8, RAMPOWERDOWN_A>;
impl RAMPOWERDOWN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, RAMPOWERDOWN_A> {
use crate::Variant::*;
match self.bits {
0 => Val(RAMPOWERDOWN_A::NONE),
8 => Val(RAMPOWERDOWN_A::BLK4),
12 => Val(RAMPOWERDOWN_A::BLK3TO4),
14 => Val(RAMPOWERDOWN_A::BLK2TO4),
15 => Val(RAMPOWERDOWN_A::BLK1TO4),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `NONE`"]
#[inline(always)]
pub fn is_none(&self) -> bool {
*self == RAMPOWERDOWN_A::NONE
}
#[doc = "Checks if the value of the field is `BLK4`"]
#[inline(always)]
pub fn is_blk4(&self) -> bool {
*self == RAMPOWERDOWN_A::BLK4
}
#[doc = "Checks if the value of the field is `BLK3TO4`"]
#[inline(always)]
pub fn is_blk3to4(&self) -> bool {
*self == RAMPOWERDOWN_A::BLK3TO4
}
#[doc = "Checks if the value of the field is `BLK2TO4`"]
#[inline(always)]
pub fn is_blk2to4(&self) -> bool {
*self == RAMPOWERDOWN_A::BLK2TO4
}
#[doc = "Checks if the value of the field is `BLK1TO4`"]
#[inline(always)]
pub fn is_blk1to4(&self) -> bool {
*self == RAMPOWERDOWN_A::BLK1TO4
}
}
#[doc = "Write proxy for field `RAMPOWERDOWN`"]
pub struct RAMPOWERDOWN_W<'a> {
w: &'a mut W,
}
impl<'a> RAMPOWERDOWN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RAMPOWERDOWN_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "None of the RAM blocks powered down"]
#[inline(always)]
pub fn none(self) -> &'a mut W {
self.variant(RAMPOWERDOWN_A::NONE)
}
#[doc = "Power down RAM blocks 4 and above"]
#[inline(always)]
pub fn blk4(self) -> &'a mut W {
self.variant(RAMPOWERDOWN_A::BLK4)
}
#[doc = "Power down RAM blocks 3 and above"]
#[inline(always)]
pub fn blk3to4(self) -> &'a mut W {
self.variant(RAMPOWERDOWN_A::BLK3TO4)
}
#[doc = "Power down RAM blocks 2 and above"]
#[inline(always)]
pub fn blk2to4(self) -> &'a mut W {
self.variant(RAMPOWERDOWN_A::BLK2TO4)
}
#[doc = "Power down RAM blocks 1 and above"]
#[inline(always)]
pub fn blk1to4(self) -> &'a mut W {
self.variant(RAMPOWERDOWN_A::BLK1TO4)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - RAM0 Blockset Power-down"]
#[inline(always)]
pub fn rampowerdown(&self) -> RAMPOWERDOWN_R {
RAMPOWERDOWN_R::new((self.bits & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - RAM0 Blockset Power-down"]
#[inline(always)]
pub fn rampowerdown(&mut self) -> RAMPOWERDOWN_W {
RAMPOWERDOWN_W { w: self }
}
}
|
use State::*;
enum State {
Start,
Group,
Garbage,
Escape,
}
pub fn get_score(input: &str) -> usize {
let mut analyzer = StreamAnalyzer::new();
input.chars()
.for_each(|ch| analyzer.next_char(ch));
analyzer.get_score()
}
pub fn count_garbage(input: &str) -> usize {
let mut analyzer = StreamAnalyzer::new();
input.chars()
.for_each(|ch| analyzer.next_char(ch));
analyzer.count_garbage()
}
pub struct StreamAnalyzer {
state: State,
level: usize,
score: usize,
garbage_count: usize,
}
impl StreamAnalyzer {
pub fn new() -> StreamAnalyzer {
StreamAnalyzer {
state: Start,
level: 0,
score: 0,
garbage_count: 0,
}
}
pub fn next_char(&mut self, ch: char) {
match self.state {
Start => {
match ch {
'{' => {
self.state = Group;
self.level = 1;
self.score += 1;
},
'<' => {
self.state = Garbage;
}
_ => (),
};
},
Group => {
match ch {
'{' => {
self.level += 1;
self.score += self.level;
},
'}' => {
self.level -= 1;
if 0 == self.level {
self.state = Start;
}
},
'<' => {
self.state = Garbage;
},
_ => (),
};
},
Garbage => {
match ch {
'>' => {
self.state = if self.level == 0 {
Start
} else {
Group
};
},
'!' => {
self.state = Escape;
},
_ => {
self.garbage_count += 1;
},
};
},
Escape => {
self.state = Garbage;
},
};
}
pub fn get_score(&self) -> usize {
self.score
}
pub fn count_garbage(&self) -> usize {
self.garbage_count
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_score() {
assert_eq!(1, get_score("{}"));
assert_eq!(6, get_score("{{{}}}"));
assert_eq!(5, get_score("{{},{}}"));
assert_eq!(16, get_score("{{{},{},{{}}}}"));
assert_eq!(1, get_score("{<a>,<a>,<a>,<a>}"));
assert_eq!(9, get_score("{{<ab>},{<ab>},{<ab>},{<ab>}}"));
assert_eq!(9, get_score("{{<!!>},{<!!>},{<!!>},{<!!>}}"));
assert_eq!(3, get_score("{{<a!>},{<a!>},{<a!>},{<ab>}}"));
}
#[test]
fn test_count_garbage() {
assert_eq!(0, count_garbage("<>"));
assert_eq!(17, count_garbage("<random characters>"));
assert_eq!(3, count_garbage("<<<<>"));
assert_eq!(2, count_garbage("<{!>}>"));
assert_eq!(0, count_garbage("<!!>"));
assert_eq!(0, count_garbage("<!!!>>"));
assert_eq!(10, count_garbage(r#"<{o"i!a,<{i<a>"#));
}
}
|
use std::thread;
struct Philosopher{
name: String,
}
impl Philosopher{
fn new(name: &str) -> Philosopher{
Philosopher{
name: name.to_string(),
}
}
fn eat(&self){
println!("{} is eating", self.name);
thread::sleep_ms(10);
println!("{} is done eating", self.name);
}
}
fn main(){
let v = vec![
Philosopher::new("p1"),
Philosopher::new("p2"),
Philosopher::new("p3"),
Philosopher::new("p4"),
Philosopher::new("p5"),
];
let handles: Vec<_> = v.into_iter().map(|p| {
thread::spawn(move || {
p.eat();
})
}).collect();
for h in handles{
h.join().unwrap();
}
}
|
fn add_one(x: i32) -> i32 {
x + 1
}
/// fn is a concrete type and implements all of Fn, FnOnce and FnMut
/// So below we dont have to mark the param fn
/// By doing so users cannot pause closures to the function
fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
f(arg) + f(arg)
}
fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
Box::new(|x| x + 1)
}
fn do_twice_generic(f: impl Fn(i32) -> i32, arg: i32) -> i32
{
f(arg) + f(arg)
}
fn main() {
let _answer = do_twice(add_one, 5);
// let inc = 2;
// let answer = do_twice(|x| x + inc, 5); // compilation error
let _answer = do_twice_generic(|x| x + 1, 5);
let _answer = returns_closure()(5);
} |
// Copyright 2019 The vault713 Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::client::Output;
use crate::swap::message::SecondaryUpdate;
use crate::swap::ser::*;
use crate::swap::types::{Network, SecondaryData};
use crate::swap::{ErrorKind, Keychain};
use bitcoin::blockdata::opcodes::{all::*, OP_FALSE};
use bitcoin::blockdata::script::Builder;
use bitcoin::consensus::Encodable;
use bitcoin::network::constants::Network as BtcNetwork;
use bitcoin::{Address, Script, Transaction, TxIn, TxOut, VarInt};
use bitcoin_hashes::sha256d;
use byteorder::{ByteOrder, LittleEndian};
use chrono::Utc;
use grin_keychain::{Identifier, SwitchCommitmentType};
use grin_util::secp::key::{PublicKey, SecretKey};
use grin_util::secp::{Message, Secp256k1, Signature};
use std::io::Cursor;
use std::ops::Deref;
use std::time::Duration;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BtcRedeemTx {
pub txid: sha256d::Hash,
#[serde(serialize_with = "bytes_to_hex", deserialize_with = "bytes_from_hex")]
pub tx: Vec<u8>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BtcData {
pub lock_time: u32,
/// Key owned by seller
#[serde(serialize_with = "pubkey_to_hex", deserialize_with = "pubkey_from_hex")]
pub cosign: PublicKey,
/// Key owned by buyer
#[serde(
serialize_with = "option_pubkey_to_hex",
deserialize_with = "option_pubkey_from_hex"
)]
pub refund: Option<PublicKey>,
pub confirmed_outputs: Vec<Output>,
pub locked: bool,
pub redeem_tx: Option<BtcRedeemTx>,
pub redeem_confirmations: Option<u64>,
#[serde(skip)]
pub script: Option<Script>,
}
impl BtcData {
pub(crate) fn new<K>(
keychain: &K,
context: &BtcSellerContext,
duration: Duration,
) -> Result<Self, ErrorKind>
where
K: Keychain,
{
let lock_time = if crate::swap::is_test_mode() {
1567718553
} else {
Utc::now().timestamp() as u64 + duration.as_secs()
};
assert!(lock_time > 0 && lock_time < std::u32::MAX as u64);
let cosign = PublicKey::from_secret_key(
keychain.secp(),
&keychain.derive_key(0, &context.cosign, &SwitchCommitmentType::None)?,
)?;
Ok(Self {
lock_time: lock_time as u32,
cosign,
refund: None,
confirmed_outputs: Vec::new(),
locked: false,
redeem_tx: None,
redeem_confirmations: None,
script: None,
})
}
pub(crate) fn from_offer<K>(
keychain: &K,
offer: BtcOfferUpdate,
context: &BtcBuyerContext,
) -> Result<Self, ErrorKind>
where
K: Keychain,
{
let key = keychain.derive_key(0, &context.refund, &SwitchCommitmentType::None)?;
Ok(Self {
lock_time: offer.lock_time,
cosign: offer.cosign,
refund: Some(PublicKey::from_secret_key(keychain.secp(), &key)?),
confirmed_outputs: Vec::new(),
locked: false,
redeem_tx: None,
redeem_confirmations: None,
script: None,
})
}
pub(crate) fn accepted_offer(
&mut self,
accepted_offer: BtcAcceptOfferUpdate,
) -> Result<(), ErrorKind> {
self.refund = Some(accepted_offer.refund);
Ok(())
}
pub(crate) fn wrap(self) -> SecondaryData {
SecondaryData::Btc(self)
}
/// Generate the multisig-with-timelocked-refund script
pub fn script(&mut self, secp: &Secp256k1, redeem: &PublicKey) -> Result<(), ErrorKind> {
if self.script.is_none() {
let mut time = [0; 4];
LittleEndian::write_u32(&mut time, self.lock_time);
let refund = self
.refund
.ok_or(ErrorKind::SecondaryDataIncomplete)?
.serialize_vec(secp, true);
let cosign = self.cosign.serialize_vec(secp, true);
let redeem = redeem.serialize_vec(secp, true);
let builder = Builder::new()
.push_opcode(OP_IF) // Refund path
.push_slice(&time)
.push_opcode(OP_CLTV) // Check transaction lock time
.push_opcode(OP_DROP)
.push_slice(refund.as_slice())
.push_opcode(OP_CHECKSIG) // Check signature
.push_opcode(OP_ELSE) // Redeem path
.push_opcode(OP_PUSHNUM_2)
.push_slice(cosign.as_slice())
.push_slice(redeem.as_slice())
.push_opcode(OP_PUSHNUM_2)
.push_opcode(OP_CHECKMULTISIG) // Check 2-of-2 multisig
.push_opcode(OP_ENDIF);
self.script = Some(builder.into_script());
}
Ok(())
}
/// Generate the P2SH address for the script
pub fn address(&self, network: Network) -> Result<Address, ErrorKind> {
let address = Address::p2sh(
self.script
.as_ref()
.ok_or(ErrorKind::Generic("Missing script".into()))?,
btc_network(network),
);
Ok(address)
}
pub(crate) fn redeem_tx(
&mut self,
secp: &Secp256k1,
redeem_address: &Address,
fee_sat_per_byte: u64,
cosign_secret: &SecretKey,
redeem_secret: &SecretKey,
) -> Result<(Transaction, usize, usize), ErrorKind> {
let input_script = self
.script
.as_ref()
.ok_or(ErrorKind::Generic("Missing script".into()))?;
// Input(s)
let mut input = Vec::with_capacity(self.confirmed_outputs.len());
let mut total_amount = 0;
for o in &self.confirmed_outputs {
total_amount += o.value;
input.push(TxIn {
previous_output: o.out_point.clone(),
script_sig: Script::new(),
sequence: 0xFFFFFFFF,
witness: Vec::new(),
});
}
// Output
let mut output = Vec::with_capacity(1);
output.push(TxOut {
value: total_amount, // Will be overwritten later
script_pubkey: redeem_address.script_pubkey(),
});
let mut tx = Transaction {
version: 2,
lock_time: 0,
input,
output,
};
// Calculate tx size
let mut script_sig_size = input_script.len();
script_sig_size += VarInt(script_sig_size as u64).len();
script_sig_size += 2 * (1 + 72 + 1); // Signatures
script_sig_size += 2; // Opcodes
let tx_size = tx.get_weight() / 4 + script_sig_size * tx.input.len();
// Subtract fee from output
tx.output[0].value = total_amount.saturating_sub(tx_size as u64 * fee_sat_per_byte);
// Sign for inputs
for idx in 0..tx.input.len() {
let hash = tx.signature_hash(idx, &input_script, 0x01);
let msg = Message::from_slice(hash.deref())?;
tx.input.get_mut(idx).unwrap().script_sig = self.redeem_script_sig(
secp,
&secp.sign(&msg, cosign_secret)?,
&secp.sign(&msg, redeem_secret)?,
)?;
}
let mut cursor = Cursor::new(Vec::with_capacity(tx_size));
let actual_size = tx
.consensus_encode(&mut cursor)
.map_err(|_| ErrorKind::Generic("Unable to encode redeem tx".into()))?;
self.redeem_tx = Some(BtcRedeemTx {
txid: tx.txid(),
tx: cursor.into_inner(),
});
Ok((tx, tx_size, actual_size))
}
fn redeem_script_sig(
&self,
secp: &Secp256k1,
cosign_signature: &Signature,
redeem_signature: &Signature,
) -> Result<Script, ErrorKind> {
let mut cosign_ser = cosign_signature.serialize_der(secp);
cosign_ser.push(0x01); // SIGHASH_ALL
let mut redeem_ser = redeem_signature.serialize_der(secp);
redeem_ser.push(0x01); // SIGHASH_ALL
let script_sig = Builder::new()
.push_opcode(OP_FALSE) // Bitcoin multisig bug
.push_slice(&cosign_ser)
.push_slice(&redeem_ser)
.push_opcode(OP_FALSE) // Choose redeem path in original script
.push_slice(
&self
.script
.as_ref()
.ok_or(ErrorKind::Generic("Missing script".into()))?
.to_bytes(),
)
.into_script();
Ok(script_sig)
}
pub(crate) fn offer_update(&self) -> BtcUpdate {
BtcUpdate::Offer(BtcOfferUpdate {
lock_time: self.lock_time,
cosign: self.cosign.clone(),
})
}
pub(crate) fn accept_offer_update(&self) -> Result<BtcUpdate, ErrorKind> {
Ok(BtcUpdate::AcceptOffer(BtcAcceptOfferUpdate {
refund: self.refund.ok_or(ErrorKind::UnexpectedMessageType)?.clone(),
}))
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BtcSellerContext {
pub cosign: Identifier,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BtcBuyerContext {
pub refund: Identifier,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum BtcUpdate {
Offer(BtcOfferUpdate),
AcceptOffer(BtcAcceptOfferUpdate),
}
impl BtcUpdate {
pub fn unwrap_offer(self) -> Result<BtcOfferUpdate, ErrorKind> {
match self {
BtcUpdate::Offer(u) => Ok(u),
_ => Err(ErrorKind::UnexpectedMessageType),
}
}
pub fn unwrap_accept_offer(self) -> Result<BtcAcceptOfferUpdate, ErrorKind> {
match self {
BtcUpdate::AcceptOffer(u) => Ok(u),
_ => Err(ErrorKind::UnexpectedMessageType),
}
}
pub fn wrap(self) -> SecondaryUpdate {
SecondaryUpdate::BTC(self)
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BtcOfferUpdate {
pub lock_time: u32,
#[serde(serialize_with = "pubkey_to_hex", deserialize_with = "pubkey_from_hex")]
pub cosign: PublicKey,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BtcAcceptOfferUpdate {
#[serde(serialize_with = "pubkey_to_hex", deserialize_with = "pubkey_from_hex")]
pub refund: PublicKey,
}
fn btc_network(network: Network) -> BtcNetwork {
match network {
Network::Floonet => BtcNetwork::Testnet,
Network::Mainnet => BtcNetwork::Bitcoin,
}
}
#[cfg(test)]
mod tests {
use super::*;
use bitcoin::util::address::Payload;
use bitcoin::util::key::PublicKey as BTCPublicKey;
use bitcoin::OutPoint;
use bitcoin_hashes::{hash160, Hash};
use grin_util::from_hex;
use grin_util::secp::key::PublicKey;
use grin_util::secp::{ContextFlag, Secp256k1};
use rand::{thread_rng, Rng, RngCore};
use std::collections::HashMap;
#[test]
/// Test vector from the PoC
fn test_lock_script() {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let mut data = BtcData {
lock_time: 1541355813,
cosign: PublicKey::from_slice(
&secp,
&from_hex(
"02b4e59070d367a364a31981a71fc5ab6c5034d0e279eecec19287f3c95db84aef".into(),
)
.unwrap(),
)
.unwrap(),
refund: Some(
PublicKey::from_slice(
&secp,
&from_hex(
"022fd8c0455bede249ad3b9a9fb8159829e8cfb2c360863896e5309ea133d122f2".into(),
)
.unwrap(),
)
.unwrap(),
),
confirmed_outputs: Vec::new(),
locked: false,
redeem_tx: None,
redeem_confirmations: None,
script: None,
};
data.script(
&secp,
&PublicKey::from_slice(
&secp,
&from_hex(
"03cf15041579b5fb7accbac2997fb2f3e1001e9a522a19c83ceabe5ae51a596c7c".into(),
)
.unwrap(),
)
.unwrap(),
)
.unwrap();
let script_ref = from_hex("63042539df5bb17521022fd8c0455bede249ad3b9a9fb8159829e8cfb2c360863896e5309ea133d122f2ac67522102b4e59070d367a364a31981a71fc5ab6c5034d0e279eecec19287f3c95db84aef2103cf15041579b5fb7accbac2997fb2f3e1001e9a522a19c83ceabe5ae51a596c7c52ae68".into()).unwrap();
assert_eq!(data.script.clone().unwrap().to_bytes(), script_ref);
assert_eq!(
format!("{}", data.address(Network::Floonet).unwrap()),
String::from("2NEwEAG9VyFYt2sjLpuHrU4Abb7nGJfc7PR")
);
}
#[test]
fn test_redeem_script() {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let rng = &mut thread_rng();
let network = Network::Floonet;
let cosign = SecretKey::new(&secp, rng);
let refund = SecretKey::new(&secp, rng);
let redeem = SecretKey::new(&secp, rng);
let mut data = BtcData {
lock_time: Utc::now().timestamp() as u32,
cosign: PublicKey::from_secret_key(&secp, &cosign).unwrap(),
refund: Some(PublicKey::from_secret_key(&secp, &refund).unwrap()),
confirmed_outputs: Vec::new(),
locked: false,
redeem_tx: None,
redeem_confirmations: None,
script: None,
};
data.script(&secp, &PublicKey::from_secret_key(&secp, &redeem).unwrap())
.unwrap();
let lock_address = data.address(network).unwrap();
let lock_script_pubkey = lock_address.script_pubkey();
// Create a bunch of funding transactions
let count = rng.gen_range(3, 7);
let mut funding_txs = HashMap::with_capacity(count);
for i in 0..count {
let value = (i as u64 + 1) * 1_000_000;
// Generate a bunch of trash P2PKH and P2SH outputs
let vout = rng.gen_range(0usize, 5);
let mut output = Vec::with_capacity(vout + 1);
for _ in 0..vout {
let mut hash: Vec<u8> = vec![0; 20];
rng.fill_bytes(&mut hash);
let hash = hash160::Hash::from_slice(&hash).unwrap();
let payload = if rng.gen_bool(0.5) {
Payload::PubkeyHash(hash)
} else {
Payload::ScriptHash(hash)
};
let script_pubkey = payload.script_pubkey();
output.push(TxOut {
value: rng.gen(),
script_pubkey,
});
}
output.push(TxOut {
value,
script_pubkey: lock_script_pubkey.clone(),
});
let tx = Transaction {
version: 2,
lock_time: data.lock_time - 1,
input: vec![],
output,
};
let txid = tx.txid();
data.confirmed_outputs.push(Output {
out_point: OutPoint {
txid: txid.clone(),
vout: vout as u32,
},
value,
height: 1,
});
funding_txs.insert(tx.txid(), tx);
}
let redeem_address = Address::p2pkh(
&BTCPublicKey {
compressed: true,
key: PublicKey::from_secret_key(&secp, &SecretKey::new(&secp, rng)).unwrap(),
},
btc_network(network),
);
// Generate redeem transaction
let (tx, est_size, actual_size) = data
.redeem_tx(&secp, &redeem_address, 10, &cosign, &redeem)
.unwrap();
let diff = (est_size as i64 - actual_size as i64).abs() as usize;
assert!(diff <= count); // Our size estimation should be very close to the real size
// Moment of truth: our redeem tx should be valid
tx.verify(&funding_txs).unwrap();
}
}
|
use std::io;
// use rand::Rng;
use std::time::Duration;
use std::thread;
const CORRELATIVE_STARTS:[&'static str; 5] = ["ki","ti","i","neni","ĉi"];
const CORRELATIVE_ENDS: [&'static str; 9] = ["a","al","am","om","el","es","o","u","e"];
const UI_DELAY: u64 = 20;
fn ui_delay(m: u64) {
thread::sleep(Duration::from_millis(UI_DELAY * m))
}
fn main() {
ui_delay(50);
let mut start_input = String::new();
println!("Welcome to the correlative quiz game!");
ui_delay(10);
println!("Bonvenon al la ludo de tabelvortoj!");
ui_delay(10);
println!("");
ui_delay(30);
println!("Type \"start\" to begin.");
ui_delay(10);
println!("Tajpu \"ek\" por komenci.");
io::stdin().read_line(&mut start_input).expect("Could not read input");
let mut correlatives = Vec::new();
for c_start in CORRELATIVE_STARTS.iter() {
for c_end in CORRELATIVE_ENDS.iter() {
let correlative = format!("{}{}", c_start, c_end);
println!("{}", correlative);
correlatives.push(correlative);
}
}
println!("{:?}", correlatives)
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::SEMSTAT {
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
}
#[doc = "Possible values of the field `SEMSTAT`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SEMSTATR {
#[doc = "Semaphore is free."]
FREE,
#[doc = "Semaphore is assigned to the CPU."]
CPU,
#[doc = "Semaphore is assigned to the SPIS."]
SPIS,
#[doc = "Semaphore is assigned to the SPIS, but a handover to the CPU is pending."]
CPUPENDING,
}
impl SEMSTATR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
SEMSTATR::FREE => 0,
SEMSTATR::CPU => 1,
SEMSTATR::SPIS => 2,
SEMSTATR::CPUPENDING => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> SEMSTATR {
match value {
0 => SEMSTATR::FREE,
1 => SEMSTATR::CPU,
2 => SEMSTATR::SPIS,
3 => SEMSTATR::CPUPENDING,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `FREE`"]
#[inline]
pub fn is_free(&self) -> bool {
*self == SEMSTATR::FREE
}
#[doc = "Checks if the value of the field is `CPU`"]
#[inline]
pub fn is_cpu(&self) -> bool {
*self == SEMSTATR::CPU
}
#[doc = "Checks if the value of the field is `SPIS`"]
#[inline]
pub fn is_spis(&self) -> bool {
*self == SEMSTATR::SPIS
}
#[doc = "Checks if the value of the field is `CPUPENDING`"]
#[inline]
pub fn is_cpupending(&self) -> bool {
*self == SEMSTATR::CPUPENDING
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - Semaphore status."]
#[inline]
pub fn semstat(&self) -> SEMSTATR {
SEMSTATR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
}
|
// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.
#[derive(Debug)]
pub struct Duration {
seconds: u64,
}
impl From<u64> for Duration {
fn from(s: u64) -> Self {
return Duration { seconds: s };
}
}
pub trait Planet {
fn years_during(d: &Duration) -> f64 {
unimplemented!(
"convert a duration ({:?}) to the number of years on this planet for that duration",
d,
);
}
orbital_time: f64;
}
struct Planet{
orbital_time: f64
}
pub struct Mercury;
pub struct Venus;
pub struct Earth;
pub struct Mars;
pub struct Jupiter;
pub struct Saturn;
pub struct Uranus;
pub struct Neptune;
impl Planet for Mercury {}
impl Planet for Venus {}
impl Planet for Earth {}
impl Planet for Mars {}
impl Planet for Jupiter {}
impl Planet for Saturn {}
impl Planet for Uranus {}
impl Planet for Neptune {}
use std::convert::From;
#[derive(Debug)]
struct Number {
value: i32,
}
impl From<i32> for Number {
fn from(item: i32) -> Self {
Number { value: item }
}
}
fn main() {
let num = Number::from(30);
println!("My number is {:?}", num);
}
|
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Character {
pub name: String,
pub league: String,
pub class_id: i32,
pub class: String,
pub level: i32,
}
#[derive(Deserialize, Debug)]
pub struct CharacterWindowGetItems {
pub items: Vec<Item>,
pub character: Character,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Item {
ilvl: i32,
name: String,
type_line: String,
implicit_mods: Option<Vec<String>>,
explicit_mods: Option<Vec<String>>,
inventory_id: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct League {
pub id: String,
pub description: String,
pub url: Option<String>,
pub start_at: Option<String>,
pub end_at: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct PublicStashTab {
pub next_change_id: String,
pub stashes: Vec<StashTab>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct StashTab {
pub id: String,
pub public: bool,
pub account_name: Option<String>,
pub last_character_name: Option<String>,
pub stash: Option<String>,
pub stash_type: String,
}
|
use error;
pub fn solve_puzzle(puzzle: &mut [[u32; 9]; 9])
{
puzzle_loop(puzzle, 0, 0);
if validate_puzzle(puzzle) == true
{
print_puzzle(puzzle);
println!("Puzzle complete!");
}
else
{
println!("Puzzle cannot be solved");
}
}
//The recursive loop that solves the puzzle
fn puzzle_loop(puzzle: &mut [[u32; 9]; 9], y: usize, x: usize) -> bool
{
if y == 9
{
return true
}
if puzzle[y][x] == 0
{
for n in 1..10
{
puzzle[y][x] = n;
if validate_specific_val(puzzle, y, x) == true
{
if x == 8
{
if puzzle_loop(puzzle, y + 1, 0) == true
{
return true
}
}
else
{
if puzzle_loop(puzzle, y, x + 1) == true
{
return true
}
}
}
}
puzzle[y][x] = 0;
return false
}
else
{
if x == 8
{
if puzzle_loop(puzzle, y + 1, 0) == true
{
return true
}
}
else
{
if puzzle_loop(puzzle, y, x + 1) == true
{
return true
}
}
}
return false
}
pub fn print_puzzle(puzzle: &[[u32; 9]; 9])
{
for y in 0..9
{
println!("{}{}{} | {}{}{} | {}{}{}", puzzle[y][0], puzzle[y][1], puzzle[y][2], puzzle[y][3], puzzle[y][4], puzzle[y][5], puzzle[y][6], puzzle[y][7], puzzle[y][8]);
if (y + 1) % 3 == 0 && y != 8
{
println!("----+-----+----");
}
}
}
//Validates the entire puzzle
pub fn validate_puzzle(puzzle: &[[u32; 9]; 9]) -> bool
{
for y in 0..9
{
for x in 0..9
{
if validate_specific_val(puzzle, y, x) == false
{
return false
}
}
}
true
}
//Validates a specific piece of the puzzle
fn validate_specific_val(puzzle: &[[u32; 9]; 9], y: usize, x: usize) -> bool
{
//For the current column
for c in 0..9
{
//Ignore the piece we are validating
if y != c
{
if puzzle[y][x] == puzzle[c][x]
{
return false
}
}
}
//For the current row
for r in 0..9
{
//Ignore the piece we are validating
if x != r
{
if puzzle[y][x] == puzzle[y][r]
{
return false
}
}
}
//For the current block
let b_y: usize = (y / 3) + 1;
let b_x: usize = (x / 3) + 1;
for c_y in ((b_y - 1) * 3)..((b_y * 3) - 1)
{
for c_x in ((b_x - 1) * 3)..((b_x * 3) - 1)
{
//Ignore the piece we are validating
if c_y != y && c_x != x
{
if puzzle[y][x] == puzzle[c_y][c_x]
{
return false
}
}
}
}
true
} |
pub mod core;
pub use crate::core::*;
pub mod debug;
pub mod disassembly;
|
use crate::{error::Error, resource::Resource};
use log::error;
use std::io::{self, Read, Write};
use std::net::{Shutdown, TcpStream};
use url::Url;
pub struct Http {
stream: TcpStream,
}
impl Resource for Http {
fn new(u: Url) -> Result<Http, Error> {
if let None = u.host() {
return Err(Error::InvalidArgument);
}
let host = u.host().unwrap();
let port: u16 = match u.port() {
Some(port_num) => port_num,
None => 80,
};
TcpStream::connect((host.to_string().as_str(), port))
.or_else(|why| {
error!(
"connection error to {}:{}: {:?}",
u.host().unwrap(),
port,
why
);
Err(Error::Unknown)
})
.and_then(|conn| Ok(Http { stream: conn }))
}
fn close(&mut self) {
if let Err(why) = self.stream.shutdown(Shutdown::Both) {
error!("error closing TCP stream: {:?}", why);
}
drop(&self.stream);
}
}
impl Read for Http {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.stream.read(buf)
}
}
impl Write for Http {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.stream.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.stream.shutdown(Shutdown::Write)
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
pub const FONTS_CMX: &str = "fuchsia-pkg://fuchsia.com/fonts#meta/fonts.cmx";
mod experimental_api;
mod old_api;
mod reviewed_api;
|
use std::{borrow::Cow, pin::Pin};
use futures_util::stream::{Stream, StreamExt};
use crate::{
parser::types::Selection, registry, registry::Registry, Context, ContextSelectionSet,
PathSegment, Response, ServerError, ServerResult,
};
/// A GraphQL subscription object
pub trait SubscriptionType: Send + Sync {
/// Type the name.
fn type_name() -> Cow<'static, str>;
/// Qualified typename.
fn qualified_type_name() -> String {
format!("{}!", Self::type_name())
}
/// Create type information in the registry and return qualified typename.
fn create_type_info(registry: &mut registry::Registry) -> String;
/// This function returns true of type `EmptySubscription` only.
#[doc(hidden)]
fn is_empty() -> bool {
false
}
#[doc(hidden)]
fn create_field_stream<'a>(
&'a self,
ctx: &'a Context<'_>,
) -> Option<Pin<Box<dyn Stream<Item = Response> + Send + 'a>>>;
}
pub(crate) type BoxFieldStream<'a> = Pin<Box<dyn Stream<Item = Response> + 'a + Send>>;
pub(crate) fn collect_subscription_streams<'a, T: SubscriptionType + 'static>(
ctx: &ContextSelectionSet<'a>,
root: &'a T,
streams: &mut Vec<BoxFieldStream<'a>>,
) -> ServerResult<()> {
for selection in &ctx.item.node.items {
if let Selection::Field(field) = &selection.node {
streams.push(Box::pin({
let ctx = ctx.clone();
async_stream::stream! {
let ctx = ctx.with_field(field);
let field_name = ctx.item.node.response_key().node.clone();
let stream = root.create_field_stream(&ctx);
if let Some(mut stream) = stream {
while let Some(resp) = stream.next().await {
yield resp;
}
} else {
let err = ServerError::new(format!(r#"Cannot query field "{}" on type "{}"."#, field_name, T::type_name()), Some(ctx.item.pos))
.with_path(vec![PathSegment::Field(field_name.to_string())]);
yield Response::from_errors(vec![err]);
}
}
}))
}
}
Ok(())
}
impl<T: SubscriptionType> SubscriptionType for &T {
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn create_type_info(registry: &mut Registry) -> String {
T::create_type_info(registry)
}
fn create_field_stream<'a>(
&'a self,
ctx: &'a Context<'_>,
) -> Option<Pin<Box<dyn Stream<Item = Response> + Send + 'a>>> {
T::create_field_stream(*self, ctx)
}
}
|
pub mod handler;
pub mod model;
use crate::batch::model::{AutoCancel, ComeFind};
use crate::models::{AppStateWithTxt, DbExecutor};
use actix::prelude::*;
use futures::Future;
use std::time::Duration;
use crate::errors::ServiceError;
use crate::fcm::model::*;
use crate::fcm::router::to_user;
use crate::utils::client::SSLClinet;
use actix_web::{web::Data, Error};
pub struct Batch {
pub db: Data<Addr<DbExecutor>>,
pub store: Data<AppStateWithTxt>,
}
impl Batch {
pub fn new(db: Data<Addr<DbExecutor>>, store: Data<AppStateWithTxt>) -> Batch {
Batch { db, store }
}
fn come_find(&self, ctx: &mut actix::Context<Self>) {
ctx.run_interval(Duration::new(3, 0), move |act, _ctx| {
let result = index4(act.db.clone(), act.store.clone());
// spawn future to reactor
Arbiter::spawn(
result
.map(|_res| {
//println!("Got result: {}", res);
})
.map_err(|e| {
println!("batch: auto_cancel : {}", e);
}),
);
});
}
fn auto_cancel(&self, ctx: &mut actix::Context<Self>) {
ctx.run_interval(Duration::new(3, 0), move |act, _ctx| {
let result = index3(act.db.clone(), act.store.clone());
// spawn future to reactor
Arbiter::spawn(
result
.map(|_res| {
//println!("Got result: {}", res);
})
.map_err(|e| {
println!("batch: auto_cancel : {}", e);
}),
);
});
}
}
impl Actor for Batch {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
println!("I am alive!");
self.auto_cancel(ctx);
self.come_find(ctx);
}
}
fn index4(
db: Data<Addr<DbExecutor>>,
store: Data<AppStateWithTxt>,
) -> Box<dyn Future<Item = &'static str, Error = Error>> {
use futures::future::ok;
let sd = ComeFind {
db: db.clone(),
store: store.clone(),
};
let db2 = db.clone();
let store2 = store.clone();
Box::new({
db.send(sd).from_err().and_then(move |res| match res {
Ok(list) => {
for res in &list {
let db_addr = db2.clone();
let store3 = store2.clone();
let to = res.to.clone();
let title = format!("[{}] 수령하세요.", res.shop_name);
let body = res.content.to_string();
let send_data = ReqToUser {
comm: ReqToComm::new_comefind(
res.order_id.clone(),
res.order_detail_id.clone(),
res.shop_notification_id.clone(),
),
params: ReqToUserData::new(to, title, body),
};
let result = to_user(send_data, db_addr, store3);
Arbiter::spawn(
result
.map(|_res| {
// println!("Actor is map");
})
.map_err(|e| {
println!("Actor is probably dead: {}", e);
}),
);
}
ok::<_, Error>("Welcome!2 Welcome")
}
Err(e) => {
println!(" index4--: errr {:?}", e);
ok::<_, Error>("Welcome!2 ERRR")
}
})
})
}
fn index3(
db: Data<Addr<DbExecutor>>,
store: Data<AppStateWithTxt>,
) -> Box<dyn Future<Item = &'static str, Error = Error>> {
use futures::future::ok;
let websocket_url = store.websocket.send.clone();
let sd = AutoCancel {
db: db.clone(),
store: store.clone(),
};
let db2 = db.clone();
let store2 = store.clone();
Box::new({
db.send(sd).from_err().and_then(move |res| match res {
Ok(list) => {
for res in &list {
let db_addr = db2.clone();
let store3 = store2.clone();
let shop_id = res.shop_id.clone();
let to = res.notification_key.clone();
let title = format!("[자동] 주문후 5분 미응답");
let body = format!("주문 자동취소됨.!");
let send_data = ReqToUser {
comm: ReqToComm::new_auto_cancle(res.id.clone()),
params: ReqToUserData::new(to, title, body),
};
let websocket_url2 = websocket_url.clone();
let o_id = res.id.clone();
let user_to = res.sw_token.clone();
let user_title = format!("주문이 취소됬습니다.");
let user_body = format!("가게가 미응답하여 자동 취소됬습니다.");
let u_d=
ReqToUser {
comm: ReqToComm::new_order(o_id.clone()),
params: ReqToUserData::new(user_to.clone(), user_title.clone(), user_body.clone()),
};
let send_user =to_user(u_d, db_addr.clone(), store2.clone());
let result = to_user(send_data, db_addr, store3).and_then(|_|{
send_user
})
.and_then(move |res| {
let url = format!("{}{}/test", websocket_url2, shop_id);
SSLClinet::build()
.get(url)
.send()
.map_err(|e| {
println!("SSLClinet::build(): {}", e);
ServiceError::BadRequest(e.to_string())
})
.and_then(|_response| res)
.from_err()
});
Arbiter::spawn(
result
.map(|_res| {
// println!("Actor is map");
})
.map_err(|e| {
println!("Actor is probably dead: {}", e);
}),
);
}
ok::<_, Error>("Welcome!2 Welcome")
}
Err(e) => {
println!(" index3--: errr {:?}", e);
ok::<_, Error>("Welcome!2 ERRR")
}
})
})
}
|
pub struct Point {
pub x: i32,
pub y: i32,
}
impl Clone for Point {
fn clone(&self) -> Self {
Point {
x: self.x,
y: self.y,
}
}
}
impl Eq for Point {}
impl PartialEq for Point {
fn eq(&self, other: &Point) -> bool {
self.x == other.x && self.y == other.y
}
}
impl Point {
pub fn new(x: i32, y: i32) -> Point {
Point { x: x, y: y }
}
}
pub const LEFT: Point = Point { x: -1, y: 0 };
pub const RIGHT: Point = Point { x: 1, y: 0 };
pub const UP: Point = Point { x: 0, y: -1 };
pub const DOWN: Point = Point { x: 0, y: 1 };
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct CellularClass(pub i32);
impl CellularClass {
pub const None: Self = Self(0i32);
pub const Gsm: Self = Self(1i32);
pub const Cdma: Self = Self(2i32);
}
impl ::core::marker::Copy for CellularClass {}
impl ::core::clone::Clone for CellularClass {
fn clone(&self) -> Self {
*self
}
}
pub type DeleteSmsMessageOperation = *mut ::core::ffi::c_void;
pub type DeleteSmsMessagesOperation = *mut ::core::ffi::c_void;
pub type GetSmsDeviceOperation = *mut ::core::ffi::c_void;
pub type GetSmsMessageOperation = *mut ::core::ffi::c_void;
pub type GetSmsMessagesOperation = *mut ::core::ffi::c_void;
pub type ISmsBinaryMessage = *mut ::core::ffi::c_void;
pub type ISmsDevice = *mut ::core::ffi::c_void;
pub type ISmsMessage = *mut ::core::ffi::c_void;
pub type ISmsMessageBase = *mut ::core::ffi::c_void;
pub type ISmsTextMessage = *mut ::core::ffi::c_void;
pub type SendSmsMessageOperation = *mut ::core::ffi::c_void;
pub type SmsAppMessage = *mut ::core::ffi::c_void;
pub type SmsBinaryMessage = *mut ::core::ffi::c_void;
pub type SmsBroadcastMessage = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmsBroadcastType(pub i32);
impl SmsBroadcastType {
pub const Other: Self = Self(0i32);
pub const CmasPresidential: Self = Self(1i32);
pub const CmasExtreme: Self = Self(2i32);
pub const CmasSevere: Self = Self(3i32);
pub const CmasAmber: Self = Self(4i32);
pub const CmasTest: Self = Self(5i32);
pub const EUAlert1: Self = Self(6i32);
pub const EUAlert2: Self = Self(7i32);
pub const EUAlert3: Self = Self(8i32);
pub const EUAlertAmber: Self = Self(9i32);
pub const EUAlertInfo: Self = Self(10i32);
pub const EtwsEarthquake: Self = Self(11i32);
pub const EtwsTsunami: Self = Self(12i32);
pub const EtwsTsunamiAndEarthquake: Self = Self(13i32);
pub const LatAlertLocal: Self = Self(14i32);
}
impl ::core::marker::Copy for SmsBroadcastType {}
impl ::core::clone::Clone for SmsBroadcastType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmsDataFormat(pub i32);
impl SmsDataFormat {
pub const Unknown: Self = Self(0i32);
pub const CdmaSubmit: Self = Self(1i32);
pub const GsmSubmit: Self = Self(2i32);
pub const CdmaDeliver: Self = Self(3i32);
pub const GsmDeliver: Self = Self(4i32);
}
impl ::core::marker::Copy for SmsDataFormat {}
impl ::core::clone::Clone for SmsDataFormat {
fn clone(&self) -> Self {
*self
}
}
pub type SmsDevice = *mut ::core::ffi::c_void;
pub type SmsDevice2 = *mut ::core::ffi::c_void;
pub type SmsDeviceMessageStore = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmsDeviceStatus(pub i32);
impl SmsDeviceStatus {
pub const Off: Self = Self(0i32);
pub const Ready: Self = Self(1i32);
pub const SimNotInserted: Self = Self(2i32);
pub const BadSim: Self = Self(3i32);
pub const DeviceFailure: Self = Self(4i32);
pub const SubscriptionNotActivated: Self = Self(5i32);
pub const DeviceLocked: Self = Self(6i32);
pub const DeviceBlocked: Self = Self(7i32);
}
impl ::core::marker::Copy for SmsDeviceStatus {}
impl ::core::clone::Clone for SmsDeviceStatus {
fn clone(&self) -> Self {
*self
}
}
pub type SmsDeviceStatusChangedEventHandler = *mut ::core::ffi::c_void;
#[repr(C)]
pub struct SmsEncodedLength {
pub SegmentCount: u32,
pub CharacterCountLastSegment: u32,
pub CharactersPerSegment: u32,
pub ByteCountLastSegment: u32,
pub BytesPerSegment: u32,
}
impl ::core::marker::Copy for SmsEncodedLength {}
impl ::core::clone::Clone for SmsEncodedLength {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmsEncoding(pub i32);
impl SmsEncoding {
pub const Unknown: Self = Self(0i32);
pub const Optimal: Self = Self(1i32);
pub const SevenBitAscii: Self = Self(2i32);
pub const Unicode: Self = Self(3i32);
pub const GsmSevenBit: Self = Self(4i32);
pub const EightBit: Self = Self(5i32);
pub const Latin: Self = Self(6i32);
pub const Korean: Self = Self(7i32);
pub const IA5: Self = Self(8i32);
pub const ShiftJis: Self = Self(9i32);
pub const LatinHebrew: Self = Self(10i32);
}
impl ::core::marker::Copy for SmsEncoding {}
impl ::core::clone::Clone for SmsEncoding {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmsFilterActionType(pub i32);
impl SmsFilterActionType {
pub const AcceptImmediately: Self = Self(0i32);
pub const Drop: Self = Self(1i32);
pub const Peek: Self = Self(2i32);
pub const Accept: Self = Self(3i32);
}
impl ::core::marker::Copy for SmsFilterActionType {}
impl ::core::clone::Clone for SmsFilterActionType {
fn clone(&self) -> Self {
*self
}
}
pub type SmsFilterRule = *mut ::core::ffi::c_void;
pub type SmsFilterRules = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmsGeographicalScope(pub i32);
impl SmsGeographicalScope {
pub const None: Self = Self(0i32);
pub const CellWithImmediateDisplay: Self = Self(1i32);
pub const LocationArea: Self = Self(2i32);
pub const Plmn: Self = Self(3i32);
pub const Cell: Self = Self(4i32);
}
impl ::core::marker::Copy for SmsGeographicalScope {}
impl ::core::clone::Clone for SmsGeographicalScope {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmsMessageClass(pub i32);
impl SmsMessageClass {
pub const None: Self = Self(0i32);
pub const Class0: Self = Self(1i32);
pub const Class1: Self = Self(2i32);
pub const Class2: Self = Self(3i32);
pub const Class3: Self = Self(4i32);
}
impl ::core::marker::Copy for SmsMessageClass {}
impl ::core::clone::Clone for SmsMessageClass {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmsMessageFilter(pub i32);
impl SmsMessageFilter {
pub const All: Self = Self(0i32);
pub const Unread: Self = Self(1i32);
pub const Read: Self = Self(2i32);
pub const Sent: Self = Self(3i32);
pub const Draft: Self = Self(4i32);
}
impl ::core::marker::Copy for SmsMessageFilter {}
impl ::core::clone::Clone for SmsMessageFilter {
fn clone(&self) -> Self {
*self
}
}
pub type SmsMessageReceivedEventArgs = *mut ::core::ffi::c_void;
pub type SmsMessageReceivedEventHandler = *mut ::core::ffi::c_void;
pub type SmsMessageReceivedTriggerDetails = *mut ::core::ffi::c_void;
pub type SmsMessageRegistration = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmsMessageType(pub i32);
impl SmsMessageType {
pub const Binary: Self = Self(0i32);
pub const Text: Self = Self(1i32);
pub const Wap: Self = Self(2i32);
pub const App: Self = Self(3i32);
pub const Broadcast: Self = Self(4i32);
pub const Voicemail: Self = Self(5i32);
pub const Status: Self = Self(6i32);
}
impl ::core::marker::Copy for SmsMessageType {}
impl ::core::clone::Clone for SmsMessageType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmsModemErrorCode(pub i32);
impl SmsModemErrorCode {
pub const Other: Self = Self(0i32);
pub const MessagingNetworkError: Self = Self(1i32);
pub const SmsOperationNotSupportedByDevice: Self = Self(2i32);
pub const SmsServiceNotSupportedByNetwork: Self = Self(3i32);
pub const DeviceFailure: Self = Self(4i32);
pub const MessageNotEncodedProperly: Self = Self(5i32);
pub const MessageTooLarge: Self = Self(6i32);
pub const DeviceNotReady: Self = Self(7i32);
pub const NetworkNotReady: Self = Self(8i32);
pub const InvalidSmscAddress: Self = Self(9i32);
pub const NetworkFailure: Self = Self(10i32);
pub const FixedDialingNumberRestricted: Self = Self(11i32);
}
impl ::core::marker::Copy for SmsModemErrorCode {}
impl ::core::clone::Clone for SmsModemErrorCode {
fn clone(&self) -> Self {
*self
}
}
pub type SmsReceivedEventDetails = *mut ::core::ffi::c_void;
pub type SmsSendMessageResult = *mut ::core::ffi::c_void;
pub type SmsStatusMessage = *mut ::core::ffi::c_void;
pub type SmsTextMessage = *mut ::core::ffi::c_void;
pub type SmsTextMessage2 = *mut ::core::ffi::c_void;
pub type SmsVoicemailMessage = *mut ::core::ffi::c_void;
pub type SmsWapMessage = *mut ::core::ffi::c_void;
|
use std::os::unix::net::UnixStream;
use std::io::{BufWriter, Write};
fn main() {
let mut stream = UnixStream::connect("/home/majortom/tmp/can.sock").unwrap();
let mut bf = BufWriter::new(&stream);
let mut n = 0;
while n < 200 {
n+=1;
let mut s = String::new();
s.push_str(format!("number: {}\n", n).as_str());
bf.write_all(s.as_bytes());
bf.flush();
}
drop(bf);
} |
use std::ops::Range;
#[derive(Debug, Copy, Clone)]
enum CardinalDirection {
North,
West,
South,
East
}
impl CardinalDirection {
fn turn(self, td: TurnDirection) -> CardinalDirection {
match td {
TurnDirection::Right => {
match self {
CardinalDirection::North => CardinalDirection::East,
CardinalDirection::West => CardinalDirection::North,
CardinalDirection::South => CardinalDirection::West,
CardinalDirection::East => CardinalDirection::South,
}
},
TurnDirection::Left => {
match self {
CardinalDirection::North => CardinalDirection::West,
CardinalDirection::West => CardinalDirection::South,
CardinalDirection::South => CardinalDirection::East,
CardinalDirection::East => CardinalDirection::North,
}
}
}
}
}
#[derive(Debug)]
enum TurnDirection {
Right,
Left
}
#[derive(Debug)]
struct Position {
x: i32,
y: i32,
direction: CardinalDirection
}
impl Position {
fn grid_distance(&self, other: &Position) -> i32 {
(other.x - self.x).abs() + (other.y - self.y).abs()
}
fn go(self, units: i32) -> Position {
match self.direction {
CardinalDirection::North => Position { x: self.x, y: self.y + units, direction: self.direction },
CardinalDirection::West => Position { x: self.x - units, y: self.y, direction: self.direction },
CardinalDirection::South => Position { x: self.x, y: self.y - units, direction: self.direction },
CardinalDirection::East => Position { x: self.x + units, y: self.y, direction: self.direction },
}
}
fn path(&self, units: i32) -> Vec<Position> {
let mut positions : Vec<Position> = vec![];
for i in (Range { start: 1, end: units + 1 }) {
positions.push(
match self.direction {
CardinalDirection::North => Position { x: self.x, y: self.y + i, direction: self.direction },
CardinalDirection::West => Position { x: self.x - i, y: self.y, direction: self.direction },
CardinalDirection::South => Position { x: self.x, y: self.y - i, direction: self.direction },
CardinalDirection::East => Position { x: self.x + i, y: self.y, direction: self.direction },
}
)
}
positions
}
fn turn(self, td: TurnDirection) -> Position {
Position { x: self.x, y: self.y, direction: self.direction.turn(td)}
}
fn is_same_point(&self, other: &Position) -> bool {
self.x == other.x && self.y == other.y
}
}
pub fn puzzle1() -> i32 {
let data = "L5, R1, L5, L1, R5, R1, R1, L4, L1, L3, R2, R4, L4, L1, L1, R2, R4, R3, L1, R4, L4, L5, L4, R4, L5, R1, R5, L2, R1, R3, L2, L4, L4, R1, L192, R5, R1, R4, L5, L4, R5, L1, L1, R48, R5, R5, L2, R4, R4, R1, R3, L1, L4, L5, R1, L4, L2, L5, R5, L2, R74, R4, L1, R188, R5, L4, L2, R5, R2, L4, R4, R3, R3, R2, R1, L3, L2, L5, L5, L2, L1, R1, R5, R4, L3, R5, L1, L3, R4, L1, L3, L2, R1, R3, R2, R5, L3, L1, L1, R5, L4, L5, R5, R2, L5, R2, L1, L5, L3, L5, L5, L1, R1, L4, L3, L1, R2, R5, L1, L3, R4, R5, L4, L1, R5, L1, R5, R5, R5, R2, R1, R2, L5, L5, L5, R4, L5, L4, L4, R5, L2, R1, R5, L1, L5, R4, L3, R4, L2, R3, R3, R3, L2, L2, L2, L1, L4, R3, L4, L2, R2, R5, L1, R2";
let mut pos = Position { x: 0, y: 0, direction: CardinalDirection:: North };
for instruction in data.split(", ") {
let td = match &instruction[..1] {
"L" => TurnDirection::Left,
"R" => TurnDirection::Right,
_ => panic!("Instruction started with something other than L or R"),
};
let units: i32 = instruction[1..].parse().unwrap();
pos = pos.turn(td).go(units);
}
(Position { x: 0, y: 0, direction: CardinalDirection:: North }).grid_distance(&pos)
}
pub fn puzzle2() -> i32 {
let data = "L5, R1, L5, L1, R5, R1, R1, L4, L1, L3, R2, R4, L4, L1, L1, R2, R4, R3, L1, R4, L4, L5, L4, R4, L5, R1, R5, L2, R1, R3, L2, L4, L4, R1, L192, R5, R1, R4, L5, L4, R5, L1, L1, R48, R5, R5, L2, R4, R4, R1, R3, L1, L4, L5, R1, L4, L2, L5, R5, L2, R74, R4, L1, R188, R5, L4, L2, R5, R2, L4, R4, R3, R3, R2, R1, L3, L2, L5, L5, L2, L1, R1, R5, R4, L3, R5, L1, L3, R4, L1, L3, L2, R1, R3, R2, R5, L3, L1, L1, R5, L4, L5, R5, R2, L5, R2, L1, L5, L3, L5, L5, L1, R1, L4, L3, L1, R2, R5, L1, L3, R4, R5, L4, L1, R5, L1, R5, R5, R5, R2, R1, R2, L5, L5, L5, R4, L5, L4, L4, R5, L2, R1, R5, L1, L5, R4, L3, R4, L2, R3, R3, R3, L2, L2, L2, L1, L4, R3, L4, L2, R2, R5, L1, R2";
let mut pos = Position { x: 0, y: 0, direction: CardinalDirection:: North };
let mut positions : Vec<Position> = vec![];
for instruction in data.split(", ") {
let td = match &instruction[..1] {
"L" => TurnDirection::Left,
"R" => TurnDirection::Right,
_ => panic!("Instruction started with something other than L or R"),
};
let units: i32 = instruction[1..].parse().unwrap();
pos = pos.turn(td);
positions.extend(pos.path(units));
pos = pos.go(units);
}
// now find the first repeated x/y position in the list.
for (i, i_position) in positions.iter().enumerate() {
for (_, j_position) in positions.iter().take(i).enumerate() {
if i_position.is_same_point(j_position) {
return (Position { x: 0, y: 0, direction: CardinalDirection:: North }).grid_distance(&i_position);
}
}
}
panic!("Could not find any locations that were visited twice.");
}
|
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Writer for register CSR"]
pub type W = crate::W<u32, super::CSR>;
#[doc = "Register CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SOF0`"]
pub type SOF0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF0`"]
pub struct SOF0_W<'a> {
w: &'a mut W,
}
impl<'a> SOF0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `SOF1`"]
pub type SOF1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF1`"]
pub struct SOF1_W<'a> {
w: &'a mut W,
}
impl<'a> SOF1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `SOF2`"]
pub type SOF2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF2`"]
pub struct SOF2_W<'a> {
w: &'a mut W,
}
impl<'a> SOF2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `SOF3`"]
pub type SOF3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF3`"]
pub struct SOF3_W<'a> {
w: &'a mut W,
}
impl<'a> SOF3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `SOF4`"]
pub type SOF4_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF4`"]
pub struct SOF4_W<'a> {
w: &'a mut W,
}
impl<'a> SOF4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `SOF5`"]
pub type SOF5_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF5`"]
pub struct SOF5_W<'a> {
w: &'a mut W,
}
impl<'a> SOF5_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `SOF6`"]
pub type SOF6_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF6`"]
pub struct SOF6_W<'a> {
w: &'a mut W,
}
impl<'a> SOF6_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `SOF7`"]
pub type SOF7_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF7`"]
pub struct SOF7_W<'a> {
w: &'a mut W,
}
impl<'a> SOF7_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `SOF8`"]
pub type SOF8_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF8`"]
pub struct SOF8_W<'a> {
w: &'a mut W,
}
impl<'a> SOF8_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `SOF9`"]
pub type SOF9_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF9`"]
pub struct SOF9_W<'a> {
w: &'a mut W,
}
impl<'a> SOF9_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `SOF10`"]
pub type SOF10_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF10`"]
pub struct SOF10_W<'a> {
w: &'a mut W,
}
impl<'a> SOF10_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `SOF11`"]
pub type SOF11_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF11`"]
pub struct SOF11_W<'a> {
w: &'a mut W,
}
impl<'a> SOF11_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `SOF12`"]
pub type SOF12_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF12`"]
pub struct SOF12_W<'a> {
w: &'a mut W,
}
impl<'a> SOF12_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `SOF13`"]
pub type SOF13_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF13`"]
pub struct SOF13_W<'a> {
w: &'a mut W,
}
impl<'a> SOF13_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `SOF14`"]
pub type SOF14_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF14`"]
pub struct SOF14_W<'a> {
w: &'a mut W,
}
impl<'a> SOF14_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `SOF15`"]
pub type SOF15_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOF15`"]
pub struct SOF15_W<'a> {
w: &'a mut W,
}
impl<'a> SOF15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
impl R {
#[doc = "Bit 0 - Synchronization Overrun Flag 0"]
#[inline(always)]
pub fn sof0(&self) -> SOF0_R {
SOF0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Synchronization Overrun Flag 1"]
#[inline(always)]
pub fn sof1(&self) -> SOF1_R {
SOF1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Synchronization Overrun Flag 2"]
#[inline(always)]
pub fn sof2(&self) -> SOF2_R {
SOF2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Synchronization Overrun Flag 3"]
#[inline(always)]
pub fn sof3(&self) -> SOF3_R {
SOF3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Synchronization Overrun Flag 4"]
#[inline(always)]
pub fn sof4(&self) -> SOF4_R {
SOF4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Synchronization Overrun Flag 5"]
#[inline(always)]
pub fn sof5(&self) -> SOF5_R {
SOF5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Synchronization Overrun Flag 6"]
#[inline(always)]
pub fn sof6(&self) -> SOF6_R {
SOF6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Synchronization Overrun Flag 7"]
#[inline(always)]
pub fn sof7(&self) -> SOF7_R {
SOF7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Synchronization Overrun Flag 8"]
#[inline(always)]
pub fn sof8(&self) -> SOF8_R {
SOF8_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Synchronization Overrun Flag 9"]
#[inline(always)]
pub fn sof9(&self) -> SOF9_R {
SOF9_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - Synchronization Overrun Flag 10"]
#[inline(always)]
pub fn sof10(&self) -> SOF10_R {
SOF10_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - Synchronization Overrun Flag 11"]
#[inline(always)]
pub fn sof11(&self) -> SOF11_R {
SOF11_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - Synchronization Overrun Flag 12"]
#[inline(always)]
pub fn sof12(&self) -> SOF12_R {
SOF12_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Synchronization Overrun Flag 13"]
#[inline(always)]
pub fn sof13(&self) -> SOF13_R {
SOF13_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - Synchronization Overrun Flag 13"]
#[inline(always)]
pub fn sof14(&self) -> SOF14_R {
SOF14_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - Synchronization Overrun Flag 13"]
#[inline(always)]
pub fn sof15(&self) -> SOF15_R {
SOF15_R::new(((self.bits >> 15) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Synchronization Overrun Flag 0"]
#[inline(always)]
pub fn sof0(&mut self) -> SOF0_W {
SOF0_W { w: self }
}
#[doc = "Bit 1 - Synchronization Overrun Flag 1"]
#[inline(always)]
pub fn sof1(&mut self) -> SOF1_W {
SOF1_W { w: self }
}
#[doc = "Bit 2 - Synchronization Overrun Flag 2"]
#[inline(always)]
pub fn sof2(&mut self) -> SOF2_W {
SOF2_W { w: self }
}
#[doc = "Bit 3 - Synchronization Overrun Flag 3"]
#[inline(always)]
pub fn sof3(&mut self) -> SOF3_W {
SOF3_W { w: self }
}
#[doc = "Bit 4 - Synchronization Overrun Flag 4"]
#[inline(always)]
pub fn sof4(&mut self) -> SOF4_W {
SOF4_W { w: self }
}
#[doc = "Bit 5 - Synchronization Overrun Flag 5"]
#[inline(always)]
pub fn sof5(&mut self) -> SOF5_W {
SOF5_W { w: self }
}
#[doc = "Bit 6 - Synchronization Overrun Flag 6"]
#[inline(always)]
pub fn sof6(&mut self) -> SOF6_W {
SOF6_W { w: self }
}
#[doc = "Bit 7 - Synchronization Overrun Flag 7"]
#[inline(always)]
pub fn sof7(&mut self) -> SOF7_W {
SOF7_W { w: self }
}
#[doc = "Bit 8 - Synchronization Overrun Flag 8"]
#[inline(always)]
pub fn sof8(&mut self) -> SOF8_W {
SOF8_W { w: self }
}
#[doc = "Bit 9 - Synchronization Overrun Flag 9"]
#[inline(always)]
pub fn sof9(&mut self) -> SOF9_W {
SOF9_W { w: self }
}
#[doc = "Bit 10 - Synchronization Overrun Flag 10"]
#[inline(always)]
pub fn sof10(&mut self) -> SOF10_W {
SOF10_W { w: self }
}
#[doc = "Bit 11 - Synchronization Overrun Flag 11"]
#[inline(always)]
pub fn sof11(&mut self) -> SOF11_W {
SOF11_W { w: self }
}
#[doc = "Bit 12 - Synchronization Overrun Flag 12"]
#[inline(always)]
pub fn sof12(&mut self) -> SOF12_W {
SOF12_W { w: self }
}
#[doc = "Bit 13 - Synchronization Overrun Flag 13"]
#[inline(always)]
pub fn sof13(&mut self) -> SOF13_W {
SOF13_W { w: self }
}
#[doc = "Bit 14 - Synchronization Overrun Flag 13"]
#[inline(always)]
pub fn sof14(&mut self) -> SOF14_W {
SOF14_W { w: self }
}
#[doc = "Bit 15 - Synchronization Overrun Flag 13"]
#[inline(always)]
pub fn sof15(&mut self) -> SOF15_W {
SOF15_W { w: self }
}
}
|
use binary_search_range::BinarySearchRange;
use proconio::input;
fn main() {
input! {
n: usize,
a: [usize; n],
q: usize,
lrx: [(usize, usize, usize); q],
};
let mut positions = vec![vec![]; n];
for i in 0..n {
positions[a[i] - 1].push(i);
}
for i in 0..n {
positions[i].sort();
}
for (l, r, x) in lrx {
let rng = positions[x - 1].range((l - 1)..r);
println!("{}", rng.count());
}
}
|
use std::sync::{Arc, mpsc, Mutex, RwLock};
use crate::event::Event;
use crate::event::core::ShutdownEvent;
use crate::event::scene::SnapshotEvent;
use crate::scene::SceneStack;
pub fn scene_manager_event_thread(
snapshot_queue: Arc<Mutex<Vec<SnapshotEvent>>>,
scene_stack: Arc<RwLock<SceneStack>>,
events_receiver: mpsc::Receiver<Box<dyn Event>>,
outgoing_events_sender: mpsc::Sender<Box<dyn Event>>,
) {
loop {
let event = events_receiver.recv().unwrap();
if event.as_any().is::<SnapshotEvent>() {
//
} else if event.as_any().is::<ShutdownEvent>() {
break;
}
}
} |
// Inspired from https://github.com/jgallagher/rusqlite/blob/master/libsqlite3-sys/build.rs
fn main() {
build::build_and_link();
bindings::add_bindings();
}
#[cfg(feature = "vendored")]
mod build {
use std::path::PathBuf;
pub fn build_and_link() {
let basedir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("yara");
let mut cc = cc::Build::new();
cc
.include(basedir.join("libyara"))
.include(basedir.join("libyara/include"))
.file(basedir.join("libyara/ahocorasick.c"))
.file(basedir.join("libyara/arena.c"))
.file(basedir.join("libyara/atoms.c"))
.file(basedir.join("libyara/base64.c"))
.file(basedir.join("libyara/bitmask.c"))
.file(basedir.join("libyara/compiler.c"))
.file(basedir.join("libyara/endian.c"))
.file(basedir.join("libyara/exec.c"))
.file(basedir.join("libyara/exefiles.c"))
.file(basedir.join("libyara/filemap.c"))
.file(basedir.join("libyara/grammar.c"))
.file(basedir.join("libyara/hash.c"))
.file(basedir.join("libyara/hex_grammar.c"))
.file(basedir.join("libyara/hex_lexer.c"))
.file(basedir.join("libyara/lexer.c"))
.file(basedir.join("libyara/libyara.c"))
.file(basedir.join("libyara/mem.c"))
.file(basedir.join("libyara/notebook.c"))
.file(basedir.join("libyara/object.c"))
.file(basedir.join("libyara/parser.c"))
.file(basedir.join("libyara/proc.c"))
.file(basedir.join("libyara/re.c"))
.file(basedir.join("libyara/re_grammar.c"))
.file(basedir.join("libyara/re_lexer.c"))
.file(basedir.join("libyara/rules.c"))
.file(basedir.join("libyara/scan.c"))
.file(basedir.join("libyara/scanner.c"))
.file(basedir.join("libyara/sizedstr.c"))
.file(basedir.join("libyara/stack.c"))
.file(basedir.join("libyara/stopwatch.c"))
.file(basedir.join("libyara/stream.c"))
.file(basedir.join("libyara/strutils.c"))
.file(basedir.join("libyara/threading.c"))
.file(basedir.join("libyara/modules.c"))
.file(basedir.join("libyara/modules/elf/elf.c"))
.file(basedir.join("libyara/modules/math/math.c"))
.file(basedir.join("libyara/modules/pe/pe.c"))
.file(basedir.join("libyara/modules/pe/pe_utils.c"))
.file(basedir.join("libyara/modules/tests/tests.c"))
.file(basedir.join("libyara/modules/time/time.c"))
.define("DEX_MODULE", "")
.file(basedir.join("libyara/modules/dex/dex.c"))
.define("DOTNET_MODULE", "")
.file(basedir.join("libyara/modules/dotnet/dotnet.c"))
.define("MACHO_MODULE", "")
.file(basedir.join("libyara/modules/macho/macho.c"))
.define("NDEBUG", "1");
// Use correct proc functions
match std::env::var("CARGO_CFG_TARGET_OS").ok().unwrap().as_str() {
"windows"
=> cc.file(basedir.join("libyara/proc/windows.c"))
.define("USE_WINDOWS_PROC", ""),
"linux"
=> cc.file(basedir.join("libyara/proc/linux.c"))
.define("USE_LINUX_PROC", ""),
"macos"
=> cc.file(basedir.join("libyara/proc/mach.c"))
.define("USE_MACH_PROC", ""),
_
=> cc.file(basedir.join("libyara/proc/none.c"))
.define("USE_NO_PROC", ""),
};
if std::env::var("CARGO_CFG_TARGET_FAMILY").ok().unwrap().as_str() != "windows" {
cc.define("POSIX", "");
};
// Unfortunately, YARA compilation produces lots of warnings
cc.warnings(false);
cc.compile("yara");
let include_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("yara/libyara/include");
let lib_dir = std::env::var("OUT_DIR").unwrap();
println!("cargo:rustc-link-search=native={}", lib_dir);
println!("cargo:rustc-link-lib=static=yara");
println!("cargo:include={}", include_dir.display());
println!("cargo:lib={}", lib_dir);
// tell the add_bindings phase to generate bindings from `include_dir`.
std::env::set_var("YARA_INCLUDE_DIR", include_dir);
}
}
#[cfg(not(feature = "vendored"))]
mod build {
/// Tell cargo to tell rustc to link the system yara
/// shared library.
pub fn build_and_link() {
let kind = match std::env::var("LIBYARA_STATIC").ok().as_deref() {
Some("0") => "dylib",
Some(_) => "static",
None => "dylib",
};
println!("cargo:rustc-link-lib={}=yara", kind);
// Add the environment variable YARA_LIBRARY_PATH to the library search path.
if let Some(yara_library_path) = std::env::var("YARA_LIBRARY_PATH")
.ok()
.filter(|path| !path.is_empty())
{
println!("cargo:rustc-link-search=native={}", yara_library_path);
}
}
}
#[cfg(feature = "bundled-4_1_0")]
mod bindings {
use std::env;
use std::fs;
use std::path::PathBuf;
pub fn add_bindings() {
let binding_file = match env::var("CARGO_CFG_TARGET_FAMILY").unwrap().as_ref() {
"unix" => "yara-4.1.0-unix.rs",
"windows" => "yara-4.1.0-windows.rs",
f => panic!("no bundled bindings for family {}", f),
};
let out_dir = env::var("OUT_DIR")
.expect("$OUT_DIR should be defined");
let out_path = PathBuf::from(out_dir).join("bindings.rs");
fs::copy(PathBuf::from("bindings").join(binding_file), out_path)
.expect("Could not copy bindings to output directory");
}
}
#[cfg(not(feature = "bundled-4_1_0"))]
mod bindings {
extern crate bindgen;
use std::env;
use std::path::PathBuf;
pub fn add_bindings() {
let mut builder = bindgen::Builder::default()
.header("wrapper.h")
.allowlist_var("CALLBACK_.*")
.allowlist_var("ERROR_.*")
.allowlist_var("META_TYPE_.*")
.allowlist_var("META_FLAGS_LAST_IN_RULE")
.allowlist_var("STRING_FLAGS_LAST_IN_RULE")
.allowlist_var("YARA_ERROR_LEVEL_.*")
.allowlist_var("SCAN_FLAGS_.*")
.allowlist_function("yr_initialize")
.allowlist_function("yr_finalize")
.allowlist_function("yr_finalize_thread")
.allowlist_function("yr_compiler_.*")
.allowlist_function("yr_rule_.*")
.allowlist_function("yr_rules_.*")
.allowlist_function("yr_scanner_.*")
.allowlist_type("YR_ARENA")
.allowlist_type("YR_EXTERNAL_VARIABLE")
.allowlist_type("YR_MATCH")
.opaque_type("YR_COMPILER")
.opaque_type("YR_AC_MATCH_TABLE")
.opaque_type("YR_AC_TRANSITION_TABLE")
.opaque_type("_YR_EXTERNAL_VARIABLE");
if let Some(yara_include_dir) = env::var("YARA_INCLUDE_DIR")
.ok()
.filter(|dir| !dir.is_empty())
{
builder = builder.clang_arg(format!("-I{}", yara_include_dir))
}
let bindings = builder.generate().expect("Unable to generate bindings");
// Write the bindings to the $OUT_DIR/bindings.rs file.
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
}
|
// Copyright 2015 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.
// run-pass
// This should resolve fine.
// Prior to fix, the crossed imports between a and b
// would block on the glob import, itself never being resolved
// because these previous imports were not resolved.
pub mod a {
use b::fn_b;
use c::*;
pub fn fn_a(){
}
}
pub mod b {
use a::fn_a;
use c::*;
pub fn fn_b(){
}
}
pub mod c{
pub fn fn_c(){
}
}
use a::fn_a;
use b::fn_b;
fn main() {
}
|
use std::io;
use serde_json;
use websocket::result::WebSocketError;
use websocket::client::ParseError;
#[derive(Debug)]
pub enum MessageError {
WebSocket(WebSocketError),
Json(serde_json::Error),
}
impl From<WebSocketError> for MessageError {
fn from(e: WebSocketError) -> Self {
return MessageError::WebSocket(e);
}
}
impl From<serde_json::Error> for MessageError {
fn from(e: serde_json::Error) -> Self {
return MessageError::Json(e);
}
}
#[derive(Debug)]
pub enum ConnectError {
WebSocket(WebSocketError),
Parse(ParseError),
IO(io::Error),
}
impl From<WebSocketError> for ConnectError {
fn from(e: WebSocketError) -> Self {
return ConnectError::WebSocket(e);
}
}
impl From<ParseError> for ConnectError {
fn from(e: ParseError) -> Self {
return ConnectError::Parse(e);
}
}
impl From<io::Error> for ConnectError {
fn from(e: io::Error) -> Self {
return ConnectError::IO(e);
}
}
#[derive(Debug)]
pub enum JoinError {
WebSocket(WebSocketError),
Json(serde_json::Error),
}
impl From<serde_json::Error> for JoinError {
fn from(e: serde_json::Error) -> Self {
return JoinError::Json(e);
}
}
impl From<WebSocketError> for JoinError {
fn from(e: WebSocketError) -> Self {
return JoinError::WebSocket(e);
}
}
|
//! This module contains DataFusion utility functions and helpers
use std::{
cmp::{max, min},
convert::TryInto,
sync::Arc,
};
use arrow::{
array::TimestampNanosecondArray,
compute::SortOptions,
datatypes::{DataType, Schema as ArrowSchema},
record_batch::RecordBatch,
};
use data_types::TimestampMinMax;
use datafusion::{
self,
common::{tree_node::TreeNodeRewriter, DFSchema, ToDFSchema},
datasource::{provider_as_source, MemTable},
error::{DataFusionError, Result as DatafusionResult},
execution::context::ExecutionProps,
logical_expr::{BinaryExpr, ExprSchemable, LogicalPlan, LogicalPlanBuilder},
optimizer::simplify_expressions::{ExprSimplifier, SimplifyContext},
physical_expr::create_physical_expr,
physical_plan::{
expressions::{col as physical_col, PhysicalSortExpr},
ColumnStatistics, ExecutionPlan, PhysicalExpr, Statistics,
},
prelude::{binary_expr, lit, Column, Expr},
scalar::ScalarValue,
};
use itertools::Itertools;
use observability_deps::tracing::trace;
use predicate::rpc_predicate::{FIELD_COLUMN_NAME, MEASUREMENT_COLUMN_NAME};
use schema::{sort::SortKey, InfluxColumnType, Schema, TIME_COLUMN_NAME};
use snafu::{ensure, OptionExt, ResultExt, Snafu};
#[derive(Debug, Snafu)]
#[allow(missing_copy_implementations, missing_docs)]
pub enum Error {
#[snafu(display("The Record batch is empty"))]
EmptyBatch,
#[snafu(display("Error while searching Time column in a Record Batch"))]
TimeColumn { source: arrow::error::ArrowError },
#[snafu(display("Error while casting Timenanosecond on Time column"))]
TimeCasting,
#[snafu(display("Time column does not have value"))]
TimeValue,
#[snafu(display("Time column is null"))]
TimeNull,
}
/// A specialized `Error`
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Create a logical plan that produces the record batch
pub fn make_scan_plan(batch: RecordBatch) -> std::result::Result<LogicalPlan, DataFusionError> {
let schema = batch.schema();
let partitions = vec![vec![batch]];
let projection = None; // scan all columns
let table = MemTable::try_new(schema, partitions)?;
let source = provider_as_source(Arc::new(table));
LogicalPlanBuilder::scan("memtable", source, projection)?.build()
}
/// Returns the pk in arrow's expression used for data sorting
pub fn arrow_pk_sort_exprs(
key_columns: Vec<&str>,
input_schema: &ArrowSchema,
) -> Vec<PhysicalSortExpr> {
let mut sort_exprs = vec![];
for key in key_columns {
let expr = physical_col(key, input_schema).expect("pk in schema");
sort_exprs.push(PhysicalSortExpr {
expr,
options: SortOptions {
descending: false,
nulls_first: false,
},
});
}
sort_exprs
}
pub fn logical_sort_key_exprs(sort_key: &SortKey) -> Vec<Expr> {
sort_key
.iter()
.map(|(key, options)| {
let expr = Expr::Column(Column::from_name(key.as_ref()));
expr.sort(!options.descending, options.nulls_first)
})
.collect()
}
pub fn arrow_sort_key_exprs(
sort_key: &SortKey,
input_schema: &ArrowSchema,
) -> Vec<PhysicalSortExpr> {
sort_key
.iter()
.flat_map(|(key, options)| {
// Skip over missing columns
let expr = physical_col(key, input_schema).ok()?;
Some(PhysicalSortExpr {
expr,
options: SortOptions {
descending: options.descending,
nulls_first: options.nulls_first,
},
})
})
.collect()
}
/// Build a datafusion physical expression from a logical one
pub fn df_physical_expr(
input: &dyn ExecutionPlan,
expr: Expr,
) -> std::result::Result<Arc<dyn PhysicalExpr>, DataFusionError> {
let schema = input.schema();
let df_schema = Arc::clone(&schema).to_dfschema_ref()?;
let props = ExecutionProps::new();
let simplifier =
ExprSimplifier::new(SimplifyContext::new(&props).with_schema(Arc::clone(&df_schema)));
// apply type coercion here to ensure types match
trace!(%df_schema, "input schema");
let expr = simplifier.coerce(expr, Arc::clone(&df_schema))?;
trace!(%expr, "coerced logical expression");
create_physical_expr(&expr, df_schema.as_ref(), schema.as_ref(), &props)
}
/// Rewrites the provided expr such that references to any column that
/// are not present in `schema` become null.
///
/// So for example, if the predicate is
///
/// `(STATE = 'CA') OR (READING >0)`
///
/// but the schema only has `STATE` (and not `READING`), then the
/// predicate is rewritten to
///
/// `(STATE = 'CA') OR (NULL >0)`
///
/// This matches the Influx data model where any value that is not
/// explicitly specified is implicitly NULL. Since different chunks
/// and measurements can have different subsets of the columns, only
/// parts of the predicate make sense.
/// See comments on 'is_null_column'
#[derive(Debug)]
pub struct MissingColumnsToNull<'a> {
schema: &'a Schema,
df_schema: DFSchema,
}
impl<'a> MissingColumnsToNull<'a> {
pub fn new(schema: &'a Schema) -> Self {
let df_schema: DFSchema = schema
.as_arrow()
.as_ref()
.clone()
.try_into()
.expect("Create DF Schema");
Self { schema, df_schema }
}
/// Returns true if `expr` is a `Expr::Column` reference to a
/// column that doesn't exist in this schema
fn is_null_column(&self, expr: &Expr) -> bool {
if let Expr::Column(column) = &expr {
if column.name != MEASUREMENT_COLUMN_NAME && column.name != FIELD_COLUMN_NAME {
return self.schema.find_index_of(&column.name).is_none();
}
}
false
}
/// Rewrites an arg like col if col refers to a non existent
/// column into a null literal with "type" of `other_arg`, if possible
fn rewrite_op_arg(&self, arg: Expr, other_arg: &Expr) -> DatafusionResult<Expr> {
if self.is_null_column(&arg) {
let other_datatype = match other_arg.get_type(&self.df_schema) {
Ok(other_datatype) => other_datatype,
Err(_) => {
// the other arg is also unknown and will be
// rewritten, default to Int32 (sins due to
// https://github.com/apache/arrow-datafusion/issues/1179)
DataType::Int32
}
};
let scalar: ScalarValue = (&other_datatype).try_into()?;
Ok(Expr::Literal(scalar))
} else {
Ok(arg)
}
}
}
impl<'a> TreeNodeRewriter for MissingColumnsToNull<'a> {
type N = Expr;
fn mutate(&mut self, expr: Expr) -> DatafusionResult<Expr> {
// Ideally this would simply find all Expr::Columns and
// replace them with a constant NULL value. However, doing do
// is blocked on DF bug
// https://github.com/apache/arrow-datafusion/issues/1179
//
// Until then, we need to know what type of expr the column is
// being compared with, so workaround by finding the datatype of the other arg
match expr {
Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
let left = self.rewrite_op_arg(*left, &right)?;
let right = self.rewrite_op_arg(*right, &left)?;
Ok(binary_expr(left, op, right))
}
Expr::IsNull(expr) if self.is_null_column(&expr) => Ok(lit(true)),
Expr::IsNotNull(expr) if self.is_null_column(&expr) => Ok(lit(false)),
expr => Ok(expr),
}
}
}
/// Return min and max for column `time` of the given set of record batches
pub fn compute_timenanosecond_min_max<'a, I>(batches: I) -> Result<TimestampMinMax>
where
I: IntoIterator<Item = &'a RecordBatch>,
{
let mut min_time = i64::MAX;
let mut max_time = i64::MIN;
for batch in batches {
let (mi, ma) = compute_timenanosecond_min_max_for_one_record_batch(batch)?;
min_time = min(min_time, mi);
max_time = max(max_time, ma);
}
Ok(TimestampMinMax {
min: min_time,
max: max_time,
})
}
/// Return min and max for column `time` in the given record batch
pub fn compute_timenanosecond_min_max_for_one_record_batch(
batch: &RecordBatch,
) -> Result<(i64, i64)> {
ensure!(batch.num_columns() > 0, EmptyBatchSnafu);
let index = batch
.schema()
.index_of(TIME_COLUMN_NAME)
.context(TimeColumnSnafu {})?;
let time_col = batch
.column(index)
.as_any()
.downcast_ref::<TimestampNanosecondArray>()
.context(TimeCastingSnafu {})?;
let (min, max) = match time_col.iter().minmax() {
itertools::MinMaxResult::NoElements => return Err(Error::TimeValue),
itertools::MinMaxResult::OneElement(val) => {
let val = val.context(TimeNullSnafu)?;
(val, val)
}
itertools::MinMaxResult::MinMax(min, max) => {
(min.context(TimeNullSnafu)?, max.context(TimeNullSnafu)?)
}
};
Ok((min, max))
}
/// Create basic table summary.
///
/// This contains:
/// - correct column types
/// - [total count](Statistics::num_rows)
/// - [min](ColumnStatistics::min_value)/[max](ColumnStatistics::max_value) for the timestamp column
pub fn create_basic_summary(
row_count: u64,
schema: &Schema,
ts_min_max: Option<TimestampMinMax>,
) -> Statistics {
let mut columns = Vec::with_capacity(schema.len());
for (t, _field) in schema.iter() {
let stats = match t {
InfluxColumnType::Timestamp => ColumnStatistics {
null_count: Some(0),
max_value: Some(ScalarValue::TimestampNanosecond(
ts_min_max.map(|v| v.max),
None,
)),
min_value: Some(ScalarValue::TimestampNanosecond(
ts_min_max.map(|v| v.min),
None,
)),
distinct_count: None,
},
_ => ColumnStatistics::default(),
};
columns.push(stats)
}
Statistics {
num_rows: Some(row_count as usize),
total_byte_size: None,
column_statistics: Some(columns),
is_exact: true,
}
}
#[cfg(test)]
mod tests {
use arrow::datatypes::DataType;
use datafusion::{
common::tree_node::TreeNode,
prelude::{col, lit},
scalar::ScalarValue,
};
use schema::{builder::SchemaBuilder, InfluxFieldType};
use super::*;
#[test]
fn test_missing_colums_to_null() {
let schema = SchemaBuilder::new()
.tag("tag")
.field("str", DataType::Utf8)
.unwrap()
.field("int", DataType::Int64)
.unwrap()
.field("uint", DataType::UInt64)
.unwrap()
.field("float", DataType::Float64)
.unwrap()
.field("bool", DataType::Boolean)
.unwrap()
.build()
.unwrap();
// The fact that these need to be typed is due to
// https://github.com/apache/arrow-datafusion/issues/1179
let utf8_null = Expr::Literal(ScalarValue::Utf8(None));
let int32_null = Expr::Literal(ScalarValue::Int32(None));
// no rewrite
let expr = lit(1);
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// tag != str (no rewrite)
let expr = col("tag").not_eq(col("str"));
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// tag == str (no rewrite)
let expr = col("tag").eq(col("str"));
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// int < 5 (no rewrite, int part of schema)
let expr = col("int").lt(lit(5));
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// unknown < 5 --> NULL < 5 (unknown not in schema)
let expr = col("unknown").lt(lit(5));
let expected = int32_null.clone().lt(lit(5));
assert_rewrite(&schema, expr, expected);
// 5 < unknown --> 5 < NULL (unknown not in schema)
let expr = lit(5).lt(col("unknown"));
let expected = lit(5).lt(int32_null.clone());
assert_rewrite(&schema, expr, expected);
// _measurement < 5 --> _measurement < 5 (special column)
let expr = col("_measurement").lt(lit(5));
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// _field < 5 --> _field < 5 (special column)
let expr = col("_field").lt(lit(5));
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// _field < 5 OR col("unknown") < 5 --> _field < 5 OR (NULL < 5)
let expr = col("_field").lt(lit(5)).or(col("unknown").lt(lit(5)));
let expected = col("_field").lt(lit(5)).or(int32_null.clone().lt(lit(5)));
assert_rewrite(&schema, expr, expected);
// unknown < unknown2 --> NULL < NULL (both unknown columns)
let expr = col("unknown").lt(col("unknown2"));
let expected = int32_null.clone().lt(int32_null);
assert_rewrite(&schema, expr, expected);
// int < 5 OR unknown != "foo"
let expr = col("int").lt(lit(5)).or(col("unknown").not_eq(lit("foo")));
let expected = col("int").lt(lit(5)).or(utf8_null.not_eq(lit("foo")));
assert_rewrite(&schema, expr, expected);
// int IS NULL
let expr = col("int").is_null();
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// unknown IS NULL --> true
let expr = col("unknown").is_null();
let expected = lit(true);
assert_rewrite(&schema, expr, expected);
// int IS NOT NULL
let expr = col("int").is_not_null();
let expected = expr.clone();
assert_rewrite(&schema, expr, expected);
// unknown IS NOT NULL --> false
let expr = col("unknown").is_not_null();
let expected = lit(false);
assert_rewrite(&schema, expr, expected);
}
fn assert_rewrite(schema: &Schema, expr: Expr, expected: Expr) {
let mut rewriter = MissingColumnsToNull::new(schema);
let rewritten_expr = expr
.clone()
.rewrite(&mut rewriter)
.expect("Rewrite successful");
assert_eq!(
&rewritten_expr, &expected,
"Mismatch rewriting\nInput: {expr}\nRewritten: {rewritten_expr}\nExpected: {expected}"
);
}
#[test]
fn test_create_basic_summary_no_columns_no_rows() {
let schema = SchemaBuilder::new().build().unwrap();
let row_count = 0;
let actual = create_basic_summary(row_count, &schema, None);
let expected = Statistics {
num_rows: Some(row_count as usize),
total_byte_size: None,
column_statistics: Some(vec![]),
is_exact: true,
};
assert_eq!(actual, expected);
}
#[test]
fn test_create_basic_summary_no_rows() {
let schema = full_schema();
let row_count = 0;
let ts_min_max = TimestampMinMax { min: 10, max: 20 };
let actual = create_basic_summary(row_count, &schema, Some(ts_min_max));
let expected = Statistics {
num_rows: Some(0),
total_byte_size: None,
column_statistics: Some(vec![
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics {
null_count: Some(0),
min_value: Some(ScalarValue::TimestampNanosecond(Some(10), None)),
max_value: Some(ScalarValue::TimestampNanosecond(Some(20), None)),
distinct_count: None,
},
]),
is_exact: true,
};
assert_eq!(actual, expected);
}
#[test]
fn test_create_basic_summary() {
let schema = full_schema();
let row_count = 3;
let ts_min_max = TimestampMinMax { min: 42, max: 42 };
let actual = create_basic_summary(row_count, &schema, Some(ts_min_max));
let expected = Statistics {
num_rows: Some(3),
total_byte_size: None,
column_statistics: Some(vec![
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics::default(),
ColumnStatistics {
null_count: Some(0),
min_value: Some(ScalarValue::TimestampNanosecond(Some(42), None)),
max_value: Some(ScalarValue::TimestampNanosecond(Some(42), None)),
distinct_count: None,
},
]),
is_exact: true,
};
assert_eq!(actual, expected);
}
fn full_schema() -> Schema {
SchemaBuilder::new()
.tag("tag")
.influx_field("field_bool", InfluxFieldType::Boolean)
.influx_field("field_float", InfluxFieldType::Float)
.influx_field("field_integer", InfluxFieldType::Integer)
.influx_field("field_string", InfluxFieldType::String)
.influx_field("field_uinteger", InfluxFieldType::UInteger)
.timestamp()
.build()
.unwrap()
}
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test using overloaded indexing when the "map" is stored in a
// field. This caused problems at some point.
use std::ops::Index;
struct Foo {
x: isize,
y: isize,
}
struct Bar {
foo: Foo
}
impl Index<isize> for Foo {
type Output = isize;
fn index(&self, z: isize) -> &isize {
if z == 0 {
&self.x
} else {
&self.y
}
}
}
trait Int {
fn get(self) -> isize;
fn get_from_ref(&self) -> isize;
fn inc(&mut self);
}
impl Int for isize {
fn get(self) -> isize { self }
fn get_from_ref(&self) -> isize { *self }
fn inc(&mut self) { *self += 1; }
}
fn main() {
let f = Bar { foo: Foo {
x: 1,
y: 2,
} };
assert_eq!(f.foo[1].get(), 2);
}
|
//! https://github.com/lumen/otp/tree/lumen/lib/tftp/src
use super::*;
test_compiles_lumen_otp!(tftp imports "lib/kernel/src/application", "lib/tftp/src/tftp_engine", "lib/tftp/src/tftp_sup");
test_compiles_lumen_otp!(tftp_app imports "lib/tftp/src/tftp_sup");
test_compiles_lumen_otp!(tftp_binary);
test_compiles_lumen_otp!(tftp_engine);
test_compiles_lumen_otp!(tftp_file);
test_compiles_lumen_otp!(tftp_lib);
test_compiles_lumen_otp!(tftp_logger imports "lib/kernel/src/error_logger");
test_compiles_lumen_otp!(tftp_sup);
fn includes() -> Vec<&'static str> {
let mut includes = super::includes();
includes.extend(vec!["lib/kernel/src", "lib/tftp/src"]);
includes
}
fn relative_directory_path() -> PathBuf {
super::relative_directory_path().join("tftp/src")
}
|
#[doc = "Reader of register CSGCM0R"]
pub type R = crate::R<u32, super::CSGCM0R>;
#[doc = "Writer for register CSGCM0R"]
pub type W = crate::W<u32, super::CSGCM0R>;
#[doc = "Register CSGCM0R `reset()`'s with value 0"]
impl crate::ResetValue for super::CSGCM0R {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `CSGCM0`"]
pub type CSGCM0_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `CSGCM0`"]
pub struct CSGCM0_W<'a> {
w: &'a mut W,
}
impl<'a> CSGCM0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - CSGCM0"]
#[inline(always)]
pub fn csgcm0(&self) -> CSGCM0_R {
CSGCM0_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - CSGCM0"]
#[inline(always)]
pub fn csgcm0(&mut self) -> CSGCM0_W {
CSGCM0_W { w: self }
}
}
|
#[macro_export]
macro_rules! timerchannel_pin {
($TimerN: ident, $ChannelX: ident, $Pin: ident, $locI: ident, $ccXloc: ident, $ccXpen: ident) => {
impl super::HasLocForFunction<$TimerN, $ChannelX> for crate::gpio::pins::$Pin<crate::gpio::Output> {
unsafe fn configure() {
// FIXME https://github.com/chrysn/efm32gg-hal/issues/1
let reg = &mut *crate::timer::TimerChannel::<$TimerN, $ChannelX>::register();
cortex_m::interrupt::free(|_| {
reg.routeloc0.modify(|_, w| w.$ccXloc().$locI());
reg.routepen.modify(|_, w| w.$ccXpen().set_bit());
});
}
unsafe fn deconfigure() {
// FIXME https://github.com/chrysn/efm32gg-hal/issues/1
let reg = &mut *crate::timer::TimerChannel::<$TimerN, $ChannelX>::register();
cortex_m::interrupt::free(|_| {
reg.routepen.modify(|_, w| w.$ccXpen().clear_bit());
});
}
}
}
}
pub(crate) use timerchannel_pin;
|
use std::sync::RwLock;
use wapc_guest::prelude::*;
use wasmcolonies_protocol as protocol;
use wasmcolonies_protocol::{deserialize, serialize};
lazy_static! {
#[doc(hidden)]
static ref PLAYER_TICK: RwLock<Option<fn(protocol::PlayerTick) -> HandlerResult<protocol::PlayerTickResponse>>> =
RwLock::new(None);
}
#[doc(hidden)]
pub struct Handlers {}
#[doc(hidden)]
impl Handlers {
pub fn register_player_tick(
f: fn(protocol::PlayerTick) -> HandlerResult<protocol::PlayerTickResponse>,
) {
*PLAYER_TICK.write().unwrap() = Some(f);
register_function(&"PlayerTick", player_tick_wrapper);
}
}
fn player_tick_wrapper(input_payload: &[u8]) -> CallResult {
let input = deserialize::<protocol::PlayerTick>(input_payload)?;
let lock = PLAYER_TICK.read().unwrap().unwrap();
let result = lock(input)?;
Ok(serialize(result)?)
}
|
use std::fmt;
use std::thread;
use std::time::Duration;
use core::fmt::Debug;
use rppal::gpio::{Gpio, OutputPin, Level};
/// GPIO BCM pin number for DAT.
pub const GPIO_DAT: u8 = 10;
/// GPIO BCM pin number for CLK.
pub const GPIO_CLK: u8 = 11;
/// GPIO BCM pin number for CS.
pub const GPIO_CS: u8 = 8;
/// Number of pixels.
pub const NUM_PIXELS: usize = 7;
/// Brightness.
pub const BRIGHTNESS: u8 = 7;
/// Sleep time between pin commands.
pub const SLEEP_TIME : u64 = 0;
/// Rainbow HAT APA102 Driver.
#[derive(Debug)]
pub struct APA102 {
/// Output pin to write to GPIO. Optional as not used in simulated mode.
pin_dat: Option<Box<OutputPin>>,
/// Output pin to write to GPIO. Optional as not used in simulated mode.
pin_clk: Option<Box<OutputPin>>,
/// Output pin to write to GPIO. Optional as not used in simulated mode.
pin_cs: Option<Box<OutputPin>>,
/// pixels to be printed
pub pixels: [[u8;4] ; NUM_PIXELS],
/// brightness between 0 and 15
brightness: u8,
/// In simulation mode, no interaction with the hardware is done to simplify testability.
simulation: bool,
/// is the setup completed
is_setup: bool,
}
impl APA102 {
/// Creates a APA102.
pub fn new() -> Result<APA102, Error> {
Ok(Self {
pin_dat: None,
pin_clk: None,
pin_cs: None,
pixels:[[0; 4]; NUM_PIXELS],
brightness: BRIGHTNESS,
simulation: false,
is_setup: false,
})
}
/// Initialize driver.
pub fn setup(&mut self) -> Result <(), Error> {
if !self.is_setup {
// Ignore Gpio initialization if in simulation mode
if !self.simulation {
let gpio_dat = Gpio::new()?;
let output_dat = gpio_dat.get(GPIO_DAT)?.into_output();
self.pin_dat = Some(Box::new(output_dat));
let gpio_clk = Gpio::new()?;
let output_clk = gpio_clk.get(GPIO_CLK)?.into_output();
self.pin_clk = Some(Box::new(output_clk));
let gpio_cs = Gpio::new()?;
let output_cs = gpio_cs.get(GPIO_CS)?.into_output();
self.pin_cs = Some(Box::new(output_cs));
}
self.is_setup = true;
}
Ok(())
}
/// Exit.
pub fn exit(&mut self) -> Result <(), Error> {
self.clear();
self.show()?;
Ok(())
}
/// Set the brightness of all pixels.
/// # Arguments
///
/// * `brightness` - Brightness: 0.0 to 1.0.
pub fn set_brightness(&mut self, brightness : f32) {
assert!(brightness >= 0.0);
assert!(brightness <= 1.0);
for i in 0..self.pixels.len() {
self.pixels[i][3] = (31.0 * brightness.round()) as u8;
}
}
/// Clear the pixel buffer.
pub fn clear(&mut self) {
for i in 0..self.pixels.len() {
self.pixels[i][0] = 0 as u8; // R
self.pixels[i][1] = 0 as u8; // G
self.pixels[i][2] = 0 as u8; // B
}
}
/// Write a single byte to the DAT and CLK pins.
/// # Arguments
///
/// * `byte` - Bite to write.
fn write_byte (&mut self, byte : u8) {
if !self.simulation {
let output_dat = self.pin_dat.as_deref_mut().unwrap();
let output_clk = self.pin_clk.as_deref_mut().unwrap();
// Scan from most significative to least
for i in 0..8 {
if APA102::get_bit_at(byte, 7 - i) {
output_dat.write(Level::High);
} else {
output_dat.write(Level::Low);
}
output_clk.write(Level::High);
thread::sleep(Duration::from_millis(SLEEP_TIME));
output_clk.write(Level::Low);
thread::sleep(Duration::from_millis(SLEEP_TIME));
}
}
}
/// Ends writing data.
fn eof(&mut self) {
if !self.simulation {
let output_dat = self.pin_dat.as_deref_mut().unwrap();
let output_clk = self.pin_clk.as_deref_mut().unwrap();
output_dat.write(Level::Low);
for _x in 0..36 {
output_clk.write(Level::High);
thread::sleep(Duration::from_millis(SLEEP_TIME));
output_clk.write(Level::Low);
thread::sleep(Duration::from_millis(SLEEP_TIME));
}
}
}
/// Starts writing data.
fn sof(&mut self) {
if !self.simulation {
let output_dat = self.pin_dat.as_deref_mut().unwrap();
let output_clk = self.pin_clk.as_deref_mut().unwrap();
output_dat.write(Level::Low);
for _x in 0..32 {
output_clk.write(Level::High);
thread::sleep(Duration::from_millis(SLEEP_TIME));
output_clk.write(Level::Low);
thread::sleep(Duration::from_millis(SLEEP_TIME));
}
}
}
/// Output the buffer.
pub fn show(&mut self) -> Result <(), Error>{
// Initialize if not done yet
if !self.is_setup {
let _result = self.setup();
}
if !self.simulation {
let output_cs = self.pin_cs.as_deref_mut().unwrap();
output_cs.write(Level::Low);
self.sof();
for i in 0..self.pixels.len() {
self.write_byte(0b11100000 | self.pixels[i][3]); // brightness
self.write_byte(self.pixels[i][2]); // b
self.write_byte(self.pixels[i][1]); // g
self.write_byte(self.pixels[i][0]); // r
}
self.eof();
let output_cs = self.pin_cs.as_deref_mut().unwrap();
output_cs.write(Level::High);
}
Ok(())
}
/// Set the RGB value and optionally brightness of all pixels.
/// # Arguments
///
/// * `r` - Amount of red: 0 to 255
/// * `g` - Amount of green: 0 to 255
/// * `b` - Amount of blue: 0 to 255
/// * `brightness` - Brightness: 0.0 to 1.0
pub fn set_all(&mut self, r : u8, g: u8, b: u8, brightness: f32) {
for i in 0..self.pixels.len() {
self.set_pixel(i, r, g, b, brightness);
}
}
/// Set the RGB value, and optionally brightness, of a single pixel.
/// # Arguments
///
/// * `x` - The horizontal position of the pixel: 0 to 7
/// * `r` - Amount of red: 0 to 255
/// * `g` - Amount of green: 0 to 255
/// * `b` - Amount of blue: 0 to 255
/// * `brightness` - Brightness: 0.0 to 1.0
pub fn set_pixel(&mut self, x: usize, r : u8, g: u8, b: u8, brightness: f32) {
assert!(brightness >= 0.0);
assert!(brightness <= 1.0);
self.pixels[x][0] = r as u8; // R
self.pixels[x][1] = g as u8; // G
self.pixels[x][2] = b as u8; // B
self.pixels[x][3] = (31.0 * brightness.round()) as u8; // Brightness
}
/// gets the bit at position `n`. Bits are numbered from 0 (least significant) to 31 (most significant).
/// # Arguments
///
/// * `byte` - The byte to get the bit from.
/// * `n` - Bit position.
fn get_bit_at(byte: u8, n: u8) -> bool {
assert!(n < 8);
byte & (1 << n) != 0
}
}
/// Errors that can occur.
#[derive(Debug)]
pub enum Error {
/// Gpio error.
Gpio(rppal::gpio::Error),
}
impl std::error::Error for Error {}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &*self {
Error::Gpio(err) => write!(f, "Gpio error: {}", &err),
}
}
}
/// Converts Gpio error
impl From<rppal::gpio::Error> for Error {
fn from(err: rppal::gpio::Error) -> Error {
Error::Gpio(err)
}
}
/// Unit tests
#[cfg(test)]
mod tests {
use super::*;
/// Tests the setup of the light.
#[test]
fn test_apa102_setup() -> Result<(), Error> {
let mut apa102 = APA102::new()?;
apa102.simulation = true;
// Not setup
assert!(apa102.is_setup == false);
// Force setup
let _result = apa102.setup();
assert!(apa102.is_setup == true);
Ok(())
}
/// Tests the setup of the light.
#[test]
fn test_apa102_set_brightness() -> Result<(), Error> {
let mut apa102 = APA102::new()?;
apa102.simulation = true;
let _result = apa102.setup();
apa102.set_brightness(0.0);
for i in 0..apa102.pixels.len() {
assert!(apa102.pixels[i][3] == 0);
}
apa102.set_brightness(1.0);
for i in 0..apa102.pixels.len() {
assert!(apa102.pixels[i][3] == 31);
}
Ok(())
}
/// Test clearing the buffer.
#[test]
fn test_apa102_clear() -> Result<(), Error> {
let mut apa102 = APA102::new()?;
apa102.simulation = true;
let _result = apa102.setup();
let brightness : u8 = 31;
for i in 0..apa102.pixels.len() {
apa102.pixels[i][0] = 250 as u8; // R
apa102.pixels[i][1] = 250 as u8; // G
apa102.pixels[i][2] = 250 as u8; // B
apa102.pixels[i][3] = brightness;
}
apa102.clear();
// The RGB pixels are clear but the brightness is unchanged
for i in 0..apa102.pixels.len() {
assert!(apa102.pixels[i][0] == 0);
assert!(apa102.pixels[i][1] == 0);
assert!(apa102.pixels[i][2] == 0);
assert!(apa102.pixels[i][3] == 31);
}
Ok(())
}
/// Tests to set pixel colors.
#[test]
fn test_apa102_set_pixel() -> Result<(), Error> {
let mut apa102 = APA102::new()?;
apa102.simulation = true;
let _result = apa102.setup();
apa102.set_pixel(0, 123, 234, 012, 1.0);
apa102.set_pixel(6, 12, 58, 123, 0.0);
assert!(apa102.pixels[0][0] == 123);
assert!(apa102.pixels[0][1] == 234);
assert!(apa102.pixels[0][2] == 12);
assert!(apa102.pixels[0][3] == 31);
assert!(apa102.pixels[6][0] == 12);
assert!(apa102.pixels[6][1] == 58);
assert!(apa102.pixels[6][2] == 123);
assert!(apa102.pixels[6][3] == 0);
Ok(())
}
/// Tests to set all
#[test]
fn test_apa102_set_all() -> Result<(), Error> {
let mut apa102 = APA102::new()?;
apa102.simulation = true;
let _result = apa102.setup();
apa102.set_all(123, 234, 012, 1.0);
for i in 0..apa102.pixels.len() {
assert!(apa102.pixels[i][0] == 123);
assert!(apa102.pixels[i][1] == 234);
assert!(apa102.pixels[i][2] == 12);
assert!(apa102.pixels[i][3] == 31);
}
Ok(())
}
/// Tests obtaining a bit from a byte.
#[test]
fn test_apa102_get_bit_at() -> Result<(), Error> {
let value = 0b00010101 as u8;
assert!(APA102::get_bit_at(value, 0) == true);
assert!(APA102::get_bit_at(value, 1) == false);
assert!(APA102::get_bit_at(value, 2) == true);
assert!(APA102::get_bit_at(value, 3) == false);
assert!(APA102::get_bit_at(value, 4) == true);
assert!(APA102::get_bit_at(value, 5) == false);
assert!(APA102::get_bit_at(value, 6) == false);
assert!(APA102::get_bit_at(value, 7) == false);
Ok(())
}
}
|
/*
* @lc app=leetcode id=1006 lang=rust
*
* [1006] Clumsy Factorial
*/
impl Solution {
pub fn clumsy(n: i32) -> i32 {
let mut f = 0;
let mut i = n;
while i > 0 {
let mut a = i;
if i > 1 { a *= i-1; }
if i > 2 { a /= i-2; }
if i == n { f += a; } else { f -= a; }
if i > 3 { f += i-3; }
i -= 4;
}
f
}
}
|
use crate::{integer::Integer, rational::Rational};
use core::ops::DivAssign;
// DivAssign The division assignment operator /=.
// ['Rational', 'Rational', 'Rational::divide_assign', 'no', [], ['ref']]
impl DivAssign<Rational> for Rational {
fn div_assign(&mut self, rhs: Rational) {
Rational::divide_assign(self, &rhs)
}
}
// ['Rational', '&Rational', 'Rational::divide_assign', 'no', [], []]
impl DivAssign<&Rational> for Rational {
fn div_assign(&mut self, rhs: &Rational) {
Rational::divide_assign(self, rhs)
}
}
// ['Rational', 'Integer', 'Rational::divide_assign_integer', 'no', [], ['ref']]
impl DivAssign<Integer> for Rational {
fn div_assign(&mut self, rhs: Integer) {
Rational::divide_assign_integer(self, &rhs)
}
}
// ['Rational', '&Integer', 'Rational::divide_assign_integer', 'no', [], []]
impl DivAssign<&Integer> for Rational {
fn div_assign(&mut self, rhs: &Integer) {
Rational::divide_assign_integer(self, rhs)
}
}
// ['Rational', 'i8', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<i8> for Rational {
fn div_assign(&mut self, rhs: i8) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&i8', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&i8> for Rational {
fn div_assign(&mut self, rhs: &i8) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'u8', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<u8> for Rational {
fn div_assign(&mut self, rhs: u8) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&u8', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&u8> for Rational {
fn div_assign(&mut self, rhs: &u8) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'i16', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<i16> for Rational {
fn div_assign(&mut self, rhs: i16) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&i16', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&i16> for Rational {
fn div_assign(&mut self, rhs: &i16) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'u16', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<u16> for Rational {
fn div_assign(&mut self, rhs: u16) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&u16', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&u16> for Rational {
fn div_assign(&mut self, rhs: &u16) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'i32', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<i32> for Rational {
fn div_assign(&mut self, rhs: i32) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&i32', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&i32> for Rational {
fn div_assign(&mut self, rhs: &i32) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'u32', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<u32> for Rational {
fn div_assign(&mut self, rhs: u32) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&u32', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&u32> for Rational {
fn div_assign(&mut self, rhs: &u32) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'i64', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<i64> for Rational {
fn div_assign(&mut self, rhs: i64) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&i64', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&i64> for Rational {
fn div_assign(&mut self, rhs: &i64) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'u64', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<u64> for Rational {
fn div_assign(&mut self, rhs: u64) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&u64', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&u64> for Rational {
fn div_assign(&mut self, rhs: &u64) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'i128', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<i128> for Rational {
fn div_assign(&mut self, rhs: i128) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&i128', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&i128> for Rational {
fn div_assign(&mut self, rhs: &i128) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
// ['Rational', 'u128', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}]]
impl DivAssign<u128> for Rational {
fn div_assign(&mut self, rhs: u128) {
Rational::divide_assign_integer(self, &Integer::from(rhs))
}
}
// ['Rational', '&u128', 'Rational::divide_assign_integer', 'no', [], ['ref',
// {'convert': 'Integer'}, 'deref']]
impl DivAssign<&u128> for Rational {
fn div_assign(&mut self, rhs: &u128) {
Rational::divide_assign_integer(self, &Integer::from(*rhs))
}
}
|
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 = scan!(u64);
let mut ans = 0;
let mut i = 1;
while i <= n {
// i: 1, 11, 111, 1111, ...
let mut j = i;
let mut k = i + 1;
while j <= n {
// i: 111
// j: 111, 1110, 11100, 111000, ...
// k: 112, 1120, 11200, 112000, ...
ans += k.min(n) - j;
j *= 10;
k *= 10;
}
i = i * 10 + 1;
}
println!("{}", ans + f(n));
}
fn f(n: u64) -> u64 {
n.to_string().chars().take_while(|&ch| ch == '1').count() as u64
}
|
use std::io;
fn main() {
// "!" - signifies a macro prntln! is a macro because it can take a different
// number of arguments
println!("Enter your weight (kg): ");
let mut input = String::new(); //Strings live on the heap
io::stdin().read_line(&mut input).unwrap();
let weight: f32 = input.trim().parse().unwrap();
dbg!(weight);
let mars_weight = calculate_weight_on_mars(weight);
println!("Weight on Mars: {}kg", mars_weight);
}
fn calculate_weight_on_mars(weight: f32) -> f32 {
//the last expression that doesn't have semi-colon means "return"
(weight / 9.81) * 3.711
}
//Each value in Rust is owned by a variable.
//When the owner goes out of scope, the value will be dealocated.
//There can be only ONE owner at a time.
|
use super::{tls_connector, MaybeTlsSettings, MaybeTlsStream, Result, TlsError};
use futures01::{Async, Future};
use openssl::ssl::{ConnectConfiguration, HandshakeError};
use std::net::SocketAddr;
use tokio01::net::tcp::{ConnectFuture, TcpStream};
use tokio_openssl03::{ConnectAsync, ConnectConfigurationExt};
enum State {
Connecting(ConnectFuture, Option<ConnectConfiguration>),
Negotiating(ConnectAsync<TcpStream>),
}
/// This is an asynchronous connection future that will optionally
/// negotiate a TLS session before returning a ready connection.
pub(crate) struct MaybeTlsConnector {
host: String,
state: State,
}
impl MaybeTlsConnector {
fn new(host: String, addr: SocketAddr, tls: &MaybeTlsSettings) -> Result<Self> {
let connector = TcpStream::connect(&addr);
let tls_connector = match tls {
MaybeTlsSettings::Raw(()) => None,
MaybeTlsSettings::Tls(_) => Some(tls_connector(tls)?),
};
let state = State::Connecting(connector, tls_connector);
Ok(Self { host, state })
}
}
impl Future for MaybeTlsConnector {
type Item = MaybeTlsStream<TcpStream>;
type Error = TlsError;
fn poll(&mut self) -> std::result::Result<Async<Self::Item>, Self::Error> {
loop {
match &mut self.state {
State::Connecting(connector, tls) => match connector.poll() {
Err(source) => return Err(TlsError::Connect { source }),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Ok(Async::Ready(stream)) => match tls.take() {
// Here's where the magic happens. If there is
// no TLS connector, just return ready with the
// raw stream. Otherwise, start the TLS
// negotiation and switch to that state.
None => return Ok(Async::Ready(MaybeTlsStream::Raw(stream))),
Some(tls_config) => {
let connector = tls_config.connect_async(&self.host, stream);
self.state = State::Negotiating(connector)
}
},
},
State::Negotiating(connector) => match connector.poll() {
Err(error) => {
return Err(match error {
HandshakeError::WouldBlock(_) => TlsError::HandshakeNotReady,
HandshakeError::Failure(stream) => TlsError::Handshake {
source: stream.into_error(),
},
HandshakeError::SetupFailure(source) => {
TlsError::HandshakeSetup { source }
}
})
}
Ok(Async::NotReady) => return Ok(Async::NotReady),
Ok(Async::Ready(stream)) => {
debug!(message = "negotiated TLS");
return Ok(Async::Ready(MaybeTlsStream::Tls(stream)));
}
},
}
}
}
}
impl MaybeTlsSettings {
pub(crate) fn connect(&self, host: String, addr: SocketAddr) -> Result<MaybeTlsConnector> {
MaybeTlsConnector::new(host, addr, self)
}
}
|
macro_rules! arr {
($type: ty, $value: expr, $long: expr) => {
Arr::new([$value as $type; $long]) as Arr<$type, [$type; $long]>;
}
}
macro_rules! gethead {
($self:ident, $index: expr) => {
$self.head[$index]
}
}
macro_rules! headlen {
($self:ident) => {
$self.head.len()
}
}
macro_rules! get {
($self:ident, $index: expr) => {
if $index < headlen!($self) {
gethead!($self, $index)
} else if $index < headlen!($self) + $self.follow.len() {
$self.follow[$index - headlen!($self)]
} else {
panic!("Cross-border visit");
}
}
}
macro_rules! append {
($self:ident, $value: expr) => {
$self.follow.push($value);
}
}
struct Arr<T, A> {
head: A,
follow: Vec<T>,
}
impl<T, A> Arr<T, A> {
fn new(value: A) -> Self {
Arr {
head: value,
follow: Vec::new(),
}
}
}
fn main() {
let mut foo = arr!(u8, 1, 2);
println!("{}", get!(foo, 1));
append!(foo, 2);
println!("{}", get!(foo, 2));
println!("{}", get!(foo, 3));
}
|
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
/// card stats
#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug)]
pub struct Stats {
/// the card's skills at time of minting
pub base: Vec<u8>,
/// the card's current skills
pub current: Vec<u8>,
}
|
mod common;
mod create;
mod error;
mod getattr;
mod lookup;
mod mkdir;
mod mknod;
mod read;
mod readdir;
mod release;
mod rename;
mod rmdir;
mod unlink;
mod write;
mod virtualdir;
pub use common::MenmosFS;
pub use error::{Error, Result};
use crate::constants;
use async_fuse::{FileAttr, FileType};
use menmos_client::{Meta, Type};
use std::time::UNIX_EPOCH;
fn build_attributes(inode: u64, meta: &Meta, perm: u16) -> FileAttr {
let kind = match meta.blob_type {
Type::Directory => FileType::Directory,
Type::File => FileType::RegularFile,
};
FileAttr {
ino: inode,
size: meta.size,
blocks: meta.size / constants::BLOCK_SIZE,
atime: UNIX_EPOCH, // 1970-01-01 00:00:00
mtime: UNIX_EPOCH,
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind,
perm,
nlink: if kind == FileType::RegularFile {
1
} else {
2 + meta.parents.len() as u32
},
uid: 1000,
gid: 1000,
rdev: 0,
flags: 0,
}
}
|
use criterion::*;
use itertools::*;
use legion::*;
#[derive(Copy, Clone, Debug, PartialEq)]
struct A(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct B(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct C(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct D(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct E(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct F(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct Tag(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct Position(f32);
#[derive(Copy, Clone, Debug, PartialEq)]
struct Rotation(f32);
fn create_entities(
world: &mut World,
variants: &mut [Box<dyn FnMut(Entity, &mut World)>],
num_components: usize,
count: usize,
) {
let len_variants = variants.len();
let components = (0..)
.flat_map(|step| (0..len_variants).map(move |i| (i + i * step) % len_variants))
.chunks(num_components);
for initializers in (&components).into_iter().take(count) {
let entity = world.push((A(0.0),));
for i in initializers {
let init = variants.get_mut(i).unwrap();
init(entity, world);
}
}
}
fn add_background_entities(world: &mut World, count: usize) {
create_entities(
world,
&mut [
Box::new(|e, w| w.entry(e).unwrap().add_component(B(0.0))),
Box::new(|e, w| w.entry(e).unwrap().add_component(A(0.0))),
Box::new(|e, w| w.entry(e).unwrap().add_component(C(0.0))),
Box::new(|e, w| w.entry(e).unwrap().add_component(D(0.0))),
Box::new(|e, w| w.entry(e).unwrap().add_component(E(0.0))),
Box::new(|e, w| w.entry(e).unwrap().add_component(F(0.0))),
],
5,
count,
);
}
fn setup(n: usize) -> World {
let mut world = World::default();
world.extend((0..n).map(|_| (Position(0.), Rotation(0.))));
world
}
fn bench_create_delete(c: &mut Criterion) {
c.bench_function_over_inputs(
"create-delete",
|b, count| {
let mut world = setup(0);
b.iter(|| {
let entities = world.extend((0..*count).map(|_| (Position(0.),))).to_vec();
for e in entities {
world.remove(e);
}
})
},
(0..10).map(|i| i * 100),
);
}
fn bench_iter_simple(c: &mut Criterion) {
c.bench_function("iter-simple", |b| {
let mut world = setup(2000);
add_background_entities(&mut world, 10000);
let mut query = <(Read<Position>, Write<Rotation>)>::query();
b.iter(|| {
for (pos, rot) in query.iter_mut(&mut world) {
rot.0 = pos.0;
}
});
});
}
fn bench_iter_complex(c: &mut Criterion) {
c.bench_function("iter-complex", |b| {
let mut world = setup(0);
add_background_entities(&mut world, 10000);
for _ in 0..200 {
world.extend((0..2000).map(|_| (Position(0.), Rotation(0.))));
}
let mut query = <(Read<Position>, Write<Rotation>)>::query().filter(!component::<A>());
b.iter(|| {
for (pos, rot) in query.iter_mut(&mut world) {
rot.0 = pos.0;
}
});
});
}
fn bench_iter_chunks_simple(c: &mut Criterion) {
c.bench_function("iter-chunks-simple", |b| {
let mut world = setup(10000);
add_background_entities(&mut world, 10000);
let mut query = <(Write<Position>, Read<Rotation>)>::query();
b.iter(|| {
for mut c in query.iter_chunks_mut(&mut world) {
unsafe {
c.component_slice_mut::<Position>()
.unwrap()
.get_unchecked_mut(0)
.0 = 0.0
};
}
});
});
}
fn bench_iter_chunks_complex(c: &mut Criterion) {
c.bench_function("iter-chunks-complex", |b| {
let mut world = setup(0);
add_background_entities(&mut world, 10000);
for _ in 0..200 {
world.extend((0..10000).map(|_| (Position(0.), Rotation(0.))));
}
let mut query = <(Write<Position>, Read<Rotation>)>::query().filter(!component::<A>());
b.iter(|| {
for mut c in query.iter_chunks_mut(&mut world) {
unsafe {
c.component_slice_mut::<Position>()
.unwrap()
.get_unchecked_mut(0)
.0 = 0.0
};
}
});
});
}
criterion_group!(
basic,
bench_create_delete,
bench_iter_simple,
bench_iter_complex,
bench_iter_chunks_simple,
bench_iter_chunks_complex
);
criterion_main!(basic);
|
extern crate proconio;
use proconio::input;
fn main() {
input! {
mut s: String,
}
let s = s.chars().collect::<Vec<_>>();
let mut ans = 0;
if s[0] == 'R' || s[1] == 'R' || s[2] == 'R' {
ans = 1;
}
if s[0..2] == ['R', 'R'] || s[1..3] == ['R', 'R'] {
ans = 2;
}
if s == ['R', 'R', 'R'] {
ans = 3;
}
println!("{}", ans);
}
|
use wayland_client::{
protocol::wl_registry::WlRegistry, AnonymousObject, Attached, DispatchData, GlobalEvent, Main,
RawEvent,
};
pub fn print_global_event(
event: GlobalEvent,
_registry: Attached<WlRegistry>,
_data: DispatchData,
) {
match event {
GlobalEvent::New {
id,
interface,
version,
} => {
eprintln!("New global: {} id={} (v{})", interface, id, version);
}
GlobalEvent::Removed { id, interface } => {
eprintln!("Removed global: {} id={}", interface, id);
}
}
}
#[allow(dead_code)]
pub fn print_unfiltered_events(event: RawEvent, _obj: Main<AnonymousObject>, _data: DispatchData) {
eprintln!("Uncaught event: {}::{}", event.interface, event.name);
}
|
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read};
const REQUIRED_KEYS: [&str; 7] = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];
const VALID_KEYS: [&str; 8] = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"];
struct ID(HashMap<String, String>);
impl From<String> for ID {
fn from(id_str: String) -> Self {
let tokens: Vec<&str> = id_str
.split(' ')
.filter(|tok| !tok.is_empty())
.collect::<Vec<&str>>();
ID(tokens
.iter()
.map(|val| {
let key_val = val.clone().split(':').collect::<Vec<&str>>();
(key_val[0].to_string(), key_val[1].to_string())
})
.collect::<HashMap<String, String>>())
}
}
impl ID {
fn valid_keys(&self) -> bool {
let keys = self.0.keys().cloned().collect::<Vec<String>>();
let additional_keys: Vec<String> = keys
.clone()
.into_iter()
.filter(|val| !VALID_KEYS.contains(&val.as_str()))
.collect::<Vec<String>>();
if additional_keys.len() > 0 {
return false;
}
let missing_required_keys: Vec<&str> = REQUIRED_KEYS
.to_vec()
.into_iter()
.filter(|val| !keys.contains(&val.to_string()))
.collect();
if missing_required_keys.len() > 0 {
return false;
}
return true;
}
fn val_between(&self, key: &str, min: usize, max: usize) -> bool {
let mut val_ok = false;
if let Ok(year) = self.0[key].parse::<usize>() {
if year <= max && year >= min {
val_ok = true;
}
}
val_ok
}
fn valid_height(&self) -> bool {
let chars: Vec<char> = self.0["hgt"].chars().collect();
let unit: String = chars
.clone()
.into_iter()
.filter(|val| val.is_alphabetic())
.collect();
if unit != "cm" && unit != "in" {
return false;
}
let value: String = chars.into_iter().filter(|val| val.is_numeric()).collect();
if let Ok(value_usize) = value.parse::<usize>() {
if unit == "cm" && value_usize <= 193 && value_usize >= 150 {
return true;
}
if unit == "in" && value_usize <= 76 && value_usize >= 59 {
return true;
}
}
return false;
}
fn valid_hcl(&self) -> bool {
if self.0["hcl"].len() != 7 {
return false;
}
let mut chars = self.0["hcl"].chars();
if chars.nth(0) != Some('#') {
return false;
}
chars
.nth(1)
.into_iter()
.filter(|val| !val.is_alphanumeric())
.collect::<Vec<char>>()
.len()
== 0
}
fn valid_ecl(&self) -> bool {
const VALID_EYE_COLOR: [&'static str; 7] =
["amb", "blu", "brn", "gry", "grn", "hzl", "oth"];
VALID_EYE_COLOR.contains(&self.0["ecl"].as_str())
}
fn valid_pid(&self) -> bool {
let pid = &self.0["pid"];
pid.len() == 9
&& pid
.chars()
.into_iter()
.filter(|val| !val.is_numeric())
.collect::<Vec<char>>()
.len()
== 0
}
fn valid_values(&self) -> bool {
let byr_ok = self.val_between("byr", 1920, 2002);
let iyr_ok = self.val_between("iyr", 2010, 2020);
let eyr_ok = self.val_between("eyr", 2020, 2030);
let hgt_ok = self.valid_height();
let hcl_ok = self.valid_hcl();
let ecl_ok = self.valid_ecl();
let pid_ok = self.valid_pid();
return byr_ok && iyr_ok && eyr_ok && hgt_ok && hcl_ok && ecl_ok && pid_ok;
}
fn is_valid(&self) -> bool {
self.valid_keys() && self.valid_values()
}
}
fn read_all_ids<R: Read>(reader: R) -> Vec<String> {
let buf_reader = BufReader::new(reader);
let mut result = Vec::new();
let mut passport_str = String::new();
for line_res in buf_reader.lines() {
let line = line_res.unwrap();
if line == String::new() {
result.push(passport_str);
passport_str = String::new();
} else {
passport_str.push_str(line.as_str());
passport_str.push_str(" ");
}
}
result
}
pub fn solve_puzzle<R: Read>(reader: R) {
let passports = read_all_ids(reader);
let mut count = 0;
for passport_str in passports {
let id = ID::from(passport_str);
count += id.is_valid() as usize;
}
println!("Nr of valid IDs = {}", count);
}
#[cfg(test)]
mod tests {
use crate::dec4::solve_puzzle;
use std::fs::File;
#[test]
fn test() {
solve_puzzle(File::open("src/dec4/input.txt").unwrap());
}
}
|
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let _: usize = rd.get();
let a: Vec<Vec<char>> = (0..n).map(|_| rd.get_chars()).collect();
if !reachable(0.0, &a) {
println!("-1");
return;
}
let mut ng = 10.0;
let mut ok = 0.0;
for _ in 0..100 {
let lb = (ng + ok) / 2.0;
if reachable(lb, &a) {
ok = lb;
} else {
ng = lb;
}
}
println!("{:10}", ok);
}
fn reachable(lb: f64, a: &[Vec<char>]) -> bool {
let (n, m) = (a.len(), a[0].len());
let (mut si, mut sj) = (0, 0);
let (mut gi, mut gj) = (0, 0);
for i in 0..n {
for j in 0..m {
if a[i][j] == 's' {
si = i;
sj = j;
}
if a[i][j] == 'g' {
gi = i;
gj = j;
}
}
}
const NSEW: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, 1), (0, -1)];
let inf = std::u64::MAX;
let mut d = vec![vec![inf; m]; n];
d[si][sj] = 0;
use std::collections::VecDeque;
let mut q = VecDeque::new();
q.push_back((si, sj));
'outer: while let Some((i, j)) = q.pop_front() {
for (ni, nj) in around(i, j).y_range(0..n).x_range(0..m).directions(&NSEW) {
if a[ni][nj] == 'g' {
d[ni][nj] = d[i][j] + 1;
break 'outer;
}
if a[ni][nj] == '#' {
continue;
}
if d[ni][nj] != inf {
continue;
}
let sun = a[ni][nj] as u64 - '0' as u64;
let light = (sun as f64) * 0.99_f64.powi((d[i][j] + 1) as i32);
if light >= lb {
d[ni][nj] = d[i][j] + 1;
q.push_back((ni, nj));
}
}
}
d[gi][gj] < inf
}
pub struct Around<'a> {
y: usize,
x: usize,
y_range: std::ops::Range<usize>,
x_range: std::ops::Range<usize>,
directions: &'a [(isize, isize)],
dir_idx: usize,
}
pub fn around<'a>(y: usize, x: usize) -> Around<'a> {
Around {
y,
x,
y_range: 0..std::usize::MAX,
x_range: 0..std::usize::MAX,
directions: &[],
dir_idx: 0,
}
}
impl<'a> Around<'a> {
pub fn y_range(self, y_rng: impl std::ops::RangeBounds<usize>) -> Self {
Self {
y_range: half_open_range(y_rng),
..self
}
}
pub fn x_range(self, x_rng: impl std::ops::RangeBounds<usize>) -> Self {
Self {
x_range: half_open_range(x_rng),
..self
}
}
pub fn directions(self, dirs: &'a [(isize, isize)]) -> Self {
Self {
directions: dirs,
..self
}
}
}
impl<'a> Iterator for Around<'a> {
type Item = (usize, usize);
fn next(&mut self) -> Option<Self::Item> {
fn dest(u: usize, i: isize) -> Option<usize> {
if i.is_positive() {
u.checked_add(i as usize)
} else {
u.checked_sub((-i) as usize)
}
}
while let Some(&(dy, dx)) = self.directions.get(self.dir_idx) {
self.dir_idx += 1;
if let Some(ny) = dest(self.y, dy) {
if let Some(nx) = dest(self.x, dx) {
if self.y_range.contains(&self.y)
&& self.x_range.contains(&self.x)
&& self.y_range.contains(&ny)
&& self.x_range.contains(&nx)
{
return Some((ny, nx));
}
}
}
}
None
}
}
fn half_open_range(rng: impl std::ops::RangeBounds<usize>) -> std::ops::Range<usize> {
use std::ops::Bound::{Excluded, Included, Unbounded};
let start = match rng.start_bound() {
Included(&s) => s,
Excluded(&s) => s + 1,
Unbounded => 0,
};
let end = match rng.end_bound() {
Included(&e) => e + 1,
Excluded(&e) => e,
Unbounded => std::usize::MAX,
};
start..end
}
pub struct ProconReader<R> {
r: R,
l: String,
i: usize,
}
impl<R: std::io::BufRead> ProconReader<R> {
pub fn new(reader: R) -> Self {
Self {
r: reader,
l: String::new(),
i: 0,
}
}
pub fn get<T>(&mut self) -> T
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
self.skip_blanks();
assert!(self.i < self.l.len()); // remain some character
assert_ne!(&self.l[self.i..=self.i], " ");
let rest = &self.l[self.i..];
let len = rest.find(' ').unwrap_or_else(|| rest.len());
// parse self.l[self.i..(self.i + len)]
let val = rest[..len]
.parse()
.unwrap_or_else(|e| panic!("{:?}, attempt to read `{}`", e, rest));
self.i += len;
val
}
fn skip_blanks(&mut self) {
loop {
match self.l[self.i..].find(|ch| ch != ' ') {
Some(j) => {
self.i += j;
break;
}
None => {
let mut buf = String::new();
let num_bytes = self
.r
.read_line(&mut buf)
.unwrap_or_else(|_| panic!("invalid UTF-8"));
assert!(num_bytes > 0, "reached EOF :(");
self.l = buf
.trim_end_matches('\n')
.trim_end_matches('\r')
.to_string();
self.i = 0;
}
}
}
}
pub fn get_vec<T>(&mut self, n: usize) -> Vec<T>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
(0..n).map(|_| self.get()).collect()
}
pub fn get_chars(&mut self) -> Vec<char> {
self.get::<String>().chars().collect()
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use common_exception::Result;
use super::optimize_expr::OptimizeExprTask;
use super::Task;
use crate::optimizer::cascades::scheduler::Scheduler;
use crate::optimizer::cascades::tasks::ExploreGroupTask;
use crate::optimizer::cascades::tasks::SharedCounter;
use crate::optimizer::cascades::CascadesOptimizer;
use crate::optimizer::group::GroupState;
use crate::IndexType;
#[derive(Clone, Copy, Debug)]
pub enum OptimizeGroupState {
Init,
Explored,
Optimized,
}
#[derive(Clone, Copy, Debug)]
pub enum OptimizeGroupEvent {
Exploring,
Explored,
Optimizing,
Optimized,
}
#[derive(Debug)]
pub struct OptimizeGroupTask {
pub state: OptimizeGroupState,
pub group_index: IndexType,
pub last_optimized_expr_index: Option<IndexType>,
pub ref_count: Rc<SharedCounter>,
pub parent: Option<Rc<SharedCounter>>,
}
impl OptimizeGroupTask {
pub fn new(group_index: IndexType) -> Self {
Self {
state: OptimizeGroupState::Init,
group_index,
last_optimized_expr_index: None,
ref_count: Rc::new(SharedCounter::new()),
parent: None,
}
}
pub fn with_parent(group_index: IndexType, parent: &Rc<SharedCounter>) -> Self {
let mut task = Self::new(group_index);
parent.inc();
task.parent = Some(parent.clone());
task
}
pub fn execute(
mut self,
optimizer: &mut CascadesOptimizer,
scheduler: &mut Scheduler,
) -> Result<()> {
if matches!(self.state, OptimizeGroupState::Optimized) {
return Ok(());
}
self.transition(optimizer, scheduler)?;
scheduler.add_task(Task::OptimizeGroup(self));
Ok(())
}
fn transition(
&mut self,
optimizer: &mut CascadesOptimizer,
scheduler: &mut Scheduler,
) -> Result<()> {
let event = match self.state {
OptimizeGroupState::Init => self.explore_group(optimizer, scheduler)?,
OptimizeGroupState::Explored => self.optimize_group(optimizer, scheduler)?,
OptimizeGroupState::Optimized => unreachable!(),
};
match (self.state, event) {
(OptimizeGroupState::Init, OptimizeGroupEvent::Exploring) => {}
(OptimizeGroupState::Init, OptimizeGroupEvent::Explored) => {
self.state = OptimizeGroupState::Explored;
}
(OptimizeGroupState::Explored, OptimizeGroupEvent::Optimizing) => {}
(OptimizeGroupState::Explored, OptimizeGroupEvent::Optimized) => {
self.state = OptimizeGroupState::Optimized;
}
_ => unreachable!(),
}
Ok(())
}
fn explore_group(
&mut self,
optimizer: &mut CascadesOptimizer,
scheduler: &mut Scheduler,
) -> Result<OptimizeGroupEvent> {
let group = optimizer.memo.group(self.group_index)?;
if !group.state.explored() {
let task = ExploreGroupTask::with_parent(group.group_index, &self.ref_count);
scheduler.add_task(Task::ExploreGroup(task));
Ok(OptimizeGroupEvent::Exploring)
} else {
Ok(OptimizeGroupEvent::Explored)
}
}
fn optimize_group(
&mut self,
optimizer: &mut CascadesOptimizer,
scheduler: &mut Scheduler,
) -> Result<OptimizeGroupEvent> {
let group = optimizer.memo.group_mut(self.group_index)?;
// Check if there is new added `MExpr`s.
let start_index = self.last_optimized_expr_index.unwrap_or_default();
if start_index == group.num_exprs() {
group.set_state(GroupState::Optimized);
if let Some(parent) = &self.parent {
parent.dec();
}
return Ok(OptimizeGroupEvent::Optimized);
}
for m_expr in group.m_exprs.iter() {
let task =
OptimizeExprTask::with_parent(self.group_index, m_expr.index, &self.ref_count);
scheduler.add_task(Task::OptimizeExpr(task));
}
self.last_optimized_expr_index = Some(group.num_exprs());
Ok(OptimizeGroupEvent::Optimizing)
}
}
|
fn main() {
let input = include_str!("../input.txt");
println!("{}", day_10_part_1(input));
day_10_part_2(input);
}
fn day_10_part_1(input: &str) -> usize {
let mut list = (0..256).collect::<Vec<usize>>();
let mut skip_size = 0;
let mut curr_pos = 0;
let input_lengths = input
.split(',')
.map(|i| i.parse().unwrap())
.collect::<Vec<usize>>();
for length in input_lengths {
reverse_slice_section_circular(&mut list[..], curr_pos % 256, length);
curr_pos += skip_size + length;
skip_size += 1;
}
list[0] * list[1]
}
fn day_10_part_2(input: &str) {
let mut list = (0..256).collect::<Vec<usize>>();
let mut skip_size = 0;
let mut curr_pos = 0;
let mut input_lengths = input.chars().map(|i| i as usize).collect::<Vec<usize>>();
println!("{:?}", input_lengths);
input_lengths.extend_from_slice(&[17, 31, 73, 47, 23]);
for _ in 0..64 {
for &length in &input_lengths {
reverse_slice_section_circular(&mut list[..], curr_pos % 256, length);
curr_pos += skip_size + length;
skip_size += 1;
}
}
let mut collection = Vec::with_capacity(16);
for i in 0..16 {
collection.push(
(list[i * 16 + 0] ^ list[i * 16 + 1] ^ list[i * 16 + 2] ^ list[i * 16 + 3]
^ list[i * 16 + 4] ^ list[i * 16 + 5] ^ list[i * 16 + 6]
^ list[i * 16 + 7] ^ list[i * 16 + 8] ^ list[i * 16 + 9]
^ list[i * 16 + 10] ^ list[i * 16 + 11] ^ list[i * 16 + 12]
^ list[i * 16 + 13] ^ list[i * 16 + 14] ^ list[i * 16 + 15]) as u8,
);
}
println!("{}", collection.len());
for val in collection {
print!("{:0>2x}", val);
}
println!("");
}
fn reverse_slice_section_circular(slice: &mut [usize], start: usize, len: usize) {
let mut rev = slice
.iter()
.cycle()
.skip(start)
.take(len)
.map(|x| *x)
.collect::<Vec<usize>>();
rev.reverse();
for (i, &v) in rev.iter().enumerate() {
let idx = if start + i >= slice.len() {
(start + i) - slice.len()
} else {
start + i
};
slice[idx] = v;
}
}
#[test]
fn test_swap_normal() {
let mut arr = [0, 1, 2, 3, 4];
reverse_slice_section_circular(&mut arr[..], 0, 5);
assert_eq!(arr, [4, 3, 2, 1, 0]);
}
#[test]
fn test_swap_start_bigger() {
let mut arr = [2, 1, 0, 3, 4];
reverse_slice_section_circular(&mut arr[..], 3, 4);
assert_eq!(arr, [4, 3, 0, 1, 2]);
}
|
use directories::{BaseDirs, ProjectDirs};
use std::path::PathBuf;
use std::sync::OnceLock;
pub struct Dirs;
impl Dirs {
/// Project directory specifically for Vim Clap.
///
/// All the files created by vim-clap are stored there.
pub fn project() -> &'static ProjectDirs {
static CELL: OnceLock<ProjectDirs> = OnceLock::new();
CELL.get_or_init(|| {
ProjectDirs::from("org", "vim", "Vim Clap")
.expect("Couldn't create project directory for vim-clap")
})
}
/// Provides access to the standard directories that the operating system uses.
pub fn base() -> &'static BaseDirs {
static CELL: OnceLock<BaseDirs> = OnceLock::new();
CELL.get_or_init(|| BaseDirs::new().expect("Failed to construct BaseDirs"))
}
/// Cache directory for Vim Clap project.
pub fn clap_cache_dir() -> std::io::Result<PathBuf> {
let cache_dir = Self::project().cache_dir();
std::fs::create_dir_all(cache_dir)?;
Ok(cache_dir.to_path_buf())
}
}
|
// 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.
use infer::canonical::{Canonical, Canonicalized, CanonicalizedQueryResult, QueryResult};
use traits::query::Fallible;
use ty::{ParamEnvAnd, Predicate, TyCtxt};
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct ProvePredicate<'tcx> {
pub predicate: Predicate<'tcx>,
}
impl<'tcx> ProvePredicate<'tcx> {
pub fn new(predicate: Predicate<'tcx>) -> Self {
ProvePredicate { predicate }
}
}
impl<'gcx: 'tcx, 'tcx> super::QueryTypeOp<'gcx, 'tcx> for ProvePredicate<'tcx> {
type QueryResult = ();
fn try_fast_path(
_tcx: TyCtxt<'_, 'gcx, 'tcx>,
_key: &ParamEnvAnd<'tcx, Self>,
) -> Option<Self::QueryResult> {
None
}
fn perform_query(
tcx: TyCtxt<'_, 'gcx, 'tcx>,
canonicalized: Canonicalized<'gcx, ParamEnvAnd<'tcx, Self>>,
) -> Fallible<CanonicalizedQueryResult<'gcx, ()>> {
tcx.type_op_prove_predicate(canonicalized)
}
fn shrink_to_tcx_lifetime(
v: &'a CanonicalizedQueryResult<'gcx, ()>,
) -> &'a Canonical<'tcx, QueryResult<'tcx, ()>> {
v
}
}
BraceStructTypeFoldableImpl! {
impl<'tcx> TypeFoldable<'tcx> for ProvePredicate<'tcx> {
predicate,
}
}
BraceStructLiftImpl! {
impl<'a, 'tcx> Lift<'tcx> for ProvePredicate<'a> {
type Lifted = ProvePredicate<'tcx>;
predicate,
}
}
impl_stable_hash_for! {
struct ProvePredicate<'tcx> { predicate }
}
|
#[inline]
pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
debug_assert!(min <= max, "min must be less than or equal to max");
if input < min {
min
} else if input > max {
max
} else {
input
}
}
|
use std::env;
use std::fmt::Write;
use std::fs;
use std::path::Path;
use stark_curve::*;
fn generate_consts(bits: u32) -> Result<String, std::fmt::Error> {
let mut buf = String::with_capacity(10 * 1024 * 1024);
write!(buf, "pub const CURVE_CONSTS_BITS: usize = {bits};\n\n")?;
push_points(&mut buf, "P1", &PEDERSEN_P1, 248, bits)?;
buf.push_str("\n\n\n");
push_points(&mut buf, "P2", &PEDERSEN_P2, 4, bits)?;
buf.push_str("\n\n\n");
push_points(&mut buf, "P3", &PEDERSEN_P3, 248, bits)?;
buf.push_str("\n\n\n");
push_points(&mut buf, "P4", &PEDERSEN_P4, 4, bits)?;
Ok(buf)
}
fn push_points(
buf: &mut String,
name: &str,
base: &ProjectivePoint,
max_bits: u32,
bits: u32,
) -> std::fmt::Result {
let base = AffinePoint::from(base);
let full_chunks = max_bits / bits;
let leftover_bits = max_bits % bits;
let table_size_full = (1 << bits) - 1;
let table_size_leftover = (1 << leftover_bits) - 1;
let len = full_chunks * table_size_full + table_size_leftover;
writeln!(
buf,
"pub const CURVE_CONSTS_{name}: [AffinePoint; {len}] = ["
)?;
let mut bits_left = max_bits;
let mut outer_point = base;
while bits_left > 0 {
let eat_bits = std::cmp::min(bits_left, bits);
let table_size = (1 << eat_bits) - 1;
println!("Processing {eat_bits} bits, remaining: {bits_left}");
// Loop through each possible bit combination except zero
let mut inner_point = outer_point.clone();
for j in 1..(table_size + 1) {
if bits_left < max_bits || j > 1 {
buf.push_str(",\n");
}
push_point(buf, &inner_point)?;
inner_point.add(&outer_point);
}
// Shift outer point #bits times
bits_left -= eat_bits;
for _i in 0..bits {
outer_point.double();
}
}
buf.push_str("\n];");
Ok(())
}
fn push_point(buf: &mut String, p: &AffinePoint) -> std::fmt::Result {
let x = p.x.inner();
let y = p.y.inner();
buf.push_str(" AffinePoint::new(");
buf.push_str("\n [");
write!(buf, "\n {},", x[0])?;
write!(buf, "\n {},", x[1])?;
write!(buf, "\n {},", x[2])?;
write!(buf, "\n {},", x[3])?;
buf.push_str("\n ],");
buf.push_str("\n [");
write!(buf, "\n {},", y[0])?;
write!(buf, "\n {},", y[1])?;
write!(buf, "\n {},", y[2])?;
write!(buf, "\n {},", y[3])?;
buf.push_str("\n ]");
buf.push_str("\n )");
Ok(())
}
fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("curve_consts.rs");
let bits = 4;
let consts = generate_consts(bits).expect("should had been able to format the curve constants");
fs::write(dest_path, consts)
.expect("should had been able to write to $OUT_DIR/curve_consts.rs");
}
|
extern crate regex;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use regex::Regex;
#[derive(PartialEq)]
enum OpType
{
AND,
OR,
LSHIFT,
RSHIFT,
NOT,
}
struct LogicSimulator
{
evaluated:bool,
name:String,
value:u16,
left_identifier:String,
right_identifier:String,
}
impl Default for LogicSimulator {
fn default () -> LogicSimulator
{
LogicSimulator {evaluated : false,
name: String::new(),
value: 0,
left_identifier: String::new(),
right_identifier: String::new()
}
}
}
fn parse_line(in_str:&str)
{
let number_regex = Regex::new(r"[0-9]+").unwrap();
let tokens:Vec<&str> = in_str.split(' ').collect();
if number_regex.is_match(tokens[0])
{
}
else
{
}
}
fn main()
{
let f = File::open("input.txt").unwrap();
let reader = BufReader::new(f);
// Iterate over lines
for line in reader.lines()
{
let unwrapped_line = line.unwrap();
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn AddDllDirectory(newdirectory: super::super::Foundation::PWSTR) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn BeginUpdateResourceA(pfilename: super::super::Foundation::PSTR, bdeleteexistingresources: super::super::Foundation::BOOL) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn BeginUpdateResourceW(pfilename: super::super::Foundation::PWSTR, bdeleteexistingresources: super::super::Foundation::BOOL) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn DisableThreadLibraryCalls(hlibmodule: super::super::Foundation::HINSTANCE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EndUpdateResourceA(hupdate: super::super::Foundation::HANDLE, fdiscard: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EndUpdateResourceW(hupdate: super::super::Foundation::HANDLE, fdiscard: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceLanguagesA(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lpname: super::super::Foundation::PSTR, lpenumfunc: ENUMRESLANGPROCA, lparam: isize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceLanguagesExA(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lpname: super::super::Foundation::PSTR, lpenumfunc: ENUMRESLANGPROCA, lparam: isize, dwflags: u32, langid: u16) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceLanguagesExW(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lpname: super::super::Foundation::PWSTR, lpenumfunc: ENUMRESLANGPROCW, lparam: isize, dwflags: u32, langid: u16) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceLanguagesW(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lpname: super::super::Foundation::PWSTR, lpenumfunc: ENUMRESLANGPROCW, lparam: isize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceNamesA(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lpenumfunc: ENUMRESNAMEPROCA, lparam: isize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceNamesExA(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lpenumfunc: ENUMRESNAMEPROCA, lparam: isize, dwflags: u32, langid: u16) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceNamesExW(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lpenumfunc: ENUMRESNAMEPROCW, lparam: isize, dwflags: u32, langid: u16) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceNamesW(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lpenumfunc: ENUMRESNAMEPROCW, lparam: isize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceTypesA(hmodule: super::super::Foundation::HINSTANCE, lpenumfunc: ENUMRESTYPEPROCA, lparam: isize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceTypesExA(hmodule: super::super::Foundation::HINSTANCE, lpenumfunc: ENUMRESTYPEPROCA, lparam: isize, dwflags: u32, langid: u16) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceTypesExW(hmodule: super::super::Foundation::HINSTANCE, lpenumfunc: ENUMRESTYPEPROCW, lparam: isize, dwflags: u32, langid: u16) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn EnumResourceTypesW(hmodule: super::super::Foundation::HINSTANCE, lpenumfunc: ENUMRESTYPEPROCW, lparam: isize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindResourceA(hmodule: super::super::Foundation::HINSTANCE, lpname: super::super::Foundation::PSTR, lptype: super::super::Foundation::PSTR) -> super::super::Foundation::HRSRC;
#[cfg(feature = "Win32_Foundation")]
pub fn FindResourceExA(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lpname: super::super::Foundation::PSTR, wlanguage: u16) -> super::super::Foundation::HRSRC;
#[cfg(feature = "Win32_Foundation")]
pub fn FindResourceExW(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lpname: super::super::Foundation::PWSTR, wlanguage: u16) -> super::super::Foundation::HRSRC;
#[cfg(feature = "Win32_Foundation")]
pub fn FindResourceW(hmodule: super::super::Foundation::HINSTANCE, lpname: super::super::Foundation::PWSTR, lptype: super::super::Foundation::PWSTR) -> super::super::Foundation::HRSRC;
#[cfg(feature = "Win32_Foundation")]
pub fn FreeLibrary(hlibmodule: super::super::Foundation::HINSTANCE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FreeLibraryAndExitThread(hlibmodule: super::super::Foundation::HINSTANCE, dwexitcode: u32);
#[cfg(feature = "Win32_Foundation")]
pub fn FreeResource(hresdata: isize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDllDirectoryA(nbufferlength: u32, lpbuffer: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDllDirectoryW(nbufferlength: u32, lpbuffer: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetModuleFileNameA(hmodule: super::super::Foundation::HINSTANCE, lpfilename: super::super::Foundation::PSTR, nsize: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetModuleFileNameW(hmodule: super::super::Foundation::HINSTANCE, lpfilename: super::super::Foundation::PWSTR, nsize: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetModuleHandleA(lpmodulename: super::super::Foundation::PSTR) -> super::super::Foundation::HINSTANCE;
#[cfg(feature = "Win32_Foundation")]
pub fn GetModuleHandleExA(dwflags: u32, lpmodulename: super::super::Foundation::PSTR, phmodule: *mut super::super::Foundation::HINSTANCE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetModuleHandleExW(dwflags: u32, lpmodulename: super::super::Foundation::PWSTR, phmodule: *mut super::super::Foundation::HINSTANCE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetModuleHandleW(lpmodulename: super::super::Foundation::PWSTR) -> super::super::Foundation::HINSTANCE;
#[cfg(feature = "Win32_Foundation")]
pub fn GetProcAddress(hmodule: super::super::Foundation::HINSTANCE, lpprocname: super::super::Foundation::PSTR) -> super::super::Foundation::FARPROC;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadLibraryA(lplibfilename: super::super::Foundation::PSTR) -> super::super::Foundation::HINSTANCE;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadLibraryExA(lplibfilename: super::super::Foundation::PSTR, hfile: super::super::Foundation::HANDLE, dwflags: LOAD_LIBRARY_FLAGS) -> super::super::Foundation::HINSTANCE;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadLibraryExW(lplibfilename: super::super::Foundation::PWSTR, hfile: super::super::Foundation::HANDLE, dwflags: LOAD_LIBRARY_FLAGS) -> super::super::Foundation::HINSTANCE;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadLibraryW(lplibfilename: super::super::Foundation::PWSTR) -> super::super::Foundation::HINSTANCE;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadModule(lpmodulename: super::super::Foundation::PSTR, lpparameterblock: *const ::core::ffi::c_void) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadPackagedLibrary(lpwlibfilename: super::super::Foundation::PWSTR, reserved: u32) -> super::super::Foundation::HINSTANCE;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadResource(hmodule: super::super::Foundation::HINSTANCE, hresinfo: super::super::Foundation::HRSRC) -> isize;
pub fn LockResource(hresdata: isize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn RemoveDllDirectory(cookie: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetDefaultDllDirectories(directoryflags: LOAD_LIBRARY_FLAGS) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetDllDirectoryA(lppathname: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetDllDirectoryW(lppathname: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SizeofResource(hmodule: super::super::Foundation::HINSTANCE, hresinfo: super::super::Foundation::HRSRC) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UpdateResourceA(hupdate: super::super::Foundation::HANDLE, lptype: super::super::Foundation::PSTR, lpname: super::super::Foundation::PSTR, wlanguage: u16, lpdata: *const ::core::ffi::c_void, cb: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn UpdateResourceW(hupdate: super::super::Foundation::HANDLE, lptype: super::super::Foundation::PWSTR, lpname: super::super::Foundation::PWSTR, wlanguage: u16, lpdata: *const ::core::ffi::c_void, cb: u32) -> super::super::Foundation::BOOL;
}
pub const CURRENT_IMPORT_REDIRECTION_VERSION: u32 = 1u32;
#[cfg(feature = "Win32_Foundation")]
pub type ENUMRESLANGPROCA = ::core::option::Option<unsafe extern "system" fn(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lpname: super::super::Foundation::PSTR, wlanguage: u16, lparam: isize) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type ENUMRESLANGPROCW = ::core::option::Option<unsafe extern "system" fn(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lpname: super::super::Foundation::PWSTR, wlanguage: u16, lparam: isize) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type ENUMRESNAMEPROCA = ::core::option::Option<unsafe extern "system" fn(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lpname: super::super::Foundation::PSTR, lparam: isize) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type ENUMRESNAMEPROCW = ::core::option::Option<unsafe extern "system" fn(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lpname: super::super::Foundation::PWSTR, lparam: isize) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type ENUMRESTYPEPROCA = ::core::option::Option<unsafe extern "system" fn(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PSTR, lparam: isize) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type ENUMRESTYPEPROCW = ::core::option::Option<unsafe extern "system" fn(hmodule: super::super::Foundation::HINSTANCE, lptype: super::super::Foundation::PWSTR, lparam: isize) -> super::super::Foundation::BOOL>;
#[repr(C)]
pub struct ENUMUILANG {
pub NumOfEnumUILang: u32,
pub SizeOfEnumUIBuffer: u32,
pub pEnumUIBuffer: *mut u16,
}
impl ::core::marker::Copy for ENUMUILANG {}
impl ::core::clone::Clone for ENUMUILANG {
fn clone(&self) -> Self {
*self
}
}
pub const FIND_RESOURCE_DIRECTORY_LANGUAGES: u32 = 1024u32;
pub const FIND_RESOURCE_DIRECTORY_NAMES: u32 = 512u32;
pub const FIND_RESOURCE_DIRECTORY_TYPES: u32 = 256u32;
pub const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 4u32;
pub const GET_MODULE_HANDLE_EX_FLAG_PIN: u32 = 1u32;
pub const GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT: u32 = 2u32;
pub type LOAD_LIBRARY_FLAGS = u32;
pub const DONT_RESOLVE_DLL_REFERENCES: LOAD_LIBRARY_FLAGS = 1u32;
pub const LOAD_LIBRARY_AS_DATAFILE: LOAD_LIBRARY_FLAGS = 2u32;
pub const LOAD_WITH_ALTERED_SEARCH_PATH: LOAD_LIBRARY_FLAGS = 8u32;
pub const LOAD_IGNORE_CODE_AUTHZ_LEVEL: LOAD_LIBRARY_FLAGS = 16u32;
pub const LOAD_LIBRARY_AS_IMAGE_RESOURCE: LOAD_LIBRARY_FLAGS = 32u32;
pub const LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE: LOAD_LIBRARY_FLAGS = 64u32;
pub const LOAD_LIBRARY_REQUIRE_SIGNED_TARGET: LOAD_LIBRARY_FLAGS = 128u32;
pub const LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR: LOAD_LIBRARY_FLAGS = 256u32;
pub const LOAD_LIBRARY_SEARCH_APPLICATION_DIR: LOAD_LIBRARY_FLAGS = 512u32;
pub const LOAD_LIBRARY_SEARCH_USER_DIRS: LOAD_LIBRARY_FLAGS = 1024u32;
pub const LOAD_LIBRARY_SEARCH_SYSTEM32: LOAD_LIBRARY_FLAGS = 2048u32;
pub const LOAD_LIBRARY_SEARCH_DEFAULT_DIRS: LOAD_LIBRARY_FLAGS = 4096u32;
pub const LOAD_LIBRARY_SAFE_CURRENT_DIRS: LOAD_LIBRARY_FLAGS = 8192u32;
pub const LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER: LOAD_LIBRARY_FLAGS = 16384u32;
pub const LOAD_LIBRARY_OS_INTEGRITY_CONTINUITY: u32 = 32768u32;
#[cfg(feature = "Win32_Foundation")]
pub type PGET_MODULE_HANDLE_EXA = ::core::option::Option<unsafe extern "system" fn(dwflags: u32, lpmodulename: super::super::Foundation::PSTR, phmodule: *mut super::super::Foundation::HINSTANCE) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type PGET_MODULE_HANDLE_EXW = ::core::option::Option<unsafe extern "system" fn(dwflags: u32, lpmodulename: super::super::Foundation::PWSTR, phmodule: *mut super::super::Foundation::HINSTANCE) -> super::super::Foundation::BOOL>;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct REDIRECTION_DESCRIPTOR {
pub Version: u32,
pub FunctionCount: u32,
pub Redirections: *mut REDIRECTION_FUNCTION_DESCRIPTOR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for REDIRECTION_DESCRIPTOR {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for REDIRECTION_DESCRIPTOR {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct REDIRECTION_FUNCTION_DESCRIPTOR {
pub DllName: super::super::Foundation::PSTR,
pub FunctionName: super::super::Foundation::PSTR,
pub RedirectionTarget: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for REDIRECTION_FUNCTION_DESCRIPTOR {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for REDIRECTION_FUNCTION_DESCRIPTOR {
fn clone(&self) -> Self {
*self
}
}
pub const RESOURCE_ENUM_LN: u32 = 1u32;
pub const RESOURCE_ENUM_MODULE_EXACT: u32 = 16u32;
pub const RESOURCE_ENUM_MUI: u32 = 2u32;
pub const RESOURCE_ENUM_MUI_SYSTEM: u32 = 4u32;
pub const RESOURCE_ENUM_VALIDATE: u32 = 8u32;
pub const SUPPORT_LANG_NUMBER: u32 = 32u32;
|
use crypto::sha2::Sha256;
use crypto::digest::Digest;
use std::ops::{Index, Range, RangeFull};
use std::fmt::{Debug, Display, Formatter};
use std::io::{Write};
use serde::{ser, de};
use common::ValidityErr;
use rustc_serialize::hex::FromHex;
#[derive(RustcEncodable, RustcDecodable, Copy, Clone, Hash,
Eq, PartialEq, Ord, PartialOrd)]
pub struct DoubleSha256Hash([u8; 32]);
impl DoubleSha256Hash {
pub fn blank() -> DoubleSha256Hash {
DoubleSha256Hash([0u8; 32])
}
pub fn hash(data: &[u8]) -> DoubleSha256Hash {
let DoubleSha256Hash(mut buf) = DoubleSha256Hash::blank();
let mut sha256 = Sha256::new();
sha256.input(data);
sha256.result(&mut buf);
sha256.reset();
sha256.input(&buf);
sha256.result(&mut buf);
DoubleSha256Hash(buf)
}
/// You should use this function for any string hashes that must
/// be reproduced in client-side JavaScript; using the other method
/// that accepts a slice makes the client-side code needlessly complex.
pub fn hash_string(string: &str) -> DoubleSha256Hash {
let DoubleSha256Hash(mut buf) = DoubleSha256Hash::blank();
let mut sha256 = Sha256::new();
sha256.input_str(string);
let string2 = sha256.result_str();
sha256.reset();
sha256.input_str(&string2);
sha256.result(&mut buf);
DoubleSha256Hash(buf)
}
pub fn from_string(hash_str: &str) -> Result<DoubleSha256Hash, ValidityErr> {
let hash_vec = match hash_str.from_hex() {
Ok(v) => v,
Err(_) => return Err(ValidityErr::DoubleSha256HashExpected)
};
if hash_vec.len() != 32 {
return Err(ValidityErr::DoubleSha256HashExpected);
}
let mut hash_arr = [0u8; 32];
for i in 0..hash_vec.len() {
hash_arr[i] = hash_vec[i];
}
Ok(DoubleSha256Hash(hash_arr))
}
pub fn from_slice(slice: &[u8]) -> DoubleSha256Hash {
let DoubleSha256Hash(mut buf) = DoubleSha256Hash::blank();
assert_eq!(slice.len(), buf.len());
for i in 0..slice.len() {
buf[i] = slice[i]
}
DoubleSha256Hash(buf)
}
pub fn genesis_block_parent_hash() -> DoubleSha256Hash {
DoubleSha256Hash::from_slice(&[0u8; 32][..])
}
}
impl Debug for DoubleSha256Hash {
fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
let &DoubleSha256Hash(data) = self;
for b in data.iter() {
try!(write!(f, "{:02x}", b));
}
Ok(())
}
}
impl ser::Serialize for DoubleSha256Hash {
fn serialize<S: ser::Serializer>(&self, s: &mut S)
-> Result<(), S::Error> {
s.visit_str(&format!("{}", self)[..])
}
}
impl de::Deserialize for DoubleSha256Hash {
fn deserialize<D: de::Deserializer>(d: &mut D)
-> Result<DoubleSha256Hash, D::Error> {
d.visit_str(DoubleSha256HashVisitor)
}
}
struct DoubleSha256HashVisitor;
impl de::Visitor for DoubleSha256HashVisitor {
type Value = DoubleSha256Hash;
fn visit_str<E: de::Error>(&mut self, value: &str)
-> Result<DoubleSha256Hash, E> {
match DoubleSha256Hash::from_string(value) {
Ok(hash) => Ok(hash),
Err(_) => Err(de::Error::syntax(&format!(
"The visited string {} could not be deserialized \
into a DoubleSha256Hash.", value)[..]))
}
}
}
impl Display for DoubleSha256Hash {
fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
let &DoubleSha256Hash(data) = self;
for b in data.iter() {
try!(write!(f, "{:02x}", b));
}
Ok(())
}
}
impl Index<usize> for DoubleSha256Hash {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
let &DoubleSha256Hash(ref data) = self;
&data[index]
}
}
impl Index<Range<usize>> for DoubleSha256Hash {
type Output = [u8];
fn index(&self, index: Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl Index<RangeFull> for DoubleSha256Hash {
type Output = [u8];
fn index(&self, _: RangeFull) -> &[u8] {
&self.0[..]
}
}
|
/*
* @lc app=leetcode.cn id=49 lang=rust
*
* [49] 字母异位词分组
*
* https://leetcode-cn.com/problems/group-anagrams/description/
*
* algorithms
* Medium (54.26%)
* Total Accepted: 11.8K
* Total Submissions: 21.7K
* Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
*
* 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
*
* 示例:
*
* 输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
* 输出:
* [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
*
* 说明:
*
*
* 所有输入均为小写字母。
* 不考虑答案输出的顺序。
*
*
*/
use std::collections::HashMap;
impl Solution {
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
strs.into_iter()
.fold(HashMap::new(), |mut map, s| {
let hash = s.as_bytes().iter().fold([0; 26], |mut hash, &c| {
hash[(c - b'a') as usize] += 1u8;
hash
});
map.entry(hash).or_insert(vec![]).push(s);
map
})
.into_iter()
.map(|e| e.1)
.collect()
}
}
fn main() {
let v: Vec<String> = vec!["eat", "tea", "tan", "ate", "nat", "bat"]
.iter()
.map(|it| it.to_string())
.collect();
let res = Solution::group_anagrams(v);
res.iter().for_each(|it| {
println!("{:?}", it);
})
}
struct Solution {}
|
pub fn example3()
{
xprintln!("5 + 4 = {}", 5 + 4);
xprintln!("5 - 4 = {}", 5 - 4);
xprintln!("5 * 4 = {}", 5 * 4);
xprintln!("5 / 4 = {}", 5 / 4);
xprintln!("5 % 4 = {}", 5 % 4);
let neg_4 = -4i32;
xprintln!("abs(-4) = {}", neg_4.abs());
xprintln!("4 ^ 6 = {}", 4i32.pow(6));
xprintln!("sqrt 9 = {}", 9f64.sqrt());
xprintln!("cbrt 9 = {}", 27f64.cbrt());
xprintln!("Round 1.45 = {}", 1.45f64.round());
xprintln!("Floor 1.45 = {}", 1.45f64.floor());
xprintln!("Ceiling 1.45 = {}", 1.45f64.ceil());
xprintln!("e ^ 2 = {}", 2f64.exp());
xprintln!("log(2) = {}", 2f64.ln());
xprintln!("log10(2) = {}", 2f64.log10());
xprintln!("90 to Radians = {}", 90f64.to_radians());
xprintln!("PI to Degrees = {}", 3.14f64.to_degrees());
xprintln!("Max 4, 5 = {}", 4f64.max(5f64));
xprintln!("Min 4, 5 = {}", 4f64.min(5f64));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.