text stringlengths 8 4.13M |
|---|
#[derive(Debug, Copy, Clone)]
pub enum Direction {
Forward,
Backward
}
pub trait LegacyMovable {
fn ride(&mut self, d: Direction, velocity: u32);
fn print(&self);
}
#[derive(Debug, Copy, Clone)]
pub struct LegacyTrain {
pub d: Direction,
pub v: u32,
}
impl LegacyTrain {
pub fn new(d: Direction, v: u32) -> LegacyTrain {
LegacyTrain { d: d, v: v }
}
}
impl LegacyMovable for LegacyTrain {
fn ride(&mut self, d: Direction, velocity: u32) {
self.d = d;
self.v = velocity;
}
fn print(&self) {
println!("Legacy ride {:?}", self);
}
}
pub fn legacy_use() {
println!("-------------------- {} --------------------", file!());
let mut l = LegacyTrain::new(Direction::Forward, 12);
l.print();
l.ride(Direction::Backward, 5);
l.print();
}
|
use bson::{doc, Bson, Document};
use juniper::{
graphql_interface, graphql_object, http::GraphQLRequest, EmptySubscription, FieldError,
FieldResult, GraphQLInputObject, GraphQLObject, RootNode, ID,
};
use mongodb::{
options::ClientOptions, options::FindOneAndUpdateOptions, options::FindOptions,
options::ReturnDocument, options::UpdateOptions, Client, Collection, Database,
};
use serde::{Deserialize, Serialize};
use tide::{Body, Request, Response, StatusCode};
use uuid::Uuid;
use async_std::stream::StreamExt;
use std::cmp;
use std::sync::Arc;
use stockmove::Restore;
mod models;
use models::stockmove;
type StockId = String;
type EventId = i32;
type MoveId = String;
type Revision = i32;
type StoreResult<T> = Result<T, Box<dyn std::error::Error>>;
#[derive(Clone)]
struct Store(Database);
impl juniper::Context for Store {}
impl Store {
async fn save_stock(&self, stock: &StoredStock) -> StoreResult<()> {
let query = doc! {"_id": &stock.id};
Self::set_on_insert(self.0.collection("stocks"), query, stock)
.await
.map(|_| ())
}
async fn load_stock(&self, item: String, location: String) -> StoreResult<Option<StoredStock>> {
let query = doc! {"_id": stock_id(&item, &location)};
let r = self.0.collection("stocks").find_one(query, None).await?;
if let Some(d) = r {
let s = bson::from_document::<StoredStock>(d)?;
let query = doc! {
"$and": [
{"item": item.clone()},
{"$or": [
{"from": location.clone()},
{"to": location.clone()},
]},
]
};
let es = self
.load_events(query, doc! {"_id": 1})
.await?
.into_iter()
.map(|e| e.event);
Ok(Some(s.stock.restore(es).into()))
} else {
Ok(None)
}
}
async fn save_event(
&self,
move_id: MoveId,
revision: Revision,
data: &(stockmove::StockMove, stockmove::MoveEvent),
) -> StoreResult<RestoredStockMove> {
let info = data.0.info().ok_or("invalid state")?;
let id = self.next_event_id().await?;
let event = StoredEvent {
id,
move_id: move_id.clone(),
revision: revision.clone(),
item: info.item,
from: info.from,
to: info.to,
event: data.1.clone(),
};
let query = doc! {"move_id": move_id.clone(), "revision": revision};
Self::set_on_insert(self.0.collection("events"), query, &event)
.await
.map(|_| RestoredStockMove {
move_id,
revision,
state: data.0.clone(),
})
}
async fn load_move(&self, move_id: MoveId) -> StoreResult<Option<RestoredStockMove>> {
let es = self
.load_events(doc! {"move_id": move_id.clone()}, doc! {"revision": 1})
.await?;
let revision = es.iter().fold(0, |acc, x| cmp::max(acc, x.revision));
let fst = stockmove::StockMove::initial_state();
let state = fst.clone().restore(es.into_iter().map(|e| e.event));
if state == fst {
Ok(None)
} else {
Ok(Some(RestoredStockMove {
move_id,
revision,
state,
}))
}
}
async fn load_events(&self, query: Document, sort: Document) -> StoreResult<Vec<StoredEvent>> {
let opts = FindOptions::builder().sort(Some(sort)).build();
let es = self
.0
.collection("events")
.find(query, opts)
.await?
.map(|r| {
r.clone()
.and_then(|d| bson::from_document::<StoredEvent>(d).map_err(|e| e.into()))
})
.collect::<Vec<_>>()
.await
.iter()
.cloned()
.flat_map(|r| r.ok())
.collect::<Vec<_>>();
println!("debug: {:?}", es);
Ok(es)
}
async fn set_on_insert<T>(col: Collection, query: Document, data: &T) -> StoreResult<Bson>
where
T: Serialize,
{
let doc = bson::to_bson(data)?;
if let Bson::Document(d) = doc {
println!("to_bson: {:?}", d);
let opts = UpdateOptions::builder().upsert(true).build();
col.update_one(query, doc! {"$setOnInsert": d}, opts)
.await?
.upserted_id
.ok_or("conflict".into())
} else {
Err("invalid type".into())
}
}
async fn next_event_id(&self) -> StoreResult<EventId> {
let opts = FindOneAndUpdateOptions::builder()
.upsert(true)
.return_document(Some(ReturnDocument::After))
.build();
let doc = self
.0
.collection("events_seq")
.find_one_and_update(doc! {"_id": "seq_no"}, doc! {"$inc": {"seq_no": 1}}, opts)
.await?
.ok_or("no document")?;
println!("{:?}", doc);
doc.get_i32("seq_no").map_err(|e| format!("{:?}", e).into())
}
}
#[derive(Debug, Deserialize, Serialize)]
struct StoredStock {
#[serde(rename = "_id")]
id: StockId,
stock: stockmove::Stock,
}
impl From<stockmove::Stock> for StoredStock {
fn from(stock: stockmove::Stock) -> Self {
Self {
id: stock_id(stock.item().as_str(), stock.location().as_str()),
stock: stock.clone(),
}
}
}
#[derive(Debug, Clone)]
struct RestoredStockMove {
move_id: MoveId,
revision: Revision,
state: stockmove::StockMove,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
struct StoredEvent {
#[serde(rename = "_id")]
id: EventId,
move_id: MoveId,
revision: Revision,
item: stockmove::ItemCode,
from: stockmove::LocationCode,
to: stockmove::LocationCode,
event: stockmove::MoveEvent,
}
#[graphql_interface(for = [ManagedStock, UnmanagedStock])]
trait Stock {
fn item(&self) -> ID;
fn location(&self) -> ID;
}
#[derive(Debug, Clone, GraphQLObject, Deserialize, Serialize)]
#[graphql(impl = StockValue)]
struct ManagedStock {
#[serde(rename = "_id")]
id: String,
item: ID,
location: ID,
qty: i32,
assigned: i32,
}
#[graphql_interface]
impl Stock for ManagedStock {
fn item(&self) -> ID {
self.item.clone()
}
fn location(&self) -> ID {
self.location.clone()
}
}
#[derive(Debug, Clone, GraphQLObject, Deserialize, Serialize)]
#[graphql(impl = StockValue)]
struct UnmanagedStock {
#[serde(rename = "_id")]
id: String,
item: ID,
location: ID,
}
#[graphql_interface]
impl Stock for UnmanagedStock {
fn item(&self) -> ID {
self.item.clone()
}
fn location(&self) -> ID {
self.location.clone()
}
}
impl From<StoredStock> for StockValue {
fn from(s: StoredStock) -> Self {
match s.stock {
stockmove::Stock::Managed {
item,
location,
qty,
assigned,
} => ManagedStock {
id: stock_id(&item, &location),
item: item.into(),
location: location.into(),
qty,
assigned,
}
.into(),
stockmove::Stock::Unmanaged { item, location } => UnmanagedStock {
id: stock_id(&item, &location),
item: item.into(),
location: location.into(),
}
.into(),
}
}
}
#[derive(Debug, Clone, GraphQLInputObject)]
struct CreateStockInput {
item: ID,
location: ID,
}
#[derive(Debug, Clone, GraphQLInputObject)]
struct StartMoveInput {
item: ID,
qty: i32,
from: ID,
to: ID,
}
#[derive(Debug, Clone, GraphQLObject)]
struct StockMoveInfo {
item: ID,
qty: i32,
from: ID,
to: ID,
}
impl From<stockmove::StockMoveInfo> for StockMoveInfo {
fn from(s: stockmove::StockMoveInfo) -> Self {
Self {
item: s.item.into(),
qty: s.qty,
from: s.from.into(),
to: s.to.into(),
}
}
}
#[graphql_interface(for = [DraftStockMove, CompletedStockMove, CancelledStockMove, AssignedStockMove, ShippedStockMove, ArrivedStockMove, AssignFailedStockMove, ShipmentFailedStockMove])]
trait StockMove {
fn id(&self) -> ID;
fn info(&self) -> &StockMoveInfo;
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct DraftStockMove {
id: ID,
info: StockMoveInfo,
}
#[graphql_interface]
impl StockMove for DraftStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct CompletedStockMove {
id: ID,
info: StockMoveInfo,
outgoing: i32,
incoming: i32,
}
#[graphql_interface]
impl StockMove for CompletedStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct CancelledStockMove {
id: ID,
info: StockMoveInfo,
}
#[graphql_interface]
impl StockMove for CancelledStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct AssignedStockMove {
id: ID,
info: StockMoveInfo,
assigned: i32,
}
#[graphql_interface]
impl StockMove for AssignedStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct ShippedStockMove {
id: ID,
info: StockMoveInfo,
outgoing: i32,
}
#[graphql_interface]
impl StockMove for ShippedStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct ArrivedStockMove {
id: ID,
info: StockMoveInfo,
outgoing: i32,
incoming: i32,
}
#[graphql_interface]
impl StockMove for ArrivedStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct AssignFailedStockMove {
id: ID,
info: StockMoveInfo,
}
#[graphql_interface]
impl StockMove for AssignFailedStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
#[derive(Debug, Clone, GraphQLObject)]
#[graphql(impl = StockMoveValue)]
struct ShipmentFailedStockMove {
id: ID,
info: StockMoveInfo,
}
#[graphql_interface]
impl StockMove for ShipmentFailedStockMove {
fn id(&self) -> ID {
self.id.clone()
}
fn info(&self) -> &StockMoveInfo {
&self.info
}
}
impl From<RestoredStockMove> for Option<StockMoveValue> {
fn from(s: RestoredStockMove) -> Self {
match s.state {
stockmove::StockMove::Nothing => None,
stockmove::StockMove::Draft { info } => Some(
DraftStockMove {
id: s.move_id.into(),
info: info.into(),
}
.into(),
),
stockmove::StockMove::Completed {
info,
outgoing,
incoming,
} => Some(
CompletedStockMove {
id: s.move_id.into(),
info: info.into(),
outgoing,
incoming,
}
.into(),
),
stockmove::StockMove::Cancelled { info } => Some(
CancelledStockMove {
id: s.move_id.into(),
info: info.into(),
}
.into(),
),
stockmove::StockMove::Assigned { info, assigned } => Some(
AssignedStockMove {
id: s.move_id.into(),
info: info.into(),
assigned,
}
.into(),
),
stockmove::StockMove::Shipped { info, outgoing } => Some(
ShippedStockMove {
id: s.move_id.into(),
info: info.into(),
outgoing,
}
.into(),
),
stockmove::StockMove::Arrived {
info,
outgoing,
incoming,
} => Some(
ArrivedStockMove {
id: s.move_id.into(),
info: info.into(),
outgoing,
incoming,
}
.into(),
),
stockmove::StockMove::AssignFailed { info } => Some(
AssignFailedStockMove {
id: s.move_id.into(),
info: info.into(),
}
.into(),
),
stockmove::StockMove::ShipmentFailed { info } => Some(
ShipmentFailedStockMove {
id: s.move_id.into(),
info: info.into(),
}
.into(),
),
}
}
}
fn stock_id(item: &str, location: &str) -> String {
format!("{}/{}", item, location)
}
async fn action(
ctx: &Store,
rs: RestoredStockMove,
act: stockmove::StockMoveAction,
) -> FieldResult<Option<StockMoveValue>> {
let mr = rs.state.action(act);
if let Some(t) = mr {
let rev = rs.revision + 1;
ctx.save_event(rs.move_id.clone(), rev, &t)
.await
.map(|s| s.into())
.map_err(|e| e.into())
} else {
Ok(None)
}
}
async fn find_and_action(
ctx: &Store,
move_id: MoveId,
act: stockmove::StockMoveAction,
) -> FieldResult<Option<StockMoveValue>> {
let rs = ctx.load_move(move_id).await?;
if let Some(r) = rs {
action(ctx, r, act).await
} else {
Ok(None)
}
}
#[derive(Debug)]
struct Query;
#[graphql_object(Context = Store)]
impl Query {
async fn find_stock(
ctx: &Store,
item: String,
location: String,
) -> FieldResult<Option<StockValue>> {
let r = ctx
.load_stock(item, location)
.await
.map_err(|e| error(format!("{:?}", e).as_str()))?;
Ok(r.map(|s| s.into()))
}
async fn find_move(ctx: &Store, id: ID) -> FieldResult<Option<StockMoveValue>> {
let r = ctx
.load_move(id.to_string())
.await
.map_err(|e| error(format!("{:?}", e).as_str()))?;
Ok(r.and_then(|s| s.into()))
}
}
#[derive(Debug)]
struct Mutation;
#[graphql_object(Context = Store)]
impl Mutation {
async fn create_managed(ctx: &Store, input: CreateStockInput) -> FieldResult<StockValue> {
let stock =
stockmove::Stock::managed_new(input.item.to_string(), input.location.to_string());
let s: StoredStock = stock.into();
ctx.save_stock(&s)
.await
.map(|_| s.into())
.map_err(|e| error(format!("{:?}", e).as_str()))
}
async fn create_unmanaged(ctx: &Store, input: CreateStockInput) -> FieldResult<StockValue> {
let stock =
stockmove::Stock::unmanaged_new(input.item.to_string(), input.location.to_string());
let s: StoredStock = stock.into();
ctx.save_stock(&s)
.await
.map(|_| s.into())
.map_err(|e| error(format!("{:?}", e).as_str()))
}
async fn start(ctx: &Store, input: StartMoveInput) -> FieldResult<Option<StockMoveValue>> {
let act = stockmove::StockMoveAction::Start {
item: input.item.to_string(),
qty: input.qty,
from: input.from.to_string(),
to: input.to.to_string(),
};
let rs = RestoredStockMove {
move_id: format!("move-{}", Uuid::new_v4()),
revision: 0,
state: stockmove::StockMove::initial_state(),
};
action(ctx, rs, act).await
}
async fn complete(ctx: &Store, id: ID) -> FieldResult<Option<StockMoveValue>> {
find_and_action(ctx, id.to_string(), stockmove::StockMoveAction::Complete).await
}
async fn cancel(ctx: &Store, id: ID) -> FieldResult<Option<StockMoveValue>> {
find_and_action(ctx, id.to_string(), stockmove::StockMoveAction::Cancel).await
}
async fn assign(ctx: &Store, id: ID) -> FieldResult<Option<StockMoveValue>> {
let rs = ctx.load_move(id.to_string()).await?;
if let Some(r) = rs {
let info = r.state.info().ok_or("not found info")?;
let st = ctx
.load_stock(info.item.clone(), info.from.clone())
.await?
.unwrap_or(stockmove::Stock::managed_new(info.item, info.from).into());
let act = stockmove::StockMoveAction::Assign { stock: st.stock };
action(ctx, r, act).await
} else {
Ok(None)
}
}
async fn ship(ctx: &Store, id: ID, outgoing: i32) -> FieldResult<Option<StockMoveValue>> {
find_and_action(
ctx,
id.to_string(),
stockmove::StockMoveAction::Ship { outgoing },
)
.await
}
async fn arrive(ctx: &Store, id: ID, incoming: i32) -> FieldResult<Option<StockMoveValue>> {
find_and_action(
ctx,
id.to_string(),
stockmove::StockMoveAction::Arrive { incoming },
)
.await
}
}
type Schema = RootNode<'static, Query, Mutation, EmptySubscription<Store>>;
type State = (Store, Arc<Schema>);
#[async_std::main]
async fn main() -> tide::Result<()> {
let addr = "127.0.0.1:4000";
let opt = ClientOptions::parse("mongodb://localhost").await?;
let mongo = Client::with_options(opt)?;
let state = (
Store(mongo.database("stockmoves")),
Arc::new(Schema::new(Query, Mutation, EmptySubscription::new())),
);
let mut app = tide::with_state(state);
app.at("/graphql").post(handle_graphql);
app.listen(addr).await?;
Ok(())
}
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())
}
fn error(msg: &str) -> FieldError {
FieldError::new(msg, juniper::Value::Null)
}
|
use egg::*;
use unscramble::*;
define_language! {
enum Prop {
Num(i32),
"*" = Times([Id; 2]),
"x" = X,
Symbol(Symbol),
}
}
type EGraph = egg::EGraph<Prop, ()>;
type Rewrite = egg::Rewrite<Prop, ()>;
macro_rules! rule {
($name:ident, $left:literal, $right:literal) => {
#[allow(dead_code)]
fn $name() -> Rewrite {
rewrite!(stringify!($name); $left => $right)
}
};
($name:ident, $name2:ident, $left:literal, $right:literal) => {
rule!($name, $left, $right);
rule!($name2, $right, $left);
};
}
macro_rules! rev_rule {
($name:ident, $left:literal, $right:literal) => {
#[allow(dead_code)]
fn $name() -> Rewrite {
rewrite!(stringify!($name); $right => $left)
}
};
}
rule! {times_to_shift, "(* ?x 2)", "(<< ?x 1)"}
rule! {mul_comm, "(* ?x ?y)", "(* ?y ?x)"}
rule! {input2, "2", "x"}
rule! {input3, "3", "x"}
fn prove_something(name: &str, start: &str, rewrites: &[Rewrite], goals: &[&str]) {
let _ = env_logger::builder().is_test(true).try_init();
println!("Proving {}", name);
let start_expr: RecExpr<_> = start.parse().unwrap();
let goal_exprs: Vec<RecExpr<_>> = goals.iter().map(|g| g.parse().unwrap()).collect();
let egraph = Runner::default()
.with_iter_limit(20)
.with_node_limit(5_000)
.with_expr(&start_expr)
.run(rewrites)
.egraph;
egraph.dot().to_dot(format!("tests/{}.dot", name)).unwrap();
let intersection = intersect(&egraph, &egraph);
intersection
.dot()
.to_dot(format!("tests/{}-intersect.dot", name))
.unwrap();
for (i, (goal_expr, goal_str)) in goal_exprs.iter().zip(goals).enumerate() {
println!("Trying to prove goal {}: {}", i, goal_str);
let equivs = egraph.equivs(&start_expr, &goal_expr);
if equivs.is_empty() {
panic!("Couldn't prove goal {}: {}", i, goal_str);
}
}
}
fn get_egraph(start: &str, rewrites: &[Rewrite]) -> EGraph {
let start_expr: RecExpr<_> = start.parse().unwrap();
Runner::default()
.with_iter_limit(20)
.with_node_limit(5_000)
.with_expr(&start_expr)
.run(rewrites)
.egraph
}
#[test]
fn prove_two_simp() {
let _ = env_logger::builder().is_test(true).try_init();
let rules = &[mul_comm(), input2()];
prove_something("two_simp", "(* a 2)", rules, &[]);
}
#[test]
fn prove_three_simp() {
let _ = env_logger::builder().is_test(true).try_init();
let rules = &[mul_comm(), input3()];
prove_something("three_simp", "(* a 3)", rules, &[]);
}
fn intersect_and_dump(name: &str, egg1: &EGraph, egg2: &EGraph) {
let intersection = intersect(&egg1, &egg2);
intersection
.dot()
.to_dot(format!("tests/{}-intersect.dot", name))
.unwrap();
}
#[test]
fn prove_two_three_simp() {
let _ = env_logger::builder().is_test(true).try_init();
let rules1 = &[mul_comm(), input2()];
let rules2 = &[mul_comm(), input3()];
let egg1 = get_egraph("(* a 2)", rules1);
let egg2 = get_egraph("(* a 3)", rules2);
intersect_and_dump("two_three_simp-intersect", &egg1, &egg2);
}
|
#[macro_export]
macro_rules! c {
($x:tt = $y:tt) => {
Condition {
field_name: stringify!($x).to_string(),
operator: Operator::Eq,
value: stringify!($y).to_string(),
};
}
} |
pub fn hello2() {
println!("hello2");
} |
use heck::CamelCase;
use heck::SnakeCase;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use std::collections::{BTreeMap, BTreeSet};
use syn::{
braced, bracketed,
parse::{Parse, ParseStream, Result},
punctuated::Punctuated,
Attribute, ExprBlock, Ident, ItemEnum, ItemFn, Stmt, Token, Type,
};
use crate::fsm::events::Events;
use crate::fsm::{events::Event, states::State};
#[derive(Debug, PartialEq)]
pub(crate) struct TransitionPair {
pub from: Ident,
pub to: Ident,
}
impl Parse for TransitionPair {
/// example transition pair:
///
/// ```text
/// S1 => S2
/// ```
fn parse(input: ParseStream<'_>) -> Result<Self> {
// `S1 => S2`
// ^^
let from = Ident::parse(&input)?;
// `S1 => S2`
// ^^
let _: Token![=>] = input.parse()?;
// `S1 => S2`
// ^^
let to = Ident::parse(&input)?;
Ok(TransitionPair { from, to })
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct Transition {
pub event_name: Ident,
pub pairs: BTreeMap<Ident, BTreeSet<Ident>>,
}
impl Parse for Transition {
fn parse(input: ParseStream<'_>) -> Result<Self> {
// EVENT1 [ ... ]
// ^^^^^^
let event_name: Ident = input.parse()?;
// EVENT1 [ ... ]
// ^^^
let block_transition;
bracketed!(block_transition in input);
let mut transition_pairs: BTreeMap<Ident, BTreeSet<Ident>> = BTreeMap::new();
// EVENT1 [ S1 => S2, S1 => S3, ]
// ^^^^^^^^^^^^^^^^^^^
let punctuated_block_transition: Punctuated<TransitionPair, Token![,]> =
block_transition.parse_terminated(TransitionPair::parse)?;
for pair in punctuated_block_transition {
if let Some(v) = transition_pairs.get_mut(&pair.from) {
v.insert(pair.to);
} else {
let mut v = BTreeSet::new();
v.insert(pair.to);
transition_pairs.insert(pair.from, v);
}
}
Ok(Transition {
event_name,
pairs: transition_pairs,
})
}
}
struct AfterExitCase {
pub from: Ident,
pub to: Ident,
}
impl ToTokens for AfterExitCase {
fn to_tokens(&self, tokens: &mut TokenStream) {
let to = &self.to;
tokens.extend(quote! {
State::#to(state) => {
self.current_state = State::#to(state);
state.entry();
Ok(true)
}
})
}
}
struct StateCase {
pub from: Ident,
pub tos: BTreeSet<Ident>,
}
impl ToTokens for StateCase {
fn to_tokens(&self, tokens: &mut TokenStream) {
let from = &self.from;
let after_exit_cases: Vec<_> = self
.tos
.iter()
.map(|v| AfterExitCase {
from: from.clone(),
to: v.clone(),
})
.collect();
tokens.extend(quote! {
State::#from(state) => {
match state.exit() {
Ok(r) => {
match r {
#( #after_exit_cases )*
_ => {
panic!("cant't go to state from current state")
}
}
}
Err(err) => {
Err(err)
}
}
}
})
}
}
struct EventCase {
pub event_name: Ident,
pub pairs: BTreeMap<Ident, BTreeSet<Ident>>,
}
impl ToTokens for EventCase {
fn to_tokens(&self, tokens: &mut TokenStream) {
let event_name = &self.event_name;
let state_cases: Vec<_> = self
.pairs
.iter()
.map(|v| StateCase {
from: v.0.clone(),
tos: v.1.clone(),
})
.collect();
tokens.extend(quote! {
Event::#event_name(event) => {
if let Err(err) = event.on() {
return Err(err);
}
match self.current_state {
#( #state_cases )*
}
}
})
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct Transitions(pub Vec<Transition>);
impl Parse for Transitions {
/// example transitions tokens:
///
/// ```text
/// Transitions {
/// EVENT1 [
/// S1 => S2,
/// S1 => S3,
/// ],
///
/// EVENT2 [
/// S4 => S5,
/// ],
/// }
/// ```
fn parse(input: ParseStream<'_>) -> Result<Self> {
/// Transitions { ... }
/// -----------
let magic = Ident::parse(input)?;
if magic != "Transitions" {
return Err(input.error("expected Transitions { ... }"));
}
let content;
braced!(content in input);
let mut transitions: Vec<Transition> = Vec::new();
let transitions: Punctuated<Transition, Token![,]> =
content.parse_terminated(Transition::parse)?;
Ok(Transitions(transitions.into_iter().collect()))
}
}
impl Transitions {
pub fn to_event_fn_tokens(&self) -> TokenStream {
let event_cases: Vec<_> = self
.0
.iter()
.map(|v| EventCase {
event_name: v.event_name.clone(),
pairs: v.pairs.clone(),
})
.collect();
quote! {
fn event(&mut self, event: Event) -> Result<bool, &'static str> {
match event {
#( #event_cases )*
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use proc_macro2::TokenStream;
use syn::{self, parse_quote};
// #[test]
// fn test_transition_parse_and_to_tokens() {
// let transition: Transition = syn::parse2(quote! {
// EVENT1 [
// S1 => S2,
// S1 => S3,
// ]
// })
// .unwrap();
//
// let left = quote! {
// mod event1 {
// pub enum AfterExitS1 {
// S2,
// S3,
// }
// pub trait Callback {
// fn on_event1(&self, data: (&str)) -> Result<(), &'static str>;
// fn exit_s1(&self, data: (&str)) -> Result<AfterExitS1, &'static str>;
// fn entry_s2_from_s1(&self, data: (&str));
// fn entry_s3_from_s1(&self, data: (&str));
// }
// }
// };
//
// let mut right = transition.to_def_tokens();
//
// assert_eq!(format!("{}", left), format!("{}", right))
// }
// #[test]
// fn test_transitions_parse_and_to_tokens() {
// let transitions: Transitions = syn::parse2(quote! {
// Transitions {
// EVENT1 [
// S1 => S2,
// S1 => S3,
// ],
// EVENT2 [
// S2 => S4,
// ]
// }
// })
// .unwrap();
//
// let left = quote! {
// mod event1 {
// pub enum AfterExitS1 {
// S2,
// S3,
// }
// pub trait Callback {
// fn on_event1(&self, data: (&str)) -> Result<(), &'static str>;
// fn exit_s1(&self, data: (&str)) -> Result<AfterExitS1, &'static str>;
// fn entry_s2_from_s1(&self, data: (&str));
// fn entry_s3_from_s1(&self, data: (&str));
// }
// }
// mod event2 {
// pub enum AfterExitS2 {
// S4,
// }
// pub trait Callback {
// fn on_event2(&self, data: (&str)) -> Result<(), &'static str>;
// fn exit_s2(&self, data: (&str)) -> Result<AfterExitS2, &'static str>;
// fn entry_s4_from_s2(&self, data: (&str));
// }
// }
// };
//
// let mut right = transitions.to_def_tokens();
//
// assert_eq!(format!("{}", left), format!("{}", right))
// }
}
|
#![crate_name = "uu_users"]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// Allow dead code here in order to keep all fields, constants here, for consistency.
#![allow(dead_code)]
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::ffi::{CStr, CString};
use std::mem;
use std::ptr;
use uucore::utmpx::*;
extern {
fn getutxent() -> *const c_utmp;
fn getutxid(ut: *const c_utmp) -> *const c_utmp;
fn getutxline(ut: *const c_utmp) -> *const c_utmp;
fn pututxline(ut: *const c_utmp) -> *const c_utmp;
fn setutxent();
fn endutxent();
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn utmpxname(file: *const libc::c_char) -> libc::c_int;
}
#[cfg(target_os = "freebsd")]
unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
static NAME: &'static str = "users";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f),
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]", NAME);
println!("");
println!("{}", opts.usage("Output who is currently logged in according to FILE."));
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
let filename = if !matches.free.is_empty() {
matches.free[0].as_ref()
} else {
DEFAULT_FILE
};
exec(filename);
0
}
fn exec(filename: &str) {
unsafe {
utmpxname(CString::new(filename).unwrap().as_ptr());
}
let mut users = vec!();
unsafe {
setutxent();
loop {
let line = getutxent();
if line == ptr::null() {
break;
}
if (*line).ut_type == USER_PROCESS {
let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string();
users.push(user);
}
}
endutxent();
}
if !users.is_empty() {
users.sort();
println!("{}", users.join(" "));
}
}
|
pub mod control_knob;
pub use control_knob::*;
pub mod levels;
pub use levels::*;
pub mod value_knob;
pub use value_knob::*; |
use core::fmt;
use embedded_hal::blocking::{delay::DelayMs, i2c};
pub trait Display {
type Error;
fn clear(&mut self) -> Result<(), Self::Error>;
fn set_cursor_position(&mut self, row: u8, column: u8) -> Result<(), Self::Error>;
fn write(&mut self, characters: &[u8]) -> Result<(), Self::Error>;
}
pub struct BufferedDisplay<const ROWS: usize, const COLUMNS: usize> {
backing_buffer: [[u8; COLUMNS]; ROWS],
visible_buffer: [[u8; COLUMNS]; ROWS],
current_row: u8,
current_column: u8,
}
#[derive(Debug)]
pub enum BufferedDisplayError {
OutOfBounds,
}
#[allow(dead_code)]
pub enum CursorMode {
Underline,
Blinking,
Off,
}
impl<const ROWS: usize, const COLUMNS: usize> BufferedDisplay<ROWS, COLUMNS> {
pub const fn new() -> Self {
BufferedDisplay {
backing_buffer: [[b' '; COLUMNS]; ROWS],
visible_buffer: [[0u8; COLUMNS]; ROWS],
current_row: 0,
current_column: 0,
}
}
//
pub fn apply<D: Display>(&mut self, target: &mut D) -> Result<bool, D::Error> {
// iterate over all rows and write them out
let mut changed = false;
let mut set_pos = true;
for row in 0..ROWS {
for col in 0..COLUMNS {
if self.backing_buffer[row][col] == self.visible_buffer[row][col] {
set_pos = true;
} else {
if set_pos {
target.set_cursor_position(row as u8, col as u8)?;
set_pos = false;
}
target.write(&[self.backing_buffer[row][col]])?;
self.visible_buffer[row][col] = self.backing_buffer[row][col];
changed = true;
}
}
}
Ok(changed)
}
#[allow(dead_code)]
fn force_redraw(&mut self) {
for row in 0..ROWS {
for col in 0..COLUMNS {
self.visible_buffer[row][col] = 0;
}
}
}
}
impl<const ROWS: usize, const COLUMNS: usize> Display for BufferedDisplay<ROWS, COLUMNS> {
type Error = BufferedDisplayError;
fn clear(&mut self) -> Result<(), Self::Error> {
for row in 0..ROWS {
for col in 0..COLUMNS {
self.backing_buffer[row][col] = b' ';
}
}
self.current_row = 0;
self.current_column = 0;
Ok(())
}
fn set_cursor_position(&mut self, row: u8, column: u8) -> Result<(), Self::Error> {
if row >= ROWS as u8 || column >= COLUMNS as u8 {
return Err(Self::Error::OutOfBounds);
}
self.current_row = row;
self.current_column = column;
Ok(())
}
fn write(&mut self, characters: &[u8]) -> Result<(), Self::Error> {
for &b in characters {
self.backing_buffer[self.current_row as usize][self.current_column as usize] = b;
self.current_column += 1;
if self.current_column >= COLUMNS as u8 {
self.current_column = 0;
self.current_row += 1;
self.current_row = (self.current_row + 1) % ROWS as u8;
// if self.current_row >= ROWS as u8 {
// self.current_row = 0;
// }
}
}
Ok(())
}
}
pub struct I2CDisplayDriver<I> {
port: I,
address: u8,
rows: u8,
columns: u8,
}
#[allow(dead_code)]
impl<I: i2c::Write> I2CDisplayDriver<I> {
pub fn new(port: I, address: u8, rows: u8, columns: u8) -> Self {
I2CDisplayDriver {
port,
address,
rows,
columns,
}
}
fn cmd(&mut self, cmd: u8) -> Result<(), I::Error> {
// self.port.write_read(self.address, &[0x00, cmd], &mut[0u8; 0])
self.port.write(self.address, &[0x00, cmd])
}
pub fn set_type<D: DelayMs<u8>>(&mut self, t: u8, delay: &mut D) -> Result<(), I::Error> {
self.cmd(0x18)?;
self.cmd(t)?;
delay.delay_ms(10);
Ok(())
}
pub fn set_cursor_mode(&mut self, mode: CursorMode) -> Result<(), I::Error> {
match mode {
CursorMode::Underline => self.cmd(0x05),
CursorMode::Blinking => self.cmd(0x06),
CursorMode::Off => self.cmd(0x04),
}
}
pub fn set_backlight_enabled(&mut self, on: bool) -> Result<(), I::Error> {
match on {
true => self.cmd(0x13),
false => self.cmd(0x14),
}
}
pub fn set_backlight_brightness(&mut self, brightness: u8) -> Result<(), I::Error> {
self.cmd(0x1f)?;
self.cmd(brightness)
}
pub fn set_contrast(&mut self, contrast: u8) -> Result<(), I::Error> {
self.cmd(0x1e)?;
self.cmd(contrast)
}
}
impl<I: i2c::Write> Display for I2CDisplayDriver<I> {
type Error = I::Error;
fn clear(&mut self) -> Result<(), Self::Error> {
self.cmd(0x0c)
}
fn set_cursor_position(&mut self, row: u8, column: u8) -> Result<(), Self::Error> {
// bounds check
if row >= self.rows || column >= self.columns {
// panic for now
panic!("Cursor position out of bounds")
}
self.cmd(0x02)?;
self.cmd(row * self.columns + column + 1)
}
fn write(&mut self, characters: &[u8]) -> Result<(), Self::Error> {
for &c in characters {
self.cmd(c)?;
}
Ok(())
}
}
impl<const ROWS: usize, const COLUMNS: usize> core::fmt::Write for BufferedDisplay<ROWS, COLUMNS> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write(s.as_bytes()).map_err(|_| fmt::Error)
}
}
// impl<I, E> Mpu6050<I> where I: Write<Error = E> + WriteRead<Error = E> {}
/* Python driver source
class LCD():
ADDR = 0x63
REG_CMD = 0x00
WIDTH = 20
HEIGHT = 4
def __init__(self, bus, brightness = 32):
self.bus = bus
###### Init the LCD
self.set_type(4)
# Underline cursor
self.lcd_cmd(0x04)
self.clear()
self.set_brightness(brightness)
def lcd_cmd(self, cmd):
""" Main function for sending commands to the display :)"""
self.bus.write_byte_data(self.ADDR,self.REG_CMD,cmd)
def lcd_write(self, text):
# Converts simple text to ASCII characters and send to display
#text = [ ord(c) for c in text]
[self.lcd_cmd(ord(str(c))) for c in text]
def set_cursor(self, row, column):
if row < 1 or row > self.HEIGHT or column < 0 or column > self.WIDTH - 1:
raise ValueError("Value for row and column passed to set_cursor are out of limits :", row, column)
self.lcd_cmd(0x02)
self.lcd_cmd((((row - 1) * self.WIDTH) + column + 1))
def set_type(self, type):
self.lcd_cmd(0x18)
self.lcd_cmd(type)
sleep(.01)
def set_backlit(self, val):
if val == True:
self.lcd_cmd(0x13)
elif val == False:
self.lcd_cmd(0x14)
def set_brightness(self, val):
if val < 0 or val > 255:
raise ValueError("Value passed to set_brightness is not > 0 and < 255!! It's: " + str(val))
self.lcd_cmd(0x1f)
self.lcd_cmd(val)
def set_contrast(self, val):
if val < 0 or val > 255:
raise ValueError("Value passed to set_contrast is not > 0 and < 255!! It's: " + str(val))
self.lcd_cmd(0x1e)
self.lcd_cmd(val)
def clear(self):
self.lcd_cmd(0x0c)
def write(self, string, row = -1, column = -1, centered = False):
""" Writes text to the screen at a specific place or just at current cursor."""
if centered:
column = self.WIDTH / 2 - len(string) / 2
if row != -1 and column == -1:
self.set_cursor(row, 0)
elif column != -1 and row != -1:
self.set_cursor(row, column)
self.lcd_write(string)
*/
|
use std::io;
use byteorder::ByteOrder;
use code_wizards::model::Tree;
const PROTOCOL_VERSION: i32 = 1;
pub fn run<'r, B: ByteOrder>(host: &'r str, port: u16, token: String) -> io::Result<()> {
use std::io::{Error, ErrorKind, Write};
use std::net::TcpStream;
use code_wizards::model::Move;
use code_wizards::MyStrategy;
use super::message::Message;
use super::read_message::ReadMessage;
use super::write_message::WriteMessage;
let mut stream = try!(TcpStream::connect((host, port)));
try!(stream.set_nodelay(true));
try!(stream.write_message::<B>(&Message::AuthenticationToken(token.clone())));
try!(stream.write_message::<B>(&Message::ProtocolVersion(PROTOCOL_VERSION)));
let team_size = match try!(stream.read_message::<B>()) {
Message::TeamSize(v) => v,
v => return Err(Error::new(ErrorKind::Other, format!("Expected Message::TeamSize, but received: {:?}", v))),
};
if team_size < 0 {
return Err(Error::new(ErrorKind::Other, format!("Team size < 0: {}", team_size)));
}
let game = match try!(stream.read_message::<B>()) {
Message::GameContext(v) => v,
v => return Err(Error::new(ErrorKind::Other, format!("Expected Message::GameContext, but received: {:?}", v))),
};
let mut strategies = vec![MyStrategy::new(); team_size as usize];
let mut trees = vec![];
loop {
let player_context = match try!(stream.read_message::<B>()) {
Message::GameOver => break,
Message::PlayerContext(v) => {
if v.is_some() {
trees = v.as_ref().unwrap().world.trees.clone();
}
v
}
Message::PlayerContextWithoutTrees(mut v) => {
if v.is_some() {
v.as_mut().unwrap().world.trees = trees.clone();
}
v
}
v => return Err(Error::new(ErrorKind::Other,
format!("Expected Message::GameOver, \
Message::PlayerContext or \
Message::PlayerContextWithoutTrees, but \
received: {:?}", v)))
};
if let Some(v) = player_context {
let mut moves = vec![Move::new(); team_size as usize];
for i in 0..team_size as usize {
strategies[i].move_(&v.wizards[i], &v.world, &game, &mut moves[i]);
}
try!(stream.write_message::<B>(&Message::MovesMessage(moves)));
} else {
break;
}
}
Ok(())
}
|
// One parameter of this macro has a default value
macro_rules! make_a_awesome_function {
($id: ident) => {
fn $id() {
println!("You called a awesome function named {}!", stringify!($id));
}
};
() => {
make_a_awesome_function!(foo);
};
}
make_a_awesome_function!(bar);
make_a_awesome_function!();
fn main() {
foo();
bar();
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::error::Error, fidl_fuchsia_pkg::ExperimentToggle as Experiment,
fidl_fuchsia_pkg_ext::BlobId, fuchsia_url_rewrite::RuleConfig, serde_json, std::path::PathBuf,
};
const HELP: &str = "\
USAGE:
pkgctl <SUBCOMMAND>
FLAGS:
-h, --help prints help information
SUBCOMMANDS:
help prints this message or the help of the given subcommand(s)
open open a package by merkle root
repo repo subcommands
resolve resolve a package
rule manage URL rewrite rules
experiment manage runtime experiment states
update check for a system update and apply it if available
gc trigger garbage collection of package cache
";
const HELP_OPEN: &str = "\
open a package by merkle root
USAGE:
pkgctl open <meta_far_blob_id> [selectors]...
ARGS:
<meta_far_blob_id> Merkle root of package's meta.far to cache
<selectors>... Package selectors
";
const HELP_REPO: &str = "\
The repo command manages one or more known repositories.
A fuchsia package URL contains a repository hostname to identify the package's source. Example repository hostnames are:
fuchsia.com
mycorp.com
Without any arguments the command outputs the list of configured repository URLs.
USAGE:
pkgctl repo [-v|--verbose|<SUBCOMMAND>]
SUBCOMMANDS:
add add a source repository configuration
help prints this message or the help of the given subcommand
rm remove a source repository configuration
";
const HELP_REPO_ADD: &str = "\
The add command allows you to add a source repository.
The input file format is a json file that contains the different repository metadata and URLs.
USAGE:
pkgctl repo add -f|--file <file>
ARGS:
<file> path to a repository config file
";
const HELP_REPO_RM: &str = "\
The rm command allows you to remove a configured source repository.
The full repository URL needs to be passed as an argument. This can be obtained using `pkgctl repo`.
USAGE:
pkgctl repo rm <URL>
ARGS:
<URL> the repository url to remove
";
const HELP_RESOLVE: &str = "\
resolve a package
USAGE:
pkgctl resolve <pkg_url> [selectors]...
ARGS:
<pkg_url> URL of package to cache
<selectors>... Package selectors
";
const HELP_RULE: &str = "\
manage URL rewrite rules
USAGE:
pkgctl rule <SUBCOMMAND>
SUBCOMMANDS:
clear clear all rules
help prints this message or the help of the given subcommand(s)
list list all rules
replace replace all dynamic rules with the provided rules
";
const HELP_RULE_CLEAR: &str = "\
clear all rules
USAGE:
pkgctl rule clear
";
const HELP_RULE_LIST: &str = "\
list all rules
USAGE:
pkgctl rule list
";
const HELP_RULE_REPLACE: &str = "\
replace all dynamic rules with the provided rules
USAGE:
pkgctl rule replace <SUBCOMMAND>
SUBCOMMANDS:
file
json
";
const HELP_RULE_REPLACE_FILE: &str = "\
USAGE:
pkgctl rule replace file <path>
ARGS:
<path> path to rewrite rule config file
";
const HELP_RULE_REPLACE_JSON: &str = "\
USAGE:
pkgctl rule replace json <config>
ARGS:
<config> JSON encoded rewrite rule config
";
const HELP_EXPERIMENT: &str = "\
manage runtime experiment states
experiments may be added or removed over time and should not be considered to be stable.
USAGE:
pkgctl experiment <SUBCOMMAND>
SUBCOMMANDS:
enable enables the given experiment
disable disables the given experiment
";
// known_experiments can't be defined as a const &str as concat! needs all inputs to be literals.
macro_rules! known_experiments {
() => {
"
EXPERIMENTS:
lightbulb no-op experiment
download-blob pkg-resolver drives package installation and blob downloading
"
};
}
const HELP_EXPERIMENT_ENABLE: &str = concat!(
"\
USAGE:
pkgctl experiment enable <experiment>
ARGS:
<experiment> The experiment to enable
",
known_experiments!()
);
const HELP_EXPERIMENT_DISABLE: &str = concat!(
"\
USAGE:
pkgctl experiment disable <experiment>
ARGS:
<experiment> The experiment to disable
",
known_experiments!()
);
const HELP_UPDATE: &str = "\
The update command performs a system update check and triggers an OTA if present.
The command is non-blocking. View the syslog for more detailed progress information.
USAGE:
pkgctl update
";
const HELP_GC: &str = "\
The gc command allows you to trigger a manual garbage collection of the package cache.
This deletes any cached packages that are not present in the static and dynamic index. Any blobs associated with these packages will be removed if they are not referenced by another component or package.
USAGE:
pkgctl gc
";
#[derive(Debug, PartialEq)]
pub enum Command {
Resolve { pkg_url: String, selectors: Vec<String> },
Open { meta_far_blob_id: BlobId, selectors: Vec<String> },
Repo(RepoCommand),
Rule(RuleCommand),
Experiment(ExperimentCommand),
Update,
Gc,
}
#[derive(Debug, PartialEq)]
pub enum RepoCommand {
Add { file: PathBuf },
Remove { repo_url: String },
List,
ListVerbose,
}
#[derive(Debug, PartialEq)]
pub enum RuleCommand {
List,
Clear,
Replace { input_type: RuleConfigInputType },
}
#[derive(Debug, PartialEq)]
pub enum ExperimentCommand {
Enable(Experiment),
Disable(Experiment),
}
#[derive(Debug, PartialEq)]
pub enum RuleConfigInputType {
File { path: PathBuf },
Json { config: RuleConfig },
}
impl From<RepoCommand> for Command {
fn from(repo: RepoCommand) -> Command {
Command::Repo(repo)
}
}
impl From<RuleCommand> for Command {
fn from(rule: RuleCommand) -> Command {
Command::Rule(rule)
}
}
impl From<RuleConfigInputType> for Command {
fn from(rule: RuleConfigInputType) -> Command {
Command::Rule(RuleCommand::Replace { input_type: rule })
}
}
impl From<ExperimentCommand> for Command {
fn from(experiment: ExperimentCommand) -> Command {
Command::Experiment(experiment)
}
}
pub fn parse_args<'a, I>(mut iter: I) -> Result<Command, Error>
where
I: Iterator<Item = &'a str>,
{
macro_rules! unrecognized {
($arg:expr) => {
return Err(Error::UnrecognizedArgument($arg.to_string()));
};
}
macro_rules! done {
($e:expr) => {
match iter.next() {
None => $e,
Some(arg) => unrecognized!(arg),
}
};
}
match iter.next().ok_or_else(|| Error::Help(HELP))? {
"-h" | "--help" => done!(Err(Error::Help(HELP))),
"help" => {
let help = match iter.next() {
None => HELP,
Some("repo") => match iter.next() {
None => HELP_REPO,
Some("add") => done!(HELP_REPO_ADD),
Some("rm") => done!(HELP_REPO_RM),
Some(arg) => unrecognized!(arg),
},
Some("resolve") => done!(HELP_RESOLVE),
Some("rule") => match iter.next() {
None => HELP_RULE,
Some("clear") => done!(HELP_RULE_CLEAR),
Some("list") => done!(HELP_RULE_LIST),
Some("replace") => match iter.next() {
None => HELP_RULE_REPLACE,
Some("file") => done!(HELP_RULE_REPLACE_FILE),
Some("json") => done!(HELP_RULE_REPLACE_JSON),
Some(arg) => unrecognized!(arg),
},
Some(arg) => unrecognized!(arg),
},
Some("experiment") => match iter.next() {
None => HELP_EXPERIMENT,
Some("enable") => done!(HELP_EXPERIMENT_ENABLE),
Some("disable") => done!(HELP_EXPERIMENT_DISABLE),
Some(arg) => unrecognized!(arg),
},
Some("open") => done!(HELP_OPEN),
Some("update") => done!(HELP_UPDATE),
Some("gc") => done!(HELP_GC),
Some(arg) => unrecognized!(arg),
};
Err(Error::Help(help))
}
"open" => {
let meta_far_blob_id =
iter.next().ok_or_else(|| Error::MissingArgument("meta_far_blob_id"))?;
let selectors = iter.map(|s| s.to_string()).collect();
Ok(Command::Open { meta_far_blob_id: meta_far_blob_id.parse()?, selectors })
}
"resolve" => {
let pkg_url = iter.next().ok_or_else(|| Error::MissingArgument("pkg_url"))?;
let selectors = iter.map(|s| s.to_string()).collect();
Ok(Command::Resolve { pkg_url: pkg_url.to_string(), selectors })
}
"repo" => match iter.next() {
None => Ok(RepoCommand::List.into()),
Some("-v") | Some("--verbose") => done!(Ok(RepoCommand::ListVerbose.into())),
Some("add") => match iter.next() {
None => Err(Error::MissingArgument("--file")),
Some("-f") | Some("--file") => {
let file = iter.next().ok_or_else(|| Error::MissingArgument("file"))?;
done!(Ok(RepoCommand::Add { file: file.into() }.into()))
}
Some(arg) => unrecognized!(arg),
},
Some("rm") => match iter.next() {
None => Err(Error::MissingArgument("repo-url")),
Some(url) => done!(Ok(RepoCommand::Remove { repo_url: url.to_string() }.into())),
},
Some(arg) => unrecognized!(arg),
},
"rule" => match iter.next() {
None => Err(Error::MissingCommand),
Some("clear") => done!(Ok(RuleCommand::Clear.into())),
Some("list") => done!(Ok(RuleCommand::List.into())),
Some("replace") => match iter.next() {
None => Err(Error::MissingCommand),
Some("file") => {
let path = iter.next().ok_or_else(|| Error::MissingArgument("path"))?;
done!(Ok(RuleConfigInputType::File { path: path.into() }.into()))
}
Some("json") => {
let config = iter.next().ok_or_else(|| Error::MissingArgument("config"))?;
let config = serde_json::from_str(&config)?;
done!(Ok(RuleConfigInputType::Json { config }.into()))
}
Some(arg) => unrecognized!(arg),
},
Some(arg) => unrecognized!(arg),
},
"experiment" => match iter.next() {
None => Err(Error::MissingCommand),
Some("enable") => {
let experiment = parse_experiment_id(
iter.next().ok_or_else(|| Error::MissingArgument("experiment"))?,
)?;
done!(Ok(ExperimentCommand::Enable(experiment).into()))
}
Some("disable") => {
let experiment = parse_experiment_id(
iter.next().ok_or_else(|| Error::MissingArgument("experiment"))?,
)?;
done!(Ok(ExperimentCommand::Disable(experiment).into()))
}
Some(arg) => unrecognized!(arg),
},
"update" => match iter.next() {
None => Ok(Command::Update),
Some(arg) => unrecognized!(arg),
},
"gc" => match iter.next() {
None => Ok(Command::Gc),
Some(arg) => unrecognized!(arg),
},
arg => unrecognized!(arg),
}
}
fn parse_experiment_id(experiment: &str) -> Result<Experiment, Error> {
match experiment {
"lightbulb" => Ok(Experiment::Lightbulb),
"download-blob" => Ok(Experiment::DownloadBlob),
experiment => Err(Error::ExperimentId(experiment.to_owned())),
}
}
#[cfg(test)]
mod tests {
use {super::*, matches::assert_matches};
const REPO_URL: &str = "fuchsia-pkg://fuchsia.com";
const CONFIG_JSON: &str = r#"{"version": "1", "content": []}"#;
#[test]
fn test_unrecognized_argument() {
fn check(args: &[&str]) {
for expected in &["foo", "--foo"] {
let args = args.iter().chain(Some(expected)).collect::<Vec<_>>();
match parse_args(args.iter().map(|s| &***s)) {
Err(Error::UnrecognizedArgument(arg)) => {
assert_eq!(&arg, expected, "arg: {:?}", args);
}
result => panic!("unexpected result {:?} for {:?}", result, args),
}
}
}
// note, specifically leaving out "open" and "resolve" since they accept arbitrary
// selectors and "experiment enable/disable" since they return different errors on
// unexpected experiment IDs.
let cases: &[&[&str]] = &[
&[],
&["help"],
&["help", "repo"],
&["help", "repo", "add"],
&["help", "repo", "rm"],
&["help", "rule"],
&["help", "rule", "clear"],
&["help", "rule", "list"],
&["help", "rule", "replace"],
&["help", "rule", "replace", "file"],
&["help", "rule", "replace", "json"],
&["help", "experiment"],
&["help", "experiment", "enable"],
&["help", "experiment", "disable"],
&["help", "open"],
&["help", "update"],
&["help", "gc"],
&["repo", "add"],
&["repo", "add", "-f", "foo"],
&["repo", "add", "--file", "foo"],
&["repo", "rm", REPO_URL],
&["repo", "-v"],
&["repo", "--verbose"],
&["repo"],
&["rule", "clear"],
&["rule", "list"],
&["rule", "replace"],
&["rule", "replace", "file", "foo"],
&["rule", "replace", "json", CONFIG_JSON],
&["rule"],
&["experiment"],
&["update"],
&["gc"],
];
for case in cases {
check(case);
}
}
#[test]
fn test_help() {
fn check(args: &[&str], expected: &str) {
match parse_args(args.into_iter().map(|s| *s)) {
Err(Error::Help(msg)) => {
assert_eq!(msg, expected);
}
result => panic!("unexpected result {:?}", result),
};
}
check(&[], HELP);
check(&["-h"], HELP);
check(&["--help"], HELP);
check(&["help"], HELP);
check(&["help", "gc"], HELP_GC);
check(&["help", "update"], HELP_UPDATE);
check(&["help", "open"], HELP_OPEN);
check(&["help", "repo"], HELP_REPO);
check(&["help", "repo", "add"], HELP_REPO_ADD);
check(&["help", "repo", "rm"], HELP_REPO_RM);
check(&["help", "resolve"], HELP_RESOLVE);
check(&["help", "rule"], HELP_RULE);
check(&["help", "rule", "clear"], HELP_RULE_CLEAR);
check(&["help", "rule", "replace"], HELP_RULE_REPLACE);
check(&["help", "rule", "replace", "file"], HELP_RULE_REPLACE_FILE);
check(&["help", "rule", "replace", "json"], HELP_RULE_REPLACE_JSON);
check(&["help", "experiment"], HELP_EXPERIMENT);
check(&["help", "experiment", "enable"], HELP_EXPERIMENT_ENABLE);
check(&["help", "experiment", "disable"], HELP_EXPERIMENT_DISABLE);
}
#[test]
fn test_resolve() {
fn check(args: &[&str], expected_pkg_url: &str, expected_selectors: &[String]) {
match parse_args(args.into_iter().map(|s| *s)) {
Ok(Command::Resolve { pkg_url, selectors }) => {
assert_eq!(&pkg_url, expected_pkg_url);
assert_eq!(selectors, expected_selectors);
}
result => panic!("unexpected result {:?}", result),
};
}
let url = "fuchsia-pkg://fuchsia.com/foo/bar";
check(&["resolve", url], url, &[]);
check(
&["resolve", url, "selector1", "selector2"],
url,
&["selector1".to_string(), "selector2".to_string()],
);
}
#[test]
fn test_open() {
fn check(args: &[&str], expected_blob_id: &str, expected_selectors: &[String]) {
match parse_args(args.into_iter().map(|s| *s)) {
Ok(Command::Open { meta_far_blob_id, selectors }) => {
let expected_blob_id: BlobId = expected_blob_id.parse().unwrap();
assert_eq!(meta_far_blob_id, expected_blob_id);
assert_eq!(selectors, expected_selectors);
}
result => panic!("unexpected result {:?}", result),
};
}
let blob_id = "1111111111111111111111111111111111111111111111111111111111111111";
check(&["open", blob_id], blob_id, &[]);
check(
&["open", blob_id, "selector1", "selector2"],
blob_id,
&["selector1".to_string(), "selector2".to_string()],
);
}
#[test]
fn test_open_reject_malformed_blobs() {
match parse_args(["open", "bad_id"].iter().map(|a| *a)) {
Err(Error::BlobId(_)) => {}
result => panic!("unexpected result {:?}", result),
}
}
#[test]
fn test_repo() {
fn check(args: &[&str], expected: RepoCommand) {
match parse_args(args.into_iter().map(|s| *s)) {
Ok(Command::Repo(cmd)) => {
assert_eq!(cmd, expected);
}
result => panic!("unexpected result {:?}", result),
};
}
check(&["repo"], RepoCommand::List);
check(&["repo", "-v"], RepoCommand::ListVerbose);
check(&["repo", "--verbose"], RepoCommand::ListVerbose);
check(&["repo", "add", "-f", "foo"], RepoCommand::Add { file: "foo".into() });
check(&["repo", "add", "--file", "foo"], RepoCommand::Add { file: "foo".into() });
check(&["repo", "rm", REPO_URL], RepoCommand::Remove { repo_url: REPO_URL.to_string() });
}
#[test]
fn test_rule() {
fn check(args: &[&str], expected: RuleCommand) {
match parse_args(args.into_iter().map(|s| *s)) {
Ok(Command::Rule(cmd)) => {
assert_eq!(cmd, expected);
}
result => panic!("unexpected result {:?}", result),
};
}
check(&["rule", "list"], RuleCommand::List);
check(&["rule", "clear"], RuleCommand::Clear);
check(
&["rule", "replace", "file", "foo"],
RuleCommand::Replace { input_type: RuleConfigInputType::File { path: "foo".into() } },
);
check(
&["rule", "replace", "json", CONFIG_JSON],
RuleCommand::Replace {
input_type: RuleConfigInputType::Json { config: RuleConfig::Version1(vec![]) },
},
);
}
#[test]
fn test_experiment_ok() {
assert_matches!(
parse_args(["experiment", "enable", "lightbulb"].iter().cloned()),
Ok(Command::Experiment(ExperimentCommand::Enable(Experiment::Lightbulb)))
);
assert_matches!(
parse_args(["experiment", "disable", "lightbulb"].iter().cloned()),
Ok(Command::Experiment(ExperimentCommand::Disable(Experiment::Lightbulb)))
);
}
#[test]
fn test_experiment_unknown() {
assert_matches!(
parse_args(["experiment", "enable", "unknown"].iter().cloned()),
Err(Error::ExperimentId(id)) if id == "unknown"
);
assert_matches!(
parse_args(["experiment", "disable", "unknown"].iter().cloned()),
Err(Error::ExperimentId(id)) if id == "unknown"
);
}
#[test]
fn test_rule_replace_json_rejects_malformed_json() {
match parse_args(["rule", "replace", "json", "{"].iter().map(|a| *a)) {
Err(Error::Json(_)) => {}
result => panic!("unexpected result {:?}", result),
}
}
#[test]
fn test_update() {
match parse_args(["update"].iter().map(|a| *a)) {
Ok(Command::Update) => {}
result => panic!("unexpected result {:?}", result),
}
}
#[test]
fn test_gc() {
match parse_args(["gc"].iter().map(|a| *a)) {
Ok(Command::Gc) => {}
result => panic!("unexpected result {:?}", result),
}
}
}
|
//! This contains thin wrappers around `memfd_create` and the associated file sealing API.
//!
//! The [`MemFile`] struct represents a file created by the `memfd_create` syscall.
//! Such files are memory backed and fully anonymous, meaning no other process can see them (well... except by looking in `/proc` on Linux).
//!
//! After creation, the file descriptors can be shared with child processes, or even sent to another process over a Unix socket.
//! The files can then be memory mapped to be used as shared memory.
//!
//! This is all quite similar to `shm_open`, except that files created by `shm_open` are not anoynmous.
//! Depending on your application, the anonymous nature of `memfd` may be a nice property.
//! Additionally, files created by `shm_open` do not support file sealing.
//!
//! # File sealing
//! You can enable file sealing for [`MemFile`] by creating them with [`CreateOptions::allow_sealing(true)`][CreateOptions::allow_sealing].
//! This allows you to use [`MemFile::add_seals`] to add seals to the file.
//! You can also get the list of seals with [`MemFile::get_seals`].
//!
//! Once a seal is added to a file, it can not be removed.
//! Each seal prevents certain types of actions on the file.
//! For example: the [`Seal::Write`] seal prevents writing to the file, both through syscalls and memory mappings,
//! and the [`Seal::Shrink`] and [`Seal::Grow`] seals prevent the file from being resized.
//!
//! This is quite interesting for Rust, as it is the only guaranteed safe way to map memory:
//! when a file is sealed with [`Seal::Write`] and [`Seal::Shrink`], the file contents can not change, and the file can not be shrinked.
//! The latter is also important, because trying to read from a memory mapping a of file that was shrinked too far will raise a `SIGBUS` signal
//! and likely crash your application.
//!
//! Another interesting option is to first create a shared, writable memory mapping for your [`MemFile`],
//! and then add the [`Seal::FutureWrite`] and [`Seal::Shrink`] seals.
//! In that case, only the existing memory mapping can be used to change the contents of the file, even after the seals have been added.
//! When sharing the file with other processes, it prevents those processes from shrinking or writing to the file,
//! while the original process can still change the file contents.
//!
//! # Example
//! ```
//! # fn main() -> std::io::Result<()> {
//! use memfile::{MemFile, CreateOptions, Seal};
//! use std::io::Write;
//!
//! let mut file = MemFile::create("foo", CreateOptions::new().allow_sealing(true))?;
//! file.write_all(b"Hello world!")?;
//! file.add_seals(Seal::Write | Seal::Shrink | Seal::Grow)?;
//! // From now on, all writes or attempts to created shared, writable memory mappings will fail.
//! # Ok(())
//! # }
//! ```
use std::fs::File;
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
mod sys;
mod seal;
pub use seal::{Seal, Seals};
/// A memory backed file that can have seals applied to it.
///
/// The struct implements [`AsRawFd`], [`IntoRawFd`] and [`FromRawFd`].
/// When using [`FromRawFd::from_raw_fd`], you must ensure that the file descriptor is a valid `memfd`.
#[derive(Debug)]
pub struct MemFile {
file: File,
}
impl MemFile {
/// Create a new `memfd` with the given options.
///
/// The `name` argument is purely for debugging purposes.
/// On Linux it shows up in `/proc`, but it serves no other purpose.
/// In particular, multiple files can be created with the same name.
///
/// The close-on-exec flag is set on the created file descriptor.
/// If you want to pass it to a child process, you should use [`libc::dup2`] or something similar *after forking*.
/// Disabling the close-on-exec flag before forking causes a race condition with other threads.
pub fn create(name: &str, options: CreateOptions) -> std::io::Result<Self> {
let file = sys::memfd_create(name, options.as_flags())?;
Ok(Self { file })
}
/// Create a new `memfd` with default options.
///
/// Sealing is not enabled for the created file.
///
/// See [`Self::create`] for more information.
pub fn create_default(name: &str) -> std::io::Result<Self> {
Self::create(name, CreateOptions::default())
}
/// Create a new `memfd` with file sealing enabled.
///
/// Sealing is enabled for the created file.
/// All other options are the same as the defaults.
///
/// See [`Self::create`] for more information.
pub fn create_sealable(name: &str) -> std::io::Result<Self> {
Self::create(name, CreateOptions::new().allow_sealing(true))
}
/// Try to create a new [`MemFile`] Createinstance that shares the same underlying file handle as the existing [`MemFile`] instance.
///
/// Reads, writes, and seeks will affect both [`MemFile`] instances simultaneously.
pub fn try_clone(&self) -> std::io::Result<Self> {
let file = self.file.try_clone()?;
Ok(Self { file })
}
/// Wrap an already-open file as [`MemFile`].
///
/// This function returns an error if the file was not created by `memfd_create`.
///
/// If the function succeeds, the passed in file object is consumed and the returned [`MemFile`] takes ownership of the file descriptor.
/// If the function fails, the original file object is included in the returned error.
pub fn from_file<T: AsRawFd + IntoRawFd>(file: T) -> Result<Self, FromFdError<T>> {
match sys::memfd_get_seals(file.as_raw_fd()) {
Ok(_) => {
let file = unsafe { File::from_raw_fd(file.into_raw_fd()) };
Ok(Self { file })
},
Err(error) => Err(FromFdError { error, file }),
}
}
/// Convert this [`MemFile`] into an [`std::fs::File`].
///
/// This may be useful for interoperability with other crates.
pub fn into_file(self) -> std::fs::File {
self.file
}
/// Query metadata about the underlying file.
///
/// Note that not all information in the metadata is not very meaningfull for a `memfd`.
/// The file type is particularly useless since it is always the same.
/// Some information, like the file size, may be useful.
pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
self.file.metadata()
}
/// Truncate or extend the underlying file, updating the size of this file to become size.
///
/// If the size is less than the current file's size, then the file will be shrunk.
/// If it is greater than the current file's size, then the file will be extended to size and have all of the intermediate data filled in with 0s.
/// The file's cursor isn't changed.
/// In particular, if the cursor was at the end and the file is shrunk using this operation, the cursor will now be past the end.
pub fn set_len(&self, size: u64) -> std::io::Result<()> {
self.file.set_len(size)
}
/// Get the active seals of the file.
pub fn get_seals(&self) -> std::io::Result<Seals> {
let seals = sys::memfd_get_seals(self.as_raw_fd())?;
Ok(Seals::from_bits_truncate(seals as u32))
}
/// Add a single seal to the file.
///
/// If you want to add multiple seals, you should prefer [`Self::add_seals`] to reduce the number of syscalls.
///
/// This function will fail if the file was not created with sealing support,
/// if the file has already been sealed with [`Seal::Seal`],
/// or if you try to add [`Seal::Write`] while a shared, writable memory mapping exists for the file.
///
/// Adding a seal that is already active is a no-op.
pub fn add_seal(&self, seal: Seal) -> std::io::Result<()> {
self.add_seals(seal.into())
}
/// Add multiple seals to the file.
///
/// This function will fail if the file was not created with sealing support,
/// if the file has already been sealed with [`Seal::Seal`],
/// or if you try to add [`Seal::Write`] while a shared, writable memory mapping exists for the file.
///
/// Adding seals that are already active is a no-op.
pub fn add_seals(&self, seals: Seals) -> std::io::Result<()> {
sys::memfd_add_seals(self.as_raw_fd(), seals.bits() as std::os::raw::c_int)
}
}
impl FromRawFd for MemFile {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
let file = File::from_raw_fd(fd);
Self { file }
}
}
impl AsRawFd for MemFile {
fn as_raw_fd(&self) -> RawFd {
self.file.as_raw_fd()
}
}
impl IntoRawFd for MemFile {
fn into_raw_fd(self) -> RawFd {
self.file.into_raw_fd()
}
}
impl std::os::unix::fs::FileExt for MemFile {
fn read_at(&self, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
self.file.read_at(buf, offset)
}
fn write_at(&self, buf: &[u8], offset: u64) -> std::io::Result<usize> {
self.file.write_at(buf, offset)
}
}
impl std::io::Write for MemFile {
fn flush(&mut self) -> std::io::Result<()> {
self.file.flush()
}
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.file.write(buf)
}
}
impl std::io::Read for MemFile {
fn read(&mut self, buf: &mut[u8]) -> std::io::Result<usize> {
self.file.read(buf)
}
}
impl std::io::Seek for MemFile {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
self.file.seek(pos)
}
}
impl From<MemFile> for std::process::Stdio {
fn from(other: MemFile) -> Self {
other.file.into()
}
}
/// Options for creating a [`MemFile`].
///
/// Support for options depend on platform and OS details.
/// Refer to your kernel documentation of `memfd_create` for details.
#[derive(Copy, Clone, Debug, Default)]
pub struct CreateOptions {
allow_sealing: bool,
huge_table: Option<HugeTlb>,
}
impl CreateOptions {
/// Get the default creation options for a [`MemFile`].
///
/// Initially, file sealing is not enabled no no huge TLB page size is configured.
///
/// Note that the close-on-exec flag will always be set on the created file descriptor.
/// If you want to pass it to a child process, you should use [`libc::dup2`] or something similar *after forking*.
/// Disabling the close-on-exec flag before forking causes a race condition with other threads.
pub fn new() -> Self {
Self::default()
}
/// Create a new [`MemFile`]` with the given options.
///
/// This is a shorthand for [`MemFile::create`].
/// See that function for more details.
pub fn create(&self, name: &str) -> std::io::Result<MemFile> {
MemFile::create(name, *self)
}
/// Allow sealing operations on the created [`MemFile`].
pub fn allow_sealing(mut self, value: bool) -> Self {
self.allow_sealing = value;
self
}
/// Create the file in a `hugetlbfs` filesystem using huge pages for the translation look-aside buffer.
///
/// Support for this feature and specific sizes depend on the CPU and kernel configuration.
/// See also: <https://www.kernel.org/doc/html/latest/admin-guide/mm/hugetlbpage.html>
pub fn huge_tlb(mut self, value: impl Into<Option<HugeTlb>>) -> Self {
self.huge_table = value.into();
self
}
/// Get the options as raw flags for `libc::memfd_create`.
fn as_flags(&self) -> std::os::raw::c_int {
let mut flags = sys::flags::MFD_CLOEXEC;
if self.allow_sealing {
flags |= sys::flags::MFD_ALLOW_SEALING;
}
#[cfg(target_os = "linux")]
if let Some(size) = self.huge_table {
flags |= sys::flags::MFD_HUGETLB | size as u32 as std::os::raw::c_int;
}
flags
}
}
/// Page size for the translation look-aside buffer.
///
/// Support for specific sizes depends on the CPU and kernel configuration.
/// See also: <https://www.kernel.org/doc/html/latest/admin-guide/mm/hugetlbpage.html>
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[repr(u32)]
#[non_exhaustive]
pub enum HugeTlb {
Huge64KB = sys::flags::MFD_HUGE_64KB as u32,
Huge512KB = sys::flags::MFD_HUGE_512KB as u32,
Huge1MB = sys::flags::MFD_HUGE_1MB as u32,
Huge2MB = sys::flags::MFD_HUGE_2MB as u32,
Huge8MB = sys::flags::MFD_HUGE_8MB as u32,
Huge16MB = sys::flags::MFD_HUGE_16MB as u32,
Huge32MB = sys::flags::MFD_HUGE_32MB as u32,
Huge256MB = sys::flags::MFD_HUGE_256MB as u32,
Huge512MB = sys::flags::MFD_HUGE_512MB as u32,
Huge1GB = sys::flags::MFD_HUGE_1GB as u32,
Huge2GB = sys::flags::MFD_HUGE_2GB as u32,
Huge16GB = sys::flags::MFD_HUGE_16GB as u32,
}
/// Error returned when the file passed to [`MemFile::from_file`] is not a `memfd`.
///
/// This struct contains the [`std::io::Error`] that occurred and the original value passed to `from_file`.
/// It is also directly convertible to [`std::io::Error`], so you can pass it up using the `?` operator
/// from a function that returns an [`std::io::Result`].
pub struct FromFdError<T> {
error: std::io::Error,
file: T,
}
impl<T> FromFdError<T> {
/// Get a reference to the I/O error.
pub fn error(&self) -> &std::io::Error {
&self.error
}
/// Get a reference to the original file object.
pub fn file(&self) -> &T {
&self.file
}
/// Consume the struct and return the I/O error and the original file object as tuple.
pub fn into_parts(self) -> (std::io::Error, T) {
(self.error, self.file)
}
/// Consume the struct and return the I/O error.
pub fn into_error(self) -> std::io::Error {
self.error
}
/// Consume the struct and return the original file object.
pub fn into_file(self) -> T {
self.file
}
}
impl<T> From<FromFdError<T>> for std::io::Error {
fn from(other: FromFdError<T>) -> Self {
other.into_error()
}
}
|
fn main() {
const A: u32 = 1;
println!("A: {}", A);
let asas = 2;
println!("asas: {}", asas);
println!("{}", 4.0 / 3.0);
}
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from ../gir-files
// DO NOT EDIT
use crate::SessionFeature;
use std::fmt;
glib::wrapper! {
#[doc(alias = "SoupWebsocketExtensionManager")]
pub struct WebsocketExtensionManager(Object<ffi::SoupWebsocketExtensionManager, ffi::SoupWebsocketExtensionManagerClass>) @implements SessionFeature;
match fn {
type_ => || ffi::soup_websocket_extension_manager_get_type(),
}
}
impl WebsocketExtensionManager {}
pub const NONE_WEBSOCKET_EXTENSION_MANAGER: Option<&WebsocketExtensionManager> = None;
impl fmt::Display for WebsocketExtensionManager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("WebsocketExtensionManager")
}
}
|
pub mod data;
pub mod song;
use radio::song::Song;
/// A radio must be able to provide the currently played song
pub trait Radio {
/// Get the currently playing song.
fn get_current_song(&self) -> Option<Song>;
}
/// Representation of a radiostation
pub struct RadioStation {
/// Name
pub name: &'static str,
/// Shorthand
pub shorthand: &'static str,
/// URL to a site containing the currently playing song
url: &'static str,
/// Function to get the currently playing song
get_song: fn(&str) -> Option<Song>,
}
impl Radio for RadioStation {
fn get_current_song(&self) -> Option<Song> {
use util::http_scraper::scrape;
// Get html from url
let html = match scrape(self.url, self.name) {
Some(html) => html,
None => return None,
};
// Get song
let song = match (self.get_song)(&html) {
Some(song) => {
if song.is_empty() {
return None;
}
song
},
None => return None,
};
Some(song)
}
}
|
mod primes_iter;
mod primality_checker;
pub fn iter() -> primes_iter::PrimesIter {
primes_iter::new()
}
pub fn is_prime(num: u64) -> bool {
primality_checker::new().is_prime(num)
}
#[test]
fn test_is_prime() {
assert_eq!(false, is_prime(10));
assert_eq!(true, is_prime(11));
} |
#![feature(box_syntax)]
extern crate actix_web;
extern crate rusqlite;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate askama;
#[macro_use]
extern crate log;
extern crate stderrlog;
extern crate structopt;
extern crate rusoto_core;
extern crate rusoto_s3;
extern crate futures;
extern crate hyper;
use std::path::PathBuf;
use std::sync::{mpsc, Arc};
use std::sync::mpsc::{SyncSender, Receiver};
use std::thread;
use actix_web::{server, App, fs, middleware};
use structopt::StructOpt;
mod db;
mod worker;
mod httphandler;
mod cache;
use worker::worker_loop;
use httphandler::{get_main_page, get_reader_page, get_book_list,
get_book_data, get_reader_status,
AppConfig};
#[derive(StructOpt, Debug, Clone)]
#[structopt(name = "basic")]
struct Opt {
#[structopt(short = "d", long = "db")]
meta_data_db: String,
#[structopt(short = "s", long = "static-pages", parse(from_os_str))]
static_path: PathBuf,
#[structopt(short = "c", long = "cache-dir", parse(from_os_str))]
cache_path: PathBuf,
#[structopt(short = "D", long = "data-root-dir", parse(from_os_str))]
data_path: Option<PathBuf>,
#[structopt(short = "C", long = "converter", default_value = "ebook-convert")]
converter_bin: String,
#[structopt(short = "v", long = "verbose", parse(from_occurrences))]
verbosity: usize,
#[structopt(short = "p", long = "app-uri-prefix", default_value = "")]
app_prefix: String,
#[structopt(short = "b", long = "bind-to", default_value = "0.0.0.0:8000")]
bind_to: String,
#[structopt(long = "s3-region", default_value = "us-east-1")]
s3_region: String
}
impl Opt {
pub fn make_app_config(self,
conv_task_tx: SyncSender<(PathBuf, PathBuf)>)
-> AppConfig {
// As an intermediate solution, only metadata can be read from S3 directly.
// In case the meta_data_db is S3 URI, there's no way to resolve data path.
// Therefore, the startup process will exit with an error code, then.
if self.meta_data_db.starts_with("s3://") {
let data_path = self.data_path.expect(
"Need to specify data path explicitly when metadata is from S3");
AppConfig {
db_connector: box db::S3DBConnector::new(
&self.meta_data_db,
&self.s3_region),
static_path: self.static_path,
cache_path: self.cache_path,
data_path: data_path,
app_prefix: self.app_prefix,
conv_task_tx: conv_task_tx,
}
} else {
let default_data_path = {
let mut p = PathBuf::from(self.meta_data_db.clone());
p.pop();
p
};
AppConfig {
db_connector: box db::LocalDBConnector::new(&self.meta_data_db),
static_path: self.static_path,
cache_path: self.cache_path,
data_path: self.data_path.unwrap_or(default_data_path),
app_prefix: self.app_prefix,
conv_task_tx: conv_task_tx
}
}
}
}
fn main() {
let opt = Opt::from_args();
stderrlog::new().verbosity(opt.verbosity).init().unwrap();
info!("Starting e-book converter thread...");
let (tx, rx): (SyncSender<(PathBuf, PathBuf)>, Receiver<(PathBuf, PathBuf)>) =
mpsc::sync_channel(100);
let converter_bin = opt.converter_bin.clone();
thread::spawn(move || {
worker_loop(&converter_bin, rx);
});
let conf = Arc::new(opt.clone().make_app_config(tx));
server::new(move || {
App::with_state(conf.clone())
.prefix(conf.app_prefix.clone())
.middleware(middleware::Logger::default())
.resource("/api/booklist.js", |r| r.f(get_book_list))
.resource("/api/{bookid}/reader_status.js",
|r| r.f(get_reader_status))
.resource("", |r| r.f(get_main_page))
.resource("/", |r| r.f(get_main_page))
.resource(
"/data/{bookid}/{datatype}",
|r| r.f(get_book_data))
.resource(
"/reader/{bookid}",
|r| r.f(get_reader_page))
.handler(
"/book",
fs::StaticFiles::new(conf.cache_path.to_str().unwrap())
.unwrap()
.show_files_listing())
.handler(
"/",
fs::StaticFiles::new(conf.static_path.to_str().unwrap())
.unwrap()
.show_files_listing())
})
.bind(&opt.bind_to)
.expect(&format!("Can not bind to {}", &opt.bind_to))
.run();
}
|
// Copyright 2018 Ulysse Beaugnon and Ecole Normale Superieure
//
// 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.
//! Unsafe wrapper around library from Kalray.
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
pub mod opencl;
// Include files generated by bindgen for telajax
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
use lazy_static::lazy_static;
use libc;
use log::debug;
use std::{
ffi::CStr,
result::Result,
sync::{Arc, RwLock},
};
// OpenCL is supposed to be thread-safe but is not, so we have to sequentialize every call to
// telajax by safety. Some of these call could probably be called without protection and still
// working, but we are being conservative here
lazy_static! {
static ref MEM_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
}
// This macro does the job of wrapping every call to telajax with a lock
macro_rules! telajax_call {
($fn:ident, $( $arg:expr),* ) => {{
let _ = MEM_MUTEX.lock();
$fn($($arg),*)
}}
}
lazy_static! {
static ref DEVICE: Device = Device::init().unwrap();
}
#[derive(Debug)]
pub enum RWError {
SizeMismatch(usize, usize),
CLError(opencl::Error),
}
/// Buffer in MPPA RAM.
/// This is actually a wrapper around Mem that also holds type information and present a safe
/// interface (access protected with RwLock)
pub struct Buffer<T: Copy> {
pub mem: RwLock<Mem>,
/// number of T elements (not of bytes like in mem)
pub len: usize,
pub executor: &'static Device,
phantom: std::marker::PhantomData<T>,
}
impl<T: Copy> Buffer<T> {
pub fn new(executor: &'static Device, len: usize) -> Self {
let mem_block = executor.alloc(len * std::mem::size_of::<T>()).unwrap();
Buffer {
mem: RwLock::new(mem_block),
len,
executor,
phantom: std::marker::PhantomData,
}
}
pub fn raw_ptr(&self) -> *const libc::c_void {
self.mem.read().unwrap().raw_ptr()
}
pub fn read(&self) -> Result<Vec<T>, RWError> {
let mut data: Vec<T> = Vec::with_capacity(self.len);
let mem = self.mem.read().unwrap();
let res = self
.executor
.read_buffer(&mem, data.as_mut_slice(), self.len);
if let Err(rw_error) = res {
Err(rw_error)
} else {
unsafe {
Vec::set_len(&mut data, self.len);
}
Ok(data)
}
}
pub fn write(&self, data: &[T]) -> Result<(), RWError> {
let mut mem = self.mem.write().unwrap();
self.executor.write_buffer(data, &mut mem)
}
}
/// A Telajax execution context.
pub struct Device {
/// We use an Arc to make sure that no callback is pointing to the device when we try to drop
/// it
inner: Arc<device_t>,
}
unsafe impl Sync for Device {}
unsafe impl Send for Device {}
impl Device {
/// Returns a reference to the `Device`. As Telajax implementation is
/// supposed to be thread-safe, it should be therefore safe to call
/// this api from different threads. These calls are done through a
/// static immutable reference
/// It appeared that the Kalray OpenCL is actually not thread-safe at all,
/// see above
pub fn get() -> &'static Device {
&DEVICE
}
/// Initializes the device.
fn init() -> Result<Self, opencl::Error> {
let mut error = 0;
let device = unsafe {
Device {
inner: Arc::new(telajax_call!(
telajax_device_init,
0,
std::ptr::null_mut(),
&mut error
)),
}
};
if error != 0 {
Err(error.into())
} else {
Ok(device)
}
}
/// allocate an array of len T elements on device
pub fn allocate_array<T: Copy>(&'static self, len: usize) -> Buffer<T> {
Buffer::new(self, len)
}
/// Build a wrapper for a kernel.
pub fn build_wrapper(
&self,
name: &CStr,
code: &CStr,
) -> Result<Wrapper, opencl::Error> {
let mut error = 0;
let flags: &'static CStr = Default::default();
let wrapper = unsafe {
telajax_call!(
telajax_wrapper_build,
name.as_ptr(),
code.as_ptr(),
flags.as_ptr(),
&*self.inner as *const device_t as *mut device_t,
&mut error
)
};
if error != 0 {
Err(error.into())
} else {
Ok(Wrapper(wrapper))
}
}
/// Compiles a kernel.
pub fn build_kernel(
&self,
code: &CStr,
cflags: &CStr,
lflags: &CStr,
wrapper: &Wrapper,
) -> Result<Kernel, opencl::Error> {
let mut error = 0;
{
let kernel = unsafe {
telajax_call!(
telajax_kernel_build,
code.as_ptr(),
cflags.as_ptr(),
lflags.as_ptr(),
&wrapper.0 as *const wrapper_t as *mut wrapper_t,
&*self.inner as *const device_t as *mut device_t,
&mut error
)
};
if error != 0 {
Err(error.into())
} else {
Ok(Kernel(kernel))
}
}
}
/// Asynchronously executes a `Kernel`.
pub fn enqueue_kernel(&self, kernel: &mut Kernel) -> Result<Event, opencl::Error> {
let mut event = Event::new();
unsafe {
let err = telajax_call!(
telajax_kernel_enqueue,
&mut kernel.0 as *mut kernel_t,
&*self.inner as *const device_t as *mut device_t,
&mut event.0 as *mut cl_event
);
if err != 0 {
Err(err.into())
} else {
Ok(event)
}
}
}
/// Executes a `Kernel` and then wait for completion.
pub fn execute_kernel(&self, kernel: &mut Kernel) -> Result<(), opencl::Error> {
let mut event = Event::new();
unsafe {
let err = telajax_call!(
telajax_kernel_enqueue,
&mut kernel.0 as *mut kernel_t,
&*self.inner as *const device_t as *mut device_t,
&mut event.0 as *mut cl_event
);
if err != 0 {
return Err(err.into());
}
let err = telajax_call!(telajax_event_wait, 1, &mut event.0 as *mut cl_event);
if err != 0 {
Err(err.into())
} else {
Ok(())
}
}
}
/// Waits until all kernels have completed their execution.
pub fn wait_all(&self) -> Result<(), opencl::Error> {
unsafe {
let err = telajax_call!(
telajax_device_waitall,
&*self.inner as *const device_t as *mut device_t
);
if err == 0 {
Ok(())
} else {
Err(err.into())
}
}
}
/// Allocates a memory buffer. Should only be used by Buffer::new
fn alloc(&self, size: usize) -> Result<Mem, opencl::Error> {
let mut error = 0;
let mem = unsafe {
telajax_call!(
telajax_device_mem_alloc,
size,
1 << 0,
&*self.inner as *const device_t as *mut device_t,
&mut error
)
};
if error == 0 {
Ok(Mem {
ptr: mem,
len: size,
})
} else {
Err(error.into())
}
}
/// Asynchronously copies a buffer to the device.
fn async_write_buffer<T: Copy>(
&self,
data: &[T],
mem: &mut Mem,
wait_events: &[Event],
) -> Result<Event, RWError> {
let size = data.len() * std::mem::size_of::<T>();
if size > mem.len {
return Err(RWError::SizeMismatch(size, mem.len));
}
let data_ptr = data.as_ptr() as *mut std::os::raw::c_void;
let wait_n = wait_events.len() as libc::c_uint;
let wait_ptr = wait_events.as_ptr() as *const event_t;
let mut event = Event::new();
unsafe {
let res = telajax_call!(
telajax_device_mem_write,
&*self.inner as *const device_t as *mut device_t,
mem.ptr,
data_ptr,
size,
wait_n,
wait_ptr,
&mut event.0 as *mut cl_event
);
if res != 0 {
Err(RWError::CLError(res.into()))
} else {
Ok(event)
}
}
}
/// Copies a buffer to the device.
fn write_buffer<T: Copy>(&self, data: &[T], mem: &mut Mem) -> Result<(), RWError> {
let size = data.len() * std::mem::size_of::<T>();
if size > mem.len {
return Err(RWError::SizeMismatch(size, mem.len));
}
let data_ptr = data.as_ptr() as *mut std::os::raw::c_void;
let wait_ptr = std::ptr::null() as *const event_t;
let event_ptr = std::ptr::null_mut();
unsafe {
let err = telajax_call!(
telajax_device_mem_write,
&*self.inner as *const device_t as *mut device_t,
mem.ptr,
data_ptr,
size,
0,
wait_ptr,
event_ptr
);
if err != 0 {
Err(RWError::CLError(err.into()))
} else {
Ok(())
}
}
}
/// Asynchronously copies a buffer from the device.
fn async_read_buffer<T: Copy>(
&self,
mem: &Mem,
data: &mut [T],
len: usize,
wait_events: &[Event],
) -> Result<Event, RWError> {
let size = len * std::mem::size_of::<T>();
if size > mem.len {
return Err(RWError::SizeMismatch(size, mem.len));
}
let data_ptr = data.as_ptr() as *mut std::os::raw::c_void;
let wait_n = wait_events.len() as std::os::raw::c_uint;
let mut event = Event::new();
{
// Block for lock drop
let wait_ptr = if wait_n == 0 {
std::ptr::null() as *const event_t
} else {
wait_events.as_ptr() as *const event_t
};
unsafe {
let res = telajax_call!(
telajax_device_mem_read,
&*self.inner as *const device_t as *mut device_t,
mem.ptr,
data_ptr,
size,
wait_n,
wait_ptr,
&mut event.0 as *mut cl_event
);
if res != 0 {
Err(RWError::CLError(res.into()))
} else {
Ok(event)
}
}
}
}
/// Copies a buffer from the device.
fn read_buffer<T: Copy>(
&self,
mem: &Mem,
data: &mut [T],
len: usize,
) -> Result<(), RWError> {
let size = len * std::mem::size_of::<T>();
if size > mem.len {
return Err(RWError::SizeMismatch(size, mem.len));
}
let data_ptr = data.as_ptr() as *mut std::os::raw::c_void;
let null_mut = std::ptr::null_mut();
let wait_n = 0;
let wait_ptr = std::ptr::null() as *const event_t;
unsafe {
let res = telajax_call!(
telajax_device_mem_read,
&*self.inner as *const device_t as *mut device_t,
mem.ptr,
data_ptr,
size,
wait_n,
wait_ptr,
null_mut
);
if res != 0 {
Err(RWError::CLError(res.into()))
} else {
Ok(())
}
}
}
/// Set a callback to call when an event is triggered.
pub fn set_event_callback<F>(&self, event: &Event, closure: F) -> Result<(), ()>
where
F: FnOnce() + Send,
{
let callback_data = CallbackData {
closure,
arc_device: Arc::clone(&self.inner),
};
let data_ptr = Box::into_raw(Box::new(callback_data));
let callback = callback_wrapper::<F>;
unsafe {
let data_ptr = data_ptr as *mut std::os::raw::c_void;
if telajax_call!(
telajax_event_set_callback,
Some(callback),
data_ptr,
event.0
) == 0
{
Ok(())
} else {
Err(())
}
}
}
}
impl Drop for Device {
fn drop(&mut self) {
if let Some(inner) = Arc::get_mut(&mut self.inner) {
unsafe {
telajax_call!(telajax_device_finalize, inner);
}
} else {
// if None is returned here, this means that some callback still holds a closure to the
// Device. This is not supposed to happen, so we panic
panic!("Trying to drop Device while there is still someone holding a reference to it");
}
debug!("MPPA device finalized");
}
}
/// A wrapper openCL that will call the kernel through OpenCL interface
pub struct Wrapper(wrapper_t);
unsafe impl Send for Wrapper {}
unsafe impl Sync for Wrapper {}
impl Drop for Wrapper {
fn drop(&mut self) {
unsafe {
assert_eq!(
telajax_call!(telajax_wrapper_release, &mut self.0 as *mut wrapper_t),
0
);
}
}
}
pub struct Kernel(kernel_t);
unsafe impl Send for Kernel {}
impl Kernel {
/// Sets the arguments of the `Kernel`.
pub fn set_args(
&mut self,
sizes: &[usize],
args: &[*const libc::c_void],
) -> Result<(), ()> {
if sizes.len() != args.len() {
return Err(());
};
let num_arg = sizes.len() as i32;
let sizes_ptr = sizes.as_ptr();
unsafe {
// Needs *mut ptr mostly because they were not specified as const in original
// c api
if telajax_call!(
telajax_kernel_set_args,
num_arg,
sizes_ptr as *const usize as *mut usize,
args.as_ptr() as *const *const libc::c_void as *mut *mut libc::c_void,
&mut self.0 as *mut kernel_t
) == 0
{
Ok(())
} else {
Err(())
}
}
}
/// Sets the number of clusters that must execute the `Kernel`.
pub fn set_num_clusters(&mut self, num: usize) -> Result<(), ()> {
if num > 16 {
return Err(());
}
unsafe {
if telajax_call!(
telajax_kernel_set_dim,
1,
[1].as_ptr(),
[num].as_ptr(),
&mut self.0 as *mut kernel_t
) == 0
{
Ok(())
} else {
Err(())
}
}
}
}
impl Drop for Kernel {
fn drop(&mut self) {
unsafe {
assert_eq!(
telajax_call!(telajax_kernel_release, &mut self.0 as *mut kernel_t),
0
);
}
}
}
/// A buffer allocated on the device.
pub struct Mem {
/// pointer in host memory that will be passed to telajax calls
ptr: mem_t,
/// number of bytes allocated on device
len: usize,
}
unsafe impl Sync for Mem {}
unsafe impl Send for Mem {}
impl Mem {
/// Telajax_set_args needs to have the size of the ptr for its call
/// in general, this is just a pointer on host
pub fn get_mem_size() -> usize {
std::mem::size_of::<mem_t>()
}
pub fn raw_ptr(&self) -> *const libc::c_void {
&self.ptr as *const mem_t as *const libc::c_void
}
pub fn len(&self) -> usize {
self.len
}
}
impl Drop for Mem {
fn drop(&mut self) {
unsafe {
assert_eq!(telajax_call!(telajax_device_mem_release, self.ptr), 0);
}
}
}
/// An event triggered at the end of a memory operation or kernel execution.
#[repr(C)]
pub struct Event(*mut _cl_event);
impl Event {
/// Event is always initialized by a call to an OpenCL function (for exemple
/// clEnqueueWriteKernel so we just have to pass a null pointer (more precisely, a pointer to a
/// null pointer)
fn new() -> Self {
let event: *mut _cl_event = std::ptr::null_mut();
Event(event)
}
}
impl Drop for Event {
fn drop(&mut self) {
unsafe {
telajax_call!(telajax_event_release, self.0);
}
}
}
/// Calls the closure passed in data.
unsafe extern "C" fn callback_wrapper<F: FnOnce()>(
_: cl_event,
_: i32,
data: *mut std::os::raw::c_void,
) {
let data = Box::from_raw(data as *mut CallbackData<F>);
(data.closure)();
}
type Callback = unsafe extern "C" fn(*const libc::c_void, i32, *mut libc::c_void);
struct CallbackData<F: FnOnce()> {
closure: F,
arc_device: Arc<device_t>,
}
|
pub mod descriptorsetlayoutbindingflagscreateinfoext;
pub mod descriptorsetvariabledescriptorcountallocationinfoext;
pub mod descriptorsetvariabledescriptorcountlayoutsupportext;
pub mod physicaldevicedescriptorindexingfeaturesext;
pub mod physicaldevicedescriptorindexingpropertiesext;
pub mod physicaldevicememorybudgetpropertiesext;
pub mod prelude;
|
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::prelude::*;
use std::io::Read;
use std::process::Command;
#[derive(Serialize, Deserialize, Debug)]
struct Lock {
lock: bool, // commit to git
name: i64,
}
#[derive(Serialize, Deserialize, Debug)]
struct Data {
value: Vec<Insd>,
}
#[derive(Serialize, Deserialize, Debug)]
struct Insd {
filename: String,
value: String,
}
fn maketext(data: &Data) {
let mut file = File::create("all.txt").expect("notcreated");
let mut st = String::new();
for i in data.value.iter() {
st.push_str("Ques ");
st.push_str(&i.filename);
st.push_str(" >>>>\n");
st.push_str(&i.value.replace("\n\n", "\n"));
st.push_str("===============================================================\n");
}
file.write_all(&st.as_bytes()).expect("not written");
}
fn get_lock() -> Lock {
let lk: Lock = serde_json::from_reader(File::open("lock.json").unwrap()).unwrap();
lk
}
fn get_lock_increment() -> Lock {
let mut lk: Lock = serde_json::from_reader(File::open("lock.json").unwrap()).unwrap();
lk.name += 1;
serde_json::to_writer(File::create("lock.json").unwrap(), &lk).unwrap();
lk
}
fn get_lock_true() -> Lock {
let mut lk: Lock = serde_json::from_reader(File::open("lock.json").unwrap()).unwrap();
lk.lock = true;
serde_json::to_writer(File::create("lock.json").unwrap(), &lk).unwrap();
lk
}
fn get_lock_false() -> Lock {
let mut lk: Lock = serde_json::from_reader(File::open("lock.json").unwrap()).unwrap();
lk.lock = false;
serde_json::to_writer(File::create("lock.json").unwrap(), &lk).unwrap();
lk
}
fn main() {
let mut lk = get_lock_increment();
let mut name: String = lk.name.to_string();
name.push_str(".png");
let file = lk.name.to_string();
let mut maimpng = lk.name.to_string();
maimpng.push_str("/");
maimpng.push_str(&name);
let mut ttext = lk.name.to_string();
ttext.push_str("/");
ttext.push_str(&file);
let mkfold = Command::new("mkdir")
.arg(&file)
.spawn()
.expect("asf")
.wait()
.unwrap();
let maimout = Command::new("maim")
.arg("-s")
.arg(&maimpng)
.spawn()
.expect("maim no crop")
.wait()
.unwrap();
let notifyout = Command::new("notify-send")
.arg("Taken")
.arg("Screenshot")
.spawn()
.expect("notify-send not")
.wait()
.unwrap();
let tesseractout = Command::new("tesseract")
.arg(&maimpng)
.arg(&ttext)
.spawn()
.expect("tesseract")
.wait()
.unwrap();
let fina = ttext.clone();
ttext.push_str(".txt");
let mut file = File::open("questionlist.json").unwrap();
let mut foo: Data = serde_json::from_reader(file).unwrap();
foo.value.push(Insd {
value: get_text(&ttext),
filename: fina,
});
println!("{:#?}", foo);
maketext(&foo);
serde_json::to_writer(File::create("questionlist.json").unwrap(), &foo).unwrap();
let mut tlock: Lock = serde_json::from_reader(File::open("lock.json").unwrap()).unwrap();
if tlock.lock == false {
get_lock_true();
let commit = Command::new("./commit.sh")
.spawn()
.expect("commitfaile")
.wait()
.expect("wait fil");
get_lock_false();
}
}
fn get_text(path: &str) -> String {
let mut a: String = std::fs::read_to_string(path).unwrap().parse().unwrap();
a = a.replace("\n\n", "\n");
a = a.replace("\n\n", "\n");
a = a.replace("O000", "");
a = a.replace("O ", "");
a = a.replace("Q", "");
a = a.replace("Q ", "");
a = a.replace("o ", "");
a = a.replace("Options.", "");
a = a.replace("options.", "");
a = a.replace("Options", "");
a = a.replace("options", "");
a
}
|
// 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_base::base::tokio;
use common_exception::Result;
use common_management::*;
use common_meta_app::principal::UserSetting;
use common_meta_app::principal::UserSettingValue;
use common_meta_embedded::MetaEmbedded;
use common_meta_kvapi::kvapi::KVApi;
use common_meta_types::MatchSeq;
use common_meta_types::SeqV;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_set_setting() -> Result<()> {
let (kv_api, mgr) = new_setting_api().await?;
{
let setting = UserSetting::create("max_threads", UserSettingValue::UInt64(3));
mgr.set_setting(setting.clone()).await?;
let value = kv_api
.get_kv("__fd_settings/databend_query/max_threads")
.await?;
match value {
Some(SeqV {
seq: 1,
meta: _,
data: value,
}) => {
assert_eq!(value, serde_json::to_vec(&setting)?);
}
catch => panic!("GetKVActionReply{:?}", catch),
}
}
// Set again.
{
let setting = UserSetting::create("max_threads", UserSettingValue::UInt64(1));
mgr.set_setting(setting.clone()).await?;
let value = kv_api
.get_kv("__fd_settings/databend_query/max_threads")
.await?;
match value {
Some(SeqV {
seq: 2,
meta: _,
data: value,
}) => {
assert_eq!(value, serde_json::to_vec(&setting)?);
}
catch => panic!("GetKVActionReply{:?}", catch),
}
}
// Get settings.
{
let expect = vec![UserSetting::create(
"max_threads",
UserSettingValue::UInt64(1),
)];
let actual = mgr.get_settings().await?;
assert_eq!(actual, expect);
}
// Get setting.
{
let expect = UserSetting::create("max_threads", UserSettingValue::UInt64(1));
let actual = mgr.get_setting("max_threads", MatchSeq::GE(0)).await?;
assert_eq!(actual.data, expect);
}
// Drop setting.
{
mgr.drop_setting("max_threads", MatchSeq::GE(1)).await?;
}
// Get settings.
{
let actual = mgr.get_settings().await?;
assert_eq!(0, actual.len());
}
// Get setting.
{
let res = mgr.get_setting("max_threads", MatchSeq::GE(0)).await;
assert!(res.is_err());
}
// Drop setting not exists.
{
let res = mgr.drop_setting("max_threads_not", MatchSeq::GE(1)).await;
assert!(res.is_err());
}
Ok(())
}
async fn new_setting_api() -> Result<(Arc<MetaEmbedded>, SettingMgr)> {
let test_api = Arc::new(MetaEmbedded::new_temp().await?);
let mgr = SettingMgr::create(test_api.clone(), "databend_query")?;
Ok((test_api, mgr))
}
|
use std::io::BufWriter;
use protobuf::{parse_from_bytes, CodedInputStream, CodedOutputStream, Message};
use protobuf_exploration::message::gen::core::*;
use protobuf_exploration::message::gen::request::*;
use std::time::SystemTime;
fn main() {
let start = SystemTime::now();
let limit = 1_000_000;
for _ in 0..limit {
let mut uuid = UuidMessage::new();
uuid.set_v1(4567894567890);
uuid.set_v2(9876549876543);
let mut north = Request::new();
north.set_Id(123123);
north.set_Session(uuid.clone());
north.set_Character(uuid.clone());
north.set_Movement(Direction::North);
let mut south = north.clone();
south.set_Facing(Direction::South);
let mut buffer1 = vec![0u8; 0];
let mut buffer2 = vec![0u8; 0];
let mut os1 = CodedOutputStream::new(&mut buffer1);
let mut os2 = CodedOutputStream::new(&mut buffer2);
let _ = north.write_to(&mut os1);
let _ = south.write_to(&mut os2);
let _ = os1.flush();
let _ = os2.flush();
let mut request1: Request = parse_from_bytes(&buffer1).unwrap();
let mut request2: Request = parse_from_bytes(&buffer2).unwrap();
assert_eq!(request1.Id, request2.Id);
}
let microseconds = SystemTime::now().duration_since(start).unwrap().as_micros();
println!(
"Took {}µs to iterate {} times ({} iter/µs, 1 iter every {}µs).",
microseconds,
limit,
(limit as f32 / microseconds as f32),
(microseconds as f32 / limit as f32)
);
}
|
mod circular_buf;
mod raw_slab;
pub use self::circular_buf::CircularBuf;
pub use self::raw_slab::RawSlab;
|
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use tiberius::{numeric::Decimal, time::chrono::NaiveDate, Row};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ImageSource {
pub id: u8,
pub name: String,
}
impl TryFrom<&Row> for ImageSource {
type Error = crate::error::Error;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let id = row.try_get::<u8, _>(0)?.unwrap();
let name = row.try_get::<&str, _>(1)?.unwrap().to_string();
Ok(ImageSource { id, name })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StateType {
State,
Territory,
FederalCapital,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct State {
pub id: String,
pub name: String,
pub capital: Option<String>,
pub population: Option<i32>,
pub area_square_km: Option<i32>,
pub state_type: StateType,
}
impl TryFrom<&Row> for State {
type Error = crate::error::Error;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let id = row.try_get::<&str, _>(0)?.unwrap().to_string();
let name = row.try_get::<&str, _>(1)?.unwrap().to_string();
let capital = row.try_get::<&str, _>(2)?.map(|s| s.to_string());
let population = row.try_get::<i32, _>(3)?;
let area_square_km = row.try_get::<i32, _>(4)?;
let state_type = match row.try_get::<&str, _>(5)? {
Some("S") => StateType::State,
Some("T") => StateType::Territory,
Some("F") => StateType::FederalCapital,
x @ _ => return Err(Self::Error::UnknownStateType(format!("{:?}", x))),
};
Ok(State {
id,
name,
capital,
population,
area_square_km,
state_type,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct County {
pub id: i32,
pub state_id: String,
pub name: String,
}
impl TryFrom<&Row> for County {
type Error = crate::error::Error;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let id = row.try_get::<i32, _>(0)?.unwrap();
let state_id = row.try_get::<&str, _>(1)?.unwrap().to_string();
let name = row.try_get::<&str, _>(2)?.unwrap().to_string();
Ok(County { id, state_id, name })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ConfidenceLevel {
Low = 1,
Medium = 2,
High = 3,
}
impl TryFrom<Option<u8>> for ConfidenceLevel {
type Error = crate::error::Error;
fn try_from(value: Option<u8>) -> Result<Self, Self::Error> {
match value {
Some(1) => Ok(ConfidenceLevel::Low),
Some(2) => Ok(ConfidenceLevel::Medium),
Some(3) => Ok(ConfidenceLevel::High),
x @ _ => Err(Self::Error::UnknownConfidenceLevel(format!("{:?}", x))),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Manufacturer {
pub id: i32,
pub name: String,
}
impl TryFrom<&Row> for Manufacturer {
type Error = crate::error::Error;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let id = row.try_get::<i32, _>(0)?.unwrap();
let name = row.try_get::<&str, _>(1)?.unwrap().to_string();
Ok(Manufacturer { id, name })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Project {
pub id: i32,
pub name: String,
pub num_turbines: Option<i16>,
pub capacity_mw: Option<Decimal>,
}
impl TryFrom<&Row> for Project {
type Error = crate::error::Error;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let id = row.try_get::<i32, _>(0)?.unwrap();
let name = row.try_get::<&str, _>(1)?.unwrap().to_string();
let num_turbines = row.try_get::<i16, _>(2)?;
let capacity_mw = row.try_get::<Decimal, _>(3)?;
Ok(Project {
id,
name,
num_turbines,
capacity_mw,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Model {
pub id: i32,
pub manufacturer_id: i32,
pub name: String,
pub capacity_kw: Option<i32>,
pub hub_height: Option<Decimal>,
pub rotor_diameter: Option<Decimal>,
pub rotor_swept_area: Option<Decimal>,
pub total_height_to_tip: Option<Decimal>,
}
impl TryFrom<&Row> for Model {
type Error = crate::error::Error;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let id = row.try_get::<i32, _>(0)?.unwrap();
let manufacturer_id = row.try_get::<i32, _>(1)?.unwrap();
let name = row.try_get::<&str, _>(2)?.unwrap().to_string();
let capacity_kw = row.try_get::<i32, _>(3)?;
let hub_height = row.try_get::<Decimal, _>(4)?;
let rotor_diameter = row.try_get::<Decimal, _>(5)?;
let rotor_swept_area = row.try_get::<Decimal, _>(6)?;
let total_height_to_tip = row.try_get::<Decimal, _>(7)?;
Ok(Model {
id,
manufacturer_id,
name,
capacity_kw,
hub_height,
rotor_diameter,
rotor_swept_area,
total_height_to_tip,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Turbine {
pub id: i32,
pub county_id: i32,
pub project_id: i32,
pub model_id: i32,
pub image_source_id: u8,
pub retrofit: bool,
pub retrofit_year: Option<i16>,
pub attributes_confidence_level: ConfidenceLevel,
pub location_confidence_level: ConfidenceLevel,
pub image_date: Option<NaiveDate>,
pub latitude: Decimal,
pub longitude: Decimal,
}
impl TryFrom<&Row> for Turbine {
type Error = crate::error::Error;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let id = row.try_get::<i32, _>(0)?.unwrap();
let county_id = row.try_get::<i32, _>(1)?.unwrap();
let project_id = row.try_get::<i32, _>(2)?.unwrap();
let model_id = row.try_get::<i32, _>(3)?.unwrap();
let image_source_id = row.try_get::<u8, _>(4)?.unwrap();
let retrofit = row.try_get::<bool, _>(5)?.unwrap();
let retrofit_year = row.try_get::<i16, _>(6)?;
let attributes_confidence_level = ConfidenceLevel::try_from(row.try_get::<u8, _>(7)?)?;
let location_confidence_level = ConfidenceLevel::try_from(row.try_get::<u8, _>(8)?)?;
let image_date = row.try_get::<NaiveDate, _>(9)?;
let latitude = row.try_get::<Decimal, _>(10)?.unwrap();
let longitude = row.try_get::<Decimal, _>(11)?.unwrap();
Ok(Turbine {
id,
county_id,
project_id,
model_id,
image_source_id,
retrofit,
retrofit_year,
attributes_confidence_level,
location_confidence_level,
image_date,
latitude,
longitude,
})
}
}
|
mod topography;
use nalgebra::Vector2;
use petgraph::algo::dijkstra;
use petgraph::graph::DiGraph;
use petgraph::prelude::NodeIndex;
use petgraph::Graph;
use topography::Topography;
struct Lift {
start: Vector2<u32>,
end: Vector2<u32>,
}
struct World {
topography: Topography,
lifts: Vec<Lift>,
}
struct GraphRepr {
graph: DiGraph<Vector2<i32>, u32>,
indicies: Vec<Vec<NodeIndex<u32>>>,
}
fn grid_graph(topo: &Topography, slope_function: fn(f32) -> u32) -> GraphRepr {
let mut graph = Graph::new();
let indicies: Vec<Vec<NodeIndex<u32>>> = (0..topo.dimensions.x)
.map(|i| {
(0..topo.dimensions.y)
.map(|j| graph.add_node(Vector2::new(i as i32, j as i32)))
.collect()
})
.collect();
for i in 0..topo.dimensions.x {
for j in 0..topo.dimensions.y {
let source = Vector2::new(i, j);
if i >= 1 {
let end = Vector2::new(i - 1, j);
let slope = slope_function(topo.slope(source, end));
graph.add_edge(
indicies[i as usize][j as usize],
indicies[i as usize - 1][j as usize],
slope,
);
let slope = slope_function(topo.slope(end, source));
graph.add_edge(
indicies[i as usize - 1][j as usize],
indicies[i as usize][j as usize],
slope,
);
}
if j >= 1 {
let end = Vector2::new(i, j - 1);
let slope = slope_function(topo.slope(source, end));
graph.add_edge(
indicies[i as usize][j as usize],
indicies[i as usize][j as usize - 1],
slope,
);
let slope = slope_function(topo.slope(end, source));
graph.add_edge(
indicies[i as usize][j as usize - 1],
indicies[i as usize][j as usize],
slope,
);
}
}
}
GraphRepr { graph, indicies }
}
trait DecisionTreeNode {
fn children(&self) -> Vec<Box<dyn DecisionTreeNode>>;
fn cost(&self, world: &World, position: Vector2<u32>) -> (f32, Vector2<u32>);
fn name(&self) -> String;
fn best_path(
&self,
path_length: usize,
world: &World,
position: Vector2<u32>,
) -> Vec<(f32, String)> {
if path_length == 0 {
vec![(self.cost(world, position).0, self.name())]
} else {
let mut best = vec![];
let mut best_weight = f32::MAX;
for child in self.children().iter() {
let weight = child
.best_path(path_length - 1, world, position)
.iter()
.fold(0.0, |acc, (weight, _)| acc + weight);
if weight < best_weight {
best = vec![];
let (cost, position) = self.cost(world, position);
best.push((cost, self.name()));
for c in child.best_path(path_length - 1, &world, position).iter() {
best.push(c.clone());
}
best_weight = weight;
}
}
best
}
}
}
struct Up {}
impl Up {
fn slope(x: f32) -> u32 {
if x < 0.0 {
1000000
} else {
(x * 1.0) as u32
}
}
}
impl DecisionTreeNode for Up {
fn children(&self) -> Vec<Box<dyn DecisionTreeNode>> {
vec![Box::new(Up {}), Box::new(Down {})]
}
fn cost(&self, world: &World, position: Vector2<u32>) -> (f32, Vector2<u32>) {
let g = grid_graph(&world.topography, Self::slope);
let (cost, position) = world
.lifts
.iter()
.map(|lift| {
let start = g.indicies[lift.start.x as usize][lift.start.y as usize];
let end = g.indicies[lift.end.x as usize][lift.end.y as usize];
let path = dijkstra(&g.graph, start, Some(end), |x| 1);
let cost: u32 = path.iter().map(|(_, cost)| cost).sum();
(cost, lift.end)
})
.fold(
(u32::MAX, Vector2::new(0, 0)),
|(acc_cost, acc_lift), (x_cost, x_lift)| {
if acc_cost < x_cost {
(acc_cost, acc_lift)
} else {
(x_cost, x_lift)
}
},
);
(cost as f32, position)
}
fn name(&self) -> String {
"Up".to_string()
}
}
struct Down {}
impl Down {
fn slope(x: f32) -> u32 {
if x > 0.0 {
100000
} else {
(x.abs() * 1.0) as u32
}
}
}
impl DecisionTreeNode for Down {
fn children(&self) -> Vec<Box<dyn DecisionTreeNode>> {
vec![Box::new(Up {}), Box::new(Down {})]
}
fn cost(&self, world: &World, position: Vector2<u32>) -> (f32, Vector2<u32>) {
let g = grid_graph(&world.topography, Self::slope);
let (cost, position) = world
.lifts
.iter()
.map(|lift| {
let start = g.indicies[position.x as usize][position.y as usize];
let end = g.indicies[lift.start.x as usize][lift.start.y as usize];
let path = dijkstra(&g.graph, start, Some(end), |x| x.weight().clone());
let cost: u32 = path.iter().map(|(_, cost)| cost.clone().clone()).sum();
(cost, lift.end)
})
.fold(
(u32::MAX, Vector2::new(0, 0)),
|(acc_cost, acc_lift), (x_cost, x_lift)| {
if acc_cost < x_cost {
(acc_cost, acc_lift)
} else {
(x_cost, x_lift)
}
},
);
(cost as f32, position)
}
fn name(&self) -> String {
"Down".to_string()
}
}
fn new_world() -> World {
World {
topography: Topography::cone(Vector2::new(100, 100), Vector2::new(50.0, 50.0), -1.0),
lifts: vec![Lift {
start: Vector2::new(0, 0),
end: Vector2::new(10, 10),
}],
}
}
pub fn main() {
let n: Box<dyn DecisionTreeNode> = Box::new(Up {});
for (cost, name) in n.best_path(2, &new_world(), Vector2::new(0, 0)) {
println!("{}, {}", cost, name);
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
// ignore-compare-mode-nll
// revisions: base nll
// [nll]compile-flags: -Zborrowck=mir
// Test that we give a note when the old LUB/GLB algorithm would have
// succeeded but the new code (which is stricter) gives an error.
trait Foo<T, U> {}
fn foo(x: &dyn for<'a, 'b> Foo<&'a u8, &'b u8>, y: &dyn for<'a> Foo<&'a u8, &'a u8>) {
let z = match 22 {
//[base]~^ ERROR mismatched types
0 => x,
_ => y,
//[nll]~^ ERROR mismatched types
//[nll]~| ERROR mismatched types
};
}
fn bar(x: &dyn for<'a, 'b> Foo<&'a u8, &'b u8>, y: &dyn for<'a> Foo<&'a u8, &'a u8>) {
// Accepted with explicit case:
let z = match 22 {
0 => x as &dyn for<'a> Foo<&'a u8, &'a u8>,
_ => y,
};
}
fn main() {}
|
mod dependency;
pub use dependency::Dependency;
mod lemma;
pub use lemma::Lemma;
|
fn main() {
let mut s = String::from("Hello world!");
let index = first_world(&s);
println!("The index of first world of {} is {}", s, index);
s.clear(); //no problem。直接使用下标的方式在下标返回后就和原始字符串没有关联了,在字符串清空后,index并不受影响。这样就可能造成潜在的下标越界异常。
println!("The index of first world of {} is {}", s, index);
let mut s1 = String::from("hello world");
let s1_slice = silce_first_world(&s1);
println!("s1={},s1_slice={}", s1, s1_slice);
s1.clear();
println!("s1={}", s1);
//这里清空了s1的内容,string slice与底层string的状态是绑定的,因此下面再使用s1_slice就不合法了。Rust可以在编译期就发现问题。
//println!("s1={},s1_slice={}", s1, s1_slice);
let s2 = "Hello world!";
//silce_first_world(s2); //s2类型实际上就是string slice切片类型&str
//&Str &String 通用的切面方法
let s2_slice = str_first_world(s2); //s2类型实际上就是string slice切片类型&str。所以可以直接传s2进去
println!("{}", s2_slice);
let s3 = String::from("hello hha");
let s3_slice = str_first_world(&s3[..]); //将s3作为切片传进去
println!("{}", s3_slice);
let a = [1, 2, 3, 4, 5];
let a_slice = &a[1..3]; //整数数组切片 &[i32]
}
//查找字符串的第一个单词
fn first_world(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
//接收String类型的引用.
fn silce_first_world(s: &String) -> &str {
//&str 表示string slice类型
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i]; //返回0到i的slice
}
}
&s[..]
}
fn str_first_world(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
s
}
|
mod q {
/// Blurb.
fn foo() {
}
}
fn main() {
q::foo<caret>();
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2
use crate::FutureResult;
use jsonrpc_derive::rpc;
use starcoin_types::transaction::SignedUserTransaction;
pub use self::gen_client::Client as TxPoolClient;
#[rpc]
pub trait TxPoolApi {
#[rpc(name = "txpool.submit_transaction")]
fn submit_transaction(&self, tx: SignedUserTransaction) -> FutureResult<bool>;
}
|
extern crate rustplot;
use rustplot::chart_builder;
use rustplot::chart_builder::Chart;
use rustplot::data_parser;
#[test]
fn bar_chart_tests() {
let data_1 = data_parser::get_str_col(0, 0, 5, "./resources/bar_chart_tests.csv");
let data_2 = data_parser::get_num_col(1, 0, 5, "./resources/bar_chart_tests.csv");
let bar1 = chart_builder::VerticalBarChart::new(
String::from("Test Bar Chart 1"),
data_1.clone(),
vec![data_2.clone()],
);
bar1.draw();
let data_3 = data_parser::get_str_col(2, 0, 5, "./resources/bar_chart_tests.csv");
let data_4 = data_parser::get_num_col(3, 0, 5, "./resources/bar_chart_tests.csv");
let bar2 = chart_builder::VerticalBarChart::new(
String::from("Test Bar Chart 2"),
data_3.clone(),
vec![data_4.clone()],
);
bar2.draw();
let data_5 = data_parser::get_str_col(4, 0, 5, "./resources/bar_chart_tests.csv");
let data_6 = data_parser::get_num_col(5, 0, 5, "./resources/bar_chart_tests.csv");
let bar3 = chart_builder::VerticalBarChart::new(
String::from("Test Bar Chart 3"),
data_5.clone(),
vec![data_6.clone()],
);
bar3.draw();
let data_7 = data_parser::get_num_col(6, 0, 5, "./resources/bar_chart_tests.csv");
let data_8 = data_parser::get_num_col(7, 0, 5, "./resources/bar_chart_tests.csv");
let data_9 = data_parser::get_num_col(8, 0, 5, "./resources/bar_chart_tests.csv");
let mut multi_bar_1 = chart_builder::VerticalBarChart::new(
String::from("Test Bar Chart 4"),
data_1.clone(),
vec![data_7.clone(), data_8.clone(), data_9.clone()],
);
multi_bar_1.chart_prop.set_show_legend(true);
multi_bar_1.chart_prop.set_legend_values(vec![
String::from("Location 1"),
String::from("Location 2"),
String::from("Location 3"),
]);
multi_bar_1.draw();
let data_10 = data_parser::get_num_col(9, 0, 5, "./resources/bar_chart_tests.csv");
let data_11 = data_parser::get_num_col(10, 0, 5, "./resources/bar_chart_tests.csv");
let data_12 = data_parser::get_num_col(11, 0, 5, "./resources/bar_chart_tests.csv");
let mut multi_bar_1 = chart_builder::VerticalBarChart::new(
String::from("Test Bar Chart 5"),
data_1.clone(),
vec![data_10.clone(), data_11.clone(), data_12.clone()],
);
multi_bar_1.chart_prop.set_show_legend(true);
multi_bar_1.chart_prop.set_legend_values(vec![
String::from("Location 1"),
String::from("Location 2"),
String::from("Location 3"),
]);
multi_bar_1.draw();
let mut multi_bar_3 = chart_builder::VerticalBarChart::new(
String::from("Test Bar Chart 6"),
data_1.clone(),
vec![data_2.clone(), data_4.clone(), data_6.clone()],
);
multi_bar_3.chart_prop.set_show_legend(true);
multi_bar_3.chart_prop.set_legend_values(vec![
String::from("Location 1"),
String::from("Location 2"),
String::from("Location 3"),
]);
multi_bar_3.draw();
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportDeleteImportedItemsFromSourceResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportDeleteImportedItemsFromSourceResult {
type Vtable = IPhotoImportDeleteImportedItemsFromSourceResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf4e112f8_843d_428a_a1a6_81510292b0ae);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportDeleteImportedItemsFromSourceResult_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportFindItemsResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportFindItemsResult {
type Vtable = IPhotoImportFindItemsResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3915e647_6c78_492b_844e_8fe5e8f6bfb9);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportFindItemsResult_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PhotoImportImportMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportImportMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportFindItemsResult2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportFindItemsResult2 {
type Vtable = IPhotoImportFindItemsResult2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfbdd6a3b_ecf9_406a_815e_5015625b0a88);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportFindItemsResult2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rangestart: super::super::Foundation::DateTime, rangelength: super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportImportItemsResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportImportItemsResult {
type Vtable = IPhotoImportImportItemsResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe4d4f478_d419_4443_a84e_f06a850c0b00);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportImportItemsResult_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportItem(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportItem {
type Vtable = IPhotoImportItem_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa9d07e76_9bfc_43b8_b356_633b6a988c9e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportItem_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportContentType) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportItem2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportItem2 {
type Vtable = IPhotoImportItem2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf1053505_f53b_46a3_9e30_3610791a9110);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportItem2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportItemImportedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportItemImportedEventArgs {
type Vtable = IPhotoImportItemImportedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x42cb2fdd_7d68_47b5_bc7c_ceb73e0c77dc);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportItemImportedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportManagerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportManagerStatics {
type Vtable = IPhotoImportManagerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2771903d_a046_4f06_9b9c_bfd662e83287);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportManagerStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportOperation(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportOperation {
type Vtable = IPhotoImportOperation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd9f797e4_a09a_4ee4_a4b1_20940277a5be);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportOperation_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportStage) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportSelectionChangedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportSelectionChangedEventArgs {
type Vtable = IPhotoImportSelectionChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x10461782_fa9d_4c30_8bc9_4d64911572d5);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportSelectionChangedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportSession(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportSession {
type Vtable = IPhotoImportSession_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaa63916e_ecdb_4efe_94c6_5f5cafe34cfb);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportSession_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage"))] usize,
#[cfg(feature = "Storage")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PhotoImportSubfolderCreationMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportSubfolderCreationMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, contenttypefilter: PhotoImportContentTypeFilter, itemselectionmode: PhotoImportItemSelectionMode, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportSession2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportSession2 {
type Vtable = IPhotoImportSession2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2a526710_3ec6_469d_a375_2b9f4785391e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportSession2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PhotoImportSubfolderDateFormat) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportSubfolderDateFormat) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportSidecar(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportSidecar {
type Vtable = IPhotoImportSidecar_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x46d7d757_f802_44c7_9c98_7a71f4bc1486);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportSidecar_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportSource(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportSource {
type Vtable = IPhotoImportSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f8ea35e_145b_4cd6_87f1_54965a982fef);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportSource_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportConnectionTransport) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportSourceType) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportPowerSource) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportSourceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportSourceStatics {
type Vtable = IPhotoImportSourceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0528e586_32d8_467c_8cee_23a1b2f43e85);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportSourceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sourceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sourcerootfolder: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportStorageMedium(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportStorageMedium {
type Vtable = IPhotoImportStorageMedium_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf2b9b093_fc85_487f_87c2_58d675d05b07);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportStorageMedium_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportStorageMediumType) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PhotoImportAccessMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPhotoImportVideoSegment(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPhotoImportVideoSegment {
type Vtable = IPhotoImportVideoSegment_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x623c0289_321a_41d8_9166_8c62a333276c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPhotoImportVideoSegment_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportAccessMode(pub i32);
impl PhotoImportAccessMode {
pub const ReadWrite: PhotoImportAccessMode = PhotoImportAccessMode(0i32);
pub const ReadOnly: PhotoImportAccessMode = PhotoImportAccessMode(1i32);
pub const ReadAndDelete: PhotoImportAccessMode = PhotoImportAccessMode(2i32);
}
impl ::core::convert::From<i32> for PhotoImportAccessMode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportAccessMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportAccessMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportAccessMode;i4)");
}
impl ::windows::core::DefaultType for PhotoImportAccessMode {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportConnectionTransport(pub i32);
impl PhotoImportConnectionTransport {
pub const Unknown: PhotoImportConnectionTransport = PhotoImportConnectionTransport(0i32);
pub const Usb: PhotoImportConnectionTransport = PhotoImportConnectionTransport(1i32);
pub const IP: PhotoImportConnectionTransport = PhotoImportConnectionTransport(2i32);
pub const Bluetooth: PhotoImportConnectionTransport = PhotoImportConnectionTransport(3i32);
}
impl ::core::convert::From<i32> for PhotoImportConnectionTransport {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportConnectionTransport {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportConnectionTransport {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportConnectionTransport;i4)");
}
impl ::windows::core::DefaultType for PhotoImportConnectionTransport {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportContentType(pub i32);
impl PhotoImportContentType {
pub const Unknown: PhotoImportContentType = PhotoImportContentType(0i32);
pub const Image: PhotoImportContentType = PhotoImportContentType(1i32);
pub const Video: PhotoImportContentType = PhotoImportContentType(2i32);
}
impl ::core::convert::From<i32> for PhotoImportContentType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportContentType {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportContentType {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportContentType;i4)");
}
impl ::windows::core::DefaultType for PhotoImportContentType {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportContentTypeFilter(pub i32);
impl PhotoImportContentTypeFilter {
pub const OnlyImages: PhotoImportContentTypeFilter = PhotoImportContentTypeFilter(0i32);
pub const OnlyVideos: PhotoImportContentTypeFilter = PhotoImportContentTypeFilter(1i32);
pub const ImagesAndVideos: PhotoImportContentTypeFilter = PhotoImportContentTypeFilter(2i32);
pub const ImagesAndVideosFromCameraRoll: PhotoImportContentTypeFilter = PhotoImportContentTypeFilter(3i32);
}
impl ::core::convert::From<i32> for PhotoImportContentTypeFilter {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportContentTypeFilter {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportContentTypeFilter {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportContentTypeFilter;i4)");
}
impl ::windows::core::DefaultType for PhotoImportContentTypeFilter {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportDeleteImportedItemsFromSourceResult(pub ::windows::core::IInspectable);
impl PhotoImportDeleteImportedItemsFromSourceResult {
pub fn Session(&self) -> ::windows::core::Result<PhotoImportSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSession>(result__)
}
}
pub fn HasSucceeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn DeletedItems(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportItem>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportItem>>(result__)
}
}
pub fn PhotosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn PhotosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn VideosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn VideosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SidecarsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SidecarsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SiblingsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SiblingsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn TotalCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn TotalSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportDeleteImportedItemsFromSourceResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportDeleteImportedItemsFromSourceResult;{f4e112f8-843d-428a-a1a6-81510292b0ae})");
}
unsafe impl ::windows::core::Interface for PhotoImportDeleteImportedItemsFromSourceResult {
type Vtable = IPhotoImportDeleteImportedItemsFromSourceResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf4e112f8_843d_428a_a1a6_81510292b0ae);
}
impl ::windows::core::RuntimeName for PhotoImportDeleteImportedItemsFromSourceResult {
const NAME: &'static str = "Windows.Media.Import.PhotoImportDeleteImportedItemsFromSourceResult";
}
impl ::core::convert::From<PhotoImportDeleteImportedItemsFromSourceResult> for ::windows::core::IUnknown {
fn from(value: PhotoImportDeleteImportedItemsFromSourceResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportDeleteImportedItemsFromSourceResult> for ::windows::core::IUnknown {
fn from(value: &PhotoImportDeleteImportedItemsFromSourceResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportDeleteImportedItemsFromSourceResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportDeleteImportedItemsFromSourceResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportDeleteImportedItemsFromSourceResult> for ::windows::core::IInspectable {
fn from(value: PhotoImportDeleteImportedItemsFromSourceResult) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportDeleteImportedItemsFromSourceResult> for ::windows::core::IInspectable {
fn from(value: &PhotoImportDeleteImportedItemsFromSourceResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportDeleteImportedItemsFromSourceResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportDeleteImportedItemsFromSourceResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportDeleteImportedItemsFromSourceResult {}
unsafe impl ::core::marker::Sync for PhotoImportDeleteImportedItemsFromSourceResult {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportFindItemsResult(pub ::windows::core::IInspectable);
impl PhotoImportFindItemsResult {
pub fn Session(&self) -> ::windows::core::Result<PhotoImportSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSession>(result__)
}
}
pub fn HasSucceeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn FoundItems(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportItem>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportItem>>(result__)
}
}
pub fn PhotosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn PhotosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn VideosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn VideosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SidecarsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SidecarsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SiblingsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SiblingsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn TotalCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn TotalSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SelectAll(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this)).ok() }
}
pub fn SelectNone(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn SelectNewAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
pub fn SetImportMode(&self, value: PhotoImportImportMode) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ImportMode(&self) -> ::windows::core::Result<PhotoImportImportMode> {
let this = self;
unsafe {
let mut result__: PhotoImportImportMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportImportMode>(result__)
}
}
pub fn SelectedPhotosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SelectedPhotosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SelectedVideosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SelectedVideosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SelectedSidecarsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SelectedSidecarsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SelectedSiblingsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SelectedSiblingsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SelectedTotalCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SelectedTotalSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SelectionChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PhotoImportFindItemsResult, PhotoImportSelectionChangedEventArgs>>>(&self, value: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveSelectionChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).35)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ImportItemsAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportImportItemsResult, PhotoImportProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).36)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportImportItemsResult, PhotoImportProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ItemImported<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PhotoImportFindItemsResult, PhotoImportItemImportedEventArgs>>>(&self, value: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).37)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveItemImported<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).38)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn AddItemsInDateRangeToSelection<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, rangestart: Param0, rangelength: Param1) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IPhotoImportFindItemsResult2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), rangestart.into_param().abi(), rangelength.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportFindItemsResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportFindItemsResult;{3915e647-6c78-492b-844e-8fe5e8f6bfb9})");
}
unsafe impl ::windows::core::Interface for PhotoImportFindItemsResult {
type Vtable = IPhotoImportFindItemsResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3915e647_6c78_492b_844e_8fe5e8f6bfb9);
}
impl ::windows::core::RuntimeName for PhotoImportFindItemsResult {
const NAME: &'static str = "Windows.Media.Import.PhotoImportFindItemsResult";
}
impl ::core::convert::From<PhotoImportFindItemsResult> for ::windows::core::IUnknown {
fn from(value: PhotoImportFindItemsResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportFindItemsResult> for ::windows::core::IUnknown {
fn from(value: &PhotoImportFindItemsResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportFindItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportFindItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportFindItemsResult> for ::windows::core::IInspectable {
fn from(value: PhotoImportFindItemsResult) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportFindItemsResult> for ::windows::core::IInspectable {
fn from(value: &PhotoImportFindItemsResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportFindItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportFindItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportFindItemsResult {}
unsafe impl ::core::marker::Sync for PhotoImportFindItemsResult {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportImportItemsResult(pub ::windows::core::IInspectable);
impl PhotoImportImportItemsResult {
pub fn Session(&self) -> ::windows::core::Result<PhotoImportSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSession>(result__)
}
}
pub fn HasSucceeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn ImportedItems(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportItem>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportItem>>(result__)
}
}
pub fn PhotosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn PhotosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn VideosCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn VideosSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SidecarsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SidecarsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn SiblingsCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SiblingsSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn TotalCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn TotalSizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn DeleteImportedItemsFromSourceAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportDeleteImportedItemsFromSourceResult, f64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportDeleteImportedItemsFromSourceResult, f64>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportImportItemsResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportImportItemsResult;{e4d4f478-d419-4443-a84e-f06a850c0b00})");
}
unsafe impl ::windows::core::Interface for PhotoImportImportItemsResult {
type Vtable = IPhotoImportImportItemsResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe4d4f478_d419_4443_a84e_f06a850c0b00);
}
impl ::windows::core::RuntimeName for PhotoImportImportItemsResult {
const NAME: &'static str = "Windows.Media.Import.PhotoImportImportItemsResult";
}
impl ::core::convert::From<PhotoImportImportItemsResult> for ::windows::core::IUnknown {
fn from(value: PhotoImportImportItemsResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportImportItemsResult> for ::windows::core::IUnknown {
fn from(value: &PhotoImportImportItemsResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportImportItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportImportItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportImportItemsResult> for ::windows::core::IInspectable {
fn from(value: PhotoImportImportItemsResult) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportImportItemsResult> for ::windows::core::IInspectable {
fn from(value: &PhotoImportImportItemsResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportImportItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportImportItemsResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportImportItemsResult {}
unsafe impl ::core::marker::Sync for PhotoImportImportItemsResult {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportImportMode(pub i32);
impl PhotoImportImportMode {
pub const ImportEverything: PhotoImportImportMode = PhotoImportImportMode(0i32);
pub const IgnoreSidecars: PhotoImportImportMode = PhotoImportImportMode(1i32);
pub const IgnoreSiblings: PhotoImportImportMode = PhotoImportImportMode(2i32);
pub const IgnoreSidecarsAndSiblings: PhotoImportImportMode = PhotoImportImportMode(3i32);
}
impl ::core::convert::From<i32> for PhotoImportImportMode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportImportMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportImportMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportImportMode;i4)");
}
impl ::windows::core::DefaultType for PhotoImportImportMode {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportItem(pub ::windows::core::IInspectable);
impl PhotoImportItem {
pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ItemKey(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn ContentType(&self) -> ::windows::core::Result<PhotoImportContentType> {
let this = self;
unsafe {
let mut result__: PhotoImportContentType = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportContentType>(result__)
}
}
pub fn SizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Date(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__)
}
}
pub fn Sibling(&self) -> ::windows::core::Result<PhotoImportSidecar> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSidecar>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Sidecars(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportSidecar>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportSidecar>>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn VideoSegments(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportVideoSegment>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportVideoSegment>>(result__)
}
}
pub fn IsSelected(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsSelected(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "Storage_Streams")]
pub fn Thumbnail(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStreamReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IRandomAccessStreamReference>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn ImportedFileNames(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn DeletedFileNames(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
pub fn Path(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IPhotoImportItem2>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportItem {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportItem;{a9d07e76-9bfc-43b8-b356-633b6a988c9e})");
}
unsafe impl ::windows::core::Interface for PhotoImportItem {
type Vtable = IPhotoImportItem_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa9d07e76_9bfc_43b8_b356_633b6a988c9e);
}
impl ::windows::core::RuntimeName for PhotoImportItem {
const NAME: &'static str = "Windows.Media.Import.PhotoImportItem";
}
impl ::core::convert::From<PhotoImportItem> for ::windows::core::IUnknown {
fn from(value: PhotoImportItem) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportItem> for ::windows::core::IUnknown {
fn from(value: &PhotoImportItem) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportItem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportItem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportItem> for ::windows::core::IInspectable {
fn from(value: PhotoImportItem) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportItem> for ::windows::core::IInspectable {
fn from(value: &PhotoImportItem) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportItem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportItem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportItem {}
unsafe impl ::core::marker::Sync for PhotoImportItem {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportItemImportedEventArgs(pub ::windows::core::IInspectable);
impl PhotoImportItemImportedEventArgs {
pub fn ImportedItem(&self) -> ::windows::core::Result<PhotoImportItem> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportItem>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportItemImportedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportItemImportedEventArgs;{42cb2fdd-7d68-47b5-bc7c-ceb73e0c77dc})");
}
unsafe impl ::windows::core::Interface for PhotoImportItemImportedEventArgs {
type Vtable = IPhotoImportItemImportedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x42cb2fdd_7d68_47b5_bc7c_ceb73e0c77dc);
}
impl ::windows::core::RuntimeName for PhotoImportItemImportedEventArgs {
const NAME: &'static str = "Windows.Media.Import.PhotoImportItemImportedEventArgs";
}
impl ::core::convert::From<PhotoImportItemImportedEventArgs> for ::windows::core::IUnknown {
fn from(value: PhotoImportItemImportedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportItemImportedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PhotoImportItemImportedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportItemImportedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportItemImportedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportItemImportedEventArgs> for ::windows::core::IInspectable {
fn from(value: PhotoImportItemImportedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportItemImportedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PhotoImportItemImportedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportItemImportedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportItemImportedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportItemImportedEventArgs {}
unsafe impl ::core::marker::Sync for PhotoImportItemImportedEventArgs {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportItemSelectionMode(pub i32);
impl PhotoImportItemSelectionMode {
pub const SelectAll: PhotoImportItemSelectionMode = PhotoImportItemSelectionMode(0i32);
pub const SelectNone: PhotoImportItemSelectionMode = PhotoImportItemSelectionMode(1i32);
pub const SelectNew: PhotoImportItemSelectionMode = PhotoImportItemSelectionMode(2i32);
}
impl ::core::convert::From<i32> for PhotoImportItemSelectionMode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportItemSelectionMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportItemSelectionMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportItemSelectionMode;i4)");
}
impl ::windows::core::DefaultType for PhotoImportItemSelectionMode {
type DefaultType = Self;
}
pub struct PhotoImportManager {}
impl PhotoImportManager {
#[cfg(feature = "Foundation")]
pub fn IsSupportedAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
Self::IPhotoImportManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
})
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllSourcesAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PhotoImportSource>>> {
Self::IPhotoImportManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PhotoImportSource>>>(result__)
})
}
#[cfg(feature = "Foundation_Collections")]
pub fn GetPendingOperations() -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportOperation>> {
Self::IPhotoImportManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportOperation>>(result__)
})
}
pub fn IPhotoImportManagerStatics<R, F: FnOnce(&IPhotoImportManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PhotoImportManager, IPhotoImportManagerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for PhotoImportManager {
const NAME: &'static str = "Windows.Media.Import.PhotoImportManager";
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportOperation(pub ::windows::core::IInspectable);
impl PhotoImportOperation {
pub fn Stage(&self) -> ::windows::core::Result<PhotoImportStage> {
let this = self;
unsafe {
let mut result__: PhotoImportStage = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportStage>(result__)
}
}
pub fn Session(&self) -> ::windows::core::Result<PhotoImportSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSession>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ContinueFindingItemsAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportFindItemsResult, u32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportFindItemsResult, u32>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ContinueImportingItemsAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportImportItemsResult, PhotoImportProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportImportItemsResult, PhotoImportProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ContinueDeletingImportedItemsFromSourceAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportDeleteImportedItemsFromSourceResult, f64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportDeleteImportedItemsFromSourceResult, f64>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportOperation {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportOperation;{d9f797e4-a09a-4ee4-a4b1-20940277a5be})");
}
unsafe impl ::windows::core::Interface for PhotoImportOperation {
type Vtable = IPhotoImportOperation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd9f797e4_a09a_4ee4_a4b1_20940277a5be);
}
impl ::windows::core::RuntimeName for PhotoImportOperation {
const NAME: &'static str = "Windows.Media.Import.PhotoImportOperation";
}
impl ::core::convert::From<PhotoImportOperation> for ::windows::core::IUnknown {
fn from(value: PhotoImportOperation) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportOperation> for ::windows::core::IUnknown {
fn from(value: &PhotoImportOperation) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportOperation> for ::windows::core::IInspectable {
fn from(value: PhotoImportOperation) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportOperation> for ::windows::core::IInspectable {
fn from(value: &PhotoImportOperation) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportOperation {}
unsafe impl ::core::marker::Sync for PhotoImportOperation {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportPowerSource(pub i32);
impl PhotoImportPowerSource {
pub const Unknown: PhotoImportPowerSource = PhotoImportPowerSource(0i32);
pub const Battery: PhotoImportPowerSource = PhotoImportPowerSource(1i32);
pub const External: PhotoImportPowerSource = PhotoImportPowerSource(2i32);
}
impl ::core::convert::From<i32> for PhotoImportPowerSource {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportPowerSource {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportPowerSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportPowerSource;i4)");
}
impl ::windows::core::DefaultType for PhotoImportPowerSource {
type DefaultType = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct PhotoImportProgress {
pub ItemsImported: u32,
pub TotalItemsToImport: u32,
pub BytesImported: u64,
pub TotalBytesToImport: u64,
pub ImportProgress: f64,
}
impl PhotoImportProgress {}
impl ::core::default::Default for PhotoImportProgress {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for PhotoImportProgress {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("PhotoImportProgress").field("ItemsImported", &self.ItemsImported).field("TotalItemsToImport", &self.TotalItemsToImport).field("BytesImported", &self.BytesImported).field("TotalBytesToImport", &self.TotalBytesToImport).field("ImportProgress", &self.ImportProgress).finish()
}
}
impl ::core::cmp::PartialEq for PhotoImportProgress {
fn eq(&self, other: &Self) -> bool {
self.ItemsImported == other.ItemsImported && self.TotalItemsToImport == other.TotalItemsToImport && self.BytesImported == other.BytesImported && self.TotalBytesToImport == other.TotalBytesToImport && self.ImportProgress == other.ImportProgress
}
}
impl ::core::cmp::Eq for PhotoImportProgress {}
unsafe impl ::windows::core::Abi for PhotoImportProgress {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportProgress {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Media.Import.PhotoImportProgress;u4;u4;u8;u8;f8)");
}
impl ::windows::core::DefaultType for PhotoImportProgress {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportSelectionChangedEventArgs(pub ::windows::core::IInspectable);
impl PhotoImportSelectionChangedEventArgs {
pub fn IsSelectionEmpty(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportSelectionChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportSelectionChangedEventArgs;{10461782-fa9d-4c30-8bc9-4d64911572d5})");
}
unsafe impl ::windows::core::Interface for PhotoImportSelectionChangedEventArgs {
type Vtable = IPhotoImportSelectionChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x10461782_fa9d_4c30_8bc9_4d64911572d5);
}
impl ::windows::core::RuntimeName for PhotoImportSelectionChangedEventArgs {
const NAME: &'static str = "Windows.Media.Import.PhotoImportSelectionChangedEventArgs";
}
impl ::core::convert::From<PhotoImportSelectionChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: PhotoImportSelectionChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportSelectionChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PhotoImportSelectionChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportSelectionChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportSelectionChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportSelectionChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: PhotoImportSelectionChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportSelectionChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PhotoImportSelectionChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportSelectionChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportSelectionChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportSelectionChangedEventArgs {}
unsafe impl ::core::marker::Sync for PhotoImportSelectionChangedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportSession(pub ::windows::core::IInspectable);
impl PhotoImportSession {
pub fn Source(&self) -> ::windows::core::Result<PhotoImportSource> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSource>(result__)
}
}
pub fn SessionId(&self) -> ::windows::core::Result<::windows::core::GUID> {
let this = self;
unsafe {
let mut result__: ::windows::core::GUID = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
}
#[cfg(feature = "Storage")]
pub fn SetDestinationFolder<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFolder>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Storage")]
pub fn DestinationFolder(&self) -> ::windows::core::Result<super::super::Storage::IStorageFolder> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::IStorageFolder>(result__)
}
}
pub fn SetAppendSessionDateToDestinationFolder(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AppendSessionDateToDestinationFolder(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetSubfolderCreationMode(&self, value: PhotoImportSubfolderCreationMode) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SubfolderCreationMode(&self) -> ::windows::core::Result<PhotoImportSubfolderCreationMode> {
let this = self;
unsafe {
let mut result__: PhotoImportSubfolderCreationMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSubfolderCreationMode>(result__)
}
}
pub fn SetDestinationFileNamePrefix<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn DestinationFileNamePrefix(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn FindItemsAsync(&self, contenttypefilter: PhotoImportContentTypeFilter, itemselectionmode: PhotoImportItemSelectionMode) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportFindItemsResult, u32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), contenttypefilter, itemselectionmode, &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<PhotoImportFindItemsResult, u32>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
pub fn SetSubfolderDateFormat(&self, value: PhotoImportSubfolderDateFormat) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IPhotoImportSession2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SubfolderDateFormat(&self) -> ::windows::core::Result<PhotoImportSubfolderDateFormat> {
let this = &::windows::core::Interface::cast::<IPhotoImportSession2>(self)?;
unsafe {
let mut result__: PhotoImportSubfolderDateFormat = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSubfolderDateFormat>(result__)
}
}
pub fn SetRememberDeselectedItems(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IPhotoImportSession2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn RememberDeselectedItems(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IPhotoImportSession2>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportSession {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportSession;{aa63916e-ecdb-4efe-94c6-5f5cafe34cfb})");
}
unsafe impl ::windows::core::Interface for PhotoImportSession {
type Vtable = IPhotoImportSession_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaa63916e_ecdb_4efe_94c6_5f5cafe34cfb);
}
impl ::windows::core::RuntimeName for PhotoImportSession {
const NAME: &'static str = "Windows.Media.Import.PhotoImportSession";
}
impl ::core::convert::From<PhotoImportSession> for ::windows::core::IUnknown {
fn from(value: PhotoImportSession) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportSession> for ::windows::core::IUnknown {
fn from(value: &PhotoImportSession) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportSession> for ::windows::core::IInspectable {
fn from(value: PhotoImportSession) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportSession> for ::windows::core::IInspectable {
fn from(value: &PhotoImportSession) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PhotoImportSession> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PhotoImportSession) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PhotoImportSession> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PhotoImportSession) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PhotoImportSession {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PhotoImportSession {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PhotoImportSession {}
unsafe impl ::core::marker::Sync for PhotoImportSession {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportSidecar(pub ::windows::core::IInspectable);
impl PhotoImportSidecar {
pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Date(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportSidecar {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportSidecar;{46d7d757-f802-44c7-9c98-7a71f4bc1486})");
}
unsafe impl ::windows::core::Interface for PhotoImportSidecar {
type Vtable = IPhotoImportSidecar_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x46d7d757_f802_44c7_9c98_7a71f4bc1486);
}
impl ::windows::core::RuntimeName for PhotoImportSidecar {
const NAME: &'static str = "Windows.Media.Import.PhotoImportSidecar";
}
impl ::core::convert::From<PhotoImportSidecar> for ::windows::core::IUnknown {
fn from(value: PhotoImportSidecar) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportSidecar> for ::windows::core::IUnknown {
fn from(value: &PhotoImportSidecar) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportSidecar {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportSidecar {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportSidecar> for ::windows::core::IInspectable {
fn from(value: PhotoImportSidecar) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportSidecar> for ::windows::core::IInspectable {
fn from(value: &PhotoImportSidecar) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportSidecar {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportSidecar {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportSidecar {}
unsafe impl ::core::marker::Sync for PhotoImportSidecar {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportSource(pub ::windows::core::IInspectable);
impl PhotoImportSource {
pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Description(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Manufacturer(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Model(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SerialNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ConnectionProtocol(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ConnectionTransport(&self) -> ::windows::core::Result<PhotoImportConnectionTransport> {
let this = self;
unsafe {
let mut result__: PhotoImportConnectionTransport = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportConnectionTransport>(result__)
}
}
pub fn Type(&self) -> ::windows::core::Result<PhotoImportSourceType> {
let this = self;
unsafe {
let mut result__: PhotoImportSourceType = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSourceType>(result__)
}
}
pub fn PowerSource(&self) -> ::windows::core::Result<PhotoImportPowerSource> {
let this = self;
unsafe {
let mut result__: PhotoImportPowerSource = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportPowerSource>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BatteryLevelPercent(&self) -> ::windows::core::Result<super::super::Foundation::IReference<u32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<u32>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn DateTime(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn StorageMedia(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportStorageMedium>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportStorageMedium>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn IsLocked(&self) -> ::windows::core::Result<super::super::Foundation::IReference<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<bool>>(result__)
}
}
pub fn IsMassStorage(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Storage_Streams")]
pub fn Thumbnail(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStreamReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IRandomAccessStreamReference>(result__)
}
}
pub fn CreateImportSession(&self) -> ::windows::core::Result<PhotoImportSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSession>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(sourceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PhotoImportSource>> {
Self::IPhotoImportSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), sourceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PhotoImportSource>>(result__)
})
}
#[cfg(all(feature = "Foundation", feature = "Storage"))]
pub fn FromFolderAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFolder>>(sourcerootfolder: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PhotoImportSource>> {
Self::IPhotoImportSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), sourcerootfolder.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PhotoImportSource>>(result__)
})
}
pub fn IPhotoImportSourceStatics<R, F: FnOnce(&IPhotoImportSourceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PhotoImportSource, IPhotoImportSourceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportSource;{1f8ea35e-145b-4cd6-87f1-54965a982fef})");
}
unsafe impl ::windows::core::Interface for PhotoImportSource {
type Vtable = IPhotoImportSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f8ea35e_145b_4cd6_87f1_54965a982fef);
}
impl ::windows::core::RuntimeName for PhotoImportSource {
const NAME: &'static str = "Windows.Media.Import.PhotoImportSource";
}
impl ::core::convert::From<PhotoImportSource> for ::windows::core::IUnknown {
fn from(value: PhotoImportSource) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportSource> for ::windows::core::IUnknown {
fn from(value: &PhotoImportSource) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportSource> for ::windows::core::IInspectable {
fn from(value: PhotoImportSource) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportSource> for ::windows::core::IInspectable {
fn from(value: &PhotoImportSource) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportSource {}
unsafe impl ::core::marker::Sync for PhotoImportSource {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportSourceType(pub i32);
impl PhotoImportSourceType {
pub const Generic: PhotoImportSourceType = PhotoImportSourceType(0i32);
pub const Camera: PhotoImportSourceType = PhotoImportSourceType(1i32);
pub const MediaPlayer: PhotoImportSourceType = PhotoImportSourceType(2i32);
pub const Phone: PhotoImportSourceType = PhotoImportSourceType(3i32);
pub const Video: PhotoImportSourceType = PhotoImportSourceType(4i32);
pub const PersonalInfoManager: PhotoImportSourceType = PhotoImportSourceType(5i32);
pub const AudioRecorder: PhotoImportSourceType = PhotoImportSourceType(6i32);
}
impl ::core::convert::From<i32> for PhotoImportSourceType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportSourceType {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportSourceType {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportSourceType;i4)");
}
impl ::windows::core::DefaultType for PhotoImportSourceType {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportStage(pub i32);
impl PhotoImportStage {
pub const NotStarted: PhotoImportStage = PhotoImportStage(0i32);
pub const FindingItems: PhotoImportStage = PhotoImportStage(1i32);
pub const ImportingItems: PhotoImportStage = PhotoImportStage(2i32);
pub const DeletingImportedItemsFromSource: PhotoImportStage = PhotoImportStage(3i32);
}
impl ::core::convert::From<i32> for PhotoImportStage {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportStage {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportStage {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportStage;i4)");
}
impl ::windows::core::DefaultType for PhotoImportStage {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportStorageMedium(pub ::windows::core::IInspectable);
impl PhotoImportStorageMedium {
pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Description(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SerialNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn StorageMediumType(&self) -> ::windows::core::Result<PhotoImportStorageMediumType> {
let this = self;
unsafe {
let mut result__: PhotoImportStorageMediumType = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportStorageMediumType>(result__)
}
}
pub fn SupportedAccessMode(&self) -> ::windows::core::Result<PhotoImportAccessMode> {
let this = self;
unsafe {
let mut result__: PhotoImportAccessMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportAccessMode>(result__)
}
}
pub fn CapacityInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn AvailableSpaceInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
pub fn Refresh(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportStorageMedium {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportStorageMedium;{f2b9b093-fc85-487f-87c2-58d675d05b07})");
}
unsafe impl ::windows::core::Interface for PhotoImportStorageMedium {
type Vtable = IPhotoImportStorageMedium_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf2b9b093_fc85_487f_87c2_58d675d05b07);
}
impl ::windows::core::RuntimeName for PhotoImportStorageMedium {
const NAME: &'static str = "Windows.Media.Import.PhotoImportStorageMedium";
}
impl ::core::convert::From<PhotoImportStorageMedium> for ::windows::core::IUnknown {
fn from(value: PhotoImportStorageMedium) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportStorageMedium> for ::windows::core::IUnknown {
fn from(value: &PhotoImportStorageMedium) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportStorageMedium {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportStorageMedium {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportStorageMedium> for ::windows::core::IInspectable {
fn from(value: PhotoImportStorageMedium) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportStorageMedium> for ::windows::core::IInspectable {
fn from(value: &PhotoImportStorageMedium) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportStorageMedium {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportStorageMedium {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportStorageMedium {}
unsafe impl ::core::marker::Sync for PhotoImportStorageMedium {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportStorageMediumType(pub i32);
impl PhotoImportStorageMediumType {
pub const Undefined: PhotoImportStorageMediumType = PhotoImportStorageMediumType(0i32);
pub const Fixed: PhotoImportStorageMediumType = PhotoImportStorageMediumType(1i32);
pub const Removable: PhotoImportStorageMediumType = PhotoImportStorageMediumType(2i32);
}
impl ::core::convert::From<i32> for PhotoImportStorageMediumType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportStorageMediumType {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportStorageMediumType {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportStorageMediumType;i4)");
}
impl ::windows::core::DefaultType for PhotoImportStorageMediumType {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportSubfolderCreationMode(pub i32);
impl PhotoImportSubfolderCreationMode {
pub const DoNotCreateSubfolders: PhotoImportSubfolderCreationMode = PhotoImportSubfolderCreationMode(0i32);
pub const CreateSubfoldersFromFileDate: PhotoImportSubfolderCreationMode = PhotoImportSubfolderCreationMode(1i32);
pub const CreateSubfoldersFromExifDate: PhotoImportSubfolderCreationMode = PhotoImportSubfolderCreationMode(2i32);
pub const KeepOriginalFolderStructure: PhotoImportSubfolderCreationMode = PhotoImportSubfolderCreationMode(3i32);
}
impl ::core::convert::From<i32> for PhotoImportSubfolderCreationMode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportSubfolderCreationMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportSubfolderCreationMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportSubfolderCreationMode;i4)");
}
impl ::windows::core::DefaultType for PhotoImportSubfolderCreationMode {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PhotoImportSubfolderDateFormat(pub i32);
impl PhotoImportSubfolderDateFormat {
pub const Year: PhotoImportSubfolderDateFormat = PhotoImportSubfolderDateFormat(0i32);
pub const YearMonth: PhotoImportSubfolderDateFormat = PhotoImportSubfolderDateFormat(1i32);
pub const YearMonthDay: PhotoImportSubfolderDateFormat = PhotoImportSubfolderDateFormat(2i32);
}
impl ::core::convert::From<i32> for PhotoImportSubfolderDateFormat {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PhotoImportSubfolderDateFormat {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PhotoImportSubfolderDateFormat {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Import.PhotoImportSubfolderDateFormat;i4)");
}
impl ::windows::core::DefaultType for PhotoImportSubfolderDateFormat {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PhotoImportVideoSegment(pub ::windows::core::IInspectable);
impl PhotoImportVideoSegment {
pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SizeInBytes(&self) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Date(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__)
}
}
pub fn Sibling(&self) -> ::windows::core::Result<PhotoImportSidecar> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PhotoImportSidecar>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Sidecars(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PhotoImportSidecar>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PhotoImportSidecar>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PhotoImportVideoSegment {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Import.PhotoImportVideoSegment;{623c0289-321a-41d8-9166-8c62a333276c})");
}
unsafe impl ::windows::core::Interface for PhotoImportVideoSegment {
type Vtable = IPhotoImportVideoSegment_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x623c0289_321a_41d8_9166_8c62a333276c);
}
impl ::windows::core::RuntimeName for PhotoImportVideoSegment {
const NAME: &'static str = "Windows.Media.Import.PhotoImportVideoSegment";
}
impl ::core::convert::From<PhotoImportVideoSegment> for ::windows::core::IUnknown {
fn from(value: PhotoImportVideoSegment) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PhotoImportVideoSegment> for ::windows::core::IUnknown {
fn from(value: &PhotoImportVideoSegment) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PhotoImportVideoSegment {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PhotoImportVideoSegment {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PhotoImportVideoSegment> for ::windows::core::IInspectable {
fn from(value: PhotoImportVideoSegment) -> Self {
value.0
}
}
impl ::core::convert::From<&PhotoImportVideoSegment> for ::windows::core::IInspectable {
fn from(value: &PhotoImportVideoSegment) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PhotoImportVideoSegment {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PhotoImportVideoSegment {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PhotoImportVideoSegment {}
unsafe impl ::core::marker::Sync for PhotoImportVideoSegment {}
|
mod literals;
#[doc(hidden)]
pub use literals::*;
pub type HRESULT = i32;
pub type HSTRING = *mut ::core::ffi::c_void;
pub type IUnknown = *mut ::core::ffi::c_void;
pub type IInspectable = *mut ::core::ffi::c_void;
pub type PSTR = *mut u8;
pub type PWSTR = *mut u16;
pub type PCSTR = *const u8;
pub type PCWSTR = *const u16;
pub type BSTR = *const u16;
#[repr(C)]
pub struct GUID {
pub data1: u32,
pub data2: u16,
pub data3: u16,
pub data4: [u8; 8],
}
impl ::core::marker::Copy for GUID {}
impl ::core::clone::Clone for GUID {
fn clone(&self) -> Self {
*self
}
}
impl GUID {
pub const fn from_u128(uuid: u128) -> Self {
Self { data1: (uuid >> 96) as u32, data2: (uuid >> 80 & 0xffff) as u16, data3: (uuid >> 64 & 0xffff) as u16, data4: (uuid as u64).to_be_bytes() }
}
}
|
use serde::Serialize;
use crate::application::common::http_status;
use crate::application::dtos::response_dto::{ResponseBodyDto, ResponseDto};
pub fn body_to_vec<T: Serialize>(
status_code: u16,
message: String,
serialize_body: Option<T>,
) -> Vec<u8> {
let response = ResponseBodyDto::<T> {
code: status_code,
message: message,
body: serialize_body,
};
let response_dto: Vec<u8> = match serde_json::to_vec(&response) {
Ok(res) => res,
Err(_error) => serde_json::to_vec(&ResponseBodyDto::<Option<T>> {
code: http_status::INTERNAL_SERVER_ERROR,
message: String::from("Error converting body into response"),
body: None,
})
.unwrap(),
};
response_dto
}
pub fn to_vec(status_code: u16, message: String) -> Vec<u8> {
let response = ResponseDto {
code: status_code,
message: message,
};
let response_dto: Vec<u8> = match serde_json::to_vec(&response) {
Ok(res) => res,
Err(_error) => serde_json::to_vec(&ResponseDto {
code: http_status::INTERNAL_SERVER_ERROR,
message: String::from("Error converting body into response"),
})
.unwrap(),
};
response_dto
}
|
use projecteuler::primes;
fn main() {
dbg!(solve_1(10));
//dbg!(solve_1(10_000));
dbg!(solve_2(10_000));
}
fn solve_1(n: usize) -> usize {
let mut sum = 0;
for a in 1..n {
let b = sum_divisors_1(a);
if a < b && a == sum_divisors_1(b) {
sum += a + b;
}
}
sum
}
fn sum_divisors_1(n: usize) -> usize {
let mut sum = 0;
for i in 1..n {
if n % i == 0 {
sum += i;
}
}
sum
}
fn solve_2(n: usize) -> usize {
let sieve = primes::SieveDivisor::new(n);
let mut sum = 0;
for a in 1..n {
let b = sieve.sum_of_divisors(a);
if b < a && a == sieve.sum_of_divisors(b) {
sum += a + b;
}
}
sum
}
|
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
mod primary;
mod backup;
mod start_view_change;
mod do_view_change;
mod start_view;
mod state_transfer;
mod recovery;
mod reconfiguration;
mod leaving;
mod shutdown;
mod utils;
mod common;
pub use self::primary::Primary;
pub use self::backup::Backup;
pub use self::start_view_change::StartViewChange;
pub use self::do_view_change::DoViewChange;
pub use self::start_view::StartView;
pub use self::state_transfer::StateTransfer;
pub use self::recovery::Recovery;
pub use self::reconfiguration::Reconfiguration;
pub use self::leaving::Leaving;
pub use self::shutdown::Shutdown;
|
use crate::clients::localsoup::graph::RECIPE;
use crate::clients::{Parameters, ReadRequest, VoteClient, WriteRequest};
use clap;
use failure::ResultExt;
use noria::{self, ControllerHandle, TableOperation, ZookeeperAuthority};
use tokio::prelude::*;
use tower_service::Service;
#[derive(Clone)]
pub(crate) struct Conn {
ch: ControllerHandle<ZookeeperAuthority>,
r: Option<noria::View>,
w: Option<noria::Table>,
}
impl VoteClient for Conn {
type Future = Box<dyn Future<Item = Self, Error = failure::Error> + Send>;
fn new(
_: tokio::runtime::TaskExecutor,
params: Parameters,
args: clap::ArgMatches,
) -> <Self as VoteClient>::Future {
let zk = format!(
"{}/{}",
args.value_of("zookeeper").unwrap(),
args.value_of("deployment").unwrap()
);
Box::new(
ZookeeperAuthority::new(&zk)
.into_future()
.and_then(ControllerHandle::new)
.and_then(move |mut c| {
if params.prime {
// for prepop, we need a mutator
future::Either::A(
c.install_recipe(RECIPE)
.and_then(move |_| c.table("Article").map(move |a| (c, a)))
.and_then(move |(c, a)| {
a.perform_all((0..params.articles).map(|i| {
vec![
((i + 1) as i32).into(),
format!("Article #{}", i).into(),
]
}))
.map(move |_| c)
.map_err(|e| e.error)
.then(|r| {
r.context("failed to do article prepopulation")
.map_err(Into::into)
})
}),
)
} else {
future::Either::B(future::ok(c))
}
})
.and_then(|mut c| c.table("Vote").map(move |v| (c, v)))
.and_then(|(mut c, v)| c.view("ArticleWithVoteCount").map(move |awvc| (c, v, awvc)))
.map(|(c, v, awvc)| Conn {
ch: c,
r: Some(awvc),
w: Some(v),
}),
)
}
}
impl Service<ReadRequest> for Conn {
type Response = ();
type Error = failure::Error;
type Future = Box<dyn Future<Item = (), Error = failure::Error> + Send>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.r
.as_mut()
.unwrap()
.poll_ready()
.map_err(failure::Error::from)
}
fn call(&mut self, req: ReadRequest) -> Self::Future {
let len = req.0.len();
let arg = req
.0
.into_iter()
.map(|article_id| vec![(article_id as usize).into()])
.collect();
Box::new(
self.r
.as_mut()
.unwrap()
.call((arg, true))
.map(move |rows| {
// TODO: assert_eq!(rows.map(|rows| rows.len()), Ok(1));
assert_eq!(rows.len(), len);
})
.map_err(failure::Error::from),
)
}
}
impl Service<WriteRequest> for Conn {
type Response = ();
type Error = failure::Error;
type Future = Box<dyn Future<Item = (), Error = failure::Error> + Send>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Service::<Vec<TableOperation>>::poll_ready(self.w.as_mut().unwrap())
.map_err(failure::Error::from)
}
fn call(&mut self, req: WriteRequest) -> Self::Future {
let data: Vec<TableOperation> = req
.0
.into_iter()
.map(|article_id| vec![(article_id as usize).into(), 0.into()].into())
.collect();
Box::new(
self.w
.as_mut()
.unwrap()
.call(data)
.map(|_| ())
.map_err(failure::Error::from),
)
}
}
impl Drop for Conn {
fn drop(&mut self) {
drop(self.r.take());
drop(self.w.take());
}
}
|
use clap::clap_app;
use crossbeam::{channel::unbounded, sync::WaitGroup};
use itertools::Itertools;
use num::{BigInt, BigRational, ToPrimitive};
use parking_lot::Mutex;
use std::{collections::HashMap, error::Error, sync::Arc, thread::spawn};
fn main() -> Result<(), Box<dyn Error>> {
let matches = clap_app!(first_sort_i =>
(version: "1.1")
(author: "Victor Azadinho Miranda <victorazadinho@pm.me>")
(about: "Solve E(n) as described in the 'First Sort I' coding challenge")
(@arg cache: -c "\
Sets the use of function caching to optimize linear performance (disables multi-threading)")
(@arg threads: -t +takes_value "Sets the number of threads to use (default: 1)")
(@arg VALUE: +required "Sets the value of n to solve")
)
.get_matches();
match matches.value_of("VALUE").unwrap_or("").parse::<u64>() {
Ok(n) => {
let result: f64;
if matches.is_present("cache") {
result = cache_e(n);
} else if matches.is_present("threads") {
result = par_e(
n,
matches
.value_of("threads")
.unwrap_or_default()
.parse::<usize>()
.unwrap_or(1),
);
} else {
result = e(n);
}
println!("{}", result);
Ok(())
}
Err(e) => Err(Box::new(e)),
}
}
fn cache_f(l: Vec<u64>, c: &mut HashMap<Vec<u64>, u64>) -> u64 {
match c.get(&l) {
Some(val) => *val,
None => {
if l.is_empty() {
c.insert(l, 0);
return 0;
}
if l[l.len() - 1] == l.len() as u64 {
let mut l2 = l.clone();
l2.remove(l2.len() - 1);
let r = cache_f(l2, c);
c.insert(l, r);
return r;
}
for i in 0..(l.len() - 1) {
if l[i] > l[i + 1] {
let mut l2 = l.clone();
l2.insert(0, l2[i + 1]);
l2.remove(i + 2);
let r = 1 + cache_f(l2, c);
c.insert(l, r);
return r;
}
}
0
}
}
}
fn f(mut l: Vec<u64>) -> u64 {
let mut i = 0;
let mut s = 0;
while i < l.len() - 1 {
if l[i] > l[i + 1] {
l.insert(0, l[i + 1]);
l.remove(i + 2);
s += 1;
i = 0;
} else {
i += 1;
}
}
s
}
fn par_e(n: u64, t: usize) -> f64 {
let acc = Arc::new(Mutex::new(BigInt::from(0)));
let wg = WaitGroup::new();
let (tx, rx) = unbounded::<bool>();
for (i, p) in (1..(n + 1))
.into_iter()
.permutations(n as usize)
.unique()
.enumerate()
{
if i > (t - 1) {
rx.recv().unwrap_or_default();
}
let (acc, wg, tx) = (acc.clone(), wg.clone(), tx.clone());
spawn(move || {
let r = f(p);
let mut acc = acc.lock();
*acc += r;
drop(wg);
tx.send(true).unwrap_or_default();
});
}
wg.wait();
let r = acc.lock();
BigRational::new(
r.clone(),
(1..(n + 1))
.into_iter()
.fold(BigInt::from(1), |acc, x| acc * x),
)
.to_f64()
.unwrap_or_default()
}
fn cache_e(n: u64) -> f64 {
let mut cache: HashMap<Vec<u64>, u64> = HashMap::new();
BigRational::new(
(1..(n + 1))
.into_iter()
.permutations(n as usize)
.unique()
.map(|x| cache_f((*x).iter().copied().collect(), &mut cache))
.sum(),
(1..(n + 1))
.into_iter()
.fold(BigInt::from(1), |acc, x| acc * x),
)
.to_f64()
.unwrap_or_default()
}
fn e(n: u64) -> f64 {
BigRational::new(
(1..(n + 1))
.into_iter()
.permutations(n as usize)
.unique()
.map(|x| f((*x).iter().copied().collect()))
.sum(),
(1..(n + 1))
.into_iter()
.fold(BigInt::from(1), |acc, x| acc * x),
)
.to_f64()
.unwrap_or_default()
}
|
//
// Mimic
//! A ComputerCraft emulator.
//
extern crate terminal;
extern crate jni;
extern crate serialize;
use emulator::Emulator;
use config::Config;
use error::ErrorWindow;
mod minion;
mod color;
mod emulator;
mod convert;
mod storage;
mod config;
mod error;
fn main() {
// Create the storage directory and default configuration file if needed.
storage::create();
// Load the configuration.
let potential = Config::from_file(&storage::config());
match potential {
Ok(config) => {
// Successfully loaded. Start the emulator.
let mut emulator = Emulator::new(&config);
emulator.new_minion(true, false);
emulator.run();
},
Err(message) => {
// Failed.
println!("Configuration loading failed:\n{}", message);
let mut err_window = ErrorWindow::new(&[
"Failed to load configuration.",
"Check the command line for more information.",
]);
while err_window.term.is_running() {
err_window.update();
}
}
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qpainter.h
// dst-file: /src/gui/qpainter.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::super::core::qrect::*; // 771
use super::super::core::qstring::*; // 771
use super::qtextoption::*; // 773
use super::super::core::qpoint::*; // 771
use super::qpicture::*; // 773
use super::qmatrix::*; // 773
use super::qcolor::*; // 773
use super::qpixmap::*; // 773
use super::qbrush::*; // 773
use super::qimage::*; // 773
use super::qpen::*; // 773
use super::super::core::qline::*; // 771
use super::qtransform::*; // 773
use super::qpolygon::*; // 773
use super::qstatictext::*; // 773
use super::qpainterpath::*; // 773
use super::qfont::*; // 773
use super::qregion::*; // 773
use super::qpaintdevice::*; // 773
use super::qpaintengine::*; // 773
use super::qfontmetrics::*; // 773
use super::qglyphrun::*; // 773
use super::qfontinfo::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QPainter_Class_Size() -> c_int;
// proto: QRectF QPainter::boundingRect(const QRectF & rect, const QString & text, const QTextOption & o);
fn C_ZN8QPainter12boundingRectERK6QRectFRK7QStringRK11QTextOption(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: void QPainter::drawPicture(const QPointF & p, const QPicture & picture);
fn C_ZN8QPainter11drawPictureERK7QPointFRK8QPicture(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: const QMatrix & QPainter::worldMatrix();
fn C_ZNK8QPainter11worldMatrixEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawText(const QPointF & p, const QString & str, int tf, int justificationPadding);
fn C_ZN8QPainter8drawTextERK7QPointFRK7QStringii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: c_int, arg3: c_int);
// proto: void QPainter::fillRect(int x, int y, int w, int h, const QColor & color);
fn C_ZN8QPainter8fillRectEiiiiRK6QColor(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: *mut c_void);
// proto: const QMatrix & QPainter::matrix();
fn C_ZNK8QPainter6matrixEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: qreal QPainter::opacity();
fn C_ZNK8QPainter7opacityEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QPainter::drawText(int x, int y, const QString & s);
fn C_ZN8QPainter8drawTextEiiRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void);
// proto: void QPainter::drawTiledPixmap(const QRectF & rect, const QPixmap & pm, const QPointF & offset);
fn C_ZN8QPainter15drawTiledPixmapERK6QRectFRK7QPixmapRK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: void QPainter::setBackground(const QBrush & bg);
fn C_ZN8QPainter13setBackgroundERK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QRect QPainter::boundingRect(const QRect & rect, int flags, const QString & text);
fn C_ZN8QPainter12boundingRectERK5QRectiRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: *mut c_void) -> *mut c_void;
// proto: void QPainter::drawChord(const QRectF & rect, int a, int alen);
fn C_ZN8QPainter9drawChordERK6QRectFii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::drawImage(const QRectF & r, const QImage & image);
fn C_ZN8QPainter9drawImageERK6QRectFRK6QImage(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::setClipping(bool enable);
fn C_ZN8QPainter11setClippingEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QPainter::setBrush(const QBrush & brush);
fn C_ZN8QPainter8setBrushERK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::setMatrix(const QMatrix & matrix, bool combine);
fn C_ZN8QPainter9setMatrixERK7QMatrixb(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_char);
// proto: void QPainter::drawChord(const QRect & , int a, int alen);
fn C_ZN8QPainter9drawChordERK5QRectii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::eraseRect(const QRectF & );
fn C_ZN8QPainter9eraseRectERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::translate(const QPoint & offset);
fn C_ZN8QPainter9translateERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QPainter::viewTransformEnabled();
fn C_ZNK8QPainter20viewTransformEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPainter::setPen(const QPen & pen);
fn C_ZN8QPainter6setPenERK4QPen(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawLines(const QLineF * lines, int lineCount);
fn C_ZN8QPainter9drawLinesEPK6QLineFi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::setBrushOrigin(int x, int y);
fn C_ZN8QPainter14setBrushOriginEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int);
// proto: const QTransform & QPainter::worldTransform();
fn C_ZNK8QPainter14worldTransformEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawRects(const QRect * rects, int rectCount);
fn C_ZN8QPainter9drawRectsEPK5QRecti(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::drawEllipse(const QPoint & center, int rx, int ry);
fn C_ZN8QPainter11drawEllipseERK6QPointii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::drawArc(int x, int y, int w, int h, int a, int alen);
fn C_ZN8QPainter7drawArcEiiiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: c_int, arg5: c_int);
// proto: void QPainter::drawPolyline(const QPolygonF & polyline);
fn C_ZN8QPainter12drawPolylineERK9QPolygonF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QPainter::hasClipping();
fn C_ZNK8QPainter11hasClippingEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPainter::drawPixmap(const QRectF & targetRect, const QPixmap & pixmap, const QRectF & sourceRect);
fn C_ZN8QPainter10drawPixmapERK6QRectFRK7QPixmapS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: void QPainter::drawStaticText(int left, int top, const QStaticText & staticText);
fn C_ZN8QPainter14drawStaticTextEiiRK11QStaticText(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void);
// proto: void QPainter::strokePath(const QPainterPath & path, const QPen & pen);
fn C_ZN8QPainter10strokePathERK12QPainterPathRK4QPen(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawPixmap(int x, int y, const QPixmap & pm, int sx, int sy, int sw, int sh);
fn C_ZN8QPainter10drawPixmapEiiRK7QPixmapiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void, arg3: c_int, arg4: c_int, arg5: c_int, arg6: c_int);
// proto: void QPainter::drawRects(const QRectF * rects, int rectCount);
fn C_ZN8QPainter9drawRectsEPK6QRectFi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::drawConvexPolygon(const QPoint * points, int pointCount);
fn C_ZN8QPainter17drawConvexPolygonEPK6QPointi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::drawPath(const QPainterPath & path);
fn C_ZN8QPainter8drawPathERK12QPainterPath(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawPixmap(int x, int y, const QPixmap & pm);
fn C_ZN8QPainter10drawPixmapEiiRK7QPixmap(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void);
// proto: QMatrix QPainter::combinedMatrix();
fn C_ZNK8QPainter14combinedMatrixEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::setMatrixEnabled(bool enabled);
fn C_ZN8QPainter16setMatrixEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QPainter::drawPolyline(const QPolygon & polygon);
fn C_ZN8QPainter12drawPolylineERK8QPolygon(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawTiledPixmap(const QRect & , const QPixmap & , const QPoint & );
fn C_ZN8QPainter15drawTiledPixmapERK5QRectRK7QPixmapRK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: void QPainter::setFont(const QFont & f);
fn C_ZN8QPainter7setFontERK5QFont(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawChord(int x, int y, int w, int h, int a, int alen);
fn C_ZN8QPainter9drawChordEiiiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: c_int, arg5: c_int);
// proto: void QPainter::drawPixmap(int x, int y, int w, int h, const QPixmap & pm);
fn C_ZN8QPainter10drawPixmapEiiiiRK7QPixmap(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: *mut c_void);
// proto: void QPainter::setWindow(const QRect & window);
fn C_ZN8QPainter9setWindowERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: const QMatrix & QPainter::deviceMatrix();
fn C_ZNK8QPainter12deviceMatrixEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawLines(const QPointF * pointPairs, int lineCount);
fn C_ZN8QPainter9drawLinesEPK7QPointFi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::drawPixmap(const QPointF & p, const QPixmap & pm);
fn C_ZN8QPainter10drawPixmapERK7QPointFRK7QPixmap(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: QRect QPainter::boundingRect(int x, int y, int w, int h, int flags, const QString & text);
fn C_ZN8QPainter12boundingRectEiiiiiRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: c_int, arg5: *mut c_void) -> *mut c_void;
// proto: void QPainter::drawLines(const QLine * lines, int lineCount);
fn C_ZN8QPainter9drawLinesEPK5QLinei(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::drawPie(int x, int y, int w, int h, int a, int alen);
fn C_ZN8QPainter7drawPieEiiiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: c_int, arg5: c_int);
// proto: void QPainter::drawPixmap(const QPoint & p, const QPixmap & pm, const QRect & sr);
fn C_ZN8QPainter10drawPixmapERK6QPointRK7QPixmapRK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: void QPainter::drawStaticText(const QPointF & topLeftPosition, const QStaticText & staticText);
fn C_ZN8QPainter14drawStaticTextERK7QPointFRK11QStaticText(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::setWorldMatrixEnabled(bool enabled);
fn C_ZN8QPainter21setWorldMatrixEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QPainter::drawPoints(const QPolygon & points);
fn C_ZN8QPainter10drawPointsERK8QPolygon(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawPicture(const QPoint & p, const QPicture & picture);
fn C_ZN8QPainter11drawPictureERK6QPointRK8QPicture(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawRect(int x1, int y1, int w, int h);
fn C_ZN8QPainter8drawRectEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: void QPainter::drawEllipse(const QRectF & r);
fn C_ZN8QPainter11drawEllipseERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawRect(const QRectF & rect);
fn C_ZN8QPainter8drawRectERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawPoints(const QPointF * points, int pointCount);
fn C_ZN8QPainter10drawPointsEPK7QPointFi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: QRegion QPainter::clipRegion();
fn C_ZNK8QPainter10clipRegionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawText(const QRectF & r, int flags, const QString & text, QRectF * br);
fn C_ZN8QPainter8drawTextERK6QRectFiRK7QStringPS0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: *mut c_void, arg3: *mut c_void);
// proto: void QPainter::drawLine(const QLineF & line);
fn C_ZN8QPainter8drawLineERK6QLineF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawLine(const QPointF & p1, const QPointF & p2);
fn C_ZN8QPainter8drawLineERK7QPointFS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawPixmap(const QRect & r, const QPixmap & pm);
fn C_ZN8QPainter10drawPixmapERK5QRectRK7QPixmap(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawTiledPixmap(int x, int y, int w, int h, const QPixmap & , int sx, int sy);
fn C_ZN8QPainter15drawTiledPixmapEiiiiRK7QPixmapii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: *mut c_void, arg5: c_int, arg6: c_int);
// proto: QPaintDevice * QPainter::device();
fn C_ZNK8QPainter6deviceEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::setViewport(const QRect & viewport);
fn C_ZN8QPainter11setViewportERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::fillRect(const QRect & , const QColor & color);
fn C_ZN8QPainter8fillRectERK5QRectRK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::setBrushOrigin(const QPointF & );
fn C_ZN8QPainter14setBrushOriginERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawTextItem(int x, int y, const QTextItem & ti);
fn C_ZN8QPainter12drawTextItemEiiRK9QTextItem(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void);
// proto: void QPainter::QPainter(QPaintDevice * );
fn C_ZN8QPainterC2EP12QPaintDevice(arg0: *mut c_void) -> u64;
// proto: void QPainter::drawPixmap(int x, int y, int w, int h, const QPixmap & pm, int sx, int sy, int sw, int sh);
fn C_ZN8QPainter10drawPixmapEiiiiRK7QPixmapiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: *mut c_void, arg5: c_int, arg6: c_int, arg7: c_int, arg8: c_int);
// proto: void QPainter::drawImage(const QPoint & p, const QImage & image);
fn C_ZN8QPainter9drawImageERK6QPointRK6QImage(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawPie(const QRect & , int a, int alen);
fn C_ZN8QPainter7drawPieERK5QRectii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::drawTextItem(const QPoint & p, const QTextItem & ti);
fn C_ZN8QPainter12drawTextItemERK6QPointRK9QTextItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawLines(const QPoint * pointPairs, int lineCount);
fn C_ZN8QPainter9drawLinesEPK6QPointi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::drawPicture(int x, int y, const QPicture & picture);
fn C_ZN8QPainter11drawPictureEiiRK8QPicture(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void);
// proto: void QPainter::save();
fn C_ZN8QPainter4saveEv(qthis: u64 /* *mut c_void*/);
// proto: void QPainter::translate(qreal dx, qreal dy);
fn C_ZN8QPainter9translateEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double);
// proto: QTransform QPainter::combinedTransform();
fn C_ZNK8QPainter17combinedTransformEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QPainter::end();
fn C_ZN8QPainter3endEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPainter::setViewport(int x, int y, int w, int h);
fn C_ZN8QPainter11setViewportEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: void QPainter::drawRoundRect(const QRect & r, int xround, int yround);
fn C_ZN8QPainter13drawRoundRectERK5QRectii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::setWorldTransform(const QTransform & matrix, bool combine);
fn C_ZN8QPainter17setWorldTransformERK10QTransformb(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_char);
// proto: void QPainter::drawPoints(const QPolygonF & points);
fn C_ZN8QPainter10drawPointsERK9QPolygonF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::restore();
fn C_ZN8QPainter7restoreEv(qthis: u64 /* *mut c_void*/);
// proto: void QPainter::drawStaticText(const QPoint & topLeftPosition, const QStaticText & staticText);
fn C_ZN8QPainter14drawStaticTextERK6QPointRK11QStaticText(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: QRectF QPainter::boundingRect(const QRectF & rect, int flags, const QString & text);
fn C_ZN8QPainter12boundingRectERK6QRectFiRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: *mut c_void) -> *mut c_void;
// proto: void QPainter::fillRect(int x, int y, int w, int h, const QBrush & );
fn C_ZN8QPainter8fillRectEiiiiRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: *mut c_void);
// proto: void QPainter::drawRoundRect(const QRectF & r, int xround, int yround);
fn C_ZN8QPainter13drawRoundRectERK6QRectFii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::drawPoint(const QPoint & p);
fn C_ZN8QPainter9drawPointERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static QPaintDevice * QPainter::redirected(const QPaintDevice * device, QPoint * offset);
fn C_ZN8QPainter10redirectedEPK12QPaintDeviceP6QPoint(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QPainter::shear(qreal sh, qreal sv);
fn C_ZN8QPainter5shearEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double);
// proto: void QPainter::drawText(const QRect & r, int flags, const QString & text, QRect * br);
fn C_ZN8QPainter8drawTextERK5QRectiRK7QStringPS0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: *mut c_void, arg3: *mut c_void);
// proto: const QFont & QPainter::font();
fn C_ZNK8QPainter4fontEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const QTransform & QPainter::deviceTransform();
fn C_ZNK8QPainter15deviceTransformEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::eraseRect(int x, int y, int w, int h);
fn C_ZN8QPainter9eraseRectEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: void QPainter::resetMatrix();
fn C_ZN8QPainter11resetMatrixEv(qthis: u64 /* *mut c_void*/);
// proto: void QPainter::drawPolyline(const QPoint * points, int pointCount);
fn C_ZN8QPainter12drawPolylineEPK6QPointi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: QPaintEngine * QPainter::paintEngine();
fn C_ZNK8QPainter11paintEngineEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawEllipse(const QRect & r);
fn C_ZN8QPainter11drawEllipseERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawLine(const QLine & line);
fn C_ZN8QPainter8drawLineERK5QLine(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QPainter::isActive();
fn C_ZNK8QPainter8isActiveEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPainter::drawArc(const QRectF & rect, int a, int alen);
fn C_ZN8QPainter7drawArcERK6QRectFii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: static void QPainter::restoreRedirected(const QPaintDevice * device);
fn C_ZN8QPainter17restoreRedirectedEPK12QPaintDevice(arg0: *mut c_void);
// proto: void QPainter::drawPixmap(const QPointF & p, const QPixmap & pm, const QRectF & sr);
fn C_ZN8QPainter10drawPixmapERK7QPointFRK7QPixmapRK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: void QPainter::drawEllipse(const QPointF & center, qreal rx, qreal ry);
fn C_ZN8QPainter11drawEllipseERK7QPointFdd(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_double, arg2: c_double);
// proto: void QPainter::drawConvexPolygon(const QPointF * points, int pointCount);
fn C_ZN8QPainter17drawConvexPolygonEPK7QPointFi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::setBrushOrigin(const QPoint & );
fn C_ZN8QPainter14setBrushOriginERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawText(const QRectF & r, const QString & text, const QTextOption & o);
fn C_ZN8QPainter8drawTextERK6QRectFRK7QStringRK11QTextOption(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: bool QPainter::worldMatrixEnabled();
fn C_ZNK8QPainter18worldMatrixEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPainter::drawPixmap(const QPoint & p, const QPixmap & pm);
fn C_ZN8QPainter10drawPixmapERK6QPointRK7QPixmap(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawLine(int x1, int y1, int x2, int y2);
fn C_ZN8QPainter8drawLineEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: void QPainter::drawPoint(int x, int y);
fn C_ZN8QPainter9drawPointEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int);
// proto: const QTransform & QPainter::transform();
fn C_ZNK8QPainter9transformEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static void QPainter::setRedirected(const QPaintDevice * device, QPaintDevice * replacement, const QPoint & offset);
fn C_ZN8QPainter13setRedirectedEPK12QPaintDevicePS0_RK6QPoint(arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: void QPainter::drawPixmap(const QRect & targetRect, const QPixmap & pixmap, const QRect & sourceRect);
fn C_ZN8QPainter10drawPixmapERK5QRectRK7QPixmapS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: QFontMetrics QPainter::fontMetrics();
fn C_ZNK8QPainter11fontMetricsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawGlyphRun(const QPointF & position, const QGlyphRun & glyphRun);
fn C_ZN8QPainter12drawGlyphRunERK7QPointFRK9QGlyphRun(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::fillRect(const QRectF & , const QBrush & );
fn C_ZN8QPainter8fillRectERK6QRectFRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::resetTransform();
fn C_ZN8QPainter14resetTransformEv(qthis: u64 /* *mut c_void*/);
// proto: void QPainter::fillRect(const QRect & , const QBrush & );
fn C_ZN8QPainter8fillRectERK5QRectRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: const QBrush & QPainter::brush();
fn C_ZNK8QPainter5brushEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::~QPainter();
fn C_ZN8QPainterD2Ev(qthis: u64 /* *mut c_void*/);
// proto: bool QPainter::begin(QPaintDevice * );
fn C_ZN8QPainter5beginEP12QPaintDevice(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: void QPainter::drawRect(const QRect & rect);
fn C_ZN8QPainter8drawRectERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawTextItem(const QPointF & p, const QTextItem & ti);
fn C_ZN8QPainter12drawTextItemERK7QPointFRK9QTextItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::scale(qreal sx, qreal sy);
fn C_ZN8QPainter5scaleEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double);
// proto: void QPainter::setWorldMatrix(const QMatrix & matrix, bool combine);
fn C_ZN8QPainter14setWorldMatrixERK7QMatrixb(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_char);
// proto: QPainterPath QPainter::clipPath();
fn C_ZNK8QPainter8clipPathEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QPoint QPainter::brushOrigin();
fn C_ZNK8QPainter11brushOriginEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawConvexPolygon(const QPolygonF & polygon);
fn C_ZN8QPainter17drawConvexPolygonERK9QPolygonF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawEllipse(int x, int y, int w, int h);
fn C_ZN8QPainter11drawEllipseEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: void QPainter::drawConvexPolygon(const QPolygon & polygon);
fn C_ZN8QPainter17drawConvexPolygonERK8QPolygon(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawPoints(const QPoint * points, int pointCount);
fn C_ZN8QPainter10drawPointsEPK6QPointi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: const QBrush & QPainter::background();
fn C_ZNK8QPainter10backgroundEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawRoundRect(int x, int y, int w, int h, int , int );
fn C_ZN8QPainter13drawRoundRectEiiiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: c_int, arg5: c_int);
// proto: QRect QPainter::viewport();
fn C_ZNK8QPainter8viewportEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawArc(const QRect & , int a, int alen);
fn C_ZN8QPainter7drawArcERK5QRectii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::fillPath(const QPainterPath & path, const QBrush & brush);
fn C_ZN8QPainter8fillPathERK12QPainterPathRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawText(int x, int y, int w, int h, int flags, const QString & text, QRect * br);
fn C_ZN8QPainter8drawTextEiiiiiRK7QStringP5QRect(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int, arg4: c_int, arg5: *mut c_void, arg6: *mut c_void);
// proto: bool QPainter::matrixEnabled();
fn C_ZNK8QPainter13matrixEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPainter::drawPolyline(const QPointF * points, int pointCount);
fn C_ZN8QPainter12drawPolylineEPK7QPointFi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int);
// proto: void QPainter::setTransform(const QTransform & transform, bool combine);
fn C_ZN8QPainter12setTransformERK10QTransformb(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_char);
// proto: void QPainter::setPen(const QColor & color);
fn C_ZN8QPainter6setPenERK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::eraseRect(const QRect & );
fn C_ZN8QPainter9eraseRectERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QRect QPainter::window();
fn C_ZNK8QPainter6windowEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawImage(const QRect & r, const QImage & image);
fn C_ZN8QPainter9drawImageERK5QRectRK6QImage(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::initFrom(const QPaintDevice * device);
fn C_ZN8QPainter8initFromEPK12QPaintDevice(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QFontInfo QPainter::fontInfo();
fn C_ZNK8QPainter8fontInfoEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::endNativePainting();
fn C_ZN8QPainter17endNativePaintingEv(qthis: u64 /* *mut c_void*/);
// proto: void QPainter::setViewTransformEnabled(bool enable);
fn C_ZN8QPainter23setViewTransformEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QPainter::drawPoint(const QPointF & pt);
fn C_ZN8QPainter9drawPointERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::setOpacity(qreal opacity);
fn C_ZN8QPainter10setOpacityEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QPainter::fillRect(const QRectF & , const QColor & color);
fn C_ZN8QPainter8fillRectERK6QRectFRK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::QPainter();
fn C_ZN8QPainterC2Ev() -> u64;
// proto: void QPainter::translate(const QPointF & offset);
fn C_ZN8QPainter9translateERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QPainter::drawText(const QPointF & p, const QString & s);
fn C_ZN8QPainter8drawTextERK7QPointFRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawImage(const QPointF & p, const QImage & image);
fn C_ZN8QPainter9drawImageERK7QPointFRK6QImage(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: const QPen & QPainter::pen();
fn C_ZNK8QPainter3penEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::rotate(qreal a);
fn C_ZN8QPainter6rotateEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: QRectF QPainter::clipBoundingRect();
fn C_ZNK8QPainter16clipBoundingRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPainter::drawLine(const QPoint & p1, const QPoint & p2);
fn C_ZN8QPainter8drawLineERK6QPointS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::drawPie(const QRectF & rect, int a, int alen);
fn C_ZN8QPainter7drawPieERK6QRectFii(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int, arg2: c_int);
// proto: void QPainter::drawText(const QPoint & p, const QString & s);
fn C_ZN8QPainter8drawTextERK6QPointRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QPainter::setWindow(int x, int y, int w, int h);
fn C_ZN8QPainter9setWindowEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: void QPainter::beginNativePainting();
fn C_ZN8QPainter19beginNativePaintingEv(qthis: u64 /* *mut c_void*/);
} // <= ext block end
// body block begin =>
// class sizeof(QPainter)=1
#[derive(Default)]
pub struct QPainter {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QPainter {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QPainter {
return QPainter{qclsinst: qthis, ..Default::default()};
}
}
// proto: QRectF QPainter::boundingRect(const QRectF & rect, const QString & text, const QTextOption & o);
impl /*struct*/ QPainter {
pub fn boundingRect<RetType, T: QPainter_boundingRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.boundingRect(self);
// return 1;
}
}
pub trait QPainter_boundingRect<RetType> {
fn boundingRect(self , rsthis: & QPainter) -> RetType;
}
// proto: QRectF QPainter::boundingRect(const QRectF & rect, const QString & text, const QTextOption & o);
impl<'a> /*trait*/ QPainter_boundingRect<QRectF> for (&'a QRectF, &'a QString, Option<&'a QTextOption>) {
fn boundingRect(self , rsthis: & QPainter) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12boundingRectERK6QRectFRK7QStringRK11QTextOption()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = (if self.2.is_none() {QTextOption::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN8QPainter12boundingRectERK6QRectFRK7QStringRK11QTextOption(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawPicture(const QPointF & p, const QPicture & picture);
impl /*struct*/ QPainter {
pub fn drawPicture<RetType, T: QPainter_drawPicture<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawPicture(self);
// return 1;
}
}
pub trait QPainter_drawPicture<RetType> {
fn drawPicture(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawPicture(const QPointF & p, const QPicture & picture);
impl<'a> /*trait*/ QPainter_drawPicture<()> for (&'a QPointF, &'a QPicture) {
fn drawPicture(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawPictureERK7QPointFRK8QPicture()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter11drawPictureERK7QPointFRK8QPicture(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QMatrix & QPainter::worldMatrix();
impl /*struct*/ QPainter {
pub fn worldMatrix<RetType, T: QPainter_worldMatrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.worldMatrix(self);
// return 1;
}
}
pub trait QPainter_worldMatrix<RetType> {
fn worldMatrix(self , rsthis: & QPainter) -> RetType;
}
// proto: const QMatrix & QPainter::worldMatrix();
impl<'a> /*trait*/ QPainter_worldMatrix<QMatrix> for () {
fn worldMatrix(self , rsthis: & QPainter) -> QMatrix {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter11worldMatrixEv()};
let mut ret = unsafe {C_ZNK8QPainter11worldMatrixEv(rsthis.qclsinst)};
let mut ret1 = QMatrix::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawText(const QPointF & p, const QString & str, int tf, int justificationPadding);
impl /*struct*/ QPainter {
pub fn drawText<RetType, T: QPainter_drawText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawText(self);
// return 1;
}
}
pub trait QPainter_drawText<RetType> {
fn drawText(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawText(const QPointF & p, const QString & str, int tf, int justificationPadding);
impl<'a> /*trait*/ QPainter_drawText<()> for (&'a QPointF, &'a QString, i32, i32) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextERK7QPointFRK7QStringii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN8QPainter8drawTextERK7QPointFRK7QStringii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::fillRect(int x, int y, int w, int h, const QColor & color);
impl /*struct*/ QPainter {
pub fn fillRect<RetType, T: QPainter_fillRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.fillRect(self);
// return 1;
}
}
pub trait QPainter_fillRect<RetType> {
fn fillRect(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::fillRect(int x, int y, int w, int h, const QColor & color);
impl<'a> /*trait*/ QPainter_fillRect<()> for (i32, i32, i32, i32, &'a QColor) {
fn fillRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8fillRectEiiiiRK6QColor()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8fillRectEiiiiRK6QColor(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4)};
// return 1;
}
}
// proto: const QMatrix & QPainter::matrix();
impl /*struct*/ QPainter {
pub fn matrix<RetType, T: QPainter_matrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.matrix(self);
// return 1;
}
}
pub trait QPainter_matrix<RetType> {
fn matrix(self , rsthis: & QPainter) -> RetType;
}
// proto: const QMatrix & QPainter::matrix();
impl<'a> /*trait*/ QPainter_matrix<QMatrix> for () {
fn matrix(self , rsthis: & QPainter) -> QMatrix {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter6matrixEv()};
let mut ret = unsafe {C_ZNK8QPainter6matrixEv(rsthis.qclsinst)};
let mut ret1 = QMatrix::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QPainter::opacity();
impl /*struct*/ QPainter {
pub fn opacity<RetType, T: QPainter_opacity<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.opacity(self);
// return 1;
}
}
pub trait QPainter_opacity<RetType> {
fn opacity(self , rsthis: & QPainter) -> RetType;
}
// proto: qreal QPainter::opacity();
impl<'a> /*trait*/ QPainter_opacity<f64> for () {
fn opacity(self , rsthis: & QPainter) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter7opacityEv()};
let mut ret = unsafe {C_ZNK8QPainter7opacityEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QPainter::drawText(int x, int y, const QString & s);
impl<'a> /*trait*/ QPainter_drawText<()> for (i32, i32, &'a QString) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextEiiRK7QString()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawTextEiiRK7QString(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawTiledPixmap(const QRectF & rect, const QPixmap & pm, const QPointF & offset);
impl /*struct*/ QPainter {
pub fn drawTiledPixmap<RetType, T: QPainter_drawTiledPixmap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawTiledPixmap(self);
// return 1;
}
}
pub trait QPainter_drawTiledPixmap<RetType> {
fn drawTiledPixmap(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawTiledPixmap(const QRectF & rect, const QPixmap & pm, const QPointF & offset);
impl<'a> /*trait*/ QPainter_drawTiledPixmap<()> for (&'a QRectF, &'a QPixmap, Option<&'a QPointF>) {
fn drawTiledPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter15drawTiledPixmapERK6QRectFRK7QPixmapRK7QPointF()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = (if self.2.is_none() {QPointF::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN8QPainter15drawTiledPixmapERK6QRectFRK7QPixmapRK7QPointF(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::setBackground(const QBrush & bg);
impl /*struct*/ QPainter {
pub fn setBackground<RetType, T: QPainter_setBackground<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBackground(self);
// return 1;
}
}
pub trait QPainter_setBackground<RetType> {
fn setBackground(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setBackground(const QBrush & bg);
impl<'a> /*trait*/ QPainter_setBackground<()> for (&'a QBrush) {
fn setBackground(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter13setBackgroundERK6QBrush()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter13setBackgroundERK6QBrush(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QRect QPainter::boundingRect(const QRect & rect, int flags, const QString & text);
impl<'a> /*trait*/ QPainter_boundingRect<QRect> for (&'a QRect, i32, &'a QString) {
fn boundingRect(self , rsthis: & QPainter) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12boundingRectERK5QRectiRK7QString()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN8QPainter12boundingRectERK5QRectiRK7QString(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawChord(const QRectF & rect, int a, int alen);
impl /*struct*/ QPainter {
pub fn drawChord<RetType, T: QPainter_drawChord<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawChord(self);
// return 1;
}
}
pub trait QPainter_drawChord<RetType> {
fn drawChord(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawChord(const QRectF & rect, int a, int alen);
impl<'a> /*trait*/ QPainter_drawChord<()> for (&'a QRectF, i32, i32) {
fn drawChord(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawChordERK6QRectFii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
unsafe {C_ZN8QPainter9drawChordERK6QRectFii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawImage(const QRectF & r, const QImage & image);
impl /*struct*/ QPainter {
pub fn drawImage<RetType, T: QPainter_drawImage<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawImage(self);
// return 1;
}
}
pub trait QPainter_drawImage<RetType> {
fn drawImage(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawImage(const QRectF & r, const QImage & image);
impl<'a> /*trait*/ QPainter_drawImage<()> for (&'a QRectF, &'a QImage) {
fn drawImage(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawImageERK6QRectFRK6QImage()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9drawImageERK6QRectFRK6QImage(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setClipping(bool enable);
impl /*struct*/ QPainter {
pub fn setClipping<RetType, T: QPainter_setClipping<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setClipping(self);
// return 1;
}
}
pub trait QPainter_setClipping<RetType> {
fn setClipping(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setClipping(bool enable);
impl<'a> /*trait*/ QPainter_setClipping<()> for (i8) {
fn setClipping(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11setClippingEb()};
let arg0 = self as c_char;
unsafe {C_ZN8QPainter11setClippingEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::setBrush(const QBrush & brush);
impl /*struct*/ QPainter {
pub fn setBrush<RetType, T: QPainter_setBrush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBrush(self);
// return 1;
}
}
pub trait QPainter_setBrush<RetType> {
fn setBrush(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setBrush(const QBrush & brush);
impl<'a> /*trait*/ QPainter_setBrush<()> for (&'a QBrush) {
fn setBrush(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8setBrushERK6QBrush()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8setBrushERK6QBrush(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::setMatrix(const QMatrix & matrix, bool combine);
impl /*struct*/ QPainter {
pub fn setMatrix<RetType, T: QPainter_setMatrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMatrix(self);
// return 1;
}
}
pub trait QPainter_setMatrix<RetType> {
fn setMatrix(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setMatrix(const QMatrix & matrix, bool combine);
impl<'a> /*trait*/ QPainter_setMatrix<()> for (&'a QMatrix, Option<i8>) {
fn setMatrix(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9setMatrixERK7QMatrixb()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {false as i8} else {self.1.unwrap()}) as c_char;
unsafe {C_ZN8QPainter9setMatrixERK7QMatrixb(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawChord(const QRect & , int a, int alen);
impl<'a> /*trait*/ QPainter_drawChord<()> for (&'a QRect, i32, i32) {
fn drawChord(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawChordERK5QRectii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
unsafe {C_ZN8QPainter9drawChordERK5QRectii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::eraseRect(const QRectF & );
impl /*struct*/ QPainter {
pub fn eraseRect<RetType, T: QPainter_eraseRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.eraseRect(self);
// return 1;
}
}
pub trait QPainter_eraseRect<RetType> {
fn eraseRect(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::eraseRect(const QRectF & );
impl<'a> /*trait*/ QPainter_eraseRect<()> for (&'a QRectF) {
fn eraseRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9eraseRectERK6QRectF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9eraseRectERK6QRectF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::translate(const QPoint & offset);
impl /*struct*/ QPainter {
pub fn translate<RetType, T: QPainter_translate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.translate(self);
// return 1;
}
}
pub trait QPainter_translate<RetType> {
fn translate(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::translate(const QPoint & offset);
impl<'a> /*trait*/ QPainter_translate<()> for (&'a QPoint) {
fn translate(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9translateERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9translateERK6QPoint(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QPainter::viewTransformEnabled();
impl /*struct*/ QPainter {
pub fn viewTransformEnabled<RetType, T: QPainter_viewTransformEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.viewTransformEnabled(self);
// return 1;
}
}
pub trait QPainter_viewTransformEnabled<RetType> {
fn viewTransformEnabled(self , rsthis: & QPainter) -> RetType;
}
// proto: bool QPainter::viewTransformEnabled();
impl<'a> /*trait*/ QPainter_viewTransformEnabled<i8> for () {
fn viewTransformEnabled(self , rsthis: & QPainter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter20viewTransformEnabledEv()};
let mut ret = unsafe {C_ZNK8QPainter20viewTransformEnabledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPainter::setPen(const QPen & pen);
impl /*struct*/ QPainter {
pub fn setPen<RetType, T: QPainter_setPen<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPen(self);
// return 1;
}
}
pub trait QPainter_setPen<RetType> {
fn setPen(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setPen(const QPen & pen);
impl<'a> /*trait*/ QPainter_setPen<()> for (&'a QPen) {
fn setPen(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter6setPenERK4QPen()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter6setPenERK4QPen(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawLines(const QLineF * lines, int lineCount);
impl /*struct*/ QPainter {
pub fn drawLines<RetType, T: QPainter_drawLines<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawLines(self);
// return 1;
}
}
pub trait QPainter_drawLines<RetType> {
fn drawLines(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawLines(const QLineF * lines, int lineCount);
impl<'a> /*trait*/ QPainter_drawLines<()> for (&'a QLineF, i32) {
fn drawLines(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawLinesEPK6QLineFi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter9drawLinesEPK6QLineFi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setBrushOrigin(int x, int y);
impl /*struct*/ QPainter {
pub fn setBrushOrigin<RetType, T: QPainter_setBrushOrigin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBrushOrigin(self);
// return 1;
}
}
pub trait QPainter_setBrushOrigin<RetType> {
fn setBrushOrigin(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setBrushOrigin(int x, int y);
impl<'a> /*trait*/ QPainter_setBrushOrigin<()> for (i32, i32) {
fn setBrushOrigin(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14setBrushOriginEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter14setBrushOriginEii(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QTransform & QPainter::worldTransform();
impl /*struct*/ QPainter {
pub fn worldTransform<RetType, T: QPainter_worldTransform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.worldTransform(self);
// return 1;
}
}
pub trait QPainter_worldTransform<RetType> {
fn worldTransform(self , rsthis: & QPainter) -> RetType;
}
// proto: const QTransform & QPainter::worldTransform();
impl<'a> /*trait*/ QPainter_worldTransform<QTransform> for () {
fn worldTransform(self , rsthis: & QPainter) -> QTransform {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter14worldTransformEv()};
let mut ret = unsafe {C_ZNK8QPainter14worldTransformEv(rsthis.qclsinst)};
let mut ret1 = QTransform::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawRects(const QRect * rects, int rectCount);
impl /*struct*/ QPainter {
pub fn drawRects<RetType, T: QPainter_drawRects<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawRects(self);
// return 1;
}
}
pub trait QPainter_drawRects<RetType> {
fn drawRects(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawRects(const QRect * rects, int rectCount);
impl<'a> /*trait*/ QPainter_drawRects<()> for (&'a QRect, i32) {
fn drawRects(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawRectsEPK5QRecti()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter9drawRectsEPK5QRecti(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawEllipse(const QPoint & center, int rx, int ry);
impl /*struct*/ QPainter {
pub fn drawEllipse<RetType, T: QPainter_drawEllipse<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawEllipse(self);
// return 1;
}
}
pub trait QPainter_drawEllipse<RetType> {
fn drawEllipse(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawEllipse(const QPoint & center, int rx, int ry);
impl<'a> /*trait*/ QPainter_drawEllipse<()> for (&'a QPoint, i32, i32) {
fn drawEllipse(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawEllipseERK6QPointii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
unsafe {C_ZN8QPainter11drawEllipseERK6QPointii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawArc(int x, int y, int w, int h, int a, int alen);
impl /*struct*/ QPainter {
pub fn drawArc<RetType, T: QPainter_drawArc<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawArc(self);
// return 1;
}
}
pub trait QPainter_drawArc<RetType> {
fn drawArc(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawArc(int x, int y, int w, int h, int a, int alen);
impl<'a> /*trait*/ QPainter_drawArc<()> for (i32, i32, i32, i32, i32, i32) {
fn drawArc(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7drawArcEiiiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4 as c_int;
let arg5 = self.5 as c_int;
unsafe {C_ZN8QPainter7drawArcEiiiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)};
// return 1;
}
}
// proto: void QPainter::drawPolyline(const QPolygonF & polyline);
impl /*struct*/ QPainter {
pub fn drawPolyline<RetType, T: QPainter_drawPolyline<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawPolyline(self);
// return 1;
}
}
pub trait QPainter_drawPolyline<RetType> {
fn drawPolyline(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawPolyline(const QPolygonF & polyline);
impl<'a> /*trait*/ QPainter_drawPolyline<()> for (&'a QPolygonF) {
fn drawPolyline(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawPolylineERK9QPolygonF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter12drawPolylineERK9QPolygonF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QPainter::hasClipping();
impl /*struct*/ QPainter {
pub fn hasClipping<RetType, T: QPainter_hasClipping<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasClipping(self);
// return 1;
}
}
pub trait QPainter_hasClipping<RetType> {
fn hasClipping(self , rsthis: & QPainter) -> RetType;
}
// proto: bool QPainter::hasClipping();
impl<'a> /*trait*/ QPainter_hasClipping<i8> for () {
fn hasClipping(self , rsthis: & QPainter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter11hasClippingEv()};
let mut ret = unsafe {C_ZNK8QPainter11hasClippingEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPainter::drawPixmap(const QRectF & targetRect, const QPixmap & pixmap, const QRectF & sourceRect);
impl /*struct*/ QPainter {
pub fn drawPixmap<RetType, T: QPainter_drawPixmap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawPixmap(self);
// return 1;
}
}
pub trait QPainter_drawPixmap<RetType> {
fn drawPixmap(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawPixmap(const QRectF & targetRect, const QPixmap & pixmap, const QRectF & sourceRect);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (&'a QRectF, &'a QPixmap, &'a QRectF) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapERK6QRectFRK7QPixmapS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapERK6QRectFRK7QPixmapS2_(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawStaticText(int left, int top, const QStaticText & staticText);
impl /*struct*/ QPainter {
pub fn drawStaticText<RetType, T: QPainter_drawStaticText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawStaticText(self);
// return 1;
}
}
pub trait QPainter_drawStaticText<RetType> {
fn drawStaticText(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawStaticText(int left, int top, const QStaticText & staticText);
impl<'a> /*trait*/ QPainter_drawStaticText<()> for (i32, i32, &'a QStaticText) {
fn drawStaticText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14drawStaticTextEiiRK11QStaticText()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter14drawStaticTextEiiRK11QStaticText(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::strokePath(const QPainterPath & path, const QPen & pen);
impl /*struct*/ QPainter {
pub fn strokePath<RetType, T: QPainter_strokePath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.strokePath(self);
// return 1;
}
}
pub trait QPainter_strokePath<RetType> {
fn strokePath(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::strokePath(const QPainterPath & path, const QPen & pen);
impl<'a> /*trait*/ QPainter_strokePath<()> for (&'a QPainterPath, &'a QPen) {
fn strokePath(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10strokePathERK12QPainterPathRK4QPen()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10strokePathERK12QPainterPathRK4QPen(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(int x, int y, const QPixmap & pm, int sx, int sy, int sw, int sh);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (i32, i32, &'a QPixmap, i32, i32, i32, i32) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapEiiRK7QPixmapiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
let arg3 = self.3 as c_int;
let arg4 = self.4 as c_int;
let arg5 = self.5 as c_int;
let arg6 = self.6 as c_int;
unsafe {C_ZN8QPainter10drawPixmapEiiRK7QPixmapiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5, arg6)};
// return 1;
}
}
// proto: void QPainter::drawRects(const QRectF * rects, int rectCount);
impl<'a> /*trait*/ QPainter_drawRects<()> for (&'a QRectF, i32) {
fn drawRects(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawRectsEPK6QRectFi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter9drawRectsEPK6QRectFi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawConvexPolygon(const QPoint * points, int pointCount);
impl /*struct*/ QPainter {
pub fn drawConvexPolygon<RetType, T: QPainter_drawConvexPolygon<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawConvexPolygon(self);
// return 1;
}
}
pub trait QPainter_drawConvexPolygon<RetType> {
fn drawConvexPolygon(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawConvexPolygon(const QPoint * points, int pointCount);
impl<'a> /*trait*/ QPainter_drawConvexPolygon<()> for (&'a QPoint, i32) {
fn drawConvexPolygon(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter17drawConvexPolygonEPK6QPointi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter17drawConvexPolygonEPK6QPointi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPath(const QPainterPath & path);
impl /*struct*/ QPainter {
pub fn drawPath<RetType, T: QPainter_drawPath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawPath(self);
// return 1;
}
}
pub trait QPainter_drawPath<RetType> {
fn drawPath(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawPath(const QPainterPath & path);
impl<'a> /*trait*/ QPainter_drawPath<()> for (&'a QPainterPath) {
fn drawPath(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawPathERK12QPainterPath()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawPathERK12QPainterPath(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(int x, int y, const QPixmap & pm);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (i32, i32, &'a QPixmap) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapEiiRK7QPixmap()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapEiiRK7QPixmap(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: QMatrix QPainter::combinedMatrix();
impl /*struct*/ QPainter {
pub fn combinedMatrix<RetType, T: QPainter_combinedMatrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.combinedMatrix(self);
// return 1;
}
}
pub trait QPainter_combinedMatrix<RetType> {
fn combinedMatrix(self , rsthis: & QPainter) -> RetType;
}
// proto: QMatrix QPainter::combinedMatrix();
impl<'a> /*trait*/ QPainter_combinedMatrix<QMatrix> for () {
fn combinedMatrix(self , rsthis: & QPainter) -> QMatrix {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter14combinedMatrixEv()};
let mut ret = unsafe {C_ZNK8QPainter14combinedMatrixEv(rsthis.qclsinst)};
let mut ret1 = QMatrix::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::setMatrixEnabled(bool enabled);
impl /*struct*/ QPainter {
pub fn setMatrixEnabled<RetType, T: QPainter_setMatrixEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMatrixEnabled(self);
// return 1;
}
}
pub trait QPainter_setMatrixEnabled<RetType> {
fn setMatrixEnabled(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setMatrixEnabled(bool enabled);
impl<'a> /*trait*/ QPainter_setMatrixEnabled<()> for (i8) {
fn setMatrixEnabled(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter16setMatrixEnabledEb()};
let arg0 = self as c_char;
unsafe {C_ZN8QPainter16setMatrixEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawPolyline(const QPolygon & polygon);
impl<'a> /*trait*/ QPainter_drawPolyline<()> for (&'a QPolygon) {
fn drawPolyline(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawPolylineERK8QPolygon()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter12drawPolylineERK8QPolygon(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawTiledPixmap(const QRect & , const QPixmap & , const QPoint & );
impl<'a> /*trait*/ QPainter_drawTiledPixmap<()> for (&'a QRect, &'a QPixmap, Option<&'a QPoint>) {
fn drawTiledPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter15drawTiledPixmapERK5QRectRK7QPixmapRK6QPoint()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = (if self.2.is_none() {QPoint::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN8QPainter15drawTiledPixmapERK5QRectRK7QPixmapRK6QPoint(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::setFont(const QFont & f);
impl /*struct*/ QPainter {
pub fn setFont<RetType, T: QPainter_setFont<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setFont(self);
// return 1;
}
}
pub trait QPainter_setFont<RetType> {
fn setFont(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setFont(const QFont & f);
impl<'a> /*trait*/ QPainter_setFont<()> for (&'a QFont) {
fn setFont(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7setFontERK5QFont()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter7setFontERK5QFont(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawChord(int x, int y, int w, int h, int a, int alen);
impl<'a> /*trait*/ QPainter_drawChord<()> for (i32, i32, i32, i32, i32, i32) {
fn drawChord(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawChordEiiiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4 as c_int;
let arg5 = self.5 as c_int;
unsafe {C_ZN8QPainter9drawChordEiiiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(int x, int y, int w, int h, const QPixmap & pm);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (i32, i32, i32, i32, &'a QPixmap) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapEiiiiRK7QPixmap()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapEiiiiRK7QPixmap(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4)};
// return 1;
}
}
// proto: void QPainter::setWindow(const QRect & window);
impl /*struct*/ QPainter {
pub fn setWindow<RetType, T: QPainter_setWindow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWindow(self);
// return 1;
}
}
pub trait QPainter_setWindow<RetType> {
fn setWindow(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setWindow(const QRect & window);
impl<'a> /*trait*/ QPainter_setWindow<()> for (&'a QRect) {
fn setWindow(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9setWindowERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9setWindowERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: const QMatrix & QPainter::deviceMatrix();
impl /*struct*/ QPainter {
pub fn deviceMatrix<RetType, T: QPainter_deviceMatrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.deviceMatrix(self);
// return 1;
}
}
pub trait QPainter_deviceMatrix<RetType> {
fn deviceMatrix(self , rsthis: & QPainter) -> RetType;
}
// proto: const QMatrix & QPainter::deviceMatrix();
impl<'a> /*trait*/ QPainter_deviceMatrix<QMatrix> for () {
fn deviceMatrix(self , rsthis: & QPainter) -> QMatrix {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter12deviceMatrixEv()};
let mut ret = unsafe {C_ZNK8QPainter12deviceMatrixEv(rsthis.qclsinst)};
let mut ret1 = QMatrix::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawLines(const QPointF * pointPairs, int lineCount);
impl<'a> /*trait*/ QPainter_drawLines<()> for (&'a QPointF, i32) {
fn drawLines(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawLinesEPK7QPointFi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter9drawLinesEPK7QPointFi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(const QPointF & p, const QPixmap & pm);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (&'a QPointF, &'a QPixmap) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapERK7QPointFRK7QPixmap()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapERK7QPointFRK7QPixmap(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QRect QPainter::boundingRect(int x, int y, int w, int h, int flags, const QString & text);
impl<'a> /*trait*/ QPainter_boundingRect<QRect> for (i32, i32, i32, i32, i32, &'a QString) {
fn boundingRect(self , rsthis: & QPainter) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12boundingRectEiiiiiRK7QString()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4 as c_int;
let arg5 = self.5.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN8QPainter12boundingRectEiiiiiRK7QString(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawLines(const QLine * lines, int lineCount);
impl<'a> /*trait*/ QPainter_drawLines<()> for (&'a QLine, i32) {
fn drawLines(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawLinesEPK5QLinei()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter9drawLinesEPK5QLinei(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPie(int x, int y, int w, int h, int a, int alen);
impl /*struct*/ QPainter {
pub fn drawPie<RetType, T: QPainter_drawPie<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawPie(self);
// return 1;
}
}
pub trait QPainter_drawPie<RetType> {
fn drawPie(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawPie(int x, int y, int w, int h, int a, int alen);
impl<'a> /*trait*/ QPainter_drawPie<()> for (i32, i32, i32, i32, i32, i32) {
fn drawPie(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7drawPieEiiiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4 as c_int;
let arg5 = self.5 as c_int;
unsafe {C_ZN8QPainter7drawPieEiiiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(const QPoint & p, const QPixmap & pm, const QRect & sr);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (&'a QPoint, &'a QPixmap, &'a QRect) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapERK6QPointRK7QPixmapRK5QRect()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapERK6QPointRK7QPixmapRK5QRect(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawStaticText(const QPointF & topLeftPosition, const QStaticText & staticText);
impl<'a> /*trait*/ QPainter_drawStaticText<()> for (&'a QPointF, &'a QStaticText) {
fn drawStaticText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14drawStaticTextERK7QPointFRK11QStaticText()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter14drawStaticTextERK7QPointFRK11QStaticText(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setWorldMatrixEnabled(bool enabled);
impl /*struct*/ QPainter {
pub fn setWorldMatrixEnabled<RetType, T: QPainter_setWorldMatrixEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWorldMatrixEnabled(self);
// return 1;
}
}
pub trait QPainter_setWorldMatrixEnabled<RetType> {
fn setWorldMatrixEnabled(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setWorldMatrixEnabled(bool enabled);
impl<'a> /*trait*/ QPainter_setWorldMatrixEnabled<()> for (i8) {
fn setWorldMatrixEnabled(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter21setWorldMatrixEnabledEb()};
let arg0 = self as c_char;
unsafe {C_ZN8QPainter21setWorldMatrixEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawPoints(const QPolygon & points);
impl /*struct*/ QPainter {
pub fn drawPoints<RetType, T: QPainter_drawPoints<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawPoints(self);
// return 1;
}
}
pub trait QPainter_drawPoints<RetType> {
fn drawPoints(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawPoints(const QPolygon & points);
impl<'a> /*trait*/ QPainter_drawPoints<()> for (&'a QPolygon) {
fn drawPoints(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPointsERK8QPolygon()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPointsERK8QPolygon(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawPicture(const QPoint & p, const QPicture & picture);
impl<'a> /*trait*/ QPainter_drawPicture<()> for (&'a QPoint, &'a QPicture) {
fn drawPicture(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawPictureERK6QPointRK8QPicture()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter11drawPictureERK6QPointRK8QPicture(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawRect(int x1, int y1, int w, int h);
impl /*struct*/ QPainter {
pub fn drawRect<RetType, T: QPainter_drawRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawRect(self);
// return 1;
}
}
pub trait QPainter_drawRect<RetType> {
fn drawRect(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawRect(int x1, int y1, int w, int h);
impl<'a> /*trait*/ QPainter_drawRect<()> for (i32, i32, i32, i32) {
fn drawRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawRectEiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN8QPainter8drawRectEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::drawEllipse(const QRectF & r);
impl<'a> /*trait*/ QPainter_drawEllipse<()> for (&'a QRectF) {
fn drawEllipse(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawEllipseERK6QRectF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter11drawEllipseERK6QRectF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawRect(const QRectF & rect);
impl<'a> /*trait*/ QPainter_drawRect<()> for (&'a QRectF) {
fn drawRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawRectERK6QRectF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawRectERK6QRectF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawPoints(const QPointF * points, int pointCount);
impl<'a> /*trait*/ QPainter_drawPoints<()> for (&'a QPointF, i32) {
fn drawPoints(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPointsEPK7QPointFi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter10drawPointsEPK7QPointFi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QRegion QPainter::clipRegion();
impl /*struct*/ QPainter {
pub fn clipRegion<RetType, T: QPainter_clipRegion<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clipRegion(self);
// return 1;
}
}
pub trait QPainter_clipRegion<RetType> {
fn clipRegion(self , rsthis: & QPainter) -> RetType;
}
// proto: QRegion QPainter::clipRegion();
impl<'a> /*trait*/ QPainter_clipRegion<QRegion> for () {
fn clipRegion(self , rsthis: & QPainter) -> QRegion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter10clipRegionEv()};
let mut ret = unsafe {C_ZNK8QPainter10clipRegionEv(rsthis.qclsinst)};
let mut ret1 = QRegion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawText(const QRectF & r, int flags, const QString & text, QRectF * br);
impl<'a> /*trait*/ QPainter_drawText<()> for (&'a QRectF, i32, &'a QString, Option<&'a QRectF>) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextERK6QRectFiRK7QStringPS0_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
let arg3 = (if self.3.is_none() {0} else {self.3.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN8QPainter8drawTextERK6QRectFiRK7QStringPS0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::drawLine(const QLineF & line);
impl /*struct*/ QPainter {
pub fn drawLine<RetType, T: QPainter_drawLine<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawLine(self);
// return 1;
}
}
pub trait QPainter_drawLine<RetType> {
fn drawLine(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawLine(const QLineF & line);
impl<'a> /*trait*/ QPainter_drawLine<()> for (&'a QLineF) {
fn drawLine(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawLineERK6QLineF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawLineERK6QLineF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawLine(const QPointF & p1, const QPointF & p2);
impl<'a> /*trait*/ QPainter_drawLine<()> for (&'a QPointF, &'a QPointF) {
fn drawLine(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawLineERK7QPointFS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawLineERK7QPointFS2_(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(const QRect & r, const QPixmap & pm);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (&'a QRect, &'a QPixmap) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapERK5QRectRK7QPixmap()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapERK5QRectRK7QPixmap(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawTiledPixmap(int x, int y, int w, int h, const QPixmap & , int sx, int sy);
impl<'a> /*trait*/ QPainter_drawTiledPixmap<()> for (i32, i32, i32, i32, &'a QPixmap, Option<i32>, Option<i32>) {
fn drawTiledPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter15drawTiledPixmapEiiiiRK7QPixmapii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4.qclsinst as *mut c_void;
let arg5 = (if self.5.is_none() {0} else {self.5.unwrap()}) as c_int;
let arg6 = (if self.6.is_none() {0} else {self.6.unwrap()}) as c_int;
unsafe {C_ZN8QPainter15drawTiledPixmapEiiiiRK7QPixmapii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5, arg6)};
// return 1;
}
}
// proto: QPaintDevice * QPainter::device();
impl /*struct*/ QPainter {
pub fn device<RetType, T: QPainter_device<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.device(self);
// return 1;
}
}
pub trait QPainter_device<RetType> {
fn device(self , rsthis: & QPainter) -> RetType;
}
// proto: QPaintDevice * QPainter::device();
impl<'a> /*trait*/ QPainter_device<QPaintDevice> for () {
fn device(self , rsthis: & QPainter) -> QPaintDevice {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter6deviceEv()};
let mut ret = unsafe {C_ZNK8QPainter6deviceEv(rsthis.qclsinst)};
let mut ret1 = QPaintDevice::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::setViewport(const QRect & viewport);
impl /*struct*/ QPainter {
pub fn setViewport<RetType, T: QPainter_setViewport<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setViewport(self);
// return 1;
}
}
pub trait QPainter_setViewport<RetType> {
fn setViewport(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setViewport(const QRect & viewport);
impl<'a> /*trait*/ QPainter_setViewport<()> for (&'a QRect) {
fn setViewport(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11setViewportERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter11setViewportERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::fillRect(const QRect & , const QColor & color);
impl<'a> /*trait*/ QPainter_fillRect<()> for (&'a QRect, &'a QColor) {
fn fillRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8fillRectERK5QRectRK6QColor()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8fillRectERK5QRectRK6QColor(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setBrushOrigin(const QPointF & );
impl<'a> /*trait*/ QPainter_setBrushOrigin<()> for (&'a QPointF) {
fn setBrushOrigin(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14setBrushOriginERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter14setBrushOriginERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawTextItem(int x, int y, const QTextItem & ti);
impl /*struct*/ QPainter {
pub fn drawTextItem<RetType, T: QPainter_drawTextItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawTextItem(self);
// return 1;
}
}
pub trait QPainter_drawTextItem<RetType> {
fn drawTextItem(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawTextItem(int x, int y, const QTextItem & ti);
impl<'a> /*trait*/ QPainter_drawTextItem<()> for (i32, i32, &'a QTextItem) {
fn drawTextItem(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawTextItemEiiRK9QTextItem()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter12drawTextItemEiiRK9QTextItem(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::QPainter(QPaintDevice * );
impl /*struct*/ QPainter {
pub fn new<T: QPainter_new>(value: T) -> QPainter {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QPainter_new {
fn new(self) -> QPainter;
}
// proto: void QPainter::QPainter(QPaintDevice * );
impl<'a> /*trait*/ QPainter_new for (&'a QPaintDevice) {
fn new(self) -> QPainter {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainterC2EP12QPaintDevice()};
let ctysz: c_int = unsafe{QPainter_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_ZN8QPainterC2EP12QPaintDevice(arg0)};
let rsthis = QPainter{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QPainter::drawPixmap(int x, int y, int w, int h, const QPixmap & pm, int sx, int sy, int sw, int sh);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (i32, i32, i32, i32, &'a QPixmap, i32, i32, i32, i32) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapEiiiiRK7QPixmapiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4.qclsinst as *mut c_void;
let arg5 = self.5 as c_int;
let arg6 = self.6 as c_int;
let arg7 = self.7 as c_int;
let arg8 = self.8 as c_int;
unsafe {C_ZN8QPainter10drawPixmapEiiiiRK7QPixmapiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)};
// return 1;
}
}
// proto: void QPainter::drawImage(const QPoint & p, const QImage & image);
impl<'a> /*trait*/ QPainter_drawImage<()> for (&'a QPoint, &'a QImage) {
fn drawImage(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawImageERK6QPointRK6QImage()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9drawImageERK6QPointRK6QImage(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPie(const QRect & , int a, int alen);
impl<'a> /*trait*/ QPainter_drawPie<()> for (&'a QRect, i32, i32) {
fn drawPie(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7drawPieERK5QRectii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
unsafe {C_ZN8QPainter7drawPieERK5QRectii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawTextItem(const QPoint & p, const QTextItem & ti);
impl<'a> /*trait*/ QPainter_drawTextItem<()> for (&'a QPoint, &'a QTextItem) {
fn drawTextItem(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawTextItemERK6QPointRK9QTextItem()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter12drawTextItemERK6QPointRK9QTextItem(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawLines(const QPoint * pointPairs, int lineCount);
impl<'a> /*trait*/ QPainter_drawLines<()> for (&'a QPoint, i32) {
fn drawLines(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawLinesEPK6QPointi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter9drawLinesEPK6QPointi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPicture(int x, int y, const QPicture & picture);
impl<'a> /*trait*/ QPainter_drawPicture<()> for (i32, i32, &'a QPicture) {
fn drawPicture(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawPictureEiiRK8QPicture()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter11drawPictureEiiRK8QPicture(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::save();
impl /*struct*/ QPainter {
pub fn save<RetType, T: QPainter_save<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.save(self);
// return 1;
}
}
pub trait QPainter_save<RetType> {
fn save(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::save();
impl<'a> /*trait*/ QPainter_save<()> for () {
fn save(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter4saveEv()};
unsafe {C_ZN8QPainter4saveEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QPainter::translate(qreal dx, qreal dy);
impl<'a> /*trait*/ QPainter_translate<()> for (f64, f64) {
fn translate(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9translateEdd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
unsafe {C_ZN8QPainter9translateEdd(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QTransform QPainter::combinedTransform();
impl /*struct*/ QPainter {
pub fn combinedTransform<RetType, T: QPainter_combinedTransform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.combinedTransform(self);
// return 1;
}
}
pub trait QPainter_combinedTransform<RetType> {
fn combinedTransform(self , rsthis: & QPainter) -> RetType;
}
// proto: QTransform QPainter::combinedTransform();
impl<'a> /*trait*/ QPainter_combinedTransform<QTransform> for () {
fn combinedTransform(self , rsthis: & QPainter) -> QTransform {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter17combinedTransformEv()};
let mut ret = unsafe {C_ZNK8QPainter17combinedTransformEv(rsthis.qclsinst)};
let mut ret1 = QTransform::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QPainter::end();
impl /*struct*/ QPainter {
pub fn end<RetType, T: QPainter_end<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.end(self);
// return 1;
}
}
pub trait QPainter_end<RetType> {
fn end(self , rsthis: & QPainter) -> RetType;
}
// proto: bool QPainter::end();
impl<'a> /*trait*/ QPainter_end<i8> for () {
fn end(self , rsthis: & QPainter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter3endEv()};
let mut ret = unsafe {C_ZN8QPainter3endEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPainter::setViewport(int x, int y, int w, int h);
impl<'a> /*trait*/ QPainter_setViewport<()> for (i32, i32, i32, i32) {
fn setViewport(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11setViewportEiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN8QPainter11setViewportEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::drawRoundRect(const QRect & r, int xround, int yround);
impl /*struct*/ QPainter {
pub fn drawRoundRect<RetType, T: QPainter_drawRoundRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawRoundRect(self);
// return 1;
}
}
pub trait QPainter_drawRoundRect<RetType> {
fn drawRoundRect(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawRoundRect(const QRect & r, int xround, int yround);
impl<'a> /*trait*/ QPainter_drawRoundRect<()> for (&'a QRect, Option<i32>, Option<i32>) {
fn drawRoundRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter13drawRoundRectERK5QRectii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {25} else {self.1.unwrap()}) as c_int;
let arg2 = (if self.2.is_none() {25} else {self.2.unwrap()}) as c_int;
unsafe {C_ZN8QPainter13drawRoundRectERK5QRectii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::setWorldTransform(const QTransform & matrix, bool combine);
impl /*struct*/ QPainter {
pub fn setWorldTransform<RetType, T: QPainter_setWorldTransform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWorldTransform(self);
// return 1;
}
}
pub trait QPainter_setWorldTransform<RetType> {
fn setWorldTransform(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setWorldTransform(const QTransform & matrix, bool combine);
impl<'a> /*trait*/ QPainter_setWorldTransform<()> for (&'a QTransform, Option<i8>) {
fn setWorldTransform(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter17setWorldTransformERK10QTransformb()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {false as i8} else {self.1.unwrap()}) as c_char;
unsafe {C_ZN8QPainter17setWorldTransformERK10QTransformb(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPoints(const QPolygonF & points);
impl<'a> /*trait*/ QPainter_drawPoints<()> for (&'a QPolygonF) {
fn drawPoints(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPointsERK9QPolygonF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPointsERK9QPolygonF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::restore();
impl /*struct*/ QPainter {
pub fn restore<RetType, T: QPainter_restore<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.restore(self);
// return 1;
}
}
pub trait QPainter_restore<RetType> {
fn restore(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::restore();
impl<'a> /*trait*/ QPainter_restore<()> for () {
fn restore(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7restoreEv()};
unsafe {C_ZN8QPainter7restoreEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QPainter::drawStaticText(const QPoint & topLeftPosition, const QStaticText & staticText);
impl<'a> /*trait*/ QPainter_drawStaticText<()> for (&'a QPoint, &'a QStaticText) {
fn drawStaticText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14drawStaticTextERK6QPointRK11QStaticText()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter14drawStaticTextERK6QPointRK11QStaticText(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QRectF QPainter::boundingRect(const QRectF & rect, int flags, const QString & text);
impl<'a> /*trait*/ QPainter_boundingRect<QRectF> for (&'a QRectF, i32, &'a QString) {
fn boundingRect(self , rsthis: & QPainter) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12boundingRectERK6QRectFiRK7QString()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN8QPainter12boundingRectERK6QRectFiRK7QString(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::fillRect(int x, int y, int w, int h, const QBrush & );
impl<'a> /*trait*/ QPainter_fillRect<()> for (i32, i32, i32, i32, &'a QBrush) {
fn fillRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8fillRectEiiiiRK6QBrush()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8fillRectEiiiiRK6QBrush(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4)};
// return 1;
}
}
// proto: void QPainter::drawRoundRect(const QRectF & r, int xround, int yround);
impl<'a> /*trait*/ QPainter_drawRoundRect<()> for (&'a QRectF, Option<i32>, Option<i32>) {
fn drawRoundRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter13drawRoundRectERK6QRectFii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {25} else {self.1.unwrap()}) as c_int;
let arg2 = (if self.2.is_none() {25} else {self.2.unwrap()}) as c_int;
unsafe {C_ZN8QPainter13drawRoundRectERK6QRectFii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawPoint(const QPoint & p);
impl /*struct*/ QPainter {
pub fn drawPoint<RetType, T: QPainter_drawPoint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawPoint(self);
// return 1;
}
}
pub trait QPainter_drawPoint<RetType> {
fn drawPoint(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawPoint(const QPoint & p);
impl<'a> /*trait*/ QPainter_drawPoint<()> for (&'a QPoint) {
fn drawPoint(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawPointERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9drawPointERK6QPoint(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static QPaintDevice * QPainter::redirected(const QPaintDevice * device, QPoint * offset);
impl /*struct*/ QPainter {
pub fn redirected_s<RetType, T: QPainter_redirected_s<RetType>>( overload_args: T) -> RetType {
return overload_args.redirected_s();
// return 1;
}
}
pub trait QPainter_redirected_s<RetType> {
fn redirected_s(self ) -> RetType;
}
// proto: static QPaintDevice * QPainter::redirected(const QPaintDevice * device, QPoint * offset);
impl<'a> /*trait*/ QPainter_redirected_s<QPaintDevice> for (&'a QPaintDevice, Option<&'a QPoint>) {
fn redirected_s(self ) -> QPaintDevice {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10redirectedEPK12QPaintDeviceP6QPoint()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN8QPainter10redirectedEPK12QPaintDeviceP6QPoint(arg0, arg1)};
let mut ret1 = QPaintDevice::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::shear(qreal sh, qreal sv);
impl /*struct*/ QPainter {
pub fn shear<RetType, T: QPainter_shear<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.shear(self);
// return 1;
}
}
pub trait QPainter_shear<RetType> {
fn shear(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::shear(qreal sh, qreal sv);
impl<'a> /*trait*/ QPainter_shear<()> for (f64, f64) {
fn shear(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter5shearEdd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
unsafe {C_ZN8QPainter5shearEdd(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawText(const QRect & r, int flags, const QString & text, QRect * br);
impl<'a> /*trait*/ QPainter_drawText<()> for (&'a QRect, i32, &'a QString, Option<&'a QRect>) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextERK5QRectiRK7QStringPS0_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
let arg3 = (if self.3.is_none() {0} else {self.3.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN8QPainter8drawTextERK5QRectiRK7QStringPS0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: const QFont & QPainter::font();
impl /*struct*/ QPainter {
pub fn font<RetType, T: QPainter_font<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.font(self);
// return 1;
}
}
pub trait QPainter_font<RetType> {
fn font(self , rsthis: & QPainter) -> RetType;
}
// proto: const QFont & QPainter::font();
impl<'a> /*trait*/ QPainter_font<QFont> for () {
fn font(self , rsthis: & QPainter) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter4fontEv()};
let mut ret = unsafe {C_ZNK8QPainter4fontEv(rsthis.qclsinst)};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QTransform & QPainter::deviceTransform();
impl /*struct*/ QPainter {
pub fn deviceTransform<RetType, T: QPainter_deviceTransform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.deviceTransform(self);
// return 1;
}
}
pub trait QPainter_deviceTransform<RetType> {
fn deviceTransform(self , rsthis: & QPainter) -> RetType;
}
// proto: const QTransform & QPainter::deviceTransform();
impl<'a> /*trait*/ QPainter_deviceTransform<QTransform> for () {
fn deviceTransform(self , rsthis: & QPainter) -> QTransform {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter15deviceTransformEv()};
let mut ret = unsafe {C_ZNK8QPainter15deviceTransformEv(rsthis.qclsinst)};
let mut ret1 = QTransform::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::eraseRect(int x, int y, int w, int h);
impl<'a> /*trait*/ QPainter_eraseRect<()> for (i32, i32, i32, i32) {
fn eraseRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9eraseRectEiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN8QPainter9eraseRectEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::resetMatrix();
impl /*struct*/ QPainter {
pub fn resetMatrix<RetType, T: QPainter_resetMatrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resetMatrix(self);
// return 1;
}
}
pub trait QPainter_resetMatrix<RetType> {
fn resetMatrix(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::resetMatrix();
impl<'a> /*trait*/ QPainter_resetMatrix<()> for () {
fn resetMatrix(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11resetMatrixEv()};
unsafe {C_ZN8QPainter11resetMatrixEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QPainter::drawPolyline(const QPoint * points, int pointCount);
impl<'a> /*trait*/ QPainter_drawPolyline<()> for (&'a QPoint, i32) {
fn drawPolyline(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawPolylineEPK6QPointi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter12drawPolylineEPK6QPointi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QPaintEngine * QPainter::paintEngine();
impl /*struct*/ QPainter {
pub fn paintEngine<RetType, T: QPainter_paintEngine<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.paintEngine(self);
// return 1;
}
}
pub trait QPainter_paintEngine<RetType> {
fn paintEngine(self , rsthis: & QPainter) -> RetType;
}
// proto: QPaintEngine * QPainter::paintEngine();
impl<'a> /*trait*/ QPainter_paintEngine<QPaintEngine> for () {
fn paintEngine(self , rsthis: & QPainter) -> QPaintEngine {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter11paintEngineEv()};
let mut ret = unsafe {C_ZNK8QPainter11paintEngineEv(rsthis.qclsinst)};
let mut ret1 = QPaintEngine::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawEllipse(const QRect & r);
impl<'a> /*trait*/ QPainter_drawEllipse<()> for (&'a QRect) {
fn drawEllipse(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawEllipseERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter11drawEllipseERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawLine(const QLine & line);
impl<'a> /*trait*/ QPainter_drawLine<()> for (&'a QLine) {
fn drawLine(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawLineERK5QLine()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawLineERK5QLine(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QPainter::isActive();
impl /*struct*/ QPainter {
pub fn isActive<RetType, T: QPainter_isActive<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isActive(self);
// return 1;
}
}
pub trait QPainter_isActive<RetType> {
fn isActive(self , rsthis: & QPainter) -> RetType;
}
// proto: bool QPainter::isActive();
impl<'a> /*trait*/ QPainter_isActive<i8> for () {
fn isActive(self , rsthis: & QPainter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter8isActiveEv()};
let mut ret = unsafe {C_ZNK8QPainter8isActiveEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPainter::drawArc(const QRectF & rect, int a, int alen);
impl<'a> /*trait*/ QPainter_drawArc<()> for (&'a QRectF, i32, i32) {
fn drawArc(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7drawArcERK6QRectFii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
unsafe {C_ZN8QPainter7drawArcERK6QRectFii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: static void QPainter::restoreRedirected(const QPaintDevice * device);
impl /*struct*/ QPainter {
pub fn restoreRedirected_s<RetType, T: QPainter_restoreRedirected_s<RetType>>( overload_args: T) -> RetType {
return overload_args.restoreRedirected_s();
// return 1;
}
}
pub trait QPainter_restoreRedirected_s<RetType> {
fn restoreRedirected_s(self ) -> RetType;
}
// proto: static void QPainter::restoreRedirected(const QPaintDevice * device);
impl<'a> /*trait*/ QPainter_restoreRedirected_s<()> for (&'a QPaintDevice) {
fn restoreRedirected_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter17restoreRedirectedEPK12QPaintDevice()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter17restoreRedirectedEPK12QPaintDevice(arg0)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(const QPointF & p, const QPixmap & pm, const QRectF & sr);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (&'a QPointF, &'a QPixmap, &'a QRectF) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapERK7QPointFRK7QPixmapRK6QRectF()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapERK7QPointFRK7QPixmapRK6QRectF(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawEllipse(const QPointF & center, qreal rx, qreal ry);
impl<'a> /*trait*/ QPainter_drawEllipse<()> for (&'a QPointF, f64, f64) {
fn drawEllipse(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawEllipseERK7QPointFdd()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
unsafe {C_ZN8QPainter11drawEllipseERK7QPointFdd(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawConvexPolygon(const QPointF * points, int pointCount);
impl<'a> /*trait*/ QPainter_drawConvexPolygon<()> for (&'a QPointF, i32) {
fn drawConvexPolygon(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter17drawConvexPolygonEPK7QPointFi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter17drawConvexPolygonEPK7QPointFi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setBrushOrigin(const QPoint & );
impl<'a> /*trait*/ QPainter_setBrushOrigin<()> for (&'a QPoint) {
fn setBrushOrigin(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14setBrushOriginERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter14setBrushOriginERK6QPoint(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawText(const QRectF & r, const QString & text, const QTextOption & o);
impl<'a> /*trait*/ QPainter_drawText<()> for (&'a QRectF, &'a QString, Option<&'a QTextOption>) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextERK6QRectFRK7QStringRK11QTextOption()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = (if self.2.is_none() {QTextOption::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN8QPainter8drawTextERK6QRectFRK7QStringRK11QTextOption(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: bool QPainter::worldMatrixEnabled();
impl /*struct*/ QPainter {
pub fn worldMatrixEnabled<RetType, T: QPainter_worldMatrixEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.worldMatrixEnabled(self);
// return 1;
}
}
pub trait QPainter_worldMatrixEnabled<RetType> {
fn worldMatrixEnabled(self , rsthis: & QPainter) -> RetType;
}
// proto: bool QPainter::worldMatrixEnabled();
impl<'a> /*trait*/ QPainter_worldMatrixEnabled<i8> for () {
fn worldMatrixEnabled(self , rsthis: & QPainter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter18worldMatrixEnabledEv()};
let mut ret = unsafe {C_ZNK8QPainter18worldMatrixEnabledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPainter::drawPixmap(const QPoint & p, const QPixmap & pm);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (&'a QPoint, &'a QPixmap) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapERK6QPointRK7QPixmap()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapERK6QPointRK7QPixmap(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawLine(int x1, int y1, int x2, int y2);
impl<'a> /*trait*/ QPainter_drawLine<()> for (i32, i32, i32, i32) {
fn drawLine(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawLineEiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN8QPainter8drawLineEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::drawPoint(int x, int y);
impl<'a> /*trait*/ QPainter_drawPoint<()> for (i32, i32) {
fn drawPoint(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawPointEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter9drawPointEii(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QTransform & QPainter::transform();
impl /*struct*/ QPainter {
pub fn transform<RetType, T: QPainter_transform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.transform(self);
// return 1;
}
}
pub trait QPainter_transform<RetType> {
fn transform(self , rsthis: & QPainter) -> RetType;
}
// proto: const QTransform & QPainter::transform();
impl<'a> /*trait*/ QPainter_transform<QTransform> for () {
fn transform(self , rsthis: & QPainter) -> QTransform {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter9transformEv()};
let mut ret = unsafe {C_ZNK8QPainter9transformEv(rsthis.qclsinst)};
let mut ret1 = QTransform::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QPainter::setRedirected(const QPaintDevice * device, QPaintDevice * replacement, const QPoint & offset);
impl /*struct*/ QPainter {
pub fn setRedirected_s<RetType, T: QPainter_setRedirected_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setRedirected_s();
// return 1;
}
}
pub trait QPainter_setRedirected_s<RetType> {
fn setRedirected_s(self ) -> RetType;
}
// proto: static void QPainter::setRedirected(const QPaintDevice * device, QPaintDevice * replacement, const QPoint & offset);
impl<'a> /*trait*/ QPainter_setRedirected_s<()> for (&'a QPaintDevice, &'a QPaintDevice, Option<&'a QPoint>) {
fn setRedirected_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter13setRedirectedEPK12QPaintDevicePS0_RK6QPoint()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = (if self.2.is_none() {QPoint::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN8QPainter13setRedirectedEPK12QPaintDevicePS0_RK6QPoint(arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawPixmap(const QRect & targetRect, const QPixmap & pixmap, const QRect & sourceRect);
impl<'a> /*trait*/ QPainter_drawPixmap<()> for (&'a QRect, &'a QPixmap, &'a QRect) {
fn drawPixmap(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPixmapERK5QRectRK7QPixmapS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter10drawPixmapERK5QRectRK7QPixmapS2_(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: QFontMetrics QPainter::fontMetrics();
impl /*struct*/ QPainter {
pub fn fontMetrics<RetType, T: QPainter_fontMetrics<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.fontMetrics(self);
// return 1;
}
}
pub trait QPainter_fontMetrics<RetType> {
fn fontMetrics(self , rsthis: & QPainter) -> RetType;
}
// proto: QFontMetrics QPainter::fontMetrics();
impl<'a> /*trait*/ QPainter_fontMetrics<QFontMetrics> for () {
fn fontMetrics(self , rsthis: & QPainter) -> QFontMetrics {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter11fontMetricsEv()};
let mut ret = unsafe {C_ZNK8QPainter11fontMetricsEv(rsthis.qclsinst)};
let mut ret1 = QFontMetrics::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawGlyphRun(const QPointF & position, const QGlyphRun & glyphRun);
impl /*struct*/ QPainter {
pub fn drawGlyphRun<RetType, T: QPainter_drawGlyphRun<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawGlyphRun(self);
// return 1;
}
}
pub trait QPainter_drawGlyphRun<RetType> {
fn drawGlyphRun(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::drawGlyphRun(const QPointF & position, const QGlyphRun & glyphRun);
impl<'a> /*trait*/ QPainter_drawGlyphRun<()> for (&'a QPointF, &'a QGlyphRun) {
fn drawGlyphRun(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawGlyphRunERK7QPointFRK9QGlyphRun()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter12drawGlyphRunERK7QPointFRK9QGlyphRun(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::fillRect(const QRectF & , const QBrush & );
impl<'a> /*trait*/ QPainter_fillRect<()> for (&'a QRectF, &'a QBrush) {
fn fillRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8fillRectERK6QRectFRK6QBrush()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8fillRectERK6QRectFRK6QBrush(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::resetTransform();
impl /*struct*/ QPainter {
pub fn resetTransform<RetType, T: QPainter_resetTransform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resetTransform(self);
// return 1;
}
}
pub trait QPainter_resetTransform<RetType> {
fn resetTransform(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::resetTransform();
impl<'a> /*trait*/ QPainter_resetTransform<()> for () {
fn resetTransform(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14resetTransformEv()};
unsafe {C_ZN8QPainter14resetTransformEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QPainter::fillRect(const QRect & , const QBrush & );
impl<'a> /*trait*/ QPainter_fillRect<()> for (&'a QRect, &'a QBrush) {
fn fillRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8fillRectERK5QRectRK6QBrush()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8fillRectERK5QRectRK6QBrush(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QBrush & QPainter::brush();
impl /*struct*/ QPainter {
pub fn brush<RetType, T: QPainter_brush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.brush(self);
// return 1;
}
}
pub trait QPainter_brush<RetType> {
fn brush(self , rsthis: & QPainter) -> RetType;
}
// proto: const QBrush & QPainter::brush();
impl<'a> /*trait*/ QPainter_brush<QBrush> for () {
fn brush(self , rsthis: & QPainter) -> QBrush {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter5brushEv()};
let mut ret = unsafe {C_ZNK8QPainter5brushEv(rsthis.qclsinst)};
let mut ret1 = QBrush::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::~QPainter();
impl /*struct*/ QPainter {
pub fn free<RetType, T: QPainter_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QPainter_free<RetType> {
fn free(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::~QPainter();
impl<'a> /*trait*/ QPainter_free<()> for () {
fn free(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainterD2Ev()};
unsafe {C_ZN8QPainterD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QPainter::begin(QPaintDevice * );
impl /*struct*/ QPainter {
pub fn begin<RetType, T: QPainter_begin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.begin(self);
// return 1;
}
}
pub trait QPainter_begin<RetType> {
fn begin(self , rsthis: & QPainter) -> RetType;
}
// proto: bool QPainter::begin(QPaintDevice * );
impl<'a> /*trait*/ QPainter_begin<i8> for (&'a QPaintDevice) {
fn begin(self , rsthis: & QPainter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter5beginEP12QPaintDevice()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN8QPainter5beginEP12QPaintDevice(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPainter::drawRect(const QRect & rect);
impl<'a> /*trait*/ QPainter_drawRect<()> for (&'a QRect) {
fn drawRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawRectERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawRectERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawTextItem(const QPointF & p, const QTextItem & ti);
impl<'a> /*trait*/ QPainter_drawTextItem<()> for (&'a QPointF, &'a QTextItem) {
fn drawTextItem(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawTextItemERK7QPointFRK9QTextItem()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter12drawTextItemERK7QPointFRK9QTextItem(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::scale(qreal sx, qreal sy);
impl /*struct*/ QPainter {
pub fn scale<RetType, T: QPainter_scale<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.scale(self);
// return 1;
}
}
pub trait QPainter_scale<RetType> {
fn scale(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::scale(qreal sx, qreal sy);
impl<'a> /*trait*/ QPainter_scale<()> for (f64, f64) {
fn scale(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter5scaleEdd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
unsafe {C_ZN8QPainter5scaleEdd(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setWorldMatrix(const QMatrix & matrix, bool combine);
impl /*struct*/ QPainter {
pub fn setWorldMatrix<RetType, T: QPainter_setWorldMatrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWorldMatrix(self);
// return 1;
}
}
pub trait QPainter_setWorldMatrix<RetType> {
fn setWorldMatrix(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setWorldMatrix(const QMatrix & matrix, bool combine);
impl<'a> /*trait*/ QPainter_setWorldMatrix<()> for (&'a QMatrix, Option<i8>) {
fn setWorldMatrix(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter14setWorldMatrixERK7QMatrixb()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {false as i8} else {self.1.unwrap()}) as c_char;
unsafe {C_ZN8QPainter14setWorldMatrixERK7QMatrixb(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QPainterPath QPainter::clipPath();
impl /*struct*/ QPainter {
pub fn clipPath<RetType, T: QPainter_clipPath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clipPath(self);
// return 1;
}
}
pub trait QPainter_clipPath<RetType> {
fn clipPath(self , rsthis: & QPainter) -> RetType;
}
// proto: QPainterPath QPainter::clipPath();
impl<'a> /*trait*/ QPainter_clipPath<QPainterPath> for () {
fn clipPath(self , rsthis: & QPainter) -> QPainterPath {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter8clipPathEv()};
let mut ret = unsafe {C_ZNK8QPainter8clipPathEv(rsthis.qclsinst)};
let mut ret1 = QPainterPath::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QPoint QPainter::brushOrigin();
impl /*struct*/ QPainter {
pub fn brushOrigin<RetType, T: QPainter_brushOrigin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.brushOrigin(self);
// return 1;
}
}
pub trait QPainter_brushOrigin<RetType> {
fn brushOrigin(self , rsthis: & QPainter) -> RetType;
}
// proto: QPoint QPainter::brushOrigin();
impl<'a> /*trait*/ QPainter_brushOrigin<QPoint> for () {
fn brushOrigin(self , rsthis: & QPainter) -> QPoint {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter11brushOriginEv()};
let mut ret = unsafe {C_ZNK8QPainter11brushOriginEv(rsthis.qclsinst)};
let mut ret1 = QPoint::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawConvexPolygon(const QPolygonF & polygon);
impl<'a> /*trait*/ QPainter_drawConvexPolygon<()> for (&'a QPolygonF) {
fn drawConvexPolygon(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter17drawConvexPolygonERK9QPolygonF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter17drawConvexPolygonERK9QPolygonF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawEllipse(int x, int y, int w, int h);
impl<'a> /*trait*/ QPainter_drawEllipse<()> for (i32, i32, i32, i32) {
fn drawEllipse(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter11drawEllipseEiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN8QPainter11drawEllipseEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::drawConvexPolygon(const QPolygon & polygon);
impl<'a> /*trait*/ QPainter_drawConvexPolygon<()> for (&'a QPolygon) {
fn drawConvexPolygon(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter17drawConvexPolygonERK8QPolygon()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter17drawConvexPolygonERK8QPolygon(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawPoints(const QPoint * points, int pointCount);
impl<'a> /*trait*/ QPainter_drawPoints<()> for (&'a QPoint, i32) {
fn drawPoints(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10drawPointsEPK6QPointi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter10drawPointsEPK6QPointi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QBrush & QPainter::background();
impl /*struct*/ QPainter {
pub fn background<RetType, T: QPainter_background<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.background(self);
// return 1;
}
}
pub trait QPainter_background<RetType> {
fn background(self , rsthis: & QPainter) -> RetType;
}
// proto: const QBrush & QPainter::background();
impl<'a> /*trait*/ QPainter_background<QBrush> for () {
fn background(self , rsthis: & QPainter) -> QBrush {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter10backgroundEv()};
let mut ret = unsafe {C_ZNK8QPainter10backgroundEv(rsthis.qclsinst)};
let mut ret1 = QBrush::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawRoundRect(int x, int y, int w, int h, int , int );
impl<'a> /*trait*/ QPainter_drawRoundRect<()> for (i32, i32, i32, i32, Option<i32>, Option<i32>) {
fn drawRoundRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter13drawRoundRectEiiiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = (if self.4.is_none() {25} else {self.4.unwrap()}) as c_int;
let arg5 = (if self.5.is_none() {25} else {self.5.unwrap()}) as c_int;
unsafe {C_ZN8QPainter13drawRoundRectEiiiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)};
// return 1;
}
}
// proto: QRect QPainter::viewport();
impl /*struct*/ QPainter {
pub fn viewport<RetType, T: QPainter_viewport<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.viewport(self);
// return 1;
}
}
pub trait QPainter_viewport<RetType> {
fn viewport(self , rsthis: & QPainter) -> RetType;
}
// proto: QRect QPainter::viewport();
impl<'a> /*trait*/ QPainter_viewport<QRect> for () {
fn viewport(self , rsthis: & QPainter) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter8viewportEv()};
let mut ret = unsafe {C_ZNK8QPainter8viewportEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawArc(const QRect & , int a, int alen);
impl<'a> /*trait*/ QPainter_drawArc<()> for (&'a QRect, i32, i32) {
fn drawArc(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7drawArcERK5QRectii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
unsafe {C_ZN8QPainter7drawArcERK5QRectii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::fillPath(const QPainterPath & path, const QBrush & brush);
impl /*struct*/ QPainter {
pub fn fillPath<RetType, T: QPainter_fillPath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.fillPath(self);
// return 1;
}
}
pub trait QPainter_fillPath<RetType> {
fn fillPath(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::fillPath(const QPainterPath & path, const QBrush & brush);
impl<'a> /*trait*/ QPainter_fillPath<()> for (&'a QPainterPath, &'a QBrush) {
fn fillPath(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8fillPathERK12QPainterPathRK6QBrush()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8fillPathERK12QPainterPathRK6QBrush(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawText(int x, int y, int w, int h, int flags, const QString & text, QRect * br);
impl<'a> /*trait*/ QPainter_drawText<()> for (i32, i32, i32, i32, i32, &'a QString, Option<&'a QRect>) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextEiiiiiRK7QStringP5QRect()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let arg4 = self.4 as c_int;
let arg5 = self.5.qclsinst as *mut c_void;
let arg6 = (if self.6.is_none() {0} else {self.6.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN8QPainter8drawTextEiiiiiRK7QStringP5QRect(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5, arg6)};
// return 1;
}
}
// proto: bool QPainter::matrixEnabled();
impl /*struct*/ QPainter {
pub fn matrixEnabled<RetType, T: QPainter_matrixEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.matrixEnabled(self);
// return 1;
}
}
pub trait QPainter_matrixEnabled<RetType> {
fn matrixEnabled(self , rsthis: & QPainter) -> RetType;
}
// proto: bool QPainter::matrixEnabled();
impl<'a> /*trait*/ QPainter_matrixEnabled<i8> for () {
fn matrixEnabled(self , rsthis: & QPainter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter13matrixEnabledEv()};
let mut ret = unsafe {C_ZNK8QPainter13matrixEnabledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPainter::drawPolyline(const QPointF * points, int pointCount);
impl<'a> /*trait*/ QPainter_drawPolyline<()> for (&'a QPointF, i32) {
fn drawPolyline(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12drawPolylineEPK7QPointFi()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
unsafe {C_ZN8QPainter12drawPolylineEPK7QPointFi(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setTransform(const QTransform & transform, bool combine);
impl /*struct*/ QPainter {
pub fn setTransform<RetType, T: QPainter_setTransform<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTransform(self);
// return 1;
}
}
pub trait QPainter_setTransform<RetType> {
fn setTransform(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setTransform(const QTransform & transform, bool combine);
impl<'a> /*trait*/ QPainter_setTransform<()> for (&'a QTransform, Option<i8>) {
fn setTransform(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter12setTransformERK10QTransformb()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {false as i8} else {self.1.unwrap()}) as c_char;
unsafe {C_ZN8QPainter12setTransformERK10QTransformb(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setPen(const QColor & color);
impl<'a> /*trait*/ QPainter_setPen<()> for (&'a QColor) {
fn setPen(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter6setPenERK6QColor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter6setPenERK6QColor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::eraseRect(const QRect & );
impl<'a> /*trait*/ QPainter_eraseRect<()> for (&'a QRect) {
fn eraseRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9eraseRectERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9eraseRectERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QRect QPainter::window();
impl /*struct*/ QPainter {
pub fn window<RetType, T: QPainter_window<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.window(self);
// return 1;
}
}
pub trait QPainter_window<RetType> {
fn window(self , rsthis: & QPainter) -> RetType;
}
// proto: QRect QPainter::window();
impl<'a> /*trait*/ QPainter_window<QRect> for () {
fn window(self , rsthis: & QPainter) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter6windowEv()};
let mut ret = unsafe {C_ZNK8QPainter6windowEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawImage(const QRect & r, const QImage & image);
impl<'a> /*trait*/ QPainter_drawImage<()> for (&'a QRect, &'a QImage) {
fn drawImage(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawImageERK5QRectRK6QImage()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9drawImageERK5QRectRK6QImage(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::initFrom(const QPaintDevice * device);
impl /*struct*/ QPainter {
pub fn initFrom<RetType, T: QPainter_initFrom<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.initFrom(self);
// return 1;
}
}
pub trait QPainter_initFrom<RetType> {
fn initFrom(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::initFrom(const QPaintDevice * device);
impl<'a> /*trait*/ QPainter_initFrom<()> for (&'a QPaintDevice) {
fn initFrom(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8initFromEPK12QPaintDevice()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8initFromEPK12QPaintDevice(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QFontInfo QPainter::fontInfo();
impl /*struct*/ QPainter {
pub fn fontInfo<RetType, T: QPainter_fontInfo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.fontInfo(self);
// return 1;
}
}
pub trait QPainter_fontInfo<RetType> {
fn fontInfo(self , rsthis: & QPainter) -> RetType;
}
// proto: QFontInfo QPainter::fontInfo();
impl<'a> /*trait*/ QPainter_fontInfo<QFontInfo> for () {
fn fontInfo(self , rsthis: & QPainter) -> QFontInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter8fontInfoEv()};
let mut ret = unsafe {C_ZNK8QPainter8fontInfoEv(rsthis.qclsinst)};
let mut ret1 = QFontInfo::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::endNativePainting();
impl /*struct*/ QPainter {
pub fn endNativePainting<RetType, T: QPainter_endNativePainting<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.endNativePainting(self);
// return 1;
}
}
pub trait QPainter_endNativePainting<RetType> {
fn endNativePainting(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::endNativePainting();
impl<'a> /*trait*/ QPainter_endNativePainting<()> for () {
fn endNativePainting(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter17endNativePaintingEv()};
unsafe {C_ZN8QPainter17endNativePaintingEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QPainter::setViewTransformEnabled(bool enable);
impl /*struct*/ QPainter {
pub fn setViewTransformEnabled<RetType, T: QPainter_setViewTransformEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setViewTransformEnabled(self);
// return 1;
}
}
pub trait QPainter_setViewTransformEnabled<RetType> {
fn setViewTransformEnabled(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setViewTransformEnabled(bool enable);
impl<'a> /*trait*/ QPainter_setViewTransformEnabled<()> for (i8) {
fn setViewTransformEnabled(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter23setViewTransformEnabledEb()};
let arg0 = self as c_char;
unsafe {C_ZN8QPainter23setViewTransformEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawPoint(const QPointF & pt);
impl<'a> /*trait*/ QPainter_drawPoint<()> for (&'a QPointF) {
fn drawPoint(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawPointERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9drawPointERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::setOpacity(qreal opacity);
impl /*struct*/ QPainter {
pub fn setOpacity<RetType, T: QPainter_setOpacity<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setOpacity(self);
// return 1;
}
}
pub trait QPainter_setOpacity<RetType> {
fn setOpacity(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::setOpacity(qreal opacity);
impl<'a> /*trait*/ QPainter_setOpacity<()> for (f64) {
fn setOpacity(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter10setOpacityEd()};
let arg0 = self as c_double;
unsafe {C_ZN8QPainter10setOpacityEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::fillRect(const QRectF & , const QColor & color);
impl<'a> /*trait*/ QPainter_fillRect<()> for (&'a QRectF, &'a QColor) {
fn fillRect(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8fillRectERK6QRectFRK6QColor()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8fillRectERK6QRectFRK6QColor(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::QPainter();
impl<'a> /*trait*/ QPainter_new for () {
fn new(self) -> QPainter {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainterC2Ev()};
let ctysz: c_int = unsafe{QPainter_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN8QPainterC2Ev()};
let rsthis = QPainter{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QPainter::translate(const QPointF & offset);
impl<'a> /*trait*/ QPainter_translate<()> for (&'a QPointF) {
fn translate(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9translateERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9translateERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPainter::drawText(const QPointF & p, const QString & s);
impl<'a> /*trait*/ QPainter_drawText<()> for (&'a QPointF, &'a QString) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextERK7QPointFRK7QString()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawTextERK7QPointFRK7QString(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawImage(const QPointF & p, const QImage & image);
impl<'a> /*trait*/ QPainter_drawImage<()> for (&'a QPointF, &'a QImage) {
fn drawImage(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9drawImageERK7QPointFRK6QImage()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter9drawImageERK7QPointFRK6QImage(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QPen & QPainter::pen();
impl /*struct*/ QPainter {
pub fn pen<RetType, T: QPainter_pen<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.pen(self);
// return 1;
}
}
pub trait QPainter_pen<RetType> {
fn pen(self , rsthis: & QPainter) -> RetType;
}
// proto: const QPen & QPainter::pen();
impl<'a> /*trait*/ QPainter_pen<QPen> for () {
fn pen(self , rsthis: & QPainter) -> QPen {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter3penEv()};
let mut ret = unsafe {C_ZNK8QPainter3penEv(rsthis.qclsinst)};
let mut ret1 = QPen::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::rotate(qreal a);
impl /*struct*/ QPainter {
pub fn rotate<RetType, T: QPainter_rotate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rotate(self);
// return 1;
}
}
pub trait QPainter_rotate<RetType> {
fn rotate(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::rotate(qreal a);
impl<'a> /*trait*/ QPainter_rotate<()> for (f64) {
fn rotate(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter6rotateEd()};
let arg0 = self as c_double;
unsafe {C_ZN8QPainter6rotateEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QRectF QPainter::clipBoundingRect();
impl /*struct*/ QPainter {
pub fn clipBoundingRect<RetType, T: QPainter_clipBoundingRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clipBoundingRect(self);
// return 1;
}
}
pub trait QPainter_clipBoundingRect<RetType> {
fn clipBoundingRect(self , rsthis: & QPainter) -> RetType;
}
// proto: QRectF QPainter::clipBoundingRect();
impl<'a> /*trait*/ QPainter_clipBoundingRect<QRectF> for () {
fn clipBoundingRect(self , rsthis: & QPainter) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QPainter16clipBoundingRectEv()};
let mut ret = unsafe {C_ZNK8QPainter16clipBoundingRectEv(rsthis.qclsinst)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPainter::drawLine(const QPoint & p1, const QPoint & p2);
impl<'a> /*trait*/ QPainter_drawLine<()> for (&'a QPoint, &'a QPoint) {
fn drawLine(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawLineERK6QPointS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawLineERK6QPointS2_(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::drawPie(const QRectF & rect, int a, int alen);
impl<'a> /*trait*/ QPainter_drawPie<()> for (&'a QRectF, i32, i32) {
fn drawPie(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter7drawPieERK6QRectFii()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
unsafe {C_ZN8QPainter7drawPieERK6QRectFii(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QPainter::drawText(const QPoint & p, const QString & s);
impl<'a> /*trait*/ QPainter_drawText<()> for (&'a QPoint, &'a QString) {
fn drawText(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter8drawTextERK6QPointRK7QString()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN8QPainter8drawTextERK6QPointRK7QString(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QPainter::setWindow(int x, int y, int w, int h);
impl<'a> /*trait*/ QPainter_setWindow<()> for (i32, i32, i32, i32) {
fn setWindow(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter9setWindowEiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN8QPainter9setWindowEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QPainter::beginNativePainting();
impl /*struct*/ QPainter {
pub fn beginNativePainting<RetType, T: QPainter_beginNativePainting<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.beginNativePainting(self);
// return 1;
}
}
pub trait QPainter_beginNativePainting<RetType> {
fn beginNativePainting(self , rsthis: & QPainter) -> RetType;
}
// proto: void QPainter::beginNativePainting();
impl<'a> /*trait*/ QPainter_beginNativePainting<()> for () {
fn beginNativePainting(self , rsthis: & QPainter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QPainter19beginNativePaintingEv()};
unsafe {C_ZN8QPainter19beginNativePaintingEv(rsthis.qclsinst)};
// return 1;
}
}
// <= body block end
|
use crate::{config::Flavor, curse_api, tukui_api, utility::strip_non_digits};
use std::cmp::Ordering;
use std::path::PathBuf;
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
pub enum AddonState {
Ajour(Option<String>),
Downloading,
Fingerprint,
Unpacking,
Updatable,
}
#[derive(Debug, Clone)]
/// Struct which stores identifiers for the different repositories.
pub struct RepositoryIdentifiers {
pub wowi: Option<String>,
pub tukui: Option<String>,
pub curse: Option<u32>,
}
#[derive(Debug, Clone)]
/// Struct which stores information about a single Addon.
pub struct Addon {
pub id: String,
pub title: String,
pub author: Option<String>,
pub notes: Option<String>,
pub version: Option<String>,
pub remote_version: Option<String>,
pub remote_url: Option<String>,
pub path: PathBuf,
pub dependencies: Vec<String>,
pub state: AddonState,
pub wowi_id: Option<String>,
pub tukui_id: Option<String>,
pub curse_id: Option<u32>,
pub fingerprint: Option<u32>,
// States for GUI
pub details_btn_state: iced::button::State,
pub update_btn_state: iced::button::State,
pub force_btn_state: iced::button::State,
pub delete_btn_state: iced::button::State,
pub ignore_btn_state: iced::button::State,
pub unignore_btn_state: iced::button::State,
}
impl Addon {
/// Creates a new Addon
#[allow(clippy::too_many_arguments)]
pub fn new(
id: String,
title: String,
author: Option<String>,
notes: Option<String>,
version: Option<String>,
path: PathBuf,
dependencies: Vec<String>,
wowi_id: Option<String>,
tukui_id: Option<String>,
curse_id: Option<u32>,
) -> Self {
Addon {
id,
title,
author,
notes,
version,
remote_version: None,
remote_url: None,
path,
dependencies,
state: AddonState::Ajour(None),
wowi_id,
tukui_id,
curse_id,
fingerprint: None,
details_btn_state: Default::default(),
update_btn_state: Default::default(),
force_btn_state: Default::default(),
delete_btn_state: Default::default(),
ignore_btn_state: Default::default(),
unignore_btn_state: Default::default(),
}
}
/// Package from Tukui.
///
/// This function takes a `Package` and updates self with the information.
pub fn apply_tukui_package(&mut self, package: &tukui_api::TukuiPackage) {
self.remote_version = Some(package.version.clone());
self.remote_url = Some(package.url.clone());
if self.is_updatable() {
self.state = AddonState::Updatable;
}
}
/// Package from Curse.
///
/// This function takes a `Package` and updates self with the information
pub fn apply_curse_package(&mut self, package: &curse_api::Package) {
self.title = package.name.clone();
}
pub fn apply_fingerprint_module(
&mut self,
info: &curse_api::AddonFingerprintInfo,
flavor: Flavor,
) {
let dependencies: Vec<String> = info
.file
.modules
.iter()
.map(|m| m.foldername.clone())
.collect();
let flavor = format!("wow_{}", flavor.to_string());
// We try to find the latest stable release. If we can't find that.
// We will fallback to latest beta release. And lastly we give up.
let file = if let Some(file) = info.latest_files.iter().find(|f| {
f.release_type == 1 // 1 is stable, 2 is beta, 3 is alpha.
&& !f.is_alternate
&& f.game_version_flavor == flavor
}) {
Some(file)
} else if let Some(file) = info.latest_files.iter().find(|f| {
f.release_type == 2 // 1 is stable, 2 is beta, 3 is alpha.
&& !f.is_alternate
&& f.game_version_flavor == flavor
}) {
Some(file)
} else {
None
};
if let Some(file) = file {
self.remote_version = Some(file.display_name.clone());
self.remote_url = Some(file.download_url.clone());
if file.id > info.file.id {
self.state = AddonState::Updatable;
}
}
self.dependencies = dependencies;
self.version = Some(info.file.display_name.clone());
self.curse_id = Some(info.id);
}
/// Function returns a `bool` indicating if the user has manually ignored the addon.
pub fn is_ignored(&self, ignored: Option<&Vec<String>>) -> bool {
match ignored {
Some(ignored) => ignored.iter().any(|i| i == &self.id),
_ => false,
}
}
/// Check if the `Addon` is updatable.
/// We strip both version for non digits, and then
/// checks if `remote_version` is a sub_slice of `local_version`.
///
/// Eg:
/// local_version: 4.10.5 => 4105.
/// remote_version: Rematch_4_10_5.zip => 4105.
/// Since `4105` is a sub_slice of `4105` it's not updatable.
fn is_updatable(&self) -> bool {
match (&self.remote_version, &self.version) {
(Some(rv), Some(lv)) => {
let srv = strip_non_digits(&rv);
let slv = strip_non_digits(&lv);
if let (Some(srv), Some(slv)) = (srv, slv) {
return !slv.contains(&srv);
}
false
}
_ => false,
}
}
}
impl PartialEq for Addon {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl PartialOrd for Addon {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(
self.title
.cmp(&other.title)
.then_with(|| self.remote_version.cmp(&other.remote_version).reverse()),
)
}
}
impl Ord for Addon {
fn cmp(&self, other: &Self) -> Ordering {
self.title
.cmp(&other.title)
.then_with(|| self.remote_version.cmp(&other.remote_version).reverse())
}
}
impl Eq for Addon {}
|
extern crate regex;
extern crate num_cpus;
extern crate memmap;
extern crate time;
extern crate ansi_term;
use std::fs::DirEntry;
use std::sync::{Arc, Mutex};
use std::thread;
use self::memmap::{Mmap, Protection};
use self::ansi_term::{Style, Colour};
use self::regex::bytes::Regex;
use std::path::PathBuf;
use std::str;
pub fn run_search(pattern: String, entries: Vec<DirEntry>) {
let start_time = time::precise_time_ns();
let num_entries = entries.len();
let num_cores = num_cpus::get();
let mut num_threads = 0;
if num_cores < num_entries {
let mutex = Arc::new(Mutex::new(false));
let shared_entries = Arc::new(entries);
let shared_pattern = Arc::new(pattern);
let mut threads = Vec::new();
for idx in 0..num_cores {
let child_entries = shared_entries.clone();
let child_pattern = shared_pattern.clone();
let child_mutex = mutex.clone();
let block_size = num_entries / num_cores;
let mut range = (idx * block_size, (idx + 1) * block_size - 1);
if idx == num_cores {
// This corrects for round-off error in integer division
range.1 = num_entries;
}
threads.push(thread::spawn(move || {
search_rangeof_files(&child_pattern, &child_entries, range, Some(&child_mutex));
}));
num_threads += 1;
}
for thrd in threads {
let res = thrd.join();
match res {
Err(e) => {
println!("Error: thread panicked with error code {:?}", e);
}
_ => {}
}
}
} else {
num_threads = 1;
search_rangeof_files(&pattern, &entries, (0, entries.len()), None);
}
let elapsed = time::precise_time_ns() - start_time;
println!("[Completed search of {0} files in {1} ns using {2} thread(s)]",
num_entries,
elapsed,
num_threads);
}
#[allow(unused_variables)] // lock_grd needs to exist for thread synchronization
fn search_rangeof_files(pattern: &String,
entries: &Vec<DirEntry>,
range: (usize, usize),
mutex: Option<&Mutex<bool>>) {
let ret = Regex::new(pattern);
match ret {
Err(_) => println!("Failed to construct regular expression."),
Ok(regex) => {
for idx in range.0..range.1 {
let entry = &entries[idx];
let res = Mmap::open_path(entry.path(), Protection::Read);
match res {
Ok(file_mmap) => {
let bytes: &[u8] = unsafe { file_mmap.as_slice() };
let matches = search_mmap(bytes, ®ex);
match mutex {
Some(m) => {
let lock_grd = m.lock().unwrap();
print_results(bytes, matches, entry.path());
}
None => print_results(bytes, matches, entry.path()),
}
}
Err(_) => {
// TODO: don't print errors for mmaping empty files
println!("Error: Failed to mmap {:?}", entry.path());
continue;
}
}
}
}
}
}
fn search_mmap(bytes: &[u8], regex: &Regex) -> Vec<(usize, usize)> {
let mut matches = Vec::new();
for pos in regex.find_iter(bytes) {
matches.push(pos);
}
return matches;
}
fn print_results(bytes: &[u8], matches: Vec<(usize, usize)>, path: PathBuf) {
if matches.len() == 0 {
return;
}
let fname = path.file_name().unwrap().to_str().unwrap();
println!("[{}]", Style::new().bold().paint(fname));
for matched_pattern_idxs in matches {
print!("\t");
print_leading_context(bytes, matched_pattern_idxs);
print_match(bytes, matched_pattern_idxs);
print_trailing_context(bytes, matched_pattern_idxs);
print!("{}", Style::default().paint("\n"));
}
print!("\n\n");
}
fn print_match(bytes: &[u8], matched_pattern_idxs: (usize, usize)) {
let matched_pattern_slice = &bytes[matched_pattern_idxs.0..matched_pattern_idxs.1];
let ret = str::from_utf8(&matched_pattern_slice);
match ret {
Ok(matched_string) => {
print!("{}",
Style::new().on(Colour::Green).fg(Colour::Black).paint(matched_string));
}
_ => {
let error_fmt = Style::new().bold().fg(Colour::Red);
println!("{}",
error_fmt.paint("Found non-utf8 character, skipping..."));
}
}
}
fn print_leading_context(bytes: &[u8], matched_pattern_idxs: (usize, usize)) {
let line_start_idx = seek_line_start(bytes, matched_pattern_idxs.0);
if line_start_idx != matched_pattern_idxs.0 {
let leading_slice = &bytes[line_start_idx..(matched_pattern_idxs.0)];
let ret = str::from_utf8(&leading_slice);
match ret {
Ok(leading_string) => print!("{}", leading_string),
_ => {
let error_fmt = Style::new().bold().fg(Colour::Red);
println!("{}",
error_fmt.paint("Found non-utf8 character, skipping..."));
}
}
}
}
fn print_trailing_context(bytes: &[u8], matched_pattern_idxs: (usize, usize)) {
let line_end_idx = seek_line_end(bytes, matched_pattern_idxs.1);
if line_end_idx != matched_pattern_idxs.1 {
let trailing_slice = &bytes[(matched_pattern_idxs.1)..line_end_idx];
let ret = str::from_utf8(&trailing_slice);
match ret {
Ok(trailing_string) => print!("{}", trailing_string),
_ => {
let error_fmt = Style::new().bold().fg(Colour::Red);
println!("{}",
error_fmt.paint("Found non-utf8 character, skipping..."));
}
}
}
}
fn seek_line_start(bytes: &[u8], position: usize) -> usize {
let mut idx = position;
while idx != 0 {
idx -= 1;
if bytes[idx] == '\n' as u8 {
idx += 1;
break;
}
}
return idx;
}
fn seek_line_end(bytes: &[u8], position: usize) -> usize {
let mut idx = position;
while idx != bytes.len() - 1 {
idx += 1;
if bytes[idx] == '\n' as u8 {
break;
}
}
return idx;
}
|
// enumns can be defined with or without data contained in them
// data contained can be any type of primitive type, structs, an enum
// recursuive enum type need to be behind a pointer(Box,Rc)
#[derive(Debug)]
enum Direction {
N,
E,
W,
S,
}
enum PlayerAction {
Move { direction: Direction, speed: u8 },
Wait,
Attack(Direction),
}
fn main() {
let sim_player = PlayerAction::Move {
direction: Direction::N,
speed: 2,
};
let rs = match sim_player {
PlayerAction::Wait => println!("User is waiting !!"),
PlayerAction::Move { direction, speed } => {
println!(
"Player wants to move in direction {:?} with speed {:?}",
direction, speed
);
()
}
PlayerAction::Attack(direction) => println!("Attacking direction {:?}", direction),
};
println!("rs {:?}", rs);
}
|
// Copyright (c) 2018-2022 Ministerio de Fomento
// Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>,
// Daniel Jiménez González <dani@ietcc.csic.es>,
// Marta Sorribes Gil <msorribes@ietcc.csic.es>
use std::fmt;
use std::str;
use serde::{Deserialize, Serialize};
use super::{HasValues, Service};
use crate::error::EpbdError;
use crate::vecops::vecvecsum;
// -------------------- Building Energy Needs Component
// Define basic Building Energy Needs Component type and a container of all Building needs
// The component is used to express energy needs of the whole building provide service X (X=CAL/REF/ACS) (Q_X_nd_t)
// The component stores building needs for heating (CAL), cooling (REF) and domestic heat water (ACS)
/// Demandas del edificio
#[allow(non_snake_case)]
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct BuildingNeeds {
/// Timestep building energy needs to provide the domestic heat water service, Q_DHW_nd_t. kWh
#[serde(default)]
#[serde(skip_serializing_if="Option::is_none")]
pub ACS: Option<Vec<f32>>,
/// Timestep building energy needs to provide the heating service, Q_H_nd_t. kWh
#[serde(default)]
#[serde(skip_serializing_if="Option::is_none")]
pub CAL: Option<Vec<f32>>,
/// Timestep building energy needs to provide the cooling service, Q_C_nd_t. kWh
#[serde(default)]
#[serde(skip_serializing_if="Option::is_none")]
pub REF: Option<Vec<f32>>,
}
impl BuildingNeeds {
/// Añade elemento de demanda del edificio, sumando los valores si ya se han definido para ese servicio
pub fn add(&mut self, need: Needs) -> Result<(), EpbdError> {
let update = |cur_values: &Option<Vec<f32>>, new_values| {
if let Some(nd) = cur_values {
Some(vecvecsum(nd, new_values))
} else {
Some(new_values.to_owned())
}
};
match need.service {
Service::ACS => self.ACS = update(&self.ACS, &need.values),
Service::CAL => self.CAL = update(&self.CAL, &need.values),
Service::REF => self.REF = update(&self.REF, &need.values),
_ => {
return Err(EpbdError::WrongInput(format!(
"Demanda de edificio con servicio no contemplado por el programa: {}",
need.service
)))
}
};
Ok(())
}
}
/// Componente de demanda de edificio.
///
/// Se serializa como: `DEMANDA, servicio, vals... # comentario`
///
/// - servicio == CAL / REF / ACS
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Needs {
/// End use (CAL, REF, ACS)
pub service: Service,
/// List of timestep energy needs for the building to provide service X, Q_X_nd_t. kWh
pub values: Vec<f32>,
}
impl HasValues for Needs {
fn values(&self) -> &[f32] {
&self.values
}
}
impl fmt::Display for Needs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let valuelist = self
.values
.iter()
.map(|v| format!("{:.2}", v))
.collect::<Vec<_>>()
.join(", ");
write!(f, "DEMANDA, {}, {}", self.service, valuelist)
}
}
impl str::FromStr for Needs {
type Err = EpbdError;
fn from_str(s: &str) -> Result<Needs, Self::Err> {
// Split comment from the rest of fields
let items: Vec<&str> = s.trim().splitn(2, '#').map(str::trim).collect();
let items: Vec<&str> = items[0].split(',').map(str::trim).collect();
// Minimal possible length (DEMANDA + Service + 1 value)
if items.len() < 3 {
return Err(EpbdError::ParseError(s.into()));
};
// Check DEMANDA marker fields;
if items[0] != "DEMANDA" {
return Err(EpbdError::ParseError(format!(
"No se reconoce el formato como elemento de Demanda: {}",
s
)));
}
// Check valid service field CAL, REF, ACS
let service = items[1].parse()?;
if ![Service::CAL, Service::REF, Service::ACS].contains(&service) {
return Err(EpbdError::ParseError(format!(
"Servicio no soportado en componente de DEMANDA del edificio: {}",
service
)));
}
// Collect energy values from the service field on
let values = items[2..]
.iter()
.map(|v| v.parse::<f32>())
.collect::<Result<Vec<f32>, _>>()?;
Ok(Needs { service, values })
}
}
// ========================== Tests
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn component_building_needs() {
// zone energy needs component
let component1 = Needs {
service: "REF".parse().unwrap(),
values: vec![
1.0, 2.0, 3.0, 4.0, 5.0, -6.0, -7.0, -8.0, -9.0, 10.0, 11.0, 12.0,
]
};
let component1str = "DEMANDA, REF, 1.00, 2.00, 3.00, 4.00, 5.00, -6.00, -7.00, -8.00, -9.00, 10.00, 11.00, 12.00";
assert_eq!(component1.to_string(), component1str);
// roundtrip building from/to string
assert_eq!(
component1str.parse::<Needs>().unwrap().to_string(),
component1str
);
}
}
|
//! Background for an output
use rustwlc::WlcView;
use wayland_sys::server::wl_client;
/// A background is not complete until you call the "complete" method on it.
/// This will need to be executed via the view_created callback, because before that
/// we haven't properly set it.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct IncompleteBackground {
client: usize
}
/// A background for an output.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Background {
pub handle: WlcView
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum MaybeBackground {
Incomplete(IncompleteBackground),
Complete(Background)
}
impl Into<MaybeBackground> for IncompleteBackground {
fn into(self) -> MaybeBackground {
MaybeBackground::Incomplete(self)
}
}
impl Into<MaybeBackground> for Background {
fn into(self) -> MaybeBackground {
MaybeBackground::Complete(self)
}
}
impl IncompleteBackground {
pub fn new(client: *mut wl_client) -> Self {
IncompleteBackground { client: client as _ }
}
/// Builds the background if the client matches
/// If it fails, then the incomplete background is returned instead.
pub fn build(self, client: *mut wl_client, handle: WlcView)
-> MaybeBackground {
if self.client as *mut wl_client == client {
Background { handle }.into()
} else {
self.into()
}
}
}
|
mod minimax;
pub use minimax::*;
mod alphabeta;
pub use alphabeta::*;
use std::fmt::Debug;
use crate::game::Game;
pub const WIN: f64 = 10000.0;
pub const DRAW: f64 = 0.0;
pub const LOSS: f64 = -10000.0;
/// A heuristic that evaluates the game state at the leafs of a tree search.
pub trait Heuristic: Debug + Send + Sync + 'static {
fn eval(&self, game: &Game) -> f64;
}
|
use super::{expm1, expo2};
// sinh(x) = (exp(x) - 1/exp(x))/2
// = (exp(x)-1 + (exp(x)-1)/exp(x))/2
// = x + x^3/6 + o(x^5)
//
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn sinh(x: f64) -> f64 {
// union {double f; uint64_t i;} u = {.f = x};
// uint32_t w;
// double t, h, absx;
let mut uf: f64 = x;
let mut ui: u64 = f64::to_bits(uf);
let w: u32;
let t: f64;
let mut h: f64;
let absx: f64;
h = 0.5;
if ui >> 63 != 0 {
h = -h;
}
/* |x| */
ui &= !1 / 2;
uf = f64::from_bits(ui);
absx = uf;
w = (ui >> 32) as u32;
/* |x| < log(DBL_MAX) */
if w < 0x40862e42 {
t = expm1(absx);
if w < 0x3ff00000 {
if w < 0x3ff00000 - (26 << 20) {
/* note: inexact and underflow are raised by expm1 */
/* note: this branch avoids spurious underflow */
return x;
}
return h * (2.0 * t - t * t / (t + 1.0));
}
/* note: |x|>log(0x1p26)+eps could be just h*exp(x) */
return h * (t + t / (t + 1.0));
}
/* |x| > log(DBL_MAX) or nan */
/* note: the result is stored to handle overflow */
t = 2.0 * h * expo2(absx);
t
}
|
use amethyst::core::shrev::{ReaderId};
use amethyst::ecs::{Write, ReadStorage, System, Read};
use amethyst::ecs::{Component, VecStorage};
use amethyst::core::transform::Transform;
use amethyst::prelude::*;
use amethyst::ecs::SystemData;
use specs_physics::events::{ProximityEvent, ProximityEvents};
use crate::room::DestRoom;
use crate::room;
impl Component for DestRoom {
type Storage = VecStorage<Self>;
}
pub struct PerformRoomExit(pub room::DestRoom, pub (i32, i32));
pub struct RoomExitSystem {
reader: ReaderId<ProximityEvent>
}
/*impl Default for RoomExitSystem {
fn default() -> Self {
RoomExitSystem {
reader: None
}
}
}*/
impl RoomExitSystem {
pub fn new(world: &mut World) -> Self {
<Self as System<'_>>::SystemData::setup(world);
let reader = world.fetch_mut::<ProximityEvents>().register_reader();
RoomExitSystem {
reader
}
}
}
impl<'s> System<'s> for RoomExitSystem {
type SystemData = (
Read<'s, ProximityEvents>,
ReadStorage<'s, DestRoom>,
Write<'s, Option<PerformRoomExit>>,
ReadStorage<'s, Transform>,
);
fn run(
&mut self,
(channel, destrooms, mut perform_room_exit, transforms,): Self::SystemData,
) {
for collision in channel.read(&mut self.reader) {
let solid_entity = collision.collider1;
if let Some(exit) = destrooms.get(solid_entity) {
if let Some(_transform) = transforms.get(solid_entity) {
let position = exit.spawn_point();
*perform_room_exit = Some(PerformRoomExit(*exit, position));
}
}
let solid_entity = collision.collider2;
if let Some(exit) = destrooms.get(solid_entity) {
if let Some(_transform) = transforms.get(solid_entity) {
let position = exit.spawn_point();
*perform_room_exit = Some(PerformRoomExit(*exit, position));
}
}
}
}
} |
mod advanced_functions_and_closures;
mod advanced_traits;
mod advanced_types;
mod unsafe_rust;
fn main() {
println!("===== 19. advanced features ======\n");
unsafe_rust::main();
advanced_traits::main();
advanced_types::main();
advanced_functions_and_closures::main();
}
|
extern crate midi_message;
extern crate rand;
pub mod color;
pub mod color_strip;
pub mod opc_strip;
pub mod midi_light_strip;
pub mod rainbow;
mod effects {
pub mod effect;
pub mod ripple;
pub mod flash;
pub mod blink;
pub mod stream;
pub mod stream_center;
pub mod push;
pub mod river;
pub mod fish;
} |
#![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
use cuda::ffi::driver_types::{cudaStream_t};
use cuda::ffi::library_types::{cudaDataType};
include!(concat!(env!("OUT_DIR"), "/cublas_bind.rs"));
|
use std::fmt::Debug;
fn add_things<T: Debug>(a: T, b: T) {
// a + b
println!("A : {:?} ", a);
}
fn where_display<T>(val: T)
where
T: Debug,
{
println!("Value is {:?}", val);
}
fn main() {
add_things(2, 2);
where_display(9);
}
|
use anymap::AnyMap;
use std::any::TypeId;
use std::collections::HashSet;
#[derive(Debug)]
pub struct Entity {
pub(crate) components: AnyMap,
pub(crate) shape: HashSet<TypeId>,
}
impl Default for Entity {
fn default() -> Self {
Self::new()
}
}
impl Entity {
pub fn new() -> Self {
Self {
components: AnyMap::new(),
shape: HashSet::new(),
}
}
pub fn deregister_component<T: 'static>(&mut self) {
self.components.remove::<T>();
self.shape.remove(&TypeId::of::<T>());
}
fn register_component<T: 'static>(&mut self, value: T) {
self.components.insert::<T>(value);
}
pub fn remove<T: 'static>(&mut self) {
self.deregister_component::<T>()
}
pub fn with<T: 'static>(mut self, value: T) -> Self {
self.shape.insert(TypeId::of::<T>());
self.register_component(value);
self
}
pub fn set<T: 'static>(&mut self, value: T) {
self.components.insert::<T>(value);
}
pub fn get<T: 'static>(&self) -> Option<&T> {
self.components.get::<T>()
}
pub fn get_mut<T: 'static>(&mut self) -> Option<&'static mut T> {
unsafe { std::mem::transmute(self.components.get_mut::<T>()) }
}
pub fn has<A: 'static>(&self) -> bool {
self.components.contains::<A>()
}
}
|
pub use crate::traits::*;
pub use crate::{create_render_core, RenderCoreCreateInfo};
pub use crate::presentationcore::{ApplicationInfo, PresentationBackend, PresentationCore, VRMode};
pub use crate::renderbackend::{Eye, TargetMode, VRTransformations};
// input
pub use crate::input::{
controller::Controller, controlleraxis::ControllerAxis, guidirection::GuiDirection,
mousebutton::MouseButton,
};
// wsi
pub use crate::wsi::windowsystemintegration::{Display, WindowCreateInfo};
pub use sdl2::{controller::Button as ControllerButton, keyboard::Keycode};
pub use utilities::prelude::*;
pub use vulkan_rs::prelude::*;
|
pub fn mean(li: &[i64]) -> f64 {
let sum: i64 = li.iter().sum();
sum as f64 / li.len() as f64
}
use std::cmp::Ord;
pub fn med<T: Ord + Copy>(list: &[T]) -> T {
let mut new_vec = list.to_vec();
new_vec.sort();
new_vec[new_vec.len() / 2]
}
use std::collections::HashMap;
use std::hash::Hash;
fn count<T: Eq + Copy + Hash>(it: &[T]) -> HashMap<T, i64> {
let mut result: HashMap<T, i64> = HashMap::new();
for thing in it {
*result.entry(*thing).or_insert(0) += 1;
}
result
}
pub fn mode<T: Eq + Copy + Hash + Ord>(it: &[T]) -> T {
let counter = count(it);
let mut pairs: Vec<(&T, &i64)> = counter.iter().collect();
pairs.sort_by(|(_, val1), (_, val2)| val1.partial_cmp(val2).unwrap());
let (key, _) = pairs.last().unwrap();
**key
}
use std::collections::HashSet;
use std::iter::FromIterator;
pub fn to_pig_latin(word: &mut String) {
let vowels: HashSet<char> = HashSet::from_iter("aeiou".chars());
if !vowels.contains(&word.char_indices().next().unwrap().1.to_ascii_lowercase()) {
let ch = word.remove(0);
word.push_str(&format!("-{}ay", ch.to_string()));
} else {
word.push_str("-hay");
}
}
fn sorted<T: Ord + Clone>(collection: &[T]) -> Vec<T> {
let mut copy = collection.to_owned();
copy.sort();
copy
}
use regex::Regex;
use std::collections::BTreeMap;
// We use btree and not hashmap to keep the keys sorted.
type Employees = BTreeMap<String, Vec<String>>;
// Instead of printing I return a string with what should be printed.
pub fn process_command(employees: &mut Employees, command: &str) -> Option<String> {
let add_command = Regex::new(r"(?i)add (?P<name>\w+) to (?P<department>\w+)").unwrap();
let list_command = Regex::new(r"(?i)list(?:\s(?P<department>\w+))?").unwrap();
if let Some(add) = add_command.captures(&command.to_ascii_lowercase()) {
employees
.entry(add.name("department").unwrap().as_str().to_owned())
.or_default()
.push(add.name("name").unwrap().as_str().to_owned());
None
} else if let Some(list_match) = list_command.captures(command) {
fn format_department(department: &str, names: &[String]) -> String {
format!("{}: {}", department, sorted(&names).join(", "))
};
println!("{:?}", list_match);
if let Some(department) = list_match.name("department") {
employees
.get(&department.as_str().to_lowercase())
.map(|names| format_department(department.as_str(), names))
} else {
Some(
employees
.iter()
// unpack the tuple becuse I don't know how to starmap
.map(|(department, names)| format_department(department, names))
.collect::<Vec<String>>()
.join("\n"),
)
}
} else {
panic!("Unkown command! AHHHHHH!")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mean_sanity() {
assert_eq!(mean(&vec![1, 2, 3]), 2.0);
assert_eq!(mean(&vec![1, 2]), 1.5);
}
#[test]
fn median_sanity() {
assert_eq!(med(&vec![1, 2, 3]), 2);
assert_eq!(med(&vec![1, 2]), 2);
assert_eq!(med(&vec!["a", "b", "c"]), "b");
}
#[test]
fn mode_sanity() {
assert_eq!(mode(&vec![1, 1, 2, 2, 1, 3]), 1);
assert_eq!(mode(&vec!["a", "b", "b", "c"]), "b")
}
#[test]
fn pig_latin_sanity() {
let mut a = "first".to_owned();
to_pig_latin(&mut a);
assert_eq!(a, "irst-fay");
let mut b = "apple".to_owned();
to_pig_latin(&mut b);
assert_eq!(b, "apple-hay");
}
#[test]
fn add_command() {
let mut employees: Employees = Employees::new();
process_command(&mut employees, "add Susan to State");
process_command(&mut employees, "add John to State");
assert!(employees.get("state").unwrap().iter().any(|e| e == "susan"));
process_command(&mut employees, "add Michael to Finance");
assert!(employees
.get("finance")
.unwrap()
.contains(&"michael".to_owned()));
}
#[test]
fn list_command() {
let mut employees: Employees = Employees::new();
process_command(&mut employees, "add Susan to State");
process_command(&mut employees, "add John to State");
assert_eq!(
process_command(&mut employees, "list"),
Some("state: john, susan".to_owned())
);
process_command(&mut employees, "add Michael to Finance");
assert_eq!(
process_command(&mut employees, "list"),
Some("finance: michael\nstate: john, susan".to_owned())
);
}
#[test]
fn list_department_command() {
let mut employees: Employees = Employees::new();
process_command(&mut employees, "add Susan to State");
process_command(&mut employees, "add John to State");
process_command(&mut employees, "add Michael to Finance");
assert_eq!(
process_command(&mut employees, "list State").map(|st| st.to_lowercase()),
Some("state: john, susan".to_owned())
);
}
}
|
pub const LIFESPAN: isize = 500;
pub const SCREEN_WIDTH: isize = 1200;
pub const SCREEN_HEIGHT: isize = 800;
pub const POPULATION_SIZE: usize = 300;
pub const POPULATION_ORIGIN_X: i32 = SCREEN_WIDTH as i32 / 2;
pub const POPULATION_ORIGIN_Y: i32 = SCREEN_HEIGHT as i32;
|
pub mod delete;
pub mod howto;
pub mod list;
pub mod new;
use colored::*;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Formatter, Result};
#[derive(Serialize, Deserialize)]
pub struct Command {
pub id: usize,
pub command: String,
pub keywords: Vec<String>,
}
impl fmt::Display for Command {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(
f,
"{}: {}\n{}: {}\n{}: {}",
"ID".bold().blue(),
self.id,
"Command".bold().blue(),
self.command,
"Keywords".bold().blue(),
self.keywords.join(" "),
)
}
}
|
struct Thing;
trait Method<T> {
fn method(&self) -> T;
fn mut_method(&mut self) -> T;
}
impl Method<i32> for Thing {
fn method(&self) -> i32 { 0 }
fn mut_method(&mut self) -> i32 { 0 }
}
impl Method<u32> for Thing {
fn method(&self) -> u32 { 0 }
fn mut_method(&mut self) -> u32 { 0 }
}
fn main() {
let thing = Thing;
thing.method();
//~^ ERROR type annotations needed
//~| ERROR type annotations needed
thing.mut_method(); //~ ERROR type annotations needed
}
|
use super::*;
use crate::engine::input::{InputEngine, InputState};
use cvar::IVisit;
use gvfs::filesystem::Filesystem;
use rhai::{
packages::{Package, StandardPackage},
plugin::*,
Dynamic, Engine, Scope, AST,
};
use std::{collections::HashMap, fmt, io::Read, path::PathBuf, str::FromStr};
pub struct ScriptEngine {
vars: HashMap<String, String>,
commands: HashMap<&'static str, (usize, CommandFunction)>,
aliases: HashMap<String, String>,
engine: Engine,
ast: HashMap<String, AST>,
event_send: BroadcastSender<Event>,
event_recv: BroadcastReceiver<Event>,
}
pub struct ScriptError {
source: Option<String>,
line: Option<usize>,
message: String,
}
impl ScriptError {
fn from_line<S: Into<String>>(message: S, line: usize) -> Self {
ScriptError {
source: None,
line: Some(line),
message: message.into(),
}
}
fn from_source<S: Into<String>>(message: S, source: S) -> Self {
ScriptError {
source: Some(source.into()),
line: None,
message: message.into(),
}
}
fn set_source<S: Into<String>>(&mut self, source: S) {
self.source.replace(source.into());
}
}
impl fmt::Display for ScriptError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(source) = &self.source {
write!(
f,
"{}{} | {}",
source,
self.line
.map_or_else(String::new, |line| { format!(":{}", line) }),
self.message
)
} else if self.line.is_none() {
write!(f, "{}", self.message)
} else {
write!(f, ":{} | {}", self.line.unwrap(), self.message)
}
}
}
struct Env<'a> {
aliases: &'a mut HashMap<String, String>,
input: &'a mut InputEngine,
config: &'a mut dyn IVisit,
fs: &'a mut Filesystem,
vars: &'a mut HashMap<String, String>,
engine: &'a mut Engine,
ast: &'a mut HashMap<String, AST>,
world: &'a mut hecs::World,
event_sender: &'a BroadcastSender<Event>,
}
type CommandFunction = fn(&[&str], &mut Env) -> Result<Option<String>, String>;
#[derive(Clone)]
pub struct WorldEnv {
inner: *mut hecs::World,
}
impl ScriptEngine {
pub fn new(
event_send: BroadcastSender<Event>,
event_recv: BroadcastReceiver<Event>,
) -> ScriptEngine {
let mut commands = HashMap::new();
commands.insert("exec", (1, fake_command as CommandFunction));
commands.insert("alias", (2, alias_command as CommandFunction));
commands.insert("get", (1, cvars_get as CommandFunction));
commands.insert("set", (2, cvars_set as CommandFunction));
commands.insert("toggle", (1, cvars_toggle as CommandFunction));
commands.insert("log", (1, log_info as CommandFunction));
commands.insert("warn", (1, log_warn as CommandFunction));
commands.insert("error", (1, log_error as CommandFunction));
commands.insert("bind", (1, bind_key as CommandFunction));
commands.insert("unbind", (1, unbind_key as CommandFunction));
commands.insert("unbindall", (0, unbind_all as CommandFunction));
commands.insert("echo", (0, echo_args as CommandFunction));
commands.insert("exit", (0, exit_game as CommandFunction));
commands.insert("eval", (1, eval_rhai as CommandFunction));
commands.insert("run", (1, run_rhai as CommandFunction));
let mut engine = Engine::new_raw();
engine.on_print(|text| log::info!("{}", text));
engine.on_debug(|text, source, pos| {
if let Some(source) = source {
log::debug!("{}:{:?} | {}", source, pos, text);
} else if pos.is_none() {
log::debug!("{}", text);
} else {
log::debug!("{:?} | {}", pos, text);
}
});
let package = StandardPackage::new().as_shared_module();
engine.register_global_module(package);
engine.register_type_with_name::<WorldEnv>("World");
engine.register_global_module(exported_module!(world_api).into());
ScriptEngine {
vars: HashMap::new(),
commands,
aliases: HashMap::new(),
engine,
ast: HashMap::new(),
event_send,
event_recv,
}
}
pub fn evaluate<S: Into<String>>(
&mut self,
file_name: Option<&str>,
script: S,
input: &mut InputEngine,
config: &mut dyn IVisit,
fs: &mut Filesystem,
world: &mut hecs::World,
) -> Result<(), ScriptError> {
// Reset internal state
self.vars.insert("IFS".to_string(), " ".to_string());
self.vars.insert("NL".to_string(), "\n".to_string());
self.vars.insert("TAB".to_string(), "\t".to_string());
self.vars.insert("SPACE".to_string(), " ".to_string());
for (i, line) in script.into().lines().enumerate() {
let i = i + 1; // files start counting lines with line 1
let mut words: Vec<String> = line
.split_ascii_whitespace()
.take_while(|word| !word.starts_with('#') && !word.starts_with("//"))
.map(|s| {
let mut s = String::from(s);
if s.starts_with('"') && s.ends_with('"') {
s.remove(0);
s.pop();
}
s
})
.collect();
if words.is_empty() {
continue;
}
// skip some Soldat cvar commands
if words[0].starts_with("cl_")
|| words[0].starts_with("r_")
|| words[0].starts_with("snd_")
{
log::trace!("Skipping line {}", i);
// TODO? push these to separate engine modules via event_sender
continue;
}
let mut idx = 0;
let mut assignment = false;
let mut result = None;
if words.len() > 2 && words[1] == "=" {
// variable assignment
assignment = true;
idx = 2;
}
if words.len() <= idx {
return Err(ScriptError::from_line("Command missing.", i));
}
for word in words.iter_mut().skip(idx) {
if word.starts_with('$') {
if let Some(value) = self.vars.get(&word[1..]) {
*word = value.clone();
} else {
return Err(ScriptError::from_line(
format!("Variable unset: {}.", word),
i,
));
}
}
}
let words: Vec<&str> = words.iter().map(String::as_str).collect();
// We already have variable replacements here, so it is possible
// to have command name resolved from variable
let command = words[idx];
idx += 1;
if let Some((min_args, cmd)) = self.commands.get(command) {
if words.len() - idx < *min_args {
return Err(ScriptError::from_line("Not enough arguments.", i));
} else {
let args = &words[idx..];
if command == "exec" {
if args.is_empty() || !args[0].ends_with(".cfg") {
return Err(ScriptError::from_line(
"Script must end with .cfg extension.".to_string(),
i,
));
}
let path = PathBuf::from(args[0]);
let path = if path.is_absolute() {
path
} else if let Some(current) = file_name {
let mut base = PathBuf::from(current);
base.pop();
base.push(path);
base
} else {
return Err(ScriptError::from_line(
"Relative exec not possible in string evaluate.".to_string(),
i,
));
};
let path = path.to_string_lossy();
log::info!("Executing {}", path);
if let Err(err) = self.evaluate_file(path, input, config, fs, world) {
return Err(err);
}
} else {
match cmd(
args,
&mut Env {
aliases: &mut self.aliases,
config,
fs,
input,
vars: &mut self.vars,
engine: &mut self.engine,
ast: &mut self.ast,
world,
event_sender: &self.event_send,
},
) {
Ok(res) => result = res,
Err(err) => {
return Err(ScriptError::from_line(err, i));
}
}
}
}
} else {
return Err(ScriptError::from_line(
format!("Unknown command: {:?}.", command),
i,
));
}
if assignment {
if let Some(result) = result {
self.vars.insert(words[0].to_string(), result);
} else {
self.vars.remove(words[0]);
}
} else if result.is_some() {
return Err(ScriptError::from_line("Unused result.", i));
}
}
Ok(())
}
pub fn evaluate_file<S: AsRef<str>>(
&mut self,
file_name: S,
input: &mut InputEngine,
config: &mut dyn IVisit,
fs: &mut Filesystem,
world: &mut hecs::World,
) -> Result<(), ScriptError> {
let file_name = file_name.as_ref();
let mut file = fs
.open(file_name)
.map_err(|err| ScriptError::from_source(err.to_string(), file_name.to_string()))?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)
.map_err(|err| ScriptError::from_source(err.to_string(), file_name.to_string()))?;
self.evaluate(
Some(file_name),
String::from_utf8_lossy(&buffer).as_ref(),
input,
config,
fs,
world,
)
.map_err(|mut err| {
if err.source.is_none() {
err.set_source(file_name)
};
err
})
}
pub(crate) fn consume_events(
&mut self,
input: &mut InputEngine,
config: &mut dyn IVisit,
fs: &mut Filesystem,
world: &mut hecs::World,
) {
let mut commands = Vec::new();
for event in &self.event_recv {
log::trace!("ScriptEngine Event consumer got {:?}", event);
if let Event::Command(script) = event {
commands.push(script);
}
}
for command in commands {
if let Err(err) = self.evaluate(None, command, input, config, fs, world) {
log::error!("Error evaluating Command Event: {}", err);
}
}
}
pub(crate) fn drain_events(&mut self) {
for event in &self.event_recv {
if let Event::Command(script) = event {
log::error!("Unhandled Command Event: {}\nForgot to call ScriptEngine::consume_events() in Game::update()?", script);
}
}
}
}
fn fake_command(_args: &[&str], _env: &mut Env) -> Result<Option<String>, String> {
Err("Called fake command.".to_string())
}
fn alias_command(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
env.aliases.insert(args[0].to_string(), args[1..].join(" "));
Ok(None)
}
fn cvars_get(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
let var = args[0];
if var.starts_with("--") {
match var {
"--dump" => {
let mut dump = Vec::new();
cvar::console::walk(env.config, |path, node| {
if let cvar::Node::Prop(prop) = node.as_node() {
dump.push(format!("{} = `{}`", path, prop.get()));
}
});
Ok(Some(dump.join("\n")))
}
_ => Err(format!("Unknown option: {:?}.", var)),
}
} else {
Ok(cvar::console::get(env.config, args[0]))
}
}
fn cvars_set(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
match cvar::console::set(env.config, args[0], args[1]).unwrap() {
true => {
if let Err(err) = env.event_sender.try_send(Event::ConfigChanged) {
log::error!("Cannot send ConfigChanged Event: {}", err);
}
Ok(None)
}
false => Err("No such cvar.".to_string()),
}
}
fn cvars_toggle(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
let mut output = Err("No such cvar.".to_string());
cvar::console::find(env.config, args[0], |node| {
if let cvar::Node::Prop(prop) = node.as_node() {
match prop.get().as_str() {
"true" => {
if prop.set("false").is_ok() {
output = Ok(None);
}
}
"false" => {
if prop.set("true").is_ok() {
output = Ok(None);
}
}
_ => {
output = Err("Value of cvar is not boolean".to_string());
}
}
}
});
if output.is_ok() {
if let Err(err) = env.event_sender.try_send(Event::ConfigChanged) {
log::error!("Cannot send ConfigChanged Event: {}", err);
}
}
output
}
fn join_args(args: &[&str], env: &mut Env) -> String {
args.join(env.vars.get("IFS").unwrap_or(&"".to_string()))
}
fn log_info(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
log::info!("{}", join_args(args, env));
Ok(None)
}
fn log_error(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
log::error!("{}", join_args(args, env));
Ok(None)
}
fn log_warn(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
log::warn!("{}", join_args(args, env));
Ok(None)
}
fn bind_key(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
let key = args[0].to_ascii_lowercase();
let mut mods = KeyMods::default();
let kb = if let Some(button) = key.strip_prefix("mouse") {
KeyBind::Mouse(match button {
"1" => mq::MouseButton::Left,
"2" => mq::MouseButton::Middle,
"3" => mq::MouseButton::Right,
_ => return Err("Unknown mouse button.".to_string()),
})
} else if let Some(wheel) = key.strip_prefix("mwheel") {
KeyBind::Wheel(match wheel {
"up" => Direction::Up,
"down" => Direction::Down,
"left" => Direction::Left,
"right" => Direction::Right,
_ => return Err("Unknown mouse wheel direction.".to_string()),
})
} else {
let mut rest = "";
for key in key.split('+') {
match key {
"shift" => mods.shift = true,
"ctrl" => mods.ctrl = true,
"alt" => mods.alt = true,
k => {
rest = k;
break;
}
}
}
KeyBind::from_str(rest).map_err(|_err| "Unknown keycode.".to_string())?
};
if args[1].starts_with('+') {
if let Ok(state) = InputState::from_str(&args[1][1..]) {
env.input.bind_key(kb, mods, state);
return Ok(None);
}
Err("Unknown input state.".to_string())
} else {
let mut script = args[1..].join(" ");
if script.starts_with('"') && script.ends_with('"') {
script.remove(0);
script.pop();
}
env.input.bind_script(kb, mods, script);
Ok(None)
}
}
fn unbind_key(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
match KeyBind::from_str(args[0]) {
Ok(kc) => {
env.input.unbind_key(kc);
Ok(None)
}
Err(_) => Err("Unknown keycode.".to_string()),
}
}
fn unbind_all(_args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
env.input.unbind_all();
Ok(None)
}
fn echo_args(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
if args.is_empty() {
Ok(None)
} else {
Ok(Some(join_args(args, env)))
}
}
fn exit_game(_args: &[&str], _env: &mut Env) -> Result<Option<String>, String> {
if cfg!(debug_assertions) {
log::info!("Script exit");
std::process::abort();
} else {
log::warn!("Attempted script exit!");
}
Ok(None)
}
fn eval_rhai(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
let res = env
.engine
.eval_expression::<Dynamic>(args.join(" ").as_str())
.map_err(|err| {
log::error!("Failed to eval: {:?}", err);
"Failed to eval.".to_string()
})?;
Ok(Some(res.to_string()))
}
fn run_rhai(args: &[&str], env: &mut Env) -> Result<Option<String>, String> {
let script = args[0];
let ast = if let Some(ast) = env.ast.get(script) {
ast
} else {
if !script.ends_with(".rhai") {
return Err("Script must end with .rhai extension.".to_string());
}
let mut file = env.fs.open(script).map_err(|err| err.to_string())?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)
.map_err(|err| err.to_string())?;
let mut ast = env
.engine
.compile(String::from_utf8_lossy(&buffer).as_ref())
.map_err(|err| format!("Failed to compile {}: {}", script, err))?;
ast.set_source(script);
env.ast.insert(script.to_string(), ast);
env.ast.get(script).unwrap()
};
let mut scope = Scope::new();
scope.push_constant("World", WorldEnv::new(env.world));
env.engine
.consume_ast_with_scope(&mut scope, ast)
.map_err(|err| format!("Error running {}: {}", script, err))?;
Ok(None)
}
impl WorldEnv {
fn new(world: &mut hecs::World) -> Self {
WorldEnv { inner: world }
}
fn len(&self) -> i32 {
unsafe { self.inner.as_ref() }.unwrap().len() as i32
}
}
#[export_module]
mod world_api {
#[rhai_fn(get = "len", pure)]
pub fn get_len(world: &mut WorldEnv) -> i32 {
world.len()
}
}
|
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
// submodules
mod errors;
mod input;
mod local_search;
use input::{PlanningData, Player};
/// The command line options that can be given to this application.
#[derive(Debug, StructOpt)]
#[structopt(
name = "match-planner",
about = "A planning application for assigning players to matches."
)]
struct Opt {
/// Input file, stdin if not present
#[structopt(short = "i", long = "input", parse(from_os_str))]
input: Option<PathBuf>,
/// Output file, stdout if not present
#[structopt(short = "o", long = "output", parse(from_os_str))]
output: Option<PathBuf>,
/// Previous plannings that should be continued
#[structopt(short = "p", long = "past", parse(from_os_str))]
past: Vec<PathBuf>,
/// Whether to plan double or single matches.
#[structopt(short, long)]
mode: local_search::Mode,
/// Quiet mode, do not print anything to stderr
#[structopt(short = "q", long = "quiet")]
quiet: bool,
}
fn main() -> ! {
let opt = Opt::from_args();
match run(opt) {
Err(err) => {
eprintln!("{}", err);
std::process::exit(1)
}
Ok(_) => std::process::exit(0),
}
}
fn run(opt: Opt) -> errors::Result<()> {
let input = match opt.input {
None => PlanningData::load(std::io::stdin())?,
Some(file_name) => {
let file = File::open(&file_name)?;
PlanningData::load(file)?
}
};
let mut log_out: Box<dyn Write> = if opt.quiet {
Box::new(NullWrite)
} else {
Box::new(std::io::stderr())
};
// Setup planning constraints
let availability = make_availability_table(&input);
let mode = opt.mode;
let past_match_table = load_past_matches(opt.past.iter(), mode, &input.players())?;
writeln!(log_out, "Number of players: {}", input.players().len())?;
writeln!(log_out, "Number of matches: {}", input.match_count())?;
writeln!(
log_out,
"Number of past matches: {}",
past_match_table.match_count()
)?;
writeln!(
log_out,
"--------------------------------------------------"
)?;
let solution = local_search::iterated_local_search(&past_match_table, &availability, mode);
match opt.output {
None => print_solution(std::io::stdout(), input.players(), &solution)?,
Some(file_name) => {
let file = File::create(&file_name)?;
print_solution(file, input.players(), &solution)?;
}
}
Ok(())
}
fn load_past_matches<P: AsRef<Path>, I: Iterator<Item = P>>(
previous_match_files: I,
mode: local_search::Mode,
players: &[Player],
) -> errors::Result<local_search::MatchTable> {
let mut past_matches = Vec::new();
for previous_file in previous_match_files {
read_previous_file_into(previous_file.as_ref(), mode, players, &mut past_matches)?;
}
let table = if past_matches.is_empty() {
local_search::MatchTable::new(0, players.len())
} else {
let past_match_table = {
let views: Vec<_> = past_matches
.iter()
.map(|row| row.view().into_shape((1, players.len())).unwrap())
.collect();
ndarray::stack(ndarray::Axis(0), &views).unwrap()
};
local_search::MatchTable::from_table(past_match_table)
};
Ok(table)
}
fn read_previous_file_into(
filename: &Path,
mode: local_search::Mode,
players: &[Player],
rows: &mut Vec<ndarray::Array1<bool>>,
) -> errors::Result<()> {
let mut reader = csv::ReaderBuilder::new()
.delimiter(b'\t')
.has_headers(true)
.trim(csv::Trim::All)
.from_path(filename)?;
// Headers must match
if !reader
.headers()?
.iter()
.eq(players.iter().map(Player::name))
{
return Err(errors::Error::InvalidTimetable {
file: filename.to_path_buf(),
line: 1,
error: errors::TimetableError::PlayerMismatch,
});
}
for (record_num, record) in reader.into_records().enumerate() {
use std::iter::FromIterator;
// find the ones in the row
let row = ndarray::Array::from_iter(record?.iter().map(|column| column == "1"));
let num_players: usize = row.iter().map(|playing| *playing as usize).sum();
if num_players <= mode.max_players() {
rows.push(row);
} else {
return Err(errors::Error::InvalidTimetable {
file: filename.to_path_buf(),
line: record_num + 2,
error: errors::TimetableError::InvalidPlayerCount,
});
}
}
Ok(())
}
/// Build the availability table used for local search from the parsed inpput
fn make_availability_table(input: &PlanningData) -> local_search::AvailabilityTable {
let mut availability =
ndarray::Array::from_elem((input.match_count(), input.players().len()), false);
for (player_index, player) in input.players().iter().enumerate() {
for (match_index, available) in player.availability().iter().enumerate() {
availability[(match_index, player_index)] = *available;
}
}
local_search::AvailabilityTable::new(availability)
}
fn print_solution<W: Write>(
out: W,
players: &[Player],
assignment: &local_search::MatchTable,
) -> errors::Result<()> {
let mut writer = csv::WriterBuilder::new().delimiter(b'\t').from_writer(out);
// Header, consists of the player names
writer.write_record(players.iter().map(|p| p.name()))?;
// Rows, one for each match day. Contains a 1 in the columns of the two players playing on that day.
for match_index in (0..assignment.match_count()).map(local_search::Match) {
writer.write_record(
(0..assignment.player_count())
.map(local_search::Player)
.map(|player_index| {
if assignment.is_playing(match_index, player_index) {
"1"
} else {
""
}
}),
)?;
}
Ok(())
}
/// Implements Write but doesn't write anything.
struct NullWrite;
impl Write for NullWrite {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
|
//! This is a seperate file where the Errors for the filesystem have been defined
use thiserror::Error;
use cplfs_api::error_given::APIError;
use std::fmt;
use std::fmt::Formatter;
#[derive(Error, Debug)]
/// This structure defines the errors for the filestructure
/// All the potential errors are grouped here
pub enum FileSystemError {
/// This error is raised whe the given superblock is invalid
InvalidSuperBlock(),
/// This error is a conversion from an API error and is raised when there occurs when interacting with a Device
DeviceAPIError(#[from] APIError),
/// This error is raised whenever a Device is not set and we try to reach for the Devide
/// Remember that the Device field in our filesystem is optional
DeviceNotSet(),
/// This error can be raised whenever allocating a block/inode/dir fails
AllocationError(),
/// This error will be raised when the to be freed block is allreads free
AllreadyFreeError(),
/// Error when de index is out of bound in a block
IndexOutOfBounds(),
/// Raised when the dir name is not valid
InvalidDirname(),
/// Raised when a problem occurs when free an inode
INodeNotFreeable(),
/// Raised when we are interacting with an inode that should be an Directory type but is not.
INodeNotADirectory(),
/// Raised whenever the inode on the disk is not up to date (not used)
INodeNotFoundNotUpToDate(),
/// When a directory has not been found when earching with its name.
DirectoryNotFound(),
///Raised when reading a part of a block will result in an error
ReadError(),
}
impl fmt::Display for FileSystemError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self{
FileSystemError::InvalidSuperBlock() =>
write!(f,"Invalid superblock"),
FileSystemError::DeviceAPIError(api_error) =>
write!(f,"Device API error"),
FileSystemError::DeviceNotSet() =>
write!(f,"FileSystem does not have a device set"),
FileSystemError::AllocationError() =>
write!(f,"No free room was found to allocate!"),
FileSystemError::AllreadyFreeError() =>
write!(f,"Cannot free the block at the requested index, it is already free"),
FileSystemError::IndexOutOfBounds() =>
write!(f,"Index Out of bounds!"),
FileSystemError::INodeNotFreeable() =>
write!(f,"Inode is not freeable, it still has links in the filesystem"),
FileSystemError::InvalidDirname() =>
write!(f,"The Provided directory name is not valid or too long or does contain illegal characters"),
FileSystemError::INodeNotADirectory() =>
write!(f,"Inode not a directory"),
FileSystemError::INodeNotFoundNotUpToDate() =>
write!(f,"Inode not up to date with the one in the filesystem"),
FileSystemError::DirectoryNotFound() =>
write!(f,"Directory not found in the filesystem"),
FileSystemError::ReadError() =>
write!(f,"Something went wrong reading a Block/Inode")
}
}
}
|
#[doc = "Reader of register CONFRN4"]
pub type R = crate::R<u32, super::CONFRN4>;
#[doc = "Writer for register CONFRN4"]
pub type W = crate::W<u32, super::CONFRN4>;
#[doc = "Register CONFRN4 `reset()`'s with value 0"]
impl crate::ResetValue for super::CONFRN4 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `HD`"]
pub type HD_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HD`"]
pub struct HD_W<'a> {
w: &'a mut W,
}
impl<'a> HD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `HA`"]
pub type HA_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HA`"]
pub struct HA_W<'a> {
w: &'a mut W,
}
impl<'a> HA_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `QT`"]
pub type QT_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `QT`"]
pub struct QT_W<'a> {
w: &'a mut W,
}
impl<'a> QT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2);
self.w
}
}
#[doc = "Reader of field `NB`"]
pub type NB_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `NB`"]
pub struct NB_W<'a> {
w: &'a mut W,
}
impl<'a> NB_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4);
self.w
}
}
#[doc = "Reader of field `VSF`"]
pub type VSF_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `VSF`"]
pub struct VSF_W<'a> {
w: &'a mut W,
}
impl<'a> VSF_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Reader of field `HSF`"]
pub type HSF_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `HSF`"]
pub struct HSF_W<'a> {
w: &'a mut W,
}
impl<'a> HSF_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12);
self.w
}
}
impl R {
#[doc = "Bit 0 - Huffman DC Selects the Huffman table for encoding the DC coefficients."]
#[inline(always)]
pub fn hd(&self) -> HD_R {
HD_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Huffman AC Selects the Huffman table for encoding the AC coefficients."]
#[inline(always)]
pub fn ha(&self) -> HA_R {
HA_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bits 2:3 - Quantization Table Selects quantization table associated with a color component."]
#[inline(always)]
pub fn qt(&self) -> QT_R {
QT_R::new(((self.bits >> 2) & 0x03) as u8)
}
#[doc = "Bits 4:7 - Number of Block Number of data units minus 1 that belong to a particular color in the MCU."]
#[inline(always)]
pub fn nb(&self) -> NB_R {
NB_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:11 - Vertical Sampling Factor Vertical sampling factor for component i."]
#[inline(always)]
pub fn vsf(&self) -> VSF_R {
VSF_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - Horizontal Sampling Factor Horizontal sampling factor for component i."]
#[inline(always)]
pub fn hsf(&self) -> HSF_R {
HSF_R::new(((self.bits >> 12) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bit 0 - Huffman DC Selects the Huffman table for encoding the DC coefficients."]
#[inline(always)]
pub fn hd(&mut self) -> HD_W {
HD_W { w: self }
}
#[doc = "Bit 1 - Huffman AC Selects the Huffman table for encoding the AC coefficients."]
#[inline(always)]
pub fn ha(&mut self) -> HA_W {
HA_W { w: self }
}
#[doc = "Bits 2:3 - Quantization Table Selects quantization table associated with a color component."]
#[inline(always)]
pub fn qt(&mut self) -> QT_W {
QT_W { w: self }
}
#[doc = "Bits 4:7 - Number of Block Number of data units minus 1 that belong to a particular color in the MCU."]
#[inline(always)]
pub fn nb(&mut self) -> NB_W {
NB_W { w: self }
}
#[doc = "Bits 8:11 - Vertical Sampling Factor Vertical sampling factor for component i."]
#[inline(always)]
pub fn vsf(&mut self) -> VSF_W {
VSF_W { w: self }
}
#[doc = "Bits 12:15 - Horizontal Sampling Factor Horizontal sampling factor for component i."]
#[inline(always)]
pub fn hsf(&mut self) -> HSF_W {
HSF_W { w: self }
}
}
|
//! Creates the nlprule binaries from a *build directory*. Usage information in /build/README.md.
use fs_err as fs;
use fs::File;
use std::{
hash::{Hash, Hasher},
io::{self, BufReader, BufWriter},
num::ParseIntError,
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
};
use crate::{
rules::Rules,
tokenizer::{chunk::Chunker, multiword::MultiwordTagger, tag::Tagger, Tokenizer},
types::DefaultHasher,
};
use log::info;
use self::parse_structure::{BuildInfo, RegexCache};
use thiserror::Error;
mod impls;
mod parse_structure;
mod structure;
mod utils;
struct BuildFilePaths {
lang_code_path: PathBuf,
tag_paths: Vec<PathBuf>,
tag_remove_paths: Vec<PathBuf>,
chunker_path: PathBuf,
disambiguation_path: PathBuf,
grammar_path: PathBuf,
multiword_tag_path: PathBuf,
common_words_path: PathBuf,
regex_cache_path: PathBuf,
srx_path: PathBuf,
}
impl BuildFilePaths {
fn new<P: AsRef<Path>>(build_dir: P) -> Self {
let p = build_dir.as_ref();
BuildFilePaths {
lang_code_path: p.join("lang_code.txt"),
tag_paths: vec![p.join("tags/output.dump"), p.join("tags/added.txt")],
tag_remove_paths: vec![p.join("tags/removed.txt")],
chunker_path: p.join("chunker.json"),
disambiguation_path: p.join("disambiguation.xml"),
grammar_path: p.join("grammar.xml"),
multiword_tag_path: p.join("tags/multiwords.txt"),
common_words_path: p.join("common.txt"),
regex_cache_path: p.join("regex_cache.bin"),
srx_path: p.join("segment.srx"),
}
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error("input/output error")]
Io(#[from] std::io::Error),
#[error("serialization error")]
Serialization(#[from] bincode::Error),
#[error("JSON deserialization error")]
JSON(#[from] serde_json::Error),
#[error("error loading SRX")]
SRX(#[from] srx::Error),
#[error("unknown error")]
Other(#[from] Box<dyn std::error::Error>),
#[error("config does not exist for '{lang_code}'")]
ConfigDoesNotExist { lang_code: String },
#[error("regex compilation error: {0}")]
Regex(#[from] onig::Error),
#[error("unexpected condition: {0}")]
Unexpected(String),
#[error("feature not implemented: {0}")]
Unimplemented(String),
#[error("error parsing to integer: {0}")]
ParseError(#[from] ParseIntError),
}
pub fn compile(
build_dir: impl AsRef<Path>,
mut rules_dest: impl io::Write,
mut tokenizer_dest: impl io::Write,
) -> Result<(), Error> {
let paths = BuildFilePaths::new(&build_dir);
let lang_code = fs::read_to_string(paths.lang_code_path)?;
info!(
"Reading common words from {}.",
paths.common_words_path.display()
);
let common_words = fs::read_to_string(paths.common_words_path)?
.lines()
.map(|x| x.to_string())
.collect();
let tokenizer_options =
utils::tokenizer_options(&lang_code).ok_or_else(|| Error::ConfigDoesNotExist {
lang_code: lang_code.clone(),
})?;
let rules_options =
utils::rules_options(&lang_code).ok_or_else(|| Error::ConfigDoesNotExist {
lang_code: lang_code.clone(),
})?;
info!("Creating tagger.");
let tagger = Tagger::from_dumps(
&paths.tag_paths,
&paths.tag_remove_paths,
&tokenizer_options.extra_tags,
&common_words,
)?;
let mut hasher = DefaultHasher::default();
let mut word_store = tagger.word_store().iter().collect::<Vec<_>>();
word_store.sort_by(|a, b| a.1.cmp(b.1));
word_store.hash(&mut hasher);
let word_store_hash = hasher.finish();
let regex_cache = if let Ok(file) = File::open(&paths.regex_cache_path) {
let cache: RegexCache = bincode::deserialize_from(BufReader::new(file))?;
if *cache.word_hash() == word_store_hash {
info!(
"Regex cache at {} is valid.",
paths.regex_cache_path.display()
);
cache
} else {
info!("Regex cache was provided but is not valid. Rebuilding.");
RegexCache::new(word_store_hash)
}
} else {
info!(
"No regex cache provided. Building and writing to {}.",
paths.regex_cache_path.display()
);
RegexCache::new(word_store_hash)
};
let mut build_info = BuildInfo::new(Arc::new(tagger), regex_cache);
let chunker = if paths.chunker_path.exists() {
info!("{} exists. Building chunker.", paths.chunker_path.display());
let reader = BufReader::new(File::open(paths.chunker_path)?);
let chunker = Chunker::from_json(reader)?;
Some(chunker)
} else {
None
};
let multiword_tagger = if paths.multiword_tag_path.exists() {
info!(
"{} exists. Building multiword tagger.",
paths.multiword_tag_path.display()
);
Some(MultiwordTagger::from_dump(
paths.multiword_tag_path,
&build_info,
)?)
} else {
None
};
info!("Creating tokenizer.");
let tokenizer = Tokenizer::from_xml(
&paths.disambiguation_path,
&mut build_info,
chunker,
multiword_tagger,
srx::SRX::from_str(&fs::read_to_string(&paths.srx_path)?)?.language_rules(lang_code),
tokenizer_options,
)?;
bincode::serialize_into(&mut tokenizer_dest, &tokenizer)?;
info!("Creating grammar rules.");
let rules = Rules::from_xml(&paths.grammar_path, &mut build_info, &rules_options);
bincode::serialize_into(&mut rules_dest, &rules)?;
// we need to write the regex cache after building the rules, otherwise it isn't fully populated
let f = BufWriter::new(File::create(&paths.regex_cache_path)?);
bincode::serialize_into(f, build_info.mut_regex_cache())?;
Ok(())
}
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use arrow_flight::utils::batches_to_flight_data;
use arrow_flight::FlightData;
use async_stream::stream;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::DataBlock;
use common_expression::DataSchema;
use common_sql::plans::Plan;
use common_sql::PlanExtras;
use common_sql::Planner;
use common_storages_fuse::TableContext;
use futures_util::StreamExt;
use tonic::Status;
use super::status;
use super::DoGetStream;
use super::FlightSqlServiceImpl;
use crate::interpreters::InterpreterFactory;
use crate::sessions::Session;
impl FlightSqlServiceImpl {
pub(super) fn block_to_flight_data(
block: DataBlock,
data_schema: &DataSchema,
) -> Result<Vec<FlightData>> {
let batch = block
.to_record_batch(data_schema)
.map_err(|e| ErrorCode::Internal(format!("{e:?}")))?;
let schema = (*batch.schema()).clone();
let batches = vec![batch];
batches_to_flight_data(schema, batches).map_err(|e| ErrorCode::Internal(format!("{e:?}")))
}
pub(super) async fn plan_sql(
&self,
session: &Arc<Session>,
query: &str,
) -> Result<(Plan, PlanExtras)> {
let context = session
.create_query_context()
.await
.map_err(|e| status!("Could not create_query_context", e))?;
let mut planner = Planner::new(context.clone());
planner.plan_sql(query).await
}
pub(super) async fn execute_plan(
&self,
session: Arc<Session>,
plan: &Plan,
plan_extras: &PlanExtras,
) -> Result<DoGetStream> {
let context = session
.create_query_context()
.await
.map_err(|e| status!("Could not create_query_context", e))?;
context.attach_query_str(plan.to_string(), plan_extras.stament.to_mask_sql());
let interpreter = InterpreterFactory::get(context.clone(), plan).await?;
let data_schema = interpreter.schema();
let mut data_stream = interpreter.execute(context.clone()).await?;
let stream = stream! {
while let Some(block) = data_stream.next().await {
match block {
Ok(block) => {
match Self::block_to_flight_data(block, &data_schema) {
Ok(data) => {
for d in data {
yield Ok(d)
}
}
Err(err) => {
yield Err(status!("Could not convert batches", err))
}
}
}
Err(err) => {
yield Err(status!("Could not convert batches", err))
}
};
}
// to hold session ref until stream is all consumed
let _ = session.get_id();
};
Ok(Box::pin(stream))
}
}
|
//! A module providing a CLI command to inspect the contents of a WAL file.
use std::{io::Write, ops::RangeInclusive, path::PathBuf};
use itertools::Itertools;
use wal::SequencedWalOp;
use super::Error;
#[derive(Debug, clap::Parser)]
pub struct Config {
/// The path to the input WAL file
#[clap(value_parser)]
input: PathBuf,
/// An optional range of sequence numbers to restrict the inspection to, in
/// the format "%d-%d". Only entries that have a sequence number falling
/// within the range (inclusive) will be displayed
#[clap(long, short, value_parser = parse_sequence_number_range)]
sequence_number_range: Option<RangeInclusive<u64>>,
}
fn parse_sequence_number_range(s: &str) -> Result<RangeInclusive<u64>, String> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("sequence number range provided does not use format <START>-<END>".to_string());
}
let min = parts[0]
.parse()
.map_err(|_| format!("{} isn't a valid sequence number", parts[0]))?;
let max = parts[1]
.parse()
.map_err(|_| format!("{} isn't a valid sequence number", parts[1]))?;
if max < min {
Err(format!(
"invalid sequence number range provided, {max} is less than {min}"
))
} else {
Ok(RangeInclusive::new(min, max))
}
}
pub fn command(config: Config) -> Result<(), Error> {
let reader = wal::ClosedSegmentFileReader::from_path(&config.input)
.map_err(Error::UnableToReadWalFile)?;
inspect(config.sequence_number_range, &mut std::io::stdout(), reader)
}
fn inspect<W, R>(
sequence_number_range: Option<RangeInclusive<u64>>,
output: &mut W,
reader: R,
) -> Result<(), Error>
where
W: Write,
R: Iterator<Item = Result<Vec<SequencedWalOp>, wal::Error>>,
{
let mut inspect_errors = Vec::<wal::Error>::new();
let formatter = reader
.flatten_ok()
.filter_ok(|op| {
sequence_number_range.as_ref().map_or(true, |range| {
op.table_write_sequence_numbers
.values()
.any(|seq| range.contains(seq))
})
})
.format_with(",\n", |op, f| match op {
Ok(op) => f(&format_args!("{:#?}", op)),
Err(e) => {
let err_string = e.to_string();
inspect_errors.push(e);
f(&err_string)
}
});
let result = writeln!(output, "{}", formatter);
if inspect_errors.is_empty() {
result.map_err(Error::IoFailure)
} else {
Err(Error::IncompleteInspection {
sources: inspect_errors,
})
}
}
#[cfg(test)]
mod tests {
use data_types::TableId;
use generated_types::influxdata::iox::wal::v1::sequenced_wal_op::Op as WalOp;
use proptest::{prelude::*, prop_assert};
use super::*;
fn arbitrary_sequence_wal_op(seq_number: u64) -> SequencedWalOp {
SequencedWalOp {
table_write_sequence_numbers: [(TableId::new(0), seq_number)].into(),
op: WalOp::Write(Default::default()),
}
}
#[test]
fn test_range_filters_operations() {
let mut sink = Vec::<u8>::new();
inspect(
Some(RangeInclusive::new(2, 3)),
&mut sink,
[
Ok(vec![
arbitrary_sequence_wal_op(1),
arbitrary_sequence_wal_op(2),
]),
Ok(vec![
arbitrary_sequence_wal_op(3),
arbitrary_sequence_wal_op(4),
arbitrary_sequence_wal_op(5),
]),
]
.into_iter(),
)
.expect("should inspect entries given without error");
let results = String::from_utf8(sink).expect("failed to recover string from write sink");
// Expect two operations inspected, with the appropriate sequence numbers
assert_eq!(results.matches("SequencedWalOp").count(), 2);
// Strip the whitespace before checking the output
let results: String = results.chars().filter(|c| !c.is_whitespace()).collect();
assert_eq!(
results
.matches("table_write_sequence_numbers:{TableId(0,):2,},")
.count(),
1
);
assert_eq!(
results
.matches("table_write_sequence_numbers:{TableId(0,):3,},")
.count(),
1
);
}
proptest! {
#[test]
fn test_sequence_number_range_parsing(a in any::<u64>(), b in any::<u64>()) {
let input = format!("{}-{}", a, b);
match parse_sequence_number_range(input.as_str()) {
Ok(_) => prop_assert!(a <= b),
Err(_) => prop_assert!(a > b),
}
}
}
}
|
/*
@TODO:
+ move logic to separate module/lib
+ move URL building to separate struct
- accept command line arguments
*/
extern crate getopts;
extern crate rustc_serialize;
#[allow(unused_imports)]
use self::rustc_serialize::json;
#[allow(unused_imports)]
use self::rustc_serialize::json::Json;
#[allow(unused_imports)]
use self::getopts::Options;
use std::env;
use coin_api::CoinApi;
mod parse;
mod coin_api;
static COIN_LOGIN: &'static str = "";
static COIN_PASSWORD: &'static str = "";
fn main() {
let args: Vec<String> = env::args().collect();
println!("args: {:?}", args);
//let unwrapped_args: Vec<&str> = args.iter().map(|& ref x| println!("arg: {:?}", x));
enum ParsingState {
Empty,
ExpectLogin,
ExpectPassword,
ExpectInputFile
}
let mut state: ParsingState = ParsingState::Empty;
let mut login: &str = "";
let mut password: &str = "";
let mut input_file_path: &str = "";
for arg in args.iter() {
match arg.as_ref() {
"-l" => {
state = ParsingState::ExpectLogin;
println!("state: login");
},
"-p" => {
state = ParsingState::ExpectPassword;
println!("state: password");
}
"-i" => {
state = ParsingState::ExpectInputFile;
println!("state: input file");
}
value @ _ => {
match state {
ParsingState::ExpectLogin => {
state = ParsingState::Empty;
login = value;
}
ParsingState::ExpectPassword => {
state = ParsingState::Empty;
password = value;
}
ParsingState::ExpectInputFile => {
state = ParsingState::Empty;
input_file_path = value;
}
ParsingState::Empty => {
println!("Skipping: {}", value)
}
}
}
}
}
// Handling login
if login.len() > 0 && password.len() > 0 {
let mut coin_api = CoinApi::new(login, password);
coin_api.login();
// Printing stats
let categories_count = coin_api.categories_count();
let expense_count = coin_api.expenses_count();
println!("Categories: {}", categories_count);
println!("Expenses: {}", expense_count);
}
// Handling input
let mut fake_coin_api = CoinApi::new(COIN_LOGIN, COIN_PASSWORD);
if input_file_path.len() > 0 {
println!("Got path: {}", input_file_path);
let expenses = fake_coin_api.parse_file(input_file_path);
println!("Parsed {} expenses", expenses.len());
}
}
|
use cortex_m::interrupt::free;
use heapless::{ArrayLength, Vec};
pub fn get_current_ticks() -> u32 {
free(|cs| {
let mut data = crate::SYSTEM_DATA.borrow(cs).borrow_mut();
data.get_mut().ticks_since_reset
})
}
pub fn uart_buffer_push(c: u8) {
free(|cs| {
let mut buffer = crate::UART_BUFFER.borrow(cs).borrow_mut();
buffer.push((c & 0xff) as u8);
});
}
pub fn uart_buffer_pop<'t, N>() -> Vec<u8, N>
where
N: ArrayLength<u8>,
{
free(|cs| {
let mut input_buffer = crate::UART_BUFFER.borrow(cs).borrow_mut();
input_buffer.by_ref().take(9).collect()
})
}
|
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Struct and enum definitions of values in the XKCD API model.
//!
//! For more information, see [XKCD's API
//! documentation](https://xkcd.com/json.html).
use serde::Deserialize;
use serde::de::{self, Deserializer};
use std::fmt::Display;
use std::str::FromStr;
use url::Url;
use url_serde;
/// `XkcdResponse` is the outer wrapper for all results from the XKCD API query.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct XkcdResponse {
/// The month the comic was published in, represented as an integer from 1
/// to 12.
#[serde(deserialize_with = "de_from_str")]
pub month: u8,
/// The number/ID of the comic.
pub num: u32,
/// The URL in the anchor tag of the hyperlink surrounding the image, if the
/// image is a hyperlinked one.
pub link: String,
/// The year the comic was published in.
#[serde(deserialize_with = "de_from_str")]
pub year: u32,
/// News or updates regarding the comic.
pub news: String,
/// A plain ASCII representation of the title.
pub safe_title: String,
/// A transcript of the text of the comic.
pub transcript: String,
/// Alt text for the comic.
pub alt: String,
/// A link to the comic image.
#[serde(deserialize_with = "url_serde::deserialize")]
pub img: Url,
/// The title of the comic.
pub title: String,
/// The day of the month the comic was published on.
#[serde(deserialize_with = "de_from_str")]
pub day: u8,
}
fn de_from_str<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where D: Deserializer<'de>,
T: FromStr,
T::Err: Display,
{
let s = String::deserialize(deserializer)?;
T::from_str(&s).map_err(de::Error::custom)
}
#[cfg(test)]
mod tests {
use serde_json::from_str;
use super::XkcdResponse;
use super::super::parse_xkcd_response;
use url::Url;
use util::read_sample_data_from_path;
#[test]
fn test_parse_xkcd_response() {
let result = read_sample_data_from_path("tests/sample-data/example.json");
let response = from_str::<XkcdResponse>(result.as_str()).unwrap();
assert_eq!(response, XkcdResponse {
month: 9,
num: 1572,
link: "http://goo.gl/forms/pj0OhX6wfO".to_owned(),
year: 2015,
news: "".to_owned(),
safe_title: "xkcd Survey".to_owned(),
transcript: "Introducing the XKCD SURVEY! A search for weird correlations.\n\nNOTE: This survey is anonymous, but all responses will be posted publicly so people can play with the data.\n\nClick here to take the survey.\n\nhttp:\n\ngoo.gl\nforms\nlzZr7P9Qlm\n\nOr click here, or here. The whole comic is a link because I still haven't gotten the hang of HTML imagemaps.\n\n{{Title text: The xkcd Survey: Big Data for a Big Planet}}".to_owned(),
alt: "The xkcd Survey: Big Data for a Big Planet".to_owned(),
img: "http://imgs.xkcd.com/comics/xkcd_survey.png".to_owned().parse::<Url>().unwrap(),
title: "xkcd Survey".to_owned(),
day: 1,
});
}
#[test]
fn test_parse_xkcd_response_no_link() {
let result = read_sample_data_from_path("tests/sample-data/no-link.json");
let response = parse_xkcd_response::<XkcdResponse>(result.as_str()).unwrap();
assert_eq!(response, XkcdResponse {
month: 6,
num: 1698,
link: "".to_owned(),
year: 2016,
news: "".to_owned(),
safe_title: "Theft Quadrants".to_owned(),
transcript: "".to_owned(),
alt: "TinyURL was the most popular link shortener for long enough that it made it into a lot of printed publications. I wonder what year the domain will finally lapse and get picked up by a porn site.".to_owned(),
img: "http://imgs.xkcd.com/comics/theft_quadrants.png".to_owned().parse::<Url>().unwrap(),
title: "Theft Quadrants".to_owned(),
day: 24,
});
}
}
|
#[doc = "Reader of register STS"]
pub type R = crate::R<u32, super::STS>;
#[doc = "Writer for register STS"]
pub type W = crate::W<u32, super::STS>;
#[doc = "Register STS `reset()`'s with value 0"]
impl crate::ResetValue for super::STS {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Last Error Code\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum LEC_A {
#[doc = "0: No Error"]
NONE = 0,
#[doc = "1: Stuff Error"]
STUFF = 1,
#[doc = "2: Format Error"]
FORM = 2,
#[doc = "3: ACK Error"]
ACK = 3,
#[doc = "4: Bit 1 Error"]
BIT1 = 4,
#[doc = "5: Bit 0 Error"]
BIT0 = 5,
#[doc = "6: CRC Error"]
CRC = 6,
#[doc = "7: No Event"]
NOEVENT = 7,
}
impl From<LEC_A> for u8 {
#[inline(always)]
fn from(variant: LEC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `LEC`"]
pub type LEC_R = crate::R<u8, LEC_A>;
impl LEC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LEC_A {
match self.bits {
0 => LEC_A::NONE,
1 => LEC_A::STUFF,
2 => LEC_A::FORM,
3 => LEC_A::ACK,
4 => LEC_A::BIT1,
5 => LEC_A::BIT0,
6 => LEC_A::CRC,
7 => LEC_A::NOEVENT,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `NONE`"]
#[inline(always)]
pub fn is_none(&self) -> bool {
*self == LEC_A::NONE
}
#[doc = "Checks if the value of the field is `STUFF`"]
#[inline(always)]
pub fn is_stuff(&self) -> bool {
*self == LEC_A::STUFF
}
#[doc = "Checks if the value of the field is `FORM`"]
#[inline(always)]
pub fn is_form(&self) -> bool {
*self == LEC_A::FORM
}
#[doc = "Checks if the value of the field is `ACK`"]
#[inline(always)]
pub fn is_ack(&self) -> bool {
*self == LEC_A::ACK
}
#[doc = "Checks if the value of the field is `BIT1`"]
#[inline(always)]
pub fn is_bit1(&self) -> bool {
*self == LEC_A::BIT1
}
#[doc = "Checks if the value of the field is `BIT0`"]
#[inline(always)]
pub fn is_bit0(&self) -> bool {
*self == LEC_A::BIT0
}
#[doc = "Checks if the value of the field is `CRC`"]
#[inline(always)]
pub fn is_crc(&self) -> bool {
*self == LEC_A::CRC
}
#[doc = "Checks if the value of the field is `NOEVENT`"]
#[inline(always)]
pub fn is_noevent(&self) -> bool {
*self == LEC_A::NOEVENT
}
}
#[doc = "Write proxy for field `LEC`"]
pub struct LEC_W<'a> {
w: &'a mut W,
}
impl<'a> LEC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LEC_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "No Error"]
#[inline(always)]
pub fn none(self) -> &'a mut W {
self.variant(LEC_A::NONE)
}
#[doc = "Stuff Error"]
#[inline(always)]
pub fn stuff(self) -> &'a mut W {
self.variant(LEC_A::STUFF)
}
#[doc = "Format Error"]
#[inline(always)]
pub fn form(self) -> &'a mut W {
self.variant(LEC_A::FORM)
}
#[doc = "ACK Error"]
#[inline(always)]
pub fn ack(self) -> &'a mut W {
self.variant(LEC_A::ACK)
}
#[doc = "Bit 1 Error"]
#[inline(always)]
pub fn bit1(self) -> &'a mut W {
self.variant(LEC_A::BIT1)
}
#[doc = "Bit 0 Error"]
#[inline(always)]
pub fn bit0(self) -> &'a mut W {
self.variant(LEC_A::BIT0)
}
#[doc = "CRC Error"]
#[inline(always)]
pub fn crc(self) -> &'a mut W {
self.variant(LEC_A::CRC)
}
#[doc = "No Event"]
#[inline(always)]
pub fn noevent(self) -> &'a mut W {
self.variant(LEC_A::NOEVENT)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "Reader of field `TXOK`"]
pub type TXOK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TXOK`"]
pub struct TXOK_W<'a> {
w: &'a mut W,
}
impl<'a> TXOK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `RXOK`"]
pub type RXOK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RXOK`"]
pub struct RXOK_W<'a> {
w: &'a mut W,
}
impl<'a> RXOK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `EPASS`"]
pub type EPASS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EPASS`"]
pub struct EPASS_W<'a> {
w: &'a mut W,
}
impl<'a> EPASS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `EWARN`"]
pub type EWARN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EWARN`"]
pub struct EWARN_W<'a> {
w: &'a mut W,
}
impl<'a> EWARN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `BOFF`"]
pub type BOFF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BOFF`"]
pub struct BOFF_W<'a> {
w: &'a mut W,
}
impl<'a> BOFF_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
}
}
impl R {
#[doc = "Bits 0:2 - Last Error Code"]
#[inline(always)]
pub fn lec(&self) -> LEC_R {
LEC_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bit 3 - Transmitted a Message Successfully"]
#[inline(always)]
pub fn txok(&self) -> TXOK_R {
TXOK_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Received a Message Successfully"]
#[inline(always)]
pub fn rxok(&self) -> RXOK_R {
RXOK_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Error Passive"]
#[inline(always)]
pub fn epass(&self) -> EPASS_R {
EPASS_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Warning Status"]
#[inline(always)]
pub fn ewarn(&self) -> EWARN_R {
EWARN_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Bus-Off Status"]
#[inline(always)]
pub fn boff(&self) -> BOFF_R {
BOFF_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - Last Error Code"]
#[inline(always)]
pub fn lec(&mut self) -> LEC_W {
LEC_W { w: self }
}
#[doc = "Bit 3 - Transmitted a Message Successfully"]
#[inline(always)]
pub fn txok(&mut self) -> TXOK_W {
TXOK_W { w: self }
}
#[doc = "Bit 4 - Received a Message Successfully"]
#[inline(always)]
pub fn rxok(&mut self) -> RXOK_W {
RXOK_W { w: self }
}
#[doc = "Bit 5 - Error Passive"]
#[inline(always)]
pub fn epass(&mut self) -> EPASS_W {
EPASS_W { w: self }
}
#[doc = "Bit 6 - Warning Status"]
#[inline(always)]
pub fn ewarn(&mut self) -> EWARN_W {
EWARN_W { w: self }
}
#[doc = "Bit 7 - Bus-Off Status"]
#[inline(always)]
pub fn boff(&mut self) -> BOFF_W {
BOFF_W { w: self }
}
}
|
//! Macro for opaque `Debug` trait implementation.
#![no_std]
/// Macro for defining opaque `Debug` implementation. It will use the following
/// format: "HasherName { ... }". While it's convinient to have it
/// (e.g. for including in other structs), it could be undesirable to leak
/// internall state, which can happen for example through uncareful logging.
#[macro_export]
macro_rules! impl_opaque_debug {
($state:ty) => {
use core::fmt;
impl fmt::Debug for $state {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, concat!(stringify!($state), " {{ ... }}"))
}
}
}
}
|
// Copyright 2021 Chiral Ltd.
// Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
//!
//! Workflow for Extenion Module: Molecule
//!
//! # Examples
//!
//! ```rust
//! use graph_canonicalization;
//!
//! let atom_vec = graph_canonicalization::ext::molecule::smiles_to_atom_vec("C(C)(C)CCN");
//! let (orbits_givp, numbering) = graph_canonicalization::ext::molecule::symmetry_perception_givp(&atom_vec);
//! assert_eq!(orbits_givp, vec![vec![1, 2]]);
//! assert_eq!(numbering, vec![6, 2, 2, 5, 4, 3]);
//! let (orbits_cnap) = graph_canonicalization::ext::molecule::symmetry_perception_cnap(&atom_vec, &orbits_givp, &numbering);
//! assert_eq!(orbits_cnap, vec![vec![1, 2]]);
//! ```
use crate::core;
use crate::core::graph::*;
use super::atom;
use super::extendable_hash;
use super::local_symmetry;
use super::molecule;
type BondRepresentation = (usize, usize, usize);
/// Grab all bond information, save to an array of tuples, (first atom id, second atom id, bond representative value)
fn get_bond_talbe(
atoms: &Vec<atom::Atom>,
atom_indexes: &Vec<usize>
) -> Vec<BondRepresentation> {
atom_indexes.iter()
.map(|&ai| atoms[ai].bonds.iter().map(move |b| (ai, b.tid, b.fixed_hash_value())))
.flatten()
.collect()
}
pub type AtomVec = core::graph::VertexVec<atom::Atom>;
/// Parse SMILES string to AtomVec
pub fn smiles_to_atom_vec(smiles: &str) -> AtomVec {
let mol = molecule::Molecule::from_smiles(&smiles);
let indexes_all: Vec<usize> = (0..mol.atoms.len()).collect();
core::graph::VertexVec::init(indexes_all, mol.atoms)
}
/// Calculate symmetric orbits and atom numbering(ranking) by GIVP
pub fn symmetry_perception_givp(
vv: &AtomVec
) -> (Vec<core::orbit_ops::Orbit>, Vec<usize>) {
let mut numbering: Vec<usize> = vec![];
let mut orbits_givp: Vec<core::orbit_ops::Orbit> = vec![];
core::givp::run::<extendable_hash::AtomExtendable>(&vv, &mut numbering, &mut orbits_givp);
(orbits_givp, numbering)
}
/// Confirm symmetric orbits from GIVP by CNAP
pub fn symmetry_perception_cnap(
vv: &AtomVec,
orbits_givp: &Vec<core::orbit_ops::Orbit>,
numbering_givp: &Vec<usize>
) -> Vec<core::orbit_ops::Orbit> {
// let (orbits_givp, numbering, vv) = symmetry_perception_givp(&smiles);
let mut orbits_cnap: Vec<core::orbit_ops::Orbit> = vec![];
if orbits_givp.len() != 0 {
let mut rg = core::reduce::ReducibleGraph {
vv: vv.clone(),
mapping: vec![],
boundary_edges: vec![],
orbits_after_partition: orbits_givp.to_vec(),
numbering: numbering_givp.to_vec()
};
core::symmetry_perception_by_graph_reduction::<extendable_hash::AtomExtendable>(&mut rg, &mut orbits_cnap, get_bond_talbe, local_symmetry::get_local_symmetric_orbits, 200);
}
core::orbit_ops::orbits_sort(&mut orbits_cnap);
orbits_cnap
}
// a process combined with GIVP and CNAP
pub fn canonical_numbering_and_symmetry_perception(
atoms: &Vec<atom::Atom>,
orbits_after_partition: &mut Vec<core::orbit_ops::Orbit>,
orbits_symmetry: &mut Vec<core::orbit_ops::Orbit>,
numbering: &mut Vec<usize>,
) {
let indexes_all: Vec<usize> = (0..atoms.len()).collect();
let vv = core::graph::VertexVec::init(indexes_all, atoms.to_vec());
numbering.clear();
// calculate and save the givp result for comparison
core::givp::run::<extendable_hash::AtomExtendable>(&vv, numbering, orbits_after_partition);
let mut rg = core::reduce::ReducibleGraph {
vv: vv,
mapping: vec![],
boundary_edges: vec![],
orbits_after_partition: orbits_after_partition.clone(),
numbering: numbering.clone()
};
core::symmetry_perception_by_graph_reduction::<extendable_hash::AtomExtendable>(&mut rg, orbits_symmetry, get_bond_talbe, local_symmetry::get_local_symmetric_orbits, 200);
}
#[cfg(test)]
mod test_ext_mol_workflow {
use super::*;
use crate::ext::molecule;
#[test]
fn test_get_bond_table() {
type InputType1 = String;
type ReturnType1 = Vec<BondRepresentation>;
let test_data: Vec<(InputType1, ReturnType1)> = vec![
(
"C(C)(C)CC=N",
vec![(0, 1, 10), (0, 2, 10), (0, 3, 10), (1, 0, 10), (2, 0, 10), (3, 0, 10), (3, 4, 10), (4, 3, 10), (4, 5, 20), (5, 4, 20)]
)
].into_iter().map(|s| (s.0.to_string(), s.1)).collect();
for td in test_data.iter() {
let (smiles, bondtable) = td.clone();
let mol = molecule::molecule::Molecule::from_smiles(&smiles);
assert_eq!(get_bond_talbe(&mol.atoms, &(0..mol.atoms.len()).collect()), bondtable);
}
}
#[test]
fn test_canonical_numbering_and_symmetry_perception() {
type InputType1 = String;
let test_data: Vec<InputType1> = vecCc1ccc(cc1)-c1cccc(c1C(=O)O)-c1ccc(cc1)C[n+]1ccn(c1)Cc1ccc(cc1)C3=O", // chembl 15,
// "CC(C)(CCCOc1cc(Cl)c(OCCCC(C)(C)C(=O)O)cc1Cl)C(=O)O", // 4631
// "C[N+](C)(CCCCCC[N+](C)(C)CCCN1C(=O)C2C3c4ccccc4C(c4ccccc43)C2C1=O)CCCN1C(=O)c2ccccc2C1=O", // 6053 separable graph
// "N[C@@H](Cc1cnc(C23CC4CC(CC(C4)C2)C3)[nH]1)C(=O)N[C@@H](Cc1c[nH]c2ccccc12)C(=O)N[C@@H](Cc1cnc(C23CC4CC(CC(C4)C2)C3)[nH]1)C(=O)NCc1ccccc1", // 7844 separable graph
// "OCCCCCNCc1c2ccccc2c(CNCCCCCO)c2ccccc12", // 23218
// // "NC[C@@H]1O[C@H](O[C@@H]2[C@@H](CSCCNC(=S)NCCCCn3c(=O)c4ccc5c6ccc7c(=O)n(CCCCNC(=S)NCCSC[C@H]8O[C@@H](O[C@@H]9[C@@H](O)[C@H](N)C[C@H](N)[C@H]9O[C@H]9O[C@H](CN)[C@@H](O)[C@H](O)[C@H]9N)[C@H](O)[C@@H]8O[C@H]8O[C@@H](CN)[C@@H](O)[C@H](O)[C@H]8N)c(=O)c8ccc(c9ccc(c3=O)c4c59)c6c78)O[C@@H](O[C@@H]3[C@@H](O)[C@H](N)C[C@H](N)[C@H]3O[C@H]3O[C@H](CN)[C@@H](O)[C@H](O)[C@H]3N)[C@@H]2O)[C@H](N)[C@@H](O)[C@@H]1O", // 52881
// "CC1(C)c2ccc([nH]2)C2(C)CCCCNC(=O)c3cccc(n3)C(=O)NCCCCC(C)(c3ccc1[nH]3)c1ccc([nH]1)C(C)(C)c1ccc2[nH]1", // 4971 interesting example, 8 vertices cycle, 2 folded symmetry
// "O=C1NNC(=O)c2ccccc2SSc2ccccc2C(=O)NNC(=O)c2ccccc2SSc2ccccc21", // 140635
// "O=P1([O-])OC2C3OP(=O)([O-])OP(=O)([O-])OC3C3OP(=O)([O-])OP(=O)([O-])OC3C2OP(=O)([O-])O1", // 168272
// "O=P1([O-])OC2C3OP(=O)([O-])OP(=O)([O-])OC3C3OP(=O)([O-])OP(=O)([O-])OC3C2OP(=O)([O-])O1", // 171007
// "C1CC1N1CN2c3nonc3N3CN(C4CC4)CN4c5nonc5N(C1)C2C34", // 199821
// "O=P1(O)OC2C3OP(=O)(O)OP(=O)(O)OC3C3OP(=O)(O)OP(=O)(O)OC3C2OP(=O)(O)O1", // 208361
// // "CC[n+]1ccc(-c2cc[n+](Cc3cc(C[n+]4ccc(-c5cc[n+](CC)cc5)cc4)cc(C[n+]4ccc(-c5cc[n+](Cc6cc(C[n+]7ccc(-c8cc[n+](Cc9cc(C[n+]%10ccc(-c%11cc[n+](CC)cc%11)cc%10)cc(C[n+]%10ccc(-c%11cc[n+](CC)cc%11)cc%10)c9)cc8)cc7)cc(-[n+]7ccc(-c8cc[n+](-c9cc(C[n+]%10ccc(-c%11cc[n+](Cc%12cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)c%12)cc%11)cc%10)cc(C[n+]%10ccc(-c%11cc[n+](Cc%12cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)c%12)cc%11)cc%10)c9)cc8)cc7)c6)cc5)cc4)c3)cc2)cc1", // 826428 long givp time
// // "CC[n+]1ccc(-c2cc[n+](Cc3cc(C[n+]4ccc(-c5cc[n+](CC)cc5)cc4)cc(C[n+]4ccc(-c5cc[n+](Cc6cc(C[n+]7ccc(-c8cc[n+](Cc9cc(C[n+]%10ccc(-c%11cc[n+](CC)cc%11)cc%10)cc(C[n+]%10ccc(-c%11cc[n+](CC)cc%11)cc%10)c9)cc8)cc7)cc(-[n+]7ccc(-c8cc[n+](-c9cc(C[n+]%10ccc(-c%11cc[n+](Cc%12cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)c%12)cc%11)cc%10)cc(C[n+]%10ccc(-c%11cc[n+](Cc%12cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)cc(C[n+]%13ccc(-c%14cc[n+](CC)cc%14)cc%13)c%12)cc%11)cc%10)c9)cc8)cc7)c6)cc5)cc4)c3)cc2)cc1", // 1246825
// "BrC1CCC(Br)C(Br)CCC(Br)C(Br)CCC1Br", // 377203
// "C[N+]1(C)CC23c4c5c6c7c8c4c4c2c2c9c%10c%11c%12c%13c9c9c%14c%15c%16c%17c%18c%19c(c8c%17c4c%16c29)C7C2c4c-%19c7c8c9c(c%14c%13c%13c9c9c8c4c4c2c6c2c5c(c=%11c5c2c4c9c5c%12%13)C%103C1)C%15C%187", // CHEMBL415840 failure case in Schneider paper
// "CCC[C@H]1CC[C@H]([C@H]2CC[C@H](OC(=O)[C@H]3[C@@H](c4ccc(O)cc4)[C@H](C(=O)O[C@H]4CC[C@H]([C@H]5CC[C@H](CCC)CC5)CC4)[C@@H]3c3ccc(O)cc3)CC2)CC1", // CHEMBL2348759, failure case in Schneider paper
//
// *** NOT SOLVED ***
// "OC(c1ccccc1)C1(c2ccccc2)C23c4c5c6c7c8c9c(c%10c%11c2c2c4c4c%12c5c5c6c6c8c8c%13c9c9c%10c%10c%11c%11c2c2c4c4c%12c%12c5c5c6c8c6c8c%13c9c9c%10c%10c%11c2c2c4c4c%12c5c6c5c8c9c%10c2c45)C731", // 408840 beneze ball
// "O=C(CCCc1ccc(C2(c3ccccc3)C34c5c6c7c8c9c%10c(c%11c%12c3c3c5c5c%13c6c6c7c7c9c9c%14c%10c%10c%11c%11c%12c%12c3c3c5c5c%13c%13c6c6c7c9c7c9c%14c%10c%10c%11c%11c%12c3c3c5c5c%13c6c7c6c9c%10c%11c3c56)C824)cc1)NC(CO)(CO)CO", // 267348 beneze ball
// "O=C(CCCc1ccc(C2(c3ccccc3)C34c5c6c7c8c9c%10c(c%11c%12c3c3c5c5c%13c6c6c7c7c9c9c%14c%10c%10c%11c%11c%12c%12c3c3c5c5c%13c%13c6c6c7c9c7c9c%14c%10c%10c%11c%11c%12c3c3c5c5c%13c6c7c6c9c%10c%11c3c56)C824)cc1)NC(CO)(CO)CO", // 267348
// r#"C[C@H](CC[C@@H]([C@@H]([C@H](C)C[C@H](C(=C)/C(=C/CO)/C)O)O)OS(=O)(=O)[O-])[C@H]([C@@H](C)[C@H]1[C@@H]([C@@H]([C@H]2[C@H](O1)[C@@H](C[C@]3([C@H](O2)C[C@H]4[C@H](O3)C[C@]5([C@H](O4)[C@H]([C@H]6[C@H](O5)C[C@H]([C@H](O6)[C@@H]([C@H](C[C@H]7[C@@H]([C@@H]([C@H]8[C@H](O7)C[C@H]9[C@H](O8)C[C@H]1[C@H](O9)[C@H]([C@@H]2[C@@H](O1)[C@@H]([C@H]([C@@H](O2)[C@H]1[C@@H]([C@H]([C@H]2[C@@H](O1)C[C@H]([C@@H](O2)[C@@H](C[C@H](C[C@H]1[C@@H]([C@H]([C@H]2[C@@H](O1)C[C@H]([C@@H](O2)[C@H]1[C@@H](C[C@]2([C@H](O1)[C@@H]([C@]1([C@H](O2)C[C@]2([C@H](O1)CC[C@]1([C@H](O2)C[C@]2([C@H](O1)C[C@H]1[C@H](O2)CC[C@H](O1)[C@]1([C@@H](C[C@H]2[C@](O1)(C[C@H]1[C@](O2)(CC[C@]2([C@H](O1)C[C@H]1[C@](O2)(C[C@H]2[C@H](O1)C/C=C\[C@H]1[C@H](O2)C[C@H]2[C@](O1)(C[C@]1([C@H](O2)C[C@H]2[C@](O1)(CC[C@H](O2)[C@H]([C@@H](C[C@@H](C)[C@@H](C)CC=C)O)O)C)C)C)C)C)C)C)O)C)C)C)C)C)O)C)O)O)O)O)O)O)O)O)O)O)O)O)O)OS(=O)(=O)[O-])O)O)O)O)C)C)O)O)O)O"#, // Maitotoxin
// "OC(=O)c1cc2Cc3cc(Cc4cc(Cc5cc(Cc(c2)c1)cc(c5)C(O)=O)cc(c4)C(O)=O)cc(c3)C(O)=O", // graph reduction demo
"C1C2CC3CC1CC(C2)C3", // example from nauty, https://pallini.di.uniroma1.it/Introduction.html
].into_iter().map(|s| s.to_string()).collect();
for td in test_data.iter() {
let smiles = td.clone();
let mol = molecule::molecule::Molecule::from_smiles(&smiles);
if cfg!(debug_assertions) {
println!("{}", mol.smiles_with_index(&smiles, &vec![]));
}
let mut orbits_partitioned: Vec<core::orbit_ops::Orbit> = vec![];
let mut orbits_symmetry: Vec<core::orbit_ops::Orbit> = vec![];
let mut numbering: Vec<usize> = vec![];
molecule::workflow::canonical_numbering_and_symmetry_perception(&mol.atoms, &mut orbits_partitioned, &mut orbits_symmetry, &mut numbering);
println!("{}", mol.smiles_with_index(&smiles, &numbering));
if cfg!(debug_assertions) {
core::orbit_ops::orbits_sort(&mut orbits_partitioned);
core::orbit_ops::orbits_sort(&mut orbits_symmetry);
println!("GIVP: {:?}\nCNAP: {:?}", orbits_partitioned, orbits_symmetry);
}
assert_eq!(core::orbit_ops::orbits_equal(&orbits_partitioned, &orbits_symmetry), true);
}
}
#[test]
fn test_symmetry_perception_givp() {
type InputType1 = String;
type ReturnType1 = Vec<core::orbit_ops::Orbit>;
type ReturnType2 = Vec<usize>;
let test_data: Vec<(InputType1, ReturnType1, ReturnType2)> = vec![
(
"C(C)(C)CCN",
vec![vec![1, 2]],
vec![6, 2, 2, 5, 4, 3],
),
(
"C(C)(C)CCNCCC(C)(C)",
vec![vec![0, 8], vec![1, 2, 9, 10], vec![3, 7], vec![4, 6]],
vec![11, 4, 4, 8, 6, 9, 6, 8, 11, 4, 4]
)
].into_iter().map(|s| (s.0.to_string(), s.1, s.2)).collect();
for td in test_data.iter() {
let (smiles, orbits_givp, numbering) = td;
let vv = smiles_to_atom_vec(smiles);
let results = symmetry_perception_givp(&vv);
assert_eq!(results.0, *orbits_givp);
assert_eq!(results.1, *numbering);
}
}
#[test]
fn test_symmetry_perception_cnap() {
type InputType1 = String;
type InputType2 = Vec<core::orbit_ops::Orbit>;
type InputType3 = Vec<usize>;
type ReturenType1 = Vec<core::orbit_ops::Orbit>;
let test_data: Vec<(InputType1, InputType2, InputType3, ReturenType1)> = vec![
(
"C(C)(C)CCN",
vec![vec![1, 2]],
vec![6, 2, 2, 5, 4, 3],
vec![vec![1, 2]],
),
(
"C(C)(C)CCNCCC(C)(C)",
vec![vec![0, 8], vec![1, 2, 9, 10], vec![3, 7], vec![4, 6]],
vec![11, 4, 4, 8, 6, 9, 6, 8, 11, 4, 4],
vec![vec![0, 8], vec![1, 2, 9, 10], vec![3, 7], vec![4, 6]],
)
].into_iter().map(|s| (s.0.to_string(), s.1, s.2, s.3)).collect();
for td in test_data.iter() {
let (smiles, orbits_givp, numbering, orbits_cnap) = td;
let vv = smiles_to_atom_vec(smiles);
let results = symmetry_perception_cnap(&vv, orbits_givp, numbering);
assert_eq!(results, *orbits_cnap);
}
}
} |
fn main() {
other();
}
fn other() {}
|
use crate::token::{Token, TokenType};
use std::convert::TryInto;
pub struct Scanner<'a> {
pub source: &'a str,
pub tokens: Vec<Token>,
start: usize,
current: usize,
line: u32,
had_error: bool,
}
impl<'a> Scanner<'a> {
pub fn new(source: &str) -> Scanner {
let tokens: Vec<Token> = Vec::new();
Scanner {
source: source,
tokens: tokens,
start: 0,
current: 0,
line: 1,
had_error: false,
}
}
pub fn scan_tokens(&mut self) -> &Vec<Token> {
while !self.is_at_end() {
self.start = self.current;
self.scan_token();
}
let tok = Token::new(TokenType::Eof, "".to_string(), None, self.line);
self.tokens.push(tok);
&self.tokens
}
fn scan_token(&mut self) {
let c = self.advance();
match c {
'(' => self.add_token(TokenType::LeftParen, None),
')' => self.add_token(TokenType::RightParen, None),
'{' => self.add_token(TokenType::LeftBrace, None),
'}' => self.add_token(TokenType::RightBrace, None),
',' => self.add_token(TokenType::Comma, None),
'.' => self.add_token(TokenType::Dot, None),
'-' => self.add_token(TokenType::Minus, None),
'+' => self.add_token(TokenType::Plus, None),
';' => self.add_token(TokenType::Semicolon, None),
'*' => self.add_token(TokenType::Star, None),
'!' => {
if self.match_next('=') == true {
self.add_token(TokenType::BangEqual, None);
} else {
self.add_token(TokenType::Bang, None);
}
}
'=' => {
if self.match_next('=') == true {
self.add_token(TokenType::EqualEqual, None);
} else {
self.add_token(TokenType::Equal, None);
}
}
'<' => {
if self.match_next('=') == true {
self.add_token(TokenType::LessEqual, None);
} else {
self.add_token(TokenType::Less, None);
}
}
'>' => {
if self.match_next('=') == true {
self.add_token(TokenType::GreaterEqual, None);
} else {
self.add_token(TokenType::Greater, None);
}
}
'/' => {
if self.match_next('/') == true {
// A comment goes until the end of the line
while self.peek() != '\n' && self.is_at_end() == false {
self.advance();
}
} else {
self.add_token(TokenType::Slash, None);
}
}
// Cases we are going to ignore for the most part
' ' => (),
'\r' => (),
'\t' => (),
'\n' => self.line += 1,
// Collecting string literals
'"' => self.string_literal_parse(),
_ => {
eprintln!("Invalid or Unhandled char: {}", c);
self.had_error = true;
}
}
}
fn peek(&self) -> char {
if self.is_at_end() == true {
'\0'
} else {
self.source.chars().nth(self.current).unwrap()
}
}
fn advance(&mut self) -> char {
self.current += 1;
let index: usize = self.current - 1;
self.source.chars().nth(index).unwrap()
}
fn string_literal_parse(&mut self) {
while self.peek() != '"' && self.is_at_end() == false {
if self.peek() == '\n' {
self.line += 1;
}
self.advance();
}
if self.is_at_end() == true {
panic!("Unterminated string on line {}", self.line);
}
// The closing '"'
self.advance();
let val: String = self.source[self.start+1..self.current-1].to_string();
self.add_token(TokenType::RainString, Some(val));
}
fn match_next(&mut self, expected: char) -> bool {
if self.is_at_end() {
false
} else if self.source.chars().nth(self.current).unwrap() != expected {
false
} else {
self.current += 1;
true
}
}
fn add_token(&mut self, token_type: TokenType, value: Option<String>) {
self.add_token_wrapped(token_type, value);
}
fn is_at_end(&self) -> bool {
self.current >= self.source.len().try_into().unwrap()
}
fn add_token_wrapped(&mut self, token_type: TokenType, literal: Option<String>) {
let text: String = self.source[self.start..self.current].to_string();
let tok = Token::new(token_type, text, literal, self.line);
self.tokens.push(tok);
}
}
|
mod assets;
mod handle;
pub use assets::*;
pub use handle::Handle;
|
use crate::prelude::*;
use utilities::prelude::*;
use super::block::Block;
use std::os::raw::c_void;
use std::sync::Arc;
pub struct Chunk {
device: Arc<Device>,
memory: VkDeviceMemory,
memory_type_index: u32,
size: VkDeviceSize,
blocks: Vec<Block>,
mapping: Option<*mut c_void>,
}
unsafe impl Sync for Chunk {}
unsafe impl Send for Chunk {}
impl Chunk {
pub fn new(
device: Arc<Device>,
memory_type_index: u32,
size: VkDeviceSize,
) -> VerboseResult<Self> {
let memory_ci = VkMemoryAllocateInfo::new(size, memory_type_index);
let memory = device.allocate_memory(&memory_ci)?;
let mapping = if (device.physical_device().memory_properties().memoryTypes
[memory_type_index as usize]
.propertyFlagBits
& VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
== VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
{
Some(device.map_memory_raw(memory, 0, VK_WHOLE_SIZE, VK_MEMORY_MAP_NULL_BIT)?)
} else {
None
};
Ok(Chunk {
device,
memory,
memory_type_index,
size,
blocks: vec![Block::new(memory, 0, size)],
mapping,
})
}
pub fn allocate(
&mut self,
size: VkDeviceSize,
alignment: VkDeviceSize,
) -> VerboseResult<Option<Block>> {
if self.size < size {
return Ok(None);
}
let mut result_block = None;
let mut new_block = None;
for block in &mut self.blocks {
if !block.used {
let mut new_size = block.size;
if block.offset % alignment != 0 {
new_size -= alignment - block.offset % alignment;
}
if new_size >= size {
block.size = new_size;
// We compute offset and size that care about alignment (for this Block)
if block.offset % alignment != 0 {
block.offset += alignment - block.offset % alignment;
}
// ptr address
if let Some(mapping) = self.mapping {
block.set_host_ptr(Some(unsafe { mapping.offset(block.offset as isize) }));
}
// check for perfect match
if block.size != size {
// create new empty block at the end
new_block = Some(Block::new(
self.memory,
block.offset + size,
block.size - size,
));
// set block size
block.size = size;
}
block.used = true;
result_block = Some(block.clone());
break;
}
}
}
if let Some(block) = new_block {
self.blocks.push(block);
}
Ok(result_block)
}
pub fn deallocate(&mut self, block: &Block) {
debug_assert!(self.contains(block));
let internal_block = self
.blocks
.iter_mut()
.find(|b| *b == block)
.expect("wrong chunk!");
internal_block.used = false;
}
pub fn contains(&self, block: &Block) -> bool {
self.blocks.contains(block)
}
pub fn memory_type_index(&self) -> u32 {
self.memory_type_index
}
}
impl Drop for Chunk {
fn drop(&mut self) {
if self.mapping.is_some() {
self.mapping = None;
self.device.unmap_memory(self.memory);
}
}
}
|
fn main() {
println!("My first Rust Program on GitHub");
}
|
#[derive(Clone)]
pub enum ArmaValue {
Number(f32),
Array(Vec<ArmaValue>),
Boolean(bool),
String(String),
}
impl std::fmt::Display for ArmaValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Number(n) => write!(f, "{}", n.to_string()),
Self::Array(a) => write!(
f,
"[{}]",
a.iter()
.map(|x| x.to_string())
.collect::<Vec<String>>()
.join(",")
),
Self::Boolean(b) => write!(f, "{}", b.to_string()),
Self::String(s) => write!(f, "\"{}\"", s.to_string().replace("\"", "\"\"")),
}
}
}
pub trait ToArma {
fn to_arma(&self) -> ArmaValue;
}
impl ToArma for ArmaValue {
fn to_arma(&self) -> ArmaValue {
self.to_owned()
}
}
impl<T: ToArma> ToArma for Vec<T> {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Array(self.iter().map(|x| x.to_arma()).collect::<Vec<ArmaValue>>())
}
}
impl ToArma for String {
fn to_arma(&self) -> ArmaValue {
ArmaValue::String(self.to_string())
}
}
impl ToArma for &'static str {
fn to_arma(&self) -> ArmaValue {
ArmaValue::String(self.to_string())
}
}
impl ToArma for u8 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for u16 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for u32 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for u64 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for u128 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for i8 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for i16 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for i32 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for i64 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for i128 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for f32 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
impl ToArma for f64 {
fn to_arma(&self) -> ArmaValue {
ArmaValue::Number(self.to_owned() as f32)
}
}
|
#![forbid(unsafe_code)]
#![no_std]
|
use crate::prelude::*;
use super::super::{c_char_to_vkstring, raw_to_slice};
use std::os::raw::{c_char, c_void};
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkDebugUtilsMessengerCallbackDataEXT {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkDebugUtilsMessengerCallbackDataFlagBitsEXT,
pub pMessageIdName: *const c_char,
pub messageIdNumber: i32,
pub pMessage: *const c_char,
pub queueLabelCount: u32,
pub pQueueLabels: *const VkDebugUtilsLabelEXT,
pub cmdBufLabelCount: u32,
pub pCmdBufLabels: *const VkDebugUtilsLabelEXT,
pub objectCount: u32,
pub pObjects: *const VkDebugUtilsObjectNameInfoEXT,
}
impl VkDebugUtilsMessengerCallbackDataEXT {
pub fn new<'a, 'b: 'a, 'c: 'a, 'd: 'a, 'e: 'a, T>(
flags: T,
message_id_name: &VkString,
message_id_number: i32,
message: &'b VkString,
queue_labels: &'c [VkDebugUtilsLabelEXT],
cmd_buf_labels: &'d [VkDebugUtilsLabelEXT],
objects: &'e [VkDebugUtilsObjectNameInfoEXT],
) -> Self
where
T: Into<VkDebugUtilsMessengerCallbackDataFlagBitsEXT>,
{
VkDebugUtilsMessengerCallbackDataEXT {
sType: VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT,
pNext: ptr::null(),
flags: flags.into(),
pMessageIdName: message_id_name.as_ptr(),
messageIdNumber: message_id_number,
pMessage: message.as_ptr(),
queueLabelCount: queue_labels.len() as u32,
pQueueLabels: queue_labels.as_ptr(),
cmdBufLabelCount: cmd_buf_labels.len() as u32,
pCmdBufLabels: cmd_buf_labels.as_ptr(),
objectCount: objects.len() as u32,
pObjects: objects.as_ptr(),
}
}
pub fn objects(&self) -> &[VkDebugUtilsObjectNameInfoEXT] {
raw_to_slice(self.pObjects, self.objectCount)
}
pub fn message(&self) -> Result<VkString, String> {
c_char_to_vkstring(self.pMessage)
}
}
|
#[doc = "Reader of register OUT"]
pub type R = crate::R<u8, super::OUT>;
#[doc = "Reader of field `out`"]
pub type OUT_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7"]
#[inline(always)]
pub fn out(&self) -> OUT_R {
OUT_R::new((self.bits & 0xff) as u8)
}
}
|
/// A Struct that stores some test data
#[derive(Debug)]
pub struct TestStruct {
pub name: String,
pub age: u8,
pub favorite_words: Vec<String>,
}
pub fn moved_param(param: TestStruct) {
println!("{:?}", param);
}
pub fn moved_and_returned_param(param: TestStruct) -> TestStruct {
println!("{:?}", param);
param
}
pub fn borrowed_param(param: &TestStruct) {
println!("{:?}", param);
do_something_with_string(¶m.name);
}
fn do_something_with_string(str: &String) {
println!("{}", str);
}
pub fn get_struct() -> TestStruct {
TestStruct {
name: "FART".to_string(),
age: 31,
favorite_words: vec!(
"fart".to_string(),
"turd".to_string(),
"butt".to_string()
)
}
}
#[test]
fn test_moved_param() {
let param1 = TestStruct{
name: "FART".to_string(),
age: 31,
favorite_words: vec!(
"fart".to_string(),
"turd".to_string(),
"butt".to_string())};
moved_param(param1);
// this would cause a compile error
// moved_param(param1);
}
|
// 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 core::any::Any;
use super::super::super::file::*;
use super::super::super::attr::*;
use super::super::super::dentry::*;
use super::super::super::dirent::*;
use super::super::super::super::kernel::waiter::*;
use super::super::super::super::qlib::common::*;
use super::super::super::super::qlib::linux_def::*;
use super::super::super::super::task::*;
use super::super::super::host::hostinodeop::*;
use super::*;
pub trait DynamicDirFileNode : Send + Sync {
fn ReadDir(&self, _task: &Task, _f: &File, _offset: i64, _serializer: &mut DentrySerializer) -> Result<i64> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn IterateDir(&self, _task: &Task, _d: &Dirent, _dirCtx: &mut DirCtx, _offset: i32) -> (i32, Result<i64>) {
return (0, Err(Error::SysError(SysErr::ENOTDIR)))
}
}
pub struct DynamicDirFileOperations<T: 'static + DynamicDirFileNode> {
pub node: T,
}
impl <T: 'static + DynamicDirFileNode> Waitable for DynamicDirFileOperations <T> {}
impl <T: 'static + DynamicDirFileNode> SpliceOperations for DynamicDirFileOperations <T> {}
impl <T: 'static + DynamicDirFileNode> FileOperations for DynamicDirFileOperations <T> {
fn as_any(&self) -> &Any {
return self
}
fn FopsType(&self) -> FileOpsType {
return FileOpsType::DynamicDirFileOperations
}
fn Seekable(&self) -> bool {
return true;
}
fn Seek(&self, task: &Task, f: &File, whence: i32, current: i64, offset: i64) -> Result<i64> {
return SeekWithDirCursor(task, f, whence, current, offset, None)
}
fn ReadAt(&self, _task: &Task, _f: &File, _dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> {
return Err(Error::SysError(SysErr::EISDIR))
}
fn WriteAt(&self, _task: &Task, _f: &File, _srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> {
return Err(Error::SysError(SysErr::EISDIR))
}
fn Append(&self, task: &Task, f: &File, srcs: &[IoVec]) -> Result<(i64, i64)> {
let n = self.WriteAt(task, f, srcs, 0, false)?;
return Ok((n, 0))
}
fn Fsync(&self, _task: &Task, _f: &File, _start: i64, _end: i64, _syncType: SyncType) -> Result<()> {
return Ok(())
}
fn Flush(&self, _task: &Task, _f: &File) -> Result<()> {
return Ok(())
}
fn Ioctl(&self, _task: &Task, _f: &File, _fd: i32, _request: u64, _val: u64) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTTY))
}
fn UnstableAttr(&self, task: &Task, f: &File) -> Result<UnstableAttr> {
let inode = f.Dirent.Inode();
return inode.UnstableAttr(task);
}
fn IterateDir(&self, task: &Task,d: &Dirent, dirCtx: &mut DirCtx, offset: i32) -> (i32, Result<i64>) {
return self.node.IterateDir(task, d, dirCtx, offset)
}
fn ReadDir(&self, task: &Task, f: &File, offset: i64, serializer: &mut DentrySerializer) -> Result<i64> {
return self.node.ReadDir(task, f, offset, serializer)
}
fn Mappable(&self) -> Result<HostInodeOp> {
return Err(Error::SysError(SysErr::ENODEV))
}
}
impl <T: 'static + DynamicDirFileNode> SockOperations for DynamicDirFileOperations <T> {} |
use core::ops::FnMut;
use nom::bytes::complete::{escaped, is_not};
use nom::character::complete::{char, line_ending, one_of};
use nom::combinator::{flat_map, map_res};
use nom::error::context;
use nom::multi::many0;
use nom::sequence::terminated;
use nom::IResult;
use nom::Parser;
use crate::error::{FullError, StompParseError};
use crate::model::headers::parser::*;
use crate::model::headers::*;
trait HeaderParser<'a, E: FullError<&'a [u8], StompParseError>>:
FnMut(&'a [u8]) -> IResult<&'a [u8], Header, E> + 'a
{
}
impl<'a, E, T> HeaderParser<'a, E> for T
where
E: FullError<&'a [u8], StompParseError>,
T: FnMut(&'a [u8]) -> IResult<&'a [u8], Header, E> + 'a,
{
}
/// Creates an new HeadersParser accepting the specified required and optional Headers,
/// and optionally arbitrary other headers as "custom" headers.
pub fn headers_parser<'a, E>(
required: Vec<HeaderType>,
optional: Vec<HeaderType>,
allows_custom: bool,
) -> Box<dyn Parser<&'a [u8], Vec<Header>, E> + 'a>
where
E: 'a + FullError<&'a [u8], StompParseError>,
{
let parser_selector = init_headers_parser(required, optional, allows_custom);
Box::new(terminated(
many0(flat_map(header_name, parser_selector)), // Accept many headers...
context("header_terminator", line_ending), //...terminated by a blank line
))
}
fn init_headers_parser<'a, E>(
required: Vec<HeaderType>,
optional: Vec<HeaderType>,
allows_custom: bool,
) -> Box<dyn Fn(&'a str) -> Box<dyn HeaderParser<'a, E>> + 'a>
where
E: 'a + FullError<&'a [u8], StompParseError>,
{
// The part that deals with the specified required and optional headers
let known_headers = init_known_header_parser(required, optional, allows_custom);
// The part that deals with any other headers encountered
//let custom_header_parser_provider = custom_header_parser_provider_factory(allows_custom);
Box::new(move |name: &'a str| {
// Determine the type
known_headers(name) // Then see if it is a known header, and return the appropriate parser
.unwrap_or_else(|_| disallowed_header_parser(name))
})
}
fn find_header<'a, 'b, E>(
name: &'a str,
required: &'b Vec<HeaderType>,
optional: &'b Vec<HeaderType>,
allows_custom: bool,
) -> Result<Box<dyn HeaderParser<'a, E> + 'a>, StompParseError>
where
'a: 'b,
E: 'a + FullError<&'a [u8], StompParseError>,
{
required
.iter()
.find(|header_type| header_type.matches(name))
.or_else(|| {
optional
.iter()
.find(|header_type| header_type.matches(name))
})
.map(|header_type| {
Ok(known_header_parser::<'a, E>(find_header_parser(
*header_type,
)))
})
.unwrap_or_else(|| {
if allows_custom {
Ok(known_header_parser::<'a, E>(Box::new(
move |value: &str| {
Ok(Header::Custom(CustomValue::new(
unsafe { std::mem::transmute::<&'a str, &'static str>(name) },
unsafe { std::mem::transmute::<&'_ str, &'static str>(value) },
)))
},
)))
} else {
Err(StompParseError::new(format!("Unknown header: {}", name)))
}
})
}
fn init_known_header_parser<'a, E>(
required: Vec<HeaderType>,
optional: Vec<HeaderType>,
allows_custom: bool,
) -> impl Fn(&'a str) -> Result<Box<dyn HeaderParser<'a, E>>, StompParseError> + 'a
where
E: 'a + FullError<&'a [u8], StompParseError>,
{
move |name: &'a str| find_header(name, &required, &optional, allows_custom)
}
fn header_section<'a, E: FullError<&'a [u8], StompParseError>>(
input: &'a [u8],
) -> IResult<&'a [u8], &'a [u8], E> {
escaped(is_not("\\:\n\r"), '\\', one_of("rnc\\"))(input)
}
fn into_string<'a>(input: &'a [u8]) -> Result<&'a str, StompParseError> {
std::str::from_utf8(input).map_err(|_| StompParseError::new("bytes are not utf8"))
}
fn header_name<'a, E: FullError<&'a [u8], StompParseError>>(
input: &'a [u8],
) -> IResult<&'a [u8], &'a str, E> {
context(
"header name",
map_res(terminated(header_section, char(':')), into_string),
)(input)
}
fn header_value<'a, E: FullError<&'a [u8], StompParseError>>(
input: &'a [u8],
) -> IResult<&'a [u8], &'a str, E> {
context(
"header value",
map_res(terminated(header_section, line_ending), into_string),
)(input)
}
fn disallowed_header_parser<'a, E: 'a + FullError<&'a [u8], StompParseError>>(
name: &'a str,
) -> Box<dyn HeaderParser<'a, E>> {
Box::new(map_res(header_value, move |_| {
Err(StompParseError::new(format!(
"Unexpected header '{}' encountered",
name
)))
}))
}
fn known_header_parser<'a, E: 'a + FullError<&'a [u8], StompParseError>>(
parser: Box<dyn Fn(&str) -> Result<Header, StompParseError> + 'a>,
) -> Box<dyn HeaderParser<'a, E>> {
Box::new(map_res(header_value, parser))
}
#[cfg(test)]
mod tests {
use either::Either;
use nom::error::dbg_dmp;
use nom::error::VerboseError;
use super::headers_parser;
use crate::error::{FullError, StompParseError};
use crate::model::headers::*;
use nom::IResult;
use std::vec::Vec;
fn header<E: 'static + FullError<&'static [u8], StompParseError> + std::fmt::Debug>(
input: &'static [u8],
) -> IResult<&'static [u8], Header, E> {
headers(input).map(|x| {
let bytes = x.0;
let mut vec = x.1;
(bytes, vec.pop().unwrap())
})
}
fn headers<E: 'static + FullError<&'static [u8], StompParseError> + std::fmt::Debug>(
input: &'static [u8],
) -> IResult<&'static [u8], Vec<Header>, E> {
dbg_dmp(
|input| {
headers_parser(
Vec::new(),
vec![
HeaderType::HeartBeat,
HeaderType::Destination,
HeaderType::Host,
],
true,
)
.parse(input)
},
"header_line",
)(input)
}
fn headers_no_custom<
E: 'static + FullError<&'static [u8], StompParseError> + std::fmt::Debug,
>(
input: &'static [u8],
) -> IResult<&'static [u8], Vec<Header>, E> {
dbg_dmp(
|input| {
headers_parser(
Vec::new(),
vec![
HeaderType::HeartBeat,
HeaderType::Destination,
HeaderType::Host,
],
false,
)
.parse(input)
},
"header_line",
)(input)
}
fn assert_custom_header(
input: &'static str,
expected_key: &'static str,
expected_value: &'static str,
expected_decoded_key: Option<&'static str>,
expected_decoded_value: Option<&'static str>,
) {
let result = headers::<VerboseError<&'static [u8]>>(input.as_bytes())
.unwrap()
.1;
if let Header::Custom(value) = &result[0] {
assert_eq!(expected_key, value.header_name());
check_raw_and_decoded(
expected_key,
value.header_name(),
expected_decoded_key,
value.decoded_name(),
);
check_raw_and_decoded(
expected_value,
value.value(),
expected_decoded_value,
value.decoded_value(),
);
} else {
panic!("Expected custom header");
}
}
fn check_raw_and_decoded(
expected_value: &str,
actual_value: &str,
expected_decoded_value: Option<&str>,
actual_decoded: Result<Either<&str, String>, StompParseError>,
) {
assert_eq!(expected_value, actual_value);
if let Some(expected_decoded_value) = expected_decoded_value {
match actual_decoded {
Ok(Either::Left(val)) => {
assert_eq!(expected_decoded_value, val);
}
Ok(Either::Right(val)) => {
assert_eq!(expected_decoded_value, &val);
}
Err(_) => {
panic!("Decode failed!")
}
}
}
}
#[test]
fn header_line_terminated_by_rn() {
assert_custom_header("abc:def\r\n\n", "abc", "def", Some("abc"), Some("def"));
}
#[test]
fn header_line_terminated_by_n() {
assert_custom_header("abc:def\n\n", "abc", "def", Some("abc"), None);
}
#[test]
fn header_with_cr_fails() {
let result = dbg_dmp(header::<VerboseError<&[u8]>>, "header_line")(b"ab\rc:def\n");
assert!(result.is_err());
}
#[test]
fn header_with_nl_fails() {
let result = dbg_dmp(header::<VerboseError<&[u8]>>, "header_line")(b"ab\nc:def\n");
assert!(result.is_err());
}
#[test]
fn header_with_colon_fails() {
let result = dbg_dmp(header::<VerboseError<&[u8]>>, "header_line")(b"abc:d:ef\n");
assert!(result.is_err());
}
use nom::bytes::complete::{escaped, is_not};
use nom::character::complete::one_of;
fn esc(input: &[u8]) -> IResult<&[u8], &[u8]> {
escaped(is_not("\\:\n\r"), '\\', one_of("rn:\\"))(input)
}
#[test]
fn test_escaped() {
let (_, matched) = esc(b"a\\rbc:def\n\n" as &[u8]).expect("Should be fine");
assert_eq!(b"a\\rbc", matched)
}
#[test]
fn header_accepts_escaped_cr() {
assert_custom_header("a\\rbc:def\n\n", "a\\rbc", "def", Some("a\rbc"), None);
}
#[test]
fn header_line_accepts_escaped_nl() {
assert_custom_header(
"abc:d\\nef\n\n",
"abc",
"d\\nef",
Some("abc"),
Some("d\nef"),
);
}
#[test]
fn header_line_accepts_escaped_colon() {
assert_custom_header("abc:d\\cef\n\n", "abc", "d\\cef", None, Some("d:ef"));
}
#[test]
fn header_accepts_fwd_slash() {
assert_custom_header("abc:d\\\\ef\n\n", "abc", "d\\\\ef", None, Some("d\\ef"));
}
#[test]
fn header_rejects_escaped_tab() {
let result = dbg_dmp(header::<VerboseError<&[u8]>>, "header_line")(b"abc:d\\tef\n\n");
assert!(result.is_err());
}
#[test]
fn header_works_for_custom() {
assert_custom_header(
"a\\rbc:d\\\\ef\n\n",
"a\\rbc",
"d\\\\ef",
Some("a\rbc"),
Some("d\\ef"),
);
}
#[test]
fn header_works_for_host() {
let header = dbg_dmp(header::<VerboseError<&[u8]>>, "header_line")(b"host:d\\nef\n\n")
.unwrap()
.1;
if let Header::Host(value) = header {
assert_eq!("d\\nef", value.value());
} else {
panic!("Expected host header");
}
}
#[test]
fn header_works_for_heart_beat() {
let header = dbg_dmp(header::<VerboseError<&[u8]>>, "header_line")(b"heart-beat:10,20\n\n")
.unwrap()
.1;
if let Header::HeartBeat(value) = header {
assert_eq!(
HeartBeatIntervalls {
supplied: 10,
expected: 20,
},
*value.value()
);
} else {
panic!("Expected heart-beat header");
}
}
#[test]
fn header_is_case_sensitive() {
//heart-beat not recognised
assert_custom_header(
"heArt-beat:10,20\n\n",
"heArt-beat",
"10,20",
Some("heArt-beat"),
None,
);
}
#[test]
fn headers_works_for_no_headers() {
let headers = dbg_dmp(headers::<VerboseError<&[u8]>>, "headers")(b"\n\n")
.unwrap()
.1;
assert_eq!(0, headers.len());
}
#[test]
fn headers_works_for_single_header() {
let headers = dbg_dmp(headers::<VerboseError<&[u8]>>, "headers")(b"heart-beat:10,20\n\n")
.unwrap()
.1;
assert_eq!(1, headers.len());
assert_eq!(
Header::HeartBeat(HeartBeatValue::new(HeartBeatIntervalls {
supplied: 10,
expected: 20,
})),
headers[0]
);
}
#[test]
fn headers_works_for_multiple_headers() {
let headers = dbg_dmp(headers::<VerboseError<&[u8]>>, "headers")(
b"heart-beat:10,20\r\nabc:d\\nef\n\n",
)
.unwrap()
.1;
assert_eq!(2, headers.len());
assert_eq!(
Header::HeartBeat(HeartBeatValue::new(HeartBeatIntervalls {
supplied: 10,
expected: 20,
})),
headers[0]
);
assert_eq!(
Header::Custom(CustomValue::new("abc", "d\\nef")),
headers[1]
);
}
#[test]
fn headers_rejects_custom_when_disallowed() {
let result = dbg_dmp(headers_no_custom::<VerboseError<&[u8]>>, "headers")(
b"heart-beat:10,20\r\nabc:d\\nef\n\n",
);
assert_eq!(true, result.is_err());
}
#[test]
fn headers_fails_when_no_empty_line() {
let headers =
dbg_dmp(headers::<VerboseError<&[u8]>>, "headers")(b"heart-beat:10,20\r\nabc:d\\nef\n");
assert!(headers.is_err());
}
}
|
// Copyright 2020 - 2021 Alex Dukhno
//
// 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 crate::session_old::statement::{Portal, PreparedStatement};
use std::collections::HashMap;
/// Module contains functionality to hold data about `PreparedStatement`
pub mod statement;
/// A `Session` holds SQL state that is attached to a session.
#[derive(Clone, Debug)]
pub struct Session {
/// A map from statement names to parameterized statements
prepared_statements: HashMap<String, PreparedStatement>,
/// A map from statement names to bound statements
portals: HashMap<String, Portal>,
}
impl Default for Session {
fn default() -> Session {
Session {
prepared_statements: HashMap::default(),
portals: HashMap::default(),
}
}
}
impl Session {
/// get `PreparedStatement` by its name
pub fn get_prepared_statement(&mut self, name: &str) -> Option<&mut PreparedStatement> {
self.prepared_statements.get_mut(name)
}
/// save `PreparedStatement` associated with a name
pub fn set_prepared_statement(&mut self, name: String, statement: PreparedStatement) {
self.prepared_statements.insert(name, statement);
}
/// get `Portal` by its name
pub fn get_portal(&self, name: &str) -> Option<&Portal> {
self.portals.get(name)
}
/// save `Portal` associated with a name
pub fn set_portal(&mut self, portal_name: String, portal: Portal) {
self.portals.insert(portal_name, portal);
}
pub fn remove_portal(&mut self, portal_name: &str) {
self.portals.remove(portal_name);
}
}
|
use crate::tiles::*;
use crate::groups::Set::{Chow, Pung, Pair};
pub use std::str::FromStr;
use std::fmt::{Display, Formatter, Error, Debug};
use crate::score::Fu;
/// 複数枚の牌に関する情報
pub trait Tiles {
/// 么九牌を含むかどうか
fn contains_yaotyu(&self) -> bool;
/// 么九牌のみかどうか
fn all_yaotyu(&self) -> bool;
/// 一九牌を含むかどうか
fn contains_terminal(&self) -> bool;
/// 一九牌のみかどうか
fn all_terminal(&self) -> bool;
/// 連続した並び(1,2,3や6,7,8,9など)かどうか
fn is_sequential(&self) -> bool;
/// 刻子のような並び(1,1,1や6,6,6,6など)かどうか
fn is_flat(&self) -> bool;
/// 該当する牌の集計
fn count(&self, tile: &Tile) -> u8;
/// 三色同順,三食同刻の判定に利用する
fn sum_tile(&self) -> Option<Tile>;
}
impl Tiles for Vec<Tile> {
fn contains_yaotyu(&self) -> bool {
self.iter().any(|tile| tile.is_yaotyu())
}
fn all_yaotyu(&self) -> bool {
self.iter().all(|tile| tile.is_yaotyu())
}
fn contains_terminal(&self) -> bool {
self.iter().any(|tile| tile.is_terminal())
}
fn all_terminal(&self) -> bool {
self.iter().all(|tile| tile.is_terminal())
}
fn is_sequential(&self) -> bool {
let mut iter = self.iter().peekable();
while let (Some(n), Some(p)) = (iter.next(), iter.peek()) {
// validation
match n {
Tile::Character(u) => {
if p != &&Tile::Character(u + 1) {
return false;
}
}
Tile::Circle(u) => {
if p != &&Tile::Circle(u + 1) {
return false;
}
}
Tile::Bamboo(u) => {
if p != &&Tile::Bamboo(u + 1) {
return false;
}
}
_ => {
// 字牌は並びを持たない
return false;
}
}
}
return true;
}
fn is_flat(&self) -> bool {
let mut iter = self.iter();
match iter.next() {
Some(tile) => {
iter.all(|t| tile == t)
}
None => {
false
}
}
}
fn count(&self, tile: &Tile) -> u8 {
let mut count: u8 = 0;
for t in self {
if t == tile { count += 1; }
}
count
}
fn sum_tile(&self) -> Option<Tile> {
let mut sum = 0;
self.iter().for_each(|tile| {
sum +=
if tile.is_honours() {
// 字牌は0
0
} else {
match tile {
Tile::Character(u) => u,
Tile::Circle(u) => u,
Tile::Bamboo(u) => u,
_ => unreachable!()
}.clone()
}
});
match self.get(0) {
Some(tile) => {
match tile {
Tile::Character(_) => Some(Tile::Character(sum)),
Tile::Circle(_) => Some(Tile::Circle(sum)),
Tile::Bamboo(_) => Some(Tile::Bamboo(sum)),
_ => None,
}
}
None => None
}
}
}
pub struct TilesNewType(pub Vec<Tile>);
impl FromStr for TilesNewType {
type Err = failure::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut tiles = Vec::with_capacity(14);
// パース
let mut iter = s.chars().peekable();
while let Some(c) = iter.next() {
let tile =
match c.to_string().parse::<u8>() {
Ok(u) => {
if u == 0 {
return Err(format_err!("数字が不正です: {} in {}",u,s));
}
match iter.next() {
Some(c) => {
if Tile::characters_markers().contains(&c) {
// 萬子
Tile::Character(u)
} else if Tile::circles_markers().contains(&c) {
// 筒子
Tile::Circle(u)
} else if Tile::bamboos_markers().contains(&c) {
// 索子
Tile::Bamboo(u)
} else {
match c.to_string().parse::<u8>() {
// 数字
Ok(u2) => {
// 123m456p789sのような省略記法の場合
let mut nums = Vec::with_capacity(14);
nums.push(u);
nums.push(u2);
while let Some(c) = iter.next() {
let mut tiles_tmp: Vec<Tile> =
if Tile::characters_markers().contains(&c) {
// 萬子
nums.iter().map(|u| Tile::Character(u.clone())).collect()
} else if Tile::circles_markers().contains(&c) {
// 筒子
nums.iter().map(|u| Tile::Circle(u.clone())).collect()
} else if Tile::bamboos_markers().contains(&c) {
// 索子
nums.iter().map(|u| Tile::Bamboo(u.clone())).collect()
} else {
match c.to_string().parse::<u8>() {
// 数字の連続
Ok(u) => {
nums.push(u);
continue;
}
// エラー: 全く関係のない文字
Err(_) => {
return Err(format_err!("不正な文字があります: {} in {}",c,s));
}
}
};
tiles.append(&mut tiles_tmp);
break;
}
continue;
}
// エラー(`123s4W`など)
Err(_) => {
return Err(format_err!("不正な文字があります: {} in {}",c,s));
}
}
}
}
None => {
return Err(format_err!("入力に不足があります: {}",s));
}
}
}
Err(_) => {
if Tile::east_markers().contains(&c) {
Wind::East.tile()
} else if Tile::south_markers().contains(&c) {
Wind::South.tile()
} else if Tile::west_markers().contains(&c) {
Wind::West.tile()
} else if Tile::north_markers().contains(&c) {
Wind::North.tile()
} else if Tile::white_markers().contains(&c) {
Dragon::White.tile()
} else if Tile::green_markers().contains(&c) {
Dragon::Green.tile()
} else if Tile::red_markers().contains(&c) {
Dragon::Red.tile()
} else {
return Err(format_err!("入力が不正です: {} in {}",c,s));
}
}
};
tiles.push(tile);
}
Ok(TilesNewType(tiles))
}
}
impl Display for TilesNewType {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let TilesNewType(vec) = &self;
for v in vec {
std::fmt::Display::fmt(v, f)?;
}
Ok(())
}
}
pub struct DisplayVec<T: Display + Debug>(pub Vec<T>);
impl<T: Display + Debug> Display for DisplayVec<T> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let DisplayVec(vec) = &self;
for v in vec {
std::fmt::Display::fmt(v, f)?;
writeln!(f, "")?;
}
Ok(())
}
}
/// 手牌という概念
#[derive(Debug, Clone)]
pub struct Hand {
/// 手牌(晒していない手牌)
pub tiles: Vec<Tile>,
/// 鳴きで成立した面子
pub open_sets: Vec<OpenSet>,
/// 当たり牌
pub winning: Tile,
}
impl Hand {
pub fn tiles(&self) -> &Vec<Tile> {
&self.tiles
}
}
impl FromStr for Hand {
type Err = failure::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// 手牌
let mut tiles = Vec::with_capacity(14);
let mut open_sets = Vec::with_capacity(4);
// パース
let mut iter = s.chars().peekable();
let mut store_tmp = String::new();
while let Some(c) = iter.next() {
if c == '[' {
// これまでの並びを登録
if store_tmp.len() != 0 {
let TilesNewType(mut tiles_tmp) = TilesNewType::from_str(&store_tmp)?;
tiles.append(&mut tiles_tmp);
}
// 鳴き成立の面子の譜面を読み取る
let mut chars = Vec::new();
while let Some(c) = iter.next() {
if c == ']' { break; }
chars.push(c);
}
store_tmp = chars.iter().collect();
// 登録
open_sets.push(OpenSet::from_str(&store_tmp)?);
// 一時変数を初期化
store_tmp = String::new();
} else if c == '(' {
// これまでの並びを登録
if store_tmp.len() != 0 {
let TilesNewType(mut tiles_tmp) = TilesNewType::from_str(&store_tmp)?;
tiles.append(&mut tiles_tmp);
}
// 鳴き成立の面子の譜面を読み取る
let mut chars = Vec::new();
while let Some(c) = iter.next() {
if c == ')' { break; }
chars.push(c);
}
store_tmp = chars.iter().collect();
let TilesNewType(tiles_tmp) = TilesNewType::from_str(&store_tmp)?;
// 登録
open_sets.push(OpenSet::ConcealedKong(tiles_tmp));
// 一時変数を初期化
store_tmp = String::new();
} else {
store_tmp.push(c);
}
}
if store_tmp.len() != 0 {
let TilesNewType(mut tiles_tmp) = TilesNewType::from_str(&store_tmp)?;
tiles.append(&mut tiles_tmp);
}
// 少牌or多牌
if tiles.len() + 3 * open_sets.len() < 14 {
return Err(format_err!("少牌です: {}",s));
} else if tiles.len() + 3 * open_sets.len() > 14 {
return Err(format_err!("多牌です: {}",s));
}
// 当たり牌
let winning = tiles.last().unwrap().clone();
// ソート
tiles.sort();
println!("{}", &Hand { tiles: tiles.clone(), open_sets: open_sets.clone(), winning: winning.clone() });
Ok(Hand { tiles, open_sets, winning })
}
}
impl Display for Hand {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
TilesNewType(self.tiles.clone()).fmt(f)?;
write!(f, " <{}> ", &self.winning)?;
self.open_sets.iter().try_for_each(|set| std::fmt::Display::fmt(set, f))
}
}
/// 面子
pub trait Sets {
fn fu(&self) -> Fu;
fn all_character(&self) -> bool;
fn all_circle(&self) -> bool;
fn all_bamboo(&self) -> bool;
fn all_honor(&self) -> bool;
fn consists_of(&self, tiles: &Vec<Tile>) -> bool {
self.vec().iter().all(|t| {
tiles.contains(t)
})
}
fn vec(&self) -> Vec<Tile>;
}
/// 鳴きで成立した面子
#[derive(Debug, Clone, PartialEq)]
pub enum OpenSet {
/// ポン
Pung(Vec<Tile>),
/// チー
Chow(Vec<Tile>),
/// 明槓
Kong(Vec<Tile>),
/// 暗槓
ConcealedKong(Vec<Tile>),
}
impl FromStr for OpenSet {
type Err = failure::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// 中身
let TilesNewType(mut vec) = TilesNewType::from_str(&s)?;
vec.sort();
// validation
match vec.len() {
3 => {
if vec.is_flat() {
// 刻子
Ok(OpenSet::Pung(vec))
} else if vec.is_sequential() {
// 順子
Ok(OpenSet::Chow(vec))
} else {
Err(format_err!("入力が不正です: [{}]", s))
}
}
4 => {
if vec.is_flat() {
// 明槓 (暗槓はHand.parse()時に判断する)
Ok(OpenSet::Kong(vec))
} else {
Err(format_err!("入力が不正です: [{}]", s))
}
}
_ => {
Err(format_err!("入力が不正です: [{}]", s))
}
}
}
}
impl Display for OpenSet {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match &self {
OpenSet::Pung(tiles) => {
write!(f, "[")?;
TilesNewType(tiles.clone()).fmt(f)?;
write!(f, "]")
}
OpenSet::Chow(tiles) => {
write!(f, "[")?;
TilesNewType(tiles.clone()).fmt(f)?;
write!(f, "]")
}
OpenSet::Kong(tiles) => {
write!(f, "[")?;
TilesNewType(tiles.clone()).fmt(f)?;
write!(f, "]")
}
OpenSet::ConcealedKong(tiles) => {
write!(f, "(")?;
TilesNewType(tiles.clone()).fmt(f)?;
write!(f, ")")
}
}
}
}
impl Sets for OpenSet {
fn fu(&self) -> Fu {
match &self {
OpenSet::Pung(vec) => {
Fu(if vec.all_yaotyu() {
4
} else { 2 })
}
OpenSet::ConcealedKong(vec) => {
Fu(if vec.all_yaotyu() {
32
} else { 16 })
}
OpenSet::Kong(vec) => {
Fu(if vec.all_yaotyu() {
16
} else { 8 })
}
_ => Fu(0)
}
}
fn all_character(&self) -> bool {
let vec = match &self {
OpenSet::Chow(vec) => vec,
OpenSet::Pung(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Character(_) => true,
_ => false,
})
}
fn all_circle(&self) -> bool {
let vec = match &self {
OpenSet::Chow(vec) => vec,
OpenSet::Pung(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Circle(_) => true,
_ => false,
})
}
fn all_bamboo(&self) -> bool {
let vec = match &self {
OpenSet::Chow(vec) => vec,
OpenSet::Pung(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Bamboo(_) => true,
_ => false,
})
}
fn all_honor(&self) -> bool {
let vec = match &self {
OpenSet::Chow(vec) => vec,
OpenSet::Pung(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Honour(_) => true,
_ => false,
})
}
fn vec(&self) -> Vec<Tile> {
match &self {
OpenSet::Chow(vec) => vec,
OpenSet::Pung(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.clone()
}
}
impl Tiles for OpenSet {
fn contains_yaotyu(&self) -> bool {
match &self {
OpenSet::Pung(vec) => vec,
OpenSet::Chow(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.contains_yaotyu()
}
fn all_yaotyu(&self) -> bool {
match &self {
OpenSet::Pung(vec) => vec,
OpenSet::Chow(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.all_yaotyu()
}
fn contains_terminal(&self) -> bool {
match &self {
OpenSet::Pung(vec) => vec,
OpenSet::Chow(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.contains_terminal()
}
fn all_terminal(&self) -> bool {
match &self {
OpenSet::Pung(vec) => vec,
OpenSet::Chow(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.all_terminal()
}
fn is_sequential(&self) -> bool {
match &self {
OpenSet::Pung(vec) => vec,
OpenSet::Chow(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.is_sequential()
}
fn is_flat(&self) -> bool {
match &self {
OpenSet::Pung(vec) => vec,
OpenSet::Chow(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.is_flat()
}
fn count(&self, tile: &Tile) -> u8 {
match &self {
OpenSet::Pung(vec) => vec,
OpenSet::Chow(vec) => vec,
OpenSet::Kong(vec) => vec,
OpenSet::ConcealedKong(vec) => vec,
}.count(tile)
}
fn sum_tile(&self) -> Option<Tile> {
match &self {
OpenSet::Pung(vec) => vec.clone(),
OpenSet::Chow(vec) => vec.clone(),
OpenSet::Kong(vec) => {
let mut vec = vec.clone();
vec.remove(0);
vec
}
OpenSet::ConcealedKong(vec) => {
let mut vec = vec.clone();
vec.remove(0);
vec
}
}.sum_tile()
}
}
/// 手牌の中で成立した面子
#[derive(Debug, Clone, PartialEq)]
pub enum Set {
/// 順子
Chow(Vec<Tile>),
/// 刻子
Pung(Vec<Tile>),
/// 対子
Pair(Vec<Tile>),
}
impl Set {
pub fn new(vec: Vec<Tile>) -> Result<Self, failure::Error> {
if vec.is_sequential() {
Ok(Chow(vec))
} else if vec.is_flat() {
if vec.len() == 2 {
Ok(Pair(vec))
} else {
Ok(Pung(vec))
}
} else {
Err(format_err!("面子ではありません: {:?}",vec))
}
}
}
impl Sets for Set {
fn fu(&self) -> Fu {
match &self {
Set::Pung(vec) => {
Fu(if vec.all_yaotyu() {
8
} else { 4 })
}
_ => Fu(0)
}
}
fn all_character(&self) -> bool {
let vec = match &self {
Set::Chow(vec) => vec,
Set::Pung(vec) => vec,
Set::Pair(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Character(_) => true,
_ => false,
})
}
fn all_circle(&self) -> bool {
let vec = match &self {
Set::Chow(vec) => vec,
Set::Pung(vec) => vec,
Set::Pair(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Circle(_) => true,
_ => false,
})
}
fn all_bamboo(&self) -> bool {
let vec = match &self {
Set::Chow(vec) => vec,
Set::Pung(vec) => vec,
Set::Pair(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Bamboo(_) => true,
_ => false,
})
}
fn all_honor(&self) -> bool {
let vec = match &self {
Set::Chow(vec) => vec,
Set::Pung(vec) => vec,
Set::Pair(vec) => vec,
};
vec.iter().all(|tile| match tile {
Tile::Honour(_) => true,
_ => false,
})
}
fn vec(&self) -> Vec<Tile> {
match &self {
Set::Chow(vec) => vec,
Set::Pung(vec) => vec,
Set::Pair(vec) => vec,
}.clone()
}
}
impl Display for Set {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let tiles = match &self {
Set::Pung(tiles) => tiles,
Set::Chow(tiles) => tiles,
Set::Pair(tiles) => tiles,
}.clone();
TilesNewType(tiles).fmt(f)
}
}
impl Tiles for Set {
fn contains_yaotyu(&self) -> bool {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.contains_yaotyu()
}
fn all_yaotyu(&self) -> bool {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.all_yaotyu()
}
fn contains_terminal(&self) -> bool {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.contains_terminal()
}
fn all_terminal(&self) -> bool {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.all_terminal()
}
fn is_sequential(&self) -> bool {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.is_sequential()
}
fn is_flat(&self) -> bool {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.is_flat()
}
fn count(&self, tile: &Tile) -> u8 {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.count(tile)
}
fn sum_tile(&self) -> Option<Tile> {
match &self {
Chow(vec) => vec,
Pung(vec) => vec,
Pair(vec) => vec,
}.sum_tile()
}
} |
// TODO: compare these to the ones in the ropey examples
use ropey::{iter::Chunks, str_utils::byte_to_char_idx, RopeSlice};
use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
use unicode_width::UnicodeWidthStr;
// hard code for base 10 digits,
// because I don't think we'll have any other kind
pub fn digit_count(mut n: usize) -> usize {
let mut d = 0;
loop {
n /= 10;
d += 1;
if n == 0 {
return d;
}
}
}
//=============================================================
pub fn grapheme_width(slice: &RopeSlice) -> usize {
use term_ui::smallstring::SmallString;
if let Some(text) = slice.as_str() {
return UnicodeWidthStr::width(text);
} else {
let text = SmallString::from_rope_slice(slice);
return UnicodeWidthStr::width(&text[..]);
}
}
/// Finds the previous grapheme boundary before the given char position.
pub fn prev_grapheme_boundary(slice: &RopeSlice, char_idx: usize) -> usize {
// Bounds check
debug_assert!(char_idx <= slice.len_chars());
// We work with bytes for this, so convert.
let byte_idx = slice.char_to_byte(char_idx);
// Get the chunk with our byte index in it.
let (mut chunk, mut chunk_byte_idx, mut chunk_char_idx, _) = slice.chunk_at_byte(byte_idx);
// Set up the grapheme cursor.
let mut gc = GraphemeCursor::new(byte_idx, slice.len_bytes(), true);
// Find the previous grapheme cluster boundary.
loop {
match gc.prev_boundary(chunk, chunk_byte_idx) {
Ok(None) => return 0,
Ok(Some(n)) => {
let tmp = byte_to_char_idx(chunk, n - chunk_byte_idx);
return chunk_char_idx + tmp;
}
Err(GraphemeIncomplete::PrevChunk) => {
let (a, b, c, _) = slice.chunk_at_byte(chunk_byte_idx - 1);
chunk = a;
chunk_byte_idx = b;
chunk_char_idx = c;
}
Err(GraphemeIncomplete::PreContext(n)) => {
let ctx_chunk = slice.chunk_at_byte(n - 1).0;
gc.provide_context(ctx_chunk, n - ctx_chunk.len());
}
_ => unreachable!(),
}
}
}
/// Finds the next grapheme boundary after the given char position.
pub fn next_grapheme_boundary(slice: &RopeSlice, char_idx: usize) -> usize {
// Bounds check
debug_assert!(char_idx <= slice.len_chars());
// We work with bytes for this, so convert.
let byte_idx = slice.char_to_byte(char_idx);
// Get the chunk with our byte index in it.
let (mut chunk, mut chunk_byte_idx, mut chunk_char_idx, _) = slice.chunk_at_byte(byte_idx);
// Set up the grapheme cursor.
let mut gc = GraphemeCursor::new(byte_idx, slice.len_bytes(), true);
// Find the next grapheme cluster boundary.
loop {
match gc.next_boundary(chunk, chunk_byte_idx) {
Ok(None) => return slice.len_chars(),
Ok(Some(n)) => {
let tmp = byte_to_char_idx(chunk, n - chunk_byte_idx);
return chunk_char_idx + tmp;
}
Err(GraphemeIncomplete::NextChunk) => {
chunk_byte_idx += chunk.len();
let (a, _, c, _) = slice.chunk_at_byte(chunk_byte_idx);
chunk = a;
chunk_char_idx = c;
}
Err(GraphemeIncomplete::PreContext(n)) => {
let ctx_chunk = slice.chunk_at_byte(n - 1).0;
gc.provide_context(ctx_chunk, n - ctx_chunk.len());
}
_ => unreachable!(),
}
}
}
/// Returns whether the given char position is a grapheme boundary.
pub fn is_grapheme_boundary(slice: &RopeSlice, char_idx: usize) -> bool {
// Bounds check
debug_assert!(char_idx <= slice.len_chars());
// We work with bytes for this, so convert.
let byte_idx = slice.char_to_byte(char_idx);
// Get the chunk with our byte index in it.
let (chunk, chunk_byte_idx, _, _) = slice.chunk_at_byte(byte_idx);
// Set up the grapheme cursor.
let mut gc = GraphemeCursor::new(byte_idx, slice.len_bytes(), true);
// Determine if the given position is a grapheme cluster boundary.
loop {
match gc.is_boundary(chunk, chunk_byte_idx) {
Ok(n) => return n,
Err(GraphemeIncomplete::PreContext(n)) => {
let (ctx_chunk, ctx_byte_start, _, _) = slice.chunk_at_byte(n - 1);
gc.provide_context(ctx_chunk, ctx_byte_start);
}
_ => unreachable!(),
}
}
}
/// An iterator over the graphemes of a RopeSlice.
pub struct RopeGraphemes<'a> {
text: RopeSlice<'a>,
chunks: Chunks<'a>,
cur_chunk: &'a str,
cur_chunk_start: usize,
cursor: GraphemeCursor,
}
impl<'a> RopeGraphemes<'a> {
pub fn new<'b>(slice: &RopeSlice<'b>) -> RopeGraphemes<'b> {
let mut chunks = slice.chunks();
let first_chunk = chunks.next().unwrap_or("");
RopeGraphemes {
text: *slice,
chunks: chunks,
cur_chunk: first_chunk,
cur_chunk_start: 0,
cursor: GraphemeCursor::new(0, slice.len_bytes(), true),
}
}
}
impl<'a> Iterator for RopeGraphemes<'a> {
type Item = RopeSlice<'a>;
fn next(&mut self) -> Option<RopeSlice<'a>> {
let a = self.cursor.cur_cursor();
let b;
loop {
match self
.cursor
.next_boundary(self.cur_chunk, self.cur_chunk_start)
{
Ok(None) => {
return None;
}
Ok(Some(n)) => {
b = n;
break;
}
Err(GraphemeIncomplete::NextChunk) => {
self.cur_chunk_start += self.cur_chunk.len();
self.cur_chunk = self.chunks.next().unwrap_or("");
}
_ => unreachable!(),
}
}
if a < self.cur_chunk_start {
let a_char = self.text.byte_to_char(a);
let b_char = self.text.byte_to_char(b);
Some(self.text.slice(a_char..b_char))
} else {
let a2 = a - self.cur_chunk_start;
let b2 = b - self.cur_chunk_start;
Some((&self.cur_chunk[a2..b2]).into())
}
}
}
//=============================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn digit_count_base_10() {
assert_eq!(digit_count(0), 1);
assert_eq!(digit_count(9), 1);
assert_eq!(digit_count(10), 2);
assert_eq!(digit_count(99), 2);
assert_eq!(digit_count(100), 3);
assert_eq!(digit_count(999), 3);
assert_eq!(digit_count(1000), 4);
assert_eq!(digit_count(9999), 4);
assert_eq!(digit_count(10000), 5);
assert_eq!(digit_count(99999), 5);
assert_eq!(digit_count(100000), 6);
assert_eq!(digit_count(999999), 6);
assert_eq!(digit_count(1000000), 7);
assert_eq!(digit_count(9999999), 7);
}
}
|
//! Datastructures and functions for building and simulating a redcode core
mod mars;
pub use self::mars::{
Mars,
LoadResult,
LoadError,
SimulationResult,
SimulationEvent,
SimulationError
};
mod builder;
pub use self::builder::{
MarsBuilder,
BuilderError
};
|
//! Backoff functionality.
#![deny(rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms)]
#![warn(
missing_copy_implementations,
missing_debug_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 observability_deps::tracing::warn;
use rand::prelude::*;
use snafu::Snafu;
use std::ops::ControlFlow;
use std::time::Duration;
/// Exponential backoff with jitter
///
/// See <https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/>
#[derive(Debug, Clone, PartialEq)]
#[allow(missing_copy_implementations)]
pub struct BackoffConfig {
/// Initial backoff.
pub init_backoff: Duration,
/// Maximum backoff.
pub max_backoff: Duration,
/// Multiplier for each backoff round.
pub base: f64,
/// Timeout until we try to retry.
pub deadline: Option<Duration>,
}
impl Default for BackoffConfig {
fn default() -> Self {
Self {
init_backoff: Duration::from_millis(100),
max_backoff: Duration::from_secs(500),
base: 3.,
deadline: None,
}
}
}
/// Error after giving up retrying.
#[derive(Debug, Snafu, PartialEq, Eq)]
#[allow(missing_copy_implementations, missing_docs)]
pub enum BackoffError<E>
where
E: std::error::Error + 'static,
{
#[snafu(display("Retry did not exceed within {deadline:?}: {source}"))]
DeadlineExceeded { deadline: Duration, source: E },
}
/// Backoff result.
pub type BackoffResult<T, E> = Result<T, BackoffError<E>>;
/// [`Backoff`] can be created from a [`BackoffConfig`]
///
/// Consecutive calls to [`Backoff::next`] will return the next backoff interval
///
pub struct Backoff {
init_backoff: f64,
next_backoff_secs: f64,
max_backoff_secs: f64,
base: f64,
total: f64,
deadline: Option<f64>,
rng: Option<Box<dyn RngCore + Sync + Send>>,
}
impl std::fmt::Debug for Backoff {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Backoff")
.field("init_backoff", &self.init_backoff)
.field("next_backoff_secs", &self.next_backoff_secs)
.field("max_backoff_secs", &self.max_backoff_secs)
.field("base", &self.base)
.field("total", &self.total)
.field("deadline", &self.deadline)
.finish()
}
}
impl Backoff {
/// Create a new [`Backoff`] from the provided [`BackoffConfig`].
///
/// # Pancis
/// Panics if [`BackoffConfig::base`] is not finite or < 1.0.
pub fn new(config: &BackoffConfig) -> Self {
Self::new_with_rng(config, None)
}
/// Creates a new `Backoff` with the optional `rng`.
///
/// Used [`rand::thread_rng()`] if no rng provided.
///
/// See [`new`](Self::new) for panic handling.
pub fn new_with_rng(
config: &BackoffConfig,
rng: Option<Box<dyn RngCore + Sync + Send>>,
) -> Self {
assert!(
config.base.is_finite(),
"Backoff base ({}) must be finite.",
config.base,
);
assert!(
config.base >= 1.0,
"Backoff base ({}) must be greater or equal than 1.",
config.base,
);
let max_backoff = config.max_backoff.as_secs_f64();
let init_backoff = config.init_backoff.as_secs_f64().min(max_backoff);
Self {
init_backoff,
next_backoff_secs: init_backoff,
max_backoff_secs: max_backoff,
base: config.base,
total: 0.0,
deadline: config.deadline.map(|d| d.as_secs_f64()),
rng,
}
}
/// Fade this backoff over to a different backoff config.
pub fn fade_to(&mut self, config: &BackoffConfig) {
// Note: `new` won't have the same RNG, but this doesn't matter
let new = Self::new(config);
*self = Self {
init_backoff: new.init_backoff,
next_backoff_secs: self.next_backoff_secs,
max_backoff_secs: new.max_backoff_secs,
base: new.base,
total: self.total,
deadline: new.deadline,
rng: self.rng.take(),
};
}
/// Perform an async operation that retries with a backoff
pub async fn retry_with_backoff<F, F1, B, E>(
&mut self,
task_name: &str,
mut do_stuff: F,
) -> BackoffResult<B, E>
where
F: (FnMut() -> F1) + Send,
F1: std::future::Future<Output = ControlFlow<B, E>> + Send,
E: std::error::Error + Send + 'static,
{
loop {
// first execute `F` and then use it, so we can avoid `F: Sync`.
let do_stuff = do_stuff();
let e = match do_stuff.await {
ControlFlow::Break(r) => break Ok(r),
ControlFlow::Continue(e) => e,
};
let backoff = match self.next() {
Some(backoff) => backoff,
None => {
return Err(BackoffError::DeadlineExceeded {
deadline: Duration::from_secs_f64(self.deadline.expect("deadline")),
source: e,
});
}
};
warn!(
error=%e,
task_name,
backoff_secs = backoff.as_secs(),
"request encountered non-fatal error - backing off",
);
tokio::time::sleep(backoff).await;
}
}
/// Retry all errors.
pub async fn retry_all_errors<F, F1, B, E>(
&mut self,
task_name: &str,
mut do_stuff: F,
) -> BackoffResult<B, E>
where
F: (FnMut() -> F1) + Send,
F1: std::future::Future<Output = Result<B, E>> + Send,
E: std::error::Error + Send + 'static,
{
self.retry_with_backoff(task_name, move || {
// first execute `F` and then use it, so we can avoid `F: Sync`.
let do_stuff = do_stuff();
async {
match do_stuff.await {
Ok(b) => ControlFlow::Break(b),
Err(e) => ControlFlow::Continue(e),
}
}
})
.await
}
}
impl Iterator for Backoff {
type Item = Duration;
/// Returns the next backoff duration to wait for, if any
fn next(&mut self) -> Option<Self::Item> {
let range = self.init_backoff..=(self.next_backoff_secs * self.base);
let rand_backoff = match self.rng.as_mut() {
Some(rng) => rng.gen_range(range),
None => thread_rng().gen_range(range),
};
let next_backoff = self.max_backoff_secs.min(rand_backoff);
self.total += next_backoff;
let res = std::mem::replace(&mut self.next_backoff_secs, next_backoff);
if let Some(deadline) = self.deadline {
if self.total >= deadline {
return None;
}
}
duration_try_from_secs_f64(res)
}
}
const MAX_F64_SECS: f64 = 1_000_000.0;
/// Try to get `Duration` from `f64` secs.
///
/// This is required till <https://github.com/rust-lang/rust/issues/83400> is resolved.
fn duration_try_from_secs_f64(secs: f64) -> Option<Duration> {
(secs.is_finite() && (0.0..=MAX_F64_SECS).contains(&secs))
.then(|| Duration::from_secs_f64(secs))
}
#[cfg(test)]
mod tests {
use super::*;
use rand::rngs::mock::StepRng;
#[test]
fn test_backoff() {
let init_backoff_secs = 1.;
let max_backoff_secs = 500.;
let base = 3.;
let config = BackoffConfig {
init_backoff: Duration::from_secs_f64(init_backoff_secs),
max_backoff: Duration::from_secs_f64(max_backoff_secs),
deadline: None,
base,
};
let assert_fuzzy_eq = |a: f64, b: f64| assert!((b - a).abs() < 0.0001, "{a} != {b}");
// Create a static rng that takes the minimum of the range
let rng = Box::new(StepRng::new(0, 0));
let mut backoff = Backoff::new_with_rng(&config, Some(rng));
for _ in 0..20 {
assert_eq!(backoff.next().unwrap().as_secs_f64(), init_backoff_secs);
}
// Create a static rng that takes the maximum of the range
let rng = Box::new(StepRng::new(u64::MAX, 0));
let mut backoff = Backoff::new_with_rng(&config, Some(rng));
for i in 0..20 {
let value = (base.powi(i) * init_backoff_secs).min(max_backoff_secs);
assert_fuzzy_eq(backoff.next().unwrap().as_secs_f64(), value);
}
// Create a static rng that takes the mid point of the range
let rng = Box::new(StepRng::new(u64::MAX / 2, 0));
let mut backoff = Backoff::new_with_rng(&config, Some(rng));
let mut value = init_backoff_secs;
for _ in 0..20 {
assert_fuzzy_eq(backoff.next().unwrap().as_secs_f64(), value);
value =
(init_backoff_secs + (value * base - init_backoff_secs) / 2.).min(max_backoff_secs);
}
// deadline
let rng = Box::new(StepRng::new(u64::MAX, 0));
let deadline = Duration::from_secs_f64(init_backoff_secs);
let mut backoff = Backoff::new_with_rng(
&BackoffConfig {
deadline: Some(deadline),
..config
},
Some(rng),
);
assert_eq!(backoff.next(), None);
}
#[test]
fn test_overflow() {
let rng = Box::new(StepRng::new(u64::MAX, 0));
let cfg = BackoffConfig {
init_backoff: Duration::MAX,
max_backoff: Duration::MAX,
..Default::default()
};
let mut backoff = Backoff::new_with_rng(&cfg, Some(rng));
assert_eq!(backoff.next(), None);
}
#[test]
fn test_duration_try_from_f64() {
for d in [-0.1, f64::INFINITY, f64::NAN, MAX_F64_SECS + 0.1] {
assert!(duration_try_from_secs_f64(d).is_none());
}
for d in [0.0, MAX_F64_SECS] {
assert!(duration_try_from_secs_f64(d).is_some());
}
}
#[test]
fn test_max_backoff_smaller_init() {
let rng = Box::new(StepRng::new(u64::MAX, 0));
let cfg = BackoffConfig {
init_backoff: Duration::from_secs(2),
max_backoff: Duration::from_secs(1),
..Default::default()
};
let mut backoff = Backoff::new_with_rng(&cfg, Some(rng));
assert_eq!(backoff.next(), Some(Duration::from_secs(1)));
assert_eq!(backoff.next(), Some(Duration::from_secs(1)));
}
#[test]
#[should_panic(expected = "Backoff base (inf) must be finite.")]
fn test_panic_inf_base() {
let cfg = BackoffConfig {
base: f64::INFINITY,
..Default::default()
};
Backoff::new(&cfg);
}
#[test]
#[should_panic(expected = "Backoff base (NaN) must be finite.")]
fn test_panic_nan_base() {
let cfg = BackoffConfig {
base: f64::NAN,
..Default::default()
};
Backoff::new(&cfg);
}
#[test]
#[should_panic(expected = "Backoff base (0) must be greater or equal than 1.")]
fn test_panic_zero_base() {
let cfg = BackoffConfig {
base: 0.0,
..Default::default()
};
Backoff::new(&cfg);
}
#[test]
fn test_constant_backoff() {
let rng = Box::new(StepRng::new(u64::MAX, 0));
let cfg = BackoffConfig {
init_backoff: Duration::from_secs(1),
max_backoff: Duration::from_secs(1),
base: 1.0,
..Default::default()
};
let mut backoff = Backoff::new_with_rng(&cfg, Some(rng));
assert_eq!(backoff.next(), Some(Duration::from_secs(1)));
assert_eq!(backoff.next(), Some(Duration::from_secs(1)));
}
}
|
//! Methods for dealing with segments of a segmented sieve represented in a memory-efficient way.
//!
//! # Overview
//!
//! A segment represents the numbers in a given range which are prime. The range must begin and
//! end on a multiple of 240, due to the way that the segment is represented internally, and is
//! indexed from 0, so that the zeroth element is the beginning of the range, and so on. In
//! reality, the only indices which make sense are those which are 1, 7, 11, 13, 17, 19, 23 or 29
//! more than a multiple of 30, and any other indices will always return `false`.
//!
//! # Details
//!
//! Each group of 30 numbers is represented as a single byte. This is possible since, by
//! eliminating multiples of 2, 3 and 5, only 8 numbers in the given segment can possibly be
//! primes - we need not bother to store any information for the other numbers. These bytes are
//! grouped together and stored internally as 64-bit integers.
pub const MODULUS: u64 = 240;
/// Calculate the internal index at which the bit for a given index into the range is found.
#[inline]
fn index_for(idx: u64) -> (bool, usize, u64) {
const POS: &'static [(bool, u64); MODULUS as usize] =
// 0
&[(false, 1 << 0), (true, 1 << 0), (false, 1 << 1), (false, 1 << 1), (false, 1 << 1),
(false, 1 << 1), (false, 1 << 1), (true, 1 << 1), (false, 1 << 2), (false, 1 << 2),
(false, 1 << 2), (true, 1 << 2), (false, 1 << 3), (true, 1 << 3), (false, 1 << 4),
(false, 1 << 4), (false, 1 << 4), (true, 1 << 4), (false, 1 << 5), (true, 1 << 5),
(false, 1 << 6), (false, 1 << 6), (false, 1 << 6), (true, 1 << 6), (false, 1 << 7),
(false, 1 << 7), (false, 1 << 7), (false, 1 << 7), (false, 1 << 7), (true, 1 << 7),
// 30
(false, 1 << 8), (true, 1 << 8), (false, 1 << 9), (false, 1 << 9), (false, 1 << 9),
(false, 1 << 9), (false, 1 << 9), (true, 1 << 9), (false, 1 << 10), (false, 1 << 10),
(false, 1 << 10), (true, 1 << 10), (false, 1 << 11), (true, 1 << 11), (false, 1 << 12),
(false, 1 << 12), (false, 1 << 12), (true, 1 << 12), (false, 1 << 13), (true, 1 << 13),
(false, 1 << 14), (false, 1 << 14), (false, 1 << 14), (true, 1 << 14), (false, 1 << 15),
(false, 1 << 15), (false, 1 << 15), (false, 1 << 15), (false, 1 << 15), (true, 1 << 15),
// 60
(false, 1 << 16), (true, 1 << 16), (false, 1 << 17), (false, 1 << 17), (false, 1 << 17),
(false, 1 << 17), (false, 1 << 17), (true, 1 << 17), (false, 1 << 18), (false, 1 << 18),
(false, 1 << 18), (true, 1 << 18), (false, 1 << 19), (true, 1 << 19), (false, 1 << 20),
(false, 1 << 20), (false, 1 << 20), (true, 1 << 20), (false, 1 << 21), (true, 1 << 21),
(false, 1 << 22), (false, 1 << 22), (false, 1 << 22), (true, 1 << 22), (false, 1 << 23),
(false, 1 << 23), (false, 1 << 23), (false, 1 << 23), (false, 1 << 23), (true, 1 << 23),
// 90
(false, 1 << 24), (true, 1 << 24), (false, 1 << 25), (false, 1 << 25), (false, 1 << 25),
(false, 1 << 25), (false, 1 << 25), (true, 1 << 25), (false, 1 << 26), (false, 1 << 26),
(false, 1 << 26), (true, 1 << 26), (false, 1 << 27), (true, 1 << 27), (false, 1 << 28),
(false, 1 << 28), (false, 1 << 28), (true, 1 << 28), (false, 1 << 29), (true, 1 << 29),
(false, 1 << 30), (false, 1 << 30), (false, 1 << 30), (true, 1 << 30), (false, 1 << 31),
(false, 1 << 31), (false, 1 << 31), (false, 1 << 31), (false, 1 << 31), (true, 1 << 31),
// 120
(false, 1 << 32), (true, 1 << 32), (false, 1 << 33), (false, 1 << 33), (false, 1 << 33),
(false, 1 << 33), (false, 1 << 33), (true, 1 << 33), (false, 1 << 34), (false, 1 << 34),
(false, 1 << 34), (true, 1 << 34), (false, 1 << 35), (true, 1 << 35), (false, 1 << 36),
(false, 1 << 36), (false, 1 << 36), (true, 1 << 36), (false, 1 << 37), (true, 1 << 37),
(false, 1 << 38), (false, 1 << 38), (false, 1 << 38), (true, 1 << 38), (false, 1 << 39),
(false, 1 << 39), (false, 1 << 39), (false, 1 << 39), (false, 1 << 39), (true, 1 << 39),
// 150
(false, 1 << 40), (true, 1 << 40), (false, 1 << 41), (false, 1 << 41), (false, 1 << 41),
(false, 1 << 41), (false, 1 << 41), (true, 1 << 41), (false, 1 << 42), (false, 1 << 42),
(false, 1 << 42), (true, 1 << 42), (false, 1 << 43), (true, 1 << 43), (false, 1 << 44),
(false, 1 << 44), (false, 1 << 44), (true, 1 << 44), (false, 1 << 45), (true, 1 << 45),
(false, 1 << 46), (false, 1 << 46), (false, 1 << 46), (true, 1 << 46), (false, 1 << 47),
(false, 1 << 47), (false, 1 << 47), (false, 1 << 47), (false, 1 << 47), (true, 1 << 47),
// 180
(false, 1 << 48), (true, 1 << 48), (false, 1 << 49), (false, 1 << 49), (false, 1 << 49),
(false, 1 << 49), (false, 1 << 49), (true, 1 << 49), (false, 1 << 50), (false, 1 << 50),
(false, 1 << 50), (true, 1 << 50), (false, 1 << 51), (true, 1 << 51), (false, 1 << 52),
(false, 1 << 52), (false, 1 << 52), (true, 1 << 52), (false, 1 << 53), (true, 1 << 53),
(false, 1 << 54), (false, 1 << 54), (false, 1 << 54), (true, 1 << 54), (false, 1 << 55),
(false, 1 << 55), (false, 1 << 55), (false, 1 << 55), (false, 1 << 55), (true, 1 << 55),
// 210
(false, 1 << 56), (true, 1 << 56), (false, 1 << 57), (false, 1 << 57), (false, 1 << 57),
(false, 1 << 57), (false, 1 << 57), (true, 1 << 57), (false, 1 << 58), (false, 1 << 58),
(false, 1 << 58), (true, 1 << 58), (false, 1 << 59), (true, 1 << 59), (false, 1 << 60),
(false, 1 << 60), (false, 1 << 60), (true, 1 << 60), (false, 1 << 61), (true, 1 << 61),
(false, 1 << 62), (false, 1 << 62), (false, 1 << 62), (true, 1 << 62), (false, 1 << 63),
(false, 1 << 63), (false, 1 << 63), (false, 1 << 63), (false, 1 << 63), (true, 1 << 63),
];
let byte = (idx / MODULUS) as usize;
let byte_idx = POS[(idx % MODULUS) as usize];
(byte_idx.0, byte, byte_idx.1)
}
/// Get the bit representing the number at the given index in the range.
#[inline]
pub fn get(segment: &[u64], idx: u64) -> bool {
match index_for(idx) {
(false, _, _) => false,
(true, x, y) => (segment[x] & y != 0),
}
}
/// Set the bit representing the number at the given index in the range to off.
#[inline]
pub fn set_off(segment: &mut [u64], idx: u64) {
match index_for(idx) {
(false, _, _) => {}
(true, x, y) => segment[x] &= !y,
}
}
/// Set the bit representing the number at the given index in the range to on.
#[inline]
pub fn set_on(segment: &mut [u64], idx: u64) {
match index_for(idx) {
(false, _, _) => {}
(true, x, y) => segment[x] |= y,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn set_small_values() {
for ix in 0..MODULUS {
let mut segment = [!0; 1];
set_off(&mut segment, ix);
assert_eq!(get(&segment, ix), false);
set_on(&mut segment, ix);
let expected = if (ix % 2 == 0) || (ix % 3 == 0) || (ix % 5 == 0) {
false
} else {
true
};
assert_eq!(get(&segment, ix), expected);
}
}
#[test]
fn set_large_values() {
for ix in 0..MODULUS {
let mut segment = [!0; 100];
set_off(&mut segment, ix + 99 * 30);
assert_eq!(get(&segment, ix + 99 * 30), false);
set_on(&mut segment, ix + 99 * 30);
let expected = if (ix % 2 == 0) || (ix % 3 == 0) || (ix % 5 == 0) {
false
} else {
true
};
assert_eq!(get(&segment, ix + 99 * 30), expected);
}
}
} |
pub mod binary;
pub mod localization;
pub mod pack;
pub mod prefab;
pub mod set;
pub mod text;
pub mod yaml;
pub mod prelude {
pub use super::{binary::*, localization::*, pack::*, prefab::*, set::*, text::*, yaml::*};
}
|
use diesel;
use diesel::result::Error;
use diesel::ExpressionMethods;
use diesel::QueryDsl;
use diesel::RunQueryDsl;
use uuid::Uuid;
use crate::db;
use crate::models::maps::{Map, NewMap};
use crate::schema::maps;
use crate::schema::maps::dsl::*;
pub struct Filters<'a> {
pub hash: Option<&'a String>,
}
pub fn get_maps(offset: i64, limit: i64, filters: Filters) -> Result<Vec<Map>, Error> {
let conn = db::establish_connection();
let mut query = maps.into_boxed();
if let Some(f_hash) = &filters.hash {
query = query.filter(hash.eq(f_hash.clone()));
}
query
.order((max_rp.desc(), id.asc()))
.offset(offset)
.limit(limit)
.load::<Map>(&conn)
}
pub fn create_map(new_map: NewMap) -> Result<Map, Error> {
let conn = db::establish_connection();
diesel::insert_into(maps::table)
.values(&new_map)
.get_result(&conn)
}
pub fn get_map(identifier: Uuid) -> Result<Map, Error> {
let conn = db::establish_connection();
maps.find(identifier).first(&conn)
}
|
//! Loggers and logging events for declarative dataflow.
/// Logger for differential dataflow events.
pub type Logger = ::timely::logging::Logger<DeclarativeEvent>;
/// Possible different declarative events.
#[derive(Debug, Clone, Serialize, Ord, PartialOrd, Eq, PartialEq)]
pub enum DeclarativeEvent {
/// Tuples materialized during a join.
JoinTuples(JoinTuplesEvent),
}
/// Tuples materialized during a join.
#[derive(Debug, Clone, Serialize, Ord, PartialOrd, Eq, PartialEq)]
pub struct JoinTuplesEvent {
/// How many tuples.
pub cardinality: i64,
}
impl From<JoinTuplesEvent> for DeclarativeEvent {
fn from(e: JoinTuplesEvent) -> Self {
DeclarativeEvent::JoinTuples(e)
}
}
|
// 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.
/// The following property tags are defined by <https://www.iana.org/assignments/pkix-parameters/pkix-parameters.xhtml>.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CertificateAuthorityAuthorizationPropertyTag
{
/// `issue`.
///
/// Authorization Entry by Domain.
///
/// Defined by RFC 6844.
AuthorizationEntryByDomain,
/// `issuewild`.
///
/// Authorization Entry by Wildcard Domain.
///
/// Defined by RFC 6844.
AuthorizationEntryByWildcardDomain,
/// `iodef`.
///
/// Report incident by IODEF report.
///
/// Defined by RFC 6844.
ReportIncidentByIodefReport,
/// `contactemail`.
///
/// Authorized e-mail contact for domain validation.
///
/// Defined by CA/Browser Forum 1.6.3.
AuthorizedEMailContactForDomainValidation,
}
|
// 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.
/// ┌─────────────────┐
/// │ Configuration │
/// └─────────────────┘
/// │
/// publish
/// │
/// ▼
/// ┌─────────────────┐
/// │ Repository │
/// └─────────────────┘
/// │
/// find
/// │
/// ▼
/// ┌─────────────────┐
/// │ Artefact │
/// └─────────────────┘
/// │
/// bind
/// │
/// ▼
/// ┌─────────────────┐
/// │ Registry │ (instance registry)
/// └─────────────────┘
use crate::errors::{ErrorKind, Result};
use crate::lifecycle::{ActivationState, ActivatorLifecycleFsm};
use crate::repository::{
Artefact, ArtefactId, BindingArtefact, OfframpArtefact, OnrampArtefact, PipelineArtefact,
};
use crate::url::TremorUrl;
use async_channel::bounded;
use async_std::task;
use hashbrown::HashMap;
use std::default::Default;
use std::fmt;
mod servant;
pub use servant::{
Binding as BindingServant, Id as ServantId, Offramp as OfframpServant, Onramp as OnrampServant,
Pipeline as PipelineServant,
};
#[derive(Clone, Debug)]
pub(crate) struct Servant<A>
where
A: Artefact,
{
artefact: A,
artefact_id: ArtefactId,
id: ServantId,
}
#[derive(Default, Debug)]
pub(crate) struct Registry<A: Artefact> {
map: HashMap<ServantId, ActivatorLifecycleFsm<A>>,
}
impl<A: Artefact> Registry<A> {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
pub fn find(&self, mut id: ServantId) -> Option<&ActivatorLifecycleFsm<A>> {
id.trim_to_instance();
self.map.get(&id)
}
pub fn find_mut(&mut self, mut id: ServantId) -> Option<&mut ActivatorLifecycleFsm<A>> {
id.trim_to_instance();
self.map.get_mut(&id)
}
pub fn publish(
&mut self,
mut id: ServantId,
servant: ActivatorLifecycleFsm<A>,
) -> Result<&ActivatorLifecycleFsm<A>> {
id.trim_to_instance();
match self.map.insert(id.clone(), servant) {
Some(_old) => Err(ErrorKind::UnpublishFailedDoesNotExist(id.to_string()).into()),
None => self
.map
.get(&id)
.ok_or_else(|| ErrorKind::UnpublishFailedDoesNotExist(id.to_string()).into()),
}
}
pub fn unpublish(&mut self, mut id: ServantId) -> Result<ActivatorLifecycleFsm<A>> {
id.trim_to_instance();
match self.map.remove(&id) {
Some(removed) => Ok(removed),
None => Err(ErrorKind::PublishFailedAlreadyExists(id.to_string()).into()),
}
}
pub fn values(&self) -> Vec<A> {
self.map.values().map(|v| v.artefact.clone()).collect()
}
}
pub(crate) enum Msg<A: Artefact> {
SerializeServants(async_channel::Sender<Vec<A>>),
FindServant(
async_channel::Sender<Result<Option<A::SpawnResult>>>,
ServantId,
),
PublishServant(
async_channel::Sender<Result<ActivationState>>,
ServantId,
ActivatorLifecycleFsm<A>,
),
UnpublishServant(async_channel::Sender<Result<ActivationState>>, ServantId),
Transition(
async_channel::Sender<Result<ActivationState>>,
ServantId,
ActivationState,
),
}
impl<A> Registry<A>
where
A: Artefact + Send + Sync + 'static,
A::SpawnResult: Send + Sync + 'static,
{
fn start(mut self) -> async_channel::Sender<Msg<A>> {
let (tx, rx) = bounded(crate::QSIZE);
task::spawn::<_, Result<()>>(async move {
loop {
match rx.recv().await? {
Msg::SerializeServants(r) => r.send(self.values()).await?,
Msg::FindServant(r, id) => {
r.send(
A::servant_id(&id)
.map(|id| self.find(id).and_then(|v| v.resolution.clone())),
)
.await?;
}
Msg::PublishServant(r, id, s) => {
r.send(
A::servant_id(&id).and_then(|id| self.publish(id, s).map(|p| p.state)),
)
.await?;
}
Msg::UnpublishServant(r, id) => {
r.send(
A::servant_id(&id).and_then(|id| self.unpublish(id).map(|p| p.state)),
)
.await?;
}
Msg::Transition(r, mut id, new_state) => {
id.trim_to_instance();
let res = match self.find_mut(id) {
Some(s) => s.transition(new_state).map(|s| s.state),
None => Err("Servant not found".into()),
};
r.send(res).await?;
}
}
}
});
tx
}
}
/// The tremor registry holding running artifacts
#[derive(Clone)]
pub struct Registries {
pipeline: async_channel::Sender<Msg<PipelineArtefact>>,
onramp: async_channel::Sender<Msg<OnrampArtefact>>,
offramp: async_channel::Sender<Msg<OfframpArtefact>>,
binding: async_channel::Sender<Msg<BindingArtefact>>,
}
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for Registries {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Registries {{ ... }}")
}
}
#[cfg(not(tarpaulin_include))]
impl Default for Registries {
fn default() -> Self {
Self::new()
}
}
impl Registries {
/// Create a new Registry
#[must_use]
pub fn new() -> Self {
Self {
binding: Registry::new().start(),
pipeline: Registry::new().start(),
onramp: Registry::new().start(),
offramp: Registry::new().start(),
}
}
/// serialize the mappings of this registry
///
/// # Errors
/// * if we can't serialize the mappings
pub async fn serialize_mappings(&self) -> Result<crate::config::MappingMap> {
let (tx, rx) = bounded(1);
self.binding.send(Msg::SerializeServants(tx)).await?;
Ok(rx.recv().await?.into_iter().filter_map(|v| v.mapping).fold(
HashMap::new(),
|mut acc, v| {
acc.extend(v);
acc
},
))
}
/// Finds a pipeline
///
/// # Errors
/// * if we can't find a pipeline
pub async fn find_pipeline(
&self,
id: &TremorUrl,
) -> Result<Option<<PipelineArtefact as Artefact>::SpawnResult>> {
let (tx, rx) = bounded(1);
self.pipeline.send(Msg::FindServant(tx, id.clone())).await?;
rx.recv().await?
}
/// Publishes a pipeline
///
/// # Errors
/// * if I can't publish a pipeline
pub async fn publish_pipeline(
&self,
id: &TremorUrl,
servant: PipelineServant,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.pipeline
.send(Msg::PublishServant(tx, id.clone(), servant))
.await?;
rx.recv().await?
}
/// unpublishes a pipeline
///
/// # Errors
/// * if we can't unpublish a pipeline
pub async fn unpublish_pipeline(&self, id: &TremorUrl) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.pipeline
.send(Msg::UnpublishServant(tx, id.clone()))
.await?;
rx.recv().await?
}
/// Transitions a pipeline
///
/// # Errors
/// * if we can't transition a pipeline
pub async fn transition_pipeline(
&self,
id: &TremorUrl,
new_state: ActivationState,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.pipeline
.send(Msg::Transition(tx, id.clone(), new_state))
.await?;
rx.recv().await?
}
/// Finds an onramp
///
/// # Errors
/// * if we can't find a onramp
pub async fn find_onramp(
&self,
id: &TremorUrl,
) -> Result<Option<<OnrampArtefact as Artefact>::SpawnResult>> {
let (tx, rx) = bounded(1);
self.onramp.send(Msg::FindServant(tx, id.clone())).await?;
rx.recv().await?
}
/// Publishes an onramp
///
/// # Errors
/// * if we can't publish the onramp
pub async fn publish_onramp(
&self,
id: &TremorUrl,
servant: OnrampServant,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.onramp
.send(Msg::PublishServant(tx, id.clone(), servant))
.await?;
rx.recv().await?
}
/// Usnpublishes an onramp
///
/// # Errors
/// * if we can't unpublish an onramp
pub async fn unpublish_onramp(&self, id: &TremorUrl) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.onramp
.send(Msg::UnpublishServant(tx, id.clone()))
.await?;
rx.recv().await?
}
#[cfg(test)]
pub async fn transition_onramp(
&self,
id: &TremorUrl,
new_state: ActivationState,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.onramp
.send(Msg::Transition(tx, id.clone(), new_state))
.await?;
rx.recv().await?
}
/// Finds an onramp
///
/// # Errors
/// * if we can't find an offramp
pub async fn find_offramp(
&self,
id: &TremorUrl,
) -> Result<Option<<OfframpArtefact as Artefact>::SpawnResult>> {
let (tx, rx) = bounded(1);
self.offramp.send(Msg::FindServant(tx, id.clone())).await?;
rx.recv().await?
}
/// Publishes an offramp
///
/// # Errors
/// * if we can't pubish an offramp
pub async fn publish_offramp(
&self,
id: &TremorUrl,
servant: OfframpServant,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.offramp
.send(Msg::PublishServant(tx, id.clone(), servant))
.await?;
rx.recv().await?
}
/// Unpublishes an offramp
///
/// # Errors
/// * if we can't unpublish an offramp
pub async fn unpublish_offramp(&self, id: &TremorUrl) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.offramp
.send(Msg::UnpublishServant(tx, id.clone()))
.await?;
rx.recv().await?
}
#[cfg(test)]
pub async fn transition_offramp(
&self,
id: &TremorUrl,
new_state: ActivationState,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.offramp
.send(Msg::Transition(tx, id.clone(), new_state))
.await?;
rx.recv().await?
}
/// Finds a binding
///
/// # Errors
/// * if we can't find a binding
pub async fn find_binding(
&self,
id: &TremorUrl,
) -> Result<Option<<BindingArtefact as Artefact>::SpawnResult>> {
let (tx, rx) = bounded(1);
self.binding.send(Msg::FindServant(tx, id.clone())).await?;
rx.recv().await?
}
/// Publishes a binding
///
/// # Errors
/// * if we can't publish a binding
pub async fn publish_binding(
&self,
id: &TremorUrl,
servant: BindingServant,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.binding
.send(Msg::PublishServant(tx, id.clone(), servant))
.await?;
rx.recv().await?
}
/// Unpublishes a binding
///
/// # Errors
/// * if we can't unpublish a binding
pub async fn unpublish_binding(&self, id: &TremorUrl) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.binding
.send(Msg::UnpublishServant(tx, id.clone()))
.await?;
rx.recv().await?
}
#[cfg(test)]
pub async fn transition_binding(
&self,
id: &TremorUrl,
new_state: ActivationState,
) -> Result<ActivationState> {
let (tx, rx) = bounded(1);
self.binding
.send(Msg::Transition(tx, id.clone(), new_state))
.await?;
rx.recv().await?
}
}
|
#[doc = "Reader of register CFGR3"]
pub type R = crate::R<u32, super::CFGR3>;
#[doc = "Writer for register CFGR3"]
pub type W = crate::W<u32, super::CFGR3>;
#[doc = "Register CFGR3 `reset()`'s with value 0"]
impl crate::ResetValue for super::CFGR3 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DAC1_TRIG5_RMP`"]
pub type DAC1_TRIG5_RMP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DAC1_TRIG5_RMP`"]
pub struct DAC1_TRIG5_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> DAC1_TRIG5_RMP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `DAC1_TRIG3_RMP`"]
pub type DAC1_TRIG3_RMP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DAC1_TRIG3_RMP`"]
pub struct DAC1_TRIG3_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> DAC1_TRIG3_RMP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `I2C1_RX_DMA_RMP`"]
pub type I2C1_RX_DMA_RMP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `I2C1_RX_DMA_RMP`"]
pub struct I2C1_RX_DMA_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> I2C1_RX_DMA_RMP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4);
self.w
}
}
#[doc = "Reader of field `SPI1_TX_DMA_RMP`"]
pub type SPI1_TX_DMA_RMP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SPI1_TX_DMA_RMP`"]
pub struct SPI1_TX_DMA_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> SPI1_TX_DMA_RMP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2);
self.w
}
}
#[doc = "Reader of field `SPI1_RX_DMA_RMP`"]
pub type SPI1_RX_DMA_RMP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SPI1_RX_DMA_RMP`"]
pub struct SPI1_RX_DMA_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> SPI1_RX_DMA_RMP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);
self.w
}
}
#[doc = "Reader of field `I2C1_TX_DMA_RMP`"]
pub type I2C1_TX_DMA_RMP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `I2C1_TX_DMA_RMP`"]
pub struct I2C1_TX_DMA_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> I2C1_TX_DMA_RMP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6);
self.w
}
}
#[doc = "Reader of field `ADC2_DMA_RMP`"]
pub type ADC2_DMA_RMP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADC2_DMA_RMP`"]
pub struct ADC2_DMA_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> ADC2_DMA_RMP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
impl R {
#[doc = "Bit 17 - DAC1_CH1 / DAC1_CH2 Trigger remap"]
#[inline(always)]
pub fn dac1_trig5_rmp(&self) -> DAC1_TRIG5_RMP_R {
DAC1_TRIG5_RMP_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16 - DAC1_CH1 / DAC1_CH2 Trigger remap"]
#[inline(always)]
pub fn dac1_trig3_rmp(&self) -> DAC1_TRIG3_RMP_R {
DAC1_TRIG3_RMP_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bits 4:5 - I2C1_RX DMA remapping bit"]
#[inline(always)]
pub fn i2c1_rx_dma_rmp(&self) -> I2C1_RX_DMA_RMP_R {
I2C1_RX_DMA_RMP_R::new(((self.bits >> 4) & 0x03) as u8)
}
#[doc = "Bits 2:3 - SPI1_TX DMA remapping bit"]
#[inline(always)]
pub fn spi1_tx_dma_rmp(&self) -> SPI1_TX_DMA_RMP_R {
SPI1_TX_DMA_RMP_R::new(((self.bits >> 2) & 0x03) as u8)
}
#[doc = "Bits 0:1 - SPI1_RX DMA remapping bit"]
#[inline(always)]
pub fn spi1_rx_dma_rmp(&self) -> SPI1_RX_DMA_RMP_R {
SPI1_RX_DMA_RMP_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bits 6:7 - I2C1_TX DMA remapping bit"]
#[inline(always)]
pub fn i2c1_tx_dma_rmp(&self) -> I2C1_TX_DMA_RMP_R {
I2C1_TX_DMA_RMP_R::new(((self.bits >> 6) & 0x03) as u8)
}
#[doc = "Bits 8:9 - ADC2 DMA remapping bit"]
#[inline(always)]
pub fn adc2_dma_rmp(&self) -> ADC2_DMA_RMP_R {
ADC2_DMA_RMP_R::new(((self.bits >> 8) & 0x03) as u8)
}
}
impl W {
#[doc = "Bit 17 - DAC1_CH1 / DAC1_CH2 Trigger remap"]
#[inline(always)]
pub fn dac1_trig5_rmp(&mut self) -> DAC1_TRIG5_RMP_W {
DAC1_TRIG5_RMP_W { w: self }
}
#[doc = "Bit 16 - DAC1_CH1 / DAC1_CH2 Trigger remap"]
#[inline(always)]
pub fn dac1_trig3_rmp(&mut self) -> DAC1_TRIG3_RMP_W {
DAC1_TRIG3_RMP_W { w: self }
}
#[doc = "Bits 4:5 - I2C1_RX DMA remapping bit"]
#[inline(always)]
pub fn i2c1_rx_dma_rmp(&mut self) -> I2C1_RX_DMA_RMP_W {
I2C1_RX_DMA_RMP_W { w: self }
}
#[doc = "Bits 2:3 - SPI1_TX DMA remapping bit"]
#[inline(always)]
pub fn spi1_tx_dma_rmp(&mut self) -> SPI1_TX_DMA_RMP_W {
SPI1_TX_DMA_RMP_W { w: self }
}
#[doc = "Bits 0:1 - SPI1_RX DMA remapping bit"]
#[inline(always)]
pub fn spi1_rx_dma_rmp(&mut self) -> SPI1_RX_DMA_RMP_W {
SPI1_RX_DMA_RMP_W { w: self }
}
#[doc = "Bits 6:7 - I2C1_TX DMA remapping bit"]
#[inline(always)]
pub fn i2c1_tx_dma_rmp(&mut self) -> I2C1_TX_DMA_RMP_W {
I2C1_TX_DMA_RMP_W { w: self }
}
#[doc = "Bits 8:9 - ADC2 DMA remapping bit"]
#[inline(always)]
pub fn adc2_dma_rmp(&mut self) -> ADC2_DMA_RMP_W {
ADC2_DMA_RMP_W { w: self }
}
}
|
#[cfg(test)]
extern crate env_logger;
#[macro_use]
extern crate statechart;
use statechart::ast::*;
use statechart::interpreter::*;
#[test]
fn assign_string() {
let _ = env_logger::init();
let sc = states!{ S {
substates: [
state!{ S1 {
transitions: [goto!(target: S2)],
on_entry: [action_assign!(key: "hello", value: Value::from_str("assign"))],
}},
final_state!{ S2 {
result: Output::ValueOf(ValueOfBuilder::default().key("hello").build().unwrap()),
}},
]}};
let ctx = Context::new(sc);
let mut it = Interpreter::new();
let result = it.run(&ctx);
assert!(result.is_ok(), "fault: {:?}", result.err().unwrap());
assert_eq!(result.unwrap(), Value::from_str("assign"));
}
|
//! # What's this?
//!
//! A **resizeable array** based on a **segmented array structure**.
//!
//! ## When should I use it?
//!
//! You may want to use a `SegVec` instead of a `Vec` if:
//! - **...you have a `Vec` that grows a lot** over the lifetime of your program
//! - ...**you want to shrink a `Vec`**, but don't want to pay the overhead of
//! copying every element in the `Vec`.
//! - ...you want elements in the `Vec` to have **stable memory locations**
//!
//! You should *not* use `SegVec` if:
//! - **...the `Vec` will never be resized**. In order to provide optimal resizing
//! performance, `SegVec` introduces some constant-factor overhead when
//! indexing the vector. This overhead is fairly small, but if your vector
//! never changes its size after it's allocated, it's not worth paying that
//! cost for no reason.
//! - **...you want to slice the `Vec`**. Because a `SegVec` is _segmented_,
//! storing chunks of data at different non-contiguous memory locations, you
//! cannot slice a contiguous region of the vector. It is possible to
//! _iterate_ over ranges of a `SegVec`, but you cannot obtain a slice of data
//! in a `SegVec`. If you need to slice your vector, you can't use this.
use std::{
cmp, fmt,
iter::FromIterator,
mem,
ops::{Index, IndexMut},
slice,
};
#[cfg(test)]
macro_rules! test_dbg {
(let $name:ident = $x:expr;) => {
let $name = $x;
let name = stringify!($name);
eprintln!(
"[{}:{}] let {} = {:<width$} // {}",
file!(),
line!(),
name,
$name,
stringify!($x),
width = 20 - name.len(),
);
};
(let mut $name:ident = $x:expr;) => {
let mut $name = $x;
eprintln!(
"[{}:{}] let mut {} = {:<width$} // {}",
file!(),
line!(),
name,
$name,
stringify!($x),
width = 16 - name.len(),
);
};
($x:expr) => {
dbg!($x)
};
}
#[cfg(not(test))]
macro_rules! test_dbg {
(let $name:ident = $x:expr;) => {
let $name = $x;
};
(let mut $name:ident = $x:expr;) => {
let mut $name = $x;
};
($x:expr) => {
$x
};
}
#[cfg(test)]
mod tests;
pub struct SegVec<T> {
meta: Meta,
/// The total capacity of the `SegVec`. This _includes_ used capacity.
///
/// This should always be >= `self.len()`.
capacity: usize,
/// The "index block". This holds pointers to the allocated data blocks.
index: Vec<Block<T>>,
#[cfg(debug_assertions)]
is_initialized: bool,
}
#[derive(Debug)]
pub struct Iter<'segvec, T> {
len: usize,
blocks: slice::Iter<'segvec, Block<T>>,
curr_block: slice::Iter<'segvec, T>,
}
#[derive(Debug)]
pub struct IterMut<'segvec, T> {
len: usize,
blocks: slice::IterMut<'segvec, Block<T>>,
curr_block: slice::IterMut<'segvec, T>,
}
#[derive(Debug)]
struct Meta {
/// The total number of elements in this `SegVec`.
///
/// This is denoted by _n_ in the paper.
len: usize,
/// Current superblock index.
superblock: usize,
/// The capacity of the current superblock.
///
/// When the superblock has `sb_cap` blocks in it, allocating a new block
/// will increment the superblock index and reset `sb_cap`.
sb_cap: usize,
/// The current number of blocks in the current superblock.
sb_len: usize,
/// The capacity of the blocks in the current superblock.
block_cap: usize,
skipped_blocks: usize,
skipped_indices: usize,
/// The current empty data block to push in.
empty_data_block: usize,
}
struct Block<T> {
elements: Vec<T>,
}
/// TODO(eliza): consider making this an API?
#[cfg(test)]
struct DebugDetails<'segvec, T>(&'segvec SegVec<T>);
impl<T> SegVec<T> {
pub const fn new() -> Self {
Self {
meta: Meta::empty(),
index: Vec::new(),
capacity: 0,
#[cfg(debug_assertions)]
is_initialized: false,
}
}
// Minimum size of the first data block `Vec`.
// This is what `std` will allocate initially if a `Vec` is constructed
// without using `with_capacity`.
// Copied from https://github.com/rust-lang/rust/blob/996ff2e0a0f911f52bb1de6bdd0cfd5704de1fc9/library/alloc/src/raw_vec.rs#L117-L128
const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
8
} else if mem::size_of::<T>() <= 1024 {
4
} else {
1
};
pub fn with_capacity(capacity: usize) -> Self {
let mut this = Self::new();
this.reserve(capacity);
this
}
/// Returns the number of elements the `SegVec` can hold without
/// reallocating.
///
/// # Examples
///
/// ```
/// use segvec::SegVec;
///
/// let sv: SegVec<i32> = SegVec::with_capacity(10);
/// assert!(sv.capacity() >= 10);
/// ```
#[inline]
pub fn capacity(&self) -> usize {
self.capacity
}
/// Returns the number of elements in the `SegVec`, also referred to
/// as its 'length'.
///
/// # Examples
///
// TODO(eliza): fix this example.
/// ```ignore
/// use segvec::segvec;
///
/// let sv = segvec![1, 2, 3];
/// assert_eq!(a.len(), 3);
/// ```
#[doc(alias = "length")]
#[inline]
pub fn len(&self) -> usize {
self.meta.len
}
/// Reserves capacity for at least `additional` more elements to be inserted
/// in the given `SegVec<T>`. The collection may reserve more space to avoid
/// frequent reallocations. After calling `reserve`, capacity will be
/// greater than or equal to `self.len() + additional`. Does nothing if
/// capacity is already sufficient.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` bytes.
///
/// # Examples
///
/// ```
/// use segvec::SegVec;
///
/// let mut sv: SegVec<i32> = SegVec::with_capacity(1);
/// sv.reserve(10);
/// assert!(sv.capacity() >= 11);
/// ```
pub fn reserve(&mut self, mut additional: usize) {
assert!(additional < isize::MAX as usize);
if additional == 0 {
return;
}
if self.capacity == 0 {
// If the requested capacity is not a power of two, round up to the next
// power of two.
if test_dbg!(!additional.is_power_of_two()) {
additional = test_dbg!(additional.next_power_of_two());
};
// If the capacity is less than the reasonable minimum capacity for the
// size of elements in the `SegVec`, use that capacity instead.
test_dbg!(let additional = cmp::max(additional, Self::MIN_NON_ZERO_CAP););
self.initialize(additional);
return;
}
#[cfg(debug_assertions)]
debug_assert!(self.is_initialized);
let _ = test_dbg!((self.capacity(), self.len(), additional));
if test_dbg!(self.capacity() - self.len() >= additional) {
return;
}
while test_dbg!(self.capacity() - self.len() < additional) {
self.grow();
let _ = test_dbg!(&self.meta);
}
}
// this code was implemented from a computer science paper lol
#[allow(clippy::many_single_char_names)]
fn locate(&self, i: usize) -> (usize, usize) {
const BITS2: usize = (usize::BITS - 1) as usize;
// TODO(eliza): it is almost certainly possible to optimize this using
// the `log2` of the current block size...
// 1. Let `r` denote the binary representation of `i + 1`, with all
// leading zeroes removed.
test_dbg!(let r = i + 1 + self.meta.skipped_indices;);
// 2. Note that the desired element `i` is element `e` of data block `b`
// of superblock `k`, where:
// (a). `k = |r| - 1`
test_dbg!(let k = BITS2.saturating_sub(r.leading_zeros() as usize););
// (c). `e` is the last `ceil(k/2)` bits of `r`.
test_dbg!(let e_bits = (k + 1) >> 1;);
test_dbg!(let e = r & !(usize::MAX << e_bits););
test_dbg!(let r = r >> e_bits;);
// (b). `b` is the last `floor(k/2)` bits of `r` immediately after the
// leading 1-bit
test_dbg!(let b_bits = k >> 1;);
test_dbg!(let b = r & !(usize::MAX << b_bits););
// 3. let `p = 2^k - 1` be the number of datablocks in superblocks prior to
// `SB[k]`.
test_dbg!(let p = (1 << e_bits) + (1 << b_bits) - 2;);
// 4. Return the location of element `e` in data block `DB[p + b]`.
// NOTE: also compensate for skipped low-size blocks.
test_dbg!(let data_block = p + b - self.meta.skipped_blocks;);
// If the data block index is out of bounds, panic with a nicer
// assertion with more debugging information.
debug_assert!(
data_block < self.index.len(),
"assertion failed: data_block < self.index.len(); \
data_block={}; self.index.len()={}; p={}; b={}; \
metadata={:#?}",
data_block,
self.index.len(),
p,
b,
self.meta,
);
(data_block, test_dbg!(e))
}
pub fn is_empty(&self) -> bool {
self.meta.len == 0
}
pub fn get(&self, idx: usize) -> Option<&T> {
if idx > self.meta.len {
return None;
}
let (block, idx) = self.locate(idx);
self.index.get(block)?.elements.get(idx)
}
pub fn get_mut(&mut self, idx: usize) -> Option<&mut T> {
if idx > self.meta.len {
return None;
}
let (block, idx) = self.locate(idx);
self.index.get_mut(block)?.elements.get_mut(idx)
}
pub fn push(&mut self, element: T) -> usize {
if self.capacity == 0 {
self.initialize(Self::MIN_NON_ZERO_CAP);
} else {
#[cfg(debug_assertions)]
debug_assert!(self.is_initialized);
};
let mut curr_block = &mut self.index[self.meta.empty_data_block];
// Is the current block to push in full?
if curr_block.is_full() {
// Is the current block the last one (e.g. are we out of blocks)?
// If so, allocate a new block. Otherwise, we have additional free
// blocks to fill (due to `reserve`/`with_capacity`) calls.
// NOTE: the Brodnik et al paper doesn't consider that you might
// want to reserve capacity, so this is one of our deviations
// from their algorithm.
if self.meta.empty_data_block == self.index.len() - 1 {
self.grow();
}
self.meta.empty_data_block += 1;
curr_block = &mut self.index[self.meta.empty_data_block];
}
curr_block.push(element);
let len = self.meta.len;
self.meta.len += 1;
len
}
pub fn iter(&self) -> Iter<'_, T> {
let mut blocks = self.index.iter();
let curr_block = blocks
.next()
.map(|block| block.elements.iter())
.unwrap_or_else(|| [].iter());
Iter {
len: self.len(),
blocks,
curr_block,
}
}
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
let len = self.len();
let mut blocks = self.index.iter_mut();
let curr_block = blocks
.next()
.map(|block| block.elements.iter_mut())
.unwrap_or_else(|| [].iter_mut());
IterMut {
len,
blocks,
curr_block,
}
}
fn grow(&mut self) {
if self.capacity == 0 {
self.initialize(Self::MIN_NON_ZERO_CAP);
} else {
#[cfg(debug_assertions)]
debug_assert!(self.is_initialized);
};
self.meta.grow();
self.index.push(Block::new(self.meta.block_cap));
self.capacity += self.meta.block_cap;
}
fn initialize(&mut self, capacity: usize) {
#[cfg(debug_assertions)]
debug_assert!(!self.is_initialized);
debug_assert!(capacity.is_power_of_two());
debug_assert!(capacity >= Self::MIN_NON_ZERO_CAP);
// Grow the metadata up to the requested capacity.
while test_dbg!(self.meta.block_cap) < capacity {
self.meta.grow();
self.meta.skipped_blocks += 1;
self.meta.skipped_indices += self.meta.block_cap;
let _ = test_dbg!(&self.meta);
}
// Build the index, in a vector with enough room for at least the number
// of skipped data blocks plus the first actual data block.
self.index.reserve(self.meta.skipped_blocks);
// Grow the metadata again and push the first actual data block.
self.meta.grow();
self.index.push(Block::new(capacity));
debug_assert_eq!(self.meta.block_cap, capacity);
let _ = test_dbg!(&self.meta);
#[cfg(debug_assertions)]
{
self.is_initialized = true;
}
self.capacity = capacity;
}
// TODO(eliza): consider making this an API?
#[cfg(test)]
fn debug_details(&self) -> DebugDetails<'_, T> {
DebugDetails(self)
}
}
impl<T> Index<usize> for SegVec<T> {
type Output = T;
#[track_caller]
fn index(&self, idx: usize) -> &Self::Output {
match self.get(idx) {
None => panic!(
"SegVec index out of bounds: the len is {} but the index is {}",
self.len(),
idx
),
Some(elem) => elem,
}
}
}
impl<T> IndexMut<usize> for SegVec<T> {
#[track_caller]
fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
let len = self.meta.len;
match self.get_mut(idx) {
None => panic!(
"SegVec index out of bounds: the len is {} but the index is {}",
len, idx
),
Some(elem) => elem,
}
}
}
impl<T> Extend<T> for SegVec<T> {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
let iter = iter.into_iter();
// If the iterator provides a size hint, try to reserve enough capacity
// to hold its elements before pushing.
let cap = size_hint_capacity(&iter);
self.reserve(cap);
for item in iter {
self.push(item);
}
}
// TODO(eliza): add `extend_reserve` once that's stable!
}
impl<T> FromIterator<T> for SegVec<T> {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = T>,
{
let iter = iter.into_iter();
// If the iterator provides us with a size hint, try to preallocate the
// segvec with enough capacity for the iterator.
let cap = size_hint_capacity(&iter);
// TODO(eliza): we could just use `Vec::collect` and push that as block 1...
let mut this = Self::with_capacity(cap);
for item in iter.into_iter() {
this.push(item);
}
this
}
}
impl<'segvec, T> IntoIterator for &'segvec SegVec<T> {
type IntoIter = Iter<'segvec, T>;
type Item = &'segvec T;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'segvec, T> IntoIterator for &'segvec mut SegVec<T> {
type IntoIter = IterMut<'segvec, T>;
type Item = &'segvec mut T;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
impl<T: fmt::Debug> fmt::Debug for SegVec<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<T> Default for SegVec<T> {
fn default() -> Self {
Self::new()
}
}
// === impl Iter ===
impl<'segvec, T> Iterator for Iter<'segvec, T> {
type Item = &'segvec T;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(elem) = self.curr_block.next() {
return Some(elem);
}
self.curr_block = self.blocks.next()?.elements.iter();
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<T> ExactSizeIterator for Iter<'_, T> {
fn len(&self) -> usize {
self.len
}
}
// === impl IterMut ===
impl<'segvec, T> Iterator for IterMut<'segvec, T> {
type Item = &'segvec mut T;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(elem) = self.curr_block.next() {
return Some(elem);
}
self.curr_block = self.blocks.next()?.elements.iter_mut();
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<T> ExactSizeIterator for IterMut<'_, T> {
fn len(&self) -> usize {
self.len
}
}
// === impl Meta ===
impl Meta {
/// Returns new metadata describing an empty `SegVec`.
const fn empty() -> Self {
Self {
len: 0,
superblock: 0,
sb_cap: 1,
sb_len: 0,
block_cap: 1,
skipped_blocks: 0,
skipped_indices: 0,
empty_data_block: 0,
}
}
/// Grow the `SegVec` described by this `Meta`.
///
/// This does *not* allocate a new data block. Instead, it increments the
/// variables tracking the numbers of blocks and superblocks, and increments
/// the block size or superblock size, as needed.
///
/// This should be called prior to allocating a new data block.
fn grow(&mut self) {
// 1. If the last non-empty data block `DB[d-1]` is full:
// (a). if the last superblock `SB[s-1]` is full:
if self.sb_cap == self.sb_len {
// i. increment `s`
self.superblock += 1;
self.sb_len = 0;
// ii. if `s` is odd, double the number of data block in a superblock
if self.superblock % 2 == 0 {
self.sb_cap *= 2;
// iii. otherwise, double the number of elements in a data block.
} else {
self.block_cap *= 2;
}
}
// (b). if there are no empty data blocks:
self.sb_len += 1;
}
}
// === impl Block ==
impl<T> Block<T> {
fn new(capacity: usize) -> Self {
let elements = Vec::with_capacity(capacity);
debug_assert_eq!(capacity, elements.capacity());
Self { elements }
}
fn is_full(&self) -> bool {
self.elements.capacity() == self.elements.len()
}
fn push(&mut self, element: T) {
debug_assert!(!self.is_full(), "Block vectors should never reallocate");
self.elements.push(element);
}
}
impl<T: fmt::Debug> fmt::Debug for Block<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Block")
.field("len", &self.elements.len())
.field("capacity", &self.elements.capacity())
.field("elements", &self.elements)
.finish()
}
}
// === impl DebugDetails ===
#[cfg(test)]
impl<T: fmt::Debug> fmt::Debug for DebugDetails<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut f = f.debug_struct("SegVec");
f.field("meta", &self.0.meta)
.field("capacity", &self.0.capacity)
.field("index", &self.0.index);
#[cfg(debug_assertions)]
{
f.field("is_initialized", &self.0.is_initialized);
}
f.finish()
}
}
/// Determine the capacity to preallocate for an iterator, based on its
/// `size_hint`.
///
/// This is used when extending or collecting iterators into a `SegVec`.
#[inline(always)]
fn size_hint_capacity(iter: &impl Iterator) -> usize {
let (lower, upper) = iter.size_hint();
// If the size hint has an upper bound, use that as the capacity so we
// can put all the elements in one block. Otherwise, make the first
// block the size hint's lower bound.
upper.unwrap_or(lower)
}
|
use once_cell::sync::Lazy;
use regex::Regex;
/// The Card is the main unit of analysis. We use it to represent a
/// zettel file.
use std::path::{Path, PathBuf};
type Tag = String;
static TAG_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"#[[:alnum:]:-]+").unwrap());
#[derive(Debug, Clone)]
pub struct Card {
/// The zettel on the filesystem.
// I'm not decided on whether I should immediately read the zettel
// into memory, considering if that would impact tracking updates
// to the zettel.
path: PathBuf,
}
impl Card {
/// Looks through a card and attempts to extract anything that
/// resembles a tag. A tag looks something like this:
/// #abc123-def456:ghi-789 (something alphanumeric with dashes
/// and/or colons, that starts with a pound)
pub fn extract_tags(&self) -> Vec<Tag> {
TAG_REGEX
.find_iter(std::fs::read_to_string(&self.path).unwrap().as_str())
.map(|m| String::from(m.as_str()))
.collect::<Vec<Tag>>()
}
}
impl std::convert::From<PathBuf> for Card {
fn from(path: PathBuf) -> Self {
Self { path: path }
}
}
impl std::convert::From<&Path> for Card {
fn from(path: &Path) -> Self {
Self {
path: path.to_path_buf(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_path() {
let path = PathBuf::from("some-file");
let card = Card::from(path.as_path());
assert_eq!(card.path, path);
}
}
|
use std::{hint::unreachable_unchecked, io::{BufRead, Read, stdin}, ops::{Index, IndexMut}};
#[derive(Copy, Clone)]
struct SVecC {
inner: [u8; 80],
len: usize
}
impl SVecC {
pub fn new() -> Self {
Self {
inner: [0; 80],
len: 0
}
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item=&u8> {
self.inner[0..self.len].iter()
}
#[inline]
pub fn chars<'a>(&'a self) -> SVecCIter<'a> {
SVecCIter {
inner: &self.inner[0..self.len],
index: 0
}
}
#[inline]
pub fn push(&mut self, c: u8) {
self.inner[self.len] = c;
self.len += 1;
}
#[inline]
pub fn clear(&mut self) {
self.len = 0;
}
}
impl Index<usize> for SVecC {
type Output = u8;
fn index(&self, index: usize) -> &Self::Output {
&self.inner[index]
}
}
impl IndexMut<usize> for SVecC {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.inner[index]
}
}
struct SVecCIter<'a> {
inner: &'a [u8],
index: usize
}
impl<'a> Iterator for SVecCIter<'a> {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.inner.len() {
None
} else {
let ret = match self.inner[self.index] {
0xa5 => 'å',
0xa4 => 'ä',
0xb6 => 'ö',
o => o as char
};
self.index += 1;
Some(ret)
}
}
}
fn main() {
#[cfg(feature = "bench")]
let start = std::time::Instant::now();
let mut word_list: Vec<SVecC> = Vec::with_capacity(500_000);
let mut misspelled: Vec<SVecC> = Vec::with_capacity(100);
let mut stdin = std::io::stdin();
let mut input = String::with_capacity(201_000_000);
stdin.read_to_string(&mut input);
//let mut lines = input.lines();
let mut bytes = input.bytes();
// FOR DEBUGGING PURPOSES
#[cfg(feature = "testing")]
let input_file = std::env::args().skip(1).next().expect("path to test file expected");
#[cfg(feature = "testing")]
let input = std::fs::read_to_string(input_file).unwrap();
#[cfg(feature = "testing")]
let mut lines = input.lines().map(|l| Result::<_, ()>::Ok(l.to_string()));
let mut buffer = SVecC::new();
loop {
if let Some(c) = bytes.next() {
match c {
b'#' => break,
b'\n' => {
word_list.push(buffer);
buffer.clear();
},
#[cfg(windows)]
b'\r' => {},
0xc3 => buffer.push(match bytes.next() { Some(v) => v, None => unsafe { unreachable_unchecked() } }),
o => buffer.push(o)
}
} else {
break
}
}
#[cfg(windows)]
bytes.next();
bytes.next();
loop {
if let Some(c) = bytes.next() {
match c {
b'\n' => {
misspelled.push(buffer);
buffer.clear();
},
#[cfg(windows)]
b'\r' => {},
0xc3 => buffer.push(match bytes.next() { Some(v) => v, None => unsafe { unreachable_unchecked() } }),
o => buffer.push(o)
}
} else {
break;
}
}
let mut matrix = [[0; 41]; 41];
for i in 1..41 {
matrix[i][0] = i as u8;
matrix[0][i] = i as u8;
}
for word1 in &misspelled {
let l1 = word1.len();
let mut min_dist = std::u8::MAX;
let mut res = vec![];
let mut last = &SVecC::new();
for word2 in &word_list {
let l2 = word2.len();
if if l1 > l2 { l1 - l2 } else { l2 - l1 } > min_dist as usize { continue; }
let mut start = 1;
for i in 0..last.len().min(l2) {
if last[i] != word2[i] {
break;
}
start += 1;
}
#[cfg(feature = "testing")]
eprintln!(" {}", word2.iter().map(|c| vec![' ', ' ', *c]).flatten().collect::<String>());
for p1 in 1..=word1.len() {
#[cfg(feature = "testing")]
eprint!(" {}", word1[p1 - 1]);
#[cfg(feature = "testing")]
for i in 1..start {
eprint!("{:3}", matrix[p1][i]);
}
for p2 in start..=word2.len() {
let a = matrix[p1 - 1][p2] + 1;
let b = matrix[p1][p2 - 1] + 1;
let c = matrix[p1 - 1][p2 - 1] + if word1[p1 - 1] == word2[p2 - 1] { 0 } else { 1 };
let d = a.min(b).min(c);
matrix[p1][p2] = d;
#[cfg(feature = "testing")]
eprint!("{:3}", d);
}
#[cfg(feature = "testing")]
eprintln!();
}
let d = matrix[l1 as usize][l2 as usize];
if d < min_dist {
min_dist = d;
res.clear();
res.push(word2);
} else if d == min_dist {
res.push(word2);
}
last = word2;
}
print!("{} ({})", word1.chars().collect::<String>(), min_dist);
for word in res {
print!(" {}", word.chars().collect::<String>());
}
println!();
}
#[cfg(feature = "bench")]
{
let end = std::time::Instant::now();
eprintln!("Time: {:?}", end - start);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.