text stringlengths 8 4.13M |
|---|
//////////////////////////////////////////////////
//
// sound.rs
// 波形データを受け取って再生するサンプル
//
extern crate alto;
extern crate failure;
// alto
use alto::*;
// failure
use failure::Error;
// rust std
use std::cmp::min;
// inner modules
use crate::wave::*;
pub fn stream_play(info: &WaveInformation, data: &WaveBuffer) -> Result<(), Error>
{
let alto = Alto::load_default().unwrap();
let device = alto.open(None).unwrap();
let context = device.new_context(None).unwrap();
let mut source = context.new_streaming_source().unwrap();
let mut que_count = 0;
for i in 0..
{
let rate = info.sampling_rate;
let curr = ((rate * 4) * i) as usize;
let buffer = match data
{
WaveBuffer::U8Mono(data) =>
{
if ((rate * 4) * i) as usize >= data.len() { break; }
let next = min(((rate * 4) * (i + 1)) as usize, data.len());
context.new_buffer(&data[curr..next], rate as i32).unwrap()
},
WaveBuffer::I16Mono(data) =>
{
if ((rate * 4) * i) as usize >= data.len() { break; }
let next = min(((rate * 4) * (i + 1)) as usize, data.len());
context.new_buffer(&data[curr..next], rate as i32).unwrap()
},
WaveBuffer::U8Stereo(data) =>
{
if ((rate * 4) * i) as usize >= data.len() { break; }
let next = min(((rate * 4) * (i + 1)) as usize, data.len());
context.new_buffer(&data[curr..next], rate as i32).unwrap()
},
WaveBuffer::I16Stereo(data) =>
{
if ((rate * 4) * i) as usize >= data.len() { break; }
let next = min(((rate * 4) * (i + 1)) as usize, data.len());
context.new_buffer(&data[curr..next], rate as i32).unwrap()
},
};
source.queue_buffer(buffer).unwrap();
que_count += 1;
}
source.play();
while source.buffers_processed() < que_count { }
Ok(())
} |
#[cfg(any(feature = "bpf_c", feature = "bpf_rust"))]
mod bpf {
use morgan_runtime::bank::Bank;
use morgan_runtime::bank_client::BankClient;
use morgan_runtime::loader_utils::load_program;
use morgan_interface::genesis_block::create_genesis_block;
use morgan_interface::native_loader;
use std::env;
use std::fs::File;
use std::path::PathBuf;
/// BPF program file extension
const PLATFORM_FILE_EXTENSION_BPF: &str = "so";
/// Create a BPF program file name
fn create_bpf_path(name: &str) -> PathBuf {
let mut pathbuf = {
let current_exe = env::current_exe().unwrap();
PathBuf::from(current_exe.parent().unwrap().parent().unwrap())
};
pathbuf.push("bpf/");
pathbuf.push(name);
pathbuf.set_extension(PLATFORM_FILE_EXTENSION_BPF);
pathbuf
}
#[cfg(feature = "bpf_c")]
mod bpf_c {
use super::*;
use morgan_runtime::loader_utils::create_invoke_instruction;
use morgan_interface::bpf_loader;
use morgan_interface::client::SyncClient;
use morgan_interface::signature::KeypairUtil;
use std::io::Read;
#[test]
fn test_program_bpf_c_noop() {
morgan_logger::setup();
let mut file = File::open(create_bpf_path("noop")).expect("file open failed");
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
let (genesis_block, alice_keypair) = create_genesis_block(50);
let bank = Bank::new(&genesis_block);
let bank_client = BankClient::new(bank);
// Call user program
let program_id = load_program(&bank_client, &alice_keypair, &bpf_loader::id(), elf);
let instruction = create_invoke_instruction(alice_keypair.pubkey(), program_id, &1u8);
bank_client
.send_instruction(&alice_keypair, instruction)
.unwrap();
}
#[test]
fn test_program_bpf_c() {
morgan_logger::setup();
let programs = [
"bpf_to_bpf",
"multiple_static",
"noop",
"noop++",
"relative_call",
"struct_pass",
"struct_ret",
];
for program in programs.iter() {
println!("Test program: {:?}", program);
let mut file = File::open(create_bpf_path(program)).expect("file open failed");
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
let (genesis_block, alice_keypair) = create_genesis_block(50);
let bank = Bank::new(&genesis_block);
let bank_client = BankClient::new(bank);
let loader_pubkey = load_program(
&bank_client,
&alice_keypair,
&native_loader::id(),
"morgan_bpf_loader".as_bytes().to_vec(),
);
// Call user program
let program_id = load_program(&bank_client, &alice_keypair, &loader_pubkey, elf);
let instruction =
create_invoke_instruction(alice_keypair.pubkey(), program_id, &1u8);
bank_client
.send_instruction(&alice_keypair, instruction)
.unwrap();
}
}
}
#[cfg(feature = "bpf_rust")]
mod bpf_rust {
use super::*;
use morgan_interface::client::SyncClient;
use morgan_interface::instruction::{AccountMeta, Instruction};
use morgan_interface::signature::{Keypair, KeypairUtil};
use std::io::Read;
#[test]
fn test_program_bpf_rust() {
morgan_logger::setup();
let programs = [
"morgan_bpf_rust_alloc",
// Disable due to #4271 "morgan_bpf_rust_iter",
"morgan_bpf_rust_noop",
];
for program in programs.iter() {
let filename = create_bpf_path(program);
println!("Test program: {:?} from {:?}", program, filename);
let mut file = File::open(filename).unwrap();
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
let (genesis_block, alice_keypair) = create_genesis_block(50);
let bank = Bank::new(&genesis_block);
let bank_client = BankClient::new(bank);
let loader_pubkey = load_program(
&bank_client,
&alice_keypair,
&native_loader::id(),
"morgan_bpf_loader".as_bytes().to_vec(),
);
// Call user program
let program_id = load_program(&bank_client, &alice_keypair, &loader_pubkey, elf);
let account_metas = vec![
AccountMeta::new(alice_keypair.pubkey(), true),
AccountMeta::new(Keypair::new().pubkey(), false),
];
let instruction = Instruction::new(program_id, &1u8, account_metas);
bank_client
.send_instruction(&alice_keypair, instruction)
.unwrap();
}
}
}
}
|
extern crate prost_build;
fn main() {
println!("cargo:rerun-if-changed=src/items.proto");
prost_build::compile_protos(&["src/items.proto"], &["src/"]).unwrap();
}
|
use tonic::transport::Certificate;
use x509_parser::prelude::*;
/// A CommonName extracted from a mTLS client certificate
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ClientName(String);
impl ClientName {
/// Extract subject CommonName fields from a DER-encoded certificate.
/// Pre-condition: Certificate validated by the tonic server.
/// Pre-condition: Root CA will not sign nonconforming certificates.
/// Might panic if pre-conditions are not met.
pub fn from_cert(cert: &Certificate) -> Self {
let (_, x509) = parse_x509_certificate(cert.get_ref()).expect("Could not decode DER data");
let s = x509.subject();
let name = s
.iter_common_name()
.next()
.expect("Client CN missing from certificate");
let cn = name.as_str().expect("Could not get client CN as string");
Self(cn.to_owned())
}
/// Reads certificate info from a Tonic request
pub fn from_request<T>(request: &tonic::Request<T>) -> Option<Self> {
use std::borrow::Borrow;
let arc = request.peer_certs()?;
let certs: &Vec<Certificate> = arc.borrow();
Some(ClientName::from_cert(certs.first()?))
}
}
|
use std::mem;
pub fn move_element<T>(vector: &mut Vec<Option<T>>, index: usize) -> Option<T> {
mem::replace(&mut vector[index], None)
}
macro_rules! move_tuplet {
{ ($y:ident $(, $x:ident)*) = $v:expr } => {
let ($y, $($x),*) = move_tuplet!($v ; 1 ; ($($x),*) ; (move_element(&mut $v, 0)) );
};
{ $v:expr ; $j:expr ; ($y:ident $(, $x:ident)*) ; ($($a:expr),*) } => {
move_tuplet!( $v ; $j+1 ; ($($x),*) ; ($($a),*,move_element(&mut $v, $j)) )
};
{ $v:expr ; $j:expr ; () ; $accu:expr } => {
$accu
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tuplet_test() {
let mut v = vec![Some(1), Some(2), Some(3)];
move_tuplet!((a, b, c) = v);
assert_eq!(a, Some(1));
assert_eq!(b, Some(2));
assert_eq!(c, Some(3));
}
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
use crate::erlang::read_timer;
#[native_implemented::function(erlang:read_timer/1)]
pub fn result(process: &Process, timer_reference: Term) -> exception::Result<Term> {
read_timer(timer_reference, Default::default(), process).map_err(From::from)
}
|
use piston_window::{PistonWindow, WindowSettings, Window, Glyphs, TextureSettings};
use glfw_window::GlfwWindow;
use piston_window::{Event, Input};
use crate::widget::Widget;
use crate::widget::Rect;
pub struct DrawingWindow {
pub window: PistonWindow<GlfwWindow>,
pub root: Box<Widget>,
pub glyphs: Glyphs
}
impl DrawingWindow {
pub fn new(root: Box<Widget>) -> Self {
let window: PistonWindow<GlfwWindow> =
WindowSettings::new("title", [640, 480])
.build().unwrap();
let font_data: &[u8] = include_bytes!("../assets/FiraSans-Regular.ttf");
let factory = window.factory.clone();
let glyphs = Glyphs::from_bytes(font_data, factory, TextureSettings::new()).unwrap();
DrawingWindow {
window,
root,
glyphs
}
}
pub fn run(&mut self) {
let mut first = true;
let root = &mut self.root;
let glyphs = &mut self.glyphs;
while let Some(event) = self.window.next() {
let width = self.window.size().width;
let height = self.window.size().height;
if first {
let rect = Rect {
origin: [0.0, 0.0],
size: [width as f64, height as f64]
};
root.layout(rect);
first = false;
}
self.window.draw_2d(&event, |ctx, gl| {
root.draw(ctx, gl, glyphs);
});
match event {
Event::Input(ref input) => {
match input {
Input::Resize(ref x, ref y) => {
let rect = Rect {
origin: [0.0, 0.0],
size: [x.clone(), y.clone()]
};
root.layout(rect);
println!("resize {} {}", x, y);
},
_ => {}
}
},
Event::Loop(ref l) => {
},
Event::Custom(ref id, _) => {
}
}
// if let Some(Button::Keyboard(key)) = event.press_args() {
// self.handle_key_input(key);
// self.render(&event, window);
// };
}
}
}
|
extern crate proc_macro;
use proc_macro::TokenStream;
use syn::{parse_macro_input, Result, Token};
use syn::parse::{Parse, ParseStream};
use syn::LitInt;
struct RepeatInput {
times: LitInt,
tt: proc_macro2::TokenStream
}
impl Parse for RepeatInput {
fn parse(input: ParseStream) -> Result<Self> {
let times = syn::LitInt::parse(input)?;
let _comma = <Token![,]>::parse(input)?;
Ok(RepeatInput{
times,
tt: input.parse()?
})
}
}
#[proc_macro]
pub fn repeat(input: TokenStream) -> TokenStream {
//
let input = parse_macro_input!(input as RepeatInput);
let mut t = proc_macro2::TokenStream::new();
let times = input.times.base10_parse().unwrap();
for _ in 0..times {
t.extend(input.tt.clone());
}
t.into()
}
|
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
use crate::erlang::cancel_timer;
#[native_implemented::function(erlang:cancel_timer/1)]
pub fn result(process: &Process, timer_reference: Term) -> exception::Result<Term> {
cancel_timer(timer_reference, Default::default(), process).map_err(From::from)
}
|
use rowan::{GreenNode, TextRange};
use text_edit::Indel;
use crate::{SyntaxError, SyntaxNode};
pub(crate) fn incremental_reparse(
node: &SyntaxNode,
edit: &Indel,
errors: Vec<SyntaxError>,
) -> Option<(GreenNode, Vec<SyntaxError>, TextRange)> {
todo!()
}
|
/* origin: FreeBSD /usr/src/lib/msun/src/e_log.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* log(x)
* Return the logarithm of x
*
* Method :
* 1. Argument Reduction: find k and f such that
* x = 2^k * (1+f),
* where sqrt(2)/2 < 1+f < sqrt(2) .
*
* 2. Approximation of log(1+f).
* Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s)
* = 2s + 2/3 s**3 + 2/5 s**5 + .....,
* = 2s + s*R
* We use a special Remez algorithm on [0,0.1716] to generate
* a polynomial of degree 14 to approximate R The maximum error
* of this polynomial approximation is bounded by 2**-58.45. In
* other words,
* 2 4 6 8 10 12 14
* R(z) ~ Lg1*s +Lg2*s +Lg3*s +Lg4*s +Lg5*s +Lg6*s +Lg7*s
* (the values of Lg1 to Lg7 are listed in the program)
* and
* | 2 14 | -58.45
* | Lg1*s +...+Lg7*s - R(z) | <= 2
* | |
* Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2.
* In order to guarantee error in log below 1ulp, we compute log
* by
* log(1+f) = f - s*(f - R) (if f is not too large)
* log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy)
*
* 3. Finally, log(x) = k*ln2 + log(1+f).
* = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo)))
* Here ln2 is split into two floating point number:
* ln2_hi + ln2_lo,
* where n*ln2_hi is always exact for |n| < 2000.
*
* Special cases:
* log(x) is NaN with signal if x < 0 (including -INF) ;
* log(+INF) is +INF; log(0) is -INF with signal;
* log(NaN) is that NaN with no signal.
*
* Accuracy:
* according to an error analysis, the error is always less than
* 1 ulp (unit in the last place).
*
* Constants:
* The hexadecimal values are the intended ones for the following
* constants. The decimal values may be used, provided that the
* compiler will convert from decimal to binary accurately enough
* to produce the hexadecimal values shown.
*/
const LN2_HI: f64 = 6.93147180369123816490e-01; /* 3fe62e42 fee00000 */
const LN2_LO: f64 = 1.90821492927058770002e-10; /* 3dea39ef 35793c76 */
const LG1: f64 = 6.666666666666735130e-01; /* 3FE55555 55555593 */
const LG2: f64 = 3.999999999940941908e-01; /* 3FD99999 9997FA04 */
const LG3: f64 = 2.857142874366239149e-01; /* 3FD24924 94229359 */
const LG4: f64 = 2.222219843214978396e-01; /* 3FCC71C5 1D8E78AF */
const LG5: f64 = 1.818357216161805012e-01; /* 3FC74664 96CB03DE */
const LG6: f64 = 1.531383769920937332e-01; /* 3FC39A09 D078C69F */
const LG7: f64 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn log(mut x: f64) -> f64 {
let x1p54 = f64::from_bits(0x4350000000000000); // 0x1p54 === 2 ^ 54
let mut ui = x.to_bits();
let mut hx: u32 = (ui >> 32) as u32;
let mut k: i32 = 0;
if (hx < 0x00100000) || ((hx >> 31) != 0) {
/* x < 2**-126 */
if ui << 1 == 0 {
return -1. / (x * x); /* log(+-0)=-inf */
}
if hx >> 31 != 0 {
return (x - x) / 0.0; /* log(-#) = NaN */
}
/* subnormal number, scale x up */
k -= 54;
x *= x1p54;
ui = x.to_bits();
hx = (ui >> 32) as u32;
} else if hx >= 0x7ff00000 {
return x;
} else if hx == 0x3ff00000 && ui << 32 == 0 {
return 0.;
}
/* reduce x into [sqrt(2)/2, sqrt(2)] */
hx += 0x3ff00000 - 0x3fe6a09e;
k += ((hx >> 20) as i32) - 0x3ff;
hx = (hx & 0x000fffff) + 0x3fe6a09e;
ui = ((hx as u64) << 32) | (ui & 0xffffffff);
x = f64::from_bits(ui);
let f: f64 = x - 1.0;
let hfsq: f64 = 0.5 * f * f;
let s: f64 = f / (2.0 + f);
let z: f64 = s * s;
let w: f64 = z * z;
let t1: f64 = w * (LG2 + w * (LG4 + w * LG6));
let t2: f64 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7)));
let r: f64 = t2 + t1;
let dk: f64 = k as f64;
s * (hfsq + r) + dk * LN2_LO - hfsq + f + dk * LN2_HI
}
|
use std::fmt;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::io::Write;
use board::stones::stone::Stone;
use go_rules::go_action::GoAction;
pub struct Prop {
key: String,
value: String,
}
impl Display for Prop {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}[{}]", self.key, self.value)
}
}
pub struct Node {
props: Vec<Prop>
}
impl Display for Node {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, ";");
for prop in self.props.iter() {
write!(f, "{}", prop);
}
fmt::Result::Ok(())
}
}
pub struct Sequence {
data: Vec<Node>
}
impl Display for Sequence {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "(");
for n in self.data.iter() {
write!(f, "{}", n);
}
write!(f, ")")
}
}
pub struct SGF {}
impl SGF {
pub fn save(board_size: usize, stone: Stone, actions: &[GoAction]) {
if let Ok(mut file) = File::create("output.sgf") {
file.write_all(SGF::game(board_size, stone, actions).to_string().as_bytes());
}
}
fn prop(key: &str, value: &str) -> Prop {
Prop {
key: String::from(key),
value: String::from(value),
}
}
fn header(size: usize) -> Node {
Node {
props: vec![
SGF::prop("AP", "rust-mcts"),
SGF::prop("FF", "4"),
SGF::prop("GM", "1"),
SGF::prop("SZ", &size.to_string()),
SGF::prop("KM", "5.5"),
SGF::prop("PL", "B"),
SGF::prop("RU", "Japanese"),
]
}
}
fn action(stone: Stone, a: GoAction) -> Node {
let stone_string = format!("{:?}", stone).chars().next().unwrap().to_string();
let a_string = match a {
GoAction::Pass => String::from("tt"),
_ => {
a.to_string().to_lowercase()
}
};
Node {
props: vec![
SGF::prop(&stone_string, &a_string)
]
}
}
pub fn game(board_size: usize, stone: Stone, actions: &[GoAction]) -> Sequence {
let mut x = vec![SGF::header(board_size)];
let mut side = stone;
for &a in actions {
x.push(SGF::action(side, a));
side = side.switch();
}
Sequence {
data: x
}
}
}
#[test]
fn stone_groups() {
let main = SGF::game(13, Stone::Black, &[
GoAction::Cell(3, 2),
GoAction::Cell(2, 2),
GoAction::Cell(1, 1),
]);
let var1 = SGF::game(13, Stone::Black, &[
GoAction::Cell(3, 2),
GoAction::Cell(2, 2),
GoAction::Cell(1, 1),
]);
let var2 = SGF::game(13, Stone::Black, &[
GoAction::Cell(3, 2),
GoAction::Cell(2, 2),
GoAction::Cell(1, 1),
]);
println!("{}", main);
println!("{}", var1);
println!("{}", var2);
}
|
// Copyright 2020-2021, The Tremor Team
//
// 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.
//! # File Offramp
//!
//! Writes events to a file, one event per line
//!
//! ## Configuration
//!
//! See [Config](struct.Config.html) for details.
#![cfg(not(tarpaulin_include))]
use crate::sink::prelude::*;
use async_std::fs::File as FSFile;
use async_std::io::prelude::*;
use halfbrown::HashMap;
use tremor_common::asy::file as cfile;
/// An offramp that write a given file
pub struct File {
file: Option<FSFile>,
postprocessors: Postprocessors,
config: Config,
}
#[derive(Deserialize)]
pub struct Config {
/// Filename to write to
pub file: String,
}
impl ConfigImpl for Config {}
impl offramp::Impl for File {
fn from_config(config: &Option<OpConfig>) -> Result<Box<dyn Offramp>> {
if let Some(config) = config {
let config: Config = Config::new(config)?;
Ok(SinkManager::new_box(Self {
file: None,
config,
postprocessors: vec![],
}))
} else {
Err("Blackhole offramp requires a config".into())
}
}
}
#[async_trait::async_trait]
impl Sink for File {
async fn terminate(&mut self) {
if let Some(file) = &mut self.file {
if let Err(e) = file.flush().await {
error!("Failed to flush file: {}", e);
}
}
}
async fn on_event(
&mut self,
_input: &str,
codec: &mut dyn Codec,
_codec_map: &HashMap<String, Box<dyn Codec>>,
mut event: Event,
) -> ResultVec {
if let Some(file) = &mut self.file {
for value in event.value_iter() {
let raw = codec.encode(value)?;
let packets = postprocess(&mut self.postprocessors, event.ingest_ns, raw)?;
for packet in packets {
file.write_all(&packet).await?;
file.write_all(b"\n").await?;
}
}
file.flush().await?;
}
Ok(Some(vec![sink::Reply::Insight(event.insight_ack())]))
}
fn default_codec(&self) -> &str {
"json"
}
#[allow(clippy::too_many_arguments)]
async fn init(
&mut self,
_sink_uid: u64,
_sink_url: &TremorUrl,
_codec: &dyn Codec,
_codec_map: &HashMap<String, Box<dyn Codec>>,
processors: Processors<'_>,
_is_linked: bool,
_reply_channel: Sender<sink::Reply>,
) -> Result<()> {
self.postprocessors = make_postprocessors(processors.post)?;
let file = cfile::create(&self.config.file).await?;
self.file = Some(file);
Ok(())
}
async fn on_signal(&mut self, _signal: Event) -> ResultVec {
Ok(None)
}
fn is_active(&self) -> bool {
true
}
fn auto_ack(&self) -> bool {
true
}
}
|
use juniper::{
EmptySubscription, FieldResult, FieldError,
ID, RootNode, http::GraphQLRequest
};
use tide::{Body, Request, Response, StatusCode};
use uuid::Uuid;
use bson::{Bson, doc};
use mongodb::{Client, options::ClientOptions, Collection};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Clone)]
struct Store(Collection);
impl juniper::Context for Store {}
#[derive(Debug, Clone, juniper::GraphQLObject, Deserialize, Serialize)]
struct Item {
#[serde(rename = "_id")]
id: ID,
name: String,
value: i32,
}
#[derive(Debug, Clone, juniper::GraphQLInputObject)]
struct ItemInput {
name: String,
value: i32,
}
#[derive(Debug)]
struct Query;
#[juniper::graphql_object(Context = Store)]
impl Query {
async fn find(ctx: &Store, id: ID) -> FieldResult<Option<Item>> {
let query = doc! {"_id": id.to_string()};
ctx.0
.find_one(query, None)
.await
.map_err(|e|
error(format!("find error: {:?}", e).as_str())
)
.map(|r|
r.and_then(|b|
bson::from_document::<Item>(b).ok()
)
)
}
}
#[derive(Debug)]
struct Mutation;
#[juniper::graphql_object(Context = Store)]
impl Mutation {
async fn create(ctx: &Store, input: ItemInput) -> FieldResult<Item> {
let item = Item {
id: format!("item-{}", Uuid::new_v4()).into(),
name: input.name,
value: input.value,
};
if let Ok(Bson::Document(doc)) = bson::to_bson(&item) {
println!("to_bson: {:?}", doc);
ctx.0
.insert_one(doc, None)
.await
.map(|_| item)
.map_err(|e|
error(format!("insert error: {:?}", e).as_str())
)
} else {
Err(error("failed create"))
}
}
}
type Schema = RootNode<'static, Query, Mutation, EmptySubscription<Store>>;
type State = (Store, Arc<Schema>);
#[async_std::main]
async fn main() -> tide::Result<()> {
let opt = ClientOptions::parse("mongodb://localhost").await?;
let mongo = Client::with_options(opt)?;
let state = (
Store(mongo.database("items").collection("data")),
Arc::new(Schema::new(Query, Mutation, EmptySubscription::new())),
);
let mut app = tide::with_state(state);
app.at("/graphql").post(handle_graphql);
app.listen("127.0.0.1:8080").await?;
Ok(())
}
fn error(msg: &str) -> FieldError {
FieldError::new(msg, juniper::Value::Null)
}
async fn handle_graphql(mut req: Request<State>) -> tide::Result {
let query: GraphQLRequest = req.body_json().await?;
let state = req.state();
println!("{:?}", query);
let res = query.execute(&state.1, &state.0).await;
let status = if res.is_ok() {
StatusCode::Ok
} else {
StatusCode::BadRequest
};
Body::from_json(&res)
.map(|b|
Response::builder(status)
.body(b)
.build()
)
} |
pub(crate) mod systems;
pub mod module;
pub mod runner;
mod plugin;
pub use plugin::*;
|
use ggez::{self, error::GameResult, graphics};
pub trait Gui {
fn update(&mut self, mouse_x: f32, mouse_y: f32) -> GameResult<()>;
fn draw(&mut self, ctx: &mut ggez::Context, mouse_x: f32, mouse_y: f32) -> GameResult<()>;
fn mouse_pressed(&mut self, mouse_x: f32, mouse_y: f32);
fn mouse_released(&mut self, mouse_x: f32, mouse_y: f32);
}
pub trait ButtonType<T: Gui> {
fn perform(&self, gui: &mut T);
}
pub struct GuiComponents<G: Gui, T: ButtonType<G>> {
buttons: Vec<Button<G, T>>,
}
impl<G: Gui, T: ButtonType<G>> GuiComponents<G, T> {
pub fn new(buttons: Vec<Button<G, T>>) -> Self {
GuiComponents { buttons }
}
pub fn draw(&self, gui: &mut G, ctx: &mut ggez::Context, mouse_x: f32, mouse_y: f32) -> GameResult<()> {
for button in self.buttons {
button.draw(ctx, mouse_x, mouse_y)?;
}
Ok(())
}
pub fn mouse_pressed(&self, gui: &mut G, mouse_x: f32, mouse_y: f32) {
let button_types: Vec<ButtonType<G>> = self.buttons.iter()
.filter(|button| button.is_selected(mouse_x, mouse_y))
.map(|button| button.button_type.clone())
.collect();
for button_type in button_types {
button_type.perform(gui);
}
}
}
pub struct Button<G: Gui, T: ButtonType<G>> {
button_type: T,
pub pos: graphics::Point2,
pub size: graphics::Point2,
icon: Option<graphics::Image>,
fill_color: graphics::Color,
hover_color: graphics::Color,
}
impl<G: Gui, T: ButtonType<G>> Button<G, T> {
pub fn new(button_type: T, pos: graphics::Point2, size: graphics::Point2, icon: Option<graphics::Image>, fill_color: graphics::Color, hover_color: graphics::Color) -> Self {
Button { button_type, pos, size, icon, fill_color, hover_color }
}
pub fn draw(&self, ctx: &mut ggez::Context, mouse_x: f32, mouse_y: f32) -> GameResult<()> {
draw_rectangle(ctx, self.pos, self.size, if self.is_selected(mouse_x, mouse_y) {
self.hover_color
} else {
self.fill_color
})?;
if let Some(icon) = self.icon.as_ref() {
draw_texture(ctx, icon, graphics::Point2::new(
self.pos.x + (self.size.x - icon.width() as f32) / 2.0,
self.pos.y + (self.size.y - icon.height() as f32) / 2.0,
))?;
}
Ok(())
}
pub fn is_selected(&self, mouse_x: f32, mouse_y: f32) -> bool {
mouse_x >= self.pos.x && mouse_y >= self.pos.y && mouse_x < self.pos.x + self.size.x
&& mouse_y < self.pos.y + self.size.y
}
}
fn draw_rectangle(ctx: &mut ggez::Context, pos: graphics::Point2, size: graphics::Point2, color: graphics::Color) -> GameResult<()> {
graphics::set_color(ctx, color)?;
graphics::rectangle(ctx, graphics::DrawMode::Fill, graphics::Rect::new(
pos.x * ::GLOBAL_SCALE,
pos.y * ::GLOBAL_SCALE,
size.x * ::GLOBAL_SCALE,
size.y * ::GLOBAL_SCALE,
))?;
graphics::set_color(ctx, graphics::Color::new(1.0, 1.0, 1.0, 1.0))?;
Ok(())
}
fn draw_texture(ctx: &mut ggez::Context, icon: &graphics::Image, pos: graphics::Point2) -> GameResult<()> {
graphics::draw_ex(
ctx,
icon,
graphics::DrawParam {
src: graphics::Rect::one(),
dest: graphics::Point2::new(
pos.x * ::GLOBAL_SCALE,
pos.y * ::GLOBAL_SCALE,
),
rotation: 0.0,
scale: graphics::Point2::new(::GLOBAL_SCALE, ::GLOBAL_SCALE),
offset: graphics::Point2::new(0.0, 0.0),
shear: graphics::Point2::new(0.0, 0.0),
color: None,
},
)
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_meta_app::schema::DatabaseIdent;
use common_meta_app::schema::DatabaseInfo;
use common_meta_app::schema::DatabaseMeta;
use common_meta_app::schema::DatabaseNameIdent;
use common_storages_information_schema::ColumnsTable;
use common_storages_information_schema::KeyColumnUsageTable;
use common_storages_information_schema::KeywordsTable;
use common_storages_information_schema::SchemataTable;
use common_storages_information_schema::StatisticsTable;
use common_storages_information_schema::TablesTable;
use common_storages_information_schema::ViewsTable;
use crate::catalogs::InMemoryMetas;
use crate::databases::Database;
use crate::storages::Table;
#[derive(Clone)]
pub struct InformationSchemaDatabase {
db_info: DatabaseInfo,
}
impl InformationSchemaDatabase {
pub fn create(sys_db_meta: &mut InMemoryMetas) -> Self {
let table_list: Vec<Arc<dyn Table>> = vec![
ColumnsTable::create(sys_db_meta.next_table_id()),
TablesTable::create(sys_db_meta.next_table_id()),
KeywordsTable::create(sys_db_meta.next_table_id()),
ViewsTable::create(sys_db_meta.next_table_id()),
SchemataTable::create(sys_db_meta.next_table_id()),
StatisticsTable::create(sys_db_meta.next_table_id()),
KeyColumnUsageTable::create(sys_db_meta.next_table_id()),
];
let db = "information_schema";
for tbl in table_list.into_iter() {
sys_db_meta.insert(db, tbl);
}
let db_info = DatabaseInfo {
ident: DatabaseIdent {
db_id: sys_db_meta.next_db_id(),
seq: 0,
},
name_ident: DatabaseNameIdent {
tenant: "".to_string(),
db_name: db.to_string(),
},
meta: DatabaseMeta {
engine: "SYSTEM".to_string(),
..Default::default()
},
};
Self { db_info }
}
}
#[async_trait::async_trait]
impl Database for InformationSchemaDatabase {
fn name(&self) -> &str {
"information_schema"
}
fn get_db_info(&self) -> &DatabaseInfo {
&self.db_info
}
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use std::convert::TryInto;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
use crate::runtime::time::{monotonic, Unit};
#[native_implemented::function(erlang:monotonic_time/1)]
pub fn result(process: &Process, unit: Term) -> exception::Result<Term> {
let unit_unit: Unit = unit.try_into()?;
let big_int = monotonic::time_in_unit(unit_unit);
let term = process.integer(big_int);
Ok(term)
}
|
use yew::prelude::*;
pub struct UserViewDetail {}
pub enum Msg {}
impl Component for UserViewDetail {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
UserViewDetail {}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<>
<div class="mx-auto pt-5 pb-5 px-4" style="max-width: 1048px">
<div>
<a href="" class="text-muted">
<i class="bi bi-arrow-left me-2"></i>
<span>{"Back to users"}</span>
</a>
</div>
<div class="mt-2">
<div class="row">
<div class="col">
<p class="mb-0" style="font-size: 32px; font-weight: bold">
{"yeskahaganta3838@gmail.com"}
</p>
<p class="text-muted">
{"user_id : "}
<span>
<code style="background-color: beige; color: black"
>{"auth0|6137122101cefa0073474fbb"}</code
>
</span>
</p>
</div>
<div class="col-auto">
<div class="dropdown">
<a class="btn btn-primary dropdown-toggle mt-3" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
{"Actions"}
</a>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<li>
<a class="dropdown-item" href="#"><i class="bi bi-envelope me-2"></i
><span>{"Send Verification Email"}</span></a
>
</li>
<li>
<hr class="dropdown-divider" />
</li>
<li><a class="dropdown-item" href="#">{"Change Email"}</a></li>
<li>
<a class="dropdown-item" href="#">{"Change Password"}</a>
</li>
<li>
<hr class="dropdown-divider" />
</li>
<li>
<a class="dropdown-item" href="#">
<svg xmlns="http://www.w3.org/2000/svg" class="me-1" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"></line></svg>
<span> {"Block"} </span>
</a>
</li>
<li>
<a class="dropdown-item" href="#">
<i class="bi bi-trash text-danger"></i>
<span class="text-danger">{"Delete"}</span>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="mt-3">
<ul class="nav nav-tabs" id="myTab" role="tablist" style="font-size:13px;">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="user-details-tab" data-bs-toggle="tab" data-bs-target="#detailtab" type="button" role="tab" aria-controls="detailtab" aria-selected="true">{"Details"}</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="user-devices-tab" data-bs-toggle="tab" data-bs-target="#devicetab" type="button" role="tab" aria-controls="devicetab" aria-selected="false">{"Devices"}</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="user-history-tab" data-bs-toggle="tab" data-bs-target="#historytab" type="button" role="tab" aria-controls="historytab" aria-selected="false">{"History"}</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="rawjson-tab" data-bs-toggle="tab" data-bs-target="#rawjsontab" type="button" role="tab" aria-controls="rawjsontab" aria-selected="false">{"RAW JSON"}</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="authorapp-tab" data-bs-toggle="tab" data-bs-target="#authorapptab" type="button" role="tab" aria-controls="authorapptab" aria-selected="false">{"Authorized Applications"}</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="permission-tab" data-bs-toggle="tab" data-bs-target="#permissiontab" type="button" role="tab" aria-controls="permissiontab" aria-selected="false">{"Permissions"}</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="roles-tab" data-bs-toggle="tab" data-bs-target="#rolestab" type="button" role="tab" aria-controls="roles" aria-selected="false">{"Roles"}</button>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="detailtab" role="tabpanel" aria-labelledby="user-details-tab">
<div class="mt-4">
<div class="card">
<div class="card-body">
<div class="container">
<div class="row">
<div class="col">
<p class="text-muted mb-1">{"Name"}</p>
<p class="mb-1">{"yeskahaganta3838@gmail.com"}</p>
<a href="">{"Edit"}</a>
</div>
<div class="col">
<p class="text-muted mb-1 ">{"Email"}</p>
<p class="mb-1">{"yeskahaganta3838@gmail.com"}</p>
<p class="text-muted mb-1">{"(verified)"}</p>
<a href="">{"Edit"}</a>
</div>
<div class="col">
<p class="text-muted mb-1">{"Signed Up"}</p>
<p class="mb-1">{"September 7th 2021, 2:17:53 PM"}</p>
</div>
</div>
<div class="row mt-3">
<div class="col">
<p class="text-muted mb-1">{"Primary Identity Provider"}</p>
<p class="mb-1">{"Database"}</p>
</div>
<div class="col mb-1">
<p class="text-muted mb-1">{"Latest Login"}</p>
<p class="mb-1">{"Never"}</p>
</div>
<div class="col">
<p class="text-muted mb-1">{"Accounts Associated"}</p>
<p>{"None"}</p>
</div>
</div>
<div class="row mt-3">
<div class="col">
<p class="text-muted mb-1">{"Browser"}</p>
<p class="mb-1">{"Chrome 91.0.4472/ Linux 0.0.0"}</p>
</div>
<div class="col">
</div>
<div class="col">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="mt-4">
<div class="card">
<div class="card-body">
<p class="fw-bold">{"Multi-Factor Authentication"}</p>
<div class="p-4" style="background-color: rgb(239,240,242)">
<p class="text-center mb-0">{"MFA is enabled for this user. "} <a href="">{"Send and enrollment invitation."}</a></p>
</div>
</div>
</div>
</div>
<div class="mt-4">
</div>
</div>
<div class="tab-pane fade" id="devicetab" role="tabpanel" aria-labelledby="user-devices-tab">
<div class="mt-4">
<p>{"These are the devices being used by this particular user. If you click on Unlink, the refresh token will be revoked, forcing the user to re-login on the application."}</p>
</div>
<div class="mt-4">
<table class="table">
<thead>
<tr>
<th scope="col">{"Client"}</th>
<th scope="col">{"Devices"}</th>
<th scope="col">{"Number of Refresh Tokens"}</th>
</tr>
</thead>
</table>
<div class="p-4" style="background-color: rgb(239,240,242)">
<p class="text-center mb-0">{"There are no linked devices yet. "}</p>
</div>
</div>
</div>
<div class="tab-pane fade" id="historytab" role="tabpanel" aria-labelledby="user-history-tab">
<div class="mt-4">
<p>
{"Max. Log Storage: 2 days"}
</p>
</div>
<div class="mt-4">
<table class="table">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">{"Event"}</th>
<th scope="col">{"When"}</th>
<th scope="col">{"App"}</th>
<th scope="col">{"Identity Provider"}</th>
<th scope="col">{"From"}</th>
</tr>
</thead>
</table>
<div class="p-4" style="background-color: rgb(239,240,242)">
<p class="text-center mb-0">{"There are no logs yet. "}</p>
</div>
</div>
<div class="mt-4">
<div class="row">
<div class="col d-flex justify-content-start">
<button type="button" class="btn btn-primary" disabled=true>
<i class="bi bi-arrow-left"></i>
<span>{"Previous"}</span>
</button>
</div>
<div class="col d-flex justify-content-center">
<p>{"Page 1"}</p>
</div>
<div class="col d-flex justify-content-end">
<button type="button" class="btn btn-primary" disabled=true>
<i class="bi bi-arrow-right"></i>
<span>{"Next"}</span>
</button>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="rawjsontab" role="tabpanel" aria-labelledby="rawjson-tab">
</div>
<div class="tab-pane fade" id="authorapptab" role="tabpanel" aria-labelledby="authorapp-tab">
<div class="mt-4">
<p>{"List of applications that this user has authorized."}</p>
</div>
<div class="mt-4">
<div class="p-4" style="background-color: rgb(239,240,242)">
<p class="text-center mb-0">{"There are no applications to display. "}</p>
</div>
</div>
</div>
<div class="tab-pane fade" id="permissiontab" role="tabpanel" aria-labelledby="permission-tab">
<div class="mt-4">
<div class="row">
<div class="col d-flex justify-content-start">
<p>{"List of permissions this user has."}</p>
</div>
<div class="col d-flex justify-content-end">
<button type="button" class="btn btn-primary">{"Assign Permissions"}</button>
</div>
</div>
</div>
<div class="mt-4">
<table class="table">
<thead>
<tr>
<th scope="col">{"Name"}</th>
<th scope="col">{"Description"}</th>
<th scope="col">{"API"}</th>
<th scope="col">{"Assignment"}</th>
<th scope="col"></th>
</tr>
</thead>
</table>
</div>
<div class="mt-4">
<div class="p-4" style="background-color: rgb(239,240,242)">
<p class="text-center mb-0">{"There are no permissions assigned to this user yet. "}</p>
</div>
</div>
</div>
<div class="tab-pane fade" id="rolestab" role="tabpanel" aria-labelledby="roles-tab">
<div class="mt-4">
<div class="row">
<div class="col d-flex justify-content-start">
<p>{"All Roles assigned to this User."}</p>
</div>
<div class="col d-flex justify-content-end">
<button type="button" class="btn btn-primary">{"Assign Roles"}</button>
</div>
</div>
<div class="mt-4">
<table class="table">
<thead>
<tr>
<th scope="col">{"Name"}</th>
<th scope="col">{"Description"}</th>
<th scope="col">{"API"}</th>
<th scope="col">{"Assignment"}</th>
<th scope="col"></th>
</tr>
</thead>
</table>
</div>
<div class="mt-4">
<div class="p-4" style="background-color: rgb(239,240,242)">
<p class="text-center mb-0">{"There are no roles assigned to this user yet. "}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</>
}
}
}
|
use std::path::PathBuf;
use firefly_target::{CodeModel, LinkerFlavor, RelocModel, TlsModel};
use firefly_target::{MergeFunctions, RelroLevel};
use firefly_compiler_macros::option_group;
use crate::config::*;
#[option_group(
name = "codegen",
short = "C",
help = "Available flags for customizing code generation"
)]
#[derive(Debug, Clone, Default)]
pub struct CodegenOptions {
#[option(value_name("MODEL"), takes_value(true), hidden(true))]
/// Choose the code model to use
pub code_model: Option<CodeModel>,
#[option(
next_line_help(true),
takes_value(true),
value_name("CHECK_TYPE"),
default_value("disabled"),
possible_values("false", "true", "disabled", "checks", "nochecks"),
hidden(true)
)]
/**
* Use Windows Control Flow Guard:
* checks = emit metadata and checks
* nochecks = emit metadata but no checks
* disabled = do not emit metadata or checks
* true = alias for `checks`
* false = alias for `disabled`
* _
*/
pub control_flow_guard: CFGuard,
#[option]
/// Enable debug assertions
pub debug_assertions: Option<bool>,
#[option(default_value("false"))]
/// Allow the linker to link its default libraries
pub default_linker_libraries: bool,
#[option(default_value("false"), hidden(true))]
pub embed_bitcode: bool,
#[option(hidden(true))]
pub force_frame_pointers: Option<bool>,
#[option(hidden(true))]
pub force_unwind_tables: Option<bool>,
/// Set whether each function should go in its own section
#[option(hidden(true))]
pub function_sections: Option<bool>,
#[option(hidden(true))]
pub gcc_ld: Option<LdImpl>,
#[option(value_name("N"), takes_value(true), hidden(true))]
/// Set the threshold for inlining a function
pub inline_threshold: Option<u64>,
#[option(multiple(true), takes_value(true), value_name("ARG"))]
/// A single argument to append to the linker args (can be used multiple times)
pub linker_arg: Vec<String>,
#[option(value_name("ARGS"), takes_value(true), requires_delimiter(true))]
/// Extra arguments to append to the linker invocation (comma separated list)
pub linker_args: Option<Vec<String>>,
#[option]
/// Prevent the linker from stripping dead code (useful for code coverage)
pub link_dead_code: Option<bool>,
#[option(default_value("true"))]
/// Link native libraries in the linker invocation
pub link_native_libraries: bool,
#[option(hidden(true))]
/// Control whether to link Rust provided C objects/libraries or rely on
/// C toolchain installed on the system
pub link_self_contained: Option<bool>,
#[option(value_name("PATH"), takes_value(true))]
/// The system linker to link with
pub linker: Option<PathBuf>,
#[option(value_name("FLAVOR"), takes_value(true))]
/// Linker flavor, e.g. 'gcc', 'ld', 'msvc', 'wasm-ld'
pub linker_flavor: Option<LinkerFlavor>,
#[option(
next_line_help(true),
takes_value(true),
default_value("false"),
hidden(true)
)]
/**
* Generate build artifacts that are compatible with linker-based LTO
* auto = let the compiler choose
* disabled = do not build LTO-compatible artifacts (default)
* false = alias for 'disabled'
* _
*/
pub linker_plugin_lto: LinkerPluginLto,
#[option(value_name("ARGS"), takes_value(true), requires_delimiter(true))]
/// Extra arguments to pass through to LLVM (comma separated list)
pub llvm_args: Vec<String>,
#[option(
takes_value(true),
hidden(true),
possible_values("no", "yes", "thin", "fat")
)]
/// Perform link-time optimization
pub lto: LtoCli,
#[option(
takes_value(true),
possible_values("disabled", "trampolines", "aliases"),
hidden(true)
)]
/// Control the operation of the MergeFunctions LLVM pass, taking
/// the same values as the target option of the same name
pub merge_functions: Option<MergeFunctions>,
#[option]
/// Run all passes except codegen; no output
pub no_codegen: bool,
/// Compile without linking
#[option]
pub no_link: bool,
#[option(hidden(true))]
/// Don't pre-populate the pass manager with a list of passes
pub no_prepopulate_passes: bool,
#[option(hidden(true))]
/// When set, does not implicitly link the Firefly runtime
pub no_std: Option<bool>,
#[option(hidden(true))]
pub no_unique_section_names: bool,
/**
* Optimization level
* 0 = no optimization (default)
* 1 = minimal optimizations
* 2 = normal optimizations
* 3 = aggressive optimizations
* s = optimize for size
* z = aggressively optimize for size
*/
#[option(
next_line_help(true),
takes_value(true),
value_name("LEVEL"),
default_value("0"),
possible_values("0", "1", "2", "3", "s", "z")
)]
pub opt_level: OptLevel,
#[option]
/// Pass `-install_name @rpath/...` to the macOS linker
pub osx_rpath_install_name: bool,
#[option(value_name("PASSES"), takes_value(true), requires_delimiter(true))]
/// A list of extra LLVM passes to run (comma separated list)
pub passes: Vec<String>,
#[option(takes_value(true), value_name("ARG"))]
/// A single extra argument to prepend the linker invocation
/// can be used more than once
pub pre_link_arg: Vec<String>,
#[option(takes_value(true), value_name("ARGS"), require_delimiter(true))]
/// Extra arguments to prepend to the linker invocation (space separated)
pub pre_link_args: Option<Vec<String>>,
#[option]
/// Prefer dynamic linking to static linking
pub prefer_dynamic: bool,
#[option(value_name("MODEL"), takes_value(true), hidden(true))]
/// Choose the relocation model to use
pub relocation_model: Option<RelocModel>,
#[option(
takes_value(true),
possible_values("full", "partial", "off", "none"),
hidden(true)
)]
/// Choose which RELRO level to use")
pub relro_level: Option<RelroLevel>,
#[option(value_name("PASSES"), takes_value(true), hidden(true))]
/// Print remarks for these optimization passes (comma separated, or 'all')
pub remark: Passes,
#[option]
/// Set rpath values in libs/exes
pub rpath: bool,
/**
* Tell the linker which information to strip:
* none = do not strip anything
* debuginfo = strip debugging information
* symbols = strip debugging symbols wh
* _
*/
#[option(
next_line_help(true),
takes_value(true),
value_name("TYPE"),
default_value("none"),
possible_values("none", "debuginfo", "symbols")
)]
pub strip: Strip,
#[option(value_name("CPU"), takes_value(true))]
/// Select target processor (see `firefly print target-cpus`)
pub target_cpu: Option<String>,
#[option(value_name("FEATURES"), takes_value(true))]
/// Select target specific attributes (see `firefly print target-features`)
pub target_features: Option<String>,
#[option(hidden(true))]
/// Enable ThinLTO when possible
pub thinlto: Option<bool>,
#[option(hidden(true))]
/// Choose the TLS model to use
pub tls_model: Option<TlsModel>,
/// Whether to build a WASI command or reactor
#[option(
takes_value(true),
value_name("MODEL"),
possible_values("command", "reactor")
)]
pub wasi_exec_model: Option<WasiExecModel>,
}
|
//! Extension traits for dealing with [`Option`]s as [`Future`]s or [`Stream`]s.
//!
//! # Examples
//!
//! ```rust
//! use futures::future::{self, FusedFuture as _};
//! use futures_option::OptionExt as _;
//! # futures::executor::block_on(async {
//! let mut f = Some(future::ready::<u32>(1));
//! assert!(f.is_some());
//! assert_eq!(f.current().await, 1);
//! assert!(f.is_none());
//! assert!(f.current().is_terminated());
//! # });
//! ```
//!
//! This is useful when you want to implement optional branches using the
//! `select!` macro.
//!
//! ```rust
//! #![recursion_limit="128"]
//!
//! use futures::{future, stream, StreamExt as _};
//! use futures_option::OptionExt as _;
//! # futures::executor::block_on(async {
//! let mut value = None;
//! let mut values = Some(stream::iter(vec![1u32, 2u32, 4u32].into_iter()).fuse());
//! let mut parked = None;
//!
//! let mut sum = 0;
//!
//! loop {
//! futures::select! {
//! value = value.current() => {
//! sum += value;
//! std::mem::swap(&mut parked, &mut values);
//! }
//! v = values.next() => {
//! match v {
//! Some(v) => {
//! value = Some(future::ready(v));
//! std::mem::swap(&mut parked, &mut values);
//! },
//! None => break,
//! }
//! }
//! }
//! }
//!
//! assert_eq!(7, sum);
//! # });
//! ```
//!
//! [`Option`]: Option
//! [`Stream`]: futures_core::stream::Stream
//! [`Future`]: futures_core::future::Future
use futures_core::{ready, FusedFuture, Stream};
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
impl<T> OptionExt<T> for Option<T> {
fn next(&mut self) -> Next<'_, T>
where
T: Stream + Unpin,
{
Next { stream: self }
}
fn select_next_some(&mut self) -> SelectNextSome<'_, T>
where
T: Stream + Unpin,
{
SelectNextSome { stream: self }
}
fn current(&mut self) -> Current<'_, T>
where
T: Future + Unpin,
{
Current { future: self }
}
}
/// Extension methods for [`Option`] of [`Stream`]s or [`Future`]s.
///
/// [`Option`]: std::option::Option
/// [`Stream`]: Stream
/// [`Future`]: Future
pub trait OptionExt<T>: Sized {
/// Convert [`Option`] into a Future that resolves to the next item in the [`Stream`].
///
/// If the [`Option`] is [`None`], the returned future also resolves to [`None`].
///
/// [`Option`]: Option
/// [`None`]: Option::None
/// [`Stream`]: Stream
fn next(&mut self) -> Next<'_, T>
where
T: Stream + Unpin;
/// Returns a [Future] that resolves when the next item in this stream is ready.
///
/// If the [`Option`] is [`None`], the returned future will always be pending.
///
/// [Future]: Future
fn select_next_some(&mut self) -> SelectNextSome<'_, T>
where
T: Stream + Unpin;
/// Convert [`Option`] into a Future that resolves to the same value as the stored [`Future`].
///
/// If the [`Option`] is [`None`], the returned future also resolves to [`None`].
///
/// [`Option`]: Option
/// [`None`]: Option::None
/// [`Future`]: Future
fn current(&mut self) -> Current<'_, T>
where
T: Future + Unpin;
}
/// Adapter future for `Option` to get the next value of the stored future.
///
/// Resolves to `None` if no future is present.
#[derive(Debug)]
pub struct Next<'a, T> {
pub(crate) stream: &'a mut Option<T>,
}
impl<'a, T> Future for Next<'a, T>
where
T: Stream + Unpin,
{
type Output = Option<T::Item>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
assert!(self.stream.is_some(), "Next polled after terminated");
if let Some(stream) = self.stream.as_mut() {
if let Some(result) = ready!(Pin::new(stream).poll_next(cx)) {
return Poll::Ready(Some(result));
}
}
*self.stream = None;
Poll::Ready(None)
}
}
impl<'a, T> FusedFuture for Next<'a, T>
where
T: Unpin + Stream,
{
fn is_terminated(&self) -> bool {
self.stream.is_none()
}
}
/// Adapter future for `Option` to get the next value of the stored future.
///
/// Resolves to `None` if no future is present.
#[derive(Debug)]
pub struct SelectNextSome<'a, T> {
pub(crate) stream: &'a mut Option<T>,
}
impl<'a, T> Future for SelectNextSome<'a, T>
where
T: Stream + Unpin,
{
type Output = T::Item;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
assert!(
self.stream.is_some(),
"SelectNextSome polled after terminated"
);
if let Some(stream) = self.stream.as_mut() {
if let Some(result) = ready!(Pin::new(stream).poll_next(cx)) {
return Poll::Ready(result);
}
}
*self.stream = None;
cx.waker().wake_by_ref();
return Poll::Pending;
}
}
impl<'a, T> FusedFuture for SelectNextSome<'a, T>
where
T: Unpin + Stream,
{
fn is_terminated(&self) -> bool {
self.stream.is_none()
}
}
/// Adapter future for `Option` to get the next value of the stored stream.
///
/// Resolves to `None` if no stream is present.
#[derive(Debug)]
pub struct Current<'a, T> {
pub(crate) future: &'a mut Option<T>,
}
impl<'a, T> Future for Current<'a, T>
where
T: Future + Unpin,
{
type Output = T::Output;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let future = self
.future
.as_mut()
.expect("Current polled after terminated");
let result = ready!(Pin::new(future).poll(cx));
// NB: we do this to mark the future as terminated.
*self.future = None;
Poll::Ready(result)
}
}
impl<'a, T> FusedFuture for Current<'a, T>
where
T: Unpin + Future,
{
fn is_terminated(&self) -> bool {
self.future.is_none()
}
}
|
use std::ops::Add;
use rbatis::crud::CRUDTable;
use rbatis::rbatis::Rbatis;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use lazy_static::lazy_static;
use crate::kits::Error;
use crate::ma::{BtcTokenType, Dao, EeeTokenType, EthTokenType, MAccountInfoSyncProg, MAddress, MBtcChainToken, MBtcChainTokenAuth, MBtcChainTokenDefault, MBtcChainTokenShared, MBtcChainTx, MBtcInputTx, MBtcOutputTx, MChainTypeMeta, MEeeChainToken, MEeeChainTokenAuth, MEeeChainTokenDefault, MEeeChainTokenShared, MEeeChainTx, MEeeTokenxTx, MEthChainToken, MEthChainTokenAuth, MEthChainTokenDefault, MEthChainTokenShared, MEthChainTx, MMnemonic, MSetting, MSubChainBasicInfo, MTokenAddress, MWallet, MEthChainTokenNonAuth, MTokenShared};
use crate::{kits, NetType, CTrue};
/// Note that cashbox is currently on version 1. Version 2 is this version,
/// when cashbox want to update version we must synchronize this database version value;
pub const VERSION: i64 = 1;
lazy_static! {
static ref SET_VERSION_SQL: String = format!("PRAGMA user_version = {version}", version = VERSION);
}
#[derive(Debug, Default, Clone)]
pub struct DbName {
pub path: String,
pub prefix: String,
pub cashbox_wallets: String,
pub cashbox_mnemonic: String,
pub wallet_mainnet: String,
pub wallet_private: String,
pub wallet_testnet: String,
pub wallet_testnet_private: String,
}
impl DbName {
pub fn new(pre: &str, path: &str) -> DbName {
let temp = DbName {
path: path.to_owned(),
prefix: pre.to_owned(),
..Default::default()
};
DbName::generate_full_name(&temp)
}
pub fn generate_full_name(names: &DbName) -> DbName {
let path = {
//todo 需要优化 path 字段若为空,是否抛出错误?
let path = names.path.clone();
if path.ends_with('/') {
path
} else if path.ends_with('\\') {
path.replace("\\", "/")
} else if !path.is_empty() {
path.add("/") //c
} else {
path
}
};
let pre = names.prefix.clone();
DbName {
path: path.to_owned(),
prefix: pre.to_owned(),
cashbox_wallets: if names.cashbox_wallets.is_empty() {
format!("{}{}{}", path, pre, DbNameType::cashbox_wallets.to_string())
} else {
names.cashbox_wallets.clone()
},
cashbox_mnemonic: if names.cashbox_mnemonic.is_empty() {
format!("{}{}{}", path, pre, DbNameType::cashbox_mnemonic.to_string())
} else {
names.cashbox_mnemonic.clone()
},
wallet_mainnet: if names.wallet_mainnet.is_empty() {
format!("{}{}{}", path, pre, DbNameType::wallet_mainnet.to_string())
} else {
names.wallet_mainnet.clone()
},
wallet_private: if names.wallet_private.is_empty() {
format!("{}{}{}", path, pre, DbNameType::wallet_private.to_string())
} else {
names.wallet_private.clone()
},
wallet_testnet: if names.wallet_testnet.is_empty() {
format!("{}{}{}", path, pre, DbNameType::wallet_testnet.to_string())
} else {
names.wallet_testnet.clone()
},
wallet_testnet_private: if names.wallet_testnet_private.is_empty() {
format!("{}{}{}", path, pre, DbNameType::wallet_testnet_private.to_string())
} else {
names.wallet_testnet_private.clone()
},
}
}
pub fn db_name(&self, db_type: &DbNameType) -> String {
let t = match db_type {
DbNameType::cashbox_wallets => &self.cashbox_wallets,
DbNameType::cashbox_mnemonic => &self.cashbox_mnemonic,
DbNameType::wallet_mainnet => &self.wallet_mainnet,
DbNameType::wallet_private => &self.wallet_private,
DbNameType::wallet_testnet => &self.wallet_testnet,
DbNameType::wallet_testnet_private => &self.wallet_testnet_private,
};
t.clone()
}
pub fn db_name_type(&self, db_name: &str) -> Option<DbNameType> {
match &db_name.to_owned() {
k if k == &self.cashbox_wallets => Some(DbNameType::cashbox_wallets),
k if k == &self.cashbox_mnemonic => Some(DbNameType::cashbox_mnemonic),
k if k == &self.wallet_mainnet => Some(DbNameType::wallet_mainnet),
k if k == &self.wallet_private => Some(DbNameType::wallet_private),
k if k == &self.wallet_testnet => Some(DbNameType::wallet_testnet),
k if k == &self.wallet_testnet_private => Some(DbNameType::wallet_testnet_private),
_ => None,
}
}
}
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, EnumIter)]
pub enum DbNameType {
cashbox_wallets,
cashbox_mnemonic,
wallet_mainnet,
wallet_private,
wallet_testnet,
wallet_testnet_private,
}
impl DbNameType {
pub fn from(db_name: &str) -> Result<Self, Error> {
match db_name {
"cashbox_wallets.db" => Ok(DbNameType::cashbox_wallets),
"cashbox_mnemonic.db" => Ok(DbNameType::cashbox_mnemonic),
"wallet_mainnet.db" => Ok(DbNameType::wallet_mainnet),
"wallet_private.db" => Ok(DbNameType::wallet_private),
"wallet_testnet.db" => Ok(DbNameType::wallet_testnet),
"wallet_testnet_private.db" => Ok(DbNameType::wallet_testnet_private),
_ => {
let err = format!("the str:{} can not to DbName", db_name);
log::error!("{}", err);
Err(Error::from(err.as_str()))
}
}
}
}
impl ToString for DbNameType {
fn to_string(&self) -> String {
match &self {
DbNameType::cashbox_wallets => "cashbox_wallets.db".to_owned(),
DbNameType::cashbox_mnemonic => "cashbox_mnemonic.db".to_owned(),
DbNameType::wallet_mainnet => "wallet_mainnet.db".to_owned(),
DbNameType::wallet_private => "wallet_private.db".to_owned(),
DbNameType::wallet_testnet => "wallet_testnet.db".to_owned(),
DbNameType::wallet_testnet_private => "wallet_testnet_private.db".to_owned(),
}
}
}
pub enum DbCreateType {
NotExists,
CleanData,
//call delete from table
Drop,
}
#[derive(Default)]
pub struct Db {
cashbox_wallets: Rbatis,
cashbox_mnemonic: Rbatis,
wallet_mainnet: Rbatis,
wallet_private: Rbatis,
wallet_testnet: Rbatis,
wallet_testnet_private: Rbatis,
pub db_name: DbName,
}
impl Db {
///链数据的数据据库
pub fn data_db(&self, net_type: &NetType) -> &Rbatis {
match net_type {
NetType::Main => &self.wallet_mainnet,
NetType::Test => &self.wallet_testnet,
NetType::Private => &self.wallet_private,
NetType::PrivateTest => &self.wallet_testnet_private,
}
}
///钱包名等信息的数据库
pub fn wallets_db(&self) -> &Rbatis {
&self.cashbox_wallets
}
///助记词的数据库
pub fn mnemonic_db(&self) -> &Rbatis {
&self.cashbox_mnemonic
}
pub async fn connect(&mut self, name: &DbName) -> Result<(), Error> {
self.db_name = name.clone();
self.cashbox_wallets = kits::make_rbatis(&self.db_name.cashbox_wallets).await?;
self.cashbox_mnemonic = kits::make_rbatis(&self.db_name.cashbox_mnemonic).await?;
self.wallet_mainnet = kits::make_rbatis(&self.db_name.wallet_mainnet).await?;
self.wallet_private = kits::make_rbatis(&self.db_name.wallet_private).await?;
self.wallet_testnet = kits::make_rbatis(&self.db_name.wallet_testnet).await?;
self.wallet_testnet_private =
kits::make_rbatis(&self.db_name.wallet_testnet_private).await?;
Ok(())
}
pub async fn init_memory_sql(&mut self, name: &DbName) -> Result<(), Error> {
self.db_name = name.clone();
self.cashbox_wallets = kits::make_memory_rbatis().await?;
self.cashbox_mnemonic = kits::make_memory_rbatis().await?;
self.wallet_mainnet = kits::make_memory_rbatis().await?;
self.wallet_private = kits::make_memory_rbatis().await?;
self.wallet_testnet = kits::make_memory_rbatis().await?;
self.wallet_testnet_private = kits::make_memory_rbatis().await?;
Ok(())
}
pub async fn init_tables(&self, create_type: &DbCreateType) -> Result<(), Error> {
let wallets_rb = self.wallets_db();
let user_version: i64 = wallets_rb.fetch("", "PRAGMA user_version").await?;
if user_version == 0 {
wallets_rb.exec("", &SET_VERSION_SQL).await?;
self.create(create_type).await?;
Db::insert_chain_token(self).await?;
return Ok(());
}
if user_version != VERSION {
if user_version < VERSION {
self.update(user_version).await?;
} else {
let error_msg = "Current application version is higher,please uninstall and reinstall";
log::error!("{}", error_msg);
return Err(Error { err: error_msg.to_string() });
}
}
Ok(())
}
async fn create(&self, create_type: &DbCreateType) -> Result<(), Error> {
Db::create_table_wallets(self.wallets_db(), create_type).await?;
Db::create_table_mnemonic(self.mnemonic_db(), create_type).await?;
for net_type in NetType::iter() {
let data_rb = self.data_db(&net_type);
Db::create_table_data(data_rb, create_type).await?;
}
Ok(())
}
async fn update(&self, from: i64) -> Result<(), Error> {
log::debug!("Upgrading schema from {} to {}", from, VERSION);
if from == VERSION {
return Ok(());
}
assert_ne!(
from, 0,
"Upgrading from user_version = 0 should already be handled (in `init`)"
);
//todo add database update logic
Ok(())
}
pub async fn create_table(rb: &Rbatis, sql: &str, name: &str, create_type: &DbCreateType) -> Result<(), Error> {
match create_type {
DbCreateType::NotExists => {
rb.exec("", sql).await?;
}
DbCreateType::CleanData => {
rb.exec("", sql).await?;
rb.exec("", &format!("delete from {};", name)).await?;
}
DbCreateType::Drop => {
rb.exec("", &format!("drop table if exists {};", name))
.await?;
rb.exec("", sql).await?;
}
}
Ok(())
}
pub async fn create_table_mnemonic(rb: &Rbatis, create_type: &DbCreateType) -> Result<(), Error> {
Db::create_table(rb, MMnemonic::create_table_script(), &MMnemonic::table_name(), create_type).await?;
Ok(())
}
///total: 16
pub async fn create_table_wallets(rb: &Rbatis, create_type: &DbCreateType) -> Result<(), Error> {
Db::create_table(rb, MWallet::create_table_script(), &MWallet::table_name(), create_type).await?;
Db::create_table(rb, MChainTypeMeta::create_table_script(), &MChainTypeMeta::table_name(), create_type).await?;
Db::create_table(rb, MAddress::create_table_script(), &MAddress::table_name(), create_type).await?;
Db::create_table(rb, MSetting::create_table_script(), &MSetting::table_name(), create_type).await?;
Db::create_table(rb, MEthChainTokenShared::create_table_script(), &MEeeChainTokenShared::table_name(), create_type).await?;
Db::create_table(rb, MEthChainTokenAuth::create_table_script(), &MEthChainTokenAuth::table_name(), create_type).await?;
Db::create_table(rb, MEthChainTokenNonAuth::create_table_script(), &MEthChainTokenNonAuth::table_name(), create_type).await?;
Db::create_table(rb, MEthChainTokenDefault::create_table_script(), &MEthChainTokenDefault::table_name(), create_type).await?;
Db::create_table(rb, MEeeChainTokenShared::create_table_script(), &MEeeChainTokenShared::table_name(), create_type).await?;
Db::create_table(rb, MEeeChainTokenAuth::create_table_script(), &MEeeChainTokenAuth::table_name(), create_type).await?;
Db::create_table(rb, MEeeChainTokenDefault::create_table_script(), &MEeeChainTokenDefault::table_name(), create_type).await?;
Db::create_table(rb, MBtcChainTokenShared::create_table_script(), &MBtcChainTokenShared::table_name(), create_type).await?;
Db::create_table(rb, MBtcChainTokenAuth::create_table_script(), &MBtcChainTokenAuth::table_name(), create_type).await?;
Db::create_table(rb, MBtcChainTokenDefault::create_table_script(), &MBtcChainTokenDefault::table_name(), create_type).await?;
Ok(())
}
///total: 12
pub async fn create_table_data(rb: &Rbatis, create_type: &DbCreateType) -> Result<(), Error> {
Db::create_table(rb, MTokenAddress::create_table_script(), &MTokenAddress::table_name(), create_type).await?;
Db::create_table(rb, MEthChainToken::create_table_script(), &MEthChainToken::table_name(), create_type).await?;
Db::create_table(rb, MEthChainTx::create_table_script(), &MEthChainTx::table_name(), create_type).await?;
Db::create_table(rb, MEeeChainToken::create_table_script(), &MEeeChainToken::table_name(), create_type).await?;
Db::create_table(rb, MEeeChainTx::create_table_script(), &MEeeChainTx::table_name(), create_type).await?;
Db::create_table(rb, MEeeTokenxTx::create_table_script(), &MEeeTokenxTx::table_name(), create_type).await?;
Db::create_table(rb, MBtcChainToken::create_table_script(), &MBtcChainToken::table_name(), create_type).await?;
Db::create_table(rb, MBtcChainTx::create_table_script(), &MBtcChainTx::table_name(), create_type).await?;
Db::create_table(rb, MBtcInputTx::create_table_script(), &MBtcInputTx::table_name(), create_type).await?;
Db::create_table(rb, MBtcOutputTx::create_table_script(), &MBtcOutputTx::table_name(), create_type).await?;
Db::create_table(rb, MSubChainBasicInfo::create_table_script(), &MSubChainBasicInfo::table_name(), create_type).await?;
Db::create_table(rb, MAccountInfoSyncProg::create_table_script(), &MAccountInfoSyncProg::table_name(), create_type).await?;
Ok(())
}
/// such as: eth,eee,btc
pub async fn insert_chain_token(db: &Db) -> Result<(), Error> {
{
//eth
let rb = db.wallets_db();
let token_shared = {
let mut eth = MEthChainTokenShared{
token_type: EthTokenType::Eth.to_string(),
gas_limit: 0,
decimal: 18,
token_shared: MTokenShared{
name:"Ethereum".to_owned(),
symbol:"ETH".to_owned(),
project_name:"ethereum".to_owned(),
project_home:"https://ethereum.org/zh/".to_owned(),
project_note:"Ethereum is a global, open-source platform for decentralized applications.".to_owned(),
..Default::default()
},
..Default::default()
};
let old_eth = {
let wrapper = rb
.new_wrapper()
.eq(MEeeChainTokenShared::token_type, ð.token_type);
MEthChainTokenShared::fetch_by_wrapper(rb, "", &wrapper).await?
};
if let Some(t) = old_eth {
eth = t;
} else {
eth.save(rb, "").await?;
}
eth
};
{
//token_default
for net_type in NetType::iter() {
let wrapper = rb.new_wrapper()
.eq(
MEthChainTokenDefault::chain_token_shared_id,
token_shared.id.clone(),
)
.eq(MEthChainTokenDefault::net_type, net_type.to_string());
let old = MEthChainTokenDefault::exist_by_wrapper(rb, "", &wrapper).await?;
if !old {
let mut token_default = MEthChainTokenDefault{
chain_token_shared_id: token_shared.id.clone(),
net_type: net_type.to_string(),
position: 0,
status: CTrue as i64,
..Default::default()
};
token_default.save(rb, "").await?;
}
}
}
}
{
//eee
let rb = db.wallets_db();
let token_shared = {
let mut eee = MEeeChainTokenShared{
token_type: EeeTokenType::Eee.to_string(),
decimal: 15,
token_shared: MTokenShared{
name:"EEE".to_owned(),
symbol:"EEE".to_owned(),
project_name: "EEE".to_owned(),
project_home:"https://scry.info".to_owned(),
project_note:"EEE is a global".to_owned(),
..Default::default()
},
..Default::default()
};
let old_eth = {
let wrapper = rb
.new_wrapper()
.eq(MEeeChainTokenShared::token_type, &eee.token_type);
MEeeChainTokenShared::fetch_by_wrapper(rb, "", &wrapper).await?
};
if let Some(t) = old_eth {
eee = t;
} else {
eee.save(rb, "").await?;
}
eee
};
{
//token_default
for net_type in NetType::iter() {
let wrapper = rb.new_wrapper()
.eq(
MEeeChainTokenDefault::chain_token_shared_id,
token_shared.id.clone(),
)
.eq(MEeeChainTokenDefault::net_type, net_type.to_string());
let old = MEeeChainTokenDefault::exist_by_wrapper(rb, "", &wrapper).await?;
if !old {
let mut token_default = MEeeChainTokenDefault{
chain_token_shared_id: token_shared.id.clone(),
net_type: net_type.to_string(),
status: CTrue as i64,
..Default::default()
};
token_default.save(rb, "").await?;
}
}
}
}
{
//btc
let rb = db.wallets_db();
let token_shared = {
let mut btc = MBtcChainTokenShared{
token_type: BtcTokenType::Btc.to_string(),
fee_per_byte: 19,
decimal: 18,
token_shared: MTokenShared{
name:"Bitcoin".to_owned(),
symbol: "BTC".to_owned(),
project_name: "Bitcoin".to_owned(),
project_home: "https://bitcoin.org/en/".to_owned(),
project_note: "Bitcoin is a global, open-source platform for decentralized applications.".to_owned(),
..Default::default()
},
..Default::default()
};
let old_eth = {
let wrapper = rb.new_wrapper()
.eq(MBtcChainTokenShared::token_type, &btc.token_type);
MBtcChainTokenShared::fetch_by_wrapper(rb, "", &wrapper).await?
};
if let Some(t) = old_eth {
btc = t;
} else {
btc.save(rb, "").await?;
}
btc
};
{
//token_default
for net_type in NetType::iter() {
let wrapper = rb.new_wrapper()
.eq(
MBtcChainTokenDefault::chain_token_shared_id,
token_shared.id.clone(),
)
.eq(MBtcChainTokenDefault::net_type, net_type.to_string());
let old = MBtcChainTokenDefault::exist_by_wrapper(rb, "", &wrapper).await?;
if !old {
let mut token_default= MBtcChainTokenDefault{
net_type: net_type.to_string(),
chain_token_shared_id: token_shared.id.clone(),
position: 0,
status: CTrue as i64,
..Default::default()
};
token_default.save(rb, "").await?;
}
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use futures::executor::block_on;
use rbatis::rbatis::Rbatis;
use strum::IntoEnumIterator;
use crate::ma::{Db, DbName, DbNameType};
use crate::NetType;
#[test]
fn db_name_type_test() {
for it in DbNameType::iter() {
assert_eq!(it, DbNameType::from(&it.to_string()).unwrap());
}
}
#[test]
fn db_names_test() {
{
let pre = "";
let db = DbName::new(pre, "");
for it in DbNameType::iter() {
let name = db.db_name(&it);
assert_eq!(name, pre.to_owned() + &it.to_string());
let db_type = db
.db_name_type(&name)
.expect(&format!("can not find name: {}", &name));
assert_eq!(db_type, it);
}
}
{
let pre = "test";
let db = DbName::new(pre, "");
for it in DbNameType::iter() {
let name = db.db_name(&it);
assert_eq!(name, pre.to_owned() + &it.to_string());
let db_type = db
.db_name_type(&name)
.expect(&format!("can not find name: {}", &name));
assert_eq!(db_type, it);
}
}
{
let pre = "test";
let db = DbName::new(pre, "/");
for it in DbNameType::iter() {
let name = db.db_name(&it);
assert_eq!(name, format!("/{}{}", pre, it.to_string()));
let db_type = db
.db_name_type(&name)
.expect(&format!("can not find name: {}", &name));
assert_eq!(db_type, it);
}
}
{
let pre = "test";
let db = DbName::new(pre, "/user");
for it in DbNameType::iter() {
let name = db.db_name(&it);
assert_eq!(name, format!("/user/{}{}", pre, it.to_string()));
let db_type = db
.db_name_type(&name)
.expect(&format!("can not find name: {}", &name));
assert_eq!(db_type, it);
}
}
{
let pre = "test";
let db = DbName::new(pre, "/user/");
for it in DbNameType::iter() {
let name = db.db_name(&it);
assert_eq!(name, format!("/user/{}{}", pre, it.to_string()));
let db_type = db
.db_name_type(&name)
.expect(&format!("can not find name: {}", &name));
assert_eq!(db_type, it);
}
}
}
#[test]
fn db_test() {
let mut db = Db::default();
let re = block_on(db.connect(&DbName::new("test_", "./temp")));
assert_eq!(false, re.is_err(), "{:?}", re);
assert_eq!(
&db.cashbox_wallets as *const Rbatis,
db.wallets_db() as *const Rbatis
);
assert_eq!(
&db.cashbox_mnemonic as *const Rbatis,
db.mnemonic_db() as *const Rbatis
);
assert_eq!(
&db.wallet_mainnet as *const Rbatis,
db.data_db(&NetType::Main) as *const Rbatis
);
assert_eq!(
&db.wallet_testnet as *const Rbatis,
db.data_db(&NetType::Test) as *const Rbatis
);
assert_eq!(
&db.wallet_private as *const Rbatis,
db.data_db(&NetType::Private) as *const Rbatis
);
assert_eq!(
&db.wallet_testnet_private as *const Rbatis,
db.data_db(&NetType::PrivateTest) as *const Rbatis
);
}
} |
#![deny(warnings, missing_docs, missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/string/0.1.3")]
//! A UTF-8 encoded string with configurable byte storage.
//!
//! This crate provides `String`, a type similar to its std counterpart, but
//! with one significant difference: the underlying byte storage is
//! configurable. In other words, `String<T>` is a marker type wrapping `T`,
//! indicating that it represents a UTF-8 encoded string.
//!
//! For example, one can represent small strings (stack allocated) by wrapping
//! an array:
//!
//! ```
//! # use string::*;
//! let s: String<[u8; 2]> = String::try_from([b'h', b'i']).unwrap();
//! assert_eq!(&s[..], "hi");
//! ```
use std::{borrow, fmt, hash, ops, str};
/// A UTF-8 encoded string with configurable byte storage.
///
/// This type differs from `std::String` in that it is generic over the
/// underlying byte storage, enabling it to use `Vec<[u8]>`, `&[u8]`, or third
/// party types, such as [`Bytes`].
///
/// [`Bytes`]: https://docs.rs/bytes/0.4.8/bytes/struct.Bytes.html
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
pub struct String<T = Vec<u8>> {
value: T,
}
impl<T> String<T> {
/// Get a reference to the underlying byte storage.
///
/// # Examples
///
/// ```
/// # use string::*;
/// let s = String::new();
/// let vec = s.get_ref();
/// ```
pub fn get_ref(&self) -> &T {
&self.value
}
/// Get a mutable reference to the underlying byte storage.
///
/// It is inadvisable to directly manipulate the byte storage. This function
/// is unsafe as the bytes could no longer be valid UTF-8 after mutation.
///
/// # Examples
///
/// ```
/// # use string::*;
/// let mut s = String::new();
///
/// unsafe {
/// let vec = s.get_mut();
/// }
/// ```
pub unsafe fn get_mut(&mut self) -> &mut T {
&mut self.value
}
/// Unwraps this `String`, returning the underlying byte storage.
///
/// # Examples
///
/// ```
/// # use string::*;
/// let s = String::new();
/// let vec = s.into_inner();
/// ```
pub fn into_inner(self) -> T {
self.value
}
/// Creates a new `String` from a &str.
///
/// Use `TryFrom` for conversion from &[u8].
///
/// ```
/// # use string::*;
/// let _: String<Vec<u8>> = String::from_str("nice str");
/// ```
pub fn from_str<'a>(src: &'a str) -> String<T>
where T: From<&'a [u8]>,
{
let value: T = src.as_bytes().into();
Self { value }
}
}
impl String {
/// Creates a new empty `String`.
///
/// Given that the `String` is empty, this will not allocate.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// let s = String::new();
/// assert_eq!(s, "");
/// ```
pub fn new() -> String {
String::default()
}
}
impl<T> String<T>
where T: AsRef<[u8]>,
{
/// Converts the provided value to a `String` without checking that the
/// given value is valid UTF-8.
///
/// Use `TryFrom` for a safe conversion.
pub unsafe fn from_utf8_unchecked(value: T) -> String<T> {
String { value }
}
}
impl<T> PartialEq<str> for String<T>
where T: AsRef<[u8]>
{
fn eq(&self, other: &str) -> bool {
&*self == other
}
}
impl<T> hash::Hash for String<T>
where T: AsRef<[u8]>
{
fn hash<H: hash::Hasher>(&self, state: &mut H) {
ops::Deref::deref(self).hash(state);
}
}
impl<T> ops::Deref for String<T>
where T: AsRef<[u8]>
{
type Target = str;
#[inline]
fn deref(&self) -> &str {
let b = self.value.as_ref();
unsafe { str::from_utf8_unchecked(b) }
}
}
impl<T> ops::DerefMut for String<T>
where T: AsRef<[u8]> + AsMut<[u8]>
{
#[inline]
fn deref_mut(&mut self) -> &mut str {
let b = self.value.as_mut();
unsafe { str::from_utf8_unchecked_mut(b) }
}
}
impl<T> borrow::Borrow<str> for String<T>
where T: AsRef<[u8]>
{
fn borrow(&self) -> &str {
&*self
}
}
impl From<::std::string::String> for String<::std::string::String> {
fn from(value: ::std::string::String) -> Self {
String { value }
}
}
impl<'a> From<&'a str> for String<&'a str> {
fn from(value: &'a str) -> Self {
String { value }
}
}
impl<T> TryFrom<T> for String<T>
where T: AsRef<[u8]>
{
type Error = str::Utf8Error;
fn try_from(value: T) -> Result<Self, Self::Error> {
let _ = str::from_utf8(value.as_ref())?;
Ok(String { value })
}
}
impl<T: AsRef<[u8]>> fmt::Debug for String<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(fmt)
}
}
impl<T: AsRef<[u8]>> fmt::Display for String<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(fmt)
}
}
/// Attempt to construct `Self` via a conversion.
///
/// This trait will be deprecated in favor of [std::convert::TryFrom] once it
/// reaches stable Rust.
pub trait TryFrom<T>: Sized + sealed::Sealed {
/// The type returned in the event of a conversion error.
type Error;
/// Performs the conversion.
fn try_from(value: T) -> Result<Self, Self::Error>;
}
impl<T> sealed::Sealed for String<T> {}
mod sealed {
/// Private trait to this crate to prevent traits from being implemented in
/// downstream crates.
pub trait Sealed {}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_from_std_string() {
let s: String<_> = "hello".to_string().into();
assert_eq!(&s[..], "hello");
}
#[test]
fn test_from_str() {
let _: String<Vec<u8>> = String::from_str("nice str");
}
#[test]
fn test_try_from_bytes() {
let _ = String::try_from(b"nice bytes").unwrap();
}
}
|
//! Группа унификации фундаментов под стенами и колоннами
use crate::sig::rab_e::*;
use crate::sig::HasWrite;
use nom::{bytes::complete::take, multi::count, number::complete::le_u16, IResult};
use std::fmt;
#[derive(Debug)]
pub struct UnificationFound {
unification_group: u16, //Номер группы унификаций
amount: u16, //Количество элементов в группе унификаций
//64b WS
elements: Vec<FoundElem>, //Вектор номеров элементов в группе
ws: Vec<u8>, //64b
}
impl HasWrite for UnificationFound {
fn write(&self) -> Vec<u8> {
let mut out: Vec<u8> = vec![];
out.extend(&self.unification_group.to_le_bytes());
out.extend(&self.amount.to_le_bytes());
out.extend(&self.ws[0..64]);
for i in &self.elements {
out.extend(&i.write());
}
out
}
fn name(&self) -> &str {
""
}
}
impl fmt::Display for UnificationFound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"group: {}, amount: {}",
&self.unification_group, &self.amount
)?;
let vec = &self.elements;
for (count, v) in vec.iter().enumerate() {
write!(f, "\n found №{}: {}", count, v)?;
}
write!(f, "")
}
}
#[derive(Debug)]
pub struct FoundElem {
element_type: u16, //Тип конструкции. 1=колонна, 2=стена
element_num: u16, //Номер элемента в схеме
//16 WS
ws: Vec<u8>, //16b
}
impl HasWrite for FoundElem {
fn write(&self) -> Vec<u8> {
let mut out: Vec<u8> = vec![];
out.extend(&self.element_type.to_le_bytes());
out.extend(&self.element_num.to_le_bytes());
out.extend(&self.ws[0..16]);
out
}
fn name(&self) -> &str {
""
}
}
impl fmt::Display for FoundElem {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"type: {}, num: {}",
&self.element_type, &self.element_num
)
}
}
pub fn read_unification_found(i: &[u8]) -> IResult<&[u8], UnificationFound> {
let (i, unification_group) = le_u16(i)?;
let (i, amount) = le_u16(i)?;
let (i, ws) = take(64u8)(i)?; //64b WS
let (i, elements) = count(read_found_elem, amount as usize)(i)?;
let ws = ws.to_vec();
Ok((
i,
UnificationFound {
unification_group,
amount,
elements,
ws,
},
))
}
pub fn read_found_elem(i: &[u8]) -> IResult<&[u8], FoundElem> {
let (i, element_type) = le_u16(i)?;
let (i, element_num) = le_u16(i)?;
let (i, ws) = take(16u8)(i)?; //16b WS
let ws = ws.to_vec();
Ok((
i,
FoundElem {
element_type,
element_num,
ws,
},
))
}
#[cfg(test)]
fn test_unification_found(path_str: &str) {
use crate::tests::rab_e_sig_test::read_test_sig;
let original_in = read_test_sig(path_str);
let (_, unification) =
read_unification_found(&original_in).expect("couldn't read_unification_found");
assert_eq!(original_in, unification.write());
}
#[test]
fn unification_test() {
test_unification_found("test_sig/unification_founds/uni.test");
}
#[test]
fn unification_16el_test() {
test_unification_found("test_sig/unification_founds/uni_16el.test");
}
#[test]
fn s_unification_found_full_value_test() {
use crate::tests::rab_e_sig_test::read_test_sig;
let original_in = read_test_sig("test_sig/unification_founds/S_uni.test");
let (_, unification) =
read_unification_found(&original_in).expect("couldn't read_unification_found");
let mut ws = vec![];
for i in 1..=64 {
ws.push(i);
}
let mut ws_elem = vec![];
for i in 1..=16 {
ws_elem.push(i);
}
let elements = vec![
FoundElem {
element_type: 2u16,
element_num: 1u16,
ws: ws_elem.clone(),
},
FoundElem {
element_type: 2u16,
element_num: 2u16,
ws: ws_elem,
},
];
let c_unification = UnificationFound {
unification_group: 1u16,
amount: 2u16,
elements,
ws,
};
assert_eq!(unification.write(), c_unification.write())
}
|
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[allow(non_snake_case)]
#[wasm_bindgen]
pub fn sum(a: Vec<i32>) -> i32 {
a.iter().sum()
}
#[wasm_bindgen]
pub fn run() {
for i in 0..10000 {
sum(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
};
}
|
use super::{healthcheck_response, GcpAuthConfig, GcpCredentials, Scope};
use crate::{
event::{self, Event},
serde::to_string,
sinks::{
util::{
encoding::{EncodingConfig, EncodingConfiguration},
http::{HttpClient, HttpClientFuture},
retries2::{RetryAction, RetryLogic},
service2::{ServiceBuilderExt, TowerCompat, TowerRequestConfig},
BatchConfig, BatchSettings, Buffer, Compression, PartitionBatchSink, PartitionBuffer,
PartitionInnerBuffer,
},
Healthcheck, RouterSink,
},
template::{Template, TemplateError},
tls::{TlsOptions, TlsSettings},
topology::config::{DataType, SinkConfig, SinkContext, SinkDescription},
};
use bytes::Bytes;
use chrono::Utc;
use futures::{FutureExt, TryFutureExt};
use futures01::{stream::iter_ok, Sink};
use http::{StatusCode, Uri};
use hyper::{
header::{HeaderName, HeaderValue},
Body, Request, Response,
};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::task::Poll;
use tower03::{Service, ServiceBuilder};
use tracing::field;
use uuid::Uuid;
const NAME: &str = "gcp_cloud_storage";
const BASE_URL: &str = "https://storage.googleapis.com/";
#[derive(Clone)]
struct GcsSink {
bucket: String,
client: HttpClient,
creds: Option<GcpCredentials>,
base_url: String,
settings: RequestSettings,
}
#[derive(Debug, Snafu)]
enum GcsError {
#[snafu(display("Bucket {:?} not found", bucket))]
BucketNotFound { bucket: String },
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct GcsSinkConfig {
bucket: String,
acl: Option<GcsPredefinedAcl>,
storage_class: Option<GcsStorageClass>,
metadata: Option<HashMap<String, String>>,
key_prefix: Option<String>,
filename_time_format: Option<String>,
filename_append_uuid: Option<bool>,
filename_extension: Option<String>,
encoding: EncodingConfig<Encoding>,
#[serde(default)]
compression: Compression,
#[serde(default)]
batch: BatchConfig,
#[serde(default)]
request: TowerRequestConfig,
#[serde(flatten)]
auth: GcpAuthConfig,
tls: Option<TlsOptions>,
}
#[cfg(test)]
fn default_config(e: Encoding) -> GcsSinkConfig {
GcsSinkConfig {
bucket: Default::default(),
acl: Default::default(),
storage_class: Default::default(),
metadata: Default::default(),
key_prefix: Default::default(),
filename_time_format: Default::default(),
filename_append_uuid: Default::default(),
filename_extension: Default::default(),
encoding: e.into(),
compression: Compression::Gzip,
batch: Default::default(),
request: Default::default(),
auth: Default::default(),
tls: Default::default(),
}
}
#[derive(Clone, Copy, Debug, Derivative, Deserialize, Serialize)]
#[derivative(Default)]
#[serde(rename_all = "kebab-case")]
enum GcsPredefinedAcl {
AuthenticatedRead,
BucketOwnerFullControl,
BucketOwnerRead,
Private,
#[derivative(Default)]
ProjectPrivate,
PublicRead,
}
#[derive(Clone, Copy, Debug, Derivative, Deserialize, Serialize)]
#[derivative(Default)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum GcsStorageClass {
#[derivative(Default)]
Standard,
Nearline,
Coldline,
Archive,
}
lazy_static! {
static ref REQUEST_DEFAULTS: TowerRequestConfig = TowerRequestConfig {
in_flight_limit: Some(25),
rate_limit_num: Some(25),
..Default::default()
};
}
#[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Clone, Copy)]
#[serde(rename_all = "snake_case")]
enum Encoding {
Text,
Ndjson,
}
impl Encoding {
fn content_type(&self) -> &'static str {
match self {
Self::Text => "text/plain",
Self::Ndjson => "application/x-ndjson",
}
}
}
inventory::submit! {
SinkDescription::new_without_default::<GcsSinkConfig>(NAME)
}
#[async_trait::async_trait]
#[typetag::serde(name = "gcp_cloud_storage")]
impl SinkConfig for GcsSinkConfig {
fn build(&self, _cx: SinkContext) -> crate::Result<(RouterSink, Healthcheck)> {
unimplemented!()
}
async fn build_async(&self, cx: SinkContext) -> crate::Result<(RouterSink, Healthcheck)> {
let sink = GcsSink::new(self, &cx).await?;
let healthcheck = sink.clone().healthcheck().boxed().compat();
let service = sink.service(self, &cx)?;
Ok((service, Box::new(healthcheck)))
}
fn input_type(&self) -> DataType {
DataType::Log
}
fn sink_type(&self) -> &'static str {
NAME
}
}
#[derive(Debug, Snafu)]
enum HealthcheckError {
#[snafu(display("Invalid credentials"))]
InvalidCredentials,
#[snafu(display("Unknown bucket: {:?}", bucket))]
UnknownBucket { bucket: String },
#[snafu(display("key_prefix template parse error: {}", source))]
KeyPrefixTemplate { source: TemplateError },
}
impl GcsSink {
async fn new(config: &GcsSinkConfig, cx: &SinkContext) -> crate::Result<Self> {
let creds = config
.auth
.make_credentials(Scope::DevStorageReadWrite)
.await?;
let settings = RequestSettings::new(config)?;
let tls = TlsSettings::from_options(&config.tls)?;
let client = HttpClient::new(cx.resolver(), tls)?;
let base_url = format!("{}{}/", BASE_URL, config.bucket);
let bucket = config.bucket.clone();
Ok(GcsSink {
client,
creds,
settings,
base_url,
bucket,
})
}
fn service(self, config: &GcsSinkConfig, cx: &SinkContext) -> crate::Result<RouterSink> {
let request = config.request.unwrap_with(&REQUEST_DEFAULTS);
let encoding = config.encoding.clone();
let batch = BatchSettings::default()
.bytes(bytesize::mib(10u64))
.timeout(300)
.parse_config(config.batch)?;
let key_prefix = config.key_prefix.as_deref().unwrap_or("date=%F/");
let key_prefix = Template::try_from(key_prefix).context(KeyPrefixTemplate)?;
let settings = self.settings.clone();
let svc = ServiceBuilder::new()
.map(move |req| RequestWrapper::new(req, settings.clone()))
.settings(request, GcsRetryLogic)
.service(self);
let buffer = PartitionBuffer::new(Buffer::new(batch.size, config.compression));
let sink =
PartitionBatchSink::new(TowerCompat::new(svc), buffer, batch.timeout, cx.acker())
.sink_map_err(|e| error!("Fatal gcs sink error: {}", e))
.with_flat_map(move |e| iter_ok(encode_event(e, &key_prefix, &encoding)));
Ok(Box::new(sink))
}
async fn healthcheck(mut self) -> crate::Result<()> {
let uri = self.base_url.parse::<Uri>()?;
let mut request = http::Request::head(uri).body(Body::empty())?;
if let Some(creds) = self.creds.as_ref() {
creds.apply(&mut request);
}
let bucket = self.bucket;
let not_found_error = GcsError::BucketNotFound { bucket }.into();
let response = self.client.send(request).await?;
healthcheck_response(self.creds, not_found_error)(response)
}
}
impl Service<RequestWrapper> for GcsSink {
type Response = Response<Body>;
type Error = hyper::Error;
type Future = HttpClientFuture;
fn poll_ready(&mut self, _: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: RequestWrapper) -> Self::Future {
let settings = request.settings;
let uri = format!("{}{}", self.base_url, request.key)
.parse::<Uri>()
.unwrap();
let mut builder = Request::put(uri);
let headers = builder.headers_mut().unwrap();
headers.insert("content-type", settings.content_type);
headers.insert(
"content-length",
HeaderValue::from_str(&format!("{}", request.body.len())).unwrap(),
);
settings
.content_encoding
.map(|ce| headers.insert("content-encoding", ce));
settings.acl.map(|acl| headers.insert("x-goog-acl", acl));
headers.insert("x-goog-storage-class", settings.storage_class);
for (p, v) in settings.metadata {
headers.insert(p, v);
}
let mut request = builder.body(Body::from(request.body)).unwrap();
if let Some(creds) = &self.creds {
creds.apply(&mut request);
}
self.client.call(request)
}
}
#[derive(Clone, Debug)]
struct RequestWrapper {
body: Vec<u8>,
key: String,
settings: RequestSettings,
}
impl RequestWrapper {
fn new(req: PartitionInnerBuffer<Vec<u8>, Bytes>, settings: RequestSettings) -> Self {
let (body, key) = req.into_parts();
// TODO: pull the seconds from the last event
let filename = {
let seconds = Utc::now().format(&settings.time_format);
if settings.append_uuid {
let uuid = Uuid::new_v4();
format!("{}-{}", seconds, uuid.to_hyphenated())
} else {
seconds.to_string()
}
};
let key = format!(
"{}{}.{}",
String::from_utf8_lossy(&key[..]),
filename,
settings.extension
);
debug!(
message = "sending events.",
bytes = &field::debug(body.len()),
key = &field::debug(&key)
);
Self {
body,
key,
settings,
}
}
}
// Settings required to produce a request that do not change per
// request. All possible values are pre-computed for direct use in
// producing a request.
#[derive(Clone, Debug)]
struct RequestSettings {
acl: Option<HeaderValue>,
content_type: HeaderValue,
content_encoding: Option<HeaderValue>,
storage_class: HeaderValue,
metadata: Vec<(HeaderName, HeaderValue)>,
extension: String,
time_format: String,
append_uuid: bool,
}
impl RequestSettings {
fn new(config: &GcsSinkConfig) -> crate::Result<Self> {
let acl = config
.acl
.map(|acl| HeaderValue::from_str(&to_string(acl)).unwrap());
let content_type = HeaderValue::from_str(config.encoding.codec().content_type()).unwrap();
let content_encoding = config
.compression
.content_encoding()
.map(|ce| HeaderValue::from_str(&to_string(ce)).unwrap());
let storage_class = config.storage_class.unwrap_or_default();
let storage_class = HeaderValue::from_str(&to_string(storage_class)).unwrap();
let metadata = config
.metadata
.as_ref()
.map(|metadata| {
metadata
.iter()
.map(make_header)
.collect::<Result<Vec<_>, _>>()
})
.unwrap_or_else(|| Ok(vec![]))?;
let extension = config
.filename_extension
.clone()
.unwrap_or_else(|| config.compression.extension().into());
let time_format = config
.filename_time_format
.clone()
.unwrap_or_else(|| "%s".into());
let append_uuid = config.filename_append_uuid.unwrap_or(true);
Ok(Self {
acl,
content_type,
content_encoding,
storage_class,
metadata,
extension,
time_format,
append_uuid,
})
}
}
// Make a header pair from a key-value string pair
fn make_header((name, value): (&String, &String)) -> crate::Result<(HeaderName, HeaderValue)> {
Ok((
HeaderName::from_bytes(name.as_bytes())?,
HeaderValue::from_str(&value)?,
))
}
fn encode_event(
mut event: Event,
key_prefix: &Template,
encoding: &EncodingConfig<Encoding>,
) -> Option<PartitionInnerBuffer<Vec<u8>, Bytes>> {
encoding.apply_rules(&mut event);
let key = key_prefix
.render_string(&event)
.map_err(|missing_keys| {
warn!(
message = "Keys do not exist on the event. Dropping event.",
?missing_keys,
rate_limit_secs = 30,
);
})
.ok()?;
let log = event.into_log();
let bytes = match encoding.codec() {
Encoding::Ndjson => serde_json::to_vec(&log)
.map(|mut b| {
b.push(b'\n');
b
})
.expect("Failed to encode event as json, this is a bug!"),
Encoding::Text => {
let mut bytes = log
.get(&event::log_schema().message_key())
.map(|v| v.as_bytes().to_vec())
.unwrap_or_default();
bytes.push(b'\n');
bytes
}
};
Some(PartitionInnerBuffer::new(bytes, key.into()))
}
#[derive(Clone)]
struct GcsRetryLogic;
// This is a clone of HttpRetryLogic for the Body type, should get merged
impl RetryLogic for GcsRetryLogic {
type Error = hyper::Error;
type Response = Response<Body>;
fn is_retriable_error(&self, error: &Self::Error) -> bool {
error.is_connect() || error.is_closed()
}
fn should_retry_response(&self, response: &Self::Response) -> RetryAction {
let status = response.status();
match status {
StatusCode::TOO_MANY_REQUESTS => RetryAction::Retry("Too many requests".into()),
StatusCode::NOT_IMPLEMENTED => {
RetryAction::DontRetry("endpoint not implemented".into())
}
_ if status.is_server_error() => RetryAction::Retry(format!("{}", status)),
_ if status.is_success() => RetryAction::Successful,
_ => RetryAction::DontRetry(format!("response status: {}", status)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event::{self, Event};
use std::collections::HashMap;
#[test]
fn gcs_encode_event_text() {
let message = "hello world".to_string();
let batch_time_format = Template::try_from("date=%F").unwrap();
let bytes = encode_event(
message.clone().into(),
&batch_time_format,
&Encoding::Text.into(),
)
.unwrap();
let encoded_message = message + "\n";
let (bytes, _) = bytes.into_parts();
assert_eq!(&bytes[..], encoded_message.as_bytes());
}
#[test]
fn gcs_encode_event_ndjson() {
let message = "hello world".to_string();
let mut event = Event::from(message.clone());
event.as_mut_log().insert("key", "value");
let batch_time_format = Template::try_from("date=%F").unwrap();
let bytes = encode_event(event, &batch_time_format, &Encoding::Ndjson.into()).unwrap();
let (bytes, _) = bytes.into_parts();
let map: HashMap<String, String> = serde_json::from_slice(&bytes[..]).unwrap();
assert_eq!(
map.get(&event::log_schema().message_key().to_string()),
Some(&message)
);
assert_eq!(map["key"], "value".to_string());
}
fn request_settings(
extension: Option<&str>,
uuid: bool,
compression: Compression,
) -> RequestSettings {
RequestSettings::new(&GcsSinkConfig {
key_prefix: Some("key/".into()),
filename_time_format: Some("date".into()),
filename_extension: extension.map(Into::into),
filename_append_uuid: Some(uuid),
compression,
..default_config(Encoding::Ndjson)
})
.expect("Could not create request settings")
}
#[test]
fn gcs_build_request() {
let buf = PartitionInnerBuffer::new(vec![0u8; 10], Bytes::from("key/"));
let req = RequestWrapper::new(
buf.clone(),
request_settings(Some("ext"), false, Compression::None),
);
assert_eq!(req.key, "key/date.ext".to_string());
let req = RequestWrapper::new(
buf.clone(),
request_settings(None, false, Compression::None),
);
assert_eq!(req.key, "key/date.log".to_string());
let req = RequestWrapper::new(
buf.clone(),
request_settings(None, false, Compression::Gzip),
);
assert_eq!(req.key, "key/date.log.gz".to_string());
let req = RequestWrapper::new(buf, request_settings(None, true, Compression::Gzip));
assert_ne!(req.key, "key/date.log.gz".to_string());
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![feature(async_await, await_macro, futures_api)]
#![deny(warnings)]
mod app;
mod view_controller;
use app::App;
use failure::{Error, ResultExt};
use fidl::endpoints::ServiceMarker;
use fidl_fuchsia_ui_app as viewsv2;
use fidl_fuchsia_ui_viewsv1::ViewProviderMarker;
use fuchsia_async as fasync;
use std::env;
fn main() -> Result<(), Error> {
env::set_var("RUST_BACKTRACE", "full");
let mut executor = fasync::Executor::new().context("Error creating executor")?;
let app_for_v1 = App::new()?;
let app_for_v2 = app_for_v1.clone();
let fut = fuchsia_app::server::ServicesServer::new()
.add_service((ViewProviderMarker::NAME, move |chan| {
App::spawn_v1_view_provider_server(&app_for_v1, chan)
}))
.add_service((viewsv2::ViewProviderMarker::NAME, move |chan| {
App::spawn_v2_view_provider_server(&app_for_v2, chan)
}))
.start()
.context("Error starting view provider server")?;
executor.run_singlethreaded(fut)?;
Ok(())
}
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtQuick/qquickitem.h
// dst-file: /src/quick/qquickitem.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::QObject; // 771
use std::ops::Deref;
// use super::qquickitem::QQuickItem; // 773
use super::super::gui::qmatrix4x4::QMatrix4x4; // 771
use super::super::core::qpoint::QPointF; // 771
use super::super::core::qstring::QString; // 771
use super::super::core::qrect::QRectF; // 771
use super::qsgtextureprovider::QSGTextureProvider; // 773
use super::super::gui::qcursor::QCursor; // 771
use super::qquickwindow::QQuickWindow; // 773
use super::super::core::qsize::QSizeF; // 771
use super::super::qml::qjsvalue::QJSValue; // 771
use super::super::core::qsize::QSize; // 771
use super::super::gui::qtransform::QTransform; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QQuickTransform_Class_Size() -> c_int;
// proto: void QQuickTransform::~QQuickTransform();
fn _ZN15QQuickTransformD2Ev(qthis: u64 /* *mut c_void*/);
// proto: const QMetaObject * QQuickTransform::metaObject();
fn _ZNK15QQuickTransform10metaObjectEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickTransform::QQuickTransform(QObject * parent);
fn _ZN15QQuickTransformC2EP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickTransform::appendToItem(QQuickItem * );
fn _ZN15QQuickTransform12appendToItemEP10QQuickItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickTransform::applyTo(QMatrix4x4 * matrix);
fn _ZNK15QQuickTransform7applyToEP10QMatrix4x4(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickTransform::prependToItem(QQuickItem * );
fn _ZN15QQuickTransform13prependToItemEP10QQuickItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
fn QQuickItem_Class_Size() -> c_int;
// proto: qreal QQuickItem::implicitWidth();
fn _ZNK10QQuickItem13implicitWidthEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QQuickItem::setImplicitWidth(qreal );
fn _ZN10QQuickItem16setImplicitWidthEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QQuickItem::setBaselineOffset(qreal );
fn _ZN10QQuickItem17setBaselineOffsetEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QQuickItem::resetWidth();
fn _ZN10QQuickItem10resetWidthEv(qthis: u64 /* *mut c_void*/);
// proto: qreal QQuickItem::y();
fn _ZNK10QQuickItem1yEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::forceActiveFocus();
fn _ZN10QQuickItem16forceActiveFocusEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::setClip(bool );
fn _ZN10QQuickItem7setClipEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QQuickItem::setHeight(qreal );
fn _ZN10QQuickItem9setHeightEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QQuickItem::setY(qreal );
fn _ZN10QQuickItem4setYEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: qreal QQuickItem::rotation();
fn _ZNK10QQuickItem8rotationEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: qreal QQuickItem::opacity();
fn _ZNK10QQuickItem7opacityEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: qreal QQuickItem::implicitHeight();
fn _ZNK10QQuickItem14implicitHeightEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: bool QQuickItem::isTextureProvider();
fn _ZNK10QQuickItem17isTextureProviderEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QQuickItem::smooth();
fn _ZNK10QQuickItem6smoothEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QQmlListProperty<QQuickTransform> QQuickItem::transform();
fn _ZN10QQuickItem9transformEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::stackBefore(const QQuickItem * );
fn _ZN10QQuickItem11stackBeforeEPKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickItem::setActiveFocusOnTab(bool );
fn _ZN10QQuickItem19setActiveFocusOnTabEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: qreal QQuickItem::scale();
fn _ZNK10QQuickItem5scaleEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QQuickItem::setEnabled(bool );
fn _ZN10QQuickItem10setEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QQuickItem::setImplicitHeight(qreal );
fn _ZN10QQuickItem17setImplicitHeightEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QQuickItem::setPosition(const QPointF & );
fn _ZN10QQuickItem11setPositionERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickItem::setSmooth(bool );
fn _ZN10QQuickItem9setSmoothEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QPointF QQuickItem::mapFromScene(const QPointF & point);
fn _ZNK10QQuickItem12mapFromSceneERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QQuickItem::setAcceptHoverEvents(bool enabled);
fn _ZN10QQuickItem20setAcceptHoverEventsEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QPointF QQuickItem::transformOriginPoint();
fn _ZNK10QQuickItem20transformOriginPointEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickItem::setState(const QString & );
fn _ZN10QQuickItem8setStateERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QQuickItem * QQuickItem::parentItem();
fn _ZNK10QQuickItem10parentItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QQuickItem::isFocusScope();
fn _ZNK10QQuickItem12isFocusScopeEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QQuickItem::contains(const QPointF & point);
fn _ZNK10QQuickItem8containsERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: QRectF QQuickItem::boundingRect();
fn _ZNK10QQuickItem12boundingRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickItem::resetAntialiasing();
fn _ZN10QQuickItem17resetAntialiasingEv(qthis: u64 /* *mut c_void*/);
// proto: QRectF QQuickItem::mapRectToItem(const QQuickItem * item, const QRectF & rect);
fn _ZNK10QQuickItem13mapRectToItemEPKS_RK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: qreal QQuickItem::x();
fn _ZNK10QQuickItem1xEv(qthis: u64 /* *mut c_void*/);
// proto: QPointF QQuickItem::mapFromItem(const QQuickItem * item, const QPointF & point);
fn _ZNK10QQuickItem11mapFromItemEPKS_RK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: bool QQuickItem::isVisible();
fn _ZNK10QQuickItem9isVisibleEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QSGTextureProvider * QQuickItem::textureProvider();
fn _ZNK10QQuickItem15textureProviderEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickItem::setZ(qreal );
fn _ZN10QQuickItem4setZEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QQuickItem::unsetCursor();
fn _ZN10QQuickItem11unsetCursorEv(qthis: u64 /* *mut c_void*/);
// proto: bool QQuickItem::acceptHoverEvents();
fn _ZNK10QQuickItem17acceptHoverEventsEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QQuickItem::setFiltersChildMouseEvents(bool filter);
fn _ZN10QQuickItem26setFiltersChildMouseEventsEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QQuickItem::isEnabled();
fn _ZNK10QQuickItem9isEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QPointF QQuickItem::mapToItem(const QQuickItem * item, const QPointF & point);
fn _ZNK10QQuickItem9mapToItemEPKS_RK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: qreal QQuickItem::width();
fn _ZNK10QQuickItem5widthEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: QPointF QQuickItem::mapToScene(const QPointF & point);
fn _ZNK10QQuickItem10mapToSceneERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: bool QQuickItem::keepTouchGrab();
fn _ZNK10QQuickItem13keepTouchGrabEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QRectF QQuickItem::childrenRect();
fn _ZN10QQuickItem12childrenRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const QMetaObject * QQuickItem::metaObject();
fn _ZNK10QQuickItem10metaObjectEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::setKeepMouseGrab(bool );
fn _ZN10QQuickItem16setKeepMouseGrabEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QQuickItem::filtersChildMouseEvents();
fn _ZNK10QQuickItem23filtersChildMouseEventsEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QQuickItem::hasActiveFocus();
fn _ZNK10QQuickItem14hasActiveFocusEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QQuickItem::isUnderMouse();
fn _ZNK10QQuickItem12isUnderMouseEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QQuickItem::setTransformOriginPoint(const QPointF & );
fn _ZN10QQuickItem23setTransformOriginPointERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickItem::polish();
fn _ZN10QQuickItem6polishEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::setParentItem(QQuickItem * parent);
fn _ZN10QQuickItem13setParentItemEPS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickItem::QQuickItem(QQuickItem * parent);
fn _ZN10QQuickItemC2EPS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickItem::setWidth(qreal );
fn _ZN10QQuickItem8setWidthEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: QQuickItem * QQuickItem::nextItemInFocusChain(bool forward);
fn _ZN10QQuickItem20nextItemInFocusChainEb(qthis: u64 /* *mut c_void*/, arg0: c_char) -> *mut c_void;
// proto: void QQuickItem::ungrabTouchPoints();
fn _ZN10QQuickItem17ungrabTouchPointsEv(qthis: u64 /* *mut c_void*/);
// proto: bool QQuickItem::keepMouseGrab();
fn _ZNK10QQuickItem13keepMouseGrabEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QRectF QQuickItem::mapRectFromScene(const QRectF & rect);
fn _ZNK10QQuickItem16mapRectFromSceneERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QPointF QQuickItem::position();
fn _ZNK10QQuickItem8positionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: qreal QQuickItem::height();
fn _ZNK10QQuickItem6heightEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: QQuickItem * QQuickItem::childAt(qreal x, qreal y);
fn _ZNK10QQuickItem7childAtEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double) -> *mut c_void;
// proto: QCursor QQuickItem::cursor();
fn _ZNK10QQuickItem6cursorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QQuickItem::clip();
fn _ZNK10QQuickItem4clipEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QQuickItem::antialiasing();
fn _ZNK10QQuickItem12antialiasingEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QQuickWindow * QQuickItem::window();
fn _ZNK10QQuickItem6windowEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QRectF QQuickItem::mapRectFromItem(const QQuickItem * item, const QRectF & rect);
fn _ZNK10QQuickItem15mapRectFromItemEPKS_RK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QQuickItem::setVisible(bool );
fn _ZN10QQuickItem10setVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QQuickItem::setFocus(bool );
fn _ZN10QQuickItem8setFocusEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QQuickItem::activeFocusOnTab();
fn _ZNK10QQuickItem16activeFocusOnTabEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: qreal QQuickItem::z();
fn _ZNK10QQuickItem1zEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QQuickItem::setOpacity(qreal );
fn _ZN10QQuickItem10setOpacityEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QQuickItem::setAntialiasing(bool );
fn _ZN10QQuickItem15setAntialiasingEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QList<QQuickItem *> QQuickItem::childItems();
fn _ZNK10QQuickItem10childItemsEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::setSize(const QSizeF & size);
fn _ZN10QQuickItem7setSizeERK6QSizeF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickItem::~QQuickItem();
fn _ZN10QQuickItemD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QQuickItem * QQuickItem::scopedFocusItem();
fn _ZNK10QQuickItem15scopedFocusItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QQuickItem::grabToImage(const QJSValue & callback, const QSize & targetSize);
fn _ZN10QQuickItem11grabToImageERK8QJSValueRK5QSize(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: QTransform QQuickItem::itemTransform(QQuickItem * , bool * );
fn _ZNK10QQuickItem13itemTransformEPS_Pb(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_char) -> *mut c_void;
// proto: void QQuickItem::update();
fn _ZN10QQuickItem6updateEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::setCursor(const QCursor & cursor);
fn _ZN10QQuickItem9setCursorERK7QCursor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QSharedPointer<QQuickItemGrabResult> QQuickItem::grabToImage(const QSize & targetSize);
fn _ZN10QQuickItem11grabToImageERK5QSize(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QRectF QQuickItem::clipRect();
fn _ZNK10QQuickItem8clipRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickItem::ungrabMouse();
fn _ZN10QQuickItem11ungrabMouseEv(qthis: u64 /* *mut c_void*/);
// proto: QRectF QQuickItem::mapRectToScene(const QRectF & rect);
fn _ZNK10QQuickItem14mapRectToSceneERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QQuickItem::setRotation(qreal );
fn _ZN10QQuickItem11setRotationEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: bool QQuickItem::hasFocus();
fn _ZNK10QQuickItem8hasFocusEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QQuickItem::setX(qreal );
fn _ZN10QQuickItem4setXEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: QString QQuickItem::state();
fn _ZNK10QQuickItem5stateEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickItem::setScale(qreal );
fn _ZN10QQuickItem8setScaleEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QQuickItem::resetHeight();
fn _ZN10QQuickItem11resetHeightEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::QQuickItem(const QQuickItem & );
fn _ZN10QQuickItemC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuickItem::grabMouse();
fn _ZN10QQuickItem9grabMouseEv(qthis: u64 /* *mut c_void*/);
// proto: void QQuickItem::setKeepTouchGrab(bool );
fn _ZN10QQuickItem16setKeepTouchGrabEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QQuickItem::stackAfter(const QQuickItem * );
fn _ZN10QQuickItem10stackAfterEPKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: qreal QQuickItem::baselineOffset();
fn _ZNK10QQuickItem14baselineOffsetEv(qthis: u64 /* *mut c_void*/) -> c_double;
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem14opacityChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem14visibleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem13heightChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem19childrenRectChangedERK6QRectF(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem8yChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem19antialiasingChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem22visibleChildrenChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem12widthChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem15rotationChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem13smoothChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem15childrenChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem14enabledChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem21implicitHeightChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem13parentChangedEPS_(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem8xChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem13windowChangedEP12QQuickWindow(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem11clipChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem12scaleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem12focusChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem12stateChangedERK7QString(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem20implicitWidthChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem18activeFocusChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem21baselineOffsetChangedEd(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem23activeFocusOnTabChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QQuickItem_SlotProxy_connect__ZN10QQuickItem8zChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QQuickTransform)=1
#[derive(Default)]
pub struct QQuickTransform {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QQuickItem)=1
#[derive(Default)]
pub struct QQuickItem {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
pub _childrenChanged: QQuickItem_childrenChanged_signal,
pub _parentChanged: QQuickItem_parentChanged_signal,
pub _stateChanged: QQuickItem_stateChanged_signal,
pub _visibleChildrenChanged: QQuickItem_visibleChildrenChanged_signal,
pub _transformOriginChanged: QQuickItem_transformOriginChanged_signal,
pub _rotationChanged: QQuickItem_rotationChanged_signal,
pub _antialiasingChanged: QQuickItem_antialiasingChanged_signal,
pub _scaleChanged: QQuickItem_scaleChanged_signal,
pub _heightChanged: QQuickItem_heightChanged_signal,
pub _visibleChanged: QQuickItem_visibleChanged_signal,
pub _clipChanged: QQuickItem_clipChanged_signal,
pub _smoothChanged: QQuickItem_smoothChanged_signal,
pub _widthChanged: QQuickItem_widthChanged_signal,
pub _windowChanged: QQuickItem_windowChanged_signal,
pub _opacityChanged: QQuickItem_opacityChanged_signal,
pub _enabledChanged: QQuickItem_enabledChanged_signal,
pub _xChanged: QQuickItem_xChanged_signal,
pub _activeFocusOnTabChanged: QQuickItem_activeFocusOnTabChanged_signal,
pub _implicitHeightChanged: QQuickItem_implicitHeightChanged_signal,
pub _zChanged: QQuickItem_zChanged_signal,
pub _focusChanged: QQuickItem_focusChanged_signal,
pub _activeFocusChanged: QQuickItem_activeFocusChanged_signal,
pub _yChanged: QQuickItem_yChanged_signal,
pub _implicitWidthChanged: QQuickItem_implicitWidthChanged_signal,
pub _childrenRectChanged: QQuickItem_childrenRectChanged_signal,
pub _baselineOffsetChanged: QQuickItem_baselineOffsetChanged_signal,
}
impl /*struct*/ QQuickTransform {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QQuickTransform {
return QQuickTransform{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QQuickTransform {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QQuickTransform {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QQuickTransform::~QQuickTransform();
impl /*struct*/ QQuickTransform {
pub fn free<RetType, T: QQuickTransform_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QQuickTransform_free<RetType> {
fn free(self , rsthis: & QQuickTransform) -> RetType;
}
// proto: void QQuickTransform::~QQuickTransform();
impl<'a> /*trait*/ QQuickTransform_free<()> for () {
fn free(self , rsthis: & QQuickTransform) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QQuickTransformD2Ev()};
unsafe {_ZN15QQuickTransformD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: const QMetaObject * QQuickTransform::metaObject();
impl /*struct*/ QQuickTransform {
pub fn metaObject<RetType, T: QQuickTransform_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QQuickTransform_metaObject<RetType> {
fn metaObject(self , rsthis: & QQuickTransform) -> RetType;
}
// proto: const QMetaObject * QQuickTransform::metaObject();
impl<'a> /*trait*/ QQuickTransform_metaObject<()> for () {
fn metaObject(self , rsthis: & QQuickTransform) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QQuickTransform10metaObjectEv()};
unsafe {_ZNK15QQuickTransform10metaObjectEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickTransform::QQuickTransform(QObject * parent);
impl /*struct*/ QQuickTransform {
pub fn new<T: QQuickTransform_new>(value: T) -> QQuickTransform {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QQuickTransform_new {
fn new(self) -> QQuickTransform;
}
// proto: void QQuickTransform::QQuickTransform(QObject * parent);
impl<'a> /*trait*/ QQuickTransform_new for (&'a QObject) {
fn new(self) -> QQuickTransform {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QQuickTransformC2EP7QObject()};
let ctysz: c_int = unsafe{QQuickTransform_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN15QQuickTransformC2EP7QObject(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QQuickTransform{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QQuickTransform::appendToItem(QQuickItem * );
impl /*struct*/ QQuickTransform {
pub fn appendToItem<RetType, T: QQuickTransform_appendToItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.appendToItem(self);
// return 1;
}
}
pub trait QQuickTransform_appendToItem<RetType> {
fn appendToItem(self , rsthis: & QQuickTransform) -> RetType;
}
// proto: void QQuickTransform::appendToItem(QQuickItem * );
impl<'a> /*trait*/ QQuickTransform_appendToItem<()> for (&'a QQuickItem) {
fn appendToItem(self , rsthis: & QQuickTransform) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QQuickTransform12appendToItemEP10QQuickItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN15QQuickTransform12appendToItemEP10QQuickItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickTransform::applyTo(QMatrix4x4 * matrix);
impl /*struct*/ QQuickTransform {
pub fn applyTo<RetType, T: QQuickTransform_applyTo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.applyTo(self);
// return 1;
}
}
pub trait QQuickTransform_applyTo<RetType> {
fn applyTo(self , rsthis: & QQuickTransform) -> RetType;
}
// proto: void QQuickTransform::applyTo(QMatrix4x4 * matrix);
impl<'a> /*trait*/ QQuickTransform_applyTo<()> for (&'a QMatrix4x4) {
fn applyTo(self , rsthis: & QQuickTransform) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QQuickTransform7applyToEP10QMatrix4x4()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZNK15QQuickTransform7applyToEP10QMatrix4x4(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickTransform::prependToItem(QQuickItem * );
impl /*struct*/ QQuickTransform {
pub fn prependToItem<RetType, T: QQuickTransform_prependToItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.prependToItem(self);
// return 1;
}
}
pub trait QQuickTransform_prependToItem<RetType> {
fn prependToItem(self , rsthis: & QQuickTransform) -> RetType;
}
// proto: void QQuickTransform::prependToItem(QQuickItem * );
impl<'a> /*trait*/ QQuickTransform_prependToItem<()> for (&'a QQuickItem) {
fn prependToItem(self , rsthis: & QQuickTransform) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QQuickTransform13prependToItemEP10QQuickItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN15QQuickTransform13prependToItemEP10QQuickItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
impl /*struct*/ QQuickItem {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QQuickItem {
return QQuickItem{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QQuickItem {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QQuickItem {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: qreal QQuickItem::implicitWidth();
impl /*struct*/ QQuickItem {
pub fn implicitWidth<RetType, T: QQuickItem_implicitWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.implicitWidth(self);
// return 1;
}
}
pub trait QQuickItem_implicitWidth<RetType> {
fn implicitWidth(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::implicitWidth();
impl<'a> /*trait*/ QQuickItem_implicitWidth<f64> for () {
fn implicitWidth(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem13implicitWidthEv()};
let mut ret = unsafe {_ZNK10QQuickItem13implicitWidthEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: void QQuickItem::setImplicitWidth(qreal );
impl /*struct*/ QQuickItem {
pub fn setImplicitWidth<RetType, T: QQuickItem_setImplicitWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setImplicitWidth(self);
// return 1;
}
}
pub trait QQuickItem_setImplicitWidth<RetType> {
fn setImplicitWidth(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setImplicitWidth(qreal );
impl<'a> /*trait*/ QQuickItem_setImplicitWidth<()> for (f64) {
fn setImplicitWidth(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem16setImplicitWidthEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem16setImplicitWidthEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setBaselineOffset(qreal );
impl /*struct*/ QQuickItem {
pub fn setBaselineOffset<RetType, T: QQuickItem_setBaselineOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBaselineOffset(self);
// return 1;
}
}
pub trait QQuickItem_setBaselineOffset<RetType> {
fn setBaselineOffset(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setBaselineOffset(qreal );
impl<'a> /*trait*/ QQuickItem_setBaselineOffset<()> for (f64) {
fn setBaselineOffset(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem17setBaselineOffsetEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem17setBaselineOffsetEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::resetWidth();
impl /*struct*/ QQuickItem {
pub fn resetWidth<RetType, T: QQuickItem_resetWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resetWidth(self);
// return 1;
}
}
pub trait QQuickItem_resetWidth<RetType> {
fn resetWidth(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::resetWidth();
impl<'a> /*trait*/ QQuickItem_resetWidth<()> for () {
fn resetWidth(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem10resetWidthEv()};
unsafe {_ZN10QQuickItem10resetWidthEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: qreal QQuickItem::y();
impl /*struct*/ QQuickItem {
pub fn y<RetType, T: QQuickItem_y<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.y(self);
// return 1;
}
}
pub trait QQuickItem_y<RetType> {
fn y(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::y();
impl<'a> /*trait*/ QQuickItem_y<()> for () {
fn y(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem1yEv()};
unsafe {_ZNK10QQuickItem1yEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::forceActiveFocus();
impl /*struct*/ QQuickItem {
pub fn forceActiveFocus<RetType, T: QQuickItem_forceActiveFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.forceActiveFocus(self);
// return 1;
}
}
pub trait QQuickItem_forceActiveFocus<RetType> {
fn forceActiveFocus(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::forceActiveFocus();
impl<'a> /*trait*/ QQuickItem_forceActiveFocus<()> for () {
fn forceActiveFocus(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem16forceActiveFocusEv()};
unsafe {_ZN10QQuickItem16forceActiveFocusEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::setClip(bool );
impl /*struct*/ QQuickItem {
pub fn setClip<RetType, T: QQuickItem_setClip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setClip(self);
// return 1;
}
}
pub trait QQuickItem_setClip<RetType> {
fn setClip(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setClip(bool );
impl<'a> /*trait*/ QQuickItem_setClip<()> for (i8) {
fn setClip(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem7setClipEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem7setClipEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setHeight(qreal );
impl /*struct*/ QQuickItem {
pub fn setHeight<RetType, T: QQuickItem_setHeight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setHeight(self);
// return 1;
}
}
pub trait QQuickItem_setHeight<RetType> {
fn setHeight(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setHeight(qreal );
impl<'a> /*trait*/ QQuickItem_setHeight<()> for (f64) {
fn setHeight(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem9setHeightEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem9setHeightEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setY(qreal );
impl /*struct*/ QQuickItem {
pub fn setY<RetType, T: QQuickItem_setY<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setY(self);
// return 1;
}
}
pub trait QQuickItem_setY<RetType> {
fn setY(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setY(qreal );
impl<'a> /*trait*/ QQuickItem_setY<()> for (f64) {
fn setY(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem4setYEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem4setYEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QQuickItem::rotation();
impl /*struct*/ QQuickItem {
pub fn rotation<RetType, T: QQuickItem_rotation<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rotation(self);
// return 1;
}
}
pub trait QQuickItem_rotation<RetType> {
fn rotation(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::rotation();
impl<'a> /*trait*/ QQuickItem_rotation<f64> for () {
fn rotation(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem8rotationEv()};
let mut ret = unsafe {_ZNK10QQuickItem8rotationEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: qreal QQuickItem::opacity();
impl /*struct*/ QQuickItem {
pub fn opacity<RetType, T: QQuickItem_opacity<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.opacity(self);
// return 1;
}
}
pub trait QQuickItem_opacity<RetType> {
fn opacity(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::opacity();
impl<'a> /*trait*/ QQuickItem_opacity<f64> for () {
fn opacity(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem7opacityEv()};
let mut ret = unsafe {_ZNK10QQuickItem7opacityEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: qreal QQuickItem::implicitHeight();
impl /*struct*/ QQuickItem {
pub fn implicitHeight<RetType, T: QQuickItem_implicitHeight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.implicitHeight(self);
// return 1;
}
}
pub trait QQuickItem_implicitHeight<RetType> {
fn implicitHeight(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::implicitHeight();
impl<'a> /*trait*/ QQuickItem_implicitHeight<f64> for () {
fn implicitHeight(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem14implicitHeightEv()};
let mut ret = unsafe {_ZNK10QQuickItem14implicitHeightEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: bool QQuickItem::isTextureProvider();
impl /*struct*/ QQuickItem {
pub fn isTextureProvider<RetType, T: QQuickItem_isTextureProvider<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isTextureProvider(self);
// return 1;
}
}
pub trait QQuickItem_isTextureProvider<RetType> {
fn isTextureProvider(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::isTextureProvider();
impl<'a> /*trait*/ QQuickItem_isTextureProvider<i8> for () {
fn isTextureProvider(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem17isTextureProviderEv()};
let mut ret = unsafe {_ZNK10QQuickItem17isTextureProviderEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: bool QQuickItem::smooth();
impl /*struct*/ QQuickItem {
pub fn smooth<RetType, T: QQuickItem_smooth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.smooth(self);
// return 1;
}
}
pub trait QQuickItem_smooth<RetType> {
fn smooth(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::smooth();
impl<'a> /*trait*/ QQuickItem_smooth<i8> for () {
fn smooth(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem6smoothEv()};
let mut ret = unsafe {_ZNK10QQuickItem6smoothEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QQmlListProperty<QQuickTransform> QQuickItem::transform();
impl /*struct*/ QQuickItem {
pub fn transform<RetType, T: QQuickItem_transform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.transform(self);
// return 1;
}
}
pub trait QQuickItem_transform<RetType> {
fn transform(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QQmlListProperty<QQuickTransform> QQuickItem::transform();
impl<'a> /*trait*/ QQuickItem_transform<()> for () {
fn transform(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem9transformEv()};
unsafe {_ZN10QQuickItem9transformEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::stackBefore(const QQuickItem * );
impl /*struct*/ QQuickItem {
pub fn stackBefore<RetType, T: QQuickItem_stackBefore<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.stackBefore(self);
// return 1;
}
}
pub trait QQuickItem_stackBefore<RetType> {
fn stackBefore(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::stackBefore(const QQuickItem * );
impl<'a> /*trait*/ QQuickItem_stackBefore<()> for (&'a QQuickItem) {
fn stackBefore(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11stackBeforeEPKS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem11stackBeforeEPKS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setActiveFocusOnTab(bool );
impl /*struct*/ QQuickItem {
pub fn setActiveFocusOnTab<RetType, T: QQuickItem_setActiveFocusOnTab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setActiveFocusOnTab(self);
// return 1;
}
}
pub trait QQuickItem_setActiveFocusOnTab<RetType> {
fn setActiveFocusOnTab(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setActiveFocusOnTab(bool );
impl<'a> /*trait*/ QQuickItem_setActiveFocusOnTab<()> for (i8) {
fn setActiveFocusOnTab(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem19setActiveFocusOnTabEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem19setActiveFocusOnTabEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QQuickItem::scale();
impl /*struct*/ QQuickItem {
pub fn scale<RetType, T: QQuickItem_scale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.scale(self);
// return 1;
}
}
pub trait QQuickItem_scale<RetType> {
fn scale(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::scale();
impl<'a> /*trait*/ QQuickItem_scale<f64> for () {
fn scale(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem5scaleEv()};
let mut ret = unsafe {_ZNK10QQuickItem5scaleEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: void QQuickItem::setEnabled(bool );
impl /*struct*/ QQuickItem {
pub fn setEnabled<RetType, T: QQuickItem_setEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setEnabled(self);
// return 1;
}
}
pub trait QQuickItem_setEnabled<RetType> {
fn setEnabled(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setEnabled(bool );
impl<'a> /*trait*/ QQuickItem_setEnabled<()> for (i8) {
fn setEnabled(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem10setEnabledEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem10setEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setImplicitHeight(qreal );
impl /*struct*/ QQuickItem {
pub fn setImplicitHeight<RetType, T: QQuickItem_setImplicitHeight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setImplicitHeight(self);
// return 1;
}
}
pub trait QQuickItem_setImplicitHeight<RetType> {
fn setImplicitHeight(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setImplicitHeight(qreal );
impl<'a> /*trait*/ QQuickItem_setImplicitHeight<()> for (f64) {
fn setImplicitHeight(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem17setImplicitHeightEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem17setImplicitHeightEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setPosition(const QPointF & );
impl /*struct*/ QQuickItem {
pub fn setPosition<RetType, T: QQuickItem_setPosition<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPosition(self);
// return 1;
}
}
pub trait QQuickItem_setPosition<RetType> {
fn setPosition(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setPosition(const QPointF & );
impl<'a> /*trait*/ QQuickItem_setPosition<()> for (&'a QPointF) {
fn setPosition(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11setPositionERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem11setPositionERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setSmooth(bool );
impl /*struct*/ QQuickItem {
pub fn setSmooth<RetType, T: QQuickItem_setSmooth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSmooth(self);
// return 1;
}
}
pub trait QQuickItem_setSmooth<RetType> {
fn setSmooth(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setSmooth(bool );
impl<'a> /*trait*/ QQuickItem_setSmooth<()> for (i8) {
fn setSmooth(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem9setSmoothEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem9setSmoothEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QPointF QQuickItem::mapFromScene(const QPointF & point);
impl /*struct*/ QQuickItem {
pub fn mapFromScene<RetType, T: QQuickItem_mapFromScene<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapFromScene(self);
// return 1;
}
}
pub trait QQuickItem_mapFromScene<RetType> {
fn mapFromScene(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QPointF QQuickItem::mapFromScene(const QPointF & point);
impl<'a> /*trait*/ QQuickItem_mapFromScene<QPointF> for (&'a QPointF) {
fn mapFromScene(self , rsthis: & QQuickItem) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem12mapFromSceneERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem12mapFromSceneERK7QPointF(rsthis.qclsinst, arg0)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::setAcceptHoverEvents(bool enabled);
impl /*struct*/ QQuickItem {
pub fn setAcceptHoverEvents<RetType, T: QQuickItem_setAcceptHoverEvents<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAcceptHoverEvents(self);
// return 1;
}
}
pub trait QQuickItem_setAcceptHoverEvents<RetType> {
fn setAcceptHoverEvents(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setAcceptHoverEvents(bool enabled);
impl<'a> /*trait*/ QQuickItem_setAcceptHoverEvents<()> for (i8) {
fn setAcceptHoverEvents(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem20setAcceptHoverEventsEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem20setAcceptHoverEventsEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QPointF QQuickItem::transformOriginPoint();
impl /*struct*/ QQuickItem {
pub fn transformOriginPoint<RetType, T: QQuickItem_transformOriginPoint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.transformOriginPoint(self);
// return 1;
}
}
pub trait QQuickItem_transformOriginPoint<RetType> {
fn transformOriginPoint(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QPointF QQuickItem::transformOriginPoint();
impl<'a> /*trait*/ QQuickItem_transformOriginPoint<QPointF> for () {
fn transformOriginPoint(self , rsthis: & QQuickItem) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem20transformOriginPointEv()};
let mut ret = unsafe {_ZNK10QQuickItem20transformOriginPointEv(rsthis.qclsinst)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::setState(const QString & );
impl /*struct*/ QQuickItem {
pub fn setState<RetType, T: QQuickItem_setState<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setState(self);
// return 1;
}
}
pub trait QQuickItem_setState<RetType> {
fn setState(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setState(const QString & );
impl<'a> /*trait*/ QQuickItem_setState<()> for (&'a QString) {
fn setState(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem8setStateERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem8setStateERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QQuickItem * QQuickItem::parentItem();
impl /*struct*/ QQuickItem {
pub fn parentItem<RetType, T: QQuickItem_parentItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.parentItem(self);
// return 1;
}
}
pub trait QQuickItem_parentItem<RetType> {
fn parentItem(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QQuickItem * QQuickItem::parentItem();
impl<'a> /*trait*/ QQuickItem_parentItem<QQuickItem> for () {
fn parentItem(self , rsthis: & QQuickItem) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem10parentItemEv()};
let mut ret = unsafe {_ZNK10QQuickItem10parentItemEv(rsthis.qclsinst)};
let mut ret1 = QQuickItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickItem::isFocusScope();
impl /*struct*/ QQuickItem {
pub fn isFocusScope<RetType, T: QQuickItem_isFocusScope<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isFocusScope(self);
// return 1;
}
}
pub trait QQuickItem_isFocusScope<RetType> {
fn isFocusScope(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::isFocusScope();
impl<'a> /*trait*/ QQuickItem_isFocusScope<i8> for () {
fn isFocusScope(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem12isFocusScopeEv()};
let mut ret = unsafe {_ZNK10QQuickItem12isFocusScopeEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: bool QQuickItem::contains(const QPointF & point);
impl /*struct*/ QQuickItem {
pub fn contains<RetType, T: QQuickItem_contains<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.contains(self);
// return 1;
}
}
pub trait QQuickItem_contains<RetType> {
fn contains(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::contains(const QPointF & point);
impl<'a> /*trait*/ QQuickItem_contains<i8> for (&'a QPointF) {
fn contains(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem8containsERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem8containsERK7QPointF(rsthis.qclsinst, arg0)};
return ret as i8;
// return 1;
}
}
// proto: QRectF QQuickItem::boundingRect();
impl /*struct*/ QQuickItem {
pub fn boundingRect<RetType, T: QQuickItem_boundingRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.boundingRect(self);
// return 1;
}
}
pub trait QQuickItem_boundingRect<RetType> {
fn boundingRect(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QRectF QQuickItem::boundingRect();
impl<'a> /*trait*/ QQuickItem_boundingRect<QRectF> for () {
fn boundingRect(self , rsthis: & QQuickItem) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem12boundingRectEv()};
let mut ret = unsafe {_ZNK10QQuickItem12boundingRectEv(rsthis.qclsinst)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::resetAntialiasing();
impl /*struct*/ QQuickItem {
pub fn resetAntialiasing<RetType, T: QQuickItem_resetAntialiasing<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resetAntialiasing(self);
// return 1;
}
}
pub trait QQuickItem_resetAntialiasing<RetType> {
fn resetAntialiasing(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::resetAntialiasing();
impl<'a> /*trait*/ QQuickItem_resetAntialiasing<()> for () {
fn resetAntialiasing(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem17resetAntialiasingEv()};
unsafe {_ZN10QQuickItem17resetAntialiasingEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QRectF QQuickItem::mapRectToItem(const QQuickItem * item, const QRectF & rect);
impl /*struct*/ QQuickItem {
pub fn mapRectToItem<RetType, T: QQuickItem_mapRectToItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapRectToItem(self);
// return 1;
}
}
pub trait QQuickItem_mapRectToItem<RetType> {
fn mapRectToItem(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QRectF QQuickItem::mapRectToItem(const QQuickItem * item, const QRectF & rect);
impl<'a> /*trait*/ QQuickItem_mapRectToItem<QRectF> for (&'a QQuickItem, &'a QRectF) {
fn mapRectToItem(self , rsthis: & QQuickItem) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem13mapRectToItemEPKS_RK6QRectF()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem13mapRectToItemEPKS_RK6QRectF(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QQuickItem::x();
impl /*struct*/ QQuickItem {
pub fn x<RetType, T: QQuickItem_x<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.x(self);
// return 1;
}
}
pub trait QQuickItem_x<RetType> {
fn x(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::x();
impl<'a> /*trait*/ QQuickItem_x<()> for () {
fn x(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem1xEv()};
unsafe {_ZNK10QQuickItem1xEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QPointF QQuickItem::mapFromItem(const QQuickItem * item, const QPointF & point);
impl /*struct*/ QQuickItem {
pub fn mapFromItem<RetType, T: QQuickItem_mapFromItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapFromItem(self);
// return 1;
}
}
pub trait QQuickItem_mapFromItem<RetType> {
fn mapFromItem(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QPointF QQuickItem::mapFromItem(const QQuickItem * item, const QPointF & point);
impl<'a> /*trait*/ QQuickItem_mapFromItem<QPointF> for (&'a QQuickItem, &'a QPointF) {
fn mapFromItem(self , rsthis: & QQuickItem) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem11mapFromItemEPKS_RK7QPointF()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem11mapFromItemEPKS_RK7QPointF(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickItem::isVisible();
impl /*struct*/ QQuickItem {
pub fn isVisible<RetType, T: QQuickItem_isVisible<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isVisible(self);
// return 1;
}
}
pub trait QQuickItem_isVisible<RetType> {
fn isVisible(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::isVisible();
impl<'a> /*trait*/ QQuickItem_isVisible<i8> for () {
fn isVisible(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem9isVisibleEv()};
let mut ret = unsafe {_ZNK10QQuickItem9isVisibleEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QSGTextureProvider * QQuickItem::textureProvider();
impl /*struct*/ QQuickItem {
pub fn textureProvider<RetType, T: QQuickItem_textureProvider<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.textureProvider(self);
// return 1;
}
}
pub trait QQuickItem_textureProvider<RetType> {
fn textureProvider(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QSGTextureProvider * QQuickItem::textureProvider();
impl<'a> /*trait*/ QQuickItem_textureProvider<QSGTextureProvider> for () {
fn textureProvider(self , rsthis: & QQuickItem) -> QSGTextureProvider {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem15textureProviderEv()};
let mut ret = unsafe {_ZNK10QQuickItem15textureProviderEv(rsthis.qclsinst)};
let mut ret1 = QSGTextureProvider::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::setZ(qreal );
impl /*struct*/ QQuickItem {
pub fn setZ<RetType, T: QQuickItem_setZ<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setZ(self);
// return 1;
}
}
pub trait QQuickItem_setZ<RetType> {
fn setZ(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setZ(qreal );
impl<'a> /*trait*/ QQuickItem_setZ<()> for (f64) {
fn setZ(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem4setZEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem4setZEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::unsetCursor();
impl /*struct*/ QQuickItem {
pub fn unsetCursor<RetType, T: QQuickItem_unsetCursor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.unsetCursor(self);
// return 1;
}
}
pub trait QQuickItem_unsetCursor<RetType> {
fn unsetCursor(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::unsetCursor();
impl<'a> /*trait*/ QQuickItem_unsetCursor<()> for () {
fn unsetCursor(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11unsetCursorEv()};
unsafe {_ZN10QQuickItem11unsetCursorEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QQuickItem::acceptHoverEvents();
impl /*struct*/ QQuickItem {
pub fn acceptHoverEvents<RetType, T: QQuickItem_acceptHoverEvents<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.acceptHoverEvents(self);
// return 1;
}
}
pub trait QQuickItem_acceptHoverEvents<RetType> {
fn acceptHoverEvents(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::acceptHoverEvents();
impl<'a> /*trait*/ QQuickItem_acceptHoverEvents<i8> for () {
fn acceptHoverEvents(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem17acceptHoverEventsEv()};
let mut ret = unsafe {_ZNK10QQuickItem17acceptHoverEventsEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QQuickItem::setFiltersChildMouseEvents(bool filter);
impl /*struct*/ QQuickItem {
pub fn setFiltersChildMouseEvents<RetType, T: QQuickItem_setFiltersChildMouseEvents<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setFiltersChildMouseEvents(self);
// return 1;
}
}
pub trait QQuickItem_setFiltersChildMouseEvents<RetType> {
fn setFiltersChildMouseEvents(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setFiltersChildMouseEvents(bool filter);
impl<'a> /*trait*/ QQuickItem_setFiltersChildMouseEvents<()> for (i8) {
fn setFiltersChildMouseEvents(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem26setFiltersChildMouseEventsEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem26setFiltersChildMouseEventsEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QQuickItem::isEnabled();
impl /*struct*/ QQuickItem {
pub fn isEnabled<RetType, T: QQuickItem_isEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEnabled(self);
// return 1;
}
}
pub trait QQuickItem_isEnabled<RetType> {
fn isEnabled(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::isEnabled();
impl<'a> /*trait*/ QQuickItem_isEnabled<i8> for () {
fn isEnabled(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem9isEnabledEv()};
let mut ret = unsafe {_ZNK10QQuickItem9isEnabledEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QPointF QQuickItem::mapToItem(const QQuickItem * item, const QPointF & point);
impl /*struct*/ QQuickItem {
pub fn mapToItem<RetType, T: QQuickItem_mapToItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapToItem(self);
// return 1;
}
}
pub trait QQuickItem_mapToItem<RetType> {
fn mapToItem(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QPointF QQuickItem::mapToItem(const QQuickItem * item, const QPointF & point);
impl<'a> /*trait*/ QQuickItem_mapToItem<QPointF> for (&'a QQuickItem, &'a QPointF) {
fn mapToItem(self , rsthis: & QQuickItem) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem9mapToItemEPKS_RK7QPointF()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem9mapToItemEPKS_RK7QPointF(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QQuickItem::width();
impl /*struct*/ QQuickItem {
pub fn width<RetType, T: QQuickItem_width<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.width(self);
// return 1;
}
}
pub trait QQuickItem_width<RetType> {
fn width(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::width();
impl<'a> /*trait*/ QQuickItem_width<f64> for () {
fn width(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem5widthEv()};
let mut ret = unsafe {_ZNK10QQuickItem5widthEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: QPointF QQuickItem::mapToScene(const QPointF & point);
impl /*struct*/ QQuickItem {
pub fn mapToScene<RetType, T: QQuickItem_mapToScene<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapToScene(self);
// return 1;
}
}
pub trait QQuickItem_mapToScene<RetType> {
fn mapToScene(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QPointF QQuickItem::mapToScene(const QPointF & point);
impl<'a> /*trait*/ QQuickItem_mapToScene<QPointF> for (&'a QPointF) {
fn mapToScene(self , rsthis: & QQuickItem) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem10mapToSceneERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem10mapToSceneERK7QPointF(rsthis.qclsinst, arg0)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickItem::keepTouchGrab();
impl /*struct*/ QQuickItem {
pub fn keepTouchGrab<RetType, T: QQuickItem_keepTouchGrab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.keepTouchGrab(self);
// return 1;
}
}
pub trait QQuickItem_keepTouchGrab<RetType> {
fn keepTouchGrab(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::keepTouchGrab();
impl<'a> /*trait*/ QQuickItem_keepTouchGrab<i8> for () {
fn keepTouchGrab(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem13keepTouchGrabEv()};
let mut ret = unsafe {_ZNK10QQuickItem13keepTouchGrabEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QRectF QQuickItem::childrenRect();
impl /*struct*/ QQuickItem {
pub fn childrenRect<RetType, T: QQuickItem_childrenRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.childrenRect(self);
// return 1;
}
}
pub trait QQuickItem_childrenRect<RetType> {
fn childrenRect(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QRectF QQuickItem::childrenRect();
impl<'a> /*trait*/ QQuickItem_childrenRect<QRectF> for () {
fn childrenRect(self , rsthis: & QQuickItem) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem12childrenRectEv()};
let mut ret = unsafe {_ZN10QQuickItem12childrenRectEv(rsthis.qclsinst)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QQuickItem::metaObject();
impl /*struct*/ QQuickItem {
pub fn metaObject<RetType, T: QQuickItem_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QQuickItem_metaObject<RetType> {
fn metaObject(self , rsthis: & QQuickItem) -> RetType;
}
// proto: const QMetaObject * QQuickItem::metaObject();
impl<'a> /*trait*/ QQuickItem_metaObject<()> for () {
fn metaObject(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem10metaObjectEv()};
unsafe {_ZNK10QQuickItem10metaObjectEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::setKeepMouseGrab(bool );
impl /*struct*/ QQuickItem {
pub fn setKeepMouseGrab<RetType, T: QQuickItem_setKeepMouseGrab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setKeepMouseGrab(self);
// return 1;
}
}
pub trait QQuickItem_setKeepMouseGrab<RetType> {
fn setKeepMouseGrab(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setKeepMouseGrab(bool );
impl<'a> /*trait*/ QQuickItem_setKeepMouseGrab<()> for (i8) {
fn setKeepMouseGrab(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem16setKeepMouseGrabEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem16setKeepMouseGrabEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QQuickItem::filtersChildMouseEvents();
impl /*struct*/ QQuickItem {
pub fn filtersChildMouseEvents<RetType, T: QQuickItem_filtersChildMouseEvents<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.filtersChildMouseEvents(self);
// return 1;
}
}
pub trait QQuickItem_filtersChildMouseEvents<RetType> {
fn filtersChildMouseEvents(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::filtersChildMouseEvents();
impl<'a> /*trait*/ QQuickItem_filtersChildMouseEvents<i8> for () {
fn filtersChildMouseEvents(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem23filtersChildMouseEventsEv()};
let mut ret = unsafe {_ZNK10QQuickItem23filtersChildMouseEventsEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: bool QQuickItem::hasActiveFocus();
impl /*struct*/ QQuickItem {
pub fn hasActiveFocus<RetType, T: QQuickItem_hasActiveFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasActiveFocus(self);
// return 1;
}
}
pub trait QQuickItem_hasActiveFocus<RetType> {
fn hasActiveFocus(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::hasActiveFocus();
impl<'a> /*trait*/ QQuickItem_hasActiveFocus<i8> for () {
fn hasActiveFocus(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem14hasActiveFocusEv()};
let mut ret = unsafe {_ZNK10QQuickItem14hasActiveFocusEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: bool QQuickItem::isUnderMouse();
impl /*struct*/ QQuickItem {
pub fn isUnderMouse<RetType, T: QQuickItem_isUnderMouse<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isUnderMouse(self);
// return 1;
}
}
pub trait QQuickItem_isUnderMouse<RetType> {
fn isUnderMouse(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::isUnderMouse();
impl<'a> /*trait*/ QQuickItem_isUnderMouse<i8> for () {
fn isUnderMouse(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem12isUnderMouseEv()};
let mut ret = unsafe {_ZNK10QQuickItem12isUnderMouseEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QQuickItem::setTransformOriginPoint(const QPointF & );
impl /*struct*/ QQuickItem {
pub fn setTransformOriginPoint<RetType, T: QQuickItem_setTransformOriginPoint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTransformOriginPoint(self);
// return 1;
}
}
pub trait QQuickItem_setTransformOriginPoint<RetType> {
fn setTransformOriginPoint(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setTransformOriginPoint(const QPointF & );
impl<'a> /*trait*/ QQuickItem_setTransformOriginPoint<()> for (&'a QPointF) {
fn setTransformOriginPoint(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem23setTransformOriginPointERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem23setTransformOriginPointERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::polish();
impl /*struct*/ QQuickItem {
pub fn polish<RetType, T: QQuickItem_polish<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.polish(self);
// return 1;
}
}
pub trait QQuickItem_polish<RetType> {
fn polish(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::polish();
impl<'a> /*trait*/ QQuickItem_polish<()> for () {
fn polish(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem6polishEv()};
unsafe {_ZN10QQuickItem6polishEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::setParentItem(QQuickItem * parent);
impl /*struct*/ QQuickItem {
pub fn setParentItem<RetType, T: QQuickItem_setParentItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setParentItem(self);
// return 1;
}
}
pub trait QQuickItem_setParentItem<RetType> {
fn setParentItem(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setParentItem(QQuickItem * parent);
impl<'a> /*trait*/ QQuickItem_setParentItem<()> for (&'a QQuickItem) {
fn setParentItem(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem13setParentItemEPS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem13setParentItemEPS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::QQuickItem(QQuickItem * parent);
impl /*struct*/ QQuickItem {
pub fn new<T: QQuickItem_new>(value: T) -> QQuickItem {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QQuickItem_new {
fn new(self) -> QQuickItem;
}
// proto: void QQuickItem::QQuickItem(QQuickItem * parent);
impl<'a> /*trait*/ QQuickItem_new for (&'a QQuickItem) {
fn new(self) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItemC2EPS_()};
let ctysz: c_int = unsafe{QQuickItem_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItemC2EPS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QQuickItem{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QQuickItem::setWidth(qreal );
impl /*struct*/ QQuickItem {
pub fn setWidth<RetType, T: QQuickItem_setWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWidth(self);
// return 1;
}
}
pub trait QQuickItem_setWidth<RetType> {
fn setWidth(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setWidth(qreal );
impl<'a> /*trait*/ QQuickItem_setWidth<()> for (f64) {
fn setWidth(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem8setWidthEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem8setWidthEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QQuickItem * QQuickItem::nextItemInFocusChain(bool forward);
impl /*struct*/ QQuickItem {
pub fn nextItemInFocusChain<RetType, T: QQuickItem_nextItemInFocusChain<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.nextItemInFocusChain(self);
// return 1;
}
}
pub trait QQuickItem_nextItemInFocusChain<RetType> {
fn nextItemInFocusChain(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QQuickItem * QQuickItem::nextItemInFocusChain(bool forward);
impl<'a> /*trait*/ QQuickItem_nextItemInFocusChain<QQuickItem> for (i8) {
fn nextItemInFocusChain(self , rsthis: & QQuickItem) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem20nextItemInFocusChainEb()};
let arg0 = self as c_char;
let mut ret = unsafe {_ZN10QQuickItem20nextItemInFocusChainEb(rsthis.qclsinst, arg0)};
let mut ret1 = QQuickItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::ungrabTouchPoints();
impl /*struct*/ QQuickItem {
pub fn ungrabTouchPoints<RetType, T: QQuickItem_ungrabTouchPoints<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.ungrabTouchPoints(self);
// return 1;
}
}
pub trait QQuickItem_ungrabTouchPoints<RetType> {
fn ungrabTouchPoints(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::ungrabTouchPoints();
impl<'a> /*trait*/ QQuickItem_ungrabTouchPoints<()> for () {
fn ungrabTouchPoints(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem17ungrabTouchPointsEv()};
unsafe {_ZN10QQuickItem17ungrabTouchPointsEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QQuickItem::keepMouseGrab();
impl /*struct*/ QQuickItem {
pub fn keepMouseGrab<RetType, T: QQuickItem_keepMouseGrab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.keepMouseGrab(self);
// return 1;
}
}
pub trait QQuickItem_keepMouseGrab<RetType> {
fn keepMouseGrab(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::keepMouseGrab();
impl<'a> /*trait*/ QQuickItem_keepMouseGrab<i8> for () {
fn keepMouseGrab(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem13keepMouseGrabEv()};
let mut ret = unsafe {_ZNK10QQuickItem13keepMouseGrabEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QRectF QQuickItem::mapRectFromScene(const QRectF & rect);
impl /*struct*/ QQuickItem {
pub fn mapRectFromScene<RetType, T: QQuickItem_mapRectFromScene<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapRectFromScene(self);
// return 1;
}
}
pub trait QQuickItem_mapRectFromScene<RetType> {
fn mapRectFromScene(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QRectF QQuickItem::mapRectFromScene(const QRectF & rect);
impl<'a> /*trait*/ QQuickItem_mapRectFromScene<QRectF> for (&'a QRectF) {
fn mapRectFromScene(self , rsthis: & QQuickItem) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem16mapRectFromSceneERK6QRectF()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem16mapRectFromSceneERK6QRectF(rsthis.qclsinst, arg0)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QPointF QQuickItem::position();
impl /*struct*/ QQuickItem {
pub fn position<RetType, T: QQuickItem_position<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.position(self);
// return 1;
}
}
pub trait QQuickItem_position<RetType> {
fn position(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QPointF QQuickItem::position();
impl<'a> /*trait*/ QQuickItem_position<QPointF> for () {
fn position(self , rsthis: & QQuickItem) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem8positionEv()};
let mut ret = unsafe {_ZNK10QQuickItem8positionEv(rsthis.qclsinst)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QQuickItem::height();
impl /*struct*/ QQuickItem {
pub fn height<RetType, T: QQuickItem_height<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.height(self);
// return 1;
}
}
pub trait QQuickItem_height<RetType> {
fn height(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::height();
impl<'a> /*trait*/ QQuickItem_height<f64> for () {
fn height(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem6heightEv()};
let mut ret = unsafe {_ZNK10QQuickItem6heightEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: QQuickItem * QQuickItem::childAt(qreal x, qreal y);
impl /*struct*/ QQuickItem {
pub fn childAt<RetType, T: QQuickItem_childAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.childAt(self);
// return 1;
}
}
pub trait QQuickItem_childAt<RetType> {
fn childAt(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QQuickItem * QQuickItem::childAt(qreal x, qreal y);
impl<'a> /*trait*/ QQuickItem_childAt<QQuickItem> for (f64, f64) {
fn childAt(self , rsthis: & QQuickItem) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem7childAtEdd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let mut ret = unsafe {_ZNK10QQuickItem7childAtEdd(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QQuickItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QCursor QQuickItem::cursor();
impl /*struct*/ QQuickItem {
pub fn cursor<RetType, T: QQuickItem_cursor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.cursor(self);
// return 1;
}
}
pub trait QQuickItem_cursor<RetType> {
fn cursor(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QCursor QQuickItem::cursor();
impl<'a> /*trait*/ QQuickItem_cursor<QCursor> for () {
fn cursor(self , rsthis: & QQuickItem) -> QCursor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem6cursorEv()};
let mut ret = unsafe {_ZNK10QQuickItem6cursorEv(rsthis.qclsinst)};
let mut ret1 = QCursor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickItem::clip();
impl /*struct*/ QQuickItem {
pub fn clip<RetType, T: QQuickItem_clip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clip(self);
// return 1;
}
}
pub trait QQuickItem_clip<RetType> {
fn clip(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::clip();
impl<'a> /*trait*/ QQuickItem_clip<i8> for () {
fn clip(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem4clipEv()};
let mut ret = unsafe {_ZNK10QQuickItem4clipEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: bool QQuickItem::antialiasing();
impl /*struct*/ QQuickItem {
pub fn antialiasing<RetType, T: QQuickItem_antialiasing<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.antialiasing(self);
// return 1;
}
}
pub trait QQuickItem_antialiasing<RetType> {
fn antialiasing(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::antialiasing();
impl<'a> /*trait*/ QQuickItem_antialiasing<i8> for () {
fn antialiasing(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem12antialiasingEv()};
let mut ret = unsafe {_ZNK10QQuickItem12antialiasingEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: QQuickWindow * QQuickItem::window();
impl /*struct*/ QQuickItem {
pub fn window<RetType, T: QQuickItem_window<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.window(self);
// return 1;
}
}
pub trait QQuickItem_window<RetType> {
fn window(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QQuickWindow * QQuickItem::window();
impl<'a> /*trait*/ QQuickItem_window<QQuickWindow> for () {
fn window(self , rsthis: & QQuickItem) -> QQuickWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem6windowEv()};
let mut ret = unsafe {_ZNK10QQuickItem6windowEv(rsthis.qclsinst)};
let mut ret1 = QQuickWindow::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QRectF QQuickItem::mapRectFromItem(const QQuickItem * item, const QRectF & rect);
impl /*struct*/ QQuickItem {
pub fn mapRectFromItem<RetType, T: QQuickItem_mapRectFromItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapRectFromItem(self);
// return 1;
}
}
pub trait QQuickItem_mapRectFromItem<RetType> {
fn mapRectFromItem(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QRectF QQuickItem::mapRectFromItem(const QQuickItem * item, const QRectF & rect);
impl<'a> /*trait*/ QQuickItem_mapRectFromItem<QRectF> for (&'a QQuickItem, &'a QRectF) {
fn mapRectFromItem(self , rsthis: & QQuickItem) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem15mapRectFromItemEPKS_RK6QRectF()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem15mapRectFromItemEPKS_RK6QRectF(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::setVisible(bool );
impl /*struct*/ QQuickItem {
pub fn setVisible<RetType, T: QQuickItem_setVisible<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setVisible(self);
// return 1;
}
}
pub trait QQuickItem_setVisible<RetType> {
fn setVisible(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setVisible(bool );
impl<'a> /*trait*/ QQuickItem_setVisible<()> for (i8) {
fn setVisible(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem10setVisibleEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem10setVisibleEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setFocus(bool );
impl /*struct*/ QQuickItem {
pub fn setFocus<RetType, T: QQuickItem_setFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setFocus(self);
// return 1;
}
}
pub trait QQuickItem_setFocus<RetType> {
fn setFocus(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setFocus(bool );
impl<'a> /*trait*/ QQuickItem_setFocus<()> for (i8) {
fn setFocus(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem8setFocusEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem8setFocusEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QQuickItem::activeFocusOnTab();
impl /*struct*/ QQuickItem {
pub fn activeFocusOnTab<RetType, T: QQuickItem_activeFocusOnTab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.activeFocusOnTab(self);
// return 1;
}
}
pub trait QQuickItem_activeFocusOnTab<RetType> {
fn activeFocusOnTab(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::activeFocusOnTab();
impl<'a> /*trait*/ QQuickItem_activeFocusOnTab<i8> for () {
fn activeFocusOnTab(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem16activeFocusOnTabEv()};
let mut ret = unsafe {_ZNK10QQuickItem16activeFocusOnTabEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: qreal QQuickItem::z();
impl /*struct*/ QQuickItem {
pub fn z<RetType, T: QQuickItem_z<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.z(self);
// return 1;
}
}
pub trait QQuickItem_z<RetType> {
fn z(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::z();
impl<'a> /*trait*/ QQuickItem_z<f64> for () {
fn z(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem1zEv()};
let mut ret = unsafe {_ZNK10QQuickItem1zEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
// proto: void QQuickItem::setOpacity(qreal );
impl /*struct*/ QQuickItem {
pub fn setOpacity<RetType, T: QQuickItem_setOpacity<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setOpacity(self);
// return 1;
}
}
pub trait QQuickItem_setOpacity<RetType> {
fn setOpacity(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setOpacity(qreal );
impl<'a> /*trait*/ QQuickItem_setOpacity<()> for (f64) {
fn setOpacity(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem10setOpacityEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem10setOpacityEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::setAntialiasing(bool );
impl /*struct*/ QQuickItem {
pub fn setAntialiasing<RetType, T: QQuickItem_setAntialiasing<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAntialiasing(self);
// return 1;
}
}
pub trait QQuickItem_setAntialiasing<RetType> {
fn setAntialiasing(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setAntialiasing(bool );
impl<'a> /*trait*/ QQuickItem_setAntialiasing<()> for (i8) {
fn setAntialiasing(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem15setAntialiasingEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem15setAntialiasingEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QList<QQuickItem *> QQuickItem::childItems();
impl /*struct*/ QQuickItem {
pub fn childItems<RetType, T: QQuickItem_childItems<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.childItems(self);
// return 1;
}
}
pub trait QQuickItem_childItems<RetType> {
fn childItems(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QList<QQuickItem *> QQuickItem::childItems();
impl<'a> /*trait*/ QQuickItem_childItems<()> for () {
fn childItems(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem10childItemsEv()};
unsafe {_ZNK10QQuickItem10childItemsEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::setSize(const QSizeF & size);
impl /*struct*/ QQuickItem {
pub fn setSize<RetType, T: QQuickItem_setSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSize(self);
// return 1;
}
}
pub trait QQuickItem_setSize<RetType> {
fn setSize(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setSize(const QSizeF & size);
impl<'a> /*trait*/ QQuickItem_setSize<()> for (&'a QSizeF) {
fn setSize(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem7setSizeERK6QSizeF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem7setSizeERK6QSizeF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::~QQuickItem();
impl /*struct*/ QQuickItem {
pub fn free<RetType, T: QQuickItem_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QQuickItem_free<RetType> {
fn free(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::~QQuickItem();
impl<'a> /*trait*/ QQuickItem_free<()> for () {
fn free(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItemD2Ev()};
unsafe {_ZN10QQuickItemD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QQuickItem * QQuickItem::scopedFocusItem();
impl /*struct*/ QQuickItem {
pub fn scopedFocusItem<RetType, T: QQuickItem_scopedFocusItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.scopedFocusItem(self);
// return 1;
}
}
pub trait QQuickItem_scopedFocusItem<RetType> {
fn scopedFocusItem(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QQuickItem * QQuickItem::scopedFocusItem();
impl<'a> /*trait*/ QQuickItem_scopedFocusItem<QQuickItem> for () {
fn scopedFocusItem(self , rsthis: & QQuickItem) -> QQuickItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem15scopedFocusItemEv()};
let mut ret = unsafe {_ZNK10QQuickItem15scopedFocusItemEv(rsthis.qclsinst)};
let mut ret1 = QQuickItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuickItem::grabToImage(const QJSValue & callback, const QSize & targetSize);
impl /*struct*/ QQuickItem {
pub fn grabToImage<RetType, T: QQuickItem_grabToImage<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.grabToImage(self);
// return 1;
}
}
pub trait QQuickItem_grabToImage<RetType> {
fn grabToImage(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::grabToImage(const QJSValue & callback, const QSize & targetSize);
impl<'a> /*trait*/ QQuickItem_grabToImage<i8> for (&'a QJSValue, &'a QSize) {
fn grabToImage(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11grabToImageERK8QJSValueRK5QSize()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN10QQuickItem11grabToImageERK8QJSValueRK5QSize(rsthis.qclsinst, arg0, arg1)};
return ret as i8;
// return 1;
}
}
// proto: QTransform QQuickItem::itemTransform(QQuickItem * , bool * );
impl /*struct*/ QQuickItem {
pub fn itemTransform<RetType, T: QQuickItem_itemTransform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.itemTransform(self);
// return 1;
}
}
pub trait QQuickItem_itemTransform<RetType> {
fn itemTransform(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QTransform QQuickItem::itemTransform(QQuickItem * , bool * );
impl<'a> /*trait*/ QQuickItem_itemTransform<QTransform> for (&'a QQuickItem, &'a mut Vec<i8>) {
fn itemTransform(self , rsthis: & QQuickItem) -> QTransform {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem13itemTransformEPS_Pb()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.as_ptr() as *mut c_char;
let mut ret = unsafe {_ZNK10QQuickItem13itemTransformEPS_Pb(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QTransform::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::update();
impl /*struct*/ QQuickItem {
pub fn update<RetType, T: QQuickItem_update<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.update(self);
// return 1;
}
}
pub trait QQuickItem_update<RetType> {
fn update(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::update();
impl<'a> /*trait*/ QQuickItem_update<()> for () {
fn update(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem6updateEv()};
unsafe {_ZN10QQuickItem6updateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::setCursor(const QCursor & cursor);
impl /*struct*/ QQuickItem {
pub fn setCursor<RetType, T: QQuickItem_setCursor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCursor(self);
// return 1;
}
}
pub trait QQuickItem_setCursor<RetType> {
fn setCursor(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setCursor(const QCursor & cursor);
impl<'a> /*trait*/ QQuickItem_setCursor<()> for (&'a QCursor) {
fn setCursor(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem9setCursorERK7QCursor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem9setCursorERK7QCursor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSharedPointer<QQuickItemGrabResult> QQuickItem::grabToImage(const QSize & targetSize);
impl<'a> /*trait*/ QQuickItem_grabToImage<()> for (&'a QSize) {
fn grabToImage(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11grabToImageERK5QSize()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem11grabToImageERK5QSize(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QRectF QQuickItem::clipRect();
impl /*struct*/ QQuickItem {
pub fn clipRect<RetType, T: QQuickItem_clipRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clipRect(self);
// return 1;
}
}
pub trait QQuickItem_clipRect<RetType> {
fn clipRect(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QRectF QQuickItem::clipRect();
impl<'a> /*trait*/ QQuickItem_clipRect<QRectF> for () {
fn clipRect(self , rsthis: & QQuickItem) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem8clipRectEv()};
let mut ret = unsafe {_ZNK10QQuickItem8clipRectEv(rsthis.qclsinst)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::ungrabMouse();
impl /*struct*/ QQuickItem {
pub fn ungrabMouse<RetType, T: QQuickItem_ungrabMouse<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.ungrabMouse(self);
// return 1;
}
}
pub trait QQuickItem_ungrabMouse<RetType> {
fn ungrabMouse(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::ungrabMouse();
impl<'a> /*trait*/ QQuickItem_ungrabMouse<()> for () {
fn ungrabMouse(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11ungrabMouseEv()};
unsafe {_ZN10QQuickItem11ungrabMouseEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QRectF QQuickItem::mapRectToScene(const QRectF & rect);
impl /*struct*/ QQuickItem {
pub fn mapRectToScene<RetType, T: QQuickItem_mapRectToScene<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mapRectToScene(self);
// return 1;
}
}
pub trait QQuickItem_mapRectToScene<RetType> {
fn mapRectToScene(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QRectF QQuickItem::mapRectToScene(const QRectF & rect);
impl<'a> /*trait*/ QQuickItem_mapRectToScene<QRectF> for (&'a QRectF) {
fn mapRectToScene(self , rsthis: & QQuickItem) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem14mapRectToSceneERK6QRectF()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK10QQuickItem14mapRectToSceneERK6QRectF(rsthis.qclsinst, arg0)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::setRotation(qreal );
impl /*struct*/ QQuickItem {
pub fn setRotation<RetType, T: QQuickItem_setRotation<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRotation(self);
// return 1;
}
}
pub trait QQuickItem_setRotation<RetType> {
fn setRotation(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setRotation(qreal );
impl<'a> /*trait*/ QQuickItem_setRotation<()> for (f64) {
fn setRotation(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11setRotationEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem11setRotationEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QQuickItem::hasFocus();
impl /*struct*/ QQuickItem {
pub fn hasFocus<RetType, T: QQuickItem_hasFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasFocus(self);
// return 1;
}
}
pub trait QQuickItem_hasFocus<RetType> {
fn hasFocus(self , rsthis: & QQuickItem) -> RetType;
}
// proto: bool QQuickItem::hasFocus();
impl<'a> /*trait*/ QQuickItem_hasFocus<i8> for () {
fn hasFocus(self , rsthis: & QQuickItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem8hasFocusEv()};
let mut ret = unsafe {_ZNK10QQuickItem8hasFocusEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QQuickItem::setX(qreal );
impl /*struct*/ QQuickItem {
pub fn setX<RetType, T: QQuickItem_setX<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setX(self);
// return 1;
}
}
pub trait QQuickItem_setX<RetType> {
fn setX(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setX(qreal );
impl<'a> /*trait*/ QQuickItem_setX<()> for (f64) {
fn setX(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem4setXEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem4setXEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QString QQuickItem::state();
impl /*struct*/ QQuickItem {
pub fn state<RetType, T: QQuickItem_state<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.state(self);
// return 1;
}
}
pub trait QQuickItem_state<RetType> {
fn state(self , rsthis: & QQuickItem) -> RetType;
}
// proto: QString QQuickItem::state();
impl<'a> /*trait*/ QQuickItem_state<QString> for () {
fn state(self , rsthis: & QQuickItem) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem5stateEv()};
let mut ret = unsafe {_ZNK10QQuickItem5stateEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickItem::setScale(qreal );
impl /*struct*/ QQuickItem {
pub fn setScale<RetType, T: QQuickItem_setScale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setScale(self);
// return 1;
}
}
pub trait QQuickItem_setScale<RetType> {
fn setScale(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setScale(qreal );
impl<'a> /*trait*/ QQuickItem_setScale<()> for (f64) {
fn setScale(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem8setScaleEd()};
let arg0 = self as c_double;
unsafe {_ZN10QQuickItem8setScaleEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::resetHeight();
impl /*struct*/ QQuickItem {
pub fn resetHeight<RetType, T: QQuickItem_resetHeight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resetHeight(self);
// return 1;
}
}
pub trait QQuickItem_resetHeight<RetType> {
fn resetHeight(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::resetHeight();
impl<'a> /*trait*/ QQuickItem_resetHeight<()> for () {
fn resetHeight(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem11resetHeightEv()};
unsafe {_ZN10QQuickItem11resetHeightEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::grabMouse();
impl /*struct*/ QQuickItem {
pub fn grabMouse<RetType, T: QQuickItem_grabMouse<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.grabMouse(self);
// return 1;
}
}
pub trait QQuickItem_grabMouse<RetType> {
fn grabMouse(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::grabMouse();
impl<'a> /*trait*/ QQuickItem_grabMouse<()> for () {
fn grabMouse(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem9grabMouseEv()};
unsafe {_ZN10QQuickItem9grabMouseEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QQuickItem::setKeepTouchGrab(bool );
impl /*struct*/ QQuickItem {
pub fn setKeepTouchGrab<RetType, T: QQuickItem_setKeepTouchGrab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setKeepTouchGrab(self);
// return 1;
}
}
pub trait QQuickItem_setKeepTouchGrab<RetType> {
fn setKeepTouchGrab(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::setKeepTouchGrab(bool );
impl<'a> /*trait*/ QQuickItem_setKeepTouchGrab<()> for (i8) {
fn setKeepTouchGrab(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem16setKeepTouchGrabEb()};
let arg0 = self as c_char;
unsafe {_ZN10QQuickItem16setKeepTouchGrabEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuickItem::stackAfter(const QQuickItem * );
impl /*struct*/ QQuickItem {
pub fn stackAfter<RetType, T: QQuickItem_stackAfter<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.stackAfter(self);
// return 1;
}
}
pub trait QQuickItem_stackAfter<RetType> {
fn stackAfter(self , rsthis: & QQuickItem) -> RetType;
}
// proto: void QQuickItem::stackAfter(const QQuickItem * );
impl<'a> /*trait*/ QQuickItem_stackAfter<()> for (&'a QQuickItem) {
fn stackAfter(self , rsthis: & QQuickItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QQuickItem10stackAfterEPKS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QQuickItem10stackAfterEPKS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QQuickItem::baselineOffset();
impl /*struct*/ QQuickItem {
pub fn baselineOffset<RetType, T: QQuickItem_baselineOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.baselineOffset(self);
// return 1;
}
}
pub trait QQuickItem_baselineOffset<RetType> {
fn baselineOffset(self , rsthis: & QQuickItem) -> RetType;
}
// proto: qreal QQuickItem::baselineOffset();
impl<'a> /*trait*/ QQuickItem_baselineOffset<f64> for () {
fn baselineOffset(self , rsthis: & QQuickItem) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QQuickItem14baselineOffsetEv()};
let mut ret = unsafe {_ZNK10QQuickItem14baselineOffsetEv(rsthis.qclsinst)};
return ret as f64;
// return 1;
}
}
#[derive(Default)] // for QQuickItem_childrenChanged
pub struct QQuickItem_childrenChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn childrenChanged(&self) -> QQuickItem_childrenChanged_signal {
return QQuickItem_childrenChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_childrenChanged_signal {
pub fn connect<T: QQuickItem_childrenChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_childrenChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_childrenChanged_signal);
}
#[derive(Default)] // for QQuickItem_parentChanged
pub struct QQuickItem_parentChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn parentChanged(&self) -> QQuickItem_parentChanged_signal {
return QQuickItem_parentChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_parentChanged_signal {
pub fn connect<T: QQuickItem_parentChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_parentChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_parentChanged_signal);
}
#[derive(Default)] // for QQuickItem_stateChanged
pub struct QQuickItem_stateChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn stateChanged(&self) -> QQuickItem_stateChanged_signal {
return QQuickItem_stateChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_stateChanged_signal {
pub fn connect<T: QQuickItem_stateChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_stateChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_stateChanged_signal);
}
#[derive(Default)] // for QQuickItem_visibleChildrenChanged
pub struct QQuickItem_visibleChildrenChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn visibleChildrenChanged(&self) -> QQuickItem_visibleChildrenChanged_signal {
return QQuickItem_visibleChildrenChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_visibleChildrenChanged_signal {
pub fn connect<T: QQuickItem_visibleChildrenChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_visibleChildrenChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_visibleChildrenChanged_signal);
}
#[derive(Default)] // for QQuickItem_transformOriginChanged
pub struct QQuickItem_transformOriginChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn transformOriginChanged(&self) -> QQuickItem_transformOriginChanged_signal {
return QQuickItem_transformOriginChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_transformOriginChanged_signal {
pub fn connect<T: QQuickItem_transformOriginChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_transformOriginChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_transformOriginChanged_signal);
}
#[derive(Default)] // for QQuickItem_rotationChanged
pub struct QQuickItem_rotationChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn rotationChanged(&self) -> QQuickItem_rotationChanged_signal {
return QQuickItem_rotationChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_rotationChanged_signal {
pub fn connect<T: QQuickItem_rotationChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_rotationChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_rotationChanged_signal);
}
#[derive(Default)] // for QQuickItem_antialiasingChanged
pub struct QQuickItem_antialiasingChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn antialiasingChanged(&self) -> QQuickItem_antialiasingChanged_signal {
return QQuickItem_antialiasingChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_antialiasingChanged_signal {
pub fn connect<T: QQuickItem_antialiasingChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_antialiasingChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_antialiasingChanged_signal);
}
#[derive(Default)] // for QQuickItem_scaleChanged
pub struct QQuickItem_scaleChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn scaleChanged(&self) -> QQuickItem_scaleChanged_signal {
return QQuickItem_scaleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_scaleChanged_signal {
pub fn connect<T: QQuickItem_scaleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_scaleChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_scaleChanged_signal);
}
#[derive(Default)] // for QQuickItem_heightChanged
pub struct QQuickItem_heightChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn heightChanged(&self) -> QQuickItem_heightChanged_signal {
return QQuickItem_heightChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_heightChanged_signal {
pub fn connect<T: QQuickItem_heightChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_heightChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_heightChanged_signal);
}
#[derive(Default)] // for QQuickItem_visibleChanged
pub struct QQuickItem_visibleChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn visibleChanged(&self) -> QQuickItem_visibleChanged_signal {
return QQuickItem_visibleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_visibleChanged_signal {
pub fn connect<T: QQuickItem_visibleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_visibleChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_visibleChanged_signal);
}
#[derive(Default)] // for QQuickItem_clipChanged
pub struct QQuickItem_clipChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn clipChanged(&self) -> QQuickItem_clipChanged_signal {
return QQuickItem_clipChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_clipChanged_signal {
pub fn connect<T: QQuickItem_clipChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_clipChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_clipChanged_signal);
}
#[derive(Default)] // for QQuickItem_smoothChanged
pub struct QQuickItem_smoothChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn smoothChanged(&self) -> QQuickItem_smoothChanged_signal {
return QQuickItem_smoothChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_smoothChanged_signal {
pub fn connect<T: QQuickItem_smoothChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_smoothChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_smoothChanged_signal);
}
#[derive(Default)] // for QQuickItem_widthChanged
pub struct QQuickItem_widthChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn widthChanged(&self) -> QQuickItem_widthChanged_signal {
return QQuickItem_widthChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_widthChanged_signal {
pub fn connect<T: QQuickItem_widthChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_widthChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_widthChanged_signal);
}
#[derive(Default)] // for QQuickItem_windowChanged
pub struct QQuickItem_windowChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn windowChanged(&self) -> QQuickItem_windowChanged_signal {
return QQuickItem_windowChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_windowChanged_signal {
pub fn connect<T: QQuickItem_windowChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_windowChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_windowChanged_signal);
}
#[derive(Default)] // for QQuickItem_opacityChanged
pub struct QQuickItem_opacityChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn opacityChanged(&self) -> QQuickItem_opacityChanged_signal {
return QQuickItem_opacityChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_opacityChanged_signal {
pub fn connect<T: QQuickItem_opacityChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_opacityChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_opacityChanged_signal);
}
#[derive(Default)] // for QQuickItem_enabledChanged
pub struct QQuickItem_enabledChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn enabledChanged(&self) -> QQuickItem_enabledChanged_signal {
return QQuickItem_enabledChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_enabledChanged_signal {
pub fn connect<T: QQuickItem_enabledChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_enabledChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_enabledChanged_signal);
}
#[derive(Default)] // for QQuickItem_xChanged
pub struct QQuickItem_xChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn xChanged(&self) -> QQuickItem_xChanged_signal {
return QQuickItem_xChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_xChanged_signal {
pub fn connect<T: QQuickItem_xChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_xChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_xChanged_signal);
}
#[derive(Default)] // for QQuickItem_activeFocusOnTabChanged
pub struct QQuickItem_activeFocusOnTabChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn activeFocusOnTabChanged(&self) -> QQuickItem_activeFocusOnTabChanged_signal {
return QQuickItem_activeFocusOnTabChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_activeFocusOnTabChanged_signal {
pub fn connect<T: QQuickItem_activeFocusOnTabChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_activeFocusOnTabChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_activeFocusOnTabChanged_signal);
}
#[derive(Default)] // for QQuickItem_implicitHeightChanged
pub struct QQuickItem_implicitHeightChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn implicitHeightChanged(&self) -> QQuickItem_implicitHeightChanged_signal {
return QQuickItem_implicitHeightChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_implicitHeightChanged_signal {
pub fn connect<T: QQuickItem_implicitHeightChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_implicitHeightChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_implicitHeightChanged_signal);
}
#[derive(Default)] // for QQuickItem_zChanged
pub struct QQuickItem_zChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn zChanged(&self) -> QQuickItem_zChanged_signal {
return QQuickItem_zChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_zChanged_signal {
pub fn connect<T: QQuickItem_zChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_zChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_zChanged_signal);
}
#[derive(Default)] // for QQuickItem_focusChanged
pub struct QQuickItem_focusChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn focusChanged(&self) -> QQuickItem_focusChanged_signal {
return QQuickItem_focusChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_focusChanged_signal {
pub fn connect<T: QQuickItem_focusChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_focusChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_focusChanged_signal);
}
#[derive(Default)] // for QQuickItem_activeFocusChanged
pub struct QQuickItem_activeFocusChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn activeFocusChanged(&self) -> QQuickItem_activeFocusChanged_signal {
return QQuickItem_activeFocusChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_activeFocusChanged_signal {
pub fn connect<T: QQuickItem_activeFocusChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_activeFocusChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_activeFocusChanged_signal);
}
#[derive(Default)] // for QQuickItem_yChanged
pub struct QQuickItem_yChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn yChanged(&self) -> QQuickItem_yChanged_signal {
return QQuickItem_yChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_yChanged_signal {
pub fn connect<T: QQuickItem_yChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_yChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_yChanged_signal);
}
#[derive(Default)] // for QQuickItem_implicitWidthChanged
pub struct QQuickItem_implicitWidthChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn implicitWidthChanged(&self) -> QQuickItem_implicitWidthChanged_signal {
return QQuickItem_implicitWidthChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_implicitWidthChanged_signal {
pub fn connect<T: QQuickItem_implicitWidthChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_implicitWidthChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_implicitWidthChanged_signal);
}
#[derive(Default)] // for QQuickItem_childrenRectChanged
pub struct QQuickItem_childrenRectChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn childrenRectChanged(&self) -> QQuickItem_childrenRectChanged_signal {
return QQuickItem_childrenRectChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_childrenRectChanged_signal {
pub fn connect<T: QQuickItem_childrenRectChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_childrenRectChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_childrenRectChanged_signal);
}
#[derive(Default)] // for QQuickItem_baselineOffsetChanged
pub struct QQuickItem_baselineOffsetChanged_signal{poi:u64}
impl /* struct */ QQuickItem {
pub fn baselineOffsetChanged(&self) -> QQuickItem_baselineOffsetChanged_signal {
return QQuickItem_baselineOffsetChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QQuickItem_baselineOffsetChanged_signal {
pub fn connect<T: QQuickItem_baselineOffsetChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QQuickItem_baselineOffsetChanged_signal_connect {
fn connect(self, sigthis: QQuickItem_baselineOffsetChanged_signal);
}
// opacityChanged()
extern fn QQuickItem_opacityChanged_signal_connect_cb_0(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_opacityChanged_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 */ QQuickItem_opacityChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_opacityChanged_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 = QQuickItem_opacityChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem14opacityChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_opacityChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_opacityChanged_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 = QQuickItem_opacityChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem14opacityChangedEv(arg0, arg1, arg2)};
}
}
// visibleChanged()
extern fn QQuickItem_visibleChanged_signal_connect_cb_1(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_visibleChanged_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 */ QQuickItem_visibleChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_visibleChanged_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 = QQuickItem_visibleChanged_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem14visibleChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_visibleChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_visibleChanged_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 = QQuickItem_visibleChanged_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem14visibleChangedEv(arg0, arg1, arg2)};
}
}
// heightChanged()
extern fn QQuickItem_heightChanged_signal_connect_cb_2(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_heightChanged_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 */ QQuickItem_heightChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_heightChanged_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 = QQuickItem_heightChanged_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13heightChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_heightChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_heightChanged_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 = QQuickItem_heightChanged_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13heightChangedEv(arg0, arg1, arg2)};
}
}
// childrenRectChanged(const class QRectF &)
extern fn QQuickItem_childrenRectChanged_signal_connect_cb_3(rsfptr:fn(QRectF), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QRectF::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QQuickItem_childrenRectChanged_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(QRectF)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QRectF::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_childrenRectChanged_signal_connect for fn(QRectF) {
fn connect(self, sigthis: QQuickItem_childrenRectChanged_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 = QQuickItem_childrenRectChanged_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem19childrenRectChangedERK6QRectF(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_childrenRectChanged_signal_connect for Box<Fn(QRectF)> {
fn connect(self, sigthis: QQuickItem_childrenRectChanged_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 = QQuickItem_childrenRectChanged_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem19childrenRectChangedERK6QRectF(arg0, arg1, arg2)};
}
}
// yChanged()
extern fn QQuickItem_yChanged_signal_connect_cb_4(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_yChanged_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 */ QQuickItem_yChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_yChanged_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 = QQuickItem_yChanged_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem8yChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_yChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_yChanged_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 = QQuickItem_yChanged_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem8yChangedEv(arg0, arg1, arg2)};
}
}
// antialiasingChanged(_Bool)
extern fn QQuickItem_antialiasingChanged_signal_connect_cb_5(rsfptr:fn(i8), arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i8;
rsfptr(rsarg0);
}
extern fn QQuickItem_antialiasingChanged_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i8;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_antialiasingChanged_signal_connect for fn(i8) {
fn connect(self, sigthis: QQuickItem_antialiasingChanged_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 = QQuickItem_antialiasingChanged_signal_connect_cb_5 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem19antialiasingChangedEb(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_antialiasingChanged_signal_connect for Box<Fn(i8)> {
fn connect(self, sigthis: QQuickItem_antialiasingChanged_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 = QQuickItem_antialiasingChanged_signal_connect_cb_box_5 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem19antialiasingChangedEb(arg0, arg1, arg2)};
}
}
// visibleChildrenChanged()
extern fn QQuickItem_visibleChildrenChanged_signal_connect_cb_6(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_visibleChildrenChanged_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 */ QQuickItem_visibleChildrenChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_visibleChildrenChanged_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 = QQuickItem_visibleChildrenChanged_signal_connect_cb_6 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem22visibleChildrenChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_visibleChildrenChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_visibleChildrenChanged_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 = QQuickItem_visibleChildrenChanged_signal_connect_cb_box_6 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem22visibleChildrenChangedEv(arg0, arg1, arg2)};
}
}
// widthChanged()
extern fn QQuickItem_widthChanged_signal_connect_cb_7(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_widthChanged_signal_connect_cb_box_7(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickItem_widthChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_widthChanged_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 = QQuickItem_widthChanged_signal_connect_cb_7 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12widthChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_widthChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_widthChanged_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 = QQuickItem_widthChanged_signal_connect_cb_box_7 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12widthChangedEv(arg0, arg1, arg2)};
}
}
// rotationChanged()
extern fn QQuickItem_rotationChanged_signal_connect_cb_8(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_rotationChanged_signal_connect_cb_box_8(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickItem_rotationChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_rotationChanged_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 = QQuickItem_rotationChanged_signal_connect_cb_8 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem15rotationChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_rotationChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_rotationChanged_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 = QQuickItem_rotationChanged_signal_connect_cb_box_8 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem15rotationChangedEv(arg0, arg1, arg2)};
}
}
// smoothChanged(_Bool)
extern fn QQuickItem_smoothChanged_signal_connect_cb_9(rsfptr:fn(i8), arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i8;
rsfptr(rsarg0);
}
extern fn QQuickItem_smoothChanged_signal_connect_cb_box_9(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i8;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_smoothChanged_signal_connect for fn(i8) {
fn connect(self, sigthis: QQuickItem_smoothChanged_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 = QQuickItem_smoothChanged_signal_connect_cb_9 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13smoothChangedEb(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_smoothChanged_signal_connect for Box<Fn(i8)> {
fn connect(self, sigthis: QQuickItem_smoothChanged_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 = QQuickItem_smoothChanged_signal_connect_cb_box_9 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13smoothChangedEb(arg0, arg1, arg2)};
}
}
// childrenChanged()
extern fn QQuickItem_childrenChanged_signal_connect_cb_10(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_childrenChanged_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 */ QQuickItem_childrenChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_childrenChanged_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 = QQuickItem_childrenChanged_signal_connect_cb_10 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem15childrenChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_childrenChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_childrenChanged_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 = QQuickItem_childrenChanged_signal_connect_cb_box_10 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem15childrenChangedEv(arg0, arg1, arg2)};
}
}
// enabledChanged()
extern fn QQuickItem_enabledChanged_signal_connect_cb_11(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_enabledChanged_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 */ QQuickItem_enabledChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_enabledChanged_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 = QQuickItem_enabledChanged_signal_connect_cb_11 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem14enabledChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_enabledChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_enabledChanged_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 = QQuickItem_enabledChanged_signal_connect_cb_box_11 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem14enabledChangedEv(arg0, arg1, arg2)};
}
}
// implicitHeightChanged()
extern fn QQuickItem_implicitHeightChanged_signal_connect_cb_12(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_implicitHeightChanged_signal_connect_cb_box_12(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickItem_implicitHeightChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_implicitHeightChanged_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 = QQuickItem_implicitHeightChanged_signal_connect_cb_12 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem21implicitHeightChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_implicitHeightChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_implicitHeightChanged_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 = QQuickItem_implicitHeightChanged_signal_connect_cb_box_12 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem21implicitHeightChangedEv(arg0, arg1, arg2)};
}
}
// parentChanged(class QQuickItem *)
extern fn QQuickItem_parentChanged_signal_connect_cb_13(rsfptr:fn(QQuickItem), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QQuickItem::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QQuickItem_parentChanged_signal_connect_cb_box_13(rsfptr_raw:*mut Box<Fn(QQuickItem)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QQuickItem::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_parentChanged_signal_connect for fn(QQuickItem) {
fn connect(self, sigthis: QQuickItem_parentChanged_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 = QQuickItem_parentChanged_signal_connect_cb_13 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13parentChangedEPS_(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_parentChanged_signal_connect for Box<Fn(QQuickItem)> {
fn connect(self, sigthis: QQuickItem_parentChanged_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 = QQuickItem_parentChanged_signal_connect_cb_box_13 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13parentChangedEPS_(arg0, arg1, arg2)};
}
}
// xChanged()
extern fn QQuickItem_xChanged_signal_connect_cb_14(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_xChanged_signal_connect_cb_box_14(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickItem_xChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_xChanged_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 = QQuickItem_xChanged_signal_connect_cb_14 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem8xChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_xChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_xChanged_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 = QQuickItem_xChanged_signal_connect_cb_box_14 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem8xChangedEv(arg0, arg1, arg2)};
}
}
// windowChanged(class QQuickWindow *)
extern fn QQuickItem_windowChanged_signal_connect_cb_15(rsfptr:fn(QQuickWindow), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QQuickWindow::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QQuickItem_windowChanged_signal_connect_cb_box_15(rsfptr_raw:*mut Box<Fn(QQuickWindow)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QQuickWindow::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_windowChanged_signal_connect for fn(QQuickWindow) {
fn connect(self, sigthis: QQuickItem_windowChanged_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 = QQuickItem_windowChanged_signal_connect_cb_15 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13windowChangedEP12QQuickWindow(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_windowChanged_signal_connect for Box<Fn(QQuickWindow)> {
fn connect(self, sigthis: QQuickItem_windowChanged_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 = QQuickItem_windowChanged_signal_connect_cb_box_15 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem13windowChangedEP12QQuickWindow(arg0, arg1, arg2)};
}
}
// clipChanged(_Bool)
extern fn QQuickItem_clipChanged_signal_connect_cb_16(rsfptr:fn(i8), arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i8;
rsfptr(rsarg0);
}
extern fn QQuickItem_clipChanged_signal_connect_cb_box_16(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i8;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_clipChanged_signal_connect for fn(i8) {
fn connect(self, sigthis: QQuickItem_clipChanged_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 = QQuickItem_clipChanged_signal_connect_cb_16 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem11clipChangedEb(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_clipChanged_signal_connect for Box<Fn(i8)> {
fn connect(self, sigthis: QQuickItem_clipChanged_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 = QQuickItem_clipChanged_signal_connect_cb_box_16 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem11clipChangedEb(arg0, arg1, arg2)};
}
}
// scaleChanged()
extern fn QQuickItem_scaleChanged_signal_connect_cb_17(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_scaleChanged_signal_connect_cb_box_17(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickItem_scaleChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_scaleChanged_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 = QQuickItem_scaleChanged_signal_connect_cb_17 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12scaleChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_scaleChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_scaleChanged_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 = QQuickItem_scaleChanged_signal_connect_cb_box_17 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12scaleChangedEv(arg0, arg1, arg2)};
}
}
// focusChanged(_Bool)
extern fn QQuickItem_focusChanged_signal_connect_cb_18(rsfptr:fn(i8), arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i8;
rsfptr(rsarg0);
}
extern fn QQuickItem_focusChanged_signal_connect_cb_box_18(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i8;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_focusChanged_signal_connect for fn(i8) {
fn connect(self, sigthis: QQuickItem_focusChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QQuickItem_focusChanged_signal_connect_cb_18 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12focusChangedEb(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_focusChanged_signal_connect for Box<Fn(i8)> {
fn connect(self, sigthis: QQuickItem_focusChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QQuickItem_focusChanged_signal_connect_cb_box_18 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12focusChangedEb(arg0, arg1, arg2)};
}
}
// stateChanged(const class QString &)
extern fn QQuickItem_stateChanged_signal_connect_cb_19(rsfptr:fn(QString), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QString::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QQuickItem_stateChanged_signal_connect_cb_box_19(rsfptr_raw:*mut Box<Fn(QString)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QString::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_stateChanged_signal_connect for fn(QString) {
fn connect(self, sigthis: QQuickItem_stateChanged_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 = QQuickItem_stateChanged_signal_connect_cb_19 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12stateChangedERK7QString(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_stateChanged_signal_connect for Box<Fn(QString)> {
fn connect(self, sigthis: QQuickItem_stateChanged_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 = QQuickItem_stateChanged_signal_connect_cb_box_19 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem12stateChangedERK7QString(arg0, arg1, arg2)};
}
}
// implicitWidthChanged()
extern fn QQuickItem_implicitWidthChanged_signal_connect_cb_20(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_implicitWidthChanged_signal_connect_cb_box_20(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickItem_implicitWidthChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_implicitWidthChanged_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 = QQuickItem_implicitWidthChanged_signal_connect_cb_20 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem20implicitWidthChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_implicitWidthChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_implicitWidthChanged_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 = QQuickItem_implicitWidthChanged_signal_connect_cb_box_20 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem20implicitWidthChangedEv(arg0, arg1, arg2)};
}
}
// activeFocusChanged(_Bool)
extern fn QQuickItem_activeFocusChanged_signal_connect_cb_21(rsfptr:fn(i8), arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i8;
rsfptr(rsarg0);
}
extern fn QQuickItem_activeFocusChanged_signal_connect_cb_box_21(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i8;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_activeFocusChanged_signal_connect for fn(i8) {
fn connect(self, sigthis: QQuickItem_activeFocusChanged_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 = QQuickItem_activeFocusChanged_signal_connect_cb_21 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem18activeFocusChangedEb(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_activeFocusChanged_signal_connect for Box<Fn(i8)> {
fn connect(self, sigthis: QQuickItem_activeFocusChanged_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 = QQuickItem_activeFocusChanged_signal_connect_cb_box_21 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem18activeFocusChangedEb(arg0, arg1, arg2)};
}
}
// baselineOffsetChanged(qreal)
extern fn QQuickItem_baselineOffsetChanged_signal_connect_cb_22(rsfptr:fn(f64), arg0: c_double) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as f64;
rsfptr(rsarg0);
}
extern fn QQuickItem_baselineOffsetChanged_signal_connect_cb_box_22(rsfptr_raw:*mut Box<Fn(f64)>, arg0: c_double) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as f64;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_baselineOffsetChanged_signal_connect for fn(f64) {
fn connect(self, sigthis: QQuickItem_baselineOffsetChanged_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 = QQuickItem_baselineOffsetChanged_signal_connect_cb_22 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem21baselineOffsetChangedEd(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_baselineOffsetChanged_signal_connect for Box<Fn(f64)> {
fn connect(self, sigthis: QQuickItem_baselineOffsetChanged_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 = QQuickItem_baselineOffsetChanged_signal_connect_cb_box_22 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem21baselineOffsetChangedEd(arg0, arg1, arg2)};
}
}
// activeFocusOnTabChanged(_Bool)
extern fn QQuickItem_activeFocusOnTabChanged_signal_connect_cb_23(rsfptr:fn(i8), arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i8;
rsfptr(rsarg0);
}
extern fn QQuickItem_activeFocusOnTabChanged_signal_connect_cb_box_23(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i8;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QQuickItem_activeFocusOnTabChanged_signal_connect for fn(i8) {
fn connect(self, sigthis: QQuickItem_activeFocusOnTabChanged_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 = QQuickItem_activeFocusOnTabChanged_signal_connect_cb_23 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem23activeFocusOnTabChangedEb(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_activeFocusOnTabChanged_signal_connect for Box<Fn(i8)> {
fn connect(self, sigthis: QQuickItem_activeFocusOnTabChanged_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 = QQuickItem_activeFocusOnTabChanged_signal_connect_cb_box_23 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem23activeFocusOnTabChangedEb(arg0, arg1, arg2)};
}
}
// zChanged()
extern fn QQuickItem_zChanged_signal_connect_cb_24(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QQuickItem_zChanged_signal_connect_cb_box_24(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QQuickItem_zChanged_signal_connect for fn() {
fn connect(self, sigthis: QQuickItem_zChanged_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 = QQuickItem_zChanged_signal_connect_cb_24 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem8zChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QQuickItem_zChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QQuickItem_zChanged_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 = QQuickItem_zChanged_signal_connect_cb_box_24 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QQuickItem_SlotProxy_connect__ZN10QQuickItem8zChangedEv(arg0, arg1, arg2)};
}
}
// <= body block end
|
// entity.rs
//
// Copyright (c) 2019, Univerisity of Minnesota
//
// Author: Bridger Herman (herma582@umn.edu)
//! Entity (GameObject)
use wasm_bindgen::prelude::*;
use crate::material::Material;
use crate::transform::Transform;
pub type EntityId = usize;
#[wasm_bindgen]
#[derive(Debug, Clone, Copy)]
pub struct Entity {
pub id: EntityId,
transform: Transform,
material: Material,
}
#[wasm_bindgen]
impl Entity {
#[wasm_bindgen(constructor)]
pub fn new(id: EntityId) -> Self {
Self {
id,
transform: Transform::identity(),
material: Material::default(),
}
}
#[wasm_bindgen(getter)]
pub fn transform(&self) -> Transform {
self.transform
}
#[wasm_bindgen(setter)]
pub fn set_transform(&mut self, tf: &Transform) {
self.transform = *tf;
}
#[wasm_bindgen(getter)]
pub fn material(&self) -> Material {
self.material
}
#[wasm_bindgen(setter)]
pub fn set_material(&mut self, mat: &Material) {
self.material = *mat;
}
}
|
use core::{RayIntersection, RayCaster, LightIntersection, LightSource, Illuminator};
pub type LightSourceVec = Vec<Box<LightSource>>;
pub struct SimpleIlluminator {
lights : LightSourceVec
}
impl SimpleIlluminator {
pub fn new(lights: LightSourceVec) -> Self {
Self { lights: lights}
}
}
impl Illuminator for SimpleIlluminator {
fn get_illumination_at(&self, intersection: &RayIntersection, illumination_caster: &RayCaster) -> Vec<LightIntersection> {
self.lights.iter().filter_map(|light| {
match light.get_ray_to_intersection(intersection) {
None => None,
Some(ray) => {
match illumination_caster.cast_colored_light_ray(&ray, intersection) {
None => None,
Some(illumintaion_shadowing) => {
match light.get_illumination_at(intersection) {
None => None,
Some(illumination) => {
Some(illumination.get_shadowed(&illumintaion_shadowing))
}
}
}
}
}
}
}).collect()
}
} |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_exception::Result;
use common_expression::DataBlock;
// The trait will connect runtime filter source of join build side
// with join probe side
#[async_trait::async_trait]
pub trait RuntimeFilterConnector: Send + Sync {
fn attach(&self);
fn detach(&self) -> Result<()>;
fn is_finished(&self) -> Result<bool>;
async fn wait_finish(&self) -> Result<()>;
// Consume runtime filter for blocks from join probe side
fn consume(&self, data: &DataBlock) -> Result<Vec<DataBlock>>;
// Collect runtime filter from join build side
fn collect(&self, data: &DataBlock) -> Result<()>;
}
|
use futures::future::ready;
use futures_signals::signal::SignalExt;
use log::*;
use wasm_bindgen_futures::spawn_local;
use web_sys::MouseEvent;
use yew::prelude::*;
use super::store::{
ActionType::{ClearIp, GetIp},
ArcState, Store, StoreInput, StoreOutput,
};
use super::subscriber::Subscriber;
pub struct App {
ip: Option<String>,
link: ComponentLink<App>,
store: Box<dyn Bridge<Store>>,
state_ref: Option<ArcState>,
total_subs: i32,
}
pub enum Msg {
FromStore(StoreOutput),
GetIp,
ClearIp,
SetIp(Option<String>),
IncSubs,
DecSubs,
}
// Yew implementation
impl Component for App {
type Properties = ();
type Message = Msg;
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
let store = Store::bridge(link.callback(|d| Msg::FromStore(d)));
Self {
ip: None,
link,
store,
state_ref: None,
total_subs: 2,
}
}
fn mounted(&mut self) -> ShouldRender {
self.register_state_handlers();
true
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
self.handle_updates(msg)
}
fn view(&self) -> Html {
let message = String::from("No ip, please click the button");
let ip = if self.ip.is_some() {
self.ip.as_ref().unwrap()
} else {
&message
};
let ip_button = if self.ip.is_none() {
html! {<button onclick=&self.get_ip()>{{ "Get ip" }}</button>}
} else {
html! { <button onclick=&self.clear_ip()>{{ "Clear IP" }}</button> }
};
let subs = (0..self.total_subs).map(|x| html! { <Subscriber id=x /> });
html! {
<div class="app-container">
<h2>{{ "Click the button to get your ip" }}</h2>
<p>{{ ip }}</p>
<div class="buttons">
{{ ip_button }}
<button onclick=&self.add_sub()>{{ "Add subscriber" }}</button>
<button onclick=&self.dec_sub()>{{ "Remove Subscriber" }}</button>
</div>
{ for subs }
</div>
}
}
}
// Custom component methods
impl App {
// You don't need to extract this, but I did to make things easier to read in the render area
fn handle_updates(&mut self, msg: <App as Component>::Message) -> ShouldRender {
match msg {
Msg::FromStore(s) => match s {
StoreOutput::StateInstance(state) => {
self.state_ref = Some(state);
true
}
},
// State action -- no re-render
Msg::GetIp => {
self.store.send(StoreInput::Action(GetIp));
false
}
// State action -- no re-render
Msg::ClearIp => {
self.store.send(StoreInput::Action(ClearIp));
false
}
// State subscription action -- needs a re-render
Msg::SetIp(ip) => {
self.ip = ip;
true
}
// Local action -- needs a re-render
Msg::IncSubs => {
self.total_subs += 1;
true
}
// Local action -- needs a re-render
Msg::DecSubs => {
if self.total_subs - 1 >= 1 {
self.total_subs -= 1;
}
true
}
}
}
fn register_state_handlers(&self) {
let callback = self.link.callback(|ip| Msg::SetIp(ip));
let state = self.state_ref.as_ref().unwrap();
let handler = state.ip.signal_cloned().for_each(move |u| {
info!("{:?}", u);
callback.emit(u);
ready(())
});
spawn_local(handler);
}
fn get_ip(&self) -> Callback<MouseEvent> {
self.link.callback(|_| Msg::GetIp)
}
fn clear_ip(&self) -> Callback<MouseEvent> {
self.link.callback(|_| Msg::ClearIp)
}
fn add_sub(&self) -> Callback<MouseEvent> {
self.link.callback(|_| Msg::IncSubs)
}
fn dec_sub(&self) -> Callback<MouseEvent> {
self.link.callback(|_| Msg::DecSubs)
}
}
|
// "Bubble" the highest element for each cycle to the last position(s), by swapping adjacent pairs.
//
pub fn bubble_sort<T: PartialOrd>(collection: &mut [T]) {
// If the collection is already sorted, only one pass is performed.
//
for start in 0..collection.len() {
let mut sorted = true;
// For each cycle, we can ignore the last `start` elements, because on each pass moves the
// highest element [considered] to the end of the [considered] interval.
//
for i in 0..(collection.len() - 1 - start) {
if collection[i] > collection[i + 1] {
collection.swap(i, i + 1);
sorted = false;
}
}
if sorted {
return;
}
}
}
#[cfg(test)]
mod tests {
use super::bubble_sort;
use crate::test_sort;
test_sort!(test_bubble_sort, collection, bubble_sort(&mut collection));
}
|
mod utils;
mod pool;
mod platform;
mod io;
mod window;
mod async_io_worker;
extern crate sourcerenderer_core;
extern crate sourcerenderer_engine;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate rayon;
#[macro_use]
extern crate lazy_static;
extern crate crossbeam_channel;
use std::cell::RefCell;
use std::cell::RefMut;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering;
use sourcerenderer_core::Platform;
use sourcerenderer_core::platform::Window;
use sourcerenderer_engine::Engine;
use sourcerenderer_webgl::WebGLSwapchain;
use crate::pool::WorkerPool;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::window;
use web_sys::{EventTarget, HtmlCanvasElement, Worker};
use self::platform::WebPlatform;
use sourcerenderer_webgl::WebGLThreadDevice;
use crossbeam_channel::unbounded;
#[wasm_bindgen]
extern "C" {
// Use `js_namespace` here to bind `console.log(..)` instead of just
// `log(..)`
#[wasm_bindgen(js_namespace = console)]
pub fn log(s: &str);
// The `console.log` is quite polymorphic, so we can bind it with multiple
// signatures. Note that we need to use `js_name` to ensure we always call
// `log` in JS.
#[wasm_bindgen(js_namespace = console, js_name = log)]
pub fn log_u32(a: u32);
// Multiple arguments too!
#[wasm_bindgen(js_namespace = console, js_name = log)]
pub fn log_many(a: &str, b: &str);
// Multiple arguments too!
#[wasm_bindgen(js_namespace = console, js_name = log)]
pub fn logv(a: &JsValue);
}
#[macro_export]
macro_rules! console_log {
// Note that this is using the `log` function imported above during
// `bare_bones`
($($t:tt)*) => (crate::log(&format_args!($($t)*).to_string()))
}
struct EngineWrapper {
engine: Engine<WebPlatform>,
gl_device: WebGLThreadDevice
}
#[wasm_bindgen(js_name = "startEngine")]
pub fn start_engine(canvas: HtmlCanvasElement, worker_pool: WorkerPool) -> usize {
utils::set_panic_hook();
console_log::init_with_level(log::Level::Trace).unwrap();
console_log!("Initializing platform");
let platform = WebPlatform::new(canvas, worker_pool);
console_log!("Initializing engine");
let engine = Engine::run(&platform);
console_log!("Initialized engine");
let device = engine.device().clone();
console_log!("Got device");
let surface = engine.surface().clone();
console_log!("Got surface");
let receiver = device.receiver();
let window = platform.window();
let document = window.document();
let thread_device = WebGLThreadDevice::new(receiver, &surface, document);
let wrapper = Box::new(RefCell::new(EngineWrapper {
gl_device: thread_device,
engine
}));
Box::into_raw(wrapper) as usize
}
fn engine_from_usize<'a>(engine_ptr: usize) -> RefMut<'a, EngineWrapper> {
assert_ne!(engine_ptr, 0);
unsafe {
let ptr = std::mem::transmute::<usize, *mut RefCell<EngineWrapper>>(engine_ptr);
let engine: RefMut<EngineWrapper> = (*ptr).borrow_mut();
let engine_ref = std::mem::transmute::<RefMut<EngineWrapper>, RefMut<'a, EngineWrapper>>(engine);
engine_ref
}
}
#[wasm_bindgen]
pub struct RayonInitialization {
rayon_threads: u32,
ready_thread_counter: Arc<AtomicU32>
}
#[wasm_bindgen(js_name = "startRayonWorkers")]
pub fn start_rayon_workers(worker_pool: &WorkerPool, rayon_thread_count: u32) -> RayonInitialization {
let initialize_counter = Arc::new(AtomicU32::new(0));
let (rayon_start_sender, rayon_start_receiver) = unbounded::<rayon::ThreadBuilder>();
for _ in 0..rayon_thread_count {
let c_receiver = rayon_start_receiver.clone();
let c_counter = initialize_counter.clone();
worker_pool.run_permanent(move || {
console_log!("Rayon worker waiting for initialization");
let thread_builder = c_receiver.recv().unwrap();
console_log!("Rayon worker initializing");
c_counter.fetch_add(1, Ordering::SeqCst);
thread_builder.run();
}, Some("Rayon worker")).unwrap();
}
worker_pool.run(move || {
rayon::ThreadPoolBuilder::new()
.num_threads(rayon_thread_count as usize)
.spawn_handler(|builder| {
rayon_start_sender.send(builder).unwrap();
Ok(())
})
.build_global()
.unwrap();
}).unwrap();
RayonInitialization {
ready_thread_counter: initialize_counter,
rayon_threads: rayon_thread_count
}
}
#[wasm_bindgen]
impl RayonInitialization {
#[wasm_bindgen(js_name = "isDone")]
pub fn is_done(&self) -> bool {
self.ready_thread_counter.load(Ordering::SeqCst) == self.rayon_threads
}
}
#[wasm_bindgen(js_name = "engineFrame")]
pub fn engine_frame(engine: usize) -> bool {
let mut wrapper = engine_from_usize(engine);
wrapper.engine.frame();
wrapper.gl_device.process();
true
}
|
fn main(){
let mut s = String::from("hello");
{
let r1 = &mut s;
println!("{}",s);
}
let r2 = &mut s;
}
///これなんでエラーでるんだろ?
/// 可変な参照してるr1 可変ではあっても参照のはずだからsのデータ "hello"の所有権はr1にうつってないよね?
/// 可変な参照 って所有権うつるの???????もしかして
/// うーむ
|
pub mod cpu;
pub mod mem_map;
pub mod memory;
pub mod ppu;
|
use super::*;
use std::string::String;
#[test]
fn it_works() {
let mut map = IndexMap::new();
assert_eq!(map.is_empty(), true);
map.insert(1, ());
map.insert(1, ());
assert_eq!(map.len(), 1);
assert!(map.get(&1).is_some());
assert_eq!(map.is_empty(), false);
}
#[test]
fn new() {
let map = IndexMap::<String, String>::new();
println!("{:?}", map);
assert_eq!(map.capacity(), 0);
assert_eq!(map.len(), 0);
assert_eq!(map.is_empty(), true);
}
#[test]
fn insert() {
let insert = [0, 4, 2, 12, 8, 7, 11, 5];
let not_present = [1, 3, 6, 9, 10];
let mut map = IndexMap::with_capacity(insert.len());
for (i, &elt) in insert.iter().enumerate() {
assert_eq!(map.len(), i);
map.insert(elt, elt);
assert_eq!(map.len(), i + 1);
assert_eq!(map.get(&elt), Some(&elt));
assert_eq!(map[&elt], elt);
}
println!("{:?}", map);
for &elt in ¬_present {
assert!(map.get(&elt).is_none());
}
}
#[test]
fn insert_full() {
let insert = vec![9, 2, 7, 1, 4, 6, 13];
let present = vec![1, 6, 2];
let mut map = IndexMap::with_capacity(insert.len());
for (i, &elt) in insert.iter().enumerate() {
assert_eq!(map.len(), i);
let (index, existing) = map.insert_full(elt, elt);
assert_eq!(existing, None);
assert_eq!(Some(index), map.get_full(&elt).map(|x| x.0));
assert_eq!(map.len(), i + 1);
}
let len = map.len();
for &elt in &present {
let (index, existing) = map.insert_full(elt, elt);
assert_eq!(existing, Some(elt));
assert_eq!(Some(index), map.get_full(&elt).map(|x| x.0));
assert_eq!(map.len(), len);
}
}
#[test]
fn insert_2() {
let mut map = IndexMap::with_capacity(16);
let mut keys = vec![];
keys.extend(0..16);
keys.extend(if cfg!(miri) { 32..64 } else { 128..267 });
for &i in &keys {
let old_map = map.clone();
map.insert(i, ());
for key in old_map.keys() {
if map.get(key).is_none() {
println!("old_map: {:?}", old_map);
println!("map: {:?}", map);
panic!("did not find {} in map", key);
}
}
}
for &i in &keys {
assert!(map.get(&i).is_some(), "did not find {}", i);
}
}
#[test]
fn insert_order() {
let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
let mut map = IndexMap::new();
for &elt in &insert {
map.insert(elt, ());
}
assert_eq!(map.keys().count(), map.len());
assert_eq!(map.keys().count(), insert.len());
for (a, b) in insert.iter().zip(map.keys()) {
assert_eq!(a, b);
}
for (i, k) in (0..insert.len()).zip(map.keys()) {
assert_eq!(map.get_index(i).unwrap().0, k);
}
}
#[test]
fn grow() {
let insert = [0, 4, 2, 12, 8, 7, 11];
let not_present = [1, 3, 6, 9, 10];
let mut map = IndexMap::with_capacity(insert.len());
for (i, &elt) in insert.iter().enumerate() {
assert_eq!(map.len(), i);
map.insert(elt, elt);
assert_eq!(map.len(), i + 1);
assert_eq!(map.get(&elt), Some(&elt));
assert_eq!(map[&elt], elt);
}
println!("{:?}", map);
for &elt in &insert {
map.insert(elt * 10, elt);
}
for &elt in &insert {
map.insert(elt * 100, elt);
}
for (i, &elt) in insert.iter().cycle().enumerate().take(100) {
map.insert(elt * 100 + i as i32, elt);
}
println!("{:?}", map);
for &elt in ¬_present {
assert!(map.get(&elt).is_none());
}
}
#[test]
fn reserve() {
let mut map = IndexMap::<usize, usize>::new();
assert_eq!(map.capacity(), 0);
map.reserve(100);
let capacity = map.capacity();
assert!(capacity >= 100);
for i in 0..capacity {
assert_eq!(map.len(), i);
map.insert(i, i * i);
assert_eq!(map.len(), i + 1);
assert_eq!(map.capacity(), capacity);
assert_eq!(map.get(&i), Some(&(i * i)));
}
map.insert(capacity, std::usize::MAX);
assert_eq!(map.len(), capacity + 1);
assert!(map.capacity() > capacity);
assert_eq!(map.get(&capacity), Some(&std::usize::MAX));
}
#[test]
fn try_reserve() {
let mut map = IndexMap::<usize, usize>::new();
assert_eq!(map.capacity(), 0);
assert_eq!(map.try_reserve(100), Ok(()));
assert!(map.capacity() >= 100);
assert!(map.try_reserve(usize::MAX).is_err());
}
#[test]
fn shrink_to_fit() {
let mut map = IndexMap::<usize, usize>::new();
assert_eq!(map.capacity(), 0);
for i in 0..100 {
assert_eq!(map.len(), i);
map.insert(i, i * i);
assert_eq!(map.len(), i + 1);
assert!(map.capacity() >= i + 1);
assert_eq!(map.get(&i), Some(&(i * i)));
map.shrink_to_fit();
assert_eq!(map.len(), i + 1);
assert_eq!(map.capacity(), i + 1);
assert_eq!(map.get(&i), Some(&(i * i)));
}
}
#[test]
fn remove() {
let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
let mut map = IndexMap::new();
for &elt in &insert {
map.insert(elt, elt);
}
assert_eq!(map.keys().count(), map.len());
assert_eq!(map.keys().count(), insert.len());
for (a, b) in insert.iter().zip(map.keys()) {
assert_eq!(a, b);
}
let remove_fail = [99, 77];
let remove = [4, 12, 8, 7];
for &key in &remove_fail {
assert!(map.swap_remove_full(&key).is_none());
}
println!("{:?}", map);
for &key in &remove {
//println!("{:?}", map);
let index = map.get_full(&key).unwrap().0;
assert_eq!(map.swap_remove_full(&key), Some((index, key, key)));
}
println!("{:?}", map);
for key in &insert {
assert_eq!(map.get(key).is_some(), !remove.contains(key));
}
assert_eq!(map.len(), insert.len() - remove.len());
assert_eq!(map.keys().count(), insert.len() - remove.len());
}
#[test]
fn remove_to_empty() {
let mut map = indexmap! { 0 => 0, 4 => 4, 5 => 5 };
map.swap_remove(&5).unwrap();
map.swap_remove(&4).unwrap();
map.swap_remove(&0).unwrap();
assert!(map.is_empty());
}
#[test]
fn swap_remove_index() {
let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
let mut map = IndexMap::new();
for &elt in &insert {
map.insert(elt, elt * 2);
}
let mut vector = insert.to_vec();
let remove_sequence = &[3, 3, 10, 4, 5, 4, 3, 0, 1];
// check that the same swap remove sequence on vec and map
// have the same result.
for &rm in remove_sequence {
let out_vec = vector.swap_remove(rm);
let (out_map, _) = map.swap_remove_index(rm).unwrap();
assert_eq!(out_vec, out_map);
}
assert_eq!(vector.len(), map.len());
for (a, b) in vector.iter().zip(map.keys()) {
assert_eq!(a, b);
}
}
#[test]
fn partial_eq_and_eq() {
let mut map_a = IndexMap::new();
map_a.insert(1, "1");
map_a.insert(2, "2");
let mut map_b = map_a.clone();
assert_eq!(map_a, map_b);
map_b.swap_remove(&1);
assert_ne!(map_a, map_b);
let map_c: IndexMap<_, String> = map_b.into_iter().map(|(k, v)| (k, v.into())).collect();
assert_ne!(map_a, map_c);
assert_ne!(map_c, map_a);
}
#[test]
fn extend() {
let mut map = IndexMap::new();
map.extend(vec![(&1, &2), (&3, &4)]);
map.extend(vec![(5, 6)]);
assert_eq!(
map.into_iter().collect::<Vec<_>>(),
vec![(1, 2), (3, 4), (5, 6)]
);
}
#[test]
fn entry() {
let mut map = IndexMap::new();
map.insert(1, "1");
map.insert(2, "2");
{
let e = map.entry(3);
assert_eq!(e.index(), 2);
let e = e.or_insert("3");
assert_eq!(e, &"3");
}
let e = map.entry(2);
assert_eq!(e.index(), 1);
assert_eq!(e.key(), &2);
match e {
Entry::Occupied(ref e) => assert_eq!(e.get(), &"2"),
Entry::Vacant(_) => panic!(),
}
assert_eq!(e.or_insert("4"), &"2");
}
#[test]
fn entry_and_modify() {
let mut map = IndexMap::new();
map.insert(1, "1");
map.entry(1).and_modify(|x| *x = "2");
assert_eq!(Some(&"2"), map.get(&1));
map.entry(2).and_modify(|x| *x = "doesn't exist");
assert_eq!(None, map.get(&2));
}
#[test]
fn entry_or_default() {
let mut map = IndexMap::new();
#[derive(Debug, PartialEq)]
enum TestEnum {
DefaultValue,
NonDefaultValue,
}
impl Default for TestEnum {
fn default() -> Self {
TestEnum::DefaultValue
}
}
map.insert(1, TestEnum::NonDefaultValue);
assert_eq!(&mut TestEnum::NonDefaultValue, map.entry(1).or_default());
assert_eq!(&mut TestEnum::DefaultValue, map.entry(2).or_default());
}
#[test]
fn occupied_entry_key() {
// These keys match hash and equality, but their addresses are distinct.
let (k1, k2) = (&mut 1, &mut 1);
let k1_ptr = k1 as *const i32;
let k2_ptr = k2 as *const i32;
assert_ne!(k1_ptr, k2_ptr);
let mut map = IndexMap::new();
map.insert(k1, "value");
match map.entry(k2) {
Entry::Occupied(ref e) => {
// `OccupiedEntry::key` should reference the key in the map,
// not the key that was used to find the entry.
let ptr = *e.key() as *const i32;
assert_eq!(ptr, k1_ptr);
assert_ne!(ptr, k2_ptr);
}
Entry::Vacant(_) => panic!(),
}
}
#[test]
fn keys() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: IndexMap<_, _> = vec.into_iter().collect();
let keys: Vec<_> = map.keys().copied().collect();
assert_eq!(keys.len(), 3);
assert!(keys.contains(&1));
assert!(keys.contains(&2));
assert!(keys.contains(&3));
}
#[test]
fn into_keys() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: IndexMap<_, _> = vec.into_iter().collect();
let keys: Vec<i32> = map.into_keys().collect();
assert_eq!(keys.len(), 3);
assert!(keys.contains(&1));
assert!(keys.contains(&2));
assert!(keys.contains(&3));
}
#[test]
fn values() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: IndexMap<_, _> = vec.into_iter().collect();
let values: Vec<_> = map.values().copied().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&'a'));
assert!(values.contains(&'b'));
assert!(values.contains(&'c'));
}
#[test]
fn values_mut() {
let vec = vec![(1, 1), (2, 2), (3, 3)];
let mut map: IndexMap<_, _> = vec.into_iter().collect();
for value in map.values_mut() {
*value *= 2
}
let values: Vec<_> = map.values().copied().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&2));
assert!(values.contains(&4));
assert!(values.contains(&6));
}
#[test]
fn into_values() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: IndexMap<_, _> = vec.into_iter().collect();
let values: Vec<char> = map.into_values().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&'a'));
assert!(values.contains(&'b'));
assert!(values.contains(&'c'));
}
#[test]
#[cfg(feature = "std")]
fn from_array() {
let map = IndexMap::from([(1, 2), (3, 4)]);
let mut expected = IndexMap::new();
expected.insert(1, 2);
expected.insert(3, 4);
assert_eq!(map, expected)
}
#[test]
fn iter_default() {
struct K;
struct V;
fn assert_default<T>()
where
T: Default + Iterator,
{
assert!(T::default().next().is_none());
}
assert_default::<Iter<'static, K, V>>();
assert_default::<IterMut<'static, K, V>>();
assert_default::<IntoIter<K, V>>();
assert_default::<Keys<'static, K, V>>();
assert_default::<IntoKeys<K, V>>();
assert_default::<Values<'static, K, V>>();
assert_default::<ValuesMut<'static, K, V>>();
assert_default::<IntoValues<K, V>>();
}
|
extern crate deltalake;
use arrow::datatypes::DataType as ArrowDataType;
#[test]
fn test_arrow_from_delta_decimal_type() {
let precision = 20;
let scale = 2;
let decimal_type = String::from(format!["decimal({p},{s})", p = precision, s = scale]);
let decimal_field = deltalake::SchemaDataType::primitive(decimal_type);
assert_eq!(
<ArrowDataType as From<&deltalake::SchemaDataType>>::from(&decimal_field),
ArrowDataType::Decimal(precision, scale)
);
}
|
use clap::{crate_description, crate_name, crate_version, Arg, ArgMatches};
use morgan_interface::signature::{gen_keypair_file, read_keypair, KeypairUtil};
use morgan_wallet::wallet::{app, parse_command, process_command, WalletConfig, WalletError};
use std::error;
pub fn parse_args(matches: &ArgMatches<'_>) -> Result<WalletConfig, Box<dyn error::Error>> {
let json_rpc_url = matches.value_of("json_rpc_url").unwrap().to_string();
let drone_host = if let Some(drone_host) = matches.value_of("drone_host") {
Some(morgan_netutil::parse_host(drone_host).or_else(|err| {
Err(WalletError::BadParameter(format!(
"Invalid drone host: {:?}",
err
)))
})?)
} else {
None
};
let drone_port = matches
.value_of("drone_port")
.unwrap()
.parse()
.or_else(|err| {
Err(WalletError::BadParameter(format!(
"Invalid drone port: {:?}",
err
)))
})?;
let mut path = dirs::home_dir().expect("home directory");
let id_path = if matches.is_present("keypair") {
matches.value_of("keypair").unwrap()
} else {
path.extend(&[".config", "morgan", "id.json"]);
if !path.exists() {
gen_keypair_file(path.to_str().unwrap())?;
println!("New keypair generated at: {:?}", path.to_str().unwrap());
}
path.to_str().unwrap()
};
let keypair = read_keypair(id_path).or_else(|err| {
Err(WalletError::BadParameter(format!(
"{}: Unable to open keypair file: {}",
err, id_path
)))
})?;
let command = parse_command(&keypair.pubkey(), &matches)?;
Ok(WalletConfig {
command,
drone_host,
drone_port,
json_rpc_url,
keypair,
rpc_client: None,
})
}
// Return an error if a url cannot be parsed.
fn is_url(string: String) -> Result<(), String> {
match url::Url::parse(&string) {
Ok(url) => {
if url.has_host() {
Ok(())
} else {
Err("no host provided".to_string())
}
}
Err(err) => Err(format!("{:?}", err)),
}
}
fn main() -> Result<(), Box<dyn error::Error>> {
morgan_logger::setup();
let default = WalletConfig::default();
let default_drone_port = format!("{}", default.drone_port);
let matches = app(crate_name!(), crate_description!(), crate_version!())
.arg(
Arg::with_name("json_rpc_url")
.short("u")
.long("url")
.value_name("URL")
.takes_value(true)
.default_value(&default.json_rpc_url)
.validator(is_url)
.help("JSON RPC URL for the morgan cluster"),
)
.arg(
Arg::with_name("drone_host")
.long("drone-host")
.value_name("HOST")
.takes_value(true)
.help("Drone host to use [default: same as the --url host]"),
)
.arg(
Arg::with_name("drone_port")
.long("drone-port")
.value_name("PORT")
.takes_value(true)
.default_value(&default_drone_port)
.help("Drone port to use"),
)
.arg(
Arg::with_name("keypair")
.short("k")
.long("keypair")
.value_name("PATH")
.takes_value(true)
.help("/path/to/id.json"),
)
.get_matches();
let config = parse_args(&matches)?;
let result = process_command(&config)?;
println!("{}", result);
Ok(())
}
|
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use sfxr::{Generator, Sample, WaveType};
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("setup without generate", |b| {
b.iter(|| {
let mut sample = Sample::new();
sample.wave_type = WaveType::Sine;
// Black box will make sure the compiler won't compile away the unused results
let _generator = black_box(Generator::new(sample));
});
});
c.bench_function("reset", |b| {
let mut buffer = [0.0; 44_100];
let mut sample = Sample::new();
sample.wave_type = WaveType::Sine;
let mut generator = Generator::new(sample);
generator.generate(&mut buffer);
b.iter(|| {
generator.reset();
});
});
c.bench_function("mutate", |b| {
let mut sample = Sample::new();
b.iter(|| {
sample.mutate(None);
});
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
#[doc = "Writer for register IFCR"]
pub type W = crate::W<u32, super::IFCR>;
#[doc = "Register IFCR `reset()`'s with value 0"]
impl crate::ResetValue for super::IFCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `CGIF0`"]
pub struct CGIF0_W<'a> {
w: &'a mut W,
}
impl<'a> CGIF0_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 = "Write proxy for field `CTCIF1`"]
pub struct CTCIF1_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIF1_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 = "Write proxy for field `CHTIF2`"]
pub struct CHTIF2_W<'a> {
w: &'a mut W,
}
impl<'a> CHTIF2_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 = "Write proxy for field `CTEIF3`"]
pub struct CTEIF3_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF3_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 = "Write proxy for field `CGIF4`"]
pub struct CGIF4_W<'a> {
w: &'a mut W,
}
impl<'a> CGIF4_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 = "Write proxy for field `CTCIF5`"]
pub struct CTCIF5_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIF5_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 = "Write proxy for field `CHTIF6`"]
pub struct CHTIF6_W<'a> {
w: &'a mut W,
}
impl<'a> CHTIF6_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 = "Write proxy for field `CTEIF7`"]
pub struct CTEIF7_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF7_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 = "Write proxy for field `CGIF8`"]
pub struct CGIF8_W<'a> {
w: &'a mut W,
}
impl<'a> CGIF8_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 = "Write proxy for field `CTCIF9`"]
pub struct CTCIF9_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIF9_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 = "Write proxy for field `CHTIF10`"]
pub struct CHTIF10_W<'a> {
w: &'a mut W,
}
impl<'a> CHTIF10_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 = "Write proxy for field `CTEIF11`"]
pub struct CTEIF11_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF11_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 = "Write proxy for field `CGIF12`"]
pub struct CGIF12_W<'a> {
w: &'a mut W,
}
impl<'a> CGIF12_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 = "Write proxy for field `CTCIF13`"]
pub struct CTCIF13_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIF13_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 = "Write proxy for field `CHTIF14`"]
pub struct CHTIF14_W<'a> {
w: &'a mut W,
}
impl<'a> CHTIF14_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 = "Write proxy for field `CTEIF15`"]
pub struct CTEIF15_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF15_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 = "Write proxy for field `CGIF16`"]
pub struct CGIF16_W<'a> {
w: &'a mut W,
}
impl<'a> CGIF16_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 = "Write proxy for field `CTCIF17`"]
pub struct CTCIF17_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIF17_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 = "Write proxy for field `CHTIF18`"]
pub struct CHTIF18_W<'a> {
w: &'a mut W,
}
impl<'a> CHTIF18_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 = "Write proxy for field `CTEIF19`"]
pub struct CTEIF19_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF19_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 = "Write proxy for field `CGIF20`"]
pub struct CGIF20_W<'a> {
w: &'a mut W,
}
impl<'a> CGIF20_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 = "Write proxy for field `CTCIF21`"]
pub struct CTCIF21_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIF21_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 = "Write proxy for field `CHTIF22`"]
pub struct CHTIF22_W<'a> {
w: &'a mut W,
}
impl<'a> CHTIF22_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 = "Write proxy for field `CTEIF23`"]
pub struct CTEIF23_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF23_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 = "Write proxy for field `CGIF24`"]
pub struct CGIF24_W<'a> {
w: &'a mut W,
}
impl<'a> CGIF24_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 = "Write proxy for field `CTCIF25`"]
pub struct CTCIF25_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIF25_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 = "Write proxy for field `CHTIF26`"]
pub struct CHTIF26_W<'a> {
w: &'a mut W,
}
impl<'a> CHTIF26_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 = "Write proxy for field `CTEIF27`"]
pub struct CTEIF27_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF27_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
}
}
impl W {
#[doc = "Bit 0 - Channel global interrupt flag"]
#[inline(always)]
pub fn cgif0(&mut self) -> CGIF0_W {
CGIF0_W { w: self }
}
#[doc = "Bit 1 - Channel transfer complete flag"]
#[inline(always)]
pub fn ctcif1(&mut self) -> CTCIF1_W {
CTCIF1_W { w: self }
}
#[doc = "Bit 2 - Channel half transfer flag"]
#[inline(always)]
pub fn chtif2(&mut self) -> CHTIF2_W {
CHTIF2_W { w: self }
}
#[doc = "Bit 3 - Channel transfer error flag"]
#[inline(always)]
pub fn cteif3(&mut self) -> CTEIF3_W {
CTEIF3_W { w: self }
}
#[doc = "Bit 4 - Channel global interrupt flag"]
#[inline(always)]
pub fn cgif4(&mut self) -> CGIF4_W {
CGIF4_W { w: self }
}
#[doc = "Bit 5 - Channel transfer complete flag"]
#[inline(always)]
pub fn ctcif5(&mut self) -> CTCIF5_W {
CTCIF5_W { w: self }
}
#[doc = "Bit 6 - Channel half transfer flag"]
#[inline(always)]
pub fn chtif6(&mut self) -> CHTIF6_W {
CHTIF6_W { w: self }
}
#[doc = "Bit 7 - Channel transfer error flag"]
#[inline(always)]
pub fn cteif7(&mut self) -> CTEIF7_W {
CTEIF7_W { w: self }
}
#[doc = "Bit 8 - Channel global interrupt flag"]
#[inline(always)]
pub fn cgif8(&mut self) -> CGIF8_W {
CGIF8_W { w: self }
}
#[doc = "Bit 9 - Channel transfer complete flag"]
#[inline(always)]
pub fn ctcif9(&mut self) -> CTCIF9_W {
CTCIF9_W { w: self }
}
#[doc = "Bit 10 - Channel half transfer flag"]
#[inline(always)]
pub fn chtif10(&mut self) -> CHTIF10_W {
CHTIF10_W { w: self }
}
#[doc = "Bit 11 - Channel transfer error flag"]
#[inline(always)]
pub fn cteif11(&mut self) -> CTEIF11_W {
CTEIF11_W { w: self }
}
#[doc = "Bit 12 - Channel global interrupt flag"]
#[inline(always)]
pub fn cgif12(&mut self) -> CGIF12_W {
CGIF12_W { w: self }
}
#[doc = "Bit 13 - Channel transfer complete flag"]
#[inline(always)]
pub fn ctcif13(&mut self) -> CTCIF13_W {
CTCIF13_W { w: self }
}
#[doc = "Bit 14 - Channel half transfer flag"]
#[inline(always)]
pub fn chtif14(&mut self) -> CHTIF14_W {
CHTIF14_W { w: self }
}
#[doc = "Bit 15 - Channel transfer error flag"]
#[inline(always)]
pub fn cteif15(&mut self) -> CTEIF15_W {
CTEIF15_W { w: self }
}
#[doc = "Bit 16 - Channel global interrupt flag"]
#[inline(always)]
pub fn cgif16(&mut self) -> CGIF16_W {
CGIF16_W { w: self }
}
#[doc = "Bit 17 - Channel transfer complete flag"]
#[inline(always)]
pub fn ctcif17(&mut self) -> CTCIF17_W {
CTCIF17_W { w: self }
}
#[doc = "Bit 18 - Channel half transfer flag"]
#[inline(always)]
pub fn chtif18(&mut self) -> CHTIF18_W {
CHTIF18_W { w: self }
}
#[doc = "Bit 19 - Channel transfer error flag"]
#[inline(always)]
pub fn cteif19(&mut self) -> CTEIF19_W {
CTEIF19_W { w: self }
}
#[doc = "Bit 20 - Channel global interrupt flag"]
#[inline(always)]
pub fn cgif20(&mut self) -> CGIF20_W {
CGIF20_W { w: self }
}
#[doc = "Bit 21 - Channel transfer complete flag"]
#[inline(always)]
pub fn ctcif21(&mut self) -> CTCIF21_W {
CTCIF21_W { w: self }
}
#[doc = "Bit 22 - Channel half transfer flag"]
#[inline(always)]
pub fn chtif22(&mut self) -> CHTIF22_W {
CHTIF22_W { w: self }
}
#[doc = "Bit 23 - Channel transfer error flag"]
#[inline(always)]
pub fn cteif23(&mut self) -> CTEIF23_W {
CTEIF23_W { w: self }
}
#[doc = "Bit 24 - Channel global interrupt flag"]
#[inline(always)]
pub fn cgif24(&mut self) -> CGIF24_W {
CGIF24_W { w: self }
}
#[doc = "Bit 25 - Channel transfer complete flag"]
#[inline(always)]
pub fn ctcif25(&mut self) -> CTCIF25_W {
CTCIF25_W { w: self }
}
#[doc = "Bit 26 - Channel half transfer flag"]
#[inline(always)]
pub fn chtif26(&mut self) -> CHTIF26_W {
CHTIF26_W { w: self }
}
#[doc = "Bit 27 - Channel transfer error flag"]
#[inline(always)]
pub fn cteif27(&mut self) -> CTEIF27_W {
CTEIF27_W { w: self }
}
}
|
fn main() {
//argument
let a: &[isize] = &[1, 2, 4, 7];
let k: isize = 13;
println!("{}", solve(a, k));
}
fn solve(a: &[isize], k: isize) -> bool {
if depth_first_search(a, k, 0, 0) {
return true;
} else {
return false;
}
}
fn depth_first_search(a: &[isize], k: isize, sum: isize, i: usize) -> bool {
if i == a.len() {
return sum == k;
}
if depth_first_search(a, k, sum, i + 1) {
return true;
}
if depth_first_search(a, k, sum + a[i], i + 1) {
return true;
}
return false;
}
#[test]
fn check_answer() {
assert_eq!(solve(&[1, 2, 4, 7], 13), true);
assert_eq!(solve(&[1, 2, 4, 7], 15), false);
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use common_base::base::tokio;
use common_base::base::tokio::task::JoinHandle;
use common_base::base::GlobalInstance;
use common_exception::Result;
use common_meta_app::principal::RoleInfo;
use parking_lot::RwLock;
use tracing::warn;
use crate::role_util::find_all_related_roles;
use crate::UserApiProvider;
struct CachedRoles {
roles: HashMap<String, RoleInfo>,
cached_at: Instant,
}
pub struct RoleCacheManager {
user_manager: Arc<UserApiProvider>,
cache: Arc<RwLock<HashMap<String, CachedRoles>>>,
polling_interval: Duration,
polling_join_handle: Option<JoinHandle<()>>,
}
impl RoleCacheManager {
pub fn init() -> Result<()> {
// Check that the user API has been initialized.
let instance = UserApiProvider::instance();
GlobalInstance::set(Self::try_create(instance)?);
Ok(())
}
pub fn try_create(user_manager: Arc<UserApiProvider>) -> Result<Arc<RoleCacheManager>> {
let mut role_cache_manager = Self {
user_manager,
polling_join_handle: None,
cache: Arc::new(RwLock::new(HashMap::new())),
polling_interval: Duration::new(15, 0),
};
role_cache_manager.background_polling();
Ok(Arc::new(role_cache_manager))
}
pub fn instance() -> Arc<RoleCacheManager> {
GlobalInstance::get()
}
pub fn background_polling(&mut self) {
let cache = self.cache.clone();
let polling_interval = self.polling_interval;
let user_manager = self.user_manager.clone();
self.polling_join_handle = Some(tokio::spawn(async move {
loop {
let tenants: Vec<String> = {
let cached = cache.read();
cached.keys().cloned().collect()
};
for tenant in tenants {
match load_roles_data(&user_manager, &tenant).await {
Err(err) => {
warn!(
"role_cache_mgr load roles data of tenant {} failed: {}",
tenant, err,
)
}
Ok(data) => {
let mut cached = cache.write();
cached.insert(tenant.to_string(), data);
}
}
}
tokio::time::sleep(polling_interval).await
}
}));
}
pub fn invalidate_cache(&self, tenant: &str) {
let mut cached = self.cache.write();
cached.remove(tenant);
}
pub async fn find_role(&self, tenant: &str, role: &str) -> Result<Option<RoleInfo>> {
let cached = self.cache.read();
let cached_roles = match cached.get(tenant) {
None => return Ok(None),
Some(cached_roles) => cached_roles,
};
Ok(cached_roles.roles.get(role).cloned())
}
// find_related_roles is called on validating an user's privileges.
pub async fn find_related_roles(
&self,
tenant: &str,
roles: &[String],
) -> Result<Vec<RoleInfo>> {
self.maybe_reload(tenant).await?;
let cached = self.cache.read();
let cached_roles = match cached.get(tenant) {
None => return Ok(vec![]),
Some(cached_roles) => cached_roles,
};
Ok(find_all_related_roles(&cached_roles.roles, roles))
}
pub async fn force_reload(&self, tenant: &str) -> Result<()> {
let data = load_roles_data(&self.user_manager, tenant).await?;
let mut cached = self.cache.write();
cached.insert(tenant.to_string(), data);
Ok(())
}
// Load roles data if not found in cache. Watch this tenant's role data in background if
// once it loads successfully.
async fn maybe_reload(&self, tenant: &str) -> Result<()> {
let need_reload = {
let cached = self.cache.read();
match cached.get(tenant) {
None => true,
Some(cached_roles) => {
// force reload the data when:
// - if the cache is too old (the background polling task
// may got some network errors, leaves the cache outdated)
// - if the cache is empty
cached_roles.cached_at.elapsed() >= self.polling_interval * 2
|| cached_roles.roles.is_empty()
}
}
};
if need_reload {
self.force_reload(tenant).await?;
}
Ok(())
}
}
async fn load_roles_data(user_api: &Arc<UserApiProvider>, tenant: &str) -> Result<CachedRoles> {
let roles = user_api.get_roles(tenant).await?;
let roles_map = roles
.into_iter()
.map(|r| (r.identity().to_string(), r))
.collect::<HashMap<_, _>>();
Ok(CachedRoles {
roles: roles_map,
cached_at: Instant::now(),
})
}
|
mod futex;
// legacy versions:
//mod rwfutex;
//mod rwfutex2;
//mod rwfutex3;
mod rwfutex4;
pub use self::futex::Futex as Mutex;
pub use self::rwfutex4::RwFutex2 as RwLock;
#[cfg(test)]
mod tests {
use std::thread;
use std::time::Duration;
use std::sync::Arc;
use super::*;
#[test]
fn mutex() {
let futex = Arc::new(Mutex::new());
let futex2 = futex.clone();
futex.acquire();
thread::spawn(move || {
thread::sleep(Duration::from_millis(100));
futex2.release();
}).join().unwrap();
futex.acquire();
futex.release();
}
#[test]
fn rwlock() {
let futex = Arc::new(RwLock::new());
let futex2 = futex.clone();
futex.acquire_read();
futex.acquire_read();
futex.acquire_read();
thread::spawn(move || {
futex2.acquire_read();
futex2.release_read();
futex2.acquire_write();
thread::sleep(Duration::from_millis(100));
futex2.release_write();
});
futex.release_read();
futex.release_read();
futex.release_read();
futex.acquire_read();
futex.release_read();
}
}
|
use crate::{
buffers::{self, Buffer, Buffers, CapacityError, DefaultBuffers},
Comment, GCode, Span, Word,
};
use core::fmt::{self, Debug, Formatter};
/// A single line, possibly containing some [`Comment`]s or [`GCode`]s.
#[derive(Clone, PartialEq)]
#[cfg_attr(
feature = "serde-1",
derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
pub struct Line<'input, B: Buffers<'input> = DefaultBuffers> {
gcodes: B::Commands,
comments: B::Comments,
line_number: Option<Word>,
span: Span,
}
impl<'input, B> Debug for Line<'input, B>
where
B: Buffers<'input>,
{
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// explicitly implement Debug because the normal derive is too strict
let Line {
gcodes,
comments,
line_number,
span,
} = self;
f.debug_struct("Line")
.field("gcodes", &buffers::debug(gcodes))
.field("comments", &buffers::debug(comments))
.field("line_number", line_number)
.field("span", span)
.finish()
}
}
impl<'input, B> Default for Line<'input, B>
where
B: Buffers<'input>,
B::Commands: Default,
B::Comments: Default,
{
fn default() -> Line<'input, B> {
Line {
gcodes: B::Commands::default(),
comments: B::Comments::default(),
line_number: None,
span: Span::default(),
}
}
}
impl<'input, B: Buffers<'input>> Line<'input, B> {
/// All [`GCode`]s in this line.
pub fn gcodes(&self) -> &[GCode<B::Arguments>] { self.gcodes.as_slice() }
/// All [`Comment`]s in this line.
pub fn comments(&self) -> &[Comment<'input>] { self.comments.as_slice() }
/// Try to add another [`GCode`] to the line.
pub fn push_gcode(
&mut self,
gcode: GCode<B::Arguments>,
) -> Result<(), CapacityError<GCode<B::Arguments>>> {
// Note: We need to make sure a failed push doesn't change our span
let span = self.span.merge(gcode.span());
self.gcodes.try_push(gcode)?;
self.span = span;
Ok(())
}
/// Try to add a [`Comment`] to the line.
pub fn push_comment(
&mut self,
comment: Comment<'input>,
) -> Result<(), CapacityError<Comment<'input>>> {
let span = self.span.merge(comment.span);
self.comments.try_push(comment)?;
self.span = span;
Ok(())
}
/// Does the [`Line`] contain anything at all?
pub fn is_empty(&self) -> bool {
self.gcodes.as_slice().is_empty()
&& self.comments.as_slice().is_empty()
&& self.line_number().is_none()
}
/// Try to get the line number, if there was one.
pub fn line_number(&self) -> Option<Word> { self.line_number }
/// Set the [`Line::line_number()`].
pub fn set_line_number<W: Into<Option<Word>>>(&mut self, line_number: W) {
match line_number.into() {
Some(n) => {
self.span = self.span.merge(n.span);
self.line_number = Some(n);
},
None => self.line_number = None,
}
}
/// Get the [`Line`]'s position in its source text.
pub fn span(&self) -> Span { self.span }
pub(crate) fn into_gcodes(self) -> B::Commands { self.gcodes }
}
|
use crate::vec3::{Point3};
use crate::ray::Ray;
use crate::hittable::{Hittable, HitRecord};
use crate::material::Material;
pub struct Sphere {
pub center: Point3,
pub radius: f32,
pub material: Material,
}
impl Sphere{
pub fn sphere(center: Point3, radius: f32, material: Material) -> Sphere {
Sphere {
center,
radius,
material,
}
}
}
impl Hittable for Sphere {
fn hit(&self, r: &Ray, t_min: f32, t_max: f32) -> Option<HitRecord>{
let oc = r.origin() - self.center;
let a = r.direction().length_squared();
let half_b = oc.dot(r.direction());
let c = oc.length_squared() - self.radius*self.radius;
let discriminat = half_b*half_b - a*c;
if discriminat > 0.0 {
let root = discriminat.sqrt();
let mut temp = (-half_b - root) / a;
if temp < t_max && temp > t_min {
let outward_normal = (r.at(temp) - self.center) / self.radius;
let mut h = HitRecord{
t: temp,
hit_point: r.at(temp),
normal: Default::default(),
front_face: Default::default(),
material: self.material,
};
h.set_face_normal(r, &outward_normal);
return Some(h);
}
temp = (-half_b + root) / a;
if temp < t_max && temp > t_min {
let outward_normal = (r.at(temp) - self.center) / self.radius;
let mut h = HitRecord{
t: temp,
hit_point: r.at(temp),
normal: Default::default(),
front_face: Default::default(),
material: self.material,
};
h.set_face_normal(r, &outward_normal);
return Some(h);
}
}
None
}
} |
fn main() {
let collection_of_numbers = (1..101).collect::<Vec<i32>>();
for num in &collection_of_numbers {
print!("{} ", num);
}
let big_numbers = (1..101).find(|n| *n > 42);
match big_numbers {
Some(n) => { print!("big {} ", n) },
None => { print!("-") },
}
println!("");
/* fold(base, |accumulator, element| ...) */
let sum = (1..10).fold(0, |sum, n| sum + n);
println!("sum={} ", sum);
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
/// A DNS key.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DnsKey<'a>
{
/// Computed key tag.
pub computed_key_tag: KeyTag,
/// DNS key purpose.
pub purpose: DnsKeyPurpose,
/// Certificate algorithm.
pub security_algorithm: SecurityAlgorithm,
/// Certificate type and data.
pub public_key: &'a [u8],
}
|
use core::clone::Clone;
use nannou::color::conv::IntoLinSrgba;
use nannou::draw::primitive::Path;
use nannou::draw::primitive::PathStroke;
use nannou::draw::properties::ColorScalar;
use nannou::draw::Drawing;
use nannou::prelude::*;
type Points = Vec<Point2>;
pub trait DrawExtension {
fn polylines(&self, num_polylines: usize) -> PolylineDrawings<PathStroke>;
}
impl DrawExtension for Draw {
fn polylines(&self, num_polylines: usize) -> PolylineDrawings<PathStroke> {
let polyline_drawings: Vec<Drawing<PathStroke>> =
(0..num_polylines).map(|_| self.polyline()).collect();
PolylineDrawings { polyline_drawings }
}
}
pub struct PolylineDrawings<'a, T> {
polyline_drawings: Vec<Drawing<'a, T>>,
}
impl<'a> PolylineDrawings<'a, Path> {
pub fn color<C>(self, color: C) -> Self
where
C: IntoLinSrgba<ColorScalar> + Clone,
{
let polyline_drawings: Vec<Drawing<Path>> = self
.polyline_drawings
.into_iter()
.map(|drawing| drawing.color(color.clone()))
.collect();
PolylineDrawings { polyline_drawings }
}
}
impl<'a> PolylineDrawings<'a, PathStroke> {
pub fn color<C>(self, color: C) -> Self
where
C: IntoLinSrgba<ColorScalar> + Clone,
{
let polyline_drawings: Vec<Drawing<PathStroke>> = self
.polyline_drawings
.into_iter()
.map(|drawing| drawing.color(color.clone()))
.collect();
PolylineDrawings { polyline_drawings }
}
pub fn points(self, paths: Vec<Vec<Point2>>) -> PolylineDrawings<'a, Path> {
let polyline_drawings: Vec<Drawing<Path>> = self
.polyline_drawings
.into_iter()
.zip(paths.into_iter())
.map(|(drawing, path)| drawing.points(path))
.collect();
PolylineDrawings { polyline_drawings }
}
}
|
use std::ptr;
use libc::{c_short, c_int};
use curses;
use {Error, Result, Color};
use super::Screen;
pub struct Colors<'a> {
screen: &'a mut Screen,
}
impl<'a> Colors<'a> {
#[inline]
pub unsafe fn wrap(screen: &mut Screen) -> Colors {
Colors { screen: screen }
}
}
impl<'a> Colors<'a> {
#[inline]
pub fn default(&mut self, fg: Color, bg: Color) -> Result<()> {
unsafe {
try!(Error::check(curses::assume_default_colors(fg.into(), bg.into())));
}
Ok(())
}
#[inline]
pub fn available(&self) -> bool {
unsafe {
curses::has_colors()
}
}
#[inline]
pub fn redefinable(&self) -> bool {
unsafe {
curses::can_change_color()
}
}
#[inline]
pub fn limit(&self) -> usize {
curses::COLOR_PAIRS as usize
}
#[inline]
pub fn define(&mut self, index: usize, (fg, bg): (Color, Color)) -> Result<()> {
unsafe {
try!(Error::check(curses::init_pair(index as c_short, fg.into(), bg.into())));
}
Ok(())
}
#[inline]
pub fn definition(&self, index: usize) -> Result<(Color, Color)> {
unsafe {
let mut f = 0;
let mut b = 0;
try!(Error::check(curses::pair_content(index as c_short, &mut f, &mut b)));
Ok((Color::from(f), Color::from(b)))
}
}
#[inline]
pub fn redefine(&mut self, color: Color, (r, g, b): (u8, u8, u8)) -> Result<()> {
unsafe {
try!(Error::check(curses::init_color(color.into(), r as c_short, g as c_short, b as c_short)));
}
Ok(())
}
#[inline]
pub fn redefinition(&self, color: Color) -> Result<(u8, u8, u8)> {
unsafe {
let mut r = 0;
let mut g = 0;
let mut b = 0;
try!(Error::check(curses::color_content(color.into(), &mut r, &mut g, &mut b)));
Ok((r as u8, g as u8, b as u8))
}
}
#[inline]
pub fn set(self, pair: usize) -> Result<&'a mut Screen> {
unsafe {
try!(Error::check(curses::color_set(pair as c_short, ptr::null())));
}
Ok(self.screen)
}
#[inline]
pub fn current(&self) -> Result<usize> {
unsafe {
let mut attr = 0;
let mut pair = 0;
try!(Error::check(curses::attr_get(&mut attr, &mut pair, ptr::null())));
Ok(pair as usize)
}
}
#[inline]
pub fn change(&mut self, pair: usize, len: Option<usize>) -> Result<()> {
unsafe {
if let Some(n) = len {
try!(Error::check(curses::chgat(n as c_int, 0, pair as c_short, ptr::null())));
}
else {
try!(Error::check(curses::chgat(-1, 0, pair as c_short, ptr::null())));
}
Ok(())
}
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {failure::Error, fidl_fuchsia_mem::Buffer, fuchsia_zircon as zx};
/// Converts a module_path into a string.
/// Example: ["abc", "1:2"] -> "abc:1\:2"
pub fn encoded_module_path(module_path: Vec<String>) -> String {
module_path.iter().map(|part| part.replace(":", "\\:")).collect::<Vec<String>>().join(":")
}
/// Converts a transport VMO into a string.
pub fn vmo_buffer_to_string(buffer: Box<Buffer>) -> Result<String, Error> {
let buffer_size = buffer.size;
let buffer_vmo = buffer.vmo;
let mut bytes = vec![0; buffer_size as usize];
buffer_vmo.read(&mut bytes, 0)?;
Ok(String::from_utf8_lossy(&bytes).to_string())
}
/// Converts an impl Into<String> to a VMO buffer.
pub fn string_to_vmo_buffer(content: impl Into<String>) -> Result<Buffer, Error> {
let content_string = content.into();
let data_to_write = content_string.as_bytes();
let vmo = zx::Vmo::create(data_to_write.len() as u64)?;
vmo.write(&data_to_write, 0)?;
Ok(Buffer { vmo, size: data_to_write.len() as u64 })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn string_conversion() -> Result<(), Error> {
let converted_buffer = string_to_vmo_buffer("value")?;
let converted_string = vmo_buffer_to_string(Box::new(converted_buffer))?;
assert_eq!(&converted_string, "value");
Ok(())
}
}
|
// Copyright 2017 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.
//! Type-safe bindings for Zircon threads.
use crate::ok;
use crate::{AsHandleRef, Handle, HandleBased, HandleRef, Status};
use fuchsia_zircon_sys as sys;
/// An object representing a Zircon thread.
///
/// As essentially a subtype of `Handle`, it can be freely interconverted.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct Thread(Handle);
impl_handle_based!(Thread);
impl Thread {
/// Cause the thread to begin execution.
///
/// Wraps the
/// [zx_thread_start](https://fuchsia.googlesource.com/fuchsia/+/master/docs/zircon/syscalls/thread_start.md)
/// syscall.
pub fn start(
&self,
thread_entry: usize,
stack: usize,
arg1: usize,
arg2: usize,
) -> Result<(), Status> {
let thread_raw = self.raw_handle();
let status = unsafe { sys::zx_thread_start(thread_raw, thread_entry, stack, arg1, arg2) };
ok(status)
}
/// Terminate the current running thread.
///
/// Extreme caution should be used-- this is basically always UB in Rust.
/// There's almost no "normal" program code where this is okay to call.
/// Users should take care that no references could possibly exist to
/// stack variables on this thread, and that any destructors, closure
/// suffixes, or other "after this thing runs" code is waiting to run
/// in order for safety.
pub unsafe fn exit() {
sys::zx_thread_exit()
}
}
|
//! 线程 [`Thread`]
use super::*;
use core::hash::{Hash, Hasher};
/// 线程 ID 使用 `isize`,可以用负数表示错误
pub type ThreadID = isize;
/// 线程计数器,用于设置线程 ID
static mut THREAD_COUNTER: ThreadID = 0;
/// 线程的信息
pub struct Thread {
/// 线程 ID
pub id: ThreadID, // 用于唯一确认一个线程,它会在系统调用等时刻用到。
/// 线程的栈
pub stack: Range<VirtualAddress>, // 运行栈:每个线程都必须有一个独立的运行栈,保存运行时数据。这里只是记录栈的地址区间
/// 所属的进程,使用 引用计数 增加安全性
pub process: Arc<Process>, // 所属进程的记号:同一个进程中的多个线程,会共享页表、打开文件等信息。因此,我们将它们提取出来放到线程中。
/// 用 `Mutex` 包装一些可变的变量
pub inner: Mutex<ThreadInner>, // 因为线程一般使用 Arc<Thread> 来保存,它是不可变的,所以其中再用 Mutex 来包装一部分,让这部分可以修改。
}
/// 线程中需要可变的部分
pub struct ThreadInner {
/// 线程执行上下文
/// 当线程不在执行时,我们需要保存其上下文(其实就是一堆寄存器的值),这样之后才能够将其恢复
/// 当且仅当线程被暂停执行时,`context` 为 `Some`
pub context: Option<Context>,
/// 是否进入休眠
pub sleeping: bool,
/// 是否已经结束
pub dead: bool,
/// priority, 用于Stride Scheduling 调度算法
pub priority: usize,
}
// 单个线程级的操作
impl Thread {
/// 准备执行一个线程
/// 启动一个线程除了需要 Context,还需要切换页表
/// 激活对应进程的页表,将 Context 放至内核栈顶,并返回其 Context
/// 页表的切换不会影响OS运行,因为在中断期间是操作系统正在执行,而操作系统所用到的内核线性映射是存在于每个页表中的。
/// 进一步说,每一个进程的 MemorySet 都会映射操作系统的空间,否则在遇到中断的时候,将无法执行异常处理。
pub fn prepare(&self) -> *mut Context {
// 激活页表,换入新线程的页表
self.process.inner().memory_set.activate();
// 取出 Context
let parked_frame = self.inner().context.take().unwrap();
// 将 Context 放至内核栈顶 (压栈),之后会返回到 __restore 中,完成切换上下文并跳到线程入口
unsafe { KERNEL_STACK.push_context(parked_frame) }
}
/// 发生时钟中断后暂停线程,保存当前线程的 `Context`
pub fn park(&self, context: Context) {
// 检查目前线程内的 context 应当为 None
assert!(self.inner().context.is_none());
// 将 Context 保存到线程中
self.inner().context.replace(context);
}
/// 创建一个线程
pub fn new(
process: Arc<Process>, // 占用process所有权
entry_point: usize,
arguments: Option<&[usize]>,
priority: usize,
) -> MemoryResult<Arc<Thread>> {
// 让 所属进程 分配一段连续虚拟空间并映射一段物理空间,作为线程的栈
// 也就是,线程时资源的使用者,该资源从进程那里获取,进程并不会使用这些资源,而只是向操作系统索取。
// 页面段的权限包括: Flags::READABLE(R), Flags::WRITABLE(W). 以及 process 是否是用户态进程(U)
let stack = process.alloc_page_range(STACK_SIZE, Flags::READABLE | Flags::WRITABLE)?;
// 构建线程的 Context, 包括 sepc 设置为entry_point,sp设为stack.end.into()(即线程栈顶), 压入参数arguments(<8个), sstatus的spp位 = is_user
let context = Context::new(stack.end.into(), entry_point, arguments, process.is_user);
// 打包成线程
let thread = Arc::new(Thread {
id: unsafe {
THREAD_COUNTER += 1;
THREAD_COUNTER
},
stack, // 线程栈
process, // 所属进程
inner: Mutex::new(ThreadInner {
context: Some(context), // 上下文
sleeping: false, // 非休眠
dead: false, // 非kill
priority: priority,
}),
});
Ok(thread)
}
/// 上锁并获得可变部分 ThreadInner 的引用
pub fn inner(&self) -> spin::MutexGuard<ThreadInner> {
self.inner.lock()
}
/// fork
/// fork 后应当为目前的线程复制一份几乎一样的拷贝,新线程与旧线程同属一个进程,公用页表和大部分内存空间,而新线程的栈是一份拷贝。
pub fn fork(&self, current_context: Context) -> MemoryResult<Arc<Thread>> {
// 让所属进程分配并映射一段空间,作为线程的栈
let stack = self.process.alloc_page_range(STACK_SIZE, Flags::READABLE | Flags::WRITABLE)?;
// 新线程的栈是原先线程栈的拷贝 (原样复制)
for i in 0..STACK_SIZE {
*VirtualAddress(stack.start.0 + i).deref::<u8>() = *VirtualAddress(self.stack.start.0 + i).deref::<u8>()
}
// 构建线程的 Context, 包括 sepc 设置为entry_point,sp设为stack.end.into()(即线程栈顶), 压入参数arguments(<8个), sstatus的spp位 = is_user
let mut context = current_context.clone();
// sp 指向新线程的上下文
context.set_sp( usize::from(stack.start) - usize::from(self.stack.start) + current_context.sp() );
// 打包成线程
let thread = Arc::new(Thread {
id: unsafe {
THREAD_COUNTER += 1;
THREAD_COUNTER
},
stack, // 线程栈
process: Arc::clone(&self.process), // 所属进程
inner: Mutex::new(ThreadInner {
context: Some(context), // 上下文
sleeping: false, // 非休眠
dead: false, // 非kill
priority: self.inner().priority.clone(),
}),
});
Ok(thread)
}
}
/// 通过线程 ID 来判等
impl PartialEq for Thread {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
/// 通过线程 ID 来判等
///
/// 在 Rust 中,[`PartialEq`] trait 不要求任意对象 `a` 满足 `a == a`。
/// 将类型标注为 [`Eq`],会沿用 `PartialEq` 中定义的 `eq()` 方法,
/// 同时声明对于任意对象 `a` 满足 `a == a`。
impl Eq for Thread {}
/// 通过线程 ID 来哈希
impl Hash for Thread {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_isize(self.id);
}
}
/// 打印线程除了父进程以外的信息
impl core::fmt::Debug for Thread {
fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter
.debug_struct("Thread")
.field("thread_id", &self.id)
.field("stack", &self.stack)
.field("context", &self.inner().context)
.finish()
}
}
|
#[doc = "Reader of register MACTxTSSSR"]
pub type R = crate::R<u32, super::MACTXTSSSR>;
#[doc = "Reader of field `TXTSSHI`"]
pub type TXTSSHI_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - Transmit Timestamp Status High"]
#[inline(always)]
pub fn txtsshi(&self) -> TXTSSHI_R {
TXTSSHI_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
use libc;
use crate::x::*;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct chashdatum {
pub data: *mut libc::c_void,
pub len: libc::c_uint,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct chash {
pub size: libc::c_uint,
pub count: libc::c_uint,
pub copyvalue: libc::c_int,
pub copykey: libc::c_int,
pub cells: *mut *mut chashcell,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct chashcell {
pub func: libc::c_uint,
pub key: chashdatum,
pub value: chashdatum,
pub next: *mut chashcell,
}
pub type chashiter = chashcell;
/* Allocates a new (empty) hash using this initial size and the given flags,
specifying which data should be copied in the hash.
CHASH_COPYNONE : Keys/Values are not copied.
CHASH_COPYKEY : Keys are dupped and freed as needed in the hash.
CHASH_COPYVALUE : Values are dupped and freed as needed in the hash.
CHASH_COPYALL : Both keys and values are dupped in the hash.
*/
pub unsafe fn chash_new(mut size: libc::c_uint, mut flags: libc::c_int) -> *mut chash {
let mut h: *mut chash = 0 as *mut chash;
h = malloc(::std::mem::size_of::<chash>() as libc::size_t) as *mut chash;
if h.is_null() {
return 0 as *mut chash;
}
if size < 13i32 as libc::c_uint {
size = 13i32 as libc::c_uint
}
(*h).count = 0i32 as libc::c_uint;
(*h).cells = calloc(
size as libc::size_t,
::std::mem::size_of::<*mut chashcell>() as libc::size_t,
) as *mut *mut chashcell;
if (*h).cells.is_null() {
free(h as *mut libc::c_void);
return 0 as *mut chash;
}
(*h).size = size;
(*h).copykey = flags & 1i32;
(*h).copyvalue = flags & 2i32;
return h;
}
/* Frees a hash */
pub unsafe fn chash_free(mut hash: *mut chash) {
let mut indx: libc::c_uint = 0;
let mut iter: *mut chashiter = 0 as *mut chashiter;
let mut next: *mut chashiter = 0 as *mut chashiter;
indx = 0i32 as libc::c_uint;
while indx < (*hash).size {
iter = *(*hash).cells.offset(indx as isize);
while !iter.is_null() {
next = (*iter).next;
if 0 != (*hash).copykey {
free((*iter).key.data);
}
if 0 != (*hash).copyvalue {
free((*iter).value.data);
}
free(iter as *mut libc::c_void);
iter = next
}
indx = indx.wrapping_add(1)
}
free((*hash).cells as *mut libc::c_void);
free(hash as *mut libc::c_void);
}
/* Removes all elements from a hash */
pub unsafe fn chash_clear(mut hash: *mut chash) {
let mut indx: libc::c_uint = 0;
let mut iter: *mut chashiter = 0 as *mut chashiter;
let mut next: *mut chashiter = 0 as *mut chashiter;
indx = 0i32 as libc::c_uint;
while indx < (*hash).size {
iter = *(*hash).cells.offset(indx as isize);
while !iter.is_null() {
next = (*iter).next;
if 0 != (*hash).copykey {
free((*iter).key.data);
}
if 0 != (*hash).copyvalue {
free((*iter).value.data);
}
free(iter as *mut libc::c_void);
iter = next
}
indx = indx.wrapping_add(1)
}
memset(
(*hash).cells as *mut libc::c_void,
0i32,
((*hash).size as libc::size_t)
.wrapping_mul(::std::mem::size_of::<*mut chashcell>() as libc::size_t),
);
(*hash).count = 0i32 as libc::c_uint;
}
/* Adds an entry in the hash table.
Length can be 0 if key/value are strings.
If an entry already exists for this key, it is replaced, and its value
is returned. Otherwise, the data pointer will be NULL and the length
field be set to TRUE or FALSe to indicate success or failure. */
pub unsafe fn chash_set(
mut hash: *mut chash,
mut key: *mut chashdatum,
mut value: *mut chashdatum,
mut oldvalue: *mut chashdatum,
) -> libc::c_int {
let mut current_block: u64;
let mut func: libc::c_uint = 0;
let mut indx: libc::c_uint = 0;
let mut iter: *mut chashiter = 0 as *mut chashiter;
let mut cell: *mut chashiter = 0 as *mut chashiter;
let mut r: libc::c_int = 0;
if (*hash).count > (*hash).size.wrapping_mul(3i32 as libc::c_uint) {
r = chash_resize(
hash,
(*hash)
.count
.wrapping_div(3i32 as libc::c_uint)
.wrapping_mul(2i32 as libc::c_uint)
.wrapping_add(1i32 as libc::c_uint),
);
if r < 0i32 {
current_block = 17701753836843438419;
} else {
current_block = 7095457783677275021;
}
} else {
current_block = 7095457783677275021;
}
match current_block {
7095457783677275021 => {
func = chash_func((*key).data as *const libc::c_char, (*key).len);
indx = func.wrapping_rem((*hash).size);
iter = *(*hash).cells.offset(indx as isize);
loop {
if iter.is_null() {
current_block = 17788412896529399552;
break;
}
if (*iter).key.len == (*key).len
&& (*iter).func == func
&& 0 == memcmp((*iter).key.data, (*key).data, (*key).len as libc::size_t)
{
/* found, replacing entry */
if 0 != (*hash).copyvalue {
let mut data: *mut libc::c_char = 0 as *mut libc::c_char;
data = chash_dup((*value).data, (*value).len);
if data.is_null() {
current_block = 17701753836843438419;
break;
}
free((*iter).value.data);
(*iter).value.data = data as *mut libc::c_void;
(*iter).value.len = (*value).len
} else {
if !oldvalue.is_null() {
(*oldvalue).data = (*iter).value.data;
(*oldvalue).len = (*iter).value.len
}
(*iter).value.data = (*value).data;
(*iter).value.len = (*value).len
}
if 0 == (*hash).copykey {
(*iter).key.data = (*key).data
}
if !oldvalue.is_null() {
(*oldvalue).data = (*value).data;
(*oldvalue).len = (*value).len
}
return 0i32;
} else {
iter = (*iter).next
}
}
match current_block {
17701753836843438419 => {}
_ => {
if !oldvalue.is_null() {
(*oldvalue).data = 0 as *mut libc::c_void;
(*oldvalue).len = 0i32 as libc::c_uint
}
cell = malloc(::std::mem::size_of::<chashcell>() as libc::size_t)
as *mut chashcell;
if !cell.is_null() {
if 0 != (*hash).copykey {
(*cell).key.data =
chash_dup((*key).data, (*key).len) as *mut libc::c_void;
if (*cell).key.data.is_null() {
current_block = 4267898785354516004;
} else {
current_block = 7226443171521532240;
}
} else {
(*cell).key.data = (*key).data;
current_block = 7226443171521532240;
}
match current_block {
7226443171521532240 => {
(*cell).key.len = (*key).len;
if 0 != (*hash).copyvalue {
(*cell).value.data =
chash_dup((*value).data, (*value).len) as *mut libc::c_void;
if (*cell).value.data.is_null() {
if 0 != (*hash).copykey {
free((*cell).key.data);
}
current_block = 4267898785354516004;
} else {
current_block = 6717214610478484138;
}
} else {
(*cell).value.data = (*value).data;
current_block = 6717214610478484138;
}
match current_block {
4267898785354516004 => {}
_ => {
(*cell).value.len = (*value).len;
(*cell).func = func;
(*cell).next = *(*hash).cells.offset(indx as isize);
let ref mut fresh0 = *(*hash).cells.offset(indx as isize);
*fresh0 = cell;
(*hash).count = (*hash).count.wrapping_add(1);
return 0i32;
}
}
}
_ => {}
}
free(cell as *mut libc::c_void);
}
}
}
}
_ => {}
}
return -1i32;
}
#[inline]
unsafe fn chash_dup(mut data: *const libc::c_void, mut len: libc::c_uint) -> *mut libc::c_char {
let mut r: *mut libc::c_void = 0 as *mut libc::c_void;
r = malloc(len as libc::size_t) as *mut libc::c_char as *mut libc::c_void;
if r.is_null() {
return 0 as *mut libc::c_char;
}
memcpy(r, data, len as libc::size_t);
return r as *mut libc::c_char;
}
#[inline]
unsafe fn chash_func(mut key: *const libc::c_char, mut len: libc::c_uint) -> libc::c_uint {
let mut c: libc::c_uint = 5381i32 as libc::c_uint;
let mut k: *const libc::c_char = key;
loop {
let fresh1 = len;
len = len.wrapping_sub(1);
if !(0 != fresh1) {
break;
}
let fresh2 = k;
k = k.offset(1);
c = (c << 5i32)
.wrapping_add(c)
.wrapping_add(*fresh2 as libc::c_uint)
}
return c;
}
/* Resizes the hash table to the passed size. */
pub unsafe fn chash_resize(mut hash: *mut chash, mut size: libc::c_uint) -> libc::c_int {
let mut cells: *mut *mut chashcell = 0 as *mut *mut chashcell;
let mut indx: libc::c_uint = 0;
let mut nindx: libc::c_uint = 0;
let mut iter: *mut chashiter = 0 as *mut chashiter;
let mut next: *mut chashiter = 0 as *mut chashiter;
if (*hash).size == size {
return 0i32;
}
cells = calloc(
size as libc::size_t,
::std::mem::size_of::<*mut chashcell>() as libc::size_t,
) as *mut *mut chashcell;
if cells.is_null() {
return -1i32;
}
indx = 0i32 as libc::c_uint;
while indx < (*hash).size {
iter = *(*hash).cells.offset(indx as isize);
while !iter.is_null() {
next = (*iter).next;
nindx = (*iter).func.wrapping_rem(size);
(*iter).next = *cells.offset(nindx as isize);
let ref mut fresh3 = *cells.offset(nindx as isize);
*fresh3 = iter;
iter = next
}
indx = indx.wrapping_add(1)
}
free((*hash).cells as *mut libc::c_void);
(*hash).size = size;
(*hash).cells = cells;
return 0i32;
}
/* Retrieves the data associated to the key if it is found in the hash table.
The data pointer and the length will be NULL if not found*/
pub unsafe fn chash_get(
mut hash: *mut chash,
mut key: *mut chashdatum,
mut result: *mut chashdatum,
) -> libc::c_int {
let mut func: libc::c_uint = 0;
let mut iter: *mut chashiter = 0 as *mut chashiter;
func = chash_func((*key).data as *const libc::c_char, (*key).len);
iter = *(*hash)
.cells
.offset(func.wrapping_rem((*hash).size) as isize);
while !iter.is_null() {
if (*iter).key.len == (*key).len
&& (*iter).func == func
&& 0 == memcmp((*iter).key.data, (*key).data, (*key).len as libc::size_t)
{
*result = (*iter).value;
return 0i32;
}
iter = (*iter).next
}
return -1i32;
}
/* Removes the entry associated to this key if it is found in the hash table,
and returns its contents if not dupped (otherwise, pointer will be NULL
and len TRUE). If entry is not found both pointer and len will be NULL. */
pub unsafe fn chash_delete(
mut hash: *mut chash,
mut key: *mut chashdatum,
mut oldvalue: *mut chashdatum,
) -> libc::c_int {
/* chashdatum result = { NULL, TRUE }; */
let mut func: libc::c_uint = 0;
let mut indx: libc::c_uint = 0;
let mut iter: *mut chashiter = 0 as *mut chashiter;
let mut old: *mut chashiter = 0 as *mut chashiter;
func = chash_func((*key).data as *const libc::c_char, (*key).len);
indx = func.wrapping_rem((*hash).size);
old = 0 as *mut chashiter;
iter = *(*hash).cells.offset(indx as isize);
while !iter.is_null() {
if (*iter).key.len == (*key).len
&& (*iter).func == func
&& 0 == memcmp((*iter).key.data, (*key).data, (*key).len as libc::size_t)
{
if !old.is_null() {
(*old).next = (*iter).next
} else {
let ref mut fresh4 = *(*hash).cells.offset(indx as isize);
*fresh4 = (*iter).next
}
if 0 != (*hash).copykey {
free((*iter).key.data);
}
if 0 != (*hash).copyvalue {
free((*iter).value.data);
} else if !oldvalue.is_null() {
(*oldvalue).data = (*iter).value.data;
(*oldvalue).len = (*iter).value.len
}
free(iter as *mut libc::c_void);
(*hash).count = (*hash).count.wrapping_sub(1);
return 0i32;
}
old = iter;
iter = (*iter).next
}
return -1i32;
}
/* Returns an iterator to the first non-empty entry of the hash table */
pub unsafe fn chash_begin(mut hash: *mut chash) -> *mut chashiter {
let mut iter: *mut chashiter = 0 as *mut chashiter;
let mut indx: libc::c_uint = 0i32 as libc::c_uint;
iter = *(*hash).cells.offset(0isize);
while iter.is_null() {
indx = indx.wrapping_add(1);
if indx >= (*hash).size {
return 0 as *mut chashiter;
}
iter = *(*hash).cells.offset(indx as isize)
}
return iter;
}
/* Returns the next non-empty entry of the hash table */
pub unsafe fn chash_next(mut hash: *mut chash, mut iter: *mut chashiter) -> *mut chashiter {
let mut indx: libc::c_uint = 0;
if iter.is_null() {
return 0 as *mut chashiter;
}
indx = (*iter).func.wrapping_rem((*hash).size);
iter = (*iter).next;
while iter.is_null() {
indx = indx.wrapping_add(1);
if indx >= (*hash).size {
return 0 as *mut chashiter;
}
iter = *(*hash).cells.offset(indx as isize)
}
return iter;
}
|
#![deny(missing_docs)]
//! Coi-derive simplifies implementing the traits provided in the [coi] crate.
//!
//! [coi]: https://docs.rs/coi
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, DeriveInput, Error};
mod attr;
mod ctxt;
mod symbol;
use crate::attr::Container;
use crate::ctxt::Ctxt;
/// Generates an impl for `Inject` and also generates a "Provider" struct with its own
/// `Provide` impl.
///
/// This derive proc macro impls `Inject` on the struct it modifies, and also processes #[coi(...)]
/// attributes:
/// - `#[coi(provides ...)]` - It takes the form
/// ```rust,ignore
/// #[coi(provides <vis> <ty> with <expr>)]
/// ```
/// or the form
/// ```rust,ignore
/// #[coi(provides <vis> <ty> as <name> with <expr>)]
/// ```
/// The latter form *must* be used when generating multiple providers for a single type. This might
/// be useful if you have multiple trait implementations for one struct and want to provide separate
/// unique instances for each trait in the container. That use case might be more common with mocks
/// in unit tests rather than in production code.
///
/// It generates a provider struct with visibility `<vis>`
/// that impls `Provide` with an output type of `Arc<<ty>>`. It will construct `<ty>` with `<expr>`,
/// and all params to `<expr>` must match the struct fields marked with `#[coi(inject)]` (see the
/// next bullet item). `<vis>` must match the visibility of `<ty>` or you will get code that might
/// not compile. If `<name>` is not provided, the struct name will be used and `Provider` will be
/// appended to it.
/// - `#[coi(inject)]` - All fields marked `#[coi(inject)]` are resolved in the `provide` fn
/// described above.
/// Given a field `<field_name>: <field_ty>`, this attribute will cause the following resolution to
/// be generated:
/// ```rust,ignore
/// let <field_name> = Container::resolve::<<field_ty>>(container, "<field_name>");
/// ```
/// Because of this, it's important that the field name *must* match the string that's used to
/// register the provider in the `ContainerBuilder`.
///
/// ## Examples
///
/// Private trait and no dependencies
/// ```rust
/// use coi::Inject;
/// # use coi_derive::Inject;
/// trait Priv: Inject {}
///
/// #[derive(Inject)]
/// #[coi(provides dyn Priv with SimpleStruct)]
/// # pub
/// struct SimpleStruct;
///
/// impl Priv for SimpleStruct {}
/// ```
///
/// Public trait and dependency
/// ```rust
/// use coi::Inject;
/// # use coi_derive::Inject;
/// use std::sync::Arc;
/// pub trait Pub: Inject {}
/// pub trait Dependency: Inject {}
///
/// #[derive(Inject)]
/// #[coi(provides pub dyn Pub with NewStruct::new(dependency))]
/// # pub
/// struct NewStruct {
/// #[coi(inject)]
/// dependency: Arc<dyn Dependency>,
/// }
///
/// impl NewStruct {
/// fn new(dependency: Arc<dyn Dependency>) -> Self {
/// Self {
/// dependency
/// }
/// }
/// }
///
/// impl Pub for NewStruct {}
/// ```
///
/// Struct injection
/// ```rust
/// use coi::Inject;
/// # use coi_derive::Inject;
///
/// #[derive(Inject)]
/// #[coi(provides pub InjectableStruct with InjectableStruct)]
/// # pub
/// struct InjectableStruct;
/// ```
///
/// Unnamed fields
/// ```rust
/// use coi::Inject;
/// # use coi_derive::Inject;
/// use std::sync::Arc;
///
/// #[derive(Inject)]
/// #[coi(provides Dep1 with Dep1)]
/// struct Dep1;
///
/// #[derive(Inject)]
/// #[coi(provides Impl1 with Impl1(dep1))]
/// struct Impl1(#[coi(inject = "dep1")] Arc<Dep1>);
/// ```
///
/// Generics
/// ```rust
/// use coi::{container, Inject};
/// # use coi_derive::Inject;
///
/// #[derive(Inject)]
/// #[coi(provides Impl1<T> with Impl1::<T>::new())]
/// struct Impl1<T>(T)
/// where
/// T: Default;
///
/// impl<T> Impl1<T>
/// where
/// T: Default,
/// {
/// fn new() -> Self {
/// Self(Default::default())
/// }
/// }
///
/// fn build_container() {
/// // Take note that these providers have to be constructed
/// // with explicit types.
/// let impl1_provider = Impl1Provider::<bool>::new();
/// let container = container! {
/// impl1 => impl1_provider,
/// };
/// let _bool_impl = container
/// .resolve::<Impl1<bool>>("impl1")
/// .expect("Should exist");
/// }
///
/// # build_container();
/// ```
///
/// If you need some form of constructor fn that takes arguments that are not injected, then you
/// might be able to use the [`coi::Provide`] derive. If that doesn't fit your use case, you'll
/// need to manually implement `Provide`.
///
/// [`coi::Provide`]: derive.Provide.html
#[proc_macro_derive(Inject, attributes(coi))]
pub fn inject_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let cx = Ctxt::new();
let container = Container::from_ast(&cx, &input, true);
if let Err(e) = cx.check() {
return to_compile_errors(e).into();
}
let container = container.unwrap();
let has_generics = !input.generics.params.is_empty();
let generic_params = input.generics.params;
let generics = if has_generics {
quote! {
<#generic_params>
}
} else {
quote! {}
};
let coi = container.coi_path();
let where_clause = input
.generics
.where_clause
.map(|w| {
let t: Vec<_> = generic_params.iter().collect();
quote! { #w #(, #t: Send + Sync + 'static )* }
})
.unwrap_or_default();
if container.providers.is_empty() {
let ident = input.ident;
return quote! {
impl #generics #coi::Inject for #ident #generics #where_clause {}
}
.into();
}
let container_ident = format_ident!(
"{}",
if container.injected.is_empty() {
"_"
} else {
"container"
}
);
let (resolve, keys): (Vec<_>, Vec<_>) = container
.injected
.into_iter()
.map(|field| {
let ident = field.name;
let ty = field.ty;
let key = format!("{}", ident);
(
quote! {
let #ident = #container_ident.resolve::<#ty>(#key)?;
},
key,
)
})
.unzip();
let input_ident = input.ident;
let dependencies_fn = if cfg!(feature = "debug") {
vec![quote! {
fn dependencies(&self) -> &'static[&'static str] {
&[
#( #keys, )*
]
}
}]
} else {
vec![]
};
let provider_fields = if has_generics {
let tys: Vec<_> = generic_params.iter().cloned().collect();
quote! {
(
#( ::std::marker::PhantomData<#tys> )*
)
}
} else {
quote! {}
};
let phantom_data: Vec<_> = generic_params
.iter()
.map(|_| quote! {::std::marker::PhantomData})
.collect();
let provider_impls = if !phantom_data.is_empty() {
container
.providers
.iter()
.map(|p| {
let provider = p.name_or(&input_ident);
let vis = &p.vis;
quote! {
impl #generics #provider #generics #where_clause {
#vis fn new() -> Self {
Self(#( #phantom_data )*)
}
}
}
})
.collect()
} else {
vec![]
};
let constructed_provides: Vec<_> = container
.providers
.into_iter()
.map(|p| {
let provider = p.name_or(&input_ident);
let vis = p.vis;
let ty = p.ty;
let provides_with = p.with;
quote! {
#vis struct #provider #generics #provider_fields #where_clause;
impl #generics #coi::Provide for #provider #generics #where_clause {
type Output = #ty;
fn provide(
&self,
#container_ident: &#coi::Container,
) -> #coi::Result<::std::sync::Arc<Self::Output>> {
#( #resolve )*
Ok(::std::sync::Arc::new(#provides_with) as ::std::sync::Arc<#ty>)
}
#( #dependencies_fn )*
}
}
})
.collect();
let expanded = quote! {
impl #generics #coi::Inject for #input_ident #generics #where_clause {}
#( #provider_impls )*
#( #constructed_provides )*
};
TokenStream::from(expanded)
}
/// Generates an impl for `Provide` and also generates a "Provider" struct with its own
/// `Provide` impl.
///
/// This derive proc macro impls `Provide` on the struct it modifies, and also processes #[coi(...)]
/// attributes:
/// - `#[coi(provides ...)]` - It takes the form
/// ```rust,ignore
/// #[coi(provides <vis> <ty> with <expr>)]
/// ```
///
/// Multiple `provides` attributes are not allowed since this is for a specific `Provide` impl and
/// not for the resolved type.
///
/// It generates a provider struct with visibility `<vis>`
/// that impls `Provide` with an output type of `Arc<<ty>>`. It will construct `<ty>` with `<expr>`,
/// and all params to `<expr>` must match the struct fields marked with `#[coi(inject)]` (see the
/// next bullet item). `<vis>` must match the visibility of `<ty>` or you will get code that might
/// not compile. If `<name>` is not provided, the struct name will be used and `Provider` will be
/// appended to it.
///
/// ## Examples
///
/// Private trait and no dependencies
/// ```rust
/// use coi::{Inject, Provide};
/// # use coi_derive::{Inject, Provide};
/// trait Priv: Inject {}
///
/// #[derive(Inject)]
/// # pub
/// struct SimpleStruct {
/// data: u32
/// }
///
/// impl SimpleStruct {
/// fn new(data: u32) -> Self {
/// Self { data }
/// }
/// }
///
/// impl Priv for SimpleStruct {}
///
/// #[derive(Provide)]
/// #[coi(provides dyn Priv with SimpleStruct::new(self.data))]
/// struct SimpleStructProvider {
/// data: u32,
/// }
///
/// impl SimpleStructProvider {
/// fn new(data: u32) -> Self {
/// Self { data: 42 }
/// }
/// }
/// ```
#[proc_macro_derive(Provide, attributes(coi))]
pub fn provide_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let cx = Ctxt::new();
let container = Container::from_ast(&cx, &input, false);
if let Err(e) = cx.check() {
return to_compile_errors(e).into();
}
let container = container.unwrap();
let provider = input.ident.clone();
let has_generics = !input.generics.params.is_empty();
let generic_params = input.generics.params;
let generics = if has_generics {
quote! {
<#generic_params>
}
} else {
quote! {}
};
let where_clause = input
.generics
.where_clause
.map(|w| {
let t: Vec<_> = generic_params.iter().collect();
quote! { #w #(, #t: Send + Sync + 'static )* }
})
.unwrap_or_default();
let dependencies_fn = if cfg!(feature = "debug") {
vec![{
quote! {
fn dependencies(
&self
) -> &'static [&'static str] {
&[]
}
}
}]
} else {
vec![]
};
let coi = container.coi_path();
let expanded: Vec<_> = container
.providers
.into_iter()
.map(|p| {
let ty = p.ty;
let provides_with = p.with;
quote! {
impl #generics #coi::Provide for #provider #generics #where_clause {
type Output = #ty;
fn provide(
&self,
_: &#coi::Container,
) -> #coi::Result<::std::sync::Arc<Self::Output>> {
Ok(::std::sync::Arc::new(#provides_with) as ::std::sync::Arc<#ty>)
}
#( #dependencies_fn )*
}
}
})
.collect();
TokenStream::from(quote! {
#( #expanded )*
})
}
fn to_compile_errors(errors: Vec<Error>) -> proc_macro2::TokenStream {
let compile_errors = errors.iter().map(Error::to_compile_error);
quote!(#(#compile_errors)*)
}
|
pub use self::arch::*;
#[cfg(target_arch = "x86_64")]
#[path = "x86_64.rs"]
mod arch;
|
pub fn sort(a: &mut Vec<i32>, size: usize) {
for j in 1..size {
let mut i = (j - 1) as i32;
while i >= 0 && a[i as usize] > a[j] {
a[(i + 1) as usize] = a[i as usize];
i -= 1
}
a[(i + 1) as usize] = a[j]
}
}
|
use swc_atoms::JsWord;
use swc_common::Mark;
use swc_ecma_ast::*;
use swc_ecma_visit::{Fold, FoldWith, Node, Visit, VisitWith};
/// Used to rename **binding** identifiers in constructor.
pub(super) struct UsedNameRenamer<'a> {
pub mark: Mark,
pub used_names: &'a [JsWord],
}
noop_fold_type!(UsedNameRenamer<'_>);
impl<'a> Fold for UsedNameRenamer<'a> {
fn fold_expr(&mut self, e: Expr) -> Expr {
match e {
Expr::Ident(..) => e,
_ => e.fold_children_with(self),
}
}
fn fold_ident(&mut self, ident: Ident) -> Ident {
if self.used_names.contains(&ident.sym) {
return Ident {
span: ident.span.apply_mark(self.mark),
..ident
};
}
ident
}
fn fold_member_expr(&mut self, e: MemberExpr) -> MemberExpr {
if e.computed {
MemberExpr {
obj: e.obj.fold_with(self),
prop: e.prop.fold_with(self),
..e
}
} else {
MemberExpr {
obj: e.obj.fold_with(self),
..e
}
}
}
}
pub(super) struct UsedNameCollector<'a> {
pub used_names: &'a mut Vec<JsWord>,
}
noop_visit_type!(UsedNameCollector<'_>);
macro_rules! noop {
($name:ident, $T:path) => {
/// no-op
fn $name(&mut self, _: &$T, _: &dyn Node) {}
};
}
impl<'a> Visit for UsedNameCollector<'a> {
noop!(visit_arrow_expr, ArrowExpr);
noop!(visit_function, Function);
noop!(visit_setter_prop, SetterProp);
noop!(visit_getter_prop, GetterProp);
noop!(visit_method_prop, MethodProp);
noop!(visit_constructor, Constructor);
fn visit_expr(&mut self, expr: &Expr, _: &dyn Node) {
match *expr {
Expr::Ident(ref i) => self.used_names.push(i.sym.clone()),
_ => expr.visit_children_with(self),
}
}
}
|
pub mod decompressor;
pub mod fixup_converter;
pub mod neexe;
pub mod util;
|
use std::env;
use getopts::Options;
use dirs::config_dir;
use hm::config::Config;
use hm::fetcher::LinkFetcher;
use hm::http::CurlHttp;
use hm::viewer::Viewer;
use std::fs::File;
use std::path::PathBuf;
use std::sync::{mpsc, Arc};
use hm::parser::Links;
use hm::display::LinksRepr;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optopt("q",
"query",
"perform a search, list results and exit",
"QUERY",
);
opts.optopt("c", "config", "config file location", "PATH");
opts.optflag("h", "help", "show this help");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
if matches.opt_present("h") {
print!("{}", opts.usage("Usage: hm [options]"));
return;
}
let path_arg: Result<Option<PathBuf>, _> = matches.opt_get("c");
let config_path = path_arg.ok()
.and_then(|c| c)
.or_else(|| config_dir().map(|d| d.join("hm/config")))
.ok_or_else(|| "Can't get config file".to_string());
let config = Arc::new(config_path
.and_then(|path| File::open(path).map_err(|e| e.to_string()))
.and_then(Config::from)
.unwrap_or_default());
let (ui_tx, ui_rx) = mpsc::channel();
let (ctrl_tx, ctrl_rx) = mpsc::channel();
if matches.opt_present("q") {
let query_arg: Result<Option<String>, _> = matches.opt_get("q");
match query_arg {
Ok(Some(query)) => {
let http = CurlHttp::new();
let links = LinkFetcher::fetch(&http, query.as_str(), None, &config);
match links {
Ok(Links { ref links, .. }) => {
print!("{}", LinksRepr { links: links.as_slice(), keys: None });
}
Err(e) => {
panic!("{}", e)
//TODO handle error
}
}
}
_ => panic!("Can't parse the argument to option 'q'"),
}
} else {
let viewer_config = Arc::clone(&config);
LinkFetcher::start(config, ctrl_rx, ui_tx);
let mut viewer = Viewer::new(ctrl_tx);
viewer.start(viewer_config, ui_rx);
};
}
|
use std::collections::HashMap;
pub fn lsort<T>(li: &Vec<Vec<T>>) -> Vec<&Vec<T>> {
let mut lengths: Vec<(usize, &Vec<T>)> = li.iter().map(|x| (x.len(), x)).collect();
lengths.sort_by(|a, b| a.0.cmp(&b.0));
lengths.iter().map(|&(_, x)| x).collect()
}
pub fn lsort_freq<T>(li: &Vec<Vec<T>>) -> Vec<&Vec<T>> {
// map of (length -> list of lists)
let length_map = li
.iter()
.fold(HashMap::<usize, Vec<&Vec<T>>>::new(), |mut map, x| {
let e = map.entry(x.len()).or_insert(vec![]);
e.push(x);
map
});
// list of (length, freq) pair
let mut length_freqs: Vec<(&usize, usize)> = length_map
.iter()
.map(|(len, lists)| (len, lists.len()))
.collect();
// sort by length frequency
length_freqs.sort_by(|a, b| a.1.cmp(&b.1));
// make final result
let mut res = vec![];
for (len, _) in length_freqs {
if let Some(lists) = length_map.get(&len) {
res.extend_from_slice(lists);
}
}
res
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lsort() {
let li = vec![
vec!['a', 'b', 'c'],
vec!['d', 'e'],
vec!['f', 'g', 'h'],
vec!['d', 'e'],
vec!['i', 'j', 'k', 'l'],
vec!['m', 'n'],
vec!['o'],
];
let actual = lsort(&li);
assert_eq!(actual[0], &vec!['o']);
assert_eq!(actual[1], &vec!['d', 'e']);
assert_eq!(actual[2], &vec!['d', 'e']);
assert_eq!(actual[3], &vec!['m', 'n']);
assert_eq!(actual[4], &vec!['a', 'b', 'c']);
assert_eq!(actual[5], &vec!['f', 'g', 'h']);
assert_eq!(actual[6], &vec!['i', 'j', 'k', 'l']);
}
#[test]
fn test_lsort_freq() {
let li = vec![
vec!['a', 'b', 'c'],
vec!['d', 'e'],
vec!['f', 'g', 'h'],
vec!['d', 'e'],
vec!['i', 'j', 'k', 'l'],
vec!['m', 'n'],
vec!['o'],
];
let actual = lsort_freq(&li);
assert!(
(actual[0] == &vec!['o'] && actual[1] == &vec!['i', 'j', 'k', 'l'])
|| (actual[0] == &vec!['i', 'j', 'k', 'l'] && actual[1] == &vec!['o'])
);
assert!(
(actual[2] == &vec!['a', 'b', 'c'] && actual[3] == &vec!['f', 'g', 'h'])
|| (actual[2] == &vec!['f', 'g', 'h'] && actual[3] == &vec!['a', 'b', 'c'])
);
assert!(actual[4] == &vec!['d', 'e'] || actual[4] == &vec!['m', 'n']);
assert!(actual[5] == &vec!['d', 'e'] || actual[5] == &vec!['m', 'n']);
assert!(actual[6] == &vec!['d', 'e'] || actual[6] == &vec!['m', 'n']);
}
}
|
// From the previous example, src4.rs, it may seem that defining an iterator that returns mutable references should be as
// easy as replacing each instance of & with &mut. It turns out that this is not the case. The reason it falls down is
// that an object can only have one mutable borrow at any given time whereas we can have as many immutable borrows (references)
// as we want. Below, I simulate the replacement and then discuss how the implementation fails to work.
use std::iter::IntoIterator;
use std::iter::Iterator;
pub struct NewStruct<T> {
field1: T,
field2: T,
field3: T,
field4: T,
field5: T,
}
pub struct NewStructMutRef<'a,T>
where T: 'a {
count: usize,
new_struct: &'a mut NewStruct,
}
impl<'a,T> IntoIterator for &'a mut NewStruct<T>
where T: 'a {
type Item = &'a mut T;
type IntoIter = NewStructMutRef<'a,T>;
fn into_iter( self: Self ) -> NewStructMutRef<'a,T> {
NewStructMutRef {
count: 0 as usize,
new_struct: &'a mut NewStruct,
}
}
}
// So far so good, the issue we run into is the lifetime used by the `next` method
// The following has an incorrect implementation of the Iterator trait that mirrors exactly what we did in the reference (&)
// case.
impl<'a,T> Iterator for NewStructMutRef<'a,T>
where T: 'a {
type Item = &'a mut T;
fn next<'b>( self: &'b mut Self ) -> Option<&'a mut T> {
self.count += 1;
match self.count {
1 => { Some(&mut self.new_struct.field1) },
2 => { Some(&mut self.new_struct.field2) },
3 => { Some(&mut self.new_struct.field3) },
4 => { Some(&mut self.new_struct.field4) },
5 => { Some(&mut self.new_struct.field5) },
_ => { None },
}
}
}
// The compiler will complain that it cannot infer an appropriate lifetime for the borrow expression due to conflicting requirements
// It suggests changing the lifetime parameter 'b to 'a so that `next` looked like the following:
// fn next<'a>( self: &'a mut Self ) -> Option<&'a mut T>
// However, this will not fix the situation for two reasons:
// 1. That is not how the trait is defined so we will get a method incompatible with trait error
// 2. This new form does not describe the semantics that next is supposed to have.
// This form is now saying that the lifetime of the NewStructMutRef is the same as the elements it returns which
// we know is not the case. In particular, the lifetime 'a contains (or outlives) the NewStructMutRef
// The fact that this will not compile seems odd given that the fields of base structure (NewStruct) are disjoint so we
// should be able to borrow them individually. The problem is we don't have the semantics to properly tell the compiler that
// the mutable borrow of the field has a shorter lifetime than the mutable borrow of the NewStructMutRef so it craps out. Even if
// the lifetimes were lifted out of the `next` method and into the trait we would run into the fact that we cannot mutably
// borrow a struct more than once at a time so each call to `next` would cause the compiler to complain that the Iterator
// cannot be borrowed more than once at a time.
// You could circumvent this by using unsafe code and *mut T since there is no explicit lifetime restriction when using
// unsafe pointers.
// An implementation using unsafe pointers is located in src6.rs
|
// Copyright (c) 2018 tomlenv developers
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! `tomlenv` errors
mod codes;
mod sources;
pub(crate) use codes::ErrCode;
use getset::Getters;
pub(crate) use sources::ErrSource;
use std::fmt;
/// A result that must include an `tomlenv::Error`
pub type Result<T> = std::result::Result<T, Error>;
/// An error from the library
#[derive(Debug, Getters)]
#[getset(get = "pub(crate)")]
#[allow(dead_code)]
pub struct Error {
/// the code
code: ErrCode,
/// the reason
reason: String,
/// the description
description: String,
/// the source
source: Option<ErrSource>,
}
impl Error {
pub(crate) fn new<U>(code: ErrCode, reason: U, source: Option<ErrSource>) -> Self
where
U: Into<String>,
{
let reason = reason.into();
let code_str: &str = code.into();
let description = format!("{code_str}: {reason}");
Self {
code,
reason,
description,
source,
}
}
/// Generate an invalid runtime environment error
#[must_use]
pub fn invalid_runtime_environment(env: &str) -> Self {
Self::new(
ErrCode::Env,
format!("invalid runtime environment '{env}'"),
None,
)
}
pub(crate) fn invalid_current_environment(var: &str) -> Self {
Self::new(
ErrCode::Env,
format!("invalid current environment '{var}'"),
None,
)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
if let Some(ref x) = self.source {
Some(x)
} else {
None
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.description)
}
}
impl From<&str> for Error {
fn from(text: &str) -> Self {
let split = text.split(':');
let vec = split.collect::<Vec<&str>>();
let code = vec.first().unwrap_or(&"");
let reason = vec.get(1).unwrap_or(&"");
Self::new((*code).into(), *reason, None)
}
}
impl From<String> for Error {
fn from(text: String) -> Self {
let split = text.split(':');
let vec = split.collect::<Vec<&str>>();
let code = vec.first().unwrap_or(&"");
let reason = vec.get(1).unwrap_or(&"");
Self::new((*code).into(), *reason, None)
}
}
// impl<S> From<<S as TryFrom<String>>::Error> for Error
// where
// S: DeserializeOwned + Serialize + Ord + PartialOrd + TryFrom<String>,
// {
// fn from(_s: S) -> Self {
// Self::new(ErrCode::Env, "", None)
// }
// }
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "System_Diagnostics_DevicePortal")]
pub mod DevicePortal;
#[cfg(feature = "System_Diagnostics_Telemetry")]
pub mod Telemetry;
#[cfg(feature = "System_Diagnostics_TraceReporting")]
pub mod TraceReporting;
#[link(name = "windows")]
extern "system" {}
pub type DiagnosticActionResult = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct DiagnosticActionState(pub i32);
impl DiagnosticActionState {
pub const Initializing: Self = Self(0i32);
pub const Downloading: Self = Self(1i32);
pub const VerifyingTrust: Self = Self(2i32);
pub const Detecting: Self = Self(3i32);
pub const Resolving: Self = Self(4i32);
pub const VerifyingResolution: Self = Self(5i32);
pub const Executing: Self = Self(6i32);
}
impl ::core::marker::Copy for DiagnosticActionState {}
impl ::core::clone::Clone for DiagnosticActionState {
fn clone(&self) -> Self {
*self
}
}
pub type DiagnosticInvoker = *mut ::core::ffi::c_void;
pub type ProcessCpuUsage = *mut ::core::ffi::c_void;
pub type ProcessCpuUsageReport = *mut ::core::ffi::c_void;
pub type ProcessDiagnosticInfo = *mut ::core::ffi::c_void;
pub type ProcessDiskUsage = *mut ::core::ffi::c_void;
pub type ProcessDiskUsageReport = *mut ::core::ffi::c_void;
pub type ProcessMemoryUsage = *mut ::core::ffi::c_void;
pub type ProcessMemoryUsageReport = *mut ::core::ffi::c_void;
pub type SystemCpuUsage = *mut ::core::ffi::c_void;
pub type SystemCpuUsageReport = *mut ::core::ffi::c_void;
pub type SystemDiagnosticInfo = *mut ::core::ffi::c_void;
pub type SystemMemoryUsage = *mut ::core::ffi::c_void;
pub type SystemMemoryUsageReport = *mut ::core::ffi::c_void;
|
extern crate diesel;
extern crate payment_api;
use payment_api::*;
use std::io::{stdin};
fn main() {
let connection = establish_connection();
let mut amount = String::new();
let mut currency = String::new();
let mut name = String::new();
let mut number = String::new();
let mut email = String::new();
let complete = &false;
println!("How much do you want to transfer?");
stdin().read_line(&mut amount).unwrap();
let amount = amount.trim_right(); // Remove the trailing newline
println!("What token do you want to use?");
stdin().read_line(&mut currency).unwrap();
let currency = currency.trim_right(); // Remove the trailing newline
println!("what is their name?");
stdin().read_line(&mut name).unwrap();
let name = name.trim_right(); // Remove the trailing newline
println!("what is their number?");
stdin().read_line(&mut number).unwrap();
let number = number.trim_right(); // Remove the trailing newline
println!("what is their email?");
stdin().read_line(&mut email).unwrap();
let email = email.trim_right(); // Remove the trailing newline
// let transfer = create_transfer(&connection, amount, ¤cy, name, number, email, complete);
println!("\n~~~~ Sent transfer ~~~~~");
println!("Amount: {} {}", amount, currency);
println!("recipient: {}, {}, {}", name, number, email);
// println!("transaction id: {}\n", transfer.id);
}
|
use crate::{
prefab::{Prefab, PrefabComponent, PrefabError, PrefabProxy},
state::StateToken,
};
use oxygengine_ignite_derive::Ignite;
use serde::{Deserialize, Serialize};
use specs::{
world::{EntitiesRes, WorldExt},
Component, DenseVecStorage, Entity, FlaggedStorage, Join, ReadStorage, VecStorage, World,
WriteStorage,
};
use specs_hierarchy::Hierarchy;
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
ops::{Deref, DerefMut},
};
pub fn entity_find_world(name: &str, world: &World) -> Option<Entity> {
let entities = world.read_resource::<EntitiesRes>();
let names = world.read_storage::<Name>();
entity_find_direct(name, &entities, &names)
}
pub fn entity_find_direct<'s>(
name: &str,
entities: &EntitiesRes,
names: &ReadStorage<'s, Name>,
) -> Option<Entity> {
(entities, names)
.join()
.find_map(|(e, n)| if n.0 == name { Some(e) } else { None })
}
pub fn hierarchy_find_world(root: Entity, path: &str, world: &World) -> Option<Entity> {
let hierarchy = world.read_resource::<HierarchyRes>();
let names = world.read_storage::<Name>();
hierarchy_find_direct(root, path, &hierarchy, &names)
}
pub fn hierarchy_find_direct<'s>(
mut root: Entity,
path: &str,
hierarchy: &HierarchyRes,
names: &ReadStorage<'s, Name>,
) -> Option<Entity> {
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
if let Some(parent) = hierarchy.parent(root) {
root = parent;
} else {
return None;
}
}
part => {
let found = hierarchy.children(root).iter().find_map(|child| {
if let Some(name) = names.get(*child) {
if name.0 == part {
Some(child)
} else {
None
}
} else {
None
}
});
if let Some(child) = found {
root = *child;
} else {
return None;
}
}
}
}
Some(root)
}
pub struct ComponentContainer<'a, C>
where
C: Component,
{
entity: Entity,
storage: WriteStorage<'a, C>,
}
impl<'a, C> ComponentContainer<'a, C>
where
C: Component,
{
pub fn new(world: &'a World, entity: Entity) -> Self {
Self {
entity,
storage: world.write_storage::<C>(),
}
}
pub fn get(&self) -> Option<&C> {
self.storage.get(self.entity)
}
pub fn get_mut(&mut self) -> Option<&mut C> {
self.storage.get_mut(self.entity)
}
pub fn unwrap(&self) -> &C {
self.get().unwrap()
}
pub fn unwrap_mut(&mut self) -> &mut C {
self.get_mut().unwrap()
}
}
impl<'a, C> Deref for ComponentContainer<'a, C>
where
C: Component,
{
type Target = C;
fn deref(&self) -> &Self::Target {
if let Some(c) = self.storage.get(self.entity) {
c
} else {
panic!("Could not fetch component: {}", std::any::type_name::<C>());
}
}
}
impl<'a, C> DerefMut for ComponentContainer<'a, C>
where
C: Component,
{
fn deref_mut(&mut self) -> &mut Self::Target {
if let Some(c) = self.storage.get_mut(self.entity) {
c
} else {
panic!(
"Could not fetch mutable component: {}",
std::any::type_name::<C>()
);
}
}
}
pub trait ComponentContainerModify<'a, T> {
fn fetch(world: &'a World, entity: Entity) -> T;
}
impl<'a, C> ComponentContainerModify<'a, ComponentContainer<'a, C>> for C
where
C: Component,
{
fn fetch(world: &'a World, entity: Entity) -> ComponentContainer<'a, C> {
ComponentContainer::<C>::new(world, entity)
}
}
macro_rules! impl_component_container_modify {
( $($ty:ident),* ) => {
impl<'a, $($ty),*> ComponentContainerModify<'a, ( $( ComponentContainer<'a, $ty> , )* )> for ( $( $ty , )* )
where $($ty: Component),*
{
fn fetch(world: &'a World, entity: Entity) -> ( $( ComponentContainer<'a, $ty> , )* ) {
( $( ComponentContainer::<$ty>::new(world, entity), )* )
}
}
};
}
impl_component_container_modify!(A);
impl_component_container_modify!(A, B);
impl_component_container_modify!(A, B, C);
impl_component_container_modify!(A, B, C, D);
impl_component_container_modify!(A, B, C, D, E);
impl_component_container_modify!(A, B, C, D, E, F);
impl_component_container_modify!(A, B, C, D, E, F, G);
impl_component_container_modify!(A, B, C, D, E, F, G, H);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U);
impl_component_container_modify!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V);
impl_component_container_modify!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W
);
impl_component_container_modify!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X
);
impl_component_container_modify!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
impl_component_container_modify!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
);
pub type HierarchyRes = Hierarchy<Parent>;
#[derive(Default)]
pub struct HierarchyChangeRes {
pub(crate) entities: HashSet<Entity>,
pub(crate) added: Vec<Entity>,
pub(crate) removed: Vec<Entity>,
}
impl HierarchyChangeRes {
#[inline]
pub fn added(&self) -> &[Entity] {
&self.added
}
#[inline]
pub fn removed(&self) -> &[Entity] {
&self.removed
}
}
#[derive(Ignite, Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct Parent(pub Entity);
impl Component for Parent {
type Storage = FlaggedStorage<Self, DenseVecStorage<Self>>;
}
impl specs_hierarchy::Parent for Parent {
fn parent_entity(&self) -> Entity {
self.0
}
}
impl PrefabProxy<ParentPrefabProxy> for Parent {
fn from_proxy_with_extras(
proxy: ParentPrefabProxy,
named_entities: &HashMap<String, Entity>,
_: StateToken,
) -> Result<Self, PrefabError> {
if let Some(entity) = named_entities.get(&proxy.0) {
Ok(Self(*entity))
} else {
Err(PrefabError::Custom(format!(
"Could not find entity named: {}",
proxy.0
)))
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ParentPrefabProxy(pub String);
impl Prefab for ParentPrefabProxy {}
#[derive(Ignite, Debug, Default, Clone, Serialize, Deserialize)]
pub struct Tag(pub Cow<'static, str>);
impl Component for Tag {
type Storage = VecStorage<Self>;
}
impl Prefab for Tag {}
impl PrefabComponent for Tag {}
#[derive(Ignite, Debug, Default, Clone, Serialize, Deserialize)]
pub struct Name(pub Cow<'static, str>);
impl Component for Name {
type Storage = VecStorage<Self>;
}
impl Prefab for Name {}
impl PrefabComponent for Name {}
#[derive(Ignite, Debug, Default, Clone, Serialize, Deserialize)]
pub struct NonPersistent(pub StateToken);
impl Component for NonPersistent {
type Storage = VecStorage<Self>;
}
impl PrefabProxy<NonPersistentPrefabProxy> for NonPersistent {
fn from_proxy_with_extras(
_: NonPersistentPrefabProxy,
_: &HashMap<String, Entity>,
state_token: StateToken,
) -> Result<Self, PrefabError> {
Ok(NonPersistent(state_token))
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct NonPersistentPrefabProxy;
impl Prefab for NonPersistentPrefabProxy {}
|
use diesel::r2d2::{self, ConnectionManager};
use diesel::PgConnection;
use std::sync::Arc;
type R2D2PooledConnection = r2d2::PooledConnection<ConnectionManager<PgConnection>>;
pub enum ConnectionType {
Pg(Arc<PgConnection>),
R2D2(Arc<R2D2PooledConnection>),
}
|
extern crate sdl2;
use sdl2::pixels::{Color, PixelFormatEnum};
use sdl2::rect;
const SCALE: u32 = 20;
pub struct Gpu<'a> {
pub gfx: [[u8; 64]; 32],
pub draw_flag: bool,
pub context: sdl2::Sdl,
pub event_pump: sdl2::EventPump,
pub screen: sdl2::render::Renderer<'a>,
pub surface: sdl2::surface::Surface<'a>
}
impl<'a> Gpu<'a> {
pub fn new(title: &'static str) -> Self {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window(title, 64 * SCALE, 32 * SCALE).position_centered().opengl().build().unwrap();
let renderer = window.renderer().build().unwrap();
let event_pump = sdl_context.event_pump().unwrap();
let surface = sdl2::surface::Surface::new(64 * SCALE, 32 * SCALE, PixelFormatEnum::RGB24).unwrap();
Gpu {
gfx: [[0; 64]; 32],
draw_flag: true,
context: sdl_context,
event_pump: event_pump,
screen: renderer,
surface: surface
}
}
pub fn clear(&mut self) {
self.gfx = [[0; 64]; 32];
self.draw_flag = true;
}
pub fn draw(&mut self, x: usize, y: usize, sprite: &[u8]) -> u8 {
let mut collision = 0u8;
let n = sprite.len() as usize;
let mut yj: usize;
let mut xi: usize;
for j in 0..n {
for i in 0..8 {
yj = (y + j) % 32;
xi = (x + i) % 64;
if (sprite[j] & (0x80 >> i)) != 0 {
if self.gfx[yj][xi] == 1 { collision = 1 }
self.gfx[yj][xi] ^= 1;
}
}
}
self.draw_flag = true;
collision
}
pub fn draw_screen(&mut self) {
if !self.draw_flag { return }
let mut pixel: u8;
let sc = SCALE as u16;
let pt = |p: usize | { (p as i16) * (SCALE as i16) };
for y in 0..32 {
for x in 0..64 {
let x_rect = pt(x);
let y_rect = pt(y);
pixel = if self.gfx[y][x] != 0 { 255 } else { 0 };
let rect: sdl2::rect::Rect = rect::Rect::new(x_rect as i32, y_rect as i32, sc as u32, sc as u32);
self.screen.fill_rect(rect).unwrap();
//self.surface.fill_rect(rect, Color::RGB(pixel, pixel, pixel));
Color::RGB(pixel, pixel, pixel);
}
}
self.screen.clear();
self.screen.present();
self.draw_flag = false;
}
} |
use super::{
TimetableList, Timetable, Analysis, Logs, PushSubscription, class_url_to_name, webscrape::*
};
use chrono::prelude::*;
use postgres::Connection;
enum Action {
AutoFetched,
ForciblyFetched,
InsertedTimetables,
DeletedTimetables,
}
// Function to check if a timetable already exists
fn already_exists(conn: &Connection, class_name: &str, day: &str) -> Result<bool, failure::Error> {
Ok(!conn.query("SELECT * FROM timetables WHERE class_name = $1 AND day = $2", &[&class_name, &day])?.is_empty())
}
/*
CREATE TABLE timetables (
id serial PRIMARY KEY,
class_name VARCHAR (6) NOT NULL,
day VARCHAR (30) NOT NULL,
timetable VARCHAR NOT NULL
)
*/
/*
CREATE TABLE actions_log (
id serial PRIMARY KEY,
action VARCHAR (30) NOT NULL,
time TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
SET timezone = 'Asia/Kolkata';
*/
/*
CREATE TABLE notification_subscriptions (
id serial PRIMARY KEY,
push_subscription VARCHAR NOT NULL
)
*/
// Function to log actions in the database
fn log_action(conn: &Connection, action: Action) -> Result<(), failure::Error> {
conn.execute("INSERT INTO actions_log VALUES (DEFAULT, $1, DEFAULT)", &[&match action {
Action::AutoFetched => "Auto Fetched",
Action::ForciblyFetched => "Forcibly Fetched",
Action::InsertedTimetables => "Inserted Timetables",
Action::DeletedTimetables => "Deleted Timetables",
}])?;
Ok(())
}
// Function to insert a new timetable into the database
fn insert_timetables(conn: &Connection, timetable_list: TimetableList, force_insert: bool) -> Result<(), failure::Error> {
let mut inserted_something = false;
let mut deleted_something = false;
// Loop over all the timetables
for timetable in timetable_list.timetables {
if force_insert {
// If we need to forcibly insert, delete any existing entry for this class for this day
conn.execute("DELETE FROM timetables WHERE class_name = $1 AND day = $2", &[&timetable_list.class_name, &timetable.day])?;
deleted_something = true;
} else if already_exists(conn, &timetable_list.class_name, &timetable.day)? {
// Skip if there's already a timetable for this class for this day
continue;
}
let mut times_and_classes = Vec::new();
for row in timetable.classes {
times_and_classes.push(format!("{}={}={}={}", row.0, row.1, row.2, row.3));
}
// Insert the timetable into the database
conn.query("INSERT INTO timetables VALUES (
DEFAULT, $1, $2, $3
)", &[
&timetable_list.class_name,
&timetable.day,
×_and_classes.join("|")
])?;
inserted_something = true;
}
if deleted_something {
log_action(conn, Action::DeletedTimetables)?;
}
if inserted_something {
log_action(conn, Action::InsertedTimetables)?;
}
Ok(())
}
// Function to get the timetables
pub fn get_timetables(conn: &Connection, class_url: String) -> Result<TimetableList, failure::Error> {
let class_name = class_url_to_name(&class_url);
// Variable to store timetables from after the start of this week
let mut timetables = Vec::new();
// Variable to store this week's timetables
let mut this_week_timetables = Vec::new();
// Variable to store last week's timetables
let mut last_week_timetables = Vec::new();
// Loop over all the timetables of this class in the database
for timetable in &conn.query("SELECT day, timetable FROM timetables WHERE class_name = $1 ORDER BY id", &[&class_name])? {
// Check whether the day this timetable is for is after the start of this week
let now = Local::today().naive_local();
let day = NaiveDate::parse_from_str(&timetable.get::<_, String>(0), "%A, %B %e, %Y")?;
let start_of_last_week = now - chrono::Duration::days(now.weekday().num_days_from_sunday() as i64 + 7);
let start_of_this_week = now - chrono::Duration::days(now.weekday().num_days_from_sunday() as i64);
let end_of_this_week = start_of_this_week + chrono::Duration::weeks(1);
if start_of_this_week <= day {
// It is after the start of this week, so add it to the timetables vector
let mut classes = Vec::new();
for row in timetable.get::<_, String>(1).split("|") {
let time_and_class = row.split("=").collect::<Vec<_>>();
classes.push((time_and_class[0].to_string(), time_and_class[1].to_string(), time_and_class[2].to_string(), time_and_class[3].to_string()));
}
timetables.push(Timetable {
day: timetable.get(0),
classes: classes.clone(),
});
if day <= end_of_this_week {
this_week_timetables.push(Timetable {
day: timetable.get(0),
classes,
});
}
} else if start_of_last_week <= day {
// It is only after the start of last week, not this one, so add it
// to the vector with last week's timetables
let mut classes = Vec::new();
for row in timetable.get::<_, String>(1).split("|") {
let time_and_class = row.split("=").collect::<Vec<_>>();
classes.push((time_and_class[0].to_string(), time_and_class[1].to_string(), time_and_class[2].to_string(), time_and_class[3].to_string()));
}
last_week_timetables.push(Timetable {
day: timetable.get(0),
classes,
});
}
}
// If no timetables after the start of this week were found, scrape them from fiitjeelogin
if timetables.len() == 0 {
let mut temp = scrape_timetables(&class_name)?;
timetables.append(&mut temp.clone());
this_week_timetables.append(&mut temp);
log_action(conn, Action::AutoFetched)?;
// Add the timetables to the database so we don't have to scrape them next time
insert_timetables(conn, TimetableList {
class_name: class_name.clone(),
timetables: timetables.clone(),
analyses: None,
}, false)?;
}
let this_week_analyses = generate_analyses(&this_week_timetables)?;
println!("\n\nlast week\n\n");
let last_week_analyses = generate_analyses(&last_week_timetables)?;
Ok(TimetableList {
class_name,
timetables,
analyses: Some([this_week_analyses, last_week_analyses]),
})
}
// Function to forcibly fetch timetables from fiitjeelogin
pub fn forcibly_fetch(conn: &Connection, class_url: String) -> String {
let class_name = class_url_to_name(&class_url);
let timetables = match scrape_timetables(&class_name) {
Ok(x) => x,
Err(e) => return e.to_string(),
};
if let Err(e) = log_action(conn, Action::ForciblyFetched) {
return e.to_string();
}
if let Err(e) = insert_timetables(conn, TimetableList {
class_name,
timetables,
analyses: None,
}, true) {
return e.to_string();
}
String::from("success")
}
// Function to generate analyses from timetables
fn generate_analyses(timetables: &Vec<Timetable>) -> Result<Vec<Analysis>, failure::Error> {
let mut analyses = Vec::new();
// Only include recognized subjects
let mut math = 0;
let mut botany = 0;
let mut zoology = 0;
let mut chemistry = 0;
let mut physics = 0;
let mut english = 0;
let mut computer_science = 0;
let mut bio_or_cs = 0;
let mut games = 0;
// Loop over each day
for timetable in timetables {
// Loop over each class
for class in &timetable.classes {
println!("\n{}", class.3);
*match class.3.as_ref() {
"Math" => &mut math,
"Botany" => &mut botany,
"Zoology" => &mut zoology,
"Chemistry" => &mut chemistry,
"Physics" => &mut physics,
"English" => &mut english,
"Computer Science" => &mut computer_science,
"Bio / CS" => &mut bio_or_cs,
"Games" => &mut games,
_ => continue,
} += {
// The x.trim() is for backwards compatability with previous weeks
let times: Vec<_> = class.0.split('-').map(|x| x.trim()).collect();
(NaiveTime::parse_from_str(times[1], "%H:%M")? - NaiveTime::parse_from_str(times[0], "%H:%M")?).num_minutes()
};
}
}
let subjects_list = [
("Math", math),
("Botany", botany),
("Zoology", zoology),
("Chem", chemistry),
("Phy", physics),
("Eng", english),
("CS", computer_science),
("Bio / CS", bio_or_cs),
("Games", games),
];
// subjects_list.sort_unstable_by(|a, b| b.1.cmp(&a.1));
for subject in &subjects_list {
if subject.1 > 0 {
/*let time = chrono::Duration::minutes(subject.1);
let hours = time.num_hours();
let minutes = time.num_minutes() - hours * 60;
let aggregate_time = if hours == 1 {
if minutes > 0 {
format!("1 hour and {} minutes", minutes)
} else {
String::from("1 hour")
}
} else {
if minutes > 0 {
format!("{} hours and {} minutes", hours, minutes)
} else {
format!("{} hours", hours)
}
};*/
analyses.push(Analysis {
name: subject.0.to_string(),
aggregate_time: subject.1,
});
}
}
Ok(analyses)
}
// Function to get the logs from the database
pub fn get_logs(conn: &Connection) -> Result<Logs, failure::Error> {
let mut logs = Logs::default();
for log in &conn.query("SELECT * FROM actions_log ORDER BY id DESC", &[])? {
let action_as_class = String::from(match log.get::<_, String>(1).as_ref() {
"Auto Fetched" => "autoFetched",
"Forcibly Fetched" => "forciblyFetched",
"Inserted Timetables" => "insertedTimetables",
"Deleted Timetables" => "deletedTimetables",
x => x,
});
let action_time: DateTime<Local> = log.get(2);
logs.logs.push((action_as_class, log.get(1), action_time.format("1%F %T").to_string()));
}
Ok(logs)
}
// Function to add a notification subscription to the database
pub fn add_notification_subscription(conn: &Connection, push_subscription: PushSubscription) -> Result<String, failure::Error> {
conn.execute("INSERT INTO notification_subscriptions VALUES (
DEFAULT, $1
)", &[&serde_json::to_string(&push_subscription)?])?;
Ok(String::from("success"))
}
|
extern crate chrono;
use std::collections::{HashMap, BTreeMap};
use self::chrono::prelude::{DateTime, Utc};
use model::Model;
use strategy::{Strategy, StrategyError, StrategyId};
use order::{Order, OrderId, OrderStatus, GenerateOrderId, OrderBuilder};
pub enum StrategyType<'model> {
EntryStrategy(StrategyId, &'model Model),
ExitStrategy(StrategyId, &'model Model, OrderId)
}
pub struct StrategyCollection<'model> {
pub entry_strategies: Vec<Strategy>,
pub exit_strategies: BTreeMap<StrategyId, Strategy>,
pub order_strategy: HashMap<OrderId, StrategyId>,
pub strategy_types: HashMap<StrategyId, StrategyType<'model>>,
}
impl<'model> StrategyCollection<'model> {
pub fn new() -> StrategyCollection<'model> {
StrategyCollection {
entry_strategies: vec![],
exit_strategies: BTreeMap::new(),
order_strategy: HashMap::new(),
strategy_types: HashMap::new()
}
}
}
pub struct StrategyManager;
impl StrategyManager {
pub fn new() -> StrategyManager {
StrategyManager {}
}
/// Create a strategy collection with entry strategies from given models
pub fn initialize_strategy_collection<'model>(&self, models: &'model Vec<Box<Model>>)
-> StrategyCollection<'model>
{
let mut strategy_collection = StrategyCollection::new();
for model in models {
let entry_strategy = model.entry_strategy();
strategy_collection.strategy_types.insert(
entry_strategy.id().clone(),
StrategyType::EntryStrategy(entry_strategy.id().clone(), model)
);
strategy_collection.entry_strategies.push(entry_strategy);
}
strategy_collection
}
/// Run all strategies of the collection at the specified date
pub fn run_strategies(&self, strategies: &mut StrategyCollection, datetime: &DateTime<Utc>,
order_id_generator: &GenerateOrderId) -> Result<Vec<OrderBuilder>, StrategyError>
{
let mut order_builders = vec![];
for strategy in strategies.entry_strategies.iter_mut().chain(strategies.exit_strategies.values_mut()) {
let result = strategy.run(datetime)?;
if let Some(o) = result {
let (signal, order_builder) = o;
let order_id = order_id_generator.get_id(strategy.id().clone(), &signal, &order_builder);
let order_builder = order_builder.set_id(order_id.clone());
strategies.order_strategy.insert(order_id.clone(), strategy.id().clone());
order_builders.push(order_builder);
}
}
Ok(order_builders)
}
/// Update strategies when an order is updated
pub fn update_strategies(&self, strategy_collection: &mut StrategyCollection,
order_updates: &Vec<(&Order, OrderStatus)>)
{
for update in order_updates {
match update.1 {
OrderStatus::Filled(_) => {
self.update_exit_strategies(strategy_collection, update.0, &update.1);
},
OrderStatus::Cancelled(_) => {
self.update_exit_strategies(strategy_collection, update.0, &update.1);
},
_ => ()
}
}
}
/// Add exit strategies if an entry order is executed, remove exit strategy if its order
/// is cancelled or executed
fn update_exit_strategies<'model>(&self, strategies: &mut StrategyCollection<'model>,
closed_order: &Order, order_status: &OrderStatus)
{
let strategy_updates;
// Get strategy to add or remove
{
let strategy_id = strategies.order_strategy.get(closed_order.id()).unwrap();
let strategy_type = strategies.strategy_types.get(strategy_id).unwrap();
strategy_updates = match strategy_type {
// Add exit strategies when an entry order is executed
&StrategyType::EntryStrategy(_strategy_id, model) => {
match order_status {
&OrderStatus::Filled(_) => {
Some(StrategiesUpdate::AddExitStrategies(model.exit_strategies(closed_order), model))
},
_ => None
}
},
// Remove corresponding exit strategy when exit order is executed
&StrategyType::ExitStrategy(_strategy_id, _model, ref _entry_order_id) => {
match order_status {
&OrderStatus::Filled(_) => {
Some(StrategiesUpdate::RemoveExitStrategy(*strategy_id))
},
&OrderStatus::Cancelled(_) => {
Some(StrategiesUpdate::RemoveExitStrategy(*strategy_id))
},
_ => None
}
}
}
};
// Apply strategy updates
if let Some(updates) = strategy_updates {
match updates {
StrategiesUpdate::AddExitStrategies(new_strategies, model) => {
for strategy in new_strategies {
strategies.strategy_types.insert(
strategy.id().clone(),
StrategyType::ExitStrategy(
strategy.id().clone(),
model,
closed_order.id().clone()
)
);
strategies.exit_strategies.insert(strategy.id().clone(), strategy);
}
},
StrategiesUpdate::RemoveExitStrategy(strategy_id) => {
strategies.exit_strategies.remove(&strategy_id);
}
}
}
}
}
enum StrategiesUpdate<'model> {
AddExitStrategies(Vec<Strategy>, &'model Model),
RemoveExitStrategy(StrategyId)
}
#[cfg(test)]
mod test {
use super::*;
use self::chrono::prelude::{TimeZone};
use order::{Order, OrderBuilder, OrderKind, CancellationReason, UUIDOrderIdGenerator};
use signal::Signal;
use signal::detector::{DetectSignal, DetectSignalError};
use symbol::SymbolId;
use model::ModelId;
use direction::Direction;
use order::policy::MarketOrderPolicy;
use execution::Execution;
#[derive(Clone)]
struct MockModel {
symbol: SymbolId,
err: bool
}
impl Model for MockModel {
fn id(&self) -> ModelId {
String::from("mock model")
}
fn entry_strategy(&self) -> Strategy {
let signal: Box<DetectSignal>;
if !self.err {
signal = Box::new(SomeSignal { symbol: self.symbol.clone() });
}
else {
signal = Box::new(SignalError {});
}
Strategy::new(signal, Box::new(MarketOrderPolicy::new()))
}
fn exit_strategies(&self, _order: &Order) -> Vec<Strategy> {
vec![
Strategy::new(Box::new(SomeSignal { symbol: self.symbol.clone() }), Box::new(MarketOrderPolicy::new())),
Strategy::new(Box::new(SomeSignal { symbol: self.symbol.clone() }), Box::new(MarketOrderPolicy::new()))
]
}
}
struct SomeSignal { symbol: SymbolId }
impl DetectSignal for SomeSignal {
fn detect_signal(&self, datetime: &DateTime<Utc>) -> Result<Option<Signal>, DetectSignalError> {
Ok(Some(Signal::new(self.symbol.clone(), Direction::Long, datetime.clone(), String::new())))
}
}
struct SignalError;
impl DetectSignal for SignalError {
fn detect_signal(&self, _datetime: &DateTime<Utc>) -> Result<Option<Signal>, DetectSignalError> {
Err(DetectSignalError::IndicatorError)
}
}
/// Test that exit strategies are added to collection when the entry order is filled
#[test]
fn update_strategies_entry_order_filled() {
let symbol_id = SymbolId::from("instrument");
let model: Box<Model> = Box::new(MockModel { symbol: symbol_id.clone(), err: false });
let strategy_manager = StrategyManager::new();
let mut strategy_collection = StrategyCollection::new();
let order_id = OrderId::from("test order");
strategy_collection.entry_strategies.push(model.entry_strategy());
strategy_collection.order_strategy.insert(
order_id.clone(),
strategy_collection.entry_strategies.first().unwrap().id().clone()
);
strategy_collection.strategy_types.insert(
strategy_collection.entry_strategies.first().unwrap().id().clone(),
StrategyType::EntryStrategy(
strategy_collection.entry_strategies.first().unwrap().id().clone(),
&model
)
);
strategy_manager.update_strategies(
&mut strategy_collection,
&vec![(
&OrderBuilder::unallocated(OrderKind::MarketOrder, symbol_id.clone(), Direction::Long)
.set_id(order_id.clone())
.set_quantity(3)
.build().unwrap(),
OrderStatus::Filled(
Execution::new(
symbol_id.clone(),
3,
1234.,
Utc.ymd(2017, 12, 1).and_hms(12, 0, 0)
)
)
)]
);
assert_eq!(strategy_collection.exit_strategies.len(), 2);
}
/// Test that exit strategy is removed from the collection when its order is filled
#[test]
fn update_strategies_exit_order_filled() {
let symbol_id = SymbolId::from("instrument");
let model: Box<Model> = Box::new(MockModel { symbol: symbol_id.clone(), err: false });
let strategy_manager = StrategyManager::new();
let mut strategy_collection = StrategyCollection::new();
let entry_order_id = OrderId::from("executed entry order");
let exit_order_id = OrderId::from("exit order");
let entry_order = OrderBuilder::unallocated(
OrderKind::MarketOrder, symbol_id.clone(), Direction::Long
).set_id(entry_order_id.clone()).build().unwrap();
let exit_strategy = model.exit_strategies(&entry_order).remove(0);
strategy_collection.exit_strategies.insert(exit_strategy.id().clone(), exit_strategy);
strategy_collection.order_strategy.insert(
exit_order_id.clone(),
strategy_collection.exit_strategies.keys().next().unwrap().clone()
);
strategy_collection.strategy_types.insert(
strategy_collection.exit_strategies.keys().next().unwrap().clone(),
StrategyType::ExitStrategy(
strategy_collection.exit_strategies.keys().next().unwrap().clone(),
&model,
entry_order_id.clone()
)
);
strategy_manager.update_strategies(
&mut strategy_collection,
&vec![(
&OrderBuilder::unallocated(OrderKind::MarketOrder, symbol_id.clone(), Direction::Long)
.set_id(exit_order_id.clone()).set_quantity(3).build().unwrap(),
OrderStatus::Filled(
Execution::new(
symbol_id.clone(),
3,
1234.,
Utc.ymd(2017, 12, 1).and_hms(12, 0, 0)
)
)
)]
);
assert_eq!(strategy_collection.exit_strategies.len(), 0);
}
/// Test that exit strategy is removed from the collection when its order is cancelled
#[test]
fn update_strategies_exit_order_cancelled() {
let symbol_id = SymbolId::from("instrument");
let model: Box<Model> = Box::new(MockModel { symbol: symbol_id.clone(), err: false });
let strategy_manager = StrategyManager::new();
let mut strategy_collection = StrategyCollection::new();
let entry_order_id = OrderId::from("executed entry order");
let exit_order_id = OrderId::from("exit order");
let entry_order = OrderBuilder::unallocated(
OrderKind::MarketOrder, symbol_id.clone(), Direction::Long
).set_id(entry_order_id.clone()).build().unwrap();
let exit_strategy = model.exit_strategies(&entry_order).remove(0);
strategy_collection.exit_strategies.insert(exit_strategy.id().clone(), exit_strategy);
strategy_collection.order_strategy.insert(
exit_order_id.clone(),
strategy_collection.exit_strategies.keys().next().unwrap().clone()
);
strategy_collection.strategy_types.insert(
strategy_collection.exit_strategies.keys().next().unwrap().clone(),
StrategyType::ExitStrategy(
strategy_collection.exit_strategies.keys().next().unwrap().clone(),
&model,
entry_order_id.clone()
)
);
strategy_manager.update_strategies(
&mut strategy_collection,
&vec![(
&OrderBuilder::unallocated(OrderKind::MarketOrder, symbol_id.clone(), Direction::Long)
.set_id(exit_order_id.clone()).build().unwrap(),
OrderStatus::Cancelled(CancellationReason::FilledOca)
)]
);
assert_eq!(strategy_collection.exit_strategies.len(), 0);
}
#[test]
fn run_strategies_ok() {
let symbol = SymbolId::from("instrument");
let models: Vec<Box<Model>> = vec![Box::new(MockModel { symbol: symbol.clone(), err: false })];
let strategy_manager = StrategyManager::new();
let mut strategy_collection = strategy_manager.initialize_strategy_collection(&models);
let order_builders = strategy_manager.run_strategies(
&mut strategy_collection,
&Utc.ymd(2016, 1, 3).and_hms(17, 0, 0),
&UUIDOrderIdGenerator::new()
).unwrap();
assert!(order_builders.len() == 1);
let expected = OrderBuilder::unallocated(
OrderKind::MarketOrder,
symbol.clone(),
Direction::Long
).set_id(order_builders[0].id().clone().unwrap());
assert!(order_builders[0] == expected);
}
#[test]
fn run_strategies_err() {
let symbol = SymbolId::from("symbol");
let models: Vec<Box<Model>> = vec![Box::new(MockModel { symbol: symbol.clone(), err: true })];
let strategy_manager = StrategyManager::new();
let mut strategy_collection = strategy_manager.initialize_strategy_collection(&models);
let orders = strategy_manager.run_strategies(
&mut strategy_collection,
&Utc.ymd(2016, 1, 3).and_hms(17, 0, 0),
&UUIDOrderIdGenerator::new()
);
assert!(orders.is_err());
}
}
|
#[inline]
pub fn eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() { return false };
let mut d = 0;
for (x, y) in a.iter().zip(b.iter()) {
d |= x ^ y;
}
// NOTE ((1 & ((d - 1) >> 8)) - 1) != 0
d == 0
}
|
use std::{fmt::Debug, sync::Arc};
use data_types::sequence_number_set::SequenceNumberSet;
use futures::Future;
use observability_deps::tracing::warn;
use tokio::sync::{
mpsc::{self, error::TrySendError},
oneshot, Notify,
};
use wal::SegmentId;
use crate::{
persist::completion_observer::CompletedPersist, wal::reference_tracker::WalFileDeleter,
};
use super::WalReferenceActor;
/// A WAL file reference-count tracker handle.
///
/// The [`WalReferenceHandle`] feeds three inputs to the [`WalReferenceActor`]:
///
/// * The [`SequenceNumberSet`] and ID of rotated out WAL segment files
/// * The [`SequenceNumberSet`] of each completed persistence task
/// * All [`data_types::SequenceNumber`] of writes that failed to buffer
///
/// ```text
/// ┌ Write Processing ─ ─ ─ ─ ─ ─ ─ ─ ─
/// │
/// │ ┌────────────┐ ┌─────────────┐
/// │ WAL Rotate │ │ WAL DmlSink │ │
/// │ └────────────┘ └─────────────┘
/// │ │ │
/// │ IDs in │
/// rotated Failed │
/// │ segment write IDs
/// file │ │
/// │ │ │
/// ─ ─ ─ ─ ─│─ ─ ─ ─ ─ ─ ─ ─ ┼ ─ ─ ─ ─ ┘
/// ▼ ▼
/// ┌────────────────────────────────────┐
/// │ │
/// │ WalReferenceActor │─ ─▶ Delete Files
/// │ │
/// └────────────────────────────────────┘
/// ▲
/// │
/// ┌ Persist System ─│─ ─ ─ ─ ─ ─ ─ ─ ─
/// │ │
/// │ ┌──────────────────┐
/// │ Completed │ │
/// │ │ Persistence │
/// │ Observer │ │
/// │ └──────────────────┘
/// ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
/// ```
///
/// Using these three streams of information, the [`WalReferenceActor`] computes
/// the number of unpersisted operations referenced in each WAL segment file,
/// and updates this count as more persist operations complete.
///
/// Once all the operations in a given WAL file have been observed as persisted
/// (or failed to apply), the WAL file is no longer required (all data it
/// contains is durable in the object store) and it is deleted.
///
/// The [`WalReferenceActor`] is tolerant of out-of-order events - that is, a
/// "persisted" event can be received and processed before the WAL file the data
/// is in is known. This is necessary to handle "hot partition persistence"
/// where data is persisted before the WAL file is rotated.
///
/// The [`WalReferenceActor`] gracefully stops once all [`WalReferenceHandle`]
/// instances to it are dropped.
#[derive(Debug, Clone)]
pub(crate) struct WalReferenceHandle {
/// A stream of newly rotated segment files and the set of
/// [`data_types::SequenceNumber`] within them.
///
/// The provided channel should be sent on once the file has been processed.
file_tx: mpsc::Sender<(SegmentId, SequenceNumberSet, oneshot::Sender<()>)>,
/// A steam of persist notifications - the [`SequenceNumberSet`] of the
/// persisted data that is now durable in object storage, and which no
/// longer requires WAL entries for.
persist_tx: mpsc::Sender<Arc<CompletedPersist>>,
/// A stream of [`SequenceNumberSet`] identifying operations that have been (or
/// will be) added to the WAL, but failed to buffer/complete. These should
/// be treated as if they were "persisted", as they will never be persisted,
/// and are not expected to remain durable (user did not get an ACK).
unbuffered_tx: mpsc::Sender<SequenceNumberSet>,
/// A semaphore to wake tasks waiting for the number inactive WAL segement
/// files reaches 0.
///
/// This can happen multiple times during the lifecycle of an ingester.
empty_waker: Arc<Notify>,
}
impl WalReferenceHandle {
/// Construct a new [`WalReferenceActor`] and [`WalReferenceHandle`] pair.
///
/// The returned [`WalReferenceActor`] SHOULD be
/// [`WalReferenceActor::run()`] before the handle is used to avoid
/// potential deadlocks.
pub(crate) fn new<T>(wal: T, metrics: &metric::Registry) -> (Self, WalReferenceActor<T>)
where
T: WalFileDeleter,
{
let (file_tx, file_rx) = mpsc::channel(5);
let (persist_tx, persist_rx) = mpsc::channel(50);
let (unbuffered_tx, unbuffered_rx) = mpsc::channel(50);
let empty_waker = Default::default();
let actor = WalReferenceActor::new(
wal,
file_rx,
persist_rx,
unbuffered_rx,
Arc::clone(&empty_waker),
metrics,
);
(
Self {
file_tx,
persist_tx,
unbuffered_tx,
empty_waker,
},
actor,
)
}
/// Enqueue a new file rotation event, providing the [`SegmentId`] of the
/// WAL file and the [`SequenceNumberSet`] the WAL segment contains.
pub(crate) async fn enqueue_rotated_file(
&self,
segment_id: SegmentId,
set: SequenceNumberSet,
) -> oneshot::Receiver<()> {
let (tx, rx) = oneshot::channel();
Self::send(&self.file_tx, (segment_id, set, tx)).await;
rx
}
/// Enqueue a persist completion notification for newly persisted data.
pub(crate) async fn enqueue_persist_notification(&self, note: Arc<CompletedPersist>) {
Self::send(&self.persist_tx, note).await
}
/// Enqueue a notification that a write appearing in some WAL segment will
/// not be buffered/persisted (either the active, not-yet-rotated segment or
/// a prior, already-rotated segment).
///
/// This can happen when a write is added to the WAL segment and
/// subsequently fails to be applied to the in-memory buffer. It is
/// important to track these unusual cases to ensure the WAL file is not
/// kept forever due to an outstanding reference, waiting for the unbuffered
/// write to be persisted (which it never will).
pub(crate) async fn enqueue_unbuffered_write(&self, set: SequenceNumberSet) {
Self::send(&self.unbuffered_tx, set).await
}
/// A future that resolves when there are no partially persisted / inactive
/// WAL segment files known to the reference tracker.
///
/// NOTE: the active WAL segment file may contain unpersisted operations!
/// The tracker is only aware of inactive/rotated-out WAL files.
///
/// NOTE: the number of references may reach 0 multiple times over the
/// lifetime of an ingester.
///
/// # Ordering
///
/// Calling this method must happen-before the number of files reaches 0.
/// The number of files reaching zero happens-before the wakers are woken.
///
/// A caller must call this method before the number of inactive files
/// reaches 0 to be woken, otherwise the future will resolve the next time 0
/// is reached.
///
/// Calls to [`WalReferenceHandle::enqueue_rotated_file()`] are executed
/// asynchronously; callers should use the returned completion handle when
/// enqueuing to order processing of the file before emptying of the
/// inactive file set (this notification future).
pub(crate) fn empty_inactive_notifier(&self) -> impl Future<Output = ()> + '_ {
self.empty_waker.notified()
}
/// Send `val` over `chan`, logging a warning if `chan` is at capacity.
async fn send<T>(chan: &mpsc::Sender<T>, val: T)
where
T: Debug + Send,
{
match chan.try_send(val) {
Ok(()) => {}
Err(TrySendError::Full(val)) => {
warn!(?val, "notification buffer is full");
chan.send(val).await.expect("wal reference actor stopped");
}
Err(TrySendError::Closed(_)) => panic!("wal reference actor stopped"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::new_persist_notification;
use assert_matches::assert_matches;
use async_trait::async_trait;
use data_types::SequenceNumber;
use futures::{task::Context, Future, FutureExt};
use metric::{assert_counter, U64Gauge};
use parking_lot::Mutex;
use std::{pin::Pin, task::Poll, time::Duration};
use test_helpers::timeout::FutureTimeout;
use tokio::sync::Notify;
/// A mock file deleter that records the IDs it was asked to delete.
#[derive(Debug, Default)]
struct MockWalDeleter {
notify: Notify,
calls: Mutex<Vec<SegmentId>>,
}
impl MockWalDeleter {
/// Return the set of [`SegmentId`] that have been deleted.
fn calls(&self) -> Vec<SegmentId> {
self.calls.lock().clone()
}
/// Return a future that completes when a file is subsequently deleted,
/// or panics if no file is deleted within 5 seconds.
fn deleted_file_waker(&self) -> impl Future<Output = ()> + '_ {
self.notify
.notified()
.with_timeout_panic(Duration::from_secs(5))
}
}
#[async_trait]
impl WalFileDeleter for Arc<MockWalDeleter> {
async fn delete_file(&self, id: SegmentId) {
self.calls.lock().push(id);
self.notify.notify_waiters();
}
}
/// Return a [`SequenceNumberSet`] containing `vals`.
fn new_set<T>(vals: T) -> SequenceNumberSet
where
T: IntoIterator<Item = u64>,
{
vals.into_iter().map(SequenceNumber::new).collect()
}
/// Test in-order notifications:
///
/// * WAL file is rotated and the tracker notified
/// * Multiple persists complete, and an unbuffered notification, draining
/// the references to the file
/// * The file is deleted when refs == 0
/// * Dropping the handle stops the actor
#[tokio::test]
async fn test_rotate_persist_delete() {
const SEGMENT_ID: SegmentId = SegmentId::new(42);
let metrics = metric::Registry::default();
let wal = Arc::new(MockWalDeleter::default());
let (handle, actor) = WalReferenceHandle::new(Arc::clone(&wal), &metrics);
let actor_task = tokio::spawn(actor.run());
// Add a file with IDs 1 through 5
handle
.enqueue_rotated_file(SEGMENT_ID, new_set([1, 2, 3, 4, 5, 6]))
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// Submit a persist notification that removes refs 1 & 2.
handle
.enqueue_persist_notification(new_persist_notification([1, 2]))
.await;
// Ensure the file was not deleted
assert!(wal.calls().is_empty());
// Enqueue a unbuffered notification (out of order)
handle.enqueue_unbuffered_write(new_set([5, 6])).await;
// Ensure the file was not deleted
assert!(wal.calls().is_empty());
// Finally release the last IDs
let deleted_file_waker = wal.deleted_file_waker();
handle
.enqueue_persist_notification(new_persist_notification([3, 4]))
.await;
// Wait for it to be processed
deleted_file_waker.await;
// Validate the correct ID was deleted
assert_matches!(wal.calls().as_slice(), &[v] if v == SEGMENT_ID);
assert_counter!(
metrics,
U64Gauge,
"ingester_wal_inactive_file_count",
value = 0,
);
assert_counter!(
metrics,
U64Gauge,
"ingester_wal_inactive_file_op_reference_count",
value = 0,
);
// Assert clean shutdown behaviour.
drop(handle);
actor_task
.with_timeout_panic(Duration::from_secs(5))
.await
.expect("actor task should stop cleanly")
}
/// Test in-order notifications:
///
/// * Multiple persists complete
/// * A WAL file notification is received containing a subset of the
/// already persisted IDs
/// * The file is deleted because refs == 0
/// * A WAL file notification for a superset of the remaining persisted
/// IDs
/// * The remaining references are persisted/unbuffered
/// * The second WAL file is deleted
/// * Dropping the handle stops the actor
#[tokio::test]
async fn test_persist_all_rotate_delete() {
const SEGMENT_ID_1: SegmentId = SegmentId::new(42);
const SEGMENT_ID_2: SegmentId = SegmentId::new(24);
let metrics = metric::Registry::default();
let wal = Arc::new(MockWalDeleter::default());
let (handle, actor) = WalReferenceHandle::new(Arc::clone(&wal), &metrics);
let actor_task = tokio::spawn(actor.run());
// Submit a persist notification for the entire set of IDs [1,2,3,4] in
// the upcoming first WAL, and partially the second WAL
handle
.enqueue_persist_notification(new_persist_notification([2]))
.await;
handle
.enqueue_persist_notification(new_persist_notification([1]))
.await;
handle
.enqueue_persist_notification(new_persist_notification([3, 4]))
.await;
// Add a file with IDs 1, 2, 3
let deleted_file_waker = wal.deleted_file_waker();
handle
.enqueue_rotated_file(SEGMENT_ID_1, new_set([1, 2, 3]))
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// Wait for it to be processed
deleted_file_waker.await;
// Validate the correct ID was deleted
assert_matches!(wal.calls().as_slice(), &[v] if v == SEGMENT_ID_1);
// Enqueue the second WAL, covering 4
handle
.enqueue_rotated_file(SEGMENT_ID_2, new_set([4, 5, 6]))
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// At this point, the second WAL still has references outstanding (5, 6)
// and should not have been deleted.
assert_eq!(wal.calls().len(), 1);
// Release one of the remaining two refs
handle
.enqueue_persist_notification(new_persist_notification([6]))
.await;
// Still no deletion
assert_eq!(wal.calls().len(), 1);
// And finally release the last ref via an unbuffered notification
let empty_waker = handle.empty_inactive_notifier();
let deleted_file_waker = wal.deleted_file_waker();
handle.enqueue_unbuffered_write(new_set([5])).await;
deleted_file_waker.await;
// Validate the correct ID was deleted
assert_matches!(wal.calls().as_slice(), &[a, b] => {
assert_eq!(a, SEGMENT_ID_1);
assert_eq!(b, SEGMENT_ID_2);
});
// Wait for the "it's empty!" waker to fire, indicating the tracker has
// no references to unpersisted data.
empty_waker.with_timeout_panic(Duration::from_secs(5)).await;
// Assert clean shutdown behaviour.
drop(handle);
actor_task
.with_timeout_panic(Duration::from_secs(5))
.await
.expect("actor task should stop cleanly")
}
#[tokio::test]
async fn test_empty_file_set() {
const SEGMENT_ID: SegmentId = SegmentId::new(42);
let metrics = metric::Registry::default();
let wal = Arc::new(MockWalDeleter::default());
let (handle, actor) = WalReferenceHandle::new(Arc::clone(&wal), &metrics);
let actor_task = tokio::spawn(actor.run());
// Notifying the actor of a WAL file with no operations in it should not
// cause a panic, and should cause the file to be immediately deleted.
let empty_waker = handle.empty_inactive_notifier();
let deleted_file_waker = wal.deleted_file_waker();
handle
.enqueue_rotated_file(SEGMENT_ID, SequenceNumberSet::default())
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// Wait for the file deletion.
deleted_file_waker.await;
assert_matches!(wal.calls().as_slice(), &[v] if v == SEGMENT_ID);
// Wait for the "it's empty!" waker to fire, indicating the tracker has
// no references to unpersisted data.
empty_waker.with_timeout_panic(Duration::from_secs(5)).await;
// Assert clean shutdown behaviour.
drop(handle);
actor_task
.with_timeout_panic(Duration::from_secs(5))
.await
.expect("actor task should stop cleanly")
}
#[tokio::test]
#[should_panic(expected = "duplicate segment ID")]
async fn test_duplicate_segment_ids() {
let metrics = metric::Registry::default();
let wal = Arc::new(MockWalDeleter::default());
let (handle, actor) = WalReferenceHandle::new(Arc::clone(&wal), &metrics);
// Enqueuing a notification before the actor is running should succeed
// because of the channel buffer capacity.
handle
.enqueue_rotated_file(SegmentId::new(42), new_set([1, 2]))
.with_timeout_panic(Duration::from_secs(5))
.await;
handle
.enqueue_rotated_file(SegmentId::new(42), new_set([3, 4]))
.with_timeout_panic(Duration::from_secs(5))
.await;
// This should panic after processing the second file.
actor.run().with_timeout_panic(Duration::from_secs(5)).await;
}
/// Enqueue two segment files, enqueue persist notifications for the second
/// file and wait for it to be deleted to synchronise the state (so it's not
/// a racy test).
///
/// Then assert the metric values for the known state.
#[tokio::test]
async fn test_metrics() {
const SEGMENT_ID_1: SegmentId = SegmentId::new(42);
const SEGMENT_ID_2: SegmentId = SegmentId::new(24);
assert!(SEGMENT_ID_2 < SEGMENT_ID_1); // Test invariant
let metrics = metric::Registry::default();
let wal = Arc::new(MockWalDeleter::default());
let (handle, actor) = WalReferenceHandle::new(Arc::clone(&wal), &metrics);
let actor_task = tokio::spawn(actor.run());
// Add a file with 4 references
handle
.enqueue_rotated_file(SEGMENT_ID_1, new_set([1, 2, 3, 4, 5]))
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// Reduce the reference count for file 1 (leaving 3 references)
handle
.enqueue_persist_notification(new_persist_notification([1, 2]))
.await;
// Enqueue the second file.
handle
.enqueue_rotated_file(SEGMENT_ID_2, new_set([6]))
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// The second file was completed processed, so the minimum segment ID
// MUST now be 24.
assert_counter!(
metrics,
U64Gauge,
"ingester_wal_inactive_min_id",
value = SEGMENT_ID_2.get(),
);
// Release the references to file 2
let deleted_file_waker = wal.deleted_file_waker();
handle
.enqueue_persist_notification(new_persist_notification([6]))
.await;
deleted_file_waker.await;
//
// At this point, the actor has deleted the second file, which means it
// has already processed the first enqueued file, and the first persist
// notification that relates to the first file.
//
// A non-racy assert can now be made against this known state.
//
assert_counter!(
metrics,
U64Gauge,
"ingester_wal_inactive_file_count",
value = 1,
);
assert_counter!(
metrics,
U64Gauge,
"ingester_wal_inactive_file_op_reference_count",
value = 3, // 5 initial, reduced by 2 via persist notification
);
assert_counter!(
metrics,
U64Gauge,
"ingester_wal_inactive_min_id",
value = SEGMENT_ID_1.get(),
);
// Assert clean shutdown behaviour.
drop(handle);
actor_task
.with_timeout_panic(Duration::from_secs(5))
.await
.expect("actor task should stop cleanly")
}
/// Ensure the empty notification only fires when there are no referenced
/// WAL files and no entries in the persisted set.
#[tokio::test]
async fn test_empty_notifications() {
const SEGMENT_ID_1: SegmentId = SegmentId::new(24);
const SEGMENT_ID_2: SegmentId = SegmentId::new(42);
let metrics = metric::Registry::default();
let wal = Arc::new(MockWalDeleter::default());
let (handle, actor) = WalReferenceHandle::new(Arc::clone(&wal), &metrics);
let actor_task = tokio::spawn(actor.run());
{
let empty_waker = handle.empty_inactive_notifier();
// Allow the waker future to be polled explicitly.
let waker = futures::task::noop_waker();
let mut cx = Context::from_waker(&waker);
futures::pin_mut!(empty_waker);
// Add a file
handle
.enqueue_rotated_file(SEGMENT_ID_1, new_set([1, 2, 3, 4]))
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// Remove some file references, leaving 1 reference
handle
.enqueue_persist_notification(new_persist_notification([1, 2]))
.await;
// The tracker is not empty, so the future must not resolve.
assert_matches!(Pin::new(&mut empty_waker).poll(&mut cx), Poll::Pending);
// Add a persist notification, populating the "persisted" set.
handle
.enqueue_persist_notification(new_persist_notification([5]))
.await;
// Release the file reference, leaving only the above reference
// remaining (id=5)
handle.enqueue_unbuffered_write(new_set([3, 4])).await;
// The tracker is not empty, so the future must not resolve.
assert_matches!(Pin::new(&mut empty_waker).poll(&mut cx), Poll::Pending);
// Add a new file with two references, releasing id=5.
handle
.enqueue_rotated_file(SEGMENT_ID_2, new_set([5, 6]))
.with_timeout_panic(Duration::from_secs(5))
.flatten()
.await
.expect("did not receive file processed notification");
// The tracker is not empty, so the future must not resolve.
assert_matches!(Pin::new(&mut empty_waker).poll(&mut cx), Poll::Pending);
// Finally release the last reference (id=6)
handle.enqueue_unbuffered_write(new_set([6])).await;
// The future MUST now resolve.
empty_waker.with_timeout_panic(Duration::from_secs(5)).await;
}
// Assert clean shutdown behaviour.
drop(handle);
actor_task
.with_timeout_panic(Duration::from_secs(5))
.await
.expect("actor task should stop cleanly")
}
}
|
use anyhow::anyhow;
use anyhow::Result;
/// Convert hex string to raw bytes `Vec<u8>`, return anyhow::Error if contains
/// invalid charater (not 0~9a~f)
pub fn hexstr_to_bytes(hex: &str) -> Result<Vec<u8>> {
let chars: Vec<char> = hex.chars().collect();
match chars.len() % 2 {
0 => {
let bytes = chars
.chunks_exact(2)
.map(|chunk| {
let first_byte = chunk[0].to_digit(16).unwrap();
let second_byte = chunk[1].to_digit(16).unwrap();
(first_byte << 4 | second_byte) as u8
})
.collect();
Ok(bytes)
}
_ => Err(anyhow!("Wrong hex string length, should be even")),
}
}
/// Convert raw bytes `[u8]` to hex string
pub fn bytes_to_hexstr(bytes: &[u8]) -> String {
let mut hex_bytes: Vec<u8> = vec![];
for byte in bytes.iter() {
hex_bytes.push(byte >> 4);
hex_bytes.push(byte & 0xf);
}
let chars: Vec<char> = hex_bytes
.iter()
.map(|num| std::char::from_digit(*num as u32, 16).unwrap())
.collect();
chars.iter().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_to_bytes() {
let b: Vec<u8> = vec![18, 52, 86, 120, 144, 171, 205, 239];
assert_eq!(hexstr_to_bytes("1234567890abcdef").unwrap(), b);
assert!(hexstr_to_bytes("1ab").is_err());
}
#[test]
fn bytes_to_hex() {
let b: Vec<u8> = vec![18, 52, 86, 120, 144, 171, 205, 239];
assert_eq!(bytes_to_hexstr(&b), "1234567890abcdef");
}
}
|
use libc;
use libc::toupper;
use crate::clist::*;
use crate::mailimf::*;
use crate::mailmime::*;
use crate::mailmime_types::*;
use crate::x::*;
pub const MAILMIME_DISPOSITION_TYPE_EXTENSION: libc::c_uint = 3;
pub const MAILMIME_DISPOSITION_TYPE_ATTACHMENT: libc::c_uint = 2;
pub const MAILMIME_DISPOSITION_TYPE_INLINE: libc::c_uint = 1;
pub const MAILMIME_DISPOSITION_TYPE_ERROR: libc::c_uint = 0;
pub unsafe fn mailmime_disposition_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut mailmime_disposition,
) -> libc::c_int {
let mut current_block: u64;
let mut final_token: size_t = 0;
let mut cur_token: size_t = 0;
let mut dsp_type: *mut mailmime_disposition_type = 0 as *mut mailmime_disposition_type;
let mut list: *mut clist = 0 as *mut clist;
let mut dsp: *mut mailmime_disposition = 0 as *mut mailmime_disposition;
let mut r: libc::c_int = 0;
let mut res: libc::c_int = 0;
cur_token = *indx;
r = mailmime_disposition_type_parse(message, length, &mut cur_token, &mut dsp_type);
if r != MAILIMF_NO_ERROR as libc::c_int {
res = r
} else {
list = clist_new();
if list.is_null() {
res = MAILIMF_ERROR_MEMORY as libc::c_int
} else {
loop {
let mut param: *mut mailmime_disposition_parm = 0 as *mut mailmime_disposition_parm;
final_token = cur_token;
r = mailimf_unstrict_char_parse(
message,
length,
&mut cur_token,
';' as i32 as libc::c_char,
);
if r == MAILIMF_NO_ERROR as libc::c_int {
param = 0 as *mut mailmime_disposition_parm;
r = mailmime_disposition_parm_parse(
message,
length,
&mut cur_token,
&mut param,
);
if r == MAILIMF_NO_ERROR as libc::c_int {
r = clist_insert_after(list, (*list).last, param as *mut libc::c_void);
if !(r < 0i32) {
continue;
}
res = MAILIMF_ERROR_MEMORY as libc::c_int;
current_block = 18290070879695007868;
break;
} else if r == MAILIMF_ERROR_PARSE as libc::c_int {
cur_token = final_token;
current_block = 652864300344834934;
break;
} else {
res = r;
current_block = 18290070879695007868;
break;
}
} else {
/* do nothing */
if r == MAILIMF_ERROR_PARSE as libc::c_int {
current_block = 652864300344834934;
break;
}
res = r;
current_block = 18290070879695007868;
break;
}
}
match current_block {
652864300344834934 => {
dsp = mailmime_disposition_new(dsp_type, list);
if dsp.is_null() {
res = MAILIMF_ERROR_MEMORY as libc::c_int
} else {
*result = dsp;
*indx = cur_token;
return MAILIMF_NO_ERROR as libc::c_int;
}
}
_ => {}
}
clist_foreach(
list,
::std::mem::transmute::<
Option<unsafe fn(_: *mut mailmime_disposition_parm) -> ()>,
clist_func,
>(Some(mailmime_disposition_parm_free)),
0 as *mut libc::c_void,
);
clist_free(list);
}
mailmime_disposition_type_free(dsp_type);
}
return res;
}
/*
* libEtPan! -- a mail stuff library
*
* Copyright (C) 2001, 2005 - DINH Viet Hoa
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the libEtPan! project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* $Id: mailmime_disposition.c,v 1.17 2011/05/03 16:30:22 hoa Exp $
*/
unsafe fn mailmime_disposition_parm_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut mailmime_disposition_parm,
) -> libc::c_int {
let mut current_block: u64;
let mut filename: *mut libc::c_char = 0 as *mut libc::c_char;
let mut creation_date: *mut libc::c_char = 0 as *mut libc::c_char;
let mut modification_date: *mut libc::c_char = 0 as *mut libc::c_char;
let mut read_date: *mut libc::c_char = 0 as *mut libc::c_char;
let mut size: size_t = 0;
let mut parameter: *mut mailmime_parameter = 0 as *mut mailmime_parameter;
let mut cur_token: size_t = 0;
let mut dsp_parm: *mut mailmime_disposition_parm = 0 as *mut mailmime_disposition_parm;
let mut type_0: libc::c_int = 0;
let mut guessed_type: libc::c_int = 0;
let mut r: libc::c_int = 0;
let mut res: libc::c_int = 0;
cur_token = *indx;
filename = 0 as *mut libc::c_char;
creation_date = 0 as *mut libc::c_char;
modification_date = 0 as *mut libc::c_char;
read_date = 0 as *mut libc::c_char;
size = 0i32 as size_t;
parameter = 0 as *mut mailmime_parameter;
r = mailimf_cfws_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int {
res = r
} else {
guessed_type = mailmime_disposition_guess_type(message, length, cur_token);
type_0 = MAILMIME_DISPOSITION_PARM_PARAMETER as libc::c_int;
match guessed_type {
0 => {
r = mailmime_filename_parm_parse(message, length, &mut cur_token, &mut filename);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = guessed_type;
current_block = 13826291924415791078;
} else if r == MAILIMF_ERROR_PARSE as libc::c_int {
current_block = 13826291924415791078;
} else {
/* do nothing */
res = r;
current_block = 9120900589700563584;
}
}
1 => {
r = mailmime_creation_date_parm_parse(
message,
length,
&mut cur_token,
&mut creation_date,
);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = guessed_type;
current_block = 13826291924415791078;
} else if r == MAILIMF_ERROR_PARSE as libc::c_int {
current_block = 13826291924415791078;
} else {
/* do nothing */
res = r;
current_block = 9120900589700563584;
}
}
2 => {
r = mailmime_modification_date_parm_parse(
message,
length,
&mut cur_token,
&mut modification_date,
);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = guessed_type;
current_block = 13826291924415791078;
} else if r == MAILIMF_ERROR_PARSE as libc::c_int {
current_block = 13826291924415791078;
} else {
/* do nothing */
res = r;
current_block = 9120900589700563584;
}
}
3 => {
r = mailmime_read_date_parm_parse(message, length, &mut cur_token, &mut read_date);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = guessed_type;
current_block = 13826291924415791078;
} else if r == MAILIMF_ERROR_PARSE as libc::c_int {
current_block = 13826291924415791078;
} else {
/* do nothing */
res = r;
current_block = 9120900589700563584;
}
}
4 => {
r = mailmime_size_parm_parse(message, length, &mut cur_token, &mut size);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = guessed_type;
current_block = 13826291924415791078;
} else if r == MAILIMF_ERROR_PARSE as libc::c_int {
current_block = 13826291924415791078;
} else {
/* do nothing */
res = r;
current_block = 9120900589700563584;
}
}
_ => {
current_block = 13826291924415791078;
}
}
match current_block {
9120900589700563584 => {}
_ => {
if type_0 == MAILMIME_DISPOSITION_PARM_PARAMETER as libc::c_int {
r = mailmime_parameter_parse(message, length, &mut cur_token, &mut parameter);
if r != MAILIMF_NO_ERROR as libc::c_int {
type_0 = guessed_type;
res = r;
current_block = 9120900589700563584;
} else {
current_block = 6721012065216013753;
}
} else {
current_block = 6721012065216013753;
}
match current_block {
9120900589700563584 => {}
_ => {
dsp_parm = mailmime_disposition_parm_new(
type_0,
filename,
creation_date,
modification_date,
read_date,
size,
parameter,
);
if dsp_parm.is_null() {
res = MAILIMF_ERROR_MEMORY as libc::c_int;
if !filename.is_null() {
mailmime_filename_parm_free(filename);
}
if !creation_date.is_null() {
mailmime_creation_date_parm_free(creation_date);
}
if !modification_date.is_null() {
mailmime_modification_date_parm_free(modification_date);
}
if !read_date.is_null() {
mailmime_read_date_parm_free(read_date);
}
if !parameter.is_null() {
mailmime_parameter_free(parameter);
}
} else {
*result = dsp_parm;
*indx = cur_token;
return MAILIMF_NO_ERROR as libc::c_int;
}
}
}
}
}
}
return res;
}
unsafe fn mailmime_size_parm_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut size_t,
) -> libc::c_int {
let mut value: uint32_t = 0;
let mut cur_token: size_t = 0;
let mut r: libc::c_int = 0;
cur_token = *indx;
r = mailimf_token_case_insensitive_len_parse(
message,
length,
&mut cur_token,
b"size\x00" as *const u8 as *const libc::c_char as *mut libc::c_char,
strlen(b"size\x00" as *const u8 as *const libc::c_char),
);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_unstrict_char_parse(message, length, &mut cur_token, '=' as i32 as libc::c_char);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_cfws_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int {
return r;
}
r = mailimf_number_parse(message, length, &mut cur_token, &mut value);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
*indx = cur_token;
*result = value as size_t;
return MAILIMF_NO_ERROR as libc::c_int;
}
unsafe fn mailmime_read_date_parm_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut libc::c_char,
) -> libc::c_int {
let mut value: *mut libc::c_char = 0 as *mut libc::c_char;
let mut cur_token: size_t = 0;
let mut r: libc::c_int = 0;
cur_token = *indx;
r = mailimf_token_case_insensitive_len_parse(
message,
length,
&mut cur_token,
b"read-date\x00" as *const u8 as *const libc::c_char as *mut libc::c_char,
strlen(b"read-date\x00" as *const u8 as *const libc::c_char),
);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_unstrict_char_parse(message, length, &mut cur_token, '=' as i32 as libc::c_char);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_cfws_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int {
return r;
}
r = mailmime_quoted_date_time_parse(message, length, &mut cur_token, &mut value);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
*indx = cur_token;
*result = value;
return MAILIMF_NO_ERROR as libc::c_int;
}
unsafe fn mailmime_quoted_date_time_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut libc::c_char,
) -> libc::c_int {
return mailimf_quoted_string_parse(message, length, indx, result);
}
unsafe fn mailmime_modification_date_parm_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut libc::c_char,
) -> libc::c_int {
let mut value: *mut libc::c_char = 0 as *mut libc::c_char;
let mut cur_token: size_t = 0;
let mut r: libc::c_int = 0;
cur_token = *indx;
r = mailimf_token_case_insensitive_len_parse(
message,
length,
&mut cur_token,
b"modification-date\x00" as *const u8 as *const libc::c_char as *mut libc::c_char,
strlen(b"modification-date\x00" as *const u8 as *const libc::c_char),
);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_unstrict_char_parse(message, length, &mut cur_token, '=' as i32 as libc::c_char);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_cfws_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int {
return r;
}
r = mailmime_quoted_date_time_parse(message, length, &mut cur_token, &mut value);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
*indx = cur_token;
*result = value;
return MAILIMF_NO_ERROR as libc::c_int;
}
unsafe fn mailmime_creation_date_parm_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut libc::c_char,
) -> libc::c_int {
let mut value: *mut libc::c_char = 0 as *mut libc::c_char;
let mut r: libc::c_int = 0;
let mut cur_token: size_t = 0;
cur_token = *indx;
r = mailimf_token_case_insensitive_len_parse(
message,
length,
&mut cur_token,
b"creation-date\x00" as *const u8 as *const libc::c_char as *mut libc::c_char,
strlen(b"creation-date\x00" as *const u8 as *const libc::c_char),
);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_unstrict_char_parse(message, length, &mut cur_token, '=' as i32 as libc::c_char);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_cfws_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int {
return r;
}
r = mailmime_quoted_date_time_parse(message, length, &mut cur_token, &mut value);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
*indx = cur_token;
*result = value;
return MAILIMF_NO_ERROR as libc::c_int;
}
unsafe fn mailmime_filename_parm_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut libc::c_char,
) -> libc::c_int {
let mut value: *mut libc::c_char = 0 as *mut libc::c_char;
let mut r: libc::c_int = 0;
let mut cur_token: size_t = 0;
cur_token = *indx;
r = mailimf_token_case_insensitive_len_parse(
message,
length,
&mut cur_token,
b"filename\x00" as *const u8 as *const libc::c_char as *mut libc::c_char,
strlen(b"filename\x00" as *const u8 as *const libc::c_char),
);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_unstrict_char_parse(message, length, &mut cur_token, '=' as i32 as libc::c_char);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_cfws_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int {
return r;
}
r = mailmime_value_parse(message, length, &mut cur_token, &mut value);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
*indx = cur_token;
*result = value;
return MAILIMF_NO_ERROR as libc::c_int;
}
pub unsafe fn mailmime_disposition_guess_type(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: size_t,
) -> libc::c_int {
if indx >= length {
return MAILMIME_DISPOSITION_PARM_PARAMETER as libc::c_int;
}
match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char
as libc::c_int
{
70 => return MAILMIME_DISPOSITION_PARM_FILENAME as libc::c_int,
67 => return MAILMIME_DISPOSITION_PARM_CREATION_DATE as libc::c_int,
77 => return MAILMIME_DISPOSITION_PARM_MODIFICATION_DATE as libc::c_int,
82 => return MAILMIME_DISPOSITION_PARM_READ_DATE as libc::c_int,
83 => return MAILMIME_DISPOSITION_PARM_SIZE as libc::c_int,
_ => return MAILMIME_DISPOSITION_PARM_PARAMETER as libc::c_int,
};
}
pub unsafe fn mailmime_disposition_type_parse(
mut message: *const libc::c_char,
mut length: size_t,
mut indx: *mut size_t,
mut result: *mut *mut mailmime_disposition_type,
) -> libc::c_int {
let mut cur_token: size_t = 0;
let mut type_0: libc::c_int = 0;
let mut extension: *mut libc::c_char = 0 as *mut libc::c_char;
let mut dsp_type: *mut mailmime_disposition_type = 0 as *mut mailmime_disposition_type;
let mut r: libc::c_int = 0;
let mut res: libc::c_int = 0;
cur_token = *indx;
r = mailimf_cfws_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int {
res = r
} else {
type_0 = MAILMIME_DISPOSITION_TYPE_ERROR as libc::c_int;
extension = 0 as *mut libc::c_char;
r = mailimf_token_case_insensitive_len_parse(
message,
length,
&mut cur_token,
b"inline\x00" as *const u8 as *const libc::c_char as *mut libc::c_char,
strlen(b"inline\x00" as *const u8 as *const libc::c_char),
);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = MAILMIME_DISPOSITION_TYPE_INLINE as libc::c_int
}
if r == MAILIMF_ERROR_PARSE as libc::c_int {
r = mailimf_token_case_insensitive_len_parse(
message,
length,
&mut cur_token,
b"attachment\x00" as *const u8 as *const libc::c_char as *mut libc::c_char,
strlen(b"attachment\x00" as *const u8 as *const libc::c_char),
);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = MAILMIME_DISPOSITION_TYPE_ATTACHMENT as libc::c_int
}
}
if r == MAILIMF_ERROR_PARSE as libc::c_int {
r = mailmime_extension_token_parse(message, length, &mut cur_token, &mut extension);
if r == MAILIMF_NO_ERROR as libc::c_int {
type_0 = MAILMIME_DISPOSITION_TYPE_EXTENSION as libc::c_int
}
}
if r != MAILIMF_NO_ERROR as libc::c_int {
res = r
} else {
dsp_type = mailmime_disposition_type_new(type_0, extension);
if dsp_type.is_null() {
res = MAILIMF_ERROR_MEMORY as libc::c_int;
if !extension.is_null() {
free(extension as *mut libc::c_void);
}
} else {
*result = dsp_type;
*indx = cur_token;
return MAILIMF_NO_ERROR as libc::c_int;
}
}
}
return res;
}
|
extern crate rs_libc;
extern crate rs_libc_decentriq;
use hyper::server::Request;
use hyper::server::Response;
use rusqlite::params;
use rusqlite::Connection;
use std::io::Read;
use std::collections::HashSet;
use hyper::uri::RequestUri::AbsolutePath;
use hyper::net::Fresh;
use std::sync::Arc;
use std::sync::Mutex;
use serde::Deserialize;
use serde::Serialize;
use chrono::DateTime;
use chrono::Utc;
type UserId = String;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
struct EnclaveState {
connection: Connection,
to_notify: HashSet<UserId>,
}
struct EnclaveHandler {
state: Arc<Mutex<EnclaveState>>,
}
#[derive(Serialize, Deserialize)]
struct TimestampedCoordinate {
timestamp: DateTime<Utc>,
x: f32,
y: f32,
}
#[derive(Serialize, Deserialize)]
struct PollRequest {
user_id: UserId,
timestamped_coordinates: Vec<TimestampedCoordinate>,
}
#[derive(Serialize, Deserialize)]
struct PollResponse {
}
impl EnclaveHandler {
fn new(connection: Connection) -> EnclaveHandler {
let state = EnclaveState {
connection,
to_notify: HashSet::new(),
};
EnclaveHandler { state: Arc::new(Mutex::new(state)) }
}
fn handle_poll(&self, req: &mut Request) -> Result<Vec<u8>> {
let poll_request: PollRequest = serde_json::from_reader(req)?;
Ok(serde_json::to_vec(&poll_request).unwrap())
}
}
impl hyper::server::Handler for EnclaveHandler {
fn handle(&self, mut req: Request, mut res: Response) {
match req.uri {
AbsolutePath(ref path) => match (&req.method, &path[..]) {
(&hyper::Post, "/poll") => {
match self.handle_poll(&mut req) {
Ok(response_contents) => {
res.send(response_contents.as_slice()).unwrap();
}
Err(err) => {
*res.status_mut() = hyper::BadRequest;
res.send(format!("{:?}", err).as_bytes()).unwrap();
}
}
}
_ => {
*res.status_mut() = hyper::NotFound;
res.start().unwrap();
}
},
_ => {
*res.status_mut() = hyper::NotFound;
res.start().unwrap();
}
}
}
}
fn main() {
setup_logging();
let connection = Connection::open_in_memory().unwrap();
let enclave_handler = EnclaveHandler::new(connection);
let _listening = hyper::Server::http("[::]:3000").unwrap().handle(enclave_handler);
println!("Listening on http://[::]:3000");
}
fn setup_logging() {
std::env::set_var("RUST_LOG", "debug");
env_logger::Builder::from_default_env()
.target(env_logger::Target::Stdout)
.init();
}
|
use super::schema;
#[derive(Debug, Clone, Fail)]
pub enum ConnectionError {
#[fail(display = "Timeout: {}", _0)]
Timeout(String),
#[fail(display = "Malformed Message: {}", _0)]
MalformedMessage(String),
#[fail(display = "Wrong Type: {}", _0)]
WrongType(String),
}
#[derive(Debug, Clone, Fail)]
pub enum StreamError {
#[fail(display = "The stream has not been started.")]
NotStarted,
#[fail(display = "The stream has been removed.")]
Removed,
}
#[derive(Debug, Clone, Fail)]
pub enum ResponseError {
#[fail(display = "{}.{}: {}", service, name, description)]
Other {
service: String,
name: String,
description: String,
stack_trace: String,
},
#[fail(display = "Invalid Operation: {}", _0)]
InvalidOperation(String),
#[fail(display = "Invalid Argument: {}", _0)]
InvalidArgument(String),
#[fail(display = "Null Argument: {}", _0)]
NullArgument(String),
#[fail(display = "Argument Out of Range: {}", _0)]
ArgumentOutOfRange(String),
#[fail(display = "No result returned for the rpc call.")]
MissingResult,
}
impl From<schema::Error> for ResponseError {
fn from(err: schema::Error) -> Self {
Self::from(&err)
}
}
impl From<&schema::Error> for ResponseError {
fn from(err: &schema::Error) -> Self {
if err.get_service().eq("KRPC") && err.get_name().eq("InvalidOperationException") {
ResponseError::InvalidOperation(err.get_description().to_owned())
} else if err.get_service().eq("KRPC") && err.get_name().eq("ArgumentException") {
ResponseError::InvalidArgument(err.get_description().to_owned())
} else if err.get_service().eq("KRPC") && err.get_name().eq("ArgumentNullException") {
ResponseError::NullArgument(err.get_description().to_owned())
} else if err.get_service().eq("KRPC") && err.get_name().eq("ArgumentOutOfRangeException") {
ResponseError::ArgumentOutOfRange(err.get_description().to_owned())
} else {
ResponseError::Other {
service: err.get_service().to_owned(),
name: err.get_name().to_owned(),
description: err.get_description().to_owned(),
stack_trace: err.get_stack_trace().to_owned(),
}
}
}
}
|
use std::fmt::Display;
use data_types::{CompactionLevel, ParquetFile};
use metric::{Registry, U64Counter, U64Histogram, U64HistogramOptions};
use super::SplitOrCompact;
use crate::{file_classification::FilesToSplitOrCompact, partition_info::PartitionInfo};
const METRIC_NAME_FILES_TO_SPLIT: &str = "iox_compactor_files_to_split";
const METRIC_NAME_SPLIT_DECISION_COUNT: &str = "iox_compactor_split_decision";
const METRIC_NAME_COMPACT_DECISION_COUNT: &str = "iox_compactor_compact_decision";
#[derive(Debug)]
pub struct MetricsSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
files_to_split: U64Histogram,
split_decision_count: U64Counter,
compact_decision_count: U64Counter,
inner: T,
}
impl<T> MetricsSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
pub fn new(inner: T, registry: &Registry) -> Self {
let files_to_split = registry
.register_metric_with_options::<U64Histogram, _>(
METRIC_NAME_FILES_TO_SPLIT,
"Number of files needing to be split to minimize overlap",
|| U64HistogramOptions::new([1, 10, 100, 1_000, 10_000, u64::MAX]),
)
.recorder(&[]);
let split_decision_count = registry
.register_metric::<U64Counter>(
METRIC_NAME_SPLIT_DECISION_COUNT,
"Number of times the compactor decided to split files",
)
.recorder(&[]);
let compact_decision_count = registry
.register_metric::<U64Counter>(
METRIC_NAME_COMPACT_DECISION_COUNT,
"Number of times the compactor decided to compact files",
)
.recorder(&[]);
Self {
files_to_split,
split_decision_count,
compact_decision_count,
inner,
}
}
}
impl<T> SplitOrCompact for MetricsSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
fn apply(
&self,
partition_info: &PartitionInfo,
files: Vec<ParquetFile>,
target_level: CompactionLevel,
) -> (FilesToSplitOrCompact, Vec<ParquetFile>) {
let (files_to_split_or_compact, files_to_keep) =
self.inner.apply(partition_info, files, target_level);
match &files_to_split_or_compact {
FilesToSplitOrCompact::Split(..) => {
self.files_to_split
.record(files_to_split_or_compact.num_files_to_split() as u64);
self.split_decision_count.inc(1);
}
FilesToSplitOrCompact::Compact(..) => self.compact_decision_count.inc(1),
_ => {} // Nothing to do
}
(files_to_split_or_compact, files_to_keep)
}
}
impl<T> Display for MetricsSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "metrics({})", self.inner)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use compactor_test_utils::{create_overlapped_l0_l1_files_2, create_overlapped_l1_l2_files_2};
use data_types::CompactionLevel;
use metric::{assert_counter, assert_histogram};
use crate::{
components::split_or_compact::{split_compact::SplitCompact, SplitOrCompact},
test_utils::PartitionInfoBuilder,
};
const MAX_FILE: usize = 100;
#[test]
fn empty_records_nothing() {
let registry = Registry::new();
let files = vec![];
let p_info = Arc::new(PartitionInfoBuilder::new().build());
let split_compact = MetricsSplitOrCompactWrapper::new(
SplitCompact::new(MAX_FILE, MAX_FILE, MAX_FILE as u64),
®istry,
);
let (_files_to_split_or_compact, _files_to_keep) =
split_compact.apply(&p_info, files, CompactionLevel::Initial);
assert_histogram!(
registry,
U64Histogram,
METRIC_NAME_FILES_TO_SPLIT,
samples = 0,
);
assert_counter!(
registry,
U64Counter,
METRIC_NAME_SPLIT_DECISION_COUNT,
value = 0,
);
assert_counter!(
registry,
U64Counter,
METRIC_NAME_COMPACT_DECISION_COUNT,
value = 0,
);
}
#[test]
fn files_to_split_get_recorded() {
let registry = Registry::new();
let files = create_overlapped_l0_l1_files_2(MAX_FILE as i64);
let p_info = Arc::new(PartitionInfoBuilder::new().build());
let split_compact = MetricsSplitOrCompactWrapper::new(
SplitCompact::new(MAX_FILE, MAX_FILE, MAX_FILE as u64),
®istry,
);
let (_files_to_split_or_compact, _files_to_keep) =
split_compact.apply(&p_info, files, CompactionLevel::FileNonOverlapped);
assert_histogram!(
registry,
U64Histogram,
METRIC_NAME_FILES_TO_SPLIT,
samples = 1,
sum = 4,
);
assert_counter!(
registry,
U64Counter,
METRIC_NAME_SPLIT_DECISION_COUNT,
value = 1,
);
assert_counter!(
registry,
U64Counter,
METRIC_NAME_COMPACT_DECISION_COUNT,
value = 0,
);
}
#[test]
fn files_to_compact_get_recorded() {
let registry = Registry::new();
let files = create_overlapped_l1_l2_files_2(MAX_FILE as i64);
let p_info = Arc::new(PartitionInfoBuilder::new().build());
let split_compact = MetricsSplitOrCompactWrapper::new(
SplitCompact::new(MAX_FILE, MAX_FILE * 3, MAX_FILE as u64),
®istry,
);
let (_files_to_split_or_compact, _files_to_keep) =
split_compact.apply(&p_info, files, CompactionLevel::Final);
assert_histogram!(
registry,
U64Histogram,
METRIC_NAME_FILES_TO_SPLIT,
samples = 0,
);
assert_counter!(
registry,
U64Counter,
METRIC_NAME_SPLIT_DECISION_COUNT,
value = 0,
);
assert_counter!(
registry,
U64Counter,
METRIC_NAME_COMPACT_DECISION_COUNT,
value = 1,
);
}
}
|
use core::mem;
use std::borrow::Borrow;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::hash::Hash;
use std::ops::Deref;
use ordered_float::OrderedFloat;
use graph_lib::algo::trees::Trees;
use graph_lib::safe_tree::Tree;
use graph_lib::tree::TheTree;
use mcts::Mcts;
use policy::policy::Policy;
use policy::score::Score;
use policy::win_score::ExploreScore;
use rules::{Action, Rules};
use sim_result::SimResult;
use crate::mcts::MctsNode;
pub struct MyMcts<A: Action, S: Rules<A>> {
the_state: S,
root: MctsNode<A>,
}
impl<A: Action, S: Rules<A>> MyMcts<A, S> {
pub fn new(state: S) -> MyMcts<A, S> {
MyMcts {
the_state: state,
root: SimResult::node(),
}
}
pub fn fork(&self, node: &MctsNode<A>) -> MyMcts<A, S> {
MyMcts {
the_state: self.state().clone(),
root: node.clone(),
}
}
fn is_leaf(node: MctsNode<A>) -> bool {
node.value.borrow().is_leaf()
}
pub(crate) fn reset(&mut self) {
let current = self.root.clone();
self.the_state.reset();
for (action, _) in current.parents().iter().rev() {
self.state_mut().apply_action(action.clone())
}
}
}
fn selection_score<'a, A: 'a + Action, Sc: Score>(
cursor: &MctsNode<A>,
exploitation: &'a Sc,
) -> impl Fn(&SimResult) -> OrderedFloat<f32> + 'a
{
let copy = cursor.clone();
move |child: &SimResult| {
let parent = copy.value.borrow();
OrderedFloat(exploitation.score(child) + ExploreScore::new(&parent).score(child))
}
}
impl<A: Action, S: Rules<A>> Mcts<A, S> for MyMcts<A, S> {
fn root(&self) -> MctsNode<A> {
self.root.clone()
}
fn selection<Sc: Score>(&mut self, exploitation: &Sc) -> MctsNode<A> {
self.reset();
let mut cursor = self.root();
let mut final_score = OrderedFloat(0_f32);
while !Self::is_leaf(cursor.clone()) {
let score = selection_score(&cursor, exploitation);
match cursor.search_max_child(&score) {
None => break,
Some((action, node)) => {
final_score = score(node.value.borrow().deref());
// log::debug!("depth={}, score={}", node.depth.borrow(), final_score);
cursor.set_child(action, &node);
self.state_mut().apply_action(action);
cursor = node.clone();
}
}
}
// log::debug!("Selection: depth={:?} score={}", cursor.depth.borrow(), final_score);
cursor
}
fn expansion<P: Policy<A, S>>(&mut self, selected: &MctsNode<A>, policy: &P) -> (A, MctsNode<A>) {
let action = policy.select(self.state());
self.state_mut().apply_action(action);
let mut next_node = selected.clone();
for a in self.state().actions() {
let new_node = SimResult::node();
selected.set_child(a, &new_node);
if a == action {
next_node = new_node;
}
}
// log::debug!("Expansion: {:?}\n{}", action, next_node);
(action, next_node)
}
fn backpropagation(&mut self, cursor: &MctsNode<A>, mut res: SimResult) {
// log::debug!("Backpropagation: ({} parents)", cursor.parents().len());
cursor.value.borrow_mut().merge(&res);
let parents = cursor.parents();
for (_key, value) in parents {
value.value.borrow_mut().merge(&res);
res.swap();
}
}
fn state(&self) -> &S {
&self.the_state
}
fn state_mut(&mut self) -> &mut S {
&mut self.the_state
}
}
|
//! HTTP Write V1 and V2 implementation logic for both single, and multi-tenant
//! operational modes.
pub mod v1;
pub mod v2;
pub mod multi_tenant;
pub mod single_tenant;
mod params;
pub use params::*;
|
//! A Request represents a Gopher request made by a client. phd can
//! serve directory listings as Gopher Menus, plain text files as
//! Text, binary files as downloads, Gophermap files as menus, or
//! executable files as dynamic content.
use crate::Result;
use std::fs;
/// This struct represents a single gopher request.
#[derive(Debug, Clone)]
pub struct Request {
/// Gopher selector requested
pub selector: String,
/// Search query string, if any.
pub query: String,
/// Root directory of the server. Can't serve outside of this.
pub root: String,
/// Host of the currently running server.
pub host: String,
/// Port of the currently running server.
pub port: u16,
}
impl Request {
/// Try to create a new request state object.
pub fn from(host: &str, port: u16, root: &str) -> Result<Request> {
Ok(Request {
host: host.into(),
port,
root: fs::canonicalize(root)?.to_string_lossy().into(),
selector: String::new(),
query: String::new(),
})
}
/// Path to the target file on disk requested by this request.
pub fn file_path(&self) -> String {
format!(
"{}/{}",
self.root.to_string().trim_end_matches('/'),
self.selector.replace("..", ".").trim_start_matches('/')
)
}
/// Path to the target file relative to the server root.
pub fn relative_file_path(&self) -> String {
self.file_path().replace(&self.root, "")
}
/// Set selector + query based on what the client sent.
pub fn parse_request(&mut self, line: &str) {
self.query.clear();
self.selector.clear();
if let Some((i, _)) = line
.chars()
.enumerate()
.find(|&(_, c)| c == '\t' || c == '?')
{
if line.len() > i {
self.query.push_str(&line[i + 1..]);
self.selector.push_str(&line[..i]);
return;
}
}
self.selector.push_str(line);
// strip trailing /
if let Some(last) = self.selector.chars().last() {
if last == '/' {
self.selector.pop();
}
}
}
}
|
//! DataFusion User Defined Functions (UDF/ UDAF) for IOx
#![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)]
#![warn(
missing_copy_implementations,
missing_docs,
clippy::explicit_iter_loop,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::use_self,
clippy::clone_on_ref_ptr,
clippy::todo,
clippy::dbg_macro,
unused_crate_dependencies
)]
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
use datafusion::{
execution::FunctionRegistry,
prelude::{lit, Expr, SessionContext},
};
use group_by::WindowDuration;
use window::EncodedWindowDuration;
pub mod coalesce_struct;
/// Grouping by structs
pub mod group_by;
/// Regular Expressions
mod regex;
/// Selector Functions
pub mod selectors;
/// window_bounds expressions
mod window;
pub mod gapfill;
/// Function registry
mod registry;
pub use crate::regex::clean_non_meta_escapes;
pub use crate::regex::REGEX_MATCH_UDF_NAME;
pub use crate::regex::REGEX_NOT_MATCH_UDF_NAME;
/// Return an Expr that invokes a InfluxRPC compatible regex match to
/// determine which values satisfy the pattern. Equivalent to:
///
/// ```text
/// col ~= /pattern/
/// ```
pub fn regex_match_expr(input: Expr, pattern: String) -> Expr {
registry()
.udf(regex::REGEX_MATCH_UDF_NAME)
.expect("RegexMatch function not registered")
.call(vec![input, lit(pattern)])
}
/// Return an Expr that invokes a InfluxRPC compatible regex match to
/// determine which values do not satisfy the pattern. Equivalent to:
///
/// ```text
/// col !~ /pattern/
/// ```
pub fn regex_not_match_expr(input: Expr, pattern: String) -> Expr {
registry()
.udf(regex::REGEX_NOT_MATCH_UDF_NAME)
.expect("NotRegexMatch function not registered")
.call(vec![input, lit(pattern)])
}
/// Create a DataFusion `Expr` that invokes `window_bounds` with the
/// appropriate every and offset arguments at runtime
pub fn make_window_bound_expr(
time_arg: Expr,
every: WindowDuration,
offset: WindowDuration,
) -> Expr {
let encoded_every: EncodedWindowDuration = every.into();
let encoded_offset: EncodedWindowDuration = offset.into();
registry()
.udf(window::WINDOW_BOUNDS_UDF_NAME)
.expect("WindowBounds function not registered")
.call(vec![
time_arg,
lit(encoded_every.ty),
lit(encoded_every.field1),
lit(encoded_every.field2),
lit(encoded_offset.ty),
lit(encoded_offset.field1),
lit(encoded_offset.field2),
])
}
/// Return an [`FunctionRegistry`] with the implementations of IOx UDFs
pub fn registry() -> &'static dyn FunctionRegistry {
registry::instance()
}
/// registers scalar functions so they can be invoked via SQL
pub fn register_scalar_functions(ctx: &SessionContext) {
let registry = registry();
for f in registry.udfs() {
let udf = registry.udf(&f).unwrap();
ctx.register_udf(udf.as_ref().clone())
}
}
#[cfg(test)]
mod test {
use arrow::{
array::{ArrayRef, StringArray, TimestampNanosecondArray},
record_batch::RecordBatch,
};
use datafusion::{assert_batches_eq, prelude::col};
use datafusion_util::context_with_table;
use std::sync::Arc;
use super::*;
/// plumbing test to validate registry is connected. functions are
/// tested more thoroughly in their own modules
#[tokio::test]
async fn test_regex_match_expr() {
let batch = RecordBatch::try_from_iter(vec![(
"data",
Arc::new(StringArray::from(vec!["Foo", "Bar", "FooBar"])) as ArrayRef,
)])
.unwrap();
let ctx = context_with_table(batch);
let result = ctx
.table("t")
.await
.unwrap()
.filter(regex_match_expr(col("data"), "Foo".into()))
.unwrap()
.collect()
.await
.unwrap();
let expected = vec![
"+--------+",
"| data |",
"+--------+",
"| Foo |",
"| FooBar |",
"+--------+",
];
assert_batches_eq!(&expected, &result);
}
/// plumbing test to validate registry is connected. functions are
/// tested more thoroughly in their own modules
#[tokio::test]
async fn test_regex_not_match_expr() {
let batch = RecordBatch::try_from_iter(vec![(
"data",
Arc::new(StringArray::from(vec!["Foo", "Bar", "FooBar"])) as ArrayRef,
)])
.unwrap();
let ctx = context_with_table(batch);
let result = ctx
.table("t")
.await
.unwrap()
.filter(regex_not_match_expr(col("data"), "Foo".into()))
.unwrap()
.collect()
.await
.unwrap();
let expected = vec!["+------+", "| data |", "+------+", "| Bar |", "+------+"];
assert_batches_eq!(&expected, &result);
}
/// plumbing test to validate registry is connected. functions are
/// tested more thoroughly in their own modules
#[tokio::test]
async fn test_make_window_bound_expr() {
let batch = RecordBatch::try_from_iter(vec![(
"time",
Arc::new(TimestampNanosecondArray::from(vec![Some(1000), Some(2000)])) as ArrayRef,
)])
.unwrap();
let each = WindowDuration::Fixed { nanoseconds: 100 };
let every = WindowDuration::Fixed { nanoseconds: 200 };
let ctx = context_with_table(batch);
let result = ctx
.table("t")
.await
.unwrap()
.select(vec![
col("time"),
make_window_bound_expr(col("time"), each, every).alias("bound"),
])
.unwrap()
.collect()
.await
.unwrap();
let expected = vec![
"+----------------------------+-------------------------------+",
"| time | bound |",
"+----------------------------+-------------------------------+",
"| 1970-01-01T00:00:00.000001 | 1970-01-01T00:00:00.000001100 |",
"| 1970-01-01T00:00:00.000002 | 1970-01-01T00:00:00.000002100 |",
"+----------------------------+-------------------------------+",
];
assert_batches_eq!(&expected, &result);
}
}
|
use ron::{de::from_reader, ser::to_string_pretty, ser::PrettyConfig};
use serde::{Deserialize, Serialize};
use std::{fs::File, io::Write, path::Path};
use bevy::{
asset::HandleId, asset::LoadState, math::vec2, prelude::*, sprite::TextureAtlasBuilder,
};
// Almost literal copy of Bevy Texture Atlas example.....
#[derive(Default)]
pub struct AtlasSpriteHandles {
handles: Vec<HandleId>,
atlas_loaded: bool,
}
pub fn ta_setup(
mut rpg_sprite_handles: ResMut<AtlasSpriteHandles>,
asset_server: Res<AssetServer>,
) {
rpg_sprite_handles.handles = asset_server.load_asset_folder("assets/ship").unwrap();
}
pub fn load_atlas(
// mut commands: Commands,
mut rpg_sprite_handles: ResMut<AtlasSpriteHandles>,
asset_server: Res<AssetServer>,
mut texture_atlases: ResMut<Assets<TextureAtlas>>,
mut textures: ResMut<Assets<Texture>>,
// mut materials: ResMut<Assets<ColorMaterial>>,
) {
if rpg_sprite_handles.atlas_loaded {
return;
}
let mut texture_atlas_builder = TextureAtlasBuilder {
max_size: vec2(5000., 6000.),
..Default::default()
};
if let Some(LoadState::Loaded(_)) =
asset_server.get_group_load_state(&rpg_sprite_handles.handles)
{
for texture_id in rpg_sprite_handles.handles.iter() {
let handle = Handle::from_id(*texture_id);
let texture = textures.get(&handle).unwrap();
texture_atlas_builder.add_texture(handle, &texture);
}
let texture_atlas = texture_atlas_builder.finish(&mut textures).unwrap();
let texture_atlas_texture = texture_atlas.texture;
let atlas_handle = texture_atlases.add(texture_atlas);
// set up a scene to display our texture atlas
// let vendor_handle = asset_server
// .get_handle("assets/flycatcher.png")
// .unwrap();
// let vendor_index = texture_atlas.get_texture_index(vendor_handle).unwrap();
// commands
// .spawn(SpriteSheetComponents {
// transform: Transform::from_scale(4.0).with_translation(Vec3::new(150.0, 0.0, 0.0)),
// sprite: TextureAtlasSprite::new(vendor_index as u32),
// texture_atlas: atlas_handle,
// ..Default::default()
// })
// // draw the atlas itself
// .spawn(SpriteComponents {
// material: materials.add(texture_atlas_texture.into()),
// transform: Transform::from_translation(Vec3::new(-300.0, 0.0, 0.0)),
// ..Default::default()
// });
rpg_sprite_handles.atlas_loaded = true;
let texas = textures.get(&texture_atlas_texture).unwrap();
let texatlas = texture_atlases.get(&atlas_handle).unwrap();
print_texture_to_file(texas, "texture_atlas.png");
let mut atlas_infos = AtlasInfo::new();
let rects = &texatlas.textures;
// for (h, u) in texatlas.texture_handles.as_ref().unwrap() {
// atlas_infos.push(AtlasInfo { filepath: format!("{:?}", h), rect: rects[u.to_owned()].clone()})
// }
for entry in walkdir::WalkDir::new("assets")
.into_iter()
.filter_map(|e| e.ok())
{
println!("{}", entry.path().display());
if let Some(v_handle) = asset_server.get_handle(entry.path()) {
if let Some(v_index) = texatlas.get_texture_index(v_handle) {
atlas_infos.textures.push(TextureDetails {
filepath: format!("{}", entry.path().display()),
rect: Rectangle {
min: rects[v_index].min,
max: rects[v_index].max,
},
})
}
}
}
atlas_infos.print_to_file("texture_atlas.ron");
}
}
fn print_texture_to_file(texture: &Texture, path: &str) {
let fout = &mut File::create(&Path::new(path)).unwrap();
let encoder = image::png::PngEncoder::new(fout);
let _ok = encoder.encode(
&texture.data,
texture.size.x() as u32,
texture.size.y() as u32,
image::ColorType::Rgba8,
);
}
// import from Ron
#[derive(Debug, Deserialize, Serialize)]
pub struct AtlasInfo {
pub textures: Vec<TextureDetails>,
}
impl AtlasInfo {
fn new() -> Self {
AtlasInfo {
textures: Vec::new(),
}
}
pub fn import_from_file(path: &str) -> Self {
let f = File::open(path).expect("Failed opening file");
let atlas_info: AtlasInfo = match from_reader(f) {
Ok(x) => x,
Err(e) => {
println!("Failed to load atlas info: {}", e);
std::process::exit(1);
}
};
atlas_info
}
fn print_to_file(&self, path: &str) {
let pretty = PrettyConfig::new();
let s = to_string_pretty(self, pretty).expect("Serialization failed");
let outputfile = &mut File::create(&Path::new(&format!("texture_atlas.ron"))).unwrap();
outputfile.write_all(s.as_bytes()).expect("else");
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct TextureDetails {
pub filepath: String,
pub rect: Rectangle,
}
#[derive(Debug, Default, Copy, Clone, Deserialize, Serialize)]
pub struct Rectangle {
pub min: Vec2,
pub max: Vec2,
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 spin::Mutex;
use std::collections::VecDeque;
use super::super::qlib::mem::areaset::*;
use super::super::qlib::common::*;
use super::super::qlib::linux_def::*;
use super::super::qlib::range::*;
use super::super::memmgr::*;
use super::super::IO_MGR;
#[derive(Clone, Default)]
pub struct HostSegment {}
impl AreaValue for HostSegment {
fn Merge(&self, _r1: &Range, _r2: &Range, _vma2: &HostSegment) -> Option<HostSegment> {
return Some(HostSegment {})
}
fn Split(&self, _r: &Range, _split: u64) -> (HostSegment, HostSegment) {
return (HostSegment {}, HostSegment {})
}
}
//pub struct HostPMAKeeper (Mutex<AreaSet<HostSegment>>);
pub struct HostPMAKeeper {
pub ranges: Mutex<AreaSet<HostSegment>>,
pub hugePages: Mutex<VecDeque<u64>>,
}
impl HostPMAKeeper {
const HUGE_PAGE_RANGE: u64 = 6 * MemoryDef::ONE_GB as u64;
pub fn New() -> Self {
return Self {
ranges: Mutex::new(AreaSet::New(0,0)),
hugePages: Mutex::new(VecDeque::with_capacity((Self::HUGE_PAGE_RANGE / MemoryDef::PAGE_SIZE_2M) as usize))
}
}
pub fn FreeHugePage(&self, addr: u64) {
self.hugePages.lock().push_front(addr);
}
pub fn AllocHugePage(&self) -> Option<u64> {
let ret = self.hugePages.lock().pop_back();
return ret;
}
pub fn Init(&self, start: u64, len: u64) {
assert!(len > Self::HUGE_PAGE_RANGE as u64);
self.ranges.lock().Reset(start, len);
}
pub fn InitHugePages(&self) {
let hugePageStart = self.RangeAllocate(Self::HUGE_PAGE_RANGE, MemoryDef::PAGE_SIZE_2M).unwrap();
let mut addr = hugePageStart;
while addr < hugePageStart + Self::HUGE_PAGE_RANGE as u64 {
self.FreeHugePage(addr);
addr += MemoryDef::PAGE_SIZE_2M;
}
}
fn Map(&self, mo: &mut MapOption, r: &Range) -> Result<u64> {
match mo.MMap() {
Err(e) => {
self.RemoveSeg(r);
return Err(e);
}
Ok(addr) => {
if addr != r.Start() {
panic!("AreaSet <HostSegment>:: memmap fail to alloc fix address at {:x}", r.Start());
}
return Ok(r.Start())
}
}
}
pub fn MapAnon(&self, len: u64, prot: i32) -> Result<u64> {
let mut mo = &mut MapOption::New();
mo = mo.MapAnan().Proto(prot).Len(len);
mo.MapShare();
let start = self.Allocate(len, MemoryDef::PAGE_SIZE)?;
mo.Addr(start);
return self.Map(&mut mo, &Range::New(start, len));
}
pub fn MapFile(&self, len: u64, prot: i32, fd: i32, offset: u64) -> Result<u64> {
let osfd = IO_MGR.lock().GetFdByHost(fd).expect("MapFile: Getosfd fail");
let mut mo = &mut MapOption::New();
//let prot = prot | MmapProt::PROT_WRITE as i32;
mo = mo.Proto(prot).FileOffset(offset).FileId(osfd).Len(len).MapFixed();
//mo.MapPrivate();
mo.MapShare();
mo.MapLocked();
let start = self.Allocate(len, MemoryDef::PMD_SIZE)?;
mo.Addr(start);
return self.Map(&mut mo, &Range::New(start, len));
}
fn RangeAllocate(&self, len: u64, alignment: u64) -> Result<u64> {
let mut ranges = self.ranges.lock();
let start = ranges.FindAvailable(len, alignment)?;
let r = Range::New(start, len);
let gap = ranges.FindGap(start);
let seg = ranges.Insert(&gap, &r, HostSegment {});
assert!(seg.Ok(), "AreaSet <HostSegment>:: insert fail");
return Ok(start)
}
fn Allocate(&self, len: u64, alignment: u64) -> Result<u64> {
if len != MemoryDef::PAGE_SIZE_2M {
error!("Allocate len is {:x} alignment {:x}", len, alignment);
}
if len <= MemoryDef::PAGE_SIZE_2M {
assert!(alignment <= MemoryDef::PAGE_SIZE_2M, "Allocate fail .... {:x}/{:x}", len, alignment);
let addr = self.AllocHugePage().expect("AllocHugePage fail...");
return Ok(addr)
}
return self.RangeAllocate(len, alignment);
}
pub fn RemoveSeg(&self, r: &Range) {
if r.Len() <= MemoryDef::PAGE_SIZE_2M {
self.FreeHugePage(r.Start());
return;
}
let mut ranges = self.ranges.lock();
let (seg, _gap) = ranges.Find(r.Start());
if !seg.Ok() || !seg.Range().IsSupersetOf(r) {
panic!("AreaSet <HostSegment>::Unmap invalid, remove range {:?} from range {:?}",
r, seg.Range());
}
let seg = ranges.Isolate(&seg, r);
ranges.Remove(&seg);
}
pub fn Unmap(&self, r: &Range) -> Result<()> {
self.RemoveSeg(r);
let res = MapOption::MUnmap(r.Start(), r.Len());
return res;
}
}
impl AreaSet<HostSegment> {
fn FindAvailable(&mut self, len: u64, alignment: u64) -> Result<u64> {
let mut gap = self.FirstGap();
while gap.Ok() {
let gr = gap.Range();
if gr.Len() >= len {
let offset = gr.Start() % alignment;
if offset != 0 {
if gr.Len() >= len + alignment - offset {
return Ok(gr.Start() + alignment - offset)
}
} else {
return Ok(gr.Start());
}
}
gap = gap.NextGap();
}
return Err(Error::SysError(SysErr::ENOMEM));
}
}
|
use median::{
attr::{AttrBuilder, AttrType},
builder::{MSPWrappedBuilder, ManagedBufferRef},
class::Class,
clock::ClockHandle,
max_sys::t_atom_long,
num::Int64,
object::MSPObj,
post,
wrapper::{attr_get_tramp, attr_set_tramp, tramp, MSPObjWrapped, MSPObjWrapper},
};
median::external! {
#[name="hello_dsp~"]
pub struct HelloDSP {
value: Int64,
_v: String,
clock: ClockHandle,
buffer1: ManagedBufferRef,
buffer2: ManagedBufferRef
}
impl MSPObjWrapped<HelloDSP> for HelloDSP {
//create some signal i/o
fn new(builder: &mut dyn MSPWrappedBuilder<Self>) -> Self {
builder.add_signal_inlets(2);
builder.add_signal_outlets(2);
Self {
value: Int64::new(0),
_v: String::from("blah"),
clock: builder.with_clockfn(Self::clocked),
buffer1: builder.with_buffer(None),
buffer2: builder.with_buffer(None),
}
}
fn dsp_setup(&self, sample_rate: f64) {
median::object_post!(self.as_max_obj(), "sample rate: {}", sample_rate);
}
//perform the dsp
fn perform(&self, _ins: &[&[f64]], outs: &mut [&mut [f64]], _nframes: usize) {
let c = if self.buffer1.exists() { 1. } else { 0.} + if self.buffer2.exists() { 1. } else { 0. };
for o in outs[0].iter_mut() {
*o = c;
}
for o in outs[1].iter_mut() {
*o = 1f64;
}
}
// Register any methods you need for your class
fn class_setup(c: &mut Class<MSPObjWrapper<Self>>) {
//explicitly create a "set" selector method with a single symbol argument
c.add_method(median::method::Method::SelS(&"set", Self::set_tramp, 0)).unwrap();
c.add_attribute(
AttrBuilder::new_accessors(
"blah",
AttrType::Int64,
Self::blah_tramp,
Self::set_blah_tramp,
)
.build()
.unwrap(),
)
.expect("failed to add attribute");
}
}
impl HelloDSP {
#[bang]
pub fn bang(&self) {
median::object_post!(self.as_max_obj(), "from rust {}", self.value);
self.clock.delay(10);
}
//create a trampoline for the c.add_method in `class_setup` above.
//Max doesn't accept methods direct to your rust struct, you need to create a "trampoline"
//that it uses instead. This "trampoline" is a C method that is called on a wrapper struct
//that in turn calls this "set" method on your wrapped object.
//The trampoline methods are named with `_tramp` appended to the end.
#[tramp]
pub fn set(&self, name: median::symbol::SymbolRef) {
self.buffer1.set(name);
}
#[int]
pub fn int(&self, v: t_atom_long) {
self.value.set(v);
//XXX won't compile, needs mutex
//self._v = format!("from rust {}", self.value);
post!("from rust {}", self.value);
//just an example to show an error
if v < 0 {
median::object_error!(self.as_max_obj(), "from rust {}", self.value);
}
}
#[attr_get_tramp]
pub fn blah(&self) -> t_atom_long {
self.value.get()
}
#[attr_set_tramp]
pub fn set_blah(&self, v: t_atom_long) {
self.value.set(v);
}
pub fn clocked(&self) {
post("clocked".to_string());
}
}
}
|
#![allow(improper_ctypes)]
extern "C" {
fn merge_instr_profiles_impl(inputs: &[&str], output: &str) -> bool;
}
pub fn merge_instr_profiles(inputs: &[&str], output: &str) -> bool {
unsafe {
merge_instr_profiles_impl(inputs, output)
}
}
|
#![allow(dead_code)]
use parse::tokens::*;
#[derive(Default)]
pub struct Lexer{
pub curr_token : Token,
next_token : Token,
curr_char : char,
pub curr_string : String,
src_code : Vec<u8>,
char_pos : usize,
pub line_pos : usize
}
impl Lexer{
pub fn new(src_code : String)->Self{
Lexer{ src_code : src_code.as_bytes().to_vec(), line_pos : 1, ..Default::default()}
}
//FIXME: get_char() shouldn't be exposed
pub fn get_char(&mut self){
if self.char_pos < self.src_code.len() {
self.curr_char = self.src_code[self.char_pos] as char;
self.char_pos += 1;
}
else{
self.curr_char = '\0';
}
}
pub fn peek_next(&mut self) -> Token{
//save context
let old_pos = self.char_pos;
let old_tok = self.curr_token;
let old_string = self.curr_string.clone();
let t = self.get_token();
//load saved context
self.char_pos = old_pos;
self.curr_token = old_tok;
self.curr_string = old_string;
t
}
pub fn get_token(&mut self) -> Token{
//do not loop over the match
//this will cause a problem for ident storing (curr_string.clear())
macro_rules! get_cur_tok_and_eat{
//without the double curly braces, compiler complains saying everything after the
//first statement will be ignored. So we tell it to treat the body as a block
($e : path) => {{self.curr_token = $e; self.get_char(); self.curr_token}}
}
match self.curr_char{
'+' => { get_cur_tok_and_eat!(Token::Plus)},
'-' => { get_cur_tok_and_eat!(Token::Minus)},
'*' => { get_cur_tok_and_eat!(Token::Mul)},
'/' => { get_cur_tok_and_eat!(Token::Div)},
'&' => { get_cur_tok_and_eat!(Token::LogAnd)},
'|' => { get_cur_tok_and_eat!(Token::LogOr)},
'>' => {
self.get_char();
self.curr_token = Token::GreaterThan;
if self.curr_char == '=' {
self.get_char();
self.curr_token = Token::GreaterEquals;
}
self.curr_token
},
'<' => {
self.get_char();
self.curr_token =
if self.curr_char == '>' {
self.get_char();
Token::LessThanGreaterThan
}
else if self.curr_char == '=' {
self.get_char();
Token::LessEquals
}
else{
Token::LessThan
};
self.curr_token
},
'.' =>{
self.curr_token = Token::Dot;
self.get_char();
self.curr_token
},
'=' => {
self.get_char();
self.curr_token = Token::Equals;
self.curr_token
},
'{' => { get_cur_tok_and_eat!(Token::LeftCurly)},
'}' => { get_cur_tok_and_eat!(Token::RightCurly)},
'[' => { get_cur_tok_and_eat!(Token::LeftSquare)},
']' => { get_cur_tok_and_eat!(Token::RightSquare)},
'(' => { get_cur_tok_and_eat!(Token::LeftParen)},
')' => { get_cur_tok_and_eat!(Token::RightParen)},
',' => { get_cur_tok_and_eat!(Token::Comma)},
':' => {
self.get_char();
self.curr_token =
if self.curr_char == '=' {
self.get_char();
Token::ColonEquals
}
else {
Token::Colon
};
self.curr_token
},
';' => { self.curr_token = Token::SemiColon; self.get_char(); self.curr_token},
'"' => {
self.curr_string.clear();
loop {
self.get_char();
if self.curr_char == '\\' {
self.get_char();
match self.curr_char {
'n' => self.curr_string.push('\n'),
't' => self.curr_string.push('\t'),
'"' => self.curr_string.push('"'),
'\\' => self.curr_string.push('\\'),
_ => panic!("Unrecognized escape sequence")
}
//self.curr_string.push(self.curr_char);
continue;
}
if self.curr_char == '"' {
self.get_char(); //eat "
break;
}
if self.curr_char == '\0' {
panic!("Unexpected eof. Expected a closing '\"'.");
}
self.curr_string.push(self.curr_char);
}
self.curr_token = Token::TokString;
self.curr_token
},
'0' ... '9' => {
self.curr_string.clear();
self.curr_string.push(self.curr_char);
self.get_char();
while self.curr_char.is_digit(10) && self.curr_char != '\0' {
self.curr_string.push(self.curr_char);
self.get_char();
}
self.curr_token = Token::Number;
self.curr_token
},
'a' ... 'z' => {
self.curr_string.clear();
self.curr_string.push(self.curr_char);
self.get_char();
while self.curr_char.is_alphanumeric() && self.curr_char != '\0' {
self.curr_string.push(self.curr_char);
self.get_char();
}
self.curr_token = self.match_token(); //mat(&self.curr_string) {return Token::} else {return Token::Ident}
self.curr_token
},
//\n is also whitespace. So put it before whitespace check
'\0' => {self.curr_token = Token::Eof; self.curr_token},
'\n' => { self.line_pos += 1; self.curr_token = Token::NewLine; self.get_char(); self.curr_token },
c if c.is_whitespace() => {
loop{
self.get_char();
if !self.curr_char.is_whitespace(){
break;
}
}
self.curr_token = self.get_token();
self.curr_token
},
_ => {self.curr_token = Token::Error; self.curr_token}
}
}
fn run(&mut self){
while self.char_pos < self.src_code.len(){
self.get_char();
if !self.curr_char.is_whitespace(){
self.get_char();
}
else{
let _ = self.match_token();
}
}
}
fn match_token(&self)->Token{
match &*self.curr_string{
"let" => Token::Let,
"var" => Token::Var,
"array" => Token::Array,
"rec" => Token::Rec,
"of" => Token::Of,
"type" => Token::Type,
"break" => Token::Break,
"do" => Token::Do,
"end" => Token::End,
"while" => Token::While,
"if" => Token::If,
"then" => Token::Then,
"else" => Token::Else,
"for" => Token::For,
"in" => Token::In,
"function" => Token::Function,
"nil" => Token::Nil,
"int" => Token::Int,
"string" => Token::TokString,
"to" => Token::To,
_ => Token::Ident
}
}
}
#[cfg(test)]
mod tests {
use parse::tokens::*;
use super::*; //use stuff thats in the file but outside this module
#[test]
fn test_match_token_binary_exp_nums(){
let mut l = Lexer::new("1234+23451".to_string());
l.get_char();
assert!(l.get_token() == Token::Number);
assert!(l.get_token() == Token::Plus);
assert!(l.get_token() == Token::Number);
}
#[test]
fn test_match_token_binary_exp_vars(){
let mut l = Lexer::new("a+a".to_string());
l.get_char();
assert!(l.get_token() == Token::Ident);
assert!(l.get_token() == Token::Plus);
assert!(l.get_token() == Token::Ident);
}
#[test]
fn test_match_token_binary_exp_mixed(){
let mut l = Lexer::new("a+1".to_string());
l.get_char();
assert!(l.get_token() == Token::Ident);
assert!(l.get_token() == Token::Plus);
assert!(l.get_token() == Token::Number);
}
#[test]
fn test_match_token_binary_exp_mixed_multiple_terms(){
let mut l = Lexer::new("a+1+a".to_string());
l.get_char();
assert!(l.get_token() == Token::Ident);
assert!(l.get_token() == Token::Plus);
assert!(l.get_token() == Token::Number);
assert!(l.get_token() == Token::Plus);
assert!(l.get_token() == Token::Ident);
}
#[test]
fn test_get_char(){
let mut l = Lexer::new("1+1".to_string());
l.get_char();
assert!(l.curr_char == '1');
l.get_char();
assert!(l.curr_char == '+');
}
#[test]
fn test_match_newline(){
let mut l = Lexer::new("\n".to_string());
l.get_char();
assert!(l.get_token() == Token::NewLine);
assert!(l.get_token() == Token::Eof);
}
#[test]
fn test_line_pos(){
let mut l = Lexer::new("\n\n\n".to_string());
l.get_char();
l.get_token();
assert!(l.line_pos == 2);
l.get_token();
assert!(l.line_pos == 3);
l.get_token();
assert!(l.line_pos == 4);
}
#[test]
fn test_let_block(){
let mut l = Lexer::new("let var a : int := 1 in end".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Let);
assert_eq!(l.get_token(), Token::Var);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Colon);
assert_eq!(l.get_token(), Token::Int);
assert_eq!(l.get_token(), Token::ColonEquals);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::In);
assert_eq!(l.get_token(), Token::End);
}
#[test]
fn test_let_block_with_2_var_decls(){
let mut l = Lexer::new("let var a : int := 1\nvar b : int:=2\n in end".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Let);
assert_eq!(l.get_token(), Token::Var);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Colon);
assert_eq!(l.get_token(), Token::Int);
assert_eq!(l.get_token(), Token::ColonEquals);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::NewLine);
assert_eq!(l.get_token(), Token::Var);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Colon);
assert_eq!(l.get_token(), Token::Int);
assert_eq!(l.get_token(), Token::ColonEquals);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::NewLine);
assert_eq!(l.get_token(), Token::In);
assert_eq!(l.get_token(), Token::End);
}
#[test]
fn test_let_without_spaces() {
let mut l = Lexer::new("let var a:int := 1 in end".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Let);
assert_eq!(l.get_token(), Token::Var);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Colon);
assert_eq!(l.get_token(), Token::Int);
assert_eq!(l.get_token(), Token::ColonEquals);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::In);
assert_eq!(l.get_token(), Token::End);
}
#[test]
fn test_type_dec_int() {
let mut l = Lexer::new("type a = int".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Type);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Equals);
assert_eq!(l.get_token(), Token::Int);
}
#[test]
fn test_type_dec_array_of_int() {
let mut l = Lexer::new("type ai = array of int".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Type);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Equals);
assert_eq!(l.get_token(), Token::Array);
assert_eq!(l.get_token(), Token::Of);
assert_eq!(l.get_token(), Token::Int);
}
#[test]
fn test_field_dec_int() {
let mut l = Lexer::new("(a:int)".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::LeftParen);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Colon);
assert_eq!(l.get_token(), Token::Int);
}
#[test]
fn test_call_expr() {
let mut l = Lexer::new("f(1)".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::LeftParen);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::RightParen);
}
#[test]
fn test_call_expr_string_arg() {
let mut l = Lexer::new("f(\"abc\")".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::LeftParen);
assert_eq!(l.get_token(), Token::TokString);
assert_eq!(l.get_token(), Token::RightParen);
}
#[test]
fn test_simple_string() {
let mut l = Lexer::new("\"abhi\"".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::TokString);
assert_eq!(l.curr_string, "abhi".to_string());
}
#[test]
fn test_string_with_escaped_double_quote() {
let mut l = Lexer::new("\"ab\\\"hi\"".to_string());
l.get_char();
l.get_token();
assert_eq!(l.curr_string, "ab\"hi".to_string());
}
#[test]
fn test_string_with_escaped_backslash() {
let mut l = Lexer::new("\"ab\\\\\"".to_string());
l.get_char();
l.get_token();
assert_eq!(l.curr_string, "ab\\".to_string());
}
#[test]
fn test_if_then(){
let mut l = Lexer::new("if 1 then 1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::If);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Then);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_if_then_else(){
let mut l = Lexer::new("if 1 then 1 else 0".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::If);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Then);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Else);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_while_block(){
let mut l = Lexer::new("while 1 do 1+1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::While);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Do);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Plus);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_for_loop(){
let mut l = Lexer::new("for id := 1 to 9 do 1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::For);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::ColonEquals);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::To);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Do);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_less_than_expr(){
let mut l = Lexer::new("1 <1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::LessThan);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_less_than_equals_expr(){
let mut l = Lexer::new("1 <=1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::LessEquals);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_greater_than_equals_expr(){
let mut l = Lexer::new("1 >=1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::GreaterEquals);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_greater_than_expr(){
let mut l = Lexer::new("1 >1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::GreaterThan);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_not_equals_expr(){
let mut l = Lexer::new("1 <> 1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::LessThanGreaterThan);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_equals_expr(){
let mut l = Lexer::new("1 = 1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Equals);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_peek(){
let mut l = Lexer::new("1 <> 1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.peek_next(), Token::LessThanGreaterThan);
assert_eq!(l.peek_next(), Token::LessThanGreaterThan);
assert_eq!(l.get_token(), Token::LessThanGreaterThan);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_div_expr(){
let mut l = Lexer::new("1 / 1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Div);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_div_expr_without_spaces(){
let mut l = Lexer::new("1/1".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::Div);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_function_call_with_two_args(){
let mut l = Lexer::new("f(a()+1)".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::LeftParen);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::LeftParen);
assert_eq!(l.get_token(), Token::RightParen);
assert_eq!(l.get_token(), Token::Plus);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_function_call_with_two_args_2(){
let mut l = Lexer::new("f(a()+1)".to_string());
l.get_char();
loop{
match l.get_token(){
Token::Ident => println!("{:?}", l.curr_token),
Token::LeftParen => println!("{:?}", l.curr_token),
Token::RightParen => println!("{:?}", l.curr_token),
Token::Plus => println!("{:?}", l.curr_token),
Token::Number => println!("{:?}", l.curr_token),
_ => break
}
}
}
#[test]
fn test_array_decl(){
let mut l = Lexer::new("array of int[3] of 0".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Array);
assert_eq!(l.get_token(), Token::Of);
assert_eq!(l.get_token(), Token::Int);
assert_eq!(l.get_token(), Token::LeftSquare);
assert_eq!(l.get_token(), Token::Number);
assert_eq!(l.get_token(), Token::RightSquare);
assert_eq!(l.get_token(), Token::Of);
assert_eq!(l.get_token(), Token::Number);
}
#[test]
fn test_typdef_decl(){
let mut l = Lexer::new("type r = {a:int}".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Type);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Equals);
assert_eq!(l.get_token(), Token::LeftCurly);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Colon);
assert_eq!(l.get_token(), Token::Int);
assert_eq!(l.get_token(), Token::RightCurly);
}
#[test]
fn test_record_decl(){
let mut l = Lexer::new("r{a:int}".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::LeftCurly);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Colon);
assert_eq!(l.get_token(), Token::Int);
assert_eq!(l.get_token(), Token::RightCurly);
}
#[test]
fn test_record_access(){
let mut l = Lexer::new("a.x".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Dot);
assert_eq!(l.get_token(), Token::Ident);
}
#[test]
fn test_multi_record_access(){
let mut l = Lexer::new("a.x.b.c".to_string());
l.get_char();
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Dot);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Dot);
assert_eq!(l.get_token(), Token::Ident);
assert_eq!(l.get_token(), Token::Dot);
assert_eq!(l.get_token(), Token::Ident);
}
}
|
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::{max, min, Reverse};
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
fn main() {
input! {
n: usize,
k: usize,
mut td: [(usize, usize); n],
}
td.sort_by_key(|&(_, di)| di);
td.reverse();
let mut s = 0;
let mut heap = BinaryHeap::new();
let mut ts = HashSet::new();
for i in 0..k {
let (ti, di) = td[i];
if ts.contains(&ti) {
heap.push(Reverse(di));
} else {
s += ts.len() * 2 + 1;
ts.insert(ti);
}
s += di;
}
let mut d = vec![];
let mut i = k;
while let Some(Reverse(dj)) = heap.pop() {
while i < n && ts.contains(&td[i].0) {
i += 1;
}
if i < n {
let (ti, di) = td[i];
d.push((ts.len() * 2 + 1 + di) as i64 - dj as i64);
ts.insert(ti);
}
}
if d.len() > 0 {
// eprintln!("{:?}", d);
let mut dsum = vec![0; d.len()];
dsum[0] = d[0];
for i in 1..d.len() {
dsum[i] = dsum[i - 1] + d[i];
}
// eprintln!("{:?}", dsum);
if let Some(&d_max) = dsum.iter().max() {
if d_max > 0 {
s += d_max as usize;
}
}
}
println!("{}", s);
}
|
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
extern crate link_cplusplus;
mod inner {
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
// Overwrite the types of these to be `usize`s.
pub const RANDOMX_HASH_SIZE: usize = inner::RANDOMX_HASH_SIZE as _;
pub const RANDOMX_DATASET_ITEM_SIZE: usize = inner::RANDOMX_DATASET_ITEM_SIZE as _;
pub use inner::*;
|
//! JpDependencyParser LibPort
use libc::*;
use std::ffi::{CStr, CString};
use std::ptr::NonNull;
use std::slice;
#[repr(C)]
pub struct Chunk {
pub link: c_int,
pub head_pos: usize,
pub func_pos: usize,
pub token_size: usize,
pub token_pos: usize,
pub score: c_float,
pub feature_list: *const *const c_char,
pub additional_info: *const c_char,
pub feature_list_size: c_ushort,
}
#[repr(C)]
pub struct Token {
pub surface: *const c_char,
pub normalized_surface: *const c_char,
pub feature: *const c_char,
pub feature_list: *const *const c_char,
pub feature_list_size: c_ushort,
pub ne: *const c_char,
pub additional_info: *const c_char,
pub chunk: *const Chunk,
}
impl Chunk {
/*pub fn features(&self) -> Vec<&str> {
unsafe {
slice::from_raw_parts(self.feature_list, self.feature_list_size as _)
.iter().map(|&p| CStr::from_ptr(p).to_str().unwrap()).collect()
}
}*/
pub fn is_root(&self) -> bool {
self.link < 0
}
}
impl Token {
pub fn surface_normalized(&self) -> &str {
unsafe { CStr::from_ptr(self.normalized_surface).to_str().unwrap() }
}
pub fn features(&self) -> impl Iterator<Item = &str> {
unsafe {
slice::from_raw_parts(self.feature_list, self.feature_list_size as _)
.iter()
.map(|&p| CStr::from_ptr(p).to_str().unwrap())
}
}
/// 品詞
pub fn primary_part(&self) -> &str {
self.features().next().unwrap()
}
/// 原型
pub fn base_form(&self) -> &str {
self.features().nth(6).unwrap()
}
/// 読み(カタカナ)
pub fn reading_form(&self) -> Option<&str> {
self.features().nth(7)
}
}
#[link(name = "cabocha")]
extern "C" {
fn cabocha_new2(arg: *const c_char) -> *mut c_void;
fn cabocha_destroy(cabocha: *mut c_void);
fn cabocha_sparse_totree2(cabocha: *mut c_void, s: *const c_char, length: usize)
-> *mut c_void;
fn cabocha_tree_chunk_size(tree: *mut c_void) -> usize;
fn cabocha_tree_token(tree: *mut c_void, i: usize) -> *mut Token;
fn cabocha_tree_chunk(tree: *mut c_void, i: usize) -> *mut Chunk;
}
pub struct Cabocha(NonNull<c_void>);
impl Cabocha {
pub fn new(arg: &str) -> Self {
let carg = CString::new(arg).unwrap();
NonNull::new(unsafe { cabocha_new2(carg.as_ptr()) })
.map(Cabocha)
.expect("Failed to initialize CaboCha")
}
}
impl Drop for Cabocha {
fn drop(&mut self) {
unsafe { cabocha_destroy(self.0.as_ptr()) }
}
}
pub struct TreeRef(NonNull<c_void>);
impl Cabocha {
pub fn parse_str_to_tree(&self, s: &str) -> TreeRef {
NonNull::new(unsafe {
cabocha_sparse_totree2(self.0.as_ptr(), s.as_ptr() as *const _, s.as_bytes().len())
})
.map(TreeRef)
.unwrap()
}
}
impl TreeRef {
pub fn chunk_size(&self) -> usize {
unsafe { cabocha_tree_chunk_size(self.0.as_ptr()) }
}
pub fn chunk(&self, index: usize) -> Option<&Chunk> {
unsafe { cabocha_tree_chunk(self.0.as_ptr(), index).as_ref() }
}
pub fn token(&self, index: usize) -> Option<&Token> {
unsafe { cabocha_tree_token(self.0.as_ptr(), index).as_ref() }
}
}
pub struct ChunkIter<'c> {
source: &'c TreeRef,
current: usize,
}
impl TreeRef {
pub fn chunks<'c>(&'c self) -> ChunkIter<'c> {
ChunkIter {
source: self,
current: 0,
}
}
}
/*impl<'c> ChunkIter<'c> {
pub fn at(&self, index: usize) -> Option<&'c Token> {
let ix = self.current + index;
if ix < self.source.chunk_size() { self.source.token(ix) } else { None }
}
}*/
impl<'c> Iterator for ChunkIter<'c> {
type Item = &'c Chunk;
fn next(&mut self) -> Option<&'c Chunk> {
if self.current == self.source.chunk_size() {
return None;
}
let t = self.source.chunk(self.current);
if t.is_some() {
self.current += 1;
}
return t;
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len(), Some(self.len()))
}
}
impl<'c> ExactSizeIterator for ChunkIter<'c> {
fn len(&self) -> usize {
self.source.chunk_size() - self.current
}
}
pub struct TokenIter<'c> {
source: &'c TreeRef,
current: usize,
end: usize,
}
impl Chunk {
pub fn tokens<'c>(&self, source: &'c TreeRef) -> TokenIter<'c> {
TokenIter {
source,
current: self.token_pos,
end: self.token_pos + self.token_size,
}
}
}
impl<'c> TokenIter<'c> {
pub fn at(&self, index: usize) -> Option<&'c Token> {
let ix = self.current + index;
if ix < self.end {
self.source.token(ix)
} else {
None
}
}
}
impl<'c> Iterator for TokenIter<'c> {
type Item = &'c Token;
fn next(&mut self) -> Option<&'c Token> {
if self.current == self.end {
return None;
}
let t = self.source.token(self.current);
if t.is_some() {
self.current += 1;
}
return t;
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len(), Some(self.len()))
}
}
impl<'c> ExactSizeIterator for TokenIter<'c> {
fn len(&self) -> usize {
self.end - self.current
}
}
|
extern crate sdl2;
use sdl2::pixels::Color;
use std::{thread, time};
use std::intrinsics::size_of;
use std::ptr::null;
const SCREEN_WIDTH: u32 = 1024;
const SCREEN_HEIGHT: u32 = 768;
const SCREEN_PITCH: u32 = SCREEN_WIDTH * SCREEN_HEIGHT * 4;
const SCREEN_ASPECT_RATIO: f32 = SCREEN_WIDTH / SCREEN_HEIGHT as f32;
struct DisplayManager {}
impl DisplayManager {
pub fn new() -> Self {
DisplayManager {}
}
pub fn startSDL() {
let sdl2_context = sdl2::init().unwrap();
let video = sdl2_context.video().unwrap();
let window = video
.window("Arcade Shooter", SCREEN_WIDTH, SCREEN_HEIGHT)
.position_centered()
.opengl()
.build()
.unwrap();
if sdl2_context == null() || video == null() || window == null {
return;
}
}
} |
use crate::erlang::throw_1::result;
use crate::test::strategy;
#[test]
fn throws_reason() {
run!(
|arc_process| strategy::term(arc_process.clone()),
|reason| {
let actual = result(reason);
if let Err(liblumen_alloc::erts::exception::Exception::Runtime(
liblumen_alloc::erts::exception::RuntimeException::Throw(ref throw),
)) = actual
{
let source_message = format!("{:?}", throw.source());
let expected_substring = "explicit throw from Erlang";
assert!(
source_message.contains(expected_substring),
"source message ({}) does not contain {:?}",
source_message,
expected_substring
);
} else {
panic!("expected to throw, but got {:?}", actual);
}
Ok(())
},
);
}
|
// 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.
#![warn(missing_docs)]
//! Searches the local component index for matching programs.
use failure::{err_msg, format_err, Error, ResultExt};
use fidl_fuchsia_sys_index::{ComponentIndexMarker, FuzzySearchError};
use fuchsia_async as fasync;
use fuchsia_component::client::{launch, launcher};
use std::convert::{TryFrom, TryInto};
use std::env;
#[fasync::run_singlethreaded]
async fn main() {
match run_locate().await {
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
Ok(()) => {}
}
}
async fn run_locate() -> Result<(), Error> {
let cfg: LocateConfig = env::args().try_into()?;
if cfg.help {
help();
return Ok(());
}
let launcher = launcher().context("Failed to open launcher service.")?;
let app = launch(
&launcher,
"fuchsia-pkg://fuchsia.com/component_index#meta/component_index.cmx".to_string(),
None,
)
.context("Failed to launch component_index service.")?;
let component_index = app
.connect_to_service::<ComponentIndexMarker>()
.context("Failed to connect to component_index service.")?;
match component_index.fuzzy_search(&cfg.search_keyword).await? {
Ok(res_vec) => fuzzy_search_result(res_vec, cfg),
Err(e) => fuzzy_search_error(e, cfg),
}
}
fn fuzzy_search_result(res_vec: Vec<String>, cfg: LocateConfig) -> Result<(), Error> {
if res_vec.is_empty() {
return Err(format_err!("\"{}\" did not match any components.", cfg.search_keyword));
}
if cfg.list {
for res in &res_vec {
println!("{}", res);
}
} else {
if res_vec.len() == 1 {
println!("{}", res_vec[0]);
} else {
for res in &res_vec {
eprintln!("{}", res);
}
return Err(format_err!(
"\"{}\" matched more than one component. Try `locate --list` instead.",
cfg.search_keyword
));
}
}
Ok(())
}
fn fuzzy_search_error(e: FuzzySearchError, cfg: LocateConfig) -> Result<(), Error> {
if e == FuzzySearchError::MalformedInput {
return Err(format_err!(
"\"{}\" contains unsupported characters. Valid characters are [A-Z a-z 0-9 / _ - .].",
cfg.search_keyword
));
}
Err(err_msg("fuchsia.sys.index.FuzzySearch could not serve the input query."))
}
struct LocateConfig {
list: bool,
help: bool,
search_keyword: String,
}
impl TryFrom<env::Args> for LocateConfig {
type Error = Error;
fn try_from(args: env::Args) -> Result<LocateConfig, Error> {
let mut args = args.peekable();
// Ignore arg[0]
let _ = args.next();
// check if arg[1] is '--help'
let show_help = args.peek() == Some(&"--help".to_string());
if show_help {
return Ok(LocateConfig {
list: false,
help: show_help,
search_keyword: String::from(""),
});
}
// Consume arg[1] if it is --list
let list = args.peek() == Some(&"--list".to_string());
if list {
let _ = args.next();
}
// Ensure nothing beyond current arg.
if let (Some(search_keyword), None) = (args.next(), args.next()) {
return Ok(LocateConfig { list, help: show_help, search_keyword });
} else {
help();
return Err(err_msg("Unable to parse args."));
}
}
}
fn help() {
print!(
r"Usage: locate [--help] [--list] <search_keyword>
Locates the fuchsia-pkg URL of <search_keyword>.
Options:
--list Allows matching of more than one component.
--help Prints this message.
"
)
}
|
// Determine if Two Strings Are Close
// https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3613/
use std::collections::HashMap;
pub struct Solution;
#[derive(PartialEq, Eq)]
struct Signature {
charset: Vec<char>,
frequencies: Vec<usize>,
}
impl Signature {
pub fn from(word: String) -> Self {
let mut by_char: HashMap<char, usize> = HashMap::new();
for char in word.chars() {
*by_char.entry(char).or_default() += 1;
}
let mut charset: Vec<char> = by_char.keys().copied().collect();
charset.sort_unstable();
let mut frequencies: Vec<usize> = by_char.values().copied().collect();
frequencies.sort_unstable();
Self {
charset,
frequencies,
}
}
}
impl Solution {
pub fn close_strings(word1: String, word2: String) -> bool {
word1.len() == word2.len()
&& Signature::from(word1) == Signature::from(word2)
}
// Top from leetcode
#[cfg(disable)]
pub fn close_strings(word1: String, word2: String) -> bool {
if word1.len() != word2.len() {
return false;
}
let mut chars1 = [0; 26];
for c in word1.bytes() {
let idx = (c - b'a') as usize;
chars1[idx] += 1;
}
let mut chars2 = [0; 26];
for c in word2.bytes() {
let idx = (c - b'a') as usize;
if chars1[idx] == 0 {
return false;
}
chars2[idx] += 1;
}
chars1.sort_unstable();
chars2.sort_unstable();
chars1 == chars2
}
}
#[cfg(test)]
mod tests {
use super::*;
fn check(word1: &str, word2: &str, expected: bool) {
assert_eq!(
Solution::close_strings(word1.into(), word2.into()),
expected
);
}
#[test]
fn example1() {
check("abc", "bca", true);
}
#[test]
fn example2() {
check("a", "aa", false);
}
#[test]
fn example3() {
check("cabbba", "abbccc", true);
}
#[test]
fn example4() {
check("cabbba", "aabbss", false);
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qstorageinfo.h
// dst-file: /src/core/qstorageinfo.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 std::ops::Deref;
use super::qbytearray::*; // 773
use super::qstring::*; // 773
// use super::qlist::*; // 775
use super::qdir::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QStorageInfo_Class_Size() -> c_int;
// proto: qint64 QStorageInfo::bytesFree();
fn C_ZNK12QStorageInfo9bytesFreeEv(qthis: u64 /* *mut c_void*/) -> c_longlong;
// proto: void QStorageInfo::QStorageInfo(const QStorageInfo & other);
fn C_ZN12QStorageInfoC2ERKS_(arg0: *mut c_void) -> u64;
// proto: bool QStorageInfo::isRoot();
fn C_ZNK12QStorageInfo6isRootEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QStorageInfo::isReadOnly();
fn C_ZNK12QStorageInfo10isReadOnlyEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QByteArray QStorageInfo::fileSystemType();
fn C_ZNK12QStorageInfo14fileSystemTypeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QStorageInfo::setPath(const QString & path);
fn C_ZN12QStorageInfo7setPathERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static QList<QStorageInfo> QStorageInfo::mountedVolumes();
fn C_ZN12QStorageInfo14mountedVolumesEv() -> *mut c_void;
// proto: QString QStorageInfo::name();
fn C_ZNK12QStorageInfo4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QStorageInfo::refresh();
fn C_ZN12QStorageInfo7refreshEv(qthis: u64 /* *mut c_void*/);
// proto: bool QStorageInfo::isValid();
fn C_ZNK12QStorageInfo7isValidEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QStorageInfo::isReady();
fn C_ZNK12QStorageInfo7isReadyEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: qint64 QStorageInfo::bytesTotal();
fn C_ZNK12QStorageInfo10bytesTotalEv(qthis: u64 /* *mut c_void*/) -> c_longlong;
// proto: QString QStorageInfo::rootPath();
fn C_ZNK12QStorageInfo8rootPathEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QStorageInfo::~QStorageInfo();
fn C_ZN12QStorageInfoD2Ev(qthis: u64 /* *mut c_void*/);
// proto: qint64 QStorageInfo::bytesAvailable();
fn C_ZNK12QStorageInfo14bytesAvailableEv(qthis: u64 /* *mut c_void*/) -> c_longlong;
// proto: void QStorageInfo::QStorageInfo();
fn C_ZN12QStorageInfoC2Ev() -> u64;
// proto: void QStorageInfo::QStorageInfo(const QDir & dir);
fn C_ZN12QStorageInfoC2ERK4QDir(arg0: *mut c_void) -> u64;
// proto: static QStorageInfo QStorageInfo::root();
fn C_ZN12QStorageInfo4rootEv() -> *mut c_void;
// proto: void QStorageInfo::QStorageInfo(const QString & path);
fn C_ZN12QStorageInfoC2ERK7QString(arg0: *mut c_void) -> u64;
// proto: QByteArray QStorageInfo::device();
fn C_ZNK12QStorageInfo6deviceEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QStorageInfo::displayName();
fn C_ZNK12QStorageInfo11displayNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QStorageInfo::swap(QStorageInfo & other);
fn C_ZN12QStorageInfo4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QStorageInfo)=1
#[derive(Default)]
pub struct QStorageInfo {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QStorageInfo {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QStorageInfo {
return QStorageInfo{qclsinst: qthis, ..Default::default()};
}
}
// proto: qint64 QStorageInfo::bytesFree();
impl /*struct*/ QStorageInfo {
pub fn bytesFree<RetType, T: QStorageInfo_bytesFree<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bytesFree(self);
// return 1;
}
}
pub trait QStorageInfo_bytesFree<RetType> {
fn bytesFree(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: qint64 QStorageInfo::bytesFree();
impl<'a> /*trait*/ QStorageInfo_bytesFree<i64> for () {
fn bytesFree(self , rsthis: & QStorageInfo) -> i64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo9bytesFreeEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo9bytesFreeEv(rsthis.qclsinst)};
return ret as i64; // 1
// return 1;
}
}
// proto: void QStorageInfo::QStorageInfo(const QStorageInfo & other);
impl /*struct*/ QStorageInfo {
pub fn new<T: QStorageInfo_new>(value: T) -> QStorageInfo {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QStorageInfo_new {
fn new(self) -> QStorageInfo;
}
// proto: void QStorageInfo::QStorageInfo(const QStorageInfo & other);
impl<'a> /*trait*/ QStorageInfo_new for (&'a QStorageInfo) {
fn new(self) -> QStorageInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfoC2ERKS_()};
let ctysz: c_int = unsafe{QStorageInfo_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN12QStorageInfoC2ERKS_(arg0)};
let rsthis = QStorageInfo{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: bool QStorageInfo::isRoot();
impl /*struct*/ QStorageInfo {
pub fn isRoot<RetType, T: QStorageInfo_isRoot<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isRoot(self);
// return 1;
}
}
pub trait QStorageInfo_isRoot<RetType> {
fn isRoot(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: bool QStorageInfo::isRoot();
impl<'a> /*trait*/ QStorageInfo_isRoot<i8> for () {
fn isRoot(self , rsthis: & QStorageInfo) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo6isRootEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo6isRootEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QStorageInfo::isReadOnly();
impl /*struct*/ QStorageInfo {
pub fn isReadOnly<RetType, T: QStorageInfo_isReadOnly<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isReadOnly(self);
// return 1;
}
}
pub trait QStorageInfo_isReadOnly<RetType> {
fn isReadOnly(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: bool QStorageInfo::isReadOnly();
impl<'a> /*trait*/ QStorageInfo_isReadOnly<i8> for () {
fn isReadOnly(self , rsthis: & QStorageInfo) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo10isReadOnlyEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo10isReadOnlyEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QByteArray QStorageInfo::fileSystemType();
impl /*struct*/ QStorageInfo {
pub fn fileSystemType<RetType, T: QStorageInfo_fileSystemType<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.fileSystemType(self);
// return 1;
}
}
pub trait QStorageInfo_fileSystemType<RetType> {
fn fileSystemType(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: QByteArray QStorageInfo::fileSystemType();
impl<'a> /*trait*/ QStorageInfo_fileSystemType<QByteArray> for () {
fn fileSystemType(self , rsthis: & QStorageInfo) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo14fileSystemTypeEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo14fileSystemTypeEv(rsthis.qclsinst)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QStorageInfo::setPath(const QString & path);
impl /*struct*/ QStorageInfo {
pub fn setPath<RetType, T: QStorageInfo_setPath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPath(self);
// return 1;
}
}
pub trait QStorageInfo_setPath<RetType> {
fn setPath(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: void QStorageInfo::setPath(const QString & path);
impl<'a> /*trait*/ QStorageInfo_setPath<()> for (&'a QString) {
fn setPath(self , rsthis: & QStorageInfo) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfo7setPathERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QStorageInfo7setPathERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static QList<QStorageInfo> QStorageInfo::mountedVolumes();
impl /*struct*/ QStorageInfo {
pub fn mountedVolumes_s<RetType, T: QStorageInfo_mountedVolumes_s<RetType>>( overload_args: T) -> RetType {
return overload_args.mountedVolumes_s();
// return 1;
}
}
pub trait QStorageInfo_mountedVolumes_s<RetType> {
fn mountedVolumes_s(self ) -> RetType;
}
// proto: static QList<QStorageInfo> QStorageInfo::mountedVolumes();
impl<'a> /*trait*/ QStorageInfo_mountedVolumes_s<u64> for () {
fn mountedVolumes_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfo14mountedVolumesEv()};
let mut ret = unsafe {C_ZN12QStorageInfo14mountedVolumesEv()};
return ret as u64; // 5
// return 1;
}
}
// proto: QString QStorageInfo::name();
impl /*struct*/ QStorageInfo {
pub fn name<RetType, T: QStorageInfo_name<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.name(self);
// return 1;
}
}
pub trait QStorageInfo_name<RetType> {
fn name(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: QString QStorageInfo::name();
impl<'a> /*trait*/ QStorageInfo_name<QString> for () {
fn name(self , rsthis: & QStorageInfo) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo4nameEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo4nameEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QStorageInfo::refresh();
impl /*struct*/ QStorageInfo {
pub fn refresh<RetType, T: QStorageInfo_refresh<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.refresh(self);
// return 1;
}
}
pub trait QStorageInfo_refresh<RetType> {
fn refresh(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: void QStorageInfo::refresh();
impl<'a> /*trait*/ QStorageInfo_refresh<()> for () {
fn refresh(self , rsthis: & QStorageInfo) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfo7refreshEv()};
unsafe {C_ZN12QStorageInfo7refreshEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QStorageInfo::isValid();
impl /*struct*/ QStorageInfo {
pub fn isValid<RetType, T: QStorageInfo_isValid<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isValid(self);
// return 1;
}
}
pub trait QStorageInfo_isValid<RetType> {
fn isValid(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: bool QStorageInfo::isValid();
impl<'a> /*trait*/ QStorageInfo_isValid<i8> for () {
fn isValid(self , rsthis: & QStorageInfo) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo7isValidEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo7isValidEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QStorageInfo::isReady();
impl /*struct*/ QStorageInfo {
pub fn isReady<RetType, T: QStorageInfo_isReady<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isReady(self);
// return 1;
}
}
pub trait QStorageInfo_isReady<RetType> {
fn isReady(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: bool QStorageInfo::isReady();
impl<'a> /*trait*/ QStorageInfo_isReady<i8> for () {
fn isReady(self , rsthis: & QStorageInfo) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo7isReadyEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo7isReadyEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: qint64 QStorageInfo::bytesTotal();
impl /*struct*/ QStorageInfo {
pub fn bytesTotal<RetType, T: QStorageInfo_bytesTotal<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bytesTotal(self);
// return 1;
}
}
pub trait QStorageInfo_bytesTotal<RetType> {
fn bytesTotal(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: qint64 QStorageInfo::bytesTotal();
impl<'a> /*trait*/ QStorageInfo_bytesTotal<i64> for () {
fn bytesTotal(self , rsthis: & QStorageInfo) -> i64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo10bytesTotalEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo10bytesTotalEv(rsthis.qclsinst)};
return ret as i64; // 1
// return 1;
}
}
// proto: QString QStorageInfo::rootPath();
impl /*struct*/ QStorageInfo {
pub fn rootPath<RetType, T: QStorageInfo_rootPath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rootPath(self);
// return 1;
}
}
pub trait QStorageInfo_rootPath<RetType> {
fn rootPath(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: QString QStorageInfo::rootPath();
impl<'a> /*trait*/ QStorageInfo_rootPath<QString> for () {
fn rootPath(self , rsthis: & QStorageInfo) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo8rootPathEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo8rootPathEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QStorageInfo::~QStorageInfo();
impl /*struct*/ QStorageInfo {
pub fn free<RetType, T: QStorageInfo_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QStorageInfo_free<RetType> {
fn free(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: void QStorageInfo::~QStorageInfo();
impl<'a> /*trait*/ QStorageInfo_free<()> for () {
fn free(self , rsthis: & QStorageInfo) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfoD2Ev()};
unsafe {C_ZN12QStorageInfoD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: qint64 QStorageInfo::bytesAvailable();
impl /*struct*/ QStorageInfo {
pub fn bytesAvailable<RetType, T: QStorageInfo_bytesAvailable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bytesAvailable(self);
// return 1;
}
}
pub trait QStorageInfo_bytesAvailable<RetType> {
fn bytesAvailable(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: qint64 QStorageInfo::bytesAvailable();
impl<'a> /*trait*/ QStorageInfo_bytesAvailable<i64> for () {
fn bytesAvailable(self , rsthis: & QStorageInfo) -> i64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo14bytesAvailableEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo14bytesAvailableEv(rsthis.qclsinst)};
return ret as i64; // 1
// return 1;
}
}
// proto: void QStorageInfo::QStorageInfo();
impl<'a> /*trait*/ QStorageInfo_new for () {
fn new(self) -> QStorageInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfoC2Ev()};
let ctysz: c_int = unsafe{QStorageInfo_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN12QStorageInfoC2Ev()};
let rsthis = QStorageInfo{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QStorageInfo::QStorageInfo(const QDir & dir);
impl<'a> /*trait*/ QStorageInfo_new for (&'a QDir) {
fn new(self) -> QStorageInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfoC2ERK4QDir()};
let ctysz: c_int = unsafe{QStorageInfo_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN12QStorageInfoC2ERK4QDir(arg0)};
let rsthis = QStorageInfo{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static QStorageInfo QStorageInfo::root();
impl /*struct*/ QStorageInfo {
pub fn root_s<RetType, T: QStorageInfo_root_s<RetType>>( overload_args: T) -> RetType {
return overload_args.root_s();
// return 1;
}
}
pub trait QStorageInfo_root_s<RetType> {
fn root_s(self ) -> RetType;
}
// proto: static QStorageInfo QStorageInfo::root();
impl<'a> /*trait*/ QStorageInfo_root_s<QStorageInfo> for () {
fn root_s(self ) -> QStorageInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfo4rootEv()};
let mut ret = unsafe {C_ZN12QStorageInfo4rootEv()};
let mut ret1 = QStorageInfo::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QStorageInfo::QStorageInfo(const QString & path);
impl<'a> /*trait*/ QStorageInfo_new for (&'a QString) {
fn new(self) -> QStorageInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfoC2ERK7QString()};
let ctysz: c_int = unsafe{QStorageInfo_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN12QStorageInfoC2ERK7QString(arg0)};
let rsthis = QStorageInfo{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QByteArray QStorageInfo::device();
impl /*struct*/ QStorageInfo {
pub fn device<RetType, T: QStorageInfo_device<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.device(self);
// return 1;
}
}
pub trait QStorageInfo_device<RetType> {
fn device(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: QByteArray QStorageInfo::device();
impl<'a> /*trait*/ QStorageInfo_device<QByteArray> for () {
fn device(self , rsthis: & QStorageInfo) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo6deviceEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo6deviceEv(rsthis.qclsinst)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QStorageInfo::displayName();
impl /*struct*/ QStorageInfo {
pub fn displayName<RetType, T: QStorageInfo_displayName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.displayName(self);
// return 1;
}
}
pub trait QStorageInfo_displayName<RetType> {
fn displayName(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: QString QStorageInfo::displayName();
impl<'a> /*trait*/ QStorageInfo_displayName<QString> for () {
fn displayName(self , rsthis: & QStorageInfo) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QStorageInfo11displayNameEv()};
let mut ret = unsafe {C_ZNK12QStorageInfo11displayNameEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QStorageInfo::swap(QStorageInfo & other);
impl /*struct*/ QStorageInfo {
pub fn swap<RetType, T: QStorageInfo_swap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.swap(self);
// return 1;
}
}
pub trait QStorageInfo_swap<RetType> {
fn swap(self , rsthis: & QStorageInfo) -> RetType;
}
// proto: void QStorageInfo::swap(QStorageInfo & other);
impl<'a> /*trait*/ QStorageInfo_swap<()> for (&'a QStorageInfo) {
fn swap(self , rsthis: & QStorageInfo) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QStorageInfo4swapERS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QStorageInfo4swapERS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// <= body block end
|
extern crate amq_protocol;
extern crate futures;
extern crate lapin_futures as lapin;
#[macro_use]
extern crate log;
extern crate stderrlog;
extern crate tokio;
use std::str::FromStr;
use std::time;
use amq_protocol::uri::AMQPUri;
use futures::future::{self, Future, Loop};
use lapin::{
channel::{BasicProperties, BasicPublishOptions},
client::{Client, ConnectionOptions},
};
use tokio::{net::TcpStream, timer::Delay};
const DEFAULT_ADDR: &str = "amqp://admin:qweqweqwe@127.0.0.1//?heartbeat=5";
const DEFAULT_MSG: &str = "example message";
fn main() {
stderrlog::new().verbosity(2).init().unwrap();
let uri = AMQPUri::from_str(DEFAULT_ADDR).unwrap();
let addr = format!("{}:{}", uri.authority.host, uri.authority.port)
.parse()
.unwrap();
let opts = ConnectionOptions::from_uri(uri);
tokio::run(
TcpStream::connect(&addr)
.and_then(|stream| Client::connect(stream, opts))
.and_then(|(client, heartbeat)| {
tokio::spawn(
heartbeat.map_err(|e| error!("Heartbeat failed: {}", e)),
);
client.create_channel()
})
.map_err(|e| error!("Connection failed: {}", e))
.and_then(|ch| {
future::loop_fn((), move |_| {
ch.basic_publish(
"example-exchange",
"route_to_everybody",
DEFAULT_MSG.as_bytes().to_vec(),
BasicPublishOptions::default(),
BasicProperties::default(),
).map_err(|e| error!("Publish failed: {}", e))
.and_then(|_| {
info!("Published msg");
Delay::new(
time::Instant::now()
+ time::Duration::from_millis(500),
).map_err(|e| error!("Delay failed: {}", e))
})
.and_then(|_| Ok(Loop::Continue(())))
})
})
.map(|_: ()| info!("Done!")),
)
}
|
//argument
const MAX_I: usize = 5;
const MAX_J: usize = 6;
pub struct Counter {
pub is_first: bool,
pub count: usize,
}
impl Counter {
pub fn new(b: bool, c: usize) -> Counter {
Counter {
is_first: b,
count: c,
}
}
}
fn flip_to1(i: usize, j: usize, map: &mut [[u8; 6]; 5], counter: &mut Counter) {
if map[i][j] == 1 {
map[i][j] = 0;
if counter.is_first {
counter.is_first = false;
counter.count += 1;
}
// 再帰で隣接マスについてこれを呼び出す
if i == 0 {
if j == 0 {
flip_to1(i + 1, 0, map, counter);
flip_to1(i + 1, 1, map, counter);
flip_to1(i, 1, map, counter);
} else if j == MAX_J - 1 {
flip_to1(i + 1, j, map, counter);
flip_to1(i + 1, j - 1, map, counter);
flip_to1(i, j - 1, map, counter);
} else {
flip_to1(i + 1, j - 1, map, counter);
flip_to1(i + 1, j, map, counter);
flip_to1(i + 1, j + 1, map, counter);
flip_to1(i, j + 1, map, counter);
flip_to1(i, j - 1, map, counter);
}
} else if i == MAX_I - 1 {
if j == 0 {
flip_to1(i - 1, 0, map, counter);
flip_to1(i - 1, 1, map, counter);
flip_to1(i, 1, map, counter);
} else if j == MAX_J - 1 {
flip_to1(i - 1, j, map, counter);
flip_to1(i - 1, j - 1, map, counter);
flip_to1(i, j - 1, map, counter);
} else {
flip_to1(i - 1, j - 1, map, counter);
flip_to1(i - 1, j, map, counter);
flip_to1(i - 1, j + 1, map, counter);
flip_to1(i, j + 1, map, counter);
flip_to1(i, j - 1, map, counter);
}
} else {
if j == 0 {
flip_to1(i - 1, j, map, counter);
flip_to1(i - 1, j + 1, map, counter);
flip_to1(i, j + 1, map, counter);
flip_to1(i + 1, j, map, counter);
flip_to1(i + 1, j + 1, map, counter);
} else if j == MAX_J - 1 {
flip_to1(i - 1, j - 1, map, counter);
flip_to1(i - 1, j, map, counter);
flip_to1(i, j - 1, map, counter);
flip_to1(i + 1, j - 1, map, counter);
flip_to1(i + 1, j, map, counter);
} else {
flip_to1(i - 1, j - 1, map, counter);
flip_to1(i - 1, j, map, counter);
flip_to1(i - 1, j + 1, map, counter);
flip_to1(i, j + 1, map, counter);
flip_to1(i, j - 1, map, counter);
flip_to1(i + 1, j - 1, map, counter);
flip_to1(i + 1, j, map, counter);
flip_to1(i + 1, j + 1, map, counter);
}
}
}
}
fn main() {
let mut map: [[u8; MAX_J]; MAX_I] = [
[1, 1, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 1],
[0, 0, 1, 0, 0, 1],
[1, 1, 0, 0, 0, 0],
[1, 1, 0, 1, 1, 1],
];
println!("map = [");
for i in 0..MAX_I {
println!(" {:?}", map[i]);
}
println!("]");
let mut counter: Counter = Counter::new(true, 0);
for i in 0..MAX_I {
for j in 0..MAX_J {
flip_to1(i, j, &mut map, &mut counter);
if !counter.is_first {
counter.is_first = true;
}
}
}
println!("the number of cluster: {}", counter.count);
}
|
fn main() {
let a: u8 = 0xf0;
let b: u8 = 0xf0;
println!("{} {} {}", a, b, a + b);
}
|
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::ty::is_type_lang_item;
use clippy_utils::{match_function_call, paths};
use rustc_hir::{lang_items, Expr};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy_lint! {
/// ### What it does
/// Prevents the safe `std::mem::drop` function from being called on `std::mem::ManuallyDrop`.
///
/// ### Why is this bad?
/// The safe `drop` function does not drop the inner value of a `ManuallyDrop`.
///
/// ### Known problems
/// Does not catch cases if the user binds `std::mem::drop`
/// to a different name and calls it that way.
///
/// ### Example
/// ```rust
/// struct S;
/// drop(std::mem::ManuallyDrop::new(S));
/// ```
/// Use instead:
/// ```rust
/// struct S;
/// unsafe {
/// std::mem::ManuallyDrop::drop(&mut std::mem::ManuallyDrop::new(S));
/// }
/// ```
#[clippy::version = "1.49.0"]
pub UNDROPPED_MANUALLY_DROPS,
correctness,
"use of safe `std::mem::drop` function to drop a std::mem::ManuallyDrop, which will not drop the inner value"
}
declare_lint_pass!(UndroppedManuallyDrops => [UNDROPPED_MANUALLY_DROPS]);
impl LateLintPass<'tcx> for UndroppedManuallyDrops {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let Some([arg_0, ..]) = match_function_call(cx, expr, &paths::DROP) {
let ty = cx.typeck_results().expr_ty(arg_0);
if is_type_lang_item(cx, ty, lang_items::LangItem::ManuallyDrop) {
span_lint_and_help(
cx,
UNDROPPED_MANUALLY_DROPS,
expr.span,
"the inner value of this ManuallyDrop will not be dropped",
None,
"to drop a `ManuallyDrop<T>`, use std::mem::ManuallyDrop::drop",
);
}
}
}
}
|
/**
* Copyright © 2019
* Sami Shalayel <sami.shalayel@tutamail.com>,
* Carl Schwan <carl@carlschwan.eu>,
* Daniel Freiermuth <d_freiermu14@cs.uni-kl.de>
*
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See the LICENSE file for more details.
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See the LICENSE
* file for more details. **/
use crate::intersection::Intersection;
use crate::ray::Ray;
use crate::shader::Shader;
use crate::storage::Bounded;
use crate::world::Interceptable;
use na::{Vector2, Vector3};
pub struct Triangle {
pub a: Vector3<f64>,
pub b: Vector3<f64>,
pub c: Vector3<f64>,
pub shader: Box<Shader>,
}
impl Interceptable for Triangle {
// Shamelessly stolen from https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
fn intercept(&self, ray: &Ray) -> Option<(f64, Intersection)> {
let epsilon = 0.0001;
let edge1 = self.b - self.a;
let edge2 = self.c - self.a;
let h = ray.dir.cross(&edge2);
let a = edge1.dot(&h);
if a.abs() < epsilon {
// This ray is parallel to this triangle.
return None;
}
let f = 1.0 / a;
let s = ray.start - self.a;
let u = f * s.dot(&h);
if u < 0.0 || u > 1.0 {
return None;
}
let q = s.cross(&edge1);
let v = f * ray.dir.dot(&q);
if v < 0.0 || u + v > 1.0 {
return None;
}
// At this stage we can compute t to find out where the intersection point is on the line.
let t = f * edge2.dot(&q);
return if t > epsilon
// ray intersection
{
let pos = ray.start + ray.dir.into_inner() * t;
let h = edge1.cross(&edge2);
let normal = if h.dot(&ray.dir) < 0.0 { h } else { -h };
let intersection = Intersection {
pos: pos,
normal_at_surface: normal,
shader: &self.shader,
pos_on_surface: Vector2::new(u * edge1.norm(), v * edge2.norm()),
};
Some((t, intersection))
} else {
None
};
}
}
impl Bounded for Triangle {
fn get_min(&self) -> Vector3<f64> {
Vector3::new(
self.a.x.min(self.b.x).min(self.c.x),
self.a.y.min(self.b.y).min(self.c.y),
self.a.z.min(self.b.z).min(self.c.z),
)
}
fn get_max(&self) -> Vector3<f64> {
Vector3::new(
self.a.x.max(self.b.x).max(self.c.x),
self.a.y.max(self.b.y).max(self.c.y),
self.a.z.max(self.b.z).max(self.c.z),
)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.