text stringlengths 8 4.13M |
|---|
use super::{Dispatch, NodeId, NodeStatus, ShardId, State};
use crate::{NodeQueue, NodeQueueEntry, NodeThreadPool, QueryEstimate, QueryId};
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
use eyre::{Result, WrapErr};
use ndarray::{Array1, Array2, ArrayView1, ArrayView2};
use optimization::Optimizer;
use rand_chacha::{rand_core::SeedableRng, ChaChaRng};
use rand_distr::weighted_alias::WeightedAliasIndex;
use rand_distr::Distribution;
use simrs::{Key, QueueId};
#[derive(Debug)]
struct Weight {
value: f32,
multiplier: f32,
}
#[allow(clippy::float_cmp)] // `multiplier` is always either 0.0 or 1.0
impl Weight {
fn enable(&mut self) -> bool {
if self.multiplier == 1.0 {
false
} else {
self.multiplier = 1.0;
true
}
}
fn disable(&mut self) -> bool {
if self.multiplier == 0.0 {
false
} else {
self.multiplier = 0.0;
true
}
}
fn value(&self) -> f32 {
self.multiplier * self.value
}
}
#[derive(Debug, PartialEq)]
struct WeightMatrix {
weights: Array2<f32>,
nodes: Array1<f32>,
}
impl WeightMatrix {
fn new(weights: Array2<f32>) -> Self {
let nodes = Array1::from_elem(weights.nrows(), 1.0);
Self { weights, nodes }
}
fn weights(&self) -> Array2<f32> {
let mut weights = self.weights.t().dot(&Array2::from_diag(&self.nodes));
weights.swap_axes(0, 1);
weights
}
fn weights_scaled(&self, nodes: ArrayView1<f32>) -> Array2<f32> {
let mut weights = self.weights.t().dot(&Array2::from_diag(&nodes));
weights.swap_axes(0, 1);
weights
}
}
/// Dispatches according to given probabilities.
pub struct ProbabilisticDispatcher {
shards: Vec<WeightedAliasIndex<f32>>,
weights: Vec<Vec<Weight>>,
num_nodes: usize,
num_shards: usize,
rng: RefCell<ChaChaRng>,
weight_matrix: Option<WeightMatrix>,
load: Option<Load>,
recompute_delay: Duration,
}
pub struct Load {
pub(crate) queues: Vec<QueueId<NodeQueue<NodeQueueEntry>>>,
pub(crate) estimates: Rc<Vec<QueryEstimate>>,
pub(crate) thread_pools: Vec<Key<NodeThreadPool>>,
}
impl Load {
fn query_time(&self, query_id: QueryId, shard_id: ShardId) -> u64 {
self.estimates
.get(query_id.0 - 1)
.expect("query out of bounds")
.shard_estimate(shard_id)
}
fn queue_lengths<'a>(&'a self, state: &'a State) -> Vec<usize> {
self.queues
.iter()
.map(|queue_id| state.len(*queue_id))
.collect()
}
fn machine_weights(&self, state: &State) -> Array1<f32> {
self.machine_weights_with(state, NodeId::from(0), 0)
}
fn machine_weights_with(&self, state: &State, node: NodeId, time: u64) -> Array1<f32> {
let running = self.thread_pools.iter().map(|pool| {
state
.get(*pool)
.expect("unknown thread pool ID")
.running_threads()
.iter()
.map(|t| t.estimated.as_micros())
.sum::<u128>() as u64
});
let waiting = self.queues.iter().map(|queue| {
state
.queue(*queue)
.iter()
.map(|msg| self.query_time(msg.request.query_id(), msg.request.shard_id()))
.sum::<u64>()
});
let mut weights: Array1<f32> = running.zip(waiting).map(|(r, w)| (r + w) as f32).collect();
weights[node.0] += time as f32;
let weight_sum = weights.sum();
if weight_sum == 0.0 {
weights
} else {
weights / weight_sum
}
}
}
fn format_weights(weights: &[Weight]) -> String {
use itertools::Itertools;
format!(
"{}",
weights.iter().map(|w| w.value * w.multiplier).format(",")
)
}
fn calc_distributions(
weights: &[Vec<Weight>],
) -> Result<Vec<WeightedAliasIndex<f32>>, rand_distr::WeightedError> {
weights
.iter()
.map(|weights| WeightedAliasIndex::new(weights.iter().map(Weight::value).collect()))
.collect()
}
fn probabilities_to_weights(probabilities: ArrayView2<'_, f32>) -> Vec<Vec<Weight>> {
probabilities
.gencolumns()
.into_iter()
.map(|probabilities| {
probabilities
.into_iter()
.copied()
.map(|w| Weight {
value: w,
multiplier: 1.0,
})
.collect::<Vec<Weight>>()
})
.collect()
}
impl ProbabilisticDispatcher {
/// Constructs a new probabilistic dispatcher from the given dispatch matrix.
///
/// # Errors
///
/// Returns an error if probabilities are invalid and cannot be translated into a distribution.
pub fn new(probabilities: ArrayView2<'_, f32>) -> Result<Self> {
Self::with_rng(probabilities, ChaChaRng::from_entropy())
}
/// Constructs a new probabilistic dispatcher from the given dispatch matrix,
/// and initializes the internal PRNG from the given seed.
///
/// # Errors
///
/// Returns an error if probabilities are invalid and cannot be translated into a distribution.
pub fn with_seed(probabilities: ArrayView2<'_, f32>, seed: u64) -> Result<Self> {
Self::with_rng(probabilities, ChaChaRng::seed_from_u64(seed))
}
/// Constructs a new probabilistic dispatcher from the given dispatch matrix,
/// and initializes the internal PRNG from the given seed.
///
/// # Errors
///
/// Returns an error if probabilities are invalid and cannot be translated into a distribution.
pub fn with_rng(probabilities: ArrayView2<'_, f32>, rng: ChaChaRng) -> Result<Self> {
let num_nodes = probabilities.nrows();
let num_shards = probabilities.ncols();
let weights: Vec<_> = probabilities_to_weights(probabilities);
debug_assert_eq!(weights.len(), num_shards);
for w in &weights {
debug_assert_eq!(w.len(), num_nodes);
}
log::debug!(
"Created probabilistic dispatcher with {} shards and {} nodes",
num_shards,
num_nodes
);
Ok(Self {
num_nodes,
num_shards,
rng: RefCell::new(rng),
shards: calc_distributions(&weights)?,
weights,
weight_matrix: None,
load: None,
recompute_delay: Duration::from_millis(10),
})
}
/// Constructs a new dispatcher that optimizes probabilities based on the given weight matrix,
/// and then repeats the optimization process each time there is a change indicated, such as
/// disabling or enabling a node.
///
/// # Errors
///
/// Returns an error if probabilities are invalid and cannot be translated into a distribution.
pub fn adaptive(weight_matrix: Array2<f32>) -> Result<Self> {
Self::adaptive_with_rng(weight_matrix, ChaChaRng::from_entropy())
}
/// Constructs a new adaptive dispatcher with a random seed. See [`Self::adaptive`].
///
/// # Errors
///
/// Returns an error if probabilities are invalid and cannot be translated into a distribution.
pub fn adaptive_with_seed(weight_matrix: Array2<f32>, seed: u64) -> Result<Self> {
Self::adaptive_with_rng(weight_matrix, ChaChaRng::seed_from_u64(seed))
}
/// Constructs a new adaptive dispatcher with a PRNG. See [`Self::adaptive`].
///
/// # Errors
///
/// Returns an error if probabilities are invalid and cannot be translated into a distribution.
pub fn adaptive_with_rng(weight_matrix: Array2<f32>, rng: ChaChaRng) -> Result<Self> {
let probabilities = optimization::LpOptimizer.optimize(weight_matrix.view());
let mut dispatcher = Self::with_rng(probabilities.view(), rng)?;
dispatcher.weight_matrix = Some(WeightMatrix::new(weight_matrix));
Ok(dispatcher)
}
pub fn with_recompute_delay(self, delay: Duration) -> Self {
Self {
recompute_delay: delay,
..self
}
}
pub fn with_load_info(self, load: Load) -> Self {
Self {
load: Some(load),
..self
}
}
fn change_weight_status<F, G>(
&mut self,
node_id: NodeId,
f: F,
cond: G,
) -> Result<bool, rand_distr::WeightedError>
where
F: Fn(&mut Weight) -> bool,
G: Fn(f32) -> bool,
{
// if let Some(weight_matrix) = self.weight_matrix.as_mut() {
// let node = &mut weight_matrix.nodes[node_id.0];
// if cond(*node) {
// *node = 1.0 - *node;
// let probabilities =
// optimization::LpOptimizer.optimize(weight_matrix.weights().view());
// self.weights = probabilities_to_weights(probabilities.view());
// self.shards = calc_distributions(&self.weights)?;
// debug_assert_eq!(self.weights.len(), self.num_shards);
// debug_assert_eq!(self.shards.len(), self.num_shards);
// Ok(true)
// } else {
// Ok(false)
// }
// } else {
let num_nodes = self.num_nodes;
let changed = self.weights.iter_mut().any(|weights| {
debug_assert_eq!(weights.len(), num_nodes);
f(&mut weights[node_id.0])
});
if changed {
self.shards = calc_distributions(&self.weights)?;
debug_assert_eq!(self.weights.len(), self.num_shards);
debug_assert_eq!(self.shards.len(), self.num_shards);
}
Ok(changed)
// }
}
fn select_node_from(&self, distr: &WeightedAliasIndex<f32>) -> NodeId {
let mut rng = self.rng.borrow_mut();
NodeId::from(distr.sample(&mut *rng))
}
pub(crate) fn select_node(&self, shard_id: ShardId) -> NodeId {
self.select_node_from(self.shards.get(shard_id.0).expect("shard ID out of bounds"))
}
}
impl Dispatch for ProbabilisticDispatcher {
fn dispatch(
&self,
query_id: QueryId,
shards: &[ShardId],
state: &State,
) -> Vec<(ShardId, NodeId)> {
if let Some(load) = &self.load {
// let shard_times = (0..self.num_shards)
// .map(|shard_id| load.query_time(query_id, ShardId(shard_id)))
// .collect::<Vec<_>>();
// let min_time = shard_times.iter().min().copied().unwrap_or(0) as f32;
// let corrections: Vec<_> = if min_time == 0.0 {
// std::iter::repeat(1.0).take(self.num_shards).collect()
// } else {
// shard_times.iter().map(|&t| t as f32 / min_time).collect()
// };
// let mut machine_weights = load.machine_weights(state);
// let max_machine_weight = *machine_weights
// .iter()
// .max_by_key(|f| ordered_float::OrderedFloat(**f))
// .unwrap();
// let queue_lengths = load.queue_lengths(state);
let machine_weights = load.machine_weights(state);
// .into_iter()
// .copied()
// .enumerate()
// .collect::<Vec<_>>();
shards
.iter()
.map(|&s| {
let mut weights = self
.weights
.get(s.0)
.expect("shard ID out of bounds")
.iter()
.map(Weight::value)
.zip(&machine_weights)
.enumerate()
.filter_map(|(n, (w, mw))| if w > 0.0 { Some((n, *mw)) } else { None })
.collect::<Vec<_>>();
weights.sort_by_key(|(_, w)| ordered_float::OrderedFloat(*w));
let min = weights.first().map(|(_, w)| *w).unwrap_or(0.0);
let max = weights.last().map(|(_, w)| *w).unwrap_or(0.0);
if max - min > 0.5 {
(s, NodeId(weights[0].0))
} else {
(s, self.select_node(s))
}
// let node = self.select_node(s);
// let current_estimate = load.query_time(query_id, s);
// let machine_weights = load.machine_weights_with(state, node, current_estimate);
// let mut weights = self
// .weights
// .get(s.0)
// .expect("shard ID out of bounds")
// .iter()
// .map(Weight::value)
// .zip(&machine_weights)
// .enumerate()
// .filter_map(|(n, (w, mw))| if w > 0.0 { Some((n, *mw)) } else { None })
// .collect::<Vec<_>>();
// weights.sort_by_key(|(n, w)| ordered_float::OrderedFloat(*w));
// let min = weights.first().map(|(_, w)| *w).unwrap_or(0.0);
// let max = weights.last().map(|(_, w)| *w).unwrap_or(0.0);
// if max - min > 0.25 {
// (s, weights.iter().min().map(|()|).unwrap())
// } else {
// (s, self.select_node())
// }
//let weights = self
// .weights
// .get(s.0)
// .expect("shard ID out of bounds")
// .iter()
// .map(Weight::value)
// // .zip(&machine_weights)
// // .map(|(a, b)| max_machine_weight - *b + 1.0)
// // .zip(&queue_lengths)
// // .map(|(a, b)| a / (5.0 * *b as f32 + 1.0))
// .zip(&queue_lengths)
// .map(|(a, b)| a / (*b as f32 + 1.0))
// // .zip(&corrections)
// // .map(|(a, b)| a / b)
// .collect::<Vec<_>>();
//let distr = WeightedAliasIndex::new(weights.clone()).unwrap_or_else(|_| {
// panic!(
// "unable to calculate node weight distribution: {:?}\n{:?}",
// weights, corrections
// )
//});
// (s, self.select_node_from(&distr))
})
.collect()
} else {
shards.iter().map(|&s| (s, self.select_node(s))).collect()
}
}
fn num_nodes(&self) -> usize {
self.num_nodes
}
fn num_shards(&self) -> usize {
self.num_shards
}
#[allow(clippy::float_cmp)] // n is always either 0.0 or 1.0
fn disable_node(&mut self, node_id: NodeId) -> Result<bool> {
self.change_weight_status(node_id, Weight::disable, |n| n == 1.0)
.wrap_err_with(|| {
format!(
"unable to disable node {} (#nodes: {}; #shards: {}) with the following weights: {}",
node_id,
self.num_nodes(),
self.num_shards(),
format_weights(&self.weights[node_id.0]),
)
})
}
fn enable_node(&mut self, node_id: NodeId) -> bool {
let msg = "unable to enable node";
self.change_weight_status(node_id, Weight::enable, |n| n == 0.0)
.wrap_err(msg)
.unwrap_or_else(|e| {
log::error!("{:#}", e);
panic!("{}", msg);
})
}
fn recompute(&mut self, node_statuses: &[Key<NodeStatus>], state: &State) {
if let Some(weight_matrix) = self.weight_matrix.as_mut() {
weight_matrix.nodes = node_statuses
.iter()
.copied()
.map(|key| match state.get(key).expect("missing node status") {
NodeStatus::Healthy => 1.0,
NodeStatus::Injured(i) => *i,
NodeStatus::Unresponsive => 0.0,
})
.collect();
let probabilities = optimization::LpOptimizer.optimize(weight_matrix.weights().view());
self.weights = probabilities_to_weights(probabilities.view());
self.shards = calc_distributions(&self.weights)
.unwrap_or_else(|e| panic!("invalid distribution: {}", e));
}
}
fn recompute_delay(&self) -> Duration {
self.recompute_delay
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
#[ignore = "Logic has changed but might come back."]
fn test_probabilistic_dispatcher() -> Result<()> {
let weight_matrix = ndarray::arr2(&[[0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5]]);
let mut dispatcher = ProbabilisticDispatcher::adaptive(weight_matrix.clone())?;
assert_eq!(
weight_matrix,
dispatcher.weight_matrix.as_ref().unwrap().weights()
);
assert!(dispatcher.disable_node(NodeId::from(0))?);
assert_eq!(
ndarray::arr2(&[[0.0, 0.0, 0.0], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5]]),
dispatcher.weight_matrix.as_ref().unwrap().weights()
);
assert!(dispatcher.enable_node(NodeId::from(0)));
assert_eq!(
weight_matrix,
dispatcher.weight_matrix.as_ref().unwrap().weights()
);
Ok(())
}
}
|
use std::convert::TryFrom;
use anyhow::Result;
use chrono::Duration;
use futures::future::join_all;
use log::info;
use structopt::StructOpt;
use tokio::task;
use crate::parse::{Response, Ticker};
mod parse;
#[derive(StructOpt, Debug)]
struct Cli {
pub tickers: Vec<String>,
/// Json output
#[structopt(short, long)]
pub json: bool,
/// Calculate daily change
#[structopt(long)]
pub dy: bool,
/// Calculate weekly change
#[structopt(long)]
pub wk: bool,
/// Calculate monthly change
#[structopt(long)]
pub mo: bool,
/// Calculate yearly change
#[structopt(long)]
pub yr: bool,
}
#[tokio::main]
async fn main() {
env_logger::init();
let args: Cli = Cli::from_args();
let tickers = join_all(
args.tickers
.iter()
.cloned()
.map(|ticker| task::spawn(get_ticker(ticker))),
)
.await
.into_iter()
.map(|res| -> Result<Ticker> { Ok(Ticker::try_from(res??)?) })
.collect::<Result<Vec<_>>>();
print(&args, tickers);
}
fn calc_url(ticker: &str) -> reqwest::Url {
let now = chrono::offset::Utc::now();
let year_ago = now - Duration::days(365);
let url = format!(
"https://query1.finance.yahoo.com/v8/finance/chart/{}?formatted=true\
&lang=en-US®ion=US&includeAdjustedClose=true&interval=1wk&period1={}\
&period2={}&events=div%7Csplit&useYfid=true",
ticker,
year_ago.timestamp(),
now.timestamp()
);
reqwest::Url::parse(&url).unwrap()
}
async fn get_ticker(ticker: String) -> Result<Response> {
let response = reqwest::get(calc_url(&ticker)).await?;
info!("Requesting ticker {}", &ticker);
let resp: Response = response.json().await?;
Ok(resp)
}
fn print(args: &Cli, ticker: Result<Vec<Ticker>>) {
match ticker {
Ok(t) => {
if args.json {
print_json(t);
} else {
t.into_iter().for_each(|x| print_ticker(args, x));
}
}
Err(e) => eprintln!("Error: {}", e),
}
}
fn print_json(tickers: Vec<Ticker>) {
match serde_json::to_string_pretty(&tickers) {
Ok(t) => println!("{}", t),
Err(e) => eprintln!("Error: {}", e),
}
}
fn print_ticker(args: &Cli, ticker: Ticker) {
let mut print = format!("{} {}", ticker.symbol, ticker.value);
if args.dy {
print.push_str(&format!(" {:.3}%", ticker.daily_change))
}
if args.wk {
print.push_str(&format!(" {:.3}%", ticker.wk_change))
}
if args.mo {
print.push_str(&format!(" {:.3}%", ticker.mo_change))
}
if args.yr {
print.push_str(&format!(" {:.3}%", ticker.yr_change))
}
println!("{}", print);
}
|
#![doc(hidden)]
use super::{DefaultFilter, Fetch, IntoIndexableIter, IntoView, ReadOnly, ReadOnlyFetch, View};
use crate::internals::{
entity::Entity,
iter::indexed::IndexedIter,
permissions::Permissions,
query::{
filter::{any::Any, passthrough::Passthrough, EntityFilterTuple},
QueryResult,
},
storage::{
archetype::{Archetype, ArchetypeIndex},
component::{Component, ComponentTypeId},
Components,
},
subworld::ComponentAccess,
};
unsafe impl ReadOnly for Entity {}
impl DefaultFilter for Entity {
type Filter = EntityFilterTuple<Any, Passthrough>;
}
impl IntoView for Entity {
type View = Self;
}
impl<'data> View<'data> for Entity {
type Element = <Self::Fetch as IntoIndexableIter>::Item;
type Fetch = EntityFetch<'data>;
type Iter = Iter<'data>;
type Read = [ComponentTypeId; 0];
type Write = [ComponentTypeId; 0];
#[inline]
fn validate() {}
#[inline]
fn validate_access(_: &ComponentAccess) -> bool {
true
}
#[inline]
fn reads_types() -> Self::Read {
[]
}
#[inline]
fn writes_types() -> Self::Write {
[]
}
#[inline]
fn reads<D: Component>() -> bool {
false
}
#[inline]
fn writes<D: Component>() -> bool {
false
}
#[inline]
fn requires_permissions() -> Permissions<ComponentTypeId> {
Permissions::default()
}
unsafe fn fetch(
_: &'data Components,
archetypes: &'data [Archetype],
query: QueryResult<'data>,
) -> Self::Iter {
Iter {
archetypes,
indexes: query.index().iter(),
}
}
}
#[doc(hidden)]
pub struct Iter<'a> {
archetypes: &'a [Archetype],
indexes: std::slice::Iter<'a, ArchetypeIndex>,
}
impl<'a> Iterator for Iter<'a> {
type Item = Option<EntityFetch<'a>>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.indexes.next().map(|i| {
Some(EntityFetch {
entities: self.archetypes[*i].entities(),
})
})
}
}
#[doc(hidden)]
pub struct EntityFetch<'a> {
entities: &'a [Entity],
}
unsafe impl<'a> ReadOnlyFetch for EntityFetch<'a> {
#[inline]
fn get_components(&self) -> Self::Data {
&self.entities
}
}
impl<'a> IntoIndexableIter for EntityFetch<'a> {
type Item = &'a Entity;
type IntoIter = IndexedIter<&'a [Entity]>;
fn into_indexable_iter(self) -> Self::IntoIter {
IndexedIter::new(self.entities)
}
}
impl<'a> IntoIterator for EntityFetch<'a> {
type Item = <Self as IntoIndexableIter>::Item;
type IntoIter = <Self as IntoIndexableIter>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.into_indexable_iter()
}
}
impl<'a> Fetch for EntityFetch<'a> {
type Data = &'a [Entity];
#[inline]
fn into_components(self) -> Self::Data {
self.entities
}
#[inline]
fn find<C: 'static>(&self) -> Option<&[C]> {
None
}
#[inline]
fn find_mut<C: 'static>(&mut self) -> Option<&mut [C]> {
None
}
#[inline]
fn version<C: Component>(&self) -> Option<u64> {
None
}
#[inline]
fn accepted(&mut self) {}
}
|
use std::net::{IpAddr, SocketAddr};
use std::time::Duration;
/// Configuration options used to configure a TP-Link device.
///
/// The configuration consists of options that define the protocol that
/// device instances use in order to communicate with the host devices
/// over the local network.
///
/// # Examples
///
/// ```
/// use std::net::IpAddr;
/// use std::time::Duration;
///
/// // Define the configuration for the device.
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_cache_enabled(Duration::from_secs(3), None)
/// .build();
///
/// assert_eq!(config.addr(), IpAddr::from([192, 168, 1, 100]));
/// assert_eq!(config.cache_enabled(), true);
/// assert_eq!(config.cache_ttl(), Some(Duration::from_secs(3)));
///
/// // Create a new plug instance with the config.
/// let plug = tplink::Plug::with_config(config);
/// ```
#[derive(Debug)]
pub struct Config {
pub(crate) addr: SocketAddr,
pub(crate) read_timeout: Duration,
pub(crate) write_timeout: Duration,
pub(crate) cache_config: CacheConfig,
pub(crate) buffer_size: usize,
}
impl Config {
/// Returns a new configuration [`Builder`] for the given local address
/// of the host device with all the default configurations specified.
///
/// [`Builder`]: struct.Builder.html
///
/// # Examples
///
/// ```
/// let config = tplink::Config::for_host([192, 168, 1, 100]).build();
/// ```
pub fn for_host<A>(addr: A) -> ConfigBuilder
where
A: Into<IpAddr>,
{
ConfigBuilder::new(addr)
}
/// Returns the configured local address of host device.
///
/// # Examples
///
/// ```
/// use std::net::IpAddr;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100]).build();
/// assert_eq!(config.addr(), IpAddr::from([192, 168, 1, 100]));
/// ```
pub fn addr(&self) -> IpAddr {
self.addr.ip()
}
/// Returns the configured port number associated with the device's
/// host address.
///
/// # Examples
///
/// ```
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_port(9999)
/// .build();
/// assert_eq!(config.port(), 9999);
/// ```
pub fn port(&self) -> u16 {
self.addr.port()
}
/// Returns the configured read timeout for the device.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_read_timeout(Duration::from_secs(5))
/// .build();
/// assert_eq!(config.read_timeout(), Duration::from_secs(5));
/// ```
pub fn read_timeout(&self) -> Duration {
self.read_timeout
}
/// Returns the configured write timeout for the device.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_write_timeout(Duration::from_secs(5))
/// .build();
/// assert_eq!(config.write_timeout(), Duration::from_secs(5));
/// ```
pub fn write_timeout(&self) -> Duration {
self.write_timeout
}
/// Returns true if caching is enabled for the device, and false otherwise.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_cache_enabled(Duration::from_secs(3), None)
/// .build();
/// assert_eq!(config.cache_enabled(), true);
/// ```
pub fn cache_enabled(&self) -> bool {
self.cache_config.enable_cache
}
/// Returns the configured cache ttl (time-to-live) for the device if
/// caching is enabled, and `None` otherwise.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_cache_enabled(Duration::from_secs(3), None)
/// .build();
/// assert_eq!(config.cache_ttl(), Some(Duration::from_secs(3)));
/// ```
pub fn cache_ttl(&self) -> Option<Duration> {
self.cache_config.ttl
}
/// Returns the configured initial capacity for the cache if caching is
/// enabled, and None otherwise.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_cache_enabled(Duration::from_secs(3), Some(1024))
/// .build();
/// assert_eq!(config.cache_initial_capacity(), Some(1024));
/// ```
pub fn cache_initial_capacity(&self) -> Option<usize> {
self.cache_config.initial_capacity
}
/// Returns the configured response buffer size for the device.
///
/// # Examples
///
/// ```
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_buffer_size(4096)
/// .build();
/// assert_eq!(config.buffer_size(), 4096);
/// ```
pub fn buffer_size(&self) -> usize {
self.buffer_size
}
}
#[derive(Debug, Copy, Clone)]
pub(crate) struct CacheConfig {
pub(crate) enable_cache: bool,
pub(crate) ttl: Option<Duration>,
pub(crate) initial_capacity: Option<usize>,
}
impl Default for CacheConfig {
fn default() -> Self {
CacheConfig {
enable_cache: false,
ttl: None,
initial_capacity: None,
}
}
}
/// Builds TP-Link device [`Config`] instance with custom configuration values.
///
/// Methods can be chained in order to set the configuration values. The [`Config`]
/// instance is constructed by calling [`build`].
///
/// New instances of the `ConfigBuilder` are obtained via [`Config::for_host`].
///
/// See function level documentation for details on various configuration
/// settings.
///
/// [`Config`]: ./struct.Config.html
/// [`Config::for_host`]: ./struct.Config.html#method.for_host
/// [`build`]: #method.build
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// // Define the configuration for the device.
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_port(9999)
/// .with_read_timeout(Duration::from_secs(5))
/// .with_write_timeout(Duration::from_secs(5))
/// .with_cache_enabled(Duration::from_secs(3), None)
/// .with_buffer_size(4 * 1024)
/// .build();
///
/// // Create a new bulb instance with the config.
/// let bulb = tplink::Bulb::with_config(config);
/// ```
#[derive(Debug)]
pub struct ConfigBuilder {
host: IpAddr,
port: u16,
read_timeout: Option<Duration>,
write_timeout: Option<Duration>,
cache_config: CacheConfig,
buffer_size: Option<usize>,
}
impl ConfigBuilder {
/// Returns a new builder for the given local address of the host device
/// with all the default configurations specified.
fn new<A>(addr: A) -> ConfigBuilder
where
A: Into<IpAddr>,
{
ConfigBuilder {
host: addr.into(),
port: 9999,
read_timeout: None,
write_timeout: None,
cache_config: Default::default(),
buffer_size: None,
}
}
/// Sets the port number associated with the device's host address.
///
/// The default port used is 9999.
///
/// It is advised to use the default port and not set the property manually
/// as all the devices currently respond on default port only.
pub fn with_port(&mut self, port: u16) -> &mut ConfigBuilder {
self.port = port;
self
}
/// Sets the read timeout to the specified timeout duration.
///
/// If not set, then the default read timeout used is 3 seconds.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_read_timeout(Duration::from_secs(5))
/// .build();
/// assert_eq!(config.read_timeout(), Duration::from_secs(5));
/// ```
pub fn with_read_timeout(&mut self, duration: Duration) -> &mut ConfigBuilder {
self.read_timeout = Some(duration);
self
}
/// Sets the write timeout to the specified timeout duration.
///
/// If not set, then the default write timeout used is 3 seconds.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_write_timeout(Duration::from_secs(5))
/// .build();
/// assert_eq!(config.write_timeout(), Duration::from_secs(5));
/// ```
pub fn with_write_timeout(&mut self, duration: Duration) -> &mut ConfigBuilder {
self.write_timeout = Some(duration);
self
}
/// Enables caching device responses with the specified cache ttl (time-to-live)
/// and initial cache capacity.
///
/// By default, caching is disabled.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_cache_enabled(Duration::from_secs(3), Some(2 * 1024))
/// .build();
/// assert_eq!(config.cache_enabled(), true);
/// assert_eq!(config.cache_ttl(), Some(Duration::from_secs(3)));
/// assert_eq!(config.cache_initial_capacity(), Some(2 * 1024));
/// ```
pub fn with_cache_enabled(
&mut self,
ttl: Duration,
initial_capacity: Option<usize>,
) -> &mut ConfigBuilder {
self.cache_config = CacheConfig {
enable_cache: true,
ttl: Some(ttl),
initial_capacity,
};
self
}
/// Sets the device's response buffer size.
///
/// The buffer size should be large enough to hold device's response bytes. If the
/// response is too long to fit in the buffer of specified size, excess bytes maybe
/// discarded and the device would eventually return an [`Error`] on every request.
///
/// The default value used is 4096.
///
/// [`Error`]: ../struct.Error.html
///
/// # Examples
///
/// ```
///
/// let config = tplink::Config::for_host([192, 168, 1, 100])
/// .with_buffer_size(5 * 1024)
/// .build();
/// assert_eq!(config.buffer_size(), 5 * 1024);
/// ```
pub fn with_buffer_size(&mut self, buffer_size: usize) -> &mut ConfigBuilder {
self.buffer_size = Some(buffer_size);
self
}
/// Creates a new configured [`Config`] instance.
///
/// [`Config`]: struct.Config.html
/// # Examples
///
/// ```
///
/// // Create a new config.
/// let config = tplink::Config::for_host([192, 168, 1, 100]).build();
///
/// // Use the config to create a new device instance.
/// let plug = tplink::Plug::with_config(config);
/// ```
pub fn build(&mut self) -> Config {
let addr = SocketAddr::new(self.host, self.port);
let cache_config = self.cache_config;
// Set the default read timeout to 3 seconds
let read_timeout = self.read_timeout.unwrap_or(Duration::from_secs(3));
// Set the default write timeout to 3 seconds
let write_timeout = self.write_timeout.unwrap_or(Duration::from_secs(3));
// Set the default buffer size to 4 * 1024
let buffer_size = self.buffer_size.unwrap_or(4 * 1024);
Config {
addr,
read_timeout,
write_timeout,
cache_config,
buffer_size,
}
}
}
|
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
#[macro_use] extern crate mrusty;
extern crate rmp;
extern crate rmp_serde;
extern crate rmp_rpc;
extern crate byteorder;
extern crate serde;
extern crate getopts;
mod runner;
mod protocol;
mod api;
use std::os::unix::io::FromRawFd;
use std::os::unix::net::UnixStream;
use std::fs::File;
use byteorder::{NativeEndian, ReadBytesExt};
use getopts::Options;
use runner::Runner;
#[cfg(feature = "sandbox")]
mod sandbox {
use std::os::raw::c_char;
use std::ffi::CString;
extern {
fn sandbox(mode: *const c_char);
}
pub fn enter_sandbox(mode: &str) {
unsafe {
sandbox(CString::new(mode).unwrap().as_ptr());
}
}
}
#[cfg(not(feature = "sandbox"))]
mod sandbox {
pub fn enter_sandbox(_mode: &str) {
panic!("sandbox not available");
}
}
pub fn main() {
let args: Vec<String> = std::env::args().collect();
let mut opts = Options::new();
opts.optopt("", "sandbox", "sandbox mode", "MODE");
let matches = opts.parse(&args[1..]).unwrap();
let mut connection = unsafe {
UnixStream::from_raw_fd(3)
};
let seed = {
let mut random = unsafe { File::from_raw_fd(4) };
random.read_i32::<NativeEndian>().unwrap()
};
let runner = Runner::new(seed).unwrap();
let mut server = rmp_rpc::Server::new(runner);
if let Some(mode) = matches.opt_str("sandbox") {
sandbox::enter_sandbox(&mode);
}
server.serve(&mut connection);
}
|
use super::base::BB;
use iterable::Iterable;
use stringable::Stringable;
impl Stringable for BB {
fn to_s(&self) -> String {
let mut s = "".to_string();
let col_names = " |ABCDEFGH|\n";
s = s + col_names;
for (row, col, elem) in self.each_with_row_col() {
if col == 0 {
s.push_str((row+1).to_string().as_slice());
s.push('|');
}
if elem == 0u {
s.push('·');
} else {
s.push('X');
}
if col == 7 {
s.push('|');
s.push_str((row+1).to_string().as_slice());
s.push('\n');
}
}
s.push_str(col_names);
s
}
}
#[cfg(test)]
mod tests {
use stringable::*;
use bitboard::*;
#[test]
fn to_s() {
let expected = " |ABCDEFGH|\n\
8|X·······|8\n\
7|X·······|7\n\
6|X·······|6\n\
5|X·······|5\n\
4|X·······|4\n\
3|X·······|3\n\
2|X·······|2\n\
1|X·······|1\n \
|ABCDEFGH|\n";
let bb = 0x0101010101010101u64 as BB;
let actual = bb.to_s();
assert_eq!(actual.as_slice(), expected)
}
}
|
extern crate graph;
use graph::*;
#[test]
fn make_empty() {
let g = Graph::<i32>::new();
assert_eq!(0, g.number_of_vertices());
}
#[test]
fn make_unconnected() {
let g = graph_builders::unconnected(vec![1, 2, 10], false);
assert_eq!(3, g.number_of_vertices());
assert_eq!(1, g.node_from_index(0));
assert_eq!(2, g.node_from_index(1));
assert_eq!(10, g.node_from_index(2));
assert_eq!(0, g.index_from_node(1));
assert_eq!(1, g.index_from_node(2));
assert_eq!(2, g.index_from_node(10));
assert_eq!(0, g.get_degree_from_index(0));
assert_eq!(0, g.get_degree_from_index(1));
assert_eq!(0, g.get_degree_from_index(2));
}
#[test]
fn make_unconnected_and_add_edges() {
let mut g = graph_builders::unconnected(vec![0, 1, 2, 3, 4, 5], false);
g.add_directed_edge(0, 2);
g.add_directed_edge(4, 2);
g.add_directed_edge(2, 3);
assert_eq!(1, g.get_degree_from_index(0));
assert_eq!(0, g.get_degree_from_index(1));
assert_eq!(1, g.get_degree_from_index(2));
assert_eq!(0, g.get_degree_from_index(3));
assert_eq!(1, g.get_degree_from_index(4));
assert_eq!(0, g.get_degree_from_index(5));
// Check that adding an edge that's already in there doesn't change anything
g.add_directed_edge(0, 2);
assert_eq!(1, g.get_degree_from_index(0));
assert_eq!(0, g.get_degree_from_index(1));
assert_eq!(1, g.get_degree_from_index(2));
assert_eq!(0, g.get_degree_from_index(3));
assert_eq!(1, g.get_degree_from_index(4));
assert_eq!(0, g.get_degree_from_index(5));
g.add_undirected_edge(1, 2);
assert_eq!(1, g.get_degree_from_index(0));
assert_eq!(1, g.get_degree_from_index(1));
assert_eq!(2, g.get_degree_from_index(2));
assert_eq!(0, g.get_degree_from_index(3));
assert_eq!(1, g.get_degree_from_index(4));
assert_eq!(0, g.get_degree_from_index(5));
}
#[test]
fn read_graph_from_file() {
let g = graph_builders::from_file("test_data/graph1").unwrap();
assert_eq!(3, g.number_of_vertices());
assert_eq!(1, g.get_degree_from_index(0));
assert_eq!(1, g.get_degree_from_index(1));
assert_eq!(1, g.get_degree_from_index(2));
assert_eq!(0, g.index_from_node(0));
assert_eq!(1, g.index_from_node(1));
assert_eq!(2, g.index_from_node(2));
}
#[test]
fn read_labelled_graph_from_file() {
let g = graph_builders::from_file_with_nodes::<String>("test_data/graph1_labelled").unwrap();
assert_eq!(3, g.number_of_vertices());
assert_eq!(1, g.get_degree_from_index(0));
assert_eq!(1, g.get_degree_from_index(1));
assert_eq!(1, g.get_degree_from_index(2));
assert_eq!(0, g.index_from_node(String::from("A")));
assert_eq!(1, g.index_from_node(String::from("B")));
assert_eq!(2, g.index_from_node(String::from("C")));
}
#[test]
fn read_undirected_graph_from_file() {
let g = graph_builders::from_file("test_data/graph2").unwrap();
assert_eq!(3, g.number_of_vertices());
assert_eq!(2, g.get_degree_from_index(0));
assert_eq!(1, g.get_degree_from_index(1));
assert_eq!(1, g.get_degree_from_index(2));
assert_eq!(0, g.index_from_node(0));
assert_eq!(1, g.index_from_node(1));
assert_eq!(2, g.index_from_node(2));
}
|
use aoc2019::aoc_input::get_input;
use aoc2019::intcode::*;
fn run_program(tape: &Tape, system_id: isize) -> StreamRef {
let mut machine = IntcodeMachine::new_io(
tape.clone(),
new_stream_ref_from(system_id),
new_stream_ref(),
);
match machine.run_to_completion() {
Ok(_) => (),
Err(err) => panic!("IntcodeMachine error: {:?}", err),
}
machine.output
}
fn main() {
let input = get_input(5);
let tape = parse_intcode_program(&input);
for system_id in &[1, 5] {
let output = run_program(&tape, *system_id);
println!(
"IntcodeMachine output for System ID {}: {:?}",
system_id,
output.borrow()
);
}
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
#[repr(C, packed)]
#[derive(Copy, Clone)]
union QueryTypeOrDataType
{
query_type: QueryType,
data_type: DataType,
bytes: [u8; 2],
}
impl Debug for QueryTypeOrDataType
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter) -> fmt::Result
{
unsafe { self.bytes.fmt(f) }
}
}
impl PartialEq for QueryTypeOrDataType
{
#[inline(always)]
fn eq(&self, other: &Self) -> bool
{
unsafe { self.bytes == other.bytes }
}
}
impl Eq for QueryTypeOrDataType
{
}
impl PartialOrd for QueryTypeOrDataType
{
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering>
{
unsafe { self.bytes.partial_cmp(&other.bytes) }
}
}
impl Ord for QueryTypeOrDataType
{
#[inline(always)]
fn cmp(&self, other: &Self) -> Ordering
{
unsafe { self.bytes.cmp(&other.bytes) }
}
}
impl Hash for QueryTypeOrDataType
{
#[inline(always)]
fn hash<H: Hasher>(&self, state: &mut H)
{
unsafe { self.bytes.hash(state) }
}
}
impl QueryTypeOrDataType
{
#[inline(always)]
pub(crate) fn data_type(self) -> DataType
{
unsafe { self.data_type }
}
}
|
//! The SMB2 CREATE Response packet is sent by the server to notify
//! the client of the status of its SMB2 CREATE Request.
/// Represents the structure size of the create response.
const STRUCTURE_SIZE: &[u8; 2] = b"\x59\x00";
/// A struct that represents a create response.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Create {
/// StructureSize (2 bytes): The server MUST set this field to 89, indicating
/// the size of the request structure, not including the header.
/// The server MUST set this field to this value regardless of how long Buffer[]
/// actually is in the request being sent.
pub structure_size: Vec<u8>,
/// OplockLevel (1 byte): The oplock level that is granted to the client for this open.
pub op_lock_level: Vec<u8>,
/// Flags (1 byte): If the server implements the SMB 3.x dialect family, this field MUST be
/// constructed. Otherwise, this field MUST NOT be used and MUST be reserved.
pub flags: Vec<u8>,
/// CreateAction (4 bytes): The action taken in establishing the open.
/// This field MUST contain one of the following values.
pub create_action: Vec<u8>,
/// CreationTime (8 bytes): The time when the file was created.
pub creation_time: Vec<u8>,
/// LastAccessTime (8 bytes): The time the file was last accessed.
pub last_access_time: Vec<u8>,
/// LastWriteTime (8 bytes): The time when data was last written to the file.
pub last_write_time: Vec<u8>,
/// ChangeTime (8 bytes): The time when the file was last modified.
pub change_time: Vec<u8>,
/// AllocationSize (8 bytes): The size, in bytes, of the data that is allocated to the file.
pub allocation_size: Vec<u8>,
/// EndofFile (8 bytes): The size, in bytes, of the file.
pub end_of_file: Vec<u8>,
/// FileAttributes (4 bytes): The attributes of the file.
pub file_attributes: Vec<u8>,
/// Reserved (4 bytes): This field MUST NOT be used and MUST be reserved.
/// The server SHOULD set this to 0, and the client MUST ignore it on receipt.
pub reserved: Vec<u8>,
/// FileId (16 bytes): An SMB2_FILEID.
pub file_id: Vec<u8>,
/// CreateContextsOffset (4 bytes): The offset, in bytes, from the beginning of
/// the SMB2 header to the first 8-byte aligned SMB2_CREATE_CONTEXT response that
/// is contained in this response. If none are being returned in the response, this value MUST be 0.
pub create_contexts_offset: Vec<u8>,
/// CreateContextsLength (4 bytes): The length, in bytes, of the list of SMB2_CREATE_CONTEXT
/// response structures that are contained in this response.
pub create_contexts_length: Vec<u8>,
/// Buffer (variable): A variable-length buffer that contains the list of create contexts
/// that are contained in this response, as described by CreateContextsOffset and CreateContextsLength.
/// This takes the form of a list of SMB2_CREATE_CONTEXT Response Values.
pub buffer: Vec<u8>,
}
impl Create {
/// Creates a new instance of the create response.
pub fn default() -> Self {
Create {
structure_size: STRUCTURE_SIZE.to_vec(),
op_lock_level: Vec::new(),
flags: vec![0],
create_action: Vec::new(),
creation_time: Vec::new(),
last_access_time: Vec::new(),
last_write_time: Vec::new(),
change_time: Vec::new(),
allocation_size: Vec::new(),
end_of_file: Vec::new(),
file_attributes: Vec::new(),
reserved: vec![0; 4],
file_id: Vec::new(),
create_contexts_offset: Vec::new(),
create_contexts_length: Vec::new(),
buffer: Vec::new(),
}
}
}
/// CreateAction (4 bytes): The action taken in establishing the open.
/// This field MUST contain one of the following values.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum CreateAction {
Supersede,
Opened,
Created,
Overwritten,
}
impl CreateAction {
/// Unpacks the byte code of the corresponding create action.
pub fn unpack_byte_code(self) -> Vec<u8> {
match self {
CreateAction::Supersede => b"\x00\x00\x00\x00".to_vec(),
CreateAction::Opened => b"\x01\x00\x00\x00".to_vec(),
CreateAction::Created => b"\x02\x00\x00\x00".to_vec(),
CreateAction::Overwritten => b"\x03\x00\x00\x00".to_vec(),
}
}
}
|
use serde::{Serialize,Deserialize};
#[derive(Serialize,Deserialize)]
pub struct AddIP{
pub ip_address:String
}
#[derive(Serialize,Deserialize)]
pub struct RemoveIP{
pub ip_address:String
}
pub struct GetWhiteList;
pub struct GetLocalList;
#[derive(Serialize,Deserialize)]
pub struct ConfirmSecretKey{
pub secret_key:String
}
|
use std::env;
use actix_http::KeepAlive;
use actix_web::{App, get, HttpResponse, HttpServer, middleware::Logger, Result, web};
use couchbase::{Cluster, Collection, GetOptions};
/*use async_std::sync::Arc;*/
/*#[derive(Debug, Clone)]
struct PaceCouchbase (Collection);
*/
#[get("/getDetails/{id}")]
async fn index(
web::Path(id): web::Path<String>,
pace_couchbase: web::Data<Collection>,
) -> Result<HttpResponse, HttpResponse> {
let results = match pace_couchbase
.get(id, GetOptions::default())
.await
{
Ok(r) => HttpResponse::Ok().body(format!("{:?}", r)),
Err(e) => HttpResponse::InternalServerError().body(format!("{}", e)),
};
Ok(results)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let data = web::Data::new(Cluster::connect(
env::var("COUCHBASE_STRING").unwrap(),
env::var("COUCHBASE_USERNAME").unwrap(),
env::var("COUCHBASE_PASSWORD").unwrap(),
)
.bucket(env::var("COUCHBASE_BUCKET").unwrap())
.default_collection());
/*
let cb_cluster = Cluster::connect(
env::var("COUCHBASE_STRING").unwrap(),
env::var("COUCHBASE_USERNAME").unwrap(),
env::var("COUCHBASE_PASSWORD").unwrap(),
);
let arc_cluster = Arc::new(cb_cluster);
let cb_bucket = arc_cluster.bucket(env::var("COUCHBASE_BUCKET").unwrap());
let arc_bucket = Arc::new(cb_bucket);
*/ HttpServer::new(move || {
App::new()
.app_data(data.clone())
.wrap(Logger::new("\" % r\" %s %b \" % { Referer }i\" \"%{User-Agent}i\" %D"))
.service(index)
})
.backlog(1024)
.workers(num_cpus::get() * 4)
.bind("0.0.0.0:8082")?
.run()
.await
}
|
use std::fs::{self, File};
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let path = "foo.txt";
let mut file = File::create(path)?;
let contents = "Hello, world!";
file.write_all(contents.as_bytes())?;
println!("written = {}", contents);
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
println!("read = {}", contents);
fs::remove_file(path)
} |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
tests::suite, vault::VaultStorage, Capability, Error, Identity, KVStorage, Permission, Policy,
Value,
};
/// A test for verifying VaultStorage properly implements the LibraSecureStorage API. This test
/// depends on running Vault, which can be done by using the provided docker run script in
/// `docker/vault/run.sh`
#[test]
#[ignore]
fn execute_storage_tests_vault() {
let mut storage = Box::new(setup_vault());
suite::execute_all_storage_tests(storage.as_mut());
}
/// Creates and returns a new VaultStorage instance for testing purposes.
// TODO(joshlind): refactor this method to make it cleaner and easier to reason about.
pub fn setup_vault() -> VaultStorage {
let host = "http://localhost:8200".to_string();
let token = "root_token".to_string();
let mut storage = VaultStorage::new(host.clone(), token);
storage.reset_and_clear().unwrap();
// @TODO davidiw, the following needs to be made generic but right now the creation of a token
// / service is very backend specific.
let reader: String = "reader".to_string();
let writer: String = "writer".to_string();
let anyone = Policy::public();
let root = Policy::new(vec![]);
let partial = Policy::new(vec![
Permission::new(Identity::User(reader.clone()), vec![Capability::Read]),
Permission::new(
Identity::User(writer.clone()),
vec![Capability::Read, Capability::Write],
),
]);
let full = Policy::new(vec![
Permission::new(
Identity::User(reader.clone()),
vec![Capability::Read, Capability::Write],
),
Permission::new(
Identity::User(writer.clone()),
vec![Capability::Read, Capability::Write],
),
]);
// Initialize data and policies
storage.create("anyone", Value::U64(1), &anyone).unwrap();
storage.create("root", Value::U64(2), &root).unwrap();
storage.create("partial", Value::U64(3), &partial).unwrap();
storage.create("full", Value::U64(4), &full).unwrap();
// Verify initial reading works correctly
assert_eq!(storage.get("anyone"), Ok(Value::U64(1)));
assert_eq!(storage.get("root"), Ok(Value::U64(2)));
assert_eq!(storage.get("partial"), Ok(Value::U64(3)));
assert_eq!(storage.get("full"), Ok(Value::U64(4)));
let writer_token = storage.client.create_token(vec![&writer]).unwrap();
let mut writer = VaultStorage::new(host.clone(), writer_token);
assert_eq!(writer.get("anyone"), Ok(Value::U64(1)));
assert_eq!(writer.get("root"), Err(Error::PermissionDenied));
assert_eq!(writer.get("partial"), Ok(Value::U64(3)));
assert_eq!(writer.get("full"), Ok(Value::U64(4)));
let reader_token = storage.client.create_token(vec![&reader]).unwrap();
let mut reader = VaultStorage::new(host, reader_token);
assert_eq!(reader.get("anyone"), Ok(Value::U64(1)));
assert_eq!(reader.get("root"), Err(Error::PermissionDenied));
assert_eq!(reader.get("partial"), Ok(Value::U64(3)));
assert_eq!(reader.get("full"), Ok(Value::U64(4)));
// Attempt writes followed by reads for correctness
writer.set("anyone", Value::U64(5)).unwrap();
assert_eq!(
writer.set("root", Value::U64(6)),
Err(Error::PermissionDenied)
);
writer.set("partial", Value::U64(7)).unwrap();
writer.set("full", Value::U64(8)).unwrap();
assert_eq!(storage.get("anyone"), Ok(Value::U64(5)));
assert_eq!(storage.get("root"), Ok(Value::U64(2)));
assert_eq!(storage.get("partial"), Ok(Value::U64(7)));
assert_eq!(storage.get("full"), Ok(Value::U64(8)));
reader.set("anyone", Value::U64(9)).unwrap();
assert_eq!(
reader.set("root", Value::U64(10)),
Err(Error::PermissionDenied)
);
assert_eq!(
reader.set("partial", Value::U64(11)),
Err(Error::PermissionDenied)
);
reader.set("full", Value::U64(12)).unwrap();
assert_eq!(storage.get("anyone"), Ok(Value::U64(9)));
assert_eq!(storage.get("root"), Ok(Value::U64(2)));
assert_eq!(storage.get("partial"), Ok(Value::U64(7)));
assert_eq!(storage.get("full"), Ok(Value::U64(12)));
storage.reset_and_clear().unwrap();
storage
}
|
use core::mem;
use futures::stream::{once, Chain, Once, Stream, StreamFuture};
use futures::{Async, Future, Poll};
/// Drives a stream until just before it produces a value,
/// then performs a transformation on the stream and returns
/// the transformed stream. If the driven stream reaches its
/// end without producing a value, the transformation function
/// is not called and the returned stream also ends.
///
/// This combinator is conceptually equivalent to calling
/// `.into_future().and_then()` on a stream and properly passing
/// both the returned value and the stream through a stream
/// transformation function.
/// A stream that wraps and transforms another stream
/// once it has produced a value
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Sequence<S, F, U>
where
S: Stream,
{
state: SeqState<S, F, U>,
}
// The type of the stream passed to the stream transformation function
// (eventually we'll get rid of this...)
type OutputStream<S> = Chain<Once<<S as Stream>::Item, <S as Stream>::Error>, S>;
#[derive(Debug)]
enum SeqState<S, F, U>
where
S: Stream,
{
/// Wrapped stream is done
Done,
/// Waiting for the wrapped stream to produce a value
Waiting((StreamFuture<S>, F)),
/// Streaming transformed stream values
Streaming(U),
}
impl<S, F, U> Sequence<S, F, U>
where
S: Stream,
F: FnOnce(OutputStream<S>) -> U,
U: Stream,
{
pub fn new(stream: S, f: F) -> Sequence<S, F, U> {
Sequence {
state: SeqState::Waiting((stream.into_future(), f)),
}
}
fn poll_stream(&mut self, mut stream: U) -> Poll<Option<U::Item>, U::Error> {
let result = stream.poll();
self.state = SeqState::Streaming(stream);
result
}
}
pub trait SequenceStream: Stream + Sized {
/// Create a `Sequence` stream from a stream.
///
/// Takes a transformation function which will be applied to
/// the stream immediately before it produces a value.
fn sequence<F, U>(self, f: F) -> Sequence<Self, F, U>
where
F: FnOnce(OutputStream<Self>) -> U,
U: Stream,
{
Sequence::new(self, f)
}
}
/// Implement `sequence` for all `Stream`s
impl<S> SequenceStream for S where S: Stream {}
impl<S, F, U> Stream for Sequence<S, F, U>
where
S: Stream,
F: FnOnce(OutputStream<S>) -> U,
U: Stream,
{
type Item = U::Item;
type Error = U::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match mem::replace(&mut self.state, SeqState::Done) {
SeqState::Done => Ok(Async::Ready(None)),
SeqState::Waiting((mut stream_future, f)) => match stream_future.poll() {
Ok(Async::Ready((Some(val), stream))) => {
let stream = once(Ok(val)).chain(stream);
let stream = f(stream);
self.poll_stream(stream)
}
Err((err, stream)) => {
let stream = once(Err(err)).chain(stream);
let stream = f(stream);
self.poll_stream(stream)
}
Ok(Async::NotReady) => {
self.state = SeqState::Waiting((stream_future, f));
Ok(Async::NotReady)
}
Ok(Async::Ready((None, _stream))) => {
self.state = SeqState::Done;
Ok(Async::Ready(None))
}
},
SeqState::Streaming(stream) => self.poll_stream(stream),
}
}
}
|
use anyhow::Result;
use clap::{Parser, Subcommand};
use image::io::Reader as ImageReader;
use image::Rgb;
pub mod color;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
// Grayscale {
#[clap(long_about = "Grayscale")]
Gs {
#[clap(short, value_parser)]
div: u8,
#[clap(short, long, value_parser)]
input: String,
#[clap(short, long, value_parser)]
output: Option<String>,
},
// UniformQuantization {
#[clap(long_about = "Uniform quantization")]
Uq {
#[clap(short, value_parser)]
r: u8,
#[clap(short, value_parser)]
g: u8,
#[clap(short, value_parser)]
b: u8,
#[clap(short, long, value_parser)]
input: String,
#[clap(short, long, value_parser)]
output: Option<String>,
},
}
fn main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
Commands::Gs { div, input, output } => {
let output = if output == None {
Some(format!("{}.out.png", input))
} else {
output
};
let img = ImageReader::open(&input)?.decode()?;
let src = img.as_rgb8().unwrap();
let dim = src.dimensions();
let mut dest = image::RgbImage::new(dim.0, dim.1);
let gs = color::Grayscale::new(div);
for ((_, _, sp), (_, _, dp)) in src.enumerate_pixels().zip(dest.enumerate_pixels_mut())
{
let c = gs.get(sp);
*dp = c;
}
dest.save(&output.unwrap())?;
}
Commands::Uq {
r,
g,
b,
input,
output,
} => {
let output = if output == None {
Some(format!("{}.out.png", input))
} else {
output
};
let img = ImageReader::open(&input)?.decode()?;
let src = img.as_rgb8().unwrap();
let dim = src.dimensions();
let mut dest = image::RgbImage::new(dim.0, dim.1);
let uq = color::UniformQuantization::new(Rgb([r, g, b]));
for ((_, _, sp), (_, _, dp)) in src.enumerate_pixels().zip(dest.enumerate_pixels_mut())
{
let c = uq.get(sp);
*dp = c;
}
dest.save(&output.unwrap())?;
}
}
Ok(())
}
|
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//! Corrections for aberration
use angle;
use time;
use coords;
/**
Computes solar aberration in ecliptic longitude
# Returns
* `abrr`: Solar aberration in ecliptic
longitude *| in radians*
# Arguments
* `R`: Sun-Earth distance *| in AU*
**/
#[inline(always)]
pub fn sol_aberr(R: f64) -> f64
{
-angle::deg_frm_dms(0, 0, 20.4898).to_radians() / R
}
/**
Computes stellar aberration in equatorial coordinates
# Returns
`(abrr_in_asc, abrr_in_dec)`
* `abrr_in_asc`: Aberration in right ascension *| in radians*
* `abrr_in_dec`: Aberration in declination *| in radians*
# Arguments
* `stell_eq_point`: Equatorial coordinates of the star *| in radians*
* `JD` : Julian (Ephemeris) day
**/
pub fn stell_aberr_in_eq_coords(stell_eq_point: &coords::EqPoint,
JD: f64) -> (f64, f64)
{
let t = time::julian_cent(JD);
let l2 = 3.1761467 + 1021.3285546*t;
let l3 = 1.7534703 + 628.3075849*t;
let l4 = 6.2034809 + 334.0612431*t;
let l5 = 0.5995465 + 52.9690965*t;
let l6 = 0.8740168 + 21.3299095*t;
let l7 = 5.4812939 + 7.4781599*t;
let l8 = 5.3118863 + 3.8133036*t;
let l1 = 3.8103444 + 8399.6847337*t;
let d = 5.1984667 + 7771.3771486*t;
let m1 = 2.3555559 + 8328.6914289*t;
let f = 1.6279052 + 8433.4661601*t;
let mut x = 0.0;
let mut y = 0.0;
let mut z = 0.0;
let mut A;
let mut sinA;
let mut cosA;
// ROW 1
A = l3;
sinA = A.sin(); cosA = A.cos();
x += (-1719914.0 - 2.0*t)*sinA - 25.0*cosA;
y += (25.0 - 13.0*t)*sinA + (1578089.0 + 156.0*t)*cosA;
z += (10.0 + 32.0*t)*sinA + (684185.0 - 358.0*t)*cosA;
// ROW 2
A = 2.0 * l3;
sinA = A.sin(); cosA = A.cos();
x += (6434.0 + 141.0*t)*sinA + (28007.0 - 107.0*t)*cosA;
y += (25697.0 - 95.0*t)*sinA + (-5904.0 - 130.0*t)*cosA;
z += (11141.0 - 48.0*t)*sinA + (-2559.0 - 55.0*t)*cosA;
// ROW 3
A = l5;
sinA = A.sin(); cosA = A.cos();
x += 715.0*sinA;
y += 6.0*sinA - 657.0*cosA;
z += -15.0*sinA - 282.0*cosA;
// ROW 4
A = l1;
sinA = A.sin(); cosA = A.cos();
x += 715.0*sinA;
y += -656.0*cosA;
z += -285.0*cosA;
// ROW 5
A = 3.0 * l3;
sinA = A.sin(); cosA = A.cos();
x += (486.0 - 5.0*t)*sinA + (-236.0 - 4.0*t)*cosA;
y += (-216.0 - 4.0*t)*sinA + (-446.0 + 5.0*t)*cosA;
z += -94.0*sinA - 193.0*cosA;
// ROW 6
A = l6;
sinA = A.sin(); cosA = A.cos();
x += 159.0*sinA;
y += 2.0*sinA - 147.0*cosA;
z += -6.0*sinA - 61.0*cosA;
// ROW 7
A = f;
cosA = A.cos();
y += 26.0*cosA;
z += -59.0*cosA;
// ROW 8
A = l1 + m1;
sinA = A.sin(); cosA = A.cos();
x += 39.0*sinA;
y += -36.0*cosA;
z += -16.0*cosA;
// ROW 9
A = 2.0 * l5;
sinA = A.sin(); cosA = A.cos();
x += 33.0*sinA - 10.0*cosA;
y += -9.0*sinA - 30.0*cosA;
z += -5.0*sinA - 13.0*cosA;
// ROW 10
A = 2.0*l3 - l5;
sinA = A.sin(); cosA = A.cos();
x += 31.0*sinA + cosA;
y += sinA - 28.0*cosA;
z += -12.0*cosA;
// ROW 11
A = 3.0*l3 - 8.0*l4 + 3.0*l5;
sinA = A.sin(); cosA = A.cos();
x += 8.0*sinA - 28.0*cosA;
y += 25.0*sinA + 8.0*cosA;
z += 11.0*sinA + 3.0*cosA;
// ROW 12
A = 5.0*l3 - 8.0*l4 + 3.0*l5;
sinA = A.sin(); cosA = A.cos();
x += 8.0*sinA - 28.0*cosA;
y += -25.0*sinA - 8.0*cosA;
z += -11.0*sinA - 3.0*cosA;
// ROW 13
A = 2.0*l2 - l3;
sinA = A.sin(); cosA = A.cos();
x += 21.0*sinA;
y += -19.0*cosA;
z += -8.0*cosA;
// ROW 14
A = l2;
sinA = A.sin(); cosA = A.cos();
x += -19.0*sinA;
y += 17.0*cosA;
z += 8.0*cosA;
// ROW 15
A = l7;
sinA = A.sin(); cosA = A.cos();
x += 17.0*sinA;
y += -16.0*cosA;
z += -7.0*cosA;
// ROW 16
A = l3 - 2.0*l5;
sinA = A.sin(); cosA = A.cos();
x += 16.0*sinA;
y += 15.0*cosA;
z += sinA + 7.0*cosA;
// ROW 17
A = l8;
sinA = A.sin(); cosA = A.cos();
x += 16.0*sinA;
y += sinA - 15.0*cosA;
z += -3.0*sinA - 6.0*cosA;
// ROW 18
A = l3 + l5;
sinA = A.sin(); cosA = A.cos();
x += 11.0*sinA - cosA;
y += -1.0*sinA - 10.0*cosA;
z += -1.0*sinA - 5.0*cosA;
// ROW 19
A = 2.0 * (l2 - l3);
sinA = A.sin(); cosA = A.cos();
x += -11.0*cosA;
y += -10.0*sinA;
z += -4.0*sinA;
// ROW 20
A = l3 - l5;
sinA = A.sin(); cosA = A.cos();
x += -11.0*sinA - 2.0*cosA;
y += -2.0*sinA + 9.0*cosA;
z += -1.0*sinA + 4.0*cosA;
// ROW 21
A = 4.0*l3;
sinA = A.sin(); cosA = A.cos();
x += -7.0*sinA - 8.0*cosA;
y += -8.0*sinA + 6.0*cosA;
z += 3.0 * (cosA - sinA);
// ROW 22
A = 3.0*l3 - 2.0*l5;
sinA = A.sin(); cosA = A.cos();
x += -10.0*sinA;
y += 9.0*cosA;
z += 4.0*cosA;
// ROW 23
A = l2 - 2.0*l3;
sinA = A.sin(); cosA = A.cos();
x += -9.0*sinA;
y += -9.0*cosA;
z += -4.0*cosA;
// ROW 24
A = 2.0*l2 - 3.0*l3;
sinA = A.sin(); cosA = A.cos();
x += -9.0*sinA;
y += -8.0*cosA;
z += -4.0*cosA;
// ROW 25
A = 2.0*l6;
sinA = A.sin(); cosA = A.cos();
x += -9.0*cosA;
y += -8.0*sinA;
z += -3.0*sinA;
// ROW 26
A = 2.0*l2 - 4.0*l3;
sinA = A.sin(); cosA = A.cos();
x += -9.0*cosA;
y += 8.0*sinA;
z += 3.0*sinA;
// ROW 27
A = 3.0*l3 - 2.0*l4;
sinA = A.sin(); cosA = A.cos();
x += 8.0*sinA;
y += -8.0*cosA;
z += -3.0*cosA;
// ROW 28
A = l1 + 2.0*d - m1;
sinA = A.sin(); cosA = A.cos();
x += 8.0*sinA;
y += -7.0*cosA;
z += -3.0*cosA;
// ROW 29
A = 8.0*l2 - 12.0*l3;
sinA = A.sin(); cosA = A.cos();
x += -4.0*sinA - 7.0*cosA;
y += -6.0*sinA + 4.0*cosA;
z += -3.0*sinA + 2.0*cosA;
// ROW 30
A = 8.0*l2 - 14.0*l3;
sinA = A.sin(); cosA = A.cos();
x += -4.0*sinA - 7.0*cosA;
y += 6.0*sinA - 4.0*cosA;
z += 3.0*sinA - 2.0*cosA;
// ROW 31
A = 2.0*l4;
sinA = A.sin(); cosA = A.cos();
x += -6.0*sinA - 5.0*cosA;
y += -4.0*sinA + 5.0*cosA;
z += 2.0 * (cosA - sinA);
// ROW 32
A = 3.0*l2 - 4.0*l3;
sinA = A.sin(); cosA = A.cos();
x += -1.0 * (sinA + cosA);
y += -2.0*sinA - 7.0*cosA;
z += sinA - 4.0*cosA;
// ROW 33
A = 2.0 * (l3 - l5);
sinA = A.sin(); cosA = A.cos();
x += 4.0*sinA - 6.0*cosA;
y += -5.0*sinA - 4.0*cosA;
z += -2.0 * (sinA + cosA);
// ROW 34
A = 3.0 * (l2 - l3);
sinA = A.sin(); cosA = A.cos();
x += -7.0*cosA;
y += -6.0*sinA;
z += -3.0*sinA;
// ROW 35
A = 2.0 * (l3 - l4);
sinA = A.sin(); cosA = A.cos();
x += 5.0 * (sinA - cosA);
y += -4.0*sinA - 5.0*cosA;
z += -2.0 * (sinA + cosA);
// ROW 36
A = l1 - 2.0*d;
sinA = A.sin(); cosA = A.cos();
x += 5.0*sinA;
y += -5.0*cosA;
z += -2.0*cosA;
let c = 17314463350.0;
let (asc, dec) = (stell_eq_point.asc, stell_eq_point.dec);
let delta_asc = (y*asc.cos() - x*asc.sin()) / (c*dec.cos());
let delta_dec = -(((x*asc.cos() + y*asc.sin())*dec.sin() - z*dec.cos())) / c;
(delta_asc, delta_dec)
}
|
use anyhow::Result;
use std::path::Path;
use crate::{
action::{Action, UserPollDateInfo},
config,
database::{challenge_data::ChallengeData, task_data::TaskData, Database},
response::Response,
};
pub fn perform_action(action: &Action) -> Response {
let database = Database::new(&Path::new(config::DEFAULT_DB_PATH));
let mb_response = match action {
Action::CreateNewChallenge(challenge_data) => {
create_new_challenge(&database, challenge_data)
}
Action::SubscribeToChallenge(user_id, challenge_id, user_name) => {
subscribe_to_challenge(&database, user_id, challenge_id, user_name)
}
Action::AddTask(user_id, challenge_name, task_data) => {
add_task(&database, user_id, challenge_name, task_data)
}
Action::SignupUser(user_id, chat_id, user_name) => {
signup_user(&database, user_id, chat_id, user_name)
}
Action::ErrorMessage(message_text) => reply(&message_text),
Action::CheckDateMaybeSendPolls => send_task_polls(&database),
Action::CheckDateMaybeSendChallengeUpdates => send_challenge_updates(&database),
Action::SendHelp => Ok(Response::SendHelp),
Action::ModifyUserTaskTimestamps(poll_id, option_ids) => {
modify_user_task_timestamps(&database, poll_id, option_ids)
}
Action::WritePollInfo(info) => write_poll_info(&database, info),
Action::Nothing => Ok(Response::Nothing),
};
mb_response.unwrap_or_else(|err| Response::Reply(format!("Error: {}", err.to_string())))
}
fn write_poll_info(database: &Database, info: &Vec<UserPollDateInfo>) -> Result<Response> {
database.write_poll_info(info)?;
Ok(Response::Nothing)
}
fn modify_user_task_timestamps(
database: &Database,
poll_id: &str,
poll_option_ids: &Vec<i32>,
) -> Result<Response> {
database.modify_user_task_entries(poll_id, poll_option_ids)?;
Ok(Response::Nothing)
}
fn send_task_polls(database: &Database) -> Result<Response> {
Ok(Response::TaskPolls(
database.check_date_and_get_all_user_tasks()?,
))
}
fn send_challenge_updates(database: &Database) -> Result<Response> {
Ok(Response::ChallengeUpdates(
database.check_date_and_get_challenge_update_data()?,
))
}
fn reply(message_text: &str) -> Result<Response> {
Ok(Response::Reply(message_text.to_string()))
}
fn signup_user(
database: &Database,
user_id: &i32,
chat_id: &i64,
user_name: &str,
) -> Result<Response> {
database.signup_user(user_id, chat_id, user_name)?;
Ok(Response::Reply("Thanks. You signed up.".to_owned()))
}
fn add_task(
database: &Database,
user_id: &i32,
challenge_name: &str,
task_data: &TaskData,
) -> Result<Response> {
database.add_task(user_id, challenge_name, task_data)?;
Ok(Response::Reply(format!(
"Task {} added. Kaclxokca!",
task_data.name
)))
}
fn subscribe_to_challenge(
database: &Database,
user_id: &i32,
challenge_id: &i32,
user_name: &str,
) -> Result<Response> {
let already_subscribed = database.subscribe_to_challenge(user_id, challenge_id)?;
if !already_subscribed {
Ok(Response::Reply(format!(
"{} accepted the challenge! Kaclxokca!",
user_name
)))
} else {
Ok(Response::Nothing)
}
}
fn create_new_challenge(database: &Database, challenge_data: &ChallengeData) -> Result<Response> {
let challenge = database.add_challenge(challenge_data)?;
Ok(Response::SubscriptionPrompt(challenge))
}
|
pub type char_t = i8;
pub type uchar_t = u8;
pub type short_t = i16;
pub type ushort_t = u16;
pub type int_t = i32;
pub type uint_t = u32;
pub type long_t = i64;
pub type longlong_t = i64;
pub type ulong_t = u64;
pub type ulonglong_t= i64;
// stddef
pub type ssize_t = long_t;
pub type size_t = ulong_t;
pub type ptrdiff_t = long_t;
// stdint
pub type int8_t = char_t;
pub type int16_t = short_t;
pub type int32_t = int_t;
pub type int64_t = longlong_t;
pub type uint8_t = uchar_t;
pub type uint16_t = ushort_t;
pub type uint32_t = uint_t;
pub type uint64_t = ulonglong_t;
pub type int_least8_t = int8_t;
pub type int_least16_t = int16_t;
pub type int_least32_t = int32_t;
pub type int_least64_t = int64_t;
pub type uint_least8_t = uint8_t;
pub type uint_least16_t = uint16_t;
pub type uint_least32_t = uint32_t;
pub type uint_least64_t = uint64_t;
pub type int_fast8_t = int8_t;
pub type int_fast16_t = int16_t;
pub type int_fast32_t = int32_t;
pub type int_fast64_t = int64_t;
pub type uint_fast8_t = uint8_t;
pub type uint_fast16_t = uint16_t;
pub type uint_fast32_t = uint32_t;
pub type uint_fast64_t = uint64_t;
pub type intptr_t = long_t;
pub type uintptr_t = ulong_t;
pub type intmax_t = long_t;
pub type uintmax_t = ulong_t;
// time
pub type clock_t = ulong_t;
pub type time_t = long_t;
#[repr(C)]
pub struct tm {
pub tm_sec: int_t,
pub tm_min: int_t,
pub tm_hour: int_t,
pub tm_mday: int_t,
pub tm_mon: int_t,
pub tm_year: int_t,
pub tm_wday: int_t,
pub tm_yday: int_t,
pub tm_isdst: int_t,
pub tm_gmtoff: long_t,
pub tm_zone: *mut char_t,
}
#[repr(u8)]
pub enum void_t {
__variant1,
__variant2,
}
// sys/types.h
pub type dev_t = int32_t;
pub type gid_t = uint32_t;
pub type id_t = uint32_t;
pub type ino_t = uint64_t;
pub type mode_t = uint16_t;
pub type nlink_t = uint16_t;
pub type off_t = int64_t;
pub type pid_t = int32_t;
pub type uid_t = uint32_t;
pub type key_t = int32_t;
pub type useconds_t = uint32_t;
pub type suseconds_t = int32_t;
// sys/time.h
#[repr(C)]
pub struct timeval {
pub tv_sec: time_t,
pub tv_usec: suseconds_t,
}
#[repr(C)]
pub struct itimerval {
pub it_interval: timeval,
pub it_value: timeval,
}
#[repr(C)]
pub struct timezone {
pub tz_minuteswest: int_t,
pub tz_dsttime: int_t,
}
#[repr(C)]
pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
pub struct fd_set {
pub fds_bits: [int32_t; 32usize],
}
#[repr(C)]
pub struct rlimit {
pub rlim_cur: ulong_t,
pub rlim_max: ulong_t,
}
// kernel
pub type user_addr_t = u64;
pub type user_size_t = u64;
pub type user_ssize_t = i64;
pub type caddr_t = *const char_t;
|
//! # RN2xx3
//!
//! A `no_std` / `embedded_hal` compatible Rust driver for the RN2483 and
//! the RN2903 LoRaWAN modules. The library works without any dynamic allocations.
//!
//! ## Usage
//!
//! First, configure a serial port using a crate that implements the serial
//! traits from `embedded_hal`, for example
//! [serial](https://crates.io/crates/serial).
//!
//! ```no_run
//! use std::time::Duration;
//! use linux_embedded_hal::Serial;
//! use serial::{self, core::SerialPort};
//!
//! // Serial port settings
//! let settings = serial::PortSettings {
//! baud_rate: serial::Baud57600,
//! char_size: serial::Bits8,
//! parity: serial::ParityNone,
//! stop_bits: serial::Stop1,
//! flow_control: serial::FlowNone,
//! };
//!
//! // Open serial port
//! let mut port = serial::open("/dev/ttyACM0").expect("Could not open serial port");
//! port.configure(&settings)
//! .expect("Could not configure serial port");
//! port.set_timeout(Duration::from_secs(1))
//! .expect("Could not set serial port timeout");
//! let serialport = Serial(port);
//! ```
//!
//! Then initialize the driver, either for the RN2483 or for the RN2903, on
//! your desired frequency:
//!
//! ```no_run
//! # use std::time::Duration;
//! # use linux_embedded_hal::Serial;
//! # use serial::{self, core::SerialPort};
//! # // Serial port settings
//! # let settings = serial::PortSettings {
//! # baud_rate: serial::Baud57600,
//! # char_size: serial::Bits8,
//! # parity: serial::ParityNone,
//! # stop_bits: serial::Stop1,
//! # flow_control: serial::FlowNone,
//! # };
//! use rn2xx3;
//!
//! # let mut port = serial::open("/dev/ttyACM0").expect("Could not open serial port");
//! # port.configure(&settings).expect("Could not configure serial port");
//! # port.set_timeout(Duration::from_secs(1)).expect("Could not set serial port timeout");
//! # let serialport = Serial(port);
//! // RN2483 at 868 MHz
//! let rn = rn2xx3::rn2483_868(serialport);
//!
//! # let mut port = serial::open("/dev/ttyACM0").expect("Could not open serial port");
//! # port.configure(&settings).expect("Could not configure serial port");
//! # port.set_timeout(Duration::from_secs(1)).expect("Could not set serial port timeout");
//! # let serialport = Serial(port);
//! // RN2483 at 433 MHz
//! let rn = rn2xx3::rn2483_433(serialport);
//!
//! # let mut port = serial::open("/dev/ttyACM0").expect("Could not open serial port");
//! # port.configure(&settings).expect("Could not configure serial port");
//! # port.set_timeout(Duration::from_secs(1)).expect("Could not set serial port timeout");
//! # let serialport = Serial(port);
//! // RN2903 at 915 MHz
//! let rn = rn2xx3::rn2903_915(serialport);
//! ```
//!
//! After initializing, it's a good idea to clear the serial buffers and ensure
//! a "known good state".
//!
//! ```no_run
//! # use std::time::Duration;
//! # use linux_embedded_hal::Serial;
//! # use serial::{self, core::SerialPort};
//! # // Serial port settings
//! # let settings = serial::PortSettings {
//! # baud_rate: serial::Baud57600,
//! # char_size: serial::Bits8,
//! # parity: serial::ParityNone,
//! # stop_bits: serial::Stop1,
//! # flow_control: serial::FlowNone,
//! # };
//! # use rn2xx3;
//! # let mut port = serial::open("/dev/ttyACM0").expect("Could not open serial port");
//! # port.configure(&settings).expect("Could not configure serial port");
//! # port.set_timeout(Duration::from_secs(1)).expect("Could not set serial port timeout");
//! # let serialport = Serial(port);
//! # let mut rn = rn2xx3::rn2483_868(serialport);
//! rn.ensure_known_state().expect("Error while preparing device");
//! ```
//!
//! Now you can read information from the module and join, e.g. via OTAA:
//!
//! ```no_run
//! # use std::time::Duration;
//! # use linux_embedded_hal::Serial;
//! # use serial::{self, core::SerialPort};
//! # // Serial port settings
//! # let settings = serial::PortSettings {
//! # baud_rate: serial::Baud57600,
//! # char_size: serial::Bits8,
//! # parity: serial::ParityNone,
//! # stop_bits: serial::Stop1,
//! # flow_control: serial::FlowNone,
//! # };
//! # use rn2xx3;
//! # let mut port = serial::open("/dev/ttyACM0").expect("Could not open serial port");
//! # port.configure(&settings).expect("Could not configure serial port");
//! # port.set_timeout(Duration::from_secs(1)).expect("Could not set serial port timeout");
//! # let serialport = Serial(port);
//! # let mut rn = rn2xx3::rn2483_868(serialport);
//! use rn2xx3::{ConfirmationMode, JoinMode};
//!
//! // Reset module
//! println!("Resetting module...\n");
//! rn.reset().expect("Could not reset");
//!
//! // Show device info
//! println!("== Device info ==\n");
//! let hweui = rn.hweui().expect("Could not read hweui");
//! println!(" HW-EUI: {}", hweui);
//! let model = rn.model().expect("Could not read model");
//! println!(" Model: {:?}", model);
//! let version = rn.version().expect("Could not read version");
//! println!(" Version: {}", version);
//! let vdd = rn.vdd().expect("Could not read vdd");
//! println!("Vdd voltage: {} mV", vdd);
//!
//! // Set keys
//! println!("Setting keys...");
//! rn.set_app_eui_hex("0011223344556677").expect("Could not set app EUI");
//! rn.set_app_key_hex("0011223344556677889900aabbccddee").expect("Could not set app key");
//!
//! // Join
//! println!("Joining via OTAA...");
//! rn.join(JoinMode::Otaa).expect("Could not join");
//! println!("OK");
//!
//! // Send data
//! let fport = 1u8;
//! rn.transmit_slice(ConfirmationMode::Unconfirmed, fport, &[23, 42]).expect("Could not transmit data");
//! ```
//!
//! For more examples, refer to the `examples` directory in the source repository.
//!
//! ## Logging
//!
//! If you are running the driver from a platform that has access to `std`, you
//! can also enable the optional `logging` feature to be able to see incoming
//! and outgoing commands:
//!
//! ```text
//! $ export RUST_LOG=debug
//! $ cargo run --features logging --example join_otaa ...
//! Resetting module...
//! [2020-03-03T20:41:42Z DEBUG rn2xx3] Sending command: "sys reset"
//! [2020-03-03T20:41:42Z DEBUG rn2xx3] Received response: "RN2483 1.0.3 Mar 22 2017 06:00:42"
//! ...
//! ```
#![cfg_attr(not(test), no_std)]
pub mod errors;
mod utils;
use core::convert::TryFrom;
use core::marker::PhantomData;
use core::str::{from_utf8, FromStr};
use core::time::Duration;
use doc_comment::doc_comment;
use embedded_hal::serial;
use nb::block;
use numtoa::NumToA;
#[cfg(feature = "logging")]
use core::fmt;
#[cfg(feature = "logging")]
use log;
use crate::errors::{Error, JoinError, RnResult, TxError};
const CR: u8 = 0x0d;
const LF: u8 = 0x0a;
/// Marker trait implemented for all models / frequencies.
pub trait Frequency {}
/// Frequency type parameter for the RN2483 (433 MHz).
pub struct Freq433;
/// Frequency type parameter for the RN2483 (868 MHz).
pub struct Freq868;
/// Frequency type parameter for the RN2903 (915 MHz).
pub struct Freq915;
impl Frequency for Freq433 {}
impl Frequency for Freq868 {}
impl Frequency for Freq915 {}
#[cfg(feature = "logging")]
struct LoggableStrSlice<'o, 'i>(&'o [&'i str]);
#[cfg(feature = "logging")]
impl fmt::Display for LoggableStrSlice<'_, '_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for part in self.0 {
write!(f, "{}", part)?;
}
Ok(())
}
}
/// The main driver instance.
pub struct Driver<F: Frequency, S> {
/// Marker type with the module frequency.
frequency: PhantomData<F>,
/// Serial port.
serial: S,
/// Read buffer.
read_buf: [u8; 64],
/// This flag is set when entering sleep mode. As long as it is set,
/// sending any command will be prevented.
sleep: bool,
}
/// List of all supported RN module models.
#[derive(Debug, PartialEq, Eq)]
pub enum Model {
RN2483,
RN2903,
}
/// The join procedure.
#[derive(Debug, PartialEq, Eq)]
pub enum JoinMode {
/// Over the air activation
Otaa,
/// Activation by personalization
Abp,
}
/// Whether to send an uplink as confirmed or unconfirmed message.
#[derive(Debug, PartialEq, Eq)]
pub enum ConfirmationMode {
/// Expect a confirmation from the gateway.
Confirmed,
/// No confirmation is expected.
Unconfirmed,
}
/// The data rates valid in Europe and China.
///
/// Frequencies:
///
/// - EU 863–870 MHz (LoRaWAN Specification (2015), Page 35, Table 14)
/// - CN 779–787 MHz (LoRaWAN Specification (2015), Page 44, Table 25)
/// - EU 433 MHz (LoRaWAN Specification (2015), Page 48, Table 31)
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum DataRateEuCn {
/// Data Rate 0: SF 12 BW 125 (250 bit/s)
Sf12Bw125,
/// Data Rate 1: SF 11 BW 125 (440 bit/s)
Sf11Bw125,
/// Data Rate 2: SF 10 BW 125 (980 bit/s)
Sf10Bw125,
/// Data Rate 3: SF 9 BW 125 (1760 bit/s)
Sf9Bw125,
/// Data Rate 4: SF 8 BW 125 (3125 bit/s)
Sf8Bw125,
/// Data Rate 5: SF 7 BW 125 (5470 bit/s)
Sf7Bw125,
/// Data Rate 6: SF 7 BW 250 (11000 bit/s)
Sf7Bw250,
}
impl From<DataRateEuCn> for &str {
fn from(dr: DataRateEuCn) -> Self {
match dr {
DataRateEuCn::Sf12Bw125 => "0",
DataRateEuCn::Sf11Bw125 => "1",
DataRateEuCn::Sf10Bw125 => "2",
DataRateEuCn::Sf9Bw125 => "3",
DataRateEuCn::Sf8Bw125 => "4",
DataRateEuCn::Sf7Bw125 => "5",
DataRateEuCn::Sf7Bw250 => "6",
}
}
}
impl TryFrom<&str> for DataRateEuCn {
type Error = ();
fn try_from(val: &str) -> Result<Self, Self::Error> {
match val {
"0" => Ok(DataRateEuCn::Sf12Bw125),
"1" => Ok(DataRateEuCn::Sf11Bw125),
"2" => Ok(DataRateEuCn::Sf10Bw125),
"3" => Ok(DataRateEuCn::Sf9Bw125),
"4" => Ok(DataRateEuCn::Sf8Bw125),
"5" => Ok(DataRateEuCn::Sf7Bw125),
"6" => Ok(DataRateEuCn::Sf7Bw250),
_ => Err(()),
}
}
}
/// The data rates valid in the USA.
///
/// Frequencies:
///
/// - US 902–928 MHz (LoRaWAN Specification (2015), Page 40, Table 18)
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum DataRateUs {
/// Data Rate 0: SF 10 BW 125 (980 bit/s)
Sf10Bw125,
/// Data Rate 1: SF 9 BW 125 (1760 bit/s)
Sf9Bw125,
/// Data Rate 2: SF 8 BW 125 (3125 bit/s)
Sf8Bw125,
/// Data Rate 3: SF 7 BW 125 (5470 bit/s)
Sf7Bw125,
/// Data Rate 4: SF 8 BW 500 (12500 bit/s)
Sf8Bw500,
}
impl From<DataRateUs> for &str {
fn from(dr: DataRateUs) -> Self {
match dr {
DataRateUs::Sf10Bw125 => "0",
DataRateUs::Sf9Bw125 => "1",
DataRateUs::Sf8Bw125 => "2",
DataRateUs::Sf7Bw125 => "3",
DataRateUs::Sf8Bw500 => "4",
}
}
}
impl TryFrom<&str> for DataRateUs {
type Error = ();
fn try_from(val: &str) -> Result<Self, Self::Error> {
match val {
"0" => Ok(DataRateUs::Sf10Bw125),
"1" => Ok(DataRateUs::Sf9Bw125),
"2" => Ok(DataRateUs::Sf8Bw125),
"3" => Ok(DataRateUs::Sf7Bw125),
"4" => Ok(DataRateUs::Sf8Bw500),
_ => Err(()),
}
}
}
#[derive(Debug, PartialEq)]
pub struct Downlink<'a> {
port: u8,
hexdata: &'a str,
}
/// Create a new driver instance for the RN2483 (433 MHz), wrapping the
/// specified serial port.
pub fn rn2483_433<S, E>(serial: S) -> Driver<Freq433, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
{
Driver {
frequency: PhantomData,
serial,
read_buf: [0; 64],
sleep: false,
}
}
/// Create a new driver instance for the RN2483 (868 MHz), wrapping the
/// specified serial port.
pub fn rn2483_868<S, E>(serial: S) -> Driver<Freq868, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
{
Driver {
frequency: PhantomData,
serial,
read_buf: [0; 64],
sleep: false,
}
}
/// Create a new driver instance for the RN2903 (915 MHz), wrapping the
/// specified serial port.
pub fn rn2903_915<S, E>(serial: S) -> Driver<Freq915, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
{
Driver {
frequency: PhantomData,
serial,
read_buf: [0; 64],
sleep: false,
}
}
/// Basic commands.
impl<F, S, E> Driver<F, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
F: Frequency,
{
/// Write a single byte to the serial port.
///
/// **Note:** For performance reasons, the `sleep` flag is not being
/// checked here. Make sure not to call this method while in sleep mode.
fn write_byte(&mut self, byte: u8) -> RnResult<(), E> {
block!(self.serial.write(byte)).map_err(Error::SerialWrite)
}
/// Ensure that the device is not currently in sleep mode.
///
/// Returns `Error::SleepMode` if `self.sleep` is set.
fn ensure_not_in_sleep_mode(&self) -> RnResult<(), E> {
if self.sleep {
Err(Error::SleepMode)
} else {
Ok(())
}
}
/// Write CR+LF bytes.
fn write_crlf(&mut self) -> RnResult<(), E> {
self.ensure_not_in_sleep_mode()?;
self.write_byte(CR)?;
self.write_byte(LF)
}
/// Write all bytes from the buffer to the serial port.
fn write_all(&mut self, buffer: &[u8]) -> RnResult<(), E> {
self.ensure_not_in_sleep_mode()?;
for byte in buffer {
self.write_byte(*byte)?;
}
Ok(())
}
/// Read a single byte from the serial port.
fn read_byte(&mut self) -> RnResult<u8, E> {
block!(self.serial.read()).map_err(Error::SerialRead)
}
/// Read a CR/LF terminated line from the serial port.
///
/// The string is returned without the line termination.
pub fn read_line(&mut self) -> RnResult<&[u8], E> {
let buflen = self.read_buf.len();
let mut i = 0;
loop {
match self.read_byte()? {
LF if self.read_buf[i - 1] == CR => {
#[cfg(feature = "logging")]
log::debug!(
"Received response: {:?}",
from_utf8(&self.read_buf[0..(i - 1)]).unwrap_or("\"[invalid-utf8]\"")
);
return Ok(&self.read_buf[0..(i - 1)]);
}
other => {
self.read_buf[i] = other;
}
}
i += 1;
if i >= buflen {
return Err(Error::ReadBufferTooSmall);
}
}
}
/// Send a raw command to the module and do not wait for the response.
///
/// **Note:** If you use this for a command that returns a response (e.g.
/// `sleep`), you will have to manually read the response using the
/// `read_line()` method.
pub fn send_raw_command_nowait(&mut self, command: &[&str]) -> RnResult<(), E> {
#[cfg(feature = "logging")]
log::debug!("Sending command: \"{}\"", LoggableStrSlice(command));
for part in command {
self.write_all(part.as_bytes())?;
}
self.write_crlf()?;
Ok(())
}
/// Send a raw command to the module and return the response.
pub fn send_raw_command(&mut self, command: &[&str]) -> RnResult<&[u8], E> {
self.send_raw_command_nowait(command)?;
self.read_line()
}
/// Send a raw command and decode the resulting bytes to a `&str`.
pub fn send_raw_command_str(&mut self, command: &[&str]) -> RnResult<&str, E> {
let bytes = self.send_raw_command(command)?;
Ok(from_utf8(bytes)?)
}
/// Send a raw command that should be confirmed with 'OK'. If the response
/// is not 'OK', return `Error::CommandFailed`.
fn send_raw_command_ok(&mut self, command: &[&str]) -> RnResult<(), E> {
let response = self.send_raw_command(command)?;
if response == b"ok" {
Ok(())
} else {
Err(Error::CommandFailed)
}
}
/// Clear the module serial buffers and ensure a known good state.
///
/// ## Implementation details
///
/// This is done by first reading and discarding all available bytes from
/// the serial port.
///
/// Afterwards, to ensure that there's no valid command in the input
/// buffer, the letter 'z' is sent, followed by a newline. There is no
/// valid command that ends with 'z' and it's not a valid hex character, so
/// the module should return `invalid_param`. If it doesn't, the same
/// procedure is repeated 2 more times until giving up.
///
/// Unexpected errors while reading or writing are propagated to the
/// caller.
pub fn ensure_known_state(&mut self) -> RnResult<(), E> {
// First, clear the input buffer
loop {
match self.serial.read() {
Ok(_) => {
// A byte was returned, continue reading
#[cfg(feature = "logging")]
log::debug!("Clearing input buffer: Discarded 1 byte");
}
Err(nb::Error::WouldBlock) => break,
Err(nb::Error::Other(e)) => return Err(Error::SerialRead(e)),
}
}
#[cfg(feature = "logging")]
log::debug!("Input buffer is clear");
// Max 3 attempts
for _ in 0..3 {
#[cfg(feature = "logging")]
log::debug!("Check whether module is in a known state, expecting \"invalid_param\"");
// To ensure that there's no valid command in the input buffer, write
// the letter 'z' followed by CRLF.
self.write_byte(b'z')?;
self.write_crlf()?;
// Read the response, it should be "invalid_param".
match self.read_line()? {
b"invalid_param" => return Ok(()),
_other => {
#[cfg(feature = "logging")]
log::debug!("Error: Module returned \"{:?}\"", _other);
}
}
}
// Should not happen™
Err(Error::InvalidState)
}
}
/// System commands.
impl<F, S, E> Driver<F, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
F: Frequency,
{
/// Destroy this driver instance, return the wrapped serial device.
pub fn free(self) -> S {
self.serial
}
/// Reset and restart the RN module. Return the version string.
pub fn reset(&mut self) -> RnResult<&str, E> {
self.send_raw_command_str(&["sys reset"])
}
/// Reset the module's configuration data and user EEPROM to factory
/// default values and restart the module.
///
/// All configuration parameters will be restored to factory default
/// values. Return the version string.
pub fn factory_reset(&mut self) -> RnResult<&str, E> {
self.send_raw_command_str(&["sys factoryRESET"])
}
///// Delete the current RN2483 module application firmware and ensure_known_state it
///// for firmware upgrade. The module bootloader is then ready to receive
///// new firmware.
/////
///// This command is not unsafe in the sense of memory unsafety, but it can
///// be dangerous because it removes the firmware.
//pub unsafe fn erase_fw(&mut self) -> RnResult<()> {
// self.send_raw_command(&["sys eraseFW"])?;
// TODO: Does this return anything?
// Ok(())
//}
/// Return the preprogrammed EUI node address as uppercase hex string.
pub fn hweui(&mut self) -> RnResult<&str, E> {
self.send_raw_command_str(&["sys get hweui"])
}
/// Return the version string.
pub fn version(&mut self) -> RnResult<&str, E> {
self.send_raw_command_str(&["sys get ver"])
}
/// Return the model of the module.
pub fn model(&mut self) -> RnResult<Model, E> {
let version = self.version()?;
match &version[0..6] {
"RN2483" => Ok(Model::RN2483),
"RN2903" => Ok(Model::RN2903),
_ => Err(Error::ParsingError),
}
}
/// Measure and return the Vdd voltage in millivolts.
pub fn vdd(&mut self) -> RnResult<u16, E> {
let vdd = self.send_raw_command_str(&["sys get vdd"])?;
vdd.parse().map_err(|_| Error::ParsingError)
}
/// Set the NVM byte at `addr` to the specified value.
///
/// The address must be between 0x300 and 0x3ff, otherwise
/// `Error::BadParameter` is returned.
pub fn nvm_set(&mut self, addr: u16, byte: u8) -> RnResult<(), E> {
if addr < 0x300 || addr > 0x3ff {
return Err(Error::BadParameter);
}
let mut hex_addr_buf = [0; 4];
let addr_buf_byte_count = base16::encode_config_slice(
&addr.to_be_bytes(),
base16::EncodeLower,
&mut hex_addr_buf,
);
let hex_addr = from_utf8(&hex_addr_buf[..addr_buf_byte_count]).unwrap();
let hex_byte_bytes = base16::encode_byte_l(byte);
let hex_byte = from_utf8(&hex_byte_bytes).unwrap();
let args = ["sys set nvm ", utils::ltrim_hex(&hex_addr), " ", &hex_byte];
self.send_raw_command_ok(&args)
}
/// Get the NVM byte at `addr`.
///
/// The address must be between 0x300 and 0x3ff, otherwise
/// `Error::BadParameter` is returned.
pub fn nvm_get(&mut self, addr: u16) -> RnResult<u8, E> {
if addr < 0x300 || addr > 0x3ff {
return Err(Error::BadParameter);
}
let mut hex_addr_buf = [0; 4];
let addr_buf_byte_count = base16::encode_config_slice(
&addr.to_be_bytes(),
base16::EncodeLower,
&mut hex_addr_buf,
);
let hex_addr = from_utf8(&hex_addr_buf[..addr_buf_byte_count]).unwrap();
let response = self.send_raw_command(&["sys get nvm ", utils::ltrim_hex(&hex_addr)])?;
if response.len() != 2 {
return Err(Error::ParsingError);
}
let mut buf = [0; 1];
base16::decode_slice(response, &mut buf).map_err(|_| Error::ParsingError)?;
Ok(buf[0])
}
/// Put the system to sleep (with millisecond precision).
///
/// The module can be forced to exit from sleep by sending a break
/// condition followed by a 0x55 character at the new baud rate.
///
/// **Note:** This command is asynchronous, it will *not* wait for the module
/// to wake up. You need to call [`wait_for_wakeup()`][wait_for_wakeup] to
/// wait for the module before sending any other command.
///
/// [wait_for_wakeup]: #method.wait_for_wakeup
pub fn sleep(&mut self, duration: Duration) -> RnResult<(), E> {
// Split duration into seconds and milliseconds
let secs: u64 = duration.as_secs();
let subsec_millis: u32 = duration.subsec_millis();
// Millis must be in the range [100, 2^32).
// Do this the awkward way to avoid using the u128 type that `as_millis` returns.
let millis: u32 = if secs == 0 && subsec_millis < 100 {
return Err(Error::BadParameter);
} else if (secs < 4_294_967) || (secs == 4_294_967 && subsec_millis <= 295) {
(secs * 1000) as u32 + duration.subsec_millis()
} else {
return Err(Error::BadParameter);
};
let mut buf = [0u8; 10];
self.send_raw_command_nowait(&["sys sleep ", millis.numtoa_str(10, &mut buf)])?;
self.sleep = true;
Ok(())
}
/// After [sleep mode][sleep] has been enabled, wait for wakeup and clear
/// the `sleep` flag.
///
/// If a sleep is in progress, this will block until the module sends a
/// line on the serial bus.
///
/// If the `sleep` flag is not set, then the method will return immediately
/// without a serial read unless the `force` flag is set to `true`. This is
/// required if you create a new driver instance for a module that is still
/// in sleep mode.
///
/// **Note:** If the module responds with a response that is not the string
/// `"ok"`, a [`Error::ParsingError`][parsing-error] will be returned, but
/// the `sleep` flag will still be cleared (since the module is obviously
/// not in sleep mode anymore).
///
/// [sleep]: #method.sleep
/// [parsing-error]: errors/enum.Error.html#variant.ParsingError
pub fn wait_for_wakeup(&mut self, force: bool) -> RnResult<(), E> {
// If no sleep is in progress, return immediately
if !force && !self.sleep {
return Ok(());
}
// Wait for "ok" response.
// If any response is returned, the `sleep` flag will be cleared.
match self.read_line()? {
b"ok" => {
self.sleep = false;
Ok(())
}
_ => {
self.sleep = false;
Err(Error::ParsingError)
}
}
}
}
/// Macro to generate setters and getters for MAC parameters.
macro_rules! hex_setter_getter {
(
$field:expr, $bytes:expr, $descr:expr,
$set_hex:ident, $set_slice:ident
) => {
doc_comment! {
concat!(
"Set ",
$descr,
".",
"\n\nThe parameter must be a ", stringify!($bytes), "-byte hex string, ",
"otherwise `Error::BadParameter` will be returned.",
),
pub fn $set_hex(&mut self, val: &str) -> RnResult<(), E> {
if val.len() != $bytes * 2 {
return Err(Error::BadParameter);
}
self.send_raw_command_ok(&[concat!("mac set ", $field, " "), val])
}
}
doc_comment! {
concat!(
"Set ",
$descr,
".",
"\n\nThe parameter must be a ", stringify!($bytes), "-byte ",
"big endian byte slice, otherwise `Error::BadParameter` will be returned.",
),
pub fn $set_slice(&mut self, val: &[u8]) -> RnResult<(), E> {
if val.len() != $bytes {
return Err(Error::BadParameter);
}
let mut buf = [0; $bytes * 2];
base16::encode_config_slice(val, base16::EncodeLower, &mut buf);
self.$set_hex(from_utf8(&buf)?)
}
}
};
(
$field:expr, $bytes:expr, $descr:expr,
$set_hex:ident, $set_slice:ident,
$get_hex:ident, $get_slice:ident,
$(,)?
) => {
hex_setter_getter!($field, $bytes, $descr, $set_hex, $set_slice);
doc_comment! {
concat!("Get ", $descr, " as hex str."),
pub fn $get_hex(&mut self) -> RnResult<&str, E> {
self.send_raw_command_str(&[concat!("mac get ", $field)])
}
}
doc_comment! {
concat!("Get ", $descr, " bytes."),
pub fn $get_slice(&mut self) -> RnResult<[u8; $bytes], E> {
let hex = self.$get_hex()?;
let mut buf = [0; $bytes];
base16::decode_slice(hex, &mut buf).map_err(|_| Error::ParsingError)?;
Ok(buf)
}
}
};
// Allow trailing commas
($field:expr, $bytes:expr, $descr:expr, $set_hex:ident, $set_slice:ident,) => {
hex_setter_getter!($field, $bytes, $descr, $set_hex, $set_slice);
};
($field:expr, $bytes:expr, $descr:expr, $set_hex:ident, $set_slice:ident, $get_hex:ident, $get_slice:ident,) => {
hex_setter_getter!($field, $bytes, $descr, $set_hex, $set_slice, $get_hex, $get_slice);
};
}
/// MAC commands.
impl<F, S, E> Driver<F, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
F: Frequency,
{
/// Save MAC configuration parameters.
///
/// This command will save LoRaWAN Class A protocol configuration
/// parameters to the user EEPROM. When the next [`sys
/// reset`](#method.reset) command is issued, the LoRaWAN Class A protocol
/// configuration will be initialized with the last saved parameters.
///
/// The LoRaWAN Class A protocol configuration savable parameters are:
/// `band`, `deveui`, `appeui`, `appkey`, `nwkskey`, `appskey`, `devaddr`
/// as well as all channel parameters (e.g. frequeny, duty cycle, data).
pub fn save_config(&mut self) -> RnResult<(), E> {
self.send_raw_command_ok(&["mac save"])
}
hex_setter_getter!(
"devaddr",
4,
"the unique network device address",
set_dev_addr_hex,
set_dev_addr_slice,
get_dev_addr_hex,
get_dev_addr_slice,
);
hex_setter_getter!(
"deveui",
8,
"the globally unique device identifier",
set_dev_eui_hex,
set_dev_eui_slice,
get_dev_eui_hex,
get_dev_eui_slice,
);
hex_setter_getter!(
"appeui",
8,
"the globally unique application identifier",
set_app_eui_hex,
set_app_eui_slice,
get_app_eui_hex,
get_app_eui_slice,
);
hex_setter_getter!(
"nwkskey",
16,
"the network session key",
set_network_session_key_hex,
set_network_session_key_slice,
);
hex_setter_getter!(
"appskey",
16,
"the application session key",
set_app_session_key_hex,
set_app_session_key_slice,
);
hex_setter_getter!(
"appkey",
16,
"the application key",
set_app_key_hex,
set_app_key_slice,
);
/// Set whether the ADR (adaptive data rate) mechanism is enabled.
pub fn set_adr(&mut self, enabled: bool) -> RnResult<(), E> {
let state = if enabled { "on" } else { "off" };
self.send_raw_command_ok(&["mac set adr ", state])
}
/// Return whether the ADR (adaptive data rate) mechanism is enabled.
pub fn get_adr(&mut self) -> RnResult<bool, E> {
match self.send_raw_command_str(&["mac get adr"])? {
"on" => Ok(true),
"off" => Ok(false),
_ => Err(Error::ParsingError),
}
}
/// Set the up frame counter.
pub fn set_upctr(&mut self, upctr: u32) -> RnResult<(), E> {
let mut buf = [0u8; 10];
self.send_raw_command_ok(&["mac set upctr ", upctr.numtoa_str(10, &mut buf)])
}
/// Get the up frame counter.
pub fn get_upctr(&mut self) -> RnResult<u32, E> {
let ctr = self.send_raw_command_str(&["mac get upctr"])?;
ctr.parse().map_err(|_| Error::ParsingError)
}
/// Set the down frame counter.
pub fn set_dnctr(&mut self, dnctr: u32) -> RnResult<(), E> {
let mut buf = [0u8; 10];
self.send_raw_command_ok(&["mac set dnctr ", dnctr.numtoa_str(10, &mut buf)])
}
/// Get the down frame counter.
pub fn get_dnctr(&mut self) -> RnResult<u32, E> {
let ctr = self.send_raw_command_str(&["mac get dnctr"])?;
ctr.parse().map_err(|_| Error::ParsingError)
}
/// Join the network.
pub fn join(&mut self, mode: JoinMode) -> Result<(), JoinError<E>> {
let mode_str = match mode {
JoinMode::Otaa => "otaa",
JoinMode::Abp => "abp",
};
// First response is whether the join procedure was initialized properly.
match self.send_raw_command_str(&["mac join ", mode_str])? {
"ok" => {}
"invalid_param" => return Err(JoinError::BadParameter),
"keys_not_init" => return Err(JoinError::KeysNotInit),
"no_free_ch" => return Err(JoinError::NoFreeChannel),
"silent" => return Err(JoinError::Silent),
"busy" => return Err(JoinError::Busy),
"mac_paused" => return Err(JoinError::MacPaused),
"denied" => return Err(JoinError::JoinUnsuccessful),
_ => return Err(JoinError::UnknownResponse),
};
// Second response indicates whether the join procedure succeeded.
match self.read_line()? {
b"denied" => Err(JoinError::JoinUnsuccessful),
b"accepted" => Ok(()),
_ => Err(JoinError::UnknownResponse),
}
}
/// Send a hex uplink on the specified port.
///
/// If a downlink is received, it is returned.
pub fn transmit_hex(
&mut self,
mode: ConfirmationMode,
port: u8,
data: &str,
) -> Result<Option<Downlink>, TxError<E>> {
// Validate and parse arguments
if data.len() % 2 != 0 {
return Err(TxError::BadParameter);
}
utils::validate_port(port, TxError::BadParameter)?;
let mode_str = match mode {
ConfirmationMode::Confirmed => "cnf",
ConfirmationMode::Unconfirmed => "uncnf",
};
let mut buf = [0; 3];
let port_str = utils::u8_to_str(port, &mut buf)?;
// First response is whether the uplink transmission could be initialized.
match self.send_raw_command(&["mac tx ", mode_str, " ", port_str, " ", data])? {
b"ok" => {}
b"invalid_param" => return Err(TxError::BadParameter),
b"not_joined" => return Err(TxError::NotJoined),
b"no_free_ch" => return Err(TxError::NoFreeChannel),
b"silent" => return Err(TxError::Silent),
b"frame_counter_err_rejoin_needed" => return Err(TxError::FrameCounterRollover),
b"busy" => return Err(TxError::Busy),
b"mac_paused" => return Err(TxError::MacPaused),
b"invalid_data_len" => return Err(TxError::InvalidDataLenth),
_ => return Err(TxError::UnknownResponse),
};
// The second response could contain an error or a downlink.
match self.read_line()? {
b"mac_tx_ok" => Ok(None),
b"mac_err" => Err(TxError::TxUnsuccessful),
b"invalid_data_len" => Err(TxError::InvalidDataLenth),
val if val.starts_with(b"mac_rx ") => {
let mut parts = from_utf8(val)?.split_ascii_whitespace();
// Get port
let _ = parts.next().ok_or(TxError::Other(Error::ParsingError))?;
let port_str = parts.next().ok_or(TxError::Other(Error::ParsingError))?;
let port =
u8::from_str(&port_str).map_err(|_| TxError::Other(Error::ParsingError))?;
utils::validate_port(port, TxError::Other(Error::ParsingError))?;
// Get data
let hexdata = parts.next().ok_or(TxError::Other(Error::ParsingError))?;
if hexdata.len() % 2 != 0 {
return Err(TxError::Other(Error::ParsingError));
}
Ok(Some(Downlink { port, hexdata }))
}
_ => Err(TxError::UnknownResponse),
}
}
/// Send an uplink on the specified port.
///
/// If a downlink is received, it is returned.
pub fn transmit_slice(
&mut self,
mode: ConfirmationMode,
port: u8,
data: &[u8],
) -> Result<Option<Downlink>, TxError<E>> {
let mut buf = [0; 256];
let bytes = base16::encode_config_slice(data, base16::EncodeLower, &mut buf);
self.transmit_hex(mode, port, from_utf8(&buf[0..bytes])?)
}
}
/// MAC commands for 433 MHz modules.
impl<S, E> Driver<Freq433, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
{
/// Set the data rate to be used for the following transmissions.
pub fn set_data_rate(&mut self, data_rate: DataRateEuCn) -> RnResult<(), E> {
self.send_raw_command_ok(&["mac set dr ", data_rate.into()])
}
/// Return the currently configured data rate.
pub fn get_data_rate(&mut self) -> RnResult<DataRateEuCn, E> {
let dr = self.send_raw_command_str(&["mac get dr"])?;
DataRateEuCn::try_from(dr).map_err(|_| Error::ParsingError)
}
}
/// MAC commands for 868 MHz modules.
impl<S, E> Driver<Freq868, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
{
/// Set the data rate to be used for the following transmissions.
pub fn set_data_rate(&mut self, data_rate: DataRateEuCn) -> RnResult<(), E> {
self.send_raw_command_ok(&["mac set dr ", data_rate.into()])
}
/// Return the currently configured data rate.
pub fn get_data_rate(&mut self) -> RnResult<DataRateEuCn, E> {
let dr = self.send_raw_command_str(&["mac get dr"])?;
DataRateEuCn::try_from(dr).map_err(|_| Error::ParsingError)
}
}
/// MAC commands for 915 MHz modules.
impl<S, E> Driver<Freq915, S>
where
S: serial::Read<u8, Error = E> + serial::Write<u8, Error = E>,
{
/// Set the data rate to be used for the following transmissions.
pub fn set_data_rate(&mut self, data_rate: DataRateUs) -> RnResult<(), E> {
self.send_raw_command_ok(&["mac set dr ", data_rate.into()])
}
/// Return the currently configured data rate.
pub fn get_data_rate(&mut self) -> RnResult<DataRateUs, E> {
let dr = self.send_raw_command_str(&["mac get dr"])?;
DataRateUs::try_from(dr).map_err(|_| Error::ParsingError)
}
}
#[cfg(test)]
mod tests {
use super::*;
use embedded_hal_mock::serial::{Mock as SerialMock, Transaction};
use embedded_hal_mock::MockError;
const VERSION48: &str = "RN2483 1.0.3 Mar 22 2017 06:00:42";
const VERSION90: &str = "RN2903 1.0.3 Mar 22 2017 06:00:42";
const CRLF: &str = "\r\n";
#[test]
fn version() {
let expectations = [
Transaction::write_many(b"sys get ver\r\n"),
Transaction::read_many(VERSION48.as_bytes()),
Transaction::read_many(CRLF.as_bytes()),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.version().unwrap(), VERSION48);
mock.done();
}
#[test]
fn model_rn2483() {
let expectations = [
Transaction::write_many(b"sys get ver\r\n"),
Transaction::read_many(VERSION48.as_bytes()),
Transaction::read_many(CRLF.as_bytes()),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.model().unwrap(), Model::RN2483);
mock.done();
}
#[test]
fn model_rn2903() {
let expectations = [
Transaction::write_many(b"sys get ver\r\n"),
Transaction::read_many(VERSION90.as_bytes()),
Transaction::read_many(CRLF.as_bytes()),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.model().unwrap(), Model::RN2903);
mock.done();
}
#[test]
fn nvm_set() {
let expectations = [
Transaction::write_many(b"sys set nvm 3ab 2a\r\n"),
Transaction::read_many(b"ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
rn.nvm_set(0x3ab, 42).unwrap();
mock.done();
}
#[test]
fn nvm_get() {
let expectations = [
Transaction::write_many(b"sys get nvm 300\r\n"),
Transaction::read_many(b"ff\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.nvm_get(0x300).unwrap(), 0xff);
mock.done();
}
/// Validate length of value passed to generated methods.
/// Ensure that nothing is read/written to/from the serial device.
#[test]
fn set_dev_addr_bad_length() {
let expectations = [];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.set_dev_addr_hex("010203f"), Err(Error::BadParameter));
assert_eq!(rn.set_dev_addr_hex("010203fff"), Err(Error::BadParameter));
assert_eq!(
rn.set_dev_eui_hex("0004a30b001a55e"),
Err(Error::BadParameter)
);
assert_eq!(
rn.set_dev_eui_hex("0004a30b001a55edx"),
Err(Error::BadParameter)
);
mock.done();
}
fn _set_dev_addr() -> (SerialMock<u8>, Driver<Freq868, SerialMock<u8>>) {
let expectations = [
Transaction::write_many(b"mac set devaddr 010203ff\r\n"),
Transaction::read_many(b"ok\r\n"),
];
let mock = SerialMock::new(&expectations);
let rn = rn2483_868(mock.clone());
(mock, rn)
}
#[test]
fn set_dev_addr_hex() {
let (mut mock, mut rn) = _set_dev_addr();
assert!(rn.set_dev_addr_hex("010203ff").is_ok());
mock.done();
}
#[test]
fn set_dev_addr_slice() {
let (mut mock, mut rn) = _set_dev_addr();
assert!(rn.set_dev_addr_slice(&[0x01, 0x02, 0x03, 0xff]).is_ok());
mock.done();
}
fn _set_dev_eui() -> (SerialMock<u8>, Driver<Freq868, SerialMock<u8>>) {
let expectations = [
Transaction::write_many(b"mac set deveui 0004a30b001a55ed\r\n".as_ref()),
Transaction::read_many(b"ok\r\n"),
];
let mock = SerialMock::new(&expectations);
let rn = rn2483_868(mock.clone());
(mock, rn)
}
#[test]
fn set_dev_eui_hex() {
let (mut mock, mut rn) = _set_dev_eui();
assert!(rn.set_dev_eui_hex("0004a30b001a55ed").is_ok());
mock.done();
}
#[test]
fn set_dev_eui_slice() {
let (mut mock, mut rn) = _set_dev_eui();
assert!(rn
.set_dev_eui_slice(&[0x00, 0x04, 0xa3, 0x0b, 0x00, 0x1a, 0x55, 0xed])
.is_ok());
mock.done();
}
fn _get_dev_eui() -> (SerialMock<u8>, Driver<Freq868, SerialMock<u8>>) {
let expectations = [
Transaction::write_many(b"mac get deveui\r\n".as_ref()),
Transaction::read_many(b"0004a30b001a55ed\r\n"),
];
let mock = SerialMock::new(&expectations);
let rn = rn2483_868(mock.clone());
(mock, rn)
}
#[test]
fn get_dev_eui_hex() {
let (mut mock, mut rn) = _get_dev_eui();
let deveui = rn.get_dev_eui_hex().unwrap();
assert_eq!(deveui, "0004a30b001a55ed");
mock.done();
}
#[test]
fn get_dev_eui_slice() {
let (mut mock, mut rn) = _get_dev_eui();
let deveui = rn.get_dev_eui_slice().unwrap();
assert_eq!(deveui, [0x00, 0x04, 0xa3, 0x0b, 0x00, 0x1a, 0x55, 0xed]);
mock.done();
}
mod data_rate {
use super::*;
#[test]
fn set_sf9_eucn() {
let expectations = [
Transaction::write_many(b"mac set dr 3\r\n"),
Transaction::read_many(b"ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert!(rn.set_data_rate(DataRateEuCn::Sf9Bw125).is_ok());
mock.done();
}
#[test]
fn set_sf9_us() {
let expectations = [
Transaction::write_many(b"mac set dr 1\r\n"),
Transaction::read_many(b"ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2903_915(mock.clone());
assert!(rn.set_data_rate(DataRateUs::Sf9Bw125).is_ok());
mock.done();
}
#[test]
fn set_sf12_eucn() {
let expectations = [
Transaction::write_many(b"mac set dr 0\r\n"),
Transaction::read_many(b"ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert!(rn.set_data_rate(DataRateEuCn::Sf12Bw125).is_ok());
mock.done();
}
#[test]
fn get_sf7_us() {
let expectations = [
Transaction::write_many(b"mac get dr\r\n"),
Transaction::read_many(b"4\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2903_915(mock.clone());
assert_eq!(rn.get_data_rate().unwrap(), DataRateUs::Sf8Bw500);
mock.done();
}
}
mod adr {
use super::*;
#[test]
fn get_on() {
let expectations = [
Transaction::write_many(b"mac get adr\r\n"),
Transaction::read_many(b"on\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert!(rn.get_adr().unwrap());
mock.done();
}
#[test]
fn get_off() {
let expectations = [
Transaction::write_many(b"mac get adr\r\n"),
Transaction::read_many(b"off\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert!(!rn.get_adr().unwrap());
mock.done();
}
#[test]
fn get_invalid() {
let expectations = [
Transaction::write_many(b"mac get adr\r\n"),
Transaction::read_many(b"of\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.get_adr().unwrap_err(), Error::ParsingError);
mock.done();
}
#[test]
fn set() {
let expectations = [
Transaction::write_many(b"mac set adr on\r\n"),
Transaction::read_many(b"ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert!(rn.set_adr(true).is_ok());
mock.done();
}
}
mod sleep {
use super::*;
#[test]
fn sleep_min_max_duration() {
// Min duration: 100ms
let expectations = [Transaction::write_many(b"sys sleep 100\r\n")];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert!(rn.sleep(Duration::from_millis(100)).is_ok());
mock.done();
// Max duration: (2**32)-1 ms
let expectations = [Transaction::write_many(b"sys sleep 4294967295\r\n")];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert!(rn.sleep(Duration::from_millis((1 << 32) - 1)).is_ok());
mock.done();
}
#[test]
fn sleep_invalid_durations() {
let expectations = [];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.sleep(Duration::from_millis(0)), Err(Error::BadParameter));
assert_eq!(
rn.sleep(Duration::from_millis(99)),
Err(Error::BadParameter)
);
assert_eq!(
rn.sleep(Duration::from_millis(1 << 32)),
Err(Error::BadParameter)
);
mock.done();
}
/// While the sleep mode flag is set, don't issue any serial writes.
#[test]
fn sleep_mode_no_write() {
let expectations = [Transaction::write_many(b"sys sleep 1000\r\n")];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
// Put device into sleep mode
rn.sleep(Duration::from_secs(1)).unwrap();
// A write call should now fail without causing a write transaction
assert_eq!(rn.write_all(b"123"), Err(Error::SleepMode));
assert_eq!(rn.write_crlf(), Err(Error::SleepMode));
mock.done();
}
/// Waiting for wakeup will return immediately (without a read) if no
/// sleep is in progress.
#[test]
fn wait_for_wakeup_immediate() {
// Waiting for wakeup should not cause a read transaction...
let expectations = [];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.wait_for_wakeup(false), Ok(()));
assert_eq!(rn.wait_for_wakeup(false), Ok(()));
assert_eq!(rn.wait_for_wakeup(false), Ok(()));
mock.done();
// ...unless the `force` flag is set.
let expectations = [Transaction::read_many(b"ok\r\n")];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.wait_for_wakeup(true), Ok(()));
mock.done();
}
/// Waiting for wakeup will handle non-"ok" responses as errors.
#[test]
fn wait_for_wakeup_errors() {
let expectations = [Transaction::read_many(b"ohno\r\n")];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
rn.sleep = true;
// Parsing the response will return an error
assert_eq!(rn.wait_for_wakeup(false), Err(Error::ParsingError));
// But the sleep flag will still be cleared
assert!(!rn.sleep);
mock.done();
}
}
mod join {
use super::*;
#[test]
fn otaa_ok() {
let expectations = [
Transaction::write_many(b"mac join otaa\r\n"),
Transaction::read_many(b"ok\r\naccepted\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.join(JoinMode::Otaa), Ok(()));
mock.done();
}
#[test]
fn abp_ok() {
let expectations = [
Transaction::write_many(b"mac join abp\r\n"),
Transaction::read_many(b"ok\r\naccepted\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.join(JoinMode::Abp), Ok(()));
mock.done();
}
#[test]
fn otaa_denied() {
let expectations = [
Transaction::write_many(b"mac join otaa\r\n"),
Transaction::read_many(b"ok\r\ndenied\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.join(JoinMode::Otaa), Err(JoinError::JoinUnsuccessful));
mock.done();
}
#[test]
fn otaa_unknown_response_1() {
let expectations = [
Transaction::write_many(b"mac join otaa\r\n"),
Transaction::read_many(b"xyz\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.join(JoinMode::Otaa), Err(JoinError::UnknownResponse));
mock.done();
}
#[test]
fn otaa_unknown_response_2() {
let expectations = [
Transaction::write_many(b"mac join otaa\r\n"),
Transaction::read_many(b"ok\r\nxyz\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.join(JoinMode::Otaa), Err(JoinError::UnknownResponse));
mock.done();
}
#[test]
fn otaa_no_free_ch() {
let expectations = [
Transaction::write_many(b"mac join otaa\r\n"),
Transaction::read_many(b"no_free_ch\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(rn.join(JoinMode::Otaa), Err(JoinError::NoFreeChannel));
mock.done();
}
}
mod transmit {
use super::*;
#[test]
fn transmit_hex_uncnf_no_downlink() {
let expectations = [
Transaction::write_many(b"mac tx uncnf 42 23ff\r\n"),
Transaction::read_many(b"ok\r\nmac_tx_ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(
rn.transmit_hex(ConfirmationMode::Unconfirmed, 42, "23ff"),
Ok(None)
);
mock.done();
}
#[test]
fn transmit_hex_cnf_no_downlink() {
let expectations = [
Transaction::write_many(b"mac tx cnf 42 23ff\r\n"),
Transaction::read_many(b"ok\r\nmac_tx_ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(
rn.transmit_hex(ConfirmationMode::Confirmed, 42, "23ff"),
Ok(None)
);
mock.done();
}
#[test]
fn transmit_hex_uncnf_downlink() {
let expectations = [
Transaction::write_many(b"mac tx uncnf 42 23ff\r\n"),
Transaction::read_many(b"ok\r\nmac_rx 101 000102feff\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(
rn.transmit_hex(ConfirmationMode::Unconfirmed, 42, "23ff"),
Ok(Some(Downlink {
port: 101,
hexdata: "000102feff",
}))
);
mock.done();
}
#[test]
fn transmit_slice_uncnf_no_downlink() {
let expectations = [
Transaction::write_many(b"mac tx uncnf 42 23ff\r\n"),
Transaction::read_many(b"ok\r\nmac_tx_ok\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
assert_eq!(
rn.transmit_slice(ConfirmationMode::Unconfirmed, 42, &[0x23, 0xff]),
Ok(None),
);
mock.done();
}
}
mod ensure_known_state {
use super::*;
use std::io::ErrorKind;
#[test]
fn already_clean() {
let expectations = [
// Our initial buffer is empty
Transaction::read_error(nb::Error::WouldBlock),
// Expect the 'z' write
Transaction::write_many(b"z\r\n"),
// Read returns invalid_param
Transaction::read_many(b"invalid_param\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
rn.ensure_known_state().unwrap();
mock.done();
}
#[test]
fn non_empty_buffer() {
let expectations = [
// Our initial buffer still contains some bytes
Transaction::read_many(b"sys "),
Transaction::read_many(b"reset"),
Transaction::read_error(nb::Error::WouldBlock),
// Expect the 'z' write
Transaction::write_many(b"z\r\n"),
// Read returns invalid_param
Transaction::read_many(b"invalid_param\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
rn.ensure_known_state().unwrap();
mock.done();
}
#[test]
fn retry() {
let expectations = [
// Initial buffer empty
Transaction::read_error(nb::Error::WouldBlock),
// Expect the 'z' write
Transaction::write_many(b"z\r\n"),
// Read returns unexpected data
Transaction::read_many(b"ok\r\n"),
// Expect the 'z' write again (attempt 2)
Transaction::write_many(b"z\r\n"),
// Still unexpected data
Transaction::read_many(b"wtf\r\n"),
// Expect the 'z' write again (attempt 3)
Transaction::write_many(b"z\r\n"),
// Finally!
Transaction::read_many(b"invalid_param\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
rn.ensure_known_state().unwrap();
mock.done();
}
#[test]
fn retry_failed() {
let expectations = [
// Initial buffer empty
Transaction::read_error(nb::Error::WouldBlock),
// Unexpected response for 3 consecutive attempts
Transaction::write_many(b"z\r\n"),
Transaction::read_many(b"uhm\r\n"),
Transaction::write_many(b"z\r\n"),
Transaction::read_many(b"lol\r\n"),
Transaction::write_many(b"z\r\n"),
Transaction::read_many(b"wat\r\n"),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
// Fail after 3 attempts
assert_eq!(rn.ensure_known_state().unwrap_err(), Error::InvalidState);
mock.done();
}
#[test]
fn read_error() {
let expectations = [
// Read fails with an error
Transaction::read_error(nb::Error::Other(MockError::Io(ErrorKind::BrokenPipe))),
];
let mut mock = SerialMock::new(&expectations);
let mut rn = rn2483_868(mock.clone());
// Errors while reading are propagated
assert_eq!(
rn.ensure_known_state().unwrap_err(),
Error::SerialRead(MockError::Io(ErrorKind::BrokenPipe))
);
mock.done();
}
}
}
|
use super::error::{PineError, PineErrorKind, PineResult};
use super::input::{Input, Position, StrRange};
use super::state::{AstState, PineInputError};
use super::utils::skip_ws;
use nom::{
bytes::complete::{tag, take_while},
combinator::recognize,
sequence::tuple,
Err,
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ColorNode<'a> {
pub value: &'a str,
pub range: StrRange,
}
impl<'a> ColorNode<'a> {
#[inline]
pub fn new(value: &'a str, range: StrRange) -> ColorNode<'a> {
ColorNode { value, range }
}
pub fn from_str(value: &'a str) -> ColorNode<'a> {
ColorNode {
value,
range: StrRange::from_start(value, Position::new(0, 0)),
}
}
}
fn is_hex_digit(c: char) -> bool {
c.is_digit(16)
}
pub fn color_lit<'a>(input: Input<'a>, state: &AstState) -> PineResult<'a, ColorNode<'a>> {
let (input, _) = skip_ws(input)?;
let (next_input, out) = recognize(tuple((tag("#"), take_while(is_hex_digit))))(input)?;
match out.len() {
7 | 9 => Ok((
next_input,
ColorNode::new(out.src, StrRange::from_input(&out)),
)),
_ => {
state.catch(PineInputError::new(
PineErrorKind::InvalidColorLiteral,
StrRange::from_input(&out),
));
Ok((
next_input,
ColorNode::new(out.src, StrRange::from_input(&out)),
))
}
}
}
#[cfg(test)]
mod tests {
use super::super::input::Position;
use super::*;
#[test]
fn color_lit_test() {
assert_eq!(
color_lit(Input::new_with_str(" #123456 d"), &AstState::new()),
Ok((
Input::new(" d", Position::new(0, 8), Position::max()),
ColorNode::new(
"#123456",
StrRange::from_start("#123456", Position::new(0, 1))
)
))
);
}
}
|
#[macro_export]
macro_rules! morgan_exchange_controller {
() => {
(
"morgan_exchange_controller".to_string(),
morgan_exchange_api::id(),
)
};
}
use morgan_exchange_api::exchange_processor::process_instruction;
morgan_interface::morgan_entrypoint!(process_instruction);
|
use crate::any::{Any, AnyTypeInfo};
use crate::column::{Column, ColumnIndex};
#[cfg(feature = "postgres")]
use crate::postgres::{PgColumn, PgRow, PgStatement};
#[cfg(feature = "mysql")]
use crate::mysql::{MySqlColumn, MySqlRow, MySqlStatement};
#[cfg(feature = "sqlite")]
use crate::sqlite::{SqliteColumn, SqliteRow, SqliteStatement};
#[cfg(feature = "mssql")]
use crate::mssql::{MssqlColumn, MssqlRow, MssqlStatement};
#[derive(Debug, Clone)]
pub struct AnyColumn {
pub(crate) kind: AnyColumnKind,
pub(crate) type_info: AnyTypeInfo,
}
impl crate::column::private_column::Sealed for AnyColumn {}
#[derive(Debug, Clone)]
pub(crate) enum AnyColumnKind {
#[cfg(feature = "postgres")]
Postgres(PgColumn),
#[cfg(feature = "mysql")]
MySql(MySqlColumn),
#[cfg(feature = "sqlite")]
Sqlite(SqliteColumn),
#[cfg(feature = "mssql")]
Mssql(MssqlColumn),
}
impl Column for AnyColumn {
type Database = Any;
fn ordinal(&self) -> usize {
match &self.kind {
#[cfg(feature = "postgres")]
AnyColumnKind::Postgres(row) => row.ordinal(),
#[cfg(feature = "mysql")]
AnyColumnKind::MySql(row) => row.ordinal(),
#[cfg(feature = "sqlite")]
AnyColumnKind::Sqlite(row) => row.ordinal(),
#[cfg(feature = "mssql")]
AnyColumnKind::Mssql(row) => row.ordinal(),
}
}
fn name(&self) -> &str {
match &self.kind {
#[cfg(feature = "postgres")]
AnyColumnKind::Postgres(row) => row.name(),
#[cfg(feature = "mysql")]
AnyColumnKind::MySql(row) => row.name(),
#[cfg(feature = "sqlite")]
AnyColumnKind::Sqlite(row) => row.name(),
#[cfg(feature = "mssql")]
AnyColumnKind::Mssql(row) => row.name(),
}
}
fn type_info(&self) -> &AnyTypeInfo {
&self.type_info
}
}
// FIXME: Find a nice way to auto-generate the below or petition Rust to add support for #[cfg]
// to trait bounds
// all 4
#[cfg(all(
feature = "postgres",
feature = "mysql",
feature = "mssql",
feature = "sqlite"
))]
pub trait AnyColumnIndex:
ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
feature = "postgres",
feature = "mysql",
feature = "mssql",
feature = "sqlite"
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
// only 3 (4)
#[cfg(all(
not(feature = "mssql"),
all(feature = "postgres", feature = "mysql", feature = "sqlite")
))]
pub trait AnyColumnIndex:
ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(feature = "mssql"),
all(feature = "postgres", feature = "mysql", feature = "sqlite")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(feature = "mysql"),
all(feature = "postgres", feature = "mssql", feature = "sqlite")
))]
pub trait AnyColumnIndex:
ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(feature = "mysql"),
all(feature = "postgres", feature = "mssql", feature = "sqlite")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(feature = "sqlite"),
all(feature = "postgres", feature = "mysql", feature = "mssql")
))]
pub trait AnyColumnIndex:
ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
{
}
#[cfg(all(
not(feature = "sqlite"),
all(feature = "postgres", feature = "mysql", feature = "mssql")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
{
}
#[cfg(all(
not(feature = "postgres"),
all(feature = "sqlite", feature = "mysql", feature = "mssql")
))]
pub trait AnyColumnIndex:
ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
{
}
#[cfg(all(
not(feature = "postgres"),
all(feature = "sqlite", feature = "mysql", feature = "mssql")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
{
}
// only 2 (6)
#[cfg(all(
not(any(feature = "mssql", feature = "sqlite")),
all(feature = "postgres", feature = "mysql")
))]
pub trait AnyColumnIndex:
ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mssql", feature = "sqlite")),
all(feature = "postgres", feature = "mysql")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mysql", feature = "sqlite")),
all(feature = "postgres", feature = "mssql")
))]
pub trait AnyColumnIndex:
ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mysql", feature = "sqlite")),
all(feature = "postgres", feature = "mssql")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mysql", feature = "mssql")),
all(feature = "postgres", feature = "sqlite")
))]
pub trait AnyColumnIndex:
ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mysql", feature = "mssql")),
all(feature = "postgres", feature = "sqlite")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow>
+ for<'q> ColumnIndex<PgStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "postgres", feature = "sqlite")),
all(feature = "mssql", feature = "mysql")
))]
pub trait AnyColumnIndex:
ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "postgres", feature = "sqlite")),
all(feature = "mssql", feature = "mysql")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "postgres", feature = "mysql")),
all(feature = "mssql", feature = "sqlite")
))]
pub trait AnyColumnIndex:
ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "postgres", feature = "mysql")),
all(feature = "mssql", feature = "sqlite")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<MssqlRow>
+ for<'q> ColumnIndex<MssqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "postgres", feature = "mssql")),
all(feature = "mysql", feature = "sqlite")
))]
pub trait AnyColumnIndex:
ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "postgres", feature = "mssql")),
all(feature = "mysql", feature = "sqlite")
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<MySqlRow>
+ for<'q> ColumnIndex<MySqlStatement<'q>>
+ ColumnIndex<SqliteRow>
+ for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
// only 1 (4)
#[cfg(all(
not(any(feature = "mysql", feature = "mssql", feature = "sqlite")),
feature = "postgres"
))]
pub trait AnyColumnIndex: ColumnIndex<PgRow> + for<'q> ColumnIndex<PgStatement<'q>> {}
#[cfg(all(
not(any(feature = "mysql", feature = "mssql", feature = "sqlite")),
feature = "postgres"
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<PgRow> + for<'q> ColumnIndex<PgStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "postgres", feature = "mssql", feature = "sqlite")),
feature = "mysql"
))]
pub trait AnyColumnIndex: ColumnIndex<MySqlRow> + for<'q> ColumnIndex<MySqlStatement<'q>> {}
#[cfg(all(
not(any(feature = "postgres", feature = "mssql", feature = "sqlite")),
feature = "mysql"
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<MySqlRow> + for<'q> ColumnIndex<MySqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mysql", feature = "postgres", feature = "sqlite")),
feature = "mssql"
))]
pub trait AnyColumnIndex: ColumnIndex<MssqlRow> + for<'q> ColumnIndex<MssqlStatement<'q>> {}
#[cfg(all(
not(any(feature = "mysql", feature = "postgres", feature = "sqlite")),
feature = "mssql"
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<MssqlRow> + for<'q> ColumnIndex<MssqlStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mysql", feature = "mssql", feature = "postgres")),
feature = "sqlite"
))]
pub trait AnyColumnIndex:
ColumnIndex<SqliteRow> + for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
#[cfg(all(
not(any(feature = "mysql", feature = "mssql", feature = "postgres")),
feature = "sqlite"
))]
impl<I: ?Sized> AnyColumnIndex for I where
I: ColumnIndex<SqliteRow> + for<'q> ColumnIndex<SqliteStatement<'q>>
{
}
|
#![allow(dead_code, non_camel_case_types)]
extern crate libc;
pub use self::utmpx::{DEFAULT_FILE,USER_PROCESS,BOOT_TIME,c_utmp};
#[cfg(target_os = "linux")]
mod utmpx {
use super::libc;
pub static DEFAULT_FILE: &'static str = "/var/run/utmp";
pub const UT_LINESIZE: usize = 32;
pub const UT_NAMESIZE: usize = 32;
pub const UT_IDSIZE: usize = 4;
pub const UT_HOSTSIZE: usize = 256;
pub const EMPTY: libc::c_short = 0;
pub const RUN_LVL: libc::c_short = 1;
pub const BOOT_TIME: libc::c_short = 2;
pub const NEW_TIME: libc::c_short = 3;
pub const OLD_TIME: libc::c_short = 4;
pub const INIT_PROCESS: libc::c_short = 5;
pub const LOGIN_PROCESS: libc::c_short = 6;
pub const USER_PROCESS: libc::c_short = 7;
pub const DEAD_PROCESS: libc::c_short = 8;
pub const ACCOUNTING: libc::c_short = 9;
#[repr(C)]
pub struct c_exit_status {
pub e_termination: libc::c_short,
pub e_exit: libc::c_short,
}
#[repr(C)]
pub struct c_utmp {
pub ut_type: libc::c_short,
pub ut_pid: libc::pid_t,
pub ut_line: [libc::c_char; UT_LINESIZE],
pub ut_id: [libc::c_char; UT_IDSIZE],
pub ut_user: [libc::c_char; UT_NAMESIZE],
pub ut_host: [libc::c_char; UT_HOSTSIZE],
pub ut_exit: c_exit_status,
pub ut_session: libc::c_long,
pub ut_tv: libc::timeval,
pub ut_addr_v6: [libc::int32_t; 4],
pub __unused: [libc::c_char; 20],
}
}
#[cfg(target_os = "macos")]
mod utmpx {
use super::libc;
pub static DEFAULT_FILE: &'static str = "/var/run/utmpx";
pub const UT_LINESIZE: usize = 32;
pub const UT_NAMESIZE: usize = 256;
pub const UT_IDSIZE: usize = 4;
pub const UT_HOSTSIZE: usize = 256;
pub const EMPTY: libc::c_short = 0;
pub const RUN_LVL: libc::c_short = 1;
pub const BOOT_TIME: libc::c_short = 2;
pub const OLD_TIME: libc::c_short = 3;
pub const NEW_TIME: libc::c_short = 4;
pub const INIT_PROCESS: libc::c_short = 5;
pub const LOGIN_PROCESS: libc::c_short = 6;
pub const USER_PROCESS: libc::c_short = 7;
pub const DEAD_PROCESS: libc::c_short = 8;
pub const ACCOUNTING: libc::c_short = 9;
#[repr(C)]
pub struct c_exit_status {
pub e_termination: libc::c_short,
pub e_exit: libc::c_short,
}
#[repr(C)]
pub struct c_utmp {
pub ut_user: [libc::c_char; UT_NAMESIZE],
pub ut_id: [libc::c_char; UT_IDSIZE],
pub ut_line: [libc::c_char; UT_LINESIZE],
pub ut_pid: libc::pid_t,
pub ut_type: libc::c_short,
pub ut_tv: libc::timeval,
pub ut_host: [libc::c_char; UT_HOSTSIZE],
pub __unused: [libc::c_char; 16]
}
}
#[cfg(target_os = "freebsd")]
mod utmpx {
use super::libc;
pub static DEFAULT_FILE : &'static str = "";
pub const UT_LINESIZE : usize = 16;
pub const UT_NAMESIZE : usize = 32;
pub const UT_IDSIZE : usize = 8;
pub const UT_HOSTSIZE : usize = 128;
pub const EMPTY : libc::c_short = 0;
pub const BOOT_TIME : libc::c_short = 1;
pub const OLD_TIME : libc::c_short = 2;
pub const NEW_TIME : libc::c_short = 3;
pub const USER_PROCESS : libc::c_short = 4;
pub const INIT_PROCESS : libc::c_short = 5;
pub const LOGIN_PROCESS : libc::c_short = 6;
pub const DEAD_PROCESS : libc::c_short = 7;
pub const SHUTDOWN_TIME : libc::c_short = 8;
#[repr(C)]
pub struct c_utmp {
pub ut_type : libc::c_short,
pub ut_tv : libc::timeval,
pub ut_id : [libc::c_char; UT_IDSIZE],
pub ut_pid : libc::pid_t,
pub ut_user : [libc::c_char; UT_NAMESIZE],
pub ut_line : [libc::c_char; UT_LINESIZE],
pub ut_host : [libc::c_char; UT_HOSTSIZE],
pub ut_spare : [libc::c_char; 64],
}
}
|
use std::env;
use std::fs;
use std::io::prelude::*;
use std::io::Write;
use std::process::{Command, Stdio};
const BRIGHTNESS_PATH: &str = "/sys/class/backlight/intel_backlight/brightness";
const MAX_BRIGHTNESS_PATH: &str = "/sys/class/backlight/intel_backlight/max_brightness";
fn get_max_brightness() -> f32 {
let max_brightness_str = fs::read_to_string(MAX_BRIGHTNESS_PATH).expect("file error");
return max_brightness_str.trim().parse::<f32>().unwrap();
}
fn get_brightness() -> f32 {
let brightness_str = fs::read_to_string(BRIGHTNESS_PATH).expect("file error");
return brightness_str.trim().parse::<f32>().unwrap();
}
fn get_monitor_string() -> String {
let xrandr_out = Command::new("xrandr")
.output()
.expect("failed to spawn xrandr")
.stdout;
//let xrandr_out_s = String::from_utf8_lossy(&xrandr_out);
//println!("xrandr output {}", xrandr_out_s);
let grep_ps = Command::new("grep")
.arg("-w")
.arg("connected")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("failed to spawn grep");
grep_ps
.stdin
.unwrap()
.write_all(&xrandr_out)
.expect("unable to write to grep stdin");
let mut grep_out_vec = Vec::new();
grep_ps
.stdout
.unwrap()
.read_to_end(&mut grep_out_vec)
.unwrap();
let awk_ps = Command::new("awk")
.arg("{print $1}")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("unable to spawn awk");
awk_ps
.stdin
.unwrap()
.write_all(&grep_out_vec)
.expect("unable to writeto awk stdin");
let mut awk_out = String::new();
awk_ps.stdout.unwrap().read_to_string(&mut awk_out).unwrap();
println!("your screen {}", awk_out);
return awk_out;
}
#[derive(Debug)]
pub enum InputError {
OutOfBounds,
NotAnInteger,
TooManyArgs,
}
fn get_delta(t: &str) -> Result<i32, InputError> {
let result: Result<f32, _> = t.parse::<f32>();
if let Ok(i) = result {
if i > 100.0 || i <= 0.0 {
return Err(InputError::OutOfBounds);
} else {
let rat = i / 100.0;
let bright_d = rat * get_max_brightness();
println!("new ratio {} brightness delta {}", rat, bright_d);
return Ok(bright_d.round() as i32);
}
} else {
return Err(InputError::NotAnInteger);
}
}
fn add_brightness(t: i32) {
println!("add fn enter {} ", t);
}
fn sub_brightness(t: i32) {
println!("subtract {}", t);
}
fn set_brightness(t: i32) {
println!("set {}", t);
get_monitor_string();
}
fn main() {
let args: Vec<String> = env::args().collect();
let query = &args[1];
let current_ratio = get_brightness() / get_max_brightness();
println!(
"current brightness {} max brightness {} ratio {}",
get_brightness(),
get_max_brightness(),
current_ratio
);
if query == "max" {
println!("setting brightness to max");
} else {
let first_char = &query[0..1];
let the_rest = &query[1..query.len()];
// if first_char == "p" || first_char == "m" {
let bright_d = if first_char == "p" || first_char == "m" {
get_delta(the_rest)
} else {
get_delta(query)
};
match bright_d {
Ok(d) => match first_char {
"p" => add_brightness(d),
"m" => sub_brightness(d),
_ => set_brightness(d),
},
Err(e) => println!("Error {:?}", e),
}
}
}
|
extern crate rand;
extern crate num;
use std::cmp;
use num::{BigUint, Zero, One};
use num::bigint::{ToBigUint, RandBigInt};
pub fn main(){
println!("{}",is_probably_prime("8822644427775620595775115476130893017686687877955563534429320360900846719257311242134794074876598682100945768516181513954573564989496411792485026178767949".parse::<BigUint>().unwrap(),0));
}
fn rabin_miller_witness(test : BigUint, possible : BigUint)->bool{
let v = ipow(test,possible.clone()-1.to_biguint().unwrap(),possible.clone());
for i in v {
if i == 1.to_biguint().unwrap(){
return false;
}
}
return true;
}
fn ipow( a : BigUint, b : BigUint, n : BigUint)->Vec<BigUint>{
let mut res : Vec<BigUint> = vec![];
let mut a = &a % &n;
let mut A = a.clone();
let one = 1.to_biguint().unwrap();
res.push(A.clone());
let mut t : BigUint = One::one();
while (t <= b){
t = &t << 1;
}
t = &t >> 2;
let zero = 0.to_biguint().unwrap();
while(t>zero){
A = (&A*&A)%&n;
if (&t & &b >= one){
A = (&A*&a)%&n;
}
res.push(A.clone());
t = &t >> 1;
}
return res;
}
fn is_probably_prime(possible : BigUint, mut k : u32) -> bool{
if possible.clone() == One::one(){
return true;
}
if k == 0 {
k = default_k(possible.clone().bits() as u32);
}
let smallprimes = vec![2,3,5,7,11,13,17,19,23,29,31,37,41,43,
47,53,59,61,67,71,73,79,83,89,97];
for i in smallprimes {
if possible.clone() == i.to_biguint().unwrap(){
return true;
}
if possible.clone() % i.to_biguint().unwrap() == Zero::zero(){
return false;
}
}
let mut rng = rand::thread_rng();
let two = 2.to_biguint().unwrap();
let one = 1.to_biguint().unwrap();
let pos = &possible - 1.to_biguint().unwrap();
for i in 0 .. k{
println!("i={} of {}",i,k);
let test : BigUint = rng.gen_biguint_range(&two,&pos) | &one;
if rabin_miller_witness(test, possible.clone()){
return false;
} else {
}
}
return true;
}
fn default_k(bits : u32) -> u32{
return cmp::max(40, 2 * bits);
}
fn generate_prime(bits : u32, mut k : u32)->BigUint{
if k == 0 {
k = default_k(bits);
}
let mut rng = rand::thread_rng();
loop {
let possible : BigUint = rng.gen_biguint_range(&(num::pow(2.to_biguint().unwrap(),(bits-1) as usize)+1.to_biguint().unwrap()),&(num::pow(2.to_biguint().unwrap(),(bits) as usize))) | 1.to_biguint().unwrap();
println!("Prime {} ",possible);
if (is_probably_prime(possible.clone(),k)){
return possible;
}
}
}
|
use crate::field::FieldElement;
use bitvec::{order::Lsb0, slice::BitSlice};
use ff::Field;
/// An affine point on an elliptic curve over [FieldElement].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AffinePoint {
pub x: FieldElement,
pub y: FieldElement,
pub infinity: bool,
}
impl From<&ProjectivePoint> for AffinePoint {
fn from(p: &ProjectivePoint) -> Self {
let zinv = p.z.invert().unwrap();
let x = p.x * zinv;
let y = p.y * zinv;
AffinePoint {
x,
y,
infinity: false,
}
}
}
impl AffinePoint {
pub const fn new(x: [u64; 4], y: [u64; 4]) -> Self {
Self {
x: FieldElement::new(x),
y: FieldElement::new(y),
infinity: false,
}
}
pub fn identity() -> Self {
Self {
x: FieldElement::zero(),
y: FieldElement::zero(),
infinity: true,
}
}
pub fn double(&mut self) {
if self.infinity {
return;
}
// l = (3x^2+a)/2y with a=1 from stark curve
let lambda = {
let dividend = FieldElement::THREE * (self.x * self.x) + FieldElement::one();
let divisor_inv = (FieldElement::TWO * self.y).invert().unwrap();
dividend * divisor_inv
};
let result_x = (lambda * lambda) - self.x - self.x;
self.y = lambda * (self.x - result_x) - self.y;
self.x = result_x;
}
pub fn add(&mut self, other: &AffinePoint) {
if other.infinity {
return;
}
if self.infinity {
self.x = other.x;
self.y = other.y;
self.infinity = other.infinity;
return;
}
if self.x == other.x {
if self.y != other.y {
self.infinity = true;
} else {
self.double();
}
return;
}
// l = (y2-y1)/(x2-x1)
let lambda = {
let dividend = other.y - self.y;
let divisor_inv = (other.x - self.x).invert().unwrap();
dividend * divisor_inv
};
let result_x = (lambda * lambda) - self.x - other.x;
self.y = lambda * (self.x - result_x) - self.y;
self.x = result_x;
}
pub fn multiply(&self, bits: &BitSlice<Lsb0, u64>) -> AffinePoint {
let mut product = AffinePoint::identity();
for b in bits.iter().rev() {
product.double();
if *b {
product.add(self);
}
}
product
}
}
/// A projective point on an elliptic curve over [FieldElement].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProjectivePoint {
pub x: FieldElement,
pub y: FieldElement,
pub z: FieldElement,
pub infinity: bool,
}
impl From<&AffinePoint> for ProjectivePoint {
fn from(p: &AffinePoint) -> Self {
let x = p.x;
let y = p.y;
let z = FieldElement::ONE;
ProjectivePoint {
x,
y,
z,
infinity: false,
}
}
}
impl ProjectivePoint {
pub fn identity() -> Self {
Self {
x: FieldElement::zero(),
y: FieldElement::zero(),
z: FieldElement::ONE,
infinity: true,
}
}
pub fn double(&mut self) {
if self.infinity {
return;
}
// t=3x^2+az^2 with a=1 from stark curve
let t = FieldElement::THREE * self.x * self.x + self.z * self.z;
let u = FieldElement::TWO * self.y * self.z;
let v = FieldElement::TWO * u * self.x * self.y;
let w = t * t - FieldElement::TWO * v;
let uy = u * self.y;
let x = u * w;
let y = t * (v - w) - FieldElement::TWO * uy * uy;
let z = u * u * u;
self.x = x;
self.y = y;
self.z = z;
}
pub fn add(&mut self, other: &ProjectivePoint) {
if other.infinity {
return;
}
if self.infinity {
self.x = other.x;
self.y = other.y;
self.z = other.z;
self.infinity = other.infinity;
return;
}
let u0 = self.x * other.z;
let u1 = other.x * self.z;
let t0 = self.y * other.z;
let t1 = other.y * self.z;
if u0 == u1 {
if t0 != t1 {
self.infinity = true;
} else {
self.double();
}
return;
}
let t = t0 - t1;
let u = u0 - u1;
let u2 = u * u;
let v = self.z * other.z;
let w = t * t * v - u2 * (u0 + u1);
let u3 = u * u2;
let x = u * w;
let y = t * (u0 * u2 - w) - t0 * u3;
let z = u3 * v;
self.x = x;
self.y = y;
self.z = z;
}
pub fn add_affine(&mut self, other: &AffinePoint) {
if other.infinity {
return;
}
if self.infinity {
self.x = other.x;
self.y = other.y;
self.z = FieldElement::ONE;
self.infinity = other.infinity;
return;
}
let u0 = self.x;
let u1 = other.x * self.z;
let t0 = self.y;
let t1 = other.y * self.z;
if u0 == u1 {
if t0 != t1 {
self.infinity = true;
return;
} else {
self.double();
return;
}
}
let t = t0 - t1;
let u = u0 - u1;
let u2 = u * u;
let v = self.z;
let w = t * t * v - u2 * (u0 + u1);
let u3 = u * u2;
let x = u * w;
let y = t * (u0 * u2 - w) - t0 * u3;
let z = u3 * v;
self.x = x;
self.y = y;
self.z = z;
}
pub fn multiply(&self, bits: &BitSlice<Lsb0, u64>) -> ProjectivePoint {
let mut product = ProjectivePoint::identity();
for b in bits.iter().rev() {
product.double();
if *b {
product.add(self);
}
}
product
}
}
/// Montgomery representation of the Stark curve generator G.
#[allow(dead_code)]
pub const CURVE_G: ProjectivePoint = ProjectivePoint {
x: FieldElement::new([
14484022957141291997,
5884444832209845738,
299981207024966779,
232005955912912577,
]),
y: FieldElement::new([
6241159653446987914,
664812301889158119,
18147424675297964973,
405578048423154473,
]),
z: FieldElement::ONE,
infinity: false,
};
/// Montgomery representation of the Stark curve constant P0.
pub const PEDERSEN_P0: ProjectivePoint = ProjectivePoint {
x: FieldElement::new([
1933903796324928314,
7739989395386261137,
1641324389046377921,
316327189671755572,
]),
y: FieldElement::new([
14252083571674603243,
12587053260418384210,
4798858472748676776,
81375596133053150,
]),
z: FieldElement::ONE,
infinity: false,
};
/// Montgomery representation of the Stark curve constant P1.
pub const PEDERSEN_P1: ProjectivePoint = ProjectivePoint {
x: FieldElement::new([
3602345268353203007,
13758484295849329960,
518715844721862878,
241691544791834578,
]),
y: FieldElement::new([
13441546676070136227,
13001553326386915570,
433857700841878496,
368891789801938570,
]),
z: FieldElement::ONE,
infinity: false,
};
/// Montgomery representation of the Stark curve constant P2.
pub const PEDERSEN_P2: ProjectivePoint = ProjectivePoint {
x: FieldElement::new([
16491878934996302286,
12382025591154462459,
10043949394709899044,
253000153565733272,
]),
y: FieldElement::new([
13950428914333633429,
2545498000137298346,
5191292837124484988,
285630633187035523,
]),
z: FieldElement::ONE,
infinity: false,
};
/// Montgomery representation of the Stark curve constant P3.
pub const PEDERSEN_P3: ProjectivePoint = ProjectivePoint {
x: FieldElement::new([
1203723169299412240,
18195981508842736832,
12916675983929588442,
338510149841406402,
]),
y: FieldElement::new([
12352616181161700245,
11743524503750604092,
11088962269971685343,
161068411212710156,
]),
z: FieldElement::ONE,
infinity: false,
};
/// Montgomery representation of the Stark curve constant P4.
pub const PEDERSEN_P4: ProjectivePoint = ProjectivePoint {
x: FieldElement::new([
1145636535101238356,
10664803185694787051,
299781701614706065,
425493972656615276,
]),
y: FieldElement::new([
8187986478389849302,
4428713245976508844,
6033691581221864148,
345457391846365716,
]),
z: FieldElement::ONE,
infinity: false,
};
#[cfg(test)]
mod tests {
use super::*;
use ff::PrimeField;
use pretty_assertions::assert_eq;
fn affine_from_xy_str(x: &str, y: &str) -> AffinePoint {
let x = FieldElement::from_str_vartime(x).expect("Curve x-value invalid");
let y = FieldElement::from_str_vartime(y).expect("Curve y-value invalid");
AffinePoint {
x,
y,
infinity: false,
}
}
fn projective_from_xy_str(x: &str, y: &str) -> ProjectivePoint {
let x = FieldElement::from_str_vartime(x).expect("Curve x-value invalid");
let y = FieldElement::from_str_vartime(y).expect("Curve y-value invalid");
ProjectivePoint {
x,
y,
z: FieldElement::ONE,
infinity: false,
}
}
#[test]
fn projective_double() {
let g_double = {
let mut g = CURVE_G;
g.double();
AffinePoint::from(&g)
};
let expected = affine_from_xy_str(
"3324833730090626974525872402899302150520188025637965566623476530814354734325",
"3147007486456030910661996439995670279305852583596209647900952752170983517249",
);
assert_eq!(g_double, expected);
}
#[test]
fn projective_double_and_add() {
let g_triple = {
let mut g = CURVE_G;
g.double();
g.add(&CURVE_G);
AffinePoint::from(&g)
};
let expected = affine_from_xy_str(
"1839793652349538280924927302501143912227271479439798783640887258675143576352",
"3564972295958783757568195431080951091358810058262272733141798511604612925062",
);
assert_eq!(g_triple, expected);
}
#[test]
fn projective_multiply() {
let three = FieldElement::THREE.into_bits();
let g = CURVE_G;
let g_triple = AffinePoint::from(&g.multiply(&three));
let expected = affine_from_xy_str(
"1839793652349538280924927302501143912227271479439798783640887258675143576352",
"3564972295958783757568195431080951091358810058262272733141798511604612925062",
);
assert_eq!(g_triple, expected);
}
#[test]
fn affine_projective_multiply() {
let three = FieldElement::THREE.into_bits();
let ag = AffinePoint::from(&CURVE_G);
let ag_triple = ag.multiply(&three);
let pg = ProjectivePoint::from(&ag);
let pg_triple = pg.multiply(&three);
let result = AffinePoint::from(&pg_triple);
assert_eq!(ag_triple.x, result.x);
}
#[test]
fn const_generator() {
let expected = projective_from_xy_str(
"874739451078007766457464989774322083649278607533249481151382481072868806602",
"152666792071518830868575557812948353041420400780739481342941381225525861407",
);
assert_eq!(CURVE_G, expected);
}
#[test]
fn const_p0() {
let expected = projective_from_xy_str(
"2089986280348253421170679821480865132823066470938446095505822317253594081284",
"1713931329540660377023406109199410414810705867260802078187082345529207694986",
);
assert_eq!(PEDERSEN_P0, expected);
}
#[test]
fn const_p1() {
let expected = projective_from_xy_str(
"996781205833008774514500082376783249102396023663454813447423147977397232763",
"1668503676786377725805489344771023921079126552019160156920634619255970485781",
);
assert_eq!(PEDERSEN_P1, expected);
}
#[test]
fn const_p2() {
let expected = projective_from_xy_str(
"2251563274489750535117886426533222435294046428347329203627021249169616184184",
"1798716007562728905295480679789526322175868328062420237419143593021674992973",
);
assert_eq!(PEDERSEN_P2, expected);
}
#[test]
fn const_p3() {
let expected = projective_from_xy_str(
"2138414695194151160943305727036575959195309218611738193261179310511854807447",
"113410276730064486255102093846540133784865286929052426931474106396135072156",
);
assert_eq!(PEDERSEN_P3, expected);
}
#[test]
fn const_p4() {
let expected = projective_from_xy_str(
"2379962749567351885752724891227938183011949129833673362440656643086021394946",
"776496453633298175483985398648758586525933812536653089401905292063708816422",
);
assert_eq!(PEDERSEN_P4, expected);
}
}
|
use rand;
use rand::Rng;
use core::structs::Point;
use core::structs::MLP;
use std::f64;
pub fn init_weights(neurals: &[i32], max: i32) -> Vec<Vec<Vec<f64>>> {
let mut weights: Vec<Vec<Vec<f64>>> = Vec::new();
for _i in 0..neurals.len() {
let mut v1 = Vec::new();
for _j in 0..max {
let mut v2 = Vec::new();
for _k in 0..max {
v2.push(rand::thread_rng().gen_range(-1.0, 1.0));
}
v1.push(v2);
}
weights.push(v1);
}
weights
}
pub unsafe fn default_bottom(mlp: *mut MLP) {
for i in 0..(*mlp).neurals.len() {
(*mlp).output[i][0] = 1.0;
}
}
pub fn init_all(neurals: &[i32]) -> Vec<Vec<f64>> {
let mut v1: Vec<Vec<f64>> = Vec::new();
for nb in neurals {
let mut v2: Vec<f64> = Vec::new();
for _ in 0..*nb {
v2.push(0.0);
}
v1.push(v2);
}
v1
}
pub unsafe fn train_neural(mlp: *mut MLP, point: &Point) {
default_bottom(mlp);
(*mlp).output[0][1] = point.x;
(*mlp).output[0][2] = point.z;
for i in 1..(*mlp).neurals.len() {
let nb_neurons_for_layer = (*mlp).neurals[i];
for j in 1..nb_neurons_for_layer {
(*mlp).output[i][j as usize] = calculate_output_prediction(mlp, i as i32,j);
}
}
get_delta(mlp, point.y as f64);
gradient_retropropagation(mlp);
update_weights(mlp);
}
unsafe fn update_weights(mlp: *mut MLP) {
for i in 1..(*mlp).neurals.len() {
let neurons_in_layer = (*mlp).neurals[i];
let neurons_in_previous_layer = (*mlp).neurals[i-1];
for j in 0..neurons_in_previous_layer {
for k in 0..neurons_in_layer {
let left = (*mlp).weights[i][j as usize][k as usize];
let right = 0.1 * (*mlp).output[i-1][j as usize] * (*mlp).delta[i][k as usize];
(*mlp).weights[i][j as usize][k as usize] = left - right;
}
}
}
}
unsafe fn gradient_retropropagation(mlp: *mut MLP) {
for i in (1..((*mlp).neurals.len() - 1)).rev() {
for j in 0..(*mlp).neurals[i] {
let left = 1. - (*mlp).output[i][j as usize].powf(2.0);
let mut right = 0.;
for k in 1..(*mlp).neurals[i+1] {
right+= (*mlp).weights[i+1][j as usize][k as usize] * (*mlp).delta[i+1][k as usize];
}
(*mlp).delta[i][j as usize] = left * right;
}
}
}
unsafe fn get_delta(mlp: *mut MLP, y: f64) {
let layer = (*mlp).neurals.len() - 1;
for i in 0..*(*mlp).neurals.last().unwrap() {
let o = (*mlp).output[layer][i as usize];
if (*mlp).classification == true{
(*mlp).delta[layer][i as usize] = (1. - o.powf(2.0)) * (o - y);
}else{
(*mlp).delta[layer][i as usize] = o - y;
}
}
}
pub unsafe fn calculate_output_prediction(mlp: *mut MLP, layer_number: i32, index: i32) -> f64 {
let layer_number = layer_number;
let nb = (*mlp).neurals[(layer_number -1) as usize];
let mut x = 0.0;
for i in 0..nb {
let weight = (*mlp).weights[layer_number as usize][i as usize][index as usize];
let x_i = (*mlp).output[(layer_number -1) as usize][i as usize];
x += weight * x_i;
}
if (*mlp).classification == true{
return activation_function_tanh(x);
}else{
if layer_number as usize == ((*mlp).neurals.len() - 1){
x
}
else {
activation_function_tanh(x)
}
}
}
fn activation_function_tanh(x: f64) -> f64{
(1. - (-2. * x).exp()) / (1. + (-2. * x).exp())
}
|
use once_cell::sync::Lazy;
use serde_derive::*;
use std::{fs::OpenOptions, io::Read};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Config {
mirrors: Vec<String>,
}
impl Config {
/// Get a reference to the config's mirrors.
pub fn mirrors(&self) -> &Vec<String> {
&self.mirrors
}
}
pub static CONFIG: Lazy<Config> = Lazy::new(|| {
let mut s = String::new();
let mut f = OpenOptions::new()
.write(false)
.read(true)
.append(false)
.open("susrc")
.expect("Failed to open susrc");
f.read_to_string(&mut s).expect("Failed to read susrc");
let out: Config = toml::from_str(&s).unwrap();
out
});
|
// Longest Harmonious Subsequence
// https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3628/
pub struct Solution;
impl Solution {
pub fn find_lhs(mut nums: Vec<i32>) -> i32 {
nums.sort_unstable();
let mut max_len = 0;
let mut prev_num = nums[0];
let mut cur_num = prev_num;
let mut prev_len = 0;
let mut cur_len = 1;
for &num in &nums[1..] {
if num == cur_num {
cur_len += 1;
} else {
if (cur_num - prev_num).abs() == 1
&& prev_len + cur_len > max_len
{
max_len = prev_len + cur_len;
}
prev_num = cur_num;
cur_num = num;
prev_len = cur_len;
cur_len = 1;
}
}
if (cur_num - prev_num).abs() == 1 && prev_len + cur_len > max_len {
max_len = prev_len + cur_len;
}
max_len
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example1() {
assert_eq!(Solution::find_lhs(vec![1, 3, 2, 2, 5, 2, 3, 7]), 5);
}
#[test]
fn example2() {
assert_eq!(Solution::find_lhs(vec![1, 2, 3, 4]), 2);
}
#[test]
fn example3() {
assert_eq!(Solution::find_lhs(vec![1, 1, 1, 1]), 0);
}
}
|
use regex::Regex;
use std::collections::HashSet;
fn main() {
let args: Vec<String> = std::env::args().collect();
let url = &args[1];
let resp = ureq::get(url).call();
if !resp.ok() {
println!("error: status_code={}", resp.status());
return
};
let body = resp.into_string().unwrap();
let re = Regex::new(r"(?P<url>https://lh3\.googleusercontent\.com/[a-zA-Z0-9\-_]*)").unwrap();
let mut result = HashSet::<String>::new();
let mut max_len_url = "".to_string();
for line in body.lines() {
if re.is_match(line) {
for cap in re.captures_iter(line) {
let pickup_url = &cap["url"];
result.insert(pickup_url.to_string());
if pickup_url.len() > max_len_url.len() {
max_len_url = pickup_url.to_string()
}
}
}
}
println!("url is {}", max_len_url);
}
|
//! The HCL2 AST and parser
pub mod ast;
pub mod parser;
pub mod traits;
|
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Tamper pin enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TPE_A {
#[doc = "0: The TAMPER pin is free for general purpose I/O"]
GENERAL = 0,
#[doc = "1: Tamper alternate I/O function is activated"]
ALTERNATE = 1,
}
impl From<TPE_A> for bool {
#[inline(always)]
fn from(variant: TPE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TPE`"]
pub type TPE_R = crate::R<bool, TPE_A>;
impl TPE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TPE_A {
match self.bits {
false => TPE_A::GENERAL,
true => TPE_A::ALTERNATE,
}
}
#[doc = "Checks if the value of the field is `GENERAL`"]
#[inline(always)]
pub fn is_general(&self) -> bool {
*self == TPE_A::GENERAL
}
#[doc = "Checks if the value of the field is `ALTERNATE`"]
#[inline(always)]
pub fn is_alternate(&self) -> bool {
*self == TPE_A::ALTERNATE
}
}
#[doc = "Write proxy for field `TPE`"]
pub struct TPE_W<'a> {
w: &'a mut W,
}
impl<'a> TPE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TPE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The TAMPER pin is free for general purpose I/O"]
#[inline(always)]
pub fn general(self) -> &'a mut W {
self.variant(TPE_A::GENERAL)
}
#[doc = "Tamper alternate I/O function is activated"]
#[inline(always)]
pub fn alternate(self) -> &'a mut W {
self.variant(TPE_A::ALTERNATE)
}
#[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 = "Tamper pin active level\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TPAL_A {
#[doc = "0: A high level on the TAMPER pin resets all data backup registers (if TPE bit is set)"]
HIGH = 0,
#[doc = "1: A low level on the TAMPER pin resets all data backup registers (if TPE bit is set)"]
LOW = 1,
}
impl From<TPAL_A> for bool {
#[inline(always)]
fn from(variant: TPAL_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TPAL`"]
pub type TPAL_R = crate::R<bool, TPAL_A>;
impl TPAL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TPAL_A {
match self.bits {
false => TPAL_A::HIGH,
true => TPAL_A::LOW,
}
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline(always)]
pub fn is_high(&self) -> bool {
*self == TPAL_A::HIGH
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline(always)]
pub fn is_low(&self) -> bool {
*self == TPAL_A::LOW
}
}
#[doc = "Write proxy for field `TPAL`"]
pub struct TPAL_W<'a> {
w: &'a mut W,
}
impl<'a> TPAL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TPAL_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "A high level on the TAMPER pin resets all data backup registers (if TPE bit is set)"]
#[inline(always)]
pub fn high(self) -> &'a mut W {
self.variant(TPAL_A::HIGH)
}
#[doc = "A low level on the TAMPER pin resets all data backup registers (if TPE bit is set)"]
#[inline(always)]
pub fn low(self) -> &'a mut W {
self.variant(TPAL_A::LOW)
}
#[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
}
}
impl R {
#[doc = "Bit 0 - Tamper pin enable"]
#[inline(always)]
pub fn tpe(&self) -> TPE_R {
TPE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Tamper pin active level"]
#[inline(always)]
pub fn tpal(&self) -> TPAL_R {
TPAL_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Tamper pin enable"]
#[inline(always)]
pub fn tpe(&mut self) -> TPE_W {
TPE_W { w: self }
}
#[doc = "Bit 1 - Tamper pin active level"]
#[inline(always)]
pub fn tpal(&mut self) -> TPAL_W {
TPAL_W { w: self }
}
}
|
use crate::{DocBase, VarType};
const DESCRIPTION: &'static str = r#"
The vwma function returns volume-weighted moving average of x for y bars back. It is the same as: `sma(x * volume, y) / sma(volume, y)`
"#;
const EXAMPLE: &'static str = r#"
```pine
plot(vwma(close, 15))
// same on pine, but less efficient
pine_vwma(x, y) =>
sma(x * volume, y) / sma(volume, y)
plot(pine_vwma(close, 15))
```
"#;
const ARGUMENTS: &'static str = r#"
source (series(float)) Series of values to process.
length (int) Number of bars (length).
"#;
pub fn gen_doc() -> Vec<DocBase> {
let fn_doc = DocBase {
var_type: VarType::Function,
name: "vwma",
signatures: vec![],
description: DESCRIPTION,
example: EXAMPLE,
returns: "Volume-weighted moving average of x for y bars back.",
arguments: ARGUMENTS,
remarks: "",
links: "[sma](#fun-sma)",
};
vec![fn_doc]
}
|
#[macro_use]
extern crate morgan;
use log::*;
use morgan::treasuryStage::create_test_recorder;
use morgan::blockBufferPool::{create_new_tmp_ledger, Blocktree};
use morgan::clusterMessage::{ClusterInfo, Node};
use morgan::entryInfo::next_entry_mut;
use morgan::entryInfo::EntrySlice;
use morgan::genesisUtils::{create_genesis_block_with_leader, GenesisBlockInfo};
use morgan::gossipService::GossipService;
use morgan::packet::index_blobs;
use morgan::rpcSubscriptions::RpcSubscriptions;
use morgan::service::Service;
use morgan::storageStage::StorageState;
use morgan::storageStage::STORAGE_ROTATE_TEST_COUNT;
use morgan::streamer;
use morgan::transactionVerifyCentre::{Sockets, Tvu};
use morgan::verifier;
use morgan_runtime::epoch_schedule::MINIMUM_SLOT_LENGTH;
use morgan_interface::signature::{Keypair, KeypairUtil};
use morgan_interface::system_transaction;
use std::fs::remove_dir_all;
use std::net::UdpSocket;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use morgan_helper::logHelper::*;
fn new_gossip(
cluster_info: Arc<RwLock<ClusterInfo>>,
gossip: UdpSocket,
exit: &Arc<AtomicBool>,
) -> GossipService {
GossipService::new(&cluster_info, None, None, gossip, exit)
}
/// Test that message sent from leader to target1 and replayed to target2
#[test]
fn test_replay() {
morgan_logger::setup();
let leader = Node::new_localhost();
let target1_keypair = Keypair::new();
let target1 = Node::new_localhost_with_pubkey(&target1_keypair.pubkey());
let target2 = Node::new_localhost();
let exit = Arc::new(AtomicBool::new(false));
// start cluster_info_l
let cluster_info_l = ClusterInfo::new_with_invalid_keypair(leader.info.clone());
let cref_l = Arc::new(RwLock::new(cluster_info_l));
let dr_l = new_gossip(cref_l, leader.sockets.gossip, &exit);
// start cluster_info2
let mut cluster_info2 = ClusterInfo::new_with_invalid_keypair(target2.info.clone());
cluster_info2.insert_info(leader.info.clone());
let cref2 = Arc::new(RwLock::new(cluster_info2));
let dr_2 = new_gossip(cref2, target2.sockets.gossip, &exit);
// setup some blob services to send blobs into the socket
// to simulate the source peer and get blobs out of the socket to
// simulate target peer
let (s_reader, r_reader) = channel();
let blob_sockets: Vec<Arc<UdpSocket>> = target2.sockets.tvu.into_iter().map(Arc::new).collect();
let t_receiver = streamer::blob_receiver(blob_sockets[0].clone(), &exit, s_reader);
// simulate leader sending messages
let (s_responder, r_responder) = channel();
let t_responder = streamer::responder(
"test_replay",
Arc::new(leader.sockets.retransmit),
r_responder,
);
let mint_balance = 10_000;
let leader_balance = 100;
let GenesisBlockInfo {
mut genesis_block,
mint_keypair,
..
} = create_genesis_block_with_leader(mint_balance, &leader.info.id, leader_balance);
genesis_block.ticks_per_slot = 160;
genesis_block.slots_per_epoch = MINIMUM_SLOT_LENGTH as u64;
let (blocktree_path, blockhash) = create_new_tmp_ledger!(&genesis_block);
let tvu_addr = target1.info.tvu;
let (
bank_forks,
_bank_forks_info,
blocktree,
ledger_signal_receiver,
completed_slots_receiver,
leader_schedule_cache,
_,
) = verifier::new_banks_from_blocktree(&blocktree_path, None);
let working_bank = bank_forks.working_bank();
assert_eq!(
working_bank.get_balance(&mint_keypair.pubkey()),
mint_balance
);
let leader_schedule_cache = Arc::new(leader_schedule_cache);
// start cluster_info1
let bank_forks = Arc::new(RwLock::new(bank_forks));
let mut cluster_info1 = ClusterInfo::new_with_invalid_keypair(target1.info.clone());
cluster_info1.insert_info(leader.info.clone());
let cref1 = Arc::new(RwLock::new(cluster_info1));
let dr_1 = new_gossip(cref1.clone(), target1.sockets.gossip, &exit);
let voting_keypair = Keypair::new();
let storage_keypair = Arc::new(Keypair::new());
let blocktree = Arc::new(blocktree);
{
let (poh_service_exit, poh_recorder, poh_service, _entry_receiver) =
create_test_recorder(&working_bank, &blocktree);
let tvu = Tvu::new(
&voting_keypair.pubkey(),
Some(&Arc::new(voting_keypair)),
&storage_keypair,
&bank_forks,
&cref1,
{
Sockets {
repair: target1.sockets.repair,
retransmit: target1.sockets.retransmit,
fetch: target1.sockets.tvu,
}
},
blocktree,
STORAGE_ROTATE_TEST_COUNT,
&StorageState::default(),
None,
ledger_signal_receiver,
&Arc::new(RpcSubscriptions::default()),
&poh_recorder,
&leader_schedule_cache,
&exit,
&morgan_interface::hash::Hash::default(),
completed_slots_receiver,
);
let mut mint_ref_balance = mint_balance;
let mut msgs = Vec::new();
let mut blob_idx = 0;
let num_transfers = 10;
let mut transfer_amount = 501;
let bob_keypair = Keypair::new();
let mut cur_hash = blockhash;
for i in 0..num_transfers {
let entry0 = next_entry_mut(&mut cur_hash, i, vec![]);
let entry_tick0 = next_entry_mut(&mut cur_hash, i + 1, vec![]);
let tx0 = system_transaction::create_user_account(
&mint_keypair,
&bob_keypair.pubkey(),
transfer_amount,
blockhash,
);
let entry_tick1 = next_entry_mut(&mut cur_hash, i + 1, vec![]);
let entry1 = next_entry_mut(&mut cur_hash, i + num_transfers, vec![tx0]);
let entry_tick2 = next_entry_mut(&mut cur_hash, i + 1, vec![]);
mint_ref_balance -= transfer_amount;
transfer_amount -= 1; // Sneaky: change transfer_amount slightly to avoid DuplicateSignature errors
let entries = vec![entry0, entry_tick0, entry_tick1, entry1, entry_tick2];
let blobs = entries.to_shared_blobs();
index_blobs(&blobs, &leader.info.id, blob_idx, 1, 0);
blob_idx += blobs.len() as u64;
blobs
.iter()
.for_each(|b| b.write().unwrap().meta.set_addr(&tvu_addr));
msgs.extend(blobs.into_iter());
}
// send the blobs into the socket
s_responder.send(msgs).expect("send");
drop(s_responder);
// receive retransmitted messages
let timer = Duration::new(1, 0);
while let Ok(_msg) = r_reader.recv_timeout(timer) {
info!("{}", Info(format!("got msg").to_string()));
println!("{}",
printLn(
format!("got msg").to_string(),
module_path!().to_string()
)
);
}
let working_bank = bank_forks.read().unwrap().working_bank();
let final_mint_balance = working_bank.get_balance(&mint_keypair.pubkey());
assert_eq!(final_mint_balance, mint_ref_balance);
let bob_balance = working_bank.get_balance(&bob_keypair.pubkey());
assert_eq!(bob_balance, mint_balance - mint_ref_balance);
exit.store(true, Ordering::Relaxed);
poh_service_exit.store(true, Ordering::Relaxed);
poh_service.join().unwrap();
tvu.join().unwrap();
dr_l.join().unwrap();
dr_2.join().unwrap();
dr_1.join().unwrap();
t_receiver.join().unwrap();
t_responder.join().unwrap();
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
let _ignored = remove_dir_all(&blocktree_path);
}
|
use r2d2_redis::RedisConnectionManager;
/// Pool type is a simple wrapper over r2d2::Pool<RedisConnectionManager> -> use it to pass around your
/// pool.
pub type Pool = r2d2::Pool<RedisConnectionManager>;
pub type Conn = r2d2::PooledConnection<RedisConnectionManager>;
pub fn create_pool(db_url: &str) -> Pool {
let manager = RedisConnectionManager::new(db_url).unwrap();
r2d2::Pool::builder()
.build(manager)
.unwrap()
}
|
use crate::renderer;
use glium;
use glium::backend::glutin::glutin::GlRequest;
use glium::GlObject;
use openvr;
use std::rc::Rc;
pub struct VrApp {
display: Rc<glium::Display>,
left_eye: VrEye,
right_eye: VrEye,
renderer: renderer::Renderer,
vr_device: VrDevice,
}
impl VrApp {
pub fn new(event_loop: &glium::glutin::event_loop::EventLoop<()>) -> VrApp {
let window_builder = glium::glutin::window::WindowBuilder::new()
.with_inner_size(glium::glutin::dpi::LogicalSize::new(256.0, 256.0));
let context = glium::glutin::ContextBuilder::new()
.with_gl(GlRequest::Specific(glium::glutin::Api::OpenGl, (3, 2)))
.with_gl_profile(glium::glutin::GlProfile::Core)
.with_gl_robustness(glium::glutin::Robustness::RobustLoseContextOnReset)
.build_windowed(window_builder, &event_loop)
.unwrap();
let display: Rc<glium::Display> = Rc::new(glium::Display::from_gl_window(context).unwrap());
println!("OpenGL vendor: {}", display.get_opengl_vendor_string());
println!("OpenGL renderer: {}", display.get_opengl_renderer_string());
println!("OpenGL version: {}", display.get_opengl_version_string());
let device: VrDevice = {
let context = unsafe {
openvr::init(openvr::ApplicationType::Scene).expect("Failed to initialize OpenVR")
};
let system = context.system().expect("Failed to get system interface");
let compositor = context
.compositor()
.expect("Failed to create IVRCompositor subsystem");
system
.device_to_absolute_tracking_pose(openvr::TrackingUniverseOrigin::Standing, 0.005);
VrDevice {
context: context,
system: system,
compositor: compositor,
}
};
let target_size = device.system.recommended_render_target_size();
println!("target size: {:?}", target_size);
let left_eye = VrEye::new(&display, target_size);
let right_eye = VrEye::new(&display, target_size);
let renderer = renderer::Renderer::new(&display);
VrApp {
display: display,
left_eye: left_eye,
right_eye: right_eye,
renderer: renderer,
vr_device: device,
}
}
pub fn run(self, event_loop: glium::glutin::event_loop::EventLoop<()>) {
let mut is_submit_enabled = false;
event_loop.run(move |glutin_event, _target, control_flow| {
*control_flow = glium::glutin::event_loop::ControlFlow::Poll;
self.vr_device
.compositor
.wait_get_poses()
.expect("Getting poses");
let mut buffer = self.display.as_ref().draw();
self.renderer.render_test(&mut buffer);
buffer.finish().unwrap();
if is_submit_enabled {
// if this block is executed, the texture will read all black in the shader
unsafe {
self.left_eye.submit(&self.vr_device.compositor, openvr::Eye::Left);
self.right_eye.submit(&self.vr_device.compositor, openvr::Eye::Right);
}
}
match glutin_event {
glium::glutin::event::Event::WindowEvent { event, .. } => match event {
glium::glutin::event::WindowEvent::CloseRequested => {
*control_flow = glium::glutin::event_loop::ControlFlow::Exit;
},
glium::glutin::event::WindowEvent::MouseInput {..} => {
is_submit_enabled = true;
},
_ => {},
},
_ => {},
}
});
}
}
struct VrDevice {
// NOTE(mkovacs): The context must be kept around, otherwise other fields become invalid.
#[allow(dead_code)]
context: openvr::Context,
system: openvr::System,
compositor: openvr::Compositor,
}
struct VrEye {
color: glium::Texture2d,
}
impl VrEye {
fn new(display: &Rc<glium::Display>, size: (u32, u32)) -> VrEye {
let color = glium::texture::Texture2d::empty_with_format(
display.as_ref(),
glium::texture::UncompressedFloatFormat::U8U8U8U8,
glium::texture::MipmapsOption::NoMipmap,
size.0,
size.1,
)
.unwrap();
VrEye {
color: color,
}
}
unsafe fn submit(&self, compositor: &openvr::Compositor, eye: openvr::Eye) {
compositor
.submit(
eye,
&openvr::compositor::texture::Texture {
handle: openvr::compositor::texture::Handle::OpenGLTexture(
self.color.get_id() as usize
),
color_space: openvr::compositor::texture::ColorSpace::Auto,
},
None,
None,
)
.expect("Submitting frame");
}
}
|
use std::os::raw::*;
use std::io::Read;
use std::ffi::CString;
use detour::RawDetour;
use glua_sys::*;
use libloading::os::unix as unix_lib;
mod steam_decoder;
static mut lstate: Option<*mut lua_State> = None;
unsafe fn voice_hook_run(L: *mut lua_State, slot: i32, data: &[u8]) {
static C_HOOK: &str = "hook\0";
static C_RUN: &str = "Run\0";
static C_VOICEDATA: &str = "VoiceData\0";
lua_getglobal!(L, unsafe { C_HOOK.as_ptr() as *const c_char });
lua_getfield(L, -1, unsafe { C_RUN.as_ptr() as *const c_char });
lua_pushstring(L, unsafe { C_VOICEDATA.as_ptr() as *const c_char });
lua_pushnumber(L, slot as f64);
let data_i8 = unsafe { &*(data as *const _ as *const [i8]) };
lua_pushlstring(L, data_i8.as_ptr(), data_i8.len() as _);
// 3 arg, 0 result
let res = lua_pcall(L, 3, 0, 0);
lua_pop!(L, 1); // pop "hook"
}
type EngineBroadcastVoice = unsafe extern "C" fn(*mut c_void, c_int, *const u8, i64);
static mut voice_hook: Option<RawDetour> = None;
extern "C" fn voice_detour(client: *mut c_void, byte_count: c_int, data: *const u8, xuid: i64) {
unsafe {
let original: EngineBroadcastVoice = std::mem::transmute(voice_hook.as_ref().unwrap().trampoline());
original(client, byte_count, data, xuid);
}
if !client.is_null() && byte_count > 0 && !data.is_null() {
use std::fs::OpenOptions;
use std::io::Write;
let mut slice = unsafe { std::slice::from_raw_parts::<u8>(data, byte_count as usize) };
let mut decomp = vec!();
steam_decoder::process(&slice, &mut decomp);
let slot = unsafe { player_slot.unwrap()(client) };
unsafe {
if let Some(ref L) = lstate {
voice_hook_run(*L, slot, &decomp);
}
}
}
}
type EngineGetPlayerSlot = unsafe extern "C" fn(*mut c_void) -> c_int;
static mut player_slot: Option<EngineGetPlayerSlot> = None;
const RTLD_LAZY: c_int = 0x00001;
const RTLD_NOLOAD: c_int = 0x00004;
#[repr(C)]
struct LinkMap32 {
addr: u32
}
extern "C" fn enable_hook(L: *mut lua_State) -> c_int {
unsafe {
let path_to_lib = "bin/engine_srv.so";
let lib = match unix_lib::Library::open(Some(path_to_lib), RTLD_LAZY | RTLD_NOLOAD) {
Ok(lib) => lib,
_ => {
lua_pushboolean(L, 0);
lua_pushstring(L, CString::new(format!("cannot find engine from {}", path_to_lib)).unwrap().as_ptr());
return 2
}
};
let ptr = lib.into_raw();
let data: *const LinkMap32 = unsafe { ptr as *const LinkMap32 };
let lib_bytes = std::fs::read(path_to_lib).unwrap();
let elf = goblin::elf::Elf::parse(&lib_bytes[..]).unwrap();
let mut n = 0;
for syn in elf.syms.iter() {
let name = elf.strtab.get(syn.st_name).unwrap().unwrap();
if name == "_Z21SV_BroadcastVoiceDataP7IClientiPcx" {
let ptr = ((*data).addr as usize + syn.st_value as usize);
let mut hook = unsafe { RawDetour::new(ptr as *const (), voice_detour as *const ()).unwrap() };
unsafe { hook.enable().unwrap() };
voice_hook = Some(hook);
n += 1;
} else if name == "_ZNK11CBaseClient13GetPlayerSlotEv" {
let ptr = ((*data).addr as usize + syn.st_value as usize);
player_slot = Some(std::mem::transmute(ptr));
n += 1;
}
}
lua_pushboolean(L, if n == 2 { 1} else { 0 });
1
}
}
extern "C" fn disable(L: *mut lua_State) -> c_int {
unsafe {
if let Some(hook) = voice_hook.take() {
if hook.is_enabled() {
hook.disable().unwrap()
}
}
}
0
}
fn glua_setglobal(L: *mut lua_State, lua_name: &str) {
match CString::new(lua_name) {
Ok(cstring_name) => {
unsafe {
lua_setglobal!(L, cstring_name.as_ptr());
}
}
Err(e) => {
println!("Failed to create CString! {}", e);
}
}
}
fn glua_register_to_table(L: *mut lua_State, table_index: i32, lua_name: &str, func: unsafe extern "C" fn(*mut lua_State) -> c_int) {
match CString::new(lua_name) {
Ok(cstring_name) => {
unsafe {
lua_pushcfunction!(L, Some(func));
lua_setfield(L, table_index, cstring_name.as_ptr());
}
}
Err(e) => {
println!("Failed to create CString! {}", e);
}
}
}
#[no_mangle]
pub unsafe extern "C" fn gmod13_open(L: *mut lua_State) -> c_int {
unsafe {
lstate = Some(L);
}
lua_newtable!(L);
unsafe {
lua_pushnumber(L, 3.0);
lua_setfield(L, -2, CString::new("Version").unwrap().as_ptr());
}
glua_register_to_table(L, -2, "Enable", enable_hook);
glua_register_to_table(L, -2, "Disable", disable);
glua_setglobal(L, "rvoicehook");
0
}
#[no_mangle]
pub extern "C" fn gmod13_close(L: *mut lua_State) -> c_int {
unsafe {
lstate = None;
}
disable(L);
0
} |
/**
A very simple application that show your name in a message box.
This demo shows how to use NWG without the NativeUi trait boilerplate.
Note that this way of doing things is alot less extensible and cannot make use of native windows derive.
See `basic` for the NativeUi version and `basic_d` for the derive version
*/
extern crate native_windows_gui as nwg;
use std::rc::Rc;
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
let mut window = Default::default();
let mut name_edit = Default::default();
let mut hello_button = Default::default();
let layout = Default::default();
nwg::Window::builder()
.size((300, 115))
.position((300, 300))
.title("Basic example")
.build(&mut window)
.unwrap();
nwg::TextInput::builder()
.text("Heisenberg")
.focus(true)
.parent(&window)
.build(&mut name_edit)
.unwrap();
nwg::Button::builder()
.text("Say my name")
.parent(&window)
.build(&mut hello_button)
.unwrap();
nwg::GridLayout::builder()
.parent(&window)
.spacing(1)
.child(0, 0, &name_edit)
.child_item(nwg::GridLayoutItem::new(&hello_button, 0, 1, 1, 2))
.build(&layout)
.unwrap();
let window = Rc::new(window);
let events_window = window.clone();
let handler = nwg::full_bind_event_handler(&window.handle, move |evt, _evt_data, handle| {
use nwg::Event as E;
match evt {
E::OnWindowClose =>
if &handle == &events_window as &nwg::Window {
nwg::modal_info_message(&events_window.handle, "Goodbye", &format!("Goodbye {}", name_edit.text()));
nwg::stop_thread_dispatch();
},
E::OnButtonClick =>
if &handle == &hello_button {
nwg::modal_info_message(&events_window.handle, "Hello", &format!("Hello {}", name_edit.text()));
},
_ => {}
}
});
nwg::dispatch_thread_events();
nwg::unbind_event_handler(&handler);
}
|
use crate::{Song, Note};
use portaudio as pa;
const SAMPLE_RATE: f64 = 44_100.0;
const FRAMES: u32 = 256;
const CHANNELS: i32 = 2;
pub enum Msg {
Play,
Stop,
Song(Song),
}
pub struct Audio {
portaudio: pa::PortAudio,
stream: pa::Stream<pa::NonBlocking, pa::Output<f32>>,
tx: std::sync::mpsc::Sender<Msg>,
}
impl Audio {
pub fn start() -> Result<Audio, pa::Error> {
let (tx, rx) = std::sync::mpsc::channel();
let mut song = Song::default();
let mut playing = false;
let mut t: usize = 0;
let mut note: usize = 0;
let bpm = 120.0;
let note_length = ((60.0 / bpm as f32) * SAMPLE_RATE as f32).round() as usize;
let portaudio = pa::PortAudio::new()?;
let settings = portaudio.default_output_stream_settings(CHANNELS, SAMPLE_RATE, FRAMES)?;
let mut stream = portaudio.open_non_blocking_stream(settings, move |args| {
for msg in rx.try_iter() {
match msg {
Msg::Play => { playing = true; t = 0; note = 0; }
Msg::Stop => { playing = false; }
Msg::Song(new_song) => { song = new_song; }
}
}
if playing {
for sample in args.buffer.iter_mut() {
t += 1;
if t == note_length {
t = 0;
note = (note + 1) % song.length;
}
let mut mix: f32 = 0.0;
for (track, sample) in song.notes.chunks(song.tracks).zip(song.samples.iter()) {
let mut previous = note;
let mut length = 0;
while let Note::None = track[previous] {
previous = previous.saturating_sub(1);
length += 1;
if previous == 0 { break; }
}
if let Note::On(ref factors) = track[previous] {
let pitch = 2.0f32.powi(factors[0]) * (3.0f32 / 2.0f32).powi(factors[1]) * (5.0f32 / 4.0f32).powi(factors[2]) * (7.0f32 / 4.0f32).powi(factors[3]);
let phase: f32 = ((length * note_length + t) as f32 * pitch) % sample.len() as f32;
let phase_whole = phase as usize;
let phase_frac = phase - phase_whole as f32;
let value = (1.0 - phase_frac) * sample[phase_whole] + phase_frac * sample[(phase_whole + 1) % sample.len()];
mix += value;
}
}
*sample = mix.max(-1.0).min(1.0);
}
} else {
for sample in args.buffer.iter_mut() {
*sample = 0.0;
}
}
pa::Continue
})?;
stream.start()?;
Ok(Audio { portaudio, stream, tx })
}
pub fn send(&self, msg: Msg) {
self.tx.send(msg);
}
}
|
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate rand;
extern crate serde;
extern crate serde_json;
mod model;
mod utils;
mod init;
use model::names::NameList;
use model::sectors::Sector;
use model::business::Business;
use model::world::World;
fn main() {
let mut world = generate_world();
for _ in 0..10
{
world.tick();
}
utils::file::write_stock("/home/raveline/stocks.csv", &world).unwrap();
}
fn generate_world() -> World {
let nl = init::names::build_name_list();
let mut w = World::new();
for sec in Sector::iterate() {
for _ in 0..10 {
w.add_business(generate_business(&nl, *sec));
}
}
w
}
fn generate_business(nl: &NameList, sector : Sector) -> Business {
let name = model::names::random_company_name(sector, "english", &nl);
Business::new(name, sector)
}
|
fn main() {
if_expressions(3);
if_expressions(7);
multi_if(6);
multi_if(7);
let _foo = if_statement();
println!("Loop break = {}", loop_break());
while_loop();
for_loop();
range();
}
fn if_expressions(number: i32) {
if number < 5 { // condition must be bool - no auto-conversion
println!("Number is less than 5");
} else { // else is optional
println!("Number is greater than 5");
}
}
fn multi_if(number: i32) {
if number % 4 == 0 {
println!("number divisible by 4");
} else if number % 3 == 0 {
println!("number divisible by 3");
} else if number % 2 == 0 {
println!("number divisible by 2");
} else {
println!("number not divisible by 4, 3 or 2");
}
}
// if is statement - so can be used on right side of assignment
// or as return value of function also
fn if_statement() -> i32 {
let number = if true { 5 } else { 6 };
println!("number = {}", number);
number
}
// this also means both arms of if must have same type - otherwise compile error
// loop - runs forever - until Control-C termination
// use break
fn loop_break() -> u32 {
let mut counter = 0;
let result = loop { // loop is expression
counter += 1;
if counter == 10 {
break counter * 2;
}
};
result
}
fn while_loop() {
let mut number = 3;
while number != 0 {
println!("{}", number);
number -= 1;
}
println!("LIFTOFF!!");
}
// looping through collection
fn for_loop() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("{}", element);
}
}
fn range() {
for number in (1..4).rev() {
println!("{}!", number);
}
println!("LIFTOFF!!");
}
|
use petgraph::{Graph, Directed};
use petgraph::graph::NodeIndex;
use petgraph::visit::GetAdjacencyMatrix;
use fixedbitset::FixedBitSet;
pub fn cross<N, E>(
graph: &Graph<N, E, Directed>,
matrix: &FixedBitSet,
h1: &Vec<NodeIndex>,
h2: &Vec<NodeIndex>,
) -> u32 {
let mut result = 0;
let n = h1.len();
let m = h2.len();
for j2 in 0..m - 1 {
let mut count = 0;
for i2 in (1..n).rev() {
let i1 = i2 - 1;
if graph.is_adjacent(&matrix, h1[i2].clone(), h2[j2].clone()) {
count += 1
}
if count > 0 {
for j1 in j2 + 1..m {
if graph.is_adjacent(&matrix, h1[i1].clone(), h2[j1].clone()) {
result += count
}
}
}
}
}
result
}
#[cfg(test)]
mod tests {
use petgraph::Graph;
use petgraph::visit::GetAdjacencyMatrix;
use super::*;
#[test]
fn it_works() {
let mut graph = Graph::<&str, &str>::new();
let u1 = graph.add_node("u1");
let u2 = graph.add_node("u2");
let u3 = graph.add_node("u3");
let u4 = graph.add_node("u4");
let v1 = graph.add_node("v1");
let v2 = graph.add_node("v2");
let v3 = graph.add_node("v3");
graph.add_edge(u1, v2, "");
graph.add_edge(u2, v2, "");
graph.add_edge(u2, v3, "");
graph.add_edge(u3, v1, "");
graph.add_edge(u3, v3, "");
graph.add_edge(u4, v2, "");
let h1 = vec![u1, u2, u3, u4];
let h2 = vec![v1, v2, v3];
let matrix = graph.adjacency_matrix();
assert_eq!(cross(&graph, &matrix, &h1, &h2), 5);
}
}
|
fn main() {
println!("Hello, world!");
println!("I am famous");
}
|
#[doc = "Reader of register UR8"]
pub type R = crate::R<u32, super::UR8>;
#[doc = "Reader of field `MEPAD_2`"]
pub type MEPAD_2_R = crate::R<bool, bool>;
#[doc = "Reader of field `MESAD_2`"]
pub type MESAD_2_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Mass erase protected area disabled for bank 2"]
#[inline(always)]
pub fn mepad_2(&self) -> MEPAD_2_R {
MEPAD_2_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 16 - Mass erase secured area disabled for bank 2"]
#[inline(always)]
pub fn mesad_2(&self) -> MESAD_2_R {
MESAD_2_R::new(((self.bits >> 16) & 0x01) != 0)
}
}
|
use std::borrow::Borrow;
use std::marker::PhantomData;
use hal;
use device::{CommandBuffer, CommandQueue, Device};
use fence;
impl<D, B> Device for (D, PhantomData<B>)
where
B: hal::Backend,
D: Borrow<B::Device>,
{
type Semaphore = B::Semaphore;
type Fence = B::Fence;
type Submit = B::CommandBuffer;
type CommandPool = B::CommandPool;
type CommandBuffer = (B::CommandBuffer, PhantomData<B>);
type CommandQueue = (B::CommandQueue, PhantomData<B>);
unsafe fn create_fence(&self, info: fence::FenceCreateInfo) -> Self::Fence {
hal::Device::create_fence(self.0.borrow(), info.flags.contains(fence::FenceCreateFlags::CREATE_SIGNALED))
}
}
impl<C, B> CommandBuffer for (C, PhantomData<B>)
where
B: hal::Backend,
C: Borrow<B::CommandBuffer>,
{
type Submit = B::CommandBuffer;
unsafe fn submit(&self) -> Self::Submit {
self.0.borrow().clone()
}
}
impl<C, B> CommandQueue for (C, PhantomData<B>)
where
B: hal::Backend,
C: Borrow<B::CommandQueue>,
{
type Semaphore = B::Semaphore;
type Fence = B::Fence;
type Submit = B::CommandBuffer;
}
|
use utopia_core::{
math::Size,
widgets::{pod::WidgetPod, TypedWidget, Widget},
Backend, BoxConstraints,
};
use crate::primitives::quad::QuadPrimitive;
pub struct Background<T, Color, B: Backend> {
widget: WidgetPod<T, B>,
color: Color,
}
impl<T, Color: Default, B: Backend> Background<T, Color, B> {
pub fn new<W: TypedWidget<T, B> + 'static>(widget: W) -> Self {
Background {
widget: WidgetPod::new(widget),
color: Color::default(),
}
}
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
}
impl<T, Color: Clone, B: Backend> Widget<T> for Background<T, Color, B> {
type Primitive = (QuadPrimitive<Color>, B::Primitive);
type Context = B;
type Event = B::Event;
type Reaction = B::EventReaction;
fn draw(
&self,
origin: utopia_core::math::Vector2,
size: utopia_core::math::Size,
data: &T,
) -> Self::Primitive {
let child = TypedWidget::<T, B>::draw(&self.widget, origin, size, data);
let new_size = Size {
width: size.width,
height: size.height,
};
let background = QuadPrimitive {
origin,
size: new_size,
color: self.color.clone(),
border_radius: 0,
};
(background, child)
}
fn layout(&mut self, bc: &BoxConstraints, context: &Self::Context, data: &T) -> Size {
TypedWidget::<T, B>::layout(&mut self.widget, bc, context, data)
}
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
/// Certificate type.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CertificateType<'a>
{
/// `PKIX`.
X509ASPerPkixCertificate(&'a [u8]),
/// `SPKI`.
///
/// SPKI certificate.
SpkiCertificate(&'a [u8]),
/// `PGP`.
///
/// OpenPGP packet.
OpenPgpPacket(&'a [u8]),
/// `IPKIX`.
///
/// `I` stands for Indirect `PKIX`.
///
/// The URL of a X.509 data object.
UrlOfAX509DataObject(&'a [u8]),
/// `ISPKI`.
///
/// `I` stands for Indirect `SPKI`.
///
/// The URL of a SPKI certificate.
UrlOfASpkiCertificate(&'a [u8]),
/// `IPGP`.
///
/// `I` stands for Indirect `PGP`.
///
/// The fingerprint and URL of an OpenPGP packet.
FingerprintAndUrlOfAnOpenPgpPacket(&'a [u8]),
/// `ACPKIX`.
///
/// Attribute certificate.
AttributeCertificate(&'a [u8]),
/// `IACPKIX`.
///
/// `I` stands for Indirect `ACPKIX`.
///
/// The URL of an Attribute Certificate.
UrlOfAnAttributeCertificate(&'a [u8]),
}
|
use std::{
collections::{HashMap, HashSet, VecDeque},
fs, vec,
};
#[derive(Debug, Clone, Copy)]
struct Node {
value: u32,
next: usize,
}
fn main() {
let moves = 100;
let mut nodes = "137826495"
.chars()
.into_iter()
.enumerate()
.map(|(i, x)| Node {
value: x.to_digit(10).unwrap(),
next: i + 1,
})
.collect::<Vec<Node>>();
let max_value: u32 = nodes.iter().max_by_key(|&x| x.value).unwrap().value.clone();
let min_value: u32 = nodes.iter().min_by_key(|&x| x.value).unwrap().value.clone();
let mut templast = nodes.last_mut().unwrap();
templast.next = 0;
let mut curr_cup_index = 0;
for curr_move in 1..=moves {
let nodes_snapshot = nodes.clone();
let prev_curr_cup_index = curr_cup_index;
println!("Turn: {:?}: ", curr_move);
print!("Start:\t");
print_in_order(&nodes, prev_curr_cup_index);
let mut three_cups_index = vec![];
for _ in 1..=4 {
curr_cup_index = nodes_snapshot.get(curr_cup_index).unwrap().next;
three_cups_index.push(curr_cup_index as u32);
}
let after_three_index = three_cups_index.pop().unwrap();
// select destination
let mut possible_destination_index = 0;
let mut possible_destination_value =
if nodes_snapshot.get(prev_curr_cup_index).unwrap().value - 1 >= min_value {
nodes_snapshot.get(prev_curr_cup_index).unwrap().value - 1
} else {
max_value
};
let three_values: Vec<u32> = three_cups_index
.iter()
.map(|&x| nodes_snapshot[x as usize].value)
.collect();
loop {
if three_values.contains(&possible_destination_value) {
possible_destination_value = if possible_destination_value - 1 < min_value {
max_value
} else {
possible_destination_value - 1
};
} else {
for (i, x) in nodes_snapshot.iter().enumerate() {
if x.value == possible_destination_value {
possible_destination_index = i;
}
}
break;
}
}
nodes.get_mut(prev_curr_cup_index as usize).unwrap().next = after_three_index as usize;
// Place three cups at destination
let temp_destination_index = nodes.get(possible_destination_index).unwrap().next;
nodes.get_mut(possible_destination_index).unwrap().next = three_cups_index[0] as usize;
// change last of picked up cups to destination next
nodes.get_mut(three_cups_index[2] as usize).unwrap().next = temp_destination_index;
print!("End:\t");
print_in_order(&nodes, prev_curr_cup_index);
}
let one_position = nodes.iter().position(|x| x.value == 1).unwrap();
println!("Remove 1 from beginning of following:");
print_in_order(&nodes, one_position);
}
fn print_in_order(nodes: &Vec<Node>, start_index: usize) {
let mut curr_index = start_index;
let mut count = 0;
loop {
let temp = nodes.get(curr_index).unwrap();
print!("{:?}", temp.value);
curr_index = temp.next;
if curr_index == start_index || count >= nodes.len() {
break;
}
count += 1;
}
println!();
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::RCGCI2C {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R0R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R0W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R0W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R1R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R1W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R2R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R2W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R3R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R3W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R4R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R4R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R4W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R4W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R5R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R5R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R5W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R5W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R6R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R6R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R6W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R6W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R7R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R7R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R7W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R7W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R8R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R8R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R8W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R8W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 8);
self.w.bits |= ((value as u32) & 1) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_RCGCI2C_R9R {
bits: bool,
}
impl SYSCTL_RCGCI2C_R9R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_RCGCI2C_R9W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_RCGCI2C_R9W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 9);
self.w.bits |= ((value as u32) & 1) << 9;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - I2C Module 0 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r0(&self) -> SYSCTL_RCGCI2C_R0R {
let bits = ((self.bits >> 0) & 1) != 0;
SYSCTL_RCGCI2C_R0R { bits }
}
#[doc = "Bit 1 - I2C Module 1 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r1(&self) -> SYSCTL_RCGCI2C_R1R {
let bits = ((self.bits >> 1) & 1) != 0;
SYSCTL_RCGCI2C_R1R { bits }
}
#[doc = "Bit 2 - I2C Module 2 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r2(&self) -> SYSCTL_RCGCI2C_R2R {
let bits = ((self.bits >> 2) & 1) != 0;
SYSCTL_RCGCI2C_R2R { bits }
}
#[doc = "Bit 3 - I2C Module 3 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r3(&self) -> SYSCTL_RCGCI2C_R3R {
let bits = ((self.bits >> 3) & 1) != 0;
SYSCTL_RCGCI2C_R3R { bits }
}
#[doc = "Bit 4 - I2C Module 4 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r4(&self) -> SYSCTL_RCGCI2C_R4R {
let bits = ((self.bits >> 4) & 1) != 0;
SYSCTL_RCGCI2C_R4R { bits }
}
#[doc = "Bit 5 - I2C Module 5 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r5(&self) -> SYSCTL_RCGCI2C_R5R {
let bits = ((self.bits >> 5) & 1) != 0;
SYSCTL_RCGCI2C_R5R { bits }
}
#[doc = "Bit 6 - I2C Module 6 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r6(&self) -> SYSCTL_RCGCI2C_R6R {
let bits = ((self.bits >> 6) & 1) != 0;
SYSCTL_RCGCI2C_R6R { bits }
}
#[doc = "Bit 7 - I2C Module 7 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r7(&self) -> SYSCTL_RCGCI2C_R7R {
let bits = ((self.bits >> 7) & 1) != 0;
SYSCTL_RCGCI2C_R7R { bits }
}
#[doc = "Bit 8 - I2C Module 8 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r8(&self) -> SYSCTL_RCGCI2C_R8R {
let bits = ((self.bits >> 8) & 1) != 0;
SYSCTL_RCGCI2C_R8R { bits }
}
#[doc = "Bit 9 - I2C Module 9 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r9(&self) -> SYSCTL_RCGCI2C_R9R {
let bits = ((self.bits >> 9) & 1) != 0;
SYSCTL_RCGCI2C_R9R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - I2C Module 0 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r0(&mut self) -> _SYSCTL_RCGCI2C_R0W {
_SYSCTL_RCGCI2C_R0W { w: self }
}
#[doc = "Bit 1 - I2C Module 1 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r1(&mut self) -> _SYSCTL_RCGCI2C_R1W {
_SYSCTL_RCGCI2C_R1W { w: self }
}
#[doc = "Bit 2 - I2C Module 2 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r2(&mut self) -> _SYSCTL_RCGCI2C_R2W {
_SYSCTL_RCGCI2C_R2W { w: self }
}
#[doc = "Bit 3 - I2C Module 3 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r3(&mut self) -> _SYSCTL_RCGCI2C_R3W {
_SYSCTL_RCGCI2C_R3W { w: self }
}
#[doc = "Bit 4 - I2C Module 4 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r4(&mut self) -> _SYSCTL_RCGCI2C_R4W {
_SYSCTL_RCGCI2C_R4W { w: self }
}
#[doc = "Bit 5 - I2C Module 5 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r5(&mut self) -> _SYSCTL_RCGCI2C_R5W {
_SYSCTL_RCGCI2C_R5W { w: self }
}
#[doc = "Bit 6 - I2C Module 6 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r6(&mut self) -> _SYSCTL_RCGCI2C_R6W {
_SYSCTL_RCGCI2C_R6W { w: self }
}
#[doc = "Bit 7 - I2C Module 7 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r7(&mut self) -> _SYSCTL_RCGCI2C_R7W {
_SYSCTL_RCGCI2C_R7W { w: self }
}
#[doc = "Bit 8 - I2C Module 8 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r8(&mut self) -> _SYSCTL_RCGCI2C_R8W {
_SYSCTL_RCGCI2C_R8W { w: self }
}
#[doc = "Bit 9 - I2C Module 9 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_rcgci2c_r9(&mut self) -> _SYSCTL_RCGCI2C_R9W {
_SYSCTL_RCGCI2C_R9W { w: self }
}
}
|
pub mod connect;
pub mod packets;
pub mod state_transition_engine;
|
use front::run::compiler::Compiler;
use syntax::ast::constant::*;
use syntax::ast::op::*;
use syntax::ast::expr::Expr;
use syntax::ast::constant::Const::*;
use syntax::ast::op::CompOp::*;
use jit::{
// Context,
Compile,
Function,
Value,
get_type,
SysBool,
Int,
UInt,
NInt,
NUInt,
Float64,
Pointer
};
// TODO: convert to llvm
use llvm_rs::{
Context,
Module
};
type CompiledValue<'a> = (Value<'a>, &'a Function<'a>);
/// A compiler using the LibJIT backend
pub struct JitCompiler<'a> {
curr: Function<'a>
}
impl<'a> JitCompiler<'a> {
/// Construct a new JIT Compiler on the given context
pub fn new(context: &'a Context) -> JitCompiler<'a> {
let main_t = Type::get::<fn(f64, f64) -> f64>();
let module = Module::new("add", &context);
JitCompiler {
curr: module.add_function("add", main_t)
}
}
fn convert_bool(&'a self, val:Value<'a>) -> Value<'a> {
let bool_t = Type::get::<bool>();
let val_kind = val.get_type().get_kind();
let convert = |v| self.curr.insn_convert(&v, bool_t.clone(), false);
match val_kind {
SysBool => val,
Float64 => {
let zero = 0.0f64.compile(&self.curr);
let not_zero = self.curr.insn_neq(&val, &zero);
let not_nan = !self.curr.insn_is_nan(&val);
convert(not_zero & not_nan)
},
Int | UInt | NInt | NUInt => {
let zero = 0.compile(&self.curr);
convert(self.curr.insn_neq(&val, &zero))
},
Pointer => {
let one = 1.compile(&self.curr);
convert(self.curr.insn_gt(&val, &one))
},
_ => convert(val)
}
}
fn undefined(&'a self) -> Value<'a> {
let ptr = Value::new(&self.curr, get_type::<&u64>());
let val = 0u8.compile(&self.curr);
self.curr.insn_store(&ptr, &val);
ptr
}
}
impl<'a> Compiler<'a, (Value<'a>, &'a Function<'a>)> for JitCompiler<'a> {
fn compile_const(&'a self, constant:&Const) -> CompiledValue<'a> {
(match constant.clone() {
CString(v) =>
v.compile(&self.curr),
CNum(v) =>
v.compile(&self.curr),
CInt(v) =>
v.compile(&self.curr),
CBool(v) =>
v.compile(&self.curr),
CNull => {
let ptr = Value::new(&self.curr, get_type::<&u64>());
let val = 1u8.compile(&self.curr);
self.curr.insn_store(&ptr, &val);
ptr
},
CUndefined => {
self.undefined()
},
_ => unimplemented!()
}, &self.curr)
}
fn compile_block(&'a self, block:Vec<Expr>) -> CompiledValue<'a> {
let last = block.last();
for expr in block.iter() {
let comp = self.compile(expr);
if expr == last.unwrap() {
return comp
}
}
unreachable!()
}
fn compile_num_op(&'a self, op:NumOp, left:&Expr, right:&Expr) -> CompiledValue<'a> {
let (c_left, _) = self.compile(left);
let (c_right, _) = self.compile(right);
(match op {
OpAdd => c_left + c_right,
OpSub => c_left - c_right,
OpDiv => c_left / c_right,
OpMul => c_left * c_right,
OpMod => c_left % c_right
}, &self.curr)
}
fn compile_bit_op(&'a self, op:BitOp, left:&Expr, right:&Expr) -> CompiledValue<'a> {
let int_t = get_type::<i32>();
let (c_left, _) = self.compile(left);
let c_left = self.curr.insn_convert(&c_left, int_t.clone(), false);
let (c_right, _) = self.compile(right);
let c_right = self.curr.insn_convert(&c_right, int_t, false);
(match op {
BitAnd => c_left & c_right,
BitOr => c_left | c_right,
BitXor => c_left ^ c_right,
BitShl => c_left << c_right,
BitShr => c_left >> c_right
}, &self.curr)
}
fn compile_log_op(&'a self, op:LogOp, left:&Expr, right:&Expr) -> CompiledValue<'a> {
let (c_left, _) = self.compile(left);
let c_left = self.convert_bool(c_left);
let (c_right, _) = self.compile(right);
let c_right = self.convert_bool(c_right);
(match op {
LogAnd => c_left & c_right,
LogOr => c_left | c_right
}, &self.curr)
}
fn compile_comp_op(&'a self, op:CompOp, left:&Expr, right:&Expr) -> CompiledValue<'a> {
let (c_left, _) = self.compile(left);
let (c_right, _) = self.compile(right);
let val = match op {
CompEqual | CompStrictEqual =>
self.curr.insn_eq(&c_left, &c_right),
CompNotEqual | CompStrictNotEqual =>
self.curr.insn_neq(&c_left, &c_right),
CompGreaterThan =>
self.curr.insn_gt(&c_left, &c_right),
CompGreaterThanOrEqual =>
self.curr.insn_geq(&c_left, &c_right),
CompLessThan =>
self.curr.insn_lt(&c_left, &c_right),
CompLessThanOrEqual =>
self.curr.insn_leq(&c_left, &c_right),
};
let bool_val = self.curr.insn_convert(&val, get_type::<bool>(), false);
(bool_val, &self.curr)
}
fn compile_unary_op(&'a self, op:UnaryOp, val:&Expr) -> CompiledValue<'a> {
let (c_val, _) = self.compile(val);
(match op {
UnaryMinus => -c_val,
UnaryPlus => c_val,
UnaryNot => {
let c_not = !c_val;
self.curr.insn_convert(&c_not, get_type::<bool>(), false)
},
_ => unimplemented!()
}, &self.curr)
}
fn compile_return(&'a self, val:Option<Box<Expr>>) -> CompiledValue<'a> {
match val {
Some(box ref val) => {
let (c_val, _) = self.compile(val);
self.curr.insn_return(&c_val)
},
None => {
self.curr.insn_default_return()
}
};
(self.undefined(), &self.curr)
}
}
|
use bevy::{
core::Bytes,
prelude::*,
reflect::TypeUuid,
render::{
mesh::shape,
pipeline::{PipelineDescriptor, RenderPipeline},
render_graph::{base, AssetRenderResourcesNode, RenderGraph, RenderResourcesNode},
renderer::{RenderResource, RenderResourceType, RenderResources},
shader::{ShaderStage, ShaderStages},
},
};
#[derive(RenderResources, Default, TypeUuid)]
#[uuid = "93fb26fc-6c05-489b-9029-601edf703b6b"]
struct FireTexture {
pub texture: Handle<Texture>,
}
#[derive(RenderResources, Default, TypeUuid)]
#[render_resources(from_self)]
#[uuid = "539fe49d-df51-48c1-bbfc-d68eb1716354"]
#[repr(C)]
struct FireMaterial {
pub base_color: Color,
pub flame_height: f32,
pub distorsion_level: f32,
pub bottom_threshold: f32,
pub time: f32,
}
impl RenderResource for FireMaterial {
fn resource_type(&self) -> Option<RenderResourceType> {
Some(RenderResourceType::Buffer)
}
fn buffer_byte_len(&self) -> Option<usize> {
Some(32)
}
fn write_buffer_bytes(&self, buffer: &mut [u8]) {
let (base_color_buf, rest) = buffer.split_at_mut(16);
self.base_color.write_bytes(base_color_buf);
let (flame_height_buf, rest) = rest.split_at_mut(4);
self.flame_height.write_bytes(flame_height_buf);
let (distorsion_level_buf, rest) = rest.split_at_mut(4);
self.distorsion_level.write_bytes(distorsion_level_buf);
let (bottom_threshold_buf, rest) = rest.split_at_mut(4);
self.bottom_threshold.write_bytes(bottom_threshold_buf);
self.time.write_bytes(rest);
}
fn texture(&self) -> Option<&Handle<Texture>> {
None
}
}
struct LoadingTexture(Option<Handle<Texture>>);
struct FirePipeline(Handle<PipelineDescriptor>);
pub fn main() {
App::build()
.add_plugins(DefaultPlugins)
.add_asset::<FireMaterial>()
.add_asset::<FireTexture>()
.add_startup_system(setup.system())
.add_system(draw_fire.system())
.add_system(animate_fire.system())
.run();
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut pipelines: ResMut<Assets<PipelineDescriptor>>,
mut shaders: ResMut<Assets<Shader>>,
mut render_graph: ResMut<RenderGraph>,
) {
commands.insert_resource(LoadingTexture(Some(asset_server.load("fire.png"))));
let pipeline_handle = pipelines.add(PipelineDescriptor::default_config(ShaderStages {
vertex: shaders.add(Shader::from_glsl(
ShaderStage::Vertex,
include_str!("fire.vert"),
)),
fragment: Some(shaders.add(Shader::from_glsl(
ShaderStage::Fragment,
include_str!("fire.frag"),
))),
}));
commands.insert_resource(FirePipeline(pipeline_handle));
render_graph.add_system_node(
"fire_texture",
AssetRenderResourcesNode::<FireTexture>::new(true),
);
render_graph
.add_node_edge("fire_texture", base::node::MAIN_PASS)
.unwrap();
render_graph.add_system_node(
"fire_material",
RenderResourcesNode::<FireMaterial>::new(true),
);
render_graph
.add_node_edge("fire_material", base::node::MAIN_PASS)
.unwrap();
commands.spawn_bundle(PerspectiveCameraBundle {
transform: Transform::from_xyz(0.0, 0.0, -8.0).looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
});
}
fn draw_fire(
mut commands: Commands,
fire_pipeline: Res<FirePipeline>,
mut loading_texture: ResMut<LoadingTexture>,
mut textures: ResMut<Assets<Texture>>,
mut meshes: ResMut<Assets<Mesh>>,
mut fire_textures: ResMut<Assets<FireTexture>>,
) {
let (handle, texture) = match loading_texture.0.as_ref() {
Some(handle) => {
if let Some(texture) = textures.get_mut(handle) {
(loading_texture.0.take().unwrap(), texture)
} else {
return;
}
}
None => return,
};
texture.reinterpret_stacked_2d_as_array(3);
let fire_texture = fire_textures.add(FireTexture { texture: handle });
let fire_material = FireMaterial {
base_color: Color::rgb(0.9245, 0.3224, 0.0654),
flame_height: 0.2,
distorsion_level: 7.0,
bottom_threshold: -0.35,
time: 0.0,
};
commands
.spawn_bundle(MeshBundle {
mesh: meshes.add(Mesh::from(shape::Quad {
size: Vec2::new(5.0, 5.0),
flip: true,
})),
render_pipelines: RenderPipelines::from_pipelines(vec![RenderPipeline::new(
fire_pipeline.0.clone(),
)]),
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..Default::default()
})
.insert(fire_material)
.insert(fire_texture);
}
fn animate_fire(time: Res<Time>, mut query: Query<&mut FireMaterial>) {
for mut fire_material in query.iter_mut() {
fire_material.time = time.seconds_since_startup() as f32;
}
}
|
use super::expf;
use super::expm1f;
use super::k_expo2f;
/// Hyperbolic cosine (f64)
///
/// Computes the hyperbolic cosine of the argument x.
/// Is defined as `(exp(x) + exp(-x))/2`
/// Angles are specified in radians.
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn coshf(mut x: f32) -> f32 {
let x1p120 = f32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120
/* |x| */
let mut ix = x.to_bits();
ix &= 0x7fffffff;
x = f32::from_bits(ix);
let w = ix;
/* |x| < log(2) */
if w < 0x3f317217 {
if w < (0x3f800000 - (12 << 23)) {
force_eval!(x + x1p120);
return 1.;
}
let t = expm1f(x);
return 1. + t * t / (2. * (1. + t));
}
/* |x| < log(FLT_MAX) */
if w < 0x42b17217 {
let t = expf(x);
return 0.5 * (t + 1. / t);
}
/* |x| > log(FLT_MAX) or nan */
k_expo2f(x)
}
|
use scanner_proc_macro::insert_scanner;
use std::collections::{BTreeSet, HashMap};
#[insert_scanner]
fn main() {
let (n, m) = scan!((usize, usize));
let a = scan!(u32; n);
let b = scan!(u32; n);
let c = scan!(u32; m);
let d = scan!(u32; m);
let mut chocolate_y = HashMap::new();
for i in 0..n {
chocolate_y.entry(a[i]).or_insert(Vec::new()).push(b[i]);
}
let mut slot_yj = HashMap::new();
for j in 0..m {
slot_yj.entry(c[j]).or_insert(Vec::new()).push((d[j], j));
}
let mut xs = Vec::new();
for i in 0..n {
xs.push(a[i]);
}
for j in 0..m {
xs.push(c[j]);
}
xs.sort();
xs.dedup();
xs.reverse();
let mut ok_slot_yj = BTreeSet::new();
for x in xs {
if let Some(yj) = slot_yj.get(&x) {
for yj in yj {
ok_slot_yj.insert(yj);
}
}
if let Some(y) = chocolate_y.get(&x) {
for &y in y {
if let Some(yj) = ok_slot_yj.range((y, 0)..).next().copied() {
ok_slot_yj.remove(yj);
} else {
println!("No");
return;
}
}
}
}
println!("Yes");
}
|
use num::BigUint;
pub fn difficulty_to_max_hash(mut difficulty: u64) -> [u8; 32] {
if difficulty == 0 {
difficulty = 1;
}
let mut num = BigUint::from(2u8).pow(32 * 8);
num += BigUint::from(difficulty - 1);
num /= difficulty;
num -= BigUint::from(1u8);
let bytes = num.to_bytes_le();
let mut out = [0u8; 32];
out[..bytes.len()].copy_from_slice(&bytes);
out
}
|
mod channel_list;
mod chat_history;
mod line_edit;
mod scrollbar;
pub use self::channel_list::ChannelList;
pub use self::chat_history::ChatHistory;
pub use self::line_edit::LineEdit;
pub use self::scrollbar::Scrollbar;
|
use {Matrix, Dict};
use std::io::{BufWriter, BufReader};
use std::io::prelude::*;
use std::fs::File;
use bincode;
use bincode::rustc_serialize::{encode_into, decode_from};
use utils::W2vError;
pub struct Word2vec {
syn0: Matrix,
syn1neg: Matrix,
dim: usize,
dict: Dict,
}
impl Word2vec {
pub fn new(syn0: Matrix, syn1neg: Matrix, dim: usize, dict: Dict) -> Word2vec {
Word2vec {
syn0: syn0,
syn1neg: syn1neg,
dim: dim,
dict: dict,
}
}
pub fn norm_self(&mut self) {
self.syn0.norm_self();
}
#[cfg(feature="blas")]
#[inline(always)]
pub fn most_similar(&self, word: &str, topn: Option<usize>) -> Vec<(f32, String)> {
let mut vec = vec![0.;self.dict.nsize()];
let c = self.dict.get_idx(word);
let row = self.syn0.get_row_unmod(c);
self.syn0.sgemv(row, vec.as_mut_ptr());
let mut sorted = Vec::new();
for i in 0..vec.len() {
sorted.push((vec[i], self.dict.get_word(i)));
}
sorted.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap());
let topn = topn.unwrap_or(10);
sorted.into_iter().take(topn).collect()
}
pub fn save_vectors(&self, filename: &str) -> Result<bool, W2vError> {
let size = self.dict.nsize();
let mut file = try!(File::create(filename));
let mut meta = Vec::new();
try!(write!(&mut meta, "{} {}\n", size, self.dim));
try!(file.write_all(&meta));
let start = self.syn0.get_row_unmod(0);
for i in 0..size {
try!(file.write_all(&self.dict.get_word(i).into_bytes()[..]));
for j in 0..self.dim {
unsafe {
let s = format!(" {}", *start.offset((i * self.dim + j) as isize));
try!(file.write(&s.into_bytes()[..]));
}
}
try!(file.write(b"\n"));
}
Ok(true)
}
pub fn save(&self, filename: &str) -> Result<bool, W2vError> {
let file = File::create(filename).unwrap();
let mut writer = BufWriter::new(file);
try!(encode_into(&self.dict, &mut writer, bincode::SizeLimit::Infinite));
try!(encode_into(&self.syn0, &mut writer, bincode::SizeLimit::Infinite));
try!(encode_into(&self.syn1neg, &mut writer, bincode::SizeLimit::Infinite));
try!(encode_into(&self.dim, &mut writer, bincode::SizeLimit::Infinite));
Ok(true)
}
pub fn load_from(filename: &str) -> Result<Word2vec, W2vError> {
let file = try!(File::open(filename));
let mut reader = BufReader::new(file);
let dict: Dict = try!(decode_from(&mut reader, bincode::SizeLimit::Infinite));
let syn0: Matrix = decode_from(&mut reader, bincode::SizeLimit::Infinite).unwrap();
let syn1neg: Matrix = decode_from(&mut reader, bincode::SizeLimit::Infinite).unwrap();
let dim: usize = decode_from(&mut reader, bincode::SizeLimit::Infinite).unwrap();
Ok(Word2vec {
dict: dict,
syn0: syn0,
syn1neg: syn1neg,
dim: dim,
})
}
} |
use image::Rgba;
use serde::Deserialize;
use crate::bucket::Pixcel;
use crate::color::alpha_brend;
#[derive(Debug, Clone, Deserialize)]
pub struct Grid {
background: (u8, u8, u8, u8),
#[serde(rename = "grid_base")]
base: (u8, u8, u8),
lines: Vec<GridLine>,
}
impl Grid {
pub fn background(&self, pixcel: &Pixcel, scale: f32) -> Rgba<u8> {
let line_alpha = self.match_line(pixcel, scale);
Rgba([
alpha_brend(self.base.0, self.background.0, line_alpha),
alpha_brend(self.base.1, self.background.1, line_alpha),
alpha_brend(self.base.2, self.background.2, line_alpha),
alpha_brend(255, self.background.3, line_alpha),
])
}
fn match_line(&self, pixcel: &Pixcel, scale: f32) -> u8 {
for &gl in &self.lines {
if gl.mult <= 2.0 * scale {
break;
}
if pixcel.x_contains_mult_of(gl.mult) || pixcel.y_contains_mult_of(gl.mult) {
return gl.alpha;
}
}
0
}
}
impl Default for Grid {
fn default() -> Grid {
Grid {
background: (0, 0, 0, 255),
base: (255, 255, 255),
lines: vec![
GridLine {
mult: 100_000.0,
alpha: 255,
},
GridLine {
mult: 10_000.0,
alpha: 191,
},
GridLine {
mult: 5_000.0,
alpha: 127,
},
GridLine {
mult: 1_000.0,
alpha: 97,
},
GridLine {
mult: 500.0,
alpha: 64,
},
GridLine {
mult: 100.0,
alpha: 47,
},
],
}
}
}
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct GridLine {
mult: f32,
alpha: u8,
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const CLSID_DirectSound: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x47d4d946_62e8_11cf_93bc_444553540000);
pub const CLSID_DirectSound8: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3901cc3f_84b5_4fa4_ba35_aa8172b8a09b);
pub const CLSID_DirectSoundCapture: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0210780_89cd_11d0_af08_00a0c925cd16);
pub const CLSID_DirectSoundCapture8: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe4bcac13_7f99_4908_9a8e_74e3bf24b6e1);
pub const CLSID_DirectSoundFullDuplex: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfea4300c_7959_4147_b26a_2377b9e7a91d);
pub const DIRECTSOUND_VERSION: u32 = 1792u32;
pub const DS3DALG_HRTF_FULL: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc2413340_1c1b_11d2_94f5_00c04fc28aca);
pub const DS3DALG_HRTF_LIGHT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc2413342_1c1b_11d2_94f5_00c04fc28aca);
pub const DS3DALG_NO_VIRTUALIZATION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc241333f_1c1b_11d2_94f5_00c04fc28aca);
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub struct DS3DBUFFER {
pub dwSize: u32,
pub vPosition: super::super::super::Graphics::Direct3D::D3DVECTOR,
pub vVelocity: super::super::super::Graphics::Direct3D::D3DVECTOR,
pub dwInsideConeAngle: u32,
pub dwOutsideConeAngle: u32,
pub vConeOrientation: super::super::super::Graphics::Direct3D::D3DVECTOR,
pub lConeOutsideVolume: i32,
pub flMinDistance: f32,
pub flMaxDistance: f32,
pub dwMode: u32,
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl DS3DBUFFER {}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::default::Default for DS3DBUFFER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::fmt::Debug for DS3DBUFFER {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DS3DBUFFER")
.field("dwSize", &self.dwSize)
.field("vPosition", &self.vPosition)
.field("vVelocity", &self.vVelocity)
.field("dwInsideConeAngle", &self.dwInsideConeAngle)
.field("dwOutsideConeAngle", &self.dwOutsideConeAngle)
.field("vConeOrientation", &self.vConeOrientation)
.field("lConeOutsideVolume", &self.lConeOutsideVolume)
.field("flMinDistance", &self.flMinDistance)
.field("flMaxDistance", &self.flMaxDistance)
.field("dwMode", &self.dwMode)
.finish()
}
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::cmp::PartialEq for DS3DBUFFER {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.vPosition == other.vPosition && self.vVelocity == other.vVelocity && self.dwInsideConeAngle == other.dwInsideConeAngle && self.dwOutsideConeAngle == other.dwOutsideConeAngle && self.vConeOrientation == other.vConeOrientation && self.lConeOutsideVolume == other.lConeOutsideVolume && self.flMinDistance == other.flMinDistance && self.flMaxDistance == other.flMaxDistance && self.dwMode == other.dwMode
}
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::cmp::Eq for DS3DBUFFER {}
#[cfg(feature = "Win32_Graphics_Direct3D")]
unsafe impl ::windows::core::Abi for DS3DBUFFER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub struct DS3DLISTENER {
pub dwSize: u32,
pub vPosition: super::super::super::Graphics::Direct3D::D3DVECTOR,
pub vVelocity: super::super::super::Graphics::Direct3D::D3DVECTOR,
pub vOrientFront: super::super::super::Graphics::Direct3D::D3DVECTOR,
pub vOrientTop: super::super::super::Graphics::Direct3D::D3DVECTOR,
pub flDistanceFactor: f32,
pub flRolloffFactor: f32,
pub flDopplerFactor: f32,
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl DS3DLISTENER {}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::default::Default for DS3DLISTENER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::fmt::Debug for DS3DLISTENER {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DS3DLISTENER")
.field("dwSize", &self.dwSize)
.field("vPosition", &self.vPosition)
.field("vVelocity", &self.vVelocity)
.field("vOrientFront", &self.vOrientFront)
.field("vOrientTop", &self.vOrientTop)
.field("flDistanceFactor", &self.flDistanceFactor)
.field("flRolloffFactor", &self.flRolloffFactor)
.field("flDopplerFactor", &self.flDopplerFactor)
.finish()
}
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::cmp::PartialEq for DS3DLISTENER {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.vPosition == other.vPosition && self.vVelocity == other.vVelocity && self.vOrientFront == other.vOrientFront && self.vOrientTop == other.vOrientTop && self.flDistanceFactor == other.flDistanceFactor && self.flRolloffFactor == other.flRolloffFactor && self.flDopplerFactor == other.flDopplerFactor
}
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
impl ::core::cmp::Eq for DS3DLISTENER {}
#[cfg(feature = "Win32_Graphics_Direct3D")]
unsafe impl ::windows::core::Abi for DS3DLISTENER {
type Abi = Self;
}
pub const DS3DMODE_DISABLE: u32 = 2u32;
pub const DS3DMODE_HEADRELATIVE: u32 = 1u32;
pub const DS3DMODE_NORMAL: u32 = 0u32;
pub const DS3D_DEFAULTCONEANGLE: u32 = 360u32;
pub const DS3D_DEFAULTCONEOUTSIDEVOLUME: u32 = 0u32;
pub const DS3D_DEFAULTDISTANCEFACTOR: f32 = 1f32;
pub const DS3D_DEFAULTDOPPLERFACTOR: f32 = 1f32;
pub const DS3D_DEFAULTMAXDISTANCE: f32 = 1000000000f32;
pub const DS3D_DEFAULTMINDISTANCE: f32 = 1f32;
pub const DS3D_DEFAULTROLLOFFFACTOR: f32 = 1f32;
pub const DS3D_DEFERRED: u32 = 1u32;
pub const DS3D_IMMEDIATE: u32 = 0u32;
pub const DS3D_MAXCONEANGLE: u32 = 360u32;
pub const DS3D_MAXDOPPLERFACTOR: f32 = 10f32;
pub const DS3D_MAXROLLOFFFACTOR: f32 = 10f32;
pub const DS3D_MINCONEANGLE: u32 = 0u32;
pub const DS3D_MINDOPPLERFACTOR: f32 = 0f32;
pub const DS3D_MINROLLOFFFACTOR: f32 = 0f32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSBCAPS {
pub dwSize: u32,
pub dwFlags: u32,
pub dwBufferBytes: u32,
pub dwUnlockTransferRate: u32,
pub dwPlayCpuOverhead: u32,
}
impl DSBCAPS {}
impl ::core::default::Default for DSBCAPS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSBCAPS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSBCAPS").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("dwBufferBytes", &self.dwBufferBytes).field("dwUnlockTransferRate", &self.dwUnlockTransferRate).field("dwPlayCpuOverhead", &self.dwPlayCpuOverhead).finish()
}
}
impl ::core::cmp::PartialEq for DSBCAPS {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.dwBufferBytes == other.dwBufferBytes && self.dwUnlockTransferRate == other.dwUnlockTransferRate && self.dwPlayCpuOverhead == other.dwPlayCpuOverhead
}
}
impl ::core::cmp::Eq for DSBCAPS {}
unsafe impl ::windows::core::Abi for DSBCAPS {
type Abi = Self;
}
pub const DSBCAPS_CTRL3D: u32 = 16u32;
pub const DSBCAPS_CTRLFREQUENCY: u32 = 32u32;
pub const DSBCAPS_CTRLFX: u32 = 512u32;
pub const DSBCAPS_CTRLPAN: u32 = 64u32;
pub const DSBCAPS_CTRLPOSITIONNOTIFY: u32 = 256u32;
pub const DSBCAPS_CTRLVOLUME: u32 = 128u32;
pub const DSBCAPS_GETCURRENTPOSITION2: u32 = 65536u32;
pub const DSBCAPS_GLOBALFOCUS: u32 = 32768u32;
pub const DSBCAPS_LOCDEFER: u32 = 262144u32;
pub const DSBCAPS_LOCHARDWARE: u32 = 4u32;
pub const DSBCAPS_LOCSOFTWARE: u32 = 8u32;
pub const DSBCAPS_MUTE3DATMAXDISTANCE: u32 = 131072u32;
pub const DSBCAPS_PRIMARYBUFFER: u32 = 1u32;
pub const DSBCAPS_STATIC: u32 = 2u32;
pub const DSBCAPS_STICKYFOCUS: u32 = 16384u32;
pub const DSBCAPS_TRUEPLAYPOSITION: u32 = 524288u32;
pub const DSBFREQUENCY_MAX: u32 = 200000u32;
pub const DSBFREQUENCY_MIN: u32 = 100u32;
pub const DSBFREQUENCY_ORIGINAL: u32 = 0u32;
pub const DSBLOCK_ENTIREBUFFER: u32 = 2u32;
pub const DSBLOCK_FROMWRITECURSOR: u32 = 1u32;
pub const DSBNOTIFICATIONS_MAX: u32 = 100000u32;
pub const DSBPAN_CENTER: u32 = 0u32;
pub const DSBPAN_LEFT: i32 = -10000i32;
pub const DSBPAN_RIGHT: u32 = 10000u32;
pub const DSBPLAY_LOCHARDWARE: u32 = 2u32;
pub const DSBPLAY_LOCSOFTWARE: u32 = 4u32;
pub const DSBPLAY_LOOPING: u32 = 1u32;
pub const DSBPLAY_TERMINATEBY_DISTANCE: u64 = 16u64;
pub const DSBPLAY_TERMINATEBY_PRIORITY: u64 = 32u64;
pub const DSBPLAY_TERMINATEBY_TIME: u32 = 8u32;
pub const DSBPN_OFFSETSTOP: u32 = 4294967295u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct DSBPOSITIONNOTIFY {
pub dwOffset: u32,
pub hEventNotify: super::super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl DSBPOSITIONNOTIFY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for DSBPOSITIONNOTIFY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for DSBPOSITIONNOTIFY {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSBPOSITIONNOTIFY").field("dwOffset", &self.dwOffset).field("hEventNotify", &self.hEventNotify).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for DSBPOSITIONNOTIFY {
fn eq(&self, other: &Self) -> bool {
self.dwOffset == other.dwOffset && self.hEventNotify == other.hEventNotify
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for DSBPOSITIONNOTIFY {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for DSBPOSITIONNOTIFY {
type Abi = Self;
}
pub const DSBSIZE_FX_MIN: u32 = 150u32;
pub const DSBSIZE_MAX: u32 = 268435455u32;
pub const DSBSIZE_MIN: u32 = 4u32;
pub const DSBSTATUS_BUFFERLOST: u32 = 2u32;
pub const DSBSTATUS_LOCHARDWARE: u32 = 8u32;
pub const DSBSTATUS_LOCSOFTWARE: u32 = 16u32;
pub const DSBSTATUS_LOOPING: u32 = 4u32;
pub const DSBSTATUS_PLAYING: u32 = 1u32;
pub const DSBSTATUS_TERMINATED: u32 = 32u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSBUFFERDESC {
pub dwSize: u32,
pub dwFlags: u32,
pub dwBufferBytes: u32,
pub dwReserved: u32,
pub lpwfxFormat: *mut super::WAVEFORMATEX,
pub guid3DAlgorithm: ::windows::core::GUID,
}
impl DSBUFFERDESC {}
impl ::core::default::Default for DSBUFFERDESC {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSBUFFERDESC {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSBUFFERDESC").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("dwBufferBytes", &self.dwBufferBytes).field("dwReserved", &self.dwReserved).field("lpwfxFormat", &self.lpwfxFormat).field("guid3DAlgorithm", &self.guid3DAlgorithm).finish()
}
}
impl ::core::cmp::PartialEq for DSBUFFERDESC {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.dwBufferBytes == other.dwBufferBytes && self.dwReserved == other.dwReserved && self.lpwfxFormat == other.lpwfxFormat && self.guid3DAlgorithm == other.guid3DAlgorithm
}
}
impl ::core::cmp::Eq for DSBUFFERDESC {}
unsafe impl ::windows::core::Abi for DSBUFFERDESC {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSBUFFERDESC1 {
pub dwSize: u32,
pub dwFlags: u32,
pub dwBufferBytes: u32,
pub dwReserved: u32,
pub lpwfxFormat: *mut super::WAVEFORMATEX,
}
impl DSBUFFERDESC1 {}
impl ::core::default::Default for DSBUFFERDESC1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSBUFFERDESC1 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSBUFFERDESC1").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("dwBufferBytes", &self.dwBufferBytes).field("dwReserved", &self.dwReserved).field("lpwfxFormat", &self.lpwfxFormat).finish()
}
}
impl ::core::cmp::PartialEq for DSBUFFERDESC1 {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.dwBufferBytes == other.dwBufferBytes && self.dwReserved == other.dwReserved && self.lpwfxFormat == other.lpwfxFormat
}
}
impl ::core::cmp::Eq for DSBUFFERDESC1 {}
unsafe impl ::windows::core::Abi for DSBUFFERDESC1 {
type Abi = Self;
}
pub const DSBVOLUME_MAX: u32 = 0u32;
pub const DSBVOLUME_MIN: i32 = -10000i32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSCAPS {
pub dwSize: u32,
pub dwFlags: u32,
pub dwMinSecondarySampleRate: u32,
pub dwMaxSecondarySampleRate: u32,
pub dwPrimaryBuffers: u32,
pub dwMaxHwMixingAllBuffers: u32,
pub dwMaxHwMixingStaticBuffers: u32,
pub dwMaxHwMixingStreamingBuffers: u32,
pub dwFreeHwMixingAllBuffers: u32,
pub dwFreeHwMixingStaticBuffers: u32,
pub dwFreeHwMixingStreamingBuffers: u32,
pub dwMaxHw3DAllBuffers: u32,
pub dwMaxHw3DStaticBuffers: u32,
pub dwMaxHw3DStreamingBuffers: u32,
pub dwFreeHw3DAllBuffers: u32,
pub dwFreeHw3DStaticBuffers: u32,
pub dwFreeHw3DStreamingBuffers: u32,
pub dwTotalHwMemBytes: u32,
pub dwFreeHwMemBytes: u32,
pub dwMaxContigFreeHwMemBytes: u32,
pub dwUnlockTransferRateHwBuffers: u32,
pub dwPlayCpuOverheadSwBuffers: u32,
pub dwReserved1: u32,
pub dwReserved2: u32,
}
impl DSCAPS {}
impl ::core::default::Default for DSCAPS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSCAPS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCAPS")
.field("dwSize", &self.dwSize)
.field("dwFlags", &self.dwFlags)
.field("dwMinSecondarySampleRate", &self.dwMinSecondarySampleRate)
.field("dwMaxSecondarySampleRate", &self.dwMaxSecondarySampleRate)
.field("dwPrimaryBuffers", &self.dwPrimaryBuffers)
.field("dwMaxHwMixingAllBuffers", &self.dwMaxHwMixingAllBuffers)
.field("dwMaxHwMixingStaticBuffers", &self.dwMaxHwMixingStaticBuffers)
.field("dwMaxHwMixingStreamingBuffers", &self.dwMaxHwMixingStreamingBuffers)
.field("dwFreeHwMixingAllBuffers", &self.dwFreeHwMixingAllBuffers)
.field("dwFreeHwMixingStaticBuffers", &self.dwFreeHwMixingStaticBuffers)
.field("dwFreeHwMixingStreamingBuffers", &self.dwFreeHwMixingStreamingBuffers)
.field("dwMaxHw3DAllBuffers", &self.dwMaxHw3DAllBuffers)
.field("dwMaxHw3DStaticBuffers", &self.dwMaxHw3DStaticBuffers)
.field("dwMaxHw3DStreamingBuffers", &self.dwMaxHw3DStreamingBuffers)
.field("dwFreeHw3DAllBuffers", &self.dwFreeHw3DAllBuffers)
.field("dwFreeHw3DStaticBuffers", &self.dwFreeHw3DStaticBuffers)
.field("dwFreeHw3DStreamingBuffers", &self.dwFreeHw3DStreamingBuffers)
.field("dwTotalHwMemBytes", &self.dwTotalHwMemBytes)
.field("dwFreeHwMemBytes", &self.dwFreeHwMemBytes)
.field("dwMaxContigFreeHwMemBytes", &self.dwMaxContigFreeHwMemBytes)
.field("dwUnlockTransferRateHwBuffers", &self.dwUnlockTransferRateHwBuffers)
.field("dwPlayCpuOverheadSwBuffers", &self.dwPlayCpuOverheadSwBuffers)
.field("dwReserved1", &self.dwReserved1)
.field("dwReserved2", &self.dwReserved2)
.finish()
}
}
impl ::core::cmp::PartialEq for DSCAPS {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize
&& self.dwFlags == other.dwFlags
&& self.dwMinSecondarySampleRate == other.dwMinSecondarySampleRate
&& self.dwMaxSecondarySampleRate == other.dwMaxSecondarySampleRate
&& self.dwPrimaryBuffers == other.dwPrimaryBuffers
&& self.dwMaxHwMixingAllBuffers == other.dwMaxHwMixingAllBuffers
&& self.dwMaxHwMixingStaticBuffers == other.dwMaxHwMixingStaticBuffers
&& self.dwMaxHwMixingStreamingBuffers == other.dwMaxHwMixingStreamingBuffers
&& self.dwFreeHwMixingAllBuffers == other.dwFreeHwMixingAllBuffers
&& self.dwFreeHwMixingStaticBuffers == other.dwFreeHwMixingStaticBuffers
&& self.dwFreeHwMixingStreamingBuffers == other.dwFreeHwMixingStreamingBuffers
&& self.dwMaxHw3DAllBuffers == other.dwMaxHw3DAllBuffers
&& self.dwMaxHw3DStaticBuffers == other.dwMaxHw3DStaticBuffers
&& self.dwMaxHw3DStreamingBuffers == other.dwMaxHw3DStreamingBuffers
&& self.dwFreeHw3DAllBuffers == other.dwFreeHw3DAllBuffers
&& self.dwFreeHw3DStaticBuffers == other.dwFreeHw3DStaticBuffers
&& self.dwFreeHw3DStreamingBuffers == other.dwFreeHw3DStreamingBuffers
&& self.dwTotalHwMemBytes == other.dwTotalHwMemBytes
&& self.dwFreeHwMemBytes == other.dwFreeHwMemBytes
&& self.dwMaxContigFreeHwMemBytes == other.dwMaxContigFreeHwMemBytes
&& self.dwUnlockTransferRateHwBuffers == other.dwUnlockTransferRateHwBuffers
&& self.dwPlayCpuOverheadSwBuffers == other.dwPlayCpuOverheadSwBuffers
&& self.dwReserved1 == other.dwReserved1
&& self.dwReserved2 == other.dwReserved2
}
}
impl ::core::cmp::Eq for DSCAPS {}
unsafe impl ::windows::core::Abi for DSCAPS {
type Abi = Self;
}
pub const DSCAPS_CERTIFIED: u32 = 64u32;
pub const DSCAPS_CONTINUOUSRATE: u32 = 16u32;
pub const DSCAPS_EMULDRIVER: u32 = 32u32;
pub const DSCAPS_PRIMARY16BIT: u32 = 8u32;
pub const DSCAPS_PRIMARY8BIT: u32 = 4u32;
pub const DSCAPS_PRIMARYMONO: u32 = 1u32;
pub const DSCAPS_PRIMARYSTEREO: u32 = 2u32;
pub const DSCAPS_SECONDARY16BIT: u32 = 2048u32;
pub const DSCAPS_SECONDARY8BIT: u32 = 1024u32;
pub const DSCAPS_SECONDARYMONO: u32 = 256u32;
pub const DSCAPS_SECONDARYSTEREO: u32 = 512u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSCBCAPS {
pub dwSize: u32,
pub dwFlags: u32,
pub dwBufferBytes: u32,
pub dwReserved: u32,
}
impl DSCBCAPS {}
impl ::core::default::Default for DSCBCAPS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSCBCAPS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCBCAPS").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("dwBufferBytes", &self.dwBufferBytes).field("dwReserved", &self.dwReserved).finish()
}
}
impl ::core::cmp::PartialEq for DSCBCAPS {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.dwBufferBytes == other.dwBufferBytes && self.dwReserved == other.dwReserved
}
}
impl ::core::cmp::Eq for DSCBCAPS {}
unsafe impl ::windows::core::Abi for DSCBCAPS {
type Abi = Self;
}
pub const DSCBCAPS_CTRLFX: u32 = 512u32;
pub const DSCBCAPS_WAVEMAPPED: u32 = 2147483648u32;
pub const DSCBLOCK_ENTIREBUFFER: u32 = 1u32;
pub const DSCBSTART_LOOPING: u32 = 1u32;
pub const DSCBSTATUS_CAPTURING: u32 = 1u32;
pub const DSCBSTATUS_LOOPING: u32 = 2u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSCBUFFERDESC {
pub dwSize: u32,
pub dwFlags: u32,
pub dwBufferBytes: u32,
pub dwReserved: u32,
pub lpwfxFormat: *mut super::WAVEFORMATEX,
pub dwFXCount: u32,
pub lpDSCFXDesc: *mut DSCEFFECTDESC,
}
impl DSCBUFFERDESC {}
impl ::core::default::Default for DSCBUFFERDESC {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSCBUFFERDESC {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCBUFFERDESC")
.field("dwSize", &self.dwSize)
.field("dwFlags", &self.dwFlags)
.field("dwBufferBytes", &self.dwBufferBytes)
.field("dwReserved", &self.dwReserved)
.field("lpwfxFormat", &self.lpwfxFormat)
.field("dwFXCount", &self.dwFXCount)
.field("lpDSCFXDesc", &self.lpDSCFXDesc)
.finish()
}
}
impl ::core::cmp::PartialEq for DSCBUFFERDESC {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.dwBufferBytes == other.dwBufferBytes && self.dwReserved == other.dwReserved && self.lpwfxFormat == other.lpwfxFormat && self.dwFXCount == other.dwFXCount && self.lpDSCFXDesc == other.lpDSCFXDesc
}
}
impl ::core::cmp::Eq for DSCBUFFERDESC {}
unsafe impl ::windows::core::Abi for DSCBUFFERDESC {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSCBUFFERDESC1 {
pub dwSize: u32,
pub dwFlags: u32,
pub dwBufferBytes: u32,
pub dwReserved: u32,
pub lpwfxFormat: *mut super::WAVEFORMATEX,
}
impl DSCBUFFERDESC1 {}
impl ::core::default::Default for DSCBUFFERDESC1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSCBUFFERDESC1 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCBUFFERDESC1").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("dwBufferBytes", &self.dwBufferBytes).field("dwReserved", &self.dwReserved).field("lpwfxFormat", &self.lpwfxFormat).finish()
}
}
impl ::core::cmp::PartialEq for DSCBUFFERDESC1 {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.dwBufferBytes == other.dwBufferBytes && self.dwReserved == other.dwReserved && self.lpwfxFormat == other.lpwfxFormat
}
}
impl ::core::cmp::Eq for DSCBUFFERDESC1 {}
unsafe impl ::windows::core::Abi for DSCBUFFERDESC1 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSCCAPS {
pub dwSize: u32,
pub dwFlags: u32,
pub dwFormats: u32,
pub dwChannels: u32,
}
impl DSCCAPS {}
impl ::core::default::Default for DSCCAPS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSCCAPS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCCAPS").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("dwFormats", &self.dwFormats).field("dwChannels", &self.dwChannels).finish()
}
}
impl ::core::cmp::PartialEq for DSCCAPS {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.dwFormats == other.dwFormats && self.dwChannels == other.dwChannels
}
}
impl ::core::cmp::Eq for DSCCAPS {}
unsafe impl ::windows::core::Abi for DSCCAPS {
type Abi = Self;
}
pub const DSCCAPS_CERTIFIED: u32 = 64u32;
pub const DSCCAPS_EMULDRIVER: u32 = 32u32;
pub const DSCCAPS_MULTIPLECAPTURE: u32 = 1u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSCEFFECTDESC {
pub dwSize: u32,
pub dwFlags: u32,
pub guidDSCFXClass: ::windows::core::GUID,
pub guidDSCFXInstance: ::windows::core::GUID,
pub dwReserved1: u32,
pub dwReserved2: u32,
}
impl DSCEFFECTDESC {}
impl ::core::default::Default for DSCEFFECTDESC {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSCEFFECTDESC {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCEFFECTDESC").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("guidDSCFXClass", &self.guidDSCFXClass).field("guidDSCFXInstance", &self.guidDSCFXInstance).field("dwReserved1", &self.dwReserved1).field("dwReserved2", &self.dwReserved2).finish()
}
}
impl ::core::cmp::PartialEq for DSCEFFECTDESC {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.guidDSCFXClass == other.guidDSCFXClass && self.guidDSCFXInstance == other.guidDSCFXInstance && self.dwReserved1 == other.dwReserved1 && self.dwReserved2 == other.dwReserved2
}
}
impl ::core::cmp::Eq for DSCEFFECTDESC {}
unsafe impl ::windows::core::Abi for DSCEFFECTDESC {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct DSCFXAec {
pub fEnable: super::super::super::Foundation::BOOL,
pub fNoiseFill: super::super::super::Foundation::BOOL,
pub dwMode: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl DSCFXAec {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for DSCFXAec {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for DSCFXAec {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCFXAec").field("fEnable", &self.fEnable).field("fNoiseFill", &self.fNoiseFill).field("dwMode", &self.dwMode).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for DSCFXAec {
fn eq(&self, other: &Self) -> bool {
self.fEnable == other.fEnable && self.fNoiseFill == other.fNoiseFill && self.dwMode == other.dwMode
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for DSCFXAec {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for DSCFXAec {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct DSCFXNoiseSuppress {
pub fEnable: super::super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl DSCFXNoiseSuppress {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for DSCFXNoiseSuppress {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for DSCFXNoiseSuppress {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSCFXNoiseSuppress").field("fEnable", &self.fEnable).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for DSCFXNoiseSuppress {
fn eq(&self, other: &Self) -> bool {
self.fEnable == other.fEnable
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for DSCFXNoiseSuppress {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for DSCFXNoiseSuppress {
type Abi = Self;
}
pub const DSCFXR_LOCHARDWARE: u32 = 16u32;
pub const DSCFXR_LOCSOFTWARE: u32 = 32u32;
pub const DSCFX_AEC_MODE_FULL_DUPLEX: u32 = 2u32;
pub const DSCFX_AEC_MODE_HALF_DUPLEX: u32 = 1u32;
pub const DSCFX_AEC_MODE_PASS_THROUGH: u32 = 0u32;
pub const DSCFX_AEC_STATUS_CURRENTLY_CONVERGED: u32 = 8u32;
pub const DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED: u32 = 1u32;
pub const DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED: u32 = 2u32;
pub const DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED: u32 = 0u32;
pub const DSCFX_LOCHARDWARE: u32 = 1u32;
pub const DSCFX_LOCSOFTWARE: u32 = 2u32;
pub const DSDEVID_DefaultCapture: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdef00001_9c6d_47ed_aaf1_4dda8f2b5c03);
pub const DSDEVID_DefaultPlayback: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdef00000_9c6d_47ed_aaf1_4dda8f2b5c03);
pub const DSDEVID_DefaultVoiceCapture: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdef00003_9c6d_47ed_aaf1_4dda8f2b5c03);
pub const DSDEVID_DefaultVoicePlayback: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdef00002_9c6d_47ed_aaf1_4dda8f2b5c03);
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSEFFECTDESC {
pub dwSize: u32,
pub dwFlags: u32,
pub guidDSFXClass: ::windows::core::GUID,
pub dwReserved1: usize,
pub dwReserved2: usize,
}
impl DSEFFECTDESC {}
impl ::core::default::Default for DSEFFECTDESC {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSEFFECTDESC {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSEFFECTDESC").field("dwSize", &self.dwSize).field("dwFlags", &self.dwFlags).field("guidDSFXClass", &self.guidDSFXClass).field("dwReserved1", &self.dwReserved1).field("dwReserved2", &self.dwReserved2).finish()
}
}
impl ::core::cmp::PartialEq for DSEFFECTDESC {
fn eq(&self, other: &Self) -> bool {
self.dwSize == other.dwSize && self.dwFlags == other.dwFlags && self.guidDSFXClass == other.guidDSFXClass && self.dwReserved1 == other.dwReserved1 && self.dwReserved2 == other.dwReserved2
}
}
impl ::core::cmp::Eq for DSEFFECTDESC {}
unsafe impl ::windows::core::Abi for DSEFFECTDESC {
type Abi = Self;
}
pub const DSFXCHORUS_DELAY_MAX: f32 = 20f32;
pub const DSFXCHORUS_DELAY_MIN: f32 = 0f32;
pub const DSFXCHORUS_DEPTH_MAX: f32 = 100f32;
pub const DSFXCHORUS_DEPTH_MIN: f32 = 0f32;
pub const DSFXCHORUS_FEEDBACK_MAX: f32 = 99f32;
pub const DSFXCHORUS_FEEDBACK_MIN: f32 = -99f32;
pub const DSFXCHORUS_FREQUENCY_MAX: f32 = 10f32;
pub const DSFXCHORUS_FREQUENCY_MIN: f32 = 0f32;
pub const DSFXCHORUS_PHASE_180: u32 = 4u32;
pub const DSFXCHORUS_PHASE_90: u32 = 3u32;
pub const DSFXCHORUS_PHASE_MAX: u32 = 4u32;
pub const DSFXCHORUS_PHASE_MIN: u32 = 0u32;
pub const DSFXCHORUS_PHASE_NEG_180: u32 = 0u32;
pub const DSFXCHORUS_PHASE_NEG_90: u32 = 1u32;
pub const DSFXCHORUS_PHASE_ZERO: u32 = 2u32;
pub const DSFXCHORUS_WAVE_SIN: u32 = 1u32;
pub const DSFXCHORUS_WAVE_TRIANGLE: u32 = 0u32;
pub const DSFXCHORUS_WETDRYMIX_MAX: f32 = 100f32;
pub const DSFXCHORUS_WETDRYMIX_MIN: f32 = 0f32;
pub const DSFXCOMPRESSOR_ATTACK_MAX: f32 = 500f32;
pub const DSFXCOMPRESSOR_ATTACK_MIN: f32 = 0.01f32;
pub const DSFXCOMPRESSOR_GAIN_MAX: f32 = 60f32;
pub const DSFXCOMPRESSOR_GAIN_MIN: f32 = -60f32;
pub const DSFXCOMPRESSOR_PREDELAY_MAX: f32 = 4f32;
pub const DSFXCOMPRESSOR_PREDELAY_MIN: f32 = 0f32;
pub const DSFXCOMPRESSOR_RATIO_MAX: f32 = 100f32;
pub const DSFXCOMPRESSOR_RATIO_MIN: f32 = 1f32;
pub const DSFXCOMPRESSOR_RELEASE_MAX: f32 = 3000f32;
pub const DSFXCOMPRESSOR_RELEASE_MIN: f32 = 50f32;
pub const DSFXCOMPRESSOR_THRESHOLD_MAX: f32 = 0f32;
pub const DSFXCOMPRESSOR_THRESHOLD_MIN: f32 = -60f32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXChorus {
pub fWetDryMix: f32,
pub fDepth: f32,
pub fFeedback: f32,
pub fFrequency: f32,
pub lWaveform: i32,
pub fDelay: f32,
pub lPhase: i32,
}
impl DSFXChorus {}
impl ::core::default::Default for DSFXChorus {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXChorus {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXChorus").field("fWetDryMix", &self.fWetDryMix).field("fDepth", &self.fDepth).field("fFeedback", &self.fFeedback).field("fFrequency", &self.fFrequency).field("lWaveform", &self.lWaveform).field("fDelay", &self.fDelay).field("lPhase", &self.lPhase).finish()
}
}
impl ::core::cmp::PartialEq for DSFXChorus {
fn eq(&self, other: &Self) -> bool {
self.fWetDryMix == other.fWetDryMix && self.fDepth == other.fDepth && self.fFeedback == other.fFeedback && self.fFrequency == other.fFrequency && self.lWaveform == other.lWaveform && self.fDelay == other.fDelay && self.lPhase == other.lPhase
}
}
impl ::core::cmp::Eq for DSFXChorus {}
unsafe impl ::windows::core::Abi for DSFXChorus {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXCompressor {
pub fGain: f32,
pub fAttack: f32,
pub fRelease: f32,
pub fThreshold: f32,
pub fRatio: f32,
pub fPredelay: f32,
}
impl DSFXCompressor {}
impl ::core::default::Default for DSFXCompressor {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXCompressor {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXCompressor").field("fGain", &self.fGain).field("fAttack", &self.fAttack).field("fRelease", &self.fRelease).field("fThreshold", &self.fThreshold).field("fRatio", &self.fRatio).field("fPredelay", &self.fPredelay).finish()
}
}
impl ::core::cmp::PartialEq for DSFXCompressor {
fn eq(&self, other: &Self) -> bool {
self.fGain == other.fGain && self.fAttack == other.fAttack && self.fRelease == other.fRelease && self.fThreshold == other.fThreshold && self.fRatio == other.fRatio && self.fPredelay == other.fPredelay
}
}
impl ::core::cmp::Eq for DSFXCompressor {}
unsafe impl ::windows::core::Abi for DSFXCompressor {
type Abi = Self;
}
pub const DSFXDISTORTION_EDGE_MAX: f32 = 100f32;
pub const DSFXDISTORTION_EDGE_MIN: f32 = 0f32;
pub const DSFXDISTORTION_GAIN_MAX: f32 = 0f32;
pub const DSFXDISTORTION_GAIN_MIN: f32 = -60f32;
pub const DSFXDISTORTION_POSTEQBANDWIDTH_MAX: f32 = 8000f32;
pub const DSFXDISTORTION_POSTEQBANDWIDTH_MIN: f32 = 100f32;
pub const DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX: f32 = 8000f32;
pub const DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN: f32 = 100f32;
pub const DSFXDISTORTION_PRELOWPASSCUTOFF_MAX: f32 = 8000f32;
pub const DSFXDISTORTION_PRELOWPASSCUTOFF_MIN: f32 = 100f32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXDistortion {
pub fGain: f32,
pub fEdge: f32,
pub fPostEQCenterFrequency: f32,
pub fPostEQBandwidth: f32,
pub fPreLowpassCutoff: f32,
}
impl DSFXDistortion {}
impl ::core::default::Default for DSFXDistortion {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXDistortion {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXDistortion").field("fGain", &self.fGain).field("fEdge", &self.fEdge).field("fPostEQCenterFrequency", &self.fPostEQCenterFrequency).field("fPostEQBandwidth", &self.fPostEQBandwidth).field("fPreLowpassCutoff", &self.fPreLowpassCutoff).finish()
}
}
impl ::core::cmp::PartialEq for DSFXDistortion {
fn eq(&self, other: &Self) -> bool {
self.fGain == other.fGain && self.fEdge == other.fEdge && self.fPostEQCenterFrequency == other.fPostEQCenterFrequency && self.fPostEQBandwidth == other.fPostEQBandwidth && self.fPreLowpassCutoff == other.fPreLowpassCutoff
}
}
impl ::core::cmp::Eq for DSFXDistortion {}
unsafe impl ::windows::core::Abi for DSFXDistortion {
type Abi = Self;
}
pub const DSFXECHO_FEEDBACK_MAX: f32 = 100f32;
pub const DSFXECHO_FEEDBACK_MIN: f32 = 0f32;
pub const DSFXECHO_LEFTDELAY_MAX: f32 = 2000f32;
pub const DSFXECHO_LEFTDELAY_MIN: f32 = 1f32;
pub const DSFXECHO_PANDELAY_MAX: u32 = 1u32;
pub const DSFXECHO_PANDELAY_MIN: u32 = 0u32;
pub const DSFXECHO_RIGHTDELAY_MAX: f32 = 2000f32;
pub const DSFXECHO_RIGHTDELAY_MIN: f32 = 1f32;
pub const DSFXECHO_WETDRYMIX_MAX: f32 = 100f32;
pub const DSFXECHO_WETDRYMIX_MIN: f32 = 0f32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXEcho {
pub fWetDryMix: f32,
pub fFeedback: f32,
pub fLeftDelay: f32,
pub fRightDelay: f32,
pub lPanDelay: i32,
}
impl DSFXEcho {}
impl ::core::default::Default for DSFXEcho {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXEcho {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXEcho").field("fWetDryMix", &self.fWetDryMix).field("fFeedback", &self.fFeedback).field("fLeftDelay", &self.fLeftDelay).field("fRightDelay", &self.fRightDelay).field("lPanDelay", &self.lPanDelay).finish()
}
}
impl ::core::cmp::PartialEq for DSFXEcho {
fn eq(&self, other: &Self) -> bool {
self.fWetDryMix == other.fWetDryMix && self.fFeedback == other.fFeedback && self.fLeftDelay == other.fLeftDelay && self.fRightDelay == other.fRightDelay && self.lPanDelay == other.lPanDelay
}
}
impl ::core::cmp::Eq for DSFXEcho {}
unsafe impl ::windows::core::Abi for DSFXEcho {
type Abi = Self;
}
pub const DSFXFLANGER_DELAY_MAX: f32 = 4f32;
pub const DSFXFLANGER_DELAY_MIN: f32 = 0f32;
pub const DSFXFLANGER_DEPTH_MAX: f32 = 100f32;
pub const DSFXFLANGER_DEPTH_MIN: f32 = 0f32;
pub const DSFXFLANGER_FEEDBACK_MAX: f32 = 99f32;
pub const DSFXFLANGER_FEEDBACK_MIN: f32 = -99f32;
pub const DSFXFLANGER_FREQUENCY_MAX: f32 = 10f32;
pub const DSFXFLANGER_FREQUENCY_MIN: f32 = 0f32;
pub const DSFXFLANGER_PHASE_180: u32 = 4u32;
pub const DSFXFLANGER_PHASE_90: u32 = 3u32;
pub const DSFXFLANGER_PHASE_MAX: u32 = 4u32;
pub const DSFXFLANGER_PHASE_MIN: u32 = 0u32;
pub const DSFXFLANGER_PHASE_NEG_180: u32 = 0u32;
pub const DSFXFLANGER_PHASE_NEG_90: u32 = 1u32;
pub const DSFXFLANGER_PHASE_ZERO: u32 = 2u32;
pub const DSFXFLANGER_WAVE_SIN: u32 = 1u32;
pub const DSFXFLANGER_WAVE_TRIANGLE: u32 = 0u32;
pub const DSFXFLANGER_WETDRYMIX_MAX: f32 = 100f32;
pub const DSFXFLANGER_WETDRYMIX_MIN: f32 = 0f32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXFlanger {
pub fWetDryMix: f32,
pub fDepth: f32,
pub fFeedback: f32,
pub fFrequency: f32,
pub lWaveform: i32,
pub fDelay: f32,
pub lPhase: i32,
}
impl DSFXFlanger {}
impl ::core::default::Default for DSFXFlanger {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXFlanger {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXFlanger").field("fWetDryMix", &self.fWetDryMix).field("fDepth", &self.fDepth).field("fFeedback", &self.fFeedback).field("fFrequency", &self.fFrequency).field("lWaveform", &self.lWaveform).field("fDelay", &self.fDelay).field("lPhase", &self.lPhase).finish()
}
}
impl ::core::cmp::PartialEq for DSFXFlanger {
fn eq(&self, other: &Self) -> bool {
self.fWetDryMix == other.fWetDryMix && self.fDepth == other.fDepth && self.fFeedback == other.fFeedback && self.fFrequency == other.fFrequency && self.lWaveform == other.lWaveform && self.fDelay == other.fDelay && self.lPhase == other.lPhase
}
}
impl ::core::cmp::Eq for DSFXFlanger {}
unsafe impl ::windows::core::Abi for DSFXFlanger {
type Abi = Self;
}
pub const DSFXGARGLE_RATEHZ_MAX: u32 = 1000u32;
pub const DSFXGARGLE_RATEHZ_MIN: u32 = 1u32;
pub const DSFXGARGLE_WAVE_SQUARE: u32 = 1u32;
pub const DSFXGARGLE_WAVE_TRIANGLE: u32 = 0u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXGargle {
pub dwRateHz: u32,
pub dwWaveShape: u32,
}
impl DSFXGargle {}
impl ::core::default::Default for DSFXGargle {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXGargle {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXGargle").field("dwRateHz", &self.dwRateHz).field("dwWaveShape", &self.dwWaveShape).finish()
}
}
impl ::core::cmp::PartialEq for DSFXGargle {
fn eq(&self, other: &Self) -> bool {
self.dwRateHz == other.dwRateHz && self.dwWaveShape == other.dwWaveShape
}
}
impl ::core::cmp::Eq for DSFXGargle {}
unsafe impl ::windows::core::Abi for DSFXGargle {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXI3DL2Reverb {
pub lRoom: i32,
pub lRoomHF: i32,
pub flRoomRolloffFactor: f32,
pub flDecayTime: f32,
pub flDecayHFRatio: f32,
pub lReflections: i32,
pub flReflectionsDelay: f32,
pub lReverb: i32,
pub flReverbDelay: f32,
pub flDiffusion: f32,
pub flDensity: f32,
pub flHFReference: f32,
}
impl DSFXI3DL2Reverb {}
impl ::core::default::Default for DSFXI3DL2Reverb {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXI3DL2Reverb {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXI3DL2Reverb")
.field("lRoom", &self.lRoom)
.field("lRoomHF", &self.lRoomHF)
.field("flRoomRolloffFactor", &self.flRoomRolloffFactor)
.field("flDecayTime", &self.flDecayTime)
.field("flDecayHFRatio", &self.flDecayHFRatio)
.field("lReflections", &self.lReflections)
.field("flReflectionsDelay", &self.flReflectionsDelay)
.field("lReverb", &self.lReverb)
.field("flReverbDelay", &self.flReverbDelay)
.field("flDiffusion", &self.flDiffusion)
.field("flDensity", &self.flDensity)
.field("flHFReference", &self.flHFReference)
.finish()
}
}
impl ::core::cmp::PartialEq for DSFXI3DL2Reverb {
fn eq(&self, other: &Self) -> bool {
self.lRoom == other.lRoom
&& self.lRoomHF == other.lRoomHF
&& self.flRoomRolloffFactor == other.flRoomRolloffFactor
&& self.flDecayTime == other.flDecayTime
&& self.flDecayHFRatio == other.flDecayHFRatio
&& self.lReflections == other.lReflections
&& self.flReflectionsDelay == other.flReflectionsDelay
&& self.lReverb == other.lReverb
&& self.flReverbDelay == other.flReverbDelay
&& self.flDiffusion == other.flDiffusion
&& self.flDensity == other.flDensity
&& self.flHFReference == other.flHFReference
}
}
impl ::core::cmp::Eq for DSFXI3DL2Reverb {}
unsafe impl ::windows::core::Abi for DSFXI3DL2Reverb {
type Abi = Self;
}
pub const DSFXPARAMEQ_BANDWIDTH_MAX: f32 = 36f32;
pub const DSFXPARAMEQ_BANDWIDTH_MIN: f32 = 1f32;
pub const DSFXPARAMEQ_CENTER_MAX: f32 = 16000f32;
pub const DSFXPARAMEQ_CENTER_MIN: f32 = 80f32;
pub const DSFXPARAMEQ_GAIN_MAX: f32 = 15f32;
pub const DSFXPARAMEQ_GAIN_MIN: f32 = -15f32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXParamEq {
pub fCenter: f32,
pub fBandwidth: f32,
pub fGain: f32,
}
impl DSFXParamEq {}
impl ::core::default::Default for DSFXParamEq {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXParamEq {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXParamEq").field("fCenter", &self.fCenter).field("fBandwidth", &self.fBandwidth).field("fGain", &self.fGain).finish()
}
}
impl ::core::cmp::PartialEq for DSFXParamEq {
fn eq(&self, other: &Self) -> bool {
self.fCenter == other.fCenter && self.fBandwidth == other.fBandwidth && self.fGain == other.fGain
}
}
impl ::core::cmp::Eq for DSFXParamEq {}
unsafe impl ::windows::core::Abi for DSFXParamEq {
type Abi = Self;
}
pub const DSFXR_FAILED: i32 = 4i32;
pub const DSFXR_LOCHARDWARE: i32 = 1i32;
pub const DSFXR_LOCSOFTWARE: i32 = 2i32;
pub const DSFXR_PRESENT: i32 = 0i32;
pub const DSFXR_SENDLOOP: i32 = 6i32;
pub const DSFXR_UNALLOCATED: i32 = 3i32;
pub const DSFXR_UNKNOWN: i32 = 5i32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DSFXWavesReverb {
pub fInGain: f32,
pub fReverbMix: f32,
pub fReverbTime: f32,
pub fHighFreqRTRatio: f32,
}
impl DSFXWavesReverb {}
impl ::core::default::Default for DSFXWavesReverb {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DSFXWavesReverb {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DSFXWavesReverb").field("fInGain", &self.fInGain).field("fReverbMix", &self.fReverbMix).field("fReverbTime", &self.fReverbTime).field("fHighFreqRTRatio", &self.fHighFreqRTRatio).finish()
}
}
impl ::core::cmp::PartialEq for DSFXWavesReverb {
fn eq(&self, other: &Self) -> bool {
self.fInGain == other.fInGain && self.fReverbMix == other.fReverbMix && self.fReverbTime == other.fReverbTime && self.fHighFreqRTRatio == other.fHighFreqRTRatio
}
}
impl ::core::cmp::Eq for DSFXWavesReverb {}
unsafe impl ::windows::core::Abi for DSFXWavesReverb {
type Abi = Self;
}
pub const DSFX_I3DL2REVERB_DECAYHFRATIO_DEFAULT: f32 = 0.83f32;
pub const DSFX_I3DL2REVERB_DECAYHFRATIO_MAX: f32 = 2f32;
pub const DSFX_I3DL2REVERB_DECAYHFRATIO_MIN: f32 = 0.1f32;
pub const DSFX_I3DL2REVERB_DECAYTIME_DEFAULT: f32 = 1.49f32;
pub const DSFX_I3DL2REVERB_DECAYTIME_MAX: f32 = 20f32;
pub const DSFX_I3DL2REVERB_DECAYTIME_MIN: f32 = 0.1f32;
pub const DSFX_I3DL2REVERB_DENSITY_DEFAULT: f32 = 100f32;
pub const DSFX_I3DL2REVERB_DENSITY_MAX: f32 = 100f32;
pub const DSFX_I3DL2REVERB_DENSITY_MIN: f32 = 0f32;
pub const DSFX_I3DL2REVERB_DIFFUSION_DEFAULT: f32 = 100f32;
pub const DSFX_I3DL2REVERB_DIFFUSION_MAX: f32 = 100f32;
pub const DSFX_I3DL2REVERB_DIFFUSION_MIN: f32 = 0f32;
pub const DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT: f32 = 5000f32;
pub const DSFX_I3DL2REVERB_HFREFERENCE_MAX: f32 = 20000f32;
pub const DSFX_I3DL2REVERB_HFREFERENCE_MIN: f32 = 20f32;
pub const DSFX_I3DL2REVERB_QUALITY_DEFAULT: u32 = 2u32;
pub const DSFX_I3DL2REVERB_QUALITY_MAX: u32 = 3u32;
pub const DSFX_I3DL2REVERB_QUALITY_MIN: u32 = 0u32;
pub const DSFX_I3DL2REVERB_REFLECTIONSDELAY_DEFAULT: f32 = 0.007f32;
pub const DSFX_I3DL2REVERB_REFLECTIONSDELAY_MAX: f32 = 0.3f32;
pub const DSFX_I3DL2REVERB_REFLECTIONSDELAY_MIN: f32 = 0f32;
pub const DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT: i32 = -2602i32;
pub const DSFX_I3DL2REVERB_REFLECTIONS_MAX: u32 = 1000u32;
pub const DSFX_I3DL2REVERB_REFLECTIONS_MIN: i32 = -10000i32;
pub const DSFX_I3DL2REVERB_REVERBDELAY_DEFAULT: f32 = 0.011f32;
pub const DSFX_I3DL2REVERB_REVERBDELAY_MAX: f32 = 0.1f32;
pub const DSFX_I3DL2REVERB_REVERBDELAY_MIN: f32 = 0f32;
pub const DSFX_I3DL2REVERB_REVERB_DEFAULT: u32 = 200u32;
pub const DSFX_I3DL2REVERB_REVERB_MAX: u32 = 2000u32;
pub const DSFX_I3DL2REVERB_REVERB_MIN: i32 = -10000i32;
pub const DSFX_I3DL2REVERB_ROOMHF_DEFAULT: i32 = -100i32;
pub const DSFX_I3DL2REVERB_ROOMHF_MAX: u32 = 0u32;
pub const DSFX_I3DL2REVERB_ROOMHF_MIN: i32 = -10000i32;
pub const DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT: f32 = 0f32;
pub const DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX: f32 = 10f32;
pub const DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN: f32 = 0f32;
pub const DSFX_I3DL2REVERB_ROOM_DEFAULT: i32 = -1000i32;
pub const DSFX_I3DL2REVERB_ROOM_MAX: u32 = 0u32;
pub const DSFX_I3DL2REVERB_ROOM_MIN: i32 = -10000i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_ALLEY: i32 = 15i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_ARENA: i32 = 10i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM: i32 = 7i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_BATHROOM: i32 = 4i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY: i32 = 12i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CAVE: i32 = 9i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CITY: i32 = 17i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL: i32 = 8i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_DEFAULT: i32 = 0i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_FOREST: i32 = 16i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_GENERIC: i32 = 1i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_HALLWAY: i32 = 13i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_HANGAR: i32 = 11i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEHALL: i32 = 28i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEROOM: i32 = 26i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM: i32 = 5i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL: i32 = 27i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM: i32 = 25i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS: i32 = 18i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL: i32 = 2i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT: i32 = 21i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PLAIN: i32 = 20i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PLATE: i32 = 29i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_QUARRY: i32 = 19i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_ROOM: i32 = 3i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE: i32 = 22i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_SMALLROOM: i32 = 24i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR: i32 = 14i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_STONEROOM: i32 = 6i32;
pub const DSFX_I3DL2_ENVIRONMENT_PRESET_UNDERWATER: i32 = 23i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_BRICKWALL: i32 = 5i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_CURTAIN: i32 = 7i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_DOUBLEWINDOW: i32 = 1i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_SINGLEWINDOW: i32 = 0i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_STONEWALL: i32 = 6i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_THICKDOOR: i32 = 3i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_THINDOOR: i32 = 2i32;
pub const DSFX_I3DL2_MATERIAL_PRESET_WOODWALL: i32 = 4i32;
pub const DSFX_LOCHARDWARE: u32 = 1u32;
pub const DSFX_LOCSOFTWARE: u32 = 2u32;
pub const DSFX_WAVESREVERB_HIGHFREQRTRATIO_DEFAULT: f32 = 0.001f32;
pub const DSFX_WAVESREVERB_HIGHFREQRTRATIO_MAX: f32 = 0.999f32;
pub const DSFX_WAVESREVERB_HIGHFREQRTRATIO_MIN: f32 = 0.001f32;
pub const DSFX_WAVESREVERB_INGAIN_DEFAULT: f32 = 0f32;
pub const DSFX_WAVESREVERB_INGAIN_MAX: f32 = 0f32;
pub const DSFX_WAVESREVERB_INGAIN_MIN: f32 = -96f32;
pub const DSFX_WAVESREVERB_REVERBMIX_DEFAULT: f32 = 0f32;
pub const DSFX_WAVESREVERB_REVERBMIX_MAX: f32 = 0f32;
pub const DSFX_WAVESREVERB_REVERBMIX_MIN: f32 = -96f32;
pub const DSFX_WAVESREVERB_REVERBTIME_DEFAULT: f32 = 1000f32;
pub const DSFX_WAVESREVERB_REVERBTIME_MAX: f32 = 3000f32;
pub const DSFX_WAVESREVERB_REVERBTIME_MIN: f32 = 0.001f32;
pub const DSSCL_EXCLUSIVE: u32 = 3u32;
pub const DSSCL_NORMAL: u32 = 1u32;
pub const DSSCL_PRIORITY: u32 = 2u32;
pub const DSSCL_WRITEPRIMARY: u32 = 4u32;
pub const DSSPEAKER_5POINT1: u32 = 6u32;
pub const DSSPEAKER_5POINT1_BACK: u32 = 6u32;
pub const DSSPEAKER_5POINT1_SURROUND: u32 = 9u32;
pub const DSSPEAKER_7POINT1: u32 = 7u32;
pub const DSSPEAKER_7POINT1_SURROUND: u32 = 8u32;
pub const DSSPEAKER_7POINT1_WIDE: u32 = 7u32;
pub const DSSPEAKER_DIRECTOUT: u32 = 0u32;
pub const DSSPEAKER_GEOMETRY_MAX: u32 = 180u32;
pub const DSSPEAKER_GEOMETRY_MIN: u32 = 5u32;
pub const DSSPEAKER_GEOMETRY_NARROW: u32 = 10u32;
pub const DSSPEAKER_GEOMETRY_WIDE: u32 = 20u32;
pub const DSSPEAKER_HEADPHONE: u32 = 1u32;
pub const DSSPEAKER_MONO: u32 = 2u32;
pub const DSSPEAKER_QUAD: u32 = 3u32;
pub const DSSPEAKER_STEREO: u32 = 4u32;
pub const DSSPEAKER_SURROUND: u32 = 5u32;
pub const DS_CERTIFIED: u32 = 0u32;
pub const DS_NO_VIRTUALIZATION: ::windows::core::HRESULT = ::windows::core::HRESULT(142082058i32 as _);
pub const DS_UNCERTIFIED: u32 = 1u32;
#[inline]
pub unsafe fn DirectSoundCaptureCreate<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(pcguiddevice: *const ::windows::core::GUID, ppdsc: *mut ::core::option::Option<IDirectSoundCapture>, punkouter: Param2) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundCaptureCreate(pcguiddevice: *const ::windows::core::GUID, ppdsc: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT;
}
DirectSoundCaptureCreate(::core::mem::transmute(pcguiddevice), ::core::mem::transmute(ppdsc), punkouter.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn DirectSoundCaptureCreate8<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(pcguiddevice: *const ::windows::core::GUID, ppdsc8: *mut ::core::option::Option<IDirectSoundCapture>, punkouter: Param2) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundCaptureCreate8(pcguiddevice: *const ::windows::core::GUID, ppdsc8: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT;
}
DirectSoundCaptureCreate8(::core::mem::transmute(pcguiddevice), ::core::mem::transmute(ppdsc8), punkouter.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn DirectSoundCaptureEnumerateA(pdsenumcallback: ::core::option::Option<LPDSENUMCALLBACKA>, pcontext: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundCaptureEnumerateA(pdsenumcallback: ::windows::core::RawPtr, pcontext: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
DirectSoundCaptureEnumerateA(::core::mem::transmute(pdsenumcallback), ::core::mem::transmute(pcontext)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn DirectSoundCaptureEnumerateW(pdsenumcallback: ::core::option::Option<LPDSENUMCALLBACKW>, pcontext: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundCaptureEnumerateW(pdsenumcallback: ::windows::core::RawPtr, pcontext: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
DirectSoundCaptureEnumerateW(::core::mem::transmute(pdsenumcallback), ::core::mem::transmute(pcontext)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn DirectSoundCreate<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(pcguiddevice: *const ::windows::core::GUID, ppds: *mut ::core::option::Option<IDirectSound>, punkouter: Param2) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundCreate(pcguiddevice: *const ::windows::core::GUID, ppds: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT;
}
DirectSoundCreate(::core::mem::transmute(pcguiddevice), ::core::mem::transmute(ppds), punkouter.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn DirectSoundCreate8<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(pcguiddevice: *const ::windows::core::GUID, ppds8: *mut ::core::option::Option<IDirectSound8>, punkouter: Param2) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundCreate8(pcguiddevice: *const ::windows::core::GUID, ppds8: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT;
}
DirectSoundCreate8(::core::mem::transmute(pcguiddevice), ::core::mem::transmute(ppds8), punkouter.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn DirectSoundEnumerateA(pdsenumcallback: ::core::option::Option<LPDSENUMCALLBACKA>, pcontext: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundEnumerateA(pdsenumcallback: ::windows::core::RawPtr, pcontext: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
DirectSoundEnumerateA(::core::mem::transmute(pdsenumcallback), ::core::mem::transmute(pcontext)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn DirectSoundEnumerateW(pdsenumcallback: ::core::option::Option<LPDSENUMCALLBACKW>, pcontext: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundEnumerateW(pdsenumcallback: ::windows::core::RawPtr, pcontext: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
DirectSoundEnumerateW(::core::mem::transmute(pdsenumcallback), ::core::mem::transmute(pcontext)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn DirectSoundFullDuplexCreate<'a, Param4: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>, Param9: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(
pcguidcapturedevice: *const ::windows::core::GUID,
pcguidrenderdevice: *const ::windows::core::GUID,
pcdscbufferdesc: *const DSCBUFFERDESC,
pcdsbufferdesc: *const DSBUFFERDESC,
hwnd: Param4,
dwlevel: u32,
ppdsfd: *mut ::core::option::Option<IDirectSoundFullDuplex>,
ppdscbuffer8: *mut ::core::option::Option<IDirectSoundCaptureBuffer8>,
ppdsbuffer8: *mut ::core::option::Option<IDirectSoundBuffer8>,
punkouter: Param9,
) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn DirectSoundFullDuplexCreate(pcguidcapturedevice: *const ::windows::core::GUID, pcguidrenderdevice: *const ::windows::core::GUID, pcdscbufferdesc: *const DSCBUFFERDESC, pcdsbufferdesc: *const DSBUFFERDESC, hwnd: super::super::super::Foundation::HWND, dwlevel: u32, ppdsfd: *mut ::windows::core::RawPtr, ppdscbuffer8: *mut ::windows::core::RawPtr, ppdsbuffer8: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT;
}
DirectSoundFullDuplexCreate(
::core::mem::transmute(pcguidcapturedevice),
::core::mem::transmute(pcguidrenderdevice),
::core::mem::transmute(pcdscbufferdesc),
::core::mem::transmute(pcdsbufferdesc),
hwnd.into_param().abi(),
::core::mem::transmute(dwlevel),
::core::mem::transmute(ppdsfd),
::core::mem::transmute(ppdscbuffer8),
::core::mem::transmute(ppdsbuffer8),
punkouter.into_param().abi(),
)
.ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
pub const GUID_All_Objects: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaa114de5_c262_4169_a1c8_23d698cc73b5);
pub const GUID_DSCFX_CLASS_AEC: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbf963d80_c559_11d0_8a2b_00a0c9255ac1);
pub const GUID_DSCFX_CLASS_NS: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe07f903f_62fd_4e60_8cdd_dea7236665b5);
pub const GUID_DSCFX_MS_AEC: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcdebb919_379a_488a_8765_f53cfd36de40);
pub const GUID_DSCFX_MS_NS: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11c5c73b_66e9_4ba1_a0ba_e814c6eed92d);
pub const GUID_DSCFX_SYSTEM_AEC: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1c22c56d_9879_4f5b_a389_27996ddc2810);
pub const GUID_DSCFX_SYSTEM_NS: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5ab0882e_7274_4516_877d_4eee99ba4fd0);
pub const GUID_DSFX_STANDARD_CHORUS: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xefe6629c_81f7_4281_bd91_c9d604a95af6);
pub const GUID_DSFX_STANDARD_COMPRESSOR: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef011f79_4000_406d_87af_bffb3fc39d57);
pub const GUID_DSFX_STANDARD_DISTORTION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef114c90_cd1d_484e_96e5_09cfaf912a21);
pub const GUID_DSFX_STANDARD_ECHO: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef3e932c_d40b_4f51_8ccf_3f98f1b29d5d);
pub const GUID_DSFX_STANDARD_FLANGER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xefca3d92_dfd8_4672_a603_7420894bad98);
pub const GUID_DSFX_STANDARD_GARGLE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdafd8210_5711_4b91_9fe3_f75b7ae279bf);
pub const GUID_DSFX_STANDARD_I3DL2REVERB: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef985e71_d5c7_42d4_ba4d_2d073e2e96f4);
pub const GUID_DSFX_STANDARD_PARAMEQ: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x120ced89_3bf4_4173_a132_3cb406cf3231);
pub const GUID_DSFX_WAVES_REVERB: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x87fc0268_9a55_4360_95aa_004a1d9de26c);
#[inline]
pub unsafe fn GetDeviceID(pguidsrc: *const ::windows::core::GUID) -> ::windows::core::Result<::windows::core::GUID> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetDeviceID(pguidsrc: *const ::windows::core::GUID, pguiddest: *mut ::windows::core::GUID) -> ::windows::core::HRESULT;
}
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
GetDeviceID(::core::mem::transmute(pguidsrc), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSound(pub ::windows::core::IUnknown);
impl IDirectSound {
pub unsafe fn CreateSoundBuffer<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, pcdsbufferdesc: *const DSBUFFERDESC, ppdsbuffer: *mut ::core::option::Option<IDirectSoundBuffer>, punkouter: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsbufferdesc), ::core::mem::transmute(ppdsbuffer), punkouter.into_param().abi()).ok()
}
pub unsafe fn GetCaps(&self) -> ::windows::core::Result<DSCAPS> {
let mut result__: <DSCAPS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSCAPS>(result__)
}
pub unsafe fn DuplicateSoundBuffer<'a, Param0: ::windows::core::IntoParam<'a, IDirectSoundBuffer>>(&self, pdsbufferoriginal: Param0) -> ::windows::core::Result<IDirectSoundBuffer> {
let mut result__: <IDirectSoundBuffer as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pdsbufferoriginal.into_param().abi(), &mut result__).from_abi::<IDirectSoundBuffer>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetCooperativeLevel<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>>(&self, hwnd: Param0, dwlevel: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), hwnd.into_param().abi(), ::core::mem::transmute(dwlevel)).ok()
}
pub unsafe fn Compact(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn GetSpeakerConfig(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn SetSpeakerConfig(&self, dwspeakerconfig: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwspeakerconfig)).ok()
}
pub unsafe fn Initialize(&self, pcguiddevice: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcguiddevice)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSound {
type Vtable = IDirectSound_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x279afa83_4981_11ce_a521_0020af0be560);
}
impl ::core::convert::From<IDirectSound> for ::windows::core::IUnknown {
fn from(value: IDirectSound) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSound> for ::windows::core::IUnknown {
fn from(value: &IDirectSound) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSound {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSound {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSound_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsbufferdesc: *const DSBUFFERDESC, ppdsbuffer: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdscaps: *mut DSCAPS) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsbufferoriginal: ::windows::core::RawPtr, ppdsbufferduplicate: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hwnd: super::super::super::Foundation::HWND, dwlevel: u32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwspeakerconfig: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwspeakerconfig: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcguiddevice: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSound3DBuffer(pub ::windows::core::IUnknown);
impl IDirectSound3DBuffer {
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DS3DBUFFER> {
let mut result__: <DS3DBUFFER as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DS3DBUFFER>(result__)
}
pub unsafe fn GetConeAngles(&self, pdwinsideconeangle: *mut u32, pdwoutsideconeangle: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwinsideconeangle), ::core::mem::transmute(pdwoutsideconeangle)).ok()
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetConeOrientation(&self) -> ::windows::core::Result<super::super::super::Graphics::Direct3D::D3DVECTOR> {
let mut result__: <super::super::super::Graphics::Direct3D::D3DVECTOR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Graphics::Direct3D::D3DVECTOR>(result__)
}
pub unsafe fn GetConeOutsideVolume(&self) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
pub unsafe fn GetMaxDistance(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetMinDistance(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetMode(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetPosition(&self) -> ::windows::core::Result<super::super::super::Graphics::Direct3D::D3DVECTOR> {
let mut result__: <super::super::super::Graphics::Direct3D::D3DVECTOR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Graphics::Direct3D::D3DVECTOR>(result__)
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetVelocity(&self) -> ::windows::core::Result<super::super::super::Graphics::Direct3D::D3DVECTOR> {
let mut result__: <super::super::super::Graphics::Direct3D::D3DVECTOR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Graphics::Direct3D::D3DVECTOR>(result__)
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn SetAllParameters(&self, pcds3dbuffer: *const DS3DBUFFER, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcds3dbuffer), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetConeAngles(&self, dwinsideconeangle: u32, dwoutsideconeangle: u32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwinsideconeangle), ::core::mem::transmute(dwoutsideconeangle), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetConeOrientation(&self, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(x), ::core::mem::transmute(y), ::core::mem::transmute(z), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetConeOutsideVolume(&self, lconeoutsidevolume: i32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(lconeoutsidevolume), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetMaxDistance(&self, flmaxdistance: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(flmaxdistance), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetMinDistance(&self, flmindistance: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(flmindistance), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetMode(&self, dwmode: u32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwmode), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetPosition(&self, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(x), ::core::mem::transmute(y), ::core::mem::transmute(z), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetVelocity(&self, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(x), ::core::mem::transmute(y), ::core::mem::transmute(z), ::core::mem::transmute(dwapply)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSound3DBuffer {
type Vtable = IDirectSound3DBuffer_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x279afa86_4981_11ce_a521_0020af0be560);
}
impl ::core::convert::From<IDirectSound3DBuffer> for ::windows::core::IUnknown {
fn from(value: IDirectSound3DBuffer) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSound3DBuffer> for ::windows::core::IUnknown {
fn from(value: &IDirectSound3DBuffer) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSound3DBuffer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSound3DBuffer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSound3DBuffer_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pds3dbuffer: *mut DS3DBUFFER) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwinsideconeangle: *mut u32, pdwoutsideconeangle: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvorientation: *mut super::super::super::Graphics::Direct3D::D3DVECTOR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plconeoutsidevolume: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pflmaxdistance: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pflmindistance: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwmode: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvposition: *mut super::super::super::Graphics::Direct3D::D3DVECTOR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvvelocity: *mut super::super::super::Graphics::Direct3D::D3DVECTOR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcds3dbuffer: *const DS3DBUFFER, dwapply: u32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwinsideconeangle: u32, dwoutsideconeangle: u32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lconeoutsidevolume: i32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, flmaxdistance: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, flmindistance: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwmode: u32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSound3DListener(pub ::windows::core::IUnknown);
impl IDirectSound3DListener {
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DS3DLISTENER> {
let mut result__: <DS3DLISTENER as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DS3DLISTENER>(result__)
}
pub unsafe fn GetDistanceFactor(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetDopplerFactor(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetOrientation(&self, pvorientfront: *mut super::super::super::Graphics::Direct3D::D3DVECTOR, pvorienttop: *mut super::super::super::Graphics::Direct3D::D3DVECTOR) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvorientfront), ::core::mem::transmute(pvorienttop)).ok()
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetPosition(&self) -> ::windows::core::Result<super::super::super::Graphics::Direct3D::D3DVECTOR> {
let mut result__: <super::super::super::Graphics::Direct3D::D3DVECTOR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Graphics::Direct3D::D3DVECTOR>(result__)
}
pub unsafe fn GetRolloffFactor(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn GetVelocity(&self) -> ::windows::core::Result<super::super::super::Graphics::Direct3D::D3DVECTOR> {
let mut result__: <super::super::super::Graphics::Direct3D::D3DVECTOR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Graphics::Direct3D::D3DVECTOR>(result__)
}
#[cfg(feature = "Win32_Graphics_Direct3D")]
pub unsafe fn SetAllParameters(&self, pclistener: *const DS3DLISTENER, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pclistener), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetDistanceFactor(&self, fldistancefactor: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(fldistancefactor), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetDopplerFactor(&self, fldopplerfactor: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(fldopplerfactor), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetOrientation(&self, xfront: f32, yfront: f32, zfront: f32, xtop: f32, ytop: f32, ztop: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(xfront), ::core::mem::transmute(yfront), ::core::mem::transmute(zfront), ::core::mem::transmute(xtop), ::core::mem::transmute(ytop), ::core::mem::transmute(ztop), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetPosition(&self, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(x), ::core::mem::transmute(y), ::core::mem::transmute(z), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetRolloffFactor(&self, flrollofffactor: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(flrollofffactor), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn SetVelocity(&self, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(x), ::core::mem::transmute(y), ::core::mem::transmute(z), ::core::mem::transmute(dwapply)).ok()
}
pub unsafe fn CommitDeferredSettings(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSound3DListener {
type Vtable = IDirectSound3DListener_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x279afa84_4981_11ce_a521_0020af0be560);
}
impl ::core::convert::From<IDirectSound3DListener> for ::windows::core::IUnknown {
fn from(value: IDirectSound3DListener) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSound3DListener> for ::windows::core::IUnknown {
fn from(value: &IDirectSound3DListener) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSound3DListener {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSound3DListener {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSound3DListener_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plistener: *mut DS3DLISTENER) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfldistancefactor: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfldopplerfactor: *mut f32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvorientfront: *mut super::super::super::Graphics::Direct3D::D3DVECTOR, pvorienttop: *mut super::super::super::Graphics::Direct3D::D3DVECTOR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvposition: *mut super::super::super::Graphics::Direct3D::D3DVECTOR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pflrollofffactor: *mut f32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvvelocity: *mut super::super::super::Graphics::Direct3D::D3DVECTOR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
#[cfg(feature = "Win32_Graphics_Direct3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pclistener: *const DS3DLISTENER, dwapply: u32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Graphics_Direct3D"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fldistancefactor: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fldopplerfactor: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xfront: f32, yfront: f32, zfront: f32, xtop: f32, ytop: f32, ztop: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, flrollofffactor: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, x: f32, y: f32, z: f32, dwapply: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSound8(pub ::windows::core::IUnknown);
impl IDirectSound8 {
pub unsafe fn CreateSoundBuffer<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, pcdsbufferdesc: *const DSBUFFERDESC, ppdsbuffer: *mut ::core::option::Option<IDirectSoundBuffer>, punkouter: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsbufferdesc), ::core::mem::transmute(ppdsbuffer), punkouter.into_param().abi()).ok()
}
pub unsafe fn GetCaps(&self) -> ::windows::core::Result<DSCAPS> {
let mut result__: <DSCAPS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSCAPS>(result__)
}
pub unsafe fn DuplicateSoundBuffer<'a, Param0: ::windows::core::IntoParam<'a, IDirectSoundBuffer>>(&self, pdsbufferoriginal: Param0) -> ::windows::core::Result<IDirectSoundBuffer> {
let mut result__: <IDirectSoundBuffer as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pdsbufferoriginal.into_param().abi(), &mut result__).from_abi::<IDirectSoundBuffer>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetCooperativeLevel<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>>(&self, hwnd: Param0, dwlevel: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), hwnd.into_param().abi(), ::core::mem::transmute(dwlevel)).ok()
}
pub unsafe fn Compact(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn GetSpeakerConfig(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn SetSpeakerConfig(&self, dwspeakerconfig: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwspeakerconfig)).ok()
}
pub unsafe fn Initialize(&self, pcguiddevice: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcguiddevice)).ok()
}
pub unsafe fn VerifyCertification(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSound8 {
type Vtable = IDirectSound8_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc50a7e93_f395_4834_9ef6_7fa99de50966);
}
impl ::core::convert::From<IDirectSound8> for ::windows::core::IUnknown {
fn from(value: IDirectSound8) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSound8> for ::windows::core::IUnknown {
fn from(value: &IDirectSound8) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSound8 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSound8 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IDirectSound8> for IDirectSound {
fn from(value: IDirectSound8) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IDirectSound8> for IDirectSound {
fn from(value: &IDirectSound8) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IDirectSound> for IDirectSound8 {
fn into_param(self) -> ::windows::core::Param<'a, IDirectSound> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IDirectSound> for &IDirectSound8 {
fn into_param(self) -> ::windows::core::Param<'a, IDirectSound> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSound8_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsbufferdesc: *const DSBUFFERDESC, ppdsbuffer: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdscaps: *mut DSCAPS) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsbufferoriginal: ::windows::core::RawPtr, ppdsbufferduplicate: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hwnd: super::super::super::Foundation::HWND, dwlevel: u32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwspeakerconfig: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwspeakerconfig: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcguiddevice: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcertified: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundBuffer(pub ::windows::core::IUnknown);
impl IDirectSoundBuffer {
pub unsafe fn GetCaps(&self) -> ::windows::core::Result<DSBCAPS> {
let mut result__: <DSBCAPS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSBCAPS>(result__)
}
pub unsafe fn GetCurrentPosition(&self, pdwcurrentplaycursor: *mut u32, pdwcurrentwritecursor: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwcurrentplaycursor), ::core::mem::transmute(pdwcurrentwritecursor)).ok()
}
pub unsafe fn GetFormat(&self, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwfxformat), ::core::mem::transmute(dwsizeallocated), ::core::mem::transmute(pdwsizewritten)).ok()
}
pub unsafe fn GetVolume(&self) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
pub unsafe fn GetPan(&self) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
pub unsafe fn GetFrequency(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetStatus(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, IDirectSound>>(&self, pdirectsound: Param0, pcdsbufferdesc: *const DSBUFFERDESC) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), pdirectsound.into_param().abi(), ::core::mem::transmute(pcdsbufferdesc)).ok()
}
pub unsafe fn Lock(&self, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwoffset), ::core::mem::transmute(dwbytes), ::core::mem::transmute(ppvaudioptr1), ::core::mem::transmute(pdwaudiobytes1), ::core::mem::transmute(ppvaudioptr2), ::core::mem::transmute(pdwaudiobytes2), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn Play(&self, dwreserved1: u32, dwpriority: u32, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwreserved1), ::core::mem::transmute(dwpriority), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn SetCurrentPosition(&self, dwnewposition: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwnewposition)).ok()
}
pub unsafe fn SetFormat(&self, pcfxformat: *const super::WAVEFORMATEX) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcfxformat)).ok()
}
pub unsafe fn SetVolume(&self, lvolume: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(lvolume)).ok()
}
pub unsafe fn SetPan(&self, lpan: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpan)).ok()
}
pub unsafe fn SetFrequency(&self, dwfrequency: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwfrequency)).ok()
}
pub unsafe fn Stop(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Unlock(&self, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvaudioptr1), ::core::mem::transmute(dwaudiobytes1), ::core::mem::transmute(pvaudioptr2), ::core::mem::transmute(dwaudiobytes2)).ok()
}
pub unsafe fn Restore(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundBuffer {
type Vtable = IDirectSoundBuffer_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x279afa85_4981_11ce_a521_0020af0be560);
}
impl ::core::convert::From<IDirectSoundBuffer> for ::windows::core::IUnknown {
fn from(value: IDirectSoundBuffer) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundBuffer> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundBuffer) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundBuffer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundBuffer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundBuffer_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsbuffercaps: *mut DSBCAPS) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcurrentplaycursor: *mut u32, pdwcurrentwritecursor: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plvolume: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plpan: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwfrequency: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwstatus: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdirectsound: ::windows::core::RawPtr, pcdsbufferdesc: *const DSBUFFERDESC) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwreserved1: u32, dwpriority: u32, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwnewposition: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcfxformat: *const super::WAVEFORMATEX) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lvolume: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpan: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwfrequency: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundBuffer8(pub ::windows::core::IUnknown);
impl IDirectSoundBuffer8 {
pub unsafe fn GetCaps(&self) -> ::windows::core::Result<DSBCAPS> {
let mut result__: <DSBCAPS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSBCAPS>(result__)
}
pub unsafe fn GetCurrentPosition(&self, pdwcurrentplaycursor: *mut u32, pdwcurrentwritecursor: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwcurrentplaycursor), ::core::mem::transmute(pdwcurrentwritecursor)).ok()
}
pub unsafe fn GetFormat(&self, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwfxformat), ::core::mem::transmute(dwsizeallocated), ::core::mem::transmute(pdwsizewritten)).ok()
}
pub unsafe fn GetVolume(&self) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
pub unsafe fn GetPan(&self) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
pub unsafe fn GetFrequency(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetStatus(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, IDirectSound>>(&self, pdirectsound: Param0, pcdsbufferdesc: *const DSBUFFERDESC) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), pdirectsound.into_param().abi(), ::core::mem::transmute(pcdsbufferdesc)).ok()
}
pub unsafe fn Lock(&self, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwoffset), ::core::mem::transmute(dwbytes), ::core::mem::transmute(ppvaudioptr1), ::core::mem::transmute(pdwaudiobytes1), ::core::mem::transmute(ppvaudioptr2), ::core::mem::transmute(pdwaudiobytes2), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn Play(&self, dwreserved1: u32, dwpriority: u32, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwreserved1), ::core::mem::transmute(dwpriority), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn SetCurrentPosition(&self, dwnewposition: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwnewposition)).ok()
}
pub unsafe fn SetFormat(&self, pcfxformat: *const super::WAVEFORMATEX) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcfxformat)).ok()
}
pub unsafe fn SetVolume(&self, lvolume: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(lvolume)).ok()
}
pub unsafe fn SetPan(&self, lpan: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpan)).ok()
}
pub unsafe fn SetFrequency(&self, dwfrequency: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwfrequency)).ok()
}
pub unsafe fn Stop(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Unlock(&self, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvaudioptr1), ::core::mem::transmute(dwaudiobytes1), ::core::mem::transmute(pvaudioptr2), ::core::mem::transmute(dwaudiobytes2)).ok()
}
pub unsafe fn Restore(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn SetFX(&self, dweffectscount: u32, pdsfxdesc: *const DSEFFECTDESC, pdwresultcodes: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(dweffectscount), ::core::mem::transmute(pdsfxdesc), ::core::mem::transmute(pdwresultcodes)).ok()
}
pub unsafe fn AcquireResources(&self, dwflags: u32, dweffectscount: u32, pdwresultcodes: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwflags), ::core::mem::transmute(dweffectscount), ::core::mem::transmute(pdwresultcodes)).ok()
}
pub unsafe fn GetObjectInPath(&self, rguidobject: *const ::windows::core::GUID, dwindex: u32, rguidinterface: *const ::windows::core::GUID, ppobject: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(rguidobject), ::core::mem::transmute(dwindex), ::core::mem::transmute(rguidinterface), ::core::mem::transmute(ppobject)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundBuffer8 {
type Vtable = IDirectSoundBuffer8_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6825a449_7524_4d82_920f_50e36ab3ab1e);
}
impl ::core::convert::From<IDirectSoundBuffer8> for ::windows::core::IUnknown {
fn from(value: IDirectSoundBuffer8) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundBuffer8> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundBuffer8) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IDirectSoundBuffer8> for IDirectSoundBuffer {
fn from(value: IDirectSoundBuffer8) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IDirectSoundBuffer8> for IDirectSoundBuffer {
fn from(value: &IDirectSoundBuffer8) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IDirectSoundBuffer> for IDirectSoundBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, IDirectSoundBuffer> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IDirectSoundBuffer> for &IDirectSoundBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, IDirectSoundBuffer> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundBuffer8_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsbuffercaps: *mut DSBCAPS) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcurrentplaycursor: *mut u32, pdwcurrentwritecursor: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plvolume: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plpan: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwfrequency: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwstatus: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdirectsound: ::windows::core::RawPtr, pcdsbufferdesc: *const DSBUFFERDESC) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwreserved1: u32, dwpriority: u32, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwnewposition: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcfxformat: *const super::WAVEFORMATEX) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lvolume: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpan: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwfrequency: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dweffectscount: u32, pdsfxdesc: *const DSEFFECTDESC, pdwresultcodes: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwflags: u32, dweffectscount: u32, pdwresultcodes: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rguidobject: *const ::windows::core::GUID, dwindex: u32, rguidinterface: *const ::windows::core::GUID, ppobject: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundCapture(pub ::windows::core::IUnknown);
impl IDirectSoundCapture {
pub unsafe fn CreateCaptureBuffer<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, pcdscbufferdesc: *const DSCBUFFERDESC, ppdscbuffer: *mut ::core::option::Option<IDirectSoundCaptureBuffer>, punkouter: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdscbufferdesc), ::core::mem::transmute(ppdscbuffer), punkouter.into_param().abi()).ok()
}
pub unsafe fn GetCaps(&self) -> ::windows::core::Result<DSCCAPS> {
let mut result__: <DSCCAPS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSCCAPS>(result__)
}
pub unsafe fn Initialize(&self, pcguiddevice: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcguiddevice)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundCapture {
type Vtable = IDirectSoundCapture_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0210781_89cd_11d0_af08_00a0c925cd16);
}
impl ::core::convert::From<IDirectSoundCapture> for ::windows::core::IUnknown {
fn from(value: IDirectSoundCapture) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundCapture> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundCapture) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundCapture {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundCapture {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundCapture_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdscbufferdesc: *const DSCBUFFERDESC, ppdscbuffer: *mut ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsccaps: *mut DSCCAPS) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcguiddevice: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundCaptureBuffer(pub ::windows::core::IUnknown);
impl IDirectSoundCaptureBuffer {
pub unsafe fn GetCaps(&self) -> ::windows::core::Result<DSCBCAPS> {
let mut result__: <DSCBCAPS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSCBCAPS>(result__)
}
pub unsafe fn GetCurrentPosition(&self, pdwcaptureposition: *mut u32, pdwreadposition: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwcaptureposition), ::core::mem::transmute(pdwreadposition)).ok()
}
pub unsafe fn GetFormat(&self, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwfxformat), ::core::mem::transmute(dwsizeallocated), ::core::mem::transmute(pdwsizewritten)).ok()
}
pub unsafe fn GetStatus(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, IDirectSoundCapture>>(&self, pdirectsoundcapture: Param0, pcdscbufferdesc: *const DSCBUFFERDESC) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), pdirectsoundcapture.into_param().abi(), ::core::mem::transmute(pcdscbufferdesc)).ok()
}
pub unsafe fn Lock(&self, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwoffset), ::core::mem::transmute(dwbytes), ::core::mem::transmute(ppvaudioptr1), ::core::mem::transmute(pdwaudiobytes1), ::core::mem::transmute(ppvaudioptr2), ::core::mem::transmute(pdwaudiobytes2), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn Start(&self, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn Stop(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Unlock(&self, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvaudioptr1), ::core::mem::transmute(dwaudiobytes1), ::core::mem::transmute(pvaudioptr2), ::core::mem::transmute(dwaudiobytes2)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundCaptureBuffer {
type Vtable = IDirectSoundCaptureBuffer_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0210782_89cd_11d0_af08_00a0c925cd16);
}
impl ::core::convert::From<IDirectSoundCaptureBuffer> for ::windows::core::IUnknown {
fn from(value: IDirectSoundCaptureBuffer) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundCaptureBuffer> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundCaptureBuffer) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundCaptureBuffer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundCaptureBuffer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundCaptureBuffer_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdscbcaps: *mut DSCBCAPS) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcaptureposition: *mut u32, pdwreadposition: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwstatus: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdirectsoundcapture: ::windows::core::RawPtr, pcdscbufferdesc: *const DSCBUFFERDESC) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundCaptureBuffer8(pub ::windows::core::IUnknown);
impl IDirectSoundCaptureBuffer8 {
pub unsafe fn GetCaps(&self) -> ::windows::core::Result<DSCBCAPS> {
let mut result__: <DSCBCAPS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSCBCAPS>(result__)
}
pub unsafe fn GetCurrentPosition(&self, pdwcaptureposition: *mut u32, pdwreadposition: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwcaptureposition), ::core::mem::transmute(pdwreadposition)).ok()
}
pub unsafe fn GetFormat(&self, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwfxformat), ::core::mem::transmute(dwsizeallocated), ::core::mem::transmute(pdwsizewritten)).ok()
}
pub unsafe fn GetStatus(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, IDirectSoundCapture>>(&self, pdirectsoundcapture: Param0, pcdscbufferdesc: *const DSCBUFFERDESC) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), pdirectsoundcapture.into_param().abi(), ::core::mem::transmute(pcdscbufferdesc)).ok()
}
pub unsafe fn Lock(&self, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwoffset), ::core::mem::transmute(dwbytes), ::core::mem::transmute(ppvaudioptr1), ::core::mem::transmute(pdwaudiobytes1), ::core::mem::transmute(ppvaudioptr2), ::core::mem::transmute(pdwaudiobytes2), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn Start(&self, dwflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwflags)).ok()
}
pub unsafe fn Stop(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Unlock(&self, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvaudioptr1), ::core::mem::transmute(dwaudiobytes1), ::core::mem::transmute(pvaudioptr2), ::core::mem::transmute(dwaudiobytes2)).ok()
}
pub unsafe fn GetObjectInPath(&self, rguidobject: *const ::windows::core::GUID, dwindex: u32, rguidinterface: *const ::windows::core::GUID, ppobject: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(rguidobject), ::core::mem::transmute(dwindex), ::core::mem::transmute(rguidinterface), ::core::mem::transmute(ppobject)).ok()
}
pub unsafe fn GetFXStatus(&self, dweffectscount: u32, pdwfxstatus: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(dweffectscount), ::core::mem::transmute(pdwfxstatus)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundCaptureBuffer8 {
type Vtable = IDirectSoundCaptureBuffer8_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00990df4_0dbb_4872_833e_6d303e80aeb6);
}
impl ::core::convert::From<IDirectSoundCaptureBuffer8> for ::windows::core::IUnknown {
fn from(value: IDirectSoundCaptureBuffer8) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundCaptureBuffer8> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundCaptureBuffer8) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundCaptureBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundCaptureBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IDirectSoundCaptureBuffer8> for IDirectSoundCaptureBuffer {
fn from(value: IDirectSoundCaptureBuffer8) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IDirectSoundCaptureBuffer8> for IDirectSoundCaptureBuffer {
fn from(value: &IDirectSoundCaptureBuffer8) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IDirectSoundCaptureBuffer> for IDirectSoundCaptureBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, IDirectSoundCaptureBuffer> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IDirectSoundCaptureBuffer> for &IDirectSoundCaptureBuffer8 {
fn into_param(self) -> ::windows::core::Param<'a, IDirectSoundCaptureBuffer> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundCaptureBuffer8_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdscbcaps: *mut DSCBCAPS) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcaptureposition: *mut u32, pdwreadposition: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwfxformat: *mut super::WAVEFORMATEX, dwsizeallocated: u32, pdwsizewritten: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwstatus: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdirectsoundcapture: ::windows::core::RawPtr, pcdscbufferdesc: *const DSCBUFFERDESC) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwoffset: u32, dwbytes: u32, ppvaudioptr1: *mut *mut ::core::ffi::c_void, pdwaudiobytes1: *mut u32, ppvaudioptr2: *mut *mut ::core::ffi::c_void, pdwaudiobytes2: *mut u32, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwflags: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvaudioptr1: *const ::core::ffi::c_void, dwaudiobytes1: u32, pvaudioptr2: *const ::core::ffi::c_void, dwaudiobytes2: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rguidobject: *const ::windows::core::GUID, dwindex: u32, rguidinterface: *const ::windows::core::GUID, ppobject: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dweffectscount: u32, pdwfxstatus: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundCaptureFXAec(pub ::windows::core::IUnknown);
impl IDirectSoundCaptureFXAec {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetAllParameters(&self, pdscfxaec: *const DSCFXAec) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdscfxaec)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSCFXAec> {
let mut result__: <DSCFXAec as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSCFXAec>(result__)
}
pub unsafe fn GetStatus(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn Reset(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundCaptureFXAec {
type Vtable = IDirectSoundCaptureFXAec_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xad74143d_903d_4ab7_8066_28d363036d65);
}
impl ::core::convert::From<IDirectSoundCaptureFXAec> for ::windows::core::IUnknown {
fn from(value: IDirectSoundCaptureFXAec) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundCaptureFXAec> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundCaptureFXAec) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundCaptureFXAec {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundCaptureFXAec {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundCaptureFXAec_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdscfxaec: *const DSCFXAec) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdscfxaec: *mut DSCFXAec) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwstatus: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundCaptureFXNoiseSuppress(pub ::windows::core::IUnknown);
impl IDirectSoundCaptureFXNoiseSuppress {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetAllParameters(&self, pcdscfxnoisesuppress: *const DSCFXNoiseSuppress) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdscfxnoisesuppress)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSCFXNoiseSuppress> {
let mut result__: <DSCFXNoiseSuppress as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSCFXNoiseSuppress>(result__)
}
pub unsafe fn Reset(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundCaptureFXNoiseSuppress {
type Vtable = IDirectSoundCaptureFXNoiseSuppress_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed311e41_fbae_4175_9625_cd0854f693ca);
}
impl ::core::convert::From<IDirectSoundCaptureFXNoiseSuppress> for ::windows::core::IUnknown {
fn from(value: IDirectSoundCaptureFXNoiseSuppress) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundCaptureFXNoiseSuppress> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundCaptureFXNoiseSuppress) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundCaptureFXNoiseSuppress {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundCaptureFXNoiseSuppress {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundCaptureFXNoiseSuppress_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdscfxnoisesuppress: *const DSCFXNoiseSuppress) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdscfxnoisesuppress: *mut DSCFXNoiseSuppress) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXChorus(pub ::windows::core::IUnknown);
impl IDirectSoundFXChorus {
pub unsafe fn SetAllParameters(&self, pcdsfxchorus: *const DSFXChorus) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxchorus)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXChorus> {
let mut result__: <DSFXChorus as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXChorus>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXChorus {
type Vtable = IDirectSoundFXChorus_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x880842e3_145f_43e6_a934_a71806e50547);
}
impl ::core::convert::From<IDirectSoundFXChorus> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXChorus) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXChorus> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXChorus) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXChorus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXChorus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXChorus_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxchorus: *const DSFXChorus) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxchorus: *mut DSFXChorus) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXCompressor(pub ::windows::core::IUnknown);
impl IDirectSoundFXCompressor {
pub unsafe fn SetAllParameters(&self, pcdsfxcompressor: *const DSFXCompressor) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxcompressor)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXCompressor> {
let mut result__: <DSFXCompressor as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXCompressor>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXCompressor {
type Vtable = IDirectSoundFXCompressor_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4bbd1154_62f6_4e2c_a15c_d3b6c417f7a0);
}
impl ::core::convert::From<IDirectSoundFXCompressor> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXCompressor) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXCompressor> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXCompressor) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXCompressor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXCompressor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXCompressor_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxcompressor: *const DSFXCompressor) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxcompressor: *mut DSFXCompressor) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXDistortion(pub ::windows::core::IUnknown);
impl IDirectSoundFXDistortion {
pub unsafe fn SetAllParameters(&self, pcdsfxdistortion: *const DSFXDistortion) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxdistortion)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXDistortion> {
let mut result__: <DSFXDistortion as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXDistortion>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXDistortion {
type Vtable = IDirectSoundFXDistortion_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8ecf4326_455f_4d8b_bda9_8d5d3e9e3e0b);
}
impl ::core::convert::From<IDirectSoundFXDistortion> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXDistortion) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXDistortion> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXDistortion) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXDistortion {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXDistortion {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXDistortion_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxdistortion: *const DSFXDistortion) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxdistortion: *mut DSFXDistortion) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXEcho(pub ::windows::core::IUnknown);
impl IDirectSoundFXEcho {
pub unsafe fn SetAllParameters(&self, pcdsfxecho: *const DSFXEcho) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxecho)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXEcho> {
let mut result__: <DSFXEcho as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXEcho>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXEcho {
type Vtable = IDirectSoundFXEcho_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8bd28edf_50db_4e92_a2bd_445488d1ed42);
}
impl ::core::convert::From<IDirectSoundFXEcho> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXEcho) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXEcho> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXEcho) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXEcho {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXEcho {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXEcho_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxecho: *const DSFXEcho) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxecho: *mut DSFXEcho) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXFlanger(pub ::windows::core::IUnknown);
impl IDirectSoundFXFlanger {
pub unsafe fn SetAllParameters(&self, pcdsfxflanger: *const DSFXFlanger) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxflanger)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXFlanger> {
let mut result__: <DSFXFlanger as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXFlanger>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXFlanger {
type Vtable = IDirectSoundFXFlanger_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x903e9878_2c92_4072_9b2c_ea68f5396783);
}
impl ::core::convert::From<IDirectSoundFXFlanger> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXFlanger) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXFlanger> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXFlanger) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXFlanger {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXFlanger {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXFlanger_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxflanger: *const DSFXFlanger) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxflanger: *mut DSFXFlanger) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXGargle(pub ::windows::core::IUnknown);
impl IDirectSoundFXGargle {
pub unsafe fn SetAllParameters(&self, pcdsfxgargle: *const DSFXGargle) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxgargle)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXGargle> {
let mut result__: <DSFXGargle as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXGargle>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXGargle {
type Vtable = IDirectSoundFXGargle_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd616f352_d622_11ce_aac5_0020af0b99a3);
}
impl ::core::convert::From<IDirectSoundFXGargle> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXGargle) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXGargle> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXGargle) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXGargle {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXGargle {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXGargle_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxgargle: *const DSFXGargle) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxgargle: *mut DSFXGargle) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXI3DL2Reverb(pub ::windows::core::IUnknown);
impl IDirectSoundFXI3DL2Reverb {
pub unsafe fn SetAllParameters(&self, pcdsfxi3dl2reverb: *const DSFXI3DL2Reverb) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxi3dl2reverb)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXI3DL2Reverb> {
let mut result__: <DSFXI3DL2Reverb as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXI3DL2Reverb>(result__)
}
pub unsafe fn SetPreset(&self, dwpreset: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwpreset)).ok()
}
pub unsafe fn GetPreset(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn SetQuality(&self, lquality: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(lquality)).ok()
}
pub unsafe fn GetQuality(&self) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXI3DL2Reverb {
type Vtable = IDirectSoundFXI3DL2Reverb_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4b166a6a_0d66_43f3_80e3_ee6280dee1a4);
}
impl ::core::convert::From<IDirectSoundFXI3DL2Reverb> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXI3DL2Reverb) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXI3DL2Reverb> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXI3DL2Reverb) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXI3DL2Reverb {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXI3DL2Reverb {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXI3DL2Reverb_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxi3dl2reverb: *const DSFXI3DL2Reverb) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxi3dl2reverb: *mut DSFXI3DL2Reverb) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwpreset: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwpreset: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lquality: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plquality: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXParamEq(pub ::windows::core::IUnknown);
impl IDirectSoundFXParamEq {
pub unsafe fn SetAllParameters(&self, pcdsfxparameq: *const DSFXParamEq) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxparameq)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXParamEq> {
let mut result__: <DSFXParamEq as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXParamEq>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXParamEq {
type Vtable = IDirectSoundFXParamEq_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc03ca9fe_fe90_4204_8078_82334cd177da);
}
impl ::core::convert::From<IDirectSoundFXParamEq> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXParamEq) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXParamEq> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXParamEq) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXParamEq {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXParamEq {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXParamEq_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxparameq: *const DSFXParamEq) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxparameq: *mut DSFXParamEq) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFXWavesReverb(pub ::windows::core::IUnknown);
impl IDirectSoundFXWavesReverb {
pub unsafe fn SetAllParameters(&self, pcdsfxwavesreverb: *const DSFXWavesReverb) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdsfxwavesreverb)).ok()
}
pub unsafe fn GetAllParameters(&self) -> ::windows::core::Result<DSFXWavesReverb> {
let mut result__: <DSFXWavesReverb as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<DSFXWavesReverb>(result__)
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFXWavesReverb {
type Vtable = IDirectSoundFXWavesReverb_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x46858c3a_0dc6_45e3_b760_d4eef16cb325);
}
impl ::core::convert::From<IDirectSoundFXWavesReverb> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFXWavesReverb) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFXWavesReverb> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFXWavesReverb) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFXWavesReverb {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFXWavesReverb {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFXWavesReverb_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdsfxwavesreverb: *const DSFXWavesReverb) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdsfxwavesreverb: *mut DSFXWavesReverb) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundFullDuplex(pub ::windows::core::IUnknown);
impl IDirectSoundFullDuplex {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Initialize<'a, Param4: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>>(
&self,
pcaptureguid: *const ::windows::core::GUID,
prenderguid: *const ::windows::core::GUID,
lpdscbufferdesc: *const DSCBUFFERDESC,
lpdsbufferdesc: *const DSBUFFERDESC,
hwnd: Param4,
dwlevel: u32,
lplpdirectsoundcapturebuffer8: *mut ::core::option::Option<IDirectSoundCaptureBuffer8>,
lplpdirectsoundbuffer8: *mut ::core::option::Option<IDirectSoundBuffer8>,
) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(
::core::mem::transmute_copy(self),
::core::mem::transmute(pcaptureguid),
::core::mem::transmute(prenderguid),
::core::mem::transmute(lpdscbufferdesc),
::core::mem::transmute(lpdsbufferdesc),
hwnd.into_param().abi(),
::core::mem::transmute(dwlevel),
::core::mem::transmute(lplpdirectsoundcapturebuffer8),
::core::mem::transmute(lplpdirectsoundbuffer8),
)
.ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundFullDuplex {
type Vtable = IDirectSoundFullDuplex_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xedcb4c7a_daab_4216_a42e_6c50596ddc1d);
}
impl ::core::convert::From<IDirectSoundFullDuplex> for ::windows::core::IUnknown {
fn from(value: IDirectSoundFullDuplex) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundFullDuplex> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundFullDuplex) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundFullDuplex {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundFullDuplex {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundFullDuplex_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcaptureguid: *const ::windows::core::GUID, prenderguid: *const ::windows::core::GUID, lpdscbufferdesc: *const DSCBUFFERDESC, lpdsbufferdesc: *const DSBUFFERDESC, hwnd: super::super::super::Foundation::HWND, dwlevel: u32, lplpdirectsoundcapturebuffer8: *mut ::windows::core::RawPtr, lplpdirectsoundbuffer8: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDirectSoundNotify(pub ::windows::core::IUnknown);
impl IDirectSoundNotify {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetNotificationPositions(&self, dwpositionnotifies: u32, pcpositionnotifies: *const DSBPOSITIONNOTIFY) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwpositionnotifies), ::core::mem::transmute(pcpositionnotifies)).ok()
}
}
unsafe impl ::windows::core::Interface for IDirectSoundNotify {
type Vtable = IDirectSoundNotify_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0210783_89cd_11d0_af08_00a0c925cd16);
}
impl ::core::convert::From<IDirectSoundNotify> for ::windows::core::IUnknown {
fn from(value: IDirectSoundNotify) -> Self {
value.0
}
}
impl ::core::convert::From<&IDirectSoundNotify> for ::windows::core::IUnknown {
fn from(value: &IDirectSoundNotify) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDirectSoundNotify {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDirectSoundNotify {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDirectSoundNotify_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwpositionnotifies: u32, pcpositionnotifies: *const DSBPOSITIONNOTIFY) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
pub const KSPROPERTY_SUPPORT_GET: u32 = 1u32;
pub const KSPROPERTY_SUPPORT_SET: u32 = 2u32;
#[cfg(feature = "Win32_Foundation")]
pub type LPDSENUMCALLBACKA = unsafe extern "system" fn(param0: *mut ::windows::core::GUID, param1: super::super::super::Foundation::PSTR, param2: super::super::super::Foundation::PSTR, param3: *mut ::core::ffi::c_void) -> super::super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub type LPDSENUMCALLBACKW = unsafe extern "system" fn(param0: *mut ::windows::core::GUID, param1: super::super::super::Foundation::PWSTR, param2: super::super::super::Foundation::PWSTR, param3: *mut ::core::ffi::c_void) -> super::super::super::Foundation::BOOL;
pub const _FACDS: u32 = 2168u32;
|
mod file;
mod flags;
pub use self::file::{Async, File, IntoAsync};
pub use self::flags::{AccessMode, CreationFlags, StatusFlags};
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qapplication.h
// dst-file: /src/widgets/qapplication.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::gui::qguiapplication::*; // 771
use std::ops::Deref;
use super::super::core::qstring::*; // 771
use super::super::gui::qpalette::*; // 771
use super::qwidget::*; // 773
use super::super::gui::qfontmetrics::*; // 771
use super::super::gui::qfont::*; // 771
use super::qstyle::*; // 773
use super::super::core::qpoint::*; // 771
use super::super::core::qobjectdefs::*; // 771
use super::qdesktopwidget::*; // 773
use super::super::core::qsize::*; // 771
// use super::qlist::*; // 775
use super::super::gui::qicon::*; // 771
use super::super::core::qobject::*; // 771
use super::super::core::qcoreevent::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QApplication_Class_Size() -> c_int;
// proto: QString QApplication::styleSheet();
fn C_ZNK12QApplication10styleSheetEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static QPalette QApplication::palette(const char * className);
fn C_ZN12QApplication7paletteEPKc(arg0: *mut c_char) -> *mut c_void;
// proto: static QWidget * QApplication::activeWindow();
fn C_ZN12QApplication12activeWindowEv() -> *mut c_void;
// proto: static void QApplication::setKeyboardInputInterval(int );
fn C_ZN12QApplication24setKeyboardInputIntervalEi(arg0: c_int);
// proto: static QWidget * QApplication::focusWidget();
fn C_ZN12QApplication11focusWidgetEv() -> *mut c_void;
// proto: static QFontMetrics QApplication::fontMetrics();
fn C_ZN12QApplication11fontMetricsEv() -> *mut c_void;
// proto: static QFont QApplication::font(const char * className);
fn C_ZN12QApplication4fontEPKc(arg0: *mut c_char) -> *mut c_void;
// proto: static QStyle * QApplication::style();
fn C_ZN12QApplication5styleEv() -> *mut c_void;
// proto: static QWidget * QApplication::widgetAt(const QPoint & p);
fn C_ZN12QApplication8widgetAtERK6QPoint(arg0: *mut c_void) -> *mut c_void;
// proto: static void QApplication::setActiveWindow(QWidget * act);
fn C_ZN12QApplication15setActiveWindowEP7QWidget(arg0: *mut c_void);
// proto: static QFont QApplication::font();
fn C_ZN12QApplication4fontEv() -> *mut c_void;
// proto: static void QApplication::setWheelScrollLines(int );
fn C_ZN12QApplication19setWheelScrollLinesEi(arg0: c_int);
// proto: void QApplication::setStyleSheet(const QString & sheet);
fn C_ZN12QApplication13setStyleSheetERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QApplication::setAutoSipEnabled(const bool enabled);
fn C_ZN12QApplication17setAutoSipEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: const QMetaObject * QApplication::metaObject();
fn C_ZNK12QApplication10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static int QApplication::keyboardInputInterval();
fn C_ZN12QApplication21keyboardInputIntervalEv() -> c_int;
// proto: static int QApplication::cursorFlashTime();
fn C_ZN12QApplication15cursorFlashTimeEv() -> c_int;
// proto: static int QApplication::startDragDistance();
fn C_ZN12QApplication17startDragDistanceEv() -> c_int;
// proto: static QDesktopWidget * QApplication::desktop();
fn C_ZN12QApplication7desktopEv() -> *mut c_void;
// proto: static void QApplication::setStartDragDistance(int l);
fn C_ZN12QApplication20setStartDragDistanceEi(arg0: c_int);
// proto: static QFont QApplication::font(const QWidget * );
fn C_ZN12QApplication4fontEPK7QWidget(arg0: *mut c_void) -> *mut c_void;
// proto: static int QApplication::colorSpec();
fn C_ZN12QApplication9colorSpecEv() -> c_int;
// proto: static void QApplication::setFont(const QFont & , const char * className);
fn C_ZN12QApplication7setFontERK5QFontPKc(arg0: *mut c_void, arg1: *mut c_char);
// proto: static void QApplication::closeAllWindows();
fn C_ZN12QApplication15closeAllWindowsEv();
// proto: static void QApplication::setCursorFlashTime(int );
fn C_ZN12QApplication18setCursorFlashTimeEi(arg0: c_int);
// proto: static QWidget * QApplication::widgetAt(int x, int y);
fn C_ZN12QApplication8widgetAtEii(arg0: c_int, arg1: c_int) -> *mut c_void;
// proto: static void QApplication::alert(QWidget * widget, int duration);
fn C_ZN12QApplication5alertEP7QWidgeti(arg0: *mut c_void, arg1: c_int);
// proto: static QPalette QApplication::palette(const QWidget * );
fn C_ZN12QApplication7paletteEPK7QWidget(arg0: *mut c_void) -> *mut c_void;
// proto: static int QApplication::wheelScrollLines();
fn C_ZN12QApplication16wheelScrollLinesEv() -> c_int;
// proto: static void QApplication::aboutQt();
fn C_ZN12QApplication7aboutQtEv();
// proto: static QWidget * QApplication::activeModalWidget();
fn C_ZN12QApplication17activeModalWidgetEv() -> *mut c_void;
// proto: static QWidget * QApplication::activePopupWidget();
fn C_ZN12QApplication17activePopupWidgetEv() -> *mut c_void;
// proto: void QApplication::QApplication(int & argc, char ** argv, int );
fn C_ZN12QApplicationC2ERiPPci(arg0: *mut c_int, arg1: *mut c_char, arg2: c_int) -> u64;
// proto: static void QApplication::setStartDragTime(int ms);
fn C_ZN12QApplication16setStartDragTimeEi(arg0: c_int);
// proto: static QWidget * QApplication::topLevelAt(int x, int y);
fn C_ZN12QApplication10topLevelAtEii(arg0: c_int, arg1: c_int) -> *mut c_void;
// proto: static void QApplication::setStyle(QStyle * );
fn C_ZN12QApplication8setStyleEP6QStyle(arg0: *mut c_void);
// proto: void QApplication::~QApplication();
fn C_ZN12QApplicationD2Ev(qthis: u64 /* *mut c_void*/);
// proto: static void QApplication::setDoubleClickInterval(int );
fn C_ZN12QApplication22setDoubleClickIntervalEi(arg0: c_int);
// proto: static void QApplication::setGlobalStrut(const QSize & );
fn C_ZN12QApplication14setGlobalStrutERK5QSize(arg0: *mut c_void);
// proto: static void QApplication::setColorSpec(int );
fn C_ZN12QApplication12setColorSpecEi(arg0: c_int);
// proto: static QWidgetList QApplication::allWidgets();
fn C_ZN12QApplication10allWidgetsEv() -> *mut c_void;
// proto: static QSize QApplication::globalStrut();
fn C_ZN12QApplication11globalStrutEv() -> *mut c_void;
// proto: static void QApplication::setPalette(const QPalette & , const char * className);
fn C_ZN12QApplication10setPaletteERK8QPalettePKc(arg0: *mut c_void, arg1: *mut c_char);
// proto: static QStyle * QApplication::setStyle(const QString & );
fn C_ZN12QApplication8setStyleERK7QString(arg0: *mut c_void) -> *mut c_void;
// proto: static QWidgetList QApplication::topLevelWidgets();
fn C_ZN12QApplication15topLevelWidgetsEv() -> *mut c_void;
// proto: static int QApplication::exec();
fn C_ZN12QApplication4execEv() -> c_int;
// proto: static void QApplication::setWindowIcon(const QIcon & icon);
fn C_ZN12QApplication13setWindowIconERK5QIcon(arg0: *mut c_void);
// proto: static void QApplication::beep();
fn C_ZN12QApplication4beepEv();
// proto: bool QApplication::notify(QObject * , QEvent * );
fn C_ZN12QApplication6notifyEP7QObjectP6QEvent(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: bool QApplication::autoSipEnabled();
fn C_ZNK12QApplication14autoSipEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: static QWidget * QApplication::topLevelAt(const QPoint & p);
fn C_ZN12QApplication10topLevelAtERK6QPoint(arg0: *mut c_void) -> *mut c_void;
// proto: static int QApplication::startDragTime();
fn C_ZN12QApplication13startDragTimeEv() -> c_int;
// proto: static int QApplication::doubleClickInterval();
fn C_ZN12QApplication19doubleClickIntervalEv() -> c_int;
// proto: static QIcon QApplication::windowIcon();
fn C_ZN12QApplication10windowIconEv() -> *mut c_void;
fn QApplication_SlotProxy_connect__ZN12QApplication12focusChangedEP7QWidgetS1_(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QApplication)=1
#[derive(Default)]
pub struct QApplication {
qbase: QGuiApplication,
pub qclsinst: u64 /* *mut c_void*/,
pub _focusChanged: QApplication_focusChanged_signal,
}
impl /*struct*/ QApplication {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QApplication {
return QApplication{qbase: QGuiApplication::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QApplication {
type Target = QGuiApplication;
fn deref(&self) -> &QGuiApplication {
return & self.qbase;
}
}
impl AsRef<QGuiApplication> for QApplication {
fn as_ref(& self) -> & QGuiApplication {
return & self.qbase;
}
}
// proto: QString QApplication::styleSheet();
impl /*struct*/ QApplication {
pub fn styleSheet<RetType, T: QApplication_styleSheet<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.styleSheet(self);
// return 1;
}
}
pub trait QApplication_styleSheet<RetType> {
fn styleSheet(self , rsthis: & QApplication) -> RetType;
}
// proto: QString QApplication::styleSheet();
impl<'a> /*trait*/ QApplication_styleSheet<QString> for () {
fn styleSheet(self , rsthis: & QApplication) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QApplication10styleSheetEv()};
let mut ret = unsafe {C_ZNK12QApplication10styleSheetEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QPalette QApplication::palette(const char * className);
impl /*struct*/ QApplication {
pub fn palette_s<RetType, T: QApplication_palette_s<RetType>>( overload_args: T) -> RetType {
return overload_args.palette_s();
// return 1;
}
}
pub trait QApplication_palette_s<RetType> {
fn palette_s(self ) -> RetType;
}
// proto: static QPalette QApplication::palette(const char * className);
impl<'a> /*trait*/ QApplication_palette_s<QPalette> for (&'a String) {
fn palette_s(self ) -> QPalette {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication7paletteEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZN12QApplication7paletteEPKc(arg0)};
let mut ret1 = QPalette::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QWidget * QApplication::activeWindow();
impl /*struct*/ QApplication {
pub fn activeWindow_s<RetType, T: QApplication_activeWindow_s<RetType>>( overload_args: T) -> RetType {
return overload_args.activeWindow_s();
// return 1;
}
}
pub trait QApplication_activeWindow_s<RetType> {
fn activeWindow_s(self ) -> RetType;
}
// proto: static QWidget * QApplication::activeWindow();
impl<'a> /*trait*/ QApplication_activeWindow_s<QWidget> for () {
fn activeWindow_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication12activeWindowEv()};
let mut ret = unsafe {C_ZN12QApplication12activeWindowEv()};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QApplication::setKeyboardInputInterval(int );
impl /*struct*/ QApplication {
pub fn setKeyboardInputInterval_s<RetType, T: QApplication_setKeyboardInputInterval_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setKeyboardInputInterval_s();
// return 1;
}
}
pub trait QApplication_setKeyboardInputInterval_s<RetType> {
fn setKeyboardInputInterval_s(self ) -> RetType;
}
// proto: static void QApplication::setKeyboardInputInterval(int );
impl<'a> /*trait*/ QApplication_setKeyboardInputInterval_s<()> for (i32) {
fn setKeyboardInputInterval_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication24setKeyboardInputIntervalEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QApplication24setKeyboardInputIntervalEi(arg0)};
// return 1;
}
}
// proto: static QWidget * QApplication::focusWidget();
impl /*struct*/ QApplication {
pub fn focusWidget_s<RetType, T: QApplication_focusWidget_s<RetType>>( overload_args: T) -> RetType {
return overload_args.focusWidget_s();
// return 1;
}
}
pub trait QApplication_focusWidget_s<RetType> {
fn focusWidget_s(self ) -> RetType;
}
// proto: static QWidget * QApplication::focusWidget();
impl<'a> /*trait*/ QApplication_focusWidget_s<QWidget> for () {
fn focusWidget_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication11focusWidgetEv()};
let mut ret = unsafe {C_ZN12QApplication11focusWidgetEv()};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QFontMetrics QApplication::fontMetrics();
impl /*struct*/ QApplication {
pub fn fontMetrics_s<RetType, T: QApplication_fontMetrics_s<RetType>>( overload_args: T) -> RetType {
return overload_args.fontMetrics_s();
// return 1;
}
}
pub trait QApplication_fontMetrics_s<RetType> {
fn fontMetrics_s(self ) -> RetType;
}
// proto: static QFontMetrics QApplication::fontMetrics();
impl<'a> /*trait*/ QApplication_fontMetrics_s<QFontMetrics> for () {
fn fontMetrics_s(self ) -> QFontMetrics {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication11fontMetricsEv()};
let mut ret = unsafe {C_ZN12QApplication11fontMetricsEv()};
let mut ret1 = QFontMetrics::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QFont QApplication::font(const char * className);
impl /*struct*/ QApplication {
pub fn font_s<RetType, T: QApplication_font_s<RetType>>( overload_args: T) -> RetType {
return overload_args.font_s();
// return 1;
}
}
pub trait QApplication_font_s<RetType> {
fn font_s(self ) -> RetType;
}
// proto: static QFont QApplication::font(const char * className);
impl<'a> /*trait*/ QApplication_font_s<QFont> for (&'a String) {
fn font_s(self ) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication4fontEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZN12QApplication4fontEPKc(arg0)};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QStyle * QApplication::style();
impl /*struct*/ QApplication {
pub fn style_s<RetType, T: QApplication_style_s<RetType>>( overload_args: T) -> RetType {
return overload_args.style_s();
// return 1;
}
}
pub trait QApplication_style_s<RetType> {
fn style_s(self ) -> RetType;
}
// proto: static QStyle * QApplication::style();
impl<'a> /*trait*/ QApplication_style_s<QStyle> for () {
fn style_s(self ) -> QStyle {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication5styleEv()};
let mut ret = unsafe {C_ZN12QApplication5styleEv()};
let mut ret1 = QStyle::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QWidget * QApplication::widgetAt(const QPoint & p);
impl /*struct*/ QApplication {
pub fn widgetAt_s<RetType, T: QApplication_widgetAt_s<RetType>>( overload_args: T) -> RetType {
return overload_args.widgetAt_s();
// return 1;
}
}
pub trait QApplication_widgetAt_s<RetType> {
fn widgetAt_s(self ) -> RetType;
}
// proto: static QWidget * QApplication::widgetAt(const QPoint & p);
impl<'a> /*trait*/ QApplication_widgetAt_s<QWidget> for (&'a QPoint) {
fn widgetAt_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication8widgetAtERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN12QApplication8widgetAtERK6QPoint(arg0)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QApplication::setActiveWindow(QWidget * act);
impl /*struct*/ QApplication {
pub fn setActiveWindow_s<RetType, T: QApplication_setActiveWindow_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setActiveWindow_s();
// return 1;
}
}
pub trait QApplication_setActiveWindow_s<RetType> {
fn setActiveWindow_s(self ) -> RetType;
}
// proto: static void QApplication::setActiveWindow(QWidget * act);
impl<'a> /*trait*/ QApplication_setActiveWindow_s<()> for (&'a QWidget) {
fn setActiveWindow_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication15setActiveWindowEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QApplication15setActiveWindowEP7QWidget(arg0)};
// return 1;
}
}
// proto: static QFont QApplication::font();
impl<'a> /*trait*/ QApplication_font_s<QFont> for () {
fn font_s(self ) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication4fontEv()};
let mut ret = unsafe {C_ZN12QApplication4fontEv()};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QApplication::setWheelScrollLines(int );
impl /*struct*/ QApplication {
pub fn setWheelScrollLines_s<RetType, T: QApplication_setWheelScrollLines_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setWheelScrollLines_s();
// return 1;
}
}
pub trait QApplication_setWheelScrollLines_s<RetType> {
fn setWheelScrollLines_s(self ) -> RetType;
}
// proto: static void QApplication::setWheelScrollLines(int );
impl<'a> /*trait*/ QApplication_setWheelScrollLines_s<()> for (i32) {
fn setWheelScrollLines_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication19setWheelScrollLinesEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QApplication19setWheelScrollLinesEi(arg0)};
// return 1;
}
}
// proto: void QApplication::setStyleSheet(const QString & sheet);
impl /*struct*/ QApplication {
pub fn setStyleSheet<RetType, T: QApplication_setStyleSheet<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setStyleSheet(self);
// return 1;
}
}
pub trait QApplication_setStyleSheet<RetType> {
fn setStyleSheet(self , rsthis: & QApplication) -> RetType;
}
// proto: void QApplication::setStyleSheet(const QString & sheet);
impl<'a> /*trait*/ QApplication_setStyleSheet<()> for (&'a QString) {
fn setStyleSheet(self , rsthis: & QApplication) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication13setStyleSheetERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QApplication13setStyleSheetERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QApplication::setAutoSipEnabled(const bool enabled);
impl /*struct*/ QApplication {
pub fn setAutoSipEnabled<RetType, T: QApplication_setAutoSipEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAutoSipEnabled(self);
// return 1;
}
}
pub trait QApplication_setAutoSipEnabled<RetType> {
fn setAutoSipEnabled(self , rsthis: & QApplication) -> RetType;
}
// proto: void QApplication::setAutoSipEnabled(const bool enabled);
impl<'a> /*trait*/ QApplication_setAutoSipEnabled<()> for (i8) {
fn setAutoSipEnabled(self , rsthis: & QApplication) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication17setAutoSipEnabledEb()};
let arg0 = self as c_char;
unsafe {C_ZN12QApplication17setAutoSipEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: const QMetaObject * QApplication::metaObject();
impl /*struct*/ QApplication {
pub fn metaObject<RetType, T: QApplication_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QApplication_metaObject<RetType> {
fn metaObject(self , rsthis: & QApplication) -> RetType;
}
// proto: const QMetaObject * QApplication::metaObject();
impl<'a> /*trait*/ QApplication_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QApplication) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QApplication10metaObjectEv()};
let mut ret = unsafe {C_ZNK12QApplication10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static int QApplication::keyboardInputInterval();
impl /*struct*/ QApplication {
pub fn keyboardInputInterval_s<RetType, T: QApplication_keyboardInputInterval_s<RetType>>( overload_args: T) -> RetType {
return overload_args.keyboardInputInterval_s();
// return 1;
}
}
pub trait QApplication_keyboardInputInterval_s<RetType> {
fn keyboardInputInterval_s(self ) -> RetType;
}
// proto: static int QApplication::keyboardInputInterval();
impl<'a> /*trait*/ QApplication_keyboardInputInterval_s<i32> for () {
fn keyboardInputInterval_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication21keyboardInputIntervalEv()};
let mut ret = unsafe {C_ZN12QApplication21keyboardInputIntervalEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static int QApplication::cursorFlashTime();
impl /*struct*/ QApplication {
pub fn cursorFlashTime_s<RetType, T: QApplication_cursorFlashTime_s<RetType>>( overload_args: T) -> RetType {
return overload_args.cursorFlashTime_s();
// return 1;
}
}
pub trait QApplication_cursorFlashTime_s<RetType> {
fn cursorFlashTime_s(self ) -> RetType;
}
// proto: static int QApplication::cursorFlashTime();
impl<'a> /*trait*/ QApplication_cursorFlashTime_s<i32> for () {
fn cursorFlashTime_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication15cursorFlashTimeEv()};
let mut ret = unsafe {C_ZN12QApplication15cursorFlashTimeEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static int QApplication::startDragDistance();
impl /*struct*/ QApplication {
pub fn startDragDistance_s<RetType, T: QApplication_startDragDistance_s<RetType>>( overload_args: T) -> RetType {
return overload_args.startDragDistance_s();
// return 1;
}
}
pub trait QApplication_startDragDistance_s<RetType> {
fn startDragDistance_s(self ) -> RetType;
}
// proto: static int QApplication::startDragDistance();
impl<'a> /*trait*/ QApplication_startDragDistance_s<i32> for () {
fn startDragDistance_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication17startDragDistanceEv()};
let mut ret = unsafe {C_ZN12QApplication17startDragDistanceEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static QDesktopWidget * QApplication::desktop();
impl /*struct*/ QApplication {
pub fn desktop_s<RetType, T: QApplication_desktop_s<RetType>>( overload_args: T) -> RetType {
return overload_args.desktop_s();
// return 1;
}
}
pub trait QApplication_desktop_s<RetType> {
fn desktop_s(self ) -> RetType;
}
// proto: static QDesktopWidget * QApplication::desktop();
impl<'a> /*trait*/ QApplication_desktop_s<QDesktopWidget> for () {
fn desktop_s(self ) -> QDesktopWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication7desktopEv()};
let mut ret = unsafe {C_ZN12QApplication7desktopEv()};
let mut ret1 = QDesktopWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QApplication::setStartDragDistance(int l);
impl /*struct*/ QApplication {
pub fn setStartDragDistance_s<RetType, T: QApplication_setStartDragDistance_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setStartDragDistance_s();
// return 1;
}
}
pub trait QApplication_setStartDragDistance_s<RetType> {
fn setStartDragDistance_s(self ) -> RetType;
}
// proto: static void QApplication::setStartDragDistance(int l);
impl<'a> /*trait*/ QApplication_setStartDragDistance_s<()> for (i32) {
fn setStartDragDistance_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication20setStartDragDistanceEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QApplication20setStartDragDistanceEi(arg0)};
// return 1;
}
}
// proto: static QFont QApplication::font(const QWidget * );
impl<'a> /*trait*/ QApplication_font_s<QFont> for (&'a QWidget) {
fn font_s(self ) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication4fontEPK7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN12QApplication4fontEPK7QWidget(arg0)};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static int QApplication::colorSpec();
impl /*struct*/ QApplication {
pub fn colorSpec_s<RetType, T: QApplication_colorSpec_s<RetType>>( overload_args: T) -> RetType {
return overload_args.colorSpec_s();
// return 1;
}
}
pub trait QApplication_colorSpec_s<RetType> {
fn colorSpec_s(self ) -> RetType;
}
// proto: static int QApplication::colorSpec();
impl<'a> /*trait*/ QApplication_colorSpec_s<i32> for () {
fn colorSpec_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication9colorSpecEv()};
let mut ret = unsafe {C_ZN12QApplication9colorSpecEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static void QApplication::setFont(const QFont & , const char * className);
impl /*struct*/ QApplication {
pub fn setFont_s<RetType, T: QApplication_setFont_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setFont_s();
// return 1;
}
}
pub trait QApplication_setFont_s<RetType> {
fn setFont_s(self ) -> RetType;
}
// proto: static void QApplication::setFont(const QFont & , const char * className);
impl<'a> /*trait*/ QApplication_setFont_s<()> for (&'a QFont, Option<&'a String>) {
fn setFont_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication7setFontERK5QFontPKc()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0 as *const u8} else {self.1.unwrap().as_ptr()}) as *mut c_char;
unsafe {C_ZN12QApplication7setFontERK5QFontPKc(arg0, arg1)};
// return 1;
}
}
// proto: static void QApplication::closeAllWindows();
impl /*struct*/ QApplication {
pub fn closeAllWindows_s<RetType, T: QApplication_closeAllWindows_s<RetType>>( overload_args: T) -> RetType {
return overload_args.closeAllWindows_s();
// return 1;
}
}
pub trait QApplication_closeAllWindows_s<RetType> {
fn closeAllWindows_s(self ) -> RetType;
}
// proto: static void QApplication::closeAllWindows();
impl<'a> /*trait*/ QApplication_closeAllWindows_s<()> for () {
fn closeAllWindows_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication15closeAllWindowsEv()};
unsafe {C_ZN12QApplication15closeAllWindowsEv()};
// return 1;
}
}
// proto: static void QApplication::setCursorFlashTime(int );
impl /*struct*/ QApplication {
pub fn setCursorFlashTime_s<RetType, T: QApplication_setCursorFlashTime_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setCursorFlashTime_s();
// return 1;
}
}
pub trait QApplication_setCursorFlashTime_s<RetType> {
fn setCursorFlashTime_s(self ) -> RetType;
}
// proto: static void QApplication::setCursorFlashTime(int );
impl<'a> /*trait*/ QApplication_setCursorFlashTime_s<()> for (i32) {
fn setCursorFlashTime_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication18setCursorFlashTimeEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QApplication18setCursorFlashTimeEi(arg0)};
// return 1;
}
}
// proto: static QWidget * QApplication::widgetAt(int x, int y);
impl<'a> /*trait*/ QApplication_widgetAt_s<QWidget> for (i32, i32) {
fn widgetAt_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication8widgetAtEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let mut ret = unsafe {C_ZN12QApplication8widgetAtEii(arg0, arg1)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QApplication::alert(QWidget * widget, int duration);
impl /*struct*/ QApplication {
pub fn alert_s<RetType, T: QApplication_alert_s<RetType>>( overload_args: T) -> RetType {
return overload_args.alert_s();
// return 1;
}
}
pub trait QApplication_alert_s<RetType> {
fn alert_s(self ) -> RetType;
}
// proto: static void QApplication::alert(QWidget * widget, int duration);
impl<'a> /*trait*/ QApplication_alert_s<()> for (&'a QWidget, Option<i32>) {
fn alert_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication5alertEP7QWidgeti()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0} else {self.1.unwrap()}) as c_int;
unsafe {C_ZN12QApplication5alertEP7QWidgeti(arg0, arg1)};
// return 1;
}
}
// proto: static QPalette QApplication::palette(const QWidget * );
impl<'a> /*trait*/ QApplication_palette_s<QPalette> for (&'a QWidget) {
fn palette_s(self ) -> QPalette {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication7paletteEPK7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN12QApplication7paletteEPK7QWidget(arg0)};
let mut ret1 = QPalette::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static int QApplication::wheelScrollLines();
impl /*struct*/ QApplication {
pub fn wheelScrollLines_s<RetType, T: QApplication_wheelScrollLines_s<RetType>>( overload_args: T) -> RetType {
return overload_args.wheelScrollLines_s();
// return 1;
}
}
pub trait QApplication_wheelScrollLines_s<RetType> {
fn wheelScrollLines_s(self ) -> RetType;
}
// proto: static int QApplication::wheelScrollLines();
impl<'a> /*trait*/ QApplication_wheelScrollLines_s<i32> for () {
fn wheelScrollLines_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication16wheelScrollLinesEv()};
let mut ret = unsafe {C_ZN12QApplication16wheelScrollLinesEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static void QApplication::aboutQt();
impl /*struct*/ QApplication {
pub fn aboutQt_s<RetType, T: QApplication_aboutQt_s<RetType>>( overload_args: T) -> RetType {
return overload_args.aboutQt_s();
// return 1;
}
}
pub trait QApplication_aboutQt_s<RetType> {
fn aboutQt_s(self ) -> RetType;
}
// proto: static void QApplication::aboutQt();
impl<'a> /*trait*/ QApplication_aboutQt_s<()> for () {
fn aboutQt_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication7aboutQtEv()};
unsafe {C_ZN12QApplication7aboutQtEv()};
// return 1;
}
}
// proto: static QWidget * QApplication::activeModalWidget();
impl /*struct*/ QApplication {
pub fn activeModalWidget_s<RetType, T: QApplication_activeModalWidget_s<RetType>>( overload_args: T) -> RetType {
return overload_args.activeModalWidget_s();
// return 1;
}
}
pub trait QApplication_activeModalWidget_s<RetType> {
fn activeModalWidget_s(self ) -> RetType;
}
// proto: static QWidget * QApplication::activeModalWidget();
impl<'a> /*trait*/ QApplication_activeModalWidget_s<QWidget> for () {
fn activeModalWidget_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication17activeModalWidgetEv()};
let mut ret = unsafe {C_ZN12QApplication17activeModalWidgetEv()};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QWidget * QApplication::activePopupWidget();
impl /*struct*/ QApplication {
pub fn activePopupWidget_s<RetType, T: QApplication_activePopupWidget_s<RetType>>( overload_args: T) -> RetType {
return overload_args.activePopupWidget_s();
// return 1;
}
}
pub trait QApplication_activePopupWidget_s<RetType> {
fn activePopupWidget_s(self ) -> RetType;
}
// proto: static QWidget * QApplication::activePopupWidget();
impl<'a> /*trait*/ QApplication_activePopupWidget_s<QWidget> for () {
fn activePopupWidget_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication17activePopupWidgetEv()};
let mut ret = unsafe {C_ZN12QApplication17activePopupWidgetEv()};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QApplication::QApplication(int & argc, char ** argv, int );
impl /*struct*/ QApplication {
pub fn new<T: QApplication_new>(value: T) -> QApplication {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QApplication_new {
fn new(self) -> QApplication;
}
// proto: void QApplication::QApplication(int & argc, char ** argv, int );
impl<'a> /*trait*/ QApplication_new for (&'a mut i32, &'a mut String, Option<i32>) {
fn new(self) -> QApplication {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplicationC2ERiPPci()};
let ctysz: c_int = unsafe{QApplication_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as *mut c_int;
let arg1 = self.1.as_ptr() as *mut c_char;
let arg2 = (if self.2.is_none() {0 as i32} else {self.2.unwrap()}) as c_int;
let qthis: u64 = unsafe {C_ZN12QApplicationC2ERiPPci(arg0, arg1, arg2)};
let rsthis = QApplication{qbase: QGuiApplication::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static void QApplication::setStartDragTime(int ms);
impl /*struct*/ QApplication {
pub fn setStartDragTime_s<RetType, T: QApplication_setStartDragTime_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setStartDragTime_s();
// return 1;
}
}
pub trait QApplication_setStartDragTime_s<RetType> {
fn setStartDragTime_s(self ) -> RetType;
}
// proto: static void QApplication::setStartDragTime(int ms);
impl<'a> /*trait*/ QApplication_setStartDragTime_s<()> for (i32) {
fn setStartDragTime_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication16setStartDragTimeEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QApplication16setStartDragTimeEi(arg0)};
// return 1;
}
}
// proto: static QWidget * QApplication::topLevelAt(int x, int y);
impl /*struct*/ QApplication {
pub fn topLevelAt_s<RetType, T: QApplication_topLevelAt_s<RetType>>( overload_args: T) -> RetType {
return overload_args.topLevelAt_s();
// return 1;
}
}
pub trait QApplication_topLevelAt_s<RetType> {
fn topLevelAt_s(self ) -> RetType;
}
// proto: static QWidget * QApplication::topLevelAt(int x, int y);
impl<'a> /*trait*/ QApplication_topLevelAt_s<QWidget> for (i32, i32) {
fn topLevelAt_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication10topLevelAtEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let mut ret = unsafe {C_ZN12QApplication10topLevelAtEii(arg0, arg1)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QApplication::setStyle(QStyle * );
impl /*struct*/ QApplication {
pub fn setStyle_s<RetType, T: QApplication_setStyle_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setStyle_s();
// return 1;
}
}
pub trait QApplication_setStyle_s<RetType> {
fn setStyle_s(self ) -> RetType;
}
// proto: static void QApplication::setStyle(QStyle * );
impl<'a> /*trait*/ QApplication_setStyle_s<()> for (&'a QStyle) {
fn setStyle_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication8setStyleEP6QStyle()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QApplication8setStyleEP6QStyle(arg0)};
// return 1;
}
}
// proto: void QApplication::~QApplication();
impl /*struct*/ QApplication {
pub fn free<RetType, T: QApplication_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QApplication_free<RetType> {
fn free(self , rsthis: & QApplication) -> RetType;
}
// proto: void QApplication::~QApplication();
impl<'a> /*trait*/ QApplication_free<()> for () {
fn free(self , rsthis: & QApplication) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplicationD2Ev()};
unsafe {C_ZN12QApplicationD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: static void QApplication::setDoubleClickInterval(int );
impl /*struct*/ QApplication {
pub fn setDoubleClickInterval_s<RetType, T: QApplication_setDoubleClickInterval_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setDoubleClickInterval_s();
// return 1;
}
}
pub trait QApplication_setDoubleClickInterval_s<RetType> {
fn setDoubleClickInterval_s(self ) -> RetType;
}
// proto: static void QApplication::setDoubleClickInterval(int );
impl<'a> /*trait*/ QApplication_setDoubleClickInterval_s<()> for (i32) {
fn setDoubleClickInterval_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication22setDoubleClickIntervalEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QApplication22setDoubleClickIntervalEi(arg0)};
// return 1;
}
}
// proto: static void QApplication::setGlobalStrut(const QSize & );
impl /*struct*/ QApplication {
pub fn setGlobalStrut_s<RetType, T: QApplication_setGlobalStrut_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setGlobalStrut_s();
// return 1;
}
}
pub trait QApplication_setGlobalStrut_s<RetType> {
fn setGlobalStrut_s(self ) -> RetType;
}
// proto: static void QApplication::setGlobalStrut(const QSize & );
impl<'a> /*trait*/ QApplication_setGlobalStrut_s<()> for (&'a QSize) {
fn setGlobalStrut_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication14setGlobalStrutERK5QSize()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QApplication14setGlobalStrutERK5QSize(arg0)};
// return 1;
}
}
// proto: static void QApplication::setColorSpec(int );
impl /*struct*/ QApplication {
pub fn setColorSpec_s<RetType, T: QApplication_setColorSpec_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setColorSpec_s();
// return 1;
}
}
pub trait QApplication_setColorSpec_s<RetType> {
fn setColorSpec_s(self ) -> RetType;
}
// proto: static void QApplication::setColorSpec(int );
impl<'a> /*trait*/ QApplication_setColorSpec_s<()> for (i32) {
fn setColorSpec_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication12setColorSpecEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QApplication12setColorSpecEi(arg0)};
// return 1;
}
}
// proto: static QWidgetList QApplication::allWidgets();
impl /*struct*/ QApplication {
pub fn allWidgets_s<RetType, T: QApplication_allWidgets_s<RetType>>( overload_args: T) -> RetType {
return overload_args.allWidgets_s();
// return 1;
}
}
pub trait QApplication_allWidgets_s<RetType> {
fn allWidgets_s(self ) -> RetType;
}
// proto: static QWidgetList QApplication::allWidgets();
impl<'a> /*trait*/ QApplication_allWidgets_s<u64> for () {
fn allWidgets_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication10allWidgetsEv()};
let mut ret = unsafe {C_ZN12QApplication10allWidgetsEv()};
return ret as u64; // 5
// return 1;
}
}
// proto: static QSize QApplication::globalStrut();
impl /*struct*/ QApplication {
pub fn globalStrut_s<RetType, T: QApplication_globalStrut_s<RetType>>( overload_args: T) -> RetType {
return overload_args.globalStrut_s();
// return 1;
}
}
pub trait QApplication_globalStrut_s<RetType> {
fn globalStrut_s(self ) -> RetType;
}
// proto: static QSize QApplication::globalStrut();
impl<'a> /*trait*/ QApplication_globalStrut_s<QSize> for () {
fn globalStrut_s(self ) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication11globalStrutEv()};
let mut ret = unsafe {C_ZN12QApplication11globalStrutEv()};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QApplication::setPalette(const QPalette & , const char * className);
impl /*struct*/ QApplication {
pub fn setPalette_s<RetType, T: QApplication_setPalette_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setPalette_s();
// return 1;
}
}
pub trait QApplication_setPalette_s<RetType> {
fn setPalette_s(self ) -> RetType;
}
// proto: static void QApplication::setPalette(const QPalette & , const char * className);
impl<'a> /*trait*/ QApplication_setPalette_s<()> for (&'a QPalette, Option<&'a String>) {
fn setPalette_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication10setPaletteERK8QPalettePKc()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0 as *const u8} else {self.1.unwrap().as_ptr()}) as *mut c_char;
unsafe {C_ZN12QApplication10setPaletteERK8QPalettePKc(arg0, arg1)};
// return 1;
}
}
// proto: static QStyle * QApplication::setStyle(const QString & );
impl<'a> /*trait*/ QApplication_setStyle_s<QStyle> for (&'a QString) {
fn setStyle_s(self ) -> QStyle {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication8setStyleERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN12QApplication8setStyleERK7QString(arg0)};
let mut ret1 = QStyle::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QWidgetList QApplication::topLevelWidgets();
impl /*struct*/ QApplication {
pub fn topLevelWidgets_s<RetType, T: QApplication_topLevelWidgets_s<RetType>>( overload_args: T) -> RetType {
return overload_args.topLevelWidgets_s();
// return 1;
}
}
pub trait QApplication_topLevelWidgets_s<RetType> {
fn topLevelWidgets_s(self ) -> RetType;
}
// proto: static QWidgetList QApplication::topLevelWidgets();
impl<'a> /*trait*/ QApplication_topLevelWidgets_s<u64> for () {
fn topLevelWidgets_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication15topLevelWidgetsEv()};
let mut ret = unsafe {C_ZN12QApplication15topLevelWidgetsEv()};
return ret as u64; // 5
// return 1;
}
}
// proto: static int QApplication::exec();
impl /*struct*/ QApplication {
pub fn exec_s<RetType, T: QApplication_exec_s<RetType>>( overload_args: T) -> RetType {
return overload_args.exec_s();
// return 1;
}
}
pub trait QApplication_exec_s<RetType> {
fn exec_s(self ) -> RetType;
}
// proto: static int QApplication::exec();
impl<'a> /*trait*/ QApplication_exec_s<i32> for () {
fn exec_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication4execEv()};
let mut ret = unsafe {C_ZN12QApplication4execEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static void QApplication::setWindowIcon(const QIcon & icon);
impl /*struct*/ QApplication {
pub fn setWindowIcon_s<RetType, T: QApplication_setWindowIcon_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setWindowIcon_s();
// return 1;
}
}
pub trait QApplication_setWindowIcon_s<RetType> {
fn setWindowIcon_s(self ) -> RetType;
}
// proto: static void QApplication::setWindowIcon(const QIcon & icon);
impl<'a> /*trait*/ QApplication_setWindowIcon_s<()> for (&'a QIcon) {
fn setWindowIcon_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication13setWindowIconERK5QIcon()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QApplication13setWindowIconERK5QIcon(arg0)};
// return 1;
}
}
// proto: static void QApplication::beep();
impl /*struct*/ QApplication {
pub fn beep_s<RetType, T: QApplication_beep_s<RetType>>( overload_args: T) -> RetType {
return overload_args.beep_s();
// return 1;
}
}
pub trait QApplication_beep_s<RetType> {
fn beep_s(self ) -> RetType;
}
// proto: static void QApplication::beep();
impl<'a> /*trait*/ QApplication_beep_s<()> for () {
fn beep_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication4beepEv()};
unsafe {C_ZN12QApplication4beepEv()};
// return 1;
}
}
// proto: bool QApplication::notify(QObject * , QEvent * );
impl /*struct*/ QApplication {
pub fn notify<RetType, T: QApplication_notify<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.notify(self);
// return 1;
}
}
pub trait QApplication_notify<RetType> {
fn notify(self , rsthis: & QApplication) -> RetType;
}
// proto: bool QApplication::notify(QObject * , QEvent * );
impl<'a> /*trait*/ QApplication_notify<i8> for (&'a QObject, &'a QEvent) {
fn notify(self , rsthis: & QApplication) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication6notifyEP7QObjectP6QEvent()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN12QApplication6notifyEP7QObjectP6QEvent(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QApplication::autoSipEnabled();
impl /*struct*/ QApplication {
pub fn autoSipEnabled<RetType, T: QApplication_autoSipEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.autoSipEnabled(self);
// return 1;
}
}
pub trait QApplication_autoSipEnabled<RetType> {
fn autoSipEnabled(self , rsthis: & QApplication) -> RetType;
}
// proto: bool QApplication::autoSipEnabled();
impl<'a> /*trait*/ QApplication_autoSipEnabled<i8> for () {
fn autoSipEnabled(self , rsthis: & QApplication) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QApplication14autoSipEnabledEv()};
let mut ret = unsafe {C_ZNK12QApplication14autoSipEnabledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: static QWidget * QApplication::topLevelAt(const QPoint & p);
impl<'a> /*trait*/ QApplication_topLevelAt_s<QWidget> for (&'a QPoint) {
fn topLevelAt_s(self ) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication10topLevelAtERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN12QApplication10topLevelAtERK6QPoint(arg0)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static int QApplication::startDragTime();
impl /*struct*/ QApplication {
pub fn startDragTime_s<RetType, T: QApplication_startDragTime_s<RetType>>( overload_args: T) -> RetType {
return overload_args.startDragTime_s();
// return 1;
}
}
pub trait QApplication_startDragTime_s<RetType> {
fn startDragTime_s(self ) -> RetType;
}
// proto: static int QApplication::startDragTime();
impl<'a> /*trait*/ QApplication_startDragTime_s<i32> for () {
fn startDragTime_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication13startDragTimeEv()};
let mut ret = unsafe {C_ZN12QApplication13startDragTimeEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static int QApplication::doubleClickInterval();
impl /*struct*/ QApplication {
pub fn doubleClickInterval_s<RetType, T: QApplication_doubleClickInterval_s<RetType>>( overload_args: T) -> RetType {
return overload_args.doubleClickInterval_s();
// return 1;
}
}
pub trait QApplication_doubleClickInterval_s<RetType> {
fn doubleClickInterval_s(self ) -> RetType;
}
// proto: static int QApplication::doubleClickInterval();
impl<'a> /*trait*/ QApplication_doubleClickInterval_s<i32> for () {
fn doubleClickInterval_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication19doubleClickIntervalEv()};
let mut ret = unsafe {C_ZN12QApplication19doubleClickIntervalEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static QIcon QApplication::windowIcon();
impl /*struct*/ QApplication {
pub fn windowIcon_s<RetType, T: QApplication_windowIcon_s<RetType>>( overload_args: T) -> RetType {
return overload_args.windowIcon_s();
// return 1;
}
}
pub trait QApplication_windowIcon_s<RetType> {
fn windowIcon_s(self ) -> RetType;
}
// proto: static QIcon QApplication::windowIcon();
impl<'a> /*trait*/ QApplication_windowIcon_s<QIcon> for () {
fn windowIcon_s(self ) -> QIcon {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QApplication10windowIconEv()};
let mut ret = unsafe {C_ZN12QApplication10windowIconEv()};
let mut ret1 = QIcon::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
#[derive(Default)] // for QApplication_focusChanged
pub struct QApplication_focusChanged_signal{poi:u64}
impl /* struct */ QApplication {
pub fn focusChanged(&self) -> QApplication_focusChanged_signal {
return QApplication_focusChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QApplication_focusChanged_signal {
pub fn connect<T: QApplication_focusChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QApplication_focusChanged_signal_connect {
fn connect(self, sigthis: QApplication_focusChanged_signal);
}
// focusChanged(class QWidget *, class QWidget *)
extern fn QApplication_focusChanged_signal_connect_cb_0(rsfptr:fn(QWidget, QWidget), arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QWidget::inheritFrom(arg0 as u64);
let rsarg1 = QWidget::inheritFrom(arg1 as u64);
rsfptr(rsarg0,rsarg1);
}
extern fn QApplication_focusChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QWidget, QWidget)>, arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QWidget::inheritFrom(arg0 as u64);
let rsarg1 = QWidget::inheritFrom(arg1 as u64);
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QApplication_focusChanged_signal_connect for fn(QWidget, QWidget) {
fn connect(self, sigthis: QApplication_focusChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QApplication_focusChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QApplication_SlotProxy_connect__ZN12QApplication12focusChangedEP7QWidgetS1_(arg0, arg1, arg2)};
}
}
impl /* trait */ QApplication_focusChanged_signal_connect for Box<Fn(QWidget, QWidget)> {
fn connect(self, sigthis: QApplication_focusChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QApplication_focusChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QApplication_SlotProxy_connect__ZN12QApplication12focusChangedEP7QWidgetS1_(arg0, arg1, arg2)};
}
}
// <= body block end
|
use yew::prelude::*;
pub struct TabSettings {}
pub enum Msg {}
impl Component for TabSettings {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
TabSettings {}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<div>
<div
class="border rounded p-4 d-flex flex-column mb-5"
style="font-size: 14px;"
>
<div
class="d-flex flex-row border-bottom"
>
<div
class="w-50 text-color-primary fw-bold"
>
{"General Settings"}
</div>
<div
class="w-50"
>
<div
class="mb-4"
>
<p class="mb-2 fw-bold">
{"ID"}
</p>
<div class="input-group mb-2">
<input
type="text"
class="form-control bg-input-grey"
aria-label="Dollar amount (with dot and two decimal places)"
value="60ef247ffab77800401cca56"
/>
</div>
<p>
{"The API id on our system. Useful if you prefer to work directly with Auth0's Management API instead."}
</p>
</div>
<div
class="mb-4"
>
<p class="mb-2 fw-bold">
{"Name*"}
</p>
<div class="input-group mb-2">
<input
type="text"
class="form-control bg-input-grey"
aria-label="Dollar amount (with dot and two decimal places)"
value="Testing Name"
/>
</div>
<p>
{"A friendly name for the API. The following characters are not allowed "}
<code
style="padding: 2px 6px; font-size: 11px;"
class="bg-input-grey text-color-primary"
>
<i class="bi bi-chevron-left"></i>
</code>
<code
style="padding: 2px 6px; font-size: 11px;"
class="bg-input-grey text-color-primary"
>
<i class="bi bi-chevron-right"></i>
</code>
</p>
</div>
<div
class="mb-5"
>
<p class="mb-2 fw-bold">
{"Identifier"}
</p>
<div class="input-group mb-2">
<input
type="text"
class="form-control bg-input-grey"
aria-label="Dollar amount (with dot and two decimal places)"
value="https://test-api/"
/>
</div>
<p>
{"Unique identifier for the API. This value will be used as the "}
<code
style="padding: 2px 6px; font-size: 14px;"
class="bg-input-grey text-color-primary"
>
{"audience"}
</code>
{" parameter on authorization calls."}
</p>
</div>
</div>
</div>
<div
class="d-flex flex-row border-bottom mt-5"
>
<div
class="w-50 text-color-primary fw-bold"
>
{"Tokens Settings"}
</div>
<div
class="w-50"
>
<div
class="mb-4"
>
<p class="mb-2 fw-bold">
{"Token Expirations (Seconds)*"}
</p>
<div class="input-group mb-2">
<input
type="text"
class="form-control bg-input-grey"
aria-label="Dollar amount (with dot and two decimal places)"
value="86400"
/>
</div>
<p>
{"Expiration value (in seconds) for "}
<code
style="padding: 2px 6px; font-size: 11px;"
class="bg-input-grey text-color-primary"
>
{"access tokens"}
</code>
{" issued for this API from the Token Endpoint."}
</p>
</div>
<div
class="mb-4"
>
<p class="mb-2 fw-bold">
{"Token Expirations For Browser Flows (Seconds)*"}
</p>
<div class="input-group mb-2">
<input
type="text"
class="form-control bg-input-grey"
aria-label="Dollar amount (with dot and two decimal places)"
value="7200"
/>
</div>
<p>
{"Expiration value (in seconds) for "}
<code
style="padding: 2px 6px; font-size: 11px;"
class="bg-input-grey text-color-primary"
>
{"access tokens"}
</code>
{" issued for this API via Implicit or Hybrid Flows. Cannot be greater than the Token Lifetime value."}
</p>
</div>
<div
class="mb-5"
>
<p class="mb-2 fw-bold">
{"Signing Algorithm"}
</p>
<div class="input-group mb-2">
<input
type="text"
class="form-control bg-input-grey"
aria-label="Dollar amount (with dot and two decimal places)"
value="RS256"
/>
</div>
<p>
{"Algorithm to be used when signing the "}
<code
style="padding: 2px 6px; font-size: 11px;"
class="bg-input-grey text-color-primary"
>
{"access tokens"}
</code>
{" for this API. You can find more information"}
</p>
</div>
</div>
</div>
<div
class="d-flex flex-row border-bottom mt-5"
>
<div
class="w-50 text-color-primary fw-bold"
>
{"RBAC Settings"}
</div>
<div
class="w-50"
>
<div
class="mb-4"
>
<p class="mb-2 fw-bold">
{"Enable RBAC "}
</p>
<div class="form-check form-switch fs-3 mb-4">
<input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault"/>
</div>
<p>
{"If this setting is enabled, this API will skip user consent for applications flagged as First Party."}
</p>
</div>
<div
class="mb-4"
>
<p class="mb-2 fw-bold">
{"Allow Offline Access"}
</p>
<div class="form-check form-switch fs-3 mb-4">
<input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault"/>
</div>
<p>
{"If this setting is enabled, Auth0 will allow applications to ask for Refresh Tokens for this API."}
</p>
</div>
<button type="button" class="btn btn-primary mb-5 mt-3">{"Save"}</button>
</div>
</div>
</div>
<div
style="font-size: 14px;"
>
<p
class="fw-bold"
>
{"Danger Zone"}
</p>
<div class="alert alert-danger d-flex flex-row justify-content-between" role="alert">
<div>
<p
class="fw-bold"
>
{"Delete This API"}
</p>
{"Once confirmed, this operation can't be undone!"}
</div>
<div>
<button
type="button"
class="btn btn-danger"
>{"Delete"}</button>
</div>
</div>
</div>
</div>
}
}
}
|
use serde_json::{json, Value};
use serde_json::ser::State::Rest;
use rbatis_core::convert::StmtConvert;
use rbatis_core::db::DriverType;
use crate::ast::ast::RbatisAST;
use crate::ast::node::node::{create_deep, do_child_nodes, print_child, SqlNodePrint};
use crate::ast::node::node_type::NodeType;
use crate::ast::node::string_node::StringNode;
use crate::engine::runtime::RbatisEngine;
#[derive(Clone, Debug)]
pub struct IfNode {
pub childs: Vec<NodeType>,
pub test: String,
}
impl RbatisAST for IfNode {
fn eval(&self, convert: &impl StmtConvert, env: &mut Value, engine: &RbatisEngine, arg_array: &mut Vec<Value>) -> Result<String, rbatis_core::Error> {
let result = engine.eval(self.test.as_str(), env)?;
if !result.is_boolean() {
return Result::Err(rbatis_core::Error::from("[rbatis] express:'".to_owned() + self.test.as_str() + "' is not return bool value!"));
}
if result.as_bool().unwrap() {
return do_child_nodes(convert, &self.childs, env, engine, arg_array);
}
return Result::Ok("".to_string());
}
}
impl SqlNodePrint for IfNode {
fn print(&self, deep: i32) -> String {
let mut result = create_deep(deep) + "<if ";
result = result + " test=\"" + self.test.as_str() + "\" >";
result = result + print_child(self.childs.as_ref(), deep + 1).as_str();
result = result + create_deep(deep).as_str() + "</if>";
return result;
}
}
#[test]
pub fn test_if_node() {
let node = IfNode {
childs: vec![NodeType::NString(StringNode::new("yes"))],
test: "arg == 1".to_string(),
};
let mut john = json!({
"arg": 1,
});
let mut engine = RbatisEngine::new();
let mut arg_array = vec![];
println!("{}", node.eval(&DriverType::Mysql, &mut john, &mut engine, &mut arg_array).unwrap());
} |
pub use self::store::Store;
use diesel::r2d2::{ConnectionManager, PooledConnection};
use diesel::sql_types::Integer;
use diesel::{self, QueryResult, RunQueryDsl, SqliteConnection};
use std::ops::Deref;
mod models;
mod schema;
mod store;
pub struct Conn(PooledConnection<ConnectionManager<SqliteConnection>>);
impl Conn {
pub fn new(conn: PooledConnection<ConnectionManager<SqliteConnection>>) -> Self {
Conn(conn)
}
}
impl Deref for Conn {
type Target = SqliteConnection;
fn deref(&self) -> &Self::Target {
&self.0
}
}
no_arg_sql_function!(last_insert_rowid, Integer);
pub fn last_inserted_row_id(connection: &SqliteConnection) -> QueryResult<i32> {
diesel::select(last_insert_rowid).get_result(connection)
}
|
use postgres::{Client, NoTls};
use chrono::{DateTime, Utc};
use std::time::Instant;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::convert::TryFrom;
// IO stuff
use std::io::prelude::*;
use crate::exchange::{Exchange, Market, Order, SecStat, Trade, UserAccount, OrderStatus};
use crate::account::AuthError;
use crate::buffer::{DatabaseReadyOrder};
/* ---- Specification for the db API ----
*
* Functions that start with populate will read from the db on program startup ONLY.
* - These populate critical runtime data-structures.
* Functions that start with read will read from the db during normal program execution.
* Functions that start with write will write to the db during normal program execution.
*
* If more than 1 operation occurs in a function, ex. deletes AND updates, this will be
* clearly described above the function.
**/
/* Helper function for populate_exchange_markets.
*
* Directly inserts this order to the market
* If the market didn't exist, we will return it as Some(Market)
* so the calling function can add it to the exchange.
*/
fn direct_insert_to_market(potential_market: Option<&mut Market>, order: &Order) -> Option<Market> {
// Get the market, or create it if it doesn't exist yet.
match potential_market {
Some(market) => {
match &order.action[..] {
"BUY" => {
market.buy_orders.push(order.clone());
},
"SELL" => {
market.sell_orders.push(Reverse(order.clone()));
},
_ => ()
}
},
None => {
// The market doesn't exist, create it.
// buy is a max heap, sell is a min heap.
let mut buy_heap: BinaryHeap<Order> = BinaryHeap::new();
let mut sell_heap: BinaryHeap<Reverse<Order>> = BinaryHeap::new();
// Store order on market, and in users account.
match &order.action[..] {
"BUY" => {
buy_heap.push(order.clone());
},
"SELL" => {
sell_heap.push(Reverse(order.clone()));
},
// We can never get here.
_ => ()
};
// Create the new market
let new_market = Market::new(buy_heap, sell_heap);
return Some(new_market);
}
}
return None;
}
/* Default initializes all entries in hashmap to false,
* then sets the entries that have trades to true.
**/
pub fn populate_has_trades(exchange: &mut Exchange, conn: &mut Client) {
// 1. Read all markets in our exchange.
let result = conn.query("SELECT symbol FROM Markets;", &[]);
match result {
Ok(rows) => {
for row in rows {
let symbol: &str = row.get(0);
exchange.has_trades.insert(symbol.to_string().clone(), false);
}
},
Err(e) => {
eprintln!("{:?}", e);
panic!("Query to read all market symbols failed!");
}
}
// 2. Set markets with trades to true.
let result = conn.query("SELECT DISTINCT symbol FROM ExecutedTrades;", &[]);
match result {
Ok(rows) => {
for row in rows {
let symbol: &str = row.get(0);
exchange.has_trades.insert(symbol.to_string().clone(), true);
}
},
Err(e) => {
eprintln!("{:?}", e);
panic!("Query to read all markets with trades failed!");
}
}
}
// TODO
/* Get the relevant pending orders from all
* the markets, and insert them into the exchange.
*
* - Future note: If we distribute markets across
* machines, it might be a good idea to provide
* a list of markets to read from.
* */
pub fn populate_exchange_markets(exchange: &mut Exchange, conn: &mut Client) {
// We order by symbol (market) and action, since this will probably increase cache hits.
// This is because we populate the buys, then the sells, then move to the next market. High
// spacial locality.
for row in conn.query("\
SELECT o.* FROM PendingOrders p, Orders o
WHERE o.order_ID=p.order_ID;", &[]).expect("Something went wrong in the query.") {
let order_id: i32 = row.get(0);
let symbol: &str = row.get(1);
let action: &str = row.get(2);
let quantity: i32 = row.get(3);
let filled: i32 = row.get(4);
let price: f64 = row.get(5);
let user_id: i32 = row.get(6);
// No need to get status, it's obviously pending.
let order = Order::direct(action, symbol, quantity, filled, price, order_id, OrderStatus::PENDING, user_id);
// Add the order we found to the market.
// If a new market was created, update the exchange.
if let Some(market) = direct_insert_to_market(exchange.live_orders.get_mut(&order.symbol), &order) {
exchange.live_orders.insert(order.symbol.clone(), market);
};
}
}
// TODO: Company Name??
/* Populate the statistics for each market
* - Future note: If we distribute markets across
* machines, it might be a good idea to provide
* a list of markets to read from.
**/
pub fn populate_market_statistics(exchange: &mut Exchange, conn: &mut Client) {
for row in conn.query("SELECT * FROM Markets", &[])
.expect("Something went wrong in the query.") {
let symbol: &str = row.get(0);
// let company_name: &str = row.get(1);
let total_buys: i32 = row.get(2);
let total_sells: i32 = row.get(3);
let filled_buys: i32 = row.get(4);
let filled_sells: i32 = row.get(5);
let latest_price: Option<f64> = row.get(6); // Price might be NULL if no trades occured.
let market_stats = SecStat::direct(symbol, total_buys, total_sells, filled_buys, filled_sells, latest_price);
exchange.statistics.insert(symbol.to_string().clone(), market_stats);
}
}
// TODO
/* Populate the statistics of the exchange
* - Future note: If we distribute markets across
* machines, it might be a good idea to provide
* a list of markets to read from.
**/
pub fn populate_exchange_statistics(exchange: &mut Exchange, conn: &mut Client) {
for row in conn.query("SELECT total_orders FROM ExchangeStats", &[])
.expect("Something went wrong in the query.") {
let total_orders: Option<i32> = row.get(0);
match total_orders {
Some(count) => exchange.total_orders = count,
None => exchange.total_orders = 0
}
}
}
/* Upgrade the database according to the config file.
* TODO:
* When we fulfill a request, replace the first word with #
* as it can signify a comment/completed task.
* */
pub fn upgrade_db<R>(reader: std::io::BufReader<R>, db_name: &String)
where
R: std::io::Read
{
let db_config = format!["host=localhost user=postgres dbname={}", db_name];
let mut conn = Client::connect(db_config.as_str(), NoTls)
.expect("Failed to connect to Database!");
let mut query_string = String::from("\
INSERT INTO Markets
(symbol, name, total_buys, total_sells, filled_buys, filled_sells, latest_price)
Values
");
for line in reader.lines() {
match line {
Ok(line) => {
let mut components = line.split(',');
let action = components.next().unwrap();
let symbol = components.next().unwrap();
let company_name = str::replace(components.next().unwrap(), "'", "''"); // sanitize input
if action == "add" {
query_string.push_str(format!["('{}', '{}', 0, 0, 0, 0, NULL),\n", symbol, company_name].as_str());
}
},
Err(e) => eprintln!("{}", e)
}
}
query_string.pop(); // Removes newline
query_string.pop(); // Removes last comma
query_string.push(';');
if let Err(e) = conn.query(query_string.as_str(), &[]) {
eprintln!("{:?}", e);
panic!("Query to upgrade database failed!");
}
println!("Upgrade complete!");
}
/* Reads total user count from database for new user IDs. */
pub fn read_total_accounts(conn: &mut Client) -> i32 {
match conn.query("SELECT count(*) FROM Account;", &[]) {
Ok(result) => {
let row = &result[0];
let count: i64 = row.get(0);
return i32::try_from(count).unwrap();
},
Err(e) => {
eprintln!("{}", e);
panic!("Query to get total accounts number failed");
}
}
}
/* Check the database to see if the account user exists. */
pub fn read_account_exists(username: &String, conn: &mut Client) -> bool {
for row in conn.query("SELECT ID FROM Account WHERE Account.username = $1",
&[username]).expect("There was an issue while checking if the user is in the database.") {
let id: Option<i32> = row.get(0);
if let Some(_) = id {
return true;
}
}
return false;
}
/* Compare the provided username + password combo against the database.
* If they match, return the UserAccount, otherwise, return the error that occurred.
**/
pub fn read_auth_user<'a>(username: &'a String, password: &String, conn: &mut Client) -> Result<UserAccount, AuthError<'a>> {
let query_string = "SELECT ID, username, password FROM Account WHERE Account.username = $1";
match conn.query(query_string, &[&username]) {
Ok(result) => {
// Did not find the user
if result.len() == 0 {
return Err(AuthError::NoUser(username));
}
// Found a user, usernames are unique so we get 1 row.
let row = &result[0];
let recv_id: i32 = row.get(0);
let recv_username: &str = row.get(1);
let recv_password: &str = row.get(2);
// User authenticated.
if *password == recv_password {
return Ok(UserAccount::direct(recv_id, recv_username, recv_password));
}
// Password was incorrect.
return Err(AuthError::BadPassword(None));
},
Err(e) => {
eprintln!("{}", e);
panic!("Something went wrong with the authenticate query!");
}
}
}
/* Read the account with the given username and return the account. */
pub fn read_account(username: &String, conn: &mut Client) -> Result<UserAccount, postgres::error::Error> {
match conn.query("SELECT ID, username, password FROM Account where Account.username = $1", &[username]) {
Ok(result) => {
let row = &result[0];
let recv_id: i32 = row.get(0);
let recv_username: &str = row.get(1);
let recv_password: &str = row.get(2);
return Ok(UserAccount::direct(recv_id, recv_username, recv_password));
},
Err(e) => {
eprintln!("{}", e);
return Err(e);
}
}
}
/* Read the account with the given user ID and return the username. */
pub fn read_user_by_id(id: i32, conn: &mut Client) -> Result<String, postgres::error::Error> {
match conn.query("SELECT username FROM Account where Account.id = $1", &[&id]) {
Ok(result) => {
let row = &result[0];
let recv_username: &str = row.get(0);
return Ok(recv_username.to_string());
},
Err(e) => {
eprintln!("{}", e);
return Err(e);
}
}
}
/* Read the pending orders that belong to this user into their account.
* This is currently not in use, however, if we only store a subset
* of market info in the in-mem markets, we will have to call this
* to get the full view of an account (in, say, print_user).
**/
pub fn read_account_pending_orders(user: &mut UserAccount, conn: &mut Client) {
let query_string = "\
SELECT (o.order_ID, o.symbol, o.action, o.quantity, o.filled, o.price, o.user_ID) FROM Orders o, PendingOrders p
WHERE o.order_ID = p.order_ID
AND o.user_ID =
(SELECT ID FROM Account WHERE Account.username = $1)
ORDER BY o.order_ID;";
for row in conn.query(query_string, &[&user.username]).expect("Query to fetch pending orders failed!") {
let order_id: i32 = row.get(0);
let symbol: &str = row.get(1);
let action: &str = row.get(2);
let quantity: i32 = row.get(3);
let filled: i32 = row.get(4);
let price: f64 = row.get(5);
let user_id: i32 = row.get(6);
// let time_placed: i32 = row.get(8); // <---- TODO
// let time_updated: i32 = row.get(9); // <---- TODO
// We will just re-insert everything.
let order = Order::direct(action,
symbol,
quantity,
filled,
price,
order_id,
OrderStatus::PENDING,
user_id);
user.pending_orders.insert_order(order);
}
}
/* Get this accounts executed trades from the database. */
pub fn read_account_executed_trades(user: &UserAccount, executed_trades: &mut Vec<Trade>, conn: &mut Client) {
// First, lets get trades where we had our order filled.
let query_string = "\
SELECT * FROM ExecutedTrades e
WHERE
e.filled_UID = (SELECT ID FROM Account WHERE Account.username = $1) OR
e.filler_UID = (SELECT ID FROM Account WHERE Account.username = $1)
ORDER BY e.execution_time;";
for row in conn.query(query_string, &[&user.username]).expect("Query to fetch executed trades failed!") {
let symbol: &str = row.get(0);
let mut action: &str = row.get(1);
let price: f64 = row.get(2);
let filled_oid: i32 = row.get(3);
let filled_uid: i32 = row.get(4);
let filler_oid: i32 = row.get(5);
let filler_uid: i32 = row.get(6);
let exchanged: i32 = row.get(7);
let execution_time:
DateTime<Utc> = row.get(8);
// Switch the action because we were the filler.
if user.id.unwrap() == filler_uid {
match action {
"BUY" => action = "SELL",
"SELL" => action = "BUY",
_ => ()
}
}
let trade = Trade::direct(symbol,
action,
price,
filled_oid,
filled_uid,
filler_oid,
filler_uid,
exchanged,
execution_time);
executed_trades.push(trade);
}
}
/* TODO: Accept time periods!
* Read past trades for the requested security from the database.
* Returns Some(Vec<Trade>) if there are trades,
* otherwise, returns None.
**/
pub fn read_trades(symbol: &String, conn: &mut Client) -> Option<Vec<Trade>> {
let mut trades: Vec<Trade> = Vec::new();
for row in conn.query("SELECT * FROM ExecutedTrades WHERE symbol=$1",
&[&symbol.as_str()]).expect("Read Trades query (History) failed!") {
let symbol: &str = row.get(0);
let action: &str = row.get(1);
let price: f64 = row.get(2);
let filled_oid: i32 = row.get(3);
let filled_uid: i32 = row.get(4);
let filler_oid: i32 = row.get(5);
let filler_uid: i32 = row.get(6);
let exchanged: i32 = row.get(7);
let execution_time:
DateTime<Utc> = row.get(8);
trades.push(Trade::direct(symbol,
action,
price,
filled_oid,
filled_uid,
filler_oid,
filler_uid,
exchanged,
execution_time
));
}
return Some(trades);
}
/* TODO: Doesn't get called ever, since we have a perfect market view.
* If we cap the number of orders visible to a market in the program,
* keeping the rest in the DB, then we may trigger this code.
*
* Returns Some(action) if the user owns this pending order, else None. */
pub fn read_match_pending_order(user_id: i32, order_id: i32, conn: &mut Client) -> Option<String> {
let result = conn.query("\
SELECT action
FROM Orders o, PendingOrders p
WHERE p.order_id = $1
AND o.order_id = p.order_id
AND o.user_id = $2;", &[&order_id, &user_id]);
match result {
Ok(rows) => {
if rows.len() == 1 {
for row in rows {
let action: &str = row.get(0);
return Some(action.to_string().clone());
}
}
},
Err(e) => {
eprintln!("{:?}", e);
panic!("Match pending order query failed!");
}
}
return None;
}
/* TODO: Prepared statement.
* Write a new user to the database. */
pub fn write_insert_new_account(account: &UserAccount, conn: &mut Client) -> Result<(), ()> {
let now = Utc::now();
let query_string = "INSERT INTO Account (ID, username, password, register_time) VALUES ($1, $2, $3, $4);";
match conn.execute(query_string, &[&account.id.unwrap(), &account.username, &account.password, &now]) {
Ok(_) => return Ok(()),
Err(e) => {
eprintln!("{:?}", e);
return Err(());
}
}
}
/* Returns true if the market exists in our database, false otherwise. */
pub fn read_market_exists(market: &String, conn: &mut Client) -> bool {
let query_string = "SELECT symbol from Markets where symbol=$1;";
match conn.query(query_string, &[market]) {
Ok(result) => {
if result.len() == 1 {
return true;
}
},
Err(e) => {
eprintln!("{}", e);
panic!("Something went wrong while querying the database for the market symbol.");
}
}
return false;
}
/* Reads the first `n` market symbols into the symbol_vec Vector.
* `n` is described by the capacity of symbol_vec.
*
* This can *almost* be thought of as a 'populate' function, however
* we need to call it each time we run a simulation.
*/
pub fn read_exchange_markets_simulations(symbol_vec: &mut Vec<String>, conn: &mut Client) {
let mut i = 0;
let limit = symbol_vec.capacity();
for row in conn.query("SELECT symbol FROM Markets;", &[])
.expect("Something went wrong in the query.") {
let symbol: &str = row.get(0);
symbol_vec.push(symbol.to_string());
i += 1;
if i == limit {
return;
}
}
}
/******************************************************************************************************
* Buffered Writes API *
******************************************************************************************************/
/* TODO: Multi-row updates if possible.
**/
pub fn insert_buffered_orders(orders: &Vec<DatabaseReadyOrder>, conn: &mut Client) {
let start = Instant::now();
// TIMING
let query_exec_time = Instant::now();
let mut transaction = conn.transaction().expect("Failed to initiate transaction!");
// Everything is to be updated
let query_string = "\
INSERT INTO Orders
(order_ID, symbol, action, quantity, filled, price, user_ID, status, time_placed, time_updated)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);";
let statement = match transaction.prepare(&query_string) {
Ok(stmt) => stmt,
Err(e) => {
eprintln!("{}", e);
panic!("Failed to insert new orders to database!");
}
};
for order in orders {
let status: String = format!["{:?}", order.status.unwrap()];
transaction.execute(&statement, &[ &order.order_id,
&order.symbol,
&order.action,
&order.quantity,
&order.filled,
&order.price,
&order.user_id,
&status,
&order.time_placed,
&order.time_updated
]).expect("FAILED TO EXEC INSERT ORDERS");
}
transaction.commit().expect("Failed to commit buffered order insert transaction.");
let query_exec_time = query_exec_time.elapsed().as_millis();
let end = start.elapsed().as_millis();
println!("
Insert New Order Speed
\tQuery Build Time Elapsed: DNE
\tQuery Exec Time Elapsed: {} ms
\tTotal Time Elapsed: {} ms
\tTotal Items Inserted: {}
", query_exec_time, end, orders.len());
}
/* TODO: Multi-row updates if possible.
**/
pub fn update_buffered_orders(orders: &Vec<DatabaseReadyOrder>, conn: &mut Client) {
let start = Instant::now();
// 3 types of updates
// 1. filled & time updated
// 2. status & time updated
// 3. filled & status & time updated
let filled_string = "UPDATE Orders SET filled=$1, time_updated=$2 WHERE order_id=$3;";
let status_string = "UPDATE Orders SET status=$1, time_updated=$2 WHERE order_id=$3;";
let total_string = "UPDATE Orders SET filled=$1, status=$2, time_updated=$3 WHERE order_id=$4;";
// TIMING
let query_exec_time = Instant::now();
let mut transaction = conn.transaction().expect("Failed to initiate transaction!");
let filled_stmt = match transaction.prepare(&filled_string) {
Ok(stmt) => stmt,
Err(e) => {
eprintln!("{}", e);
panic!("Failed to create 'filled' prepared statement for updated orders!");
}
};
let status_stmt = match transaction.prepare(&status_string) {
Ok(stmt) => stmt,
Err(e) => {
eprintln!("{}", e);
panic!("Failed to create 'status' prepared statement for updated orders!");
}
};
let total_stmt = match transaction.prepare(&total_string) {
Ok(stmt) => stmt,
Err(e) => {
eprintln!("{}", e);
panic!("Failed to create 'total' prepared statement for updated orders!");
}
};
enum UpdateType {
FILL,
STATUS,
TOTAL,
NONE
}
for order in orders {
let mut order_type = UpdateType::NONE;
let mut filled: Option<i32> = None;
let mut status: Option<String> = None;
if let Some(amount_filled) = order.filled {
filled = Some(amount_filled);
order_type = UpdateType::FILL;
}
if let Some(new_status) = order.status {
status = Some(format!["{:?}", new_status]);
if let UpdateType::FILL = order_type {
order_type = UpdateType::TOTAL;
} else {
order_type = UpdateType::STATUS;
}
}
if let Some(update_time) = order.time_updated {
let time_updated = update_time;
match order_type {
UpdateType::FILL => {
let filled = filled.unwrap();
if let Err(e) = transaction.execute(&filled_stmt, &[&filled, &time_updated, &order.order_id.unwrap()]) {
eprintln!("{}", e);
panic!("Something went wrong with the buffered order update statement.");
}
},
UpdateType::STATUS => {
let status = status.unwrap();
if let Err(e) = transaction.execute(&status_stmt, &[&status, &time_updated, &order.order_id.unwrap()]) {
eprintln!("{}", e);
panic!("Something went wrong with the buffered order update statement.");
}
},
UpdateType::TOTAL => {
let filled = filled.unwrap();
let status = status.unwrap();
if let Err(e) = transaction.execute(&total_stmt, &[&filled, &status, &time_updated, &order.order_id.unwrap()]) {
eprintln!("{}", e);
panic!("Something went wrong with the buffered order update statement.");
}
},
UpdateType::NONE => panic!("Our updated order has no data??")
}
};
}
transaction.commit().expect("Failed to commit buffered order update transaction.");
let query_exec_time = query_exec_time.elapsed().as_millis();
let end = start.elapsed().as_millis();
println!("\
Update Known Order Speed
\tQuery Build Time Elapsed: DNE
\tQuery Exec Time Elapsed: {} ms
\tTotal Time Elapsed: {} ms
\tTotal Items Updated: {}
", query_exec_time, end, orders.len());
}
/* Performs 1 or more multi-row inserts to the pending orders table in
* a single transaction. */
pub fn insert_buffered_pending(pending: &Vec<i32>, conn: &mut Client) {
// TIMING
let start = Instant::now();
let mut queries: Vec<String> = Vec::new();
let query_string = String::from("INSERT INTO PendingOrders (order_id) VALUES ");
queries.push(query_string.clone());
let mut counter = 0;
let cap = 100000; // Number of rows per statement
let mut index = 0;
// TIMING
let query_build_time = Instant::now();
for order in pending {
if counter < cap {
queries[index].push_str(&format!["({}),\n", order].as_str());
} else {
// 1. Terminate the current query
queries[index].pop();
queries[index].pop();
queries[index].push(';');
// 2 Update counters
index += 1;
counter = 0;
// 3. Start new query
queries.push(query_string.clone());
queries[index].push_str(&format!["({}),\n", order].as_str());
}
counter += 1;
}
queries[index].pop();
queries[index].pop();
queries[index].push(';');
let query_build_time = query_build_time.elapsed().as_millis();
let query_exec_time = Instant::now();
let mut transaction = conn.transaction().expect("Failed to initiate transaction!");
// If we have a statement to execute...
if (counter != 0) || (queries.len() > 1) {
// Execute all the queries.
for query in &queries {
if let Err(e) = transaction.execute(query.as_str(), &[]) {
eprintln!("{}", e);
eprintln!("{}", query);
panic!("Failed to exec insert PendingOrders.");
}
}
}
transaction.commit().expect("Failed to commit buffered pending order insert transaction.");
let query_exec_time = query_exec_time.elapsed().as_millis();
let end = start.elapsed().as_millis();
println!("\
Insert Pending Speed (n = 100000)
\tQuery Build Time Elapsed: {} ms
\tQuery Exec Time Elapsed: {} ms
\tTotal Time Elapsed: {} ms
\tTotal Items Inserted: {}
", query_build_time, query_exec_time, end, pending.len());
}
/* Performs 1 or more multi-row delete queries to the pending orders table
* in a single transaction. */
pub fn delete_buffered_pending(pending: &Vec<i32>, conn: &mut Client) {
let start = Instant::now();
// TIMING
let query_build_time = Instant::now();
let mut queries: Vec<String> = Vec::new();
let query_string = String::from("DELETE FROM PendingOrders WHERE order_id IN ( ");
queries.push(query_string.clone());
let mut counter = 0;
let cap = 100000; // Number of rows per statement
let mut index = 0;
for order in pending {
if counter < cap {
queries[index].push_str(&format!["{}, ", order].as_str());
} else {
// 1. Terminate the current query
queries[index].pop();
queries[index].pop();
queries[index].push_str(");");
// 2 Update counters
index += 1;
counter = 0;
// 3. Start new query
queries.push(query_string.clone());
queries[index].push_str(&format!["{}, ", order].as_str());
}
counter += 1;
}
queries[index].pop();
queries[index].pop();
queries[index].push_str(");");
let query_build_time = query_build_time.elapsed().as_millis();
let query_exec_time = Instant::now();
let mut transaction = conn.transaction().expect("Failed to initiate transaction!");
// If we have a statement to execute...
if (counter != 0) || (queries.len() > 1) {
for query in &queries {
if let Err(e) = transaction.execute(query.as_str(), &[]) {
eprintln!("{}", e);
eprintln!("{}", query);
panic!("Failed to exec delete pending query.");
}
}
}
transaction.commit().expect("Failed to commit buffered pending order delete transaction.");
let query_exec_time = query_exec_time.elapsed().as_millis();
let end = start.elapsed().as_millis();
println!("\
Delete Pending Speed (n = 100000)
\tQuery Build Time Elapsed: {} ms
\tQuery Exec Time Elapsed: {} ms
\tTotal Time Elapsed: {} ms
\tTotal Items Deleted: {}
", query_build_time, query_exec_time, end, pending.len());
}
/* A single query to set or update the exchange stats. */
pub fn update_total_orders(total_orders: i32, conn: &mut Client) {
let mut transaction = conn.transaction().expect("Failed to initiate transaction!");
// Update the exchange total orders
let query_string = "\
INSERT INTO ExchangeStats
VALUES (1, $1)
ON CONFLICT (key) DO
UPDATE SET total_orders=$1;";
if let Err(e) = transaction.execute(query_string, &[&total_orders]) {
eprintln!("{:?}", e);
panic!("Something went wrong with the exchange total orders update query!");
};
transaction.commit().expect("Failed to commit buffered total order update transaction.");
}
/* Performs an update per modified market in a single transaction.
* This table always stays small, so the cost of 1 connection per
* query is negligible, especially when using a prepared statement.
**/
pub fn update_buffered_markets(markets: &Vec<SecStat>, conn: &mut Client) {
let mut transaction = conn.transaction().expect("Failed to initiate transaction!");
let query_string = "\
UPDATE Markets
SET (total_buys, total_sells, filled_buys, filled_sells, latest_price) =
($1, $2, $3, $4, $5)
WHERE Markets.symbol = $6;";
let statement = match transaction.prepare(&query_string) {
Ok(stmt) => stmt,
Err(e) => {
eprintln!("{}", e);
panic!("Failed to insert new orders to database!");
}
};
for market in markets {
transaction.execute(&statement, &[ &market.total_buys,
&market.total_sells,
&market.filled_buys,
&market.filled_sells,
&market.last_price,
&market.symbol
]).expect("FAILED TO EXEC UPDATE MARKETS");
}
transaction.commit().expect("Failed to commit buffered market update transaction.");
}
/* Performs 1 or more multi-row inserts in a single transaction. */
pub fn insert_buffered_trades(trades: &Vec<Trade>, conn: &mut Client) {
// TIMING
let start = Instant::now();
let mut queries: Vec<String> = Vec::new();
let query_string = String::from("INSERT INTO ExecutedTrades
(symbol, action, price, filled_OID, filled_UID, filler_OID, filler_UID, exchanged, execution_time)
VALUES ");
queries.push(query_string.clone());
let mut counter = 0;
let cap = 100000; // Number of rows per statement
let mut index = 0;
// TIMING
let query_build_time = Instant::now();
for trade in trades {
if counter < cap {
queries[index].push_str(&format!["('{}', '{}', {}, {}, {}, {}, {}, {}, '{}'),\n", trade.symbol,
trade.action,
trade.price,
trade.filled_oid,
trade.filled_uid,
trade.filler_oid,
trade.filler_uid,
trade.exchanged,
trade.execution_time.to_rfc3339()].as_str());
} else {
// 1. Terminate the current query
queries[index].pop();
queries[index].pop();
queries[index].push(';');
// 2 Update counters
index += 1;
counter = 0;
// 3. Start new query
queries.push(query_string.clone());
queries[index].push_str(&format!["('{}', '{}', {}, {}, {}, {}, {}, {}, '{}'),\n", trade.symbol,
trade.action,
trade.price,
trade.filled_oid,
trade.filled_uid,
trade.filler_oid,
trade.filler_uid,
trade.exchanged,
trade.execution_time.to_rfc3339()].as_str());
}
counter += 1;
}
queries[index].pop();
queries[index].pop();
queries[index].push(';');
// TIMING
let query_build_time = query_build_time.elapsed().as_millis();
let query_exec_time = Instant::now();
let mut transaction = conn.transaction().expect("Failed to initiate transaction!");
// If we have a statement to execute...
if (counter != 0) || (queries.len() > 1) {
for query in &queries {
if let Err(e) = transaction.execute(query.as_str(), &[]) {
eprintln!("{}", e);
eprintln!("{}", query);
panic!("Failed to exec insert ExecutedTrades.");
}
}
}
transaction.commit().expect("Failed to commit buffered trade insert transaction.");
let query_exec_time = query_exec_time.elapsed().as_millis();
let end = start.elapsed().as_millis();
println!("\
Insert Executed Trade Speed (n = 100000)
\tQuery Build Time Elapsed: {} ms
\tQuery Exec Time Elapsed: {} ms
\tTotal Time Elapsed: {} ms
\tTotal Items Inserted: {}
", query_build_time, query_exec_time, end, trades.len());
}
|
#[cfg(not(feature = "lib"))]
use std::{cell::RefCell, rc::Rc};
#[cfg(feature = "lib")]
use mold::Path;
use mold::Raster;
#[cfg(not(feature = "lib"))]
use crate::{Context, PathId, RasterId};
#[derive(Debug)]
pub struct RasterBuilder {
#[cfg(not(feature = "lib"))]
context: Rc<RefCell<Context>>,
#[cfg(not(feature = "lib"))]
paths_transforms: Vec<(PathId, [f32; 9])>,
#[cfg(feature = "lib")]
paths_transforms: Vec<(Path, [f32; 9])>,
}
impl RasterBuilder {
#[cfg(feature = "lib")]
pub fn new() -> Self {
Self {
paths_transforms: vec![],
}
}
#[cfg(not(feature = "lib"))]
pub fn new(context: Rc<RefCell<Context>>) -> Self {
Self {
context,
paths_transforms: vec![],
}
}
#[cfg(feature = "lib")]
pub fn push_path(&mut self, path: Path, transform: &[f32; 9]) {
self.paths_transforms.push((path, *transform));
}
#[cfg(not(feature = "lib"))]
pub fn push_path(&mut self, path: PathId, transform: &[f32; 9]) {
self.paths_transforms.push((path, *transform));
}
#[cfg(feature = "lib")]
pub fn build(&mut self) -> Raster {
let raster = Raster::from_paths_and_transforms(
self.paths_transforms
.iter()
.map(|(path, transform)| (path, transform)),
);
self.paths_transforms.clear();
raster
}
#[cfg(not(feature = "lib"))]
pub fn build(&mut self) -> RasterId {
let mut context = self.context.borrow_mut();
let raster = Raster::from_paths_and_transforms(
self.paths_transforms
.iter()
.map(|(path, transform)| (context.get_path(*path), transform)),
);
let id = context.insert_raster(raster.inner);
self.paths_transforms.clear();
id
}
}
|
//! A glyph embedded in another glyph.
use druid::kurbo::Affine;
use druid::Data;
use norad::GlyphName;
use crate::design_space::DVec2;
use crate::point::EntityId;
#[derive(Debug, Data, Clone)]
pub struct Component {
pub base: GlyphName,
#[data(same_fn = "affine_eq")]
pub transform: Affine,
pub id: EntityId,
}
fn affine_eq(left: &Affine, right: &Affine) -> bool {
left.as_coeffs() == right.as_coeffs()
}
impl Component {
pub fn from_norad(src: &norad::glyph::Component) -> Self {
let base = src.base.clone();
let transform = src.transform.into();
let id = EntityId::next();
Component {
base,
transform,
id,
}
}
pub fn to_norad(&self) -> norad::glyph::Component {
let base = self.base.clone();
let transform = self.transform.into();
norad::glyph::Component::new(base, transform, None, None)
}
pub(crate) fn nudge(&mut self, delta: DVec2) {
let [a, b, c, d, t_x, t_y] = self.transform.as_coeffs();
self.transform = Affine::new([a, b, c, d, t_x + delta.x, t_y + delta.y]);
}
}
|
use async_graphql_parser::*;
#[test]
fn test_recursion_limit() {
let depth = 65;
let field = "a {".repeat(depth) + &"}".repeat(depth);
let query = format!("query {{ {} }}", field.replace("{}", "{b}"));
assert_eq!(
parse_query(query).unwrap_err(),
Error::RecursionLimitExceeded
);
}
#[test]
fn test_issue_1039() {
let query = r#"
fragment onboardingFull on OnboardingState {
license
}
query globalConfig {
globalConfig {
onboarding {
...onboardingFull
}
}
}
"#;
parse_query(query).unwrap();
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::ISC {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTPWM0R {
bits: bool,
}
impl PWM_ISC_INTPWM0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTPWM0W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTPWM0W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTPWM1R {
bits: bool,
}
impl PWM_ISC_INTPWM1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTPWM1W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTPWM1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTPWM2R {
bits: bool,
}
impl PWM_ISC_INTPWM2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTPWM2W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTPWM2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTPWM3R {
bits: bool,
}
impl PWM_ISC_INTPWM3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTPWM3W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTPWM3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTFAULT0R {
bits: bool,
}
impl PWM_ISC_INTFAULT0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTFAULT0W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTFAULT0W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 16);
self.w.bits |= ((value as u32) & 1) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTFAULT1R {
bits: bool,
}
impl PWM_ISC_INTFAULT1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTFAULT1W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTFAULT1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 17);
self.w.bits |= ((value as u32) & 1) << 17;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTFAULT2R {
bits: bool,
}
impl PWM_ISC_INTFAULT2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTFAULT2W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTFAULT2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 18);
self.w.bits |= ((value as u32) & 1) << 18;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_ISC_INTFAULT3R {
bits: bool,
}
impl PWM_ISC_INTFAULT3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_ISC_INTFAULT3W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_ISC_INTFAULT3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 19);
self.w.bits |= ((value as u32) & 1) << 19;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - PWM0 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm0(&self) -> PWM_ISC_INTPWM0R {
let bits = ((self.bits >> 0) & 1) != 0;
PWM_ISC_INTPWM0R { bits }
}
#[doc = "Bit 1 - PWM1 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm1(&self) -> PWM_ISC_INTPWM1R {
let bits = ((self.bits >> 1) & 1) != 0;
PWM_ISC_INTPWM1R { bits }
}
#[doc = "Bit 2 - PWM2 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm2(&self) -> PWM_ISC_INTPWM2R {
let bits = ((self.bits >> 2) & 1) != 0;
PWM_ISC_INTPWM2R { bits }
}
#[doc = "Bit 3 - PWM3 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm3(&self) -> PWM_ISC_INTPWM3R {
let bits = ((self.bits >> 3) & 1) != 0;
PWM_ISC_INTPWM3R { bits }
}
#[doc = "Bit 16 - FAULT0 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault0(&self) -> PWM_ISC_INTFAULT0R {
let bits = ((self.bits >> 16) & 1) != 0;
PWM_ISC_INTFAULT0R { bits }
}
#[doc = "Bit 17 - FAULT1 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault1(&self) -> PWM_ISC_INTFAULT1R {
let bits = ((self.bits >> 17) & 1) != 0;
PWM_ISC_INTFAULT1R { bits }
}
#[doc = "Bit 18 - FAULT2 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault2(&self) -> PWM_ISC_INTFAULT2R {
let bits = ((self.bits >> 18) & 1) != 0;
PWM_ISC_INTFAULT2R { bits }
}
#[doc = "Bit 19 - FAULT3 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault3(&self) -> PWM_ISC_INTFAULT3R {
let bits = ((self.bits >> 19) & 1) != 0;
PWM_ISC_INTFAULT3R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - PWM0 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm0(&mut self) -> _PWM_ISC_INTPWM0W {
_PWM_ISC_INTPWM0W { w: self }
}
#[doc = "Bit 1 - PWM1 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm1(&mut self) -> _PWM_ISC_INTPWM1W {
_PWM_ISC_INTPWM1W { w: self }
}
#[doc = "Bit 2 - PWM2 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm2(&mut self) -> _PWM_ISC_INTPWM2W {
_PWM_ISC_INTPWM2W { w: self }
}
#[doc = "Bit 3 - PWM3 Interrupt Status"]
#[inline(always)]
pub fn pwm_isc_intpwm3(&mut self) -> _PWM_ISC_INTPWM3W {
_PWM_ISC_INTPWM3W { w: self }
}
#[doc = "Bit 16 - FAULT0 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault0(&mut self) -> _PWM_ISC_INTFAULT0W {
_PWM_ISC_INTFAULT0W { w: self }
}
#[doc = "Bit 17 - FAULT1 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault1(&mut self) -> _PWM_ISC_INTFAULT1W {
_PWM_ISC_INTFAULT1W { w: self }
}
#[doc = "Bit 18 - FAULT2 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault2(&mut self) -> _PWM_ISC_INTFAULT2W {
_PWM_ISC_INTFAULT2W { w: self }
}
#[doc = "Bit 19 - FAULT3 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_isc_intfault3(&mut self) -> _PWM_ISC_INTFAULT3W {
_PWM_ISC_INTFAULT3W { w: self }
}
}
|
use std::collections::HashMap;
use std::fs;
pub struct Index {
hashed_executables: HashMap<String, String>,
}
impl Index {
pub fn new(paths: &[&str]) -> Index {
Index {
hashed_executables: build_index(paths),
}
}
pub fn lookup(&self, key: &str) -> Option<&String> {
self.hashed_executables.get(key)
}
}
fn build_index(paths: &[&str]) -> HashMap<String, String> {
let mut hashed_executables = HashMap::new();
for path in paths.iter() {
let dir = match fs::read_dir(path) {
Ok(dir) => dir,
Err(_) => continue,
};
for entry in dir {
let item = match entry {
Ok(item) => item,
Err(_) => continue,
};
let filename = match item.file_name().into_string() {
Ok(name) => name,
Err(_) => continue,
};
let filepath = match item.path().into_os_string().into_string() {
Ok(path) => path,
Err(_) => continue,
};
hashed_executables.insert(filename, filepath);
debug!("Found: {:?}", item.path())
}
}
hashed_executables
}
|
pub struct Solution;
impl Solution {
pub fn compare_version(version1: String, version2: String) -> i32 {
let nums1 = version1
.split('.')
.map(|s| s.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
let nums2 = version2
.split('.')
.map(|s| s.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
for i in 0..nums1.len().max(nums2.len()) {
let num1 = if i < nums1.len() { nums1[i] } else { 0 };
let num2 = if i < nums2.len() { nums2[i] } else { 0 };
if num1 < num2 {
return -1;
}
if num1 > num2 {
return 1;
}
}
return 0;
}
}
#[test]
fn test0165() {
fn case(version1: &str, version2: &str, want: i32) {
assert_eq!(
Solution::compare_version(version1.to_string(), version2.to_string()),
want
);
}
case("0.1", "1.1", -1);
case("1.0.1", "1", 1);
case("7.5.2.4", "7.5.3", -1);
case("1.01", "1.001", 0);
case("1.0", "1.0.0", 0);
}
|
#[doc = "Reader of register MPCBB2_VCTR22"]
pub type R = crate::R<u32, super::MPCBB2_VCTR22>;
#[doc = "Writer for register MPCBB2_VCTR22"]
pub type W = crate::W<u32, super::MPCBB2_VCTR22>;
#[doc = "Register MPCBB2_VCTR22 `reset()`'s with value 0xffff_ffff"]
impl crate::ResetValue for super::MPCBB2_VCTR22 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xffff_ffff
}
}
#[doc = "Reader of field `B704`"]
pub type B704_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B704`"]
pub struct B704_W<'a> {
w: &'a mut W,
}
impl<'a> B704_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 `B705`"]
pub type B705_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B705`"]
pub struct B705_W<'a> {
w: &'a mut W,
}
impl<'a> B705_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 `B706`"]
pub type B706_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B706`"]
pub struct B706_W<'a> {
w: &'a mut W,
}
impl<'a> B706_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 `B707`"]
pub type B707_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B707`"]
pub struct B707_W<'a> {
w: &'a mut W,
}
impl<'a> B707_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 `B708`"]
pub type B708_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B708`"]
pub struct B708_W<'a> {
w: &'a mut W,
}
impl<'a> B708_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 `B709`"]
pub type B709_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B709`"]
pub struct B709_W<'a> {
w: &'a mut W,
}
impl<'a> B709_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 `B710`"]
pub type B710_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B710`"]
pub struct B710_W<'a> {
w: &'a mut W,
}
impl<'a> B710_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 `B711`"]
pub type B711_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B711`"]
pub struct B711_W<'a> {
w: &'a mut W,
}
impl<'a> B711_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 `B712`"]
pub type B712_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B712`"]
pub struct B712_W<'a> {
w: &'a mut W,
}
impl<'a> B712_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 `B713`"]
pub type B713_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B713`"]
pub struct B713_W<'a> {
w: &'a mut W,
}
impl<'a> B713_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 `B714`"]
pub type B714_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B714`"]
pub struct B714_W<'a> {
w: &'a mut W,
}
impl<'a> B714_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 `B715`"]
pub type B715_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B715`"]
pub struct B715_W<'a> {
w: &'a mut W,
}
impl<'a> B715_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 `B716`"]
pub type B716_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B716`"]
pub struct B716_W<'a> {
w: &'a mut W,
}
impl<'a> B716_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 `B717`"]
pub type B717_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B717`"]
pub struct B717_W<'a> {
w: &'a mut W,
}
impl<'a> B717_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 `B718`"]
pub type B718_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B718`"]
pub struct B718_W<'a> {
w: &'a mut W,
}
impl<'a> B718_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 `B719`"]
pub type B719_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B719`"]
pub struct B719_W<'a> {
w: &'a mut W,
}
impl<'a> B719_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
}
}
#[doc = "Reader of field `B720`"]
pub type B720_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B720`"]
pub struct B720_W<'a> {
w: &'a mut W,
}
impl<'a> B720_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 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `B721`"]
pub type B721_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B721`"]
pub struct B721_W<'a> {
w: &'a mut W,
}
impl<'a> B721_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 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `B722`"]
pub type B722_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B722`"]
pub struct B722_W<'a> {
w: &'a mut W,
}
impl<'a> B722_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 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `B723`"]
pub type B723_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B723`"]
pub struct B723_W<'a> {
w: &'a mut W,
}
impl<'a> B723_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 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `B724`"]
pub type B724_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B724`"]
pub struct B724_W<'a> {
w: &'a mut W,
}
impl<'a> B724_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 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `B725`"]
pub type B725_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B725`"]
pub struct B725_W<'a> {
w: &'a mut W,
}
impl<'a> B725_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 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `B726`"]
pub type B726_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B726`"]
pub struct B726_W<'a> {
w: &'a mut W,
}
impl<'a> B726_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 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `B727`"]
pub type B727_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B727`"]
pub struct B727_W<'a> {
w: &'a mut W,
}
impl<'a> B727_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 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `B728`"]
pub type B728_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B728`"]
pub struct B728_W<'a> {
w: &'a mut W,
}
impl<'a> B728_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 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `B729`"]
pub type B729_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B729`"]
pub struct B729_W<'a> {
w: &'a mut W,
}
impl<'a> B729_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 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `B730`"]
pub type B730_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B730`"]
pub struct B730_W<'a> {
w: &'a mut W,
}
impl<'a> B730_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 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `B731`"]
pub type B731_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B731`"]
pub struct B731_W<'a> {
w: &'a mut W,
}
impl<'a> B731_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 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `B732`"]
pub type B732_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B732`"]
pub struct B732_W<'a> {
w: &'a mut W,
}
impl<'a> B732_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 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `B733`"]
pub type B733_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B733`"]
pub struct B733_W<'a> {
w: &'a mut W,
}
impl<'a> B733_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 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `B734`"]
pub type B734_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B734`"]
pub struct B734_W<'a> {
w: &'a mut W,
}
impl<'a> B734_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 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `B735`"]
pub type B735_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B735`"]
pub struct B735_W<'a> {
w: &'a mut W,
}
impl<'a> B735_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 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - B704"]
#[inline(always)]
pub fn b704(&self) -> B704_R {
B704_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - B705"]
#[inline(always)]
pub fn b705(&self) -> B705_R {
B705_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - B706"]
#[inline(always)]
pub fn b706(&self) -> B706_R {
B706_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - B707"]
#[inline(always)]
pub fn b707(&self) -> B707_R {
B707_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - B708"]
#[inline(always)]
pub fn b708(&self) -> B708_R {
B708_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - B709"]
#[inline(always)]
pub fn b709(&self) -> B709_R {
B709_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - B710"]
#[inline(always)]
pub fn b710(&self) -> B710_R {
B710_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - B711"]
#[inline(always)]
pub fn b711(&self) -> B711_R {
B711_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - B712"]
#[inline(always)]
pub fn b712(&self) -> B712_R {
B712_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - B713"]
#[inline(always)]
pub fn b713(&self) -> B713_R {
B713_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - B714"]
#[inline(always)]
pub fn b714(&self) -> B714_R {
B714_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - B715"]
#[inline(always)]
pub fn b715(&self) -> B715_R {
B715_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - B716"]
#[inline(always)]
pub fn b716(&self) -> B716_R {
B716_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - B717"]
#[inline(always)]
pub fn b717(&self) -> B717_R {
B717_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - B718"]
#[inline(always)]
pub fn b718(&self) -> B718_R {
B718_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - B719"]
#[inline(always)]
pub fn b719(&self) -> B719_R {
B719_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - B720"]
#[inline(always)]
pub fn b720(&self) -> B720_R {
B720_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - B721"]
#[inline(always)]
pub fn b721(&self) -> B721_R {
B721_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - B722"]
#[inline(always)]
pub fn b722(&self) -> B722_R {
B722_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - B723"]
#[inline(always)]
pub fn b723(&self) -> B723_R {
B723_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - B724"]
#[inline(always)]
pub fn b724(&self) -> B724_R {
B724_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - B725"]
#[inline(always)]
pub fn b725(&self) -> B725_R {
B725_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - B726"]
#[inline(always)]
pub fn b726(&self) -> B726_R {
B726_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - B727"]
#[inline(always)]
pub fn b727(&self) -> B727_R {
B727_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - B728"]
#[inline(always)]
pub fn b728(&self) -> B728_R {
B728_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - B729"]
#[inline(always)]
pub fn b729(&self) -> B729_R {
B729_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - B730"]
#[inline(always)]
pub fn b730(&self) -> B730_R {
B730_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - B731"]
#[inline(always)]
pub fn b731(&self) -> B731_R {
B731_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - B732"]
#[inline(always)]
pub fn b732(&self) -> B732_R {
B732_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - B733"]
#[inline(always)]
pub fn b733(&self) -> B733_R {
B733_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - B734"]
#[inline(always)]
pub fn b734(&self) -> B734_R {
B734_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - B735"]
#[inline(always)]
pub fn b735(&self) -> B735_R {
B735_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - B704"]
#[inline(always)]
pub fn b704(&mut self) -> B704_W {
B704_W { w: self }
}
#[doc = "Bit 1 - B705"]
#[inline(always)]
pub fn b705(&mut self) -> B705_W {
B705_W { w: self }
}
#[doc = "Bit 2 - B706"]
#[inline(always)]
pub fn b706(&mut self) -> B706_W {
B706_W { w: self }
}
#[doc = "Bit 3 - B707"]
#[inline(always)]
pub fn b707(&mut self) -> B707_W {
B707_W { w: self }
}
#[doc = "Bit 4 - B708"]
#[inline(always)]
pub fn b708(&mut self) -> B708_W {
B708_W { w: self }
}
#[doc = "Bit 5 - B709"]
#[inline(always)]
pub fn b709(&mut self) -> B709_W {
B709_W { w: self }
}
#[doc = "Bit 6 - B710"]
#[inline(always)]
pub fn b710(&mut self) -> B710_W {
B710_W { w: self }
}
#[doc = "Bit 7 - B711"]
#[inline(always)]
pub fn b711(&mut self) -> B711_W {
B711_W { w: self }
}
#[doc = "Bit 8 - B712"]
#[inline(always)]
pub fn b712(&mut self) -> B712_W {
B712_W { w: self }
}
#[doc = "Bit 9 - B713"]
#[inline(always)]
pub fn b713(&mut self) -> B713_W {
B713_W { w: self }
}
#[doc = "Bit 10 - B714"]
#[inline(always)]
pub fn b714(&mut self) -> B714_W {
B714_W { w: self }
}
#[doc = "Bit 11 - B715"]
#[inline(always)]
pub fn b715(&mut self) -> B715_W {
B715_W { w: self }
}
#[doc = "Bit 12 - B716"]
#[inline(always)]
pub fn b716(&mut self) -> B716_W {
B716_W { w: self }
}
#[doc = "Bit 13 - B717"]
#[inline(always)]
pub fn b717(&mut self) -> B717_W {
B717_W { w: self }
}
#[doc = "Bit 14 - B718"]
#[inline(always)]
pub fn b718(&mut self) -> B718_W {
B718_W { w: self }
}
#[doc = "Bit 15 - B719"]
#[inline(always)]
pub fn b719(&mut self) -> B719_W {
B719_W { w: self }
}
#[doc = "Bit 16 - B720"]
#[inline(always)]
pub fn b720(&mut self) -> B720_W {
B720_W { w: self }
}
#[doc = "Bit 17 - B721"]
#[inline(always)]
pub fn b721(&mut self) -> B721_W {
B721_W { w: self }
}
#[doc = "Bit 18 - B722"]
#[inline(always)]
pub fn b722(&mut self) -> B722_W {
B722_W { w: self }
}
#[doc = "Bit 19 - B723"]
#[inline(always)]
pub fn b723(&mut self) -> B723_W {
B723_W { w: self }
}
#[doc = "Bit 20 - B724"]
#[inline(always)]
pub fn b724(&mut self) -> B724_W {
B724_W { w: self }
}
#[doc = "Bit 21 - B725"]
#[inline(always)]
pub fn b725(&mut self) -> B725_W {
B725_W { w: self }
}
#[doc = "Bit 22 - B726"]
#[inline(always)]
pub fn b726(&mut self) -> B726_W {
B726_W { w: self }
}
#[doc = "Bit 23 - B727"]
#[inline(always)]
pub fn b727(&mut self) -> B727_W {
B727_W { w: self }
}
#[doc = "Bit 24 - B728"]
#[inline(always)]
pub fn b728(&mut self) -> B728_W {
B728_W { w: self }
}
#[doc = "Bit 25 - B729"]
#[inline(always)]
pub fn b729(&mut self) -> B729_W {
B729_W { w: self }
}
#[doc = "Bit 26 - B730"]
#[inline(always)]
pub fn b730(&mut self) -> B730_W {
B730_W { w: self }
}
#[doc = "Bit 27 - B731"]
#[inline(always)]
pub fn b731(&mut self) -> B731_W {
B731_W { w: self }
}
#[doc = "Bit 28 - B732"]
#[inline(always)]
pub fn b732(&mut self) -> B732_W {
B732_W { w: self }
}
#[doc = "Bit 29 - B733"]
#[inline(always)]
pub fn b733(&mut self) -> B733_W {
B733_W { w: self }
}
#[doc = "Bit 30 - B734"]
#[inline(always)]
pub fn b734(&mut self) -> B734_W {
B734_W { w: self }
}
#[doc = "Bit 31 - B735"]
#[inline(always)]
pub fn b735(&mut self) -> B735_W {
B735_W { w: self }
}
}
|
use syn::{Arm, Attribute, Expr, Local, Stmt};
use super::VecExt;
pub(crate) trait Attrs {
fn attrs(&self) -> &[Attribute];
fn any_attr(&self, ident: &str) -> bool {
self.attrs().iter().any(|attr| attr.path.is_ident(ident))
}
fn any_empty_attr(&self, ident: &str) -> bool {
self.attrs().iter().any(|attr| attr.path.is_ident(ident) && attr.tokens.is_empty())
}
}
pub(crate) trait AttrsMut: Attrs {
fn attrs_mut<T>(&mut self, f: impl FnOnce(&mut Vec<Attribute>) -> T) -> T;
fn find_remove_attr(&mut self, ident: &str) -> Option<Attribute> {
self.attrs_mut(|attrs| attrs.find_remove(|attr| attr.path.is_ident(ident)))
}
}
impl Attrs for Arm {
fn attrs(&self) -> &[Attribute] {
&self.attrs
}
}
impl AttrsMut for Arm {
fn attrs_mut<T>(&mut self, f: impl FnOnce(&mut Vec<Attribute>) -> T) -> T {
f(&mut self.attrs)
}
}
impl Attrs for Local {
fn attrs(&self) -> &[Attribute] {
&self.attrs
}
}
impl AttrsMut for Local {
fn attrs_mut<T>(&mut self, f: impl FnOnce(&mut Vec<Attribute>) -> T) -> T {
f(&mut self.attrs)
}
}
impl Attrs for Stmt {
fn attrs(&self) -> &[Attribute] {
match self {
Stmt::Expr(expr) | Stmt::Semi(expr, _) => expr.attrs(),
Stmt::Local(local) => local.attrs(),
Stmt::Item(_) => &[],
}
}
}
impl AttrsMut for Stmt {
fn attrs_mut<T>(&mut self, f: impl FnOnce(&mut Vec<Attribute>) -> T) -> T {
match self {
Stmt::Expr(expr) | Stmt::Semi(expr, _) => expr.attrs_mut(f),
Stmt::Local(local) => local.attrs_mut(f),
Stmt::Item(_) => f(&mut Vec::new()),
}
}
}
macro_rules! attrs_impl {
($($Expr:ident($Struct:ident),)*) => {
impl Attrs for Expr {
fn attrs(&self) -> &[Attribute] {
match self {
$(Expr::$Expr(syn::$Struct { attrs, .. }))|* => &attrs,
_ => &[],
}
}
}
impl AttrsMut for Expr {
fn attrs_mut<T>(&mut self, f: impl FnOnce(&mut Vec<Attribute>) -> T) -> T {
match self {
$(Expr::$Expr(syn::$Struct { attrs, .. }))|* => f(attrs),
_ => f(&mut Vec::new()),
}
}
}
};
}
attrs_impl! {
Array(ExprArray),
Assign(ExprAssign),
AssignOp(ExprAssignOp),
Async(ExprAsync),
Await(ExprAwait),
Binary(ExprBinary),
Block(ExprBlock),
Box(ExprBox),
Break(ExprBreak),
Call(ExprCall),
Cast(ExprCast),
Closure(ExprClosure),
Continue(ExprContinue),
Field(ExprField),
ForLoop(ExprForLoop),
Group(ExprGroup),
If(ExprIf),
Index(ExprIndex),
Let(ExprLet),
Lit(ExprLit),
Loop(ExprLoop),
Macro(ExprMacro),
Match(ExprMatch),
MethodCall(ExprMethodCall),
Paren(ExprParen),
Path(ExprPath),
Range(ExprRange),
Reference(ExprReference),
Repeat(ExprRepeat),
Return(ExprReturn),
Struct(ExprStruct),
Try(ExprTry),
TryBlock(ExprTryBlock),
Tuple(ExprTuple),
Type(ExprType),
Unary(ExprUnary),
Unsafe(ExprUnsafe),
While(ExprWhile),
Yield(ExprYield),
}
|
use super::*;
#[test]
fn with_number_second_returns_first() {
run!(
|arc_process| {
(
strategy::term::atom(),
strategy::term::is_number(arc_process.clone()),
)
},
|(first, second)| {
prop_assert_eq!(result(first, second), first);
Ok(())
},
);
}
#[test]
fn with_lesser_atom_returns_first() {
max(|_, _| Atom::str_to_term("eirst"), First);
}
#[test]
fn with_same_atom_returns_first() {
max(|first, _| first, First);
}
#[test]
fn with_same_atom_value_returns_first() {
max(|_, _| Atom::str_to_term("first"), First);
}
#[test]
fn with_greater_atom_returns_second() {
max(|_, _| Atom::str_to_term("second"), Second);
}
#[test]
fn without_number_or_atom_returns_second() {
run!(
|arc_process| {
(
strategy::term::atom(),
strategy::term(arc_process.clone())
.prop_filter("Right cannot be a number or atom", |right| {
!(right.is_atom() || right.is_number())
}),
)
},
|(first, second)| {
prop_assert_eq!(result(first, second), second);
Ok(())
},
);
}
fn max<R>(second: R, which: FirstSecond)
where
R: FnOnce(Term, &Process) -> Term,
{
super::max(|_| Atom::str_to_term("first"), second, which);
}
|
#[doc = "Reader of register D1CFGR"]
pub type R = crate::R<u32, super::D1CFGR>;
#[doc = "Writer for register D1CFGR"]
pub type W = crate::W<u32, super::D1CFGR>;
#[doc = "Register D1CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::D1CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "D1 domain AHB prescaler\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum HPRE_A {
#[doc = "0: sys_ck not divided"]
DIV1 = 0,
#[doc = "8: sys_ck divided by 2"]
DIV2 = 8,
#[doc = "9: sys_ck divided by 4"]
DIV4 = 9,
#[doc = "10: sys_ck divided by 8"]
DIV8 = 10,
#[doc = "11: sys_ck divided by 16"]
DIV16 = 11,
#[doc = "12: sys_ck divided by 64"]
DIV64 = 12,
#[doc = "13: sys_ck divided by 128"]
DIV128 = 13,
#[doc = "14: sys_ck divided by 256"]
DIV256 = 14,
#[doc = "15: sys_ck divided by 512"]
DIV512 = 15,
}
impl From<HPRE_A> for u8 {
#[inline(always)]
fn from(variant: HPRE_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `HPRE`"]
pub type HPRE_R = crate::R<u8, HPRE_A>;
impl HPRE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, HPRE_A> {
use crate::Variant::*;
match self.bits {
0 => Val(HPRE_A::DIV1),
8 => Val(HPRE_A::DIV2),
9 => Val(HPRE_A::DIV4),
10 => Val(HPRE_A::DIV8),
11 => Val(HPRE_A::DIV16),
12 => Val(HPRE_A::DIV64),
13 => Val(HPRE_A::DIV128),
14 => Val(HPRE_A::DIV256),
15 => Val(HPRE_A::DIV512),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `DIV1`"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == HPRE_A::DIV1
}
#[doc = "Checks if the value of the field is `DIV2`"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == HPRE_A::DIV2
}
#[doc = "Checks if the value of the field is `DIV4`"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == HPRE_A::DIV4
}
#[doc = "Checks if the value of the field is `DIV8`"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == HPRE_A::DIV8
}
#[doc = "Checks if the value of the field is `DIV16`"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == HPRE_A::DIV16
}
#[doc = "Checks if the value of the field is `DIV64`"]
#[inline(always)]
pub fn is_div64(&self) -> bool {
*self == HPRE_A::DIV64
}
#[doc = "Checks if the value of the field is `DIV128`"]
#[inline(always)]
pub fn is_div128(&self) -> bool {
*self == HPRE_A::DIV128
}
#[doc = "Checks if the value of the field is `DIV256`"]
#[inline(always)]
pub fn is_div256(&self) -> bool {
*self == HPRE_A::DIV256
}
#[doc = "Checks if the value of the field is `DIV512`"]
#[inline(always)]
pub fn is_div512(&self) -> bool {
*self == HPRE_A::DIV512
}
}
#[doc = "Write proxy for field `HPRE`"]
pub struct HPRE_W<'a> {
w: &'a mut W,
}
impl<'a> HPRE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HPRE_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "sys_ck not divided"]
#[inline(always)]
pub fn div1(self) -> &'a mut W {
self.variant(HPRE_A::DIV1)
}
#[doc = "sys_ck divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut W {
self.variant(HPRE_A::DIV2)
}
#[doc = "sys_ck divided by 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut W {
self.variant(HPRE_A::DIV4)
}
#[doc = "sys_ck divided by 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut W {
self.variant(HPRE_A::DIV8)
}
#[doc = "sys_ck divided by 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut W {
self.variant(HPRE_A::DIV16)
}
#[doc = "sys_ck divided by 64"]
#[inline(always)]
pub fn div64(self) -> &'a mut W {
self.variant(HPRE_A::DIV64)
}
#[doc = "sys_ck divided by 128"]
#[inline(always)]
pub fn div128(self) -> &'a mut W {
self.variant(HPRE_A::DIV128)
}
#[doc = "sys_ck divided by 256"]
#[inline(always)]
pub fn div256(self) -> &'a mut W {
self.variant(HPRE_A::DIV256)
}
#[doc = "sys_ck divided by 512"]
#[inline(always)]
pub fn div512(self) -> &'a mut W {
self.variant(HPRE_A::DIV512)
}
#[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
}
}
#[doc = "D1 domain APB3 prescaler\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum D1PPRE_A {
#[doc = "0: rcc_hclk not divided"]
DIV1 = 0,
#[doc = "4: rcc_hclk divided by 2"]
DIV2 = 4,
#[doc = "5: rcc_hclk divided by 4"]
DIV4 = 5,
#[doc = "6: rcc_hclk divided by 8"]
DIV8 = 6,
#[doc = "7: rcc_hclk divided by 16"]
DIV16 = 7,
}
impl From<D1PPRE_A> for u8 {
#[inline(always)]
fn from(variant: D1PPRE_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `D1PPRE`"]
pub type D1PPRE_R = crate::R<u8, D1PPRE_A>;
impl D1PPRE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, D1PPRE_A> {
use crate::Variant::*;
match self.bits {
0 => Val(D1PPRE_A::DIV1),
4 => Val(D1PPRE_A::DIV2),
5 => Val(D1PPRE_A::DIV4),
6 => Val(D1PPRE_A::DIV8),
7 => Val(D1PPRE_A::DIV16),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `DIV1`"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == D1PPRE_A::DIV1
}
#[doc = "Checks if the value of the field is `DIV2`"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == D1PPRE_A::DIV2
}
#[doc = "Checks if the value of the field is `DIV4`"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == D1PPRE_A::DIV4
}
#[doc = "Checks if the value of the field is `DIV8`"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == D1PPRE_A::DIV8
}
#[doc = "Checks if the value of the field is `DIV16`"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == D1PPRE_A::DIV16
}
}
#[doc = "Write proxy for field `D1PPRE`"]
pub struct D1PPRE_W<'a> {
w: &'a mut W,
}
impl<'a> D1PPRE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: D1PPRE_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_hclk not divided"]
#[inline(always)]
pub fn div1(self) -> &'a mut W {
self.variant(D1PPRE_A::DIV1)
}
#[doc = "rcc_hclk divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut W {
self.variant(D1PPRE_A::DIV2)
}
#[doc = "rcc_hclk divided by 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut W {
self.variant(D1PPRE_A::DIV4)
}
#[doc = "rcc_hclk divided by 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut W {
self.variant(D1PPRE_A::DIV8)
}
#[doc = "rcc_hclk divided by 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut W {
self.variant(D1PPRE_A::DIV16)
}
#[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 << 4)) | (((value as u32) & 0x07) << 4);
self.w
}
}
#[doc = "D1 domain Core prescaler"]
pub type D1CPRE_A = HPRE_A;
#[doc = "Reader of field `D1CPRE`"]
pub type D1CPRE_R = crate::R<u8, HPRE_A>;
#[doc = "Write proxy for field `D1CPRE`"]
pub struct D1CPRE_W<'a> {
w: &'a mut W,
}
impl<'a> D1CPRE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: D1CPRE_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "sys_ck not divided"]
#[inline(always)]
pub fn div1(self) -> &'a mut W {
self.variant(HPRE_A::DIV1)
}
#[doc = "sys_ck divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut W {
self.variant(HPRE_A::DIV2)
}
#[doc = "sys_ck divided by 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut W {
self.variant(HPRE_A::DIV4)
}
#[doc = "sys_ck divided by 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut W {
self.variant(HPRE_A::DIV8)
}
#[doc = "sys_ck divided by 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut W {
self.variant(HPRE_A::DIV16)
}
#[doc = "sys_ck divided by 64"]
#[inline(always)]
pub fn div64(self) -> &'a mut W {
self.variant(HPRE_A::DIV64)
}
#[doc = "sys_ck divided by 128"]
#[inline(always)]
pub fn div128(self) -> &'a mut W {
self.variant(HPRE_A::DIV128)
}
#[doc = "sys_ck divided by 256"]
#[inline(always)]
pub fn div256(self) -> &'a mut W {
self.variant(HPRE_A::DIV256)
}
#[doc = "sys_ck divided by 512"]
#[inline(always)]
pub fn div512(self) -> &'a mut W {
self.variant(HPRE_A::DIV512)
}
#[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
}
}
impl R {
#[doc = "Bits 0:3 - D1 domain AHB prescaler"]
#[inline(always)]
pub fn hpre(&self) -> HPRE_R {
HPRE_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:6 - D1 domain APB3 prescaler"]
#[inline(always)]
pub fn d1ppre(&self) -> D1PPRE_R {
D1PPRE_R::new(((self.bits >> 4) & 0x07) as u8)
}
#[doc = "Bits 8:11 - D1 domain Core prescaler"]
#[inline(always)]
pub fn d1cpre(&self) -> D1CPRE_R {
D1CPRE_R::new(((self.bits >> 8) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - D1 domain AHB prescaler"]
#[inline(always)]
pub fn hpre(&mut self) -> HPRE_W {
HPRE_W { w: self }
}
#[doc = "Bits 4:6 - D1 domain APB3 prescaler"]
#[inline(always)]
pub fn d1ppre(&mut self) -> D1PPRE_W {
D1PPRE_W { w: self }
}
#[doc = "Bits 8:11 - D1 domain Core prescaler"]
#[inline(always)]
pub fn d1cpre(&mut self) -> D1CPRE_W {
D1CPRE_W { w: self }
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::_2_FLTSRC0 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_FLTSRC0_FAULT0R {
bits: bool,
}
impl PWM_2_FLTSRC0_FAULT0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_FLTSRC0_FAULT0W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_FLTSRC0_FAULT0W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_FLTSRC0_FAULT1R {
bits: bool,
}
impl PWM_2_FLTSRC0_FAULT1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_FLTSRC0_FAULT1W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_FLTSRC0_FAULT1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_FLTSRC0_FAULT2R {
bits: bool,
}
impl PWM_2_FLTSRC0_FAULT2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_FLTSRC0_FAULT2W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_FLTSRC0_FAULT2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_FLTSRC0_FAULT3R {
bits: bool,
}
impl PWM_2_FLTSRC0_FAULT3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_FLTSRC0_FAULT3W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_FLTSRC0_FAULT3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Fault0 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault0(&self) -> PWM_2_FLTSRC0_FAULT0R {
let bits = ((self.bits >> 0) & 1) != 0;
PWM_2_FLTSRC0_FAULT0R { bits }
}
#[doc = "Bit 1 - Fault1 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault1(&self) -> PWM_2_FLTSRC0_FAULT1R {
let bits = ((self.bits >> 1) & 1) != 0;
PWM_2_FLTSRC0_FAULT1R { bits }
}
#[doc = "Bit 2 - Fault2 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault2(&self) -> PWM_2_FLTSRC0_FAULT2R {
let bits = ((self.bits >> 2) & 1) != 0;
PWM_2_FLTSRC0_FAULT2R { bits }
}
#[doc = "Bit 3 - Fault3 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault3(&self) -> PWM_2_FLTSRC0_FAULT3R {
let bits = ((self.bits >> 3) & 1) != 0;
PWM_2_FLTSRC0_FAULT3R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Fault0 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault0(&mut self) -> _PWM_2_FLTSRC0_FAULT0W {
_PWM_2_FLTSRC0_FAULT0W { w: self }
}
#[doc = "Bit 1 - Fault1 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault1(&mut self) -> _PWM_2_FLTSRC0_FAULT1W {
_PWM_2_FLTSRC0_FAULT1W { w: self }
}
#[doc = "Bit 2 - Fault2 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault2(&mut self) -> _PWM_2_FLTSRC0_FAULT2W {
_PWM_2_FLTSRC0_FAULT2W { w: self }
}
#[doc = "Bit 3 - Fault3 Input"]
#[inline(always)]
pub fn pwm_2_fltsrc0_fault3(&mut self) -> _PWM_2_FLTSRC0_FAULT3W {
_PWM_2_FLTSRC0_FAULT3W { w: self }
}
}
|
use std::fmt::{Debug, Formatter};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::auth::{TokenResponseData, AUTH_CONTENT_TYPE};
use crate::{Authenticator, Authorized, utils};
use async_trait::async_trait;
use log::warn;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
use reqwest::{Body, Client};
use crate::error::http_error::IntoResult;
use crate::error::internal_error::InternalError;
use crate::error::Error;
#[derive(Clone)]
pub struct CodeAuthenticator {
/// Token
pub token: Option<String>,
/// When does it expire
pub expiration_time: Option<u128>,
/// Refresh token
pub refresh_token: Option<String>,
/// Client ID
pub(crate) client_id: String,
/// Client Secret
pub(crate) client_secret: String,
/// Authorization code
authorization_code: String,
/// Redirect URI
redirect_uri: String,
}
impl Debug for CodeAuthenticator {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"[CodeAuthenticator] Token Defined: {} Expires At {} And Refrsh Token Defined: {}",
self.token.is_some(),
self.expiration_time.unwrap_or(0),
self.refresh_token.is_some()
)
}
}
impl CodeAuthenticator {
/// Creates a new Authenticator by Code Flow
///
/// Note: The "client_secret" for non-confidential clients (Installed APPs) is an empty string.
#[allow(clippy::new_ret_no_self)]
pub fn new<S: Into<String>>(
client_id: S,
client_secret: S,
authorization_code: S,
redirect_uri: S,
) -> CodeAuthenticator {
CodeAuthenticator {
token: None,
expiration_time: None,
refresh_token: None,
client_id: client_id.into(),
client_secret: client_secret.into(),
authorization_code: authorization_code.into(),
redirect_uri: redirect_uri.into(),
}
}
/// This method does not check the values of the parameters.
///
/// Information of the data can be found [here](https://github.com/reddit-archive/reddit/wiki/OAuth2).
pub fn generate_authorization_url(
client_id: impl AsRef<str>,
redirect_uri: impl AsRef<str>,
state: impl AsRef<str>,
duration: impl AsRef<str>,
scope: Vec<&str>,
) -> String {
format!(
"https://www.reddit.com/api/v1/authorize?client_id={}&response_type=code&state={}&redirect_uri={}&duration={}&scope={}",
client_id.as_ref(),
state.as_ref(),
redirect_uri.as_ref(),
duration.as_ref(),
scope.join(",")
)
}
}
#[async_trait(?Send)]
impl Authenticator for CodeAuthenticator {
/// Logs in
async fn login(&mut self, client: &Client, user_agent: &str) -> Result<bool, Error> {
let url = "https://www.reddit.com/api/v1/access_token";
let body = format!(
"grant_type=authorization_code&code={}&redirect_uri={}",
&self.authorization_code.trim_end_matches("#_"),
&self.redirect_uri
);
let mut header = HeaderMap::new();
header.insert(
AUTHORIZATION,
HeaderValue::from_str(&*format!(
"Basic {}",
utils::basic_header(&self.client_id, &self.client_secret)
))
.unwrap(),
);
header.insert(USER_AGENT, HeaderValue::from_str(user_agent).unwrap());
header.insert(
CONTENT_TYPE,
HeaderValue::from_str("application/x-www-form-urlencoded").unwrap(),
);
let response = client
.post(url)
.body(Body::from(body))
.headers(header)
.send()
.await
.map_err(InternalError::from)?;
response.status().into_result()?;
let token: TokenResponseData = response.json().await?;
self.token = Some(token.access_token);
let x = token.expires_in * 1000;
let x1 = (x as u128)
+ SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();
self.expiration_time = Some(x1);
if !token.refresh_token.is_empty() {
self.refresh_token = Some(token.refresh_token);
}
return Ok(true);
}
/// Logs out
async fn logout(&mut self, client: &Client, user_agent: &str) -> Result<(), Error> {
let url = "https://www.reddit.com/api/v1/revoke_token";
let body = if let Some(refresh_token) = &self.refresh_token {
format!("token={}&token_type_hint=refresh_token", refresh_token)
} else if let Some(token) = self.token.as_ref() {
format!("token={}&token_type_hint=access_token", token)
} else {
// No token to revoke
return Ok(());
};
let mut header = HeaderMap::new();
header.insert(USER_AGENT, HeaderValue::from_str(user_agent).unwrap());
header.insert(CONTENT_TYPE, AUTH_CONTENT_TYPE.clone());
let response = client
.post(url)
.body(Body::from(body))
.headers(header)
.send()
.await?;
response.status().into_result()?;
self.token = None;
self.expiration_time = None;
self.refresh_token = None;
Ok(())
}
/// Returns true if successful
async fn token_refresh(&mut self, client: &Client, user_agent: &str) -> Result<bool, Error> {
let url = "https://www.reddit.com/api/v1/access_token";
let body = format!(
"grant_type=refresh_token&refresh_token={}",
&self.refresh_token.to_owned().unwrap()
);
let mut header = HeaderMap::new();
header.insert(
AUTHORIZATION,
HeaderValue::from_str(&*format!(
"Basic {}",
utils::basic_header(&self.client_id, &self.client_secret)
))
.unwrap(),
);
header.insert(USER_AGENT, HeaderValue::from_str(user_agent).unwrap());
header.insert(
CONTENT_TYPE,
HeaderValue::from_str("application/x-www-form-urlencoded").unwrap(),
);
let response = client
.post(url)
.body(Body::from(body))
.headers(header)
.send()
.await
.map_err(InternalError::from)?;
response.status().into_result()?;
let token: TokenResponseData = response.json().await?;
self.token = Some(token.access_token);
let x = token.expires_in * 1000;
let x1 = (x as u128)
+ SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();
self.expiration_time = Some(x1);
return Ok(true);
}
// headers
fn headers(&self, headers: &mut HeaderMap) {
if let Some(token) = self.token.as_ref() {
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", token)).unwrap(),
);
} else {
warn!("No token found");
}
}
/// True
fn oauth(&self) -> bool {
true
}
/// Validates Time
fn needs_token_refresh(&self) -> bool {
let i = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();
if self.refresh_token.is_some() {
if self.expiration_time.is_none() {
true
} else {
i >= self.expiration_time.unwrap()
}
} else {
false
}
}
fn get_refresh_token(&self) -> Option<String> {
self.refresh_token.to_owned()
}
}
impl Authorized for CodeAuthenticator {}
|
use std::env;
fn main() {
println!("--output--");
let path = env::var("CARGO_EVAL_SCRIPT_PATH").expect("CSSP wasn't set");
assert!(path.ends_with("script-cs-env.rs"));
assert_eq!(env::var("CARGO_EVAL_SAFE_NAME"), Ok("script-cs-env".into()));
assert_eq!(env::var("CARGO_EVAL_PKG_NAME"), Ok("script-cs-env".into()));
let base_path = env::var("CARGO_EVAL_BASE_PATH").expect("CSBP wasn't set");
assert!(base_path.ends_with("data"));
println!("Ok");
}
|
use std::fmt::{self, Display};
use crate::mysql::protocol::{ColumnDefinition, FieldFlags, TypeId};
use crate::types::TypeInfo;
#[derive(Clone, Debug, Default)]
pub struct MySqlTypeInfo {
pub(crate) id: TypeId,
pub(crate) is_unsigned: bool,
pub(crate) is_binary: bool,
pub(crate) char_set: u16,
}
impl MySqlTypeInfo {
pub(crate) const fn new(id: TypeId) -> Self {
Self {
id,
is_unsigned: false,
is_binary: true,
char_set: 0,
}
}
pub(crate) const fn unsigned(id: TypeId) -> Self {
Self {
id,
is_unsigned: true,
is_binary: false,
char_set: 0,
}
}
#[doc(hidden)]
pub const fn r#enum() -> Self {
Self {
id: TypeId::ENUM,
is_unsigned: false,
is_binary: false,
char_set: 0,
}
}
pub(crate) fn from_nullable_column_def(def: &ColumnDefinition) -> Self {
Self {
id: def.type_id,
is_unsigned: def.flags.contains(FieldFlags::UNSIGNED),
is_binary: def.flags.contains(FieldFlags::BINARY),
char_set: def.char_set,
}
}
pub(crate) fn from_column_def(def: &ColumnDefinition) -> Option<Self> {
if def.type_id == TypeId::NULL {
return None;
}
Some(Self::from_nullable_column_def(def))
}
#[doc(hidden)]
pub fn type_feature_gate(&self) -> Option<&'static str> {
match self.id {
TypeId::DATE | TypeId::TIME | TypeId::DATETIME | TypeId::TIMESTAMP => Some("chrono"),
_ => None,
}
}
}
impl Display for MySqlTypeInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.id {
TypeId::NULL => f.write_str("NULL"),
TypeId::TINY_INT if self.is_unsigned => f.write_str("TINYINT UNSIGNED"),
TypeId::SMALL_INT if self.is_unsigned => f.write_str("SMALLINT UNSIGNED"),
TypeId::INT if self.is_unsigned => f.write_str("INT UNSIGNED"),
TypeId::BIG_INT if self.is_unsigned => f.write_str("BIGINT UNSIGNED"),
TypeId::TINY_INT => f.write_str("TINYINT"),
TypeId::SMALL_INT => f.write_str("SMALLINT"),
TypeId::INT => f.write_str("INT"),
TypeId::BIG_INT => f.write_str("BIGINT"),
TypeId::FLOAT => f.write_str("FLOAT"),
TypeId::DOUBLE => f.write_str("DOUBLE"),
TypeId::CHAR if self.is_binary => f.write_str("BINARY"),
TypeId::VAR_CHAR if self.is_binary => f.write_str("VARBINARY"),
TypeId::TEXT if self.is_binary => f.write_str("BLOB"),
TypeId::CHAR => f.write_str("CHAR"),
TypeId::VAR_CHAR => f.write_str("VARCHAR"),
TypeId::TEXT => f.write_str("TEXT"),
TypeId::DATE => f.write_str("DATE"),
TypeId::TIME => f.write_str("TIME"),
TypeId::DATETIME => f.write_str("DATETIME"),
TypeId::TIMESTAMP => f.write_str("TIMESTAMP"),
TypeId::NEWDECIMAL => f.write_str("NEWDECIMAL"),
id => write!(f, "<{:#x}>", id.0),
}
}
}
impl PartialEq<MySqlTypeInfo> for MySqlTypeInfo {
fn eq(&self, other: &MySqlTypeInfo) -> bool {
match self.id {
TypeId::VAR_CHAR
| TypeId::TEXT
| TypeId::CHAR
| TypeId::TINY_BLOB
| TypeId::MEDIUM_BLOB
| TypeId::LONG_BLOB
| TypeId::ENUM
if (self.is_binary == other.is_binary)
&& match other.id {
TypeId::VAR_CHAR
| TypeId::TEXT
| TypeId::CHAR
| TypeId::TINY_BLOB
| TypeId::MEDIUM_BLOB
| TypeId::LONG_BLOB
| TypeId::ENUM => true,
_ => false,
} =>
{
return true;
}
_ => {}
}
if self.id.0 != other.id.0 {
return false;
}
match self.id {
TypeId::TINY_INT | TypeId::SMALL_INT | TypeId::INT | TypeId::BIG_INT => {
return self.is_unsigned == other.is_unsigned;
}
_ => {}
}
true
}
}
impl TypeInfo for MySqlTypeInfo {
fn compatible(&self, other: &Self) -> bool {
// NOTE: MySQL is weakly typed so much of this may be surprising to a Rust developer.
if self.id == TypeId::NULL || other.id == TypeId::NULL {
// NULL is the "bottom" type
// If the user is trying to select into a non-Option, we catch this soon with an
// UnexpectedNull error message
return true;
}
match self.id {
// All integer types should be considered compatible
TypeId::TINY_INT | TypeId::SMALL_INT | TypeId::INT | TypeId::BIG_INT
if (self.is_unsigned == other.is_unsigned)
&& match other.id {
TypeId::TINY_INT | TypeId::SMALL_INT | TypeId::INT | TypeId::BIG_INT => {
true
}
_ => false,
} =>
{
true
}
// All textual types should be considered compatible
TypeId::VAR_CHAR
| TypeId::TEXT
| TypeId::CHAR
| TypeId::TINY_BLOB
| TypeId::MEDIUM_BLOB
| TypeId::LONG_BLOB
if match other.id {
TypeId::VAR_CHAR
| TypeId::TEXT
| TypeId::CHAR
| TypeId::TINY_BLOB
| TypeId::MEDIUM_BLOB
| TypeId::LONG_BLOB => true,
_ => false,
} =>
{
true
}
// Enums are considered compatible with other text/binary types
TypeId::ENUM
if match other.id {
TypeId::VAR_CHAR
| TypeId::TEXT
| TypeId::CHAR
| TypeId::TINY_BLOB
| TypeId::MEDIUM_BLOB
| TypeId::LONG_BLOB
| TypeId::ENUM => true,
_ => false,
} =>
{
true
}
TypeId::VAR_CHAR
| TypeId::TEXT
| TypeId::CHAR
| TypeId::TINY_BLOB
| TypeId::MEDIUM_BLOB
| TypeId::LONG_BLOB
| TypeId::ENUM
if other.id == TypeId::ENUM =>
{
true
}
// FLOAT is compatible with DOUBLE
TypeId::FLOAT | TypeId::DOUBLE
if match other.id {
TypeId::FLOAT | TypeId::DOUBLE => true,
_ => false,
} =>
{
true
}
// DATETIME is compatible with TIMESTAMP
TypeId::DATETIME | TypeId::TIMESTAMP
if match other.id {
TypeId::DATETIME | TypeId::TIMESTAMP => true,
_ => false,
} =>
{
true
}
_ => self.eq(other),
}
}
}
|
#![allow(unused_imports)]
/// CD3DX12 Helper functions from here:
/// https://github.com/microsoft/DirectX-Graphics-Samples/blob/master/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h
use bindings::{
Windows::Win32::Graphics::Direct3D11::*, Windows::Win32::Graphics::Direct3D12::*,
Windows::Win32::Graphics::DirectComposition::*, Windows::Win32::Graphics::Dxgi::*,
Windows::Win32::Graphics::Gdi::*, Windows::Win32::Graphics::Hlsl::*,
Windows::Win32::System::SystemServices::*, Windows::Win32::System::Threading::*,
Windows::Win32::UI::DisplayDevices::*, Windows::Win32::UI::MenusAndResources::*,
Windows::Win32::UI::WindowsAndMessaging::*,
};
use directx_math::*;
use std::{convert::TryInto, ffi::CString, mem};
use std::{ffi::c_void, ptr::null_mut};
use windows::{Abi, Interface};
pub struct Buffers {
pub upload_buffer: ID3D12Resource,
pub gpu_buffer: ID3D12Resource,
}
/// Creates a gpu buffer from given data
///
/// Returns also upload buffer that must be kept alive until the command list is
/// executed.
pub fn create_default_buffer(
device: &ID3D12Device,
list: &ID3D12GraphicsCommandList,
data: &[u8],
) -> ::windows::Result<Buffers> {
let default_buffer = unsafe {
device.CreateCommittedResource::<ID3D12Resource>(
&cd3dx12_heap_properties_with_type(D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE,
&cd3dx12_resource_desc_buffer(data.len() as _, None, None),
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COMMON,
null_mut(),
)
}?;
let upload_buffer = unsafe {
device.CreateCommittedResource::<ID3D12Resource>(
&cd3dx12_heap_properties_with_type(D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE,
&cd3dx12_resource_desc_buffer(data.len() as _, None, None),
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ,
null_mut(),
)
}?;
unsafe {
list.ResourceBarrier(
1,
&cd3dx12_resource_barrier_transition(
&default_buffer,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COPY_DEST,
None,
None,
),
);
}
update_subresources_stack_alloc::<1>(
&list,
&default_buffer,
&upload_buffer,
0,
0,
&mut [D3D12_SUBRESOURCE_DATA {
pData: data.as_ptr() as *mut _,
RowPitch: data.len() as _,
SlicePitch: data.len() as _,
..Default::default()
}],
)?;
unsafe {
list.ResourceBarrier(
1,
&cd3dx12_resource_barrier_transition(
&default_buffer,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ,
None,
None,
),
);
}
Ok(Buffers {
gpu_buffer: default_buffer,
upload_buffer,
})
}
// #[derive(Debug)]
// pub struct ConstantBuffer<T: Sized> {
// upload_buffer: UploadBuffer<T>,
// shader_visibility: D3D12_SHADER_VISIBILITY,
// }
// TODO: UploadBuffer but like array with MutIndex or Index impl
#[derive(Debug)]
pub struct UploadBuffer<T: Sized> {
buffer: ID3D12Resource,
aligned_size: usize,
gpu_memory_ptr: *mut T,
}
impl<T: Sized> UploadBuffer<T> {
pub fn new(device: &ID3D12Device, init_data: &T) -> ::windows::Result<UploadBuffer<T>> {
unsafe {
let value_size = std::mem::size_of::<T>();
// TODO: Alignment size is required only true for constant buffers
let aligned_size = (value_size + 255) & !255;
// Generic way to create upload buffer and get address:
let buffer = device
.CreateCommittedResource::<ID3D12Resource>(
&cd3dx12_heap_properties_with_type(D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE,
&cd3dx12_resource_desc_buffer(aligned_size as _, None, None),
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ,
std::ptr::null(),
)
.expect("Unable to create constant buffer resource");
// Notice that the memory location is left mapped
let mut gpu_memory_ptr = null_mut::<T>();
buffer
.Map(
0,
&D3D12_RANGE { Begin: 0, End: 0 },
&mut gpu_memory_ptr as *mut *mut _ as *mut *mut _,
)
.ok()
.expect("Unable to get memory location for constant buffer");
std::ptr::copy_nonoverlapping(init_data, gpu_memory_ptr, 1);
Ok(UploadBuffer {
aligned_size,
buffer,
gpu_memory_ptr,
})
}
}
pub fn update(&mut self, value: &T) {
unsafe {
std::ptr::copy_nonoverlapping(value, self.gpu_memory_ptr, 1);
}
}
pub fn gpu_virtual_address(&self) -> u64 {
unsafe { self.buffer.GetGPUVirtualAddress() }
}
pub fn create_constant_buffer_view(
&self,
device: &ID3D12Device,
cbv_heap: &ID3D12DescriptorHeap,
) {
// TODO: Should I instead create and output ID3D12DescriptorHeap?
unsafe {
device.CreateConstantBufferView(
&D3D12_CONSTANT_BUFFER_VIEW_DESC {
BufferLocation: self.gpu_virtual_address(),
SizeInBytes: self.aligned_size as _,
},
cbv_heap.GetCPUDescriptorHandleForHeapStart(),
);
}
}
}
impl<T> Drop for UploadBuffer<T> {
fn drop(&mut self) {
unsafe {
self.buffer.Unmap(0, std::ptr::null());
}
}
}
pub fn create_upload_buffer(
device: &ID3D12Device,
data: &[u8],
) -> ::windows::Result<ID3D12Resource> {
unsafe {
let props = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_UPLOAD,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY::D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
CreationNodeMask: 1,
VisibleNodeMask: 1,
MemoryPoolPreference: D3D12_MEMORY_POOL::D3D12_MEMORY_POOL_UNKNOWN,
};
let desc = D3D12_RESOURCE_DESC {
Alignment: 0,
Flags: D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_NONE,
Dimension: D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_BUFFER,
DepthOrArraySize: 1,
Format: DXGI_FORMAT::DXGI_FORMAT_UNKNOWN,
Height: 1,
Width: data.len() as u64,
Layout: D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
};
let resource = device.CreateCommittedResource::<ID3D12Resource>(
&props,
D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE,
&desc,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ,
null_mut(),
)?;
let mut gpu_data: *mut u8 = null_mut();
resource
.Map(
0,
&D3D12_RANGE { Begin: 0, End: 0 },
&mut gpu_data as *mut *mut _ as *mut *mut _,
)
.ok()?;
if gpu_data.is_null() {
panic!("Failed to map");
}
std::ptr::copy_nonoverlapping(data.as_ptr(), gpu_data, data.len());
// Debug, if you want to see what was copied
// let gpu_slice = std::slice::from_raw_parts(gpu_triangle, 3);
// println!("{:?}", cpu_triangle);
// println!("{:?}", gpu_slice);
resource.Unmap(0, null_mut());
Ok(resource)
}
}
pub fn cd3dx12_heap_properties_with_type(heap_type: D3D12_HEAP_TYPE) -> D3D12_HEAP_PROPERTIES {
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L423-L433
D3D12_HEAP_PROPERTIES {
Type: heap_type,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY::D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
MemoryPoolPreference: D3D12_MEMORY_POOL::D3D12_MEMORY_POOL_UNKNOWN,
CreationNodeMask: 1,
VisibleNodeMask: 1,
}
}
pub const fn cd3dx12_depth_stencil_desc_default() -> D3D12_DEPTH_STENCIL_DESC {
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L177-L189
D3D12_DEPTH_STENCIL_DESC {
DepthEnable: BOOL(1),
DepthWriteMask: D3D12_DEPTH_WRITE_MASK::D3D12_DEPTH_WRITE_MASK_ALL,
DepthFunc: D3D12_COMPARISON_FUNC::D3D12_COMPARISON_FUNC_LESS,
StencilEnable: BOOL(0),
StencilReadMask: D3D12_DEFAULT_STENCIL_READ_MASK as _,
StencilWriteMask: D3D12_DEFAULT_STENCIL_WRITE_MASK as _,
FrontFace: D3D12_DEPTH_STENCILOP_DESC {
StencilDepthFailOp: D3D12_STENCIL_OP::D3D12_STENCIL_OP_KEEP,
StencilFailOp: D3D12_STENCIL_OP::D3D12_STENCIL_OP_KEEP,
StencilPassOp: D3D12_STENCIL_OP::D3D12_STENCIL_OP_KEEP,
StencilFunc: D3D12_COMPARISON_FUNC::D3D12_COMPARISON_FUNC_ALWAYS,
},
BackFace: D3D12_DEPTH_STENCILOP_DESC {
StencilDepthFailOp: D3D12_STENCIL_OP::D3D12_STENCIL_OP_KEEP,
StencilFailOp: D3D12_STENCIL_OP::D3D12_STENCIL_OP_KEEP,
StencilPassOp: D3D12_STENCIL_OP::D3D12_STENCIL_OP_KEEP,
StencilFunc: D3D12_COMPARISON_FUNC::D3D12_COMPARISON_FUNC_ALWAYS,
},
}
}
pub fn cd3dx12_blend_desc_default() -> D3D12_BLEND_DESC {
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L323-L338
D3D12_BLEND_DESC {
AlphaToCoverageEnable: BOOL(0),
IndependentBlendEnable: BOOL(0),
RenderTarget: (0..D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT)
.map(|_| D3D12_RENDER_TARGET_BLEND_DESC {
BlendEnable: false.into(),
LogicOpEnable: false.into(),
DestBlend: D3D12_BLEND::D3D12_BLEND_ZERO,
SrcBlend: D3D12_BLEND::D3D12_BLEND_ZERO,
DestBlendAlpha: D3D12_BLEND::D3D12_BLEND_ONE,
SrcBlendAlpha: D3D12_BLEND::D3D12_BLEND_ONE,
BlendOp: D3D12_BLEND_OP::D3D12_BLEND_OP_ADD,
LogicOp: D3D12_LOGIC_OP::D3D12_LOGIC_OP_NOOP,
BlendOpAlpha: D3D12_BLEND_OP::D3D12_BLEND_OP_ADD,
RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE::D3D12_COLOR_WRITE_ENABLE_ALL.0
as _,
})
.collect::<Vec<_>>()
.as_slice()
.try_into()
.unwrap(),
}
}
pub fn cd3dx12_rasterizer_desc_default() -> D3D12_RASTERIZER_DESC {
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L349-L359
D3D12_RASTERIZER_DESC {
FillMode: D3D12_FILL_MODE::D3D12_FILL_MODE_SOLID,
CullMode: D3D12_CULL_MODE::D3D12_CULL_MODE_BACK,
FrontCounterClockwise: false.into(),
DepthBias: D3D12_DEFAULT_DEPTH_BIAS as _,
DepthBiasClamp: D3D12_DEFAULT_DEPTH_BIAS_CLAMP,
SlopeScaledDepthBias: D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS,
DepthClipEnable: true.into(),
MultisampleEnable: false.into(),
AntialiasedLineEnable: false.into(),
ForcedSampleCount: 0,
ConservativeRaster:
D3D12_CONSERVATIVE_RASTERIZATION_MODE::D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF,
}
}
pub fn cd3dx12_resource_desc_buffer(
width: u64,
flags: Option<D3D12_RESOURCE_FLAGS>,
alignment: Option<u64>,
) -> D3D12_RESOURCE_DESC {
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/master/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L1754-L1756
// Order follows the C++ function call order
D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_BUFFER,
Alignment: alignment.unwrap_or(0),
Width: width,
DepthOrArraySize: 1,
Height: 1,
MipLevels: 1,
Format: DXGI_FORMAT::DXGI_FORMAT_UNKNOWN,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: flags.unwrap_or(D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_NONE),
}
}
pub fn cd3dx12_resource_desc_tex2d(
format: DXGI_FORMAT,
width: u64,
height: u32,
array_size: Option<u16>,
mip_levels: Option<u16>,
sample_count: Option<u32>,
sample_quality: Option<u32>,
flags: Option<D3D12_RESOURCE_FLAGS>,
layout: Option<D3D12_TEXTURE_LAYOUT>,
alignment: Option<u64>,
) -> D3D12_RESOURCE_DESC {
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L1773-L1787
D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Alignment: alignment.unwrap_or(0),
Width: width,
DepthOrArraySize: array_size.unwrap_or(1),
Height: height,
MipLevels: mip_levels.unwrap_or(0),
Format: format,
SampleDesc: DXGI_SAMPLE_DESC {
Count: sample_count.unwrap_or(1),
Quality: sample_quality.unwrap_or(0),
},
Layout: layout.unwrap_or(D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_UNKNOWN),
Flags: flags.unwrap_or(D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_NONE),
}
}
pub fn cd3dx12_resource_barrier_transition(
resource: &ID3D12Resource,
state_before: D3D12_RESOURCE_STATES,
state_after: D3D12_RESOURCE_STATES,
subresource: Option<u32>,
flags: Option<D3D12_RESOURCE_BARRIER_FLAGS>,
) -> D3D12_RESOURCE_BARRIER {
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L728-L744
let subresource = subresource.unwrap_or(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES);
let flags = flags.unwrap_or(D3D12_RESOURCE_BARRIER_FLAGS::D3D12_RESOURCE_BARRIER_FLAG_NONE);
let mut barrier = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
Flags: flags,
..unsafe { std::mem::zeroed() }
};
barrier.Anonymous.Transition.Subresource = subresource;
barrier.Anonymous.Transition.pResource = resource.abi();
barrier.Anonymous.Transition.StateBefore = state_before;
barrier.Anonymous.Transition.StateAfter = state_after;
barrier
}
pub fn cd3dx12_texture_copy_location_sub(
res: &ID3D12Resource,
sub: u32,
) -> D3D12_TEXTURE_COPY_LOCATION {
let mut res = D3D12_TEXTURE_COPY_LOCATION {
// TODO: This should be pointer, can I get rid of clone?
pResource: Some(res.clone()),
Type: D3D12_TEXTURE_COPY_TYPE::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
..unsafe { std::mem::zeroed() }
};
res.Anonymous.PlacedFootprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
..unsafe { std::mem::zeroed() }
};
res.Anonymous.SubresourceIndex = sub;
res
}
pub fn cd3dx12_texture_copy_location_footprint(
res: &ID3D12Resource,
footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
) -> D3D12_TEXTURE_COPY_LOCATION {
let mut res = D3D12_TEXTURE_COPY_LOCATION {
// TODO: This should be pointer, can I get rid of clone?
pResource: Some(res.clone()),
Type: D3D12_TEXTURE_COPY_TYPE::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
..unsafe { std::mem::zeroed() }
};
res.Anonymous.PlacedFootprint = footprint.clone();
res
}
/// WinAPI equivalent of SIZE_T(-1)
///
/// This is also bitwise not zero !0 or (in C++ ~0), not sure why the hell it's
/// written as SIZE_T(-1)
const SIZE_T_MINUS1: usize = usize::MAX;
/// Update subresources
//
/// This is mimicking stack allocation implementation
pub fn update_subresources_stack_alloc<const MAX_SUBRESOURCES: usize>(
list: &ID3D12GraphicsCommandList,
dest_resource: &ID3D12Resource,
intermediate: &ID3D12Resource,
intermediate_offset: u64,
first_subresource: u32,
p_src_data: &mut [D3D12_SUBRESOURCE_DATA; MAX_SUBRESOURCES],
) -> ::windows::Result<u64> {
update_subresources_stack_alloc_raw::<MAX_SUBRESOURCES>(
list,
dest_resource,
intermediate,
intermediate_offset,
first_subresource,
p_src_data.len() as _,
p_src_data.as_mut_ptr(),
)
}
/// Update subresources
//
/// This is mimicking stack allocation implementation
fn update_subresources_stack_alloc_raw<const MAX_SUBRESOURCES: usize>(
list: &ID3D12GraphicsCommandList,
dest_resource: &ID3D12Resource,
intermediate: &ID3D12Resource,
intermediate_offset: u64,
first_subresource: u32,
num_subresources: u32,
p_src_data: *mut D3D12_SUBRESOURCE_DATA,
) -> ::windows::Result<u64> {
// Stack alloc implementation
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L2118-L2140
let src_data = unsafe { std::slice::from_raw_parts_mut(p_src_data, num_subresources as _) };
let mut required_size = 0;
let mut layouts = [D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); MAX_SUBRESOURCES];
let mut num_rows = [0; MAX_SUBRESOURCES];
let mut row_sizes_in_bytes = [0; MAX_SUBRESOURCES];
let desc = unsafe { dest_resource.GetDesc() };
unsafe {
let dest_device = { dest_resource.GetDevice::<ID3D12Device>() }?;
dest_device.GetCopyableFootprints(
&desc,
first_subresource,
num_subresources as _,
intermediate_offset,
layouts.as_mut_ptr(),
num_rows.as_mut_ptr(),
row_sizes_in_bytes.as_mut_ptr(),
&mut required_size,
);
}
// UpdateSubresources main implementation
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L2036-L2076
// Minor validation
let intermediate_desc = unsafe { intermediate.GetDesc() };
let dest_desc = unsafe { dest_resource.GetDesc() };
if intermediate_desc.Dimension != D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_BUFFER
|| intermediate_desc.Width < (required_size + layouts[0].Offset)
|| required_size > (SIZE_T_MINUS1 as u64)
|| (dest_desc.Dimension == D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_BUFFER
&& (first_subresource != 0 || num_subresources != 1))
{
return Ok(0); // TODO: Is this actually a failure?
}
let mut p_data = null_mut();
unsafe { intermediate.Map(0, null_mut(), &mut p_data) }.ok()?;
for i in 0..(num_subresources as usize) {
if row_sizes_in_bytes[i] > (SIZE_T_MINUS1 as u64) {
return Ok(0); // TODO: Is this actually a failure?
}
let mut dest_data = D3D12_MEMCPY_DEST {
pData: ((p_data as u64) + layouts[i].Offset) as *mut _,
RowPitch: layouts[i].Footprint.RowPitch as _,
SlicePitch: (layouts[i].Footprint.RowPitch as usize) * (num_rows[i] as usize),
};
memcpy_subresource(
&mut dest_data,
&src_data[i],
row_sizes_in_bytes[i] as _,
num_rows[i],
layouts[i].Footprint.Depth,
)
}
unsafe {
intermediate.Unmap(0, null_mut());
}
if dest_desc.Dimension == D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_BUFFER {
unsafe {
list.CopyBufferRegion(
dest_resource,
0,
intermediate,
layouts[0].Offset,
layouts[0].Footprint.Width as _,
);
}
} else {
// TODO: Never tested
for i in 0..(num_subresources as usize) {
let dst =
cd3dx12_texture_copy_location_sub(&dest_resource, (i as u32) + first_subresource);
let src = cd3dx12_texture_copy_location_footprint(&intermediate, &layouts[i]);
unsafe {
list.CopyTextureRegion(&dst, 0, 0, 0, &src, null_mut());
}
}
}
return Ok(required_size);
}
/// Row-by-row memcpy
pub fn memcpy_subresource(
dest: *mut D3D12_MEMCPY_DEST,
src: *const D3D12_SUBRESOURCE_DATA,
row_size_in_bytes: usize,
num_rows: u32,
num_slices: u32,
) {
// TODO: Tested only with num_rows = 1, num_slices = 1
// unsafe {
// println!("dest {:?}", *dest);
// println!("src {:?}", *src);
// println!("num_rows {}", num_rows);
// println!("num_slices {}", num_slices);
// println!("row_size_in_bytes {}", row_size_in_bytes);
// }
// https://github.com/microsoft/DirectX-Graphics-Samples/blob/58b6bb18b928d79e5bd4e5ba53b274bdf6eb39e5/Samples/Desktop/D3D12HelloWorld/src/HelloTriangle/d3dx12.h#L1983-L2001
for z in 0..(num_slices as usize) {
unsafe {
let dest_slice = ((*dest).pData as usize) + (*dest).SlicePitch * z;
let src_slice = ((*src).pData as usize) + ((*src).SlicePitch as usize) * z;
for y in 0..(num_rows as usize) {
std::ptr::copy_nonoverlapping(
(src_slice + ((*src).RowPitch as usize) * y) as *const u8,
(dest_slice + (*dest).RowPitch * y) as *mut u8,
row_size_in_bytes,
);
}
}
}
// unsafe {
// #[derive(Debug)]
// #[repr(C)]
// struct Vertex {
// position: [f32; 3],
// color: [f32; 4],
// }
// let src_slice_view = std::slice::from_raw_parts((*src).p_data as *const Vertex, 3);
// let dest_slice_view = std::slice::from_raw_parts((*dest).p_data as *const Vertex, 3);
// println!("{:?}", src_slice_view);
// println!("{:?}", dest_slice_view);
// }
}
|
use serde::{Deserialize, Serialize};
use std::process::Command;
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ShellCmd {
cmd: String,
args: Vec<String>,
}
impl ShellCmd {
pub fn new(cmd: impl AsRef<str>, args: &[impl AsRef<str>]) -> ShellCmd {
ShellCmd {
cmd: cmd.as_ref().into(),
args: args.into_iter().map(|x| x.as_ref().into()).collect(),
}
}
pub fn execute(&self) -> String {
String::from_utf8(Command::new(&self.cmd).args(&self.args).output().unwrap().stdout)
.unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cmd_input() {
assert_eq!(
serde_json::to_string(&ShellCmd::new(
"curl",
&["https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"],
))
.unwrap(),
r#"{"cmd":"curl","args":["https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"]}"#
);
}
}
|
//! Implement INode for framebuffer
use core::any::Any;
use kernel_hal::{ColorFormat, FramebufferInfo, FRAME_BUFFER};
use rcore_fs::vfs::*;
/// framebuffer device
#[derive(Default)]
pub struct Fbdev;
impl INode for Fbdev {
#[allow(unsafe_code)]
fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize> {
info!(
"fbdev read_at: offset={:#x} buf_len={:#x}",
offset,
buf.len()
);
if let Some(fb) = FRAME_BUFFER.read().as_ref() {
if offset >= fb.screen_size {
return Ok(0);
}
let len = buf.len().min(fb.screen_size - offset);
let data =
unsafe { core::slice::from_raw_parts((fb.vaddr + offset) as *const u8, len) };
buf[..len].copy_from_slice(data);
Ok(len)
} else {
Err(FsError::NoDevice)
}
}
#[allow(unsafe_code)]
fn write_at(&self, offset: usize, buf: &[u8]) -> Result<usize> {
info!(
"fbdev write_at: offset={:#x} buf_len={:#x}",
offset,
buf.len()
);
if let Some(fb) = FRAME_BUFFER.write().as_mut() {
if offset > fb.screen_size {
return Err(FsError::NoDeviceSpace);
}
let len = buf.len().min(fb.screen_size - offset);
let data =
unsafe { core::slice::from_raw_parts_mut((fb.vaddr + offset) as *mut u8, len) };
data.copy_from_slice(&buf[..len]);
Ok(len)
} else {
Err(FsError::NoDevice)
}
}
fn poll(&self) -> Result<PollStatus> {
Ok(PollStatus {
// TOKNOW and TODO
read: true,
write: false,
error: false,
})
}
fn metadata(&self) -> Result<Metadata> {
Ok(Metadata {
dev: 5,
inode: 662,
size: 0,
blk_size: 0,
blocks: 0,
atime: Timespec { sec: 0, nsec: 0 },
mtime: Timespec { sec: 0, nsec: 0 },
ctime: Timespec { sec: 0, nsec: 0 },
type_: FileType::CharDevice,
mode: 0o660,
nlinks: 1,
uid: 0,
gid: 0,
rdev: make_rdev(29, 0),
})
}
#[allow(unsafe_code)]
fn io_control(&self, cmd: u32, data: usize) -> Result<usize> {
const FBIOGET_VSCREENINFO: u32 = 0x4600;
const FBIOGET_FSCREENINFO: u32 = 0x4602;
match cmd {
FBIOGET_FSCREENINFO => {
if let Some(fb) = FRAME_BUFFER.read().as_ref() {
let fb_fix_info = unsafe { &mut *(data as *mut FbFixScreeninfo) };
fb_fix_info.fill_from(fb);
}
Ok(0)
}
FBIOGET_VSCREENINFO => {
if let Some(fb) = FRAME_BUFFER.read().as_ref() {
let fb_var_info = unsafe { &mut *(data as *mut FbVarScreeninfo) };
fb_var_info.fill_from(fb);
}
Ok(0)
}
_ => {
warn!("use never support ioctl !");
Err(FsError::NotSupported)
}
}
}
fn as_any_ref(&self) -> &dyn Any {
self
}
}
///
#[repr(u32)]
#[allow(dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum FbType {
/// Packed Pixels
PackedPixels = 0,
/// Non interleaved planes
Planes = 1,
/// Interleaved planes
InterleavedPlanes = 2,
/// Text/attributes
Text = 3,
/// EGA/VGA planes
VgaPlanes = 4,
/// Type identified by a V4L2 FOURCC
FourCC = 5,
}
impl Default for FbType {
fn default() -> Self {
Self::PackedPixels
}
}
///
#[repr(u32)]
#[allow(dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum FbVisual {
/// Monochr. 1=Black 0=White
Mono01 = 0,
/// Monochr. 1=White 0=Black
Mono10 = 1,
/// True color
TrueColor = 2,
/// Pseudo color (like atari)
PseudoColor = 3,
/// Direct color
DirectColor = 4,
/// Pseudo color readonly
StaticPseudoColor = 5,
/// Visual identified by a V4L2 FOURCC
FourCC = 6,
}
impl Default for FbVisual {
fn default() -> Self {
Self::Mono01
}
}
/// No hardware accelerator
const FB_ACCEL_NONE: u32 = 0;
/// Fixed screen info
#[repr(C)]
#[derive(Debug, Default)]
pub struct FbFixScreeninfo {
/// identification string eg "TT Builtin"
id: [u8; 16],
/// Start of frame buffer mem (physical address)
smem_start: u64,
/// Length of frame buffer mem
smem_len: u32,
/// see FB_TYPE_*
type_: FbType,
/// Interleave for interleaved Planes
type_aux: u32,
/// see FB_VISUAL_*
visual: FbVisual,
/// zero if no hardware panning
xpanstep: u16,
/// zero if no hardware panning
ypanstep: u16,
/// zero if no hardware ywrap
ywrapstep: u16,
/// length of a line in bytes
line_length: u32,
/// Start of Memory Mapped I/O (physical address)
mmio_start: u64,
/// Length of Memory Mapped I/O
mmio_len: u32,
/// Indicate to driver which specific chip/card we have
accel: u32,
/// see FB_CAP_*
capabilities: u16,
/// Reserved for future compatibility
reserved: [u16; 2],
}
/// Variable screen info
#[repr(C)]
#[derive(Debug, Default)]
pub struct FbVarScreeninfo {
/// visible resolution x
xres: u32,
/// visible resolution y
yres: u32,
/// virtual resolution x
xres_virtual: u32,
/// virtual resolution y
yres_virtual: u32,
/// offset from virtual to visible x
xoffset: u32,
/// offset from virtual to visible y
yoffset: u32,
/// guess what
bits_per_pixel: u32,
/// 0 = color, 1 = grayscale, >1 = FOURCC
grayscale: u32,
/// bitfield in fb mem if true color, else only length is significant
red: FbBitfield,
green: FbBitfield,
blue: FbBitfield,
transp: FbBitfield,
/// != 0 Non standard pixel format
nonstd: u32,
/// see FB_ACTIVATE_*
activate: u32,
/// height of picture in mm
height: u32,
/// width of picture in mm
width: u32,
/// (OBSOLETE) see fb_info.flags
accel_flags: u32,
/* Timing: All values in pixclocks, except pixclock (of course) */
/// pixel clock in ps (pico seconds)
pixclock: u32,
/// time from sync to picture
left_margin: u32,
/// time from picture to sync
right_margin: u32,
/// time from sync to picture
upper_margin: u32,
lower_margin: u32,
/// length of horizontal sync
hsync_len: u32,
/// length of vertical sync
vsync_len: u32,
/// see FB_SYNC_*
sync: u32,
/// see FB_VMODE_*
vmode: u32,
/// angle we rotate counter clockwise
rotate: u32,
/// colorspace for FOURCC-based modes
colorspace: u32,
/// Reserved for future compatibility
reserved: [u32; 4],
}
///
#[repr(C)]
#[derive(Debug, Default)]
pub struct FbBitfield {
/// beginning of bitfield
offset: u32,
/// length of bitfield
length: u32,
/// != 0 : Most significant bit is right
msb_right: u32,
}
impl FbVarScreeninfo {
/// Transform from FramebufferInfo
pub fn fill_from(&mut self, fb_info: &FramebufferInfo) {
self.xres = fb_info.xres;
self.yres = fb_info.yres;
self.xres_virtual = fb_info.xres_virtual;
self.yres_virtual = fb_info.yres_virtual;
self.xoffset = fb_info.xoffset;
self.yoffset = fb_info.yoffset;
self.bits_per_pixel = fb_info.depth as u32;
let (rl, gl, bl, al, ro, go, bo, ao) = match fb_info.format {
ColorFormat::RGB332 => (3, 3, 2, 0, 5, 3, 0, 0),
ColorFormat::RGB565 => (5, 6, 5, 0, 11, 5, 0, 0),
ColorFormat::RGBA8888 => (8, 8, 8, 8, 16, 8, 0, 24),
ColorFormat::BGRA8888 => (8, 8, 8, 8, 0, 8, 16, 24),
ColorFormat::VgaPalette => unimplemented!(),
};
self.blue = FbBitfield {
offset: bo,
length: bl,
msb_right: 1,
};
self.green = FbBitfield {
offset: go,
length: gl,
msb_right: 1,
};
self.red = FbBitfield {
offset: ro,
length: rl,
msb_right: 1,
};
self.transp = FbBitfield {
offset: ao,
length: al,
msb_right: 1,
};
}
}
impl FbFixScreeninfo {
/// Transform from FramebufferInfo
pub fn fill_from(&mut self, fb_info: &FramebufferInfo) {
self.smem_start = fb_info.paddr as u64;
self.smem_len = fb_info.screen_size as u32;
self.type_ = FbType::PackedPixels;
// self.type_aux = fb_info.type_aux;
self.visual = FbVisual::TrueColor;
// self.xpanstep = 0;
// self.ypanstep = 0;
// self.ywrapstep = 0;
self.line_length = fb_info.xres * fb_info.depth as u32 / 8;
self.mmio_start = 0;
self.mmio_len = 0;
self.accel = FB_ACCEL_NONE;
}
}
|
pub mod mtac_lora_h_868_eu868;
pub mod mtac_lora_h_915_us915;
|
use super::*;
use proptest::collection::SizeRange;
use crate::test::strategy::NON_EMPTY_RANGE_INCLUSIVE;
#[test]
fn with_empty_list_returns_tail() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&strategy::term(arc_process.clone()), |tail| {
prop_assert_eq!(result(&arc_process, Term::NIL, tail), Ok(tail));
Ok(())
})
.unwrap();
});
}
#[test]
fn reverses_order_of_elements_of_list_and_concatenate_tail() {
let size_range: SizeRange = NON_EMPTY_RANGE_INCLUSIVE.clone().into();
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(
&(
proptest::collection::vec(strategy::term(arc_process.clone()), size_range),
strategy::term(arc_process.clone()),
),
|(vec, tail)| {
let list = arc_process.list_from_slice(&vec);
let reversed_vec: Vec<Term> = vec.iter().rev().copied().collect();
let reversed_with_tail =
arc_process.improper_list_from_slice(&reversed_vec, tail);
prop_assert_eq!(result(&arc_process, list, tail), Ok(reversed_with_tail));
Ok(())
},
)
.unwrap();
});
}
#[test]
fn reverse_reverse_with_empty_list_tail_returns_original_list() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&strategy::term::list::proper(arc_process.clone()), |list| {
let tail = Term::NIL;
let reversed_with_tail = result(&arc_process, list, tail).unwrap();
prop_assert_eq!(result(&arc_process, reversed_with_tail, tail), Ok(list));
Ok(())
})
.unwrap();
});
}
|
/* Copyright 2020 Clément Joly
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.
*/
#![forbid(unsafe_code)]
#![warn(missing_docs)]
//! Rusqlite Migration is a simple schema migration library for [rusqlite](https://lib.rs/crates/rusqlite) using [user_version][uv] instead of an SQL table to maintain the current schema version.
//!
//! It aims for:
//! - **simplicity**: define a set of SQL statements. Just add more SQL statement to change the schema. No external CLI, no macro.
//! - **performance**: no need to add a table to be parsed, the [`user_version`][uv] field is at a fixed offset in the sqlite file format.
//!
//! It works especially well with other small libraries complementing rusqlite, like [serde_rusqlite](https://crates.io/crates/serde_rusqlite).
//!
//! [uv]: https://sqlite.org/pragma.html#pragma_user_version
//!
//! ## Example
//!
//! Here, we define SQL statements to run with [Migrations::new](crate::Migrations::new) and run these (if necessary) with [.to_latest()](crate::Migrations::to_latest).
//!
//! ```
//! use rusqlite::{params, Connection};
//! use rusqlite_migration::{Migrations, M};
//!
//! // 1️⃣ Define migrations
//! let migrations = Migrations::new(vec![
//! M::up("CREATE TABLE friend(name TEXT NOT NULL);"),
//! // In the future, add more migrations here:
//! //M::up("ALTER TABLE friend ADD COLUMN email TEXT;"),
//! ]);
//!
//! let mut conn = Connection::open_in_memory().unwrap();
//!
//! // Apply some PRAGMA, often better to do it outside of migrations
//! conn.pragma_update(None, "journal_mode", &"WAL").unwrap();
//!
//! // 2️⃣ Update the database schema, atomically
//! migrations.to_latest(&mut conn).unwrap();
//!
//! // 3️⃣ Use the database 🥳
//! conn.execute("INSERT INTO friend (name) VALUES (?1)", params!["John"])
//! .unwrap();
//! ```
//!
//! Please see the [examples](https://github.com/cljoly/rusqlite_migrate/tree/master/examples) folder for more, in particular:
//! - migrations with multiple SQL statements (using for instance `r#"…"` or `include_str!(…)`)
//! - use of lazy_static
//! - migrations to previous versions (downward migrations)
//!
//! ### Built-in tests
//!
//! To test that the migrations are working, you can add this in your test module:
//!
//! ```
//! #[test]
//! fn migrations_test() {
//! assert!(MIGRATIONS.validate().is_ok());
//! }
//! ```
//!
//! ## Contributing
//!
//! Contributions (documentation or code improvements in particular) are welcome, see [contributing](https://cj.rs/docs/contribute/)!
//!
//! ## Acknowledgments
//!
//! I would like to thank all the contributors, as well as the authors of the dependencies this crate uses.
use log::{debug, info, trace, warn};
use rusqlite::Connection;
#[allow(deprecated)] // To keep compatibility with lower rusqlite versions
use rusqlite::NO_PARAMS;
mod errors;
#[cfg(test)]
mod tests;
pub use errors::{Error, MigrationDefinitionError, Result, SchemaVersionError};
use std::{
cmp::{self, Ordering},
fmt,
num::NonZeroUsize,
};
/// One migration
#[derive(Debug, PartialEq, Clone)]
pub struct M<'u> {
up: &'u str,
down: Option<&'u str>,
}
impl<'u> M<'u> {
/// Create a schema update. The SQL command will be executed only when the migration has not been
/// executed on the underlying database.
///
/// # Please note
///
/// * PRAGMA statements are discouraged here. They are often better applied outside of
/// migrations, because:
/// * a PRAGMA executed this way may not be applied consistently. For instance:
/// * [`foreign_keys`](https://sqlite.org/pragma.html#pragma_foreign_keys) needs to be
/// executed for each sqlite connection, not just once per database as a migration,
/// * [`journal_mode`](https://sqlite.org/pragma.html#pragma_journal_mode) has no effect
/// when executed inside transactions (that will be the case for the SQL written in `up`).
/// * Multiple SQL commands contaning `PRAGMA` are [not
/// working](https://github.com/rusqlite/rusqlite/pull/794) with the `extra_check` feature of
/// rusqlite.
/// * SQL commands should end with a “;”.
///
/// # Example
///
/// ```
/// use rusqlite_migration::M;
///
/// M::up("CREATE TABLE animals (name TEXT);");
/// ```
pub fn up(sql: &'u str) -> Self {
Self {
up: sql,
down: None,
}
}
/// Define a down-migration. This SQL statement should exactly reverse the changes
/// performed in `up()`.
///
/// A call to this method is **not** required.
///
/// # Example
///
/// ```
/// use rusqlite_migration::M;
///
/// M::up("CREATE TABLE animals (name TEXT);")
/// .down("DROP TABLE animals;");
/// ```
pub fn down(mut self, sql: &'u str) -> Self {
self.down = Some(sql);
self
}
}
/// Schema version, in the context of Migrations
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum SchemaVersion {
/// No schema version set
NoneSet,
/// The current version in the database is inside the range of defined
/// migrations
Inside(NonZeroUsize),
/// The current version in the database is outside any migration defined
Outside(NonZeroUsize),
}
impl From<&SchemaVersion> for usize {
/// Translate schema version to db version
fn from(schema_version: &SchemaVersion) -> usize {
match schema_version {
SchemaVersion::NoneSet => 0,
SchemaVersion::Inside(v) | SchemaVersion::Outside(v) => From::from(*v),
}
}
}
impl From<SchemaVersion> for usize {
fn from(schema_version: SchemaVersion) -> Self {
From::from(&schema_version)
}
}
impl fmt::Display for SchemaVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SchemaVersion::NoneSet => write!(f, "0 (no version set)"),
SchemaVersion::Inside(v) => write!(f, "{} (inside)", v),
SchemaVersion::Outside(v) => write!(f, "{} (outside)", v),
}
}
}
impl cmp::PartialOrd for SchemaVersion {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
let self_usize: usize = self.into();
let other_usize: usize = other.into();
self_usize.partial_cmp(&other_usize)
}
}
/// Set of migrations
#[derive(Debug, PartialEq, Clone)]
pub struct Migrations<'m> {
ms: Vec<M<'m>>,
}
impl<'m> Migrations<'m> {
/// Create a set of migrations.
///
/// # Example
///
/// ```
/// use rusqlite_migration::{Migrations, M};
///
/// let migrations = Migrations::new(vec![
/// M::up("CREATE TABLE animals (name TEXT);"),
/// M::up("CREATE TABLE food (name TEXT);"),
/// ]);
/// ```
pub fn new(ms: Vec<M<'m>>) -> Self {
Self { ms }
}
/// Performs allocations transparently.
pub fn new_iter<I: IntoIterator<Item = M<'m>>>(ms: I) -> Self {
use std::iter::FromIterator;
Self::new(Vec::from_iter(ms))
}
fn db_version_to_schema(&self, db_version: usize) -> SchemaVersion {
match db_version {
0 => SchemaVersion::NoneSet,
v if v > 0 && v <= self.ms.len() => SchemaVersion::Inside(
NonZeroUsize::new(v).expect("schema version should not be equal to 0"),
),
v => SchemaVersion::Outside(
NonZeroUsize::new(v).expect("schema version should not be equal to 0"),
),
}
}
/// Get the current schema version
///
/// # Example
///
/// ```
/// use rusqlite_migration::{Migrations, M, SchemaVersion};
/// use std::num::NonZeroUsize;
///
/// let mut conn = rusqlite::Connection::open_in_memory().unwrap();
///
/// let migrations = Migrations::new(vec![
/// M::up("CREATE TABLE animals (name TEXT);"),
/// M::up("CREATE TABLE food (name TEXT);"),
/// ]);
///
/// assert_eq!(SchemaVersion::NoneSet, migrations.current_version(&conn).unwrap());
///
/// // Go to the latest version
/// migrations.to_latest(&mut conn).unwrap();
///
/// assert_eq!(SchemaVersion::Inside(NonZeroUsize::new(2).unwrap()), migrations.current_version(&conn).unwrap());
/// ```
pub fn current_version(&self, conn: &Connection) -> Result<SchemaVersion> {
user_version(conn)
.map(|v| self.db_version_to_schema(v))
.map_err(|e| e.into())
}
/// Migrate upward methods. This is rolled back on error.
/// On success, returns the number of update performed
/// All versions are db versions
fn goto_up(
&self,
conn: &mut Connection,
current_version: usize,
target_version: usize,
) -> Result<()> {
debug_assert!(current_version <= target_version);
debug_assert!(target_version <= self.ms.len());
trace!("start migration transaction");
let tx = conn.transaction()?;
for v in current_version..target_version {
let m = &self.ms[v];
debug!("Running: {}", m.up);
tx.execute_batch(m.up)
.map_err(|e| Error::with_sql(e, m.up))?;
}
set_user_version(&tx, target_version)?;
tx.commit()?;
trace!("commited migration transaction");
Ok(())
}
/// Migrate downward. This is rolled back on error.
/// All versions are db versions
fn goto_down(
&self,
conn: &mut Connection,
current_version: usize,
target_version: usize,
) -> Result<()> {
debug_assert!(current_version >= target_version);
debug_assert!(target_version <= self.ms.len());
// First, check if all the migrations have a "down" version
if let Some((i, bad_m)) = self
.ms
.iter()
.enumerate()
.skip(target_version)
.take(current_version - target_version)
.find(|(_, m)| m.down.is_none())
{
warn!("Cannot revert: {:?}", bad_m);
return Err(Error::MigrationDefinition(
MigrationDefinitionError::DownNotDefined { migration_index: i },
));
}
trace!("start migration transaction");
let tx = conn.transaction()?;
for v in (target_version..current_version).rev() {
let m = &self.ms[v];
if let Some(ref down) = m.down {
debug!("Running: {}", down);
tx.execute_batch(down)
.map_err(|e| Error::with_sql(e, down))?;
} else {
unreachable!();
}
}
set_user_version(&tx, target_version)?;
tx.commit()?;
trace!("committed migration transaction");
Ok(())
}
/// Go to a given db version
fn goto(&self, conn: &mut Connection, target_db_version: usize) -> Result<()> {
let current_version = user_version(conn)?;
let res = match target_db_version.cmp(¤t_version) {
Ordering::Less => {
debug!(
"rollback to older version requested, target_db_version: {}, current_version: {}",
target_db_version, current_version
);
self.goto_down(conn, current_version, target_db_version)
}
Ordering::Equal => {
debug!("no migration to run, db already up to date");
return Ok(()); // return directly, so the migration message is not printed
}
Ordering::Greater => {
debug!(
"some migrations to run, target_db_version: {}, current_version: {}",
target_db_version, current_version
);
self.goto_up(conn, current_version, target_db_version)
}
};
if res.is_ok() {
info!("Database migrated to version {}", target_db_version);
}
res
}
/// Maximum version defined in the migration set
fn max_schema_version(&self) -> SchemaVersion {
match self.ms.len() {
0 => SchemaVersion::NoneSet,
v => SchemaVersion::Inside(
NonZeroUsize::new(v).expect("schema version should not be equal to 0"),
),
}
}
/// Migrate the database to latest schema version. The migrations are applied atomically.
#[deprecated(since = "0.4.0", note = "Renammed to “to_latest”")]
pub fn latest(&self, conn: &mut Connection) -> Result<()> {
self.to_latest(conn)
}
/// Migrate the database to latest schema version. The migrations are applied atomically.
///
/// # Example
///
/// ```
/// use rusqlite_migration::{Migrations, M};
/// let mut conn = rusqlite::Connection::open_in_memory().unwrap();
///
/// let migrations = Migrations::new(vec![
/// M::up("CREATE TABLE animals (name TEXT);"),
/// M::up("CREATE TABLE food (name TEXT);"),
/// ]);
///
/// // Go to the latest version
/// migrations.to_latest(&mut conn).unwrap();
///
/// // You can then insert values in the database
/// conn.execute("INSERT INTO animals (name) VALUES ('dog')", []).unwrap();
/// conn.execute("INSERT INTO food (name) VALUES ('carrot')", []).unwrap();
/// ```
pub fn to_latest(&self, conn: &mut Connection) -> Result<()> {
let v_max = self.max_schema_version();
match v_max {
SchemaVersion::NoneSet => {
warn!("no migration defined");
Err(Error::MigrationDefinition(
MigrationDefinitionError::NoMigrationsDefined,
))
}
SchemaVersion::Inside(_) => {
debug!("some migrations defined, try to migrate");
self.goto(conn, v_max.into())
}
SchemaVersion::Outside(_) => unreachable!(),
}
}
/// Migrate the database to a given schema version. The migrations are applied atomically.
///
/// # Specifying versions
///
/// - Empty database (no migrations run yet) has version `0`.
/// - The version increases after each migration, so after the first migration has run, the schema version is `1`. For instance, if there are 3 migrations, version `3` is after all migrations have run.
///
/// *Note*: As a result, the version is the index in the migrations vector *starting from 1*.
///
/// # Example
///
/// ```
/// use rusqlite_migration::{Migrations, M};
/// let mut conn = rusqlite::Connection::open_in_memory().unwrap();
/// let migrations = Migrations::new(vec![
/// // 0: version 0, before having run any migration
/// M::up("CREATE TABLE animals (name TEXT);").down("DROP TABLE animals;"),
/// // 1: version 1, after having created the “animals” table
/// M::up("CREATE TABLE food (name TEXT);").down("DROP TABLE food;"),
/// // 2: version 2, after having created the food table
/// ]);
///
/// migrations.to_latest(&mut conn).unwrap(); // Create all tables
///
/// // Go back to version 1, i.e. after running the first migration
/// migrations.to_version(&mut conn, 1);
/// conn.execute("INSERT INTO animals (name) VALUES ('dog')", []).unwrap();
/// conn.execute("INSERT INTO food (name) VALUES ('carrot')", []).unwrap_err();
///
/// // Go back to an empty database
/// migrations.to_version(&mut conn, 0);
/// conn.execute("INSERT INTO animals (name) VALUES ('cat')", []).unwrap_err();
/// conn.execute("INSERT INTO food (name) VALUES ('milk')", []).unwrap_err();
/// ```
///
/// # Errors
///
/// Attempts to migrate to a higher version than is supported will result in an error.
///
/// When migrating downwards, all the reversed migrations must have a `.down()` variant,
/// otherwise no migrations are run and the function returns an error.
pub fn to_version(&self, conn: &mut Connection, version: usize) -> Result<()> {
let target_version: SchemaVersion = self.db_version_to_schema(version);
let v_max = self.max_schema_version();
match v_max {
SchemaVersion::NoneSet => {
warn!("no migrations defined");
Err(Error::MigrationDefinition(
MigrationDefinitionError::NoMigrationsDefined,
))
}
SchemaVersion::Inside(_) => {
if target_version > v_max {
warn!("specified version is higher than the max supported version");
return Err(Error::SpecifiedSchemaVersion(
SchemaVersionError::TargetVersionOutOfRange {
specified: target_version,
highest: v_max,
},
));
}
self.goto(conn, target_version.into())
}
SchemaVersion::Outside(_) => unreachable!(),
}
}
/// Run migrations on a temporary in-memory database from first to last, one by one.
/// Convenience method for testing.
///
/// # Example
///
/// ```
/// #[cfg(test)]
/// mod tests {
///
/// // … Other tests …
///
/// #[test]
/// fn migrations_test() {
/// assert!(migrations.validate().is_ok());
/// }
/// }
/// ```
pub fn validate(&self) -> Result<()> {
let mut conn = Connection::open_in_memory()?;
self.to_latest(&mut conn)
}
}
// Read user version field from the SQLite db
fn user_version(conn: &Connection) -> Result<usize, rusqlite::Error> {
#[allow(deprecated)] // To keep compatibility with lower rusqlite versions
conn.query_row("PRAGMA user_version", NO_PARAMS, |row| row.get(0))
.map(|v: i64| v as usize)
}
// Set user version field from the SQLite db
fn set_user_version(conn: &Connection, v: usize) -> Result<()> {
trace!("set user version to: {}", v);
let v = v as u32;
conn.pragma_update(None, "user_version", &v)
.map_err(|e| Error::RusqliteError {
query: format!("PRAGMA user_version = {}; -- Approximate query", v),
err: e,
})
}
|
use std::{cell::RefCell, rc::Rc};
use naia_shared::ActorMutator;
use super::{actor_key::actor_key::ActorKey, mut_handler::MutHandler};
pub struct ServerActorMutator {
key: Option<ActorKey>,
mut_handler: Rc<RefCell<MutHandler>>,
}
impl ServerActorMutator {
pub fn new(mut_handler: &Rc<RefCell<MutHandler>>) -> Self {
ServerActorMutator {
key: None,
mut_handler: mut_handler.clone(),
}
}
pub fn set_actor_key(&mut self, key: ActorKey) {
self.key = Some(key);
}
}
impl ActorMutator for ServerActorMutator {
fn mutate(&mut self, property_index: u8) {
if let Some(key) = self.key {
self.mut_handler
.as_ref()
.borrow_mut()
.mutate(&key, property_index);
}
}
}
|
use eframe::egui;
use eframe::egui::{Response, Ui};
#[cfg_attr(
feature = "persistence",
derive(serde::Deserialize, serde::Serialize, Debug, Clone, PartialEq)
)]
pub enum Wh2Factions {
BM,
BRT,
CH,
DE,
DW,
EMP,
GS,
HE,
LM,
NRS,
SKV,
TK,
VC,
VP,
WE,
UNKNOWN,
ALL,
}
pub fn get_faction_abbreviations(faction: Wh2Factions) -> &'static str {
match faction {
Wh2Factions::BM => "BM",
Wh2Factions::BRT => "BRT",
Wh2Factions::CH => "CH",
Wh2Factions::DE => "DE",
Wh2Factions::DW => "DW",
Wh2Factions::EMP => "EMP",
Wh2Factions::GS => "GS",
Wh2Factions::HE => "HE",
Wh2Factions::LM => "LM",
Wh2Factions::NRS => "NRS",
Wh2Factions::SKV => "SKV",
Wh2Factions::TK => "TK",
Wh2Factions::VC => "VC",
Wh2Factions::VP => "VP",
Wh2Factions::WE => "WE",
Wh2Factions::UNKNOWN => "UNKNOWN",
Wh2Factions::ALL => "ALL",
}
}
pub fn get_faction_names(faction: &Wh2Factions) -> &'static str {
match faction {
Wh2Factions::BM => "Beastmen",
Wh2Factions::BRT => "Bretonnia",
Wh2Factions::CH => "Chaos",
Wh2Factions::DE => "Dark Elves",
Wh2Factions::DW => "Dwarfs",
Wh2Factions::EMP => "Empire",
Wh2Factions::GS => "Greenskins",
Wh2Factions::HE => "High Elves",
Wh2Factions::LM => "Lizardmen",
Wh2Factions::NRS => "Norsca",
Wh2Factions::SKV => "Skaven",
Wh2Factions::TK => "Tomb Kings",
Wh2Factions::VC => "Vampire Counts",
Wh2Factions::VP => "Vampire Coast",
Wh2Factions::WE => "Woodelves",
Wh2Factions::UNKNOWN => "Unknown",
Wh2Factions::ALL => "All",
}
}
pub fn parse_faction(file_name: &String) -> Wh2Factions {
let lower_file = file_name.to_ascii_lowercase();
if lower_file.contains("bm vs") {
return Wh2Factions::BM;
} else if lower_file.contains("brt vs") {
return Wh2Factions::BRT;
} else if lower_file.contains("ch vs") {
return Wh2Factions::CH;
} else if lower_file.contains("dw vs") {
return Wh2Factions::DW;
} else if lower_file.contains("emp vs") {
return Wh2Factions::EMP;
} else if lower_file.contains("ew vs") {
return Wh2Factions::DW;
} else if lower_file.contains("de vs") {
return Wh2Factions::DE;
} else if lower_file.contains("gs vs") {
return Wh2Factions::GS;
} else if lower_file.contains("he vs") {
return Wh2Factions::HE;
} else if lower_file.contains("lm vs") {
return Wh2Factions::LM;
} else if lower_file.contains("nrs vs") {
return Wh2Factions::NRS;
} else if lower_file.contains("skv vs") {
return Wh2Factions::SKV;
} else if lower_file.contains("tk vs") {
return Wh2Factions::TK;
} else if lower_file.contains("vc vs") {
return Wh2Factions::VC;
} else if lower_file.contains("vp vs") {
return Wh2Factions::VP;
} else if lower_file.contains("we vs") {
return Wh2Factions::WE;
}
Wh2Factions::UNKNOWN
}
pub fn parse_vs_faction(file_name: &String) -> Wh2Factions {
let lower_file = file_name.to_ascii_lowercase();
if lower_file.contains("vs bm") {
return Wh2Factions::BM;
} else if lower_file.contains("vs brt") {
return Wh2Factions::BRT;
} else if lower_file.contains("vs ch") {
return Wh2Factions::CH;
} else if lower_file.contains("vs de") {
return Wh2Factions::DE;
} else if lower_file.contains("vs dw") {
return Wh2Factions::DW;
} else if lower_file.contains("vs emp") {
return Wh2Factions::EMP;
} else if lower_file.contains("vs gs") {
return Wh2Factions::GS;
} else if lower_file.contains("vs he") {
return Wh2Factions::HE;
} else if lower_file.contains("vs lm") {
return Wh2Factions::LM;
} else if lower_file.contains("vs nrs") {
return Wh2Factions::NRS;
} else if lower_file.contains("vs skv") {
return Wh2Factions::SKV;
} else if lower_file.contains("vs tk") {
return Wh2Factions::TK;
} else if lower_file.contains("vs vc") {
return Wh2Factions::VC;
} else if lower_file.contains("vs vp") {
return Wh2Factions::VP;
} else if lower_file.contains("vs we") {
return Wh2Factions::WE;
} else if lower_file.contains("vs aa") {
return Wh2Factions::ALL;
}
Wh2Factions::UNKNOWN
}
pub fn faction_dropdown_button(
ui: &mut Ui,
faction: &mut Wh2Factions,
label: &str,
is_vs: bool,
) -> Response {
let faction_btn_response = egui::ComboBox::from_label(label)
.selected_text(format!("{:?}", faction))
.show_ui(ui, |ui| {
ui.selectable_value(
faction,
Wh2Factions::ALL,
get_faction_abbreviations(Wh2Factions::ALL),
);
ui.selectable_value(
faction,
Wh2Factions::BM,
get_faction_abbreviations(Wh2Factions::BM),
);
ui.selectable_value(
faction,
Wh2Factions::BRT,
get_faction_abbreviations(Wh2Factions::BRT),
);
if !is_vs {
ui.selectable_value(
faction,
Wh2Factions::CH,
get_faction_abbreviations(Wh2Factions::CH),
);
}
ui.selectable_value(
faction,
Wh2Factions::DE,
get_faction_abbreviations(Wh2Factions::DE),
);
ui.selectable_value(
faction,
Wh2Factions::DW,
get_faction_abbreviations(Wh2Factions::DW),
);
ui.selectable_value(
faction,
Wh2Factions::EMP,
get_faction_abbreviations(Wh2Factions::EMP),
);
ui.selectable_value(
faction,
Wh2Factions::GS,
get_faction_abbreviations(Wh2Factions::GS),
);
ui.selectable_value(
faction,
Wh2Factions::HE,
get_faction_abbreviations(Wh2Factions::HE),
);
ui.selectable_value(
faction,
Wh2Factions::LM,
get_faction_abbreviations(Wh2Factions::LM),
);
ui.selectable_value(
faction,
Wh2Factions::NRS,
get_faction_abbreviations(Wh2Factions::NRS),
);
ui.selectable_value(
faction,
Wh2Factions::SKV,
get_faction_abbreviations(Wh2Factions::SKV),
);
ui.selectable_value(
faction,
Wh2Factions::TK,
get_faction_abbreviations(Wh2Factions::TK),
);
ui.selectable_value(
faction,
Wh2Factions::VC,
get_faction_abbreviations(Wh2Factions::VC),
);
ui.selectable_value(
faction,
Wh2Factions::VP,
get_faction_abbreviations(Wh2Factions::VP),
);
ui.selectable_value(
faction,
Wh2Factions::WE,
get_faction_abbreviations(Wh2Factions::WE),
);
ui.selectable_value(
faction,
Wh2Factions::WE,
get_faction_abbreviations(Wh2Factions::WE),
);
ui.selectable_value(
faction,
Wh2Factions::UNKNOWN,
get_faction_abbreviations(Wh2Factions::UNKNOWN),
);
});
faction_btn_response
}
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_arrow::parquet::metadata::FileMetaData;
use common_arrow::parquet::metadata::ThriftFileMetaData;
use common_base::base::tokio;
use common_cache::Cache;
use common_expression::types::Int32Type;
use common_expression::types::NumberDataType;
use common_expression::DataBlock;
use common_expression::FromData;
use common_expression::TableDataType;
use common_expression::TableField;
use common_expression::TableSchemaRefExt;
use common_storages_fuse::io::TableMetaLocationGenerator;
use common_storages_fuse::statistics::gen_columns_statistics;
use common_storages_fuse::FuseStorageFormat;
use opendal::Operator;
use storages_common_cache::InMemoryCacheBuilder;
use storages_common_cache::InMemoryItemCacheHolder;
use storages_common_index::BloomIndexMeta;
use sysinfo::get_current_pid;
use sysinfo::ProcessExt;
use sysinfo::System;
use sysinfo::SystemExt;
use uuid::Uuid;
use crate::storages::fuse::block_writer::BlockWriter;
// NOTE:
//
// usage of memory is observed at *process* level, please do not combine them into
// one test function.
//
// by default, these cases are ignored (in CI).
//
// please run the following two cases individually (in different process)
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn test_index_meta_cache_size_file_meta_data() -> common_exception::Result<()> {
let thrift_file_meta = setup().await?;
let cache_number = 300_000;
let meta: FileMetaData = FileMetaData::try_from_thrift(thrift_file_meta)?;
let sys = System::new_all();
let pid = get_current_pid().unwrap();
let process = sys.process(pid).unwrap();
let base_memory_usage = process.memory();
let scenario = "FileMetaData";
eprintln!(
"scenario {}, pid {}, base memory {}",
scenario, pid, base_memory_usage
);
let cache = InMemoryCacheBuilder::new_item_cache::<FileMetaData>(cache_number as u64);
populate_cache(&cache, meta, cache_number);
show_memory_usage(scenario, base_memory_usage, cache_number);
drop(cache);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn test_index_meta_cache_size_bloom_meta() -> common_exception::Result<()> {
let thrift_file_meta = setup().await?;
let cache_number = 300_000;
let bloom_index_meta = BloomIndexMeta::try_from(thrift_file_meta)?;
let sys = System::new_all();
let pid = get_current_pid().unwrap();
let process = sys.process(pid).unwrap();
let base_memory_usage = process.memory();
let scenario = "BloomIndexMeta(mini)";
eprintln!(
"scenario {}, pid {}, base memory {}",
scenario, pid, base_memory_usage
);
let cache = InMemoryCacheBuilder::new_item_cache::<BloomIndexMeta>(cache_number as u64);
populate_cache(&cache, bloom_index_meta, cache_number);
show_memory_usage("BloomIndexMeta(Mini)", base_memory_usage, cache_number);
drop(cache);
Ok(())
}
fn populate_cache<T>(cache: &InMemoryItemCacheHolder<T>, item: T, num_cache: usize)
where T: Clone {
let mut c = cache.write();
for _ in 0..num_cache {
let uuid = Uuid::new_v4();
(*c).put(
format!("{}", uuid.simple()),
std::sync::Arc::new(item.clone()),
);
}
}
async fn setup() -> common_exception::Result<ThriftFileMetaData> {
let fields = (0..23)
.map(|_| TableField::new("id", TableDataType::Number(NumberDataType::Int32)))
.collect::<Vec<_>>();
let schema = TableSchemaRefExt::create(fields);
let mut columns = vec![];
for _ in 0..schema.fields().len() {
// values do not matter
let column = Int32Type::from_data(vec![1]);
columns.push(column)
}
let block = DataBlock::new_from_columns(columns);
let operator = Operator::new(opendal::services::Memory::default())?.finish();
let loc_generator = TableMetaLocationGenerator::with_prefix("/".to_owned());
let col_stats = gen_columns_statistics(&block, None, &schema)?;
let block_writer = BlockWriter::new(&operator, &loc_generator);
let (_block_meta, thrift_file_meta) = block_writer
.write(FuseStorageFormat::Parquet, &schema, block, col_stats, None)
.await?;
Ok(thrift_file_meta.unwrap())
}
fn show_memory_usage(case: &str, base_memory_usage: u64, num_cache_items: usize) {
let sys = System::new_all();
let pid = get_current_pid().unwrap();
let process = sys.process(pid).unwrap();
{
let memory_after = process.memory();
let delta = memory_after - base_memory_usage;
let delta_gb = (delta as f64) / 1024.0 / 1024.0 / 1024.0;
eprintln!(
"
cache item type : {},
number of cached items {},
mem usage(B):{:+},
mem usage(GB){:+}
",
case, num_cache_items, delta, delta_gb
);
}
}
|
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
use alloc::vec::Vec;
use codec::{Encode, Decode};
use sp_core::U256;
#[cfg(feature = "enable_serde")]
use serde::{Serialize, Deserialize};
#[derive(Encode, Decode)]
pub struct Transfer<AccountId, Balance> {
pub dest: AccountId,
pub amount: Balance,
pub sequence: u64,
}
#[derive(Encode, Decode)]
pub struct TransferData<AccountId, Balance> {
pub data: Transfer<AccountId, Balance>,
pub signature: Vec<u8>,
}
#[derive(Encode, Decode, Clone, Debug)]
#[cfg_attr(feature = "enable_serde", derive(Serialize, Deserialize))]
pub enum WorkerMessagePayload {
Heartbeat {
block_num: u32,
claim_online: bool,
claim_compute: bool,
},
}
#[derive(Encode, Decode, Clone, Debug)]
#[cfg_attr(feature = "enable_serde", derive(Serialize, Deserialize))]
pub struct WorkerMessage {
pub payload: WorkerMessagePayload,
pub sequence: u64,
}
#[derive(Encode, Decode, Clone, Debug)]
#[cfg_attr(feature = "enable_serde", derive(Serialize, Deserialize))]
pub struct SignedWorkerMessage {
pub data: WorkerMessage,
pub signature: Vec<u8>,
}
pub trait SignedDataType<T> {
fn raw_data(&self) -> Vec<u8>;
fn signature(&self) -> T;
}
impl<AccountId: Encode, Balance: Encode> SignedDataType<Vec<u8>> for TransferData<AccountId, Balance> {
fn raw_data(&self) -> Vec<u8> {
Encode::encode(&self.data)
}
fn signature(&self) -> Vec<u8> {
self.signature.clone()
}
}
impl SignedDataType<Vec<u8>> for SignedWorkerMessage {
fn raw_data(&self) -> Vec<u8> {
Encode::encode(&self.data)
}
fn signature(&self) -> Vec<u8> {
self.signature.clone()
}
}
// Types used in storage
#[derive(Encode, Decode, PartialEq, Eq, Debug)]
pub enum WorkerStateEnum<BlockNumber> {
Empty,
Free,
Gatekeeper,
MiningPending,
Mining(BlockNumber),
MiningStopping,
}
impl<BlockNumber> Default for WorkerStateEnum<BlockNumber> {
fn default() -> Self {
WorkerStateEnum::Empty
}
}
#[derive(Encode, Decode, Debug, Default)]
pub struct WorkerInfo<BlockNumber> {
// identity
pub machine_id: Vec<u8>,
pub pubkey: Vec<u8>,
pub last_updated: u64,
// mining
pub state: WorkerStateEnum<BlockNumber>,
// preformance
pub score: Option<Score>,
}
#[derive(Encode, Decode, Default)]
pub struct StashInfo<AccountId: Default> {
pub controller: AccountId,
pub payout_prefs: PayoutPrefs::<AccountId>,
}
#[derive(Encode, Decode, Default)]
pub struct PayoutPrefs<AccountId: Default> {
pub commission: u32,
pub target: AccountId,
}
#[derive(Encode, Decode, Debug, Default, Clone)]
pub struct Score {
pub overall_score: u32,
pub features: Vec<u32>
}
type MachineId = [u8; 16];
type WorkerPublicKey = [u8; 33];
#[derive(Encode, Decode, Debug)]
pub struct PRuntimeInfo {
pub version: u8,
pub machine_id: MachineId,
pub pubkey: WorkerPublicKey,
pub features: Vec<u32>
}
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, Eq)]
pub struct BlockRewardInfo {
pub seed: U256,
pub online_target: U256,
pub compute_target: U256,
}
#[derive(Encode, Decode, Debug, Default)]
pub struct RoundInfo<BlockNumber> {
pub round: u32,
pub start_block: BlockNumber,
}
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, Eq)]
pub struct RoundStats {
pub round: u32,
pub online_workers: u32,
pub compute_workers: u32,
/// The targeted online reward in fraction (base: 100_000)
pub frac_target_online_reward: u32,
pub total_power: u32,
}
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, Eq)]
pub struct MinerStatsDelta {
pub num_worker: i32,
pub num_power: i32,
}
|
//! `sled` is a flash-sympathetic persistent lock-free B+ tree.
//!
//! ```
//! let config = sled::ConfigBuilder::new().temporary(true).build();
//!
//! let t = sled::Tree::start(config);
//!
//! t.set(b"yo!".to_vec(), b"v1".to_vec());
//! assert_eq!(t.get(b"yo!"), Some(b"v1".to_vec()));
//!
//! t.cas(
//! b"yo!".to_vec(), // key
//! Some(b"v1".to_vec()), // old value, None for not present
//! Some(b"v2".to_vec()), // new value, None for delete
//! ).unwrap();
//!
//! let mut iter = t.scan(b"a non-present key before yo!");
//! assert_eq!(iter.next(), Some((b"yo!".to_vec(), b"v2".to_vec())));
//! assert_eq!(iter.next(), None);
//!
//! t.del(b"yo!");
//! assert_eq!(t.get(b"yo!"), None);
//! ```
#![deny(missing_docs)]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", allow(inline_always))]
extern crate pagecache;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate crossbeam_epoch as epoch;
extern crate bincode;
#[macro_use]
extern crate log as _log;
/// atomic lock-free tree
pub use tree::{Iter, Tree};
use pagecache::*;
pub use pagecache::{Config, ConfigBuilder};
mod tree;
type Key = Vec<u8>;
type KeyRef<'a> = &'a [u8];
type Value = Vec<u8>;
type HPtr<'g, P> =
epoch::Shared<'g, pagecache::ds::stack::Node<pagecache::CacheEntry<P>>>;
|
use crate::{
buffers::{Buffer, CapacityError, DefaultArguments},
Span, Word,
};
use core::fmt::{self, Debug, Display, Formatter};
/// The general category for a [`GCode`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serde-1",
derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
#[repr(C)]
pub enum Mnemonic {
/// Preparatory commands, often telling the controller what kind of motion
/// or offset is desired.
General,
/// Auxilliary commands.
Miscellaneous,
/// Used to give the current program a unique "name".
ProgramNumber,
/// Tool selection.
ToolChange,
}
impl Mnemonic {
/// Try to convert a letter to its [`Mnemonic`] equivalent.
///
/// # Examples
///
/// ```rust
/// # use gcode::Mnemonic;
/// assert_eq!(Mnemonic::for_letter('M'), Some(Mnemonic::Miscellaneous));
/// assert_eq!(Mnemonic::for_letter('g'), Some(Mnemonic::General));
/// ```
pub fn for_letter(letter: char) -> Option<Mnemonic> {
match letter.to_ascii_lowercase() {
'g' => Some(Mnemonic::General),
'm' => Some(Mnemonic::Miscellaneous),
'o' => Some(Mnemonic::ProgramNumber),
't' => Some(Mnemonic::ToolChange),
_ => None,
}
}
}
impl Display for Mnemonic {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Mnemonic::General => write!(f, "G"),
Mnemonic::Miscellaneous => write!(f, "M"),
Mnemonic::ProgramNumber => write!(f, "O"),
Mnemonic::ToolChange => write!(f, "T"),
}
}
}
/// The in-memory representation of a single command in the G-code language
/// (e.g. `"G01 X50.0 Y-20.0"`).
#[derive(Clone)]
#[cfg_attr(
feature = "serde-1",
derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
pub struct GCode<A = DefaultArguments> {
mnemonic: Mnemonic,
number: f32,
arguments: A,
span: Span,
}
impl GCode {
/// Create a new [`GCode`] which uses the [`DefaultArguments`] buffer.
pub fn new(mnemonic: Mnemonic, number: f32, span: Span) -> Self {
GCode {
mnemonic,
number,
span,
arguments: DefaultArguments::default(),
}
}
}
impl<A: Buffer<Word>> GCode<A> {
/// Create a new [`GCode`] which uses a custom [`Buffer`].
pub fn new_with_argument_buffer(
mnemonic: Mnemonic,
number: f32,
span: Span,
arguments: A,
) -> Self {
GCode {
mnemonic,
number,
span,
arguments,
}
}
/// The overall category this [`GCode`] belongs to.
pub fn mnemonic(&self) -> Mnemonic { self.mnemonic }
/// The integral part of a command number (i.e. the `12` in `G12.3`).
pub fn major_number(&self) -> u32 {
debug_assert!(self.number >= 0.0);
libm::floorf(self.number) as u32
}
/// The fractional part of a command number (i.e. the `3` in `G12.3`).
pub fn minor_number(&self) -> u32 {
let fract = self.number - libm::floorf(self.number);
let digit = libm::roundf(fract * 10.0);
digit as u32
}
/// The arguments attached to this [`GCode`].
pub fn arguments(&self) -> &[Word] { self.arguments.as_slice() }
/// Where the [`GCode`] was found in its source text.
pub fn span(&self) -> Span { self.span }
/// Add an argument to the list of arguments attached to this [`GCode`].
pub fn push_argument(
&mut self,
arg: Word,
) -> Result<(), CapacityError<Word>> {
self.span = self.span.merge(arg.span);
self.arguments.try_push(arg)
}
/// The builder equivalent of [`GCode::push_argument()`].
///
/// # Panics
///
/// This will panic if the underlying [`Buffer`] returns a
/// [`CapacityError`].
pub fn with_argument(mut self, arg: Word) -> Self {
if let Err(e) = self.push_argument(arg) {
panic!("Unable to add the argument {:?}: {}", arg, e);
}
self
}
/// Get the value for a particular argument.
///
/// # Examples
///
/// ```rust
/// # use gcode::{GCode, Mnemonic, Span, Word};
/// let gcode = GCode::new(Mnemonic::General, 1.0, Span::PLACEHOLDER)
/// .with_argument(Word::new('X', 30.0, Span::PLACEHOLDER))
/// .with_argument(Word::new('Y', -3.14, Span::PLACEHOLDER));
///
/// assert_eq!(gcode.value_for('Y'), Some(-3.14));
/// ```
pub fn value_for(&self, letter: char) -> Option<f32> {
let letter = letter.to_ascii_lowercase();
for arg in self.arguments() {
if arg.letter.to_ascii_lowercase() == letter {
return Some(arg.value);
}
}
None
}
}
impl<A: Buffer<Word>> Extend<Word> for GCode<A> {
fn extend<I: IntoIterator<Item = Word>>(&mut self, words: I) {
for word in words {
if self.push_argument(word).is_err() {
// we can't add any more arguments
return;
}
}
}
}
impl<A: Buffer<Word>> Debug for GCode<A> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// we manually implement Debug because the the derive will constrain
// the buffer type to be Debug, which isn't necessary and actually makes
// it impossible to print something like ArrayVec<[T; 128]>
let GCode {
mnemonic,
number,
arguments,
span,
} = self;
f.debug_struct("GCode")
.field("mnemonic", mnemonic)
.field("number", number)
.field("arguments", &crate::buffers::debug(arguments))
.field("span", span)
.finish()
}
}
impl<A: Buffer<Word>> Display for GCode<A> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.mnemonic(), self.major_number())?;
if self.minor_number() != 0 {
write!(f, ".{}", self.minor_number())?;
}
for arg in self.arguments() {
write!(f, " {}", arg)?;
}
Ok(())
}
}
impl<A, B> PartialEq<GCode<B>> for GCode<A>
where
A: Buffer<Word>,
B: Buffer<Word>,
{
fn eq(&self, other: &GCode<B>) -> bool {
let GCode {
mnemonic,
number,
arguments,
span,
} = self;
*span == other.span()
&& *mnemonic == other.mnemonic
&& *number == other.number
&& arguments.as_slice() == other.arguments.as_slice()
}
}
#[cfg(test)]
mod tests {
use super::*;
use arrayvec::ArrayVec;
use std::prelude::v1::*;
type BigBuffer = ArrayVec<[Word; 32]>;
#[test]
fn correct_major_number() {
let code = GCode {
mnemonic: Mnemonic::General,
number: 90.5,
arguments: BigBuffer::default(),
span: Span::default(),
};
assert_eq!(code.major_number(), 90);
}
#[test]
fn correct_minor_number() {
for i in 0..=9 {
let code = GCode {
mnemonic: Mnemonic::General,
number: 10.0 + (i as f32) / 10.0,
arguments: BigBuffer::default(),
span: Span::default(),
};
assert_eq!(code.minor_number(), i);
}
}
#[test]
fn get_argument_values() {
let mut code = GCode::new_with_argument_buffer(
Mnemonic::General,
90.0,
Span::default(),
BigBuffer::default(),
);
code.push_argument(Word {
letter: 'X',
value: 10.0,
span: Span::default(),
})
.unwrap();
code.push_argument(Word {
letter: 'y',
value: -3.5,
span: Span::default(),
})
.unwrap();
assert_eq!(code.value_for('X'), Some(10.0));
assert_eq!(code.value_for('x'), Some(10.0));
assert_eq!(code.value_for('Y'), Some(-3.5));
assert_eq!(code.value_for('Z'), None);
}
}
|
extern crate r3status;
fn main() {
r3status::run();
}
|
use std::io;
fn cek_prima(bil: i32) -> i32 {
let mut bagi: i32 = 3;
let mut batas: i32 = 0;
let prima = if bil == 1 {
0
}else if bil == 2 || bil == 3 {
1
}else if bil % 2 ==0 {
0
}else {
while batas > bagi {
if bil % bagi == 0 {
return 0
}
batas = bil/bagi;
bagi += 2;
}
return 1;
};
prima
}
fn main() {
let mut prima = 0;
let mut rentang = String::new();
println!("Masukan rentang");
io::stdin().read_line(&mut rentang)
.expect("failed to read line");
let cnt = rentang.trim().parse::<i32>().unwrap();
for i in 0..cnt {
prima = cek_prima(i);
if prima == 1 {
println!("{}", i);
}
}
}
|
use super::{id, Class, NSUInteger, Object, BOOL, SEL};
use std::{fmt, ops::Deref, ptr::NonNull};
/// The root class for most Objective-C objects.
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/nsobject).
#[repr(transparent)]
#[derive(Clone, Debug)]
pub struct NSObject(id);
impl Deref for NSObject {
type Target = id;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<NSObject> for NSObject {
#[inline]
fn as_ref(&self) -> &Self {
self
}
}
impl fmt::Pointer for NSObject {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_ptr().fmt(f)
}
}
impl NSObject {
/// Returns the `NSObject` class.
#[inline]
pub fn class() -> &'static Class {
extern "C" {
#[link_name = "OBJC_CLASS_$_NSObject"]
static CLASS: Class;
}
unsafe { &CLASS }
}
/// Creates an object from a raw nullable pointer.
///
/// # Safety
///
/// The pointer must point to a valid `NSObject` instance.
#[inline]
pub const unsafe fn from_ptr(ptr: *mut Object) -> Self {
Self(id::from_ptr(ptr))
}
/// Creates an object from a raw non-null pointer.
///
/// # Safety
///
/// The pointer must point to a valid `NSObject` instance.
#[inline]
pub const unsafe fn from_non_null_ptr(ptr: NonNull<Object>) -> Self {
Self(id::from_non_null_ptr(ptr))
}
/// Returns a pointer to this object's data.
#[inline]
pub fn as_id(&self) -> &id {
&self.0
}
/// Returns a raw nullable pointer to this object's data.
#[inline]
pub fn as_ptr(&self) -> *mut Object {
self.0.as_ptr()
}
/// Returns a raw non-null pointer to this object's data.
#[inline]
pub fn as_non_null_ptr(&self) -> NonNull<Object> {
self.0.as_non_null_ptr()
}
/// Returns this object's reference count.
///
/// This method is only useful for debugging certain objects.
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1571952-retaincount).
#[inline]
pub fn retain_count(&self) -> usize {
unsafe { _msg_send![self, retainCount] }
}
/// Returns `true` if this object implements or inherits a method that can
/// respond to a specified message.
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1418583-respondstoselector).
#[inline]
pub fn responds_to_selector(&self, selector: SEL) -> bool {
unsafe { _msg_send![self, respondsToSelector: selector => BOOL] != 0 }
}
/// Returns `true` if this object is an instance or subclass of `class`.
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1418511-iskindofclass)
#[inline]
pub fn is_kind_of_class(&self, class: &Class) -> bool {
unsafe { _msg_send![self, isKindOfClass: class => BOOL] != 0 }
}
/// Returns `true` if this object is an instance of `class`.
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1418766-ismemberofclass)
#[inline]
pub fn is_member_of_class(&self, class: &Class) -> bool {
unsafe { _msg_send![self, isMemberOfClass: class => BOOL] != 0 }
}
/// Returns an integer that can be used as a table address in a hash table
/// structure.
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1418859-hash).
#[inline]
pub fn hash(&self) -> NSUInteger {
unsafe { _msg_send![self, hash] }
}
/// Returns a copy of this object using
/// [`NSCopying`](https://developer.apple.com/documentation/foundation/nscopying).
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/nsobject/1418807-copy).
#[inline]
pub fn copy(&self) -> NSObject {
unsafe { _msg_send![self, copy] }
}
/// Returns a copy of this object using
/// [`NSMutableCopying`](https://developer.apple.com/documentation/foundation/nsmutablecopying).
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/nsobject/1418978-mutablecopy).
#[inline]
pub fn mutable_copy(&self) -> NSObject {
unsafe { _msg_send![self, mutableCopy] }
}
}
|
extern crate cpp_build;
fn main() {
cpp_build::Config::new().include("include").build("src/lldb.rs");
#[cfg(target_os = "linux")]
{
// println!("cargo:rustc-link-search={}", "/usr/lib/llvm-6.0/lib");
// println!("cargo:rustc-link-lib={}", "lldb-6.0");
}
#[cfg(target_os = "macos")]
{
println!("cargo:rustc-link-search={}/lib", std::env::var("LLDB_ROOT").unwrap());
println!("cargo:rustc-link-lib={}", "lldb");
}
#[cfg(windows)]
{
println!("cargo:rustc-link-search={}/lib", std::env::var("LLDB_ROOT").unwrap());
println!("cargo:rustc-link-lib={}", "liblldb");
}
}
|
use fltk::{prelude::*, *};
use fltk_flex::Flex;
fn main() {
let a = app::App::default().with_scheme(app::Scheme::Gtk);
let mut win = window::Window::default().with_size(400, 300);
{
let mut flex = Flex::default().size_of_parent().column();
{
frame::Frame::default(); // filler
let mut normal1 = button::Button::default().with_label("Normal1");
let mut normal2 = button::Button::default().with_label("Normal2");
frame::Frame::default(); // filler
flex.set_size(&mut normal1, 30);
flex.set_size(&mut normal2, 30);
flex.end();
normal1.set_callback(|b| println!("{}", b.label()));
normal2.set_callback(|b| println!("{}", b.label()));
}
win.end();
win.make_resizable(true);
win.show();
}
a.run().unwrap();
} |
use chrono::{DateTime, Local};
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
pub type Symbol = String;
pub type OrderId = i64;
pub type Price = i64;
pub type Qty = i64;
pub type Timestamp = DateTime<Local>;
#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Side {
Buy,
Sell,
}
#[allow(dead_code)]
impl Side {
fn other(self) -> Side {
match self {
Side::Buy => Side::Sell,
Side::Sell => Side::Buy,
}
}
}
pub type UserId = i64;
#[allow(dead_code)]
pub struct UserInfo {
user_id: UserId,
user_name: String,
position: HashMap<String, i32>,
pnl: i64,
}
|
pub trait Readable {}
pub trait Writable {}
#[derive(Debug, Copy, Clone)]
pub struct ReadWrite;
impl Readable for ReadWrite {}
impl Writable for ReadWrite {}
#[derive(Debug, Copy, Clone)]
pub struct ReadOnly;
impl Readable for ReadOnly {}
#[derive(Debug, Copy, Clone)]
pub struct WriteOnly;
impl Writable for WriteOnly {}
|
//! Mods Interface
use std::ffi::OsStr;
use std::path::Path;
use mime::{APPLICATION_OCTET_STREAM, IMAGE_STAR};
use url::{form_urlencoded, Url};
use crate::error::ErrorKind;
use crate::files::{FileRef, Files};
use crate::metadata::Metadata;
use crate::multipart::{FileSource, FileStream};
use crate::prelude::*;
use crate::teams::Members;
use crate::Comments;
pub use crate::types::mods::{
Dependency, Event, EventType, Image, MaturityOption, Media, MetadataMap, Mod, Popularity,
Ratings, Statistics, Tag, Visibility,
};
pub use crate::types::Logo;
pub use crate::types::Status;
/// Interface for mods the authenticated user added or is team member of.
pub struct MyMods {
modio: Modio,
}
impl MyMods {
pub(crate) fn new(modio: Modio) -> Self {
Self { modio }
}
/// List all mods the authenticated user added or is team member of. [required: token]
///
/// See [Filters and sorting](filters/index.html).
pub fn list(&self, filter: &Filter) -> Future<List<Mod>> {
token_required!(self.modio);
let mut uri = vec!["/me/mods".to_owned()];
let query = filter.to_query_string();
if !query.is_empty() {
uri.push(query);
}
self.modio.get(&uri.join("?"))
}
/// Provides a stream over mods the authenticated user added or is team member of. [required:
/// token]
///
/// See [Filters and sorting](filters/index.html).
pub fn iter(&self, filter: &Filter) -> Stream<Mod> {
token_required!(s self.modio);
let mut uri = vec!["/me/mods".to_owned()];
let query = filter.to_query_string();
if !query.is_empty() {
uri.push(query);
}
self.modio.stream(&uri.join("?"))
}
}
/// Interface for mods of a game.
pub struct Mods {
modio: Modio,
game: u32,
}
impl Mods where {
pub(crate) fn new(modio: Modio, game: u32) -> Self {
Self { modio, game }
}
fn path(&self, more: &str) -> String {
format!("/games/{}/mods{}", self.game, more)
}
/// Return a reference to a mod.
pub fn get(&self, id: u32) -> ModRef {
ModRef::new(self.modio.clone(), self.game, id)
}
/// List all mods.
///
/// See [Filters and sorting](filters/index.html).
pub fn list(&self, filter: &Filter) -> Future<List<Mod>> {
let mut uri = vec![self.path("")];
let query = filter.to_query_string();
if !query.is_empty() {
uri.push(query);
}
self.modio.get(&uri.join("?"))
}
/// Provides a stream over all mods of the game.
///
/// See [Filters and sorting](filters/index.html).
pub fn iter(&self, filter: &Filter) -> Stream<Mod> {
let mut uri = vec![self.path("")];
let query = filter.to_query_string();
if !query.is_empty() {
uri.push(query);
}
self.modio.stream(&uri.join("?"))
}
/// Add a mod and return the newly created Modio mod object. [required: token]
pub fn add(&self, options: AddModOptions) -> Future<Mod> {
token_required!(self.modio);
self.modio.post_form(&self.path(""), options)
}
/// Provides a stream over the statistics for all mods of a game.
///
/// See [Filters and sorting](filters/stats/index.html).
pub fn statistics(&self, filter: &Filter) -> Stream<Statistics> {
let mut uri = vec![self.path("/stats")];
let query = filter.to_query_string();
if !query.is_empty() {
uri.push(query);
}
self.modio.stream(&uri.join("?"))
}
/// Provides a stream over the event log for all mods of a game sorted by latest event first.
///
/// See [Filters and sorting](filters/events/index.html).
pub fn events(&self, filter: &Filter) -> Stream<Event> {
let mut uri = vec![self.path("/events")];
let query = filter.to_query_string();
if !query.is_empty() {
uri.push(query);
}
self.modio.stream(&uri.join("?"))
}
}
/// Reference interface of a mod.
pub struct ModRef {
modio: Modio,
game: u32,
id: u32,
}
impl ModRef {
pub(crate) fn new(modio: Modio, game: u32, id: u32) -> Self {
Self { modio, game, id }
}
fn path(&self, more: &str) -> String {
format!("/games/{}/mods/{}{}", self.game, self.id, more)
}
/// Get a reference to the Modio mod object that this `ModRef` refers to.
pub fn get(&self) -> Future<Mod> {
self.modio.get(&self.path(""))
}
/// Return a reference to an interface that provides access to the files of a mod.
pub fn files(&self) -> Files {
Files::new(self.modio.clone(), self.game, self.id)
}
/// Return a reference to a file of a mod.
pub fn file(&self, id: u32) -> FileRef {
FileRef::new(self.modio.clone(), self.game, self.id, id)
}
/// Return a reference to an interface to manage metadata key value pairs of a mod.
pub fn metadata(&self) -> Metadata {
Metadata::new(self.modio.clone(), self.game, self.id)
}
/// Return a reference to an interface to manage the tags of a mod.
pub fn tags(&self) -> Endpoint<Tag> {
Endpoint::new(self.modio.clone(), self.path("/tags"))
}
/// Return a reference to an interface that provides access to the comments of a mod.
pub fn comments(&self) -> Comments {
Comments::new(self.modio.clone(), self.game, self.id)
}
/// Return a reference to an interface to manage the dependencies of a mod.
pub fn dependencies(&self) -> Endpoint<Dependency> {
Endpoint::new(self.modio.clone(), self.path("/dependencies"))
}
/// Return the statistics for a mod.
pub fn statistics(&self) -> Future<Statistics> {
self.modio.get(&self.path("/stats"))
}
/// Provides a stream over the event log for a mod sorted by latest event first.
///
/// See [Filters and sorting](filters/events/index.html).
pub fn events(&self, filter: &Filter) -> Stream<Event> {
let mut uri = vec![self.path("/events")];
let query = filter.to_query_string();
if !query.is_empty() {
uri.push(query);
}
self.modio.stream(&uri.join("?"))
}
/// Return a reference to an interface to manage team members of a mod.
pub fn members(&self) -> Members {
Members::new(self.modio.clone(), self.game, self.id)
}
/// Edit details for a mod. [required: token]
pub fn edit(&self, options: &EditModOptions) -> Future<EntityResult<Mod>> {
token_required!(self.modio);
let params = options.to_query_string();
self.modio.put(&self.path(""), params)
}
/// Add new media to a mod. [required: token]
pub fn add_media(&self, options: AddMediaOptions) -> Future<()> {
token_required!(self.modio);
Box::new(
self.modio
.post_form::<ModioMessage, _>(&self.path("/media"), options)
.map(|_| ()),
)
}
/// Delete media from a mod. [required: token]
pub fn delete_media(&self, options: &DeleteMediaOptions) -> Future<()> {
token_required!(self.modio);
self.modio
.delete(&self.path("/media"), options.to_query_string())
}
/// Submit a positive or negative rating for a mod. [required: token]
pub fn rate(&self, rating: Rating) -> Future<()> {
token_required!(self.modio);
let params = rating.to_query_string();
Box::new(
self.modio
.post::<ModioMessage, _>(&self.path("/ratings"), params)
.map(|_| ())
.or_else(|err| match err.kind() {
ErrorKind::Fault {
code: StatusCode::BAD_REQUEST,
..
} => Ok(()),
_ => Err(err),
}),
)
}
/// Subscribe the authenticated user to a mod. [required: token]
pub fn subscribe(&self) -> Future<()> {
token_required!(self.modio);
Box::new(
self.modio
.post::<Mod, _>(&self.path("/subscribe"), RequestBody::Empty)
.map(|_| ())
.or_else(|err| match err.kind() {
ErrorKind::Fault {
code: StatusCode::BAD_REQUEST,
..
} => Ok(()),
_ => Err(err),
}),
)
}
/// Unsubscribe the authenticated user from a mod. [required: token]
pub fn unsubscribe(&self) -> Future<()> {
token_required!(self.modio);
Box::new(
self.modio
.delete(&self.path("/subscribe"), RequestBody::Empty)
.or_else(|err| match err.kind() {
ErrorKind::Fault {
code: StatusCode::BAD_REQUEST,
..
} => Ok(()),
_ => Err(err),
}),
)
}
}
/// Mod filters & sorting
///
/// # Filters
/// - Fulltext
/// - Id
/// - GameId
/// - Status
/// - Visible
/// - SubmittedBy
/// - DateAdded
/// - DateUpdated
/// - DateLive
/// - MaturityOption
/// - Name
/// - NameId
/// - Summary
/// - Description
/// - Homepage
/// - Modfile
/// - MetadataBlob
/// - MetadataKVP
/// - Tags
///
/// # Sorting
/// - Id
/// - Name
/// - Downloads
/// - Popular
/// - Ratings
/// - Subscribers
///
/// See the [modio docs](https://docs.mod.io/#get-all-mods) for more information.
///
/// By default this returns up to `100` items. you can limit the result by using `limit` and
/// `offset`.
///
/// # Example
/// ```
/// use modio::filter::prelude::*;
/// use modio::mods::filters::Id;
/// use modio::mods::filters::GameId;
/// use modio::mods::filters::Tags;
///
/// let filter = Id::_in(vec![1, 2]).order_by(Id::desc());
///
/// let filter = GameId::eq(6).and(Tags::eq("foobar")).limit(10);
/// ```
#[rustfmt::skip]
pub mod filters {
#[doc(inline)]
pub use crate::filter::prelude::Fulltext;
#[doc(inline)]
pub use crate::filter::prelude::Id;
#[doc(inline)]
pub use crate::filter::prelude::Name;
#[doc(inline)]
pub use crate::filter::prelude::NameId;
#[doc(inline)]
pub use crate::filter::prelude::Status;
#[doc(inline)]
pub use crate::filter::prelude::DateAdded;
#[doc(inline)]
pub use crate::filter::prelude::DateUpdated;
#[doc(inline)]
pub use crate::filter::prelude::DateLive;
#[doc(inline)]
pub use crate::filter::prelude::SubmittedBy;
filter!(GameId, GAME_ID, "game_id", Eq, NotEq, In, Cmp, OrderBy);
filter!(Visible, VISIBLE, "visible", Eq);
filter!(MaturityOption, MATURITY_OPTION, "maturity_option", Eq, Cmp, Bit);
filter!(Summary, SUMMARY, "summary", Like);
filter!(Description, DESCRIPTION, "description", Like);
filter!(Homepage, HOMEPAGE, "homepage_url", Eq, NotEq, Like, In);
filter!(Modfile, MODFILE, "modfile", Eq, NotEq, In, Cmp);
filter!(MetadataBlob, METADATA_BLOB, "metadata_blob", Eq, NotEq, Like);
filter!(MetadataKVP, METADATA_KVP, "metadata_kvp", Eq, NotEq, Like);
filter!(Tags, TAGS, "tags", Eq, NotEq, Like);
filter!(Downloads, DOWNLOADS, "downloads", OrderBy);
filter!(Popular, POPULAR, "popular", OrderBy);
filter!(Ratings, RATINGS, "ratings", OrderBy);
filter!(Subscribers, SUBSCRIBERS, "subscribers", OrderBy);
/// Mod event filters and sorting.
///
/// # Filters
/// - Id
/// - ModId
/// - UserId
/// - DateAdded
/// - EventType
///
/// # Sorting
/// - Id
/// - DateAdded
///
/// See the [modio docs](https://docs.mod.io/#events) for more information.
///
/// By default this returns up to `100` items. You can limit the result by using `limit` and
/// `offset`.
///
/// # Example
/// ```
/// use modio::filter::prelude::*;
/// use modio::mods::filters::events::EventType as Filter;
/// use modio::mods::EventType;
///
/// let filter = Id::gt(1024).and(Filter::eq(EventType::ModfileChanged));
/// ```
pub mod events {
#[doc(inline)]
pub use crate::filter::prelude::Id;
#[doc(inline)]
pub use crate::filter::prelude::ModId;
#[doc(inline)]
pub use crate::filter::prelude::DateAdded;
filter!(UserId, USER_ID, "user_id", Eq, NotEq, In, Cmp, OrderBy);
filter!(EventType, EVENT_TYPE, "event_type", Eq, NotEq, In, OrderBy);
}
/// Mod statistics filters & sorting
///
/// # Filters
/// - ModId
/// - Popularity
/// - Downloads
/// - Subscribers
/// - RatingsPositive
/// - RatingsNegative
///
/// # Sorting
/// - ModId
/// - Popularity
/// - Downloads
/// - Subscribers
/// - RatingsPositive
/// - RatingsNegative
///
/// # Example
/// ```
/// use modio::filter::prelude::*;
/// use modio::mods::filters::stats::ModId;
/// use modio::mods::filters::stats::Popularity;
///
/// let filter = ModId::_in(vec![1, 2]).order_by(Popularity::desc());
/// ```
pub mod stats {
#[doc(inline)]
pub use crate::filter::prelude::ModId;
filter!(Popularity, POPULARITY, "popularity_rank_position", Eq, NotEq, In, Cmp, OrderBy);
filter!(Downloads, DOWNLOADS, "downloads_total", Eq, NotEq, In, Cmp, OrderBy);
filter!(Subscribers, SUBSCRIBERS, "subscribers_total", Eq, NotEq, In, Cmp, OrderBy);
filter!(RatingsPositive, RATINGS_POSITIVE, "ratings_positive", Eq, NotEq, In, Cmp, OrderBy);
filter!(RatingsNegative, RATINGS_NEGATIVE, "ratings_negative", Eq, NotEq, In, Cmp, OrderBy);
}
}
#[derive(Clone, Copy)]
pub enum Rating {
Positive,
Negative,
}
impl QueryString for Rating {
fn to_query_string(&self) -> String {
format!(
"rating={}",
match *self {
Rating::Negative => -1,
Rating::Positive => 1,
}
)
}
}
pub struct AddModOptions {
visible: Option<Visibility>,
logo: FileSource,
name: String,
name_id: Option<String>,
summary: String,
description: Option<String>,
homepage_url: Option<Url>,
stock: Option<u32>,
maturity_option: Option<MaturityOption>,
metadata_blob: Option<String>,
tags: Option<Vec<String>>,
}
impl AddModOptions {
pub fn new<T, P>(name: T, logo: P, summary: T) -> AddModOptions
where
T: Into<String>,
P: AsRef<Path>,
{
let filename = logo
.as_ref()
.file_name()
.and_then(OsStr::to_str)
.map_or_else(String::new, ToString::to_string);
let logo = FileSource {
inner: FileStream::open(logo),
filename,
mime: IMAGE_STAR,
};
AddModOptions {
name: name.into(),
logo,
summary: summary.into(),
visible: None,
name_id: None,
description: None,
homepage_url: None,
stock: None,
maturity_option: None,
metadata_blob: None,
tags: None,
}
}
pub fn visible(self, v: bool) -> Self {
Self {
visible: if v {
Some(Visibility::Public)
} else {
Some(Visibility::Hidden)
},
..self
}
}
option!(name_id);
option!(description);
option!(homepage_url: Url);
option!(stock: u32);
option!(maturity_option: MaturityOption);
option!(metadata_blob);
pub fn tags(self, tags: &[String]) -> Self {
Self {
tags: Some(tags.to_vec()),
..self
}
}
}
#[doc(hidden)]
impl From<AddModOptions> for Form {
fn from(opts: AddModOptions) -> Form {
let mut form = Form::new();
form = form.text("name", opts.name).text("summary", opts.summary);
if let Some(visible) = opts.visible {
form = form.text("visible", visible.to_string());
}
if let Some(name_id) = opts.name_id {
form = form.text("name_id", name_id);
}
if let Some(desc) = opts.description {
form = form.text("description", desc);
}
if let Some(url) = opts.homepage_url {
form = form.text("homepage_url", url.to_string());
}
if let Some(stock) = opts.stock {
form = form.text("stock", stock.to_string());
}
if let Some(maturity_option) = opts.maturity_option {
form = form.text("maturity_option", maturity_option.to_string());
}
if let Some(metadata_blob) = opts.metadata_blob {
form = form.text("metadata_blob", metadata_blob);
}
if let Some(tags) = opts.tags {
for tag in tags {
form = form.text("tags[]", tag);
}
}
form.part("logo", opts.logo.into())
}
}
#[derive(Debug, Default)]
pub struct EditModOptions {
params: std::collections::BTreeMap<&'static str, String>,
}
impl EditModOptions {
option!(status: Status >> "status");
pub fn visible(self, v: bool) -> Self {
let value = if v {
Visibility::Public
} else {
Visibility::Hidden
};
let mut params = self.params;
params.insert("visible", value.to_string());
Self { params }
}
option!(visibility: Visibility >> "visible");
option!(name >> "name");
option!(name_id >> "name_id");
option!(summary >> "summary");
option!(description >> "description");
option!(homepage_url: Url >> "homepage_url");
option!(stock >> "stock");
option!(maturity_option: MaturityOption >> "maturity_option");
option!(metadata_blob >> "metadata_blob");
}
impl QueryString for EditModOptions {
fn to_query_string(&self) -> String {
form_urlencoded::Serializer::new(String::new())
.extend_pairs(&self.params)
.finish()
}
}
#[doc(hidden)]
#[deprecated(since = "0.4.1", note = "Use `EditDependenciesOptions`")]
pub type EditDepencenciesOptions = EditDependenciesOptions;
pub struct EditDependenciesOptions {
dependencies: Vec<u32>,
}
impl EditDependenciesOptions {
pub fn new(dependencies: &[u32]) -> Self {
Self {
dependencies: dependencies.to_vec(),
}
}
pub fn one(dependency: u32) -> Self {
Self {
dependencies: vec![dependency],
}
}
}
impl AddOptions for EditDependenciesOptions {}
impl DeleteOptions for EditDependenciesOptions {}
impl QueryString for EditDependenciesOptions {
fn to_query_string(&self) -> String {
form_urlencoded::Serializer::new(String::new())
.extend_pairs(
self.dependencies
.iter()
.map(|d| ("dependencies[]", d.to_string())),
)
.finish()
}
}
pub struct EditTagsOptions {
tags: Vec<String>,
}
impl EditTagsOptions {
pub fn new(tags: &[String]) -> Self {
Self {
tags: tags.to_vec(),
}
}
}
impl AddOptions for EditTagsOptions {}
impl DeleteOptions for EditTagsOptions {}
impl QueryString for EditTagsOptions {
fn to_query_string(&self) -> String {
form_urlencoded::Serializer::new(String::new())
.extend_pairs(self.tags.iter().map(|t| ("tags[]", t)))
.finish()
}
}
#[derive(Default)]
pub struct AddMediaOptions {
logo: Option<FileSource>,
images_zip: Option<FileSource>,
images: Option<Vec<FileSource>>,
youtube: Option<Vec<String>>,
sketchfab: Option<Vec<String>>,
}
impl AddMediaOptions {
pub fn logo<P: AsRef<Path>>(self, logo: P) -> Self {
let logo = logo.as_ref();
let filename = logo
.file_name()
.and_then(OsStr::to_str)
.map_or_else(String::new, ToString::to_string);
Self {
logo: Some(FileSource {
inner: FileStream::open(logo),
filename,
mime: IMAGE_STAR,
}),
..self
}
}
pub fn images_zip<P: AsRef<Path>>(self, images: P) -> Self {
Self {
images_zip: Some(FileSource {
inner: FileStream::open(images),
filename: "images.zip".into(),
mime: APPLICATION_OCTET_STREAM,
}),
..self
}
}
pub fn images<P: AsRef<Path>>(self, images: &[P]) -> Self {
Self {
images: Some(
images
.iter()
.map(|p| {
let file = p.as_ref();
let filename = file
.file_name()
.and_then(OsStr::to_str)
.map_or_else(String::new, ToString::to_string);
FileSource {
inner: FileStream::open(file),
filename,
mime: IMAGE_STAR,
}
})
.collect::<Vec<_>>(),
),
..self
}
}
pub fn youtube(self, urls: &[String]) -> Self {
Self {
youtube: Some(urls.to_vec()),
..self
}
}
pub fn sketchfab(self, urls: &[String]) -> Self {
Self {
sketchfab: Some(urls.to_vec()),
..self
}
}
}
#[doc(hidden)]
impl From<AddMediaOptions> for Form {
fn from(opts: AddMediaOptions) -> Form {
let mut form = Form::new();
if let Some(logo) = opts.logo {
form = form.part("logo", logo.into());
}
if let Some(zip) = opts.images_zip {
form = form.part("images", zip.into());
}
if let Some(images) = opts.images {
for (i, image) in images.into_iter().enumerate() {
form = form.part(format!("image{}", i), image.into());
}
}
if let Some(youtube) = opts.youtube {
for url in youtube {
form = form.text("youtube[]", url);
}
}
if let Some(sketchfab) = opts.sketchfab {
for url in sketchfab {
form = form.text("sketchfab[]", url);
}
}
form
}
}
#[derive(Default)]
pub struct DeleteMediaOptions {
images: Option<Vec<String>>,
youtube: Option<Vec<String>>,
sketchfab: Option<Vec<String>>,
}
impl DeleteMediaOptions {
pub fn images(self, images: &[String]) -> Self {
Self {
images: Some(images.to_vec()),
..self
}
}
pub fn youtube(self, urls: &[String]) -> Self {
Self {
youtube: Some(urls.to_vec()),
..self
}
}
pub fn sketchfab(self, urls: &[String]) -> Self {
Self {
sketchfab: Some(urls.to_vec()),
..self
}
}
}
impl QueryString for DeleteMediaOptions {
fn to_query_string(&self) -> String {
let mut ser = form_urlencoded::Serializer::new(String::new());
if let Some(ref images) = self.images {
ser.extend_pairs(images.iter().map(|i| ("images[]", i)));
}
if let Some(ref urls) = self.youtube {
ser.extend_pairs(urls.iter().map(|u| ("youtube[]", u)));
}
if let Some(ref urls) = self.sketchfab {
ser.extend_pairs(urls.iter().map(|u| ("sketchfab[]", u)));
}
ser.finish()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.