text stringlengths 8 4.13M |
|---|
mod exclusive_aarch64;
pub use self::exclusive_aarch64::*;
|
//! editline port
use libc::*;
#[link(name = "readline")] extern "C" {
fn using_history();
fn add_history(p: *const c_char) -> c_int;
fn clear_history();
fn read_history(f: *const c_char) -> c_int;
fn write_history(f: *const c_char) -> c_int;
fn readline(prompt: *const c_char) -> *mut c_char;
}
use std::ptr::null;
use std::ffi::{CString, CStr};
use std::str::Utf8Error;
pub struct MallocStr(*mut c_char);
impl Drop for MallocStr { fn drop(&mut self) { unsafe { free(self.0 as *mut _) } } }
impl MallocStr
{
pub fn as_str(&self) -> Result<&str, Utf8Error> { unsafe { CStr::from_ptr(self.0).to_str() } }
}
pub struct Readline(Option<CString>);
impl Readline {
pub fn init(historyfile: Option<&str>) -> Self {
let historyfile_c = historyfile.map(|p| CString::new(p).unwrap());
unsafe {
using_history();
read_history(historyfile_c.as_ref().map(|x| x.as_ptr()).unwrap_or_else(null));
}
Readline(historyfile_c)
}
pub fn readline(&self, prompt: &str) -> Option<MallocStr> {
let prompt_c = CString::new(prompt).unwrap();
unsafe {
let p = readline(prompt_c.as_ptr());
if p.is_null() { return None; }
add_history(p);
Some(MallocStr(p))
}
}
}
impl Drop for Readline {
fn drop(&mut self) {
unsafe { write_history(self.0.as_ref().map(|x| x.as_ptr()).unwrap_or_else(null)); }
}
}
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(generators, generator_trait)]
use std::ops::{Generator, GeneratorState};
fn main() {
let mut generator = static || {
let a = true;
let b = &a;
yield;
assert_eq!(b as *const _, &a as *const _);
};
unsafe {
assert_eq!(generator.resume(), GeneratorState::Yielded(()));
assert_eq!(generator.resume(), GeneratorState::Complete(()));
}
}
|
#[cfg(feature = "video")]
mod av_device;
#[cfg(feature = "video")]
pub use self::av_device::*;
|
use observability_deps::tracing::*;
use std::{sync::Arc, time::Duration};
use crate::{
partition_iter::PartitionIter,
persist::{drain_buffer::persist_partitions, queue::PersistQueue},
wal::reference_tracker::WalReferenceHandle,
};
/// Rotate the `wal` segment file every `period` duration of time, notifying
/// the [`WalReferenceHandle`].
pub(crate) async fn periodic_rotation<T, P>(
wal: Arc<wal::Wal>,
period: Duration,
wal_reference_handle: WalReferenceHandle,
buffer: T,
persist: P,
) where
T: PartitionIter + Sync + 'static,
P: PersistQueue + Clone + 'static,
{
let mut interval = tokio::time::interval(period);
// The first tick completes immediately. We want to wait one interval before rotating the wal
// and persisting for the first time, so tick once outside the loop first.
interval.tick().await;
loop {
interval.tick().await;
info!("rotating wal file");
let (stats, ids) = wal.rotate().expect("failed to rotate WAL");
debug!(
closed_id = %stats.id(),
segment_bytes = stats.size(),
n_ops = ids.len(),
"rotated wal"
);
wal_reference_handle
.enqueue_rotated_file(stats.id(), ids)
.await;
// Do not block the ticker while partitions are persisted to ensure
// timely ticking.
//
// This ticker loop MUST make progress and periodically enqueue
// partition data to the persist system - this ensures that given a
// blocked persist system (i.e. object store outage) the persist queue
// grows until it reaches saturation and the ingester rejects writes. If
// the persist ticker does not make progress, the buffer tree grows
// instead of the persist queue, until the ingester OOMs.
//
// There's no need to retain a handle to the task here; any panics are
// fatal, and nothing needs to wait for completion (except graceful
// shutdown, which works without having to wait for notifications from
// in-flight persists, but rather evaluates the buffer tree state to
// determine completeness instead). The spawned task eventually deletes
// the right WAL segment regardless of concurrent tasks.
tokio::spawn({
let persist = persist.clone();
let iter = buffer.partition_iter();
async move {
// Drain the BufferTree of partition data and persist each one.
//
// Writes that landed into the partition buffer after the rotation but
// before the partition data is read will be included in the parquet
// file, but this is not a problem in the happy case (they will not
// appear in the next persist too).
//
// In the case of an ingester crash after these partitions (with their
// extra writes) have been persisted, the ingester will replay them and
// re-persist them, causing a small number of duplicate writes to be
// present in object storage that must be asynchronously compacted later
// - a small price to pay for not having to block ingest while the WAL
// is rotated, all outstanding writes + queries complete, and all then
// partitions are marked as persisting.
persist_partitions(iter, &persist).await;
debug!(
closed_id = %stats.id(),
"partitions persisted"
);
}
});
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use assert_matches::assert_matches;
use async_trait::async_trait;
use parking_lot::Mutex;
use tempfile::tempdir;
use test_helpers::timeout::FutureTimeout;
use tokio::sync::oneshot;
use wal::WriteResult;
use super::*;
use crate::{
buffer_tree::partition::{persisting::PersistingData, PartitionData},
dml_payload::IngestOp,
persist::queue::mock::MockPersistQueue,
test_util::{
make_write_op, new_persist_notification, PartitionDataBuilder, ARBITRARY_NAMESPACE_ID,
ARBITRARY_PARTITION_KEY, ARBITRARY_TABLE_ID, ARBITRARY_TABLE_NAME,
ARBITRARY_TRANSITION_PARTITION_ID,
},
wal::traits::WalAppender,
};
const TICK_INTERVAL: Duration = Duration::from_millis(10);
#[tokio::test]
async fn test_notify_rotate_persist() {
let metrics = metric::Registry::default();
// Create a write operation to stick in the WAL, and create a partition
// iter from the data within it to mock out the buffer tree.
let write_op = make_write_op(
&ARBITRARY_PARTITION_KEY,
ARBITRARY_NAMESPACE_ID,
&ARBITRARY_TABLE_NAME,
ARBITRARY_TABLE_ID,
1,
&format!(
r#"{},city=London people=2,pigeons="millions" 10"#,
&*ARBITRARY_TABLE_NAME
),
None,
);
let mut p = PartitionDataBuilder::new().build();
for (_, table_data) in write_op.tables() {
let partitioned_data = table_data.partitioned_data();
p.buffer_write(
partitioned_data.data().clone(),
partitioned_data.sequence_number(),
)
.expect("write should succeed");
}
// Wrap the partition in the lock.
assert_eq!(p.completed_persistence_count(), 0);
let p = Arc::new(Mutex::new(p));
// Initialise a mock persist queue to inspect the calls made to the
// persist subsystem.
let persist_handle = Arc::new(MockPersistQueue::default());
// Initialise the WAL, write the operation to it
let tmp_dir = tempdir().expect("no temp dir available");
let wal = wal::Wal::new(tmp_dir.path())
.await
.expect("failed to initialise WAL");
assert_eq!(wal.closed_segments().len(), 0);
let mut write_result = wal.append(&IngestOp::Write(write_op));
write_result
.changed()
.await
.expect("should be able to get WAL write result");
assert_matches!(
write_result
.borrow()
.as_ref()
.expect("WAL should always return result"),
WriteResult::Ok(_),
"test write should succeed"
);
let (wal_reference_handle, wal_reference_actor) =
WalReferenceHandle::new(Arc::clone(&wal), &metrics);
tokio::spawn(wal_reference_actor.run());
// Start the rotation task
let rotate_task_handle = tokio::spawn(periodic_rotation(
Arc::clone(&wal),
TICK_INTERVAL,
wal_reference_handle.clone(),
vec![Arc::clone(&p)],
Arc::clone(&persist_handle),
));
tokio::time::pause();
tokio::time::advance(TICK_INTERVAL).await;
tokio::time::resume();
// Wait for the WAL to rotate, causing 1 closed segment to exist.
async {
loop {
if !wal.closed_segments().is_empty() {
return;
}
tokio::task::yield_now().await;
}
}
.with_timeout_panic(Duration::from_secs(5))
.await;
// There should be exactly 1 segment.
let mut segments = wal.closed_segments();
assert_eq!(segments.len(), 1);
let closed_segment = segments.pop().unwrap();
// Send a persistence notification to allow the actor to delete
// the WAL file
wal_reference_handle
.enqueue_persist_notification(new_persist_notification([1]))
.await;
// Wait for the closed segment to no longer appear in the WAL,
// indicating deletion
async {
loop {
if wal
.closed_segments()
.iter()
.all(|s| s.id() != closed_segment.id())
{
break;
}
tokio::task::yield_now().await;
}
}
.with_timeout_panic(Duration::from_secs(5))
.await;
// Stop the task and assert the state of the persist queue
rotate_task_handle.abort();
assert_matches!(persist_handle.calls().as_slice(), [got] => {
let guard = got.lock();
assert_eq!(guard.partition_id(), &*ARBITRARY_TRANSITION_PARTITION_ID);
})
}
/// A [`PersistQueue`] implementation that never completes a persist task
/// and therefore never signals completion of any persist task.
///
/// This simulates a persist system where all workers cannot make progress;
/// for example, an object store outage or catalog unavailability.
#[derive(Debug, Default)]
struct BlockedPersistQueue {
/// Observed PartitionData instances.
calls: Mutex<Vec<Arc<Mutex<PartitionData>>>>,
// The tx handles that callers are blocked waiting on.
tx: Mutex<Vec<oneshot::Sender<()>>>,
}
#[async_trait]
impl PersistQueue for BlockedPersistQueue {
#[allow(clippy::async_yields_async)]
async fn enqueue(
&self,
partition: Arc<Mutex<PartitionData>>,
_data: PersistingData,
) -> oneshot::Receiver<()> {
self.calls.lock().push(Arc::clone(&partition));
let (tx, rx) = oneshot::channel();
self.tx.lock().push(tx);
rx
}
}
#[tokio::test]
async fn test_persist_ticks_when_blocked() {
let metrics = metric::Registry::default();
// Create a write operation to stick in the WAL, and create a partition
// iter from the data within it to mock out the buffer tree.
let write_op = make_write_op(
&ARBITRARY_PARTITION_KEY,
ARBITRARY_NAMESPACE_ID,
&ARBITRARY_TABLE_NAME,
ARBITRARY_TABLE_ID,
1,
&format!(
r#"{},city=London people=2,pigeons="millions" 10"#,
&*ARBITRARY_TABLE_NAME
),
None,
);
let mut p = PartitionDataBuilder::new().build();
for (_, table_data) in write_op.tables() {
let partitioned_data = table_data.partitioned_data();
p.buffer_write(
partitioned_data.data().clone(),
partitioned_data.sequence_number(),
)
.expect("write should succeed");
}
// Wrap the partition in the lock.
assert_eq!(p.completed_persistence_count(), 0);
let p = Arc::new(Mutex::new(p));
// Initialise a mock persist queue that never completes.
let persist_handle = Arc::new(BlockedPersistQueue::default());
// Initialise the WAL
let tmp_dir = tempdir().expect("no temp dir available");
let wal = wal::Wal::new(tmp_dir.path())
.await
.expect("failed to initialise WAL");
assert_eq!(wal.closed_segments().len(), 0);
let mut write_result = wal.append(&IngestOp::Write(write_op.clone()));
write_result
.changed()
.await
.expect("should be able to get WAL write result");
assert_matches!(
write_result
.borrow()
.as_ref()
.expect("WAL should always return result"),
WriteResult::Ok(_),
"test write should succeed"
);
let (wal_reference_handle, wal_reference_actor) =
WalReferenceHandle::new(Arc::clone(&wal), &metrics);
tokio::spawn(wal_reference_actor.run());
// Start the rotation task
let rotate_task_handle = tokio::spawn(periodic_rotation(
Arc::clone(&wal),
TICK_INTERVAL,
wal_reference_handle,
vec![Arc::clone(&p)],
Arc::clone(&persist_handle),
));
tokio::time::pause();
tokio::time::advance(TICK_INTERVAL).await;
tokio::time::resume();
// Wait for the WAL to rotate, causing 1 closed segment to exist.
async {
loop {
if !wal.closed_segments().is_empty() {
return;
}
tokio::task::yield_now().await;
}
}
.with_timeout_panic(Duration::from_secs(5))
.await;
// There should be exactly 1 segment.
let mut segment = wal.closed_segments();
assert_eq!(segment.len(), 1);
let segment = segment.pop().unwrap();
// Move past the hacky sleep.
tokio::time::pause();
tokio::time::advance(Duration::from_secs(10)).await;
tokio::time::resume();
// Wait for the WAL segment to be deleted, indicating the end of
// processing of the first loop.
async {
loop {
match wal.closed_segments().pop() {
Some(closed) if closed.id() != segment.id() => {
// Rotation has occurred.
break closed;
}
// Rotation has not yet occurred.
Some(_) => tokio::task::yield_now().await,
// The old file was deleted and no new one has taken its
// place.
None => unreachable!(),
}
}
}
.with_timeout_panic(Duration::from_secs(5))
.await;
// Pause the ticker loop and buffer another write in the partition.
for (i, (_, table_data)) in write_op.tables().enumerate() {
let partitioned_data = table_data.partitioned_data();
p.lock()
.buffer_write(
partitioned_data.data().clone(),
partitioned_data.sequence_number() + i as u64 + 1,
)
.expect("write should succeed");
}
// Cause another tick to occur, driving the loop again.
tokio::time::pause();
tokio::time::advance(TICK_INTERVAL).await;
tokio::time::resume();
// Wait the second tick to complete.
async {
loop {
if persist_handle.calls.lock().len() == 2 {
break;
}
tokio::task::yield_now().await;
}
}
.with_timeout_panic(Duration::from_secs(5))
.await;
// Stop the worker and assert the state of the persist queue.
rotate_task_handle.abort();
let calls = persist_handle.calls.lock().clone();
assert_matches!(calls.as_slice(), [got1, got2] => {
assert!(Arc::ptr_eq(got1, got2));
})
}
}
|
fn main() {
// GetProcessHeap returns HeapHandle. So including GetProcessHeap
// should also include HeapHandle.
windows::core::build_legacy! {
Windows::Win32::System::Memory::GetProcessHeap,
};
// Note: don't add anything else to this build macro!
}
|
mod catalan;
mod stirling_s1;
mod stirling_s2;
|
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
pub mod adaptor;
pub mod admin;
pub mod node;
pub mod utils;
pub mod sensei {
use senseicore::node::{
LocalInvoice, LocalInvoiceFeatures, LocalRouteHint, LocalRouteHintHop, LocalRoutingFees,
};
tonic::include_proto!("sensei");
impl From<LocalInvoice> for Invoice {
fn from(invoice: LocalInvoice) -> Self {
Invoice {
payment_hash: invoice.payment_hash,
currency: invoice.currency,
amount: invoice.amount,
description: invoice.description,
expiry: invoice.expiry,
timestamp: invoice.timestamp,
min_final_cltv_expiry: invoice.min_final_cltv_expiry,
route_hints: invoice
.route_hints
.into_iter()
.map(|h| LocalRouteHint::from(&h).into())
.collect(),
features: invoice.features.map(|f| f.into()),
payee_pub_key: invoice.payee_pub_key.to_string(),
}
}
}
impl From<LocalRouteHint> for RouteHint {
fn from(hint: LocalRouteHint) -> Self {
Self {
hops: hint
.hops
.into_iter()
.map(|h| LocalRouteHintHop::from(&h).into())
.collect(),
}
}
}
impl From<LocalRouteHintHop> for RouteHintHop {
fn from(hop: LocalRouteHintHop) -> Self {
Self {
src_node_id: hop.src_node_id.to_string(),
short_channel_id: hop.short_channel_id,
fees: Some(LocalRoutingFees::from(hop.fees).into()),
cltv_expiry_delta: hop.cltv_expiry_delta.into(),
htlc_minimum_msat: hop.htlc_minimum_msat,
htlc_maximum_msat: hop.htlc_maximum_msat,
}
}
}
impl From<LocalRoutingFees> for RoutingFees {
fn from(fees: LocalRoutingFees) -> Self {
Self {
base_msat: fees.base_msat,
proportional_millionths: fees.proportional_millionths,
}
}
}
impl From<LocalInvoiceFeatures> for Features {
fn from(features: LocalInvoiceFeatures) -> Self {
Self {
variable_length_onion: features.variable_length_onion,
payment_secret: features.payment_secret,
basic_mpp: features.basic_mpp,
}
}
}
}
|
mod att3;
mod att2;
mod att1;
pub mod click_ana;
pub use self::att3::*;
pub use self::att2::*;
pub use self::att1::*;
|
// Copyright 2019 The vault713 Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use failure::Fail;
use grin_util::secp;
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
pub enum ErrorKind {
#[fail(display = "Invalid reveal")]
Reveal,
#[fail(display = "Invalid hash length")]
HashLength,
#[fail(display = "Participant already exists")]
ParticipantExists,
#[fail(display = "Participant doesn't exist")]
ParticipantDoesntExist,
#[fail(display = "Participant created in the wrong order")]
ParticipantOrdering,
#[fail(display = "Participant invalid")]
ParticipantInvalid,
#[fail(display = "Multisig incomplete")]
MultiSigIncomplete,
#[fail(display = "Common nonce missing")]
CommonNonceMissing,
#[fail(display = "Round 1 missing field")]
Round1Missing,
#[fail(display = "Round 2 missing field")]
Round2Missing,
#[fail(display = "Secp: _0")]
Secp(secp::Error),
}
impl From<secp::Error> for ErrorKind {
fn from(error: secp::Error) -> ErrorKind {
ErrorKind::Secp(error)
}
}
|
mod docker;
#[cfg(feature = "ssh")]
mod ssh;
|
use crate::args_setup;
use crate::object::cons_list::ConsList;
use crate::object::Node;
use crate::vm::VM;
pub(crate) fn string_concat(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> {
let args = args_setup!(args_list);
let mut new_str = String::new();
for (i, item) in args.iter().enumerate() {
match vm.eval(item)? {
Node::String(s) => {
new_str.push_str(&s);
}
_ => {
return Err(format!(
"string-concat expected a string, got a {} for arg {}",
item.type_str(),
i
))
}
}
}
Ok(Node::from_string(new_str))
}
pub(crate) fn string_replace(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> {
let args = args_setup!(args_list, "string-replace", >=, 3);
if args.len() > 4 {
return Err("string-replace requires 3-4 args".to_owned());
}
let src = match vm.eval(&args[0])? {
Node::String(s) => s,
_ => return Err("string-replace arg 1 must be a string".to_owned()),
};
let old = match vm.eval(&args[1])? {
Node::String(s) => s,
_ => return Err("string-replace arg 2 must be a string".to_owned()),
};
let new = match vm.eval(&args[2])? {
Node::String(s) => s,
_ => return Err("string-replace arg 3 must be a string".to_owned()),
};
if args.len() == 3 {
Ok(Node::from_string(src.replace(&old, &new)))
} else {
let count = match vm.eval(&args[3])? {
Node::Number(n) => n,
_ => return Err("string-replace arg 4 must be a number".to_owned()),
};
Ok(Node::from_string(src.replacen(&old, &new, count as usize)))
}
}
pub(crate) fn string_split(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> {
let args = args_setup!(args_list, "string-split", >=, 2);
if args.len() > 3 {
return Err("string-split requires 2-3 args".to_owned());
}
let src = match vm.eval(&args[0])? {
Node::String(s) => s,
_ => return Err("string-split arg 1 must be a string".to_owned()),
};
let split = match vm.eval(&args[1])? {
Node::String(s) => s,
_ => return Err("string-split arg 2 must be a string".to_owned()),
};
if args.len() == 2 {
let splits = src
.split(&split)
.map(|x| Node::from_string(x.to_owned()))
.collect();
Ok(Node::from_vec(splits))
} else {
let count = match vm.eval(&args[2])? {
Node::Number(n) => n,
_ => return Err("string-replace arg 4 must be a number".to_owned()),
};
let splits = src
.splitn(count as usize, &split)
.map(|x| Node::from_string(x.to_owned()))
.collect();
Ok(Node::from_vec(splits))
}
}
|
#[doc = "Reader of register MPCBB1_VCTR28"]
pub type R = crate::R<u32, super::MPCBB1_VCTR28>;
#[doc = "Writer for register MPCBB1_VCTR28"]
pub type W = crate::W<u32, super::MPCBB1_VCTR28>;
#[doc = "Register MPCBB1_VCTR28 `reset()`'s with value 0"]
impl crate::ResetValue for super::MPCBB1_VCTR28 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `B896`"]
pub type B896_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B896`"]
pub struct B896_W<'a> {
w: &'a mut W,
}
impl<'a> B896_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 `B897`"]
pub type B897_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B897`"]
pub struct B897_W<'a> {
w: &'a mut W,
}
impl<'a> B897_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 `B898`"]
pub type B898_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B898`"]
pub struct B898_W<'a> {
w: &'a mut W,
}
impl<'a> B898_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 `B899`"]
pub type B899_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B899`"]
pub struct B899_W<'a> {
w: &'a mut W,
}
impl<'a> B899_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 `B900`"]
pub type B900_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B900`"]
pub struct B900_W<'a> {
w: &'a mut W,
}
impl<'a> B900_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 `B901`"]
pub type B901_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B901`"]
pub struct B901_W<'a> {
w: &'a mut W,
}
impl<'a> B901_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 `B902`"]
pub type B902_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B902`"]
pub struct B902_W<'a> {
w: &'a mut W,
}
impl<'a> B902_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 `B903`"]
pub type B903_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B903`"]
pub struct B903_W<'a> {
w: &'a mut W,
}
impl<'a> B903_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 `B904`"]
pub type B904_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B904`"]
pub struct B904_W<'a> {
w: &'a mut W,
}
impl<'a> B904_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 `B905`"]
pub type B905_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B905`"]
pub struct B905_W<'a> {
w: &'a mut W,
}
impl<'a> B905_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 `B906`"]
pub type B906_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B906`"]
pub struct B906_W<'a> {
w: &'a mut W,
}
impl<'a> B906_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 `B907`"]
pub type B907_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B907`"]
pub struct B907_W<'a> {
w: &'a mut W,
}
impl<'a> B907_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 `B908`"]
pub type B908_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B908`"]
pub struct B908_W<'a> {
w: &'a mut W,
}
impl<'a> B908_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 `B909`"]
pub type B909_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B909`"]
pub struct B909_W<'a> {
w: &'a mut W,
}
impl<'a> B909_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 `B910`"]
pub type B910_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B910`"]
pub struct B910_W<'a> {
w: &'a mut W,
}
impl<'a> B910_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 `B911`"]
pub type B911_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B911`"]
pub struct B911_W<'a> {
w: &'a mut W,
}
impl<'a> B911_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 `B912`"]
pub type B912_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B912`"]
pub struct B912_W<'a> {
w: &'a mut W,
}
impl<'a> B912_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 `B913`"]
pub type B913_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B913`"]
pub struct B913_W<'a> {
w: &'a mut W,
}
impl<'a> B913_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 `B914`"]
pub type B914_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B914`"]
pub struct B914_W<'a> {
w: &'a mut W,
}
impl<'a> B914_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 `B915`"]
pub type B915_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B915`"]
pub struct B915_W<'a> {
w: &'a mut W,
}
impl<'a> B915_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 `B916`"]
pub type B916_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B916`"]
pub struct B916_W<'a> {
w: &'a mut W,
}
impl<'a> B916_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 `B917`"]
pub type B917_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B917`"]
pub struct B917_W<'a> {
w: &'a mut W,
}
impl<'a> B917_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 `B918`"]
pub type B918_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B918`"]
pub struct B918_W<'a> {
w: &'a mut W,
}
impl<'a> B918_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 `B919`"]
pub type B919_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B919`"]
pub struct B919_W<'a> {
w: &'a mut W,
}
impl<'a> B919_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 `B920`"]
pub type B920_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B920`"]
pub struct B920_W<'a> {
w: &'a mut W,
}
impl<'a> B920_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 `B921`"]
pub type B921_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B921`"]
pub struct B921_W<'a> {
w: &'a mut W,
}
impl<'a> B921_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 `B922`"]
pub type B922_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B922`"]
pub struct B922_W<'a> {
w: &'a mut W,
}
impl<'a> B922_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 `B923`"]
pub type B923_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B923`"]
pub struct B923_W<'a> {
w: &'a mut W,
}
impl<'a> B923_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 `B924`"]
pub type B924_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B924`"]
pub struct B924_W<'a> {
w: &'a mut W,
}
impl<'a> B924_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 `B925`"]
pub type B925_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B925`"]
pub struct B925_W<'a> {
w: &'a mut W,
}
impl<'a> B925_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 `B926`"]
pub type B926_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B926`"]
pub struct B926_W<'a> {
w: &'a mut W,
}
impl<'a> B926_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 `B927`"]
pub type B927_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B927`"]
pub struct B927_W<'a> {
w: &'a mut W,
}
impl<'a> B927_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 - B896"]
#[inline(always)]
pub fn b896(&self) -> B896_R {
B896_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - B897"]
#[inline(always)]
pub fn b897(&self) -> B897_R {
B897_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - B898"]
#[inline(always)]
pub fn b898(&self) -> B898_R {
B898_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - B899"]
#[inline(always)]
pub fn b899(&self) -> B899_R {
B899_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - B900"]
#[inline(always)]
pub fn b900(&self) -> B900_R {
B900_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - B901"]
#[inline(always)]
pub fn b901(&self) -> B901_R {
B901_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - B902"]
#[inline(always)]
pub fn b902(&self) -> B902_R {
B902_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - B903"]
#[inline(always)]
pub fn b903(&self) -> B903_R {
B903_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - B904"]
#[inline(always)]
pub fn b904(&self) -> B904_R {
B904_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - B905"]
#[inline(always)]
pub fn b905(&self) -> B905_R {
B905_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - B906"]
#[inline(always)]
pub fn b906(&self) -> B906_R {
B906_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - B907"]
#[inline(always)]
pub fn b907(&self) -> B907_R {
B907_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - B908"]
#[inline(always)]
pub fn b908(&self) -> B908_R {
B908_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - B909"]
#[inline(always)]
pub fn b909(&self) -> B909_R {
B909_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - B910"]
#[inline(always)]
pub fn b910(&self) -> B910_R {
B910_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - B911"]
#[inline(always)]
pub fn b911(&self) -> B911_R {
B911_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - B912"]
#[inline(always)]
pub fn b912(&self) -> B912_R {
B912_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - B913"]
#[inline(always)]
pub fn b913(&self) -> B913_R {
B913_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - B914"]
#[inline(always)]
pub fn b914(&self) -> B914_R {
B914_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - B915"]
#[inline(always)]
pub fn b915(&self) -> B915_R {
B915_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - B916"]
#[inline(always)]
pub fn b916(&self) -> B916_R {
B916_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - B917"]
#[inline(always)]
pub fn b917(&self) -> B917_R {
B917_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - B918"]
#[inline(always)]
pub fn b918(&self) -> B918_R {
B918_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - B919"]
#[inline(always)]
pub fn b919(&self) -> B919_R {
B919_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - B920"]
#[inline(always)]
pub fn b920(&self) -> B920_R {
B920_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - B921"]
#[inline(always)]
pub fn b921(&self) -> B921_R {
B921_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - B922"]
#[inline(always)]
pub fn b922(&self) -> B922_R {
B922_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - B923"]
#[inline(always)]
pub fn b923(&self) -> B923_R {
B923_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - B924"]
#[inline(always)]
pub fn b924(&self) -> B924_R {
B924_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - B925"]
#[inline(always)]
pub fn b925(&self) -> B925_R {
B925_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - B926"]
#[inline(always)]
pub fn b926(&self) -> B926_R {
B926_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - B927"]
#[inline(always)]
pub fn b927(&self) -> B927_R {
B927_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - B896"]
#[inline(always)]
pub fn b896(&mut self) -> B896_W {
B896_W { w: self }
}
#[doc = "Bit 1 - B897"]
#[inline(always)]
pub fn b897(&mut self) -> B897_W {
B897_W { w: self }
}
#[doc = "Bit 2 - B898"]
#[inline(always)]
pub fn b898(&mut self) -> B898_W {
B898_W { w: self }
}
#[doc = "Bit 3 - B899"]
#[inline(always)]
pub fn b899(&mut self) -> B899_W {
B899_W { w: self }
}
#[doc = "Bit 4 - B900"]
#[inline(always)]
pub fn b900(&mut self) -> B900_W {
B900_W { w: self }
}
#[doc = "Bit 5 - B901"]
#[inline(always)]
pub fn b901(&mut self) -> B901_W {
B901_W { w: self }
}
#[doc = "Bit 6 - B902"]
#[inline(always)]
pub fn b902(&mut self) -> B902_W {
B902_W { w: self }
}
#[doc = "Bit 7 - B903"]
#[inline(always)]
pub fn b903(&mut self) -> B903_W {
B903_W { w: self }
}
#[doc = "Bit 8 - B904"]
#[inline(always)]
pub fn b904(&mut self) -> B904_W {
B904_W { w: self }
}
#[doc = "Bit 9 - B905"]
#[inline(always)]
pub fn b905(&mut self) -> B905_W {
B905_W { w: self }
}
#[doc = "Bit 10 - B906"]
#[inline(always)]
pub fn b906(&mut self) -> B906_W {
B906_W { w: self }
}
#[doc = "Bit 11 - B907"]
#[inline(always)]
pub fn b907(&mut self) -> B907_W {
B907_W { w: self }
}
#[doc = "Bit 12 - B908"]
#[inline(always)]
pub fn b908(&mut self) -> B908_W {
B908_W { w: self }
}
#[doc = "Bit 13 - B909"]
#[inline(always)]
pub fn b909(&mut self) -> B909_W {
B909_W { w: self }
}
#[doc = "Bit 14 - B910"]
#[inline(always)]
pub fn b910(&mut self) -> B910_W {
B910_W { w: self }
}
#[doc = "Bit 15 - B911"]
#[inline(always)]
pub fn b911(&mut self) -> B911_W {
B911_W { w: self }
}
#[doc = "Bit 16 - B912"]
#[inline(always)]
pub fn b912(&mut self) -> B912_W {
B912_W { w: self }
}
#[doc = "Bit 17 - B913"]
#[inline(always)]
pub fn b913(&mut self) -> B913_W {
B913_W { w: self }
}
#[doc = "Bit 18 - B914"]
#[inline(always)]
pub fn b914(&mut self) -> B914_W {
B914_W { w: self }
}
#[doc = "Bit 19 - B915"]
#[inline(always)]
pub fn b915(&mut self) -> B915_W {
B915_W { w: self }
}
#[doc = "Bit 20 - B916"]
#[inline(always)]
pub fn b916(&mut self) -> B916_W {
B916_W { w: self }
}
#[doc = "Bit 21 - B917"]
#[inline(always)]
pub fn b917(&mut self) -> B917_W {
B917_W { w: self }
}
#[doc = "Bit 22 - B918"]
#[inline(always)]
pub fn b918(&mut self) -> B918_W {
B918_W { w: self }
}
#[doc = "Bit 23 - B919"]
#[inline(always)]
pub fn b919(&mut self) -> B919_W {
B919_W { w: self }
}
#[doc = "Bit 24 - B920"]
#[inline(always)]
pub fn b920(&mut self) -> B920_W {
B920_W { w: self }
}
#[doc = "Bit 25 - B921"]
#[inline(always)]
pub fn b921(&mut self) -> B921_W {
B921_W { w: self }
}
#[doc = "Bit 26 - B922"]
#[inline(always)]
pub fn b922(&mut self) -> B922_W {
B922_W { w: self }
}
#[doc = "Bit 27 - B923"]
#[inline(always)]
pub fn b923(&mut self) -> B923_W {
B923_W { w: self }
}
#[doc = "Bit 28 - B924"]
#[inline(always)]
pub fn b924(&mut self) -> B924_W {
B924_W { w: self }
}
#[doc = "Bit 29 - B925"]
#[inline(always)]
pub fn b925(&mut self) -> B925_W {
B925_W { w: self }
}
#[doc = "Bit 30 - B926"]
#[inline(always)]
pub fn b926(&mut self) -> B926_W {
B926_W { w: self }
}
#[doc = "Bit 31 - B927"]
#[inline(always)]
pub fn b927(&mut self) -> B927_W {
B927_W { w: self }
}
}
|
mod routes;
extern crate futures;
extern crate telegram_bot;
extern crate tokio_core;
use self::futures::Stream;
use self::tokio_core::reactor::Core;
use self::telegram_bot::*;
fn process(api: Api, message: Message) {
if let MessageKind::Text { ref data, .. } = message.kind {
api.spawn(message.text_reply(routes::resolve(data.as_str())));
}
}
pub fn init(token: String) {
let mut core = Core::new().unwrap();
let api = Api::configure(token).build(core.handle()).unwrap();
// Fetch new updates via long poll method
let future = api.stream().for_each(|update| {
if let UpdateKind::Message(message) = update.kind {
process(api.clone(), message)
}
Ok(())
});
core.run(future).unwrap();
}
|
struct ParkingSystem {
parking_map: std::collections::HashMap<i32, (i32, i32)>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl ParkingSystem {
fn new(big: i32, medium: i32, small: i32) -> Self {
let mut parking_map = std::collections::HashMap::new();
parking_map.insert(1, (0, big));
parking_map.insert(2, (0, medium));
parking_map.insert(3, (0, small));
Self { parking_map }
}
fn add_car(mut self, car_type: i32) -> bool {
let mut result = false;
self.parking_map
.entry(car_type)
.and_modify(|(current, max)| {
if current < max {
*current += 1;
result = true;
}
});
result
}
}
|
pub trait FromRef<T> {
fn from_ref(val: &T) -> Self;
}
|
// min-version: 1.60.0
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print os_string
// lldbr-check:[...]os_string = "abc" [...]
// lldbg-check:[...]$0 = "abc" [...]
// lldb-command:print os_string_empty
// lldbr-check:[...]os_string_empty = "" [...]
// lldbg-check:[...]$1 = "" [...]
// lldb-command:print os_string_unicode
// lldbr-check:[...]os_string_unicode = "A∆й中" [...]
// TODO: support WTF-8 on Windows
// lldb-command:print os_str
// lldbr-check:[...]os_str = "abc" { data_ptr = [...] length = 3 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// lldb-command:print os_str_empty
// lldbr-check:[...]os_str_empty = "" { data_ptr = [...] length = 0 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// lldb-command:print os_str_unicode
// lldbr-check:[...]os_str_unicode = "A∆й中" { data_ptr = [...] length = 9 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings and WTF-8 on Windows
// lldb-command:print c_string
// lldbr-check:[...]c_string = "abc" [...]
// MSVC LLDB without Rust support fails to print `CString` in the console (but CLion renders it fine)
// lldb-command:print c_string_empty
// lldbr-check:[...]c_string_empty = "" [...]
// MSVC LLDB without Rust support fails to print `CString` in the console (but CLion renders it fine)
// lldb-command:print c_string_unicode
// lldbr-check:[...]c_string_unicode = "A∆й中" [...]
// MSVC LLDB without Rust support fails to print `CString` in the console (but CLion renders it fine)
// lldb-command:print c_str
// lldbr-check:[...]c_str = "abcd" { data_ptr = [...] length = 5 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// lldb-command:print c_str_empty
// lldbr-check:[...]c_str_empty = "" { data_ptr = [...] length = 1 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// lldb-command:print c_str_unicode
// lldbr-check:[...]c_str_unicode = "A∆й中" { data_ptr = [...] length = 10 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// lldb-command:print path_buf
// lldbr-check:[...]path_buf = "/a/b/c" [...]
// lldbg-check:[...]$12 = "/a/b/c" [...]
// lldb-command:print path_buf_empty
// lldbr-check:[...]path_buf_empty = "" [...]
// lldbg-check:[...]$13 = "" [...]
// lldb-command:print path_buf_unicode
// lldbr-check:[...]path_buf_unicode = "/a/b/∂" [...]
// TODO: support WTF-8 on Windows
// lldb-command:print path
// lldbr-check:[...]path = "/a/b/c" { data_ptr = [...] length = 6 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// lldb-command:print path_empty
// lldbr-check:[...]path_empty = "" { data_ptr = [...] length = 0 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// lldb-command:print path_unicode
// lldbr-check:[...]path_unicode = "/a/b/∂" { data_ptr = [...] length = 8 }
// TODO: support `ref$<...>` and `ref_mut$<...>` type wrappings on Windows
// === GDB TESTS ==================================================================================
// gdb-command:run
// gdb-command:print os_string
// gdb-check:[...]$1 = "abc"
// gdb-command:print os_string_empty
// gdb-check:[...]$2 = ""
// gdb-command:print os_string_unicode
// gdb-check:[...]$3 = "A∆й中"
use std::ffi::{CStr, CString, OsStr, OsString};
use std::ops::DerefMut;
use std::path::{Path, PathBuf};
fn main() {
let mut os_string = OsString::from("abc");
let os_string_empty = OsString::from("");
let mut os_string_unicode = OsString::from("A∆й中");
let os_str = os_string.deref_mut();
let os_str_empty = OsStr::new("");
let os_str_unicode = os_string_unicode.deref_mut();
let c_string = CString::new("abc").unwrap();
let c_string_empty = CString::new("").unwrap();
let c_string_unicode = CString::new("A∆й中").unwrap();
let c_str = CStr::from_bytes_with_nul(b"abcd\0").unwrap();
let c_str_empty = CStr::from_bytes_with_nul(b"\0").unwrap();
let c_str_unicode = CStr::from_bytes_with_nul(b"A\xE2\x88\x86\xD0\xB9\xE4\xB8\xAD\0").unwrap();
let path_buf = PathBuf::from("/a/b/c");
let path_buf_empty = PathBuf::from("");
let path_buf_unicode = PathBuf::from("/a/b/∂");
let path = Path::new("/a/b/c");
let path_empty = Path::new("");
let path_unicode = Path::new("/a/b/∂");
print!(""); // #break
}
|
//! Neo4j driver compatible with neo4j 4.x versions
//!
//! * An implementation of the [bolt protocol][bolt] to interact with Neo4j server
//! * async/await apis using [tokio][tokio]
//! * Supports bolt 4.2 specification
//! * tested with Neo4j versions: 4.0, 4.1, 4.2
//!
//!
//! [bolt]: https://7687.org/
//! [tokio]: https://github.com/tokio-rs/tokio
//!
//!
//! # Examples
//!
//! ```
//! use neo4rs::*;
//! use std::sync::Arc;
//! use std::sync::atomic::{AtomicU32, Ordering};
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let id = Uuid::new_v4().to_string();
//!
//! let graph = Arc::new(Graph::new(&uri, user, pass).await.unwrap());
//! let mut result = graph.run(
//! query("CREATE (p:Person {id: $id})").param("id", id.clone())
//! ).await.unwrap();
//!
//! let mut handles = Vec::new();
//! let mut count = Arc::new(AtomicU32::new(0));
//! for _ in 1..=42 {
//! let graph = graph.clone();
//! let id = id.clone();
//! let count = count.clone();
//! let handle = tokio::spawn(async move {
//! let mut result = graph.execute(
//! query("MATCH (p:Person {id: $id}) RETURN p").param("id", id)
//! ).await.unwrap();
//! while let Ok(Some(row)) = result.next().await {
//! count.fetch_add(1, Ordering::Relaxed);
//! }
//! });
//! handles.push(handle);
//! }
//!
//! futures::future::join_all(handles).await;
//! assert_eq!(count.load(Ordering::Relaxed), 42);
//! }
//! ```
//!
//! ## Configurations
//!
//! Use the config builder to override the default configurations like
//! * `fetch_size` - number of rows to fetch in batches (default is 200)
//! * `max_connections` - maximum size of the connection pool (default is 16)
//! * `db` - the database to connect to (default is `neo4j`)
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//!
//! #[tokio::main]
//! async fn main() {
//! let config = config()
//! .uri("127.0.0.1:7687")
//! .user("neo4j")
//! .password("neo")
//! .db("neo4j")
//! .fetch_size(500)
//! .max_connections(10)
//! .build()
//! .unwrap();
//! let graph = Graph::connect(config).await.unwrap();
//! let mut result = graph.execute(query("RETURN 1")).await.unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let value: i64 = row.get("1").unwrap();
//! assert_eq!(1, value);
//! assert!(result.next().await.unwrap().is_none());
//! }
//! ```
//!
//! ## Nodes
//! A simple example to create a node and consume the created node from the row stream.
//!
//! * [`Graph::run`] just returns [`errors::Result`]`<()>`, usually used for write only queries.
//! * [`Graph::execute`] returns [`errors::Result`]`<`[`RowStream`]`>`
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//!
//! assert!(graph.run(query("RETURN 1")).await.is_ok());
//!
//! let mut result = graph.execute(
//! query( "CREATE (friend:Person {name: $name}) RETURN friend")
//! .param("name", "Mr Mark")
//! ).await.unwrap();
//!
//! while let Ok(Some(row)) = result.next().await {
//! let node: Node = row.get("friend").unwrap();
//! let id = node.id();
//! let labels = node.labels();
//! let name: String = node.get("name").unwrap();
//! assert_eq!(name, "Mr Mark");
//! assert_eq!(labels, vec!["Person"]);
//! assert!(id > 0);
//! }
//! }
//! ```
//!
//! ## Transactions
//!
//! Start a new transaction using [`Graph::start_txn`], which will return a handle [`Txn`] that can
//! be used to [`Txn::commit`] or [`Txn::rollback`] the transaction.
//!
//! Note that the handle takes a connection from the connection pool, which will be released once
//! the Txn is dropped
//!
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let txn = graph.start_txn().await.unwrap();
//! let id = Uuid::new_v4().to_string();
//! let result = txn.run_queries(vec![
//! query("CREATE (p:Person {id: $id})").param("id", id.clone()),
//! query("CREATE (p:Person {id: $id})").param("id", id.clone())
//! ]).await;
//!
//! assert!(result.is_ok());
//! txn.commit().await.unwrap();
//! let mut result = graph
//! .execute(query("MATCH (p:Person) WHERE p.id = $id RETURN p.id").param("id", id.clone()))
//! .await
//! .unwrap();
//! # assert!(result.next().await.unwrap().is_some());
//! # assert!(result.next().await.unwrap().is_some());
//! # assert!(result.next().await.unwrap().is_none());
//! }
//!
//! ```
//!
//! ### Streams within a transaction
//!
//! Each [`RowStream`] returned by various execute within the same transaction are well isolated,
//! so you can consume the stream anytime within the transaction using [`RowStream::next`]
//!
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let config = config()
//! .uri("127.0.0.1:7687")
//! .user("neo4j")
//! .password("neo")
//! .fetch_size(1)
//! .build()
//! .unwrap();
//! let graph = Graph::connect(config).await.unwrap();
//! let name = Uuid::new_v4().to_string();
//! let txn = graph.start_txn().await.unwrap();
//!
//! txn.run_queries(vec![
//! query("CREATE (p { name: $name })").param("name", name.clone()),
//! query("CREATE (p { name: $name })").param("name", name.clone()),
//! ])
//! .await
//! .unwrap();
//!
//!
//! //start stream_one
//! let mut stream_one = txn
//! .execute(query("MATCH (p {name: $name}) RETURN p").param("name", name.clone()))
//! .await
//! .unwrap();
//! let row = stream_one.next().await.unwrap().unwrap();
//! assert_eq!(row.get::<Node>("p").unwrap().get::<String>("name").unwrap(), name.clone());
//!
//! //start stream_two
//! let mut stream_two = txn.execute(query("RETURN 1")).await.unwrap();
//! let row = stream_two.next().await.unwrap().unwrap();
//! assert_eq!(row.get::<i64>("1").unwrap(), 1);
//!
//! //stream_one is still active here
//! let row = stream_one.next().await.unwrap().unwrap();
//! assert_eq!(row.get::<Node>("p").unwrap().get::<String>("name").unwrap(), name.clone());
//!
//! //stream_one completes
//! assert!(stream_one.next().await.unwrap().is_none());
//! //stream_two completes
//! assert!(stream_two.next().await.unwrap().is_none());
//! txn.commit().await.unwrap();
//! }
//!
//! ```
//!
//!
//! ### Rollback a transaction
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//!
//! let txn = graph.start_txn().await.unwrap();
//! let id = Uuid::new_v4().to_string();
//! // create a node
//! txn.run(query("CREATE (p:Person {id: $id})").param("id", id.clone()))
//! .await
//! .unwrap();
//! // rollback the changes
//! txn.rollback().await.unwrap();
//!
//! // changes not updated in the database
//! let mut result = graph
//! .execute(query("MATCH (p:Person) WHERE p.id = $id RETURN p.id").param("id", id.clone()))
//! .await
//! .unwrap();
//! assert!(result.next().await.unwrap().is_none());
//! }
//!
//! ```
//!
//! ### Txn vs Graph
//!
//! Everytime you execute a query using [`Graph::run`] or [`Graph::execute`], a new connection is
//! taken from the pool and released immediately.
//!
//! However, when you execute a query on a transaction using [`Txn::run`] or [`Txn::execute`] the
//! same connection will be reused, the underlying connection will be released to the pool in a
//! clean state only after you commit/rollback the transaction and the [`Txn`] handle is dropped.
//!
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let txn = graph.start_txn().await.unwrap();
//! let id = Uuid::new_v4().to_string();
//! txn.run(query("CREATE (p:Person {id: $id})").param("id", id.clone()))
//! .await
//! .unwrap();
//! txn.run(query("CREATE (p:Person {id: $id})").param("id", id.clone()))
//! .await
//! .unwrap();
//! // graph.execute(..) will not see the changes done above as the txn is not committed yet
//! let mut result = graph
//! .execute(query("MATCH (p:Person) WHERE p.id = $id RETURN p.id").param("id", id.clone()))
//! .await
//! .unwrap();
//! assert!(result.next().await.unwrap().is_none());
//! txn.commit().await.unwrap();
//!
//! //changes are now seen as the transaction is committed.
//! let mut result = graph
//! .execute(query("MATCH (p:Person) WHERE p.id = $id RETURN p.id").param("id", id.clone()))
//! .await
//! .unwrap();
//! assert!(result.next().await.unwrap().is_some());
//! assert!(result.next().await.unwrap().is_some());
//! assert!(result.next().await.unwrap().is_none());
//! }
//!
//! ```
//!
//! ## Relationships
//!
//! Bounded Relationship between nodes are created using cypher queries and the same can be parsed
//! from the [`RowStream`]
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let mut result = graph.execute(
//! query("CREATE (p:Person { name: 'Oliver Stone' })-[r:WORKS_AT {as: 'Engineer'}]->(neo) RETURN r")
//! ).await.unwrap();
//!
//! let row = result.next().await.unwrap().unwrap();
//! let relation: Relation = row.get("r").unwrap();
//! assert!(relation.id() > -1);
//! assert!(relation.start_node_id() > -1);
//! assert!(relation.end_node_id() > -1);
//! assert_eq!(relation.typ(), "WORKS_AT");
//! assert_eq!(relation.get::<String>("as").unwrap(), "Engineer");
//! }
//! ```
//!
//!
//! Similar to bounded relation, an unbounded relation can also be created/parsed.
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let mut result = graph.execute(
//! query("MERGE (p1:Person { name: 'Oliver Stone' })-[r:RELATED {as: 'friend'}]-(p2: Person {name: 'Mark'}) RETURN r")
//! ).await.unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let relation: Relation = row.get("r").unwrap();
//! assert!(relation.id() > -1);
//! assert!(relation.start_node_id() > -1);
//! assert!(relation.end_node_id() > -1);
//! assert_eq!(relation.typ(), "RELATED");
//! assert_eq!(relation.get::<String>("as").unwrap(), "friend");
//! }
//!
//! ```
//!
//!
//!
//! ## Points
//!
//! A 2d or 3d point can be represented with the types [`Point2D`] and [`Point3D`]
//!
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//!
//! let mut result = graph
//! .execute(query(
//! "WITH point({ x: 2.3, y: 4.5, crs: 'cartesian' }) AS p1,
//! point({ x: 1.1, y: 5.4, crs: 'cartesian' }) AS p2 RETURN distance(p1,p2) AS dist, p1, p2",
//! ))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let dist: f64 = row.get("dist").unwrap();
//! let p1: Point2D = row.get("p1").unwrap();
//! let p2: Point2D = row.get("p2").unwrap();
//! assert_eq!(1.5, dist);
//! assert_eq!(p1.sr_id(), 7203);
//! assert_eq!(p1.x(), 2.3);
//! assert_eq!(p1.y(), 4.5);
//! assert_eq!(p2.sr_id(), 7203);
//! assert_eq!(p2.x(), 1.1);
//! assert_eq!(p2.y(), 5.4);
//! assert!(result.next().await.unwrap().is_none());
//!
//! let mut result = graph
//! .execute(query(
//! "RETURN point({ longitude: 56.7, latitude: 12.78, height: 8 }) AS point",
//! ))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let point: Point3D = row.get("point").unwrap();
//! assert_eq!(point.sr_id(), 4979);
//! assert_eq!(point.x(), 56.7);
//! assert_eq!(point.y(), 12.78);
//! assert_eq!(point.z(), 8.0);
//! assert!(result.next().await.unwrap().is_none());
//!
//! }
//!
//! ```
//!
//! ## Raw bytes
//!
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let mut result = graph
//! .execute(query("RETURN $b as output").param("b", vec![11, 12]))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let b: Vec<u8> = row.get("output").unwrap();
//! assert_eq!(b, &[11, 12]);
//! assert!(result.next().await.unwrap().is_none());
//! }
//!
//! ```
//!
//! ## Durations
//!
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let duration = std::time::Duration::new(5259600, 7);
//! let mut result = graph
//! .execute(query("RETURN $d as output").param("d", duration))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let d: std::time::Duration = row.get("output").unwrap();
//! assert_eq!(d.as_secs(), 5259600);
//! assert_eq!(d.subsec_nanos(), 7);
//! assert!(result.next().await.unwrap().is_none());
//! }
//!
//! ```
//! ## Date
//!
//! See [NaiveDate][naive_date] for date abstraction, it captures the date without time component.
//!
//! [naive_date]: https://docs.rs/chrono/0.4.19/chrono/naive/struct.NaiveDate.html
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let date = chrono::NaiveDate::from_ymd(1985, 2, 5);
//! let mut result = graph
//! .execute(query("RETURN $d as output").param("d", date))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let d: chrono::NaiveDate = row.get("output").unwrap();
//! assert_eq!(d.to_string(), "1985-02-05");
//! assert!(result.next().await.unwrap().is_none());
//! }
//! ```
//!
//!
//! ## Time
//!
//! * [NaiveTime][naive_time] captures only the time of the day
//! * `tuple`([NaiveTime][naive_time], `Option`<[FixedOffset][fixed_offset]>) captures the time of the day along with the
//! offset
//!
//! [naive_time]: https://docs.rs/chrono/0.4.19/chrono/naive/struct.NaiveTime.html
//! [fixed_offset]: https://docs.rs/chrono/0.4.19/chrono/offset/struct.FixedOffset.html
//!
//!
//! ### Time as param
//!
//! Pass a time as a parameter to the query:
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//!
//! //send time without offset as param
//! let time = chrono::NaiveTime::from_hms_nano(11, 15, 30, 200);
//! let mut result = graph.execute(query("RETURN $d as output").param("d", time)).await.unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: (chrono::NaiveTime, Option<chrono::FixedOffset>) = row.get("output").unwrap();
//! assert_eq!(t.0.to_string(), "11:15:30.000000200");
//! assert_eq!(t.1, None);
//! assert!(result.next().await.unwrap().is_none());
//!
//!
//! //send time with offset as param
//! let time = chrono::NaiveTime::from_hms_nano(11, 15, 30, 200);
//! let offset = chrono::FixedOffset::east(3 * 3600);
//! let mut result = graph
//! .execute(query("RETURN $d as output").param("d", (time, offset)))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: (chrono::NaiveTime, Option<chrono::FixedOffset>) = row.get("output").unwrap();
//! assert_eq!(t.0.to_string(), "11:15:30.000000200");
//! assert_eq!(t.1, Some(offset));
//! assert!(result.next().await.unwrap().is_none());
//! }
//! ```
//!
//!
//! ### Parsing time from result
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//!
//! //Parse time without offset
//! let mut result = graph
//! .execute(query(
//! " WITH time({hour:10, minute:15, second:30, nanosecond: 200}) AS t RETURN t",
//! ))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: (chrono::NaiveTime, Option<chrono::FixedOffset>) = row.get("t").unwrap();
//! assert_eq!(t.0.to_string(), "10:15:30.000000200");
//! assert_eq!(t.1, None);
//! assert!(result.next().await.unwrap().is_none());
//!
//! //Parse time with timezone information
//! let mut result = graph
//! .execute(query(
//! " WITH time({hour:10, minute:15, second:33, nanosecond: 200, timezone: '+01:00'}) AS t RETURN t",
//! ))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: (chrono::NaiveTime, Option<chrono::FixedOffset>) = row.get("t").unwrap();
//! assert_eq!(t.0.to_string(), "10:15:33.000000200");
//! assert_eq!(t.1, Some(chrono::FixedOffset::east(1 * 3600)));
//! assert!(result.next().await.unwrap().is_none());
//! }
//!
//! ```
//!
//!
//! ## DateTime
//!
//!
//! * [DateTime][date_time] captures the date and time with offset
//! * [NaiveDateTime][naive_date_time] captures the date time without offset
//! * `tuple`([NaiveDateTime][naive_date_time], String) captures the date/time and the time zone id
//!
//! [date_time]: https://docs.rs/chrono/0.4.19/chrono/struct.DateTime.html
//! [naive_date_time]: https://docs.rs/chrono/0.4.19/chrono/struct.NaiveDateTime.html
//!
//!
//! ### DateTime as param
//!
//! Pass a DateTime as parameter to the query:
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//!
//! //send datetime as parameter in the query
//! let datetime = chrono::DateTime::parse_from_rfc2822("Tue, 01 Jul 2003 10:52:37 +0200").unwrap();
//!
//! let mut result = graph
//! .execute(query("RETURN $d as output").param("d", datetime))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: chrono::DateTime<chrono::FixedOffset> = row.get("output").unwrap();
//! assert_eq!(t.to_string(), "2003-07-01 10:52:37 +02:00");
//! assert!(result.next().await.unwrap().is_none());
//!
//! //send NaiveDateTime as parameter in the query
//! let localdatetime = chrono::NaiveDateTime::parse_from_str("2015-07-01 08:55:59.123", "%Y-%m-%d %H:%M:%S%.f").unwrap();
//!
//! let mut result = graph
//! .execute(query("RETURN $d as output").param("d", localdatetime))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: chrono::NaiveDateTime = row.get("output").unwrap();
//! assert_eq!(t.to_string(), "2015-07-01 08:55:59.123");
//! assert!(result.next().await.unwrap().is_none());
//!
//! //send NaiveDateTime with timezone id as parameter in the query
//! let datetime = chrono::NaiveDateTime::parse_from_str("2015-07-03 08:55:59.555", "%Y-%m-%d %H:%M:%S%.f").unwrap();
//! let timezone = "Europe/Paris";
//!
//! let mut result = graph
//! .execute(query("RETURN $d as output").param("d", (datetime, timezone)))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let (time, zone): (chrono::NaiveDateTime, String) = row.get("output").unwrap();
//! assert_eq!(time.to_string(), "2015-07-03 08:55:59.555");
//! assert_eq!(zone, "Europe/Paris");
//! assert!(result.next().await.unwrap().is_none());
//!
//! }
//! ```
//!
//! ### Parsing DateTime from result
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//!
//! //Parse NaiveDateTime from result
//! let mut result = graph
//! .execute(query(
//! "WITH localdatetime('2015-06-24T12:50:35.556') AS t RETURN t",
//! ))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: chrono::NaiveDateTime = row.get("t").unwrap();
//! assert_eq!(t.to_string(), "2015-06-24 12:50:35.556");
//! assert!(result.next().await.unwrap().is_none());
//!
//! //Parse DateTime from result
//! let mut result = graph
//! .execute(query(
//! "WITH datetime('2015-06-24T12:50:35.777+0100') AS t RETURN t",
//! ))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let t: chrono::DateTime<chrono::FixedOffset> = row.get("t").unwrap();
//! assert_eq!(t.to_string(), "2015-06-24 12:50:35.777 +01:00");
//! assert!(result.next().await.unwrap().is_none());
//!
//!
//! //Parse NaiveDateTime with zone id from result
//! let mut result = graph
//! .execute(query(
//! "WITH datetime({ year:1984, month:11, day:11, hour:12, minute:31, second:14, nanosecond: 645876123, timezone:'Europe/Stockholm' }) AS d return d",
//! ))
//! .await
//! .unwrap();
//! let row = result.next().await.unwrap().unwrap();
//! let (datetime, zone_id): (chrono::NaiveDateTime, String) = row.get("d").unwrap();
//! assert_eq!(datetime.to_string(), "1984-11-11 12:31:14.645876123");
//! assert_eq!(zone_id, "Europe/Stockholm");
//! assert!(result.next().await.unwrap().is_none());
//!
//! }
//!
//! ```
//!
//!
//!
//! ## Path
//!
//! ```
//! use neo4rs::*;
//! use futures::stream::*;
//! use uuid::Uuid;
//!
//! #[tokio::main]
//! async fn main() {
//! let uri = "127.0.0.1:7687";
//! let user = "neo4j";
//! let pass = "neo";
//! let graph = Graph::new(uri, user, pass).await.unwrap();
//! let name = Uuid::new_v4().to_string();
//! graph.run(
//! query("CREATE (p:Person { name: $name })-[r:WORKS_AT]->(n:Company { name: 'Neo'})").param("name", name.clone()),
//! ).await.unwrap();
//!
//! let mut result = graph.execute(
//! query("MATCH p = (person:Person { name: $name })-[r:WORKS_AT]->(c:Company) RETURN p").param("name", name),
//! ).await.unwrap();
//!
//! let row = result.next().await.unwrap().unwrap();
//! let path: Path = row.get("p").unwrap();
//! assert_eq!(path.ids().len(), 2);
//! assert_eq!(path.nodes().len(), 2);
//! assert_eq!(path.rels().len(), 1);
//! assert!(result.next().await.unwrap().is_none());
//! }
//! ```
//!
//!
mod config;
mod connection;
mod convert;
mod errors;
mod graph;
mod messages;
mod pool;
mod query;
mod row;
mod stream;
mod txn;
mod types;
mod version;
pub use crate::config::{config, Config, ConfigBuilder};
pub use crate::errors::*;
pub use crate::graph::{query, Graph};
pub use crate::query::Query;
pub use crate::row::{Node, Path, Point2D, Point3D, Relation, Row, UnboundedRelation};
pub use crate::stream::RowStream;
pub use crate::txn::Txn;
pub use crate::version::Version;
|
use std::ops;
/// A point in 2-dimensional space, with each dimension of type `N`.
///
/// Legal operations on points are addition and subtraction by vectors, and
/// subtraction between points, to give a vector representing the offset between
/// the two points. Combined with the legal operations on vectors, meaningful
/// manipulations of vectors and points can be performed.
///
/// For example, to interpolate between two points by a factor `t`:
///
/// ```
/// # use rusttype::*;
/// # let t = 0.5; let p0 = point(0.0, 0.0); let p1 = point(0.0, 0.0);
/// let interpolated_point = p0 + (p1 - p0) * t;
/// ```
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Point<N> {
pub x: N,
pub y: N,
}
/// A vector in 2-dimensional space, with each dimension of type `N`.
///
/// Legal operations on vectors are addition and subtraction by vectors,
/// addition by points (to give points), and multiplication and division by
/// scalars.
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Vector<N> {
pub x: N,
pub y: N,
}
/// A convenience function for generating `Point`s.
#[inline]
pub fn point<N>(x: N, y: N) -> Point<N> {
Point { x, y }
}
/// A convenience function for generating `Vector`s.
#[inline]
pub fn vector<N>(x: N, y: N) -> Vector<N> {
Vector { x, y }
}
impl<N: ops::Sub<Output = N>> ops::Sub for Point<N> {
type Output = Vector<N>;
fn sub(self, rhs: Point<N>) -> Vector<N> {
vector(self.x - rhs.x, self.y - rhs.y)
}
}
impl<N: ops::Add<Output = N>> ops::Add for Vector<N> {
type Output = Vector<N>;
fn add(self, rhs: Vector<N>) -> Vector<N> {
vector(self.x + rhs.x, self.y + rhs.y)
}
}
impl<N: ops::Sub<Output = N>> ops::Sub for Vector<N> {
type Output = Vector<N>;
fn sub(self, rhs: Vector<N>) -> Vector<N> {
vector(self.x - rhs.x, self.y - rhs.y)
}
}
impl ops::Mul<f32> for Vector<f32> {
type Output = Vector<f32>;
fn mul(self, rhs: f32) -> Vector<f32> {
vector(self.x * rhs, self.y * rhs)
}
}
impl ops::Mul<Vector<f32>> for f32 {
type Output = Vector<f32>;
fn mul(self, rhs: Vector<f32>) -> Vector<f32> {
vector(self * rhs.x, self * rhs.y)
}
}
impl ops::Mul<f64> for Vector<f64> {
type Output = Vector<f64>;
fn mul(self, rhs: f64) -> Vector<f64> {
vector(self.x * rhs, self.y * rhs)
}
}
impl ops::Mul<Vector<f64>> for f64 {
type Output = Vector<f64>;
fn mul(self, rhs: Vector<f64>) -> Vector<f64> {
vector(self * rhs.x, self * rhs.y)
}
}
impl ops::Div<f32> for Vector<f32> {
type Output = Vector<f32>;
fn div(self, rhs: f32) -> Vector<f32> {
vector(self.x / rhs, self.y / rhs)
}
}
impl ops::Div<Vector<f32>> for f32 {
type Output = Vector<f32>;
fn div(self, rhs: Vector<f32>) -> Vector<f32> {
vector(self / rhs.x, self / rhs.y)
}
}
impl ops::Div<f64> for Vector<f64> {
type Output = Vector<f64>;
fn div(self, rhs: f64) -> Vector<f64> {
vector(self.x / rhs, self.y / rhs)
}
}
impl ops::Div<Vector<f64>> for f64 {
type Output = Vector<f64>;
fn div(self, rhs: Vector<f64>) -> Vector<f64> {
vector(self / rhs.x, self / rhs.y)
}
}
impl<N: ops::Add<Output = N>> ops::Add<Vector<N>> for Point<N> {
type Output = Point<N>;
fn add(self, rhs: Vector<N>) -> Point<N> {
point(self.x + rhs.x, self.y + rhs.y)
}
}
impl<N: ops::Sub<Output = N>> ops::Sub<Vector<N>> for Point<N> {
type Output = Point<N>;
fn sub(self, rhs: Vector<N>) -> Point<N> {
point(self.x - rhs.x, self.y - rhs.y)
}
}
impl<N: ops::Add<Output = N>> ops::Add<Point<N>> for Vector<N> {
type Output = Point<N>;
fn add(self, rhs: Point<N>) -> Point<N> {
point(self.x + rhs.x, self.y + rhs.y)
}
}
/// A straight line between two points, `p[0]` and `p[1]`
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Line {
pub p: [Point<f32>; 2],
}
/// A quadratic Bezier curve, starting at `p[0]`, ending at `p[2]`, with control
/// point `p[1]`.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Curve {
pub p: [Point<f32>; 3],
}
/// A rectangle, with top-left corner at `min`, and bottom-right corner at
/// `max`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Rect<N> {
pub min: Point<N>,
pub max: Point<N>,
}
impl<N: ops::Sub<Output = N> + Copy> Rect<N> {
pub fn width(&self) -> N {
self.max.x - self.min.x
}
pub fn height(&self) -> N {
self.max.y - self.min.y
}
}
pub trait BoundingBox<N> {
fn bounding_box(&self) -> Rect<N> {
let (min_x, max_x) = self.x_bounds();
let (min_y, max_y) = self.y_bounds();
Rect {
min: point(min_x, min_y),
max: point(max_x, max_y),
}
}
fn x_bounds(&self) -> (N, N);
fn y_bounds(&self) -> (N, N);
}
impl BoundingBox<f32> for Line {
fn x_bounds(&self) -> (f32, f32) {
let p = &self.p;
if p[0].x < p[1].x {
(p[0].x, p[1].x)
} else {
(p[1].x, p[0].x)
}
}
fn y_bounds(&self) -> (f32, f32) {
let p = &self.p;
if p[0].y < p[1].y {
(p[0].y, p[1].y)
} else {
(p[1].y, p[0].y)
}
}
}
impl BoundingBox<f32> for Curve {
fn x_bounds(&self) -> (f32, f32) {
let p = &self.p;
if p[0].x <= p[1].x && p[1].x <= p[2].x {
(p[0].x, p[2].x)
} else if p[0].x >= p[1].x && p[1].x >= p[2].x {
(p[2].x, p[0].x)
} else {
let t = (p[0].x - p[1].x) / (p[0].x - 2.0 * p[1].x + p[2].x);
let _1mt = 1.0 - t;
let inflection = _1mt * _1mt * p[0].x + 2.0 * _1mt * t * p[1].x + t * t * p[2].x;
if p[1].x < p[0].x {
(inflection, p[0].x.max(p[2].x))
} else {
(p[0].x.min(p[2].x), inflection)
}
}
}
fn y_bounds(&self) -> (f32, f32) {
let p = &self.p;
if p[0].y <= p[1].y && p[1].y <= p[2].y {
(p[0].y, p[2].y)
} else if p[0].y >= p[1].y && p[1].y >= p[2].y {
(p[2].y, p[0].y)
} else {
let t = (p[0].y - p[1].y) / (p[0].y - 2.0 * p[1].y + p[2].y);
let _1mt = 1.0 - t;
let inflection = _1mt * _1mt * p[0].y + 2.0 * _1mt * t * p[1].y + t * t * p[2].y;
if p[1].y < p[0].y {
(inflection, p[0].y.max(p[2].y))
} else {
(p[0].y.min(p[2].y), inflection)
}
}
}
}
pub trait Cut: Sized {
fn cut_to(self, t: f32) -> Self;
fn cut_from(self, t: f32) -> Self;
fn cut_from_to(self, t0: f32, t1: f32) -> Self {
self.cut_from(t0).cut_to((t1 - t0) / (1.0 - t0))
}
}
impl Cut for Curve {
fn cut_to(self, t: f32) -> Curve {
let p = self.p;
let a = p[0] + t * (p[1] - p[0]);
let b = p[1] + t * (p[2] - p[1]);
let c = a + t * (b - a);
Curve { p: [p[0], a, c] }
}
fn cut_from(self, t: f32) -> Curve {
let p = self.p;
let a = p[0] + t * (p[1] - p[0]);
let b = p[1] + t * (p[2] - p[1]);
let c = a + t * (b - a);
Curve { p: [c, b, p[2]] }
}
}
impl Cut for Line {
fn cut_to(self, t: f32) -> Line {
let p = self.p;
Line {
p: [p[0], p[0] + t * (p[1] - p[0])],
}
}
fn cut_from(self, t: f32) -> Line {
let p = self.p;
Line {
p: [p[0] + t * (p[1] - p[0]), p[1]],
}
}
fn cut_from_to(self, t0: f32, t1: f32) -> Line {
let p = self.p;
let v = p[1] - p[0];
Line {
p: [p[0] + t0 * v, p[0] + t1 * v],
}
}
}
/// The real valued solutions to a real quadratic equation.
#[derive(Copy, Clone, Debug)]
pub enum RealQuadraticSolution {
/// Two zero-crossing solutions
Two(f32, f32),
/// One zero-crossing solution (equation is a straight line)
One(f32),
/// One zero-touching solution
Touch(f32),
/// No solutions
None,
/// All real numbers are solutions since a == b == c == 0.0
All,
}
impl RealQuadraticSolution {
/// If there are two solutions, this function ensures that they are in order
/// (first < second)
pub fn in_order(self) -> RealQuadraticSolution {
use self::RealQuadraticSolution::*;
match self {
Two(x, y) => {
if x < y {
Two(x, y)
} else {
Two(y, x)
}
}
other => other,
}
}
}
/// Solve a real quadratic equation, giving all real solutions, if any.
pub fn solve_quadratic_real(a: f32, b: f32, c: f32) -> RealQuadraticSolution {
let discriminant = b * b - 4.0 * a * c;
if discriminant > 0.0 {
let sqrt_d = discriminant.sqrt();
let common = -b + if b >= 0.0 { -sqrt_d } else { sqrt_d };
let x1 = 2.0 * c / common;
if a == 0.0 {
RealQuadraticSolution::One(x1)
} else {
let x2 = common / (2.0 * a);
RealQuadraticSolution::Two(x1, x2)
}
} else if discriminant < 0.0 {
RealQuadraticSolution::None
} else if b == 0.0 {
if a == 0.0 {
if c == 0.0 {
RealQuadraticSolution::All
} else {
RealQuadraticSolution::None
}
} else {
RealQuadraticSolution::Touch(0.0)
}
} else {
RealQuadraticSolution::Touch(2.0 * c / -b)
}
}
#[test]
fn quadratic_test() {
solve_quadratic_real(-0.000_000_1, -2.0, 10.0);
}
|
#![allow(non_snake_case)]
use crate::error::Error;
use rocket::http::Status;
use rocket::Catcher;
macro_rules! gen_err_catchers {
($($code:expr, $name:ident),+) => {
$(
#[catch($code)]
pub fn $name() -> Error {
Error::from(Status::raw($code))
}
)+
pub fn All() -> Vec<Catcher> {
catchers![$($name),*]
}
};
}
gen_err_catchers! {
400, BadRequest,
401, Unauthorized,
402, PaymentRequired,
403, Forbidden,
404, NotFound,
405, MethodNotAllowed,
406, NotAcceptable,
407, ProxyAuthenticationRequired,
408, RequestTimeout,
409, Conflict,
410, Gone,
411, LengthRequired,
412, PreconditionFailed,
413, PayloadTooLarge,
414, UriTooLong,
415, UnsupportedMediaType,
416, RangeNotSatisfiable,
417, ExpectationFailed,
418, ImATeapot,
421, MisdirectedRequest,
422, UnprocessableEntity,
423, Locked,
424, FailedDependency,
426, UpgradeRequired,
428, PreconditionRequired,
429, TooManyRequests,
431, RequestHeaderFieldsTooLarge,
451, UnavailableForLegalReasons,
500, InternalServerError,
501, NotImplemented,
502, BadGateway,
503, ServiceUnavailable,
504, GatewayTimeout,
505, HttpVersionNotSupported,
506, VariantAlsoNegotiates,
507, InsufficientStorage,
508, LoopDetected,
510, NotExtended,
511, NetworkAuthenticationRequired
}
|
extern crate linked_list;
use self::linked_list::{Cursor, LinkedList};
fn insert(steps: i32, n: i32, cursor: &mut Cursor<i32>) {
for _ in 0..steps {
match cursor.next() {
None => {
cursor.reset();
cursor.next();
},
Some(_) => {}
}
}
cursor.insert(n);
cursor.next();
}
pub fn after_last_written(cursor: &mut Cursor<i32>) -> i32 {
let at_end = cursor.peek_next().is_none();
if at_end {
cursor.reset();
let result = *cursor.peek_next().unwrap();
cursor.prev();
cursor.prev();
result
}
else {
*cursor.peek_next().unwrap()
}
}
fn after_zero(items: &LinkedList<i32>) -> i32 {
let mut prev = None;
let mut result = items.iter().next().map(|item| *item);
for item in items.iter() {
if prev == Some(0) {
result = Some(*item);
}
prev = Some(*item)
}
result.unwrap()
}
pub fn run() {
let steps = 343;
let mut items = LinkedList::new();
items.push_front(0);
{
let mut cursor = items.cursor();
for n in 1..2018 {
insert(steps, n, &mut cursor);
}
println!("Day 17 result 1: {}", after_last_written(&mut cursor));
for n in 2018..50000001 {
insert(steps, n, &mut cursor);
if (n % 10000) == 0 {
println!("{}", n)
}
}
}
println!("Day 17 result 2: {}", after_zero(&items));
} |
use pyo3::prelude::*;
use pyo3::{
types::PyString,
class::PyObjectProtocol,
};
use pathfinder_canvas::Path2D;
use pathfinder_content::{
outline::ArcDirection,
};
use crate::{AutoVector, Transform, Rect};
wrap!(Path, Path2D);
#[pymethods]
impl Path {
#[new]
pub fn new() -> Path {
Path::from(Path2D::new())
}
#[text_signature = "($self)"]
pub fn close(&mut self) {
self.inner.close_path();
}
#[text_signature = "($self, to: Vector)"]
pub fn move_to(&mut self, to: AutoVector) {
self.inner.move_to(*to);
}
#[text_signature = "($self, to: Vector)"]
pub fn line_to(&mut self, to: AutoVector) {
self.inner.line_to(*to);
}
#[text_signature = "($self, ctrl: Vector, to: Vector)"]
pub fn quadratic_curve_to(&mut self, ctrl: AutoVector, to: AutoVector) {
self.inner.quadratic_curve_to(*ctrl, *to);
}
#[text_signature = "($self, ctrl0: Vector, ctrl1: Vector, to: Vector)"]
pub fn bezier_curve_to(&mut self, ctrl0: AutoVector, ctrl1: AutoVector, to: AutoVector) {
self.inner.bezier_curve_to(*ctrl0, *ctrl1, *to);
}
#[text_signature = "($self, center: Vector, radius: float, start_angle: float, end_angle: float, clockwise: bool)"]
pub fn arc(&mut self, center: AutoVector, radius: f32, start_angle: f32, end_angle: f32, clockwise: bool) {
let direction = match clockwise {
false => ArcDirection::CCW,
true => ArcDirection::CW
};
self.inner.arc(*center, radius, start_angle, end_angle, direction);
}
#[text_signature = "($self, center: Vector, radius: float)"]
pub fn circle(&mut self, center: AutoVector, radius: f32) {
self.inner.arc(*center, radius, 0., 2.0 * std::f32::consts::PI, ArcDirection::CCW);
}
#[text_signature = "($self, ctrl: Vector, to: Vector, radius: float)"]
pub fn arc_to(&mut self, ctrl: AutoVector, to: AutoVector, radius: f32) {
self.inner.arc_to(*ctrl, *to, radius);
}
#[text_signature = "($self, rect: Rect)"]
pub fn rect(&mut self, rect: Rect) {
self.inner.rect(*rect);
}
#[text_signature = "($self, center: Vector, axes: Vector, rotation: float, start_angle: float, end_angle: float, clockwise: bool)"]
pub fn ellipse(&mut self, center: AutoVector, axes: AutoVector, rotation: f32) {
self.inner.ellipse(*center, *axes, rotation, 0.0, 2.0 * std::f32::consts::PI);
}
#[text_signature = "($self, center: Vector, axes: Vector, rotation: float, start_angle: float, end_angle: float)"]
pub fn ellipse_section(&mut self, center: AutoVector, axes: AutoVector, rotation: f32, start_angle: f32, end_angle: f32) {
self.inner.ellipse(*center, *axes, rotation, start_angle, end_angle);
}
#[text_signature = "($self, rect: Rect, transform: Transform)"]
pub fn add_path(&mut self, path: Path, transform: &Transform) {
self.inner.add_path(path.inner, &**transform)
}
}
#[pyproto]
impl PyObjectProtocol for Path {
fn __str__(&self) -> PyResult<String> {
Ok(format!("{:?}", self.inner))
}
}
|
mod echoer;
fn main() {
echoer::listen("0.0.0.0", 1212).unwrap();
}
|
use std::rc;
use smallvec::SmallVec;
use CoreResult;
use {AttemptFrom, Sym, Node, ParsedNode, SendSyncPhantomData, Stash, StashIndexable, InnerStashIndexable, NodePayload, ParsingStatus};
use helpers::BoundariesChecker;
use range::Range;
use std::slice::Iter;
use std::vec::IntoIter;
pub trait Match: Clone {
type NV: Clone;
fn byte_range(&self) -> Range;
fn to_node(&self) -> rc::Rc<Node<Self::NV>>;
}
impl<V: NodePayload> Match for ParsedNode<V> {
type NV = V::Payload;
fn byte_range(&self) -> Range {
self.root_node.byte_range
}
fn to_node(&self) -> rc::Rc<Node<Self::NV>> {
self.root_node.clone()
}
}
#[derive(Clone,Debug,PartialEq)]
pub struct Text<V: NodePayload> {
pub groups: SmallVec<[Range; 4]>,
pub byte_range: Range,
pattern_sym: Sym,
_phantom: SendSyncPhantomData<V>,
}
impl<V: NodePayload> Text<V> {
pub fn new(groups: SmallVec<[Range; 4]>, byte_range: Range, pattern_sym: Sym) -> Text<V> {
Text {
groups: groups,
byte_range: byte_range,
pattern_sym: pattern_sym,
_phantom: SendSyncPhantomData::new(),
}
}
}
impl<V: NodePayload> Match for Text<V> {
type NV = V::Payload;
fn byte_range(&self) -> Range {
self.byte_range
}
fn to_node(&self) -> rc::Rc<Node<Self::NV>> {
rc::Rc::new(Node {
rule_sym: self.pattern_sym,
byte_range: self.byte_range(),
payload: None,
children: SmallVec::new(),
})
}
}
pub struct PredicateMatches<M> {
pub matches: Vec<M>,
pub status: ParsingStatus,
}
impl<M> PredicateMatches<M> {
pub fn with_status(status: ParsingStatus) -> PredicateMatches<M> {
PredicateMatches {
matches: vec![],
status,
}
}
pub fn continue_with(matches: Vec<M>) -> PredicateMatches<M> {
PredicateMatches {
matches: matches,
status: ParsingStatus::Continue,
}
}
pub fn exit_if_empty(self) -> PredicateMatches<M> {
if self.matches.len() == 0 {
PredicateMatches::with_status(ParsingStatus::Exit)
} else {
self
}
}
pub fn push(&mut self, match_: M) {
self.matches.push(match_)
}
pub fn is_empty(&self) -> bool {
self.matches.is_empty()
}
pub fn len(&self) -> usize {
self.matches.len()
}
pub fn iter(&self) -> Iter<M> {
self.matches.iter()
}
pub fn into_iter(self) -> IntoIter<M> {
self.matches.into_iter()
}
}
pub trait Pattern<StashValue: NodePayload+StashIndexable>: Send + Sync {
type M: Match<NV=StashValue::Payload>;
fn predicate(&self,
stash: &Stash<StashValue>,
sentence: &str)
-> CoreResult<PredicateMatches<Self::M>>;
}
pub trait TerminalPattern<StashValue: NodePayload+StashIndexable>: Pattern<StashValue, M=Text<StashValue>> { }
pub struct TextPattern<StashValue: NodePayload+StashIndexable> {
pattern: ::regex::Regex,
pattern_sym: Sym,
boundaries_checker: BoundariesChecker,
_phantom: SendSyncPhantomData<StashValue>,
}
impl<StashValue: NodePayload+StashIndexable> TextPattern<StashValue> {
pub fn new(regex: ::regex::Regex, sym: Sym, boundaries_checker: BoundariesChecker) -> TextPattern<StashValue> {
TextPattern {
pattern: regex,
pattern_sym: sym,
boundaries_checker,
_phantom: SendSyncPhantomData::new()
}
}
}
impl<StashValue: NodePayload+StashIndexable> Pattern<StashValue> for TextPattern<StashValue> {
type M = Text<StashValue>;
fn predicate(&self,
_stash: &Stash<StashValue>,
sentence: &str)
-> CoreResult<PredicateMatches<Self::M>> {
let mut results = PredicateMatches::with_status(ParsingStatus::Continue);
for cap in self.pattern.captures_iter(&sentence) {
let full = cap.get(0)
.ok_or_else(|| {
format_err!("No capture for regexp {} in rule {:?} for sentence: {}",
self.pattern,
self.pattern_sym,
sentence)
})?;
let full_range = Range(full.start(), full.end());
if !self.boundaries_checker.check(sentence, full_range) {
continue;
}
let mut groups = SmallVec::new();
for (ix, group) in cap.iter().enumerate() {
let group = group.ok_or_else(|| {
format_err!("No capture for regexp {} in rule {:?}, group number {} in \
capture: {}",
self.pattern,
self.pattern_sym,
ix,
full.as_str())
})?;
let range = Range(group.start(), group.end());
groups.push(range);
}
results.push(Text {
groups: groups,
byte_range: full_range,
pattern_sym: self.pattern_sym,
_phantom: SendSyncPhantomData::new()
})
}
Ok(results.exit_if_empty())
}
}
impl<StashValue: NodePayload+StashIndexable> TerminalPattern<StashValue> for TextPattern<StashValue> {}
pub struct TextNegLHPattern<StashValue: NodePayload+StashIndexable> {
pattern: ::regex::Regex,
neg_look_ahead: ::regex::Regex,
boundaries_checker: BoundariesChecker,
pattern_sym: Sym,
_phantom: SendSyncPhantomData<StashValue>,
}
impl<StashValue: NodePayload+StashIndexable> TextNegLHPattern<StashValue> {
pub fn new(pattern: ::regex::Regex,
neg_look_ahead: ::regex::Regex,
pattern_sym: Sym,
boundaries_checker: BoundariesChecker)
-> TextNegLHPattern<StashValue> {
TextNegLHPattern {
pattern,
neg_look_ahead,
pattern_sym,
boundaries_checker,
_phantom: SendSyncPhantomData::new(),
}
}
}
impl<StashValue: NodePayload+StashIndexable> Pattern<StashValue> for TextNegLHPattern<StashValue> {
type M = Text<StashValue>;
fn predicate(&self,
_stash: &Stash<StashValue>,
sentence: &str)
-> CoreResult<PredicateMatches<Text<StashValue>>> {
let mut results = PredicateMatches::with_status(ParsingStatus::Continue);
for cap in self.pattern.captures_iter(&sentence) {
let full = cap.get(0)
.ok_or_else(|| {
format_err!("No capture for regexp {} in rule {:?} for sentence: {}",
self.pattern,
self.pattern_sym,
sentence)
})?;
let full_range = Range(full.start(), full.end());
if !self.boundaries_checker.check(sentence, full_range) {
continue;
}
if let Some(mat) = self.neg_look_ahead.find(&sentence[full.end()..]) {
if mat.start() == 0 {
continue;
}
}
let mut groups = SmallVec::new();
for (ix, group) in cap.iter().enumerate() {
let group = group.ok_or_else(|| {
format_err!("No capture for regexp {} in rule {:?}, group number {} in \
capture: {}",
self.pattern,
self.pattern_sym,
ix,
full.as_str())
})?;
let range = Range(group.start(), group.end());
groups.push(range);
}
results.push(Text {
groups: groups,
byte_range: full_range,
pattern_sym: self.pattern_sym,
_phantom: SendSyncPhantomData::new(),
})
}
Ok(results.exit_if_empty())
}
}
impl<StashValue: NodePayload+StashIndexable> TerminalPattern<StashValue> for TextNegLHPattern<StashValue> {}
pub type AnyNodePattern<V> = FilterNodePattern<V>;
pub struct FilterNodePattern<V>
where V: NodePayload + InnerStashIndexable
{
predicates: Vec<Box<Fn(&V) -> bool + Send + Sync>>,
_phantom: SendSyncPhantomData<V>,
}
impl<V: NodePayload+InnerStashIndexable> AnyNodePattern<V> {
pub fn new() -> AnyNodePattern<V> {
FilterNodePattern {
predicates: vec![],
_phantom: SendSyncPhantomData::new(),
}
}
}
impl<V> FilterNodePattern<V>
where V: NodePayload + InnerStashIndexable
{
pub fn filter(predicates: Vec<Box<Fn(&V) -> bool + Sync + Send>>) -> FilterNodePattern<V> {
FilterNodePattern {
predicates: predicates,
_phantom: SendSyncPhantomData::new(),
}
}
}
impl<StashValue, V> Pattern<StashValue> for FilterNodePattern<V>
where StashValue: NodePayload + StashIndexable,
V: NodePayload<Payload=StashValue::Payload> + InnerStashIndexable<Index=StashValue::Index> + AttemptFrom<StashValue>,
{
type M = ParsedNode<V>;
fn predicate(&self,
stash: &Stash<StashValue>,
_sentence: &str)
-> CoreResult<PredicateMatches<ParsedNode<V>>> {
Ok(PredicateMatches::continue_with(stash.filter(|v|{
self.predicates.iter().all(|predicate| (predicate)(&v))
})))
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! svec4 {
($($item:expr),*) => { {
let mut v = ::smallvec::SmallVec::<[_;4]>::new();
$( v.push($item); )*
v
}
}
}
#[test]
fn test_regex_separated_string() {
let stash = Stash::default();
let checker = BoundariesChecker::detailed();
let pat: TextPattern<usize> = TextPattern::new(::regex::Regex::new("a+").unwrap(), Sym(0), checker);
assert_eq!(vec![Text::new(svec4!(Range(0, 3)), Range(0, 3), Sym(0))],
pat.predicate(&stash, "aaa").unwrap().matches);
assert_eq!(vec![Text::new(svec4!(Range(0, 3)), Range(0, 3), Sym(0))],
pat.predicate(&stash, "aaa bbb").unwrap().matches);
assert_eq!(vec![Text::new(svec4!(Range(4, 7)), Range(4, 7), Sym(0))],
pat.predicate(&stash, "bbb aaa").unwrap().matches);
assert_eq!(Vec::<Text<usize>>::new(), pat.predicate(&stash, "baaa").unwrap().matches);
assert_eq!(Vec::<Text<usize>>::new(), pat.predicate(&stash, "aaab").unwrap().matches);
assert_eq!(Vec::<Text<usize>>::new(), pat.predicate(&stash, "aaaé").unwrap().matches);
assert_eq!(Vec::<Text<usize>>::new(), pat.predicate(&stash, "éaaa").unwrap().matches);
assert_eq!(vec![Text::new(svec4!(Range(1, 4)), Range(1, 4), Sym(0))],
pat.predicate(&stash, "1aaa").unwrap().matches);
assert_eq!(vec![Text::new(svec4!(Range(0, 3)), Range(0, 3), Sym(0))],
pat.predicate(&stash, "aaa1").unwrap().matches);
assert_eq!(vec![Text::new(svec4!(Range(0, 3)), Range(0, 3), Sym(0))],
pat.predicate(&stash, "aaa-toto").unwrap().matches);
}
}
|
extern crate env_logger;
extern crate reqwest;
#[macro_use]
extern crate serde;
extern crate serde_derive;
extern crate serde_json;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Credentials {
access_key_id: String,
secret_key: String,
session_token: String,
expiration: u64,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct KryptonResponse {
credentials: Credentials,
identity_id: String,
}
fn main() -> Result<(), Box<std::error::Error>> {
env_logger::init();
let http_client = reqwest::Client::new();
let res = http_client
.post("https://krypton.soracom.io:8036/v1/provisioning/aws/cognito/credentials")
.header("Content-Type", "application/json")
.send()
.unwrap();
/* data replied by Krypton
let json_str = r#"
{
"credetials": {
"accessKeyId": "MyAccessKeyId",
"expiration": "2019-02-09T08:39:14.701Z",
"secretKey": "MySecretKey",
"sessionToken": "MySessionToken"
},
"identityId": "MyIdentityID",
"region": "MyRegion"
}
"#;
*/
let kr: KryptonResponse = match serde_json::from_reader(res) {
Ok(val) => val,
Err(err) => {
println!("{}", err);
KryptonResponse {
credentials: Credentials {
access_key_id: "".to_string(),
expiration: 0,
secret_key: "".to_string(),
session_token: "".to_string(),
},
identity_id: "err".to_string(),
}
}
};
println!("{:?}", kr);
Ok(())
}
|
//! Futures-aware borrow cell.
//!
//! Given the asynchronous nature of working with futures, managing borrows that
//! live across callbacks can be difficult. This is because lifetimes cannot be
//! moved into closures that are `'static` (i.e. most of the futures-rs
//! combinators).
//!
//! `Borrow` provides runtime checked borrowing, similar to `RefCell`, however
//! `Borrow` also provides `Future` task notifications when borrows are dropped.
extern crate futures;
use futures::{Poll, Async};
use futures::task::AtomicTask;
use std::{fmt, ops, thread};
use std::any::Any;
use std::cell::UnsafeCell;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::{Acquire, Release};
/// A mutable memory location with future-aware dynamically checked borrow
/// rules.
///
/// Safe borrowing of data across `Future` tasks requires that the data is
/// stored in stable memory. To do this, `Borrow` internally creates an `Arc` to
/// store the data.
///
/// See crate level documentation for more details.
pub struct Borrow<T> {
/// The borrow state.
///
/// The state is stored in an `Arc` in order to ensure that it does not move
/// to a different memory location while it is being borrowed.
inner: Arc<Inner<T>>,
}
/// Holds a borrowed value obtained from `Borrow`.
///
/// When this value is dropped, the borrow is released, notiying any pending
/// tasks.
pub struct BorrowGuard<T> {
/// The borrowed ref. This could be a pointer to an inner field of the `T`
/// stored by `Borrow`.
value_ptr: *mut T,
/// Borrowed state
handle: BorrowHandle,
}
/// Error produced by a failed `poll_borrow` call.
#[derive(Debug)]
pub struct BorrowError {
_priv: (),
}
/// Error produced by a failed `try_borrow` call.
#[derive(Debug)]
pub struct TryBorrowError {
is_poisoned: bool,
}
struct Inner<T> {
/// The value that can be valued
value: UnsafeCell<T>,
/// Borrow state
state: State,
}
struct BorrowHandle {
/// The borrow state
state_ptr: *const State,
/// Holds a handle to the Arc, which prevents it from being dropped.
_inner: Arc<Any>,
}
struct State {
/// Tracks if the value is currently borrowed or poisoned.
borrowed: AtomicUsize,
/// The task to notify once the borrow is released
task: AtomicTask,
}
const UNUSED: usize = 0;
const BORROWED: usize = 1;
const POISONED: usize = 2;
// ===== impl Borrow =====
impl<T: 'static> Borrow<T> {
/// Create a new `Borrow` containing `value`.
pub fn new(value: T) -> Borrow<T> {
Borrow {
inner: Arc::new(Inner {
value: UnsafeCell::new(value),
state: State {
borrowed: AtomicUsize::new(UNUSED),
task: AtomicTask::new(),
},
}),
}
}
/// Returns `true` if the value is not already borrowed.
pub fn is_ready(&self) -> bool {
match self.inner.state.borrowed.load(Acquire) {
UNUSED => true,
BORROWED => false,
POISONED => true,
_ => unreachable!(),
}
}
/// Returns `Ready` when the value is not already borrowed.
///
/// When `Ready` is returned, the next call to `poll_borrow` or `try_borrow`
/// is guaranteed to succeed. When `NotReady` is returned, the current task
/// will be notified once the outstanding borrow is released.
pub fn poll_ready(&mut self) -> Poll<(), BorrowError> {
self.inner.state.task.register();
match self.inner.state.borrowed.load(Acquire) {
UNUSED => Ok(Async::Ready(())),
BORROWED => Ok(Async::NotReady),
POISONED => Err(BorrowError::new()),
_ => unreachable!(),
}
}
/// Attempt to borrow the value, returning `NotReady` if it cannot be
/// borrowed.
pub fn poll_borrow(&mut self) -> Poll<BorrowGuard<T>, BorrowError> {
self.inner.state.task.register();
match self.inner.state.borrowed.compare_and_swap(UNUSED, BORROWED, Acquire) {
UNUSED => {
// Lock acquired, fall through
}
BORROWED => return Ok(Async::NotReady),
POISONED => return Err(BorrowError::new()),
_ => unreachable!(),
}
let value_ptr = self.inner.value.get();
let handle = BorrowHandle {
state_ptr: &self.inner.state as *const State,
_inner: self.inner.clone() as Arc<Any>,
};
Ok(Async::Ready(BorrowGuard {
value_ptr,
handle,
}))
}
/// Attempt to borrow the value, returning `Err` if it cannot be borrowed.
pub fn try_borrow(&self) -> Result<BorrowGuard<T>, TryBorrowError> {
match self.inner.state.borrowed.compare_and_swap(UNUSED, BORROWED, Acquire) {
UNUSED => {
// Lock acquired, fall through
}
BORROWED => return Err(TryBorrowError::new(false)),
POISONED => return Err(TryBorrowError::new(true)),
_ => unreachable!(),
}
let value_ptr = self.inner.value.get();
let handle = BorrowHandle {
state_ptr: &self.inner.state as *const State,
_inner: self.inner.clone() as Arc<Any>,
};
Ok(BorrowGuard {
value_ptr,
handle,
})
}
/// Make a new `BorrowGuard` for a component of the borrowed data.
///
/// The `BorrowGuard` is already mutably borrowed, so this cannot fail.
pub fn map<F, U>(mut r: BorrowGuard<T>, f: F) -> BorrowGuard<U>
where F: FnOnce(&mut T) -> &mut U,
{
let u = f(&mut *r) as *mut U;
BorrowGuard {
value_ptr: u,
handle: r.handle,
}
}
/// Make a new `BorrowGuard` for a component of the borrowed data.
///
/// The `BorrowGuard` is already mutably borrowed, so this cannot fail.
pub fn try_map<F, U, E>(mut r: BorrowGuard<T>, f: F)
-> Result<BorrowGuard<U>, (BorrowGuard<T>, E)>
where F: FnOnce(&mut T) -> Result<&mut U, E>
{
let res = f(&mut *r)
.map(|u| u as *mut U);
match res {
Ok(u) => {
Ok(BorrowGuard {
value_ptr: u,
handle: r.handle,
})
}
Err(e) => {
Err((r, e))
}
}
}
}
impl<T: Default + 'static> Default for Borrow<T> {
fn default() -> Borrow<T> {
Borrow::new(T::default())
}
}
impl<T: fmt::Debug + 'static> fmt::Debug for Borrow<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.try_borrow() {
Ok(guard) => {
fmt.debug_struct("Borrow")
.field("data", &*guard)
.finish()
}
Err(e) => {
if e.is_poisoned() {
fmt.debug_struct("Borrow")
.field("data", &"Poisoned")
.finish()
} else {
fmt.debug_struct("Borrow")
.field("data", &"<<borrowed>>")
.finish()
}
},
}
}
}
unsafe impl<T: Send> Send for Borrow<T> { }
unsafe impl<T: Send> Sync for Borrow<T> { }
// ===== impl BorrowGuard =====
impl<T> ops::Deref for BorrowGuard<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.value_ptr }
}
}
impl<T> ops::DerefMut for BorrowGuard<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.value_ptr }
}
}
impl<T: fmt::Debug> fmt::Debug for BorrowGuard<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("BorrowGuard")
.field("data", &**self)
.finish()
}
}
unsafe impl<T: Send> Send for BorrowGuard<T> { }
unsafe impl<T: Sync> Sync for BorrowGuard<T> { }
// ===== impl BorrowHandle =====
impl Drop for BorrowHandle {
fn drop(&mut self) {
let state = unsafe { &*self.state_ptr };
if thread::panicking() {
state.borrowed.store(POISONED, Release);
} else {
state.borrowed.store(UNUSED, Release);
}
state.task.notify();
}
}
// ===== impl BorrowError =====
impl BorrowError {
fn new() -> BorrowError {
BorrowError {
_priv: (),
}
}
}
// ===== impl TryBorrowError =====
impl TryBorrowError {
fn new(is_poisoned: bool) -> TryBorrowError {
TryBorrowError {
is_poisoned,
}
}
pub fn is_poisoned(&self) -> bool {
self.is_poisoned
}
}
|
//! General Purpose Input / Output
//!
//! Abstracted over the PIO (CPUx-PORT port controller)
//!
//! Port B (PB): 10 input/output port
//! Port C (PC): 17 input/output port
//! Port D (PD): 25 input/output port
//! Port E (PE): 18 input/output port
//! Port F (PF): 7 input/output port
//! Port G (PG): 14 input/output port
//! Port H (PH): 12 input/output port
//!
//! PxY_Select variants mapped to alt functions:
//! * 000 (U0): input
//! * 001 (U1): output
//! * 010 (U2): AF0
//! * 011 (U3): AF1
//! * 100 (U4): AF2
//! * 101 (U5): AF3
//! * 110 (U6): AF4
//! * 111 (U7): disabled
use crate::ccu::Ccu;
use crate::hal::digital::v2::{toggleable, InputPin, OutputPin, StatefulOutputPin};
use crate::pac::ccu::BusClockGating2;
use crate::pac::pio::{Config0, Config1, Config2, Data, Driv0, Driv1, Pull0, Pull1, PIO};
use core::convert::Infallible;
use core::marker::PhantomData;
pub trait GpioExt {
type Parts;
fn split(self, ccu: &mut Ccu) -> Self::Parts;
}
pub struct AF0;
pub struct AF1;
pub struct AF2;
pub struct AF3;
pub struct AF4;
/// Input mode
pub struct Input<MODE> {
_mode: PhantomData<MODE>,
}
/// Floating input (type state)
pub struct Floating;
/// Pulled down input (type state)
pub struct PullDown;
/// Pulled up input (type state)
pub struct PullUp;
/// Output mode
pub struct Output<MODE> {
_mode: PhantomData<MODE>,
}
/// Push pull output (type state)
pub struct PushPull;
/// Alternate function mode
pub struct Alternate<MODE> {
_mode: PhantomData<MODE>,
}
/// Disabled mode
pub struct Disabled;
// See sun50i-a64.dtsi for drive strength values
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum DriveStrength {
L0_10mA,
L1_20mA,
L2_30mA,
L3_40mA,
}
pub struct Gpio {
pub pb: PortB,
pub pc: PortC,
pub pd: PortD,
}
impl GpioExt for PIO {
type Parts = Gpio;
fn split(self, ccu: &mut Ccu) -> Self::Parts {
ccu.bcg2.enr().modify(BusClockGating2::Pio::Set);
Gpio {
pb: PortB::_new(),
pc: PortC::_new(),
pd: PortD::_new(),
}
}
}
pub struct PortB {
pub pb0: PB0<Disabled>,
pub pb1: PB1<Disabled>,
pub pb2: PB2<Disabled>,
pub pb3: PB3<Disabled>,
pub pb4: PB4<Disabled>,
pub pb5: PB5<Disabled>,
pub pb6: PB6<Disabled>,
pub pb7: PB7<Disabled>,
pub pb8: PB8<Disabled>,
pub pb9: PB9<Disabled>,
}
impl PortB {
fn _new() -> Self {
PortB {
pb0: PB0 { _mode: PhantomData },
pb1: PB1 { _mode: PhantomData },
pb2: PB2 { _mode: PhantomData },
pb3: PB3 { _mode: PhantomData },
pb4: PB4 { _mode: PhantomData },
pb5: PB5 { _mode: PhantomData },
pb6: PB6 { _mode: PhantomData },
pb7: PB7 { _mode: PhantomData },
pb8: PB8 { _mode: PhantomData },
pb9: PB9 { _mode: PhantomData },
}
}
}
pub struct PortC {
pub pc0: PC0<Disabled>,
pub pc1: PC1<Disabled>,
pub pc2: PC2<Disabled>,
pub pc3: PC3<Disabled>,
pub pc4: PC4<Disabled>,
pub pc5: PC5<Disabled>,
pub pc6: PC6<Disabled>,
pub pc7: PC7<Disabled>,
pub pc8: PC8<Disabled>,
pub pc9: PC9<Disabled>,
pub pc10: PC10<Disabled>,
pub pc11: PC11<Disabled>,
pub pc12: PC12<Disabled>,
pub pc13: PC13<Disabled>,
pub pc14: PC14<Disabled>,
pub pc15: PC15<Disabled>,
pub pc16: PC16<Disabled>,
}
impl PortC {
fn _new() -> Self {
PortC {
pc0: PC0 { _mode: PhantomData },
pc1: PC1 { _mode: PhantomData },
pc2: PC2 { _mode: PhantomData },
pc3: PC3 { _mode: PhantomData },
pc4: PC4 { _mode: PhantomData },
pc5: PC5 { _mode: PhantomData },
pc6: PC6 { _mode: PhantomData },
pc7: PC7 { _mode: PhantomData },
pc8: PC8 { _mode: PhantomData },
pc9: PC9 { _mode: PhantomData },
pc10: PC10 { _mode: PhantomData },
pc11: PC11 { _mode: PhantomData },
pc12: PC12 { _mode: PhantomData },
pc13: PC13 { _mode: PhantomData },
pc14: PC14 { _mode: PhantomData },
pc15: PC15 { _mode: PhantomData },
pc16: PC16 { _mode: PhantomData },
}
}
}
pub struct PortD {
pub pd0: PD0<Disabled>,
pub pd1: PD1<Disabled>,
pub pd2: PD2<Disabled>,
pub pd3: PD3<Disabled>,
pub pd4: PD4<Disabled>,
pub pd5: PD5<Disabled>,
pub pd6: PD6<Disabled>,
pub pd7: PD7<Disabled>,
pub pd8: PD8<Disabled>,
pub pd9: PD9<Disabled>,
pub pd10: PD10<Disabled>,
pub pd11: PD11<Disabled>,
pub pd12: PD12<Disabled>,
pub pd13: PD13<Disabled>,
pub pd14: PD14<Disabled>,
pub pd15: PD15<Disabled>,
pub pd16: PD16<Disabled>,
}
impl PortD {
fn _new() -> Self {
PortD {
pd0: PD0 { _mode: PhantomData },
pd1: PD1 { _mode: PhantomData },
pd2: PD2 { _mode: PhantomData },
pd3: PD3 { _mode: PhantomData },
pd4: PD4 { _mode: PhantomData },
pd5: PD5 { _mode: PhantomData },
pd6: PD6 { _mode: PhantomData },
pd7: PD7 { _mode: PhantomData },
pd8: PD8 { _mode: PhantomData },
pd9: PD9 { _mode: PhantomData },
pd10: PD10 { _mode: PhantomData },
pd11: PD11 { _mode: PhantomData },
pd12: PD12 { _mode: PhantomData },
pd13: PD13 { _mode: PhantomData },
pd14: PD14 { _mode: PhantomData },
pd15: PD15 { _mode: PhantomData },
pd16: PD16 { _mode: PhantomData },
}
}
}
macro_rules! gpio_pins {
(
// struct field name (r), register type (t)
$CFGr:ident, $CFGt:ident,
$DATAr:ident,
$DRIVr:ident, $DRIVt:ident,
$PULLr:ident, $PULLt:ident,
[$($PXi:ident: ($pxi:ident, $px_field:ident, $MODE:ty),)+]
) => {
$(
pub struct $PXi<MODE> {
_mode: PhantomData<MODE>,
}
impl<MODE> $PXi<MODE> {
pub fn set_drive_strength(&mut self, level: DriveStrength) {
match level {
DriveStrength::L0_10mA =>
unsafe { (*PIO::mut_ptr()).$DRIVr.modify($DRIVt::$px_field::Level0) },
DriveStrength::L1_20mA =>
unsafe { (*PIO::mut_ptr()).$DRIVr.modify($DRIVt::$px_field::Level1) },
DriveStrength::L2_30mA =>
unsafe { (*PIO::mut_ptr()).$DRIVr.modify($DRIVt::$px_field::Level2) },
DriveStrength::L3_40mA =>
unsafe { (*PIO::mut_ptr()).$DRIVr.modify($DRIVt::$px_field::Level3) },
}
}
}
impl<MODE> OutputPin for $PXi<Output<MODE>> {
type Error = Infallible;
fn set_high(&mut self) -> Result<(), Self::Error> {
Ok(unsafe { (*PIO::mut_ptr()).$DATAr.modify(Data::$px_field::Set) })
}
fn set_low(&mut self) -> Result<(), Self::Error> {
Ok(unsafe { (*PIO::mut_ptr()).$DATAr.modify(Data::$px_field::Clear) })
}
}
impl<MODE> InputPin for $PXi<Input<MODE>> {
type Error = Infallible;
fn is_high(&self) -> Result<bool, Self::Error> {
self.is_low().map(|b| !b)
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(unsafe { (*PIO::ptr()).$DATAr.is_set(Data::$px_field::Read) } != true)
}
}
impl<MODE> StatefulOutputPin for $PXi<Output<MODE>> {
fn is_set_high(&self) -> Result<bool, Self::Error> {
self.is_set_low().map(|b| !b)
}
fn is_set_low(&self) -> Result<bool, Self::Error> {
Ok(unsafe { (*PIO::ptr()).$DATAr.is_set(Data::$px_field::Read) } != true)
}
}
impl<MODE> toggleable::Default for $PXi<Output<MODE>> {}
impl<MODE> $PXi<MODE> {
#[inline]
pub fn into_floating_input(self) -> $PXi<Input<Floating>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Input) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::Disabled) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_pull_down_input(self) -> $PXi<Input<PullDown>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Input) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::PullDown) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_pull_up_input(self) -> $PXi<Input<PullUp>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Input) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::PullUp) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_push_pull_output(self) -> $PXi<Output<PushPull>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Output) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::Disabled) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_alternate_af0(self) -> $PXi<Alternate<AF0>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Af0) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::Disabled) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_alternate_af1(self) -> $PXi<Alternate<AF1>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Af1) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::Disabled) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_alternate_af2(self) -> $PXi<Alternate<AF2>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Af2) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::Disabled) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_alternate_af3(self) -> $PXi<Alternate<AF3>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Af3) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::Disabled) };
$PXi { _mode: PhantomData }
}
#[inline]
pub fn into_alternate_af4(self) -> $PXi<Alternate<AF4>> {
unsafe { (*PIO::mut_ptr()).$CFGr.modify($CFGt::$px_field::Af4) };
unsafe { (*PIO::mut_ptr()).$PULLr.modify($PULLt::$px_field::Disabled) };
$PXi { _mode: PhantomData }
}
}
)+
}
}
gpio_pins!(
pb_cfg0,
Config0,
pb_data,
pb_driv0,
Driv0,
pb_pull0,
Pull0,
[
PB0: (pb0, Pin0, Disabled),
PB1: (pb1, Pin1, Disabled),
PB2: (pb2, Pin2, Disabled),
PB3: (pb3, Pin3, Disabled),
PB4: (pb4, Pin4, Disabled),
PB5: (pb5, Pin5, Disabled),
PB6: (pb6, Pin6, Disabled),
PB7: (pb7, Pin7, Disabled),
]
);
gpio_pins!(
pb_cfg1,
Config1,
pb_data,
pb_driv0,
Driv0,
pb_pull0,
Pull0,
[PB8: (pb8, Pin8, Disabled), PB9: (pb9, Pin9, Disabled),]
);
gpio_pins!(
pc_cfg0,
Config0,
pc_data,
pc_driv0,
Driv0,
pc_pull0,
Pull0,
[
PC0: (pc0, Pin0, Disabled),
PC1: (pc1, Pin1, Disabled),
PC2: (pc2, Pin2, Disabled),
PC3: (pc3, Pin3, Disabled),
PC4: (pc4, Pin4, Disabled),
PC5: (pc5, Pin5, Disabled),
PC6: (pc6, Pin6, Disabled),
PC7: (pc7, Pin7, Disabled),
]
);
gpio_pins!(
pc_cfg1,
Config1,
pc_data,
pc_driv0,
Driv0,
pc_pull0,
Pull0,
[
PC8: (pc8, Pin8, Disabled),
PC9: (pc9, Pin9, Disabled),
PC10: (pc10, Pin10, Disabled),
PC11: (pc11, Pin11, Disabled),
PC12: (pc12, Pin12, Disabled),
PC13: (pc13, Pin13, Disabled),
PC14: (pc14, Pin14, Disabled),
PC15: (pc15, Pin15, Disabled),
]
);
gpio_pins!(
pc_cfg2,
Config2,
pc_data,
pc_driv0,
Driv1,
pc_pull1,
Pull1,
[PC16: (pc16, Pin16, Disabled),]
);
gpio_pins!(
pd_cfg0,
Config0,
pd_data,
pd_driv0,
Driv0,
pd_pull0,
Pull0,
[
PD0: (pd0, Pin0, Disabled),
PD1: (pd1, Pin1, Disabled),
PD2: (pd2, Pin2, Disabled),
PD3: (pd3, Pin3, Disabled),
PD4: (pd4, Pin4, Disabled),
PD5: (pd5, Pin5, Disabled),
PD6: (pd6, Pin6, Disabled),
PD7: (pd7, Pin7, Disabled),
]
);
gpio_pins!(
pd_cfg1,
Config1,
pd_data,
pd_driv0,
Driv0,
pd_pull0,
Pull0,
[
PD8: (pd8, Pin8, Disabled),
PD9: (pd9, Pin9, Disabled),
PD10: (pd10, Pin10, Disabled),
PD11: (pd11, Pin11, Disabled),
PD12: (pd12, Pin12, Disabled),
PD13: (pd13, Pin13, Disabled),
PD14: (pd14, Pin14, Disabled),
PD15: (pd15, Pin15, Disabled),
]
);
gpio_pins!(
pd_cfg2,
Config2,
pd_data,
pd_driv0,
Driv1,
pd_pull1,
Pull1,
[PD16: (pd16, Pin16, Disabled),]
);
|
use traits::Primitive;
pub trait Float: Primitive {
fn sqrt(self) -> Self;
}
impl Float for f32 {
fn sqrt(self) -> Self { self.sqrt() }
}
impl Float for f64 {
fn sqrt(self) -> Self { self.sqrt() }
} |
extern crate rppal;
use std::io;
use std::{thread, time};
use std::time::{Duration};
use rppal::{gpio};
use rppal::gpio::{Gpio, Level};
use std::net::{TcpListener, TcpStream};
use std::io::Read;
use std::sync::mpsc;
//
// 27
// 22 26
// 21
// 23 25
// 24
//
const CTRLS : [u8; 4] = [16, 17, 18, 19];
const LEDS : [u8; 8] = [20, 21, 22, 23, 24, 25, 26, 27];
const SEG1 : [u8; 2] = [ 25, 26];
const SEG2 : [u8; 5] = [ 21, 23, 24, 26, 27];
const SEG3 : [u8; 5] = [ 21, 24, 25, 26, 27];
const SEG4 : [u8; 4] = [ 21, 22, 25, 26];
const SEG5 : [u8; 5] = [ 21, 22, 24, 25, 27];
const SEG6 : [u8; 6] = [ 21, 22, 23, 24, 25, 27];
const SEG7 : [u8; 3] = [ 25, 26, 27];
const SEG8 : [u8; 7] = [ 21, 22, 23, 24, 25, 26, 27];
const SEG9 : [u8; 6] = [ 21, 22, 24, 25, 26, 27];
const SEG0 : [u8; 6] = [ 22, 23, 24, 25, 26, 27];
const SEG_ : [u8; 0] = [];
const SEGA : [u8; 7] = [20, 21, 22, 23, 25, 26, 27];
const SEGB : [u8; 8] = [20, 21, 22, 23, 24, 25, 26, 27];
const SEGC : [u8; 6] = [20, 21, 22, 23, 24, 27];
const SEGD : [u8; 7] = [20, 22, 23, 24, 25, 26, 27];
const SEGE : [u8; 6] = [20, 21, 22, 23, 24, 27];
const SEGF : [u8; 5] = [20, 21, 22, 23, 27];
const DELAY : time::Duration = time::Duration::from_millis(1);
fn led(gpio : &Gpio, nums : &[u8]) {
for n in &LEDS {
gpio.write(*n, Level::High);
}
for n in nums {
gpio.write(*n, Level::Low);
}
}
fn unsel_all(gpio : &Gpio) {
for n in &CTRLS {
gpio.write(*n, Level::Low);
}
}
fn sel(gpio : &Gpio, n : u8) {
unsel_all(gpio);
gpio.write(n, Level::High);
}
fn seln(gpio : &Gpio, n : u8) {
match n {
0 => { sel(gpio, n + 16) }
1 => { sel(gpio, n + 16) }
2 => { sel(gpio, n + 16) }
3 => { sel(gpio, n + 16) }
_ => { println!("error")}
}
}
fn ledn(gpio : &Gpio, n : i32) {
match n {
0 => { led(gpio, &SEG0) }
1 => { led(gpio, &SEG1) }
2 => { led(gpio, &SEG2) }
3 => { led(gpio, &SEG3) }
4 => { led(gpio, &SEG4) }
5 => { led(gpio, &SEG5) }
6 => { led(gpio, &SEG6) }
7 => { led(gpio, &SEG7) }
8 => { led(gpio, &SEG8) }
9 => { led(gpio, &SEG9) }
_ => { led(gpio, &SEG_) }
}
}
fn ctrl_7segs(gpio : &Gpio, n : i32) {
seln(&gpio, 0);
ledn(&gpio, n % 10);
std::thread::sleep(DELAY);
let n = n / 10;
seln(&gpio, 1);
ledn(&gpio, n % 10);
std::thread::sleep(DELAY);
let n = n / 10;
seln(&gpio, 2);
ledn(&gpio, n % 10);
std::thread::sleep(DELAY);
let n = n / 10;
seln(&gpio, 3);
ledn(&gpio, n % 10);
std::thread::sleep(DELAY);
}
fn handle_client(stream: TcpStream) -> String {
let mut stream = io::BufReader::new(stream);
let mut buf = [0; 10];
let dsize;
match stream.read(&mut buf) {
Ok(size) => {
// println!("read size : {}", size);
dsize = size;
},
_ => panic!("read error!!!"),
}
// let msg = str::from_utf8(&buf[0..dsize-1]).unwrap().to_string();
let msg = String::from_utf8(buf[0..dsize-1].to_vec()).unwrap();
return msg;
}
fn socket(tx: mpsc::Sender<String>) {
let listener = TcpListener::bind("0.0.0.0:3000").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let msg = handle_client(stream);
// println!(" data : {}", msg);
tx.send(msg).unwrap();
}
Err(_) => {
panic!()
}
};
}
}
fn check_msg (rx: &mpsc::Receiver<String>) -> String {
match rx.recv_timeout(Duration::from_millis(1)) {
Err(mpsc::RecvTimeoutError::Timeout) => {
return "Err".to_string();
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return "Err".to_string();
}
Ok(msg) => {
return msg;
}
}
}
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
socket(tx);
});
let mut gpio = Gpio::new().expect( "Failed Gpio::new" );
for n in &LEDS {
gpio.set_mode(*n, gpio::Mode::Output);
}
for n in &CTRLS {
gpio.set_mode(*n, gpio::Mode::Output);
gpio.write(*n, Level::Low);
}
unsel_all(&gpio);
let mut n = 1;
loop {
let msg = check_msg(&rx);
if msg != "Err" {
// println!("Got : {}", msg);
println!("Got : {}", msg.bytes[0]);
match msg.parse::<i32>() {
Ok(val) => {
n = val;
println!(" valid request : {}", n);
},
Err(_) => {
println!("invalid request : {}", msg);
},
}
}
if msg == "exit" {
break;
}
ctrl_7segs(&gpio, n);
}
for n in &LEDS {
gpio.set_mode(*n, gpio::Mode::Input);
}
for n in &CTRLS {
gpio.set_mode(*n, gpio::Mode::Input);
}
}
|
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VR {
AE,
AS,
AT,
CS,
DA,
DS,
DT,
FD,
FL,
IS,
LO,
LT,
OB,
OD,
OF,
OL,
OW,
OV,
PN,
SH,
SL,
SQ,
SS,
ST,
SV,
TM,
UC,
UI,
UL,
UN,
UR,
US,
UT,
UV,
Unknown { bytes: [u8; 2] },
}
impl VR {
pub fn from_bytes(bytes: &[u8]) -> VR {
match bytes {
b"AE" => VR::AE,
b"AS" => VR::AS,
b"AT" => VR::AT,
b"CS" => VR::CS,
b"DA" => VR::DA,
b"DS" => VR::DS,
b"DT" => VR::DT,
b"FD" => VR::FD,
b"FL" => VR::FL,
b"IS" => VR::IS,
b"LO" => VR::LO,
b"LT" => VR::LT,
b"OB" => VR::OB,
b"OD" => VR::OD,
b"OF" => VR::OF,
b"OL" => VR::OL,
b"OW" => VR::OW,
b"OV" => VR::OV,
b"PN" => VR::PN,
b"SH" => VR::SH,
b"SL" => VR::SL,
b"SQ" => VR::SQ,
b"SS" => VR::SS,
b"ST" => VR::ST,
b"SV" => VR::SV,
b"TM" => VR::TM,
b"UC" => VR::UC,
b"UI" => VR::UI,
b"UL" => VR::UL,
b"UN" => VR::UN,
b"UR" => VR::UR,
b"US" => VR::US,
b"UT" => VR::UT,
b"UV" => VR::UV,
_ => VR::Unknown {
bytes: [bytes[0], bytes[1]],
},
}
}
pub fn explicit_length_is_u32(vr: VR) -> bool {
match vr {
VR::OW | VR::OB | VR::SQ | VR::OF | VR::UT | VR::UN => true,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::VR;
#[test]
fn from_bytes_returns_cs() {
let vr = VR::from_bytes(b"CS");
assert_eq!(vr, VR::CS);
}
#[test]
fn from_bytes_returns_unknown() {
let vr = VR::from_bytes(b"XX");
assert_eq!(
vr,
VR::Unknown {
bytes: [b'X', b'X']
}
);
}
#[test]
fn explicit_length_is_u32_returns_true() {
assert_eq!(true, VR::explicit_length_is_u32(VR::OW));
}
#[test]
fn explicit_length_is_u32_returns_false() {
assert_eq!(false, VR::explicit_length_is_u32(VR::CS));
}
}
|
use regex::Regex;
use crate::{InputType, InputValueError};
pub fn regex<T: AsRef<str> + InputType>(
value: &T,
regex: &'static str,
) -> Result<(), InputValueError<T>> {
if let Ok(true) = Regex::new(regex).map(|re| re.is_match(value.as_ref())) {
Ok(())
} else {
Err(format_args!("value doesn't match expected format '{}'", regex).into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_url() {
assert!(regex(&"123".to_string(), "^[0-9]+$").is_ok());
assert!(regex(&"12a3".to_string(), "^[0-9]+$").is_err());
}
}
|
use super::{run_data_test, InfluxRpcTest};
use async_trait::async_trait;
use data_types::{MAX_NANO_TIME, MIN_NANO_TIME};
use futures::{prelude::*, FutureExt};
use influxdb_storage_client::tag_key_bytes_to_strings;
use std::sync::Arc;
use test_helpers_end_to_end::{DataGenerator, GrpcRequestBuilder, MiniCluster, StepTestState};
#[tokio::test]
async fn tag_keys() {
let generator = Arc::new(DataGenerator::new());
run_data_test(
Arc::clone(&generator),
Box::new(move |state: &mut StepTestState| {
let generator = Arc::clone(&generator);
async move {
let mut storage_client = state.cluster().querier_storage_client();
let tag_keys_request = GrpcRequestBuilder::new()
.source(state.cluster())
.timestamp_range(generator.min_time(), generator.max_time())
.tag_predicate("host", "server01")
.build_tag_keys();
let tag_keys_response = storage_client.tag_keys(tag_keys_request).await.unwrap();
let responses: Vec<_> = tag_keys_response.into_inner().try_collect().await.unwrap();
let keys = &responses[0].values;
let keys: Vec<_> = keys
.iter()
.map(|v| tag_key_bytes_to_strings(v.clone()))
.collect();
assert_eq!(keys, vec!["_m(0x00)", "host", "name", "region", "_f(0xff)"]);
}
.boxed()
}),
)
.await
}
#[tokio::test]
async fn data_without_tags_no_predicate() {
Arc::new(TagKeysTest {
setup_name: "OneMeasurementNoTags",
request: GrpcRequestBuilder::new(),
expected_keys: vec!["_m(0x00)", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn data_without_tags_timestamp_range() {
Arc::new(TagKeysTest {
setup_name: "OneMeasurementNoTags",
request: GrpcRequestBuilder::new().timestamp_range(0, 1_000),
expected_keys: vec!["_m(0x00)", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn no_predicate() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new(),
expected_keys: vec!["_m(0x00)", "borough", "city", "county", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn timestamp_range() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new().timestamp_range(150, 201),
expected_keys: vec!["_m(0x00)", "city", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn timestamp_range_max_time_included() {
Arc::new(TagKeysTest {
setup_name: "MeasurementWithMaxTime",
request: GrpcRequestBuilder::new().timestamp_range(MIN_NANO_TIME + 1, MAX_NANO_TIME + 1),
expected_keys: vec!["_m(0x00)", "host", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn timestamp_range_max_time_excluded() {
Arc::new(TagKeysTest {
setup_name: "MeasurementWithMaxTime",
// exclusive end
request: GrpcRequestBuilder::new().timestamp_range(MIN_NANO_TIME + 1, MAX_NANO_TIME),
expected_keys: vec!["_m(0x00)", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn timestamp_range_all_time() {
Arc::new(TagKeysTest {
setup_name: "MeasurementWithMaxTime",
request: GrpcRequestBuilder::new().timestamp_range(MIN_NANO_TIME, MAX_NANO_TIME + 1),
expected_keys: vec!["_m(0x00)", "host", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn tag_predicates() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new().tag_predicate("state", "MA"),
expected_keys: vec!["_m(0x00)", "city", "county", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn always_true_predicate() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new()
.tag_predicate("state", "MA")
// nonexistent column with !=; always true
.not_tag_predicate("host", "server01"),
expected_keys: vec!["_m(0x00)", "city", "county", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn measurement_predicates() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new().measurement_predicate("o2"),
expected_keys: vec!["_m(0x00)", "borough", "city", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn timestamp_range_and_measurement_predicates() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new()
.timestamp_range(450, 550)
.measurement_predicate("o2"),
expected_keys: vec!["_m(0x00)", "city", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn timestamp_range_and_tag_predicate() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new()
.timestamp_range(150, 201)
.tag_predicate("state", "MA"),
expected_keys: vec!["_m(0x00)", "city", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn measurement_and_tag_predicate() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new()
.measurement_predicate("o2")
.tag_predicate("state", "NY"),
expected_keys: vec!["_m(0x00)", "borough", "city", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn timestamp_range_measurement_and_tag_predicate() {
Arc::new(TagKeysTest {
setup_name: "TwoMeasurementsManyNulls",
request: GrpcRequestBuilder::new()
.timestamp_range(1, 550)
.tag_predicate("state", "NY")
.measurement_predicate("o2"),
expected_keys: vec!["_m(0x00)", "city", "state", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn end_to_end() {
Arc::new(TagKeysTest {
setup_name: "EndToEndTest",
request: GrpcRequestBuilder::new()
.timestamp_range(0, 10000)
.tag_predicate("host", "server01"),
expected_keys: vec!["_m(0x00)", "host", "name", "region", "_f(0xff)"],
})
.run()
.await;
}
#[tokio::test]
async fn periods() {
Arc::new(TagKeysTest {
setup_name: "PeriodsInNames",
request: GrpcRequestBuilder::new().timestamp_range(0, 1_700_000_001_000_000_000),
expected_keys: vec!["_m(0x00)", "tag.one", "tag.two", "_f(0xff)"],
})
.run()
.await;
}
#[derive(Debug)]
struct TagKeysTest {
setup_name: &'static str,
request: GrpcRequestBuilder,
expected_keys: Vec<&'static str>,
}
#[async_trait]
impl InfluxRpcTest for TagKeysTest {
fn setup_name(&self) -> &'static str {
self.setup_name
}
async fn request_and_assert(&self, cluster: &MiniCluster) {
let mut storage_client = cluster.querier_storage_client();
let tag_keys_request = self.request.clone().source(cluster).build_tag_keys();
let tag_keys_response = storage_client.tag_keys(tag_keys_request).await.unwrap();
let responses: Vec<_> = tag_keys_response.into_inner().try_collect().await.unwrap();
let keys = &responses[0].values;
let keys: Vec<_> = keys
.iter()
.map(|s| tag_key_bytes_to_strings(s.to_vec()))
.collect();
assert_eq!(keys, self.expected_keys);
}
}
|
use sxd_document::dom::Element;
pub fn child<'d>(element: &Element<'d>, name: &str) -> Option<Element<'d>> {
element
.children()
.into_iter()
.filter_map(|c| c.element())
.find(|e| e.name().local_part() == name)
}
pub fn attribute<'d>(element: &Element<'d>, attribute: &str) -> Option<&'d str> {
element.attribute(attribute).map(|a| a.value())
}
pub fn text<'d>(element: &Element, buf: &'d mut String) -> &'d str {
buf.clear();
for part in element
.children()
.into_iter()
.filter_map(|c| c.text())
.map(|t| t.text())
{
buf.push_str(part);
}
if buf.trim().is_empty() {
""
} else {
buf
}
}
|
use byteorder::LittleEndian;
use crate::io::BufMut;
use crate::mysql::protocol::{Capabilities, Encode};
use crate::mysql::type_info::MySqlTypeInfo;
bitflags::bitflags! {
// https://dev.mysql.com/doc/dev/mysql-server/8.0.12/mysql__com_8h.html#a3e5e9e744ff6f7b989a604fd669977da
// https://mariadb.com/kb/en/library/com_stmt_execute/#flag
pub struct Cursor: u8 {
const NO_CURSOR = 0;
const READ_ONLY = 1;
const FOR_UPDATE = 2;
const SCROLLABLE = 4;
}
}
// https://dev.mysql.com/doc/dev/mysql-server/8.0.12/page_protocol_com_stmt_execute.html
#[derive(Debug)]
pub struct ComStmtExecute<'a> {
pub statement_id: u32,
pub cursor: Cursor,
pub params: &'a [u8],
pub null_bitmap: &'a [u8],
pub param_types: &'a [MySqlTypeInfo],
}
impl Encode for ComStmtExecute<'_> {
fn encode(&self, buf: &mut Vec<u8>, _: Capabilities) {
// COM_STMT_EXECUTE : int<1>
buf.put_u8(0x17);
// statement_id : int<4>
buf.put_u32::<LittleEndian>(self.statement_id);
// cursor : int<1>
buf.put_u8(self.cursor.bits());
// iterations (always 1) : int<4>
buf.put_u32::<LittleEndian>(1);
if !self.param_types.is_empty() {
// null bitmap : byte<(param_count + 7)/8>
buf.put_bytes(self.null_bitmap);
// send type to server (0 / 1) : byte<1>
buf.put_u8(1);
for ty in self.param_types {
// field type : byte<1>
buf.put_u8(ty.id.0);
// parameter flag : byte<1>
buf.put_u8(if ty.is_unsigned { 0x80 } else { 0 });
}
// byte<n> binary parameter value
buf.put_bytes(self.params);
}
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ICoreFrameworkInputViewInterop(pub ::windows::core::IUnknown);
impl ICoreFrameworkInputViewInterop {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetForWindow<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>, T: ::windows::core::Interface>(&self, appwindow: Param0) -> ::windows::core::Result<T> {
let mut result__ = ::core::option::Option::None;
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), appwindow.into_param().abi(), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__)
}
}
unsafe impl ::windows::core::Interface for ICoreFrameworkInputViewInterop {
type Vtable = ICoreFrameworkInputViewInterop_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0e3da342_b11c_484b_9c1c_be0d61c2f6c5);
}
impl ::core::convert::From<ICoreFrameworkInputViewInterop> for ::windows::core::IUnknown {
fn from(value: ICoreFrameworkInputViewInterop) -> Self {
value.0
}
}
impl ::core::convert::From<&ICoreFrameworkInputViewInterop> for ::windows::core::IUnknown {
fn from(value: &ICoreFrameworkInputViewInterop) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICoreFrameworkInputViewInterop {
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 ICoreFrameworkInputViewInterop {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreFrameworkInputViewInterop_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appwindow: super::super::super::Foundation::HWND, riid: *const ::windows::core::GUID, coreframeworkinputview: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
|
#![feature(path, io, env, core)]
extern crate "pkg-config" as pkg_config;
use std::env;
use std::old_io::{self, fs, Command};
use std::old_io::process::InheritFd;
fn main() {
register_dep("SSH2");
register_dep("OPENSSL");
let mut opts = pkg_config::default_options("libgit2");
opts.atleast_version = Some("0.22.0".to_string());
match pkg_config::find_library_opts("libgit2", &opts) {
Ok(()) => return,
Err(..) => {}
}
let mut cflags = env::var_string("CFLAGS").unwrap_or(String::new());
let target = env::var_string("TARGET").unwrap();
let mingw = target.contains("windows-gnu");
cflags.push_str(" -ffunction-sections -fdata-sections");
if target.contains("i686") {
cflags.push_str(" -m32");
} else if target.as_slice().contains("x86_64") {
cflags.push_str(" -m64");
}
if !target.contains("i686") {
cflags.push_str(" -fPIC");
}
let src = Path::new(env::var_string("CARGO_MANIFEST_DIR").unwrap());
let dst = Path::new(env::var_string("OUT_DIR").unwrap());
let _ = fs::mkdir(&dst.join("build"), old_io::USER_DIR);
let mut cmd = Command::new("cmake");
cmd.arg(src.join("libgit2"))
.cwd(&dst.join("build"));
if mingw {
cmd.arg("-G").arg("Unix Makefiles");
}
let profile = match env::var_string("PROFILE").unwrap().as_slice() {
"bench" | "release" => "Release",
_ => "Debug",
};
run(cmd.arg("-DTHREADSAFE=ON")
.arg("-DBUILD_SHARED_LIBS=OFF")
.arg("-DBUILD_CLAR=OFF")
.arg(format!("-DCMAKE_BUILD_TYPE={}", profile))
.arg(format!("-DCMAKE_INSTALL_PREFIX={}", dst.display()))
.arg("-DBUILD_EXAMPLES=OFF")
.arg(format!("-DCMAKE_C_FLAGS={}", cflags)));
run(Command::new("cmake")
.arg("--build").arg(".")
.arg("--target").arg("install")
.cwd(&dst.join("build")));
println!("cargo:root={}", dst.display());
if mingw || target.contains("windows") {
println!("cargo:rustc-flags=-l winhttp -l rpcrt4 -l ole32 \
-l ws2_32 -l bcrypt -l crypt32 \
-l git2:static -L {}",
dst.join("lib").display());
} else if env::var("HOST") == env::var("TARGET") {
opts.statik = true;
opts.atleast_version = None;
append("PKG_CONFIG_PATH", dst.join("lib/pkgconfig"));
pkg_config::find_library_opts("libgit2", &opts).unwrap();
} else {
println!("cargo:rustc-flags=-l git2:static");
println!("cargo:rustc-flags=-L {}", dst.join("lib").display());
if target.contains("apple") {
println!("cargo:rustc-flags:-l iconv");
}
}
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(cmd.stdout(InheritFd(1))
.stderr(InheritFd(2))
.status()
.unwrap()
.success());
}
fn register_dep(dep: &str) {
match env::var_string(format!("DEP_{}_ROOT", dep).as_slice()) {
Ok(s) => {
append("CMAKE_PREFIX_PATH", Path::new(s.as_slice()));
append("PKG_CONFIG_PATH", Path::new(s.as_slice()).join("lib/pkgconfig"));
}
Err(..) => {}
}
}
fn append(var: &str, val: Path) {
let prefix = env::var_string(var).unwrap_or(String::new());
let val = env::join_paths(env::split_paths(&prefix)
.chain(Some(val).into_iter())).unwrap();
env::set_var(var, &val);
}
|
///Need to determine roman numbers
pub fn solution(){
///Numerals need to be in order. Each pair of numerals can be swapped to form a different number.
///M+(DC or CD)+(LX or XL)+(VI or IV) = a pandigital roman numeral with all of the numerals exactly once
for m in [1000].into_iter(){
for cd in [400, 600].into_iter(){
for xl in [40,60].into_iter(){
for iv in [4,6].into_iter(){
println!("{}", m+cd+xl+iv);
}
}
}
}
} |
//! Comamnd Upgrade
use crate::{
registry::{redep, Registry},
result::{Error, Result},
};
use std::path::PathBuf;
/// Exec command `upgrade`
pub fn exec(path: PathBuf, mut tag: String, update: bool) -> Result<()> {
let registry = Registry::new()?;
if update {
println!("Fetching registry...");
registry.update()?;
}
// tags
let tags = registry.tag()?;
if tag.is_empty() && tags.len() > 0 {
tag = tags[tags.len() - 1].clone();
} else if !tags.contains(&tag) {
return Err(Error::Sup(format!(
"The registry at {} doesn't have tag {}",
registry.0, tag,
)));
}
// Checkout to the target tag
registry.checkout(&tag)?;
let crates = etc::find_all(path, "Cargo.toml")?;
for ct in crates {
redep(&ct, ®istry)?;
}
// Checkout back to the latest commit
registry.checkout("master")?;
Ok(())
}
|
use core::borrow::{Borrow, BorrowMut};
use core::convert::TryFrom;
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
use intrusive_collections::UnsafeRef;
use super::{Block, FreeBlock};
/// Unchecked shared pointer type
///
/// This type is essentially equivalent to a reference-counted
/// smart pointer, e.g. `Rc`/`Arc`, except that no reference count
/// is maintained. Instead the user of `BlockRef` must make sure
/// that the object pointed to is freed manually when no longer needed.
///
/// Guarantees that are expected to be upheld by users of `BlockRef`:
///
/// - The object pointed to by `BlockRef` is not moved or dropped
/// while a `BlockRef` points to it. This will result in use-after-free,
/// or undefined behavior.
/// - Additionally, you must not allow a mutable reference to be held
/// or created while a `BlockRef` pointing to the same object is in use,
/// unless special care is taken to ensure that only one or the other is
/// used to access the underlying object at any given time.
///
/// For example, if you create a `Block`, then create a `BlockRef` pointing
/// to that block, then subsequently obtain a mutable reference to the block
/// via the `BlockRef` or using standard means, then it must never be the
/// case that there are other active references pointing to the same object while
/// the mutable reference is in use.
///
/// NOTE: This type is used internally to make block management more ergonomic
/// while avoiding the use of raw pointers. It can be used in lieu of either
/// raw pointers or references, as it derefs to the `Block` it points to. Since
/// we have an extra flag bit in `Block` available, we could use it to track whether
/// more than one mutable reference has been created to the same block, and panic,
/// but currently that is not the case.
#[derive(Debug, Copy, PartialEq)]
#[repr(transparent)]
pub struct BlockRef(NonNull<Block>);
// Conversions
impl From<FreeBlockRef> for BlockRef {
#[inline]
fn from(block_ref: FreeBlockRef) -> Self {
Self(block_ref.0.cast())
}
}
impl From<&Block> for BlockRef {
#[inline]
fn from(block: &Block) -> Self {
let nn = unsafe { NonNull::new_unchecked(block as *const _ as *mut _) };
Self(nn)
}
}
impl From<&mut Block> for BlockRef {
#[inline]
fn from(block: &mut Block) -> Self {
let nn = unsafe { NonNull::new_unchecked(block as *mut _) };
Self(nn)
}
}
impl From<UnsafeRef<Block>> for BlockRef {
#[inline]
fn from(block: UnsafeRef<Block>) -> Self {
let raw = UnsafeRef::into_raw(block) as *mut Block;
let nn = unsafe { NonNull::new_unchecked(raw) };
Self(nn)
}
}
impl From<UnsafeRef<FreeBlock>> for BlockRef {
#[inline]
fn from(block: UnsafeRef<FreeBlock>) -> Self {
let raw = UnsafeRef::into_raw(block) as *const _ as *mut Block;
let nn = unsafe { NonNull::new_unchecked(raw) };
Self(nn)
}
}
impl BlockRef {
/// Creates a new `BlockRef` from a raw pointer.
///
/// NOTE: This is very unsafe! You must make sure that
/// the object being pointed to will not live longer than
/// the `BlockRef` returned, or use-after-free will result.
#[inline]
pub unsafe fn from_raw(ptr: *const Block) -> Self {
Self(NonNull::new_unchecked(ptr as *mut _))
}
/// Converts a `BlockRef` into the underlying raw pointer.
#[allow(unused)]
#[inline]
pub fn into_raw(ptr: Self) -> *mut Block {
ptr.0.as_ptr()
}
/// Gets the underlying pointer from the `BlockRef`
#[allow(unused)]
#[inline]
pub fn as_ptr(&self) -> *mut Block {
self.0.as_ptr()
}
}
impl Clone for BlockRef {
#[inline]
fn clone(&self) -> BlockRef {
Self(self.0)
}
}
impl Deref for BlockRef {
type Target = Block;
#[inline]
fn deref(&self) -> &Block {
self.as_ref()
}
}
impl DerefMut for BlockRef {
#[inline]
fn deref_mut(&mut self) -> &mut Block {
self.as_mut()
}
}
impl AsRef<Block> for BlockRef {
#[inline]
fn as_ref(&self) -> &Block {
unsafe { self.0.as_ref() }
}
}
impl AsMut<Block> for BlockRef {
#[inline]
fn as_mut(&mut self) -> &mut Block {
unsafe { self.0.as_mut() }
}
}
impl Borrow<Block> for BlockRef {
#[inline]
fn borrow(&self) -> &Block {
self.as_ref()
}
}
impl BorrowMut<Block> for BlockRef {
#[inline]
fn borrow_mut(&mut self) -> &mut Block {
self.as_mut()
}
}
unsafe impl Send for BlockRef {}
unsafe impl Sync for BlockRef {}
/// Same as `BlockRef`, but for `FreeBlock`
///
/// In many cases, it is fine to use `BlockRef` to
/// represent references to `FreeBlock`, but for safety
/// we want to ensure that we don't try to treat a
/// `Block` as a `FreeBlock` when that block was never
/// initialized as a free block, or has since been overwritten
/// with user data.
///
/// By using `FreeBlockRef` in conjunction with `BlockRef`,
/// providing safe conversions between them, as well as unsafe
/// conversions for the few occasions where that is necessary,
/// we can provide some compile-time guarantees that protect us
/// against simple mistakes
#[derive(Debug, Copy, PartialEq)]
#[repr(transparent)]
pub struct FreeBlockRef(NonNull<FreeBlock>);
// Conversions
impl From<&FreeBlock> for FreeBlockRef {
#[inline]
fn from(block: &FreeBlock) -> FreeBlockRef {
let nn = unsafe { NonNull::new_unchecked(block as *const _ as *mut _) };
FreeBlockRef(nn)
}
}
impl From<&mut FreeBlock> for FreeBlockRef {
#[inline]
fn from(block: &mut FreeBlock) -> FreeBlockRef {
let nn = unsafe { NonNull::new_unchecked(block as *mut _) };
FreeBlockRef(nn)
}
}
impl From<UnsafeRef<FreeBlock>> for FreeBlockRef {
#[inline]
fn from(block: UnsafeRef<FreeBlock>) -> FreeBlockRef {
let raw = UnsafeRef::into_raw(block);
let nn = unsafe { NonNull::new_unchecked(raw) };
FreeBlockRef(nn)
}
}
impl Into<UnsafeRef<FreeBlock>> for FreeBlockRef {
#[inline]
fn into(self) -> UnsafeRef<FreeBlock> {
let raw = FreeBlockRef::into_raw(self);
unsafe { UnsafeRef::from_raw(raw) }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TryFromBlockError;
impl TryFrom<&Block> for FreeBlockRef {
type Error = TryFromBlockError;
#[inline]
fn try_from(block: &Block) -> Result<Self, Self::Error> {
if !block.is_free() {
return Err(TryFromBlockError);
}
Ok(unsafe { FreeBlockRef::from_raw(block as *const _ as *mut FreeBlock) })
}
}
impl TryFrom<&mut Block> for FreeBlockRef {
type Error = TryFromBlockError;
#[inline]
fn try_from(block: &mut Block) -> Result<Self, Self::Error> {
if !block.is_free() {
return Err(TryFromBlockError);
}
Ok(unsafe { FreeBlockRef::from_raw(block as *const _ as *mut FreeBlock) })
}
}
impl TryFrom<BlockRef> for FreeBlockRef {
type Error = TryFromBlockError;
#[inline]
fn try_from(block: BlockRef) -> Result<Self, Self::Error> {
if !block.is_free() {
return Err(TryFromBlockError);
}
Ok(FreeBlockRef(block.0.cast()))
}
}
impl FreeBlockRef {
/// Creates a new `FreeBlockRef` from a raw pointer.
///
/// NOTE: This is very unsafe! You must make sure that
/// the object being pointed to will not live longer than
/// the `FreeBlockRef` returned, or use-after-free will result.
#[inline]
pub unsafe fn from_raw(ptr: *const FreeBlock) -> Self {
Self(NonNull::new_unchecked(ptr as *mut _))
}
/// Converts a `BlockRef` into the underlying raw pointer.
#[inline]
pub fn into_raw(ptr: Self) -> *mut FreeBlock {
ptr.0.as_ptr()
}
/// Gets the underlying pointer from the `FreeBlockRef`
#[inline]
pub fn as_ptr(&self) -> *mut FreeBlock {
self.0.as_ptr()
}
}
impl Clone for FreeBlockRef {
#[inline]
fn clone(&self) -> Self {
Self(self.0)
}
}
impl Deref for FreeBlockRef {
type Target = FreeBlock;
#[inline]
fn deref(&self) -> &FreeBlock {
self.as_ref()
}
}
impl DerefMut for FreeBlockRef {
#[inline]
fn deref_mut(&mut self) -> &mut FreeBlock {
self.as_mut()
}
}
impl AsRef<Block> for FreeBlockRef {
#[inline]
fn as_ref(&self) -> &Block {
let raw = self.0.as_ptr() as *mut Block;
unsafe { &*raw }
}
}
impl AsRef<FreeBlock> for FreeBlockRef {
#[inline]
fn as_ref(&self) -> &FreeBlock {
unsafe { self.0.as_ref() }
}
}
impl AsMut<Block> for FreeBlockRef {
#[inline]
fn as_mut(&mut self) -> &mut Block {
let raw = self.0.as_ptr() as *mut Block;
unsafe { &mut *raw }
}
}
impl AsMut<FreeBlock> for FreeBlockRef {
#[inline]
fn as_mut(&mut self) -> &mut FreeBlock {
unsafe { self.0.as_mut() }
}
}
impl Borrow<Block> for FreeBlockRef {
#[inline]
fn borrow(&self) -> &Block {
self.as_ref()
}
}
impl Borrow<FreeBlock> for FreeBlockRef {
#[inline]
fn borrow(&self) -> &FreeBlock {
self.as_ref()
}
}
impl BorrowMut<Block> for FreeBlockRef {
#[inline]
fn borrow_mut(&mut self) -> &mut Block {
self.as_mut()
}
}
impl BorrowMut<FreeBlock> for FreeBlockRef {
#[inline]
fn borrow_mut(&mut self) -> &mut FreeBlock {
self.as_mut()
}
}
unsafe impl Send for FreeBlockRef {}
unsafe impl Sync for FreeBlockRef {}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{framework::*, model::*, startup::BuiltinRootCapabilities},
cm_rust::{data, CapabilityPath},
failure::format_err,
fidl::endpoints::{Proxy, ServerEnd},
fidl_fuchsia_io::{self as fio, DirectoryProxy},
fidl_fuchsia_sys2 as fsys, fuchsia_async as fasync, fuchsia_zircon as zx,
futures::future::join_all,
std::sync::Arc,
};
/// Parameters for initializing a component model, particularly the root of the component
/// instance tree.
pub struct ModelParams {
/// Builtin services that are available in the root realm.
pub builtin_capabilities: Arc<BuiltinRootCapabilities>,
/// The URL of the root component.
pub root_component_url: String,
/// The component resolver registry used in the root realm.
/// In particular, it will be used to resolve the root component itself.
pub root_resolver_registry: ResolverRegistry,
/// The built-in ELF runner, used for starting components with an ELF binary.
pub elf_runner: Arc<dyn Runner + Send + Sync + 'static>,
/// Configuration options for the model.
pub config: ModelConfig,
}
/// The component model holds authoritative state about a tree of component instances, including
/// each instance's identity, lifecycle, capabilities, and topological relationships. It also
/// provides operations for instantiating, destroying, querying, and controlling component
/// instances at runtime.
///
/// To facilitate unit testing, the component model does not directly perform IPC. Instead, it
/// delegates external interfacing concerns to other objects that implement traits such as
/// `Runner` and `Resolver`.
#[derive(Clone)]
pub struct Model {
pub root_realm: Arc<Realm>,
pub config: ModelConfig,
/// Builtin services that are available in the root realm.
pub builtin_capabilities: Arc<BuiltinRootCapabilities>,
pub realm_capability_host: Option<RealmCapabilityHost>,
/// The built-in ELF runner, used for starting components with an ELF binary.
// TODO(fxb/4761): Remove. This should be a routed capability, and
// not explicitly passed around in the model.
pub elf_runner: Arc<dyn Runner + Send + Sync>,
}
/// Holds configuration options for the model.
#[derive(Clone)]
pub struct ModelConfig {
/// How many children, maximum, are returned by a call to `ChildIterator.next()`.
pub list_children_batch_size: usize,
}
impl ModelConfig {
pub fn default() -> Self {
ModelConfig { list_children_batch_size: 1000 }
}
fn validate(&self) {
assert!(self.list_children_batch_size > 0, "list_children_batch_size is 0");
}
}
impl Model {
/// Creates a new component model and initializes its topology.
pub fn new(params: ModelParams) -> Model {
params.config.validate();
Model {
root_realm: Arc::new(Realm::new_root_realm(
params.root_resolver_registry,
params.root_component_url,
)),
config: params.config,
builtin_capabilities: params.builtin_capabilities,
realm_capability_host: None,
elf_runner: params.elf_runner,
}
}
/// Binds to the component instance with the specified moniker, causing it to start if it is
/// not already running. Also binds to any descendant component instances that need to be
/// eagerly started.
pub async fn look_up_and_bind_instance(
&self,
abs_moniker: AbsoluteMoniker,
) -> Result<(), ModelError> {
let realm: Arc<Realm> = self.look_up_realm(&abs_moniker).await?;
self.bind_instance(realm).await
}
/// Binds to the component instance of the specified realm, causing it to start if it is
/// not already running. Also binds to any descendant component instances that need to be
/// eagerly started.
pub async fn bind_instance(&self, realm: Arc<Realm>) -> Result<(), ModelError> {
let eager_children = self.bind_single_instance(realm).await?;
// If the bind to this realm's instance succeeded but the child is shut down, allow
// the call to succeed. We don't want the fact that the child is shut down to cause the
// client to think the bind to this instance failed.
//
// TODO: Have a more general strategy for dealing with errors from eager binding. Should
// we ever pass along the error?
self.bind_eager_children_recursive(eager_children).await.or_else(|e| match e {
ModelError::InstanceShutDown { .. } => Ok(()),
_ => Err(e),
})?;
Ok(())
}
/// Given a realm and path, lazily bind to the instance in the realm, open its outgoing
/// directory at that path, then bind its eager children.
pub async fn bind_instance_open_outgoing<'a>(
&'a self,
realm: Arc<Realm>,
flags: u32,
open_mode: u32,
path: &'a CapabilityPath,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
let eager_children = {
let eager_children = self.bind_single_instance(realm.clone()).await?;
let server_end = ServerEnd::new(server_chan);
let execution = realm.lock_execution().await;
if execution.runtime.is_none() {
return Err(ModelError::capability_discovery_error(format_err!(
"component hosting capability isn't running: {}",
realm.abs_moniker
)));
}
let out_dir = &execution
.runtime
.as_ref()
.expect("bind_instance_open_outgoing: no runtime")
.outgoing_dir
.as_ref()
.ok_or(ModelError::capability_discovery_error(format_err!(
"component hosting capability is non-executable: {}",
realm.abs_moniker
)))?;
let path = path.to_string();
let path = io_util::canonicalize_path(&path);
out_dir.open(flags, open_mode, path, server_end).map_err(|e| {
ModelError::capability_discovery_error(format_err!(
"failed to open outgoing dir for {}: {}",
realm.abs_moniker,
e
))
})?;
eager_children
};
self.bind_eager_children_recursive(eager_children).await?;
Ok(())
}
/// Given a realm and path, lazily bind to the instance in the realm, open its exposed
/// directory, then bind its eager children.
pub async fn bind_instance_open_exposed<'a>(
&'a self,
realm: Arc<Realm>,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
let eager_children = {
let eager_children = self.bind_single_instance(realm.clone()).await?;
let server_end = ServerEnd::new(server_chan);
let execution = realm.lock_execution().await;
if execution.runtime.is_none() {
return Err(ModelError::capability_discovery_error(format_err!(
"component hosting capability isn't running: {}",
realm.abs_moniker
)));
}
let exposed_dir = &execution
.runtime
.as_ref()
.expect("bind_instance_open_exposed: no runtime")
.exposed_dir;
// TODO(fxb/36541): Until directory capabilities specify rights, we always open
// directories using OPEN_FLAG_POSIX which automatically opens the new connection using
// the same directory rights as the parent directory connection.
let flags = fio::OPEN_RIGHT_READABLE | fio::OPEN_FLAG_POSIX;
exposed_dir
.root_dir
.open(flags, fio::MODE_TYPE_DIRECTORY, vec![], server_end)
.await
.map_err(|e| {
ModelError::capability_discovery_error(format_err!(
"failed to open exposed dir for {}: {}",
realm.abs_moniker,
e
))
})?;
eager_children
};
self.bind_eager_children_recursive(eager_children).await?;
Ok(())
}
/// Looks up a realm by absolute moniker. The component instance in the realm will be resolved
/// if that has not already happened.
pub async fn look_up_realm<'a>(
&'a self,
look_up_abs_moniker: &'a AbsoluteMoniker,
) -> Result<Arc<Realm>, ModelError> {
let mut cur_realm = self.root_realm.clone();
for moniker in look_up_abs_moniker.path().iter() {
cur_realm = {
cur_realm.resolve_decl().await?;
let cur_state = cur_realm.lock_state().await;
let cur_state = cur_state.as_ref().expect("look_up_realm: not resolved");
if let Some(r) = cur_state.all_child_realms().get(moniker) {
r.clone()
} else {
return Err(ModelError::instance_not_found(look_up_abs_moniker.clone()));
}
};
}
cur_realm.resolve_decl().await?;
Ok(cur_realm)
}
/// Binds to the component instance in the given realm, starting it if it's not
/// already running. Returns the list of child realms whose instances need to be eagerly started
/// after this function returns. The caller is responsible for calling
/// bind_eager_children_recursive themselves to ensure eager children are recursively binded.
async fn bind_single_instance<'a>(
&'a self,
realm: Arc<Realm>,
) -> Result<Vec<Arc<Realm>>, ModelError> {
let eager_children = self.bind_inner(realm.clone()).await?;
let event = {
let routing_facade = RoutingFacade::new(self.clone());
let mut state = realm.lock_state().await;
let state = state.as_mut().expect("bind_single_instance: not resolved");
let live_child_realms = state.live_child_realms().map(|(_, r)| r.clone()).collect();
Event::BindInstance {
realm: realm.clone(),
component_decl: state.decl().clone(),
live_child_realms,
routing_facade,
}
};
realm.hooks.dispatch(&event).await?;
Ok(eager_children)
}
/// Binds to a list of instances, and any eager children they may return.
async fn bind_eager_children_recursive<'a>(
&'a self,
mut instances_to_bind: Vec<Arc<Realm>>,
) -> Result<(), ModelError> {
loop {
if instances_to_bind.is_empty() {
break;
}
let futures: Vec<_> = instances_to_bind
.iter()
.map(|realm| {
Box::pin(async move { self.bind_single_instance(realm.clone()).await })
})
.collect();
let res = join_all(futures).await;
instances_to_bind.clear();
for e in res {
instances_to_bind.append(&mut e?);
}
}
Ok(())
}
/// Resolves the instance if necessary, starts the component instance, updates the `Execution`,
/// and returns a binding and all child realms that must be bound because they had `eager`
/// startup.
async fn bind_inner<'a>(&'a self, realm: Arc<Realm>) -> Result<Vec<Arc<Realm>>, ModelError> {
let component = realm.resolver_registry.resolve(&realm.component_url).await?;
// The realm's lock needs to be held during `Runner::start` until the `Execution` is set in
// case there are concurrent calls to `bind_inner`.
let decl = {
let mut state = realm.lock_state().await;
if state.is_none() {
*state = Some(RealmState::new(&*realm, component.decl).await?);
}
state.as_ref().unwrap().decl().clone()
};
{
let mut execution = realm.lock_execution().await;
if execution.is_shut_down() {
return Err(ModelError::instance_shut_down(realm.abs_moniker.clone()));
}
if execution.runtime.is_some() {
// TODO: Add binding to the execution once we track bindings.
return Ok(vec![]);
}
let exposed_dir = ExposedDir::new(self, &realm.abs_moniker, decl.clone())?;
execution.runtime = Some(if decl.program.is_some() {
let (outgoing_dir_client, outgoing_dir_server) =
zx::Channel::create().map_err(|e| ModelError::namespace_creation_failed(e))?;
let (runtime_dir_client, runtime_dir_server) =
zx::Channel::create().map_err(|e| ModelError::namespace_creation_failed(e))?;
let mut namespace = IncomingNamespace::new(component.package)?;
let ns = namespace.populate(self.clone(), &realm.abs_moniker, &decl).await?;
let runtime = Runtime::start_from(
component.resolved_url,
Some(namespace),
Some(DirectoryProxy::from_channel(
fasync::Channel::from_channel(outgoing_dir_client).unwrap(),
)),
Some(DirectoryProxy::from_channel(
fasync::Channel::from_channel(runtime_dir_client).unwrap(),
)),
exposed_dir,
)?;
let start_info = fsys::ComponentStartInfo {
resolved_url: Some(runtime.resolved_url.clone()),
program: data::clone_option_dictionary(&decl.program),
ns: Some(ns),
outgoing_dir: Some(ServerEnd::new(outgoing_dir_server)),
runtime_dir: Some(ServerEnd::new(runtime_dir_server)),
};
self.elf_runner.start(start_info).await?;
runtime
} else {
// Although this component has no runtime environment, it is still possible to bind
// to it, which may trigger bindings to its children. For consistency, we still
// consider the component to be "executing" in this case.
Runtime::start_from(component.resolved_url, None, None, None, exposed_dir)?
});
};
let state = realm.lock_state().await;
let eager_child_realms: Vec<_> = state
.as_ref()
.expect("bind_inner: not resolved")
.live_child_realms()
.filter_map(|(_, r)| match r.startup {
fsys::StartupMode::Eager => Some(r.clone()),
fsys::StartupMode::Lazy => None,
})
.collect();
Ok(eager_child_realms)
}
}
|
pub trait EnumRepr {
type Repr;
}
|
pub mod common;
use std::pin::Pin;
use futures::{stream, Stream};
use juniper::{
execute, graphql_input_value, graphql_object, graphql_scalar, graphql_subscription,
graphql_vars,
parser::{ParseError, ScalarToken, Token},
EmptyMutation, FieldResult, InputValue, Object, ParseScalarResult, RootNode, Value, Variables,
};
use self::common::MyScalarValue;
#[graphql_scalar(with = long, scalar = MyScalarValue)]
type Long = i64;
mod long {
use super::*;
pub(super) fn to_output(v: &Long) -> Value<MyScalarValue> {
Value::scalar(*v)
}
pub(super) fn from_input(v: &InputValue<MyScalarValue>) -> Result<Long, String> {
v.as_scalar_value::<i64>()
.copied()
.ok_or_else(|| format!("Expected `MyScalarValue::Long`, found: {v}"))
}
pub(super) fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult<MyScalarValue> {
if let ScalarToken::Int(v) = value {
v.parse()
.map_err(|_| ParseError::unexpected_token(Token::Scalar(value)))
.map(|s: i64| s.into())
} else {
Err(ParseError::unexpected_token(Token::Scalar(value)))
}
}
}
struct TestType;
#[graphql_object(scalar = MyScalarValue)]
impl TestType {
fn long_field() -> i64 {
i64::from(i32::MAX) + 1
}
fn long_with_arg(long_arg: i64) -> i64 {
long_arg
}
}
struct TestSubscriptionType;
#[graphql_subscription(scalar = MyScalarValue)]
impl TestSubscriptionType {
async fn foo() -> Pin<Box<dyn Stream<Item = FieldResult<i32, MyScalarValue>> + Send>> {
Box::pin(stream::empty())
}
}
async fn run_variable_query<F>(query: &str, vars: Variables<MyScalarValue>, f: F)
where
F: Fn(&Object<MyScalarValue>) -> (),
{
let schema =
RootNode::new_with_scalar_value(TestType, EmptyMutation::<()>::new(), TestSubscriptionType);
let (result, errs) = execute(query, None, &schema, &vars, &())
.await
.expect("Execution failed");
assert_eq!(errs, []);
println!("Result: {result:?}");
let obj = result.as_object_value().expect("Result is not an object");
f(obj);
}
async fn run_query<F>(query: &str, f: F)
where
F: Fn(&Object<MyScalarValue>) -> (),
{
run_variable_query(query, graphql_vars! {}, f).await;
}
#[tokio::test]
async fn querying_long() {
run_query("{ longField }", |result| {
assert_eq!(
result.get_field_value("longField"),
Some(&Value::scalar(i64::from(i32::MAX) + 1))
);
})
.await;
}
#[tokio::test]
async fn querying_long_arg() {
run_query(
&format!("{{ longWithArg(longArg: {}) }}", i64::from(i32::MAX) + 3),
|result| {
assert_eq!(
result.get_field_value("longWithArg"),
Some(&Value::scalar(i64::from(i32::MAX) + 3))
);
},
)
.await;
}
#[tokio::test]
async fn querying_long_variable() {
let num = i64::from(i32::MAX) + 42;
run_variable_query(
"query q($test: Long!){ longWithArg(longArg: $test) }",
graphql_vars! {"test": InputValue::<_>::scalar(num)},
|result| {
assert_eq!(
result.get_field_value("longWithArg"),
Some(&Value::scalar(num)),
);
},
)
.await;
}
#[test]
fn deserialize_variable() {
let json = format!("{{\"field\": {}}}", i64::from(i32::MAX) + 42);
assert_eq!(
serde_json::from_str::<InputValue<MyScalarValue>>(&json).unwrap(),
graphql_input_value!({
"field": InputValue::<_>::scalar(i64::from(i32::MAX) + 42),
}),
);
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qgenericplugin.h
// dst-file: /src/gui/qgenericplugin.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::core::qobject::*; // 771
use std::ops::Deref;
use super::super::core::qstring::*; // 771
use super::super::core::qobjectdefs::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QGenericPlugin_Class_Size() -> c_int;
// proto: void QGenericPlugin::QGenericPlugin(QObject * parent);
fn C_ZN14QGenericPluginC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: QObject * QGenericPlugin::create(const QString & name, const QString & spec);
fn C_ZN14QGenericPlugin6createERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QGenericPlugin::~QGenericPlugin();
fn C_ZN14QGenericPluginD2Ev(qthis: u64 /* *mut c_void*/);
// proto: const QMetaObject * QGenericPlugin::metaObject();
fn C_ZNK14QGenericPlugin10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QGenericPlugin)=1
#[derive(Default)]
pub struct QGenericPlugin {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QGenericPlugin {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGenericPlugin {
return QGenericPlugin{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGenericPlugin {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QGenericPlugin {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QGenericPlugin::QGenericPlugin(QObject * parent);
impl /*struct*/ QGenericPlugin {
pub fn new<T: QGenericPlugin_new>(value: T) -> QGenericPlugin {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGenericPlugin_new {
fn new(self) -> QGenericPlugin;
}
// proto: void QGenericPlugin::QGenericPlugin(QObject * parent);
impl<'a> /*trait*/ QGenericPlugin_new for (Option<&'a QObject>) {
fn new(self) -> QGenericPlugin {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGenericPluginC2EP7QObject()};
let ctysz: c_int = unsafe{QGenericPlugin_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN14QGenericPluginC2EP7QObject(arg0)};
let rsthis = QGenericPlugin{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QObject * QGenericPlugin::create(const QString & name, const QString & spec);
impl /*struct*/ QGenericPlugin {
pub fn create<RetType, T: QGenericPlugin_create<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.create(self);
// return 1;
}
}
pub trait QGenericPlugin_create<RetType> {
fn create(self , rsthis: & QGenericPlugin) -> RetType;
}
// proto: QObject * QGenericPlugin::create(const QString & name, const QString & spec);
impl<'a> /*trait*/ QGenericPlugin_create<QObject> for (&'a QString, &'a QString) {
fn create(self , rsthis: & QGenericPlugin) -> QObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGenericPlugin6createERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN14QGenericPlugin6createERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGenericPlugin::~QGenericPlugin();
impl /*struct*/ QGenericPlugin {
pub fn free<RetType, T: QGenericPlugin_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QGenericPlugin_free<RetType> {
fn free(self , rsthis: & QGenericPlugin) -> RetType;
}
// proto: void QGenericPlugin::~QGenericPlugin();
impl<'a> /*trait*/ QGenericPlugin_free<()> for () {
fn free(self , rsthis: & QGenericPlugin) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGenericPluginD2Ev()};
unsafe {C_ZN14QGenericPluginD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: const QMetaObject * QGenericPlugin::metaObject();
impl /*struct*/ QGenericPlugin {
pub fn metaObject<RetType, T: QGenericPlugin_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QGenericPlugin_metaObject<RetType> {
fn metaObject(self , rsthis: & QGenericPlugin) -> RetType;
}
// proto: const QMetaObject * QGenericPlugin::metaObject();
impl<'a> /*trait*/ QGenericPlugin_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QGenericPlugin) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGenericPlugin10metaObjectEv()};
let mut ret = unsafe {C_ZNK14QGenericPlugin10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
/// Params defines the set of params for the distribution module.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Params {
#[prost(string, tag = "1")]
pub community_tax: std::string::String,
#[prost(string, tag = "2")]
pub base_proposer_reward: std::string::String,
#[prost(string, tag = "3")]
pub bonus_proposer_reward: std::string::String,
#[prost(bool, tag = "4")]
pub withdraw_addr_enabled: bool,
}
/// ValidatorHistoricalRewards represents historical rewards for a validator.
/// Height is implicit within the store key.
/// Cumulative reward ratio is the sum from the zeroeth period
/// until this period of rewards / tokens, per the spec.
/// The reference count indicates the number of objects
/// which might need to reference this historical entry at any point.
/// ReferenceCount =
/// number of outstanding delegations which ended the associated period (and
/// might need to read that record)
/// + number of slashes which ended the associated period (and might need to
/// read that record)
/// + one per validator for the zeroeth period, set on initialization
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorHistoricalRewards {
#[prost(message, repeated, tag = "1")]
pub cumulative_reward_ratio: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
#[prost(uint32, tag = "2")]
pub reference_count: u32,
}
/// ValidatorCurrentRewards represents current rewards and current
/// period for a validator kept as a running counter and incremented
/// each block as long as the validator's tokens remain constant.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorCurrentRewards {
#[prost(message, repeated, tag = "1")]
pub rewards: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
#[prost(uint64, tag = "2")]
pub period: u64,
}
/// ValidatorAccumulatedCommission represents accumulated commission
/// for a validator kept as a running counter, can be withdrawn at any time.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorAccumulatedCommission {
#[prost(message, repeated, tag = "1")]
pub commission: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
/// ValidatorOutstandingRewards represents outstanding (un-withdrawn) rewards
/// for a validator inexpensive to track, allows simple sanity checks.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorOutstandingRewards {
#[prost(message, repeated, tag = "1")]
pub rewards: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
/// ValidatorSlashEvent represents a validator slash event.
/// Height is implicit within the store key.
/// This is needed to calculate appropriate amount of staking tokens
/// for delegations which are withdrawn after a slash has occurred.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorSlashEvent {
#[prost(uint64, tag = "1")]
pub validator_period: u64,
#[prost(string, tag = "2")]
pub fraction: std::string::String,
}
/// ValidatorSlashEvents is a collection of ValidatorSlashEvent messages.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorSlashEvents {
#[prost(message, repeated, tag = "1")]
pub validator_slash_events: ::std::vec::Vec<ValidatorSlashEvent>,
}
/// FeePool is the global fee pool for distribution.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FeePool {
#[prost(message, repeated, tag = "1")]
pub community_pool: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
/// CommunityPoolSpendProposal details a proposal for use of community funds,
/// together with how many coins are proposed to be spent, and to which
/// recipient account.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CommunityPoolSpendProposal {
#[prost(string, tag = "1")]
pub title: std::string::String,
#[prost(string, tag = "2")]
pub description: std::string::String,
#[prost(string, tag = "3")]
pub recipient: std::string::String,
#[prost(message, repeated, tag = "4")]
pub amount: ::std::vec::Vec<super::super::base::v1beta1::Coin>,
}
/// DelegatorStartingInfo represents the starting info for a delegator reward
/// period. It tracks the previous validator period, the delegation's amount of
/// staking token, and the creation height (to check later on if any slashes have
/// occurred). NOTE: Even though validators are slashed to whole staking tokens,
/// the delegators within the validator may be left with less than a full token,
/// thus sdk.Dec is used.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DelegatorStartingInfo {
#[prost(uint64, tag = "1")]
pub previous_period: u64,
#[prost(string, tag = "2")]
pub stake: std::string::String,
#[prost(uint64, tag = "3")]
pub height: u64,
}
/// DelegationDelegatorReward represents the properties
/// of a delegator's delegation reward.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DelegationDelegatorReward {
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
#[prost(message, repeated, tag = "2")]
pub reward: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
/// CommunityPoolSpendProposalWithDeposit defines a CommunityPoolSpendProposal
/// with a deposit
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CommunityPoolSpendProposalWithDeposit {
#[prost(string, tag = "1")]
pub title: std::string::String,
#[prost(string, tag = "2")]
pub description: std::string::String,
#[prost(string, tag = "3")]
pub recipient: std::string::String,
#[prost(string, tag = "4")]
pub amount: std::string::String,
#[prost(string, tag = "5")]
pub deposit: std::string::String,
}
/// DelegatorWithdrawInfo is the address for where distributions rewards are
/// withdrawn to by default this struct is only used at genesis to feed in
/// default withdraw addresses.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DelegatorWithdrawInfo {
/// delegator_address is the address of the delegator.
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
/// withdraw_address is the address to withdraw the delegation rewards to.
#[prost(string, tag = "2")]
pub withdraw_address: std::string::String,
}
/// ValidatorOutstandingRewardsRecord is used for import/export via genesis json.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorOutstandingRewardsRecord {
/// validator_address is the address of the validator.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
/// outstanding_rewards represents the oustanding rewards of a validator.
#[prost(message, repeated, tag = "2")]
pub outstanding_rewards: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
/// ValidatorAccumulatedCommissionRecord is used for import / export via genesis
/// json.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorAccumulatedCommissionRecord {
/// validator_address is the address of the validator.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
/// accumulated is the accumulated commission of a validator.
#[prost(message, optional, tag = "2")]
pub accumulated: ::std::option::Option<ValidatorAccumulatedCommission>,
}
/// ValidatorHistoricalRewardsRecord is used for import / export via genesis
/// json.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorHistoricalRewardsRecord {
/// validator_address is the address of the validator.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
/// period defines the period the historical rewards apply to.
#[prost(uint64, tag = "2")]
pub period: u64,
/// rewards defines the historical rewards of a validator.
#[prost(message, optional, tag = "3")]
pub rewards: ::std::option::Option<ValidatorHistoricalRewards>,
}
/// ValidatorCurrentRewardsRecord is used for import / export via genesis json.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorCurrentRewardsRecord {
/// validator_address is the address of the validator.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
/// rewards defines the current rewards of a validator.
#[prost(message, optional, tag = "2")]
pub rewards: ::std::option::Option<ValidatorCurrentRewards>,
}
/// DelegatorStartingInfoRecord used for import / export via genesis json.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DelegatorStartingInfoRecord {
/// delegator_address is the address of the delegator.
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
/// validator_address is the address of the validator.
#[prost(string, tag = "2")]
pub validator_address: std::string::String,
/// starting_info defines the starting info of a delegator.
#[prost(message, optional, tag = "3")]
pub starting_info: ::std::option::Option<DelegatorStartingInfo>,
}
/// ValidatorSlashEventRecord is used for import / export via genesis json.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ValidatorSlashEventRecord {
/// validator_address is the address of the validator.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
/// height defines the block height at which the slash event occured.
#[prost(uint64, tag = "2")]
pub height: u64,
/// period is the period of the slash event.
#[prost(uint64, tag = "3")]
pub period: u64,
/// validator_slash_event describes the slash event.
#[prost(message, optional, tag = "4")]
pub validator_slash_event: ::std::option::Option<ValidatorSlashEvent>,
}
/// GenesisState defines the distribution module's genesis state.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GenesisState {
/// params defines all the paramaters of the module.
#[prost(message, optional, tag = "1")]
pub params: ::std::option::Option<Params>,
/// fee_pool defines the fee pool at genesis.
#[prost(message, optional, tag = "2")]
pub fee_pool: ::std::option::Option<FeePool>,
/// fee_pool defines the delegator withdraw infos at genesis.
#[prost(message, repeated, tag = "3")]
pub delegator_withdraw_infos: ::std::vec::Vec<DelegatorWithdrawInfo>,
/// fee_pool defines the previous proposer at genesis.
#[prost(string, tag = "4")]
pub previous_proposer: std::string::String,
/// fee_pool defines the outstanding rewards of all validators at genesis.
#[prost(message, repeated, tag = "5")]
pub outstanding_rewards: ::std::vec::Vec<ValidatorOutstandingRewardsRecord>,
/// fee_pool defines the accumulated commisions of all validators at genesis.
#[prost(message, repeated, tag = "6")]
pub validator_accumulated_commissions: ::std::vec::Vec<ValidatorAccumulatedCommissionRecord>,
/// fee_pool defines the historical rewards of all validators at genesis.
#[prost(message, repeated, tag = "7")]
pub validator_historical_rewards: ::std::vec::Vec<ValidatorHistoricalRewardsRecord>,
/// fee_pool defines the current rewards of all validators at genesis.
#[prost(message, repeated, tag = "8")]
pub validator_current_rewards: ::std::vec::Vec<ValidatorCurrentRewardsRecord>,
/// fee_pool defines the delegator starting infos at genesis.
#[prost(message, repeated, tag = "9")]
pub delegator_starting_infos: ::std::vec::Vec<DelegatorStartingInfoRecord>,
/// fee_pool defines the validator slash events at genesis.
#[prost(message, repeated, tag = "10")]
pub validator_slash_events: ::std::vec::Vec<ValidatorSlashEventRecord>,
}
/// QueryParamsRequest is the request type for the Query/Params RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryParamsRequest {}
/// QueryParamsResponse is the response type for the Query/Params RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryParamsResponse {
/// params defines the parameters of the module.
#[prost(message, optional, tag = "1")]
pub params: ::std::option::Option<Params>,
}
/// QueryValidatorOutstandingRewardsRequest is the request type for the
/// Query/ValidatorOutstandingRewards RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryValidatorOutstandingRewardsRequest {
/// validator_address defines the validator address to query for.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
}
/// QueryValidatorOutstandingRewardsResponse is the response type for the
/// Query/ValidatorOutstandingRewards RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryValidatorOutstandingRewardsResponse {
#[prost(message, optional, tag = "1")]
pub rewards: ::std::option::Option<ValidatorOutstandingRewards>,
}
/// QueryValidatorCommissionRequest is the request type for the
/// Query/ValidatorCommission RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryValidatorCommissionRequest {
/// validator_address defines the validator address to query for.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
}
/// QueryValidatorCommissionResponse is the response type for the
/// Query/ValidatorCommission RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryValidatorCommissionResponse {
/// commission defines the commision the validator received.
#[prost(message, optional, tag = "1")]
pub commission: ::std::option::Option<ValidatorAccumulatedCommission>,
}
/// QueryValidatorSlashesRequest is the request type for the
/// Query/ValidatorSlashes RPC method
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryValidatorSlashesRequest {
/// validator_address defines the validator address to query for.
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
/// starting_height defines the optional starting height to query the slashes.
#[prost(uint64, tag = "2")]
pub starting_height: u64,
/// starting_height defines the optional ending height to query the slashes.
#[prost(uint64, tag = "3")]
pub ending_height: u64,
/// pagination defines an optional pagination for the request.
#[prost(message, optional, tag = "4")]
pub pagination: ::std::option::Option<super::super::base::query::v1beta1::PageRequest>,
}
/// QueryValidatorSlashesResponse is the response type for the
/// Query/ValidatorSlashes RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryValidatorSlashesResponse {
/// slashes defines the slashes the validator received.
#[prost(message, repeated, tag = "1")]
pub slashes: ::std::vec::Vec<ValidatorSlashEvent>,
/// pagination defines the pagination in the response.
#[prost(message, optional, tag = "2")]
pub pagination: ::std::option::Option<super::super::base::query::v1beta1::PageResponse>,
}
/// QueryDelegationRewardsRequest is the request type for the
/// Query/DelegationRewards RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegationRewardsRequest {
/// delegator_address defines the delegator address to query for.
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
/// validator_address defines the validator address to query for.
#[prost(string, tag = "2")]
pub validator_address: std::string::String,
}
/// QueryDelegationRewardsResponse is the response type for the
/// Query/DelegationRewards RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegationRewardsResponse {
/// rewards defines the rewards accrued by a delegation.
#[prost(message, repeated, tag = "1")]
pub rewards: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
/// QueryDelegationTotalRewardsRequest is the request type for the
/// Query/DelegationTotalRewards RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegationTotalRewardsRequest {
/// delegator_address defines the delegator address to query for.
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
}
/// QueryDelegationTotalRewardsResponse is the response type for the
/// Query/DelegationTotalRewards RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegationTotalRewardsResponse {
/// rewards defines all the rewards accrued by a delegator.
#[prost(message, repeated, tag = "1")]
pub rewards: ::std::vec::Vec<DelegationDelegatorReward>,
/// total defines the sum of all the rewards.
#[prost(message, repeated, tag = "2")]
pub total: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
/// QueryDelegatorValidatorsRequest is the request type for the
/// Query/DelegatorValidators RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegatorValidatorsRequest {
/// delegator_address defines the delegator address to query for.
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
}
/// QueryDelegatorValidatorsResponse is the response type for the
/// Query/DelegatorValidators RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegatorValidatorsResponse {
/// validators defines the validators a delegator is delegating for.
#[prost(string, repeated, tag = "1")]
pub validators: ::std::vec::Vec<std::string::String>,
}
/// QueryDelegatorWithdrawAddressRequest is the request type for the
/// Query/DelegatorWithdrawAddress RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegatorWithdrawAddressRequest {
/// delegator_address defines the delegator address to query for.
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
}
/// QueryDelegatorWithdrawAddressResponse is the response type for the
/// Query/DelegatorWithdrawAddress RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryDelegatorWithdrawAddressResponse {
/// withdraw_address defines the delegator address to query for.
#[prost(string, tag = "1")]
pub withdraw_address: std::string::String,
}
/// QueryCommunityPoolRequest is the request type for the Query/CommunityPool RPC
/// method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryCommunityPoolRequest {}
/// QueryCommunityPoolResponse is the response type for the Query/CommunityPool
/// RPC method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryCommunityPoolResponse {
/// pool defines community pool's coins.
#[prost(message, repeated, tag = "1")]
pub pool: ::std::vec::Vec<super::super::base::v1beta1::DecCoin>,
}
#[doc = r" Generated client implementations."]
pub mod query_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = " Query defines the gRPC querier service for distribution module."]
pub struct QueryClient<T> {
inner: tonic::client::Grpc<T>,
}
impl QueryClient<tonic::transport::Channel> {
#[doc = r" Attempt to create a new client by connecting to a given endpoint."]
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: std::convert::TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
Ok(Self::new(conn))
}
}
impl<T> QueryClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
#[doc = " Params queries params of the distribution module."]
pub async fn params(
&mut self,
request: impl tonic::IntoRequest<super::QueryParamsRequest>,
) -> Result<tonic::Response<super::QueryParamsResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path =
http::uri::PathAndQuery::from_static("/cosmos.distribution.v1beta1.Query/Params");
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " ValidatorOutstandingRewards queries rewards of a validator address."]
pub async fn validator_outstanding_rewards(
&mut self,
request: impl tonic::IntoRequest<super::QueryValidatorOutstandingRewardsRequest>,
) -> Result<tonic::Response<super::QueryValidatorOutstandingRewardsResponse>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/ValidatorOutstandingRewards",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " ValidatorCommission queries accumulated commission for a validator."]
pub async fn validator_commission(
&mut self,
request: impl tonic::IntoRequest<super::QueryValidatorCommissionRequest>,
) -> Result<tonic::Response<super::QueryValidatorCommissionResponse>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/ValidatorCommission",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " ValidatorSlashes queries slash events of a validator."]
pub async fn validator_slashes(
&mut self,
request: impl tonic::IntoRequest<super::QueryValidatorSlashesRequest>,
) -> Result<tonic::Response<super::QueryValidatorSlashesResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/ValidatorSlashes",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " DelegationRewards queries the total rewards accrued by a delegation."]
pub async fn delegation_rewards(
&mut self,
request: impl tonic::IntoRequest<super::QueryDelegationRewardsRequest>,
) -> Result<tonic::Response<super::QueryDelegationRewardsResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/DelegationRewards",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " DelegationTotalRewards queries the total rewards accrued by a each"]
#[doc = " validator."]
pub async fn delegation_total_rewards(
&mut self,
request: impl tonic::IntoRequest<super::QueryDelegationTotalRewardsRequest>,
) -> Result<tonic::Response<super::QueryDelegationTotalRewardsResponse>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/DelegationTotalRewards",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " DelegatorValidators queries the validators of a delegator."]
pub async fn delegator_validators(
&mut self,
request: impl tonic::IntoRequest<super::QueryDelegatorValidatorsRequest>,
) -> Result<tonic::Response<super::QueryDelegatorValidatorsResponse>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/DelegatorValidators",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " DelegatorWithdrawAddress queries withdraw address of a delegator."]
pub async fn delegator_withdraw_address(
&mut self,
request: impl tonic::IntoRequest<super::QueryDelegatorWithdrawAddressRequest>,
) -> Result<tonic::Response<super::QueryDelegatorWithdrawAddressResponse>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/DelegatorWithdrawAddress",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " CommunityPool queries the community pool coins."]
pub async fn community_pool(
&mut self,
request: impl tonic::IntoRequest<super::QueryCommunityPoolRequest>,
) -> Result<tonic::Response<super::QueryCommunityPoolResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Query/CommunityPool",
);
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for QueryClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for QueryClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "QueryClient {{ ... }}")
}
}
}
#[doc = r" Generated server implementations."]
pub mod query_server {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = "Generated trait containing gRPC methods that should be implemented for use with QueryServer."]
#[async_trait]
pub trait Query: Send + Sync + 'static {
#[doc = " Params queries params of the distribution module."]
async fn params(
&self,
request: tonic::Request<super::QueryParamsRequest>,
) -> Result<tonic::Response<super::QueryParamsResponse>, tonic::Status>;
#[doc = " ValidatorOutstandingRewards queries rewards of a validator address."]
async fn validator_outstanding_rewards(
&self,
request: tonic::Request<super::QueryValidatorOutstandingRewardsRequest>,
) -> Result<tonic::Response<super::QueryValidatorOutstandingRewardsResponse>, tonic::Status>;
#[doc = " ValidatorCommission queries accumulated commission for a validator."]
async fn validator_commission(
&self,
request: tonic::Request<super::QueryValidatorCommissionRequest>,
) -> Result<tonic::Response<super::QueryValidatorCommissionResponse>, tonic::Status>;
#[doc = " ValidatorSlashes queries slash events of a validator."]
async fn validator_slashes(
&self,
request: tonic::Request<super::QueryValidatorSlashesRequest>,
) -> Result<tonic::Response<super::QueryValidatorSlashesResponse>, tonic::Status>;
#[doc = " DelegationRewards queries the total rewards accrued by a delegation."]
async fn delegation_rewards(
&self,
request: tonic::Request<super::QueryDelegationRewardsRequest>,
) -> Result<tonic::Response<super::QueryDelegationRewardsResponse>, tonic::Status>;
#[doc = " DelegationTotalRewards queries the total rewards accrued by a each"]
#[doc = " validator."]
async fn delegation_total_rewards(
&self,
request: tonic::Request<super::QueryDelegationTotalRewardsRequest>,
) -> Result<tonic::Response<super::QueryDelegationTotalRewardsResponse>, tonic::Status>;
#[doc = " DelegatorValidators queries the validators of a delegator."]
async fn delegator_validators(
&self,
request: tonic::Request<super::QueryDelegatorValidatorsRequest>,
) -> Result<tonic::Response<super::QueryDelegatorValidatorsResponse>, tonic::Status>;
#[doc = " DelegatorWithdrawAddress queries withdraw address of a delegator."]
async fn delegator_withdraw_address(
&self,
request: tonic::Request<super::QueryDelegatorWithdrawAddressRequest>,
) -> Result<tonic::Response<super::QueryDelegatorWithdrawAddressResponse>, tonic::Status>;
#[doc = " CommunityPool queries the community pool coins."]
async fn community_pool(
&self,
request: tonic::Request<super::QueryCommunityPoolRequest>,
) -> Result<tonic::Response<super::QueryCommunityPoolResponse>, tonic::Status>;
}
#[doc = " Query defines the gRPC querier service for distribution module."]
#[derive(Debug)]
pub struct QueryServer<T: Query> {
inner: _Inner<T>,
}
struct _Inner<T>(Arc<T>, Option<tonic::Interceptor>);
impl<T: Query> QueryServer<T> {
pub fn new(inner: T) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, None);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, Some(interceptor.into()));
Self { inner }
}
}
impl<T, B> Service<http::Request<B>> for QueryServer<T>
where
T: Query,
B: HttpBody + Send + Sync + 'static,
B::Error: Into<StdError> + Send + 'static,
{
type Response = http::Response<tonic::body::BoxBody>;
type Error = Never;
type Future = BoxFuture<Self::Response, Self::Error>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<B>) -> Self::Future {
let inner = self.inner.clone();
match req.uri().path() {
"/cosmos.distribution.v1beta1.Query/Params" => {
#[allow(non_camel_case_types)]
struct ParamsSvc<T: Query>(pub Arc<T>);
impl<T: Query> tonic::server::UnaryService<super::QueryParamsRequest> for ParamsSvc<T> {
type Response = super::QueryParamsResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryParamsRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).params(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = ParamsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/ValidatorOutstandingRewards" => {
#[allow(non_camel_case_types)]
struct ValidatorOutstandingRewardsSvc<T: Query>(pub Arc<T>);
impl<T: Query>
tonic::server::UnaryService<super::QueryValidatorOutstandingRewardsRequest>
for ValidatorOutstandingRewardsSvc<T>
{
type Response = super::QueryValidatorOutstandingRewardsResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryValidatorOutstandingRewardsRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move {
(*inner).validator_outstanding_rewards(request).await
};
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = ValidatorOutstandingRewardsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/ValidatorCommission" => {
#[allow(non_camel_case_types)]
struct ValidatorCommissionSvc<T: Query>(pub Arc<T>);
impl<T: Query>
tonic::server::UnaryService<super::QueryValidatorCommissionRequest>
for ValidatorCommissionSvc<T>
{
type Response = super::QueryValidatorCommissionResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryValidatorCommissionRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).validator_commission(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = ValidatorCommissionSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/ValidatorSlashes" => {
#[allow(non_camel_case_types)]
struct ValidatorSlashesSvc<T: Query>(pub Arc<T>);
impl<T: Query> tonic::server::UnaryService<super::QueryValidatorSlashesRequest>
for ValidatorSlashesSvc<T>
{
type Response = super::QueryValidatorSlashesResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryValidatorSlashesRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).validator_slashes(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = ValidatorSlashesSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/DelegationRewards" => {
#[allow(non_camel_case_types)]
struct DelegationRewardsSvc<T: Query>(pub Arc<T>);
impl<T: Query> tonic::server::UnaryService<super::QueryDelegationRewardsRequest>
for DelegationRewardsSvc<T>
{
type Response = super::QueryDelegationRewardsResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryDelegationRewardsRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).delegation_rewards(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = DelegationRewardsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/DelegationTotalRewards" => {
#[allow(non_camel_case_types)]
struct DelegationTotalRewardsSvc<T: Query>(pub Arc<T>);
impl<T: Query>
tonic::server::UnaryService<super::QueryDelegationTotalRewardsRequest>
for DelegationTotalRewardsSvc<T>
{
type Response = super::QueryDelegationTotalRewardsResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryDelegationTotalRewardsRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut =
async move { (*inner).delegation_total_rewards(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = DelegationTotalRewardsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/DelegatorValidators" => {
#[allow(non_camel_case_types)]
struct DelegatorValidatorsSvc<T: Query>(pub Arc<T>);
impl<T: Query>
tonic::server::UnaryService<super::QueryDelegatorValidatorsRequest>
for DelegatorValidatorsSvc<T>
{
type Response = super::QueryDelegatorValidatorsResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryDelegatorValidatorsRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).delegator_validators(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = DelegatorValidatorsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/DelegatorWithdrawAddress" => {
#[allow(non_camel_case_types)]
struct DelegatorWithdrawAddressSvc<T: Query>(pub Arc<T>);
impl<T: Query>
tonic::server::UnaryService<super::QueryDelegatorWithdrawAddressRequest>
for DelegatorWithdrawAddressSvc<T>
{
type Response = super::QueryDelegatorWithdrawAddressResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryDelegatorWithdrawAddressRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut =
async move { (*inner).delegator_withdraw_address(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = DelegatorWithdrawAddressSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Query/CommunityPool" => {
#[allow(non_camel_case_types)]
struct CommunityPoolSvc<T: Query>(pub Arc<T>);
impl<T: Query> tonic::server::UnaryService<super::QueryCommunityPoolRequest>
for CommunityPoolSvc<T>
{
type Response = super::QueryCommunityPoolResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::QueryCommunityPoolRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).community_pool(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = CommunityPoolSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
_ => Box::pin(async move {
Ok(http::Response::builder()
.status(200)
.header("grpc-status", "12")
.body(tonic::body::BoxBody::empty())
.unwrap())
}),
}
}
}
impl<T: Query> Clone for QueryServer<T> {
fn clone(&self) -> Self {
let inner = self.inner.clone();
Self { inner }
}
}
impl<T: Query> Clone for _Inner<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for _Inner<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl<T: Query> tonic::transport::NamedService for QueryServer<T> {
const NAME: &'static str = "cosmos.distribution.v1beta1.Query";
}
}
/// MsgSetWithdrawAddress sets the withdraw address for
/// a delegator (or validator self-delegation).
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgSetWithdrawAddress {
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
#[prost(string, tag = "2")]
pub withdraw_address: std::string::String,
}
/// MsgSetWithdrawAddressResponse defines the Msg/SetWithdrawAddress response type.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgSetWithdrawAddressResponse {}
/// MsgWithdrawDelegatorReward represents delegation withdrawal to a delegator
/// from a single validator.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgWithdrawDelegatorReward {
#[prost(string, tag = "1")]
pub delegator_address: std::string::String,
#[prost(string, tag = "2")]
pub validator_address: std::string::String,
}
/// MsgWithdrawDelegatorRewardResponse defines the Msg/WithdrawDelegatorReward response type.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgWithdrawDelegatorRewardResponse {}
/// MsgWithdrawValidatorCommission withdraws the full commission to the validator
/// address.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgWithdrawValidatorCommission {
#[prost(string, tag = "1")]
pub validator_address: std::string::String,
}
/// MsgWithdrawValidatorCommissionResponse defines the Msg/WithdrawValidatorCommission response type.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgWithdrawValidatorCommissionResponse {}
/// MsgFundCommunityPool allows an account to directly
/// fund the community pool.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgFundCommunityPool {
#[prost(message, repeated, tag = "1")]
pub amount: ::std::vec::Vec<super::super::base::v1beta1::Coin>,
#[prost(string, tag = "2")]
pub depositor: std::string::String,
}
/// MsgFundCommunityPoolResponse defines the Msg/FundCommunityPool response type.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MsgFundCommunityPoolResponse {}
#[doc = r" Generated client implementations."]
pub mod msg_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = " Msg defines the distribution Msg service."]
pub struct MsgClient<T> {
inner: tonic::client::Grpc<T>,
}
impl MsgClient<tonic::transport::Channel> {
#[doc = r" Attempt to create a new client by connecting to a given endpoint."]
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: std::convert::TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
Ok(Self::new(conn))
}
}
impl<T> MsgClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
#[doc = " SetWithdrawAddress defines a method to change the withdraw address "]
#[doc = " for a delegator (or validator self-delegation)."]
pub async fn set_withdraw_address(
&mut self,
request: impl tonic::IntoRequest<super::MsgSetWithdrawAddress>,
) -> Result<tonic::Response<super::MsgSetWithdrawAddressResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Msg/SetWithdrawAddress",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " WithdrawDelegatorReward defines a method to withdraw rewards of delegator"]
#[doc = " from a single validator."]
pub async fn withdraw_delegator_reward(
&mut self,
request: impl tonic::IntoRequest<super::MsgWithdrawDelegatorReward>,
) -> Result<tonic::Response<super::MsgWithdrawDelegatorRewardResponse>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Msg/WithdrawDelegatorReward",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " WithdrawValidatorCommission defines a method to withdraw the "]
#[doc = " full commission to the validator address."]
pub async fn withdraw_validator_commission(
&mut self,
request: impl tonic::IntoRequest<super::MsgWithdrawValidatorCommission>,
) -> Result<tonic::Response<super::MsgWithdrawValidatorCommissionResponse>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Msg/WithdrawValidatorCommission",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " FundCommunityPool defines a method to allow an account to directly"]
#[doc = " fund the community pool."]
pub async fn fund_community_pool(
&mut self,
request: impl tonic::IntoRequest<super::MsgFundCommunityPool>,
) -> Result<tonic::Response<super::MsgFundCommunityPoolResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/cosmos.distribution.v1beta1.Msg/FundCommunityPool",
);
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for MsgClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for MsgClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MsgClient {{ ... }}")
}
}
}
#[doc = r" Generated server implementations."]
pub mod msg_server {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = "Generated trait containing gRPC methods that should be implemented for use with MsgServer."]
#[async_trait]
pub trait Msg: Send + Sync + 'static {
#[doc = " SetWithdrawAddress defines a method to change the withdraw address "]
#[doc = " for a delegator (or validator self-delegation)."]
async fn set_withdraw_address(
&self,
request: tonic::Request<super::MsgSetWithdrawAddress>,
) -> Result<tonic::Response<super::MsgSetWithdrawAddressResponse>, tonic::Status>;
#[doc = " WithdrawDelegatorReward defines a method to withdraw rewards of delegator"]
#[doc = " from a single validator."]
async fn withdraw_delegator_reward(
&self,
request: tonic::Request<super::MsgWithdrawDelegatorReward>,
) -> Result<tonic::Response<super::MsgWithdrawDelegatorRewardResponse>, tonic::Status>;
#[doc = " WithdrawValidatorCommission defines a method to withdraw the "]
#[doc = " full commission to the validator address."]
async fn withdraw_validator_commission(
&self,
request: tonic::Request<super::MsgWithdrawValidatorCommission>,
) -> Result<tonic::Response<super::MsgWithdrawValidatorCommissionResponse>, tonic::Status>;
#[doc = " FundCommunityPool defines a method to allow an account to directly"]
#[doc = " fund the community pool."]
async fn fund_community_pool(
&self,
request: tonic::Request<super::MsgFundCommunityPool>,
) -> Result<tonic::Response<super::MsgFundCommunityPoolResponse>, tonic::Status>;
}
#[doc = " Msg defines the distribution Msg service."]
#[derive(Debug)]
pub struct MsgServer<T: Msg> {
inner: _Inner<T>,
}
struct _Inner<T>(Arc<T>, Option<tonic::Interceptor>);
impl<T: Msg> MsgServer<T> {
pub fn new(inner: T) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, None);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, Some(interceptor.into()));
Self { inner }
}
}
impl<T, B> Service<http::Request<B>> for MsgServer<T>
where
T: Msg,
B: HttpBody + Send + Sync + 'static,
B::Error: Into<StdError> + Send + 'static,
{
type Response = http::Response<tonic::body::BoxBody>;
type Error = Never;
type Future = BoxFuture<Self::Response, Self::Error>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<B>) -> Self::Future {
let inner = self.inner.clone();
match req.uri().path() {
"/cosmos.distribution.v1beta1.Msg/SetWithdrawAddress" => {
#[allow(non_camel_case_types)]
struct SetWithdrawAddressSvc<T: Msg>(pub Arc<T>);
impl<T: Msg> tonic::server::UnaryService<super::MsgSetWithdrawAddress>
for SetWithdrawAddressSvc<T>
{
type Response = super::MsgSetWithdrawAddressResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::MsgSetWithdrawAddress>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).set_withdraw_address(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = SetWithdrawAddressSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Msg/WithdrawDelegatorReward" => {
#[allow(non_camel_case_types)]
struct WithdrawDelegatorRewardSvc<T: Msg>(pub Arc<T>);
impl<T: Msg> tonic::server::UnaryService<super::MsgWithdrawDelegatorReward>
for WithdrawDelegatorRewardSvc<T>
{
type Response = super::MsgWithdrawDelegatorRewardResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::MsgWithdrawDelegatorReward>,
) -> Self::Future {
let inner = self.0.clone();
let fut =
async move { (*inner).withdraw_delegator_reward(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = WithdrawDelegatorRewardSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Msg/WithdrawValidatorCommission" => {
#[allow(non_camel_case_types)]
struct WithdrawValidatorCommissionSvc<T: Msg>(pub Arc<T>);
impl<T: Msg> tonic::server::UnaryService<super::MsgWithdrawValidatorCommission>
for WithdrawValidatorCommissionSvc<T>
{
type Response = super::MsgWithdrawValidatorCommissionResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::MsgWithdrawValidatorCommission>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move {
(*inner).withdraw_validator_commission(request).await
};
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = WithdrawValidatorCommissionSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/cosmos.distribution.v1beta1.Msg/FundCommunityPool" => {
#[allow(non_camel_case_types)]
struct FundCommunityPoolSvc<T: Msg>(pub Arc<T>);
impl<T: Msg> tonic::server::UnaryService<super::MsgFundCommunityPool> for FundCommunityPoolSvc<T> {
type Response = super::MsgFundCommunityPoolResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::MsgFundCommunityPool>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).fund_community_pool(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = FundCommunityPoolSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
_ => Box::pin(async move {
Ok(http::Response::builder()
.status(200)
.header("grpc-status", "12")
.body(tonic::body::BoxBody::empty())
.unwrap())
}),
}
}
}
impl<T: Msg> Clone for MsgServer<T> {
fn clone(&self) -> Self {
let inner = self.inner.clone();
Self { inner }
}
}
impl<T: Msg> Clone for _Inner<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for _Inner<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl<T: Msg> tonic::transport::NamedService for MsgServer<T> {
const NAME: &'static str = "cosmos.distribution.v1beta1.Msg";
}
}
|
pub mod server;
pub mod libssh;
|
use crate::ast::input::Position;
use crate::ast::stat_expr_types::*;
#[derive(PartialEq, Clone, Debug)]
pub struct FindVal<'a> {
name: Option<&'a str>,
lib_name: Option<&'a str>,
ctx_index: i32,
}
impl<'a> FindVal<'a> {
pub fn new(name: &'a str, ctx_index: i32) -> FindVal<'a> {
FindVal {
name: Some(name),
lib_name: None,
ctx_index,
}
}
pub fn new_with_lib_name(lib_name: &'a str) -> FindVal<'a> {
FindVal {
name: None,
lib_name: Some(lib_name),
ctx_index: -1,
}
}
}
struct FindState<'a> {
ctx_index: i32,
lib_names: Vec<&'a str>,
}
impl<'a> FindState<'a> {
pub fn new() -> FindState<'a> {
FindState {
ctx_index: 0,
lib_names: vec![],
}
}
pub fn new_with_lib_names(names: Vec<&'a str>) -> FindState<'a> {
FindState {
ctx_index: 0,
lib_names: names,
}
}
pub fn new_with_ctx_index(ctx_index: i32) -> FindState<'a> {
FindState {
ctx_index,
lib_names: vec![],
}
}
}
trait NodeFinder<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>>;
}
trait LibNameForPrefix {
fn gen_lib_name(&self) -> String;
}
impl<'a> NodeFinder<'a> for TupleNode<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
for exp in self.exps.iter() {
if let Some(res) = exp.find(pos, state) {
return Some(res);
}
}
Some(FindVal::new_with_lib_name("[]"))
}
}
impl<'a> NodeFinder<'a> for TypeCast<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(res) = self.exp.find(pos, state) {
return Some(res);
}
let type_str = match self.data_type {
DataType::Bool => "bool",
DataType::Color => "color",
DataType::Int => "int",
DataType::Float => "float",
DataType::String => "string",
DataType::Custom(t) => t,
};
Some(FindVal::new_with_lib_name(type_str))
}
}
impl<'a> NodeFinder<'a> for FunctionCall<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(res) = self.method.find(pos, state) {
return Some(res);
}
for exp in self.pos_args.iter() {
if let Some(res) = exp.find(pos, state) {
return Some(res);
}
}
for (_, exp) in self.dict_args.iter() {
if let Some(res) = exp.find(pos, state) {
return Some(res);
}
}
None
}
}
impl<'a> NodeFinder<'a> for RefCall<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(res) = self.name.find(pos, state) {
return Some(res);
}
if let Some(res) = self.arg.find(pos, state) {
return Some(res);
}
Some(FindVal::new_with_lib_name("[]"))
}
}
impl<'a> NodeFinder<'a> for PrefixExp<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(res) = self.left_exp.find(pos, state) {
return Some(res);
}
None
}
}
impl<'a> NodeFinder<'a> for Condition<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(res) = self.cond.find(pos, state) {
return Some(res);
}
if let Some(res) = self.exp1.find(pos, state) {
return Some(res);
}
if let Some(res) = self.exp2.find(pos, state) {
return Some(res);
}
None
}
}
impl<'a> NodeFinder<'a> for IfThenElse<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(res) = self.cond.find(pos, state) {
return Some(res);
}
if let Some(res) = self.then_blk.find(pos, state) {
return Some(res);
}
if let Some(blk) = &self.else_blk {
if let Some(e) = blk.find(pos, state) {
return Some(e);
}
}
None
}
}
impl<'a> NodeFinder<'a> for ForRange<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if self.var.range.contain(pos) {
return Some(FindVal::new(self.var.value, self.ctxid));
}
if let Some(res) = self.start.find(pos, state) {
return Some(res);
}
if let Some(res) = self.end.find(pos, state) {
return Some(res);
}
if let Some(exp) = &self.step {
if let Some(e) = exp.find(pos, state) {
return Some(e);
}
}
if let Some(e) = self.do_blk.find(pos, state) {
return Some(e);
}
None
}
}
impl<'a> NodeFinder<'a> for UnaryExp<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(v) = self.exp.find(pos, state) {
return Some(v);
}
None
}
}
impl<'a> NodeFinder<'a> for BinaryExp<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if let Some(v) = self.exp1.find(pos, state) {
return Some(v);
}
if let Some(v) = self.exp2.find(pos, state) {
return Some(v);
}
None
}
}
impl<'a> NodeFinder<'a> for Assignment<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
for (n, _id) in self.names.iter().zip(self.varids.as_ref().unwrap().iter()) {
if n.range.contain(pos) {
return Some(FindVal::new(n.value, state.ctx_index));
}
}
if let Some(e) = self.val.find(pos, state) {
return Some(e);
}
None
}
}
impl<'a> NodeFinder<'a> for VarAssignment<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if self.name.range.contain(pos) {
return Some(FindVal::new(self.name.value, state.ctx_index));
}
if let Some(exp) = self.val.find(pos, state) {
return Some(exp);
}
None
}
}
impl<'a> NodeFinder<'a> for FunctionDef<'a> {
fn find(&self, _pos: Position, _state: &mut FindState) -> Option<FindVal<'a>> {
None
}
}
impl<'a> NodeFinder<'a> for Exp<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if !self.range().contain(pos) {
return None;
}
match self {
Exp::Na(_) | Exp::Bool(_) | Exp::Num(_) | Exp::Str(_) | Exp::Color(_) => None,
Exp::VarName(name) => Some(FindVal::new(name.name.value, state.ctx_index)),
Exp::Tuple(tuple) => tuple.find(pos, state),
Exp::TypeCast(cast) => cast.find(pos, state),
Exp::FuncCall(call) => call.find(pos, state),
Exp::RefCall(call) => call.find(pos, state),
Exp::PrefixExp(prefix) => prefix.find(pos, state),
Exp::Condition(cond) => cond.find(pos, state),
Exp::Ite(ite) => ite.find(pos, state),
Exp::ForRange(for_range) => for_range.find(pos, state),
Exp::Assignment(assign) => assign.find(pos, state),
Exp::VarAssignment(assign) => assign.find(pos, state),
Exp::UnaryExp(exp) => exp.find(pos, state),
Exp::BinaryExp(exp) => exp.find(pos, state),
}
}
}
impl<'a> NodeFinder<'a> for Statement<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if !self.range().contain(pos) {
return None;
}
match self {
Statement::Assignment(assign) => assign.find(pos, state),
Statement::VarAssignment(assign) => assign.find(pos, state),
Statement::Ite(ite) => ite.find(pos, state),
Statement::ForRange(for_range) => for_range.find(pos, state),
Statement::FuncCall(call) => call.find(pos, state),
Statement::FuncDef(def) => def.find(pos, state),
Statement::Exp(exp) => exp.find(pos, state),
_ => None,
}
// Ite(Box<IfThenElse<'a>>),
// ForRange(Box<ForRange<'a>>),
// FuncCall(Box<FunctionCall<'a>>),
// FuncDef(Box<FunctionDef<'a>>),
// Exp(Exp<'a>),
}
}
impl<'a> NodeFinder<'a> for Block<'a> {
fn find(&self, pos: Position, state: &mut FindState) -> Option<FindVal<'a>> {
if !self.range.contain(pos) {
return None;
}
for stmt in self.stmts.iter() {
if let Some(exp) = stmt.find(pos, state) {
return Some(exp);
}
}
if let Some(exp) = &self.ret_stmt {
if let Some(e) = exp.find(pos, state) {
return Some(e);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::input::StrRange;
use crate::ast::name::VarName;
fn gen_var_exp(name: &str, pos: Position) -> Exp {
Exp::VarName(RVVarName::new_with_start(name, pos))
}
#[test]
fn find_exp_test() {
let exp = gen_var_exp("hello", Position::new(1, 10));
assert_eq!(
exp.find(Position::new(1, 11), &mut FindState::new()),
Some(FindVal::new("hello", 0))
);
let tuple_exp = Exp::Tuple(Box::new(TupleNode::new(
vec![
gen_var_exp("he", Position::new(0, 1)),
gen_var_exp("wo", Position::new(0, 3)),
],
StrRange::from_start("he, wo", Position::new(0, 0)),
)));
assert_eq!(
tuple_exp.find(Position::new(0, 4), &mut FindState::new_with_ctx_index(1)),
Some(FindVal::new("wo", 01))
);
assert_eq!(
tuple_exp.find(Position::new(0, 0), &mut FindState::new_with_ctx_index(1)),
Some(FindVal::new_with_lib_name("[]"))
);
let type_cast_exp = Exp::TypeCast(Box::new(TypeCast::new(
DataType::Int,
gen_var_exp("hello", Position::new(0, 10)),
StrRange::from_start("int(hello)", Position::new(0, 5)),
)));
assert_eq!(
type_cast_exp.find(Position::new(0, 11), &mut FindState::new_with_ctx_index(1)),
Some(FindVal::new("hello", 1))
);
let func_call_exp = Exp::FuncCall(Box::new(FunctionCall::new(
gen_var_exp("hello", Position::new(0, 0)),
vec![gen_var_exp("arg1", Position::new(0, 10))],
vec![(
VarName::new_with_start("key", Position::new(0, 20)),
gen_var_exp("arg2", Position::new(0, 30)),
)],
0,
StrRange::new(Position::new(0, 0), Position::new(0, 40)),
)));
assert_eq!(
func_call_exp.find(Position::new(0, 1), &mut FindState::new_with_ctx_index(1)),
Some(FindVal::new("hello", 1))
);
assert_eq!(
func_call_exp.find(Position::new(0, 11), &mut FindState::new_with_ctx_index(1)),
Some(FindVal::new("arg1", 1))
);
assert_eq!(
func_call_exp.find(Position::new(0, 31), &mut FindState::new_with_ctx_index(1)),
Some(FindVal::new("arg2", 1))
);
let ref_call_exp = Exp::RefCall(Box::new(RefCall::new(
gen_var_exp("refcall", Position::new(0, 0)),
gen_var_exp("num", Position::new(0, 10)),
StrRange::new(Position::new(0, 0), Position::new(0, 20)),
)));
assert_eq!(
ref_call_exp.find(Position::new(0, 0), &mut FindState::new()),
Some(FindVal::new("refcall", 0))
);
assert_eq!(
ref_call_exp.find(Position::new(0, 11), &mut FindState::new()),
Some(FindVal::new("num", 0))
);
let prefix_exp = Exp::PrefixExp(Box::new(PrefixExp::new(
gen_var_exp("prefix", Position::new(0, 0)),
VarName::new_with_start("a", Position::new(0, 0)),
StrRange::from_start("prefix.a", Position::new(0, 0)),
)));
assert_eq!(
prefix_exp.find(Position::new(0, 1), &mut FindState::new()),
Some(FindVal::new("prefix", 0))
);
}
}
|
pub mod stepper;
pub mod time;
use hardware::pin::Pin;
pub struct SimulatedPins {
pub x_step: Pin<u8>,
pub y_step: Pin<u8>,
pub z_step: Pin<u8>,
pub x_dir: Pin<u8>,
pub y_dir: Pin<u8>,
pub z_dir: Pin<u8>,
}
|
#![deny(missing_debug_implementations)]
#![forbid(unsafe_code)]
|
#[macro_use]
extern crate failure;
use failure::Fail;
#[derive(Debug, Fail)]
#[fail(display = "my error")]
struct MyError;
#[derive(Debug, Fail)]
#[fail(display = "my wrapping error")]
struct WrappingError(#[fail(cause)] MyError);
fn bad_function() -> Result<(), WrappingError> {
Err(WrappingError(MyError))
}
fn main() {
for cause in Fail::iter_chain(&bad_function().unwrap_err()) {
println!("{}: {}", cause.name().unwrap_or("Error"), cause);
}
}
|
mod create;
pub use create::generate_process_create_subgraph;
|
#[cfg(feature = "convert")]
pub(crate) mod as_mut;
#[cfg(feature = "convert")]
pub(crate) mod as_ref;
|
use crate::models::BelimbingError;
impl From<std::io::Error> for BelimbingError {
fn from(err: std::io::Error) -> Self {
Self::ActixIoError(err)
}
}
|
pub fn get_closest_checkpoint(chain_name: &str, height: u64) -> Option<(u64, &'static str, &'static str)> {
match chain_name {
"test" => get_test_checkpoint(height),
"main" => get_main_checkpoint(height),
_ => None
}
}
fn get_test_checkpoint(height: u64) -> Option<(u64, &'static str, &'static str)> {
let checkpoints: Vec<(u64, &str, &str)> = vec![
(350000, "000cdb1eca1bb84e799e73a32a649a1eeec0a1a563d511dfaceaff69a8006527",
"017f968fad6321e5dde81a4d88a17d262193efccdbfd446f697e2775d25c0b2619014da62eafffb89e4766facabab67199c7fd37c14889d0cce6f9daf96f170ac0060f00017eeb2a8556c7714cbc2502ef958723c1491db8008c9f06858342096880c8333b0139bdb820c2339826cbc6ebc3e8ede79004f865d4d48233e74e21d0cf4821163200000001aac1d37ab43d4417be4e222962eadd77eff4a7475ef30dbcf45618c6da1c581b01ecd7df0652ebb31ec6ca03236491e5c77c4a9de6511ee2894ae09da1a7002b36000146539f39a920f96ffb9727f94721e26b73fd66aa63125c5a4f2884ecb4c9b11b000001dd960b6c11b157d1626f0768ec099af9385aea3f31c91111a8c5b899ffb99e6b0192acd61b1853311b0bf166057ca433e231c93ab5988844a09a91c113ebc58e18019fbfd76ad6d98cafa0174391546e7022afe62e870e20e16d57c4c419a5c2bb69"
),
(550000, "04c99687df30181730a1b74d57b48f97c0df1b96bb8fa7d7a23ad1720df382e5",
"01278664cc8d581b2166cd1e1a06f87a129ca5f61575c197bf0bd979d5ac67d86101f4c1bcce00980181992cf16e481101993b258b32900426e105875bd362061c11100000017c9221fd0e10d6e46408ca079ed4d092575c01bab99760279d91a2a09de0e2260131d421582772779cebaa8260c561efa6b8141a4462b4f3944d43a250ccac993500014a41278ad3e79d44f6f92ab03dddf36ca1e02ba5b44e95f3eaf0a593d22b2c0601d8dd3c19ca05b36d4202687231d6610123d95fd6edfeccd2a61560c6dd059e58016a4238f1516a6708a8d75b06893f0201774418532b5dfc1ff1fbec670a19a54201e760ce8e5824fa9a2ae70b1ed7ecfad4c1cd2a6e9de352c29dd4013118147138012b4d55158f064e6936206f357e26afa909ba1fd7e9cdeac62eb4602603df5f6501b98b14cab05247195b3b3be3dd8639bae99a0dd10bed1282ac25b62a134afd7200000000011f8322ef806eb2430dc4a7a41c1b344bea5be946efc7b4349c1c9edb14ff9d39"
)
];
find_checkpoint(height, checkpoints)
}
fn get_main_checkpoint(height: u64) -> Option<(u64, &'static str, &'static str)> {
let checkpoints: Vec<(u64, &str, &str)> = vec![
(600000, "0000001b96cc88ed39865b79c0dbdee999e1252a56513e80f74d4147939bf451",
"01d3b69d0899d3b2a812c23def0c09aa7632cb0ec593299f4d8d6e545c36633f2f0011000001e162ba7da5a70ebaa528daf12cc93a2464385c19535ad18b79a71008746a176f01a5a8ce3bbd869afaecd611b25018ab16b53f5c7a8588846fbe26b5a66bbf7f540000012d365453fb59308f9c9665b294eb17293164c2cadad9e0c53d884e98e518b5410184b46404d973caa91670a844d689ca97f844b977dfe56c67ca1f0b4aaa2ab94200012be72e31d7db1eb1bff8c63308bbb70b8bdf597bcc8cfe9fe0e3cec0445e8d65000001e9dd3cb1e65da85f7e4dcd5479cb45a155a28795a873fa340b25a8b484ccc938019a7b8494c6dac00c1180ec6fd6765edca4f9616bcb5b1c0f8c58943dbfd93c380000011bcc61d2d87e7240c21da5f0f85fdb2d9b1806bf155da92e8f0d4de23932da08"
),
(630000, "0000001efec70b964d24382dff9436138291a0d29f0b2b37b9dc8e58187394f2",
"017e8b229c7f044b36a2f48da5c22955a9946f359818e1ee4f732e667fd0d50e3901c28397689f303da38cdccd740a542448052412e7d754b9ffe1828f7dd189b06211013f0bff67ee94046cfaad7b4562d5b4df8963b8e63445da4c2feaa3cade0f381000000000000115430c28919a755d22d52f03a63f52f89836132c48408b4500701c15cfdf895701f85eb4113a04a0c2ae3000493a09c44dbf6109ab9a72e3a70ba6b5e456a4280801626934e496c6bf071a45a722dfa3e0f7e6fe0e603d3c3e47efeeb1857e09690c0109d3c48b603a268505a5feab0db03af45ec59004ab1a221f1c92de65386a7d270001a86112ac94164cfa2f7a8bc8c70aa90c0c2f4bfad1c830ba3b30a17828b0f60e000000012bba14d7832c159b59f38f986d3ecd69cf86440efa04f8946c64cbdb5d269e70011bcc61d2d87e7240c21da5f0f85fdb2d9b1806bf155da92e8f0d4de23932da08"
),
(640000, "000000739c049682cd007c3948463a549826aa3e6ef1b37b4612e393300454c5",
"019db835c0b09f5c8a33fac7d1c24c209885c18f09f182a168ba213b4a32dfb458001101cdd1735b6bef1f93d202c68bd9dc682bb207c4dca665388a8f743c81adb65f2101696d7a939a178edf4abd3dbd818638137a9408d6dd9701a5d42384e2e840634a0001760fcea9bc08cd0208041243d2b002d745dd833f5ca00b8897493c028f544c0201da1db81f7edd08d84bfce89a7559886f7f75422a5f24ae291c43a7fd460d3f51000186b7536a6ce92e657314918b63ec248104c42ba89efdd6d3704089256f956461016d2b5023b453912969bdd54147c423bda1bb86fedd0f652d7c8372f115d8bc6d01812771731f4544301f63813eb327aeada5b85ad08758186262be6d3bb45bc6230001cf76112e4d7da1d2da4cf9d5d2196886689713c84d3c7ffd07533f7854fb31090000012f478cbd674cdd5b04b4e48edbeff3bee25062e113257a0c41d6ffd973a00e5a00012bba14d7832c159b59f38f986d3ecd69cf86440efa04f8946c64cbdb5d269e70011bcc61d2d87e7240c21da5f0f85fdb2d9b1806bf155da92e8f0d4de23932da08"
),
(660000, "0000003286e3442869e5642f4cea39d87a5d4f32884a3195bafe2742a4be98cf",
"0169873338d1915d522b88e8281f3a64e9f48701c612caa8c411e3ebfe5bff083b001100018f9ee18e20c4428767cc11c28959e5220eb121d8c464f34b6c9ac05658aa972701d5997e34da81e6825e11d577cd04e9d89b0bd57f91be9dc7f891420301360c2d0149ab15a8cf93122c5e7b1da9682db800df3325985cae7d5d45afc320b3ce0045000195b300d85aa5630caabe4cb20b270d119a22e4eba44447c1582cbc46896d2621016eb38ec2f1e6df9749f4982d4137bc9c3380481d89ce62bc06a3b427eca98c31000001bacb01d531165f74a6e8cf1b76f6cac2ad41850600a8b9e172ef7b49f40624330000019f3b513e80a5b8936b8f991776ae2a9846672e7063efb57dec38a7af7afa3a720001becfb5861740e4d88e7a2adaba26125573d022adab2a2f8c457fc89f4d6c7a29012bba14d7832c159b59f38f986d3ecd69cf86440efa04f8946c64cbdb5d269e70011bcc61d2d87e7240c21da5f0f85fdb2d9b1806bf155da92e8f0d4de23932da08"
),
(700000, "000001af200fda6d5778b8cdaf16e20c3e14da185e650efc9957b4bd73febbbc",
"0171b8ca66940c6287c5fe5673f5cbf88956f38246d736b0ed206e55644f153c5000120000000000011cfcd5b1c30cfa8868711c07cb77d2dc965716bed4ec55b52399108ff991b8430001c2b1d5fe1c648213f1aa816299990cf7f778186eb27941ef0c925d2a88cc912f01f28c52d13ef0be90f00dad5dadd597a627b70dcbbb20b4befa206e2210a4425a00000000016271aa76ac4f7f0548240b1b986c74b4c9350a2e12f46a5f9fba4b506a22834c000000018eb53ce1887c107647dd26dcbccb81844744a0f42a9f262d5f2cc6253a27ef6c"
),
(740000, "0000009c8788f2cc05c491885d04ba7f69a767e1483cdac39a90d40b9217f44e",
"0181ab8ffc3eddcab5f30ff537658e5821b953004a6212ad276a466c6ba80e9112013c03721457c3d9fd6aebcc55d3664f577334b30d4042324959c715cb839d8949120001a9ec4ba32f6e5f089a2387e35449feae02596de4adc983aaba07b8a8afb1302d016265f2f33c9779d49f5413929e17cc5f6dbc3fc2d459cc073864671d7cd3cd3c01bf0ebff0f85e9202e5348391ea9bdc99eaf50f986b1e85d0fae5a6f9d8b2c42e0189a3781fcb1af5e09d6c62f68890fd0a18950ab5c5143e8184c3a7de1f8524220001532ae473cce9c10118078868098cf0e360478cfc893cb408a61b43e694bf851501f57e9ef590a1ce440575a79bb5b33c1aeac155994fffb0b4d1286d2400144e6601a539a6658e4e190abdebbe7a1488a2922f0cf1c699ace0cce192683586a2fe37000000000144ae242cf457a8dc1c783875b0028007fd1aa28187e6f254e1b6fe8b6b66432a016e887902f0da198f0978df6a2532046166bee9e57713216166b34b75f2b1e1690000018eb53ce1887c107647dd26dcbccb81844744a0f42a9f262d5f2cc6253a27ef6c"
),
(760000, "000000c90235ab52ff3191425ada972c253b67c6b35a71d882cfebea7bcc5bb0",
"01fcdd15fa0b734bada99b72eb7d98abb4cd7f87c355f880f604ccb8f3b864802b012ce5ca9d3b1fad6f486007ba763c2e3bd1fca762b3c181cd4f59e9888f277455120001dfa906630526d66678fe47e57f3ec711d66f1e09382f2bb07ce3f00d8c62af6e01d6365b636eb227d0b8a2de7de12534d89231dfac709bcf1171e4f19d6d989a38016e0cff2a95d369853c2999a5cb2c9808933057fbb486007e069bbdc395261b4600000000000000000000000198704029f024f7b2eebf8227f4b2373a114fb2f6b940e187fa82092451ac777100018eb53ce1887c107647dd26dcbccb81844744a0f42a9f262d5f2cc6253a27ef6c"
),
];
find_checkpoint(height, checkpoints)
}
fn find_checkpoint(height: u64, chkpts: Vec<(u64, &'static str, &'static str)>) -> Option<(u64, &'static str, &'static str)> {
// Find the closest checkpoint
let mut heights = chkpts.iter().map(|(h, _, _)| *h as u64).collect::<Vec<_>>();
heights.sort();
match get_first_lower_than(height, heights) {
Some(closest_height) => {
chkpts.iter().find(|(h, _, _)| *h == closest_height).map(|t| *t)
},
None => None
}
}
fn get_first_lower_than(height: u64, heights: Vec<u64>) -> Option<u64> {
// If it's before the first checkpoint, return None.
if heights.len() == 0 || height < heights[0] {
return None;
}
for (i, h) in heights.iter().enumerate() {
if height < *h {
return Some(heights[i-1]);
}
}
return Some(*heights.last().unwrap());
}
#[cfg(test)]
pub mod tests {
use super::*;
#[test]
fn test_lower_than() {
assert_eq!(get_first_lower_than( 9, vec![10, 30, 40]), None);
assert_eq!(get_first_lower_than(10, vec![10, 30, 40]).unwrap(), 10);
assert_eq!(get_first_lower_than(11, vec![10, 30, 40]).unwrap(), 10);
assert_eq!(get_first_lower_than(29, vec![10, 30, 40]).unwrap(), 10);
assert_eq!(get_first_lower_than(30, vec![10, 30, 40]).unwrap(), 30);
assert_eq!(get_first_lower_than(40, vec![10, 30, 40]).unwrap(), 40);
assert_eq!(get_first_lower_than(41, vec![10, 30, 40]).unwrap(), 40);
assert_eq!(get_first_lower_than(99, vec![10, 30, 40]).unwrap(), 40);
}
#[test]
fn test_checkpoints() {
assert_eq!(get_test_checkpoint(300000), None);
assert_eq!(get_test_checkpoint(500000).unwrap().0, 350000);
assert_eq!(get_test_checkpoint(525000).unwrap().0, 350000);
assert_eq!(get_test_checkpoint(550000).unwrap().0, 550000);
assert_eq!(get_test_checkpoint(655000).unwrap().0, 550000);
assert_eq!(get_main_checkpoint(500000), None);
assert_eq!(get_main_checkpoint(600000).unwrap().0, 600000);
assert_eq!(get_main_checkpoint(625000).unwrap().0, 600000);
assert_eq!(get_main_checkpoint(630000).unwrap().0, 630000);
assert_eq!(get_main_checkpoint(635000).unwrap().0, 630000);
}
} |
use bytes::Bytes;
use std::error::Error;
use zmq_rs::ZmqMessage;
use zmq_rs::{Socket, SocketType};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut socket = zmq_rs::ReqSocket::connect("127.0.0.1:5555")
.await
.expect("Failed to connect");
let hello = Vec::from("Hello");
socket.send(hello).await?;
let data = socket.recv().await?;
let repl = String::from_utf8(data)?;
dbg!(repl);
let hello = Vec::from("NewHello");
socket.send(hello).await?;
let data = socket.recv().await?;
let repl = String::from_utf8(data)?;
dbg!(repl);
Ok(())
}
|
use crate::cursor::HasCursor;
use crate::database::Database;
use crate::row::HasRow;
use crate::sqlite::error::SqliteError;
use crate::sqlite::{
SqliteArgumentValue, SqliteArguments, SqliteConnection, SqliteCursor, SqliteRow,
SqliteTypeInfo, SqliteValue,
};
use crate::value::HasRawValue;
/// **Sqlite** database driver.
#[derive(Debug)]
pub struct Sqlite;
impl Database for Sqlite {
type Connection = SqliteConnection;
type Arguments = SqliteArguments;
type TypeInfo = SqliteTypeInfo;
type TableId = String;
type RawBuffer = Vec<SqliteArgumentValue>;
type Error = SqliteError;
}
impl<'c> HasRow<'c> for Sqlite {
type Database = Sqlite;
type Row = SqliteRow<'c>;
}
impl<'c, 'q> HasCursor<'c, 'q> for Sqlite {
type Database = Sqlite;
type Cursor = SqliteCursor<'c, 'q>;
}
impl<'c> HasRawValue<'c> for Sqlite {
type Database = Sqlite;
type RawValue = SqliteValue<'c>;
}
|
#[doc = "Reader of register APB1ENR2"]
pub type R = crate::R<u32, super::APB1ENR2>;
#[doc = "Writer for register APB1ENR2"]
pub type W = crate::W<u32, super::APB1ENR2>;
#[doc = "Register APB1ENR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::APB1ENR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LPUART1EN`"]
pub type LPUART1EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPUART1EN`"]
pub struct LPUART1EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPUART1EN_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 `I2C4EN`"]
pub type I2C4EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `I2C4EN`"]
pub struct I2C4EN_W<'a> {
w: &'a mut W,
}
impl<'a> I2C4EN_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 `LPTIM2EN`"]
pub type LPTIM2EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPTIM2EN`"]
pub struct LPTIM2EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM2EN_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 `LPTIM3EN`"]
pub type LPTIM3EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPTIM3EN`"]
pub struct LPTIM3EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM3EN_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 `FDCAN1EN`"]
pub type FDCAN1EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FDCAN1EN`"]
pub struct FDCAN1EN_W<'a> {
w: &'a mut W,
}
impl<'a> FDCAN1EN_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 `USBFSEN`"]
pub type USBFSEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `USBFSEN`"]
pub struct USBFSEN_W<'a> {
w: &'a mut W,
}
impl<'a> USBFSEN_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 `UCPD1EN`"]
pub type UCPD1EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `UCPD1EN`"]
pub struct UCPD1EN_W<'a> {
w: &'a mut W,
}
impl<'a> UCPD1EN_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
}
}
impl R {
#[doc = "Bit 0 - Low power UART 1 clock enable"]
#[inline(always)]
pub fn lpuart1en(&self) -> LPUART1EN_R {
LPUART1EN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - I2C4 clock enable"]
#[inline(always)]
pub fn i2c4en(&self) -> I2C4EN_R {
I2C4EN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 5 - LPTIM2EN"]
#[inline(always)]
pub fn lptim2en(&self) -> LPTIM2EN_R {
LPTIM2EN_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - LPTIM3EN"]
#[inline(always)]
pub fn lptim3en(&self) -> LPTIM3EN_R {
LPTIM3EN_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 9 - FDCAN1EN"]
#[inline(always)]
pub fn fdcan1en(&self) -> FDCAN1EN_R {
FDCAN1EN_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 21 - USBFSEN"]
#[inline(always)]
pub fn usbfsen(&self) -> USBFSEN_R {
USBFSEN_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 23 - UCPD1EN"]
#[inline(always)]
pub fn ucpd1en(&self) -> UCPD1EN_R {
UCPD1EN_R::new(((self.bits >> 23) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Low power UART 1 clock enable"]
#[inline(always)]
pub fn lpuart1en(&mut self) -> LPUART1EN_W {
LPUART1EN_W { w: self }
}
#[doc = "Bit 1 - I2C4 clock enable"]
#[inline(always)]
pub fn i2c4en(&mut self) -> I2C4EN_W {
I2C4EN_W { w: self }
}
#[doc = "Bit 5 - LPTIM2EN"]
#[inline(always)]
pub fn lptim2en(&mut self) -> LPTIM2EN_W {
LPTIM2EN_W { w: self }
}
#[doc = "Bit 6 - LPTIM3EN"]
#[inline(always)]
pub fn lptim3en(&mut self) -> LPTIM3EN_W {
LPTIM3EN_W { w: self }
}
#[doc = "Bit 9 - FDCAN1EN"]
#[inline(always)]
pub fn fdcan1en(&mut self) -> FDCAN1EN_W {
FDCAN1EN_W { w: self }
}
#[doc = "Bit 21 - USBFSEN"]
#[inline(always)]
pub fn usbfsen(&mut self) -> USBFSEN_W {
USBFSEN_W { w: self }
}
#[doc = "Bit 23 - UCPD1EN"]
#[inline(always)]
pub fn ucpd1en(&mut self) -> UCPD1EN_W {
UCPD1EN_W { w: self }
}
}
|
use super::access_flags::AccessFlags;
use super::attribute::AttributeInfo;
use super::common_type::*;
#[derive(Clone, Debug)]
pub struct MethodInfo {
pub access_flags: AccessFlags,
pub name_index: u2,
pub descriptor_index: u2,
pub attributes_count: u2,
pub attributes: Vec<AttributeInfo>,
}
|
use libusb::InterfaceDescriptor;
pub(super) struct Protocol {
pub(super) class: u8,
pub(super) subclass: u8,
pub(super) protocol: u8,
}
impl Protocol {
pub(super) fn supports(&self, descriptor: &InterfaceDescriptor) -> bool {
self.class == descriptor.class_code()
&& self.subclass == descriptor.sub_class_code()
&& self.protocol == descriptor.protocol_code()
}
}
|
pub mod grid;
pub mod nom;
use std::fs;
pub fn get_data_from_file(name: &str) -> Option<String> {
let path = format!("data/{}.txt", name);
match fs::read_to_string(path) {
Ok(s) => Some(s),
Err(e) => {
println!("Error reading data: {}", e);
None
}
}
}
pub fn get_data_from_file_res(name: &str) -> std::io::Result<String> {
let path = format!("data/{}.txt", name);
fs::read_to_string(path)
}
pub fn lines_to_longs(contents: &str) -> Vec<i64> {
let mut ints = Vec::new();
for s in contents.split_ascii_whitespace() {
ints.push(s.parse::<i64>().unwrap());
}
ints
}
pub fn ints_to_longs(ints: &[i32]) -> Vec<i64> {
let longs: Vec<i64>;
longs = ints.iter().map(|&x| x as i64).collect();
longs
}
pub fn csv_string_to_ints(contents: &str) -> Vec<i32> {
let mut ints = Vec::new();
for s in contents.split(',') {
ints.push(s.trim().parse::<i32>().unwrap());
}
ints
}
|
use std::ffi::CStr;
use std::fmt;
use std::net::{Ipv4Addr, SocketAddrV4};
use crate::Error;
use enet_sys::ENetAddress;
/// An IPv4 address that can be used with the ENet API.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Address {
addr: SocketAddrV4,
}
impl Address {
/// Create a new address from an ip and a port.
pub fn new(addr: Ipv4Addr, port: u16) -> Address {
Address {
addr: SocketAddrV4::new(addr, port),
}
}
/// Create a new address from a given hostname.
pub fn from_hostname(hostname: &CStr, port: u16) -> Result<Address, Error> {
use enet_sys::enet_address_set_host;
let mut addr = ENetAddress { host: 0, port };
let res =
unsafe { enet_address_set_host(&mut addr as *mut ENetAddress, hostname.as_ptr()) };
if res != 0 {
return Err(Error(res));
}
Ok(Address::new(
// use native byte order here, Enet already guarantees network byte order, so don't
// change it.
Ipv4Addr::from(addr.host.to_ne_bytes()),
addr.port,
))
}
/// Return the ip of this address
pub fn ip(&self) -> &Ipv4Addr {
self.addr.ip()
}
/// Returns the port of this address
pub fn port(&self) -> u16 {
self.addr.port()
}
pub(crate) fn to_enet_address(&self) -> ENetAddress {
ENetAddress {
// Use native byte order here, the octets are already arranged in the correct byte
// order, don't change it
host: u32::from_ne_bytes(self.ip().octets()),
port: self.port(),
}
}
pub(crate) fn from_enet_address(addr: &ENetAddress) -> Address {
// Split using native byte order here, as Enet guarantees that our bytes are already layed
// out in network byte order.
Address::new(Ipv4Addr::from(addr.host.to_ne_bytes()), addr.port)
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.ip(), self.port())
}
}
impl From<SocketAddrV4> for Address {
fn from(addr: SocketAddrV4) -> Address {
Address { addr }
}
}
#[cfg(test)]
mod tests {
use super::Address;
use std::ffi::CString;
use std::net::Ipv4Addr;
#[test]
fn test_from_valid_hostname() {
let addr = Address::from_hostname(&CString::new("localhost").unwrap(), 0).unwrap();
assert_eq!(addr.addr.ip(), &Ipv4Addr::new(127, 0, 0, 1));
assert_eq!(addr.addr.port(), 0);
}
#[test]
fn test_from_invalid_hostname() {
assert!(Address::from_hostname(&CString::new("").unwrap(), 0).is_err());
}
}
|
use std::fmt::{Display, Formatter, Error};
use std::ops::{Add, AddAssign};
use std::cmp::Ordering;
/// 得点
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Score {
Mangan {
han: Han,
},
Haneman {
han: Han,
},
Baiman {
han: Han,
},
Sanbaiman {
han: Han,
},
Yakuman,
KazoeYakuman {
han: Han,
},
MultipleYakuman {
multiple: u8,
},
Other {
han: Han,
fu: Fu,
},
}
impl Score {
pub fn new(han: Han, fu: Fu) -> Self {
let Han(han_value) = han;
if han_value >= 13 as u32 {
Score::KazoeYakuman { han }
} else if (11..13).contains(&han_value) {
Score::Sanbaiman { han }
} else if (8..11).contains(&han_value) {
Score::Baiman { han }
} else if (6..8).contains(&han_value) {
Score::Haneman { han }
} else if (4..6).contains(&han_value) {
Score::Mangan { han }
} else {
Score::Other { han, fu }
}
}
pub fn yakuman(multiple: u8) -> Self {
if multiple == 1 {
Score::Yakuman
} else {
Score::MultipleYakuman { multiple }
}
}
pub fn jp_name(&self) -> String {
match &self {
Score::Other { .. } => { String::new() }
Score::Mangan { .. } => { "満貫".to_string() }
Score::Haneman { .. } => { "跳満".to_string() }
Score::Baiman { .. } => { "倍満".to_string() }
Score::Sanbaiman { .. } => { "三倍満".to_string() }
Score::Yakuman => { "役満".to_string() }
Score::KazoeYakuman { .. } => { "数え役満".to_string() }
Score::MultipleYakuman { multiple } => {
if multiple > &(3 as u8) {
"マルチ役満".to_string()
} else if multiple == &3 {
"トリプル役満".to_string()
} else if multiple == &2 {
"ダブル役満".to_string()
} else {
"役満".to_string()
}
}
}
}
pub fn en_name(&self) -> String {
match &self {
Score::Other { .. } => { String::new() }
Score::Mangan { .. } => { "Mangan".to_string() }
Score::Haneman { .. } => { "Haneman".to_string() }
Score::Baiman { .. } => { "Baiman".to_string() }
Score::Sanbaiman { .. } => { "Sanbaiman".to_string() }
Score::Yakuman => { "Yakuman".to_string() }
Score::KazoeYakuman { .. } => { "Kazoe Yakuman".to_string() }
Score::MultipleYakuman { multiple } => {
if multiple > &(3 as u8) {
"Multiple Yakuman".to_string()
} else if multiple == &3 {
"Triple Yakuman".to_string()
} else if multiple == &2 {
"Double Yakuman".to_string()
} else {
"Yakuman".to_string()
}
}
}
}
pub fn score(&self, is_dealer: bool) -> u32 {
match &self {
Score::Mangan { .. } => {
if is_dealer {
12000
} else { 8000 }
}
Score::Haneman { .. } => {
if is_dealer {
18000
} else { 12000 }
}
Score::Baiman { .. } => {
if is_dealer {
24000
} else { 16000 }
}
Score::Sanbaiman { .. } => {
if is_dealer {
36000
} else { 24000 }
}
Score::KazoeYakuman { .. } | Score::Yakuman => {
if is_dealer {
48000
} else { 36000 }
}
Score::MultipleYakuman { multiple } => {
let score =
if is_dealer {
48000
} else { 36000 }
* multiple.clone() as u32;
score
}
Score::Other { han, fu } => {
let Fu(fu) = fu;
let fu = ((fu + (10 - 1)) / 10) * 10;
let Han(han) = han;
let score =
if is_dealer { 6 as u32 } else { 4 as u32 }
* fu * u32::pow(2, han.clone() + 2);
score
}
}
}
}
impl PartialOrd for Score {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self == other {
Some(Ordering::Equal)
} else {
self.score(false).partial_cmp(&other.score(false))
}
}
}
impl Display for Score {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let score = self.score(false);
let score_dealer = self.score(true);
match &self {
Score::Other { han, fu } => {
let score_display = ((score + (100 - 1)) / 100) * 100;
let score_draw_dealer = ((score / 2 + (100 - 1)) / 100) * 100;
let score_draw = ((score / 4 + (100 - 1)) / 100) * 100;
let score_dealer_display = ((score_dealer + (100 - 1)) / 100) * 100;
let score_dealer_draw = ((score_dealer / 3 + (100 - 1)) / 100) * 100;
writeln!(f, "{}{}", fu, han)?;
writeln!(f, "Non-Dealer: {} / {} - {}", score_display, score_draw, score_draw_dealer)?;
writeln!(f, "Dealer: {} / {} ALL", score_dealer_display, score_dealer_draw)
}
_ => {
writeln!(f, "{} / {}", &self.jp_name(), &self.en_name())?;
writeln!(f, "Non-Dealer: {} / {} - {}", score, score / 4, score / 2)?;
writeln!(f, "Dealer: {} / {} ALL", score_dealer, score_dealer / 3)
}
}
}
}
/// 翻
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Han(pub u32);
impl Display for Han {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let Han(han) = &self;
write!(f, "{}翻", han)
}
}
impl Add for Han {
type Output = Han;
fn add(self, rhs: Self) -> Self::Output {
let (Han(origin), Han(rhs)) = (self, rhs);
Han(origin + rhs)
}
}
impl AddAssign for Han {
fn add_assign(&mut self, rhs: Self) {
let (Han(origin), Han(rhs)) = (self, rhs);
*origin += rhs;
}
}
/// 符
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Fu(pub u32);
impl Display for Fu {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let Fu(fu) = &self;
write!(f, "{}符", fu)
}
}
impl Add for Fu {
type Output = Fu;
fn add(self, rhs: Self) -> Self::Output {
let (Fu(origin), Fu(rhs)) = (self, rhs);
Fu(origin + rhs)
}
}
impl AddAssign for Fu {
fn add_assign(&mut self, rhs: Self) {
let (Fu(origin), Fu(rhs)) = (self, rhs);
*origin += rhs;
}
} |
#[cfg(test)]
mod tests;
pub mod evaluate;
use theme::Keyword;
use rand::{Rng, SeedableRng, StdRng};
use range::Range;
use monster::*;
use super::*;
use std::f32;
pub use dungeon::generator::evaluate::*;
// temp
use display::Display;
pub struct Generator<'a> {
monster_pool: &'a [Monster],
template_monster_pool: &'a [TemplateMonster],
theme_keyword_pool: &'a [Keyword],
dungeon_keyword_count: usize,
arch_keyword_count: usize,
area_keyword_count: usize,
/// Archs define the style of the dungeon.
arch_count: usize,
/// no. of areas in an arch. Areas define thematic closures.
num_areas_in_arch: Range,
/// no. of rooms in an area. Rooms are for encounters with monsters, treasures and altars.
num_main_rooms_in_area: Range,
force_first_room_empty: bool,
}
// TOOD: reimplement with lifetime subtyping so that no copies of Keywords have
// to be made
impl<'a> Generator<'a> {
pub fn new(
monster_pool: &'a [Monster],
template_monster_pool: &'a [TemplateMonster],
theme_keyword_pool: &'a [Keyword],
dungeon_keyword_count: usize,
arch_keyword_count: usize,
area_keyword_count: usize,
arch_count: usize,
num_areas_in_arch: Range,
num_main_rooms_in_area: Range,
force_first_room_empty: bool,
) -> Generator<'a> {
Generator {
monster_pool: monster_pool,
template_monster_pool: template_monster_pool,
theme_keyword_pool: theme_keyword_pool,
dungeon_keyword_count: dungeon_keyword_count,
arch_keyword_count: arch_keyword_count,
area_keyword_count: area_keyword_count,
arch_count: arch_count,
num_areas_in_arch: num_areas_in_arch,
num_main_rooms_in_area: num_main_rooms_in_area,
force_first_room_empty,
}
}
pub fn generate(&'a self, seed: &'a [usize]) -> Dungeon {
// Rename binding for conciseness
let g = self;
// Initialize RNG with seed
let mut rng: StdRng = SeedableRng::from_seed(seed);
// Select keywords for the whole dungeon dungeon
let dungeon_keywords = rng.choose_many(g.dungeon_keyword_count, g.theme_keyword_pool);
// Split the map into arches
let arches = g.generate_arches(dungeon_keywords.as_slice(), &mut rng);
// Construct the final dungeon from the intermediaries
let mut rooms = vec![];
for arch in &arches {
for area in &arch.areas {
let rooms_in_area: Vec<Room> = area.rooms.iter().map(|room| room.clone()).collect();
rooms.extend(rooms_in_area);
}
}
if self.force_first_room_empty {
rooms[0].monster = None;
}
let mut dungeon = Dungeon::new(rooms);
// Generate paths
for i in 0..dungeon.rooms.len() - 1 {
dungeon.create_passage(i, CompassPoint::East, i + 1);
}
dungeon
}
fn generate_arches<'b>(
&'a self,
keyword_pool: &'b [Keyword],
mut rng: &'b mut StdRng,
) -> Vec<Arch> {
let g = self;
let mut arches = Vec::with_capacity(g.arch_count);
for arch_idx in 0..g.arch_count {
let difficulty_min = arch_idx as f32 / g.arch_count as f32;
let difficulty_max = (arch_idx + 1) as f32 / g.arch_count as f32;
let arch_keywords = rng.choose_many(g.arch_keyword_count, keyword_pool);
// Create the arch and areas
let r = g.num_areas_in_arch;
let num_areas_in_arch = rng.gen_range(r.offset, r.offset + r.length);
let arch = Arch::new(g.generate_areas(
num_areas_in_arch,
difficulty_min,
difficulty_max,
arch_keywords.as_slice(),
&mut rng,
));
arches.push(arch)
}
arches
}
fn generate_areas<'b>(
&'a self,
count: usize,
difficulty_min: f32,
difficulty_max: f32,
keyword_pool: &'b [Keyword],
mut rng: &'b mut StdRng,
) -> Vec<Area> {
let g = self;
let mut areas = Vec::with_capacity(count);
for area_idx in 0..count {
let area_difficulty_min = difficulty_min +
(difficulty_max - difficulty_min) * (area_idx as f32 / count as f32);
let area_difficulty_max = difficulty_min +
(difficulty_max - difficulty_min) * ((area_idx as f32 + 1.) / count as f32);
let area_keywords = rng.choose_many(g.area_keyword_count, keyword_pool);
// Create the area and rooms
let r = g.num_main_rooms_in_area;
let num_main_rooms_in_area = rng.gen_range(r.offset, r.offset + r.length);
let area = Area::new(g.generate_rooms(
num_main_rooms_in_area,
area_difficulty_min,
area_difficulty_max,
area_keywords.as_slice(),
&mut rng,
));
areas.push(area);
}
areas
}
fn generate_rooms<'b>(
&'a self,
count: usize,
area_difficulty_min: f32,
area_difficulty_max: f32,
keyword_pool: &'b [Keyword],
rng: &'b mut StdRng,
) -> Vec<Room> {
let mut rooms = Vec::with_capacity(count);
for room_idx in 0..count {
let room_difficulty = area_difficulty_min +
(area_difficulty_max - area_difficulty_min) *
((room_idx as f32 + 1.) / count as f32);
let keyword = rng.choose(keyword_pool).unwrap();
// Create the area and rooms
rooms.push(self.generate_room(
vec![keyword].as_slice(),
room_difficulty,
rng,
));
}
rooms
}
fn generate_room(&self, keywords: &[&Keyword], difficulty: f32, rng: &mut StdRng) -> Room {
Room::new(
keywords[0],
Some(self.generate_monster(difficulty, keywords, rng)),
)
}
fn generate_monster(
&self,
ambient_difficulty: f32,
ambient_theme: &[&Keyword],
rng: &mut StdRng,
) -> Monster {
let by_fitness: Vec<(f32, &Monster)> =
rank_by_fitness(self.monster_pool, ambient_difficulty, ambient_theme);
eprintln!(
"d: {:.*}, th: {} -> {:?}",
2,
ambient_difficulty,
ambient_theme.first().unwrap().id,
by_fitness
.iter()
.map(|&(f, ref m)| (f, m.name()))
.collect::<Vec<(f32, String)>>()
);
let total_fitness: f32 = by_fitness.iter().map(|&(f, _)| f).sum();
// Return what is chosen by fitness
if total_fitness > 0.01 {
return rng.choose_weighted(&by_fitness, total_fitness);
}
let by_difficulty: Vec<(f32, &Monster)> =
rank_by_difficulty(self.monster_pool, ambient_difficulty);
let total_fitness: f32 = by_difficulty.iter().map(|&(f, _)| f).sum();
// Return what is chosen by difficulty
if total_fitness > 0.01 {
return rng.choose_weighted(&by_difficulty, total_fitness);
}
// Return by random
return rng.choose(&by_difficulty).unwrap().1.clone();
}
}
struct Arch {
areas: Vec<Area>,
}
struct Area {
rooms: Vec<Room>,
}
impl Arch {
fn new(areas: Vec<Area>) -> Arch {
Arch { areas: areas }
}
}
impl Area {
fn new(rooms: Vec<Room>) -> Area {
Area { rooms: rooms }
}
}
trait DungeonRng<'a> {
fn choose_many<'f, T, K: AsRef<T>>(&'a mut self, count: usize, pool: &'f [K]) -> Vec<T>
where
T: Clone;
fn choose_weighted<T, K: AsRef<T>>(&mut self, pool: &[(f32, K)], total_weight: f32) -> T
where
T: Clone;
}
impl<'a> DungeonRng<'a> for StdRng {
fn choose_many<'f, T, K: AsRef<T>>(&'a mut self, count: usize, pool: &'f [K]) -> Vec<T>
where
T: Clone,
{
let ref_pool: Vec<&T> = pool.iter().map(|x| x.as_ref()).collect();
let mut ret = vec![];
for _ in 0..count {
let r: &T = *self.choose(ref_pool.as_slice()).unwrap();
ret.push(r.clone())
}
ret
}
fn choose_weighted<T, K: AsRef<T>>(&mut self, pool: &[(f32, K)], total_weight: f32) -> T
where
T: Clone,
{
let pick = self.next_f32() * total_weight;
let mut accumulator = 0.;
for &(ref chance, ref item) in pool {
accumulator += *chance;
if pick < accumulator {
return item.as_ref().clone();
}
}
return self.choose(pool).unwrap().1.as_ref().clone();
}
}
|
#![no_std]
#![no_main]
#![feature(lang_items)]
#![feature(globs)]
#![feature(asm)]
#![feature(macro_rules)]
#![feature(phase)]
#[phase(link,plugin)]
extern crate core;
use core::prelude::*;
use chip::interrupts;
use chip::gpio;
#[path="src/lpc1343/mod.rs"]
mod chip;
#[lang = "fail_fmt"]
fn fail_impl() -> ! {
loop {}
}
#[lang = "stack_exhausted" ] fn stack_exhausted() {}
#[lang = "eh_personality" ] fn eh_personality() {}
const LED0: gpio::Pin = gpio::PIN3_0;
const LED1: gpio::Pin = gpio::PIN3_1;
const LED2: gpio::Pin = gpio::PIN3_2;
const LED3: gpio::Pin = gpio::PIN3_3;
const LED4: gpio::Pin = gpio::PIN2_4;
const LED5: gpio::Pin = gpio::PIN2_5;
const LED6: gpio::Pin = gpio::PIN2_6;
const LED7: gpio::Pin = gpio::PIN2_7;
#[no_mangle]
pub extern "C" fn main() -> ! {
interrupts::disable();
gpio::port_direction(3, 0x0F);
gpio::port_direction(2, 0xF0);
let leds = [LED0, LED1, LED2, LED3,
LED4, LED5, LED6, LED7];
interrupts::enable();
loop {
for i in leds.iter() {
i.high();
}
for _ in range(0, 100000u) {
chip::noop();
}
for i in leds.iter() {
i.low();
}
for _ in range(0, 100000u) {
chip::noop();
}
}
}
|
use crate::scene::texture::{Texture, TextureError};
use image::DynamicImage;
use std::collections::HashMap;
use std::path::Path;
use std::pin::Pin;
pub struct TextureAtlasBuilder {
atlas: HashMap<String, Texture>,
}
impl TextureAtlasBuilder {
pub fn new() -> Self {
Self {
atlas: HashMap::new(),
}
}
pub fn add_texture_file(
&mut self,
filename: impl AsRef<Path>,
basepath: impl AsRef<Path>,
) -> Result<(), TextureError> {
self.add_texture(
filename
.as_ref()
.to_str()
.ok_or(TextureError::FileName)?
.into(),
Texture::new(basepath.as_ref().join(filename))?,
);
Ok(())
}
pub fn add_texture(&mut self, name: String, texture: Texture) {
self.atlas.insert(name, texture);
}
pub fn build<'t>(self) -> TextureAtlas<'t> {
let mut atlas = HashMap::new();
let atlassize = self.atlas.len();
let mut textures = {
let mut vec = Vec::with_capacity(atlassize);
vec.resize_with(atlassize, || Texture {
image: DynamicImage::new_rgb8(0, 0).to_rgb(),
size: (0, 0),
});
Pin::from(vec.into_boxed_slice())
};
let mut names = Vec::with_capacity(atlassize);
for (index, (key, value)) in self.atlas.into_iter().enumerate() {
textures[index] = value;
names.push(key);
}
for (index, name) in names.into_iter().enumerate() {
// Safe because textures is pinned.
let ptr: &'t Texture = unsafe { std::mem::transmute(&textures[index]) };
atlas.insert(name, ptr);
}
TextureAtlas { atlas, textures }
}
}
#[allow(unused)]
pub struct TextureAtlas<'t> {
pub(self) atlas: HashMap<String, &'t Texture>,
pub(self) textures: Pin<Box<[Texture]>>,
}
impl<'t> TextureAtlas<'t> {
pub fn get_texture(&self, name: &str) -> Option<&'t Texture> {
self.atlas.get(name).copied()
}
}
|
#[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::_0_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_0_ISC_INTCNTZEROR {
bits: bool,
}
impl PWM_0_ISC_INTCNTZEROR {
#[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_0_ISC_INTCNTZEROW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_ISC_INTCNTZEROW<'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_0_ISC_INTCNTLOADR {
bits: bool,
}
impl PWM_0_ISC_INTCNTLOADR {
#[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_0_ISC_INTCNTLOADW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_ISC_INTCNTLOADW<'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_0_ISC_INTCMPAUR {
bits: bool,
}
impl PWM_0_ISC_INTCMPAUR {
#[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_0_ISC_INTCMPAUW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_ISC_INTCMPAUW<'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_0_ISC_INTCMPADR {
bits: bool,
}
impl PWM_0_ISC_INTCMPADR {
#[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_0_ISC_INTCMPADW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_ISC_INTCMPADW<'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_0_ISC_INTCMPBUR {
bits: bool,
}
impl PWM_0_ISC_INTCMPBUR {
#[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_0_ISC_INTCMPBUW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_ISC_INTCMPBUW<'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 PWM_0_ISC_INTCMPBDR {
bits: bool,
}
impl PWM_0_ISC_INTCMPBDR {
#[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_0_ISC_INTCMPBDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_ISC_INTCMPBDW<'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
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Counter=0 Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcntzero(&self) -> PWM_0_ISC_INTCNTZEROR {
let bits = ((self.bits >> 0) & 1) != 0;
PWM_0_ISC_INTCNTZEROR { bits }
}
#[doc = "Bit 1 - Counter=Load Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcntload(&self) -> PWM_0_ISC_INTCNTLOADR {
let bits = ((self.bits >> 1) & 1) != 0;
PWM_0_ISC_INTCNTLOADR { bits }
}
#[doc = "Bit 2 - Comparator A Up Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpau(&self) -> PWM_0_ISC_INTCMPAUR {
let bits = ((self.bits >> 2) & 1) != 0;
PWM_0_ISC_INTCMPAUR { bits }
}
#[doc = "Bit 3 - Comparator A Down Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpad(&self) -> PWM_0_ISC_INTCMPADR {
let bits = ((self.bits >> 3) & 1) != 0;
PWM_0_ISC_INTCMPADR { bits }
}
#[doc = "Bit 4 - Comparator B Up Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpbu(&self) -> PWM_0_ISC_INTCMPBUR {
let bits = ((self.bits >> 4) & 1) != 0;
PWM_0_ISC_INTCMPBUR { bits }
}
#[doc = "Bit 5 - Comparator B Down Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpbd(&self) -> PWM_0_ISC_INTCMPBDR {
let bits = ((self.bits >> 5) & 1) != 0;
PWM_0_ISC_INTCMPBDR { 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 - Counter=0 Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcntzero(&mut self) -> _PWM_0_ISC_INTCNTZEROW {
_PWM_0_ISC_INTCNTZEROW { w: self }
}
#[doc = "Bit 1 - Counter=Load Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcntload(&mut self) -> _PWM_0_ISC_INTCNTLOADW {
_PWM_0_ISC_INTCNTLOADW { w: self }
}
#[doc = "Bit 2 - Comparator A Up Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpau(&mut self) -> _PWM_0_ISC_INTCMPAUW {
_PWM_0_ISC_INTCMPAUW { w: self }
}
#[doc = "Bit 3 - Comparator A Down Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpad(&mut self) -> _PWM_0_ISC_INTCMPADW {
_PWM_0_ISC_INTCMPADW { w: self }
}
#[doc = "Bit 4 - Comparator B Up Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpbu(&mut self) -> _PWM_0_ISC_INTCMPBUW {
_PWM_0_ISC_INTCMPBUW { w: self }
}
#[doc = "Bit 5 - Comparator B Down Interrupt"]
#[inline(always)]
pub fn pwm_0_isc_intcmpbd(&mut self) -> _PWM_0_ISC_INTCMPBDW {
_PWM_0_ISC_INTCMPBDW { w: self }
}
}
|
#[macro_use]
extern crate neon;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate manifest;
extern crate storage;
extern crate parking_lot;
extern crate uuid;
macro_rules! get_id_arg {
($cx:ident [ $idx:expr ] ) => {
{
let parent = $cx.argument::<JsString>($idx)?.value();
match ::uuid::Uuid::parse_str(&parent) {
Ok(id) => id,
Err(e) => {
warn!("tried to parse unparseable node ID {} ({})", parent, e);
return $cx.throw_error(format!("{}", e));
}
}
}
}
}
pub mod container;
pub mod file;
pub mod node;
pub mod stream;
use std::sync::Arc;
use parking_lot::RwLock;
use neon::prelude::*;
use manifest::Manifest;
lazy_static! {
static ref MANIFEST: Arc<RwLock<Option<Manifest>>> = Arc::new(RwLock::new(None));
}
/// Initializes logging.
///
/// # Arguments
/// None.
///
/// # Returns
/// None.
///
/// # Exceptions
/// None.
pub fn initialize_logging(mut cx: FunctionContext) -> JsResult<JsNull> {
env_logger::init();
info!("initialize_logging done");
Ok(cx.null())
}
/// Logs a line.
///
/// # Arguments
/// [payload: object]
///
/// The payload object should have the following keys:
/// message: string - the log line
/// level: string - the log level, one of "Error", "Warn", "Info", "Debug", or "Trace".
/// script: string - the name of the module/script where the log line originated
/// function: string - the name of the function where the log line originated
/// line: string - the line where the log line was fired from
/// isMain: boolean - true if this log originated in the main electron process
pub fn log(mut cx: FunctionContext) -> JsResult<JsNull> {
let args = cx.argument::<JsObject>(0)?;
let message = args.get(&mut cx, "message")?.downcast_or_throw::<JsString, _>(&mut cx)?.value();
let level = {
let level = args.get(&mut cx, "level")?.downcast_or_throw::<JsString, _>(&mut cx)?.value();
match level.as_str() {
"Error" => log::Level::Error,
"Warn" => log::Level::Warn,
"Info" => log::Level::Info,
"Debug" => log::Level::Debug,
"Trace" => log::Level::Trace,
_ => log::Level::Info,
}
};
let script = args.get(&mut cx, "script")?.downcast_or_throw::<JsString, _>(&mut cx)?.value();
let line: u32 = args.get(&mut cx, "line")?.downcast_or_throw::<JsString, _>(&mut cx)?.value().parse().unwrap();
let function = args.get(&mut cx, "function")?.downcast_or_throw::<JsString, _>(&mut cx)?.value();
let is_main = args.get(&mut cx, "isMain")?.downcast_or_throw::<JsBoolean, _>(&mut cx)?.value();
let target = if is_main { "ux_main" } else { "ux_renderer" };
let module_path = format!("{}::{}", target, function);
log::logger().log(&log::Record::builder()
.args(format_args!("{}", message))
.level(level)
.target(target)
.file(Some(script.as_str()))
.line(Some(line))
.module_path(Some(module_path.as_str()))
.build());
Ok(cx.null())
}
register_module!(mut cx, {
cx.export_function("initialize_logging", initialize_logging)?;
cx.export_function("log", log)?;
cx.export_function("create_manifest", file::create_manifest)?;
cx.export_function("save_manifest", file::save_manifest)?;
cx.export_function("load_manifest", file::load_manifest)?;
cx.export_function("close_manifest", file::close_manifest)?;
cx.export_function("get_root_node_id", node::get_root_node_id)?;
cx.export_function("create_node", node::create_node)?;
cx.export_function("find_node_children", node::find_node_children)?;
cx.export_function("get_node_streams", node::get_node_streams)?;
cx.export_function("get_node_parent", node::get_node_parent)?;
cx.export_function("get_node_type", node::get_node_type)?;
cx.export_function("set_node_names", stream::set_node_names)?;
cx.export_function("get_node_names", stream::get_node_names)?;
cx.export_function("add_container", container::add_container)?;
cx.export_function("get_containers", container::get_containers)?;
Ok(())
});
|
use crate::{
math::{Size, Vector2},
widgets::Widget,
};
use super::Controller;
pub struct Click<T> {
callback: Box<dyn Fn(&mut T)>,
}
impl<T> Click<T> {
pub fn new<F: Fn(&mut T) + 'static>(on_click: F) -> Self {
Click {
callback: Box::new(on_click),
}
}
}
#[derive(Debug, Clone)]
pub struct MouseClickEvent {
pub pos: Vector2,
pub mouse_button: MouseButton,
}
#[derive(Debug, Clone)]
pub enum MouseButton {
Left,
Right,
Middle,
Other(usize),
}
impl<T, W: Widget<T>> Controller<T, W> for Click<T> {
type Event = MouseClickEvent;
type Reaction = ();
fn event(
&mut self,
_child: &mut W,
origin: Vector2,
size: Size,
data: &mut T,
event: Self::Event,
) -> Option<Self::Reaction> {
let target = event.pos - origin;
if !size.contains(target) {
return None;
}
match event.mouse_button {
MouseButton::Left => (self.callback)(data),
_ => (),
}
None
}
}
|
/*
* Copyright 2020 Fluence Labs Limited
*
* 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 faas_api::Protocol::{self, *};
use fluence_libp2p::peerid_serializer;
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use trust_graph::{certificate_serde, Certificate};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DelegateProviding {
pub service_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetCertificates {
#[serde(with = "peerid_serializer")]
pub peer_id: PeerId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub msg_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AddCertificates {
#[serde(with = "certificate_serde::vec")]
pub certificates: Vec<Certificate>,
#[serde(with = "peerid_serializer")]
pub peer_id: PeerId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub msg_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Identify {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub msg_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum BuiltinService {
DelegateProviding(DelegateProviding),
GetCertificates(GetCertificates),
AddCertificates(AddCertificates),
Identify(Identify),
}
#[derive(Debug)]
pub enum Error<'a> {
Serde(serde_json::Error),
UnknownService(&'a str),
InvalidProtocol(&'a Protocol),
}
impl<'a> From<serde_json::Error> for Error<'a> {
fn from(err: serde_json::Error) -> Self {
Error::Serde(err)
}
}
impl<'a> Display for Error<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Serde(serderr) => serderr.fmt(f),
Error::UnknownService(s) => write!(f, "unknown builtin service `{}`", s),
Error::InvalidProtocol(p) => {
write!(f, "invalid protocol: expected /service, got `{}`", p)
}
}
}
}
impl BuiltinService {
const PROVIDE: &'static str = "provide";
const CERTS: &'static str = "certificates";
const ADD_CERTS: &'static str = "add_certificates";
const IDENTIFY: &'static str = "identify";
const SERVICES: [&'static str; 4] =
[Self::PROVIDE, Self::CERTS, Self::ADD_CERTS, Self::IDENTIFY];
pub fn from<'a>(target: &'a Protocol, arguments: serde_json::Value) -> Result<Self, Error<'a>> {
// Check it's `/service/ID` and `ID` is one of builtin services
let service_id = match target {
Service(service_id) => service_id,
_ => return Err(Error::InvalidProtocol(target)),
};
let service = match service_id.as_str() {
Self::PROVIDE => BuiltinService::DelegateProviding(serde_json::from_value(arguments)?),
Self::CERTS => BuiltinService::GetCertificates(serde_json::from_value(arguments)?),
Self::ADD_CERTS => BuiltinService::AddCertificates(serde_json::from_value(arguments)?),
Self::IDENTIFY => BuiltinService::Identify(serde_json::from_value(arguments)?),
s => return Err(Error::UnknownService(s)),
};
Ok(service)
}
pub fn is_builtin(service: &Protocol) -> bool {
match service {
Service(service_id) => Self::SERVICES.contains(&service_id.as_str()),
_ => false,
}
}
}
impl Into<(Protocol, serde_json::Value)> for BuiltinService {
fn into(self) -> (Protocol, serde_json::Value) {
use serde_json::json;
let service_id = match self {
BuiltinService::DelegateProviding { .. } => BuiltinService::PROVIDE,
BuiltinService::GetCertificates { .. } => BuiltinService::CERTS,
BuiltinService::AddCertificates { .. } => BuiltinService::ADD_CERTS,
BuiltinService::Identify { .. } => BuiltinService::IDENTIFY,
};
let target = Protocol::Service(service_id.to_string());
let arguments = json!(self);
(target, arguments)
}
}
#[cfg(test)]
pub mod test {
use super::*;
use faas_api::call_test_utils::gen_provide_call;
use faas_api::Protocol;
use fluence_libp2p::RandomPeerId;
use std::str::FromStr;
#[test]
fn serialize_provide() {
let ipfs_service = "IPFS.get_QmFile";
let (target, arguments) = BuiltinService::DelegateProviding(DelegateProviding {
service_id: ipfs_service.into(),
})
.into();
let target = ⌖
let call = gen_provide_call(target.into(), arguments);
let protocols = call.target.as_ref().expect("non empty").protocols();
let service_id = match protocols.as_slice() {
[Protocol::Service(service_id)] => service_id,
wrong => unreachable!("target should be Address::Service, was {:?}", wrong),
};
assert_eq!(service_id, "provide");
match BuiltinService::from(target, call.arguments) {
Ok(BuiltinService::DelegateProviding(DelegateProviding { service_id })) => {
assert_eq!(service_id, ipfs_service)
}
wrong => unreachable!(
"target should be Some(BuiltinService::DelegateProviding, was {:?}",
wrong
),
};
}
fn get_cert() -> Certificate {
Certificate::from_str(
r#"11
1111
GA9VsZa2Cw2RSZWfxWLDXTLnzVssAYPdrkwT1gHaTJEg
QPdFbzpN94d5tzwV4ATJXXzb31zC7JZ9RbZQ1pbgN3TTDnxuVckCmvbzvPaXYj8Mz7yrL66ATbGGyKqNuDyhXTj
18446744073709551615
1589250571718
D7p1FrGz35dd3jR7PiCT12pAZzxV5PFBcX7GdS9Y8JNb
61QT8JYsAWXjnmUcjJcuNnBHWfrn9pijJ4mX64sDX4N7Knet5jr2FzELrJZAAV1JDZQnATYpGf7DVhnitcUTqpPr
1620808171718
1589250571718
4cEQ2DYGdAbvgrAP96rmxMQvxk9MwtqCAWtzRrwJTmLy
xdHh499gCUD7XA7WLXqCR9ZXxQZFweongvN9pa2egVdC19LJR9814pNReP4MBCCctsGbLmddygT6Pbev1w62vDZ
1620808171719
1589250571719"#,
)
.expect("deserialize cert")
}
#[test]
fn serialize_add_certs() {
let certs = vec![get_cert()];
let peer_id = RandomPeerId::random();
let msg_id = uuid::Uuid::new_v4().to_string();
let (target, arguments) = BuiltinService::AddCertificates(AddCertificates {
certificates: certs.clone(),
peer_id: peer_id.clone(),
msg_id: Some(msg_id.clone()),
})
.into();
let call = gen_provide_call(target.into(), arguments);
let _service: AddCertificates =
serde_json::from_value(call.arguments.clone()).expect("deserialize");
let target = call.target.unwrap().pop_front().unwrap();
let service = BuiltinService::from(&target, call.arguments).unwrap();
match service {
BuiltinService::AddCertificates(add) => {
assert_eq!(add.certificates, certs);
assert_eq!(add.peer_id, peer_id);
assert_eq!(add.msg_id, Some(msg_id));
}
_ => unreachable!("expected add certificates"),
}
}
#[test]
fn serialize_add_certs_only() {
let certs = vec![get_cert()];
let peer_id = RandomPeerId::random();
let msg_id = uuid::Uuid::new_v4().to_string();
let add = AddCertificates {
certificates: certs,
peer_id,
msg_id: Some(msg_id),
};
let string = serde_json::to_string(&add).expect("serialize");
let deserialized = serde_json::from_str(&string).expect("deserialize");
assert_eq!(add, deserialized);
}
#[test]
fn serialize_get_certs() {
let peer_id = RandomPeerId::random();
let msg_id = uuid::Uuid::new_v4().to_string();
let (target, arguments) = BuiltinService::GetCertificates(GetCertificates {
peer_id: peer_id.clone(),
msg_id: Some(msg_id.clone()),
})
.into();
let call = gen_provide_call(target.into(), arguments);
let _service: GetCertificates =
serde_json::from_value(call.arguments.clone()).expect("deserialize");
let target = call.target.unwrap().pop_front().unwrap();
let service = BuiltinService::from(&target, call.arguments).unwrap();
match service {
BuiltinService::GetCertificates(add) => {
assert_eq!(add.peer_id, peer_id);
assert_eq!(add.msg_id, Some(msg_id));
}
_ => unreachable!("expected get certificates"),
}
}
#[test]
fn serialize_identify() {
let msg_id = Some(uuid::Uuid::new_v4().to_string());
let (target, arguments) = BuiltinService::Identify(Identify {
msg_id: msg_id.clone(),
})
.into();
let call = gen_provide_call(target.into(), arguments);
let target = call.target.unwrap().pop_front().unwrap();
let service = BuiltinService::from(&target, call.arguments).unwrap();
match service {
BuiltinService::Identify(identify) => assert_eq!(msg_id, identify.msg_id),
_ => unreachable!("expected identify"),
}
}
}
|
//! [](https://github.com/edomora97/ductile/actions?query=workflow%3ARust)
//! [](https://github.com/edomora97/ductile/actions?query=workflow%3AAudit)
//! [](https://crates.io/crates/ductile)
//! [](https://docs.rs/ductile)
//!
//! A channel implementation that allows both local in-memory channels and remote TCP-based channels
//! with the same interface.
//!
//! # Components
//!
//! This crate exposes an interface similar to `std::sync::mpsc` channels. It provides a multiple
//! producers, single consumer channel that can use under the hood local in-memory channels
//! (provided by `crossbeam_channel`) but also network channels via TCP sockets. The remote
//! connection can also be encrypted using ChaCha20.
//!
//! Like `std::sync::mpsc`, there could be more `ChannelSender` but there can be only one
//! `ChannelReceiver`. The two ends of the channel are generic over the message type sent but the
//! type must match (this is checked at compile time only for local channels). If the types do not
//! match errors will be returned and possibly a panic can occur since the channel breaks.
//!
//! The channels also offer a _raw_ mode where the data is not serialized and send as-is,
//! improving drastically the performances for unstructured data. It should be noted that you can
//! mix the two modes in the same channel but you must be careful to always receive with the correct
//! mode (you cannot receive raw data with the normal `recv` method). Extra care should be taken
//! when cloning the sender and using it from more threads.
//!
//! With remote channels the messages are serialized using `bincode`.
//!
//! # Usage
//!
//! Here there are some simple examples of how you can use this crate:
//!
//! ## Simple local channel
//! ```
//! # use ductile::new_local_channel;
//! let (tx, rx) = new_local_channel();
//! tx.send(42u64).unwrap();
//! tx.send_raw(&vec![1, 2, 3, 4]).unwrap();
//! let answer = rx.recv().unwrap();
//! assert_eq!(answer, 42u64);
//! let data = rx.recv_raw().unwrap();
//! assert_eq!(data, vec![1, 2, 3, 4]);
//! ```
//!
//! ## Local channel with custom data types
//! Note that your types must be `Serialize` and `Deserialize`.
//! ```
//! # use ductile::new_local_channel;
//! # use serde::{Serialize, Deserialize};
//! #[derive(Serialize, Deserialize)]
//! struct Thing {
//! pub x: u32,
//! pub y: String,
//! }
//! let (tx, rx) = new_local_channel();
//! tx.send(Thing {
//! x: 42,
//! y: "foobar".into(),
//! })
//! .unwrap();
//! let thing: Thing = rx.recv().unwrap();
//! assert_eq!(thing.x, 42);
//! assert_eq!(thing.y, "foobar");
//! ```
//!
//! ## Remote channels
//! ```
//! # use ductile::{ChannelServer, connect_channel};
//! let port = 18452; // let's hope we can bind this port!
//! let mut server = ChannelServer::bind(("127.0.0.1", port)).unwrap();
//!
//! // this examples need a second thread since the handshake cannot be done using a single thread
//! // only
//! let client_thread = std::thread::spawn(move || {
//! let (sender, receiver) = connect_channel(("127.0.0.1", port)).unwrap();
//!
//! sender.send(vec![1, 2, 3, 4]).unwrap();
//!
//! let data: Vec<i32> = receiver.recv().unwrap();
//! assert_eq!(data, vec![5, 6, 7, 8]);
//!
//! sender.send(vec![9, 10, 11, 12]).unwrap();
//! sender.send_raw(&vec![1, 2, 3, 4, 5, 6, 7, 8, 9]).unwrap();
//! });
//!
//! let (sender, receiver, _addr) = server.next().unwrap();
//! let data: Vec<i32> = receiver.recv().unwrap();
//! assert_eq!(data, vec![1, 2, 3, 4]);
//!
//! sender.send(vec![5, 6, 7, 8]).unwrap();
//!
//! let data = receiver.recv().unwrap();
//! assert_eq!(data, vec![9, 10, 11, 12]);
//! let data = receiver.recv_raw().unwrap();
//! assert_eq!(data, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
//! # client_thread.join().unwrap();
//! ```
//!
//! ## Remote channel with encryption
//! ```
//! # use ductile::{ChannelServer, connect_channel_with_enc};
//! let port = 18453;
//! let enc_key = [69u8; 32];
//! let mut server = ChannelServer::bind_with_enc(("127.0.0.1", port), enc_key).unwrap();
//!
//! let client_thread = std::thread::spawn(move || {
//! let (sender, receiver) = connect_channel_with_enc(("127.0.0.1", port), &enc_key).unwrap();
//!
//! sender.send(vec![1u8, 2, 3, 4]).unwrap();
//!
//! let data: Vec<u8> = receiver.recv().unwrap();
//! assert_eq!(data, vec![5u8, 6, 7, 8]);
//!
//! sender.send(vec![69u8; 12345]).unwrap();
//! sender.send_raw(&vec![1, 2, 3, 4, 5, 6, 7, 8, 9]).unwrap();
//! });
//!
//! let (sender, receiver, _addr) = server.next().unwrap();
//!
//! let data: Vec<u8> = receiver.recv().unwrap();
//! assert_eq!(data, vec![1u8, 2, 3, 4]);
//!
//! sender.send(vec![5u8, 6, 7, 8]).unwrap();
//!
//! let data = receiver.recv().unwrap();
//! assert_eq!(data, vec![69u8; 12345]);
//! let file = receiver.recv_raw().unwrap();
//! assert_eq!(file, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
//! # client_thread.join().unwrap();
//! ```
//!
//! # Protocol
//!
//! ## Messages
//! All the _normal_ (non-raw) messages are encapsulated inside a `ChannelMessage::Message`,
//! serialized and sent normally.
//!
//! The messages in raw mode are sent differently depending if the channel is local or remote.
//! If the channel is local there is no serialization penality so the data is simply sent into the
//! channel. If the channel is removed to avoid serialization a small message with the data length
//! is sent first, followed by the actual payload (that can be eventually encrypted).
//!
//! ## Handshakes
//! Local channels do not need an handshake, therefore this section refers only to remote channels.
//!
//! There are 2 kinds of handshake: one for encrypted channels and one for non-encrypted ones.
//! The porpuse of the handshake is to share encryption information (like the nonce) and check if
//! the encryption key is correct.
//!
//! For encrypted channels 2 rounds of handshakes take place:
//!
//! - both parts generate 12 bytes of cryptographically secure random data (the channel nonce) and
//! send them to the other party unencrypted.
//! - after receiving the channel nonce each party encrypts a known contant (a magic number of 4
//! bytes) and sends it back to the other.
//! - when those 4 bytes are received they get decrypted and if they match the initial magic number
//! the key is _probably_ valid and the handshake completes.
//!
//! For unencrytpted channels the same handshake is done but with a static key and nonce and only
//! the magic is encrypted. All the following messages will be sent unencrypted.
#![deny(missing_docs)]
#![deny(missing_doc_code_examples)]
#[macro_use]
extern crate log;
use std::io::{Read, Write};
use std::marker::PhantomData;
use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use chacha20::stream_cipher::{NewStreamCipher, SyncStreamCipher};
use chacha20::{ChaCha20, Key, Nonce};
use crossbeam_channel::{unbounded, Receiver, Sender};
use failure::{bail, Error};
use rand::rngs::OsRng;
use rand::RngCore;
use parking_lot::Mutex;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
/// A magic constant used to check the protocol integrity between two remote hosts.
const MAGIC: u32 = 0x69421997;
/// Wrapper to `std::result::Result` defaulting the error type.
pub type Result<T> = std::result::Result<T, Error>;
/// Message wrapper that is sent in the channel. It allows serializing normal messages as well as
/// informing the other end that some raw data is coming in the channel and it should not be
/// deserialized.
#[derive(Debug, Clone, Serialize, Deserialize)]
enum ChannelMessage<T> {
/// The message is a normal application message of type T.
Message(T),
/// Message with some raw data. This message is used only in local channels.
RawData(Vec<u8>),
/// Message telling the other end that some raw data of the specified length is coming. This is
/// used only in remote channels. The data is not included here avoiding unnecessarily
/// serialization.
/// If the channel uses encryption this value only informs about the length of the actual raw
/// data, not the number of bytes sent into the channel. In fact the actual number of bytes sent
/// is a bit larger (due to encryption overheads that can be eventually removed).
RawDataStart(usize),
}
/// Actual `ChannelSender` implementation. This exists to hide the variants from the public API.
#[derive(Clone)]
enum ChannelSenderInner<T> {
/// The connection is only a local in-memory channel.
Local(Sender<ChannelMessage<T>>),
/// The connection is with a remote party. The Arc<Mutex<>> is needed because TcpStream is not
/// Clone and sending concurrently is not safe.
Remote(Arc<Mutex<TcpStream>>),
/// The connection is with a remote party, encrypted with ChaCha20.
RemoteEnc(Arc<Mutex<(TcpStream, ChaCha20)>>),
}
/// The channel part that sends data. It is generic over the type of messages sent and abstracts the
/// underlying type of connection. The connection type can be local in memory, or remote using TCP
/// sockets.
///
/// This sender is Clone since the channel is multiple producers, single consumer, just like
/// `std::sync::mpsc`.
#[derive(Clone)]
pub struct ChannelSender<T> {
inner: ChannelSenderInner<T>,
}
/// Actual `ChannelReceiver` implementation. This exists to hide the variants from the public API.
enum ChannelReceiverInner<T> {
/// The connection is only a local in-memory channel.
Local(Receiver<ChannelMessage<T>>),
/// The connection is with a remote party over a TCP socket.
Remote(Mutex<TcpStream>),
/// The connection is with a remote party and it is encrypted using ChaCha20.
RemoteEnc(Mutex<(TcpStream, ChaCha20)>),
}
/// The channel part that receives data. It is generic over the type of messages sent in the
/// channel. The type of the messages must match between sender and receiver.
///
/// This type is not Clone since the channel is multiple producers, single consumer, just like
/// `std::sync::mpsc`.
pub struct ChannelReceiver<T> {
inner: ChannelReceiverInner<T>,
}
impl<T> ChannelSender<T>
where
T: 'static + Send + Sync + Serialize,
{
/// Serialize and send a message in the channel. The message is not actually serialized for
/// local channels, but the type must be `Send + Sync`.
///
/// For remote channel the message is serialized, if you want to send raw data (i.e. `[u8]`)
/// that not need to be serialized consider using `send_raw` since its performance is way
/// better.
///
/// This method is guaranteed to fail if the receiver is dropped only for local channels. Using
/// remote channels drops this requirement.
///
/// ```
/// # use ductile::new_local_channel;
/// let (sender, receiver) = new_local_channel();
/// sender.send(42u8).unwrap();
/// drop(receiver);
/// assert!(sender.send(69u8).is_err());
/// ```
pub fn send(&self, data: T) -> Result<()> {
match &self.inner {
ChannelSenderInner::Local(sender) => sender
.send(ChannelMessage::Message(data))
.map_err(|e| e.into()),
ChannelSenderInner::Remote(sender) => {
let mut sender = sender.lock();
let stream = sender.deref_mut();
ChannelSender::<T>::send_remote_raw(stream, ChannelMessage::Message(data))
}
ChannelSenderInner::RemoteEnc(stream) => {
let mut stream = stream.lock();
let (stream, enc) = stream.deref_mut();
ChannelSender::<T>::send_remote_raw_enc(stream, enc, ChannelMessage::Message(data))
}
}
}
/// Send some raw data in the channel without serializing it. This is possible only for raw
/// unstructured data (`[u8]`), but this methods is much faster than `send` since it avoids
/// serializing the message.
///
/// This method is guaranteed to fail if the receiver is dropped only for local channels. Using
/// remote channels drops this requirement.
///
/// ```
/// # use ductile::new_local_channel;
/// let (sender, receiver) = new_local_channel::<()>();
/// sender.send_raw(&vec![1, 2, 3, 4]).unwrap();
/// drop(receiver);
/// assert!(sender.send_raw(&vec![1, 2]).is_err());
/// ```
pub fn send_raw(&self, data: &[u8]) -> Result<()> {
match &self.inner {
ChannelSenderInner::Local(sender) => {
Ok(sender.send(ChannelMessage::RawData(data.into()))?)
}
ChannelSenderInner::Remote(sender) => {
let mut sender = sender.lock();
let stream = sender.deref_mut();
ChannelSender::<T>::send_remote_raw(
stream,
ChannelMessage::RawDataStart(data.len()),
)?;
Ok(stream.write_all(&data)?)
}
ChannelSenderInner::RemoteEnc(stream) => {
let mut stream = stream.lock();
let (stream, enc) = stream.deref_mut();
ChannelSender::<T>::send_remote_raw_enc(
stream,
enc,
ChannelMessage::RawDataStart(data.len()),
)?;
let data = ChannelSender::<T>::encrypt_buffer(data.into(), enc)?;
Ok(stream.write_all(&data)?)
}
}
}
/// Serialize and send a `ChannelMessage` data to the remote channel, without encrypting
/// message.
fn send_remote_raw(stream: &mut TcpStream, data: ChannelMessage<T>) -> Result<()> {
Ok(bincode::serialize_into(stream, &data)?)
}
/// Serialize and send a `ChannelMessage` data to the remote channel, encrypting message.
fn send_remote_raw_enc(
stream: &mut TcpStream,
encryptor: &mut ChaCha20,
data: ChannelMessage<T>,
) -> Result<()> {
let data = bincode::serialize(&data)?;
let data = ChannelSender::<T>::encrypt_buffer(data, encryptor)?;
stream.write_all(&data)?;
Ok(())
}
/// Encrypt a buffer, including it's length into a new buffer.
fn encrypt_buffer(mut data: Vec<u8>, encryptor: &mut ChaCha20) -> Result<Vec<u8>> {
let mut res = Vec::from((data.len() as u32).to_le_bytes());
res.append(&mut data);
encryptor.apply_keystream(&mut res);
Ok(res)
}
/// Given this is a remote channel, change the type of the message. Will panic if this
/// is a local channel.
///
/// This function is useful for implementing a protocol where the message types change during
/// the execution, for example because initially there is an handshake message, followed by the
/// actual protocol messages.
///
/// ```
/// # use ductile::{ChannelServer, connect_channel, ChannelSender};
/// # let server = ChannelServer::<i32, i32>::bind("127.0.0.1:12358").unwrap();
/// # let thread = std::thread::spawn(move || {
/// # let (sender, receiver) = connect_channel::<_, i32, i32>("127.0.0.1:12358").unwrap();
/// # assert_eq!(receiver.recv().unwrap(), 42i32);
/// # sender.send(69i32).unwrap();
/// let sender: ChannelSender<i32> = sender.change_type();
/// let sender: ChannelSender<String> = sender.change_type();
/// # });
/// # for (sender, receiver, address) in server {
/// # sender.send(42i32).unwrap();
/// # assert_eq!(receiver.recv().unwrap(), 69i32);
/// # break;
/// # }
/// # thread.join().unwrap();
/// ```
pub fn change_type<T2>(self) -> ChannelSender<T2> {
match self.inner {
ChannelSenderInner::Remote(r) => ChannelSender {
inner: ChannelSenderInner::Remote(r),
},
ChannelSenderInner::RemoteEnc(r) => ChannelSender {
inner: ChannelSenderInner::RemoteEnc(r),
},
ChannelSenderInner::Local(_) => panic!("Cannot change ChannelSender::Local type"),
}
}
}
impl<T> ChannelReceiver<T>
where
T: 'static + DeserializeOwned,
{
/// Receive a message from the channel. This method will block until the other end sends a
/// message.
///
/// If the other end used `send_raw` this method panics since the channel corrupts.
///
/// ```
/// # use ductile::new_local_channel;
/// let (sender, receiver) = new_local_channel();
/// sender.send(42);
/// let num: i32 = receiver.recv().unwrap();
/// assert_eq!(num, 42);
/// ```
pub fn recv(&self) -> Result<T> {
let message = match &self.inner {
ChannelReceiverInner::Local(receiver) => receiver.recv()?,
ChannelReceiverInner::Remote(receiver) => ChannelReceiver::recv_remote_raw(receiver)?,
ChannelReceiverInner::RemoteEnc(receiver) => {
let mut receiver = receiver.lock();
let (receiver, decryptor) = receiver.deref_mut();
ChannelReceiver::recv_remote_raw_enc(receiver, decryptor)?
}
};
match message {
ChannelMessage::Message(mex) => Ok(mex),
_ => panic!("Expected ChannelMessage::Message"),
}
}
/// Receive some raw data from the channel. This method will block until the other end sends
/// some data.
///
/// If the other end used `send` this method panics since the channel corrupts.
///
/// ```
/// # use ductile::new_local_channel;
/// let (sender, receiver) = new_local_channel::<()>();
/// sender.send_raw(&vec![1, 2, 3]);
/// let data: Vec<u8> = receiver.recv_raw().unwrap();
/// assert_eq!(data, vec![1, 2, 3]);
/// ```
pub fn recv_raw(&self) -> Result<Vec<u8>> {
match &self.inner {
ChannelReceiverInner::Local(receiver) => match receiver.recv()? {
ChannelMessage::RawData(data) => Ok(data),
_ => panic!("Expected ChannelMessage::RawData"),
},
ChannelReceiverInner::Remote(receiver) => {
match ChannelReceiver::<T>::recv_remote_raw(receiver)? {
ChannelMessage::RawDataStart(len) => {
let mut receiver = receiver.lock();
let mut buf = vec![0u8; len];
receiver.read_exact(&mut buf)?;
Ok(buf)
}
_ => panic!("Expected ChannelMessage::RawDataStart"),
}
}
ChannelReceiverInner::RemoteEnc(receiver) => {
let mut receiver = receiver.lock();
let (receiver, decryptor) = receiver.deref_mut();
match ChannelReceiver::<T>::recv_remote_raw_enc(receiver, decryptor)? {
ChannelMessage::RawDataStart(_) => {
let buf = ChannelReceiver::<T>::decrypt_buffer(receiver, decryptor)?;
Ok(buf)
}
_ => panic!("Expected ChannelMessage::RawDataStart"),
}
}
}
}
/// Receive a message from the TCP stream of a channel.
fn recv_remote_raw(receiver: &Mutex<TcpStream>) -> Result<ChannelMessage<T>> {
let mut receiver = receiver.lock();
Ok(bincode::deserialize_from(receiver.deref_mut())?)
}
/// Receive a message from the encrypted TCP stream of a channel.
fn recv_remote_raw_enc(
receiver: &mut TcpStream,
decryptor: &mut ChaCha20,
) -> Result<ChannelMessage<T>> {
let buf = ChannelReceiver::<T>::decrypt_buffer(receiver, decryptor)?;
Ok(bincode::deserialize(&buf)?)
}
/// Receive and decrypt a frame from the stream, removing the header and returning the contained
/// raw data.
fn decrypt_buffer(receiver: &mut TcpStream, decryptor: &mut ChaCha20) -> Result<Vec<u8>> {
let mut len = [0u8; 4];
receiver.read_exact(&mut len)?;
decryptor.apply_keystream(&mut len);
let len = u32::from_le_bytes(len) as usize;
let mut buf = vec![0u8; len];
receiver.read_exact(&mut buf)?;
decryptor.apply_keystream(&mut buf);
Ok(buf)
}
/// Given this is a remote channel, change the type of the message. Will panic if this is a
/// `ChannelReceiver::Local`.
///
/// This function is useful for implementing a protocol where the message types change during
/// the execution, for example because initially there is an handshake message, followed by the
/// actual protocol messages.
///
/// ```
/// # use ductile::{ChannelServer, connect_channel, ChannelSender, ChannelReceiver};
/// # let server = ChannelServer::<i32, i32>::bind("127.0.0.1:12358").unwrap();
/// # let thread = std::thread::spawn(move || {
/// # let (sender, receiver) = connect_channel::<_, i32, i32>("127.0.0.1:12358").unwrap();
/// # assert_eq!(receiver.recv().unwrap(), 42i32);
/// # sender.send(69i32).unwrap();
/// let receiver: ChannelReceiver<i32> = receiver.change_type();
/// let receiver: ChannelReceiver<String> = receiver.change_type();
/// # });
/// # for (sender, receiver, address) in server {
/// # sender.send(42i32).unwrap();
/// # assert_eq!(receiver.recv().unwrap(), 69i32);
/// # break;
/// # }
/// # thread.join().unwrap();
/// ```
pub fn change_type<T2>(self) -> ChannelReceiver<T2> {
match self.inner {
ChannelReceiverInner::Local(_) => panic!("Cannot change ChannelReceiver::Local type"),
ChannelReceiverInner::Remote(r) => ChannelReceiver {
inner: ChannelReceiverInner::Remote(r),
},
ChannelReceiverInner::RemoteEnc(r) => ChannelReceiver {
inner: ChannelReceiverInner::RemoteEnc(r),
},
}
}
}
/// Make a new pair of `ChannelSender` / `ChannelReceiver` that use in-memory message communication.
///
/// ```
/// # use ductile::new_local_channel;
/// let (tx, rx) = new_local_channel();
/// tx.send(42u64).unwrap();
/// tx.send_raw(&vec![1, 2, 3, 4]).unwrap();
/// let answer = rx.recv().unwrap();
/// assert_eq!(answer, 42u64);
/// let data = rx.recv_raw().unwrap();
/// assert_eq!(data, vec![1, 2, 3, 4]);
/// ```
pub fn new_local_channel<T>() -> (ChannelSender<T>, ChannelReceiver<T>) {
let (tx, rx) = unbounded();
(
ChannelSender {
inner: ChannelSenderInner::Local(tx),
},
ChannelReceiver {
inner: ChannelReceiverInner::Local(rx),
},
)
}
/// Listener for connections on some TCP socket.
///
/// The connection between the two parts is full-duplex and the types of message shared can be
/// different. `S` and `R` are the types of message sent and received respectively. When initialized
/// with an encryption key it is expected that the remote clients use the same key. Clients that use
/// the wrong key are disconnected during an initial handshake.
pub struct ChannelServer<S, R> {
/// The actual listener of the TCP socket.
listener: TcpListener,
/// An optional ChaCha20 key to use to encrypt the communication.
enc_key: Option<[u8; 32]>,
/// Save the type of the sending messages.
_sender: PhantomData<*const S>,
/// Save the type of the receiving messages.
_receiver: PhantomData<*const R>,
}
impl<S, R> ChannelServer<S, R> {
/// Bind a TCP socket and create a new `ChannelServer`. Only proper sockets are supported (not
/// Unix sockets yet). This method does not enable message encryption.
///
/// ```
/// # use ductile::{ChannelServer, connect_channel};
/// let server = ChannelServer::<i32, i32>::bind("127.0.0.1:12357").unwrap();
/// assert!(ChannelServer::<(), ()>::bind("127.0.0.1:12357").is_err()); // port already in use
///
/// # let thread =
/// std::thread::spawn(move || {
/// let (sender, receiver) = connect_channel::<_, i32, i32>("127.0.0.1:12357").unwrap();
/// assert_eq!(receiver.recv().unwrap(), 42i32);
/// sender.send(69i32).unwrap();
/// });
///
/// for (sender, receiver, address) in server {
/// sender.send(42i32).unwrap();
/// assert_eq!(receiver.recv().unwrap(), 69i32);
/// # break;
/// }
/// # thread.join().unwrap();
/// ```
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<ChannelServer<S, R>> {
Ok(ChannelServer {
listener: TcpListener::bind(addr)?,
enc_key: None,
_sender: Default::default(),
_receiver: Default::default(),
})
}
/// Bind a TCP socket and create a new `ChannelServer`. All the data transferred within this
/// socket is encrypted using ChaCha20 initialized with the provided key. That key should be the
/// same used by the clients that connect to this server.
///
/// ```
/// # use ductile::{ChannelServer, connect_channel, connect_channel_with_enc};
/// let key = [42; 32];
/// let server = ChannelServer::<i32, i32>::bind_with_enc("127.0.0.1:12357", key).unwrap();
/// assert!(ChannelServer::<(), ()>::bind("127.0.0.1:12357").is_err()); // port already in use
///
/// # let thread =
/// std::thread::spawn(move || {
/// let (sender, receiver) = connect_channel_with_enc::<_, i32, i32>("127.0.0.1:12357", &key).unwrap();
/// assert_eq!(receiver.recv().unwrap(), 42i32);
/// sender.send(69i32).unwrap();
/// });
///
/// for (sender, receiver, address) in server {
/// sender.send(42i32).unwrap();
/// assert_eq!(receiver.recv().unwrap(), 69i32);
/// # break;
/// }
/// # thread.join().unwrap();
/// ```
pub fn bind_with_enc<A: ToSocketAddrs>(
addr: A,
enc_key: [u8; 32],
) -> Result<ChannelServer<S, R>> {
Ok(ChannelServer {
listener: TcpListener::bind(addr)?,
enc_key: Some(enc_key),
_sender: Default::default(),
_receiver: Default::default(),
})
}
}
impl<S, R> Deref for ChannelServer<S, R> {
type Target = TcpListener;
fn deref(&self) -> &Self::Target {
&self.listener
}
}
impl<S, R> Iterator for ChannelServer<S, R> {
type Item = (ChannelSender<S>, ChannelReceiver<R>, SocketAddr);
fn next(&mut self) -> Option<Self::Item> {
loop {
let next = self
.listener
.incoming()
.next()
.expect("TcpListener::incoming returned None");
// `next` is Err if a client connected only partially
if let Ok(mut sender) = next {
// it is required for all the clients to have a proper SocketAddr
let peer_addr = sender.peer_addr().expect("Peer has no remote address");
// it is required that the sockets are clonable for splitting them into
// sender/receiver
let receiver = sender.try_clone().expect("Failed to clone the stream");
// if the encryption key was provided do the handshake using it
if let Some(enc_key) = &self.enc_key {
let key = Key::from_slice(enc_key);
// generate and exchange new random nonce
let (enc_nonce, dec_nonce) = match nonce_handshake(&mut sender) {
Ok(x) => x,
Err(e) => {
warn!("Nonce handshake failed with {}: {:?}", peer_addr, e);
continue;
}
};
let enc_nonce = Nonce::from_slice(&enc_nonce);
let mut enc = ChaCha20::new(&key, &enc_nonce);
let dec_nonce = Nonce::from_slice(&dec_nonce);
let mut dec = ChaCha20::new(&key, &dec_nonce);
// the last part of the handshake checks that the encryption key is correct
if let Err(e) = check_encryption_key(&mut sender, &mut enc, &mut dec) {
warn!("Magic handshake failed with {}: {:?}", peer_addr, e);
continue;
}
return Some((
ChannelSender {
inner: ChannelSenderInner::RemoteEnc(Arc::new(Mutex::new((
sender, enc,
)))),
},
ChannelReceiver {
inner: ChannelReceiverInner::RemoteEnc(Mutex::new((receiver, dec))),
},
peer_addr,
));
// if no key was provided the handshake checks that the other end also didn't use an
// encryption key
} else {
if let Err(e) = check_no_encryption(&mut sender) {
warn!("Magic handshake failed with {}: {:?}", peer_addr, e);
continue;
}
return Some((
ChannelSender {
inner: ChannelSenderInner::Remote(Arc::new(Mutex::new(sender))),
},
ChannelReceiver {
inner: ChannelReceiverInner::Remote(Mutex::new(receiver)),
},
peer_addr,
));
}
}
}
}
}
/// Connect to a remote channel.
///
/// All the remote channels are full-duplex, therefore this function returns a channel for sending
/// the message and a channel from where receive them.
///
/// This function will no enable message encryption.
///
/// ```
/// # use ductile::{ChannelServer, connect_channel};
/// let port = 18455; // let's hope we can bind this port!
/// let mut server = ChannelServer::<(), _>::bind(("127.0.0.1", port)).unwrap();
///
/// let client_thread = std::thread::spawn(move || {
/// let (sender, receiver) = connect_channel::<_, _, ()>(("127.0.0.1", port)).unwrap();
///
/// sender.send(vec![1, 2, 3, 4]).unwrap();
/// });
///
/// let (sender, receiver, _addr) = server.next().unwrap();
/// let data: Vec<i32> = receiver.recv().unwrap();
/// assert_eq!(data, vec![1, 2, 3, 4]);
/// # client_thread.join().unwrap();
/// ```
pub fn connect_channel<A: ToSocketAddrs, S, R>(
addr: A,
) -> Result<(ChannelSender<S>, ChannelReceiver<R>)> {
let mut stream = TcpStream::connect(addr)?;
let stream2 = stream.try_clone()?;
check_no_encryption(&mut stream)?;
Ok((
ChannelSender {
inner: ChannelSenderInner::Remote(Arc::new(Mutex::new(stream))),
},
ChannelReceiver {
inner: ChannelReceiverInner::Remote(Mutex::new(stream2)),
},
))
}
/// Connect to a remote channel encrypting the connection.
///
/// All the remote channels are full-duplex, therefore this function returns a channel for sending
/// the message and a channel from where receive them.
///
/// ```
/// # use ductile::{ChannelServer, connect_channel, connect_channel_with_enc};
/// let port = 18456; // let's hope we can bind this port!
/// let key = [42; 32];
/// let mut server = ChannelServer::<(), _>::bind_with_enc(("127.0.0.1", port), key).unwrap();
///
/// let client_thread = std::thread::spawn(move || {
/// let (sender, receiver) = connect_channel_with_enc::<_, _, ()>(("127.0.0.1", port), &key).unwrap();
///
/// sender.send(vec![1, 2, 3, 4]).unwrap();
/// });
///
/// let (sender, receiver, _addr) = server.next().unwrap();
/// let data: Vec<i32> = receiver.recv().unwrap();
/// assert_eq!(data, vec![1, 2, 3, 4]);
/// # client_thread.join().unwrap();
/// ```
pub fn connect_channel_with_enc<A: ToSocketAddrs, S, R>(
addr: A,
enc_key: &[u8; 32],
) -> Result<(ChannelSender<S>, ChannelReceiver<R>)> {
let mut stream = TcpStream::connect(addr)?;
let stream2 = stream.try_clone()?;
let (enc_nonce, dec_nonce) = nonce_handshake(&mut stream)?;
let key = Key::from_slice(enc_key);
let mut enc = ChaCha20::new(&key, &Nonce::from_slice(&enc_nonce));
let mut dec = ChaCha20::new(&key, &Nonce::from_slice(&dec_nonce));
check_encryption_key(&mut stream, &mut enc, &mut dec)?;
Ok((
ChannelSender {
inner: ChannelSenderInner::RemoteEnc(Arc::new(Mutex::new((stream, enc)))),
},
ChannelReceiver {
inner: ChannelReceiverInner::RemoteEnc(Mutex::new((stream2, dec))),
},
))
}
/// Send the encryption nonce and receive the decryption nonce using the provided socket.
fn nonce_handshake(s: &mut TcpStream) -> Result<([u8; 12], [u8; 12])> {
let mut enc_nonce = [0u8; 12];
OsRng.fill_bytes(&mut enc_nonce);
s.write_all(&enc_nonce)?;
s.flush()?;
let mut dec_nonce = [0u8; 12];
s.read_exact(&mut dec_nonce)?;
Ok((enc_nonce, dec_nonce))
}
/// Check that the encryption key is the same both ends.
fn check_encryption_key(
stream: &mut TcpStream,
enc: &mut ChaCha20,
dec: &mut ChaCha20,
) -> Result<()> {
let mut magic = MAGIC.to_le_bytes();
enc.apply_keystream(&mut magic);
stream.write_all(&magic)?;
stream.flush()?;
stream.read_exact(&mut magic)?;
dec.apply_keystream(&mut magic);
let magic = u32::from_le_bytes(magic);
if magic != MAGIC {
bail!("Wrong encryption key");
}
Ok(())
}
/// Check that no encryption is used by the other end.
fn check_no_encryption(stream: &mut TcpStream) -> Result<()> {
let key = b"task-maker's the best thing ever";
let nonce = b"task-maker!!";
let mut enc = ChaCha20::new(Key::from_slice(key), Nonce::from_slice(nonce));
let mut dec = ChaCha20::new(Key::from_slice(key), Nonce::from_slice(nonce));
check_encryption_key(stream, &mut enc, &mut dec)
}
#[cfg(test)]
mod tests {
use rand::Rng;
use super::*;
#[test]
fn test_remote_channels_enc_wrong_key() {
let port = rand::thread_rng().gen_range(10000u16, 20000u16);
let enc_key = [42u8; 32];
let mut server: ChannelServer<(), ()> =
ChannelServer::bind_with_enc(("127.0.0.1", port), enc_key).unwrap();
let client_thread = std::thread::spawn(move || {
let wrong_enc_key = [69u8; 32];
assert!(
connect_channel_with_enc::<_, (), ()>(("127.0.0.1", port), &wrong_enc_key).is_err()
);
// the call to .next() below blocks until a client connects successfully
connect_channel_with_enc::<_, (), ()>(("127.0.0.1", port), &enc_key).unwrap();
});
server.next().unwrap();
client_thread.join().unwrap();
}
#[test]
fn test_remote_channels_enc_no_key() {
let port = rand::thread_rng().gen_range(10000u16, 20000u16);
let enc_key = [42u8; 32];
let mut server: ChannelServer<(), ()> =
ChannelServer::bind_with_enc(("127.0.0.1", port), enc_key).unwrap();
let client_thread = std::thread::spawn(move || {
assert!(connect_channel::<_, (), ()>(("127.0.0.1", port)).is_err());
// the call to .next() below blocks until a client connects successfully
connect_channel_with_enc::<_, (), ()>(("127.0.0.1", port), &enc_key).unwrap();
});
server.next().unwrap();
client_thread.join().unwrap();
}
#[test]
fn test_remote_channels_receiver_stops() {
let port = rand::thread_rng().gen_range(10000u16, 20000u16);
let mut server: ChannelServer<(), ()> = ChannelServer::bind(("127.0.0.1", port)).unwrap();
let client_thread = std::thread::spawn(move || {
let (sender, _) = connect_channel::<_, (), ()>(("127.0.0.1", port)).unwrap();
sender.send(()).unwrap();
});
let (_, receiver, _) = server.next().unwrap();
client_thread.join().unwrap();
receiver.recv().unwrap();
// all the senders have been dropped and there are no more messages
assert!(receiver.recv().is_err());
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use std::sync::Arc;
use common_arrow::arrow::datatypes::Field;
use common_arrow::arrow::io::parquet::write::to_parquet_schema;
use common_arrow::parquet::metadata::SchemaDescriptor;
use common_catalog::plan::Projection;
use common_catalog::table_context::TableContext;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::types::DataType;
use common_expression::ColumnId;
use common_expression::DataField;
use common_expression::DataSchema;
use common_expression::FieldIndex;
use common_expression::Scalar;
use common_expression::TableField;
use common_expression::TableSchemaRef;
use common_sql::field_default_value;
use common_storage::ColumnNode;
use common_storage::ColumnNodes;
use opendal::Operator;
// TODO: make BlockReader as a trait.
#[derive(Clone)]
pub struct BlockReader {
pub(crate) operator: Operator,
pub(crate) projection: Projection,
pub(crate) projected_schema: TableSchemaRef,
pub(crate) project_indices: BTreeMap<FieldIndex, (ColumnId, Field, DataType)>,
pub(crate) project_column_nodes: Vec<ColumnNode>,
pub(crate) parquet_schema_descriptor: SchemaDescriptor,
pub(crate) default_vals: Vec<Scalar>,
pub query_internal_columns: bool,
}
fn inner_project_field_default_values(default_vals: &[Scalar], paths: &[usize]) -> Result<Scalar> {
if paths.is_empty() {
return Err(ErrorCode::BadArguments(
"path should not be empty".to_string(),
));
}
let index = paths[0];
if paths.len() == 1 {
return Ok(default_vals[index].clone());
}
match &default_vals[index] {
Scalar::Tuple(s) => inner_project_field_default_values(s, &paths[1..]),
_ => {
if paths.len() > 1 {
return Err(ErrorCode::BadArguments(
"Unable to get field default value by paths".to_string(),
));
}
inner_project_field_default_values(&[default_vals[index].clone()], &paths[1..])
}
}
}
impl BlockReader {
pub fn create(
operator: Operator,
schema: TableSchemaRef,
projection: Projection,
ctx: Arc<dyn TableContext>,
query_internal_columns: bool,
) -> Result<Arc<BlockReader>> {
// init projected_schema and default_vals of schema.fields
let (projected_schema, default_vals) = match projection {
Projection::Columns(ref indices) => {
let projected_schema = TableSchemaRef::new(schema.project(indices));
// If projection by Columns, just calc default values by projected fields.
let mut default_vals = Vec::with_capacity(projected_schema.fields().len());
for field in projected_schema.fields() {
let default_val = field_default_value(ctx.clone(), field)?;
default_vals.push(default_val);
}
(projected_schema, default_vals)
}
Projection::InnerColumns(ref path_indices) => {
let projected_schema = TableSchemaRef::new(schema.inner_project(path_indices));
let mut field_default_vals = Vec::with_capacity(schema.fields().len());
// If projection by InnerColumns, first calc default value of all schema fields.
for field in schema.fields() {
field_default_vals.push(field_default_value(ctx.clone(), field)?);
}
// Then calc project scalars by path_indices
let mut default_vals = Vec::with_capacity(schema.fields().len());
path_indices.values().for_each(|path| {
default_vals.push(
inner_project_field_default_values(&field_default_vals, path).unwrap(),
);
});
(projected_schema, default_vals)
}
};
let arrow_schema = schema.to_arrow();
let parquet_schema_descriptor = to_parquet_schema(&arrow_schema)?;
let column_nodes = ColumnNodes::new_from_schema(&arrow_schema, Some(&schema));
let project_column_nodes: Vec<ColumnNode> = projection
.project_column_nodes(&column_nodes)?
.iter()
.map(|c| (*c).clone())
.collect();
let project_indices = Self::build_projection_indices(&project_column_nodes);
Ok(Arc::new(BlockReader {
operator,
projection,
projected_schema,
project_indices,
project_column_nodes,
parquet_schema_descriptor,
default_vals,
query_internal_columns,
}))
}
pub fn support_blocking_api(&self) -> bool {
self.operator.info().can_blocking()
}
// Build non duplicate leaf_indices to avoid repeated read column from parquet
pub(crate) fn build_projection_indices(
columns: &[ColumnNode],
) -> BTreeMap<FieldIndex, (ColumnId, Field, DataType)> {
let mut indices = BTreeMap::new();
for column in columns {
for (i, index) in column.leaf_indices.iter().enumerate() {
let f: TableField = (&column.field).into();
let data_type: DataType = f.data_type().into();
indices.insert(
*index,
(column.leaf_column_ids[i], column.field.clone(), data_type),
);
}
}
indices
}
pub fn query_internal_columns(&self) -> bool {
self.query_internal_columns
}
pub fn schema(&self) -> TableSchemaRef {
self.projected_schema.clone()
}
pub fn data_fields(&self) -> Vec<DataField> {
self.schema().fields().iter().map(DataField::from).collect()
}
pub fn data_schema(&self) -> DataSchema {
let fields = self.data_fields();
DataSchema::new(fields)
}
}
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that a field can have the same name in different variants
// of an enum
pub enum Foo {
X { foo: u32 },
Y { foo: u32 }
}
pub fn foo(mut x: Foo) {
let mut y = None;
let mut z = None;
if let Foo::X { ref foo } = x {
z = Some(foo);
}
if let Foo::Y { ref mut foo } = x {
y = Some(foo);
}
}
fn main() {}
|
#[doc = "Reader of register SR"]
pub type R = crate::R<u32, super::SR>;
#[doc = "Reader of field `TFE`"]
pub type TFE_R = crate::R<bool, bool>;
#[doc = "Reader of field `TNF`"]
pub type TNF_R = crate::R<bool, bool>;
#[doc = "Reader of field `RNE`"]
pub type RNE_R = crate::R<bool, bool>;
#[doc = "Reader of field `RFF`"]
pub type RFF_R = crate::R<bool, bool>;
#[doc = "Reader of field `BSY`"]
pub type BSY_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - SSI Transmit FIFO Empty"]
#[inline(always)]
pub fn tfe(&self) -> TFE_R {
TFE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - SSI Transmit FIFO Not Full"]
#[inline(always)]
pub fn tnf(&self) -> TNF_R {
TNF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - SSI Receive FIFO Not Empty"]
#[inline(always)]
pub fn rne(&self) -> RNE_R {
RNE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - SSI Receive FIFO Full"]
#[inline(always)]
pub fn rff(&self) -> RFF_R {
RFF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - SSI Busy Bit"]
#[inline(always)]
pub fn bsy(&self) -> BSY_R {
BSY_R::new(((self.bits >> 4) & 0x01) != 0)
}
}
|
#[doc = "Reader of register TXCNTGB"]
pub type R = crate::R<u32, super::TXCNTGB>;
#[doc = "Reader of field `TXFRMGB`"]
pub type TXFRMGB_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - This field indicates the number of good and bad frames transmitted, exclusive of retried frames"]
#[inline(always)]
pub fn txfrmgb(&self) -> TXFRMGB_R {
TXFRMGB_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
#[doc = "Reader of register RX_PAYSZ"]
pub type R = crate::R<u32, super::RX_PAYSZ>;
#[doc = "Reader of field `RXPAYSZ`"]
pub type RXPAYSZ_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:9 - RXPAYSZ"]
#[inline(always)]
pub fn rxpaysz(&self) -> RXPAYSZ_R {
RXPAYSZ_R::new((self.bits & 0x03ff) as u16)
}
}
|
#[cfg(feature = "generate_bindings")]
extern crate bindgen;
extern crate cc;
use std::env;
use std::path::{Path, PathBuf};
fn main() {
let mut build = cc::Build::new();
build.include("Vulkan-Headers/include");
build.include("VulkanMemoryAllocator/include");
build.file("vma.cpp");
let target = env::var("TARGET").unwrap();
if target.contains("darwin") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.flag("-Wno-nullability-completeness")
.cpp_link_stdlib("c++")
.cpp_set_stdlib("c++")
.cpp(true);
} else if target.contains("ios") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.cpp_link_stdlib("c++")
.cpp_set_stdlib("c++")
.cpp(true);
} else if target.contains("android") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-nullability-completeness")
.flag("-Wno-reorder")
.cpp_link_stdlib("c++")
.cpp(true);
} else if target.contains("linux") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.flag("-Wno-implicit-fallthrough")
.flag("-Wno-parentheses")
.cpp_link_stdlib("stdc++")
.cpp(true);
} else if target.contains("windows") && target.contains("gnu") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.flag("-Wno-type-limits")
.cpp_link_stdlib("stdc++")
.cpp(true);
}
build.compile("vma_cpp");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
generate_bindings(&out_path.join("bindings.rs"));
}
fn generate_bindings<P>(output_file: &P)
where P: AsRef<Path> {
let bindings = bindgen::Builder::default()
.clang_arg("-IVulkan-Headers/include")
.header("VulkanMemoryAllocator/include/vk_mem_alloc.h")
.rustfmt_bindings(true)
.size_t_is_usize(true)
.blocklist_type("__darwin_.*")
.allowlist_function("vma.*")
.allowlist_function("PFN_vma.*")
.allowlist_type("Vma.*")
.parse_callbacks(Box::new(FixAshTypes))
.blocklist_type("Vk.*")
.blocklist_type("PFN_vk.*")
.raw_line("use ash::vk::*;")
.trust_clang_mangling(false)
.layout_tests(false)
.generate()
.expect("Unable to generate bindings!");
bindings
.write_to_file(output_file)
.expect("Unable to write bindings!");
}
#[derive(Debug)]
struct FixAshTypes;
impl bindgen::callbacks::ParseCallbacks for FixAshTypes {
fn item_name(&self, original_item_name: &str) -> Option<String> {
if original_item_name.starts_with("Vk") {
// Strip `Vk` prefix, will use `ash::vk::*` instead
Some(original_item_name.trim_start_matches("Vk").to_string())
} else if original_item_name.starts_with("PFN_vk") {
let name = if original_item_name.ends_with("KHR") {
// VMA uses a few extensions like `PFN_vkGetBufferMemoryRequirements2KHR`,
// ash keeps these as `PFN_vkGetBufferMemoryRequirements2`
original_item_name.trim_end_matches("KHR")
} else {
original_item_name
};
Some(format!("Option<{}>", name))
} else {
None
}
}
// When ignoring `Vk` types, bindgen loses derives for some type. Quick workaround.
fn add_derives(&self, name: &str) -> Vec<String> {
if name.starts_with("VmaAllocationInfo") || name.starts_with("VmaDefragmentationStats") {
vec!["Debug".into(), "Copy".into(), "Clone".into()]
} else {
vec![]
}
}
}
|
use super::piece_logic::*;
pub fn print_board(board: &[[Option<Piece>; 8]; 8]) {
for y in (0..board.len()).rev() {
for x in 0..board[0].len() {
print!("|");
if let Some(piece) = &board[y][x] {
print!("{}", piece);
} else {
print!(" ")
}
print!("|");
}
println!();
println!("------------------------");
}
}
|
use std::io::Read;
use std::fs::File;
use std::collections::HashMap;
fn read_passports(path: &String, out: &mut Vec<HashMap<String, String>>) {
let mut file = File::open(path).unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
let mut tmp: Vec<String> = Vec::new();
for line in content.lines() {
if line.len() > 0 {
tmp.push(line.to_string());
}
else if line.len() == 0 {
let mut passport: HashMap<String, String> = HashMap::new();
while tmp.len() > 0 {
let passport_string = tmp.pop().unwrap();
let fields = passport_string.split_whitespace();
for field in fields {
let field_pair: Vec<String> = field.split(":")
.map(|x| x.to_string())
.collect();
passport.insert(field_pair[0].clone(), field_pair[1].clone());
}
}
out.push(passport);
}
}
if tmp.len() > 0 {
let mut passport: HashMap<String, String> = HashMap::new();
while tmp.len() > 0 {
let passport_string = tmp.pop().unwrap();
let fields = passport_string.split_whitespace();
for field in fields {
let field_pair: Vec<String> = field.split(":")
.map(|x| x.to_string())
.collect();
passport.insert(field_pair[0].clone(), field_pair[1].clone());
}
}
out.push(passport);
}
}
fn is_passport_valid1(passport: &HashMap<String, String>) -> bool {
let n_fields = passport.len();
n_fields == 8 || // all fields present OR
(n_fields == 7 && // 7 fields and the missing field is the cid field
passport.contains_key(&"cid".to_string()) == false)
}
fn is_number_field_valid(passport: &HashMap<String, String>,
field: &str,
n_digits: usize,
min_value: usize,
max_value: usize) -> bool {
match get_value_of_length(&passport, &field.to_string(), n_digits) {
Ok(value) => {
match value.parse::<usize>() {
Ok(value) => {
if min_value <= value && value <= max_value {
return true;
} else {
println!("wrong min/max size {} {}/{}/{}", field, min_value, value, max_value);
return false;
}
},
Err(error) => {
println!("Could not parse {} {}", value, error);
return false;
},
}
}
Err(error) => {
println!("Error fetching value for key {} {}", field, error);
return false;
}
}
}
fn get_value_of_length(passport: &HashMap<String, String>, key: &String, len: usize) -> Result<String, String> {
match passport.get(key) {
Some(value) => {
if value.len() == len {
Ok(value.clone())
} else {
Err(format!("Value too short/long {}/{}", value.len(), len))
}
},
None => {
Err(format!("Key '{}' not found", key))
}
}
}
fn is_eye_colour_valid(passport: &HashMap<String, String>) -> bool {
match get_value_of_length(&passport, &String::from("ecl"), 3) {
Ok(value) => {
const VALID_EYE_COLOURS: [&str; 7] = [
"amb",
"blu",
"brn",
"gry",
"grn",
"hzl",
"oth",
];
if VALID_EYE_COLOURS.contains(&value.as_str()) {
return true;
} else {
println!("Wrong eye colour {}", value);
return false;
}
}
Err(_error) => false,
}
}
fn is_hair_colour_valid(passport: &HashMap<String, String>) -> bool {
match get_value_of_length(&passport, &String::from("hcl"), 7) {
Ok(value) => {
if value.starts_with("#") {
// Skip first char as it is #
for c in value[1 ..].chars() {
if c.is_alphanumeric() {
continue;
} else {
println!("Hair colour NOT valid! {} '{}'", value, c);
return false
}
}
return true
}
else {
println!("Hair colour NOT valid! does not start with #");
return false
}
},
Err(error) => {
println!("Error getting hcl {}", error);
return false;
}
}
}
fn is_height_valid(passport: &HashMap<String, String>) -> bool {
let key = String::from("hgt");
match passport.get(&key) {
Some(value) => {
if value.len() == 5 || value.len() == 4 {
let mut height = value.clone();
let unit = height.split_off(value.len() - 2);
match height.parse::<usize>() {
Ok(height) => {
if unit == "in" {
if 59 <= height && height <= 76 {
return true;
} else {
println!("Wrong height 59 / {} / 76", height);
return false;
}
} else if unit == "cm" {
if 150 <= height && height <= 193 {
return true;
} else {
println!("Wrong height 150 / {} / 193", height);
return false;
}
} else {
println!("Got invalid unit {}", unit);
return false
}
},
Err(error) => {
println!("Error Parsing height {} {}", height, error);
return false;
}
}
}
else {
println!("Error Parsing height wrong len {}", value.len());
return false
}
},
None => {
println!("Error fetching {}", "hgt");
return false;
}
}
}
fn is_passport_valid2(passport: &HashMap<String, String>) -> bool {
is_number_field_valid(&passport, "byr", 4, 1920, 2002) &&
is_number_field_valid(&passport, "iyr", 4, 2010, 2020) &&
is_number_field_valid(&passport, "eyr", 4, 2020, 2030) &&
is_number_field_valid(&passport, "pid", 9, 0, 999999999) &&
is_eye_colour_valid(&passport) &&
is_height_valid(&passport) &&
is_hair_colour_valid(&passport) &&
is_passport_valid1(&passport)
}
pub fn solve_day4(path: &String) {
let mut passport_maps = Vec::new();
read_passports(path, &mut passport_maps);
/* PART1 */
let mut n_valid_passports = 0;
for passport in &passport_maps {
if is_passport_valid1(passport) {
n_valid_passports += 1;
}
}
println!("PART1: Got {}/{} valid passports", n_valid_passports, passport_maps.len());
/* PART2 */
n_valid_passports = 0;
for passport in &passport_maps {
if is_passport_valid2(&passport) {
n_valid_passports += 1;
} else {
println!("Failed on {:?}", passport);
println!("");
println!("");
}
}
println!("PART2: Got {}/{} valid passports", n_valid_passports, passport_maps.len());
} |
use core::marker::PhantomData;
use embedded_graphics::{
mono_font::{ascii::FONT_6X10, MonoFont},
prelude::WebColors,
};
use crate::themes::default::button::{ButtonStateColors, ButtonStyle};
pub struct PrimaryButtonInactive<C>(PhantomData<C>);
pub struct PrimaryButtonIdle<C>(PhantomData<C>);
pub struct PrimaryButtonHovered<C>(PhantomData<C>);
pub struct PrimaryButtonPressed<C>(PhantomData<C>);
impl<C> ButtonStateColors<C> for PrimaryButtonInactive<C>
where
C: WebColors,
{
const LABEL_COLOR: C = C::CSS_LIGHT_GRAY;
const BORDER_COLOR: C = C::CSS_DIM_GRAY;
const BACKGROUND_COLOR: C = C::CSS_DIM_GRAY;
}
impl<C> ButtonStateColors<C> for PrimaryButtonIdle<C>
where
C: WebColors,
{
const LABEL_COLOR: C = C::WHITE;
const BORDER_COLOR: C = C::CSS_STEEL_BLUE;
const BACKGROUND_COLOR: C = C::CSS_STEEL_BLUE;
}
impl<C> ButtonStateColors<C> for PrimaryButtonHovered<C>
where
C: WebColors,
{
const LABEL_COLOR: C = C::WHITE;
const BORDER_COLOR: C = C::CSS_DODGER_BLUE;
const BACKGROUND_COLOR: C = C::CSS_DODGER_BLUE;
}
impl<C> ButtonStateColors<C> for PrimaryButtonPressed<C>
where
C: WebColors,
{
const LABEL_COLOR: C = C::WHITE;
const BORDER_COLOR: C = C::CSS_LIGHT_STEEL_BLUE;
const BACKGROUND_COLOR: C = C::CSS_LIGHT_STEEL_BLUE;
}
pub struct PrimaryButtonStyle<C>(PhantomData<C>);
impl<C> ButtonStyle<C> for PrimaryButtonStyle<C>
where
C: WebColors,
{
type Inactive = PrimaryButtonInactive<C>;
type Idle = PrimaryButtonIdle<C>;
type Hovered = PrimaryButtonHovered<C>;
type Pressed = PrimaryButtonPressed<C>;
const FONT: MonoFont<'static> = FONT_6X10;
}
|
use imgui::*;
use std::ops::Range;
mod support;
const HEIGHT: f32 = 100.0;
const X_OFFSET: f32 = 400.0;
const Y_OFFSET: f32 = 120.0;
struct State {
checked: bool,
text: ImString,
scroll_to_end: bool,
has_filter: bool,
filter_curr: ImString,
}
fn clipper<F>(ui: &Ui, count: usize, mut fun: F)
where
F: FnMut(Range<usize>),
{
use imgui_sys::{
ImGuiListClipper, ImGuiListClipper_Begin, ImGuiListClipper_End, ImGuiListClipper_Step,
};
let font_height = ui.text_line_height_with_spacing();
let mut clipper = ImGuiListClipper {
StartPosY: 0.0,
ItemsHeight: -1.0,
ItemsCount: -1,
StepNo: 0,
DisplayStart: 0,
DisplayEnd: 0,
};
unsafe {
ImGuiListClipper_Begin(
&mut clipper as *mut ImGuiListClipper,
count as std::os::raw::c_int,
font_height as std::os::raw::c_float,
);
}
while unsafe { ImGuiListClipper_Step(&mut clipper as *mut ImGuiListClipper) } {
fun(clipper.DisplayStart as usize..clipper.DisplayEnd as usize);
}
unsafe {
ImGuiListClipper_End(&mut clipper as *mut ImGuiListClipper);
}
}
fn main() {
println!("Hello, world!");
let mut state = State {
checked: false,
text: ImString::with_capacity(128),
scroll_to_end: false,
has_filter: false,
filter_curr: ImString::with_capacity(128),
};
let mut line_num = 0;
let mut lines = Vec::new();
let system = support::init(file!());
system.main_loop(move |_, ui| {
line_num += 1;
lines.push(format!("Line {}", line_num));
// Start discarding old lines after a while.
if line_num > 1000 {
lines.remove(0);
}
Window::new(im_str!("Hello world"))
.size([300.0, HEIGHT], Condition::FirstUseEver)
.position([100.0, Y_OFFSET], Condition::FirstUseEver)
.build(ui, || {
ui.text(im_str!("Hello world!"));
ui.text(im_str!("こんにちは世界!"));
ui.text(im_str!("This...is...imgui-rs!"));
ui.separator();
let mouse_pos = ui.io().mouse_pos;
ui.text(format!(
"Mouse Position: ({:.1},{:.1})",
mouse_pos[0], mouse_pos[1]
));
});
Window::new(im_str!("Tabs"))
.size([300.0, HEIGHT], Condition::FirstUseEver)
.position([100.0, Y_OFFSET * 2.0], Condition::FirstUseEver)
.build(ui, || {
TabBar::new(im_str!("basictabbar")).build(&ui, || {
TabItem::new(im_str!("Avocado")).build(&ui, || {
ui.text(im_str!("This is the Avocado tab!"));
ui.text(im_str!("blah blah blah blah blah"));
});
TabItem::new(im_str!("Broccoli")).build(&ui, || {
ui.text(im_str!("This is the Broccoli tab!"));
ui.text(im_str!("blah blah blah blah blah"));
});
TabItem::new(im_str!("Cucumber")).build(&ui, || {
ui.text(im_str!("This is the Cucumber tab!"));
ui.text(im_str!("blah blah blah blah blah"));
});
});
});
Window::new(im_str!("Collapsing Header"))
.size([300.0, HEIGHT], Condition::FirstUseEver)
.position([100.0, Y_OFFSET * 3.0], Condition::FirstUseEver)
.build(ui, || {
if CollapsingHeader::new(im_str!("Window options")).build(&ui) {
ui.checkbox(im_str!("Is it checked?"), &mut state.checked);
ui.input_text_multiline(im_str!("multiline"), &mut state.text, [300., 100.])
.build();
}
});
Window::new(im_str!("Inputs"))
.always_auto_resize(true)
.position([100.0, Y_OFFSET * 4.0], Condition::FirstUseEver)
.build(ui, || {
ui.checkbox(im_str!("Is it checked?"), &mut state.checked);
ui.input_text_multiline(im_str!("multiline"), &mut state.text, [300., 100.])
.build();
TreeNode::new(im_str!("Modals")).build(&ui, || {
ui.checkbox(im_str!("Is it checked (again)?"), &mut state.checked);
});
});
Window::new(im_str!("Logging example"))
.size([400.0, HEIGHT * 6.0], Condition::FirstUseEver)
.position([100.0 + X_OFFSET, Y_OFFSET], Condition::FirstUseEver)
.build(ui, || {
ChildWindow::new("Options")
.size([0.0, 70.0])
.border(true)
.build(ui, || {
ui.input_text(im_str!("Filter"), &mut state.filter_curr)
.build();
ui.checkbox(im_str!("Scroll to end"), &mut state.scroll_to_end);
// Save state
state.has_filter = !state.filter_curr.to_string().is_empty();
});
ChildWindow::new("Logs").border(false).build(ui, || {
if state.has_filter {
let query = state.filter_curr.to_string();
let result = lines
.iter()
.filter(|x| x.contains(&query))
.collect::<Vec<_>>();
clipper(ui, result.len(), |range| {
for i in range.start..range.end {
let line = &result[i];
ui.text(format!("{} contains {}", line, state.filter_curr));
}
});
} else {
clipper(ui, lines.len(), |range| {
for i in range.start..range.end {
let line = &lines[i];
ui.text(format!("-> {}", line));
}
});
};
if state.scroll_to_end {
if line_num > 10 {
unsafe {
imgui_sys::igSetScrollY(
ui.text_line_height_with_spacing() * (line_num - 1) as f32,
);
}
}
}
});
});
});
}
|
mod dnstunbuilder;
pub use dnstunbuilder::*;
mod forwarder;
pub use forwarder::*;
mod udpserv;
pub use udpserv::*;
mod dnstunnel;
pub use dnstunnel::*;
mod domap;
pub use domap::*;
mod dnspacket;
pub use dnspacket::*;
mod lresolver;
pub use lresolver::*;
mod netlink;
pub use netlink::*;
mod mydns;
pub use mydns::*;
|
use ring::{digest};
use crate::base::crypto::ripemd160::JRipemd160;
use crate::wallet::keypair::*;
use crate::wallet::generate_str;
use crate::base::xcodec::{is_valid_address};
use hex;
static H_ADDRESS: &[u8] = &[0];
#[derive(Debug)]
pub struct WalletAddress {}
impl WalletAddress {
pub fn build(key_pair: &Keypair) -> String {
WalletAddressBuilder::new(&key_pair).build()
}
//Codes-x
pub fn check_address(address: &String) -> Option<bool> {
is_valid_address(address)
}
}
#[derive(Debug)]
pub struct WalletAddressBuilder <'a> {
pub key_pair: &'a Keypair,
}
impl <'a> WalletAddressBuilder <'a> {
pub fn new(key_pair: &'a Keypair) -> Self {
WalletAddressBuilder {
key_pair: key_pair,
}
}
pub fn build(&self) -> String {
self.generate()
}
pub fn generate(&self) -> String {
let key: Vec<u8> = hex::decode(&self.key_pair.public_key).unwrap();
let mut ctx = digest::Context::new(&digest::SHA256);
ctx.update(&key);
let mut input = [0u8; 32];
input.copy_from_slice(ctx.finish().as_ref());
let mut ripemd160 = JRipemd160::new();
ripemd160.input(&input);
let ret: &mut [u8] = &mut [0u8;20];
ripemd160.result(ret);
let mut version: Vec<u8> = H_ADDRESS.to_vec();
generate_str(&mut version, &ret.to_vec())
}
}
|
use std::convert::{TryFrom, TryInto};
use std::slice;
pub type ItemCode = String;
pub type LocationCode = String;
pub type Quantity = u32;
pub type StockId = (ItemCode, LocationCode);
pub type StockMoveId = String;
pub trait Command<S, E> {
fn handle(&self, state: S) -> Option<E>;
}
pub trait Event<S> {
fn apply(&self, state: S) -> Option<S>;
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum Stock {
Managed { id: StockId, qty: Quantity, assigned: Quantity },
Unmanaged { id: StockId },
}
#[allow(dead_code)]
impl Stock {
pub fn managed_new(item: ItemCode, location: LocationCode) -> Self {
Self::Managed { id: (item, location), qty: 0, assigned: 0 }
}
pub fn unmanaged_new(item: ItemCode, location: LocationCode) -> Self {
Self::Unmanaged { id: (item, location) }
}
pub fn eq_id(&self, item: &ItemCode, location: &LocationCode) -> bool {
match self {
Self::Managed { id, .. } | Self::Unmanaged { id } =>
id.clone() == (item.clone(), location.clone())
}
}
pub fn is_sufficient(&self, v: Quantity) -> bool {
match self {
Self::Managed { qty, assigned, .. } =>
v + assigned <= qty.clone(),
Self::Unmanaged { .. } => true,
}
}
fn update(&self, qty: Quantity, assigned: Quantity) -> Self {
match self {
Self::Managed { id, .. } => {
Self::Managed {
id: id.clone(),
qty: qty,
assigned: assigned,
}
},
Self::Unmanaged { .. } => self.clone(),
}
}
pub(super) fn update_qty(&self, qty: Quantity) -> Self {
match self {
Self::Managed { assigned, .. } => self.update(qty, assigned.clone()),
Self::Unmanaged { .. } => self.clone(),
}
}
fn update_assigned(&self, assigned: Quantity) -> Self {
match self {
Self::Managed { qty, .. } => self.update(qty.clone(), assigned),
Self::Unmanaged { .. } => self.clone(),
}
}
}
#[derive(Debug, Default, Clone, PartialEq)]
pub struct StockMoveInfo {
item: ItemCode,
qty: Quantity,
from: LocationCode,
to: LocationCode,
}
#[derive(Debug, Clone, PartialEq)]
pub enum StockMove {
Nothing,
Draft { id: StockMoveId, info: StockMoveInfo },
Assigned { id: StockMoveId, info: StockMoveInfo,
assigned: Quantity },
Shipped { id: StockMoveId, info: StockMoveInfo,
outgoing: Quantity },
Arrived { id: StockMoveId, info: StockMoveInfo,
incoming: Quantity },
Cancelled { id: StockMoveId, info: StockMoveInfo },
AssignFailed { id: StockMoveId, info: StockMoveInfo },
ShipmentFailed { id: StockMoveId, info: StockMoveInfo },
}
impl StockMove {
fn info(&self) -> Option<StockMoveInfo> {
match self {
Self::Draft { info, .. } |
Self::Assigned { info, .. } |
Self::Shipped { info, .. } |
Self::Arrived { info, .. } |
Self::Cancelled { info, .. } |
Self::AssignFailed { info, .. } |
Self::ShipmentFailed { info, .. } => Some(info.clone()),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StartCommand {
move_id: StockMoveId,
item: ItemCode,
qty: Quantity,
from: LocationCode,
to: LocationCode,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AssignCommand {
move_id: StockMoveId,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CancelCommand {
move_id: StockMoveId,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ShipmentReport {
move_id: StockMoveId,
outgoing: Quantity,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ShipmentFailureReport {
move_id: StockMoveId,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ArrivalReport {
move_id: StockMoveId,
incoming: Quantity,
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub enum StockMoveAction {
Start(StartCommand),
Assign(AssignCommand),
Cancel(CancelCommand),
Shipment(ShipmentReport),
ShipmentFailure(ShipmentFailureReport),
Arrival(ArrivalReport),
}
#[allow(dead_code)]
impl StockMoveAction {
pub fn start(move_id: StockMoveId, item: ItemCode, qty: Quantity, from: LocationCode, to: LocationCode) -> Option<Self> {
if qty > 0 {
Some(
Self::Start(StartCommand { move_id, item, qty, from, to })
)
} else {
None
}
}
pub fn assign(move_id: StockMoveId) -> Option<Self> {
Some(Self::Assign(AssignCommand { move_id }))
}
pub fn cancel(move_id: StockMoveId) -> Option<Self> {
Some(Self::Cancel(CancelCommand { move_id }))
}
pub fn shipment(move_id: StockMoveId, qty: Quantity) -> Option<Self> {
if qty > 0 {
Some(Self::Shipment(ShipmentReport { move_id, outgoing: qty }))
} else {
None
}
}
pub fn shipment_failure(move_id: StockMoveId) -> Option<Self> {
Some(Self::ShipmentFailure(ShipmentFailureReport { move_id }))
}
pub fn arrival(move_id: StockMoveId, qty: Quantity) -> Option<Self> {
Some(Self::Arrival(ArrivalReport { move_id, incoming: qty }))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StartedEvent {
move_id: StockMoveId,
item: ItemCode,
qty: Quantity,
from: LocationCode,
to: LocationCode,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AssignedEvent {
move_id: StockMoveId,
item: ItemCode,
from: LocationCode,
assigned: Quantity,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ShippedEvent {
move_id: StockMoveId,
item: ItemCode,
from: LocationCode,
outgoing: Quantity,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AssignShippedEvent {
move_id: StockMoveId,
item: ItemCode,
from: LocationCode,
outgoing: Quantity,
assigned: Quantity,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ArrivedEvent {
move_id: StockMoveId,
item: ItemCode,
to: LocationCode,
incoming: Quantity,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CancelledEvent {
move_id: StockMoveId,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AssignFailedEvent {
move_id: StockMoveId,
item: ItemCode,
qty: Quantity,
from: LocationCode,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ShipmentFailedEvent {
move_id: StockMoveId,
item: ItemCode,
qty: Quantity,
from: LocationCode,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AssignShipmentFailedEvent {
move_id: StockMoveId,
item: ItemCode,
qty: Quantity,
from: LocationCode,
assigned: Quantity,
}
#[derive(Debug, Clone, PartialEq)]
pub enum StockMoveEvent {
Started(StartedEvent),
Assigned(AssignedEvent),
Shipped(ShippedEvent),
AssignShipped(AssignShippedEvent),
Arrived(ArrivedEvent),
Cancelled(CancelledEvent),
AssignFailed(AssignFailedEvent),
ShipmentFailed(ShipmentFailedEvent),
AssignShipmentFailed(AssignShipmentFailedEvent),
}
impl TryFrom<(&StartCommand, &StockMove)> for StockMoveEvent {
type Error = ();
fn try_from(v: (&StartCommand, &StockMove)) -> Result<Self, Self::Error> {
let (cmd, state) = v;
if *state == StockMove::Nothing {
Ok(
StockMoveEvent::Started(
StartedEvent {
move_id: cmd.move_id.clone(),
item: cmd.item.clone(),
qty: cmd.qty.clone(),
from: cmd.from.clone(),
to: cmd.to.clone(),
}
)
)
} else {
Err(())
}
}
}
impl TryFrom<(&CancelCommand, &StockMove)> for StockMoveEvent {
type Error = ();
fn try_from(v: (&CancelCommand, &StockMove)) -> Result<Self, Self::Error> {
let (cmd, state) = v;
match state {
StockMove::Draft { id, .. } if cmd.move_id == id.clone() => {
Ok(
StockMoveEvent::Cancelled(
CancelledEvent { move_id: cmd.move_id.clone() }
)
)
},
_ => Err(()),
}
}
}
impl TryFrom<(&AssignCommand, &StockMove, &Stock)> for StockMoveEvent {
type Error = ();
fn try_from(v: (&AssignCommand, &StockMove, &Stock)) -> Result<Self, Self::Error> {
let (cmd, state, stock) = v;
match state {
StockMove::Draft { id, info, .. } if cmd.move_id == id.clone() => {
Some(stock)
.filter(|s| s.eq_id(&info.item, &info.from))
.map(|s|
if s.is_sufficient(info.qty) {
StockMoveEvent::Assigned(
AssignedEvent {
move_id: cmd.move_id.clone(),
item: info.item.clone(),
from: info.from.clone(),
assigned: info.qty.clone(),
}
)
} else {
StockMoveEvent::AssignFailed(
AssignFailedEvent {
move_id: cmd.move_id.clone(),
item: info.item.clone(),
qty: info.qty.clone(),
from: info.from.clone(),
}
)
}
).ok_or(())
},
_ => Err(()),
}
}
}
impl TryFrom<(&ShipmentReport, &StockMove)> for StockMoveEvent {
type Error = ();
fn try_from(v: (&ShipmentReport, &StockMove)) -> Result<Self, Self::Error> {
let (cmd, state) = v;
match state {
StockMove::Draft { id, info, .. } if cmd.move_id == id.clone() => {
Ok(
StockMoveEvent::Shipped(
ShippedEvent {
move_id: cmd.move_id.clone(),
item: info.item.clone(),
from: info.from.clone(),
outgoing: cmd.outgoing.clone(),
}
)
)
},
StockMove::Assigned { id, info, assigned } if cmd.move_id == id.clone() => {
Ok(
StockMoveEvent::AssignShipped(
AssignShippedEvent {
move_id: cmd.move_id.clone(),
item: info.item.clone(),
from: info.from.clone(),
outgoing: cmd.outgoing.clone(),
assigned: assigned.clone(),
}
)
)
},
_ => Err(()),
}
}
}
impl TryFrom<(&ShipmentFailureReport, &StockMove)> for StockMoveEvent {
type Error = ();
fn try_from(v: (&ShipmentFailureReport, &StockMove)) -> Result<Self, Self::Error> {
let (cmd, state) = v;
match state {
StockMove::Draft { id, info, .. } if cmd.move_id == id.clone() => {
Ok(
StockMoveEvent::ShipmentFailed(
ShipmentFailedEvent {
move_id: cmd.move_id.clone(),
item: info.item.clone(),
qty: info.qty.clone(),
from: info.from.clone(),
}
)
)
},
StockMove::Assigned { id, info, assigned } if cmd.move_id == id.clone() => {
Ok(
StockMoveEvent::AssignShipmentFailed(
AssignShipmentFailedEvent {
move_id: cmd.move_id.clone(),
item: info.item.clone(),
qty: info.qty.clone(),
from: info.from.clone(),
assigned: assigned.clone(),
}
)
)
},
_ => Err(()),
}
}
}
impl TryFrom<(&ArrivalReport, &StockMove)> for StockMoveEvent {
type Error = ();
fn try_from(v: (&ArrivalReport, &StockMove)) -> Result<Self, Self::Error> {
let (cmd, state) = v;
match state {
StockMove::Draft { id, info, .. } |
StockMove::Shipped { id, info, .. }
if cmd.move_id == id.clone() => {
Ok(
StockMoveEvent::Arrived(
ArrivedEvent {
move_id: cmd.move_id.clone(),
item: info.item.clone(),
to: info.to.clone(),
incoming: cmd.incoming.clone(),
}
)
)
},
_ => Err(()),
}
}
}
impl Event<StockMove> for StartedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Nothing =>
Some(
StockMove::Draft {
id: self.move_id.clone(),
info: StockMoveInfo {
item: self.item.clone(),
qty: self.qty.clone(),
from: self.from.clone(),
to: self.to.clone(),
},
}
),
_ => None,
}
}
}
impl Event<StockMove> for AssignedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Draft { id, info }
if id == self.move_id && info.item == self.item.clone() =>
Some(
StockMove::Assigned {
id,
info,
assigned: self.assigned,
}
),
_ => None,
}
}
}
impl Event<StockMove> for ShippedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Draft { id, info }
if id == self.move_id && info.item == self.item.clone() =>
Some(
StockMove::Shipped {
id,
info,
outgoing: self.outgoing,
}
),
_ => None,
}
}
}
impl Event<StockMove> for AssignShippedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Assigned { id, info, assigned }
if id == self.move_id &&
info.item == self.item.clone() &&
assigned == self.assigned =>
Some(
StockMove::Shipped {
id,
info,
outgoing: self.outgoing,
}
),
_ => None,
}
}
}
impl Event<StockMove> for ArrivedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Draft { id, info } |
StockMove::Shipped { id, info, .. }
if id == self.move_id && info.item == self.item.clone() =>
Some(
StockMove::Arrived {
id,
info,
incoming: self.incoming,
}
),
_ => None,
}
}
}
impl Event<StockMove> for CancelledEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Draft { id, info } if id == self.move_id =>
Some(
StockMove::Cancelled { id, info }
),
_ => None,
}
}
}
impl Event<StockMove> for AssignFailedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Draft { id, info } if id == self.move_id =>
Some(
StockMove::AssignFailed { id, info }
),
_ => None,
}
}
}
impl Event<StockMove> for ShipmentFailedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Draft { id, info } if id == self.move_id =>
Some(
StockMove::ShipmentFailed { id, info }
),
_ => None,
}
}
}
impl Event<StockMove> for AssignShipmentFailedEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match state {
StockMove::Assigned { id, info, assigned }
if id == self.move_id &&
info.item == self.item.clone() &&
assigned == self.assigned.clone() =>
Some(
StockMove::ShipmentFailed { id, info }
),
_ => None,
}
}
}
impl Event<StockMove> for StockMoveEvent {
fn apply(&self, state: StockMove) -> Option<StockMove> {
match self {
StockMoveEvent::Started(d) => d.apply(state),
StockMoveEvent::Assigned(d) => d.apply(state),
StockMoveEvent::Shipped(d) => d.apply(state),
StockMoveEvent::AssignShipped(d) => d.apply(state),
StockMoveEvent::Arrived(d) => d.apply(state),
StockMoveEvent::Cancelled(d) => d.apply(state),
StockMoveEvent::AssignFailed(d) => d.apply(state),
StockMoveEvent::ShipmentFailed(d) => d.apply(state),
StockMoveEvent::AssignShipmentFailed(d) => d.apply(state),
}
}
}
pub trait Action<C, E> {
fn action(&self, cmd: C) -> Option<E>;
}
pub trait Restore<E> {
fn restore(self, events: slice::Iter<E>) -> Self;
}
impl<T> Action<&StockMoveAction, StockMoveEvent> for (StockMove, T)
where
T: Fn(ItemCode, LocationCode) -> Option<Stock>,
{
fn action(&self, cmd: &StockMoveAction) -> Option<StockMoveEvent> {
let (state, find) = self;
match cmd {
StockMoveAction::Start(d) => (d, state).try_into().ok(),
StockMoveAction::Assign(d) => {
state.info()
.and_then(|info| find(info.item, info.from))
.and_then(|stock| (d, state, &stock).try_into().ok())
},
StockMoveAction::Cancel(d) => (d, state).try_into().ok(),
StockMoveAction::Shipment(d) => (d, state).try_into().ok(),
StockMoveAction::ShipmentFailure(d) => (d, state).try_into().ok(),
StockMoveAction::Arrival(d) => (d, state).try_into().ok(),
}
}
}
impl Restore<&StockMoveEvent> for StockMove {
fn restore(self, events: slice::Iter<&StockMoveEvent>) -> Self {
events.fold(self, |acc, ev| ev.apply(acc.clone()).unwrap_or(acc))
}
}
impl Event<Stock> for AssignedEvent {
fn apply(&self, state: Stock) -> Option<Stock> {
if state.eq_id(&self.item, &self.from) {
match state {
Stock::Managed { assigned, .. } => {
assigned.checked_add(self.assigned)
.or_else(|| Some(Quantity::MAX))
.map(|a| state.update_assigned(a))
},
Stock::Unmanaged { .. } => None,
}
} else {
None
}
}
}
impl Event<Stock> for ShippedEvent {
fn apply(&self, state: Stock) -> Option<Stock> {
if state.eq_id(&self.item, &self.from) {
match state {
Stock::Managed { qty, .. } => {
qty.checked_sub(self.outgoing)
.or_else(|| Some(0))
.map(|q| state.update_qty(q))
},
Stock::Unmanaged { .. } => None,
}
} else {
None
}
}
}
impl Event<Stock> for AssignShippedEvent {
fn apply(&self, state: Stock) -> Option<Stock> {
if state.eq_id(&self.item, &self.from) {
match state {
Stock::Managed { qty, assigned, .. } => {
let q = qty.checked_sub(self.outgoing).unwrap_or(0);
let a = assigned.checked_sub(self.assigned).unwrap_or(0);
Some(state.update(q, a))
},
Stock::Unmanaged { .. } => None,
}
} else {
None
}
}
}
impl Event<Stock> for ArrivedEvent {
fn apply(&self, state: Stock) -> Option<Stock> {
if state.eq_id(&self.item, &self.to) {
match state {
Stock::Managed { qty, .. } => {
qty.checked_add(self.incoming)
.or_else(|| Some(Quantity::MAX))
.map(|q| state.update_qty(q))
},
Stock::Unmanaged { .. } => None,
}
} else {
None
}
}
}
impl Event<Stock> for AssignShipmentFailedEvent {
fn apply(&self, state: Stock) -> Option<Stock> {
if state.eq_id(&self.item, &self.from) {
match state {
Stock::Managed { assigned, .. } => {
assigned.checked_sub(self.assigned)
.or_else(|| Some(0))
.map(|a| state.update_assigned(a))
},
Stock::Unmanaged { .. } => None,
}
} else {
None
}
}
}
impl Event<Stock> for StockMoveEvent {
fn apply(&self, state: Stock) -> Option<Stock> {
match self {
StockMoveEvent::Assigned(d) => d.apply(state),
StockMoveEvent::Shipped(d) => d.apply(state),
StockMoveEvent::AssignShipped(d) => d.apply(state),
StockMoveEvent::Arrived(d) => d.apply(state),
StockMoveEvent::AssignShipmentFailed(d) => d.apply(state),
_ => None,
}
}
}
impl Restore<&StockMoveEvent> for Stock {
fn restore(self, events: slice::Iter<&StockMoveEvent>) -> Self {
events.fold(self, |acc, ev| ev.apply(acc.clone()).unwrap_or(acc))
}
}
|
//! Functionality for registering an application with Discord so that Discord can
//! start it in the future eg. when the user accpets an invite to play the game
//! by another user
#[cfg_attr(target_os = "linux", path = "registration/linux.rs")]
#[cfg_attr(target_os = "windows", path = "registration/windows.rs")]
#[cfg_attr(target_os = "macos", path = "registration/mac.rs")]
mod registrar;
use crate::Error;
pub use registrar::register_app;
pub use url::Url;
#[derive(PartialEq)]
pub enum BinArg {
/// A placeholder token that will be filled with the url that was opened
Url,
/// Generic argument
Arg(String),
}
impl From<String> for BinArg {
fn from(s: String) -> Self {
Self::Arg(s)
}
}
pub enum LaunchCommand {
/// A URL
Url(Url),
/// A binary with optional args
Bin {
/// A full path or a name of a binary in PATH
path: std::path::PathBuf,
/// The arguments to pass
args: Vec<BinArg>,
},
/// A Steam game identifier
Steam(u32),
}
impl LaunchCommand {
pub fn current_exe(args: Vec<BinArg>) -> Result<Self, Error> {
let path = std::env::current_exe()
.map_err(|e| Error::io("retrieving current executable path", e))?;
if args.iter().filter(|a| **a == BinArg::Url).count() > 1 {
return Err(Error::TooManyUrls);
}
Ok(Self::Bin { path, args })
}
}
pub struct Application {
/// The application's unique Discord identifier
pub id: crate::AppId,
/// The application name, defaults to the id if not specified
pub name: Option<String>,
/// The command to launch the application itself.
pub command: LaunchCommand,
}
#[allow(unused)]
pub(crate) fn create_command(path: std::path::PathBuf, args: Vec<BinArg>, url_str: &str) -> String {
use std::fmt::Write;
let mut cmd = format!("\"{}\"", path.display());
for arg in args {
match arg {
BinArg::Url => write!(&mut cmd, " {}", url_str),
BinArg::Arg(s) => {
// Only handle spaces, if there are other whitespace characters
// well...
if s.contains(' ') {
write!(&mut cmd, " \"{}\"", s)
} else {
write!(&mut cmd, " {}", s)
}
}
}
.unwrap();
}
cmd
}
|
#![cfg_attr(feature = "strict", deny(warnings))]
use std::io::*;
pub struct MapInput {
pub height: u8,
pub width: u8,
pub map_input_string: String
}
pub fn get_map_input() -> MapInput {
let mut height_width_string = String::new();
let mut map_input_string = String::new();
print_prompt();
stdin().read_line(&mut height_width_string).unwrap();
height_width_string = height_width_string.trim_end().to_string();
let (height, width) = get_height_width(&mut height_width_string);
for _x in 0..height {
stdin().read_line(&mut map_input_string).unwrap();
map_input_string = map_input_string.trim_end().to_string();
}
MapInput { height, width, map_input_string }
}
fn print_prompt() {
println!("Enter your civilization below with the given format:");
println!("{{height}} {{width}}");
println!("{{civilization grid}}");
println!("Where the civilization grid marks dead cells with a period (.)");
println!("and living cells with a period (*)");
println!("");
println!("For example:");
println!("");
println!("5 8");
println!("........");
println!("...**...");
println!(".*****..");
println!("........");
println!("........");
println!("");
println!("");
println!("Entry:");
println!("");
}
fn get_height_width(input_string: &mut String) -> (u8, u8) {
let height_width_vec = input_string.split(" ").collect::<Vec<&str>>();
let height: u8 = height_width_vec[0].parse().unwrap();
let width: u8 = height_width_vec[1].parse().unwrap();
(height, width)
} |
// Simple S-expression reader library.
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
pub type Result = ::std::result::Result<Option<Datum>, ParseError>;
#[derive(Debug)]
pub struct ParseError {
pub msg: String,
pub line: usize
}
impl fmt::Display for ParseError
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: Parse error: {}", self.line, &self.msg)
}
}
impl Error for ParseError
{
fn description(&self) -> &str {
&self.msg
}
fn cause(&self) -> Option<&Error> {
None // This could be the io error when appropriate
}
}
#[derive(Clone,Debug)]
pub struct Cons(Rc<(Datum, Datum)>);
impl Cons
{
pub fn car(&self) -> &Datum {
&(self.0).0
}
pub fn cdr(&self) -> &Datum {
&(self.0).1
}
}
#[derive(Clone,Debug)]
pub struct Symbol(Rc<String>);
impl Symbol
{
pub fn eq(a: &Symbol, b: &Symbol) -> bool {
Rc::ptr_eq(&a.0, &b.0)
}
}
#[derive(Clone,Debug)]
pub struct Vector(Rc<Vec<Datum>>);
#[derive(Clone,Copy,Debug)]
pub enum Number
{
Flo(f64),
Fix(i64)
}
impl PartialEq for Number
{
// TODO: This is wrong, given that 1.0 != 1 due to representations...
fn eq(&self, other: &Number) -> bool {
match (self, other) {
(Number::Fix(x), Number::Fix(y)) => x == y,
(Number::Flo(x), Number::Flo(y)) => x == y,
(Number::Flo(_x), Number::Fix(_y)) => {
// if x is integer in range of i64 then x.as_int() == y else false
false
}
(Number::Fix(_x), Number::Flo(_y)) => {
// if y is integer in range of i64 then y.as_int() == x else false
false
}
}
}
}
#[derive(Clone,Debug)]
pub struct List(Rc<Vec<Datum>>);
const UNDEFINED:Datum = Datum::Undefined;
impl List
{
pub fn at(&self, n:usize) -> &Datum {
if n < self.0.len() {
&self.0[n]
} else {
&UNDEFINED
}
}
}
#[derive(Clone,Debug)]
pub enum Datum
{
Cons(Cons),
Nil,
List(List),
Undefined,
Number(Number),
Bool(bool),
Str(String),
Sym(Symbol),
Chr(char),
Vector(Vector),
}
impl Datum
{
pub fn eq_sym(&self, s:&Symbol) -> bool {
if let Datum::Sym(ref x) = self {
Symbol::eq(x, s)
} else {
false
}
}
pub fn eqv(a: &Datum, b:&Datum) -> bool {
match (a, b) {
(Datum::Nil, Datum::Nil) => true,
(Datum::Number(ref x), Datum::Number(ref y)) => x == y,
(Datum::Bool(x), Datum::Bool(y)) => x == y,
(Datum::Chr(x), Datum::Chr(y)) => x == y,
(Datum::Sym(ref x), Datum::Sym(ref y)) => Symbol::eq(x, y),
_ => false
}
}
}
pub struct Symtab(HashMap<String, Symbol>);
impl Symtab
{
pub fn new() -> Symtab
{
Symtab(HashMap::new())
}
pub fn intern(&mut self, name:&str) -> Symbol {
if let Some(s) = self.0.get(name) {
return s.clone();
}
self.do_intern(name.to_string())
}
pub fn intern_string(&mut self, name:String) -> Symbol
{
if let Some(s) = self.0.get(&name) {
return s.clone();
}
self.do_intern(name)
}
fn do_intern(&mut self, name:String) -> Symbol {
let sym = Symbol(Rc::new(name.clone()));
self.0.insert(name, sym.clone());
sym
}
}
pub type Input = Iterator<Item = std::io::Result<char>>;
pub struct Parser<'a> {
c0: char,
input: &'a mut Input,
syms: &'a mut Symtab,
line: usize,
use_cons: bool,
quote: Datum,
dot: Datum
}
const OOB : char = '\0';
type Res = ::std::result::Result<Datum, ParseError>;
impl<'a> Parser<'a>
{
/// If `use_cons` is true then lists allow dotted pairs, and will
/// be represented by Cons values. Otherwise, lists are
/// represented by List values, which are really vectors.
pub fn new(input: &'a mut Input, symtab: &'a mut Symtab, use_cons: bool) -> Parser<'a>
{
let quote_sym = symtab.intern("quote");
let dot_sym = symtab.intern(".");
let mut parser = Parser {
c0: OOB,
input: input,
syms: symtab,
line: 1,
use_cons,
quote: Datum::Sym(quote_sym),
dot: Datum::Sym(dot_sym)
};
parser.next();
parser
}
pub fn parse(&mut self) -> Result
{
self.eat_whitespace_and_comment();
if self.peek() == OOB {
Ok(None)
} else {
match self.parse_datum_nodot() {
Ok(x) => Ok(Some(x)),
Err(e) => Err(e)
}
}
}
fn fail(&self, s: &str) -> Res {
Err(ParseError{ msg: s.to_string(), line: self.line })
}
fn fails(&self, s: String) -> Res {
Err(ParseError{ msg: s, line: self.line })
}
// Precondition: we have just called eat_whitespace_and_comment().
fn parse_datum(&mut self) -> Res
{
return match self.peek() {
OOB => self.fail("Unexpected EOF"),
'(' => self.parse_list(),
'#' => self.parse_sharp(),
'"' => self.parse_string(),
'\'' => self.parse_quote(),
c if is_symbol_or_number_initial(c)
=> self.parse_symbol_or_number(),
_ => self.fails(format!("Unknown character {}", self.peek()))
}
}
fn parse_datum_nodot(&mut self) -> Res
{
let datum = self.parse_datum()?;
if Datum::eqv(&datum, &self.dot) {
self.fail("Illegal dot symbol")
} else {
Ok(datum)
}
}
fn parse_list(&mut self) -> Res
{
let mut data = vec![];
let mut last = Datum::Nil;
self.must_eat('(');
loop {
self.eat_whitespace_and_comment();
if self.peek() == ')' {
break;
}
let datum = self.parse_datum()?;
if Datum::eqv(&datum, &self.dot) {
if !self.use_cons {
return self.fail("Illegal dotted pair")
}
self.eat_whitespace_and_comment();
last = self.parse_datum_nodot()?;
self.eat_whitespace_and_comment();
break;
}
data.push(datum);
}
self.must_eat(')');
if self.use_cons {
let mut result = last;
for d in data {
result = cons(d, result);
}
Ok(result)
} else {
Ok(Datum::List(List(Rc::new(data))))
}
}
fn parse_vector(&mut self) -> Res
{
let mut data = vec![];
self.must_eat('(');
loop {
self.eat_whitespace_and_comment();
if self.peek() == ')' {
break;
}
data.push(self.parse_datum_nodot()?);
}
self.must_eat(')');
Ok(Datum::Vector(Vector(Rc::new(data))))
}
fn parse_quote(&mut self) -> Res
{
self.must_eat('\'');
self.eat_whitespace_and_comment();
let d = self.parse_datum_nodot()?;
Ok(cons(self.quote.clone(), cons(d, Datum::Nil)))
}
fn parse_sharp(&mut self) -> Res
{
self.must_eat('#');
match self.peek() {
't' => { self.next(); Ok(Datum::Bool(true)) },
'f' => { self.next(); Ok(Datum::Bool(false)) },
'(' => { self.parse_vector() }
_ => { self.fail("Bad sharp sequence") }
}
}
fn parse_string(&mut self) -> Res
{
self.must_eat('"');
let mut s = String::new();
loop {
match self.get() {
'\\' => {
s.push(match self.get() {
'n' => '\n',
'r' => '\r',
't' => '\t',
OOB => { return self.fail("EOF in string") },
c => c
})
}
'"' => { break; }
OOB => { return self.fail("EOF in string") }
c => { s.push(c); }
}
}
Ok(Datum::Str(s))
}
fn parse_symbol_or_number(&mut self) -> Res
{
let mut name = Vec::new();
name.push(self.get());
while is_symbol_or_number_subsequent(self.peek()) {
name.push(self.get());
}
let (is_number, is_integer) = is_number_syntax(&name);
let name_str: String = name.into_iter().collect();
if is_number {
if is_integer {
Ok(Datum::Number(Number::Fix(i64::from_str(&name_str).unwrap()))) // TODO: Range error?
} else {
Ok(Datum::Number(Number::Flo(f64::from_str(&name_str).unwrap()))) // TODO: Range error?
}
} else {
Ok(Datum::Sym(self.syms.intern_string(name_str)))
}
}
fn eat_whitespace_and_comment(&mut self)
{
loop {
match self.peek() {
' ' | '\t'
=> { self.next(); }
'\r'
=> { self.line += 1; self.next();
if self.peek() == '\n' {
self.next();
}
}
'\n'
=> { self.line += 1; self.next(); }
';'
=> { self.next();
loop {
match self.peek() {
OOB | '\r' | '\n' => { break; }
_ => { self.next() }
}
}
}
_
=> { return; }
}
}
}
fn peek(&self) -> char
{
self.c0
}
fn get(&mut self) -> char
{
let c = self.c0;
self.next();
c
}
fn next(&mut self)
{
self.c0 = self.getchar();
}
fn must_eat(&mut self, c:char)
{
if self.peek() != c {
panic!("Required '{}' but did not see it", c);
}
self.next();
}
fn getchar(&mut self) -> char
{
match self.input.next() {
None => { OOB },
Some(Err(e)) => { panic!("i/o error {}", e) },
Some(Ok(c)) => { c }
}
}
}
fn cons(a: Datum, b: Datum) -> Datum
{
Datum::Cons(Cons(Rc::new((a,b))))
}
fn is_digit(c:char) -> bool
{
match c {
'0'...'9' => true,
_ => false
}
}
fn is_symbol_initial(c:char) -> bool
{
match c {
'a'...'z' | 'A'...'Z' | '~' | '!' | '@' | '$' | '%' | '^' | '&' | '*' | '_' | '-' | '+' | '=' |
':' | '<' | ',' | '>' | '?' | '/'
=> true,
_ => false
}
}
fn is_symbol_or_number_initial(c:char) -> bool
{
is_symbol_initial(c) || is_digit(c) || c == '.'
}
fn is_symbol_or_number_subsequent(c:char) -> bool
{
is_symbol_initial(c) || is_digit(c) || c == '.' || c == '#'
}
fn is_number_syntax(s:&Vec<char>) -> (bool, bool)
{
let mut i = 0;
macro_rules! digits {
() => {{
let p = i;
while i < s.len() && is_digit(s[i]) {
i += 1;
}
i > p
}}
}
macro_rules! opt_sign {
() => {
if i < s.len() && (s[i] == '+' || s[i] == '-') {
i += 1;
}
}
}
opt_sign!();
let hasint = digits!();
let mut hasfrac = false;
if i < s.len() && s[i] == '.' {
i += 1;
hasfrac = digits!();
if !hasfrac {
return (false, false);
}
}
if i < s.len() && (s[i] == 'e' || s[i] == 'E') {
i += 1;
opt_sign!();
hasfrac = digits!();
if !hasfrac {
return (false, false);
}
}
let is_number = i == s.len() && (hasint || hasfrac);
if is_number {
(true, !hasfrac)
} else {
(false, false)
}
}
extern crate unicode_reader;
#[test]
fn test_generic()
{
use unicode_reader::CodePoints;
let mut syms = Symtab::new();
let hi = Datum::Sym(syms.intern("hi"));
let ho = Datum::Sym(syms.intern("ho"));
let mut input = CodePoints::from(" hi ho(37)".as_bytes());
let mut parser = Parser::new(&mut input, &mut syms, true);
assert_eq!(Datum::eqv(&parser.parse().unwrap().unwrap(), &hi), true);
assert_eq!(Datum::eqv(&parser.parse().unwrap().unwrap(), &ho), true);
let d = &parser.parse().unwrap().unwrap();
if let Datum::Cons(ref c) = d {
if let Datum::Number(ref n) = c.car() {
assert_eq!(n == &Number::Fix(37), true);
}
assert_eq!(if let Datum::Nil = c.cdr() { true } else { false }, true);
} else {
panic!("Bad result {:?}", d)
}
}
|
use errors::*;
use types::Client;
use network::get;
use serde_json;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Version {
pub version: String,
pub os: String,
pub kernel_version: String,
pub go_version: String,
pub git_commit: String,
pub arch: String,
pub api_version: String,
#[serde(rename(deserialize = "MinAPIVersion"))]
pub min_api_version: String,
pub build_time: String,
}
pub fn version(client: Client) -> Result<Version> {
let response = get(client, "/version").chain_err(|| "Failed to get engine version")?;
if response.status_code != 200 {
bail!("non-200 response from server");
}
let version: Version =
serde_json::from_str(&response.body).chain_err(|| "Failed to deserialize engine response")?;
Ok(version)
}
pub fn ping(client: Client) -> Result<()> {
let response = get(client, "/_ping").chain_err(|| "Failed to ping engine")?;
if response.status_code != 200 {
bail!("non-200 response from engine");
}
if response.body != "OK" {
bail!("Malformed response from engine");
}
Ok(())
}
|
use crate::{FunctionData, Instruction, IntPredicate};
pub struct SimplifyComparesPass;
impl super::Pass for SimplifyComparesPass {
fn name(&self) -> &str {
"compare simplification"
}
fn time(&self) -> crate::timing::TimedBlock {
crate::timing::simplify_compares()
}
fn run_on_function(&self, function: &mut FunctionData) -> bool {
let labels = function.reachable_labels();
let creators = function.value_creators_with_labels(&labels);
let consts = function.constant_values_with_labels(&labels);
let mut replacements = Vec::new();
// Code generators will often emit sequence of `cmp`, `select`, `cmp`.
// This pass will try to detect it and optimize it to a single `cmp` if possible.
//
// v2 = u32 0
// v4 = cmp eq u32 v0, v2
// v5 = u8 0
// v6 = u8 1
// v7 = select u1 v4, u8 v6, v5
// v9 = cmp ne u8 v7, v5
// bcond u1 v9, label_2, label_3
//
// Gets optimized to:
// v2 = u32 0
// v4 = cmp eq u32 v0, v2
// bcond u1 v4, label_2, label_3
function.for_each_instruction_with_labels(&labels, |location, instruction| {
// Try to match on SECOND `cmp` of `cmp`, `select`, `cmp` sequence.
if let Instruction::IntCompare { dst, a, pred, b } = instruction {
let mut a = a;
let mut b = b;
// Try this optimization two times. First time with operands (A, B),
// second time with operands (B, A). Because we only do this on EQ and NE,
// order doesn't matter.
for _ in 0..2 {
// Left side of `cmp` must be a value created by `select` instruction.
// Right side of `cmp` must be a known constant.
let aa = creators.get(&a).map(|location| function.instruction(*location));
let bb = consts.get(&b);
// Check if requirements above are actually met.
if let (Some(Instruction::Select { cond, on_true, on_false, .. }),
Some((_, value))) = (aa, bb) {
let new_on_true;
let new_on_false;
// `select` operands must be known constants too.
if let (Some((_, on_true)), Some((_, on_false))) = (consts.get(on_true),
consts.get(on_false)) {
new_on_true = on_true;
new_on_false = on_false;
} else {
return;
}
let on_true = new_on_true;
let on_false = new_on_false;
// If select true value is the same as false value then `select`
// instruction can be optimized out. Other optimization pass
// will take care of it.
if on_true == on_false {
return;
}
// Get the corelation betwen first `cmp` and second `cmp`.
// There can be 3 cases:
// 1. second `cmp` result == first `cmp` result.
// 2. second `cmp` result == !first `cmp` result.
// 3. `cmps` are not corelated (in this case we exit).
// For simplicity we only handle EQ and NE predicates in the second `cmp`.
let result = match *pred {
IntPredicate::Equal => {
if on_true == value {
Some(false)
} else if on_false == value {
Some(true)
} else {
None
}
}
IntPredicate::NotEqual => {
if on_false == value {
Some(false)
} else if on_true == value {
Some(true)
} else {
None
}
}
_ => return,
};
// We know that both `cmps` are corelated with each other.
let mut new_instruction = None;
if let Some(inverted) = result {
if !inverted {
// If second `cmp` result == first `cmp` result than
// we will just alias second `cmp` result to first one's result.
new_instruction = Some(Instruction::Alias {
dst: *dst,
value: *cond,
});
} else {
// If `cmp` results are inverted than we want to replace second
// `cmp` with inverted copy of the first one.
let parent_compare = creators.get(&cond).map(|location| {
function.instruction(*location)
});
if let Some(&Instruction::IntCompare { a, pred, b, .. })
= parent_compare
{
// Change this instruction to inverted version of the
// first `cmp`.
new_instruction = Some(Instruction::IntCompare {
dst: *dst,
a,
pred: pred.invert(),
b,
});
}
}
}
if let Some(new_instruction) = new_instruction {
replacements.push((location, new_instruction));
}
} else {
// First try failed, swap operands and try again.
std::mem::swap(&mut a, &mut b);
continue;
}
// Optimization succeded.
break;
}
}
});
let did_something = !replacements.is_empty();
// Actually perform the replacements.
for (location, replacement) in replacements {
*function.instruction_mut(location) = replacement;
}
did_something
}
}
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Tidy checks source code in this repository
//!
//! This program runs all of the various tidy checks for style, cleanliness,
//! etc. This is run by default on `make check` and as part of the auto
//! builders.
#![deny(warnings)]
extern crate tidy;
use tidy::*;
use std::process;
use std::path::PathBuf;
use std::env;
fn main() {
let path = env::args_os().skip(1).next().expect("need path to src");
let path = PathBuf::from(path);
let cargo = env::args_os().skip(2).next().expect("need path to cargo");
let cargo = PathBuf::from(cargo);
let args: Vec<String> = env::args().skip(1).collect();
let mut bad = false;
let quiet = args.iter().any(|s| *s == "--quiet");
bins::check(&path, &mut bad);
style::check(&path, &mut bad);
errors::check(&path, &mut bad);
cargo::check(&path, &mut bad);
features::check(&path, &mut bad, quiet);
pal::check(&path, &mut bad);
unstable_book::check(&path, &mut bad);
libcoretest::check(&path, &mut bad);
if !args.iter().any(|s| *s == "--no-vendor") {
deps::check(&path, &mut bad);
}
deps::check_whitelist(&path, &cargo, &mut bad);
extdeps::check(&path, &mut bad);
ui_tests::check(&path, &mut bad);
if bad {
eprintln!("some tidy checks failed");
process::exit(1);
}
}
|
use std::error::Error;
use std::fmt;
#[derive(Debug, Clone)]
pub struct PngError {
description: String,
}
impl Error for PngError {
#[inline]
fn description(&self) -> &str {
&self.description
}
}
impl fmt::Display for PngError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description)
}
}
impl PngError {
#[inline]
pub fn new(description: &str) -> PngError {
PngError {
description: description.to_owned(),
}
}
}
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(raw_identifiers)]
#[derive(Debug, PartialEq, Eq)]
struct IntWrapper(u32);
#[derive(Debug, Ord, PartialOrd, PartialEq, Eq, Hash, Copy, Clone, Default)]
struct HasKeywordField {
r#struct: u32,
}
struct Generic<r#T>(T);
trait Trait {
fn r#trait(&self) -> u32;
}
impl Trait for Generic<u32> {
fn r#trait(&self) -> u32 {
self.0
}
}
pub fn main() {
assert_eq!(IntWrapper(1), r#IntWrapper(1));
match IntWrapper(2) {
r#IntWrapper(r#struct) => assert_eq!(2, r#struct),
}
assert_eq!("HasKeywordField { struct: 3 }", format!("{:?}", HasKeywordField { r#struct: 3 }));
assert_eq!(4, Generic(4).0);
assert_eq!(5, Generic(5).r#trait());
}
|
#[allow(unused_imports)]
use proconio::{
input, fastout,
};
fn solve(a: usize) -> usize {
a + a.pow(2) + a.pow(3)
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
input! {
a: usize,
}
println!("{}", solve(a));
Ok(())
}
fn main() {
match run() {
Err(err) => panic!("{}", err),
_ => (),
};
}
|
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::time::Duration;
use log::{debug, info, warn};
use reqwest::{Client as HttpClient, ClientBuilder, RequestBuilder};
use serde::{Deserialize, Serialize};
const NOMAD_AUTH_HEADER: &str = "X-Nomad-Token";
const NOMAD_INDEX_HEADER: &str = "X-Nomad-Index";
/// Nomad API Client
#[derive(Clone, Debug)]
pub struct Client {
address: String,
token: Option<crate::Secret>,
client: HttpClient,
}
/// Node details in List of nodes
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct NodesInList {
pub address: String,
pub datacenter: String,
pub drain: bool,
#[serde(rename = "ID")]
pub id: String,
pub name: String,
pub status: NodeStatus,
pub node_class: String,
pub scheduling_eligibility: NodeEligibility,
pub version: String,
pub modify_index: u128,
pub status_description: String,
#[cfg(all_node_details)]
pub drivers: HashMap<String, DriverInfo>,
}
/// Node Data returned from Nomad API
///
/// [Reference](https://github.com/hashicorp/nomad-java-sdk/blob/master/sdk/src/main/java/com/hashicorp/nomad/apimodel/Node.java)
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Node {
/// ID of the node
#[serde(rename = "ID")]
pub id: String,
/// Name of the Node
pub name: String,
/// Attributes for the node
pub attributes: HashMap<String, String>,
/// Computed class of the node
pub computed_class: String,
/// Create index
pub create_index: u128,
/// Data centre the node is in
pub datacenter: String,
/// Whether the node is in a draining state
pub drain: bool,
/// Strategy in which the node is draining
#[serde(default)]
pub drain_strategy: Option<DrainStrategy>,
/// HTTP Address
#[serde(rename = "HTTPAddr")]
pub http_address: String,
/// Modify Index
pub modify_index: u128,
/// Scheduling Eligiblity
pub scheduling_eligibility: NodeEligibility,
/// Secret ID
#[serde(rename = "SecretID")]
pub secret_id: String,
/// Status
pub status: NodeStatus,
/// Status Description
pub status_description: String,
/// Time status was updated
pub status_updated_at: u64,
/// Whether TLS is enabled
#[serde(rename = "TLSEnabled")]
tls_enabled: bool,
/// Class of Node
pub node_class: Option<String>,
/// Drivers information
#[serde(default)]
#[cfg(all_node_details)]
pub drivers: HashMap<String, DriverInfo>,
/// Links information
#[serde(default)]
#[cfg(all_node_details)]
pub links: Option<HashMap<String, String>>,
/// Metadata
#[serde(default)]
#[cfg(all_node_details)]
pub meta: Option<HashMap<String, String>>,
/// Reserved resources
#[cfg(all_node_details)]
pub reserved: Resource,
// We ignore events
// /// Events Information
// #[serde(default)]
// pub events: Vec<HashMap<String, serde_json::Value>>,
}
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug, Copy)]
#[serde(rename_all = "lowercase")]
pub enum NodeStatus {
/// Node is initialising
Initializing,
/// Node is ready and accepting allocations
Ready,
/// Node is down or missed a heartbeat
Down,
}
/// Node Driver Information
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
#[cfg(all_node_details)]
pub struct DriverInfo {
/// Driver specific attributes
#[serde(default)]
pub attributes: Option<HashMap<String, String>>,
/// Whether the driver is detcted
pub detected: bool,
/// Healthy or not
pub healthy: bool,
/// Description of health
pub health_description: String,
/// Time updated
pub update_time: chrono::DateTime<chrono::Utc>,
}
/// Node Resource Details
#[cfg(all_node_details)]
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug)]
pub struct Resource {
/// CPU in MHz
#[serde(rename = "CPU")]
pub cpu: u64,
/// Disk space in MB
#[serde(rename = "DiskMB")]
pub disk: u64,
/// IOPS
#[serde(rename = "IOPS")]
pub iops: u64,
/// Memory in MB
#[serde(rename = "MemoryMB")]
pub memory: u64,
/// Networks
#[serde(default, rename = "Networks")]
pub networks: Option<Vec<NetworkResource>>,
}
/// Node Network details
#[cfg(all_node_details)]
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug)]
pub struct NetworkResource {
/// CIDR of the network
#[serde(rename = "CIDR")]
pub cidr: String,
/// Device name
#[serde(rename = "Device")]
pub device: String,
/// List of dynamic ports
#[serde(default, rename = "DynamicPorts")]
pub dynamic_ports: Vec<Port>,
/// IP Address
#[serde(rename = "IP")]
pub ip: String,
/// Mbits
#[serde(rename = "MBits")]
pub mbits: u64,
/// Reserved Ports
#[serde(default, rename = "ReservedPorts")]
pub reserved_ports: Vec<Port>,
}
/// Node Port details
#[cfg(all_node_details)]
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Port {
/// Label of the port
pub label: String,
/// Port number
pub port: u64,
}
/// Drain Strategy
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct DrainStrategy {
/// Specification for draining
#[serde(default, flatten)]
pub drain_spec: Option<DrainSpec>,
/// Deadline where drain must complete
pub force_deadline: chrono::DateTime<chrono::Utc>,
}
/// Specification for draining
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug)]
#[serde(default, rename_all = "PascalCase")]
pub struct DrainSpec {
/// Deadline in seconds
pub deadline: u64,
/// Whether system jobs are ignored
pub ignore_system_jobs: bool,
}
impl Default for DrainSpec {
fn default() -> Self {
Self {
deadline: 3600, // 1 hour
ignore_system_jobs: false,
}
}
}
/// Node eligibility for scheduling
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Debug, Copy)]
#[serde(rename_all = "lowercase")]
pub enum NodeEligibility {
/// Eligible to receive new allocations
Eligible,
/// Ineligible for new allocations
Ineligible,
}
impl fmt::Display for NodeEligibility {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NodeEligibility::Eligible => write!(f, "Eligible"),
NodeEligibility::Ineligible => write!(f, "Ineligible"),
}
}
}
#[derive(Serialize, Eq, PartialEq, Clone, Debug)]
struct NodeEligibilityRequest<'a> {
#[serde(rename = "NodeID")]
pub node_id: &'a str,
#[serde(rename = "Eligibility")]
pub eligibility: NodeEligibility,
}
#[derive(Deserialize, Eq, PartialEq, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
struct NodeEligibilityResponse {
pub eval_create_index: u128,
#[serde(rename = "EvalIDs")]
pub eval_ids: Option<Vec<String>>,
pub index: u128,
pub node_modify_index: u128,
}
#[derive(Serialize, Eq, PartialEq, Clone, Debug)]
struct NodeDrainRequest<'a, 'b> {
#[serde(rename = "NodeID")]
pub node_id: &'a str,
#[serde(rename = "DrainSpec")]
pub drain_spec: &'b DrainSpec,
}
// These are the same
type NodeDrainResponse = NodeEligibilityResponse;
/// Nomad Responses that support blocking requests
///
/// See the [documentation](https://www.nomadproject.io/api/index.html#blocking-queries) for more
/// details
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct BlockingResponse<T> {
/// The index indicating the "change ID" for the current response
pub index: u64,
/// The actual data of the response
pub data: T,
}
impl Client {
/// Create a new Nomad Client
///
/// You can optionally provide a `reqwest::Client` if you have specific needs like custom root
/// CA certificate or require client authentication.
/// The default client has a timeout set to 6 minutes to allow supporting Nomad's
/// [blocking queries](https://www.nomadproject.io/api/index.html#blocking-queries). If you
/// use your own client, make sure to set this as well.
#[allow(clippy::new_ret_no_self)]
pub fn new<S1, S2>(
address: S1,
token: Option<S2>,
client: Option<HttpClient>,
) -> Result<Self, crate::Error>
where
S1: AsRef<str>,
S2: AsRef<str>,
{
let client = match client {
Some(client) => client,
None => ClientBuilder::new()
.timeout(Some(Duration::from_secs(360)))
.build()?,
};
Ok(Self {
client,
address: address.as_ref().to_string(),
token: token.map(|s| From::from(s.as_ref().to_string())),
})
}
/// Returns the Nomad Server Address
pub fn address(&self) -> &str {
&self.address
}
/// Reurns the Nomad Token, if any
pub fn token(&self) -> Option<&str> {
self.token.as_ref().map(|s| s.as_str())
}
/// Returns the HTTP Client used
pub fn http_client(&self) -> &HttpClient {
&self.client
}
fn execute_request<T>(&self, request: reqwest::Request) -> Result<T, crate::Error>
where
T: serde::de::DeserializeOwned + Debug,
{
debug!("Making request: {:#?}", request);
let mut response = self.client.execute(request)?;
debug!("Received response: {:#?}", response);
let body = response.text()?;
debug!("Response body: {}", body);
let details = serde_json::from_str(&body)?;
debug!("Deserialized Details: {:#?}", details);
Ok(details)
}
fn execute_indexed_request<T>(
&self,
request: reqwest::Request,
) -> Result<BlockingResponse<T>, crate::Error>
where
T: serde::de::DeserializeOwned + Debug,
{
debug!("Making request: {:#?}", request);
let mut response = self.client.execute(request)?;
debug!("Received response: {:#?}", response);
let body = response.text()?;
debug!("Response body: {}", body);
let details = serde_json::from_str(&body)?;
debug!("Deserialized Details: {:#?}", details);
Self::make_indexed_response(&response, details)
}
/// Get Information about a specific Node ID
///
/// Supply the optional parameters to take advantage of
/// [blocking queries](https://www.nomadproject.io/api/index.html#blocking-queries)
pub fn node_details(
&self,
node_id: &str,
wait_index: Option<u64>,
wait_timeout: Option<Duration>,
) -> Result<BlockingResponse<Node>, crate::Error> {
info!("Requesting Nomad Node {} details", node_id);
let request = self.build_node_details_request(node_id, wait_index, wait_timeout)?;
self.execute_indexed_request(request)
}
/// Build requests to get node details
fn build_node_details_request(
&self,
node_id: &str,
wait_index: Option<u64>,
wait_timeout: Option<Duration>,
) -> Result<reqwest::Request, crate::Error> {
let address = format!("{}/v1/node/{}", &self.address, node_id);
let request = self.client.get(&address);
let request = self.add_nomad_token_header(request);
let request = Self::add_blocking_requests(request, wait_index, wait_timeout);
Ok(request.build()?)
}
/// Return a list of nodes
///
/// Supply the optional parameters to take advantage of
/// [blocking queries](https://www.nomadproject.io/api/index.html#blocking-queries)
fn nodes(
&self,
wait_index: Option<u64>,
wait_timeout: Option<Duration>,
) -> Result<BlockingResponse<Vec<NodesInList>>, crate::Error> {
info!("Requesting list of Nomad nodes");
let request = self.build_nodes_request(wait_index, wait_timeout)?;
self.execute_indexed_request(request)
}
/// Build request to retrieve list of nodes
fn build_nodes_request(
&self,
wait_index: Option<u64>,
wait_timeout: Option<Duration>,
) -> Result<reqwest::Request, crate::Error> {
let address = format!("{}/v1/nodes", &self.address);
let request = self.client.get(&address);
let request = self.add_nomad_token_header(request);
let request = Self::add_blocking_requests(request, wait_index, wait_timeout);
Ok(request.build()?)
}
/// Given an AWS Instance ID, find the Node details
///
/// You can optionally provide a `reqwest::Client` if you have specific needs like custom root
/// CA certificate or require client authentication
pub fn find_node_by_instance_id(
&self,
instance_id: &str,
) -> Result<BlockingResponse<Node>, crate::Error> {
info!("Finding Nomad Node ID for AWS Instance ID {}", instance_id);
let nodes = self.nodes(None, None)?;
let result = nodes
.data
.into_iter()
.filter(|node| node.status == NodeStatus::Ready)
.map(|node| self.node_details(&node.id, None, None))
.find(|details| match details {
Ok(details) => match details
.data
.attributes
.get("unique.platform.aws.instance-id")
{
Some(id) => id == instance_id,
None => false,
},
Err(_) => false,
});
let result = result.ok_or_else(|| crate::Error::NomadNodeNotFound {
instance_id: instance_id.to_string(),
})??;
info!(
"AWS Instance ID {} is Nomad Node ID {}",
instance_id, result.data.id
);
Ok(result)
}
/// Set a node eligibility for receiving new allocations
///
/// You can optionally provide a `reqwest::Client` if you have specific needs like custom root
/// CA certificate or require client authentication
pub fn set_node_eligibility(
&self,
node_id: &str,
eligibility: NodeEligibility,
) -> Result<(), crate::Error> {
info!(
"Setting Nomad Node ID {} eligibility to {}",
node_id, eligibility
);
let request = NodeEligibilityRequest {
node_id,
eligibility,
};
let request = self.build_node_eligibility_request(node_id, &request)?;
// Request is successful if the response can be deserialized
let _: NodeEligibilityResponse = self.execute_request(request)?;
Ok(())
}
fn build_node_eligibility_request(
&self,
node_id: &str,
payload: &NodeEligibilityRequest,
) -> Result<reqwest::Request, crate::Error> {
let address = format!("{}/v1/node/{}/eligibility", self.address, node_id);
let request = self.client.post(&address).json(payload);
let request = self.add_nomad_token_header(request);
Ok(request.build()?)
}
/// Mark the node for draining
///
/// You can optionally specify a `DrainSpec`. If you don't provide one, we will use the default.
///
/// You can optionally provide a `reqwest::Client` if you have specific needs like custom root
/// CA certificate or require client authentication
pub fn set_node_drain(
&self,
node_id: &str,
monitor: bool,
drain_spec: Option<DrainSpec>,
) -> Result<(), crate::Error> {
let drain_spec = drain_spec.unwrap_or_default();
info!("Draining Node ID {} with {:#?}", node_id, drain_spec);
let payload = NodeDrainRequest {
node_id,
drain_spec: &drain_spec,
};
let request = self.build_drain_request(node_id, &payload)?;
// Request is successful if the response can be deserialized
let _: NodeDrainResponse = self.execute_request(request)?;
if monitor {
self.monitor_node_drain(node_id, None)
} else {
Ok(())
}
}
fn build_drain_request(
&self,
node_id: &str,
payload: &NodeDrainRequest,
) -> Result<reqwest::Request, crate::Error> {
let address = format!("{}/v1/node/{}/drain", &self.address, node_id);
let request = self.client.post(&address).json(payload);
let request = self.add_nomad_token_header(request);
Ok(request.build()?)
}
/// Monitor Node Drain
///
/// This function will block until the drain is complete, or an error occurs
pub fn monitor_node_drain(
&self,
node_id: &str,
wait_timeout: Option<Duration>,
) -> Result<(), crate::Error> {
// The procedure is based on https://github.com/hashicorp/nomad/blob/master/api/nodes.go
// TODOs:
// - Monitor that no allocations are running
// - Async everything!
let wait_timeout = match wait_timeout {
Some(duration) => duration,
None => Duration::from_secs(300),
};
let mut wait_index = None;
let mut node;
let mut strategy = None;
let mut strategy_changed = false;
info!("Monitoring drain for Node ID {}", node_id);
loop {
info!("Checking if Node ID {} drain is complete", node_id);
node = self.node_details(node_id, wait_index, Some(wait_timeout))?;
if node.data.drain_strategy.is_none() {
if strategy_changed {
info!(
"Node {} has has marked all allocations for migration",
node_id
);
} else {
info!("No drain strategy set for node {}", node_id);
}
break;
}
if node.data.status == NodeStatus::Down {
warn!("Node {} down", node_id);
}
if strategy != node.data.drain_strategy {
info!(
"Node {} drain updated: {:#?}",
node_id, node.data.drain_strategy
);
}
strategy = node.data.drain_strategy;
strategy_changed = true;
wait_index = Some(node.index);
}
info!("Done monitoring drain for Node ID {}", node_id);
Ok(())
}
fn add_nomad_token_header(&self, request_builder: RequestBuilder) -> RequestBuilder {
match &self.token {
Some(token) => request_builder.header(NOMAD_AUTH_HEADER, token.as_str()),
None => request_builder,
}
}
fn add_blocking_requests(
request_builder: RequestBuilder,
wait_index: Option<u64>,
wait_timeout: Option<Duration>,
) -> RequestBuilder {
match wait_index {
Some(index) => {
let request_builder = request_builder.query(&[("index", index.to_string())]);
match wait_timeout {
None => request_builder,
Some(timeout) => {
request_builder.query(&[("wait", format!("{}s", timeout.as_secs()))])
}
}
}
None => request_builder,
}
}
fn make_indexed_response<T>(
response: &reqwest::Response,
data: T,
) -> Result<BlockingResponse<T>, crate::Error> {
let index = match response.headers().get(NOMAD_INDEX_HEADER) {
None => 0,
Some(index) => index.to_str()?.parse()?,
};
Ok(BlockingResponse { data, index })
}
}
#[cfg(test)]
mod tests {
use super::*;
const NOMAD_ADDRESS: &str = "http://127.0.0.1:4646";
fn node_fixture() -> &'static str {
include_str!("../fixtures/nomad_node.json")
}
fn nodes_fixture() -> &'static str {
include_str!("../fixtures/nomad_nodes.json")
}
fn nomad_client() -> Client {
Client::new(NOMAD_ADDRESS, Some("token"), None).expect("Not to fail")
}
#[test]
fn node_is_deserialized_properly() {
let node: Node = serde_json::from_str(node_fixture()).unwrap();
assert_eq!("02802087-8786-fdf6-4497-98445c891fb7", node.id);
}
#[test]
fn nodes_list_is_deserialized_properly() {
let _: Vec<NodesInList> = serde_json::from_str(nodes_fixture()).unwrap();
}
#[test]
fn build_node_details_request_is_built_properly() -> Result<(), crate::Error> {
let client = nomad_client();
let request =
client.build_node_details_request("id", Some(1234), Some(Duration::from_secs(300)))?;
assert_eq!(
format!(
"{}/v1/node/{}?index={}&wait={}",
NOMAD_ADDRESS, "id", "1234", "300s"
),
request.url().to_string()
);
assert_eq!(&reqwest::Method::GET, request.method());
let actual_token = request.headers().get(NOMAD_AUTH_HEADER);
assert!(actual_token.is_some());
assert_eq!("token", actual_token.unwrap());
Ok(())
}
#[test]
fn node_eligibility_response_is_deserialized_properly() {
let _: NodeEligibilityResponse =
serde_json::from_str(include_str!("../fixtures/node_eligibility.json")).unwrap();
}
#[test]
fn node_drain_response_is_deserialized_properly() {
let _: NodeDrainResponse =
serde_json::from_str(include_str!("../fixtures/node_drain.json")).unwrap();
}
}
|
use micromath::F32Ext;
const PI: f32 = 3.14159265358979;
use core::ops::Div;
/// Calculate Discrete Fourier Transform of the signal - WORKS
pub fn calc_signal_dft(input_signal: &[f32], output_signal_rex: &mut [f32], output_signal_imx: &mut [f32]) {
for (k, out_re) in output_signal_rex.iter_mut().enumerate() {
for (i, input) in input_signal.iter().enumerate() {
*out_re += *input*(2.0*PI*(k as f32)*(i as f32)/(input_signal.len() as f32)).cos()
}
}
for (k, out_im) in output_signal_imx.iter_mut().enumerate() {
for (i, input) in input_signal.iter().enumerate() {
*out_im -= *input*(2.0*PI*(k as f32)*(i as f32)/(input_signal.len() as f32)).sin()
}
}
}
/// Calculate Inverse Discrete Fourier Transform of the signal
pub fn calc_signal_idft(input_rex: &mut [f32], input_imx: &mut [f32], output_idft: &mut [f32]) {
let input_len = input_rex.len();
let output_len = output_idft.len();
for k in 0..input_len {
input_rex[k] = input_rex[k]/(input_len as f32);
input_imx[k] = -input_imx[k]/(input_len as f32);
}
input_rex[0] = input_rex[0]/2.0;
input_imx[0] = -input_imx[0]/2.0;
for k in 0..input_len {
for i in 0..output_len {
output_idft[i] += input_rex[k] * ((2.0*PI*(i as f32)*(k as f32))/(output_len as f32)).cos();
output_idft[i] += input_imx[k] * ((2.0*PI*(i as f32)*(k as f32))/(output_len as f32)).sin();
}
}
}
/// TO DO
/// Calculate Inverse Discrete Fourier Transform of the signal
pub fn calc_signal_idft_better(input_rex: &mut [f32], input_imx: &mut [f32], output_idft: &mut [f32]) {
let input_len = input_rex.len();
let output_len = output_idft.len();
for (re, im) in input_rex.iter_mut().zip(input_imx.iter_mut()) {
*re = *re/input_len as f32;
*im = *im*(-1.0)/input_len as f32;
}
/*
for k in 0..input_len {
input_rex[k] = input_rex[k]/(input_len as f32);
input_imx[k] = -input_imx[k]/(input_len as f32);
}
*/
input_rex[0] = input_rex[0]/2.0;
input_imx[0] = -input_imx[0]/2.0;
for k in 0..input_len {
for i in 0..output_len {
output_idft[i] += input_rex[k] * ((2.0*PI*(i as f32)*(k as f32))/(output_len as f32)).cos();
output_idft[i] += input_imx[k] * ((2.0*PI*(i as f32)*(k as f32))/(output_len as f32)).sin();
}
}
}
/// Calculate magnitude of the signal - WORKS
pub fn calc_signal_magnitude(input_rex: &[f32], input_imx: &[f32], output_mag: &mut [f32]) {
for (rex, imx, mag) in input_rex.iter()
.zip(input_imx.iter())
.zip(output_mag.iter_mut())
.map(|((rex,imx),mag)| (rex,imx,mag))
{
*mag = (rex.powi(2) + imx.powi(2)).powf(0.5);
}
}
/// A more idiomatic version of the signal mean calculation - WORKS
pub fn calc_signal_mean(signal: &[f32]) -> f32 {
let mean: f32 = signal.iter()
.fold(0_f32, |sum, x| sum + x)
.div(signal.len() as f32);
mean
}
/// A more idiomatic version of the signal variance calculation - WORKS
pub fn calc_signal_variance(signal: &[f32], signal_mean: f32) -> f32 {
let variance: f32 = signal.iter()
.fold(0_f32, |sum, x| sum + (x-signal_mean).powi(2))
.div((signal.len()-1) as f32);
variance
}
/// Calculate standard deviation of the signal
pub fn calc_signal_stddev(signal_variance: f32) -> f32 {
signal_variance.powf(0.5)
}
/// Calculate running sum of the signal
pub fn calc_running_sum(input: &[f32], output: &mut [f32]) {
let mut acc = 0_f32;
for (i,j) in input.iter().zip(output.iter_mut()) {
*j = *i + acc;
acc += *i;
}
}
/// Convert complex signal values to polar coordinates (magnitude and phase) - WORKS
pub fn rect_to_polar(input_rex: &mut [f32],
input_imx: &[f32],
output_mag: &mut [f32],
output_phase: &mut [f32])
{
let sig_len = input_rex.len();
for (re,im,mag,ph) in input_rex.iter_mut()
.zip(input_imx.iter())
.zip(output_mag.iter_mut())
.zip(output_phase.iter_mut())
.map(|(((re, im), mag), ph)| (re,im,mag,ph))
{
*mag = (re.powi(2) + im.powi(2)).powf(0.5);
if *re == 0.0 {
*re = 10.0.powi(-20);
*ph = ((*im)/(*re)).atan();
}
if *re < 0.0 && *im < 0.0 {
*ph = *ph - PI;
}
if *re < 0.0 && *im >= 0.0 {
*ph = *ph + PI;
}
}
}
/// Calculate complex DFT of the signal (conversion from time to frequency domain) - WORKS
pub fn complex_dft(time_rex: &[f32],
time_imx: &[f32],
freq_rex: &mut [f32],
freq_imx: &mut [f32])
{
let sig_len = time_rex.len();
for (k, f_re, f_im) in freq_rex.iter_mut()
.zip(freq_imx.iter_mut())
.enumerate()
.map(|(k,(f_re,f_im))| (k,f_re,f_im)) {
for (i, t_re, t_im) in time_rex.iter()
.zip(time_imx.iter())
.enumerate()
.map(|(i,(t_re,t_im))| (i,t_re,t_im)) {
let SR = ((2.0*PI*(k as f32)*(i as f32))/(sig_len as f32)).cos();
let SI = -((2.0*PI*(k as f32)*(i as f32))/(sig_len as f32)).sin();
*f_re = *f_re + *t_re * SR - *t_im * SI;
*f_im = *f_im + *t_im * SI - *t_im * SR;
}
}
}
/*
/// convolution of two signals (signal and kernel)
pub fn convolution(input_signal: &[f32], impulse: &[f32], output: &mut [f32]) {
for i in 0..output.len() {
//output[i] = 3.0;
for j in 0..input_signal.len() {
for k in 0..impulse.len() {
output[j+k] += input_signal[j] * impulse[k]
}
}
}
}
*/
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
//use std::f32::consts::PI;
/*
/// Calculate Discrete Fourier Transform of the signal
pub fn calc_signal_dft(input: &[f32], output_rex: &mut [f32], output_imx: &mut [f32]) {
for k in 0..output_rex.len() {
for i in 0..input.len() {
output_rex[k] += input[i]*(2.0*PI*(k as f32)*(i as f32)/(input.len() as f32)).cos()
}
}
for k in 0..output_imx.len() {
for i in 0..input.len() {
output_imx[k] -= input[i]*(2.0*PI*(k as f32)*(i as f32)/(input.len() as f32)).sin()
}
}
}
*/
/*
/// Calculate magnitude of the signal
pub fn calc_signal_magnitude(input_rex: &mut [f32], input_imx: &mut [f32], output_mag: &mut [f32]) {
for i in 0..output_mag.len() {
output_mag[i] = (input_rex[i].powi(2) + input_imx[i].powi(2)).powf(0.5);
}
}
*/
/*
/// Calculate mean value of the signal
pub fn calc_signal_mean(signal: &[f32]) -> f32 {
let mut _mean: f32 = 0.0;
for i in signal {
_mean += i;
}
_mean / (signal.len() as f32)
}
*/
/*
/// Calculate variance of the signal
pub fn calc_signal_variance(signal: &[f32], signal_mean: f32) -> f32 {
let mut _variance: f32 = 0.0;
for i in signal {
_variance += (i - signal_mean).powi(2); //add squared difference
}
_variance / ((signal.len() - 1) as f32)
}
*/
/*
/// Calculate running sum of the signal
pub fn calc_running_sum(input: &[f32], output: &mut [f32]) {
for i in 0..output.len() {
if i == 0 {
output[i] = input[i];
} else {
output[i] += output[i-1] + input[i]
}
}
}
*/
/*
/// Convert complex signal values to polar coordinates (magnitude and phase)
pub fn rect_to_polar(input_rex: &mut [f32],
input_imx: &[f32],
output_mag: &mut [f32],
output_phase: &mut [f32])
{
let sig_len = input_rex.len();
for k in 0..sig_len {
output_mag[k] = (input_rex[k].powi(2) + input_imx[k].powi(2)).powf(0.5);
if input_rex[k] == 0.0 {
input_rex[k] = 10.0.powi(-20);
output_phase[k] = (input_imx[k]/input_rex[k]).atan();
}
if input_rex[k]<0.0 && input_imx[k] < 0.0 {
output_phase[k] = output_phase[k] - PI;
}
if input_rex[k]<0.0 && input_imx[k] >= 0.0 {
output_phase[k] = output_phase[k] + PI;
}
}
}
*/
/*
/// Calculate complex DFT of the signal (conversion from time to frequency domain)
pub fn complex_dft(time_rex: &[f32],
time_imx: &[f32],
freq_rex: &mut [f32],
freq_imx: &mut [f32])
{
let sig_len = time_rex.len();
for k in 0..sig_len-1 {
for i in 0..sig_len-1 {
let SR = ((2.0*PI*(k as f32)*(i as f32))/(sig_len as f32)).cos();
let SI = -((2.0*PI*(k as f32)*(i as f32))/(sig_len as f32)).sin();
freq_rex[k] = freq_rex[k] + time_rex[i] * SR - time_imx[i] * SI;
freq_imx[k] = freq_imx[k] + time_imx[i] * SI - time_imx[i] * SR;
}
}
}
*/
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib;
use glib::object::IsA;
use glib::translate::*;
use libc;
use std::fmt;
use std::ptr;
use webkit2_webextension_sys;
use DOMNode;
use DOMObject;
use DOMXPathResult;
glib_wrapper! {
pub struct DOMXPathExpression(Object<webkit2_webextension_sys::WebKitDOMXPathExpression, webkit2_webextension_sys::WebKitDOMXPathExpressionClass, DOMXPathExpressionClass>) @extends DOMObject;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_xpath_expression_get_type(),
}
}
pub const NONE_DOMX_PATH_EXPRESSION: Option<&DOMXPathExpression> = None;
pub trait DOMXPathExpressionExt: 'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn evaluate<P: IsA<DOMNode>, Q: IsA<DOMXPathResult>>(
&self,
contextNode: &P,
type_: libc::c_ushort,
inResult: &Q,
) -> Result<DOMXPathResult, glib::Error>;
}
impl<O: IsA<DOMXPathExpression>> DOMXPathExpressionExt for O {
fn evaluate<P: IsA<DOMNode>, Q: IsA<DOMXPathResult>>(
&self,
contextNode: &P,
type_: libc::c_ushort,
inResult: &Q,
) -> Result<DOMXPathResult, glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let ret = webkit2_webextension_sys::webkit_dom_xpath_expression_evaluate(
self.as_ref().to_glib_none().0,
contextNode.as_ref().to_glib_none().0,
type_,
inResult.as_ref().to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(from_glib_full(ret))
} else {
Err(from_glib_full(error))
}
}
}
}
impl fmt::Display for DOMXPathExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMXPathExpression")
}
}
|
#![recursion_limit = "1024"] // for error_chain
//! Utility types and functions used by `cpp_to_rust_generator` and
//! `cpp_to_rust_build_tools` crates.
//!
//! See [README](https://github.com/rust-qt/cpp_to_rust)
//! for more information.
//!
#[macro_use]
extern crate error_chain;
extern crate backtrace;
extern crate regex;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate term_painter;
extern crate num_cpus;
#[macro_use]
extern crate lazy_static;
pub extern crate toml;
pub mod log;
pub mod errors;
pub mod file_utils;
pub mod string_utils;
pub mod utils;
pub mod cpp_build_config;
pub mod cpp_lib_builder;
pub mod target;
/// This type contains data serialized by the generator and placed to the
/// generated crate's directory. The build script reads and uses this value.
#[derive(Debug, Clone)]
#[derive(Serialize, Deserialize)]
pub struct BuildScriptData {
/// Information required to build the C++ wrapper library
pub cpp_build_config: cpp_build_config::CppBuildConfig,
/// Name of the original C++ library passed to the generator
pub cpp_lib_version: Option<String>,
/// Name of C++ wrapper library
pub cpp_wrapper_lib_name: String,
}
#[cfg(test)]
mod tests;
|
fn main(){
let mut t=0f32;
let torus_sdf=|[x,y,z,r,w]:[f32;5]|{
let q=(x*x+z*z).sqrt()-r;(q*q+y*y).sqrt()-w
};
let m=|l|move|s|(s,2.*(s as f32)/l-1.);
let mut output=vec![vec![b' ';64];36];
loop{
let(xs,xc)=(t*3.).sin_cos();
let(zs,zc)=(t*2.).sin_cos();
for(i,u)in(0..64).map(m(64.)){
for(j,v)in(0..36).map(m(36.)){
for(_,z)in(0..32).map(m(32.)){
let vt=u*zs-v*zc;
if torus_sdf([u*zc+v*zs,vt*xc+z*xs,z*xc-vt*xs,0.7,0.25])<0.{
let al=(u*u+v*(v-1.)+z*(z+1.))/
((u*u+v*v+z*z)*(u*u+(v-1.)*(v-1.)+(z+1.)*(z+1.))).sqrt();
output[j][i]=b".,-~:;=!*#$@"[(al*11.).max(0.).round()as usize];
break;
}
}
}
}
print!("\x1b[H");
for r in output.iter_mut(){
print!("{}\n", std::str::from_utf8(r).unwrap());
r.fill(b' ');
}
t+=0.0005;
}
}
|
use std::env;
fn main() {
let libs_dir =
if let Ok(dir) = env::var("SDL_LIBS_DIR") {
Some(dir)
}
else {
if let Ok(cargo_root_dir) = env::var("CARGO_MANIFEST_DIR") {
Some(format!("{}/sdl_libs", cargo_root_dir))
}
else {
None
}
};
if let Some(libs) = libs_dir {
println!("cargo:rustc-flags=-L {}", libs);
}
}
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtQuick/qquickwindow.h
// dst-file: /src/quick/qquickwindow.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::qwindow::QWindow; // 771
use std::ops::Deref;
use super::super::core::qsize::QSize; // 771
use super::super::core::qrunnable::QRunnable; // 771
use super::super::core::qobject::QObject; // 771
use super::qquickitem::QQuickItem; // 773
use super::super::gui::qimage::QImage; // 771
use super::super::gui::qcolor::QColor; // 771
use super::qquickrendercontrol::QQuickRenderControl; // 773
use super::super::gui::qopenglframebufferobject::QOpenGLFramebufferObject; // 771
use super::super::gui::qaccessible::QAccessibleInterface; // 771
use super::super::core::qcoreevent::QEvent; // 771
use super::qsgtexture::QSGTexture; // 773
use super::super::qml::qqmlincubator::QQmlIncubationController; // 771
use super::super::gui::qopenglcontext::QOpenGLContext; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QQuickWindow_Class_Size() -> c_int;
// proto: void QQuickWindow::QQuickWindow(QWindow * parent);
fn _ZN12QQuickWindowC2EP7QWindow(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickWindow::setPersistentSceneGraph(bool persistent);
fn _ZN12QQuickWindow23setPersistentSceneGraphEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QQuickWindow::isPersistentOpenGLContext();
fn _ZNK12QQuickWindow25isPersistentOpenGLContextEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: qreal QQuickWindow::effectiveDevicePixelRatio();
fn _ZNK12QQuickWindow25effectiveDevicePixelRatioEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QQuickWindow::resetOpenGLState();
fn _ZN12QQuickWindow16resetOpenGLStateEv(qthis: u64 /* *mut c_void*/);
// proto: uint QQuickWindow::renderTargetId();
fn _ZNK12QQuickWindow14renderTargetIdEv(qthis: u64 /* *mut c_void*/) -> c_uint;
// proto: void QQuickWindow::setRenderTarget(uint fboId, const QSize & size);
fn _ZN12QQuickWindow15setRenderTargetEjRK5QSize(qthis: u64 /* *mut c_void*/, arg0: c_uint, arg1: *mut c_void);
// proto: const QMetaObject * QQuickWindow::metaObject();
fn _ZNK12QQuickWindow10metaObjectEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickWindow::QQuickWindow(const QQuickWindow & );
fn _ZN12QQuickWindowC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QObject * QQuickWindow::focusObject();
fn _ZNK12QQuickWindow11focusObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QQuickItem * QQuickWindow::activeFocusItem();
fn _ZNK12QQuickWindow15activeFocusItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickWindow::update();
fn _ZN12QQuickWindow6updateEv(qthis: u64 /* *mut c_void*/);
// proto: QOpenGLContext * QQuickWindow::openglContext();
fn _ZNK12QQuickWindow13openglContextEv(qthis: u64 /* *mut c_void*/);
// proto: QColor QQuickWindow::color();
fn _ZNK12QQuickWindow5colorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickWindow::releaseResources();
fn _ZN12QQuickWindow16releaseResourcesEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickWindow::QQuickWindow(QQuickRenderControl * renderControl);
fn _ZN12QQuickWindowC2EP19QQuickRenderControl(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QQuickItem * QQuickWindow::mouseGrabberItem();
fn _ZNK12QQuickWindow16mouseGrabberItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QQuickWindow::isPersistentSceneGraph();
fn _ZNK12QQuickWindow22isPersistentSceneGraphEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QQuickWindow::setRenderTarget(QOpenGLFramebufferObject * fbo);
fn _ZN12QQuickWindow15setRenderTargetEP24QOpenGLFramebufferObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickWindow::~QQuickWindow();
fn _ZN12QQuickWindowD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QSize QQuickWindow::renderTargetSize();
fn _ZNK12QQuickWindow16renderTargetSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickWindow::setColor(const QColor & color);
fn _ZN12QQuickWindow8setColorERK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha);
fn _ZN12QQuickWindow21setDefaultAlphaBufferEb(arg0: c_char);
// proto: QAccessibleInterface * QQuickWindow::accessibleRoot();
fn _ZNK12QQuickWindow14accessibleRootEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QQuickWindow::isSceneGraphInitialized();
fn _ZNK12QQuickWindow23isSceneGraphInitializedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QQuickWindow::setClearBeforeRendering(bool enabled);
fn _ZN12QQuickWindow23setClearBeforeRenderingEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QImage QQuickWindow::grabWindow();
fn _ZN12QQuickWindow10grabWindowEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickWindow::setPersistentOpenGLContext(bool persistent);
fn _ZN12QQuickWindow26setPersistentOpenGLContextEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QQuickWindow::sendEvent(QQuickItem * , QEvent * );
fn _ZN12QQuickWindow9sendEventEP10QQuickItemP6QEvent(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: QOpenGLFramebufferObject * QQuickWindow::renderTarget();
fn _ZNK12QQuickWindow12renderTargetEv(qthis: u64 /* *mut c_void*/);
// proto: QSGTexture * QQuickWindow::createTextureFromImage(const QImage & image);
fn _ZNK12QQuickWindow22createTextureFromImageERK6QImage(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QQmlIncubationController * QQuickWindow::incubationController();
fn _ZNK12QQuickWindow20incubationControllerEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QQuickWindow::clearBeforeRendering();
fn _ZNK12QQuickWindow20clearBeforeRenderingEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QQuickItem * QQuickWindow::contentItem();
fn _ZNK12QQuickWindow11contentItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static bool QQuickWindow::hasDefaultAlphaBuffer();
fn _ZN12QQuickWindow21hasDefaultAlphaBufferEv() -> c_char;
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow12frameSwappedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow14afterRenderingEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow15beforeRenderingEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphInvalidatedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow22activeFocusItemChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow18afterSynchronizingEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow19beforeSynchronizingEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow20openglContextCreatedEP14QOpenGLContext(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow12colorChangedERK6QColor(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphInitializedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphAboutToStopEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickWindow_SlotProxy_connect__ZN12QQuickWindow14afterAnimatingEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QQuickWindow)=1
#[derive(Default)]
pub struct QQuickWindow {
qbase: QWindow,
pub qclsinst: u64 /* *mut c_void*/,
pub _colorChanged: QQuickWindow_colorChanged_signal,
pub _sceneGraphInvalidated: QQuickWindow_sceneGraphInvalidated_signal,
pub _beforeSynchronizing: QQuickWindow_beforeSynchronizing_signal,
pub _sceneGraphAboutToStop: QQuickWindow_sceneGraphAboutToStop_signal,
pub _afterAnimating: QQuickWindow_afterAnimating_signal,
pub _sceneGraphError: QQuickWindow_sceneGraphError_signal,
pub _sceneGraphInitialized: QQuickWindow_sceneGraphInitialized_signal,
pub _activeFocusItemChanged: QQuickWindow_activeFocusItemChanged_signal,
pub _afterRendering: QQuickWindow_afterRendering_signal,
pub _closing: QQuickWindow_closing_signal,
pub _afterSynchronizing: QQuickWindow_afterSynchronizing_signal,
pub _beforeRendering: QQuickWindow_beforeRendering_signal,
pub _frameSwapped: QQuickWindow_frameSwapped_signal,
pub _openglContextCreated: QQuickWindow_openglContextCreated_signal,
}
impl /*struct*/ QQuickWindow {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QQuickWindow {
return QQuickWindow{qbase: QWindow::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QQuickWindow {
type Target = QWindow;
fn deref(&self) -> &QWindow {
return & self.qbase;
}
}
impl AsRef<QWindow> for QQuickWindow {
fn as_ref(& self) -> & QWindow {
return & self.qbase;
}
}
// proto: void QQuickWindow::QQuickWindow(QWindow * parent);
impl /*struct*/ QQuickWindow {
pub fn new<T: QQuickWindow_new>(value: T) -> QQuickWindow {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QQuickWindow_new {
fn new(self) -> QQuickWindow;
}
// proto: void QQuickWindow::QQuickWindow(QWindow * parent);
impl<'a> /*trait*/ QQuickWindow_new for (&'a QWindow) {
fn new(self) -> QQuickWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindowC2EP7QWindow()};
let ctysz: c_int = unsafe{QQuickWindow_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QQuickWindowC2EP7QWindow(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QQuickWindow{qbase: QWindow::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QQuickWindow::setPersistentSceneGraph(bool persistent);
impl /*struct*/ QQuickWindow {
pub fn setPersistentSceneGraph<RetType, T: QQuickWindow_setPersistentSceneGraph<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPersistentSceneGraph(self);
// return 1;
}
}
pub trait QQuickWindow_setPersistentSceneGraph<RetType> {
fn setPersistentSceneGraph(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::setPersistentSceneGraph(bool persistent);
impl<'a> /*trait*/ QQuickWindow_setPersistentSceneGraph<()> for (i8) {
fn setPersistentSceneGraph(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow23setPersistentSceneGraphEb()};
let arg0 = self as c_char;
unsafe {_ZN12QQuickWindow23setPersistentSceneGraphEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QQuickWindow::isPersistentOpenGLContext();
impl /*struct*/ QQuickWindow {
pub fn isPersistentOpenGLContext<RetType, T: QQuickWindow_isPersistentOpenGLContext<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isPersistentOpenGLContext(self);
// return 1;
}
}
pub trait QQuickWindow_isPersistentOpenGLContext<RetType> {
fn isPersistentOpenGLContext(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: bool QQuickWindow::isPersistentOpenGLContext();
impl<'a> /*trait*/ QQuickWindow_isPersistentOpenGLContext<i8> for () {
fn isPersistentOpenGLContext(self , rsthis: & QQuickWindow) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow25isPersistentOpenGLContextEv()};
let mut ret = unsafe {_ZNK12QQuickWindow25isPersistentOpenGLContextEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: qreal QQuickWindow::effectiveDevicePixelRatio();
impl /*struct*/ QQuickWindow {
pub fn effectiveDevicePixelRatio<RetType, T: QQuickWindow_effectiveDevicePixelRatio<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.effectiveDevicePixelRatio(self);
// return 1;
}
}
pub trait QQuickWindow_effectiveDevicePixelRatio<RetType> {
fn effectiveDevicePixelRatio(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: qreal QQuickWindow::effectiveDevicePixelRatio();
impl<'a> /*trait*/ QQuickWindow_effectiveDevicePixelRatio<f64> for () {
fn effectiveDevicePixelRatio(self , rsthis: & QQuickWindow) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow25effectiveDevicePixelRatioEv()};
let mut ret = unsafe {_ZNK12QQuickWindow25effectiveDevicePixelRatioEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: void QQuickWindow::resetOpenGLState();
impl /*struct*/ QQuickWindow {
pub fn resetOpenGLState<RetType, T: QQuickWindow_resetOpenGLState<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resetOpenGLState(self);
// return 1;
}
}
pub trait QQuickWindow_resetOpenGLState<RetType> {
fn resetOpenGLState(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::resetOpenGLState();
impl<'a> /*trait*/ QQuickWindow_resetOpenGLState<()> for () {
fn resetOpenGLState(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow16resetOpenGLStateEv()};
unsafe {_ZN12QQuickWindow16resetOpenGLStateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: uint QQuickWindow::renderTargetId();
impl /*struct*/ QQuickWindow {
pub fn renderTargetId<RetType, T: QQuickWindow_renderTargetId<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.renderTargetId(self);
// return 1;
}
}
pub trait QQuickWindow_renderTargetId<RetType> {
fn renderTargetId(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: uint QQuickWindow::renderTargetId();
impl<'a> /*trait*/ QQuickWindow_renderTargetId<u32> for () {
fn renderTargetId(self , rsthis: & QQuickWindow) -> u32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow14renderTargetIdEv()};
let mut ret = unsafe {_ZNK12QQuickWindow14renderTargetIdEv(rsthis.qclsinst)};
return ret as u32;
// return 1;
}
}
// proto: void QQuickWindow::setRenderTarget(uint fboId, const QSize & size);
impl /*struct*/ QQuickWindow {
pub fn setRenderTarget<RetType, T: QQuickWindow_setRenderTarget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRenderTarget(self);
// return 1;
}
}
pub trait QQuickWindow_setRenderTarget<RetType> {
fn setRenderTarget(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::setRenderTarget(uint fboId, const QSize & size);
impl<'a> /*trait*/ QQuickWindow_setRenderTarget<()> for (u32, &'a QSize) {
fn setRenderTarget(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow15setRenderTargetEjRK5QSize()};
let arg0 = self.0 as c_uint;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {_ZN12QQuickWindow15setRenderTargetEjRK5QSize(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QMetaObject * QQuickWindow::metaObject();
impl /*struct*/ QQuickWindow {
pub fn metaObject<RetType, T: QQuickWindow_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QQuickWindow_metaObject<RetType> {
fn metaObject(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: const QMetaObject * QQuickWindow::metaObject();
impl<'a> /*trait*/ QQuickWindow_metaObject<()> for () {
fn metaObject(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow10metaObjectEv()};
unsafe {_ZNK12QQuickWindow10metaObjectEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickWindow::QQuickWindow(const QQuickWindow & );
impl<'a> /*trait*/ QQuickWindow_new for (&'a QQuickWindow) {
fn new(self) -> QQuickWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindowC2ERKS_()};
let ctysz: c_int = unsafe{QQuickWindow_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QQuickWindowC2ERKS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QQuickWindow{qbase: QWindow::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QObject * QQuickWindow::focusObject();
impl /*struct*/ QQuickWindow {
pub fn focusObject<RetType, T: QQuickWindow_focusObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.focusObject(self);
// return 1;
}
}
pub trait QQuickWindow_focusObject<RetType> {
fn focusObject(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QObject * QQuickWindow::focusObject();
impl<'a> /*trait*/ QQuickWindow_focusObject<QObject> for () {
fn focusObject(self , rsthis: & QQuickWindow) -> QObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow11focusObjectEv()};
let mut ret = unsafe {_ZNK12QQuickWindow11focusObjectEv(rsthis.qclsinst)};
let mut ret1 = QObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QQuickItem * QQuickWindow::activeFocusItem();
impl /*struct*/ QQuickWindow {
pub fn activeFocusItem<RetType, T: QQuickWindow_activeFocusItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.activeFocusItem(self);
// return 1;
}
}
pub trait QQuickWindow_activeFocusItem<RetType> {
fn activeFocusItem(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QQuickItem * QQuickWindow::activeFocusItem();
impl<'a> /*trait*/ QQuickWindow_activeFocusItem<QQuickItem> for () {
fn activeFocusItem(self , rsthis: & QQuickWindow) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow15activeFocusItemEv()};
let mut ret = unsafe {_ZNK12QQuickWindow15activeFocusItemEv(rsthis.qclsinst)};
let mut ret1 = QQuickItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickWindow::update();
impl /*struct*/ QQuickWindow {
pub fn update<RetType, T: QQuickWindow_update<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.update(self);
// return 1;
}
}
pub trait QQuickWindow_update<RetType> {
fn update(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::update();
impl<'a> /*trait*/ QQuickWindow_update<()> for () {
fn update(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow6updateEv()};
unsafe {_ZN12QQuickWindow6updateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QOpenGLContext * QQuickWindow::openglContext();
impl /*struct*/ QQuickWindow {
pub fn openglContext<RetType, T: QQuickWindow_openglContext<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.openglContext(self);
// return 1;
}
}
pub trait QQuickWindow_openglContext<RetType> {
fn openglContext(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QOpenGLContext * QQuickWindow::openglContext();
impl<'a> /*trait*/ QQuickWindow_openglContext<()> for () {
fn openglContext(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow13openglContextEv()};
unsafe {_ZNK12QQuickWindow13openglContextEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QColor QQuickWindow::color();
impl /*struct*/ QQuickWindow {
pub fn color<RetType, T: QQuickWindow_color<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.color(self);
// return 1;
}
}
pub trait QQuickWindow_color<RetType> {
fn color(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QColor QQuickWindow::color();
impl<'a> /*trait*/ QQuickWindow_color<QColor> for () {
fn color(self , rsthis: & QQuickWindow) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow5colorEv()};
let mut ret = unsafe {_ZNK12QQuickWindow5colorEv(rsthis.qclsinst)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickWindow::releaseResources();
impl /*struct*/ QQuickWindow {
pub fn releaseResources<RetType, T: QQuickWindow_releaseResources<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.releaseResources(self);
// return 1;
}
}
pub trait QQuickWindow_releaseResources<RetType> {
fn releaseResources(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::releaseResources();
impl<'a> /*trait*/ QQuickWindow_releaseResources<()> for () {
fn releaseResources(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow16releaseResourcesEv()};
unsafe {_ZN12QQuickWindow16releaseResourcesEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickWindow::QQuickWindow(QQuickRenderControl * renderControl);
impl<'a> /*trait*/ QQuickWindow_new for (&'a QQuickRenderControl) {
fn new(self) -> QQuickWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindowC2EP19QQuickRenderControl()};
let ctysz: c_int = unsafe{QQuickWindow_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QQuickWindowC2EP19QQuickRenderControl(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QQuickWindow{qbase: QWindow::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QQuickItem * QQuickWindow::mouseGrabberItem();
impl /*struct*/ QQuickWindow {
pub fn mouseGrabberItem<RetType, T: QQuickWindow_mouseGrabberItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mouseGrabberItem(self);
// return 1;
}
}
pub trait QQuickWindow_mouseGrabberItem<RetType> {
fn mouseGrabberItem(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QQuickItem * QQuickWindow::mouseGrabberItem();
impl<'a> /*trait*/ QQuickWindow_mouseGrabberItem<QQuickItem> for () {
fn mouseGrabberItem(self , rsthis: & QQuickWindow) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow16mouseGrabberItemEv()};
let mut ret = unsafe {_ZNK12QQuickWindow16mouseGrabberItemEv(rsthis.qclsinst)};
let mut ret1 = QQuickItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickWindow::isPersistentSceneGraph();
impl /*struct*/ QQuickWindow {
pub fn isPersistentSceneGraph<RetType, T: QQuickWindow_isPersistentSceneGraph<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isPersistentSceneGraph(self);
// return 1;
}
}
pub trait QQuickWindow_isPersistentSceneGraph<RetType> {
fn isPersistentSceneGraph(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: bool QQuickWindow::isPersistentSceneGraph();
impl<'a> /*trait*/ QQuickWindow_isPersistentSceneGraph<i8> for () {
fn isPersistentSceneGraph(self , rsthis: & QQuickWindow) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow22isPersistentSceneGraphEv()};
let mut ret = unsafe {_ZNK12QQuickWindow22isPersistentSceneGraphEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QQuickWindow::setRenderTarget(QOpenGLFramebufferObject * fbo);
impl<'a> /*trait*/ QQuickWindow_setRenderTarget<()> for (&'a QOpenGLFramebufferObject) {
fn setRenderTarget(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow15setRenderTargetEP24QOpenGLFramebufferObject()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QQuickWindow15setRenderTargetEP24QOpenGLFramebufferObject(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickWindow::~QQuickWindow();
impl /*struct*/ QQuickWindow {
pub fn free<RetType, T: QQuickWindow_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QQuickWindow_free<RetType> {
fn free(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::~QQuickWindow();
impl<'a> /*trait*/ QQuickWindow_free<()> for () {
fn free(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindowD2Ev()};
unsafe {_ZN12QQuickWindowD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QSize QQuickWindow::renderTargetSize();
impl /*struct*/ QQuickWindow {
pub fn renderTargetSize<RetType, T: QQuickWindow_renderTargetSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.renderTargetSize(self);
// return 1;
}
}
pub trait QQuickWindow_renderTargetSize<RetType> {
fn renderTargetSize(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QSize QQuickWindow::renderTargetSize();
impl<'a> /*trait*/ QQuickWindow_renderTargetSize<QSize> for () {
fn renderTargetSize(self , rsthis: & QQuickWindow) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow16renderTargetSizeEv()};
let mut ret = unsafe {_ZNK12QQuickWindow16renderTargetSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickWindow::setColor(const QColor & color);
impl /*struct*/ QQuickWindow {
pub fn setColor<RetType, T: QQuickWindow_setColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setColor(self);
// return 1;
}
}
pub trait QQuickWindow_setColor<RetType> {
fn setColor(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::setColor(const QColor & color);
impl<'a> /*trait*/ QQuickWindow_setColor<()> for (&'a QColor) {
fn setColor(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow8setColorERK6QColor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN12QQuickWindow8setColorERK6QColor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha);
impl /*struct*/ QQuickWindow {
pub fn setDefaultAlphaBuffer_s<RetType, T: QQuickWindow_setDefaultAlphaBuffer_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setDefaultAlphaBuffer_s();
// return 1;
}
}
pub trait QQuickWindow_setDefaultAlphaBuffer_s<RetType> {
fn setDefaultAlphaBuffer_s(self ) -> RetType;
}
// proto: static void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha);
impl<'a> /*trait*/ QQuickWindow_setDefaultAlphaBuffer_s<()> for (i8) {
fn setDefaultAlphaBuffer_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow21setDefaultAlphaBufferEb()};
let arg0 = self as c_char;
unsafe {_ZN12QQuickWindow21setDefaultAlphaBufferEb(arg0)};
// return 1;
}
}
// proto: QAccessibleInterface * QQuickWindow::accessibleRoot();
impl /*struct*/ QQuickWindow {
pub fn accessibleRoot<RetType, T: QQuickWindow_accessibleRoot<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.accessibleRoot(self);
// return 1;
}
}
pub trait QQuickWindow_accessibleRoot<RetType> {
fn accessibleRoot(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QAccessibleInterface * QQuickWindow::accessibleRoot();
impl<'a> /*trait*/ QQuickWindow_accessibleRoot<QAccessibleInterface> for () {
fn accessibleRoot(self , rsthis: & QQuickWindow) -> QAccessibleInterface {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow14accessibleRootEv()};
let mut ret = unsafe {_ZNK12QQuickWindow14accessibleRootEv(rsthis.qclsinst)};
let mut ret1 = QAccessibleInterface::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickWindow::isSceneGraphInitialized();
impl /*struct*/ QQuickWindow {
pub fn isSceneGraphInitialized<RetType, T: QQuickWindow_isSceneGraphInitialized<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSceneGraphInitialized(self);
// return 1;
}
}
pub trait QQuickWindow_isSceneGraphInitialized<RetType> {
fn isSceneGraphInitialized(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: bool QQuickWindow::isSceneGraphInitialized();
impl<'a> /*trait*/ QQuickWindow_isSceneGraphInitialized<i8> for () {
fn isSceneGraphInitialized(self , rsthis: & QQuickWindow) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow23isSceneGraphInitializedEv()};
let mut ret = unsafe {_ZNK12QQuickWindow23isSceneGraphInitializedEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QQuickWindow::setClearBeforeRendering(bool enabled);
impl /*struct*/ QQuickWindow {
pub fn setClearBeforeRendering<RetType, T: QQuickWindow_setClearBeforeRendering<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setClearBeforeRendering(self);
// return 1;
}
}
pub trait QQuickWindow_setClearBeforeRendering<RetType> {
fn setClearBeforeRendering(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::setClearBeforeRendering(bool enabled);
impl<'a> /*trait*/ QQuickWindow_setClearBeforeRendering<()> for (i8) {
fn setClearBeforeRendering(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow23setClearBeforeRenderingEb()};
let arg0 = self as c_char;
unsafe {_ZN12QQuickWindow23setClearBeforeRenderingEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QImage QQuickWindow::grabWindow();
impl /*struct*/ QQuickWindow {
pub fn grabWindow<RetType, T: QQuickWindow_grabWindow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.grabWindow(self);
// return 1;
}
}
pub trait QQuickWindow_grabWindow<RetType> {
fn grabWindow(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QImage QQuickWindow::grabWindow();
impl<'a> /*trait*/ QQuickWindow_grabWindow<QImage> for () {
fn grabWindow(self , rsthis: & QQuickWindow) -> QImage {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow10grabWindowEv()};
let mut ret = unsafe {_ZN12QQuickWindow10grabWindowEv(rsthis.qclsinst)};
let mut ret1 = QImage::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickWindow::setPersistentOpenGLContext(bool persistent);
impl /*struct*/ QQuickWindow {
pub fn setPersistentOpenGLContext<RetType, T: QQuickWindow_setPersistentOpenGLContext<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPersistentOpenGLContext(self);
// return 1;
}
}
pub trait QQuickWindow_setPersistentOpenGLContext<RetType> {
fn setPersistentOpenGLContext(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: void QQuickWindow::setPersistentOpenGLContext(bool persistent);
impl<'a> /*trait*/ QQuickWindow_setPersistentOpenGLContext<()> for (i8) {
fn setPersistentOpenGLContext(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow26setPersistentOpenGLContextEb()};
let arg0 = self as c_char;
unsafe {_ZN12QQuickWindow26setPersistentOpenGLContextEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QQuickWindow::sendEvent(QQuickItem * , QEvent * );
impl /*struct*/ QQuickWindow {
pub fn sendEvent<RetType, T: QQuickWindow_sendEvent<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sendEvent(self);
// return 1;
}
}
pub trait QQuickWindow_sendEvent<RetType> {
fn sendEvent(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: bool QQuickWindow::sendEvent(QQuickItem * , QEvent * );
impl<'a> /*trait*/ QQuickWindow_sendEvent<i8> for (&'a QQuickItem, &'a QEvent) {
fn sendEvent(self , rsthis: & QQuickWindow) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow9sendEventEP10QQuickItemP6QEvent()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN12QQuickWindow9sendEventEP10QQuickItemP6QEvent(rsthis.qclsinst, arg0, arg1)};
return ret as i8;
// return 1;
}
}
// proto: QOpenGLFramebufferObject * QQuickWindow::renderTarget();
impl /*struct*/ QQuickWindow {
pub fn renderTarget<RetType, T: QQuickWindow_renderTarget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.renderTarget(self);
// return 1;
}
}
pub trait QQuickWindow_renderTarget<RetType> {
fn renderTarget(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QOpenGLFramebufferObject * QQuickWindow::renderTarget();
impl<'a> /*trait*/ QQuickWindow_renderTarget<()> for () {
fn renderTarget(self , rsthis: & QQuickWindow) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow12renderTargetEv()};
unsafe {_ZNK12QQuickWindow12renderTargetEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QSGTexture * QQuickWindow::createTextureFromImage(const QImage & image);
impl /*struct*/ QQuickWindow {
pub fn createTextureFromImage<RetType, T: QQuickWindow_createTextureFromImage<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.createTextureFromImage(self);
// return 1;
}
}
pub trait QQuickWindow_createTextureFromImage<RetType> {
fn createTextureFromImage(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QSGTexture * QQuickWindow::createTextureFromImage(const QImage & image);
impl<'a> /*trait*/ QQuickWindow_createTextureFromImage<QSGTexture> for (&'a QImage) {
fn createTextureFromImage(self , rsthis: & QQuickWindow) -> QSGTexture {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow22createTextureFromImageERK6QImage()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK12QQuickWindow22createTextureFromImageERK6QImage(rsthis.qclsinst, arg0)};
let mut ret1 = QSGTexture::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QQmlIncubationController * QQuickWindow::incubationController();
impl /*struct*/ QQuickWindow {
pub fn incubationController<RetType, T: QQuickWindow_incubationController<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.incubationController(self);
// return 1;
}
}
pub trait QQuickWindow_incubationController<RetType> {
fn incubationController(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QQmlIncubationController * QQuickWindow::incubationController();
impl<'a> /*trait*/ QQuickWindow_incubationController<QQmlIncubationController> for () {
fn incubationController(self , rsthis: & QQuickWindow) -> QQmlIncubationController {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow20incubationControllerEv()};
let mut ret = unsafe {_ZNK12QQuickWindow20incubationControllerEv(rsthis.qclsinst)};
let mut ret1 = QQmlIncubationController::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickWindow::clearBeforeRendering();
impl /*struct*/ QQuickWindow {
pub fn clearBeforeRendering<RetType, T: QQuickWindow_clearBeforeRendering<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clearBeforeRendering(self);
// return 1;
}
}
pub trait QQuickWindow_clearBeforeRendering<RetType> {
fn clearBeforeRendering(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: bool QQuickWindow::clearBeforeRendering();
impl<'a> /*trait*/ QQuickWindow_clearBeforeRendering<i8> for () {
fn clearBeforeRendering(self , rsthis: & QQuickWindow) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow20clearBeforeRenderingEv()};
let mut ret = unsafe {_ZNK12QQuickWindow20clearBeforeRenderingEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QQuickItem * QQuickWindow::contentItem();
impl /*struct*/ QQuickWindow {
pub fn contentItem<RetType, T: QQuickWindow_contentItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.contentItem(self);
// return 1;
}
}
pub trait QQuickWindow_contentItem<RetType> {
fn contentItem(self , rsthis: & QQuickWindow) -> RetType;
}
// proto: QQuickItem * QQuickWindow::contentItem();
impl<'a> /*trait*/ QQuickWindow_contentItem<QQuickItem> for () {
fn contentItem(self , rsthis: & QQuickWindow) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QQuickWindow11contentItemEv()};
let mut ret = unsafe {_ZNK12QQuickWindow11contentItemEv(rsthis.qclsinst)};
let mut ret1 = QQuickItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static bool QQuickWindow::hasDefaultAlphaBuffer();
impl /*struct*/ QQuickWindow {
pub fn hasDefaultAlphaBuffer_s<RetType, T: QQuickWindow_hasDefaultAlphaBuffer_s<RetType>>( overload_args: T) -> RetType {
return overload_args.hasDefaultAlphaBuffer_s();
// return 1;
}
}
pub trait QQuickWindow_hasDefaultAlphaBuffer_s<RetType> {
fn hasDefaultAlphaBuffer_s(self ) -> RetType;
}
// proto: static bool QQuickWindow::hasDefaultAlphaBuffer();
impl<'a> /*trait*/ QQuickWindow_hasDefaultAlphaBuffer_s<i8> for () {
fn hasDefaultAlphaBuffer_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QQuickWindow21hasDefaultAlphaBufferEv()};
let mut ret = unsafe {_ZN12QQuickWindow21hasDefaultAlphaBufferEv()};
return ret as i8;
// return 1;
}
}
#[derive(Default)] // for QQuickWindow_colorChanged
pub struct QQuickWindow_colorChanged_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn colorChanged(&self) -> QQuickWindow_colorChanged_signal {
return QQuickWindow_colorChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_colorChanged_signal {
pub fn connect<T: QQuickWindow_colorChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_colorChanged_signal_connect {
fn connect(self, sigthis: QQuickWindow_colorChanged_signal);
}
#[derive(Default)] // for QQuickWindow_sceneGraphInvalidated
pub struct QQuickWindow_sceneGraphInvalidated_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn sceneGraphInvalidated(&self) -> QQuickWindow_sceneGraphInvalidated_signal {
return QQuickWindow_sceneGraphInvalidated_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_sceneGraphInvalidated_signal {
pub fn connect<T: QQuickWindow_sceneGraphInvalidated_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_sceneGraphInvalidated_signal_connect {
fn connect(self, sigthis: QQuickWindow_sceneGraphInvalidated_signal);
}
#[derive(Default)] // for QQuickWindow_beforeSynchronizing
pub struct QQuickWindow_beforeSynchronizing_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn beforeSynchronizing(&self) -> QQuickWindow_beforeSynchronizing_signal {
return QQuickWindow_beforeSynchronizing_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_beforeSynchronizing_signal {
pub fn connect<T: QQuickWindow_beforeSynchronizing_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_beforeSynchronizing_signal_connect {
fn connect(self, sigthis: QQuickWindow_beforeSynchronizing_signal);
}
#[derive(Default)] // for QQuickWindow_sceneGraphAboutToStop
pub struct QQuickWindow_sceneGraphAboutToStop_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn sceneGraphAboutToStop(&self) -> QQuickWindow_sceneGraphAboutToStop_signal {
return QQuickWindow_sceneGraphAboutToStop_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_sceneGraphAboutToStop_signal {
pub fn connect<T: QQuickWindow_sceneGraphAboutToStop_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_sceneGraphAboutToStop_signal_connect {
fn connect(self, sigthis: QQuickWindow_sceneGraphAboutToStop_signal);
}
#[derive(Default)] // for QQuickWindow_afterAnimating
pub struct QQuickWindow_afterAnimating_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn afterAnimating(&self) -> QQuickWindow_afterAnimating_signal {
return QQuickWindow_afterAnimating_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_afterAnimating_signal {
pub fn connect<T: QQuickWindow_afterAnimating_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_afterAnimating_signal_connect {
fn connect(self, sigthis: QQuickWindow_afterAnimating_signal);
}
#[derive(Default)] // for QQuickWindow_sceneGraphError
pub struct QQuickWindow_sceneGraphError_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn sceneGraphError(&self) -> QQuickWindow_sceneGraphError_signal {
return QQuickWindow_sceneGraphError_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_sceneGraphError_signal {
pub fn connect<T: QQuickWindow_sceneGraphError_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_sceneGraphError_signal_connect {
fn connect(self, sigthis: QQuickWindow_sceneGraphError_signal);
}
#[derive(Default)] // for QQuickWindow_sceneGraphInitialized
pub struct QQuickWindow_sceneGraphInitialized_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn sceneGraphInitialized(&self) -> QQuickWindow_sceneGraphInitialized_signal {
return QQuickWindow_sceneGraphInitialized_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_sceneGraphInitialized_signal {
pub fn connect<T: QQuickWindow_sceneGraphInitialized_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_sceneGraphInitialized_signal_connect {
fn connect(self, sigthis: QQuickWindow_sceneGraphInitialized_signal);
}
#[derive(Default)] // for QQuickWindow_activeFocusItemChanged
pub struct QQuickWindow_activeFocusItemChanged_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn activeFocusItemChanged(&self) -> QQuickWindow_activeFocusItemChanged_signal {
return QQuickWindow_activeFocusItemChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_activeFocusItemChanged_signal {
pub fn connect<T: QQuickWindow_activeFocusItemChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_activeFocusItemChanged_signal_connect {
fn connect(self, sigthis: QQuickWindow_activeFocusItemChanged_signal);
}
#[derive(Default)] // for QQuickWindow_afterRendering
pub struct QQuickWindow_afterRendering_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn afterRendering(&self) -> QQuickWindow_afterRendering_signal {
return QQuickWindow_afterRendering_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_afterRendering_signal {
pub fn connect<T: QQuickWindow_afterRendering_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_afterRendering_signal_connect {
fn connect(self, sigthis: QQuickWindow_afterRendering_signal);
}
#[derive(Default)] // for QQuickWindow_closing
pub struct QQuickWindow_closing_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn closing(&self) -> QQuickWindow_closing_signal {
return QQuickWindow_closing_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_closing_signal {
pub fn connect<T: QQuickWindow_closing_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_closing_signal_connect {
fn connect(self, sigthis: QQuickWindow_closing_signal);
}
#[derive(Default)] // for QQuickWindow_afterSynchronizing
pub struct QQuickWindow_afterSynchronizing_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn afterSynchronizing(&self) -> QQuickWindow_afterSynchronizing_signal {
return QQuickWindow_afterSynchronizing_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_afterSynchronizing_signal {
pub fn connect<T: QQuickWindow_afterSynchronizing_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_afterSynchronizing_signal_connect {
fn connect(self, sigthis: QQuickWindow_afterSynchronizing_signal);
}
#[derive(Default)] // for QQuickWindow_beforeRendering
pub struct QQuickWindow_beforeRendering_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn beforeRendering(&self) -> QQuickWindow_beforeRendering_signal {
return QQuickWindow_beforeRendering_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_beforeRendering_signal {
pub fn connect<T: QQuickWindow_beforeRendering_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_beforeRendering_signal_connect {
fn connect(self, sigthis: QQuickWindow_beforeRendering_signal);
}
#[derive(Default)] // for QQuickWindow_frameSwapped
pub struct QQuickWindow_frameSwapped_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn frameSwapped(&self) -> QQuickWindow_frameSwapped_signal {
return QQuickWindow_frameSwapped_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_frameSwapped_signal {
pub fn connect<T: QQuickWindow_frameSwapped_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_frameSwapped_signal_connect {
fn connect(self, sigthis: QQuickWindow_frameSwapped_signal);
}
#[derive(Default)] // for QQuickWindow_openglContextCreated
pub struct QQuickWindow_openglContextCreated_signal{poi:u64}
impl /* struct */ QQuickWindow {
pub fn openglContextCreated(&self) -> QQuickWindow_openglContextCreated_signal {
return QQuickWindow_openglContextCreated_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickWindow_openglContextCreated_signal {
pub fn connect<T: QQuickWindow_openglContextCreated_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickWindow_openglContextCreated_signal_connect {
fn connect(self, sigthis: QQuickWindow_openglContextCreated_signal);
}
// frameSwapped()
extern fn QQuickWindow_frameSwapped_signal_connect_cb_0(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_frameSwapped_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_frameSwapped_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_frameSwapped_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 = QQuickWindow_frameSwapped_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow12frameSwappedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_frameSwapped_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_frameSwapped_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 = QQuickWindow_frameSwapped_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow12frameSwappedEv(arg0, arg1, arg2)};
}
}
// afterRendering()
extern fn QQuickWindow_afterRendering_signal_connect_cb_1(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_afterRendering_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_afterRendering_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_afterRendering_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 = QQuickWindow_afterRendering_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow14afterRenderingEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_afterRendering_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_afterRendering_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 = QQuickWindow_afterRendering_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow14afterRenderingEv(arg0, arg1, arg2)};
}
}
// beforeRendering()
extern fn QQuickWindow_beforeRendering_signal_connect_cb_2(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_beforeRendering_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_beforeRendering_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_beforeRendering_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 = QQuickWindow_beforeRendering_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow15beforeRenderingEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_beforeRendering_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_beforeRendering_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 = QQuickWindow_beforeRendering_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow15beforeRenderingEv(arg0, arg1, arg2)};
}
}
// sceneGraphInvalidated()
extern fn QQuickWindow_sceneGraphInvalidated_signal_connect_cb_3(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_sceneGraphInvalidated_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_sceneGraphInvalidated_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_sceneGraphInvalidated_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 = QQuickWindow_sceneGraphInvalidated_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphInvalidatedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_sceneGraphInvalidated_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_sceneGraphInvalidated_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 = QQuickWindow_sceneGraphInvalidated_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphInvalidatedEv(arg0, arg1, arg2)};
}
}
// activeFocusItemChanged()
extern fn QQuickWindow_activeFocusItemChanged_signal_connect_cb_4(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_activeFocusItemChanged_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_activeFocusItemChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_activeFocusItemChanged_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 = QQuickWindow_activeFocusItemChanged_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow22activeFocusItemChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_activeFocusItemChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_activeFocusItemChanged_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 = QQuickWindow_activeFocusItemChanged_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow22activeFocusItemChangedEv(arg0, arg1, arg2)};
}
}
// afterSynchronizing()
extern fn QQuickWindow_afterSynchronizing_signal_connect_cb_5(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_afterSynchronizing_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_afterSynchronizing_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_afterSynchronizing_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 = QQuickWindow_afterSynchronizing_signal_connect_cb_5 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow18afterSynchronizingEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_afterSynchronizing_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_afterSynchronizing_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 = QQuickWindow_afterSynchronizing_signal_connect_cb_box_5 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow18afterSynchronizingEv(arg0, arg1, arg2)};
}
}
// beforeSynchronizing()
extern fn QQuickWindow_beforeSynchronizing_signal_connect_cb_6(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_beforeSynchronizing_signal_connect_cb_box_6(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_beforeSynchronizing_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_beforeSynchronizing_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 = QQuickWindow_beforeSynchronizing_signal_connect_cb_6 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow19beforeSynchronizingEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_beforeSynchronizing_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_beforeSynchronizing_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 = QQuickWindow_beforeSynchronizing_signal_connect_cb_box_6 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow19beforeSynchronizingEv(arg0, arg1, arg2)};
}
}
// openglContextCreated(class QOpenGLContext *)
extern fn QQuickWindow_openglContextCreated_signal_connect_cb_7(rsfptr:fn(QOpenGLContext), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QOpenGLContext::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QQuickWindow_openglContextCreated_signal_connect_cb_box_7(rsfptr_raw:*mut Box<Fn(QOpenGLContext)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QOpenGLContext::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickWindow_openglContextCreated_signal_connect for fn(QOpenGLContext) {
fn connect(self, sigthis: QQuickWindow_openglContextCreated_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 = QQuickWindow_openglContextCreated_signal_connect_cb_7 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow20openglContextCreatedEP14QOpenGLContext(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_openglContextCreated_signal_connect for Box<Fn(QOpenGLContext)> {
fn connect(self, sigthis: QQuickWindow_openglContextCreated_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 = QQuickWindow_openglContextCreated_signal_connect_cb_box_7 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow20openglContextCreatedEP14QOpenGLContext(arg0, arg1, arg2)};
}
}
// colorChanged(const class QColor &)
extern fn QQuickWindow_colorChanged_signal_connect_cb_8(rsfptr:fn(QColor), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QColor::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QQuickWindow_colorChanged_signal_connect_cb_box_8(rsfptr_raw:*mut Box<Fn(QColor)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QColor::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickWindow_colorChanged_signal_connect for fn(QColor) {
fn connect(self, sigthis: QQuickWindow_colorChanged_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 = QQuickWindow_colorChanged_signal_connect_cb_8 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow12colorChangedERK6QColor(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_colorChanged_signal_connect for Box<Fn(QColor)> {
fn connect(self, sigthis: QQuickWindow_colorChanged_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 = QQuickWindow_colorChanged_signal_connect_cb_box_8 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow12colorChangedERK6QColor(arg0, arg1, arg2)};
}
}
// sceneGraphInitialized()
extern fn QQuickWindow_sceneGraphInitialized_signal_connect_cb_9(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_sceneGraphInitialized_signal_connect_cb_box_9(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_sceneGraphInitialized_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_sceneGraphInitialized_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 = QQuickWindow_sceneGraphInitialized_signal_connect_cb_9 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphInitializedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_sceneGraphInitialized_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_sceneGraphInitialized_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 = QQuickWindow_sceneGraphInitialized_signal_connect_cb_box_9 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphInitializedEv(arg0, arg1, arg2)};
}
}
// sceneGraphAboutToStop()
extern fn QQuickWindow_sceneGraphAboutToStop_signal_connect_cb_10(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_sceneGraphAboutToStop_signal_connect_cb_box_10(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_sceneGraphAboutToStop_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_sceneGraphAboutToStop_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 = QQuickWindow_sceneGraphAboutToStop_signal_connect_cb_10 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphAboutToStopEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_sceneGraphAboutToStop_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_sceneGraphAboutToStop_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 = QQuickWindow_sceneGraphAboutToStop_signal_connect_cb_box_10 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow21sceneGraphAboutToStopEv(arg0, arg1, arg2)};
}
}
// afterAnimating()
extern fn QQuickWindow_afterAnimating_signal_connect_cb_11(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickWindow_afterAnimating_signal_connect_cb_box_11(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickWindow_afterAnimating_signal_connect for fn() {
fn connect(self, sigthis: QQuickWindow_afterAnimating_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 = QQuickWindow_afterAnimating_signal_connect_cb_11 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow14afterAnimatingEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickWindow_afterAnimating_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickWindow_afterAnimating_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 = QQuickWindow_afterAnimating_signal_connect_cb_box_11 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickWindow_SlotProxy_connect__ZN12QQuickWindow14afterAnimatingEv(arg0, arg1, arg2)};
}
}
// <= body block end
|
#[path = "with_empty_list_options/with_timer.rs"]
mod with_timer;
test_stdout!(without_timer_returns_false, "false\n");
|
fn main()
{
println!("Hello World. I am a Rustecean.")
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.