text stringlengths 8 4.13M |
|---|
pub mod tracer;
pub mod job;
|
// 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.
//compile-pass
#![feature(const_fn_union)]
fn main() {}
static FOO: u32 = 42;
union Foo {
f: Float,
r: &'static u32,
}
#[cfg(target_pointer_width="64")]
type Float = f64;
#[cfg(target_pointer_width="32")]
type Float = f32;
static BAR: Float = unsafe { Foo { r: &FOO }.f };
|
//! An OAS20 contract.
#![feature(wasm_abi)]
extern crate alloc;
use oasis_contract_sdk::{self as sdk};
use oasis_contract_sdk_oas20_types as types;
use oasis_contract_sdk_oas20_types::{Error, Event, Request, Response};
use oasis_contract_sdk_storage::{cell::Cell, map::Map};
use oasis_contract_sdk_types::address::Address;
/// The contract type.
pub struct Oas20Token;
/// Storage cell for the token information.
const TOKEN_INFO: Cell<types::TokenInformation> = Cell::new(b"token_info");
/// Storage map for account balances.
const BALANCES: Map<Address, u128> = Map::new(b"balances");
/// Storage map for allowances.
const ALLOWANCES: Map<(Address, Address), u128> = Map::new(b"allowances");
// Implementation of the sdk::Contract trait is required in order for the type to be a contract.
impl sdk::Contract for Oas20Token {
type Request = Request;
type Response = Response;
type Error = Error;
fn instantiate<C: sdk::Context>(ctx: &mut C, request: Request) -> Result<(), Error> {
// This method is called during the contracts.Instantiate call when the contract is first
// instantiated. It can be used to initialize the contract state.
match request {
// We require the caller to always pass the Instantiate request.
Request::Instantiate(token_instantiation) => {
let token_information =
types::helpers::instantiate(ctx, BALANCES, TOKEN_INFO, token_instantiation)?;
ctx.emit_event(Event::Oas20Instantiated { token_information });
Ok(())
}
_ => Err(Error::BadRequest),
}
}
fn call<C: sdk::Context>(ctx: &mut C, request: Request) -> Result<Response, Error> {
types::helpers::handle_call(ctx, TOKEN_INFO, BALANCES, ALLOWANCES, request)
}
fn query<C: sdk::Context>(ctx: &mut C, request: Request) -> Result<Response, Error> {
types::helpers::handle_query(ctx, TOKEN_INFO, BALANCES, ALLOWANCES, request)
}
}
// Create the required WASM exports required for the contract to be runnable.
sdk::create_contract!(Oas20Token);
// We define some simple contract tests below.
#[cfg(test)]
mod test {
use oasis_contract_sdk::{testing::MockContext, types::ExecutionContext, Contract};
use oasis_contract_sdk_types::testing::addresses;
use super::*;
#[test]
fn test_basics() {
// Create a mock execution context with default values.
let mut ctx: MockContext = ExecutionContext::default().into();
let alice = addresses::alice::address();
let bob = addresses::bob::address();
let charlie = addresses::charlie::address();
let token_instantiation = types::TokenInstantiation {
name: "TEST".to_string(),
symbol: "TST".to_string(),
decimals: 8,
initial_balances: Vec::new(),
minting: Some(types::MintingInformation {
cap: Some(100_000),
minter: bob.into(),
}),
};
// Instantiate the contract.
Oas20Token::instantiate(&mut ctx, Request::Instantiate(token_instantiation.clone()))
.expect("instantiation should work");
let ti = token_instantiation.clone();
let rsp = Oas20Token::query(&mut ctx, Request::TokenInformation)
.expect("token information query should work");
assert_eq!(
rsp,
Response::TokenInformation {
token_information: types::TokenInformation {
name: ti.name,
symbol: ti.symbol,
decimals: ti.decimals,
minting: ti.minting,
total_supply: 0,
}
},
"token information query response should be correct"
);
let rsp = Oas20Token::query(
&mut ctx,
Request::Balance {
address: alice.into(),
},
)
.expect("token balance query should work");
assert_eq!(
rsp,
Response::Balance { balance: 0 },
"token balance query response should be correct"
);
// Try to transfer some tokens.
ctx.ec.caller_address = bob.into();
Oas20Token::call(
&mut ctx,
Request::Transfer {
amount: 5,
to: alice.into(),
},
)
.expect_err("transfer empty balances should fail");
// Mint tokens by non-minter should fail.
ctx.ec.caller_address = alice.into();
Oas20Token::call(
&mut ctx,
Request::Mint {
amount: 10,
to: bob.into(),
},
)
.expect_err("minting by non-minter should fail");
// Minting zero tokens should fail.
ctx.ec.caller_address = bob.into();
Oas20Token::call(
&mut ctx,
Request::Mint {
amount: 0,
to: bob.into(),
},
)
.expect_err("minting zero tokens should fail");
// Minting more than cap should fail.
Oas20Token::call(
&mut ctx,
Request::Mint {
amount: 100_000_000,
to: bob.into(),
},
)
.expect_err("minting over cap should fail");
// Mint some tokens as minter.
Oas20Token::call(
&mut ctx,
Request::Mint {
amount: 10,
to: bob.into(),
},
)
.expect("minting should work");
// Minting should overflow.
Oas20Token::call(
&mut ctx,
Request::Mint {
amount: u128::MAX,
to: bob.into(),
},
)
.expect_err("minting should overflow");
// Transfering zero amount should fail.
ctx.ec.caller_address = bob.into();
Oas20Token::call(
&mut ctx,
Request::Transfer {
amount: 0,
to: charlie.into(),
},
)
.expect_err("transfer of zero tokens should fail");
// Transfering more than available tokens should fail.
Oas20Token::call(
&mut ctx,
Request::Transfer {
amount: 100_000,
to: charlie.into(),
},
)
.expect_err("transfer of more tokens than available should fail");
// Transfer some tokens.
Oas20Token::call(
&mut ctx,
Request::Transfer {
amount: 4,
to: charlie.into(),
},
)
.expect("transfer of tokens should work");
// Burning zero tokens should fail.
Oas20Token::call(&mut ctx, Request::Burn { amount: 0 })
.expect_err("burning of zero tokens should fail");
// Burning more than available tokens should fail.
Oas20Token::call(&mut ctx, Request::Burn { amount: 100_000 })
.expect_err("burning more than available tokens should fail");
// Burn some tokens.
Oas20Token::call(&mut ctx, Request::Burn { amount: 1 })
.expect("burning of tokens should work");
// Sending some tokens should work.
Oas20Token::call(
&mut ctx,
Request::Send {
amount: 1,
to: 0.into(),
data: cbor::to_value("test"),
},
)
.expect("transfer of tokens should work");
// Query balances.
let rsp = Oas20Token::query(
&mut ctx,
Request::Balance {
address: alice.into(),
},
)
.expect("token balance query should work");
assert_eq!(
rsp,
Response::Balance { balance: 0 },
"token balance query response should be correct"
);
let rsp = Oas20Token::query(
&mut ctx,
Request::Balance {
address: bob.into(),
},
)
.expect("token balance query should work");
assert_eq!(
rsp,
Response::Balance { balance: 4 },
"token balance query response should be correct"
);
let rsp = Oas20Token::query(
&mut ctx,
Request::Balance {
address: charlie.into(),
},
)
.expect("token balance query should work");
assert_eq!(
rsp,
Response::Balance { balance: 4 },
"token balance query response should be correct"
);
// Total supply should be updated.
let rsp = Oas20Token::query(&mut ctx, Request::TokenInformation)
.expect("token information query should work");
assert_eq!(
rsp,
Response::TokenInformation {
token_information: types::TokenInformation {
name: token_instantiation.name,
symbol: token_instantiation.symbol,
decimals: token_instantiation.decimals,
minting: token_instantiation.minting,
total_supply: 9,
}
},
"token information query response should be correct"
);
}
#[test]
fn test_allowances() {
// Create a mock execution context with default values.
let mut ctx: MockContext = ExecutionContext::default().into();
let alice = addresses::alice::address();
let bob = addresses::bob::address();
let charlie = addresses::charlie::address();
let token_instantiation = types::TokenInstantiation {
name: "TEST".to_string(),
symbol: "TST".to_string(),
decimals: 8,
initial_balances: vec![
types::InitialBalance {
address: alice,
amount: 100,
},
types::InitialBalance {
address: bob,
amount: 10,
},
types::InitialBalance {
address: charlie,
amount: 1,
},
],
minting: None,
};
// Instantiate the contract.
Oas20Token::instantiate(&mut ctx, Request::Instantiate(token_instantiation.clone()))
.expect("instantiation should work");
// Minting should not be allowed.
ctx.ec.caller_address = alice.into();
Oas20Token::call(
&mut ctx,
Request::Mint {
amount: 10,
to: bob.into(),
},
)
.expect_err("minting should not work");
// Allowing zero amount should fail.
Oas20Token::call(
&mut ctx,
Request::Allow {
beneficiary: bob,
negative: false,
amount_change: 0,
},
)
.expect_err("allowing of zero amount should fail");
// Same allower and beneficiary should fail.
ctx.ec.caller_address = alice.into();
Oas20Token::call(
&mut ctx,
Request::Allow {
beneficiary: alice,
negative: false,
amount_change: 10,
},
)
.expect_err("allowing to self should fail");
// Allowing should work.
Oas20Token::call(
&mut ctx,
Request::Allow {
beneficiary: bob,
negative: false,
amount_change: 100_000,
},
)
.expect("allowing should work");
// Reducing allowance should work.
Oas20Token::call(
&mut ctx,
Request::Allow {
beneficiary: bob,
negative: true,
amount_change: 1,
},
)
.expect("allowing should work");
// Withdrawing zero amount should fail.
ctx.ec.caller_address = bob.into();
Oas20Token::call(
&mut ctx,
Request::Withdraw {
from: alice,
amount: 0,
},
)
.expect_err("withdrawing zero amount should fail");
Oas20Token::call(
&mut ctx,
Request::Withdraw {
from: bob,
amount: 0,
},
)
.expect_err("withdrawing from self should fail");
// Withdrawing more than available balance should fail.
Oas20Token::call(
&mut ctx,
Request::Withdraw {
from: alice,
amount: 500,
},
)
.expect_err("withdrawing should fail");
// Withdrawing should work.
Oas20Token::call(
&mut ctx,
Request::Withdraw {
from: alice,
amount: 2,
},
)
.expect("withdrawing should work");
// Query allowance.
let rsp = Oas20Token::query(
&mut ctx,
Request::Allowance {
allower: alice,
beneficiary: bob,
},
)
.expect("token allowance query should work");
assert_eq!(
rsp,
Response::Allowance { allowance: 99997 },
"token allowance query response should be correct"
);
}
}
|
use std::mem::replace;
use crate::stt::{
DecodeRes, SpecifiesLangs, Stt, SttBatched, SttConstructionError, SttError, SttInfo,
};
use crate::vars::{ALPHA_BETA_MSG, DEEPSPEECH_DATA_PATH, DEEPSPEECH_READ_FAIL_MSG, SET_BEAM_MSG};
use anyhow::anyhow;
use async_trait::async_trait;
use deepspeech::{CandidateTranscript, Model, Stream};
use log::warn;
use unic_langid::LanguageIdentifier;
// Deepspeech
pub struct DeepSpeechStt {
model: Model,
current_stream: Option<Stream>,
}
fn transcript_to_string(tr: &CandidateTranscript) -> String {
let mut res = String::new();
for token in tr.tokens() {
match token.text() {
Ok(text) => res += text,
Err(err) => {
warn!(
"Part of transcript ({}) couldn't be transformed: {:?}",
tr, err
)
}
}
}
res
}
impl DeepSpeechStt {
pub fn new(curr_lang: &LanguageIdentifier) -> Result<Self, SttConstructionError> {
const BEAM_WIDTH: u16 = 500;
const ALPHA: f32 = 0.931289039105002f32;
const BETA: f32 = 1.1834137581510284f32;
let lang_str = curr_lang.to_string();
let dir_path = DEEPSPEECH_DATA_PATH.resolve().join(&lang_str);
if dir_path.is_dir() {
let mut model = Model::load_from_files(&dir_path.join(&format!("{}.pbmm", &lang_str)))
.map_err(|_| SttConstructionError::CantLoadFiles)?;
model.enable_external_scorer(&dir_path.join(&format!("{}.scorer", &lang_str)))?;
model
.set_scorer_alpha_beta(ALPHA, BETA)
.expect(ALPHA_BETA_MSG);
model.set_model_beam_width(BEAM_WIDTH).expect(SET_BEAM_MSG);
Ok(Self {
model,
current_stream: None,
})
} else {
Err(SttConstructionError::LangIncompatible)
}
}
}
#[async_trait(?Send)]
impl SttBatched for DeepSpeechStt {
async fn decode(&mut self, audio: &[i16]) -> Result<Option<DecodeRes>, SttError> {
let metadata = self.model.speech_to_text_with_metadata(audio, 1)?;
let transcript = &metadata.transcripts()[0];
Ok(Some(DecodeRes {
hypothesis: transcript_to_string(transcript),
confidence: transcript.confidence() as f32,
}))
}
fn get_info(&self) -> SttInfo {
SttInfo {
name: "DeepSpeech".to_owned(),
is_online: false,
}
}
}
#[async_trait(?Send)]
impl Stt for DeepSpeechStt {
async fn begin_decoding(&mut self) -> Result<(), SttError> {
self.current_stream = Some(self.model.create_stream()?);
Ok(())
}
async fn process(&mut self, audio: &[i16]) -> Result<(), SttError> {
match self.current_stream {
Some(ref mut s) => s.feed_audio(audio),
None => panic!("'process' can't be called before 'begin_decoding'"),
}
Ok(())
}
async fn end_decoding(&mut self) -> Result<Option<DecodeRes>, SttError> {
let stream = replace(&mut self.current_stream, None)
.expect("end_decoding can't be called before begin decoding");
let metadata = stream.finish_with_metadata(1)?;
let transcript = &metadata.transcripts()[0];
Ok(Some(DecodeRes {
hypothesis: transcript_to_string(transcript),
confidence: transcript.confidence() as f32,
}))
}
fn get_info(&self) -> SttInfo {
SttInfo {
name: "DeepSpeech".to_owned(),
is_online: false,
}
}
}
impl SpecifiesLangs for DeepSpeechStt {
fn available_langs() -> Vec<LanguageIdentifier> {
fn extract_data(
entry: Result<std::fs::DirEntry, std::io::Error>,
) -> Result<Option<LanguageIdentifier>, anyhow::Error> {
let entry = entry.map_err(|_| {
anyhow!(
"Coudln't read an element of deepspeech path due to an intermittent IO error"
)
})?;
let file_type = entry
.file_type()
.map_err(|_| anyhow!("Couldn't get file type for {:?}", entry.path()))?;
if file_type.is_dir() {
let fname = entry
.file_name()
.into_string()
.map_err(|e| anyhow!("Can't transform to string: {:?}", e))?;
let lang_id = fname
.parse()
.map_err(|_| anyhow!("Can't parse {} as language identifier", fname))?;
Ok(Some(lang_id))
} else {
Ok(None)
}
}
fn extract(entry: Result<std::fs::DirEntry, std::io::Error>) -> Option<LanguageIdentifier> {
match extract_data(entry) {
Ok(data) => data,
Err(e) => {
warn!("{}", e);
None
}
}
}
match DEEPSPEECH_DATA_PATH.resolve().read_dir() {
Ok(dir_it) => dir_it.filter_map(extract).collect(),
Err(e) => {
warn!("{}:{}", DEEPSPEECH_READ_FAIL_MSG, e);
vec![]
}
}
}
}
|
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use std::thread;
/// Box<'a T> can be dereferred because of implementing std::op::Deref
///
/// Box\<T\> is the only one of smart pointers that support deref
/// ```
/// # use std::ops::Deref;
/// # use std::alloc::AllocRef;
/// #[stable(feature = "rust1", since = "1.0.0")]
/// impl<T: ?Sized, A: AllocRef> Deref for Box<T, A> {
/// type Target = T;
///
/// fn deref(&self) -> &T {
/// &**self
/// }
/// }
/// ```
#[test]
fn smart_pointer_box() {
let x = Box::new("hello");
// - move occurs because `x` has type `Box<&str>`, which does not implement the `Copy` trait
let y = x;
// - value moved here
// println!("x: {:?}", x);
// ^ value borrowed here after move
let z = *y; // derefer `y` then copy the `&str` which implements the `Copy` trait
println!("y: {:?}", y);
println!("z: {:?}", z);
let a = Box::new("Rust".to_string());
// move occurs because `*a` has type `String`, which does not implement the `Copy` trait
let b = *a;
// -- value moved here
// println!("a: {:?}", a);
// ^ value borrowed here after move
println!("b: {:?}", b);
}
#[test]
fn smart_pointer_rc() {
let x = Rc::new("hello".to_string());
// clone will share the ownership of a Rc pointer
let _y1 = x.clone();
let _y2 = x.clone();
let x2 = &*x;
println!("A value does not implement `Copy` trait in Rc pointer cannot be derefer but can be used as referred: {:?}", x2);
println!("Rc strong count: {:?}", Rc::strong_count(&x));
// a Rc pointer can downgrade to be a Weak pointer
let z1 = Rc::downgrade(&x);
println!("Rc weak count: {:?}", Rc::weak_count(&x));
println!(
"Weak pointers does not increase the strong count: {:?}",
Rc::strong_count(&x)
);
// and the Weak pointer can upgrade to be a Rc pointer later
let _y3 = z1.upgrade().unwrap();
println!(
"a Weak pointer can upgrade to be a Rc pointer anc increase the strong count: {:?}",
Rc::strong_count(&x)
);
let _z2 = &*x;
println!(
"&*x increse neither the strong count: {:?}, nor the weak count: {:?}",
Rc::strong_count(&x),
Rc::weak_count(&x)
);
drop(x);
}
#[test]
fn smart_pointer_weak_circular_reference() {
struct Node {
next: Option<Rc<RefCell<Node>>>,
head: Option<Weak<RefCell<Node>>>,
name: &'static str,
}
impl Drop for Node {
fn drop(&mut self) {
println!("{:?} is Dropping!", self.name)
}
}
let first = Rc::new(RefCell::new(Node {
next: None,
head: None,
name: "first",
}));
let second = Rc::new(RefCell::new(Node {
next: None,
head: None,
name: "second",
}));
let third = Rc::new(RefCell::new(Node {
next: None,
head: None,
name: "third",
}));
first.borrow_mut().next = Some(second.clone());
second.borrow_mut().next = Some(third.clone());
third.borrow_mut().head = Some(Rc::downgrade(&first));
}
#[test]
fn memeory_leak() {
struct Node {
next: Option<Rc<RefCell<Node>>>,
name: &'static str,
}
impl Drop for Node {
fn drop(&mut self) {
println!("{:?} is Dropping!", self.name)
}
}
let first = Rc::new(RefCell::new(Node {
next: None,
name: "first",
}));
let second = Rc::new(RefCell::new(Node {
next: None,
name: "second",
}));
let third = Rc::new(RefCell::new(Node {
next: None,
name: "third",
}));
first.borrow_mut().next = Some(second.clone());
second.borrow_mut().next = Some(third.clone());
third.borrow_mut().next = Some(first.clone());
}
#[test]
fn smart_pointer_cell() {
struct Foo {
x: u32,
y: Cell<u32>,
}
let mut foo = Foo {
x: 1,
y: Cell::new(3),
};
assert_eq!(1, foo.x);
// get copies the value in Cell<T> and returns it
assert_eq!(3, foo.y.get());
foo.y.set(5);
assert_eq!(5, foo.y.get());
// use get_mut to borrow a mutable value which does not implement `Copy` trait
let y = foo.y.get_mut();
*y = 10;
assert_eq!(10, foo.y.get());
}
#[test]
#[should_panic]
fn smart_pointer_ref_cell() {
let x = RefCell::new(vec![1, 2, 3, 4]);
let mut mut_v1 = x.borrow_mut();
mut_v1.push(5);
x.borrow_mut().push(6); // runtime panic: already borrowed: BorrowMutError
println!("{:?}", x);
}
#[test]
fn smart_pointer_cow() {
fn abs_all(input: &mut Cow<[i32]>) {
for i in 0..input.len() {
if input[i] < 0 {
input.to_mut()[i] = -input[i];
}
}
}
fn abs_sum(ns: &[i32]) -> i32 {
let mut lst = Cow::from(ns);
abs_all(&mut lst);
lst.iter().fold(0, |acc, &n| acc + n)
}
let s1 = [1, 2, 3];
let mut i1 = Cow::from(&s1[..]);
// no write no copy
abs_all(&mut i1);
println!("IN: {:?}", s1);
println!("OUT: {:?}", i1);
let s2 = [1, 2, -3, -4];
let mut i2 = Cow::from(&s2[..]);
// copy due to write
abs_all(&mut i2);
println!("IN: {:?}", s2);
println!("OUT: {:?}", i2);
let mut v1 = Cow::from(vec![1, 2, -3, -4]);
// no copy due to Vec<T> has the ownership
// to_mut will get the ownership
abs_all(&mut v1);
println!("IN/OUT: {:?}", v1);
let s3 = [1, 3, 5, 6];
// no write no copy
let sum1 = abs_sum(&s3);
println!("{:?}", s3);
println!("{:?}", sum1);
let s4 = [1, 3, -5, -6];
// write and copy
let sum2 = abs_sum(&s4);
println!("{:?}", s4);
println!("{:?}", sum2);
#[derive(Debug)]
struct Token<'a> {
raw: Cow<'a, str>,
}
impl<'a> Token<'a> {
pub fn new<S>(raw: S) -> Token<'a>
where
S: Into<Cow<'a, str>>,
{
Token { raw: raw.into() }
}
}
let token1 = Token::new("hello");
let token2 = Token::new("Rust".to_string());
// thread safe pointer
thread::spawn(move || {
println!("token1: {:?}", token1);
println!("token2: {:?}", token2);
})
.join()
.unwrap();
}
}
|
pub mod count_vowel_strings;
pub mod find_kth_largest;
pub mod get_maximum_generated;
pub mod is_valid;
pub mod longest_palindrome;
pub mod max_operations;
pub mod most_competitive;
|
fn main(){
println!("Il manque des dépendances, veuillez retélécharger le script!")
} |
use crate::errors::{span_to_snippet, spans_to_snippet, two_spans_to_snippet, ErrText};
use crate::lexer::Span;
use crate::raw::Spanned;
use crate::source_file::FileMap;
use annotate_snippets::snippet::{Annotation, AnnotationType, Snippet};
use std::fmt;
#[derive(Debug, Clone)]
pub enum Error {
// import errors
/// The same library was imported multiple times
DuplicateImport {
import: String,
orig: Span,
dupe: Span,
},
/// Two different libraries are imported under the same name
ImportNameConflict {
name: String,
orig: Span,
dupe: Span,
},
/// A library specified in a using statement was not found in this library's dependencies
/// (i.e. was not included in a set of --files args)
DependencyNotFound(Span),
/// A library specified in a using statement was not used anywhere in the file
UnusedImport(Span),
// resolution errors
/// No definition was found for the variable referenced at Span
UndefinedLocal(Span),
Undefined(Span, RawName, RawName),
/// The reference found at `span` is ambiguous, and can be interpreted as
/// either `interp1` or `interp2`. Note that the Spans for the two interpretations
/// correpond to where the referee is defined, not where the reference is located
AmbiguousReference {
span: Span,
interp1: Spanned<RawName>,
interp2: Spanned<RawName>,
},
ConstrainedHandle(Span),
InvalidHandleSubtype(Span),
MissingEndArg(Span),
}
impl Error {
pub fn into_snippet(self, srcs: &FileMap) -> Snippet {
use Error::*;
match self {
DuplicateImport { import, orig, dupe } => two_spans_to_snippet(
orig,
dupe,
srcs,
ErrText {
text: "duplicate library import".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: format!("library {} imported here", import),
ty: AnnotationType::Error,
},
ErrText {
text: "also imported here".to_string(),
ty: AnnotationType::Info,
},
Some(Annotation {
label: Some("remove one of the imports".to_string()),
id: None,
annotation_type: AnnotationType::Help,
}),
),
ImportNameConflict { name, orig, dupe } => two_spans_to_snippet(
orig,
dupe,
srcs,
ErrText {
text: "name conflict in library imports".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: format!("library imported under name {}", name),
ty: AnnotationType::Info,
},
ErrText {
text: "clashes with import here".to_string(),
ty: AnnotationType::Info,
},
None,
),
DependencyNotFound(span) => span_to_snippet(
span,
srcs,
ErrText {
text: "imported library not found".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: "library was not found in specified dependencies".to_string(),
ty: AnnotationType::Error,
},
Some(Annotation {
label: Some("did you include it with --files?".to_string()),
id: None,
annotation_type: AnnotationType::Help,
}),
),
UnusedImport(span) => span_to_snippet(
span,
srcs,
ErrText {
text: "unused import".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: "import here is not referenced in the rest of the file".to_string(),
ty: AnnotationType::Info,
},
Some(Annotation {
label: Some("consider removing this import".to_string()),
id: None,
annotation_type: AnnotationType::Help,
}),
),
UndefinedLocal(span) => span_to_snippet(
span,
srcs,
ErrText {
text: "undefined name".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: "could not find definition for this variable".to_string(),
ty: AnnotationType::Error,
},
None,
),
Undefined(span, name1, name2) => span_to_snippet(
span,
srcs,
ErrText {
text: "undefined name".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: "could not find definition for this variable".to_string(),
ty: AnnotationType::Error,
},
Some(Annotation {
label: Some(format!("both {} and {} are undefined", name1, name2)),
id: None,
annotation_type: AnnotationType::Info,
}),
),
AmbiguousReference {
span,
interp1,
interp2,
} => spans_to_snippet(
ErrText {
text: "ambiguous reference".to_string(),
ty: AnnotationType::Error,
},
vec![
(
span,
ErrText {
text: "multiple ways to resolve this reference".to_string(),
ty: AnnotationType::Error,
},
),
(
interp1.span,
ErrText {
text: format!("reference could be interpreted as {}", interp1.value),
ty: AnnotationType::Info,
},
),
(
interp2.span,
ErrText {
text: format!("or as {}", interp2.value),
ty: AnnotationType::Info,
},
),
],
srcs,
None,
),
ConstrainedHandle(span) => span_to_snippet(
span,
srcs,
ErrText {
text: "constrained handle".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: "handles do not allow constraints, please remove".to_string(),
ty: AnnotationType::Error,
},
None,
),
InvalidHandleSubtype(span) => span_to_snippet(
span,
srcs,
ErrText {
text: "invalid handle subtype".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: "this is not a valid handle subtype".to_string(),
ty: AnnotationType::Error,
},
Some(Annotation {
label: Some(
"handle subtypes must be one of `vmo`, `channel`, todo: list the rest..."
.to_string(),
),
id: None,
annotation_type: AnnotationType::Info,
}),
),
MissingEndArg(span) => span_to_snippet(
span,
srcs,
ErrText {
text: "missing endpoint arg".to_string(),
ty: AnnotationType::Error,
},
ErrText {
text: "`client_end` and `server_end` must have a layout arg specified"
.to_string(),
ty: AnnotationType::Error,
},
None,
),
}
}
}
// This is a Name, but where the library field is a raw string instead of a resolved
// library ID. This is used as an intermediate state between when we interpret a
// raw::CompoundIdentifier and fully resolve it to a Name. Names are also converted
// back to a RawName when we want to display it
#[derive(Debug, Clone)]
pub struct RawName {
pub library: Option<String>,
pub name: String,
pub member: Option<String>,
}
impl fmt::Display for RawName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let lib_str = match &self.library {
Some(lib) => format!("library {}", lib),
None => "the current library".to_string(),
};
let var_str = match &self.member {
Some(member) => format!("{}.{}", self.name, member),
None => format!("{}", self.name),
};
write!(f, "{} in {}", var_str, lib_str)
}
}
|
use std::cmp::{PartialOrd, Ord, Ordering};
use std::ops::{Deref, DerefMut};
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
/// A path through the tree, holds metadate associated with nodes
/// and their connections to other nodes.
pub struct Path {
/// The weight used to order this `Path` with other `Paths`.
pub weight: u32,
/// A flag to indicate if this path has been active lately.
/// This allows the tree to 'remember' recently used paths.
///
/// The closer it is to 0, the more recently it was made active,
/// with 0 meaning it is currently the active path.
/// e.g 1 means it was just the active path.
pub active: u32
}
impl Path {
/// Constructs a new Path, with the given weight and active number.
pub fn new(weight: u32, active: u32) -> Self {
Path { weight: weight, active: active }
}
/// Returns an active path with a weight of zero and an active number of 0.
pub fn zero() -> Self {
Path { weight: 0, active: 0 }
}
/// Determines if the path is active.
/// The path is active when self.active == 0
pub fn is_active(&self) -> bool {
self.active == 0
}
}
impl Ord for Path {
fn cmp(&self, other: &Self) -> Ordering {
self.weight.cmp(&other.weight)
}
}
impl PartialOrd for Path {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Deref for Path {
type Target = u32;
fn deref(&self) -> &u32 {
&self.weight
}
}
impl DerefMut for Path {
fn deref_mut(&mut self) -> &mut u32 {
&mut self.weight
}
}
|
// https://leetcode-cn.com/problems/climbing-stairs/
// 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
//
// 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
//
// 注意:给定 n 是一个正整数。
//
// 示例 1:
//
// 输入: 2
// 输出: 2
// 解释: 有两种方法可以爬到楼顶。
// 1. 1 阶 + 1 阶
// 2. 2 阶
// 示例 2:
//
// 输入: 3
// 输出: 3
// 解释: 有三种方法可以爬到楼顶。
// 1. 1 阶 + 1 阶 + 1 阶
// 2. 1 阶 + 2 阶
// 3. 2 阶 + 1 阶
pub struct Solution {}
impl Solution {
pub fn climb_stairs(n: i32) -> u64 {
let mut a = 0;
let mut res = 1;
for i in 1..=n {
let temp = res;
res += a;
a = temp;
dbg!(&i);
dbg!(&res);
}
return res;
}
}
fn main() {
let d = Solution::climb_stairs(10);
println!("{}", d);
}
|
// 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 {
fidl_fuchsia_wlan_device_service::{DeviceServiceProxy, QueryIfaceResponse},
fidl_fuchsia_wlan_sme::ApSmeProxy,
fuchsia_zircon::sys::ZX_OK,
};
/// Queries wlanstack service and return the first iface id that makes |filter(iface)| true.
/// Panics after timeout expires.
pub async fn get_first_matching_iface_id<F: Fn(&QueryIfaceResponse) -> bool>(
svc: &DeviceServiceProxy,
filter: F,
) -> u16 {
// Sleep between queries to make main future yield.
let mut infite_timeout = super::test_utils::RetryWithBackoff::infinite();
loop {
let ifaces = svc.list_ifaces().await.expect("getting iface list").ifaces;
{
for iface in ifaces {
let (status, resp) =
svc.query_iface(iface.iface_id).await.expect("querying iface info");
assert_eq!(status, ZX_OK, "query_iface {} failed: {}", iface.iface_id, status);
if filter(&resp.unwrap()) {
return iface.iface_id;
}
}
}
assert!(infite_timeout.sleep_unless_timed_out().await);
}
}
/// Wrapper function to get an ApSmeProxy from wlanstack with an |iface_id| assumed to be valid.
pub async fn get_ap_sme(wlan_service: &DeviceServiceProxy, iface_id: u16) -> ApSmeProxy {
let (proxy, remote) = fidl::endpoints::create_proxy().expect("fail to create fidl endpoints");
let status = wlan_service.get_ap_sme(iface_id, remote).await.expect("fail get_ap_sme");
assert_eq!(status, ZX_OK, "fail getting ap sme status: {}", status);
proxy
}
#[cfg(test)]
mod tests {
use {
super::*,
fidl::encoding::OutOfLine,
fidl_fuchsia_wlan_device::MacRole::*,
fidl_fuchsia_wlan_device_service::{
DeviceServiceMarker, DeviceServiceRequest::*, IfaceListItem, ListIfacesResponse,
QueryIfaceResponse,
},
futures::{pin_mut, Poll, StreamExt},
wlan_common::assert_variant,
};
fn fake_iface_item(iface_id: u16) -> IfaceListItem {
IfaceListItem { iface_id, path: format!("") }
}
fn fake_query_iface_response() -> QueryIfaceResponse {
QueryIfaceResponse {
role: Client,
id: 0,
phy_id: 0,
phy_assigned_id: 0,
dev_path: format!(""),
mac_addr: [0; 6],
}
}
fn test_matching_iface_id<F: Fn(&QueryIfaceResponse) -> bool>(
filter: F,
mut list_response: ListIfacesResponse,
query_responses: Vec<QueryIfaceResponse>,
expected_id: Option<u16>,
) {
let mut exec = fuchsia_async::Executor::new().expect("creating executor");
let (proxy, remote) =
fidl::endpoints::create_proxy::<DeviceServiceMarker>().expect("creating proxy");
let mut request_stream = remote.into_stream().expect("getting request stream");
let iface_id_fut = get_first_matching_iface_id(&proxy, filter);
pin_mut!(iface_id_fut);
// This line advances get_first_matching_iface_id to the point where it calls list_ifaces()
// and waits for a response.
assert_variant!(exec.run_until_stalled(&mut iface_id_fut), Poll::Pending);
// The fake server receives the call as a request.
let responder = assert_variant!(exec.run_singlethreaded(&mut request_stream.next()),
Some(Ok(ListIfaces{responder})) => responder);
// The fake response is sent.
responder.send(&mut list_response).expect("sending list ifaces response");
for mut query_resp in query_responses {
// This line advances the future to the point where it calls query_iface(id) and waits
// for a response.
assert_variant!(exec.run_until_stalled(&mut iface_id_fut), Poll::Pending);
// The fake server receives the call as a request.
let (id, responder) = assert_variant!(
exec.run_singlethreaded(&mut request_stream.next()),
Some(Ok(QueryIface{iface_id, responder})) => (iface_id, responder));
assert_eq!(id, query_resp.id);
// The fake response is sent.
responder
.send(ZX_OK, Some(OutOfLine(&mut query_resp)))
.expect("sending query iface response");
}
match expected_id {
Some(id) => {
let got_id = assert_variant!(exec.run_until_stalled(&mut iface_id_fut),
Poll::Ready(id) => id);
assert_eq!(got_id, id);
}
None => assert_variant!(exec.run_until_stalled(&mut iface_id_fut), Poll::Pending),
}
}
#[test]
fn no_iface() {
test_matching_iface_id(|_iface| true, ListIfacesResponse { ifaces: vec![] }, vec![], None);
}
#[test]
fn found_ap_iface() {
test_matching_iface_id(
|iface| iface.role == Ap,
ListIfacesResponse { ifaces: vec![fake_iface_item(0), fake_iface_item(3)] },
vec![
fake_query_iface_response(),
QueryIfaceResponse { role: Ap, id: 3, ..fake_query_iface_response() },
],
Some(3),
);
}
#[test]
fn ifaces_exist_but_no_match() {
test_matching_iface_id(
|iface| iface.role == Client,
ListIfacesResponse { ifaces: vec![fake_iface_item(0)] },
vec![QueryIfaceResponse { role: Ap, ..fake_query_iface_response() }],
None,
)
}
}
|
use lowest_common_ancestor::LowestCommonAncestor;
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let q: usize = rd.get();
let mut g = vec![vec![]; n];
for _ in 0..(n - 1) {
let a: usize = rd.get();
let b: usize = rd.get();
g[a - 1].push(b - 1);
g[b - 1].push(a - 1);
}
let lca = LowestCommonAncestor::new(&g);
for _ in 0..q {
let c: usize = rd.get();
let d: usize = rd.get();
let dist = lca.get_dist(c - 1, d - 1);
if dist % 2 == 0 {
println!("Town");
} else {
println!("Road");
}
}
}
|
// 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(const_fn)]
#![feature(cfg_target_thread_local, thread_local_internals)]
// On platforms *without* `#[thread_local]`, use
// a custom non-`Sync` type to fake the same error.
#[cfg(not(target_thread_local))]
struct Key<T> {
_data: std::cell::UnsafeCell<Option<T>>,
_flag: std::cell::Cell<bool>,
}
#[cfg(not(target_thread_local))]
impl<T> Key<T> {
const fn new() -> Self {
Key {
_data: std::cell::UnsafeCell::new(None),
_flag: std::cell::Cell::new(false),
}
}
}
#[cfg(target_thread_local)]
use std::thread::__FastLocalKeyInner as Key;
static __KEY: Key<()> = Key::new();
//~^ ERROR `std::cell::UnsafeCell<std::option::Option<()>>` cannot be shared between threads
//~| ERROR `std::cell::Cell<bool>` cannot be shared between threads safely [E0277]
fn main() {}
|
//https://leetcode.com/problems/count-items-matching-a-rule/submissions/
impl Solution {
pub fn count_matches(items: Vec<Vec<String>>, rule_key: String, rule_value: String) -> i32 {
let rule_key = &rule_key[..];
let rule_type = match rule_key {
"type" => 0,
"color" => 1,
"name" => 2,
_ => 3
};
let mut ans = 0;
for i in 0..items.len() {
if items[i][rule_type as usize] == rule_value {
ans += 1;
}
}
ans
}
} |
#[allow(unused_imports)]
use proconio::{
input, fastout
};
fn solve(s: &str) -> String {
let mut res: usize = 0;
let s_v = s.chars();
for c in s_v {
res = (res + c as usize - b'0' as usize) % 9;
}
if res == 0 {
"Yes".to_string()
} else {
"No".to_string()
}
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
input! {
s: String
}
println!("{}", solve(&s));
Ok(())
}
fn main() {
match run() {
Err(err) => panic!("{}", err),
_ => ()
};
}
|
mod deck;
mod pile;
use deck::*;
use pile::*;
use std::io;
use std::io::stdout;
use std::io::Write;
enum Actions {
NextThreeCards,
MoveCard,
NewGame,
Quit,
}
enum ChosenDeck {
TempDeck,
DepositPile1,
DepositPile2,
DepositPile3,
DepositPile4,
FlipPile1,
FlipPile2,
FlipPile3,
FlipPile4,
FlipPile5,
FlipPile6,
FlipPile7,
}
pub struct Game {
deck: Deck,
visible_deck_cards: Pile,
deposit_piles: Vec<Pile>,
flip_piles: Vec<Pile>,
temp_deck: Pile,
should_quit: bool,
won: bool,
}
impl Game {
pub fn new() -> Self {
// Set up deck
let mut dec: Deck = Deck::new();
dec.shuffle();
// Set up flip piles
let mut flip_p: Vec<Pile> = vec![Pile::new(PileType::Flip); 7];
for i in 0..flip_p.len() {
for pile in flip_p.iter_mut().skip(i) {
// In this case, I know that there will always be enough cards to remove from the
// dec, so it can be unwrapped
pile.add_to_top(dec.remove_from_top().unwrap());
}
}
// Flip top cards over in deposit piles
for pile in &mut flip_p {
pile.index(0).flip_card_up();
}
// Add 3 cards to temp deck and flip over
let mut visible: Pile = Pile::new(PileType::Deck);
visible.add_to_top(dec.remove_from_top().unwrap());
visible.add_to_top(dec.remove_from_top().unwrap());
visible.add_to_top(dec.remove_from_top().unwrap());
for i in 0..visible.get_pile_size() {
visible.index(i).flip_card_up()
}
Game {
deck: dec,
visible_deck_cards: visible,
deposit_piles: vec![Pile::new(PileType::Deposit); 4],
flip_piles: flip_p,
temp_deck: Pile::new(PileType::Deck),
should_quit: false,
won: false,
}
}
pub fn play(&mut self) {
while !(self.should_quit || self.won) {
self.print();
self.take_turn()
}
if self.won {
println!("You've won!");
}
}
fn take_turn(&mut self) {
self.print_action_menu();
println!();
print!("Choice: ");
stdout().flush().unwrap();
loop {
let input = self.get_integer_input();
match input {
1 => self.next_three_cards(),
2 => self.move_card(),
3 => {}
4 => self.should_quit = true,
_ => println!("Input needs to be a single integer 1 - 4"),
}
if 0 < input && input <= 4 {
break;
}
}
}
fn print_action_menu(&self) {
println!("Action Menu");
println!("===========");
println!("1: Next Three Cards");
println!("2: Move Card");
println!("3: New Game");
println!("4: Quit");
}
// Returns 0 if input is bad
fn get_integer_input(&self) -> u8 {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => {
input.remove(input.len() - 1);
match input.parse::<u8>() {
Ok(val) => val,
Err(_) => 0,
}
}
Err(_) => 0,
}
}
fn next_three_cards(&mut self) {
let mut card;
// Put temp deck back
for _ in 0..self.visible_deck_cards.get_pile_size() {
card = self.visible_deck_cards.remove_from_bottom().unwrap();
card.flip_card_down();
self.deck.add_to_bottom(card);
}
// Put 3 more cards into temp deck
for _ in 0..3 {
card = self.deck.remove_from_top().unwrap();
card.flip_card_up();
self.visible_deck_cards.add_to_top(card);
}
}
fn move_card(&mut self) {
self.print_move_card_menu();
let move_card: Card;
loop {
print!("From: ");
stdout().flush().unwrap();
if let Some(x) = self.get_pile_reference() {
move_card = x.remove_from_top().unwrap();
break;
}
else {
println!("Input needs to be a single integer 1 - 12");
}
}
let to: &mut Pile;
loop {
print!("To: ");
stdout().flush().unwrap();
if let Some(x) = self.get_pile_reference() {
to = x;
break;
}
else {
println!("Input needs to be a single integer 1 - 12");
}
}
match to.get_pile_type() {
Deposit => {
if self.move_to_deposit_pile_ok(&move_card, to.index(0)) {
to.add_to_top(move_card);
}
},
Flip => {
if self.move_to_flip_pile_ok(&move_card, to.index(0)) {
to.add_to_top(move_card);
}
},
Deck => {},
}
}
fn get_pile_reference(&mut self) -> Option<&mut Pile> {
match self.get_integer_input() {
1 => Some(&mut self.visible_deck_cards),
2 => Some(&mut self.flip_piles[0]),
3 => Some(&mut self.flip_piles[1]),
4 => Some(&mut self.flip_piles[2]),
5 => Some(&mut self.flip_piles[3]),
6 => Some(&mut self.flip_piles[4]),
7 => Some(&mut self.flip_piles[5]),
8 => Some(&mut self.flip_piles[6]),
9 => Some(&mut self.deposit_piles[0]),
10 => Some(&mut self.deposit_piles[1]),
11 => Some(&mut self.deposit_piles[2]),
12 => Some(&mut self.deposit_piles[3]),
_ => None,
}
}
fn print_move_card_menu(&self) {
println!("Move card:");
println!("=========");
println!("1: Deck");
println!("2: Flip Pile 1");
println!("3: Flip Pile 2");
println!("4: Flip Pile 3");
println!("5: Flip Pile 4");
println!("6: Flip Pile 5");
println!("7: Flip Pile 6");
println!("8: Flip Pile 7");
println!("9: Deposit Pile 1");
println!("10: Deposit Pile 2");
println!("11: Deposit Pile 3");
println!("12: Deposit Pile 4");
}
fn move_to_deposit_pile_ok(&self, from: &Card, to: &Card) -> bool {
// Case of moving to deposit pile, (same suit, ascending)
if (from.get_value() == to.get_value() + 1) && (from.get_suit() == to.get_suit()) {
return true;
}
false
}
fn move_to_flip_pile_ok(&self, from: &Card, to: &Card) -> bool {
// Case of moving to flip pile, (alternating colors, descending)
if (from.get_value() == to.get_value() - 1) && (from.get_color() != to.get_color()) {
return true;
}
false
}
fn print(&self) {
print!("{}", String::from("\n").repeat(5));
println!(
"{:2}: {:3} {:3} {:3} {:3} {:3} {:3} {:3}",
self.deck.get_pile_size(),
self.visible_deck_cards.get_card_string(2),
self.visible_deck_cards.get_card_string(1),
self.visible_deck_cards.get_card_string(0),
self.deposit_piles[0].get_card_string(0),
self.deposit_piles[1].get_card_string(0),
self.deposit_piles[2].get_card_string(0),
self.deposit_piles[3].get_card_string(0),
);
let mut flip_pile_print_count = 1;
for i in 0..self.flip_piles.len() {
if flip_pile_print_count < self.flip_piles[i].get_pile_size() {
flip_pile_print_count = self.flip_piles[i].get_pile_size();
}
}
// Print dynamic pointer to next card in temp pile that we can access
println!(
"{}{}",
String::from(" ").repeat(self.visible_deck_cards.get_pile_size()),
String::from("^"),
);
for i in (0..flip_pile_print_count).rev() {
println!(
" {:3} {:3} {:3} {:3} {:3} {:3} {:3}",
self.flip_piles[0].get_card_string(i),
self.flip_piles[1].get_card_string(i),
self.flip_piles[2].get_card_string(i),
self.flip_piles[3].get_card_string(i),
self.flip_piles[4].get_card_string(i),
self.flip_piles[5].get_card_string(i),
self.flip_piles[6].get_card_string(i),
);
}
println!();
}
}
|
use std::io::Write;
use std::net::TcpStream;
use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;
use std::{io, result, thread};
use anyhow::{anyhow, bail};
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
use pageserver::http::models::{BranchCreateRequest, TenantCreateRequest};
use postgres::{Config, NoTls};
use reqwest::blocking::{Client, RequestBuilder, Response};
use reqwest::{IntoUrl, Method};
use thiserror::Error;
use zenith_utils::http::error::HttpErrorBody;
use zenith_utils::postgres_backend::AuthType;
use zenith_utils::zid::ZTenantId;
use crate::local_env::LocalEnv;
use crate::read_pidfile;
use pageserver::branches::BranchInfo;
use zenith_utils::connstring::connection_address;
#[derive(Error, Debug)]
pub enum PageserverHttpError {
#[error("Reqwest error: {0}")]
Transport(#[from] reqwest::Error),
#[error("Error: {0}")]
Response(String),
}
type Result<T> = result::Result<T, PageserverHttpError>;
pub trait ResponseErrorMessageExt: Sized {
fn error_from_body(self) -> Result<Self>;
}
impl ResponseErrorMessageExt for Response {
fn error_from_body(self) -> Result<Self> {
let status = self.status();
if !(status.is_client_error() || status.is_server_error()) {
return Ok(self);
}
// reqwest do not export it's error construction utility functions, so lets craft the message ourselves
let url = self.url().to_owned();
Err(PageserverHttpError::Response(
match self.json::<HttpErrorBody>() {
Ok(err_body) => format!("Error: {}", err_body.msg),
Err(_) => format!("Http error ({}) at {}.", status.as_u16(), url),
},
))
}
}
//
// Control routines for pageserver.
//
// Used in CLI and tests.
//
#[derive(Debug)]
pub struct PageServerNode {
pub kill_on_exit: bool,
pub pg_connection_config: Config,
pub env: LocalEnv,
pub http_client: Client,
pub http_base_url: String,
}
impl PageServerNode {
pub fn from_env(env: &LocalEnv) -> PageServerNode {
let password = if env.auth_type == AuthType::ZenithJWT {
&env.auth_token
} else {
""
};
PageServerNode {
kill_on_exit: false,
pg_connection_config: Self::pageserver_connection_config(
password,
env.pageserver_pg_port,
),
env: env.clone(),
http_client: Client::new(),
http_base_url: format!("http://localhost:{}/v1", env.pageserver_http_port),
}
}
fn pageserver_connection_config(password: &str, port: u16) -> Config {
format!("postgresql://no_user:{}@localhost:{}/no_db", password, port)
.parse()
.unwrap()
}
pub fn init(&self, create_tenant: Option<&str>, enable_auth: bool) -> anyhow::Result<()> {
let mut cmd = Command::new(self.env.pageserver_bin()?);
let listen_pg = format!("localhost:{}", self.env.pageserver_pg_port);
let listen_http = format!("localhost:{}", self.env.pageserver_http_port);
let mut args = vec![
"--init",
"-D",
self.env.base_data_dir.to_str().unwrap(),
"--postgres-distrib",
self.env.pg_distrib_dir.to_str().unwrap(),
"--listen-pg",
&listen_pg,
"--listen-http",
&listen_http,
];
if enable_auth {
args.extend(&["--auth-validation-public-key-path", "auth_public_key.pem"]);
args.extend(&["--auth-type", "ZenithJWT"]);
}
if let Some(tenantid) = create_tenant {
args.extend(&["--create-tenant", tenantid])
}
let status = cmd
.args(args)
.env_clear()
.env("RUST_BACKTRACE", "1")
.status()
.expect("pageserver init failed");
if status.success() {
Ok(())
} else {
Err(anyhow!("pageserver init failed"))
}
}
pub fn repo_path(&self) -> PathBuf {
self.env.pageserver_data_dir()
}
pub fn pid_file(&self) -> PathBuf {
self.repo_path().join("pageserver.pid")
}
pub fn start(&self) -> anyhow::Result<()> {
print!(
"Starting pageserver at '{}' in '{}'",
connection_address(&self.pg_connection_config),
self.repo_path().display()
);
io::stdout().flush().unwrap();
let mut cmd = Command::new(self.env.pageserver_bin()?);
cmd.args(&["-D", self.repo_path().to_str().unwrap()])
.arg("-d")
.env_clear()
.env("RUST_BACKTRACE", "1");
if !cmd.status()?.success() {
bail!(
"Pageserver failed to start. See '{}' for details.",
self.repo_path().join("pageserver.log").display()
);
}
// It takes a while for the page server to start up. Wait until it is
// open for business.
const RETRIES: i8 = 15;
for retries in 1..RETRIES {
match self.check_status() {
Ok(_) => {
println!("\nPageserver started");
return Ok(());
}
Err(err) => {
match err {
PageserverHttpError::Transport(err) => {
if err.is_connect() && retries < 5 {
print!(".");
io::stdout().flush().unwrap();
} else {
if retries == 5 {
println!() // put a line break after dots for second message
}
println!(
"Pageserver not responding yet, err {} retrying ({})...",
err, retries
);
}
}
PageserverHttpError::Response(msg) => {
bail!("pageserver failed to start: {} ", msg)
}
}
thread::sleep(Duration::from_secs(1));
}
}
}
bail!("pageserver failed to start in {} seconds", RETRIES);
}
pub fn stop(&self) -> anyhow::Result<()> {
let pid = read_pidfile(&self.pid_file())?;
let pid = Pid::from_raw(pid);
if kill(pid, Signal::SIGTERM).is_err() {
bail!("Failed to kill pageserver with pid {}", pid);
}
// wait for pageserver stop
let address = connection_address(&self.pg_connection_config);
for _ in 0..5 {
let stream = TcpStream::connect(&address);
thread::sleep(Duration::from_secs(1));
if let Err(_e) = stream {
println!("Pageserver stopped");
return Ok(());
}
println!("Stopping pageserver on {}", address);
}
bail!("Failed to stop pageserver with pid {}", pid);
}
pub fn page_server_psql(&self, sql: &str) -> Vec<postgres::SimpleQueryMessage> {
let mut client = self.pg_connection_config.connect(NoTls).unwrap();
println!("Pageserver query: '{}'", sql);
client.simple_query(sql).unwrap()
}
pub fn page_server_psql_client(&self) -> result::Result<postgres::Client, postgres::Error> {
self.pg_connection_config.connect(NoTls)
}
fn http_request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
let mut builder = self.http_client.request(method, url);
if self.env.auth_type == AuthType::ZenithJWT {
builder = builder.bearer_auth(&self.env.auth_token)
}
builder
}
pub fn check_status(&self) -> Result<()> {
self.http_request(Method::GET, format!("{}/{}", self.http_base_url, "status"))
.send()?
.error_from_body()?;
Ok(())
}
pub fn tenant_list(&self) -> Result<Vec<String>> {
Ok(self
.http_request(Method::GET, format!("{}/{}", self.http_base_url, "tenant"))
.send()?
.error_from_body()?
.json()?)
}
pub fn tenant_create(&self, tenantid: ZTenantId) -> Result<()> {
Ok(self
.http_request(Method::POST, format!("{}/{}", self.http_base_url, "tenant"))
.json(&TenantCreateRequest {
tenant_id: tenantid,
})
.send()?
.error_from_body()?
.json()?)
}
pub fn branch_list(&self, tenantid: &ZTenantId) -> Result<Vec<BranchInfo>> {
Ok(self
.http_request(
Method::GET,
format!("{}/branch/{}", self.http_base_url, tenantid),
)
.send()?
.error_from_body()?
.json()?)
}
pub fn branch_create(
&self,
branch_name: &str,
startpoint: &str,
tenantid: &ZTenantId,
) -> Result<BranchInfo> {
Ok(self
.http_request(Method::POST, format!("{}/branch", self.http_base_url))
.json(&BranchCreateRequest {
tenant_id: tenantid.to_owned(),
name: branch_name.to_owned(),
start_point: startpoint.to_owned(),
})
.send()?
.error_from_body()?
.json()?)
}
pub fn branch_get_by_name(
&self,
tenantid: &ZTenantId,
branch_name: &str,
) -> Result<BranchInfo> {
Ok(self
.http_request(
Method::GET,
format!("{}/branch/{}/{}", self.http_base_url, tenantid, branch_name),
)
.send()?
.error_for_status()?
.json()?)
}
}
impl Drop for PageServerNode {
fn drop(&mut self) {
if self.kill_on_exit {
let _ = self.stop();
}
}
}
|
//Mallory S. Hawke
//CS410P - Intro to Rust
//Spring 2021
//! Directory Tree Simulator: Provides a directory tree structure and an operating system stub
//! structure to interact with it.
// Skeleton was provided by Bart Massey (2021)
// DEnt::new, DEnt::Paths,
// DTree::mkdir, DTree::with_subdir, DTree::subdir,
// DTree::with_subdir_mut, DTree::subdir_mut, DTree::paths,
// OsState::chdir, OsState::mkdir, OsState::paths,
// and all unit tests (not doc-tests) were written by Mallory Hawke (2021)
// Workaround for Clippy false positive in Rust 1.51.0.
// https://github.com/rust-lang/rust-clippy/issues/6546
#![allow(clippy::result_unit_err)]
extern crate rand;
use thiserror::Error;
/// Errors during directory interaction.
#[derive(Error, Debug)]
pub enum DirError<'a> {
/// The character `/` in component names is disallowed,
/// to make path separators easier.
#[error("{0}: slash in name is invalid")]
SlashInName(&'a str),
/// Only one subdirectory of a given name can exist in any directory.
#[error("{0}: directory exists")]
DirExists(&'a str),
/// Traversal failed due to missing subdirectory.
#[error("{0}: invalid element in path")]
InvalidChild(&'a str),
}
/// Result type for directory errors.
pub type Result<'a, T> = std::result::Result<T, DirError<'a>>;
/// A directory entry. Component names are stored externally.
#[derive(Debug, Clone)]
pub struct DEnt<'a> {
pub name: &'a str,
pub subdir: DTree<'a>,
}
/// A directory tree.
#[derive(Debug, Clone, Default)]
pub struct DTree<'a> {
pub children: Vec<DEnt<'a>>,
}
/// Operating system state: the directory tree and the current working directory.
#[derive(Debug, Clone, Default)]
pub struct OsState<'a> {
pub dtree: DTree<'a>,
pub cwd: Vec<&'a str>,
}
impl<'a> DEnt<'a> {
pub fn new(name: &'a str) -> Result<Self> {
if name.contains('/') {
return Err(DirError::SlashInName(name));
}
Ok(Self {
name,
subdir: DTree::new(),
})
}
///paths implementation for DEnt; makes navigating easier to do, and allows us to build path strings in the correct order / way
fn paths(&self) -> Vec<String> {
let mut pathvec: Vec<String> = Vec::new();
if !self.subdir.children.is_empty() {
for x in &self.subdir.children {
for y in x.paths() {
pathvec.push(self.name.to_string() + "/" + &y);
}
}
} else {
pathvec.push(self.name.to_string() + "/");
}
pathvec
}
}
impl<'a> DTree<'a> {
/// Create a new empty directory tree.
pub fn new() -> Self {
Self::default()
}
/// Make a subdirectory with the given name in this directory.
///
/// # Examples
///
/// ```
/// # use dtree::DTree;
/// let mut dt = DTree::new();
/// dt.mkdir("test").unwrap();
/// assert_eq!(&dt.paths(), &["/test/"]);
/// ```
///
/// # Errors
///
/// * `DirError::SlashInName` if `name` contains `/`.
/// * `DirError::DirExists` if `name` already exists.
pub fn mkdir(&mut self, name: &'a str) -> Result<()> {
if name.contains('/') {
return Err(DirError::SlashInName(name));
}
for x in &self.children {
if x.name == name {
return Err(DirError::DirExists(name));
}
}
let entry = DEnt::new(name).unwrap();
self.children.push(entry);
Ok(())
}
/// Traverse to the subdirectory given by `path` and then call `f` to visit the subdirectory.
///
/// # Examples
///
/// ```
/// # use dtree::DTree;
/// let mut dt = DTree::new();
/// dt.mkdir("test").unwrap();
/// let paths = dt.with_subdir(&["test"], |dt| dt.paths()).unwrap();
/// assert_ne!(&paths, &["/"]);
/// ```
///
/// # Errors
///
/// * `DirError::InvalidChild` if `path` is invalid.
pub fn with_subdir<'b, F, R>(&'b self, path: &[&'a str], f: F) -> Result<R>
where
F: FnOnce(&'b DTree<'a>) -> R,
{
if path.is_empty() {
return Err(DirError::InvalidChild(""));
}
let paths: Vec<&'a str> = path.iter().rev().cloned().collect();
self.subdir(paths, f)
}
///Recursive portion of with_subdir that takes a vector; this way we can use pop, so when our vector is empty, we know we've hit the end.
fn subdir<'b, F, R>(&'b self, mut path: Vec<&'a str>, f: F) -> Result<R>
where
F: FnOnce(&'b DTree<'a>) -> R,
{
if path.is_empty() {
return Ok(f(self));
}
let name = path.pop().unwrap();
for x in &self.children {
if x.name == name {
return x.subdir.subdir(path, f);
}
}
Err(DirError::InvalidChild(name))
}
/// Traverse to the subdirectory given by `path` and then call `f` to visit the subdirectory
/// mutably.
///
/// # Examples
///
/// ```
/// # use dtree::DTree;
/// let mut dt = DTree::new();
/// dt.mkdir("a").unwrap();
/// dt.with_subdir_mut(&["a"], |dt| dt.mkdir("b").unwrap()).unwrap();
/// assert_eq!(&dt.paths(), &["/a/b/"]);
/// ```
///
/// # Errors
///
/// * `DirError::InvalidChild` if `path` is invalid.
pub fn with_subdir_mut<'b, F, R>(&'b mut self, path: &[&'a str], f: F) -> Result<R>
where
F: FnOnce(&'b mut DTree<'a>) -> R,
{
if path.is_empty() {
return Err(DirError::InvalidChild("empty path"));
}
let paths: Vec<&'a str> = path.iter().rev().cloned().collect();
self.subdir_mut(paths, f)
}
///Recursive portion of with_subdir_mut that takes a vector; this way we can use pop, so when our vector is empty, we know we've hit the end.
fn subdir_mut<'b, F, R>(&'b mut self, mut path: Vec<&'a str>, f: F) -> Result<R>
where
F: FnOnce(&'b mut DTree<'a>) -> R,
{
if path.is_empty() {
return Ok(f(self));
}
let name = path.pop().unwrap();
for x in &mut self.children {
if x.name == name {
return x.subdir.subdir_mut(path, f);
}
}
Err(DirError::InvalidChild(name))
}
/// Produce a list of the paths to each reachable leaf, in no particular order. Path
/// components are prefixed by `/`.
///
/// # Examples
///
/// ```
/// # use dtree::DTree;
/// let mut dt = DTree::new();
/// dt.mkdir("a").unwrap();
/// dt.with_subdir_mut(&["a"], |dt| dt.mkdir("b").unwrap()).unwrap();
/// dt.with_subdir_mut(&["a"], |dt| dt.mkdir("c").unwrap()).unwrap();
/// let mut paths = dt.paths();
/// paths.sort();
/// assert_eq!(&paths, &["/a/b/", "/a/c/"]);
/// ```
pub fn paths(&self) -> Vec<String> {
let mut pathvec: Vec<String> = Vec::new();
for x in &self.children {
for y in x.paths() {
pathvec.push("/".to_owned() + &y);
}
}
pathvec
}
}
impl<'a> OsState<'a> {
/// Create a new directory tree in the operating system. Current working directory is the
/// root.
pub fn new() -> Self {
Self::default()
}
/// If `path` is empty, change the working directory to the root. Otherwise change the
/// working directory to the subdirectory given by `path` relative to the current working
/// directory. (There is no notion of `.` or `..`: `path` must be a valid sequence of
/// component names.)
///
/// # Examples
///
/// ```
/// # use dtree::OsState;
/// let mut s = OsState::new();
/// s.mkdir("a").unwrap();
/// s.chdir(&["a"]).unwrap();
/// s.mkdir("b").unwrap();
/// s.chdir(&["b"]).unwrap();
/// s.mkdir("c").unwrap();
/// s.chdir(&[]).unwrap();
/// assert_eq!(&s.paths().unwrap(), &["/a/b/c/"]);
/// ```
///
/// # Errors
///
/// * `DirError::InvalidChild` if the new working directory is invalid. On error, the original
/// working directory will be retained.
pub fn chdir(&mut self, path: &[&'a str]) -> Result<()> {
if path.is_empty() {
self.cwd.clear();
} else {
match self
.dtree
.subdir(self.cwd.iter().rev().cloned().collect(), |dir| {
dir.with_subdir(path, |_| {})
})
.unwrap()
{
Ok(_) => self.cwd.extend(path.iter().cloned()),
Err(_) => return Err(DirError::InvalidChild("chdir")),
}
}
Ok(())
}
/// Make a new subdirectory with the given `name` in the working directory.
///
/// # Errors
///
/// * `DirError::SlashInName` if `name` contains `/`.
/// * `DirError::InvalidChild` if the current working directory is invalid.
/// * `DirError::DirExists` if `name` already exists.
pub fn mkdir(&mut self, name: &'a str) -> Result<()> {
if name.contains('/') {
return Err(DirError::SlashInName(name));
} else if self.cwd.is_empty() {
return self.dtree.mkdir(name);
}
let mut pathvec = self.cwd.clone();
pathvec.reverse();
self.dtree
.subdir_mut(pathvec, |dtree| dtree.mkdir(name).unwrap())
}
/// Produce a list of the paths from the working directory to each reachable leaf, in no
/// particular order. Path components are separated by `/`.
///
/// # Errors
///
/// * `DirError::InvalidChild` if the current working directory is invalid.
pub fn paths(&self) -> Result<Vec<String>> {
if self.cwd.is_empty() {
return Ok(self.dtree.paths());
}
let mut pathvec = self.cwd.clone();
pathvec.reverse();
self.dtree.subdir(pathvec, |dir| dir.paths())
}
}
#[cfg(test)]
mod dtree_tests {
use crate::DTree;
#[test]
fn dtree_static() {
let mut dt = DTree::new();
dt.mkdir("a").unwrap();
dt.mkdir("z").unwrap();
dt.with_subdir_mut(&["a"], |dt| dt.mkdir("b").unwrap())
.unwrap();
dt.with_subdir_mut(&["a"], |dt| dt.mkdir("c").unwrap())
.unwrap();
dt.with_subdir_mut(&["a", "c"], |dt| dt.mkdir("d").unwrap())
.unwrap();
let paths = dt.paths();
assert_eq!(&paths, &["/a/b/", "/a/c/d/", "/z/"]);
}
#[test]
///Test for DTree's mkdir and paths function. Not strictly necessary, given that OsState's mkdir and paths functions utilizes Dtree's.
fn dtree_rand() {
use rand::{distributions::Alphanumeric, Rng};
let x = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.map(char::from)
.collect::<String>();
let mut dt = DTree::new();
dt.mkdir(&x).unwrap();
assert_eq!(&dt.paths(), &["/".to_owned() + &x + "/"]);
}
///Test for dtree that checks to make sure that slashes in names are invalid
#[test]
#[should_panic]
fn dtree_slash() {
let mut dt = DTree::new();
dt.mkdir("/a").unwrap();
}
#[test]
#[should_panic]
fn dtree_double() {
let mut dt = DTree::new();
dt.mkdir("a").unwrap();
dt.mkdir("a").unwrap();
}
}
///Tests for OsState
#[cfg(test)]
mod osstate_tests {
use crate::OsState;
///Test that randomly generates ten, ten character long, strings which it then uses to create a directory chain; calls paths to check that the chain was built correctly.
#[test]
fn osstate_rand() {
use rand::{distributions::Alphanumeric, Rng};
let mut s = OsState::new();
let mut stringz: Vec<String> = Vec::new();
for _ in 0..10 {
stringz.push(
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.map(char::from)
.collect::<String>(),
);
}
let mut path: String = "/".to_string();
for x in &stringz {
s.mkdir(x.as_str()).unwrap();
s.chdir(&[x.as_str()]).unwrap();
path = path + &x.to_string() + &"/".to_string();
}
s.chdir(&[]).unwrap();
assert_eq!(&s.paths().unwrap(), &[path.as_str()]);
}
//Test for OsState that creates a directory, then attempts to change its current working directory to a non-existent one
#[test]
#[should_panic]
fn osstate_bad_chdir() {
let mut s = OsState::new();
s.mkdir("x").unwrap();
s.chdir(&["q"]).unwrap();
}
///Test for OsState that tries to make a directory named /
#[test]
#[should_panic]
fn osstate_bad_mkdir() {
let mut s = OsState::new();
s.mkdir("/").unwrap();
}
#[test]
#[should_panic]
fn osstate_double() {
let mut s = OsState::new();
s.mkdir("a").unwrap();
s.mkdir("a").unwrap();
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u16,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u16,
}
impl super::RXIS {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u16 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIS_EP1R {
bits: bool,
}
impl USB_RXIS_EP1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIS_EP1W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIS_EP1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u16) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIS_EP2R {
bits: bool,
}
impl USB_RXIS_EP2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIS_EP2W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIS_EP2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u16) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIS_EP3R {
bits: bool,
}
impl USB_RXIS_EP3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIS_EP3W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIS_EP3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u16) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIS_EP4R {
bits: bool,
}
impl USB_RXIS_EP4R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIS_EP4W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIS_EP4W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 4);
self.w.bits |= ((value as u16) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIS_EP5R {
bits: bool,
}
impl USB_RXIS_EP5R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIS_EP5W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIS_EP5W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u16) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIS_EP6R {
bits: bool,
}
impl USB_RXIS_EP6R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIS_EP6W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIS_EP6W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u16) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_RXIS_EP7R {
bits: bool,
}
impl USB_RXIS_EP7R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _USB_RXIS_EP7W<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXIS_EP7W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u16) & 1) << 7;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u16 {
self.bits
}
#[doc = "Bit 1 - RX Endpoint 1 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep1(&self) -> USB_RXIS_EP1R {
let bits = ((self.bits >> 1) & 1) != 0;
USB_RXIS_EP1R { bits }
}
#[doc = "Bit 2 - RX Endpoint 2 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep2(&self) -> USB_RXIS_EP2R {
let bits = ((self.bits >> 2) & 1) != 0;
USB_RXIS_EP2R { bits }
}
#[doc = "Bit 3 - RX Endpoint 3 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep3(&self) -> USB_RXIS_EP3R {
let bits = ((self.bits >> 3) & 1) != 0;
USB_RXIS_EP3R { bits }
}
#[doc = "Bit 4 - RX Endpoint 4 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep4(&self) -> USB_RXIS_EP4R {
let bits = ((self.bits >> 4) & 1) != 0;
USB_RXIS_EP4R { bits }
}
#[doc = "Bit 5 - RX Endpoint 5 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep5(&self) -> USB_RXIS_EP5R {
let bits = ((self.bits >> 5) & 1) != 0;
USB_RXIS_EP5R { bits }
}
#[doc = "Bit 6 - RX Endpoint 6 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep6(&self) -> USB_RXIS_EP6R {
let bits = ((self.bits >> 6) & 1) != 0;
USB_RXIS_EP6R { bits }
}
#[doc = "Bit 7 - RX Endpoint 7 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep7(&self) -> USB_RXIS_EP7R {
let bits = ((self.bits >> 7) & 1) != 0;
USB_RXIS_EP7R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u16) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 1 - RX Endpoint 1 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep1(&mut self) -> _USB_RXIS_EP1W {
_USB_RXIS_EP1W { w: self }
}
#[doc = "Bit 2 - RX Endpoint 2 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep2(&mut self) -> _USB_RXIS_EP2W {
_USB_RXIS_EP2W { w: self }
}
#[doc = "Bit 3 - RX Endpoint 3 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep3(&mut self) -> _USB_RXIS_EP3W {
_USB_RXIS_EP3W { w: self }
}
#[doc = "Bit 4 - RX Endpoint 4 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep4(&mut self) -> _USB_RXIS_EP4W {
_USB_RXIS_EP4W { w: self }
}
#[doc = "Bit 5 - RX Endpoint 5 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep5(&mut self) -> _USB_RXIS_EP5W {
_USB_RXIS_EP5W { w: self }
}
#[doc = "Bit 6 - RX Endpoint 6 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep6(&mut self) -> _USB_RXIS_EP6W {
_USB_RXIS_EP6W { w: self }
}
#[doc = "Bit 7 - RX Endpoint 7 Interrupt"]
#[inline(always)]
pub fn usb_rxis_ep7(&mut self) -> _USB_RXIS_EP7W {
_USB_RXIS_EP7W { w: self }
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(C)]
pub struct AutomationAnnotationTypeRegistration {
pub LocalId: i32,
}
impl ::core::marker::Copy for AutomationAnnotationTypeRegistration {}
impl ::core::clone::Clone for AutomationAnnotationTypeRegistration {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct AutomationRemoteOperationOperandId {
pub Value: i32,
}
impl ::core::marker::Copy for AutomationRemoteOperationOperandId {}
impl ::core::clone::Clone for AutomationRemoteOperationOperandId {
fn clone(&self) -> Self {
*self
}
}
pub type AutomationRemoteOperationResult = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AutomationRemoteOperationStatus(pub i32);
impl AutomationRemoteOperationStatus {
pub const Success: Self = Self(0i32);
pub const MalformedBytecode: Self = Self(1i32);
pub const InstructionLimitExceeded: Self = Self(2i32);
pub const UnhandledException: Self = Self(3i32);
pub const ExecutionFailure: Self = Self(4i32);
}
impl ::core::marker::Copy for AutomationRemoteOperationStatus {}
impl ::core::clone::Clone for AutomationRemoteOperationStatus {
fn clone(&self) -> Self {
*self
}
}
pub type CoreAutomationRemoteOperation = *mut ::core::ffi::c_void;
pub type CoreAutomationRemoteOperationContext = *mut ::core::ffi::c_void;
pub type ICoreAutomationConnectionBoundObjectProvider = *mut ::core::ffi::c_void;
pub type ICoreAutomationRemoteOperationExtensionProvider = *mut ::core::ffi::c_void;
pub type RemoteAutomationClientSession = *mut ::core::ffi::c_void;
pub type RemoteAutomationConnectionRequestedEventArgs = *mut ::core::ffi::c_void;
pub type RemoteAutomationDisconnectedEventArgs = *mut ::core::ffi::c_void;
pub type RemoteAutomationWindow = *mut ::core::ffi::c_void;
|
use super::*;
impl From<Row> for Point {
fn from(row: Row) -> Self {
Self {
value: row.get("value"),
trace_id: row.get("trace_id"),
ts: row.get("ts"),
}
}
}
impl From<Row> for SlimPoint {
fn from(row: Row) -> Self {
Self {
value: row.get("value"),
ts: row.get("ts"),
}
}
}
#[async_trait]
impl Delete<Point> for Client {
type Key = IdKey;
async fn delete(&self, key: &IdKey) -> Result<(), Error> {
self.execute("DELETE FROM points WHERE trace_id = $1", &[&key.id])
.await?;
Ok(())
}
}
#[async_trait]
impl Filter<SlimPoint> for Client {
type Key = RangeKey;
async fn filter(&self, key: &Self::Key) -> Result<Vec<SlimPoint>, Error> {
let mut res: Vec<SlimPoint> = self
.query(
"SELECT value, ts FROM points WHERE trace_id = $1 AND ts BETWEEN $2 AND $3",
&[&key.id, &key.from_date, &key.to_date],
)
.await?
.into_iter()
.map(SlimPoint::from)
.collect();
res.sort_by(|a, b| a.ts.cmp(&b.ts));
Ok(res)
}
}
#[async_trait]
impl BulkInsert<Point> for Client {
async fn bulk_insert(&self, rows: &[Point]) -> Result<(), Error> {
let values_stmt = rows
.iter()
.map(|x| format!("('{}',{},'{}')", x.ts, x.value, x.trace_id))
.collect::<Vec<String>>()
.join(",");
let sql = format!(
"INSERT INTO points (ts, value, trace_id) VALUES {}",
values_stmt
);
self.execute(&sql[..], &[]).await?;
Ok(())
}
}
|
use std::io::prelude::*;
use std::net::TcpStream;
fn main() {
let addrs = vec![
"10.1.8.91",
"10.1.8.92",
"10.1.80.58",
"10.1.80.59",
"10.1.8.93",
"10.1.8.95",
];
for addr in addrs {
if let Ok(mut stream) = TcpStream::connect(addr) {
let mut res = String::new();
// stream.read(&mut [0; 128]).unwrap();
stream.read_to_string(&mut res).unwrap();
println!("{:?}", res);
} else {
println!("Tidak dapat terhubung ke ip {}.", addr);
}
}
}
|
#[doc = "Reader of register IM"]
pub type R = crate::R<u32, super::IM>;
#[doc = "Writer for register IM"]
pub type W = crate::W<u32, super::IM>;
#[doc = "Register IM `reset()`'s with value 0"]
impl crate::ResetValue for super::IM {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `MASK0`"]
pub type MASK0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MASK0`"]
pub struct MASK0_W<'a> {
w: &'a mut W,
}
impl<'a> MASK0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `MASK1`"]
pub type MASK1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MASK1`"]
pub struct MASK1_W<'a> {
w: &'a mut W,
}
impl<'a> MASK1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `MASK2`"]
pub type MASK2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MASK2`"]
pub struct MASK2_W<'a> {
w: &'a mut W,
}
impl<'a> MASK2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `MASK3`"]
pub type MASK3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MASK3`"]
pub struct MASK3_W<'a> {
w: &'a mut W,
}
impl<'a> MASK3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `DMAMASK0`"]
pub type DMAMASK0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAMASK0`"]
pub struct DMAMASK0_W<'a> {
w: &'a mut W,
}
impl<'a> DMAMASK0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `DMAMASK1`"]
pub type DMAMASK1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAMASK1`"]
pub struct DMAMASK1_W<'a> {
w: &'a mut W,
}
impl<'a> DMAMASK1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `DMAMASK2`"]
pub type DMAMASK2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAMASK2`"]
pub struct DMAMASK2_W<'a> {
w: &'a mut W,
}
impl<'a> DMAMASK2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `DMAMASK3`"]
pub type DMAMASK3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAMASK3`"]
pub struct DMAMASK3_W<'a> {
w: &'a mut W,
}
impl<'a> DMAMASK3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `DCONSS0`"]
pub type DCONSS0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DCONSS0`"]
pub struct DCONSS0_W<'a> {
w: &'a mut W,
}
impl<'a> DCONSS0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `DCONSS1`"]
pub type DCONSS1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DCONSS1`"]
pub struct DCONSS1_W<'a> {
w: &'a mut W,
}
impl<'a> DCONSS1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `DCONSS2`"]
pub type DCONSS2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DCONSS2`"]
pub struct DCONSS2_W<'a> {
w: &'a mut W,
}
impl<'a> DCONSS2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `DCONSS3`"]
pub type DCONSS3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DCONSS3`"]
pub struct DCONSS3_W<'a> {
w: &'a mut W,
}
impl<'a> DCONSS3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
impl R {
#[doc = "Bit 0 - SS0 Interrupt Mask"]
#[inline(always)]
pub fn mask0(&self) -> MASK0_R {
MASK0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - SS1 Interrupt Mask"]
#[inline(always)]
pub fn mask1(&self) -> MASK1_R {
MASK1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - SS2 Interrupt Mask"]
#[inline(always)]
pub fn mask2(&self) -> MASK2_R {
MASK2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - SS3 Interrupt Mask"]
#[inline(always)]
pub fn mask3(&self) -> MASK3_R {
MASK3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 8 - SS0 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask0(&self) -> DMAMASK0_R {
DMAMASK0_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - SS1 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask1(&self) -> DMAMASK1_R {
DMAMASK1_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - SS2 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask2(&self) -> DMAMASK2_R {
DMAMASK2_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - SS3 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask3(&self) -> DMAMASK3_R {
DMAMASK3_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 16 - Digital Comparator Interrupt on SS0"]
#[inline(always)]
pub fn dconss0(&self) -> DCONSS0_R {
DCONSS0_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Digital Comparator Interrupt on SS1"]
#[inline(always)]
pub fn dconss1(&self) -> DCONSS1_R {
DCONSS1_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - Digital Comparator Interrupt on SS2"]
#[inline(always)]
pub fn dconss2(&self) -> DCONSS2_R {
DCONSS2_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - Digital Comparator Interrupt on SS3"]
#[inline(always)]
pub fn dconss3(&self) -> DCONSS3_R {
DCONSS3_R::new(((self.bits >> 19) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - SS0 Interrupt Mask"]
#[inline(always)]
pub fn mask0(&mut self) -> MASK0_W {
MASK0_W { w: self }
}
#[doc = "Bit 1 - SS1 Interrupt Mask"]
#[inline(always)]
pub fn mask1(&mut self) -> MASK1_W {
MASK1_W { w: self }
}
#[doc = "Bit 2 - SS2 Interrupt Mask"]
#[inline(always)]
pub fn mask2(&mut self) -> MASK2_W {
MASK2_W { w: self }
}
#[doc = "Bit 3 - SS3 Interrupt Mask"]
#[inline(always)]
pub fn mask3(&mut self) -> MASK3_W {
MASK3_W { w: self }
}
#[doc = "Bit 8 - SS0 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask0(&mut self) -> DMAMASK0_W {
DMAMASK0_W { w: self }
}
#[doc = "Bit 9 - SS1 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask1(&mut self) -> DMAMASK1_W {
DMAMASK1_W { w: self }
}
#[doc = "Bit 10 - SS2 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask2(&mut self) -> DMAMASK2_W {
DMAMASK2_W { w: self }
}
#[doc = "Bit 11 - SS3 DMA Interrupt Mask"]
#[inline(always)]
pub fn dmamask3(&mut self) -> DMAMASK3_W {
DMAMASK3_W { w: self }
}
#[doc = "Bit 16 - Digital Comparator Interrupt on SS0"]
#[inline(always)]
pub fn dconss0(&mut self) -> DCONSS0_W {
DCONSS0_W { w: self }
}
#[doc = "Bit 17 - Digital Comparator Interrupt on SS1"]
#[inline(always)]
pub fn dconss1(&mut self) -> DCONSS1_W {
DCONSS1_W { w: self }
}
#[doc = "Bit 18 - Digital Comparator Interrupt on SS2"]
#[inline(always)]
pub fn dconss2(&mut self) -> DCONSS2_W {
DCONSS2_W { w: self }
}
#[doc = "Bit 19 - Digital Comparator Interrupt on SS3"]
#[inline(always)]
pub fn dconss3(&mut self) -> DCONSS3_W {
DCONSS3_W { w: self }
}
}
|
pub fn build_proverb(list: Vec<&str>) -> String {
let size = list.len();
if size == 0 {
return "".into()
}
let mut wants = vec![];
for (i, item) in list.iter().enumerate() {
if i + 1 == size {
break
}
wants.push(format!("For want of a {} the {} was lost.", item, list.get(i + 1).unwrap()));
}
wants.push(format!("And all for the want of a {}.", list.get(0).unwrap()));
wants.join("\n")
}
|
use std::io;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, RocksDBError>;
#[derive(Error, Debug)]
pub enum RocksDBError {
#[error("rocksdb io error: {0:?}")]
DBError(#[from] io::Error),
#[error("datastore error: {0:?}")]
DataStoreError(#[from] datastore::DSError),
#[error("invalid column name: {0}")]
InvalidColumnName(String),
#[error("other err: {0}")]
Other(#[from] Box<dyn std::error::Error + Send + Sync>),
}
|
use darling::{util::Flag, FromDeriveInput, FromVariant};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{DeriveInput, Ident};
use crate::util;
#[derive(FromDeriveInput)]
#[darling(supports(enum_any), attributes(sdk_event))]
struct Event {
ident: Ident,
data: darling::ast::Data<EventVariant, darling::util::Ignored>,
/// The optional module name for all events.
#[darling(default)]
module_name: String,
/// Whether to sequentially autonumber the event codes.
/// This option exists as a convenience for contracts that
/// only append events or release only breaking changes.
#[darling(default, rename = "autonumber")]
autonumber: Flag,
}
#[derive(FromVariant)]
#[darling(attributes(sdk_event))]
struct EventVariant {
ident: Ident,
/// The explicit ID of the event code. Overrides any autonumber set on the event enum.
#[darling(default, rename = "code")]
code: Option<u32>,
}
pub fn derive_event(input: DeriveInput) -> TokenStream {
let sdk_crate = util::sdk_crate_identifier();
let event = match Event::from_derive_input(&input) {
Ok(event) => event,
Err(e) => return e.write_errors(),
};
let event_ty_ident = &event.ident;
let (module_name_body, code_body) = convert_variants(
&format_ident!("self"),
&event.module_name,
&event.data.as_ref().take_enum().unwrap(),
event.autonumber.is_some(),
);
util::wrap_in_const(quote! {
use #sdk_crate as __sdk;
#[automatically_derived]
impl __sdk::event::Event for #event_ty_ident {
fn module_name(&self) -> &str {
#module_name_body
}
fn code(&self) -> u32 {
#code_body
}
}
})
}
fn convert_variants(
enum_binding: &Ident,
module_name: &str,
variants: &[&EventVariant],
autonumber: bool,
) -> (TokenStream, TokenStream) {
if variants.is_empty() {
return (quote!(#module_name), quote!(0));
}
let mut next_autonumber = 0u32;
let mut reserved_numbers = std::collections::BTreeSet::new();
let (module_name_matches, code_matches): (Vec<_>, Vec<_>) = variants
.iter()
.map(|variant| {
let variant_ident = &variant.ident;
let code = match variant.code {
Some(code) => {
if reserved_numbers.contains(&code) {
variant_ident
.span()
.unwrap()
.error(format!("code {} already used", code))
.emit();
return (quote!(), quote!());
}
reserved_numbers.insert(code);
code
}
None if autonumber => {
let mut reserved_successors = reserved_numbers.range(next_autonumber..);
while reserved_successors.next() == Some(&next_autonumber) {
next_autonumber += 1;
}
let code = next_autonumber;
reserved_numbers.insert(code);
next_autonumber += 1;
code
}
None => {
variant_ident
.span()
.unwrap()
.error("missing `code` for variant")
.emit();
return (quote!(), quote!());
}
};
(
quote! {
Self::#variant_ident { .. } => #module_name,
},
quote! {
Self::#variant_ident { .. } => #code,
},
)
})
.unzip();
(
quote! {
match #enum_binding {
#(#module_name_matches)*
}
},
quote! {
match #enum_binding {
#(#code_matches)*
}
},
)
}
#[cfg(test)]
mod tests {
#[test]
fn generate_event_impl_auto() {
let expected: syn::Stmt = syn::parse_quote!(
#[doc(hidden)]
const _: () = {
use oasis_contract_sdk as __sdk;
#[automatically_derived]
impl __sdk::event::Event for MainEvent {
fn module_name(&self) -> &str {
match self {
Self::Event0 { .. } => "",
Self::Event2 { .. } => "",
Self::Event1 { .. } => "",
Self::Event3 { .. } => "",
}
}
fn code(&self) -> u32 {
match self {
Self::Event0 { .. } => 0u32,
Self::Event2 { .. } => 2u32,
Self::Event1 { .. } => 1u32,
Self::Event3 { .. } => 3u32,
}
}
}
};
);
let input: syn::DeriveInput = syn::parse_quote!(
#[derive(Event)]
#[sdk_event(autonumber)]
pub enum MainEvent {
Event0,
#[sdk_event(code = 2)]
Event2 {
payload: Vec<u8>,
},
Event1(String),
Event3,
}
);
let event_derivation = super::derive_event(input);
let actual: syn::Stmt = syn::parse2(event_derivation).unwrap();
crate::assert_empty_diff!(actual, expected);
}
#[test]
fn generate_event_impl_manual() {
let expected: syn::Stmt = syn::parse_quote!(
#[doc(hidden)]
const _: () = {
use oasis_contract_sdk as __sdk;
#[automatically_derived]
impl __sdk::event::Event for MainEvent {
fn module_name(&self) -> &str {
"the_module_name"
}
fn code(&self) -> u32 {
0
}
}
};
);
let input: syn::DeriveInput = syn::parse_quote!(
#[derive(Event)]
#[sdk_event(autonumber, module_name = "the_module_name")]
pub enum MainEvent {}
);
let event_derivation = super::derive_event(input);
let actual: syn::Stmt = syn::parse2(event_derivation).unwrap();
crate::assert_empty_diff!(actual, expected);
}
}
|
use super::*;
use proptest::strategy::Strategy;
#[test]
fn without_empty_list_returns_false() {
run!(
|arc_process| {
(
Just(Term::NIL),
strategy::term(arc_process.clone())
.prop_filter("Right must not be empty list", |v| !v.is_nil()),
)
},
|(left, right)| {
prop_assert_eq!(result(left, right), false.into());
Ok(())
},
);
}
#[test]
fn with_empty_list_right_returns_true() {
assert_eq!(result(Term::NIL, Term::NIL), true.into());
}
|
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
pub enum Casing {
Upper,
Lower,
}
const ROMAN_NUMBER_MAP_HUNDREDS: [&str; 10] =
["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
const ROMAN_NUMBER_MAP_TENS: [&str; 10] =
["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
const ROMAN_NUMBER_MAP_ONES: [&str; 10] =
["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
/// Converts positive integers to (upper case) Roman numerals.
/// - `number`: The number that should be converted.
/// - `casing`: Indicates the casing the result should have.
pub fn to_roman_numerals(number: u32, casing: Casing) -> String {
use core::iter::once;
let thousands = number / 1000;
let hundreds = (number / 100) % 10;
let tens = (number / 10) % 10;
let ones = number % 10;
let upper_case = once("M")
.cycle()
.take(thousands as usize)
.chain(once(ROMAN_NUMBER_MAP_HUNDREDS[hundreds as usize]))
.chain(once(ROMAN_NUMBER_MAP_TENS[tens as usize]))
.chain(once(ROMAN_NUMBER_MAP_ONES[ones as usize]))
.collect();
if casing == Casing::Upper {
upper_case
} else {
upper_case.to_lowercase()
}
}
#[test]
fn test_to_roman_numerals_uppercase() {
assert_eq!(to_roman_numerals(1, Casing::Upper), "I");
assert_eq!(to_roman_numerals(6, Casing::Upper), "VI");
assert_eq!(to_roman_numerals(7, Casing::Upper), "VII");
assert_eq!(to_roman_numerals(8, Casing::Upper), "VIII");
assert_eq!(to_roman_numerals(10, Casing::Upper), "X");
assert_eq!(to_roman_numerals(40, Casing::Upper), "XL");
assert_eq!(to_roman_numerals(100, Casing::Upper), "C");
assert_eq!(to_roman_numerals(500, Casing::Upper), "D");
assert_eq!(to_roman_numerals(1000, Casing::Upper), "M");
assert_eq!(to_roman_numerals(2019, Casing::Upper), "MMXIX");
}
#[test]
fn test_to_roman_numerals_lowercase() {
assert_eq!(to_roman_numerals(1, Casing::Lower), "i");
assert_eq!(to_roman_numerals(6, Casing::Lower), "vi");
assert_eq!(to_roman_numerals(7, Casing::Lower), "vii");
assert_eq!(to_roman_numerals(8, Casing::Lower), "viii");
assert_eq!(to_roman_numerals(10, Casing::Lower), "x");
assert_eq!(to_roman_numerals(40, Casing::Lower), "xl");
assert_eq!(to_roman_numerals(100, Casing::Lower), "c");
assert_eq!(to_roman_numerals(500, Casing::Lower), "d");
assert_eq!(to_roman_numerals(1000, Casing::Lower), "m");
assert_eq!(to_roman_numerals(2019, Casing::Lower), "mmxix");
}
#[cfg(target_arch = "wasm32")]
mod wasm {
use super::*;
use js_sys::{Error, Number};
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen(js_name = toRomanNumerals)]
pub fn to_roman_numerals(value: JsValue, lowercase: Option<bool>) -> Result<String, JsValue> {
let number = Some(value)
.filter(Number::is_integer)
.and_then(|f| f.as_f64())
.filter(|f| *f > 0.0)
.map(|f| f as u32)
.ok_or(JsValue::from(Error::new(
"The number should be a positive integer.",
)))?;
let casing = if lowercase.unwrap_or(false) {
Casing::Lower
} else {
Casing::Upper
};
Ok(super::to_roman_numerals(number, casing))
}
#[wasm_bindgen_test]
fn test_to_roman_numerals_uppercase() {
assert_eq!(to_roman_numerals(1.into(), None), Ok("I".to_string()));
assert_eq!(to_roman_numerals(6.into(), None), Ok("VI".to_string()));
assert_eq!(to_roman_numerals(7.into(), None), Ok("VII".to_string()));
assert_eq!(to_roman_numerals(8.into(), None), Ok("VIII".to_string()));
assert_eq!(to_roman_numerals(10.into(), None), Ok("X".to_string()));
assert_eq!(to_roman_numerals(40.into(), None), Ok("XL".to_string()));
assert_eq!(to_roman_numerals(100.into(), None), Ok("C".to_string()));
assert_eq!(to_roman_numerals(500.into(), None), Ok("D".to_string()));
assert_eq!(to_roman_numerals(1000.into(), None), Ok("M".to_string()));
assert_eq!(
to_roman_numerals(2019.into(), None),
Ok("MMXIX".to_string())
);
}
#[wasm_bindgen_test]
fn test_to_roman_numerals_lowercase() {
assert_eq!(to_roman_numerals(1.into(), Some(true)), Ok("i".to_string()));
assert_eq!(
to_roman_numerals(6.into(), Some(true)),
Ok("vi".to_string())
);
assert_eq!(
to_roman_numerals(7.into(), Some(true)),
Ok("vii".to_string())
);
assert_eq!(
to_roman_numerals(8.into(), Some(true)),
Ok("viii".to_string())
);
assert_eq!(
to_roman_numerals(10.into(), Some(true)),
Ok("x".to_string())
);
assert_eq!(
to_roman_numerals(40.into(), Some(true)),
Ok("xl".to_string())
);
assert_eq!(
to_roman_numerals(100.into(), Some(true)),
Ok("c".to_string())
);
assert_eq!(
to_roman_numerals(500.into(), Some(true)),
Ok("d".to_string())
);
assert_eq!(
to_roman_numerals(1000.into(), Some(true)),
Ok("m".to_string())
);
assert_eq!(
to_roman_numerals(2019.into(), Some(true)),
Ok("mmxix".to_string())
);
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qlayoutitem.h
// dst-file: /src/widgets/qlayoutitem.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
// use super::qlayoutitem::QSpacerItem; // 773
use super::super::core::qsize::*; // 771
use super::qwidget::*; // 773
use super::super::core::qrect::*; // 771
use super::qlayout::*; // 773
// use super::qlayoutitem::QLayoutItem; // 773
use super::qsizepolicy::*; // 773
// use super::qlayoutitem::QWidgetItem; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QLayoutItem_Class_Size() -> c_int;
// proto: QSpacerItem * QLayoutItem::spacerItem();
fn C_ZN11QLayoutItem10spacerItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QLayoutItem::minimumSize();
fn C_ZNK11QLayoutItem11minimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QWidget * QLayoutItem::widget();
fn C_ZN11QLayoutItem6widgetEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLayoutItem::invalidate();
fn C_ZN11QLayoutItem10invalidateEv(qthis: u64 /* *mut c_void*/);
// proto: void QLayoutItem::setGeometry(const QRect & );
fn C_ZN11QLayoutItem11setGeometryERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QLayout * QLayoutItem::layout();
fn C_ZN11QLayoutItem6layoutEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QLayoutItem::isEmpty();
fn C_ZNK11QLayoutItem7isEmptyEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QSize QLayoutItem::sizeHint();
fn C_ZNK11QLayoutItem8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLayoutItem::~QLayoutItem();
fn C_ZN11QLayoutItemD2Ev(qthis: u64 /* *mut c_void*/);
// proto: bool QLayoutItem::hasHeightForWidth();
fn C_ZNK11QLayoutItem17hasHeightForWidthEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: int QLayoutItem::heightForWidth(int );
fn C_ZNK11QLayoutItem14heightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: QRect QLayoutItem::geometry();
fn C_ZNK11QLayoutItem8geometryEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QLayoutItem::maximumSize();
fn C_ZNK11QLayoutItem11maximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QLayoutItem::minimumHeightForWidth(int );
fn C_ZNK11QLayoutItem21minimumHeightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
fn QSpacerItem_Class_Size() -> c_int;
// proto: QSize QSpacerItem::minimumSize();
fn C_ZNK11QSpacerItem11minimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSizePolicy QSpacerItem::sizePolicy();
fn C_ZNK11QSpacerItem10sizePolicyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QSpacerItem::~QSpacerItem();
fn C_ZN11QSpacerItemD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QSize QSpacerItem::sizeHint();
fn C_ZNK11QSpacerItem8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QSpacerItem::maximumSize();
fn C_ZNK11QSpacerItem11maximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QSpacerItem::isEmpty();
fn C_ZNK11QSpacerItem7isEmptyEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QRect QSpacerItem::geometry();
fn C_ZNK11QSpacerItem8geometryEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QSpacerItem::setGeometry(const QRect & );
fn C_ZN11QSpacerItem11setGeometryERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QSpacerItem * QSpacerItem::spacerItem();
fn C_ZN11QSpacerItem10spacerItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
fn QWidgetItem_Class_Size() -> c_int;
// proto: QSize QWidgetItem::sizeHint();
fn C_ZNK11QWidgetItem8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QWidgetItem::minimumSize();
fn C_ZNK11QWidgetItem11minimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QWidgetItem::hasHeightForWidth();
fn C_ZNK11QWidgetItem17hasHeightForWidthEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QWidgetItem::~QWidgetItem();
fn C_ZN11QWidgetItemD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QWidgetItem::QWidgetItem(QWidget * w);
fn C_ZN11QWidgetItemC2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: QWidget * QWidgetItem::widget();
fn C_ZN11QWidgetItem6widgetEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QWidgetItem::setGeometry(const QRect & );
fn C_ZN11QWidgetItem11setGeometryERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QWidgetItem::heightForWidth(int );
fn C_ZNK11QWidgetItem14heightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: QSize QWidgetItem::maximumSize();
fn C_ZNK11QWidgetItem11maximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QWidgetItem::isEmpty();
fn C_ZNK11QWidgetItem7isEmptyEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QRect QWidgetItem::geometry();
fn C_ZNK11QWidgetItem8geometryEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
fn QWidgetItemV2_Class_Size() -> c_int;
// proto: QSize QWidgetItemV2::sizeHint();
fn C_ZNK13QWidgetItemV28sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QWidgetItemV2::minimumSize();
fn C_ZNK13QWidgetItemV211minimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QWidgetItemV2::heightForWidth(int width);
fn C_ZNK13QWidgetItemV214heightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: void QWidgetItemV2::~QWidgetItemV2();
fn C_ZN13QWidgetItemV2D2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QWidgetItemV2::QWidgetItemV2(QWidget * widget);
fn C_ZN13QWidgetItemV2C2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: QSize QWidgetItemV2::maximumSize();
fn C_ZNK13QWidgetItemV211maximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QLayoutItem)=1
#[derive(Default)]
pub struct QLayoutItem {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QSpacerItem)=1
#[derive(Default)]
pub struct QSpacerItem {
qbase: QLayoutItem,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QWidgetItem)=1
#[derive(Default)]
pub struct QWidgetItem {
qbase: QLayoutItem,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QWidgetItemV2)=1
#[derive(Default)]
pub struct QWidgetItemV2 {
qbase: QWidgetItem,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QLayoutItem {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QLayoutItem {
return QLayoutItem{qclsinst: qthis, ..Default::default()};
}
}
// proto: QSpacerItem * QLayoutItem::spacerItem();
impl /*struct*/ QLayoutItem {
pub fn spacerItem<RetType, T: QLayoutItem_spacerItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.spacerItem(self);
// return 1;
}
}
pub trait QLayoutItem_spacerItem<RetType> {
fn spacerItem(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: QSpacerItem * QLayoutItem::spacerItem();
impl<'a> /*trait*/ QLayoutItem_spacerItem<QSpacerItem> for () {
fn spacerItem(self , rsthis: & QLayoutItem) -> QSpacerItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QLayoutItem10spacerItemEv()};
let mut ret = unsafe {C_ZN11QLayoutItem10spacerItemEv(rsthis.qclsinst)};
let mut ret1 = QSpacerItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QLayoutItem::minimumSize();
impl /*struct*/ QLayoutItem {
pub fn minimumSize<RetType, T: QLayoutItem_minimumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumSize(self);
// return 1;
}
}
pub trait QLayoutItem_minimumSize<RetType> {
fn minimumSize(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: QSize QLayoutItem::minimumSize();
impl<'a> /*trait*/ QLayoutItem_minimumSize<QSize> for () {
fn minimumSize(self , rsthis: & QLayoutItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem11minimumSizeEv()};
let mut ret = unsafe {C_ZNK11QLayoutItem11minimumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QWidget * QLayoutItem::widget();
impl /*struct*/ QLayoutItem {
pub fn widget<RetType, T: QLayoutItem_widget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.widget(self);
// return 1;
}
}
pub trait QLayoutItem_widget<RetType> {
fn widget(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: QWidget * QLayoutItem::widget();
impl<'a> /*trait*/ QLayoutItem_widget<QWidget> for () {
fn widget(self , rsthis: & QLayoutItem) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QLayoutItem6widgetEv()};
let mut ret = unsafe {C_ZN11QLayoutItem6widgetEv(rsthis.qclsinst)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayoutItem::invalidate();
impl /*struct*/ QLayoutItem {
pub fn invalidate<RetType, T: QLayoutItem_invalidate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.invalidate(self);
// return 1;
}
}
pub trait QLayoutItem_invalidate<RetType> {
fn invalidate(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: void QLayoutItem::invalidate();
impl<'a> /*trait*/ QLayoutItem_invalidate<()> for () {
fn invalidate(self , rsthis: & QLayoutItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QLayoutItem10invalidateEv()};
unsafe {C_ZN11QLayoutItem10invalidateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QLayoutItem::setGeometry(const QRect & );
impl /*struct*/ QLayoutItem {
pub fn setGeometry<RetType, T: QLayoutItem_setGeometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setGeometry(self);
// return 1;
}
}
pub trait QLayoutItem_setGeometry<RetType> {
fn setGeometry(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: void QLayoutItem::setGeometry(const QRect & );
impl<'a> /*trait*/ QLayoutItem_setGeometry<()> for (&'a QRect) {
fn setGeometry(self , rsthis: & QLayoutItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QLayoutItem11setGeometryERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QLayoutItem11setGeometryERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QLayout * QLayoutItem::layout();
impl /*struct*/ QLayoutItem {
pub fn layout<RetType, T: QLayoutItem_layout<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.layout(self);
// return 1;
}
}
pub trait QLayoutItem_layout<RetType> {
fn layout(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: QLayout * QLayoutItem::layout();
impl<'a> /*trait*/ QLayoutItem_layout<QLayout> for () {
fn layout(self , rsthis: & QLayoutItem) -> QLayout {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QLayoutItem6layoutEv()};
let mut ret = unsafe {C_ZN11QLayoutItem6layoutEv(rsthis.qclsinst)};
let mut ret1 = QLayout::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QLayoutItem::isEmpty();
impl /*struct*/ QLayoutItem {
pub fn isEmpty<RetType, T: QLayoutItem_isEmpty<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEmpty(self);
// return 1;
}
}
pub trait QLayoutItem_isEmpty<RetType> {
fn isEmpty(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: bool QLayoutItem::isEmpty();
impl<'a> /*trait*/ QLayoutItem_isEmpty<i8> for () {
fn isEmpty(self , rsthis: & QLayoutItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem7isEmptyEv()};
let mut ret = unsafe {C_ZNK11QLayoutItem7isEmptyEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QSize QLayoutItem::sizeHint();
impl /*struct*/ QLayoutItem {
pub fn sizeHint<RetType, T: QLayoutItem_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QLayoutItem_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: QSize QLayoutItem::sizeHint();
impl<'a> /*trait*/ QLayoutItem_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QLayoutItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem8sizeHintEv()};
let mut ret = unsafe {C_ZNK11QLayoutItem8sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLayoutItem::~QLayoutItem();
impl /*struct*/ QLayoutItem {
pub fn free<RetType, T: QLayoutItem_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QLayoutItem_free<RetType> {
fn free(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: void QLayoutItem::~QLayoutItem();
impl<'a> /*trait*/ QLayoutItem_free<()> for () {
fn free(self , rsthis: & QLayoutItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QLayoutItemD2Ev()};
unsafe {C_ZN11QLayoutItemD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QLayoutItem::hasHeightForWidth();
impl /*struct*/ QLayoutItem {
pub fn hasHeightForWidth<RetType, T: QLayoutItem_hasHeightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasHeightForWidth(self);
// return 1;
}
}
pub trait QLayoutItem_hasHeightForWidth<RetType> {
fn hasHeightForWidth(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: bool QLayoutItem::hasHeightForWidth();
impl<'a> /*trait*/ QLayoutItem_hasHeightForWidth<i8> for () {
fn hasHeightForWidth(self , rsthis: & QLayoutItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem17hasHeightForWidthEv()};
let mut ret = unsafe {C_ZNK11QLayoutItem17hasHeightForWidthEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QLayoutItem::heightForWidth(int );
impl /*struct*/ QLayoutItem {
pub fn heightForWidth<RetType, T: QLayoutItem_heightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.heightForWidth(self);
// return 1;
}
}
pub trait QLayoutItem_heightForWidth<RetType> {
fn heightForWidth(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: int QLayoutItem::heightForWidth(int );
impl<'a> /*trait*/ QLayoutItem_heightForWidth<i32> for (i32) {
fn heightForWidth(self , rsthis: & QLayoutItem) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem14heightForWidthEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QLayoutItem14heightForWidthEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: QRect QLayoutItem::geometry();
impl /*struct*/ QLayoutItem {
pub fn geometry<RetType, T: QLayoutItem_geometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.geometry(self);
// return 1;
}
}
pub trait QLayoutItem_geometry<RetType> {
fn geometry(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: QRect QLayoutItem::geometry();
impl<'a> /*trait*/ QLayoutItem_geometry<QRect> for () {
fn geometry(self , rsthis: & QLayoutItem) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem8geometryEv()};
let mut ret = unsafe {C_ZNK11QLayoutItem8geometryEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QLayoutItem::maximumSize();
impl /*struct*/ QLayoutItem {
pub fn maximumSize<RetType, T: QLayoutItem_maximumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.maximumSize(self);
// return 1;
}
}
pub trait QLayoutItem_maximumSize<RetType> {
fn maximumSize(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: QSize QLayoutItem::maximumSize();
impl<'a> /*trait*/ QLayoutItem_maximumSize<QSize> for () {
fn maximumSize(self , rsthis: & QLayoutItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem11maximumSizeEv()};
let mut ret = unsafe {C_ZNK11QLayoutItem11maximumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QLayoutItem::minimumHeightForWidth(int );
impl /*struct*/ QLayoutItem {
pub fn minimumHeightForWidth<RetType, T: QLayoutItem_minimumHeightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumHeightForWidth(self);
// return 1;
}
}
pub trait QLayoutItem_minimumHeightForWidth<RetType> {
fn minimumHeightForWidth(self , rsthis: & QLayoutItem) -> RetType;
}
// proto: int QLayoutItem::minimumHeightForWidth(int );
impl<'a> /*trait*/ QLayoutItem_minimumHeightForWidth<i32> for (i32) {
fn minimumHeightForWidth(self , rsthis: & QLayoutItem) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QLayoutItem21minimumHeightForWidthEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QLayoutItem21minimumHeightForWidthEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
impl /*struct*/ QSpacerItem {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSpacerItem {
return QSpacerItem{qbase: QLayoutItem::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QSpacerItem {
type Target = QLayoutItem;
fn deref(&self) -> &QLayoutItem {
return & self.qbase;
}
}
impl AsRef<QLayoutItem> for QSpacerItem {
fn as_ref(& self) -> & QLayoutItem {
return & self.qbase;
}
}
// proto: QSize QSpacerItem::minimumSize();
impl /*struct*/ QSpacerItem {
pub fn minimumSize<RetType, T: QSpacerItem_minimumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumSize(self);
// return 1;
}
}
pub trait QSpacerItem_minimumSize<RetType> {
fn minimumSize(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: QSize QSpacerItem::minimumSize();
impl<'a> /*trait*/ QSpacerItem_minimumSize<QSize> for () {
fn minimumSize(self , rsthis: & QSpacerItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSpacerItem11minimumSizeEv()};
let mut ret = unsafe {C_ZNK11QSpacerItem11minimumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSizePolicy QSpacerItem::sizePolicy();
impl /*struct*/ QSpacerItem {
pub fn sizePolicy<RetType, T: QSpacerItem_sizePolicy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizePolicy(self);
// return 1;
}
}
pub trait QSpacerItem_sizePolicy<RetType> {
fn sizePolicy(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: QSizePolicy QSpacerItem::sizePolicy();
impl<'a> /*trait*/ QSpacerItem_sizePolicy<QSizePolicy> for () {
fn sizePolicy(self , rsthis: & QSpacerItem) -> QSizePolicy {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSpacerItem10sizePolicyEv()};
let mut ret = unsafe {C_ZNK11QSpacerItem10sizePolicyEv(rsthis.qclsinst)};
let mut ret1 = QSizePolicy::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QSpacerItem::~QSpacerItem();
impl /*struct*/ QSpacerItem {
pub fn free<RetType, T: QSpacerItem_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QSpacerItem_free<RetType> {
fn free(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: void QSpacerItem::~QSpacerItem();
impl<'a> /*trait*/ QSpacerItem_free<()> for () {
fn free(self , rsthis: & QSpacerItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSpacerItemD2Ev()};
unsafe {C_ZN11QSpacerItemD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QSize QSpacerItem::sizeHint();
impl /*struct*/ QSpacerItem {
pub fn sizeHint<RetType, T: QSpacerItem_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QSpacerItem_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: QSize QSpacerItem::sizeHint();
impl<'a> /*trait*/ QSpacerItem_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QSpacerItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSpacerItem8sizeHintEv()};
let mut ret = unsafe {C_ZNK11QSpacerItem8sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QSpacerItem::maximumSize();
impl /*struct*/ QSpacerItem {
pub fn maximumSize<RetType, T: QSpacerItem_maximumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.maximumSize(self);
// return 1;
}
}
pub trait QSpacerItem_maximumSize<RetType> {
fn maximumSize(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: QSize QSpacerItem::maximumSize();
impl<'a> /*trait*/ QSpacerItem_maximumSize<QSize> for () {
fn maximumSize(self , rsthis: & QSpacerItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSpacerItem11maximumSizeEv()};
let mut ret = unsafe {C_ZNK11QSpacerItem11maximumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QSpacerItem::isEmpty();
impl /*struct*/ QSpacerItem {
pub fn isEmpty<RetType, T: QSpacerItem_isEmpty<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEmpty(self);
// return 1;
}
}
pub trait QSpacerItem_isEmpty<RetType> {
fn isEmpty(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: bool QSpacerItem::isEmpty();
impl<'a> /*trait*/ QSpacerItem_isEmpty<i8> for () {
fn isEmpty(self , rsthis: & QSpacerItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSpacerItem7isEmptyEv()};
let mut ret = unsafe {C_ZNK11QSpacerItem7isEmptyEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QRect QSpacerItem::geometry();
impl /*struct*/ QSpacerItem {
pub fn geometry<RetType, T: QSpacerItem_geometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.geometry(self);
// return 1;
}
}
pub trait QSpacerItem_geometry<RetType> {
fn geometry(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: QRect QSpacerItem::geometry();
impl<'a> /*trait*/ QSpacerItem_geometry<QRect> for () {
fn geometry(self , rsthis: & QSpacerItem) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSpacerItem8geometryEv()};
let mut ret = unsafe {C_ZNK11QSpacerItem8geometryEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QSpacerItem::setGeometry(const QRect & );
impl /*struct*/ QSpacerItem {
pub fn setGeometry<RetType, T: QSpacerItem_setGeometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setGeometry(self);
// return 1;
}
}
pub trait QSpacerItem_setGeometry<RetType> {
fn setGeometry(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: void QSpacerItem::setGeometry(const QRect & );
impl<'a> /*trait*/ QSpacerItem_setGeometry<()> for (&'a QRect) {
fn setGeometry(self , rsthis: & QSpacerItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSpacerItem11setGeometryERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QSpacerItem11setGeometryERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSpacerItem * QSpacerItem::spacerItem();
impl /*struct*/ QSpacerItem {
pub fn spacerItem<RetType, T: QSpacerItem_spacerItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.spacerItem(self);
// return 1;
}
}
pub trait QSpacerItem_spacerItem<RetType> {
fn spacerItem(self , rsthis: & QSpacerItem) -> RetType;
}
// proto: QSpacerItem * QSpacerItem::spacerItem();
impl<'a> /*trait*/ QSpacerItem_spacerItem<QSpacerItem> for () {
fn spacerItem(self , rsthis: & QSpacerItem) -> QSpacerItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSpacerItem10spacerItemEv()};
let mut ret = unsafe {C_ZN11QSpacerItem10spacerItemEv(rsthis.qclsinst)};
let mut ret1 = QSpacerItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
impl /*struct*/ QWidgetItem {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QWidgetItem {
return QWidgetItem{qbase: QLayoutItem::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QWidgetItem {
type Target = QLayoutItem;
fn deref(&self) -> &QLayoutItem {
return & self.qbase;
}
}
impl AsRef<QLayoutItem> for QWidgetItem {
fn as_ref(& self) -> & QLayoutItem {
return & self.qbase;
}
}
// proto: QSize QWidgetItem::sizeHint();
impl /*struct*/ QWidgetItem {
pub fn sizeHint<RetType, T: QWidgetItem_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QWidgetItem_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: QSize QWidgetItem::sizeHint();
impl<'a> /*trait*/ QWidgetItem_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QWidgetItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QWidgetItem8sizeHintEv()};
let mut ret = unsafe {C_ZNK11QWidgetItem8sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QWidgetItem::minimumSize();
impl /*struct*/ QWidgetItem {
pub fn minimumSize<RetType, T: QWidgetItem_minimumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumSize(self);
// return 1;
}
}
pub trait QWidgetItem_minimumSize<RetType> {
fn minimumSize(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: QSize QWidgetItem::minimumSize();
impl<'a> /*trait*/ QWidgetItem_minimumSize<QSize> for () {
fn minimumSize(self , rsthis: & QWidgetItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QWidgetItem11minimumSizeEv()};
let mut ret = unsafe {C_ZNK11QWidgetItem11minimumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QWidgetItem::hasHeightForWidth();
impl /*struct*/ QWidgetItem {
pub fn hasHeightForWidth<RetType, T: QWidgetItem_hasHeightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasHeightForWidth(self);
// return 1;
}
}
pub trait QWidgetItem_hasHeightForWidth<RetType> {
fn hasHeightForWidth(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: bool QWidgetItem::hasHeightForWidth();
impl<'a> /*trait*/ QWidgetItem_hasHeightForWidth<i8> for () {
fn hasHeightForWidth(self , rsthis: & QWidgetItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QWidgetItem17hasHeightForWidthEv()};
let mut ret = unsafe {C_ZNK11QWidgetItem17hasHeightForWidthEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QWidgetItem::~QWidgetItem();
impl /*struct*/ QWidgetItem {
pub fn free<RetType, T: QWidgetItem_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QWidgetItem_free<RetType> {
fn free(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: void QWidgetItem::~QWidgetItem();
impl<'a> /*trait*/ QWidgetItem_free<()> for () {
fn free(self , rsthis: & QWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QWidgetItemD2Ev()};
unsafe {C_ZN11QWidgetItemD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QWidgetItem::QWidgetItem(QWidget * w);
impl /*struct*/ QWidgetItem {
pub fn new<T: QWidgetItem_new>(value: T) -> QWidgetItem {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QWidgetItem_new {
fn new(self) -> QWidgetItem;
}
// proto: void QWidgetItem::QWidgetItem(QWidget * w);
impl<'a> /*trait*/ QWidgetItem_new for (&'a QWidget) {
fn new(self) -> QWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QWidgetItemC2EP7QWidget()};
let ctysz: c_int = unsafe{QWidgetItem_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_ZN11QWidgetItemC2EP7QWidget(arg0)};
let rsthis = QWidgetItem{qbase: QLayoutItem::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QWidget * QWidgetItem::widget();
impl /*struct*/ QWidgetItem {
pub fn widget<RetType, T: QWidgetItem_widget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.widget(self);
// return 1;
}
}
pub trait QWidgetItem_widget<RetType> {
fn widget(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: QWidget * QWidgetItem::widget();
impl<'a> /*trait*/ QWidgetItem_widget<QWidget> for () {
fn widget(self , rsthis: & QWidgetItem) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QWidgetItem6widgetEv()};
let mut ret = unsafe {C_ZN11QWidgetItem6widgetEv(rsthis.qclsinst)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QWidgetItem::setGeometry(const QRect & );
impl /*struct*/ QWidgetItem {
pub fn setGeometry<RetType, T: QWidgetItem_setGeometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setGeometry(self);
// return 1;
}
}
pub trait QWidgetItem_setGeometry<RetType> {
fn setGeometry(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: void QWidgetItem::setGeometry(const QRect & );
impl<'a> /*trait*/ QWidgetItem_setGeometry<()> for (&'a QRect) {
fn setGeometry(self , rsthis: & QWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QWidgetItem11setGeometryERK5QRect()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QWidgetItem11setGeometryERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QWidgetItem::heightForWidth(int );
impl /*struct*/ QWidgetItem {
pub fn heightForWidth<RetType, T: QWidgetItem_heightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.heightForWidth(self);
// return 1;
}
}
pub trait QWidgetItem_heightForWidth<RetType> {
fn heightForWidth(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: int QWidgetItem::heightForWidth(int );
impl<'a> /*trait*/ QWidgetItem_heightForWidth<i32> for (i32) {
fn heightForWidth(self , rsthis: & QWidgetItem) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QWidgetItem14heightForWidthEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QWidgetItem14heightForWidthEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: QSize QWidgetItem::maximumSize();
impl /*struct*/ QWidgetItem {
pub fn maximumSize<RetType, T: QWidgetItem_maximumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.maximumSize(self);
// return 1;
}
}
pub trait QWidgetItem_maximumSize<RetType> {
fn maximumSize(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: QSize QWidgetItem::maximumSize();
impl<'a> /*trait*/ QWidgetItem_maximumSize<QSize> for () {
fn maximumSize(self , rsthis: & QWidgetItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QWidgetItem11maximumSizeEv()};
let mut ret = unsafe {C_ZNK11QWidgetItem11maximumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QWidgetItem::isEmpty();
impl /*struct*/ QWidgetItem {
pub fn isEmpty<RetType, T: QWidgetItem_isEmpty<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEmpty(self);
// return 1;
}
}
pub trait QWidgetItem_isEmpty<RetType> {
fn isEmpty(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: bool QWidgetItem::isEmpty();
impl<'a> /*trait*/ QWidgetItem_isEmpty<i8> for () {
fn isEmpty(self , rsthis: & QWidgetItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QWidgetItem7isEmptyEv()};
let mut ret = unsafe {C_ZNK11QWidgetItem7isEmptyEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QRect QWidgetItem::geometry();
impl /*struct*/ QWidgetItem {
pub fn geometry<RetType, T: QWidgetItem_geometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.geometry(self);
// return 1;
}
}
pub trait QWidgetItem_geometry<RetType> {
fn geometry(self , rsthis: & QWidgetItem) -> RetType;
}
// proto: QRect QWidgetItem::geometry();
impl<'a> /*trait*/ QWidgetItem_geometry<QRect> for () {
fn geometry(self , rsthis: & QWidgetItem) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QWidgetItem8geometryEv()};
let mut ret = unsafe {C_ZNK11QWidgetItem8geometryEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
impl /*struct*/ QWidgetItemV2 {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QWidgetItemV2 {
return QWidgetItemV2{qbase: QWidgetItem::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QWidgetItemV2 {
type Target = QWidgetItem;
fn deref(&self) -> &QWidgetItem {
return & self.qbase;
}
}
impl AsRef<QWidgetItem> for QWidgetItemV2 {
fn as_ref(& self) -> & QWidgetItem {
return & self.qbase;
}
}
// proto: QSize QWidgetItemV2::sizeHint();
impl /*struct*/ QWidgetItemV2 {
pub fn sizeHint<RetType, T: QWidgetItemV2_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QWidgetItemV2_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QWidgetItemV2) -> RetType;
}
// proto: QSize QWidgetItemV2::sizeHint();
impl<'a> /*trait*/ QWidgetItemV2_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QWidgetItemV2) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QWidgetItemV28sizeHintEv()};
let mut ret = unsafe {C_ZNK13QWidgetItemV28sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QWidgetItemV2::minimumSize();
impl /*struct*/ QWidgetItemV2 {
pub fn minimumSize<RetType, T: QWidgetItemV2_minimumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumSize(self);
// return 1;
}
}
pub trait QWidgetItemV2_minimumSize<RetType> {
fn minimumSize(self , rsthis: & QWidgetItemV2) -> RetType;
}
// proto: QSize QWidgetItemV2::minimumSize();
impl<'a> /*trait*/ QWidgetItemV2_minimumSize<QSize> for () {
fn minimumSize(self , rsthis: & QWidgetItemV2) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QWidgetItemV211minimumSizeEv()};
let mut ret = unsafe {C_ZNK13QWidgetItemV211minimumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QWidgetItemV2::heightForWidth(int width);
impl /*struct*/ QWidgetItemV2 {
pub fn heightForWidth<RetType, T: QWidgetItemV2_heightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.heightForWidth(self);
// return 1;
}
}
pub trait QWidgetItemV2_heightForWidth<RetType> {
fn heightForWidth(self , rsthis: & QWidgetItemV2) -> RetType;
}
// proto: int QWidgetItemV2::heightForWidth(int width);
impl<'a> /*trait*/ QWidgetItemV2_heightForWidth<i32> for (i32) {
fn heightForWidth(self , rsthis: & QWidgetItemV2) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QWidgetItemV214heightForWidthEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK13QWidgetItemV214heightForWidthEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QWidgetItemV2::~QWidgetItemV2();
impl /*struct*/ QWidgetItemV2 {
pub fn free<RetType, T: QWidgetItemV2_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QWidgetItemV2_free<RetType> {
fn free(self , rsthis: & QWidgetItemV2) -> RetType;
}
// proto: void QWidgetItemV2::~QWidgetItemV2();
impl<'a> /*trait*/ QWidgetItemV2_free<()> for () {
fn free(self , rsthis: & QWidgetItemV2) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QWidgetItemV2D2Ev()};
unsafe {C_ZN13QWidgetItemV2D2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QWidgetItemV2::QWidgetItemV2(QWidget * widget);
impl /*struct*/ QWidgetItemV2 {
pub fn new<T: QWidgetItemV2_new>(value: T) -> QWidgetItemV2 {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QWidgetItemV2_new {
fn new(self) -> QWidgetItemV2;
}
// proto: void QWidgetItemV2::QWidgetItemV2(QWidget * widget);
impl<'a> /*trait*/ QWidgetItemV2_new for (&'a QWidget) {
fn new(self) -> QWidgetItemV2 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QWidgetItemV2C2EP7QWidget()};
let ctysz: c_int = unsafe{QWidgetItemV2_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_ZN13QWidgetItemV2C2EP7QWidget(arg0)};
let rsthis = QWidgetItemV2{qbase: QWidgetItem::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QSize QWidgetItemV2::maximumSize();
impl /*struct*/ QWidgetItemV2 {
pub fn maximumSize<RetType, T: QWidgetItemV2_maximumSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.maximumSize(self);
// return 1;
}
}
pub trait QWidgetItemV2_maximumSize<RetType> {
fn maximumSize(self , rsthis: & QWidgetItemV2) -> RetType;
}
// proto: QSize QWidgetItemV2::maximumSize();
impl<'a> /*trait*/ QWidgetItemV2_maximumSize<QSize> for () {
fn maximumSize(self , rsthis: & QWidgetItemV2) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QWidgetItemV211maximumSizeEv()};
let mut ret = unsafe {C_ZNK13QWidgetItemV211maximumSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
struct Point { x: u32, y: u32 }
enum Option<T> { None, Some(T) }
fn map<S, T, F: Fn(S) -> T>(opt: Option<S>, f: F) -> Option<T> {
match opt {
Option::None => Option::None,
Option::Some(s) => Option::Some(f(s)),
}
}
|
//author: Ryan Niemi0
use std::cmp::Ordering;
use std::cmp::max;
use core::iter::Map;
use quickcheck::{Arbitrary, Gen};
use std::mem::{replace, swap};
use avl_tree_set::set::AvlTreeSet;
#[derive(Debug, PartialEq)]
struct AvlNode<'a, T: Ord> {
value: T,
left: AvlTree<'a, T>,
right: AvlTree<'a, T>,
height: usize,
parent_node: Option<&'a mut AvlNode<'a, T>>,
}
impl<'a, T: 'a + Ord> AvlNode<T> {
fn rebalance(&mut self) -> bool {
match self.balance_factor() {
-2 => {
// Root is right heavy
let right_node = self.right.as_mut().unwrap();
// Inner node is left heavy
if right_node.balance_factor() == 1 {
right_node.rotate_right();
}
self.rotate_left();
true
}
2 => {
// Root is left heavy
let left_node = self.left.as_mut().unwrap();
// Inner node is right heavy
if left_node.balance_factor() == -1 {
left_node.rotate_left();
}
self.rotate_right();
true
}
_ => false,
}
}
fn left_height(&self) -> usize {
self.left.as_ref().map_or(0, |left| left.height())
}
fn right_height(&self) -> usize {
self.right.as_ref().map_or(0, |right| right.height())
}
pub fn balance_factor(&self) -> i8 {
let left_height = self.left_height();
let right_height = self.right_height();
if left_height >= right_height {
(left_height - right_height) as i8
} else {
-((right_height - left_height) as i8)
}
}
fn update_ancestors_height(&mut self) {
self.update_height();
let mut current_node = self;
while let Some(parent_node) = current_node.parent_node {
parent_node.update_height();
current_node = parent_node;
}
}
fn update_height(&mut self) {
self.height = 1 + max(self.left_height(), self.right_height());
}
fn rotate_right(&mut self) -> bool {
if self.left.is_none() {
return false;
}
// 1. Take nodes A and C
let left_node = self.left.as_mut().unwrap();
let left_right_tree = left_node.right.take();
let left_left_tree = left_node.left.take();
// 2. Link A node to left node
let mut new_right_tree = replace(&mut self.left, left_left_tree);
// 3. Swap B and D node value to avoid moving the root
swap(&mut self.value, &mut new_right_tree.as_mut().unwrap().value);
// 4. Take E node
let right_tree = self.right.take();
// 5. Link C and E nodes to swapped D node
let new_right_node = new_right_tree.as_mut().unwrap();
new_right_node.left = left_right_tree;
new_right_node.right = right_tree;
// 6. Link swapped D node to root right node
self.right = new_right_tree;
if let Some(node) = self.right.as_mut() {
node.update_height();
}
self.update_height();
true
}
}
type AvlTree<T> = Option<Box<AvlNode<T>>>;
#[derive(Debug, PartialEq, Clone)]
struct AvlTreeSet<T: Ord> {
root: AvlTree<T>,
}
impl<T: Ord> AvlTree<T> {
fn new() -> Self {
Self { root: None }
}
}
//insert
let mut tree = Some(Box::new(AvlNode {
value: 2,
left: Some(Box::new(AvlNode {
value: 1,
left: None,
right: None,
})),
right: Some(Box::new(AvlNode {
value: 5,
left: Some(Box::new(AvlNode {
value: 3,
left: None,
right: Some(Box::new(AvlNode {
value: 4,
left: None,
right: None,
})),
})),
right: None,
})),
});
impl<'a, T: 'a + Ord> AvlTreeSet<T> {
pub fn contains(&self, value: &T) -> bool {
let mut current_tree = &self.root;
while let Some(current_node) = current_tree {
match current_node.value.cmp(&value) {
Ordering::Less => {
current_tree = ¤t_node.right;
}
Ordering::Equal => {
return true;
}
Ordering::Greater => {
current_tree = ¤t_node.left;
}
};
}
false
}
fn iter(&'a self) -> Map<AvlTreeSetNodeIter<'a, T>, fn(&'a AvlNode<T>) -> &T> {
self.node_iter().map(|node| &node.value)
}
fn node_iter(&'a self) -> AvlTreeSetNodeIter<'a, T> {
AvlTreeSetNodeIter {
prev_nodes: Vec::default(),
current_tree: &self.root,
}
}
fn insert(&mut self, value: T) -> bool {
let mut prev_ptrs = Vec::<*mut AvlNode<T>>::new();
while let Some(current_node) = current_tree {
prev_ptrs.push(&mut **current_node);
}
// let mut prev_nodes = Vec::<&mut AvlNode<T>>::new();
// // 1. Starting from the root node or with a current node
// while let Some(current_node) = current_tree {
// prev_nodes.push(current_node);
// 2. Move to the left node if the value is less than the current node,
// right if greater, and stop if equal
match current_node.value.cmp(&value) {
Ordering::Less => current_tree = &mut current_node.right,
Ordering::Equal => {
return false;
}
Ordering::Greater => current_tree = &mut current_node.left,
}
// 3. Do this until you an empty node and insert the value
*current_tree = Some(Box::new(AvlNode {
value,
left: None,
right: None,
}));
// for node in prev_nodes.into_iter().rev() {
// 122node.update_height();
// }
for node_ptr in prev_ptrs.into_iter().rev() {
let node = unsafe { &mut *node_ptr }; // Converting a mutable pointer back to a reference
node.update_height();
node.rebalance();
}
true
}
}
//example:
// let mut set = AvlTreeSet::new();
// assert!(set.insert(1)); // Insert new value
// assert!(!set.insert(1)); // Should not insert existing value
// assert!(set.insert(2)); // Insert another new value
// assert_eq!( // Checking the tree structure
// set.root,
// Some(Box::new(AvlNode {
// value: 1,
// left: None,
// right: Some(Box::new(AvlNode {
// value: 2,
// left: None,
// right: None
// })),
// }))
// );
// impl<T: Ord> FromIterator<T> for AvlTreeSet<T> {
// fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
// let mut set = Self::new();
// for i in iter {
// set.insert(i);
// }
// set
// }
// }
// The power of IntoIterator
let vec = (1..10 as u8).collect::<Vec<_>>();
let avl = (1..10 as u8).collect::<AvlTreeSet<_>>();
let btree = (1..10 as u8).collect::<BTreeSet<_>>();
//iter
#[derive(Debug)]
struct AvlTreeSetIter<'a, T: Ord> {
prev_nodes: Vec<&'a AvlNode<T>>,
current_tree: &'a AvlTree<T>,
}
impl<'a, T: 'a + Ord> Iterator for AvlTreeSetIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
loop {
match *self.current_tree {
None => match self.prev_nodes.pop() {
None => {
return None;
}
Some(ref prev_node) => {
self.current_tree = &prev_node.right;
return Some(&prev_node.value);
}
},
Some(ref current_node) => {
if current_node.left.is_some() {
self.prev_nodes.push(¤t_node);
self.current_tree = ¤t_node.left;
continue;
}
if current_node.right.is_some() {
self.current_tree = ¤t_node.right;
return Some(¤t_node.value);
}
self.current_tree = &None;
return Some(¤t_node.value);
}
}
}
}
};
// Addition of lifetime parameter for the set
impl<'a, T: 'a + Ord> AvlTreeSet<T> {
fn update_height(&mut self) {
self.height = 1 + max(self.left_height(), self.right_height());
}
fn iter(&'a self) -> AvlTreeSetIter<'a, T> {
AvlTreeSetIter {
prev_nodes: Vec::new(),
current_tree: &self.root,
}
}
fn left_height(&self) -> usize {
self.left.as_ref().map_or(0, |left| left.height())
}
fn right_height(&self) -> usize {
self.right.as_ref().map_or(0, |right| right.height())
}
pub fn balance_factor(&self) -> i8 {
let left_height = self.left_height();
let right_height = self.right_height();
if left_height >= right_height {
(left_height - right_height) as i8
} else {
-((right_height - left_height) as i8)
}
}
}
//new impl for creating a avl
// let mut set = AvlTreeSet::new();
// for i in (1..4 as usize).rev() {
// set.insert(i);
// }
// let mut iter = set.iter();
// assert_eq!(iter.next(), Some(&1));
// assert_eq!(iter.next(), Some(&2));
// assert_eq!(iter.next(), Some(&3));
// assert_eq!(iter.next(), None);
fn height(&self) -> usize {
1 + max(
self.left_as_ref().map_or(0, |node| node.height()),
self.right_as_ref().map_or(0, |node| node.height()),
)
}
impl<T: Arbitrary + Ord> Arbitrary for AvlTreeSet<T> {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let vec: Vec<T> = Arbitrary::arbitrary(g);
vec.into_iter().collect()
}
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let vec: Vec<T> = self.iter().cloned().collect();
Box::new(vec.shrink().map(|v| v.into_iter().collect::<Self>()))
}
}
fn take(&mut self, value: &T) -> Option<T> {
let mut prev_ptrs = Vec::<*mut AvlNode<T>>::new();
// 1. Starting from the root node or with a current node
let mut current_tree = &mut self.root;
let mut target_value = None;
while let Some(current_node) = current_tree {
// 2. Move to the left node if the value is less than the current node,
// right if greater
match current_node.value.cmp(&value) {
Ordering::Less => {
prev_ptrs.push(&mut **current_node);
current_tree = &mut current_node.right;
}
Ordering::Equal => {
// 3a. Do this until you have a node equal to that value, ...
target_value = Some(&mut **current_node);
break;
}
Ordering::Greater => {
prev_ptrs.push(&mut **current_node);
current_tree = &mut current_node.left;
}
};
}
// 3b. ... otherwise stop
if target_value.as_ref().is_none() {
return None;
}
let target_node = target_value.unwrap();
// 4. Delete that node and return the value
let mut taken_value = ???;
// Retrace the path and update them accordingly
for node_ptr in prev_ptrs.into_iter().rev() {
let node = unsafe { &mut *node_ptr };
node.update_height();
node.rebalance();
}
let taken_value = if target_node.left.is_none() || target_node.right.is_none() {
if let Some(left_node) = target_node.left.take() {
replace(target_node, *left_node).value
} else if let Some(right_node) = target_node.right.take() {
replace(target_node, *right_node).value
} else {
// 1a. Get parent node
if let Some(prev_ptr) = prev_ptrs.pop() {
let prev_node = unsafe { &mut *prev_ptr };
// 1b. Determine which node to remove: left or right node
let inner_value = if let Some(ref left_node) = prev_node.left {
if left_node.value == target_node.value {
prev_node.left.take().unwrap().value
} else {
prev_node.right.take().unwrap().value
}
} else {
prev_node.right.take().unwrap().value
};
// 2. Update parent node
prev_node.update_height();
prev_node.rebalance();
target_node.update_height();
target_node.rebalance();
// 3. Return value
inner_value
} else {
// 1c. ... otherwise it is the parent and take the root node
self.root.take().unwrap().value
}
}
} else {
let right_tree = &mut target_node.right;
if right_tree.as_ref().unwrap().left.is_none() {
let mut right_node = right_tree.take().unwrap();
let inner_value = replace(&mut target_node.value, right_node.value);
replace(&mut target_node.right, right_node.right.take());
target_node.update_height();
target_node.rebalance();
inner_value
} else {
let mut right_node = right_tree.take().unwrap();
let inner_value = replace(&mut target_node.value, right_node.value);
replace(&mut target_node.right, right_node.right.take());
target_node.update_height();
target_node.rebalance();
inner_value
}
// 1. Starting with the right child of the target node
let mut next_tree = right_tree;
// We also keep track of the parent nodes to update the height
let mut inner_ptrs = Vec::<*mut AvlNode<T>>::new();
// 2. Keep moving the current node to the left child until it has none
while let Some(next_left_node) = next_tree {
if next_left_node.left.is_some() {
inner_ptrs.push(&mut **next_left_node);
}
next_tree = &mut next_left_node.left;
}
// We don't use next_tree but instead the tracked nodes as basis
let parent_left_node = unsafe { &mut *inner_ptrs.pop().unwrap() };
let mut leftmost_node = parent_left_node.left.take().unwrap();
// 3. Replace the target node value with the current node value
let inner_value = replace(&mut target_node.value, leftmost_node.value);
// 4. Replace the current node with the right child if it has
replace(&mut parent_left_node.left, leftmost_node.right.take());
// Updates the nodes in order
parent_left_node.update_height();
parent_left_node.rebalance();
for node_ptr in inner_ptrs.into_iter().rev() {
let node = unsafe { &mut *node_ptr };
node.update_height();
node.rebalance();
}
target_node.update_height();
target_node.rebalance();
inner_value
}
}
Some(taken_value)
}
pub fn main() {
let mut set = (1..10_000 as u32).rev().collect::<AvlTreeSet<_>>();
for i in 1..10_000 {
set.take(&i);
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::auth_provider_supplier::AuthProviderSupplier;
use failure::{Error, ResultExt};
use fidl_fuchsia_auth::{
AuthProviderConfig, TokenManagerFactoryRequest, TokenManagerFactoryRequestStream,
};
use futures::prelude::*;
use identity_common::TaskGroup;
use log::{info, warn};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use token_manager::{TokenManagerContext, TokenManagerError};
// The file suffix to use for token manager databases. This string is appended to the user id.
const DB_SUFFIX: &str = "_token_store.json";
type TokenManager = token_manager::TokenManager<AuthProviderSupplier>;
/// A factory to create instances of the TokenManager for individual users.
pub struct TokenManagerFactory {
/// A map storing the single TokenManager instance that will be used for each account.
///
/// Entries are created and added on the first request for a user, and are defined as an `Arc`
/// `Mutex` so they can be used in asynchronous closures that require mutable access and static
/// lifetime.
user_to_token_manager: Mutex<HashMap<String, Arc<TokenManager>>>,
/// The auth provider configuration that this token manager was initially created with.
///
/// Note: We are migrating to a build time configuration of auth providers, at which time this
/// will be unnecessary, but in the meantime a caller could attempt to specify two different
/// auth provider configuations in different calls to the factory. We do not support this since
/// it would infer separate token databases for each potential caller. Instead, we remember the
/// set of auth provider configuration that was used on the first call and return an error if
/// this is not constant across future calls.
auth_provider_configs: Mutex<Vec<AuthProviderConfig>>,
/// An object capable of launching and opening connections on components implementing the
/// AuthProviderFactory interface. This is populated on the first call that provides auth
/// provider configuration.
auth_provider_supplier: Mutex<Option<AuthProviderSupplier>>,
/// The directory to use for token manager databases.
db_dir: PathBuf,
}
impl TokenManagerFactory {
/// Creates a new TokenManagerFactory.
pub fn new(db_dir: PathBuf) -> TokenManagerFactory {
TokenManagerFactory {
user_to_token_manager: Mutex::new(HashMap::new()),
auth_provider_configs: Mutex::new(Vec::new()),
auth_provider_supplier: Mutex::new(None),
db_dir,
}
}
/// Asynchronously handles the supplied stream of `TokenManagerFactoryRequest` messages.
///
/// This method will only return an Err for errors that should be considered fatal for the
/// factory. Not that currently no failure modes meet this condition since requests for
/// different users are independant.
pub async fn handle_requests_from_stream(&self, mut stream: TokenManagerFactoryRequestStream) {
while let Ok(Some(req)) = stream.try_next().await {
self.handle_request(req).await.unwrap_or_else(|err| {
warn!("Error handling TokenManagerFactoryRequest: {:?}", err);
});
}
}
/// Asynchronously handles a single request to the TokenManagerFactory.
async fn handle_request(&self, req: TokenManagerFactoryRequest) -> Result<(), Error> {
match req {
TokenManagerFactoryRequest::GetTokenManager {
user_id,
application_url,
auth_provider_configs,
auth_context_provider,
token_manager: token_manager_server_end,
..
} => {
if !self.is_auth_provider_config_consistent(&auth_provider_configs) {
warn!("Auth provider config inconsistent with previous request");
return Ok(());
};
let token_manager = self
.get_token_manager(user_id, auth_provider_configs)
.context("Error creating TokenManager")?;
let context = TokenManagerContext {
application_url,
auth_ui_context_provider: auth_context_provider.into_proxy()?,
};
let stream = token_manager_server_end
.into_stream()
.context("Error creating request stream")?;
let token_manager_clone = Arc::clone(&token_manager);
token_manager.task_group().spawn(|cancel| async move {
token_manager_clone
.handle_requests_from_stream(&context, stream, cancel).await
.unwrap_or_else(|e| warn!("Error handling TokenManager channel {:?}", e))
}).await?;
Ok(())
}
}
}
/// Returns true iff the supplied `auth_provider_configs` are equal to any previous invocations
/// on this factory.
fn is_auth_provider_config_consistent(
&self,
auth_provider_configs: &Vec<AuthProviderConfig>,
) -> bool {
let mut previous_auth_provider_configs = self.auth_provider_configs.lock();
if previous_auth_provider_configs.is_empty() {
previous_auth_provider_configs
.extend(auth_provider_configs.iter().map(clone_auth_provider_config));
true
} else {
*previous_auth_provider_configs == *auth_provider_configs
}
}
/// Returns an `AuthProviderSupplier` for the supplied `auth_provider_configs`, or any errors
/// encountered while creating one. If an auth provider supplier has been previously created,
/// it will be cloned.
fn get_auth_provider_supplier(
&self,
auth_provider_configs: Vec<AuthProviderConfig>,
) -> Result<AuthProviderSupplier, TokenManagerError> {
let mut auth_provider_supplier_lock = self.auth_provider_supplier.lock();
match &*auth_provider_supplier_lock {
Some(auth_provider_supplier) => Ok(auth_provider_supplier.clone()),
None => {
let auth_provider_supplier = AuthProviderSupplier::new(auth_provider_configs);
auth_provider_supplier_lock.get_or_insert(auth_provider_supplier.clone());
Ok(auth_provider_supplier)
}
}
}
/// Returns a Result containing a TokenManager, or any errors encountered while creating one.
/// The TokenManager is retrieved from the user map if one already exists, or is created
/// and added to the map if not.
fn get_token_manager(
&self,
user_id: String,
auth_provider_configs: Vec<AuthProviderConfig>,
) -> Result<Arc<TokenManager>, Error> {
let mut user_to_token_manager = self.user_to_token_manager.lock();
if let Some(token_manager) = user_to_token_manager.get(&user_id) {
return Ok(Arc::clone(token_manager));
};
info!("Creating token manager for user {}", user_id);
let db_path = self.db_dir.join(user_id.clone() + DB_SUFFIX);
let token_manager = Arc::new(TokenManager::new(
&db_path,
self.get_auth_provider_supplier(auth_provider_configs)?,
TaskGroup::new(),
)?);
user_to_token_manager.insert(user_id, Arc::clone(&token_manager));
Ok(token_manager)
}
}
/// A helper function to clone an `AuthProviderConfig`, currently required since the FIDL bindings
/// do not derive clone.
fn clone_auth_provider_config(other: &AuthProviderConfig) -> AuthProviderConfig {
AuthProviderConfig {
auth_provider_type: other.auth_provider_type.clone(),
url: other.url.clone(),
params: other.params.clone(),
}
}
// TODO(dnordstrom): Add unit tests
|
// Copyright 2011 Google Inc. All Rights Reserved.
// Copyright 2017 The Ninja-rs Project Developers. All Rights Reserved.
//
// 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.
extern crate libc;
extern crate libc_stdhandle;
#[cfg(unix)]
extern crate libc_spawn;
extern crate errno;
#[macro_use]
extern crate cfg_if;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;
#[cfg(windows)]
extern crate widestring;
#[macro_use]
extern crate clap;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate nom;
extern crate num_cpus;
#[cfg(windows)]
#[macro_use]
extern crate wstr;
#[macro_use]
pub mod utils;
#[cfg(test)]
pub mod test;
pub mod exit_status;
pub mod build;
pub mod graph;
pub mod build_log;
pub mod deps_log;
pub mod timestamp;
pub mod debug_flags;
pub mod version;
pub mod lexer;
pub mod eval_env;
pub mod manifest_parser;
pub mod disk_interface;
#[macro_use]
pub mod metrics;
pub mod state;
pub mod subprocess;
pub mod line_printer;
|
use bytes::Bytes;
use serde::Serialize;
#[derive(Debug, PartialEq, Eq, ToPrimitive, Serialize)]
pub enum Error {
// DB Errors
LogDoesNotExist = 0x00,
ItrExistsWithSameName = 0x01,
ItrDoesNotExist = 0x02,
MsgNotValidCbor = 0x03,
ErrRunningLua = 0x04,
ErrReadingLuaResponse = 0x05,
// Protocol Errors
ConnectionClosed = 0x06,
UnknownRequestCode = 0x07,
UnknownFrameKind = 0x08,
FailedToReadBytes = 0x09,
ServerOnlyAcceptsRequests = 0x0A,
CouldNotReadPayload = 0x0B,
// Request Validations
LogNameNotUtf8 = 0x0C,
ItrNameNotUtf8 = 0x0D,
ItrTypeNotUtf8 = 0x0E,
ItrFuncNotUtf8 = 0x0F,
ItrTypeInvalid = 0x10,
MsgIdNotNumber = 0x11,
MsgFieldNotOfTypeBinary = 0x12,
}
impl Error {
pub fn to_bytes(&self) -> Vec<u8> {
serde_cbor::to_vec(self).unwrap()
}
}
impl From<Error> for Bytes {
fn from(e: Error) -> Self {
format!("{:?}", e).into()
}
}
|
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::RefCell;
use std::rc::Rc;
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
type Node = Rc<RefCell<TreeNode>>;
fn f(left: Option<&Node>, right: Option<&Node>) -> bool {
match (left, right) {
(None, None) => true,
(Some(l), Some(r)) => {
let left_node = l.borrow();
let right_node = r.borrow();
left_node.val == right_node.val
&& f(left_node.left.as_ref(), right_node.right.as_ref())
&& f(left_node.right.as_ref(), right_node.left.as_ref())
}
_ => false,
}
}
match root {
None => true,
Some(n) => {
let n = n.borrow();
f(n.left.as_ref(), n.right.as_ref())
}
}
}
|
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let mut lines = Vec::new();
let file = File::open("input").expect("Cannot read input");
for line in BufReader::new(file).lines() {
let line = line.expect("Unable to read line");
lines.push(line);
}
for line1 in &lines {
for line2 in &lines {
if distance(line1, line2) == 1 {
println!("{}, {}, {}", line1, line2, diff(line1, line2));
}
}
}
}
fn distance(line1: &String, line2: &String) -> i32 {
let mut dist = 0;
let mut line2 = line2.chars();
for c1 in line1.chars() {
let c2 = line2.next().unwrap(); // assumption: all box ids have equal length
if c1 != c2 { dist += 1; }
}
return dist;
}
fn diff(line1: &String, line2: &String) -> String {
let mut dff = "".to_owned();
let mut line2 = line2.chars();
for c1 in line1.chars() {
let c2 = line2.next().unwrap(); // assumption: all box ids have equal length
if c1 == c2 {
dff.push(c1);
}
}
return dff;
}
|
use std::fs;
use std::io::BufReader;
use serde::{Serialize, Deserialize};
use serde_json::{Result, Value};
use std::collections::HashMap;
extern crate serde;
const PATH: &str = "/home/kfriedt/code/rust-serde/";
#[derive(Serialize, Deserialize, Debug)]
struct RegisterMap {
device_type: String,
manufacturer: String,
model: String,
registers: Vec<Register>,
}
#[derive(Serialize, Deserialize, Debug)]
struct RegisterMap2 {
device_type: String,
manufacturer: String,
model: String,
registers: HashMap<String, RegisterDetails>,
}
#[derive(Serialize, Deserialize, Debug)]
struct Register {
address: String,
details: RegisterDetails,
}
#[derive(Serialize, Deserialize, Debug)]
struct RegisterDetails {
description: String,
exp: u16,
frequency: u16,
name: String,
size: u16,
data_type: String,
value: i32,
tags: Vec<String>,
writeable: bool,
}
fn untyped_example(data: &String) -> Result<()> {
let v: Value = serde_json::from_str(&data)?;
println!("Untyped example string from file");
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
Ok(())
}
fn untyped_str_example() -> Result<()> {
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
println!("Data: {}", data);
// Parse the string of data into serde_json::
let v: Value = serde_json::from_str(data)?;
println!("The value is v: {}", v);
// Access parts of the data by indexing with square brackets.
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
println!("The age of John:{}", v["age"]);
// get an int from the JSON code
let age= v["age"].as_i64().unwrap();
Ok(())
}
fn serialize_primitive(){
let x: i32 = 5;
let xs = serde_json::to_string(&x).unwrap();
println!("i32 number {} serializes into string {}", x, xs);
let xd: i32 = serde_json::from_str(&xs).unwrap();
assert_eq!(x, xd);
}
fn battery_to_string(filepath: &str){
// THIS WORKED WITH EITHER VERSION BELOW FO THE let reg_map BUT GOT A BUNCH OF OBJECTS
// COULDN'T ACCESS THE OBJECTS DIRECTLY
// With a string that is read from a file
let contents = fs::read_to_string(filepath).unwrap(); // could add .as_ref() to get &str
// println!("Contents: {}", contents);
// WITH THE ? HERE WE WOULD HAVE TO HAVE A RETURN TYPE Result<()>
// let reg_map: serde_json::Value = serde_json::from_str(&contents)?; //if .unwrap().as_ref() then contents
let v: serde_json::Value = serde_json::from_str(&contents).expect("JSON was not well formatted"); //if .unwrap().as_ref() then contents
println!("Device Type {}", v["device_type"]);
println!("registers {}", v["registers"]);
println!("first register {:?}", v["register"][0]); // returns null DOES NOT WORK
// Ok(()) // have to return () to use the ? operator in the serde_json::from_str(&contents)?
}
fn open_file_example(filepath: &str){
// WITH THE FORMATTED JSON FILE IT WORKS
let file = fs::File::open(filepath).expect("File should open read only");
// // WITH THE OLD JSON FILE IT WORKS BUT HARD TO ACCESS REGISTERS
// let filename_2 = "src/old-battery.json";
// let filepath_2: String = PATH.to_owned() + filename_2;
// let file = fs::File::open(filepath_2).expect("File should open read only");
let reader = BufReader::new(file);
let reg_map: serde_json::Value = serde_json::from_reader(reader)
.expect("Proper JSON");
println!("{:?}", reg_map);
let device_type = reg_map.get("device_type")
.expect("File should have device_type key");
println!("Device Type: {}", device_type);
let reg_1 = reg_map.get("registers")
.expect("File should have registers key");
println!("Registers: {}", reg_1);
println!("Register 1: {}", reg_1[0]);
println!("Register 1: {:?}", reg_1[0].get("details"));
}
fn battery_to_objects(filepath: &str){
// HAD TO RE-FORMAT THE JSON FILE TO GET THE OBJECT
// TRY GETTING OBJECTS
let contents = fs::read_to_string(filepath).unwrap(); // could add .as_ref() to get &str
let reg_map: RegisterMap = serde_json::from_str(&contents).expect("JSON was not well formatted"); //if .unwrap().as_ref() then contents
println!("{:?}", reg_map);
println!("Device Type: {:?}", reg_map.device_type);
println!("Registers: {:?}", reg_map.registers);
println!("First register address: {:?}", reg_map.registers[0].address);
}
fn battery_to_objects_2(filepath: &str){
// TRY GETTING OBJECTS with original file
let contents = fs::read_to_string(filepath).unwrap(); // could add .as_ref() to get &str
let reg_map: RegisterMap2 = serde_json::from_str(&contents).expect("JSON was not well formatted"); //if .unwrap().as_ref() then contents
println!("{:?}", reg_map);
println!("Device Type: {:?}", reg_map.device_type);
println!("Registers: {:?}", reg_map.registers);
println!("First register name: {:?}", reg_map.registers["310059"].name);
}
fn register_example() {
// let filename = "src/sungrow-battery.json";
// let filepath: String = PATH.to_owned() + filename; // could use .to_owned() or .to_string() NOT .clone()
let filename2 = "src/old-battery.json";
let filepath2: String = PATH.to_owned() + filename2;
// // example where a string from the json file is used
// battery_to_string(&filepath);
// // an example where the file is opened
// open_file_example(&filepath);
// // an example where the json file is transformed into a RegisterMap object
// battery_to_objects(&filepath);
// trying to use the original improper JSON file
battery_to_objects_2(&filepath2);
}
fn main() {
// let path_filename = "/home/kfriedt/code/rust-serde/src/example.json";
// // go over opening files in rust
//
// let contents = fs::read_to_string(path_filename); // Leaves this as a Result<>
// println!("With text:\n{:?}", contents.as_ref().unwrap()); // Have to unwrap the Result<>
// println!("Can use the path_filename again: {}", path_filename);
// // Need to convert the contents: Result<String> to a String?
// untyped_example(contents.as_ref().unwrap());
// untyped_str_example();
// serialize_primitive();
register_example();
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::pin::Pin;
use std::sync::Arc;
use common_exception::ErrorCode;
use futures_util::stream;
use storages_common_cache::LoadParams;
use storages_common_table_meta::meta::TableSnapshot;
use crate::io::TableMetaLocationGenerator;
use crate::io::TableSnapshotReader;
pub type TableSnapshotStream =
Pin<Box<dyn stream::Stream<Item = common_exception::Result<Arc<TableSnapshot>>> + Send>>;
pub trait SnapshotHistoryReader {
fn snapshot_history(
self,
location: String,
format_version: u64,
location_gen: TableMetaLocationGenerator,
) -> TableSnapshotStream;
}
impl SnapshotHistoryReader for TableSnapshotReader {
fn snapshot_history(
self,
location: String,
format_version: u64,
location_gen: TableMetaLocationGenerator,
) -> TableSnapshotStream {
let stream = stream::try_unfold(
(self, location_gen, Some((location, format_version))),
|(reader, gen, next)| async move {
if let Some((loc, ver)) = next {
let load_params = LoadParams {
location: loc,
len_hint: None,
ver,
put_cache: true,
};
let snapshot = match reader.read(&load_params).await {
Ok(s) => Ok(Some(s)),
Err(e) => {
if e.code() == ErrorCode::STORAGE_NOT_FOUND {
Ok(None)
} else {
Err(e)
}
}
};
match snapshot {
Ok(Some(snapshot)) => {
if let Some((id, v)) = snapshot.prev_snapshot_id {
let new_ver = v;
let new_loc = gen.snapshot_location_from_uuid(&id, v)?;
Ok(Some((snapshot, (reader, gen, Some((new_loc, new_ver))))))
} else {
Ok(Some((snapshot, (reader, gen, None))))
}
}
Ok(None) => Ok(None),
Err(e) => Err(e),
}
} else {
Ok(None)
}
},
);
Box::pin(stream)
}
}
|
use std::hash;
use crate::errors::RLPCodecError;
use rlp::{Prototype, Rlp, RlpStream};
use sha3::{Digest, Sha3_256};
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DataType<'a> {
Empty,
Pair(&'a [u8], &'a [u8]),
Values(&'a [Vec<u8>]),
Hash(&'a [u8]),
}
pub trait NodeCodec: Sized {
type Error: ::std::error::Error;
const HASH_LENGTH: usize;
type Hash: AsRef<[u8]>
+ AsMut<[u8]>
+ Default
+ PartialEq
+ Eq
+ hash::Hash
+ Send
+ Sync
+ Clone;
fn decode<F, T>(&self, data: &[u8], f: F) -> Result<T, Self::Error>
where
F: Fn(DataType) -> Result<T, Self::Error>;
fn encode_empty(&self) -> Vec<u8>;
fn encode_pair(&self, key: &[u8], value: &[u8]) -> Vec<u8>;
fn encode_values(&self, values: &[Vec<u8>]) -> Vec<u8>;
fn encode_raw(&self, raw: &[u8]) -> Vec<u8>;
fn decode_hash(&self, data: &[u8], is_hash: bool) -> Self::Hash;
}
#[derive(Default, Debug)]
pub struct RLPNodeCodec {}
impl NodeCodec for RLPNodeCodec {
type Error = RLPCodecError;
const HASH_LENGTH: usize = 32;
type Hash = [u8; 32];
fn decode<F, T>(&self, data: &[u8], f: F) -> Result<T, Self::Error>
where
F: Fn(DataType) -> Result<T, Self::Error>,
{
let r = Rlp::new(data);
match r.prototype()? {
Prototype::Data(0) => Ok(f(DataType::Empty)?),
Prototype::List(2) => {
let key = r.at(0)?.data()?;
let rlp_data = r.at(1)?;
// TODO: if “is_data == true”, the value of the leaf node
// This is not a good implementation
// the details of MPT should not be exposed to the user.
let value = if rlp_data.is_data() {
rlp_data.data()?
} else {
rlp_data.as_raw()
};
Ok(f(DataType::Pair(&key, &value))?)
}
Prototype::List(17) => {
let mut values = vec![];
for i in 0..16 {
values.push(r.at(i)?.as_raw().to_vec());
}
// The last element is a value node.
let value_rlp = r.at(16)?;
if value_rlp.is_empty() {
values.push(self.encode_empty());
} else {
values.push(value_rlp.data()?.to_vec());
}
Ok(f(DataType::Values(&values))?)
}
Prototype::Data(Self::HASH_LENGTH) => Ok(f(DataType::Hash(r.data()?))?),
_ => panic!("invalid data"),
}
}
fn encode_empty(&self) -> Vec<u8> {
let mut stream = RlpStream::new();
stream.append_empty_data();
stream.out()
}
fn encode_pair(&self, key: &[u8], value: &[u8]) -> Vec<u8> {
let mut stream = RlpStream::new_list(2);
stream.append_raw(key, 1);
stream.append_raw(value, 1);
stream.out()
}
fn encode_values(&self, values: &[Vec<u8>]) -> Vec<u8> {
let mut stream = RlpStream::new_list(values.len());
for data in values {
stream.append_raw(data, 1);
}
stream.out()
}
fn encode_raw(&self, raw: &[u8]) -> Vec<u8> {
let mut stream = RlpStream::new();
stream.append(&raw);
stream.out()
}
fn decode_hash(&self, data: &[u8], is_hash: bool) -> Self::Hash {
let mut out = [0u8; Self::HASH_LENGTH];
if is_hash {
out.copy_from_slice(data);
} else {
out.copy_from_slice(&Sha3_256::digest(data));
}
out
}
}
|
// I och med att jag är ny till språket har jag inte kommit in
// helt i diverse conventions och liknande. Därmed finns det olika
// lösningar på liknande problem genom koden som jag inte hunnit
// och/eller orkat ändra.
// main.rs
extern crate rand;
extern crate monopoly;
use std::io;
use std::io::prelude::*;
use rand::Rng;
use rand::distributions::{IndependentSample, Range};
use monopoly::gameboard::Board;
use monopoly::actor::Player;
fn main() {
let mut board = Board::new();
board.add_tile("START", 40, 0, 0, 0, 0);
board.add_tile("StiL", 0, 0, 6, 2, 0);
board.add_tile("CHANCE", 0, 0, 0, 0, 0);
board.add_tile("Philm", 0, 0, 6, 2, 0);
board.add_tile("PARTY", 0, 18, 0, 0, -8);
board.add_tile("A109", 0, 0, 10, 3, 3);
board.add_tile("A117", 0, 0, 10, 3, 3);
board.add_tile("LIBRARY", 0, 0, 0, 0, 8);
board.add_tile("B234Ske", 0, 0, 10, 3, 3);
board.add_tile("CHANCE", 0, 0, 0, 0, 0);
board.add_tile("E632", 0, 0, 10, 3, 3);
board.add_tile("EXAM", 0, 0, 0, 0, 0);
board.add_tile("A209", 0, 0, 20, 5, 4);
board.add_tile("A210", 0, 0, 20, 5, 4);
let mut players: Vec<String> = Vec::new();
{ // Add players
let mut i = 0;
while i < 4 {
let name = match prompt(format!("Player {}: ", i+1).as_ref()).as_ref() {
"" => { continue; },
n => if n.len() > 9 { continue; }
else if players.iter().any(|p| p == n) { continue; }
else { String::from(n) },
};
let comp = match prompt("Computer[y/n]: ").as_ref() {
"y" => true,
"n" => false,
_ => { continue; }
};
i+=1;
players.push(name.clone());
let p = Player{ name: name, money: 200, knowledge: 0, tiles: Vec::new(), skip_one_turn: false, still_playing: true, is_computer: comp };
board.add_player(p);
}
}
let mut round = 0;
loop {
board.print();
if board.playing(&players[round % 4]) {
if make_play(&mut board, &players[round % 4]) {
println!("{} took the exam and passed! Congratulations, you won!",
&players[round%4]);
break;
}
}
round += 1;
}
}
fn make_play(board: &mut Board, player: &str) -> bool {
// Remove player from current tile and calc new tile
let current_tile = board.pop_tile(player);
let steps = dice(6);
let new_tile = (current_tile + steps) % board.tile_amount();
let mut player_won = false;
// Place player on new tile and execute action
let result = board.place_player(player, new_tile);
match result.as_str() {
"chance" => board.draw_chance_card(player, dice(1)), // Change to dice(5) when all cards are implemented
"exam" => if board.exam(player) { player_won=true; },
"buy" => { board.print();
prompt_buy(player, new_tile, board); }
"start" => println!("New week, new studytime"),
"library" => println!("Studying like a maniac"),
"party" => println!("PHARTEEEY!"),
x => println!("{}", x),
}
if current_tile + steps >= board.tile_amount() {
board.passed_start(player)
}
board.check_status(player);
player_won
}
fn dice(size: usize) -> usize {
let mut rng = rand::thread_rng();
let between = Range::new(1usize, 1+size);
between.ind_sample(&mut rng)
}
fn prompt_buy(player: &str, tile: usize, board: &mut Board) -> String {
let t = board.get_tile_info(tile);
print_info();
if board.is_computer(player)
{ return prompt(board.buy(player, tile).as_str()); }
match prompt(format!("Do you want to buy {}, {}? Cost: {} [y/n]> ", t.name, player, t.buy).as_str()).as_str() {
"y" => prompt(board.buy(player, tile).as_str()),
"n" => String::new(),
_ => prompt_buy(player, tile, board),
}
}
fn prompt(msg: &str) -> String {
print!("{}", msg);
io::stdout().flush().ok().expect("Could not flush stdout");
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => String::from(input.trim()),
Err(error) => {
println!("error: {}", error);
String::from("ERROR")
}
}
}
fn print_info() {
println!("\
Currency: Study-time Time is money, start with 200\n\
Tiles:\n\
\tSTART: Collect 40\n\
\tStiL/Philm: Go to the gym/cinema [buy: 6, rent 2]\n\
\tCHANCE: Draw a CHANCE card\n\
\tPARTY: Have a huge party [pay: 18, Decrease knowledge by 8]\n\
\tA109/A117/B234Ske/E632: Attend a lecture [buy: 10, rent 3, Increase knowledge by 3]\n\
\tLIBRARY: Study [Increase knowledge by 8]\n\
\tEXAM: Win if knowledge >=200 / Skip one turn.\n\
\tA209/A210: Attend a workshop [buy: 20, rent 5, Increase knowledge by 4]\n\
Win by collecting 200 knowlede and go to the EXAM tile. Lose by running out of study-time
");
}
fn test() {
// Prompt
assert_eq!(prompt("Prompt test: "), "fisk");
// Dice
let d6 = dice(6);
let contains = (1..7)
.any(|n| n == d6);
assert!(contains);
}
|
mod loader;
mod project;
pub use loader::*;
pub use project::*;
|
pub mod core;
pub mod types;
pub mod helper; |
use std::io;
use std::time::Duration;
use crate::{Battery, State, Technology};
pub trait BatteryManager: Default + Sized {
fn refresh(&mut self, battery: &mut Battery) -> io::Result<()>;
}
pub trait BatteryIterator: Iterator<Item=Battery> + Sized {}
pub trait BatteryDevice: Sized {
fn capacity(&self) -> f32 {
let full = self.energy_full() as f32;
let full_design = self.energy_full_design() as f32;
(full / full_design) * 100.0
}
fn energy(&self) -> u32;
fn energy_full(&self) -> u32;
fn energy_full_design(&self) -> u32;
fn energy_rate(&self) -> u32;
fn percentage(&self) -> f32;
fn state(&self) -> State;
fn voltage(&self) -> u32;
fn temperature(&self) -> Option<f32>;
fn vendor(&self) -> Option<&str>;
fn model(&self) -> Option<&str>;
fn serial_number(&self) -> Option<&str>;
fn technology(&self) -> Technology;
fn cycle_count(&self) -> Option<u32>;
// Default implementation for `time_to_full` and `time_to_empty`
// uses calculation based on the current energy flow,
// but if device provides by itself provides these **instant** values (do not use average values),
// it would be easier and cheaper to return them instead of making some calculations
fn time_to_full(&self) -> Option<Duration> {
let energy_rate = self.energy_rate();
match self.state() {
// In some cases energy_rate can be 0 while Charging, for example just after
// plugging in the charger. Assume that the battery doesn't have time_to_full in such
// cases, to avoid divison by zero. See https://github.com/svartalf/rust-battery/pull/5
State::Charging if energy_rate != 0 => {
// Some drivers might report that `energy_full` is lower than `energy`,
// but battery is still charging. What should we do in that case?
// As for now, assuming that battery is fully charged, since we can't guess,
// how much time left.
let energy_left = match self.energy_full().checked_sub(self.energy()) {
Some(value) => value,
None => return None,
};
let time_to_full = 3600 * energy_left / energy_rate;
if time_to_full > (20 * 60 * 60) {
None
} else {
Some(Duration::from_secs(u64::from(time_to_full)))
}
},
_ => None,
}
}
fn time_to_empty(&self) -> Option<Duration> {
let energy_rate = self.energy_rate();
match self.state() {
// In some cases energy_rate can be 0 while Discharging, for example just after
// unplugging the charger. Assume that the battery doesn't have time_to_empty in such
// cases, to avoid divison by zero. See https://github.com/svartalf/rust-battery/pull/5
State::Discharging if energy_rate != 0 => {
let time_to_empty = 3600 * self.energy() / energy_rate;
if time_to_empty > (240 * 60 * 60) { // Ten days for discharging
None
} else {
Some(Duration::from_secs(u64::from(time_to_empty)))
}
},
_ => None,
}
}
}
|
use std::error::Error;
use mio::{self, EventLoop, Token, EventSet, Sender};
use mio::util::Slab;
use scope::scope;
use {SpawnError, Scope, Response, Machine};
use SpawnError::{NoSlabSpace, UserError};
pub enum Timeo {
Fsm(Token),
}
pub enum Notify {
Fsm(Token),
}
/// Standard mio loop handler
///
///
/// # Examples
///
/// ```ignore
/// extern crate mio;
/// extern crate rotor;
///
/// let mut event_loop = mio::EventLoop::new().unwrap();
/// let mut handler = rotor::Handler::new(Context, &mut event_loop);
/// let conn = handler.add_machine_with(&mut event_loop, |scope| {
/// Ok(StateMachineConstuctor(..))
/// });
/// assert!(conn.is_ok());
/// event_loop.run(&mut handler).unwrap();
/// ```
pub struct Handler<Ctx, M>
where M: Machine<Context=Ctx>
{
slab: Slab<M>,
context: Ctx,
channel: Sender<Notify>,
}
impl<C, M> Handler<C, M>
where M: Machine<Context=C>,
{
pub fn new_with_capacity(context: C, eloop: &mut EventLoop<Handler<C, M>>,
capacity: usize)
-> Handler<C, M>
{
Handler {
slab: Slab::new(capacity),
context: context,
channel: eloop.channel(),
}
}
pub fn new(context: C, eloop: &mut EventLoop<Handler<C, M>>)
-> Handler<C, M>
{
// TODO(tailhook) create default config from the ulimit data instead
// of using real defaults
Handler {
slab: Slab::new(4096),
context: context,
channel: eloop.channel(),
}
}
}
pub fn create_handler<C, M>(slab: Slab<M>, context: C, channel: Sender<Notify>)
-> Handler<C, M>
where M: Machine<Context=C>
{
Handler {
slab: slab,
context: context,
channel: channel,
}
}
impl<C, M> Handler<C, M>
where M: Machine<Context=C>
{
pub fn add_machine_with<F>(&mut self,
eloop: &mut EventLoop<Self>, fun: F) -> Result<(), SpawnError<()>>
where F: FnOnce(&mut Scope<C>) -> Result<M, Box<Error>>
{
let ref mut ctx = self.context;
let ref mut chan = self.channel;
let res = self.slab.insert_with(|token| {
let ref mut scope = scope(token, ctx, chan, eloop);
match fun(scope) {
Ok(x) => x,
Err(_) => {
// TODO(tailhook) when Slab::insert_with_opt() lands, fix it
panic!("Unimplemented: Slab::insert_with_opt");
}
}
});
if res.is_some() {
Ok(())
} else {
Err(NoSlabSpace(()))
}
}
}
fn machine_loop<C, M, F>(handler: &mut Handler<C, M>,
eloop: &mut EventLoop<Handler<C, M>>, token: Token, fun: F)
where M: Machine<Context=C>,
F: FnOnce(M, &mut Scope<C>) -> Response<M, M::Seed>
{
let mut creator = None;
{
let ref mut scope = scope(token, &mut handler.context,
&mut handler.channel, eloop);
handler.slab.replace_with(token, |m| {
let res = fun(m, scope);
creator = res.1;
res.0
}).ok(); // Spurious events are ok in mio
}
while let Some(new) = creator.take() {
let mut new = Some(new);
let res = handler.add_machine_with(eloop, |scope| {
M::create(new.take().unwrap(), scope)
});
if let Err(err) = res {
let err = if let Some(new) = new.take() {
NoSlabSpace(new)
} else if let UserError(e) = err {
UserError(e)
} else {
unreachable!();
};
let ref mut scope = scope(token, &mut handler.context,
&mut handler.channel, eloop);
handler.slab.replace_with(token, |m| {
m.spawn_error(scope, err)
}).ok();
break;
} else {
let ref mut scope = scope(token, &mut handler.context,
&mut handler.channel, eloop);
handler.slab.replace_with(token, |m| {
let res = m.spawned(scope);
creator = res.1;
res.0
}).ok();
}
}
}
impl<Ctx, M> mio::Handler for Handler<Ctx, M>
where M: Machine<Context=Ctx>
{
type Message = Notify;
type Timeout = Timeo;
fn ready<'x>(&mut self, eloop: &'x mut EventLoop<Self>,
token: Token, events: EventSet)
{
machine_loop(self, eloop, token, |m, scope| { m.ready(events, scope) })
}
fn notify(&mut self, eloop: &mut EventLoop<Self>, msg: Notify) {
match msg {
Notify::Fsm(token) => {
machine_loop(self, eloop, token,
|m, scope| { m.wakeup(scope) })
}
}
}
fn timeout(&mut self, eloop: &mut EventLoop<Self>, timeo: Timeo) {
match timeo {
Timeo::Fsm(token) => {
machine_loop(self, eloop, token,
|m, scope| { m.timeout(scope) })
}
}
}
}
|
use std::{result, io};
use opus;
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
File(io::Error),
CorruptedFile,
Opus(opus::Error),
InvalidSize,
InvalidRange,
NotSupported,
SendFailed,
ReachedEnd
}
|
use aoc_runner_derive::{aoc, aoc_generator};
use std::collections::{HashMap, HashSet};
#[aoc_generator(day6)]
fn input_parse(inp: &str) -> Vec<Vec<Vec<char>>> {
let mut result = Vec::new();
let mut curr = Vec::new();
for line in inp.lines() {
if line == "" {
result.push(curr);
curr = Vec::new();
} else {
curr.push(line.clone().chars().collect());
}
}
result.push(curr);
result
}
#[aoc(day6, part1)]
fn solve_part1(groups: &Vec<Vec<Vec<char>>>) -> usize {
groups
.iter()
.map(|group| {
let mut set = HashSet::<char>::new();
for line in group {
for c in line.iter() {
set.insert(*c);
}
}
set.len()
})
.sum()
}
#[aoc(day6, part2)]
fn solve_part2(groups: &Vec<Vec<Vec<char>>>) -> usize {
groups
.iter()
.map(|group| {
let mut map = HashMap::<char, usize>::new();
for line in group.iter() {
for c in line.iter() {
let v = map.entry(*c).or_insert(0);
*v += 1;
}
}
map.values().filter(|v| **v == group.len()).count()
})
.sum()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_part1() {
let group = "abc
a
b
c
ab
ac
a
a
a
a
b";
assert_eq!(solve_part1(&input_parse(group)), 11);
}
#[test]
fn test_part2() {
let group = "abc
a
b
c
ab
ac
a
a
a
a
b";
assert_eq!(solve_part2(&input_parse(group)), 6);
}
}
|
/*
* @lc app=leetcode.cn id=7 lang=rust
*
* [7] 整数反转
*
* https://leetcode-cn.com/problems/reverse-integer/description/
*
* algorithms
* Easy (33.26%)
* Likes: 1553
* Dislikes: 0
* Total Accepted: 244K
* Total Submissions: 731.8K
* Testcase Example: '123'
*
* 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
*
* 示例 1:
*
* 输入: 123
* 输出: 321
*
*
* 示例 2:
*
* 输入: -123
* 输出: -321
*
*
* 示例 3:
*
* 输入: 120
* 输出: 21
*
*
* 注意:
*
* 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回
* 0。
*
*/
// @lc code=start
impl Solution {
pub fn reverse(x: i32) -> i32 {
x.signum()
* x.abs()
.to_string()
.chars()
.rev()
.collect::<String>()
.parse::<i32>()
.unwrap_or(0)
// pub fn check_overflow(x: i32) -> bool {
// let max_vec: Vec<u8> = (std::i32::MAX - 1).to_string().into();
// let max_list: Vec<char> = max_vec.into_iter().map(char::from).collect();
// let x_utf: Vec<u8> = x.to_string().into();
// let mut number_list: Vec<char> = x_utf.into_iter().map(char::from).collect();
// if number_list[0] == '-' {
// number_list.remove(0);
// }
// if max_list.len() < number_list.len() {
// return true;
// } else if max_list.len() == number_list.len() {
// for (i, digit_char) in number_list.iter().enumerate() {
// if digit_char.to_digit(10).unwrap() > max_list[i].to_digit(10).unwrap() {
// return true;
// }
// }
// }
// return false;
// }
// if x == 1463847412 {
// return 2147483641;
// } else if x == -1463847412 {
// return -2147483641;
// } else if x == 2147483641 {
// return 1463847412;
// } else if x == -2147483641 {
// return -1463847412;
// } else if x == 0 {
// return x;
// }
// if check_overflow(x) {
// return 0;
// }
// let x_utf: Vec<u8> = x.to_string().into();
// let mut number_list: Vec<char> = x_utf.into_iter().map(char::from).collect();
// let mut result = Vec::new();
// if number_list[0] == '-' {
// result.push('-');
// number_list.remove(0);
// }
// number_list.reverse();
// let mut flag = false;
// for digit in number_list {
// if digit != '0' {
// flag = true;
// }
// if flag {
// result.push(digit);
// }
// }
// let string: String = result.into_iter().collect();
// let num: i32 = string.parse::<i32>().unwrap();
// return num;
}
}
// @lc code=end
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unions_with_drop_fields)]
#![feature(untagged_unions)]
union MaybeItem<T: Iterator> {
elem: T::Item,
none: (),
}
union U<A, B> {
a: A,
b: B,
}
unsafe fn union_transmute<A, B>(a: A) -> B {
U { a: a }.b
}
fn main() {
unsafe {
let u = U::<String, Vec<u8>> { a: String::from("abcd") };
assert_eq!(u.b.len(), 4);
assert_eq!(u.b[0], b'a');
let b = union_transmute::<(u8, u8), u16>((1, 1));
assert_eq!(b, (1 << 8) + 1);
let v: Vec<u8> = vec![1, 2, 3];
let mut i = v.iter();
i.next();
let mi = MaybeItem::<std::slice::Iter<_>> { elem: i.next().unwrap() };
assert_eq!(*mi.elem, 2);
}
}
|
/* rusterver - a basic memory safe multithreaded webserver
* While it is memory safe, it is completely unsecure, so beware
* of actually using it as a web server.
*/
use std::net::{TcpStream, TcpListener, SocketAddrV4, Ipv4Addr};
use std::io::{BufReader, BufRead, BufWriter, Write};
use std::str;
use std::string::String;
use std::thread;
mod http;
use http::request::HttpRequest;
use http::response::HttpResponse;
fn do_response(stream: &TcpStream) {
let http_request: HttpRequest = parse_request(stream);
println!("method: {}, path: {}, version: {}", http_request.get_method(), http_request.get_path(), http_request.get_version());
send_response(stream);
}
fn parse_request(stream: &TcpStream) -> HttpRequest {
let mut reader = BufReader::new(stream);
let mut request_string = String::new();
HttpRequest::new(&mut reader.lines())
}
fn send_response(stream: &TcpStream) {
// send response
let mut writer = BufWriter::new(stream);
let mut response = HttpResponse::new("200", "OK");
let mut buf = Vec::new();
let byte_response: &[u8] = response.get_byte_response(&mut buf);
writer.write(byte_response).unwrap();
}
fn main() {
let port = 8080;
let ip_addr = Ipv4Addr::new(127, 0, 0, 1);
let socket_addr = SocketAddrV4::new(ip_addr, port);
let listener = TcpListener::bind(socket_addr).unwrap();
println!("Server opened on port {}", socket_addr);
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
do_response(&stream)
});
},
Err(e) => println!("{}", e),
}
}
drop(listener);
}
|
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::MICR {
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_ICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_ICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_CLKICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_CLKICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_DMARXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_DMARXICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_DMATXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_DMATXICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_NACKICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_NACKICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_STARTICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_STARTICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_STOPICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_STOPICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_ARBLOSTICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_ARBLOSTICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_TXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_TXICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 8);
self.w.bits |= ((value as u32) & 1) << 8;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_RXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_RXICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 9);
self.w.bits |= ((value as u32) & 1) << 9;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_TXFEICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_TXFEICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 10);
self.w.bits |= ((value as u32) & 1) << 10;
self.w
}
}
#[doc = r"Proxy"]
pub struct _I2C_MICR_RXFFICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_MICR_RXFFICW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 11);
self.w.bits |= ((value as u32) & 1) << 11;
self.w
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Master Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_ic(&mut self) -> _I2C_MICR_ICW {
_I2C_MICR_ICW { w: self }
}
#[doc = "Bit 1 - Clock Timeout Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_clkic(&mut self) -> _I2C_MICR_CLKICW {
_I2C_MICR_CLKICW { w: self }
}
#[doc = "Bit 2 - Receive DMA Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_dmarxic(&mut self) -> _I2C_MICR_DMARXICW {
_I2C_MICR_DMARXICW { w: self }
}
#[doc = "Bit 3 - Transmit DMA Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_dmatxic(&mut self) -> _I2C_MICR_DMATXICW {
_I2C_MICR_DMATXICW { w: self }
}
#[doc = "Bit 4 - Address/Data NACK Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_nackic(&mut self) -> _I2C_MICR_NACKICW {
_I2C_MICR_NACKICW { w: self }
}
#[doc = "Bit 5 - START Detection Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_startic(&mut self) -> _I2C_MICR_STARTICW {
_I2C_MICR_STARTICW { w: self }
}
#[doc = "Bit 6 - STOP Detection Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_stopic(&mut self) -> _I2C_MICR_STOPICW {
_I2C_MICR_STOPICW { w: self }
}
#[doc = "Bit 7 - Arbitration Lost Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_arblostic(&mut self) -> _I2C_MICR_ARBLOSTICW {
_I2C_MICR_ARBLOSTICW { w: self }
}
#[doc = "Bit 8 - Transmit FIFO Request Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_txic(&mut self) -> _I2C_MICR_TXICW {
_I2C_MICR_TXICW { w: self }
}
#[doc = "Bit 9 - Receive FIFO Request Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_rxic(&mut self) -> _I2C_MICR_RXICW {
_I2C_MICR_RXICW { w: self }
}
#[doc = "Bit 10 - Transmit FIFO Empty Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_txfeic(&mut self) -> _I2C_MICR_TXFEICW {
_I2C_MICR_TXFEICW { w: self }
}
#[doc = "Bit 11 - Receive FIFO Full Interrupt Clear"]
#[inline(always)]
pub fn i2c_micr_rxffic(&mut self) -> _I2C_MICR_RXFFICW {
_I2C_MICR_RXFFICW { w: self }
}
}
|
pub use futures::{Future, Stream, Sink, Async, AsyncSink, future, stream};
pub use future_utils::{FutureExt, StreamExt, BoxFuture, BoxStream};
pub use tokio_core::reactor::{Core, Handle};
pub use tokio_core::net::{TcpStream, UdpSocket};
pub use tokio_io::{AsyncRead, AsyncWrite};
pub use futures::prelude::*;
pub use std::time::{Duration, Instant};
pub use std::iter;
|
use chess::{ChessMove, Square};
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
pub fn read_chess_move(move_as_str: &str) -> ChessMove {
let parts: Vec<_> = move_as_str.split("-").collect();
ChessMove::new(
Square::from_string(parts[0].to_string()).unwrap(),
Square::from_string(parts[1].to_string()).unwrap(),
None,
)
}
#[cfg(test)]
mod tests {
use chess::{ChessMove, Square};
use super::read_chess_move;
#[test]
fn read_chess_move_success() {
assert_eq!(
ChessMove::new(Square::A1, Square::E7, None),
read_chess_move("a1-e7")
);
}
#[test]
#[should_panic]
fn read_chess_move_failure() {
read_chess_move("a1e7");
}
}
|
pub trait WasmSafe {}
macro_rules! impl_wasmsafe {
[$($t:ty),*] => {
$(impl WasmSafe for $t {})
}
}
impl_wasmsafe![u8, i8, u16, i16, u32, i32, u64, i64, f32, f64];
impl<T> WasmSafe for *const T {}
impl<T> WasmSafe for *mut T {}
impl<T> WasmSafe for Option<*const T> {}
impl<T> WasmSafe for Option<*mut T> {}
|
#[allow(unused_imports)]
use proconio::{
input, fastout
};
fn solve(n: usize, dice: Vec<Vec<i32>>) -> String {
for i in 0..(n - 2) {
if (dice[i][0] == dice[i][1]) &&
(dice[i + 1][0] == dice[i + 1][1]) && (dice[i + 2][0] == dice[i + 2][1]) {
return "Yes".to_string();
}
}
return "No".to_string();
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
input! {
n: usize,
dice: [[i32; 2]; n],
}
println!("{}", solve(n, dice));
Ok(())
}
fn main() {
match run() {
Err(err) => panic!("{}", err),
_ => (),
};
}
|
use crate::domain::{
catalog::{
brands::Brand,
catalog_items::{CatalogItem, DeliveryDate, ItemNumber, PowerMethod},
rolling_stocks::RollingStock,
scales::Scale,
},
collecting::{
wish_lists::{PriceInfo, Priority, WishList, WishListItem},
Price,
},
};
use super::yaml_rolling_stocks::YamlRollingStock;
#[derive(Debug, Deserialize)]
pub struct YamlWishList {
pub name: String,
#[serde(rename = "modifiedAt")]
pub modified_at: String,
pub version: u8,
pub elements: Vec<YamlWishListItem>,
}
#[derive(Debug, Deserialize)]
pub struct YamlWishListItem {
pub brand: String,
#[serde(rename = "itemNumber")]
pub item_number: String,
pub description: String,
#[serde(rename = "powerMethod")]
pub power_method: String,
pub scale: String,
#[serde(rename = "deliveryDate")]
pub delivery_date: Option<String>,
pub count: u8,
pub priority: Option<String>,
#[serde(rename = "rollingStocks")]
pub rolling_stocks: Vec<YamlRollingStock>,
#[serde(default = "Vec::new")]
pub prices: Vec<YamlPrice>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct YamlPrice {
pub shop: String,
pub price: String,
}
impl YamlWishList {
pub fn to_wish_list(self) -> anyhow::Result<WishList> {
let mut wish_list = WishList::new(&self.name, self.version);
for item in self.elements {
let mut prices: Vec<PriceInfo> = Vec::new();
for p in item.prices.iter() {
let price = p.price.parse::<Price>().unwrap();
let pi = PriceInfo::new(&p.shop, price);
prices.push(pi);
}
let priority = if let Some(p) = item.priority.clone() {
p.parse::<Priority>()?
} else {
Default::default()
};
let catalog_item = Self::parse_catalog_item(item)?;
wish_list.add_item(catalog_item, priority, prices);
}
Ok(wish_list)
}
fn parse_catalog_item(
elem: YamlWishListItem,
) -> anyhow::Result<CatalogItem> {
let mut rolling_stocks: Vec<RollingStock> = Vec::new();
for rs in elem.rolling_stocks {
let rolling_stock = rs.to_rolling_stock()?;
rolling_stocks.push(rolling_stock);
}
let mut delivery_date = None;
if let Some(dd) = elem.delivery_date {
delivery_date = Some(dd.parse::<DeliveryDate>()?);
}
let catalog_item = CatalogItem::new(
Brand::new(&elem.brand),
ItemNumber::new(&elem.item_number).expect("Invalid item number"),
elem.description,
rolling_stocks,
elem.power_method
.parse::<PowerMethod>()
.expect("Invalid power method"),
Scale::from_name(&elem.scale).unwrap(),
delivery_date,
elem.count,
);
Ok(catalog_item)
}
}
|
#![allow(unused_variables)]
#![allow(unused_imports)]
extern crate test;
use std::env;
use std::io;
fn main()
{
let args: env::Args = env::args();
test::test();
}
|
#![allow(dead_code)]
use super::*;
use rusty_peg::{Error, Symbol, Input, ParseResult};
rusty_peg! {
parser Parser<'input> {
MATCHER: Matcher = (
MATCHER_COMMA_MATCHER /
MATCHER_NOT_THEN_MATCHER /
MATCHER_THEN_NOT_MATCHER /
MATCHER_SKIP_MATCHER /
MATCHER0
);
MATCHER_COMMA_MATCHER: Matcher =
(<lhs:MATCHER0>, ",", <rhs:MATCHER>) => {
ThenMatcher::new(lhs, rhs)
};
MATCHER_THEN_NOT_MATCHER: Matcher =
(<lhs:MATCHER0>, "..", "!", <rhs:MATCHER0>) => {
ThenMatcher::new(lhs, NotMatcher::new(SkipMatcher::new(rhs)))
};
MATCHER_SKIP_MATCHER: Matcher =
(<lhs:MATCHER0>, "..", <rhs:MATCHER>) => {
ThenMatcher::new(lhs, SkipMatcher::new(rhs))
};
MATCHER_NOT_THEN_MATCHER: Matcher =
("!", <lhs:MATCHER0>, "..", <rhs:MATCHER0>) => {
SkipMatcher::with_condition(rhs, NotMatcher::new(lhs))
};
MATCHER1: Matcher =
(MATCHER_OR / MATCHER0);
MATCHER_OR: Matcher =
(<lhs:MATCHER0>, "/", <rhs:MATCHER1>) => OrMatcher::new(lhs, rhs);
MATCHER0: Matcher =
(MATCHER_RE / MATCHER_SKIP / MATCHER_PAREN / MATCHER_ANY);
MATCHER_SKIP: Matcher =
("..", <rhs:MATCHER0>) => SkipMatcher::new(rhs);
MATCHER_PAREN: Matcher =
("(", <rhs:MATCHER>, ")") => ParenMatcher::new(rhs);
MATCHER_ANY: Matcher =
(".") => WildcardMatcher::new();
}
}
#[allow(non_camel_case_types)]
pub struct MATCHER_RE;
impl<'input> Symbol<'input, Parser<'input>> for MATCHER_RE {
type Output = Matcher;
fn pretty_print(&self) -> String {
format!("MATCHER_RE")
}
fn parse(&self, _: &mut Parser<'input>, input: Input<'input>)
-> ParseResult<'input,Matcher>
{
let bytes = input.text.as_bytes();
let mut offset = input.offset;
if offset >= input.text.len() || bytes[offset] != ('{' as u8) {
return Err(Error { expected: "'{' character",
offset: input.offset });
}
let mut balance = 1;
while balance != 0 {
offset += 1;
if offset >= input.text.len() {
return Err(Error { expected: "matching '}' character",
offset: offset });
}
if bytes[offset] == ('{' as u8) {
balance += 1;
} else if bytes[offset] == ('}' as u8) {
balance -= 1;
} else if bytes[offset] == ('\\' as u8) {
offset += 1; // skip next character
}
}
offset += 1; // consume final `}`
let regex_str = &input.text[input.offset + 1 .. offset - 1];
let regex: Matcher = RegexMatcher::new(regex_str);
let output = Input { text: input.text, offset: offset };
return Ok((output, regex));
}
}
|
#[doc = "Reader of register CACR"]
pub type R = crate::R<u32, super::CACR>;
#[doc = "Writer for register CACR"]
pub type W = crate::W<u32, super::CACR>;
#[doc = "Register CACR `reset()`'s with value 0"]
impl crate::ResetValue for super::CACR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SIWT`"]
pub type SIWT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SIWT`"]
pub struct SIWT_W<'a> {
w: &'a mut W,
}
impl<'a> SIWT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `ECCEN`"]
pub type ECCEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ECCEN`"]
pub struct ECCEN_W<'a> {
w: &'a mut W,
}
impl<'a> ECCEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `FORCEWT`"]
pub type FORCEWT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FORCEWT`"]
pub struct FORCEWT_W<'a> {
w: &'a mut W,
}
impl<'a> FORCEWT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
impl R {
#[doc = "Bit 0 - SIWT"]
#[inline(always)]
pub fn siwt(&self) -> SIWT_R {
SIWT_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - ECCEN"]
#[inline(always)]
pub fn eccen(&self) -> ECCEN_R {
ECCEN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - FORCEWT"]
#[inline(always)]
pub fn forcewt(&self) -> FORCEWT_R {
FORCEWT_R::new(((self.bits >> 2) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - SIWT"]
#[inline(always)]
pub fn siwt(&mut self) -> SIWT_W {
SIWT_W { w: self }
}
#[doc = "Bit 1 - ECCEN"]
#[inline(always)]
pub fn eccen(&mut self) -> ECCEN_W {
ECCEN_W { w: self }
}
#[doc = "Bit 2 - FORCEWT"]
#[inline(always)]
pub fn forcewt(&mut self) -> FORCEWT_W {
FORCEWT_W { w: self }
}
}
|
use std::collections::HashMap;
fn main() {
// p s
// [1, 2, 4, 4, 5, 6, 7, 3, 2, 7, 8, 9, 1]
// [4, 5, 6, 7] -> len 4
// [7, 8, 9] -> len = 3
// jawaban = [4, 5, 6, 7]
let s = [1, 2, 4, 4, 5, 6, 7, 3, 2, 7, 8, 9, 1];
longest_incrementing_subslice(&s);
}
pub fn longest_incrementing_subslice(s: &[u8]) { //-> &[u8] {
let mut p = s[0];
let mut stack = Vec::new();
let mut map = HashMap::new();
let mut i = 0;
for x in 1..s.len() {
if s[x] > p {
stack.push(s[x]);
} else if s[x] == p || s[x] < p {
map.insert(i, stack);
i = i + 1;
stack.clear();
}
}
println!("{:#?}", map);
}
/*
s = [1, 2, 4, 4, 5, 6, 7, 3, 2, 7, 8, 9, 1]
p = 1
stack = [];
for i = 1; i < s.len(); i++ {
s[i] = 3, p = 7
if s[i] > p {
stack.push(s[i]);
p = s[i];
} else if s[i] == p {
stack.clear();
} else if (p > s[i])
}
*/ |
#[doc = "Reader of register JPEG_SR"]
pub type R = crate::R<u32, super::JPEG_SR>;
#[doc = "Reader of field `IFTF`"]
pub type IFTF_R = crate::R<bool, bool>;
#[doc = "Reader of field `IFNFF`"]
pub type IFNFF_R = crate::R<bool, bool>;
#[doc = "Reader of field `OFTF`"]
pub type OFTF_R = crate::R<bool, bool>;
#[doc = "Reader of field `OFNEF`"]
pub type OFNEF_R = crate::R<bool, bool>;
#[doc = "Reader of field `EOCF`"]
pub type EOCF_R = crate::R<bool, bool>;
#[doc = "Reader of field `HPDF`"]
pub type HPDF_R = crate::R<bool, bool>;
#[doc = "Reader of field `COF`"]
pub type COF_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 1 - Input FIFO Threshold Flag"]
#[inline(always)]
pub fn iftf(&self) -> IFTF_R {
IFTF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Input FIFO Not Full Flag"]
#[inline(always)]
pub fn ifnff(&self) -> IFNFF_R {
IFNFF_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Output FIFO Threshold Flag"]
#[inline(always)]
pub fn oftf(&self) -> OFTF_R {
OFTF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Output FIFO Not Empty Flag"]
#[inline(always)]
pub fn ofnef(&self) -> OFNEF_R {
OFNEF_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - End of Conversion Flag"]
#[inline(always)]
pub fn eocf(&self) -> EOCF_R {
EOCF_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Header Parsing Done Flag"]
#[inline(always)]
pub fn hpdf(&self) -> HPDF_R {
HPDF_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Codec Operation Flag"]
#[inline(always)]
pub fn cof(&self) -> COF_R {
COF_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
|
/*
Boxes allow you to store data on the heap rather than the stack. What remains
on the stack is the pointer to the heap data.
Boxes don’t have performance overhead, other than storing their data on the
heap instead of on the stack. But they don’t have many extra capabilities
either. You’ll use them most often in these situations:
1) When you have a type whose size can’t be known at compile time and you want
to use a value of that type in a context that requires an exact size.
2) When you have a large amount of data and you want to transfer ownership but
ensure the data won’t be copied when you do so.
3) When you want to own a value and you care only that it’s a type that
implements a particular trait rather than being of a specific type.
*/
// Compilation of this fails with the error: recursive type `List` has
// infinite size.
// enum List {
// Cons(i32, List),
// Nil,
// }
// To get rid of the error, change the data structure to store the value
// indirectly by storing a pointer to the value instead.
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
box_syntax();
recursive_types();
}
/*
Just like any owned value, when a box goes out of scope, as b does at the end
of main, it will be deallocated.
Putting a single value on the heap isn’t very useful, so you won’t use boxes by
themselves in this way very often. Having values like a single i32 on the stack,
where they’re stored by default, is more appropriate in the majority of
situations.
*/
fn box_syntax() {
let b = Box::new(5);
println!("In box_syntax, b = {}", b);
}
/*
At compile time, Rust needs to know how much space a type takes up. One type
whose size can’t be known at compile time is a recursive type, where a value
can have as part of itself another value of the same type. Because this nesting
of values could theoretically continue infinitely, Rust doesn’t know how much
space a value of a recursive type needs. However, boxes have a known size, so by
inserting a box in a recursive type definition, you can have recursive types.
Most of the time when you have a list of items in Rust, Vec<T> is a better
choice to use. Other, more complex recursive data types are useful in various
situations, but by starting with the cons list, we can explore how boxes let us
define a recursive data type without much distraction.
*/
fn recursive_types() {
// Compilation of this fails with the error: recursive type `List` has
// infinite size (See definition of List above).
// let list = Cons(1, Cons(2, Cons(3, Nil)));
// To get rid of the error, change the data structure to store the value
// indirectly by storing a pointer to the value instead.
let list = Cons(1,
Box::new(Cons(2,
Box::new(Cons(3,
Box::new(Nil))))));
println!("In recursive_types, list is {:?}", list);
} |
pub struct Solution;
impl Solution {
pub fn valid_utf8(data: Vec<i32>) -> bool {
fn is_1_byte_char(b: i32) -> bool {
b & 0b10000000 == 0
}
fn is_first_of_2(b: i32) -> bool {
b & 0b11100000 == 0b11000000
}
fn is_first_of_3(b: i32) -> bool {
b & 0b11110000 == 0b11100000
}
fn is_first_of_4(b: i32) -> bool {
b & 0b11111000 == 0b11110000
}
fn is_follower(b: i32) -> bool {
b & 0b11000000 == 0b10000000
}
let mut data = data.into_iter();
while let Some(b) = data.next() {
if is_1_byte_char(b) {
// ok
} else if is_first_of_2(b) {
if !data.next().map_or(false, is_follower) {
return false;
}
} else if is_first_of_3(b) {
for _ in 0..2 {
if !data.next().map_or(false, is_follower) {
return false;
}
}
} else if is_first_of_4(b) {
for _ in 0..3 {
if !data.next().map_or(false, is_follower) {
return false;
}
}
} else {
return false;
}
}
return true;
}
}
#[test]
fn test0393() {
fn case(data: Vec<i32>, want: bool) {
let got = Solution::valid_utf8(data);
assert_eq!(got, want);
}
case(vec![197, 130, 1], true);
case(vec![235, 140, 4], false);
}
|
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use say_number::english::say;
fn say_0(c: &mut Criterion) {
c.bench_function("say 0", |b| b.iter(|| say(black_box(0))));
}
fn say_42(c: &mut Criterion) {
c.bench_function("say 42", |b| b.iter(|| say(black_box(42))));
}
fn say_514(c: &mut Criterion) {
c.bench_function("say 514", |b| b.iter(|| say(black_box(514))));
}
fn say_max_u64(c: &mut Criterion) {
c.bench_function("say max u64", |b| b.iter(|| say(black_box(std::u64::MAX))));
}
criterion_group!(english, say_max_u64, say_514, say_42, say_0);
criterion_main!(english);
|
pub mod human_vs_ai;
pub mod ai_vs_ai;
pub mod utils; |
pub mod button;
pub mod common;
pub mod dropdown;
pub mod gui_component;
pub mod gui_handler;
pub mod gui_theme;
pub mod label;
pub mod prelude;
pub mod slider;
pub mod traits;
pub mod types;
|
use std::io::Read;
fn main() {
let mut buf = String::new();
// 標準入力から全部bufに読み込む
std::io::stdin().read_to_string(&mut buf).unwrap();
// 行ごとのiterが取れる
let mut iter = buf.split_whitespace();
let a: i32 = iter.next().unwrap().parse().unwrap();
let b: i32 = iter.next().unwrap().parse().unwrap();
let c: i32 = iter.next().unwrap().parse().unwrap();
let d: i32 = iter.next().unwrap().parse().unwrap();
let start = if a < c { c } else { a };
let end = if b < d { b } else { d };
println!("{}", if end - start < 0 { 0 } else { end - start });
}
|
#![feature(drain_filter)]
//! This crate works with [`flapigen`] to provide an easy to use rust code with other programming languages
//!
//! [`flapigen`]: https://docs.rs/flapigen
//!
//! This crate uses procedural macros such as `#generate_interface` to locate methods and types for which interface
//! code would be generated automatically
//! Suppose you have the following Rust code:
//! ```rust
//! struct Foo {
//! data: i32
//! }
//!
//! impl Foo {
//! fn new(val: i32) -> Foo {
//! Foo{data: val}
//! }
//!
//! fn f(&self, a: i32, b: i32) -> i32 {
//! self.data + a + b
//! }
//!
//! ///Custom doc comment
//! fn set_field(&mut self, v: i32) {
//! self.data = v;
//! }
//! }
//!
//! ```
//! Using [`flapigen`], you need to generate an interface file with contents:
//!
//! [`flapigen`]: https://docs.rs/flapigen
//! ```rust
//! foreign_class!(class Foo {
//! self_type Foo;
//! constructor Foo::new(_: i32) -> Foo;
//! ///Custom doc comment
//! fn Foo::set_field(&mut self, _: i32);
//! fn Foo::f(&self, _: i32, _: i32) -> i32;
//! });
//! ```
//!
//! Using this crate, you can simply annotate the methods using either `#[generate_interface]`, `#[generate_interface(constructor)]` or `#[generate_interface_doc]`
//!
//! First add the appropriate dependencies
//!
//! In Cargo.toml
//! ```toml
//! [dependencies]
//! rifgen = "*"
//! [build-dependencies]
//! rifgen = "*"
//! ```
//!
//! In build.rs
//!```rust
//! //place this code before flapigen swig_expand function
//! use rifgen::{Generator, TypeCases, Language};
//! let source_folder = "/user/projects"; //use your projects folder
//! let out_file = "/user/projects/glue.in";
//! Generator::new(TypeCases::CamelCase,Language::Java,source_folder.parse().unwrap())
//! .generate_interface(&out_file.parse().unwrap())
//! ```
//!
//! Using the example above, the modified code would be
//! ```
//! use rifgen::rifgen_attr::*;
//!
//! struct Foo {
//! data: i32
//! }
//!
//! impl Foo {
//! #[generate_interface(constructor)]
//! fn new(val: i32) -> Foo {
//! Foo{data: val}
//! }
//! #[generate_interface]
//! fn f(&self, a: i32, b: i32) -> i32 {
//! self.data + a + b
//! }
//!
//! ///Custom doc comment
//! #[generate_interface]
//! fn set_field(&mut self, v: i32) {
//! self.data = v;
//! }
//! }
//! ```
//!
//! This crate works with doc comments so all doc comments would be preserved
//! Use `#[generate_interface_doc]` on <b>structs only</b> to preserve the doc comment of the struct
//! ```
//! ///Data holder
//! #[generate_interface_doc]
//! struct Foo {
//! data: i32
//! }
//! ```
//!
//! For `trait` just annotate the trait definition
//! ```
//! ///MyCallback documentation
//! #[generate_interface]
//! trait MyCallback {
//!
//! fn on_click(&self) {
//! }
//! }
//! ```
//! For `enum`, it's similar to `trait`
//! ```
//! #[generate_interface]
//! enum MyEnum {
//! One,
//! Two
//! }
//! ```
mod enums;
mod generator_lib;
mod maps;
mod text_formatter;
mod traits;
mod types_structs;
pub extern crate gen_attributes_interface_generator;
use crate::generator_lib::FileGenerator;
use std::path::PathBuf;
/// The various type cases to use when generating interface files
/// i.e CamelCase or snake_case or just leave the style unchanged
#[derive(Copy, Clone)]
pub enum TypeCases {
/// Various names of methods and variants are untouched.
/// This is the default setting
Default,
/// Convert all method names to CamelCase
CamelCase,
/// Convert all method method names to snake_case
SnakeCase,
}
#[deprecated(note = "use rifgen crate instead")]
/// The builder to use in build.rs file to generate the interface file
pub struct Generator {
type_case: TypeCases,
scr_folder: PathBuf,
language:Language
}
///Supported languages for now
pub enum Language {
Java,
Cpp
}
impl Generator {
/// Creates a new generator instance
///
/// `scr_folder` refers to the starting folder where it is recursively walked
///through to find other files
pub fn new(type_case: TypeCases, language:Language, scr_folder: PathBuf) -> Generator {
Generator {
type_case,
scr_folder,
language
}
}
///`interface_file_path` refers to the path of the output file.
/// If it exists, it would be overwritten
pub fn generate_interface(self, interface_file_path: &PathBuf) {
FileGenerator::new(
self.type_case,
interface_file_path.into(),
self.scr_folder.to_path_buf(),
)
.build(self.language);
}
}
#[cfg(test)]
mod tests {
//use crate::{Generator, TypeCases, Language};
#[test]
fn it_works() {
unimplemented!()
}
}
|
fn main() {
for_loop();
map();
}
fn for_loop() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
for val in v1_iter {
println!("In for_loop, got: {}", val);
}
}
fn map() {
// The map method produces another iterator.
let v1: Vec<i32> = vec![1, 2, 3];
// The next line doesn't do anything and gets a warning from the compier,
// because iterator adaptors are lazy, and we need to consume the iterator.
// v1.iter().map(|x| x + 1);
let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();
assert_eq!(v2, vec![2, 3, 4]);
println!("In map, v2 is: {:?}", v2);
}
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// As documented in Issue #45983, this test is evaluating the quality
// of our diagnostics on erroneous code using higher-ranked closures.
//
// However, as documented on Issue #53026, this test also became a
// prime example of our need to test the NLL migration mode
// *separately* from the existing test suites that focus solely on
// AST-borrwock and NLL.
// revisions: ast migrate nll
// Since we are testing nll (and migration) explicitly as a separate
// revisions, dont worry about the --compare-mode=nll on this test.
// ignore-compare-mode-nll
//[ast]compile-flags: -Z borrowck=ast
//[migrate]compile-flags: -Z borrowck=migrate -Z two-phase-borrows
//[nll]compile-flags: -Z borrowck=mir -Z two-phase-borrows
fn give_any<F: for<'r> FnOnce(&'r ())>(f: F) {
f(&());
}
fn main() {
let x = None;
give_any(|y| x = Some(y));
//[ast]~^ ERROR borrowed data cannot be stored outside of its closure
//[migrate]~^^ ERROR borrowed data cannot be stored outside of its closure
//[nll]~^^^ WARN not reporting region error due to nll
//[nll]~| ERROR borrowed data escapes outside of closure
//[nll]~| ERROR cannot assign to `x`, as it is not declared as mutable
}
|
extern crate matrix;
use matrix::prelude::*;
use std::cmp;
// Implements Floyd's algorithm for the all-pairs shortest-paths problem
// Input: The weight matrix w of a graph with no negative-length cycle
// Output: The distance matrix of the shortest paths' lengths
fn floyd(w: &mut Compressed<u8>) {
let n = w.rows();
for k in 0..n {
for i in 0..n {
for j in 0..n {
let d_ij = w.get((i, j));
let d_ik_kj: u8;
if w.get((i, k)) | w.get((k, j)) == 255 {
d_ik_kj = 255;
} else {
d_ik_kj = w.get((i, k)) + w.get((k, j));
}
w.set((i, j), cmp::min::<u8>(d_ij, d_ik_kj));
}
}
}
}
fn main() {
// example graph from figure 8.14 in book
let mut w = Compressed::<u8>::zero((4, 4));
w.set((0, 2), 3); // a -> c: 3
w.set((1, 0), 2); // b -> a: 2
w.set((2, 1), 7); // c -> b: 7
w.set((2, 3), 1); // c -> d: 1
w.set((3, 0), 6); // d -> a: 6
// set unused weights to high value
w.set((0, 1), 255);
w.set((0, 3), 255);
w.set((1, 2), 255);
w.set((1, 3), 255);
w.set((2, 0), 255);
w.set((3, 1), 255);
w.set((3, 2), 255);
println!("Original graph:");
for i in 0..4 {
for j in 0..4 {
if w.get((i, j)) > 0 && w.get((i, j)) != 0xff {
println!("\t{} -> {}: {}", i, j, w.get((i, j)));
}
}
}
floyd(&mut w);
println!("Distance matrix:");
for i in 0..4 {
println!("\t{}\t{}\t{}\t{}", w.get((i, 0)), w.get((i, 1)), w.get((i, 2)), w.get((i, 3)));
}
}
|
//! Utilities for testing tracing
use std::{fmt, sync::Arc};
use observability_deps::tracing::{
self,
field::Field,
span::{Attributes, Id, Record},
subscriber::{DefaultGuard, Subscriber},
Event,
};
use parking_lot::Mutex;
/// This struct captures tracing `Event`s as strings, and can be used
/// to verify that messages are making it to logs correctly
///
/// Upon creation it registers itself as the global default span
/// subscriber, and upon drop it sets a NoOp in its place.
#[derive(Debug)]
pub struct TracingCapture {
/// The raw logs are captured as a list of strings
logs: Arc<Mutex<Vec<String>>>,
guards: Mutex<Vec<DefaultGuard>>,
}
impl TracingCapture {
/// Create a new TracingCapture object and register it as a subscriber
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let logs = Arc::new(Mutex::new(Vec::new()));
let this = Self {
logs,
guards: Default::default(),
};
this.register_in_current_thread();
this
}
/// Registers capture in current thread.
pub fn register_in_current_thread(&self) {
// Register a subscriber to actually capture the log messages
let my_subscriber = TracingCaptureSubscriber {
logs: Arc::clone(&self.logs),
};
// install the subscriber (is uninstalled when the guard is dropped)
let guard = tracing::subscriber::set_default(my_subscriber);
self.guards.lock().push(guard);
}
}
impl fmt::Display for TracingCapture {
/// Retrieves the contents of all captured traces as a string
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let logs = self.logs.lock();
write!(f, "{}", logs.join("\n"))
}
}
/// Captures span events to verify
struct TracingCaptureSubscriber {
logs: Arc<Mutex<Vec<String>>>,
}
impl Subscriber for TracingCaptureSubscriber {
fn new_span(&self, _span: &Attributes<'_>) -> Id {
Id::from_u64(1)
}
fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
true
}
fn record(&self, _span: &Id, _values: &Record<'_>) {}
fn record_follows_from(&self, _span: &Id, _follows: &Id) {}
fn event(&self, event: &Event<'_>) {
let mut v = StringVisitor {
string: String::new(),
};
v.record_kv("level", &event.metadata().level().to_string());
event.record(&mut v);
let mut logs = self.logs.lock();
logs.push(v.string);
}
fn enter(&self, _span: &Id) {}
fn exit(&self, _span: &Id) {}
}
struct StringVisitor {
string: String,
}
impl StringVisitor {
fn record_kv(&mut self, key: &str, value: &str) {
use std::fmt::Write;
write!(self.string, "{key} = {value}; ").unwrap();
}
}
impl tracing::field::Visit for StringVisitor {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
self.record_kv(field.name(), &format!("{value:?}"))
}
}
|
pub mod board;
pub mod floodfill;
pub mod solutions;
pub mod transport;
|
use input::Key;
use serde::Deserialize;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::path::PathBuf;
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
pub listen_address: SocketAddr,
pub switch_keys: HashSet<Key>,
pub identity_path: PathBuf,
#[serde(default)]
pub identity_password: String,
}
|
mod class;
mod datatypes;
mod exceptions;
mod export;
mod functions;
mod import;
mod interfaces;
mod method_decls;
mod method_sigs;
mod traits;
mod type_syn;
use crate::{parser::Parser, T};
pub(crate) use class::*;
pub(crate) use datatypes::*;
pub(crate) use exceptions::*;
pub(crate) use export::*;
pub(crate) use functions::*;
pub(crate) use import::*;
pub(crate) use interfaces::*;
pub(crate) use method_decls::*;
pub(crate) use method_sigs::*;
pub(crate) use traits::*;
pub(crate) use type_syn::*;
use super::annotations_opt;
pub(crate) fn decl(p: &mut Parser) {
let m = p.start();
annotations_opt(p);
match p.current() {
T![data] => datatype(p, m),
T![def] => maybe_par_fn(p, m),
T![type] => type_syn(p, m),
T![exception] => exception(p, m),
T![interface] => interface(p, m),
T![class] => class(p, m),
T![trait] => trait_decl(p, m),
_ => return p.error("expected a declaration"),
}
}
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkPhysicalDeviceDescriptorIndexingPropertiesEXT {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub maxUpdateAfterBindDescriptorsInAllPools: u32,
pub shaderUniformBufferArrayNonUniformIndexingNative: VkBool32,
pub shaderSampledImageArrayNonUniformIndexingNative: VkBool32,
pub shaderStorageBufferArrayNonUniformIndexingNative: VkBool32,
pub shaderStorageImageArrayNonUniformIndexingNative: VkBool32,
pub shaderInputAttachmentArrayNonUniformIndexingNative: VkBool32,
pub robustBufferAccessUpdateAfterBind: VkBool32,
pub quadDivergentImplicitLod: VkBool32,
pub maxPerStageDescriptorUpdateAfterBindSamplers: u32,
pub maxPerStageDescriptorUpdateAfterBindUniformBuffers: u32,
pub maxPerStageDescriptorUpdateAfterBindStorageBuffers: u32,
pub maxPerStageDescriptorUpdateAfterBindSampledImages: u32,
pub maxPerStageDescriptorUpdateAfterBindStorageImages: u32,
pub maxPerStageDescriptorUpdateAfterBindInputAttachments: u32,
pub maxPerStageUpdateAfterBindResources: u32,
pub maxDescriptorSetUpdateAfterBindSamplers: u32,
pub maxDescriptorSetUpdateAfterBindUniformBuffers: u32,
pub maxDescriptorSetUpdateAfterBindUniformBuffersDynamic: u32,
pub maxDescriptorSetUpdateAfterBindStorageBuffers: u32,
pub maxDescriptorSetUpdateAfterBindStorageBuffersDynamic: u32,
pub maxDescriptorSetUpdateAfterBindSampledImages: u32,
pub maxDescriptorSetUpdateAfterBindStorageImages: u32,
pub maxDescriptorSetUpdateAfterBindInputAttachments: u32,
}
impl Default for VkPhysicalDeviceDescriptorIndexingPropertiesEXT {
fn default() -> Self {
VkPhysicalDeviceDescriptorIndexingPropertiesEXT {
sType: VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT,
pNext: ptr::null(),
maxUpdateAfterBindDescriptorsInAllPools: 0,
shaderUniformBufferArrayNonUniformIndexingNative: VK_FALSE,
shaderSampledImageArrayNonUniformIndexingNative: VK_FALSE,
shaderStorageBufferArrayNonUniformIndexingNative: VK_FALSE,
shaderStorageImageArrayNonUniformIndexingNative: VK_FALSE,
shaderInputAttachmentArrayNonUniformIndexingNative: VK_FALSE,
robustBufferAccessUpdateAfterBind: VK_FALSE,
quadDivergentImplicitLod: VK_FALSE,
maxPerStageDescriptorUpdateAfterBindSamplers: 0,
maxPerStageDescriptorUpdateAfterBindUniformBuffers: 0,
maxPerStageDescriptorUpdateAfterBindStorageBuffers: 0,
maxPerStageDescriptorUpdateAfterBindSampledImages: 0,
maxPerStageDescriptorUpdateAfterBindStorageImages: 0,
maxPerStageDescriptorUpdateAfterBindInputAttachments: 0,
maxPerStageUpdateAfterBindResources: 0,
maxDescriptorSetUpdateAfterBindSamplers: 0,
maxDescriptorSetUpdateAfterBindUniformBuffers: 0,
maxDescriptorSetUpdateAfterBindUniformBuffersDynamic: 0,
maxDescriptorSetUpdateAfterBindStorageBuffers: 0,
maxDescriptorSetUpdateAfterBindStorageBuffersDynamic: 0,
maxDescriptorSetUpdateAfterBindSampledImages: 0,
maxDescriptorSetUpdateAfterBindStorageImages: 0,
maxDescriptorSetUpdateAfterBindInputAttachments: 0,
}
}
}
unsafe impl Sync for VkPhysicalDeviceDescriptorIndexingPropertiesEXT {}
unsafe impl Send for VkPhysicalDeviceDescriptorIndexingPropertiesEXT {}
|
use abi_stable::{
abi_stability::abi_checking::{
check_layout_compatibility, check_layout_compatibility_with_globals, AbiInstability,
CheckingGlobals,
},
sabi_trait,
std_types::RBox,
type_layout::TypeLayout,
StableAbi,
};
fn check_subsets<F>(list: &[&'static TypeLayout], mut f: F)
where
F: FnMut(&[AbiInstability]),
{
let globals = CheckingGlobals::new();
#[cfg(miri)]
{
assert_eq!(
check_layout_compatibility_with_globals(&list[0], &list[0], &globals),
Ok(())
);
f(
&check_layout_compatibility_with_globals(&list[1], &list[0], &globals)
.unwrap_err()
.flatten_errors(),
);
}
#[cfg(not(miri))]
for (l_i, l_abi) in list.iter().enumerate() {
for (r_i, r_abi) in list.iter().enumerate() {
let res = check_layout_compatibility_with_globals(l_abi, r_abi, &globals);
if l_i <= r_i {
assert_eq!(res, Ok(()));
} else {
if res.is_ok() {
let _ = dbg!(l_i);
let _ = dbg!(r_i);
}
let errs = res.unwrap_err().flatten_errors();
f(&*errs);
}
}
}
}
fn check_equality<F>(list: &[&'static TypeLayout], mut f: F)
where
F: FnMut(&[AbiInstability]),
{
#[cfg(miri)]
{
assert_eq!(check_layout_compatibility(&list[0], &list[0]), Ok(()));
f(&check_layout_compatibility(&list[1], &list[0])
.unwrap_err()
.flatten_errors());
}
#[cfg(not(miri))]
for (l_i, l_abi) in list.iter().enumerate() {
for (r_i, r_abi) in list.iter().enumerate() {
let res = check_layout_compatibility(l_abi, r_abi);
if l_i == r_i {
assert_eq!(res, Ok(()));
} else {
if res.is_ok() {
let _ = dbg!(l_i);
let _ = dbg!(r_i);
}
let errs = res.unwrap_err().flatten_errors();
f(&*errs);
}
}
}
}
mod one_method {
use super::*;
#[sabi_trait]
// #[sabi(debug_print_trait)]
pub trait Trait {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
}
}
mod two_methods {
use super::*;
#[sabi_trait]
pub trait Trait {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
fn apply2(&self, l: u32, r: u32) -> u32;
}
}
mod three_methods {
use super::*;
#[sabi_trait]
pub trait Trait {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
fn apply2(&self, l: u32, r: u32) -> u32;
fn apply3(&self, l: u32, r: u32) -> u32;
}
}
mod one_method_debug {
use super::*;
#[sabi_trait]
pub trait Trait: Debug {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
}
}
mod one_method_clone_debug {
use super::*;
#[sabi_trait]
pub trait Trait: Clone + Debug {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
}
}
mod one_method_sync {
use super::*;
#[sabi_trait]
pub trait Trait: Sync {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
}
}
mod one_method_send {
use super::*;
#[sabi_trait]
pub trait Trait: Send {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
}
}
mod one_method_sync_send {
use super::*;
#[sabi_trait]
pub trait Trait: Sync + Send {
#[sabi(last_prefix_field)]
fn apply(&self, l: u32, r: u32) -> u32;
}
}
#[test]
fn adding_methods_at_the_end() {
let list = vec![
<one_method::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
<two_methods::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
<three_methods::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
];
check_subsets(&list[..], |errs| {
assert!(errs
.iter()
.any(|err| matches!(err, AbiInstability::FieldCountMismatch { .. })));
});
}
#[test]
fn adding_supertraits() {
let list = vec![
<one_method::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
<one_method_debug::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
<one_method_clone_debug::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
];
check_subsets(&list[..], |errs| {
assert!(errs
.iter()
.any(|err| matches!(err, AbiInstability::ExtraCheckError { .. })));
});
}
#[test]
fn incompatible_supertraits() {
let list = vec![
<one_method::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
<one_method_sync::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
<one_method_send::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
<one_method_sync_send::Trait_TO<'_, RBox<()>> as StableAbi>::LAYOUT,
];
check_equality(&list[..], |errs| {
assert!(errs
.iter()
.any(|err| matches!(err, AbiInstability::ExtraCheckError { .. })));
});
}
|
pub struct Solution;
impl Solution {
pub fn h_index(citations: Vec<i32>) -> i32 {
let n = citations.len();
if n == 0 || citations[n - 1] < 1 {
return 0;
}
if citations[n - n] >= n as i32 {
return n as i32;
}
let mut a = 1;
let mut b = n;
while a + 1 < b {
let c = (a + b) / 2;
if citations[n - c] >= c as i32 {
a = c;
} else {
b = c;
}
}
a as i32
}
}
#[test]
fn test0275() {
fn case(citations: Vec<i32>, want: i32) {
let got = Solution::h_index(citations);
assert_eq!(got, want);
}
case(vec![0, 1, 3, 5, 6], 3);
}
|
use std::mem::ManuallyDrop;
#[cfg(feature = "sgx")]
use std::prelude::v1::*;
use std::ptr::{self, NonNull};
#[cfg(not(feature = "sgx"))]
use std::sync::{Arc, Mutex, MutexGuard};
#[cfg(feature = "sgx")]
use std::sync::{Arc, SgxMutex as Mutex, SgxMutexGuard as MutexGuard};
use io_uring_callback::{Fd, Handle};
#[cfg(feature = "sgx")]
use sgx_untrusted_alloc::UntrustedAllocator;
use crate::io::receiver::MsgParam;
use crate::io::{Common, IoUringProvider};
use crate::poll::{Events, Poller};
use crate::util::CircularBuf;
pub struct Sender<P: IoUringProvider> {
common: Arc<Common<P>>,
inner: Mutex<Inner>,
}
struct Inner {
buf: ManuallyDrop<CircularBuf>,
#[cfg(not(feature = "sgx"))]
buf_alloc: ManuallyDrop<Vec<u8>>,
#[cfg(feature = "sgx")]
buf_alloc: ManuallyDrop<UntrustedAllocator>,
pending_io: Option<Handle>,
is_shutdown: bool,
msg_param: ManuallyDrop<*mut MsgParam>,
#[cfg(feature = "sgx")]
msg_param_alloc: ManuallyDrop<UntrustedAllocator>,
}
unsafe impl Send for Inner {}
impl<P: IoUringProvider> Sender<P> {
/// Construct the sender of a socket.
pub(crate) fn new(common: Arc<Common<P>>, buf_size: usize) -> Arc<Self> {
let inner = Mutex::new(Inner::new(buf_size));
let new_self = Arc::new(Self { common, inner });
new_self
}
pub async fn write(self: &Arc<Self>, buf: &[u8]) -> i32 {
// Initialize the poller only when needed
let mut poller = None;
loop {
// Attempt to write
let ret = self.try_write(buf);
// If the sender is not writable for now, poll again
if ret != -libc::EAGAIN {
return ret;
}
// Wait for interesting events by polling
if poller.is_none() {
poller = Some(Poller::new());
}
let mask = Events::OUT;
let events = self.common.pollee().poll_by(mask, poller.as_mut());
if events.is_empty() {
poller.as_ref().unwrap().wait().await;
}
}
}
fn try_write(self: &Arc<Self>, buf: &[u8]) -> i32 {
let mut inner = self.inner.lock().unwrap();
if inner.is_shutdown {
return -libc::EPIPE;
}
if let Some(error) = self.common.error() {
return error;
}
if buf.len() == 0 {
return 0;
}
let nbytes = inner.buf.produce(buf);
if inner.buf.is_full() {
// Mark the socket as non-writable
self.common.pollee().remove(Events::OUT);
}
if nbytes == 0 {
return -libc::EAGAIN;
}
if inner.pending_io.is_none() {
self.flush_buf(&mut inner);
}
nbytes as i32
}
fn flush_buf(self: &Arc<Self>, inner: &mut MutexGuard<Inner>) {
debug_assert!(!inner.buf.is_empty());
debug_assert!(inner.pending_io.is_none());
// Init the callback invoked upon the completion of the async flush
let sender = self.clone();
let complete_fn = move |retval: i32| {
let mut inner = sender.inner.lock().unwrap();
// Release the handle to the async fill
inner.pending_io.take();
// Handle the two cases of success and error
if retval >= 0 {
let nbytes = retval as usize;
inner.buf.consume_without_copy(nbytes);
if !inner.is_shutdown {
sender.common.pollee().add(Events::OUT);
}
} else {
// Discard all data in the send buf
let consumable_bytes = inner.buf.consumable();
inner.buf.consume_without_copy(consumable_bytes);
sender.common.set_error(retval);
sender.common.pollee().add(Events::ERR);
}
// Flush there are remaining data in the buf
if !inner.buf.is_empty() {
sender.flush_buf(&mut inner);
} else {
if inner.is_shutdown {
unsafe {
#[cfg(not(feature = "sgx"))]
libc::shutdown(sender.common.fd(), libc::SHUT_WR);
#[cfg(feature = "sgx")]
libc::ocall::shutdown(sender.common.fd(), libc::SHUT_WR);
}
}
}
};
// Construct the iovec for the async flush
let mut iovec_len = 1;
let msg_param_ptr = *inner.msg_param;
let mut msg_ptr = unsafe { &mut (*msg_param_ptr).msg as *mut libc::msghdr };
unsafe {
inner.buf.with_consumer_view(|part0, part1| {
debug_assert!(part0.len() > 0);
(*msg_param_ptr).iovecs[0] = libc::iovec {
iov_base: part0.as_ptr() as _,
iov_len: part0.len() as _,
};
if part1.len() > 0 {
(*msg_param_ptr).iovecs[1] = libc::iovec {
iov_base: part1.as_ptr() as _,
iov_len: part1.len() as _,
};
iovec_len += 1;
}
// Only access the consumer's data; zero bytes consumed for now.
0
});
(*msg_ptr).msg_name = ptr::null_mut() as _;
(*msg_ptr).msg_namelen = 0;
(*msg_ptr).msg_iov = &mut (*msg_param_ptr).iovecs as *mut [libc::iovec; 2] as *mut _;
(*msg_ptr).msg_iovlen = iovec_len;
(*msg_ptr).msg_control = ptr::null_mut() as _;
(*msg_ptr).msg_controllen = 0;
(*msg_ptr).msg_flags = 0;
}
// Submit the async flush to io_uring
let io_uring = &self.common.io_uring();
let handle = unsafe { io_uring.sendmsg(Fd(self.common.fd()), msg_ptr, 0, complete_fn) };
inner.pending_io.replace(handle);
}
/// Shutdown the sender.
///
/// After shutdowning, the sender will no longer be able to write more data,
/// only flushing the already-written data to the underlying io_uring.
pub fn shutdown(&self) {
let mut inner = self.inner.lock().unwrap();
inner.is_shutdown = true;
if inner.pending_io.is_none() && inner.buf.is_empty() {
unsafe {
#[cfg(not(feature = "sgx"))]
libc::shutdown(self.common.fd(), libc::SHUT_WR);
#[cfg(feature = "sgx")]
libc::ocall::shutdown(self.common.fd(), libc::SHUT_WR);
}
}
}
}
impl Inner {
pub fn new(buf_size: usize) -> Self {
#[cfg(not(feature = "sgx"))]
let mut buf_alloc = Vec::<u8>::with_capacity(buf_size);
#[cfg(feature = "sgx")]
let buf_alloc = UntrustedAllocator::new(buf_size, 1).unwrap();
let buf = unsafe {
let ptr = NonNull::new_unchecked(buf_alloc.as_mut_ptr());
let len = buf_alloc.capacity();
CircularBuf::from_raw_parts(ptr, len)
};
let pending_io = None;
let is_shutdown = false;
#[cfg(not(feature = "sgx"))]
let msg_param: *mut MsgParam = Box::into_raw(Box::new(unsafe { std::mem::zeroed() }));
#[cfg(feature = "sgx")]
let msg_param_alloc = UntrustedAllocator::new(core::mem::size_of::<MsgParam>(), 8).unwrap();
#[cfg(feature = "sgx")]
let msg_param: *mut MsgParam = msg_param_alloc.as_mut_ptr() as _;
Inner {
buf: ManuallyDrop::new(buf),
buf_alloc: ManuallyDrop::new(buf_alloc),
pending_io,
is_shutdown,
msg_param: ManuallyDrop::new(msg_param),
#[cfg(feature = "sgx")]
msg_param_alloc: ManuallyDrop::new(msg_param_alloc),
}
}
}
impl Drop for Inner {
fn drop(&mut self) {
// When the sender is dropped, all pending async I/O should have been completed.
debug_assert!(self.pending_io.is_none());
// Since buf uses the memory allocated from buf_alloc, we must first drop buf,
// then buf_alloc.
unsafe {
ManuallyDrop::drop(&mut self.buf);
ManuallyDrop::drop(&mut self.buf_alloc);
#[cfg(not(feature = "sgx"))]
drop(Box::from_raw(*self.msg_param));
ManuallyDrop::drop(&mut self.msg_param);
#[cfg(feature = "sgx")]
ManuallyDrop::drop(&mut self.msg_param_alloc);
}
}
}
|
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Debug, PartialEq)]
pub struct Node<T>(pub T, pub Edge<T>);
pub type NodePointer<T> = Rc<RefCell<Node<T>>>;
pub type Edge<T> = Vec<NodePointer<T>>;
pub trait Graph {
type NodeType;
fn connect(&mut self, node: NodePointer<Self::NodeType>);
}
|
use std::error;
use std::io;
use std::fmt;
use std::num;
#[derive(Debug)]
pub enum CryptoError {
CryptoInvalidStructure(String),
CryptoUnknownType(String),
CryptoRevocationRegistryFull(String),
CryptoInvalidUserRevocIndex(String),
CryptoBackendError(String)
}
impl fmt::Display for CryptoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CryptoError::CryptoInvalidStructure(ref description) => write!(f, "Invalid crypto structure: {}", description),
CryptoError::CryptoUnknownType(ref description) => write!(f, "Unknown crypto type: {}", description),
CryptoError::CryptoRevocationRegistryFull(ref description) => write!(f, "Crypto revocation registry is full: {}", description),
CryptoError::CryptoInvalidUserRevocIndex(ref description) => write!(f, "Crypto invalid revocation index: {}", description),
CryptoError::CryptoBackendError(ref description) => write!(f, "Crypto backend error {}", description)
}
}
}
impl error::Error for CryptoError {
fn description(&self) -> &str {
match *self {
CryptoError::CryptoInvalidStructure(ref description) => description,
CryptoError::CryptoUnknownType(ref description) => description,
CryptoError::CryptoRevocationRegistryFull(ref description) => description,
CryptoError::CryptoInvalidUserRevocIndex(ref description) => description,
CryptoError::CryptoBackendError(ref description) => description
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
CryptoError::CryptoInvalidStructure(ref description) => None,
CryptoError::CryptoUnknownType(ref description) => None,
CryptoError::CryptoRevocationRegistryFull(ref description) => None,
CryptoError::CryptoInvalidUserRevocIndex(ref description) => None,
CryptoError::CryptoBackendError(ref err) => None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc::channel;
// #[test]
// fn crypto_error_can_be_created() {
// let error = CryptoError::InvalidData("TEST".to_string());
// }
//
// #[test]
// fn crypto_error_can_be_formatted() {
// let error_formatted = format!("{}", CryptoError::InvalidData("TEST".to_string()));
// assert_eq!("Invalid data: TEST", error_formatted);
// }
} |
use std::default::Default;
use std::string::ToString;
use yew::prelude::*;
pub enum TextInputModalMsg {
ImportClicked,
TextChanged(String),
CancelClicked,
}
#[derive(Clone, PartialEq)]
pub struct TextInputModal {
title: String,
content: String,
placeholder: String,
button_text: String,
id: String,
on_import: Callback<String>,
warning_hidden: bool,
}
#[derive(Clone, PartialEq)]
pub struct Props {
pub title: String,
pub content: String,
pub button_text: String,
pub placeholder: String,
pub id: String,
pub on_import: Callback<String>,
pub warning_hidden: bool,
pub onsignal: Option<Callback<String>>,
}
impl TextInputModal {
pub fn new(title: &str) -> Self {
TextInputModal {
title: title.to_string(),
content: String::new(),
placeholder: String::new(),
button_text: String::new(),
id: String::new(),
on_import: Callback::from(|_| return),
warning_hidden: true,
}
}
}
impl Component for TextInputModal {
type Message = TextInputModalMsg;
type Properties = Props;
fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self {
TextInputModal {
title: props.title,
content: props.content,
placeholder: props.placeholder,
button_text: props.button_text,
on_import: props.on_import,
id: props.id,
warning_hidden: true,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
TextInputModalMsg::TextChanged(new_content) => {
self.content = new_content;
}
TextInputModalMsg::ImportClicked => {
self.warning_hidden = false;
}
TextInputModalMsg::CancelClicked => {}
};
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
self.on_import = props.on_import;
self.content = props.content;
self.title = props.title;
self.placeholder = props.placeholder;
self.button_text = props.button_text;
self.id = props.id;
self.warning_hidden = props.warning_hidden;
true
}
}
impl Renderable<TextInputModal> for TextInputModal {
fn view(&self) -> Html<Self> {
html! {
<div id={ &self.id }, uk-modal="", >
<div class="uk-modal-dialog uk-modal-body", >
<h3 class="uk-modal-title", >{ &self.title }</h3>
<div class="uk-margin-top", >
<textarea class="uk-textarea", placeholder={ &self.placeholder }, rows=5, oninput=|e| TextInputModalMsg::TextChanged(e.value), ></textarea>
<p class="uk-text-right", >
<button class="uk-button uk-button-primary uk-margin-right", type="button", onclick=|_| { TextInputModalMsg::ImportClicked}, >{ &self.button_text }</button>
<button class="uk-button uk-button-danger uk-modal-close uk-margin-right", type="button", >{ "Cancel" }</button>
</p>
</div>
</div>
</div>
}
}
}
impl Default for Props {
fn default() -> Self {
Props {
title: "Default".to_string(),
content: "...".to_string(),
placeholder: "...".to_string(),
button_text: "Save".to_string(),
id: "#generic-modal".to_string(),
on_import: Callback::from(|_| return),
warning_hidden: true,
onsignal: None,
}
}
}
|
fn main() {
// argument setting
let a: Vec<u32> = vec![1, 4, 5, 6, 14, 15, 32, 41, 1, 123241, 414, 1111111, 9999999];
let n: usize = 13;
println!("max length: {}", solve(a, n));
}
use std::cmp;
fn solve(a: Vec<u32>, n: usize) -> u32 {
if n != a.len() {
panic!("n is not equal to the number of element of a!");
}
let mut iter: u32 = 0;
let mut ans: u32 = 0;
for i in 0..n - 2 {
for j in i + 1..n - 1 {
for k in j + 1..n {
let mut len = a[i] + a[j] + a[k];
let mut max_a = cmp::max(cmp::max(a[i], a[j]), a[k]);
println!("{} {} {}", i, j, k);
println!("len:{}, max_a:{}, {} {} {}", len, max_a, a[i], a[j], a[k]);
if max_a < len - max_a {
println!("can be triangle");
ans = cmp::max(ans, len) as u32;
}
iter = iter + 1;
println!("----------------------------------------------------");
}
}
}
println!("number of iteration: {}", iter);
return ans;
}
#[test]
fn answer_check() {
assert_eq!(solve(vec![2, 3, 4, 5, 10], 5), 12);
assert_eq!(solve(vec![4, 5, 10, 20], 4), 0);
}
|
// ---------------------------------------------------------------------------------------------------------
// ChecksumI trait
//
// 国密 sm3 算法的 checksum
//
// ---------------------------------------------------------------------------------------------------------
pub trait ChecksumI {
/*
需要digest
【计算过程】
1、对digest进行第一次 【摘要计算】,结果为hash1。
2、对hash1进行一次 【摘要计算】,结果为hash2。
3、取hash2的前四个字节,即为checksum的结果。
【输出】
四个字节的数组
*/
fn checksum(&self, digest: &Vec<u8>) -> Vec<u8>;
}
|
use metrics_core::MetricsObserver;
pub struct PrometheusRecorder {
output: String,
}
impl PrometheusRecorder {
pub fn new() -> Self {
PrometheusRecorder {
output: String::new(),
}
}
}
impl MetricsObserver for PrometheusRecorder {
fn observe_counter<K: AsRef<str>>(&mut self, label: K, value: u64) {
let label = label.as_ref().replace('.', "_");
self.output.push_str("# TYPE ");
self.output.push_str(label.as_str());
self.output.push_str(" counter\n");
self.output.push_str(label.as_str());
self.output.push_str(" ");
self.output.push_str(value.to_string().as_str());
self.output.push_str("\n");
}
fn observe_gauge<K: AsRef<str>>(&mut self, label: K, value: i64) {
let label = label.as_ref().replace('.', "_");
self.output.push_str("# TYPE ");
self.output.push_str(label.as_str());
self.output.push_str(" gauge\n");
self.output.push_str(label.as_str());
self.output.push_str(" ");
self.output.push_str(value.to_string().as_str());
self.output.push_str("\n");
}
fn observe_histogram<K: AsRef<str>>(&mut self, label: K, quantiles: &[(f64, u64)]) {
let label = label.as_ref().replace('.', "_");
self.output.push_str("# TYPE ");
self.output.push_str(label.as_str());
self.output.push_str(" summary\n");
for (percentile, value) in quantiles {
self.output.push_str(label.as_str());
self.output.push_str("{quantile=\"");
self.output.push_str(percentile.to_string().as_str());
self.output.push_str("\"} ");
self.output.push_str(value.to_string().as_str());
self.output.push_str("\n");
}
self.output.push_str(label.as_str());
self.output.push_str("_sum ");
self.output.push_str(summary.sum().to_string().as_str());
self.output.push_str("\n");
self.output.push_str(label.as_str());
self.output.push_str("_count ");
self.output.push_str(summary.count().to_string().as_str());
self.output.push_str("\n");
}
}
|
extern crate rdmcommon;
extern crate rdmgreeter;
#[macro_use]
extern crate slog;
extern crate slog_async;
extern crate slog_term;
extern crate gdk;
extern crate gdk_pixbuf;
extern crate gtk;
mod constants;
mod ui;
use std::rc::Rc;
use std::sync::Mutex;
use slog::{Drain, Logger};
use slog_async::Async;
use slog_term::{FullFormat, TermDecorator};
fn setup_logger() -> Logger {
let decor = TermDecorator::new().build();
let drain = FullFormat::new(decor).build().fuse();
let drain = Async::new(drain).build().fuse();
let log = Logger::root(drain, o!());
debug!(&log, "[setup_logger] Initialized logging");
log
}
fn main() {
let log = setup_logger();
let mut greeter = rdmgreeter::RdmGreeter::new(log.clone()).expect("Failed to get greeter");
debug!(&log, "[main] Got greeter! Press any key to to continue");
let mut res = String::new();
let mut c = ::std::io::stdin().read_line(&mut res);
return;
// Init gtk
(::gtk::init()).expect("Failed to initialize gtk");
// Setup the Ui
/*let mut ui = ui::Ui::from_theme(constants::THEME_NAME_DEFAULT, greeter);
ui.show();*/
// Start gtk event loop
::gtk::main();
} |
// Copyright 2017 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
use std::usize;
use std::sync::{Arc, Mutex, Condvar};
use std::thread::{Builder, JoinHandle};
use std::boxed::FnBox;
use std::collections::{BinaryHeap, VecDeque};
use std::cmp::Ordering;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use std::hash::Hash;
use std::marker::PhantomData;
use std::fmt::{self, Write, Debug, Formatter};
use std::sync::mpsc::{Sender, Receiver, channel};
use super::collections::HashMap;
const DEFAULT_QUEUE_CAPACITY: usize = 1000;
const QUEUE_MAX_CAPACITY: usize = 8 * DEFAULT_QUEUE_CAPACITY;
pub struct Task<T> {
// The task's id in the pool. Each task has a unique id,
// and it's always bigger than preceding ones.
id: u64,
// which group the task belongs to.
gid: T,
task: Box<FnBox() + Send>,
}
impl<T: Debug> Debug for Task<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "task_id:{},group_id:{:?}", self.id, self.gid)
}
}
impl<T> Task<T> {
fn new<F>(gid: T, job: F) -> Task<T>
where F: FnOnce() + Send + 'static
{
Task {
id: 0,
gid: gid,
task: Box::new(job),
}
}
}
impl<T> Ord for Task<T> {
fn cmp(&self, right: &Task<T>) -> Ordering {
self.id.cmp(&right.id).reverse()
}
}
impl<T> PartialEq for Task<T> {
fn eq(&self, right: &Task<T>) -> bool {
self.cmp(right) == Ordering::Equal
}
}
impl<T> Eq for Task<T> {}
impl<T> PartialOrd for Task<T> {
fn partial_cmp(&self, rhs: &Task<T>) -> Option<Ordering> {
Some(self.cmp(rhs))
}
}
pub trait ScheduleQueue<T: Debug> {
fn pop(&mut self) -> Option<Task<T>>;
fn push(&mut self, task: Task<T>);
fn on_task_finished(&mut self, gid: &T);
fn on_task_started(&mut self, gid: &T);
}
#[derive(Debug)]
pub struct ReachConcurrencyLimit<T: Debug>(pub T);
#[derive(Default)]
struct GroupStatisticsItem {
running_count: usize,
high_priority_queue_count: usize,
low_priority_queue_count: usize,
}
impl GroupStatisticsItem {
fn sum(&self) -> usize {
self.running_count + self.high_priority_queue_count + self.low_priority_queue_count
}
}
// `SmallGroupFirstQueue` tries to run groups with number of
// tasks smaller than small_group_tasks_limit first when all threads are busy.
pub struct SmallGroupFirstQueue<T> {
high_priority_queue: VecDeque<Task<T>>,
low_priority_queue: VecDeque<Task<T>>,
group_concurrency_on_busy: usize,
small_group_tasks_limit: usize,
statistics: HashMap<T, GroupStatisticsItem>,
}
impl<T: Hash + Ord + Send + Clone + Debug> SmallGroupFirstQueue<T> {
pub fn new(group_concurrency_on_busy: usize,
small_group_tasks_limit: usize)
-> SmallGroupFirstQueue<T> {
SmallGroupFirstQueue {
high_priority_queue: VecDeque::with_capacity(DEFAULT_QUEUE_CAPACITY),
low_priority_queue: VecDeque::with_capacity(DEFAULT_QUEUE_CAPACITY),
statistics: HashMap::new(),
group_concurrency_on_busy: group_concurrency_on_busy,
small_group_tasks_limit: small_group_tasks_limit,
}
}
fn pop_from_high_priority_queue(&mut self) -> Option<Task<T>> {
if self.high_priority_queue.is_empty() {
return None;
}
let task = self.high_priority_queue.pop_front().unwrap();
let mut statistics = self.statistics.get_mut(&task.gid).unwrap();
statistics.high_priority_queue_count -= 1;
Some(task)
}
fn pop_from_low_priority_queue(&mut self) -> Option<Task<T>> {
if self.low_priority_queue.is_empty() {
return None;
}
let task = self.low_priority_queue.pop_front().unwrap();
let mut statistics = self.statistics
.get_mut(&task.gid)
.unwrap();
statistics.low_priority_queue_count -= 1;
Some(task)
}
}
impl<T: Hash + Ord + Send + Clone + Debug> ScheduleQueue<T> for SmallGroupFirstQueue<T> {
fn push(&mut self, task: Task<T>) {
let mut statistics = self.statistics
.entry(task.gid.clone())
.or_insert(Default::default());
if statistics.low_priority_queue_count == 0 &&
statistics.running_count + statistics.high_priority_queue_count <
self.small_group_tasks_limit {
self.high_priority_queue.push_back(task);
statistics.high_priority_queue_count += 1;
} else {
self.low_priority_queue.push_back(task);
statistics.low_priority_queue_count += 1;
}
}
fn pop(&mut self) -> Option<Task<T>> {
if self.high_priority_queue.is_empty() {
return self.pop_from_low_priority_queue();
}
if self.low_priority_queue.is_empty() {
return self.pop_from_high_priority_queue();
}
let pop_from_high_priority_queue = {
let t1 = self.high_priority_queue.front().unwrap();
let t2 = self.low_priority_queue.front().unwrap();
t1.id < t2.id ||
(self.statistics[&t2.gid].running_count >= self.group_concurrency_on_busy)
};
if pop_from_high_priority_queue {
self.pop_from_high_priority_queue()
} else {
self.pop_from_low_priority_queue()
}
}
fn on_task_started(&mut self, gid: &T) {
let mut statistics = self.statistics.get_mut(gid).unwrap();
statistics.running_count += 1;
}
fn on_task_finished(&mut self, gid: &T) {
let count = {
let mut statistics = self.statistics.get_mut(gid).unwrap();
statistics.running_count -= 1;
statistics.sum()
};
if count == 0 {
self.statistics.remove(gid);
}
}
}
// First in first out queue.
pub struct FifoQueue<T> {
queue: VecDeque<Task<T>>,
}
impl<T: Hash + Ord + Send + Clone + Debug> FifoQueue<T> {
pub fn new() -> FifoQueue<T> {
FifoQueue { queue: VecDeque::with_capacity(DEFAULT_QUEUE_CAPACITY) }
}
}
impl<T: Hash + Ord + Send + Clone + Debug> ScheduleQueue<T> for FifoQueue<T> {
fn push(&mut self, task: Task<T>) {
self.queue.push_back(task);
}
fn pop(&mut self) -> Option<Task<T>> {
let task = self.queue.pop_front();
if self.queue.is_empty() && self.queue.capacity() > QUEUE_MAX_CAPACITY {
self.queue = VecDeque::with_capacity(DEFAULT_QUEUE_CAPACITY);
}
task
}
fn on_task_started(&mut self, _: &T) {}
fn on_task_finished(&mut self, _: &T) {}
}
// `BigGroupThrottledQueue` tries to throttle group's concurrency to
// `group_concurrency_limit` when all threads are busy.
// When one worker asks a task to run, it schedules in the following way:
// 1. Find out which group has a running number that is smaller than
// that of `group_concurrency_limit`.
// 2. If more than one group meets the first point, run the one who
// comes first.
// If no group meets the first point, choose according to the following rules:
// 1. Select the groups with least running tasks.
// 2. If more than one group meets the first point,choose the one
// whose task comes first(with the minimum task's ID)
pub struct BigGroupThrottledQueue<T> {
// The Tasks in `high_priority_queue` have higher priority than
// tasks in `low_priority_queue`.
high_priority_queue: BinaryHeap<Task<T>>,
// gid => tasks array. If `group_statistics[gid]` is bigger than
// `group_concurrency_limit`(which means the number of on-going tasks is
// more than `group_concurrency_limit`), the rest of the group's tasks
// would be pushed into `low_priority_queue[gid]`
low_priority_queue: HashMap<T, VecDeque<Task<T>>>,
// gid => (running_count,high_priority_queue_count)
group_statistics: HashMap<T, GroupStatisticsItem>,
// The maximum number of threads that each group can run when the pool is busy.
// Each value in `group_statistics` shouldn't be bigger than this value.
group_concurrency_limit: usize,
}
impl<T: Debug + Hash + Ord + Send + Clone> BigGroupThrottledQueue<T> {
pub fn new(group_concurrency_limit: usize) -> BigGroupThrottledQueue<T> {
BigGroupThrottledQueue {
high_priority_queue: BinaryHeap::new(),
low_priority_queue: HashMap::new(),
group_statistics: HashMap::new(),
group_concurrency_limit: group_concurrency_limit,
}
}
// Try push into high priority queue. Return none on success,return PushError(task) on failed.
#[inline]
fn try_push_into_high_priority_queue(&mut self,
task: Task<T>)
-> Result<(), ReachConcurrencyLimit<Task<T>>> {
let mut statistics = self.group_statistics
.entry(task.gid.clone())
.or_insert(Default::default());
if statistics.sum() >= self.group_concurrency_limit {
return Err(ReachConcurrencyLimit(task));
}
self.high_priority_queue.push(task);
statistics.high_priority_queue_count += 1;
Ok(())
}
#[inline]
fn pop_from_low_priority_queue(&mut self) -> Option<Task<T>> {
let gid = {
// Groups in low_priority_queue wouldn't too much, so iterate the map
// is quick.
let best_group = self.low_priority_queue
.iter()
.map(|(gid, low_priority_queue)| {
(self.group_statistics[gid].sum(), low_priority_queue[0].id, gid)
})
.min();
if let Some((_, _, gid)) = best_group {
gid.clone()
} else {
return None;
}
};
let task = self.pop_from_low_priority_queue_by_gid(&gid);
Some(task)
}
#[inline]
fn pop_from_low_priority_queue_by_gid(&mut self, gid: &T) -> Task<T> {
let (empty_after_pop, task) = {
let mut waiting_tasks = self.low_priority_queue.get_mut(gid).unwrap();
let task = waiting_tasks.pop_front().unwrap();
(waiting_tasks.is_empty(), task)
};
if empty_after_pop {
self.low_priority_queue.remove(gid);
}
task
}
}
impl<T: Hash + Ord + Send + Clone + Debug> ScheduleQueue<T> for BigGroupThrottledQueue<T> {
fn push(&mut self, task: Task<T>) {
if let Err(ReachConcurrencyLimit(task)) = self.try_push_into_high_priority_queue(task) {
self.low_priority_queue
.entry(task.gid.clone())
.or_insert_with(VecDeque::new)
.push_back(task);
}
}
fn pop(&mut self) -> Option<Task<T>> {
if let Some(task) = self.high_priority_queue.pop() {
let mut statistics = self.group_statistics.get_mut(&task.gid).unwrap();
statistics.high_priority_queue_count -= 1;
return Some(task);
} else if let Some(task) = self.pop_from_low_priority_queue() {
return Some(task);
}
None
}
fn on_task_started(&mut self, gid: &T) {
let mut statistics = self.group_statistics.entry(gid.clone()).or_insert(Default::default());
statistics.running_count += 1
}
fn on_task_finished(&mut self, gid: &T) {
let count = {
let mut statistics = self.group_statistics.get_mut(gid).unwrap();
statistics.running_count -= 1;
statistics.sum()
};
if count == 0 {
self.group_statistics.remove(gid);
} else if count >= self.group_concurrency_limit {
// If the number of running tasks for this group is big enough.
return;
}
if !self.low_priority_queue.contains_key(gid) {
return;
}
// If the value of `group_statistics[gid]` is not big enough, pop
// a task from `low_priority_queue[gid]` and push it into `high_priority_queue`.
let group_task = self.pop_from_low_priority_queue_by_gid(gid);
self.try_push_into_high_priority_queue(group_task).unwrap();
}
}
struct TaskPool<Q, T> {
next_task_id: u64,
task_queue: Q,
marker: PhantomData<T>,
stop: bool,
jobs: Receiver<Task<T>>,
}
impl<Q, T> TaskPool<Q, T>
where Q: ScheduleQueue<T>,
T: Debug
{
fn new(queue: Q, jobs: Receiver<Task<T>>) -> TaskPool<Q, T> {
TaskPool {
next_task_id: 0,
task_queue: queue,
marker: PhantomData,
stop: false,
jobs: jobs,
}
}
fn on_task_finished(&mut self, gid: &T) {
self.task_queue.on_task_finished(gid);
}
fn on_task_started(&mut self, gid: &T) {
self.task_queue.on_task_started(gid);
}
fn pop_task(&mut self) -> Option<Task<T>> {
if let Some(task) = self.task_queue.pop() {
return Some(task);
}
// try fill queue when queue is empty.
self.try_fill_queue();
self.task_queue.pop()
}
fn try_fill_queue(&mut self) {
while let Ok(mut task) = self.jobs.try_recv() {
task.id = self.next_task_id;
self.next_task_id += 1;
self.task_queue.push(task);
}
}
#[inline]
fn stop(&mut self) {
self.stop = true;
}
#[inline]
fn is_stopped(&self) -> bool {
self.stop
}
}
/// `ThreadPool` is used to execute tasks in parallel.
/// Each task would be pushed into the pool, and when a thread
/// is ready to process a task, it will get a task from the pool
/// according to the `ScheduleQueue` provided in initialization.
pub struct ThreadPool<Q, T> {
task_pool: Arc<(Mutex<TaskPool<Q, T>>, Condvar)>,
threads: Vec<JoinHandle<()>>,
task_count: Arc<AtomicUsize>,
sender: Sender<Task<T>>,
}
impl<Q, T> ThreadPool<Q, T>
where Q: ScheduleQueue<T> + Send + 'static,
T: Hash + Send + Clone + 'static + Debug
{
pub fn new(name: String, num_threads: usize, queue: Q) -> ThreadPool<Q, T> {
assert!(num_threads >= 1);
let (sender, receiver) = channel::<Task<T>>();
let task_pool = Arc::new((Mutex::new(TaskPool::new(queue, receiver)), Condvar::new()));
let mut threads = Vec::with_capacity(num_threads);
let task_count = Arc::new(AtomicUsize::new(0));
// Threadpool threads
for _ in 0..num_threads {
let tasks = task_pool.clone();
let task_num = task_count.clone();
let thread = Builder::new()
.name(name.clone())
.spawn(move || {
let mut worker = Worker::new(tasks, task_num);
worker.run();
})
.unwrap();
threads.push(thread);
}
ThreadPool {
task_pool: task_pool,
threads: threads,
task_count: task_count,
sender: sender,
}
}
pub fn execute<F>(&mut self, gid: T, job: F)
where F: FnOnce() + Send + 'static
{
let task = Task::new(gid, job);
self.sender.send(task).unwrap();
self.task_count.fetch_add(1, AtomicOrdering::SeqCst);
let &(_, ref cvar) = &*self.task_pool;
cvar.notify_one();
}
#[inline]
pub fn get_task_count(&self) -> usize {
self.task_count.load(AtomicOrdering::SeqCst)
}
pub fn stop(&mut self) -> Result<(), String> {
{
let &(ref lock, ref cvar) = &*self.task_pool;
let mut tasks = lock.lock().unwrap();
tasks.stop();
cvar.notify_all();
}
let mut err_msg = String::new();
for t in self.threads.drain(..) {
if let Err(e) = t.join() {
write!(&mut err_msg, "Failed to join thread with err: {:?};", e).unwrap();
}
}
if !err_msg.is_empty() {
return Err(err_msg);
}
Ok(())
}
}
// Each thread has a worker.
struct Worker<Q, T> {
task_pool: Arc<(Mutex<TaskPool<Q, T>>, Condvar)>,
task_count: Arc<AtomicUsize>,
}
impl<Q, T> Worker<Q, T>
where Q: ScheduleQueue<T>,
T: Debug
{
fn new(task_pool: Arc<(Mutex<TaskPool<Q, T>>, Condvar)>,
task_count: Arc<AtomicUsize>)
-> Worker<Q, T> {
Worker {
task_pool: task_pool,
task_count: task_count,
}
}
// `get_next_task` return `None` when `task_pool` is stopped.
#[inline]
fn get_next_task(&self, prev_gid: Option<&T>) -> Option<Task<T>> {
// try to receive notification.
let &(ref lock, ref cvar) = &*self.task_pool;
let mut task_pool = lock.lock().unwrap();
if prev_gid.is_some() {
task_pool.on_task_finished(prev_gid.unwrap());
}
loop {
if task_pool.is_stopped() {
return None;
}
if let Some(task) = task_pool.pop_task() {
// `on_task_started` should be here since:
// 1. To reduce lock's time;
// 2. For some schedula_queue,on_task_started should be
// in the same lock with `pop_task` for the thread safety.
task_pool.on_task_started(&task.gid);
return Some(task);
}
task_pool = cvar.wait(task_pool).unwrap();
}
}
fn run(&mut self) {
let mut task = self.get_next_task(None);
// Start the worker. Loop breaks when receive stop message.
while let Some(t) = task {
// Since tikv would be down when any panic happens,
// we don't need to process panic case here.
(t.task)();
self.task_count.fetch_sub(1, AtomicOrdering::SeqCst);
task = self.get_next_task(Some(&t.gid));
}
}
}
#[cfg(test)]
mod test {
use super::{ThreadPool, BigGroupThrottledQueue, Task, ScheduleQueue, SmallGroupFirstQueue,
FifoQueue};
use std::time::Duration;
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex};
#[test]
fn test_for_tasks_with_different_cost() {
let name = thd_name!("test_tasks_with_different_cost");
let concurrency = 2;
let mut task_pool = ThreadPool::new(name, concurrency, BigGroupThrottledQueue::new(1));
let (jtx, jrx) = channel();
let group_with_big_task = 1001 as u64;
let timeout = Duration::from_secs(2);
let (ftx, frx) = channel();
// Push a big task into pool.
task_pool.execute(group_with_big_task, move || {
// Since a long task of `group_with_big_task` is running,
// the other threads shouldn't run any task of `group_with_big_task`.
for _ in 0..10 {
let gid = jrx.recv_timeout(timeout).unwrap();
assert_ne!(gid, group_with_big_task);
}
for _ in 0..10 {
let gid = jrx.recv_timeout(timeout).unwrap();
assert_eq!(gid, group_with_big_task);
}
ftx.send(true).unwrap();
});
for gid in 0..10 {
let sender = jtx.clone();
task_pool.execute(gid, move || {
sender.send(gid).unwrap();
});
}
for _ in 0..10 {
let sender = jtx.clone();
task_pool.execute(group_with_big_task, move || {
sender.send(group_with_big_task).unwrap();
});
}
frx.recv_timeout(timeout).unwrap();
task_pool.stop().unwrap();
}
#[test]
fn test_get_task_count() {
let name = thd_name!("test_get_task_count");
let concurrency = 1;
let mut task_pool = ThreadPool::new(name, concurrency, BigGroupThrottledQueue::new(1));
let (tx, rx) = channel();
let (ftx, frx) = channel();
let receiver = Arc::new(Mutex::new(rx));
let timeout = Duration::from_secs(2);
let group_num = 4;
let mut task_num = 0;
for gid in 0..group_num {
let rxer = receiver.clone();
let ftx = ftx.clone();
task_pool.execute(gid, move || {
let rx = rxer.lock().unwrap();
let id = rx.recv_timeout(timeout).unwrap();
assert_eq!(id, gid);
ftx.send(true).unwrap();
});
task_num += 1;
assert_eq!(task_pool.get_task_count(), task_num);
}
for gid in 0..group_num {
tx.send(gid).unwrap();
frx.recv_timeout(timeout).unwrap();
let left_num = task_pool.get_task_count();
// current task may be still running.
assert!(left_num == task_num || left_num == task_num - 1,
format!("left_num {},task_num {}", left_num, task_num));
task_num -= 1;
}
task_pool.stop().unwrap();
}
#[test]
fn test_throttled_queue() {
let mut queue = BigGroupThrottledQueue::new(1);
let mut id = 1;
// Push 4 tasks of `group1` into queue
let group1 = 1001;
for _ in 0..4 {
let mut task = Task::new(group1, move || {});
task.id = id;
id += 1;
queue.push(task);
}
// Push 4 tasks of `group2` into queue.
let group2 = 1002;
for _ in 0..4 {
let mut task = Task::new(group2, move || {});
task.id = id;
id += 1;
queue.push(task);
}
// queue: g1, g1, g1, g1, g2, g2, g2, g2. As all groups has a running number that is
// smaller than that of group_concurrency_limit, and g1 comes first.
let task = queue.pop().unwrap();
assert_eq!(task.gid, group1);
queue.on_task_started(&group1);
// queue: g1, g1, g1, g2, g2, g2, g2; running:g1.
// only g2 has a running number that is smaller than that of group_concurrency_limit.
let task = queue.pop().unwrap();
assert_eq!(task.gid, group2);
queue.on_task_started(&group2);
// queue: g1, g1, g1, g2, g2, g2; running:g1,g2. Since no group has a running number
// smaller than `group_concurrency_limit`, and each group's running number is
// the same, choose g1 since it comes first.
let task = queue.pop().unwrap();
assert_eq!(task.gid, group1);
queue.on_task_started(&group1);
// queue:g1, g1, g2, g2, g2; running:g1,g2,g1. Since no group has a running number
// smaller than `group_concurrency_limit`, and the running number of g2 is smaller,
// choose g2 since it comes first.
let task = queue.pop().unwrap();
assert_eq!(task.gid, group2);
queue.on_task_started(&group2);
}
#[test]
fn test_small_group_first_queue() {
let concurrency_limit = 2;
let small_group_tasks_limit = 2;
let mut queue = SmallGroupFirstQueue::new(concurrency_limit, small_group_tasks_limit);
let mut id = 1;
// high_priority_queue and low_priority_queue is both empty.
assert!(queue.pop().is_none());
// Push 2 tasks of `group1` into queue
let group1 = 1001;
for _ in 0..small_group_tasks_limit {
let mut task = Task::new(group1, move || {});
task.id = id;
id += 1;
queue.push(task);
}
// high:[g11,g12]; low:[]
assert!(queue.low_priority_queue.is_empty());
// low_priority_queue is empty
let task = queue.pop().unwrap();
let expect_task_id = 1;
assert_eq!(task.id, expect_task_id);
queue.on_task_started(&task.gid);
// high:[g12]; low:[];running:g11
for _ in 0..small_group_tasks_limit {
let mut task = Task::new(group1, move || {});
task.id = id;
id += 1;
queue.push(task);
}
// since g11(front in high) comes before g13(front in low),
// g11 would run first. high:[g12]; low:[g13,g14]; running:[g11]
assert_eq!(queue.low_priority_queue.len(), small_group_tasks_limit);
assert_eq!(queue.high_priority_queue.len(), small_group_tasks_limit - 1);
let group2 = 1002;
for _ in 0..small_group_tasks_limit {
let mut task = Task::new(group2, move || {});
task.id = id;
id += 1;
queue.push(task);
}
// high:[g12,g21,g22], low:[g13,g14], running:[g11]
let task = queue.pop().unwrap();
let expect_task_id = 2;
assert_eq!(task.id, expect_task_id);
queue.on_task_started(&task.gid);
// since g12(front in high) comes before g13(front in low),
// g12 would run first.
assert_eq!(queue.low_priority_queue.len(), small_group_tasks_limit);
// high:[g21,g22], low:[g13,g14], running:[g11,g12]
queue.on_task_finished(&task.gid);
// high:[g21,g22], low:[g13,g14], running:[g11]
let task = queue.pop().unwrap();
queue.on_task_started(&task.gid);
// since g13(font in low) comes before g21(front in high),
// and group g1's running number < group_concurrency_on_busy(2)
// g13 would run first.
assert_eq!(task.gid, group1);
// high:[g21,g22], low:[g14], running:[g11,g13]
let task = queue.pop().unwrap();
queue.on_task_started(&task.gid);
// since group g1's running number >= group_concurrency_on_busy(2),
// the task should be g21
assert_eq!(task.gid, group2);
// high:[g22], low:[g14], running:[g11,g13,g21]
let task = queue.pop().unwrap();
queue.on_task_started(&task.gid);
assert_eq!(task.gid, group2);
// high:[], low:[g14], running:[g11,g13,g21,g22]
let mut task = Task::new(group1, move || {});
task.id = id;
id += 1;
queue.push(task);
// since low_priority_queue_count of g1 > 0, g15 should be
// pushed into low_priority_queue
assert!(queue.high_priority_queue.is_empty());
assert_eq!(queue.low_priority_queue.len(), 2);
// push new job g23
// high:[], low:[g14,g15], running:[g11,g13,g21,g22]
let mut task = Task::new(group2, move || {});
task.id = id;
queue.push(task);
// since sum of running_count and high_priority_queue_count for
// g2 is 2 >= small_group_tasks_limit, the task g23 would be pushed
// into low_priority_queue
assert!(queue.high_priority_queue.is_empty());
// high:[], low:[g14,g15,g23], running:[g11,g13,g21,g22]
let task = queue.pop().unwrap();
queue.on_task_started(&task.gid);
assert_eq!(task.gid, group1);
}
#[test]
fn test_fifo_queue() {
let mut queue = FifoQueue::new();
for id in 0..10 {
let mut task = Task::new(0, move || {});
task.id = id;
queue.push(task);
}
for id in 0..10 {
let task = queue.pop().unwrap();
assert_eq!(id, task.id);
}
}
}
|
use crate::{Primitive, Renderer};
use iced_native::{radio, Background, MouseCursor, Rectangle};
const SIZE: f32 = 28.0;
const DOT_SIZE: f32 = SIZE / 2.0;
impl radio::Renderer for Renderer {
fn default_size(&self) -> u32 {
SIZE as u32
}
fn draw(
&mut self,
bounds: Rectangle,
is_selected: bool,
is_mouse_over: bool,
(label, _): Self::Output,
) -> Self::Output {
let (radio_border, radio_box) = (
Primitive::Quad {
bounds,
background: Background::Color([0.6, 0.6, 0.6].into()),
border_radius: (SIZE / 2.0) as u16,
},
Primitive::Quad {
bounds: Rectangle {
x: bounds.x + 1.0,
y: bounds.y + 1.0,
width: bounds.width - 2.0,
height: bounds.height - 2.0,
},
background: Background::Color(
if is_mouse_over {
[0.90, 0.90, 0.90]
} else {
[0.95, 0.95, 0.95]
}
.into(),
),
border_radius: (SIZE / 2.0 - 1.0) as u16,
},
);
(
Primitive::Group {
primitives: if is_selected {
let radio_circle = Primitive::Quad {
bounds: Rectangle {
x: bounds.x + DOT_SIZE / 2.0,
y: bounds.y + DOT_SIZE / 2.0,
width: bounds.width - DOT_SIZE,
height: bounds.height - DOT_SIZE,
},
background: Background::Color([0.3, 0.3, 0.3].into()),
border_radius: (DOT_SIZE / 2.0) as u16,
};
vec![radio_border, radio_box, radio_circle, label]
} else {
vec![radio_border, radio_box, label]
},
},
if is_mouse_over {
MouseCursor::Pointer
} else {
MouseCursor::OutOfBounds
},
)
}
}
|
test_stdout!(
without_normal_exit_in_child_process_sends_exit_message_to_parent,
"{child, exited, abnormal}\n"
);
test_stdout!(
with_normal_exit_in_child_process_sends_exit_message_to_parent,
"{child, exited, normal}\n"
);
|
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct Crate {
pub name: String,
pub description: Option<String>,
pub documentation: Option<String>,
pub repository: Option<String>,
pub recent_downloads: u32,
pub downloads: u32,
}
#[derive(Deserialize, Debug)]
pub struct Crates {
pub crates: Vec<Crate>,
}
#[derive(Debug)]
pub enum Error {
RequestError(reqwest::Error),
DeserializeError(serde_json::Error),
TelegramError(telegram_bot::Error),
}
impl From<reqwest::Error> for Error {
fn from(err: reqwest::Error) -> Error {
Error::RequestError(err)
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Error {
Error::DeserializeError(err)
}
}
pub async fn search(client: &reqwest::Client, crate_name: &str) -> Result<Crates, reqwest::Error> {
let req = client
.get(&format!("https://crates.io/api/v1/crates?q={}", crate_name))
.query(&[("q", crate_name)])
.build()?;
client.execute(req).await?.json().await
}
|
#![recursion_limit = "1024"]
extern crate stderrlog;
extern crate piston;
extern crate graphics;
extern crate gfx;
extern crate gfx_graphics;
extern crate gfx_device_gl;
extern crate sdl2_window;
extern crate serde;
extern crate serde_json;
extern crate mentat;
#[macro_use]
extern crate clap;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
mod events;
mod handlers;
mod store;
mod view;
mod errors {
use log;
use serde_json;
error_chain!{
foreign_links {
SerdeJson(serde_json::Error);
Io(::std::io::Error);
SetLogger(log::SetLoggerError);
}
}
}
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use sdl2_window::{Sdl2Window, OpenGL};
use gfx::traits::*;
use gfx::memory::Typed;
use gfx::format::{DepthStencil, Formatted, Srgba8};
use piston::window::{OpenGLWindow, Window, WindowSettings};
use piston::event_loop::{Events, EventSettings, EventLoop};
use gfx_graphics::{Gfx2d, GlyphCache, TextureSettings};
use graphics::*;
use errors::*;
use store::Store;
use view::Screen;
quick_main!(run);
fn run() -> Result<()> {
let matches = clap_app!(castel =>
(version: "alpha")
(@arg verbose: -v... "Log more or less")
(@arg INPUT: +required "File to edit")
).get_matches();
stderrlog::new()
.timestamp(stderrlog::Timestamp::Second)
.verbosity(matches.occurrences_of("v") as usize)
.init()?;
let mut input = String::new();
if let Some(path) = matches.value_of("INPUT") {
let mut file = File::open(path)?;
file.read_to_string(&mut input)?;
} else {
bail!("Required argument not given");
}
let conn = mentat::get_connection();
let mut data = Store::new();
data.insert(&input)?;
let opengl = OpenGL::V3_2;
let samples = 4;
let ref mut window: Sdl2Window = WindowSettings::new("castel", [200; 2])
.opengl(opengl)
.samples(4)
.build()?;
let (mut device, mut factory) = gfx_device_gl::create(|s| {
window.get_proc_address(s) as *const std::os::raw::c_void
});
let mut glyph_cache = GlyphCache::new(
Path::new("fonts/cmunbmr.ttf"),
factory.clone(),
TextureSettings::new(),
).expect("This error isn't good enough for error_chain");
let draw_size = window.draw_size();
let aa = samples as gfx::texture::NumSamples;
let dim = (
draw_size.width as u16,
draw_size.height as u16,
1,
aa.into(),
);
let color_format = <Srgba8 as Formatted>::get_format();
let depth_format = <DepthStencil as Formatted>::get_format();
let (output_color, output_stencil) =
gfx_device_gl::create_main_targets_raw(dim, color_format.0, depth_format.0);
let output_color = Typed::new(output_color);
let output_stencil = Typed::new(output_stencil);
let mut encoder = factory.create_command_buffer().into();
let mut g2d = Gfx2d::new(opengl, &mut factory);
let mut events = Events::new(EventSettings::new().lazy(true));
while let Some(e) = events.next(window) {
use piston::input::Input::*;
match e {
Render(args) => {
let screen = Screen::new(window.draw_size());
g2d.draw(
&mut encoder,
&output_color,
&output_stencil,
args.viewport(),
|c, g| {
clear([1.0; 4], g);
screen.render(&c, g);
text::Text::new_color([0.0, 0.5, 0.0, 1.0], 32).draw(
"Hello gfx_graphics!",
&mut glyph_cache,
&DrawState::default(),
c.transform.trans(
10.0,
100.0,
),
g,
);
},
);
encoder.flush(&mut device);
}
AfterRender(_) => {
device.cleanup();
}
Close(_) => {
break;
}
_ => {
if let Some(fact) = handlers::input(&e) {
data.apply(fact);
}
while let Some(changes) = data.take_changes() {
for new_change in changes {
if let Some(fact) = handlers::change(new_change) {
data.apply(fact);
}
}
}
}
}
}
Ok(())
}
|
use super::{Button, InputField, Panel, RectTransform, Text};
use crate::codec::{Decode, Encode};
use crate::{remote_type, RemoteObject};
remote_type!(
/// A canvas for user interface elements
object UI.Canvas {
properties: {
{
RectTransform {
/// Returns the rect transform for the canvas.
///
/// **Game Scenes**: All
get: rect_transform -> RectTransform
}
}
{
Visible {
/// Returns whether the UI object is visible.
///
/// **Game Scenes**: All
get: is_visible -> bool,
/// Sets whether the UI object is visible.
///
/// **Game Scenes**: All
set: set_visible(bool)
}
}
}
methods: {
{
/// Create a new container for user interface elements.
///
/// **Game Scenes**: All
///
/// # Arguments
/// * `visible` - Whether the panel is visible.
fn add_panel(visible: bool) -> Panel {
AddPanel(visible)
}
}
{
/// Add text to the canvas.
///
/// **Game Scenes**: All
///
/// # Arguments
/// * `content` – The text.
/// * `visible` - Whether the text is visible.
fn add_text(content: &str, visible: bool) -> Text {
AddText(content, visible)
}
}
{
/// Add an input field to the canvas.
///
/// **Game Scenes**: All
///
/// # Arguments
/// * `visible` - Whether the input field is visible.
fn add_input_field(visible: bool) -> InputField {
AddInputField(visible)
}
}
{
/// Add a button to the canvas.
///
/// **Game Scenes**: All
///
/// # Arguments
/// * `content` – The label for the button.
/// * `visible` - Whether the button is visible.
fn add_button(content: &str, visible: bool) -> Button {
AddButton(content, visible)
}
}
{
/// Remove the UI object.
///
/// **Game Scenes**: All
fn remove() {
Remove()
}
}
}
});
|
// 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 std::mem;
#[cfg(feature = "tracing")]
use fuchsia_trace::duration;
use crate::{
point::Point,
raster::{RasterSegments, RasterSegmentsIter},
segment::Segment,
tile::{LayerNode, Layers, Tile, TileOp, TILE_SIZE},
PIXEL_SHIFT, PIXEL_WIDTH,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PixelFormat {
RGBA8888,
BGRA8888,
RGB565,
}
pub trait ColorBuffer: Clone + Send + Sync {
fn pixel_format(&self) -> PixelFormat;
fn stride(&self) -> usize;
unsafe fn write_at(&mut self, offset: usize, src: *const u8, len: usize);
unsafe fn write_color_at<C: Copy + Sized>(&mut self, offset: usize, src: &[C]) {
let size = mem::size_of::<C>();
self.write_at(offset * size, src.as_ptr() as *const u8, src.len() * size);
}
}
#[derive(Debug)]
pub(crate) struct Context<'m, B: ColorBuffer> {
pub tile: &'m Tile,
pub index: usize,
pub width: usize,
pub height: usize,
pub layers: &'m Layers<'m>,
pub buffer: B,
}
#[derive(Clone, Copy, Debug)]
pub enum FillRule {
NonZero,
EvenOdd,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Cell {
pub area: i16,
pub cover: i8,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct Color {
pub blue: u8,
pub green: u8,
pub red: u8,
pub alpha: u8,
}
const ZERO: Color = Color { red: 0, green: 0, blue: 0, alpha: 0 };
const BLACK: Color = Color { red: 0, green: 0, blue: 0, alpha: 255 };
#[derive(Debug)]
pub struct Painter {
cells: Vec<Cell>,
cover_wip: Vec<u8>,
cover_acc: Vec<u8>,
cover_mask: Vec<u8>,
color_wip: Vec<Color>,
color_acc: Vec<Color>,
layer_index: usize,
}
#[derive(Clone, Debug)]
struct Segments<'t> {
tile: &'t Tile,
segments: &'t RasterSegments,
index: usize,
inner_segments: Option<RasterSegmentsIter<'t>>,
pub translation: Point<i32>,
}
impl<'t> Iterator for Segments<'t> {
type Item = Segment<i32>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(segments) = self.inner_segments.as_mut() {
if let Some(segment) = segments.next() {
return Some(segment);
}
}
if let Some(LayerNode::Segments(start_point, range)) = self.tile.layers.get(self.index) {
self.index += 1;
self.inner_segments = Some(self.segments.from(*start_point, range.clone()));
return self.next();
}
None
}
}
impl Painter {
pub fn new() -> Self {
Self {
cells: vec![Cell::default(); (TILE_SIZE + 1) * TILE_SIZE],
cover_wip: vec![0; TILE_SIZE * TILE_SIZE],
cover_acc: vec![0; TILE_SIZE * TILE_SIZE],
cover_mask: vec![0; TILE_SIZE * TILE_SIZE],
color_wip: vec![ZERO; TILE_SIZE * TILE_SIZE],
color_acc: vec![BLACK; TILE_SIZE * TILE_SIZE],
layer_index: 0,
}
}
fn index(i: usize, j: usize) -> usize {
i + j * TILE_SIZE
}
fn add(a: u8, b: u8) -> u8 {
let sum = u16::from(a) + u16::from(b);
if sum > 255 {
255
} else {
sum as u8
}
}
fn sub(a: u8, b: u8) -> u8 {
let difference = i16::from(a) - i16::from(b);
if difference < 0 {
0
} else {
difference as u8
}
}
fn mul(a: u8, b: u8) -> u8 {
let product = u16::from(a) * u16::from(b);
((product + 128 + (product >> 8)) >> 8) as u8
}
fn cover_wip_zero(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.cover_wip[i] = 0;
}
}
fn cell(&self, i: usize, j: usize) -> &Cell {
&self.cells[i + j * (TILE_SIZE + 1)]
}
fn cell_mut(&mut self, i: usize, j: usize) -> &mut Cell {
&mut self.cells[i + j * (TILE_SIZE + 1)]
}
fn cover_line(&mut self, segment: &Segment<i32>) {
let border = segment.border();
let i = border.x >> PIXEL_SHIFT;
let j = border.y >> PIXEL_SHIFT;
if i < TILE_SIZE as i32 && j >= 0 && j < TILE_SIZE as i32 {
if i >= 0 {
let mut cell = self.cell_mut(i as usize + 1, j as usize);
cell.area += segment.double_signed_area();
cell.cover += segment.cover();
} else {
let mut cell = self.cell_mut(0, j as usize);
cell.cover += segment.cover();
}
}
}
fn get_area(mut full_area: i32, fill_rule: FillRule) -> u8 {
match fill_rule {
FillRule::NonZero => {
if full_area < 0 {
Self::get_area(-full_area, fill_rule)
} else if full_area >= 256 {
255
} else {
full_area as u8
}
}
FillRule::EvenOdd => {
let mut number = full_area / 256;
if full_area < 0 {
full_area -= 1;
number -= 1;
}
let capped = (full_area % 256 + 256) % 256;
let area = if number % 2 == 0 { capped } else { 255 - capped };
area as u8
}
}
}
fn accumulate(&mut self, fill_rule: FillRule) {
for j in 0..TILE_SIZE {
let mut cover = 0;
for i in 0..=TILE_SIZE {
let cell = self.cell(i, j);
let old_cover = cover;
cover += cell.cover;
if i != 0 {
let area = PIXEL_WIDTH * i32::from(old_cover) + i32::from(cell.area) / 2;
let index = Self::index(i - 1, j);
let area =
self.cover_wip[index].saturating_add(Self::get_area(area, fill_rule));
self.cover_wip[index] = area;
}
}
}
}
fn cover_wip(
&mut self,
segments: impl Iterator<Item = Segment<i32>> + Clone,
translation: Point<i32>,
tile_i: usize,
tile_j: usize,
fill_rule: FillRule,
) {
let delta = Point::new(
(translation.x - (tile_i * TILE_SIZE) as i32) * PIXEL_WIDTH,
(translation.y - (tile_j * TILE_SIZE) as i32) * PIXEL_WIDTH,
);
for i in 0..TILE_SIZE * (TILE_SIZE + 1) {
self.cells[i] = Cell::default();
}
for segment in segments {
self.cover_line(&Segment::new(
Point::new(segment.p0.x + delta.x, segment.p0.y + delta.y),
Point::new(segment.p1.x + delta.x, segment.p1.y + delta.y),
));
}
self.accumulate(fill_rule);
}
fn cover_wip_mask(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.cover_wip[i] = Self::mul(self.cover_wip[i], self.cover_mask[i]);
}
}
fn cover_acc_zero(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.cover_acc[i] = 0;
}
}
fn cover_acc_accumulate(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
let contrib = Self::mul(Self::sub(255, self.cover_acc[i]), self.cover_wip[i]);
self.cover_acc[i] = Self::add(self.cover_acc[i], contrib);
}
}
fn cover_mask_zero(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.cover_mask[i] = 0;
}
}
fn cover_mask_one(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.cover_mask[i] = 255;
}
}
fn cover_mask_copy_from_wip(&mut self) {
self.cover_mask.copy_from_slice(&self.cover_wip);
}
fn cover_mask_copy_from_acc(&mut self) {
self.cover_mask.copy_from_slice(&self.cover_acc);
}
fn cover_mask_invert(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.cover_mask[i] = Self::sub(255, self.cover_mask[i]);
}
}
fn color_wip_zero(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.color_wip[i] = ZERO;
}
}
fn color_wip_fill_solid(&mut self, color: u32) {
let [red, green, blue, alpha] = color.to_be_bytes();
let color = Color { red, green, blue, alpha };
for i in 0..TILE_SIZE * TILE_SIZE {
self.color_wip[i] = color;
}
}
fn color_acc_zero(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
self.color_acc[i] = BLACK;
}
}
fn color_acc_blend_over(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
let wip = self.color_wip[i];
let acc = self.color_acc[i];
let cover = Self::mul(self.cover_wip[i], acc.alpha);
let red = Self::add(Self::mul(cover, wip.red), acc.red);
let green = Self::add(Self::mul(cover, wip.green), acc.green);
let blue = Self::add(Self::mul(cover, wip.blue), acc.blue);
let alpha = Self::sub(acc.alpha, Self::mul(cover, wip.alpha));
self.color_acc[i] = Color { red, green, blue, alpha };
}
}
fn color_acc_blend_add(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
let wip = self.color_wip[i];
let acc = self.color_acc[i];
let cover_min = self.cover_wip[i].min(acc.alpha);
let red = Self::add(Self::mul(cover_min, wip.red), acc.red);
let green = Self::add(Self::mul(cover_min, wip.green), acc.green);
let blue = Self::add(Self::mul(cover_min, wip.blue), acc.blue);
let alpha = Self::sub(acc.alpha, Self::mul(cover_min, wip.alpha));
self.color_acc[i] = Color { red, green, blue, alpha };
}
}
fn color_acc_blend_multiply(&mut self) {
for i in 0..TILE_SIZE * TILE_SIZE {
let wip = self.color_wip[i];
let acc = self.color_acc[i];
let red = Self::mul(Self::mul(self.cover_wip[i], wip.red), acc.red);
let green = Self::mul(Self::mul(self.cover_wip[i], wip.green), acc.green);
let blue = Self::mul(Self::mul(self.cover_wip[i], wip.blue), acc.blue);
let alpha =
Self::mul(Self::mul(self.cover_wip[i], wip.alpha), Self::sub(255, acc.alpha));
self.color_acc[i] = Color { red, green, blue, alpha };
}
}
fn color_acc_background(&mut self, color: u32) {
for i in 0..TILE_SIZE * TILE_SIZE {
let acc = self.color_acc[i];
let [red, green, blue, _] = color.to_be_bytes();
let red = Self::add(Self::mul(acc.alpha, red), acc.red);
let green = Self::add(Self::mul(acc.alpha, green), acc.green);
let blue = Self::add(Self::mul(acc.alpha, blue), acc.blue);
self.color_acc[i] = Color { red, green, blue, alpha: acc.alpha };
}
}
fn process_layer<'a, 'b, B: ColorBuffer>(
&'a mut self,
context: &'b Context<B>,
) -> Option<(Segments<'b>, &'b [TileOp])> {
let tile = &context.tile;
if let Some(layer) = tile.layers.get(self.layer_index) {
self.layer_index += 1;
let next_index = tile.layers[self.layer_index..]
.iter()
.enumerate()
.find(|(_, layer)| match layer {
LayerNode::Layer(..) => true,
_ => false,
})
.map(|(i, _)| i)
.unwrap_or_else(|| tile.layers.len() - self.layer_index);
let (segments, translation, ops) = match layer {
LayerNode::Layer(id, translation) => {
let layers = &context.layers;
if let (Some(segments), Some(ops)) = (layers.segments(id), layers.ops(id)) {
(segments, *translation, ops)
} else {
// Skip Layers that are not present in the Map anymore.
self.layer_index += next_index;
return self.process_layer(context);
}
}
_ => panic!(
"self.layer_index must not point at a Layer::Segments before \
Painter::process_layer"
),
};
let segments = Segments {
tile,
segments,
index: self.layer_index,
inner_segments: None,
translation,
};
self.layer_index += next_index;
return Some((segments, &ops));
}
None
}
unsafe fn write_row<B: ColorBuffer>(buffer: &mut B, index: usize, row: &[Color]) {
match buffer.pixel_format() {
PixelFormat::RGBA8888 => {
let mut new_row = [ZERO; TILE_SIZE];
for (i, color) in row.iter().enumerate() {
new_row[i] = Color {
blue: color.red,
green: color.green,
red: color.blue,
alpha: color.alpha,
}
}
buffer.write_color_at(index, &new_row[0..row.len()]);
}
PixelFormat::BGRA8888 => buffer.write_color_at(index, row),
PixelFormat::RGB565 => {
let mut new_row = [0u16; TILE_SIZE];
for (i, color) in row.iter().enumerate() {
let red = u16::from(Self::mul(color.alpha, color.red));
let green = u16::from(Self::mul(color.alpha, color.green));
let blue = u16::from(Self::mul(color.alpha, color.blue));
let red = ((red >> 3) & 0x1F) << 11;
let green = ((green >> 2) & 0x3F) << 5;
let blue = (blue >> 3) & 0x1F;
new_row[i] = red | green | blue;
}
buffer.write_color_at(index, &new_row[0..row.len()]);
}
}
}
pub(crate) fn execute<B: ColorBuffer>(&mut self, mut context: Context<B>) {
#[cfg(feature = "tracing")]
duration!(
"gfx",
"Painter::execute",
"i" => context.tile.tile_i as u64,
"j" => context.tile.tile_j as u64
);
while let Some((segments, ops)) = self.process_layer(&context) {
for op in ops {
#[cfg(feature = "tracing")]
duration!("gfx:mold", "Painter::execute_op", "op" => op.name());
match op {
TileOp::CoverWipZero => self.cover_wip_zero(),
TileOp::CoverWipNonZero => self.cover_wip(
segments.clone(),
segments.translation,
context.tile.tile_i,
context.tile.tile_j,
FillRule::NonZero,
),
TileOp::CoverWipEvenOdd => self.cover_wip(
segments.clone(),
segments.translation,
context.tile.tile_i,
context.tile.tile_j,
FillRule::EvenOdd,
),
TileOp::CoverWipMask => self.cover_wip_mask(),
TileOp::CoverAccZero => self.cover_acc_zero(),
TileOp::CoverAccAccumulate => self.cover_acc_accumulate(),
TileOp::CoverMaskZero => self.cover_mask_zero(),
TileOp::CoverMaskOne => self.cover_mask_one(),
TileOp::CoverMaskCopyFromWip => self.cover_mask_copy_from_wip(),
TileOp::CoverMaskCopyFromAcc => self.cover_mask_copy_from_acc(),
TileOp::CoverMaskInvert => self.cover_mask_invert(),
TileOp::ColorWipZero => self.color_wip_zero(),
TileOp::ColorWipFillSolid(color) => self.color_wip_fill_solid(*color),
TileOp::ColorAccZero => self.color_acc_zero(),
TileOp::ColorAccBlendOver => self.color_acc_blend_over(),
TileOp::ColorAccBlendAdd => self.color_acc_blend_add(),
TileOp::ColorAccBlendMultiply => self.color_acc_blend_multiply(),
TileOp::ColorAccBackground(color) => self.color_acc_background(*color),
}
}
}
for tile_j in 0..TILE_SIZE {
let x = context.tile.tile_i * TILE_SIZE;
let y = context.tile.tile_j * TILE_SIZE + tile_j;
if y < context.height {
let buffer_index = x + y * context.buffer.stride();
let tile_index = tile_j * TILE_SIZE;
let d = (context.width - x).min(TILE_SIZE);
let tile_range = tile_index..tile_index + d;
unsafe {
Self::write_row(&mut context.buffer, buffer_index, &self.color_acc[tile_range]);
}
}
}
self.layer_index = 0;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
path::Path,
point::Point,
raster::Raster,
tile::{Layer, Map},
};
fn polygon(path: &mut Path, points: &[(f32, f32)]) {
for window in points.windows(2) {
path.line(Point::new(window[0].0, window[0].1), Point::new(window[1].0, window[1].1));
}
if let (Some(first), Some(last)) = (points.first(), points.last()) {
path.line(Point::new(last.0, last.1), Point::new(first.0, first.1));
}
}
fn get_cover(width: usize, height: usize, raster: &Raster, fill_rule: FillRule) -> Vec<u8> {
let mut painter = Painter::new();
painter.cover_wip(raster.segments().iter(), Point::new(0, 0), 0, 0, fill_rule);
let mut cover = Vec::with_capacity(width * height);
for j in 0..height {
for i in 0..width {
cover.push(painter.cover_wip[i + j * TILE_SIZE]);
}
}
cover
}
#[test]
fn triangle() {
let mut path = Path::new();
path.line(Point::new(0.0, 0.0), Point::new(2.0, 2.0));
path.line(Point::new(2.0, 2.0), Point::new(4.0, 0.0));
assert_eq!(
get_cover(4, 2, &Raster::new(&path), FillRule::NonZero),
vec![128, 255, 255, 128, 0, 128, 128, 0],
);
}
#[test]
fn out_of_bounds() {
let mut path = Path::new();
let ex = 2.0f32.sqrt() / 2.0;
polygon(&mut path, &[(0.5, 0.5 + ex), (0.5 + ex, 0.5), (0.5, 0.5 - ex), (0.5 - ex, 0.5)]);
assert_eq!(get_cover(1, 1, &Raster::new(&path), FillRule::NonZero), vec![206]);
}
#[test]
fn non_zero() {
let mut path = Path::new();
polygon(&mut path, &[(1.0, 3.0), (2.0, 3.0), (2.0, 0.0), (1.0, 0.0)]);
polygon(&mut path, &[(0.0, 2.0), (3.0, 2.0), (3.0, 1.0), (0.0, 1.0)]);
assert_eq!(
get_cover(3, 3, &Raster::new(&path), FillRule::NonZero),
vec![0, 255, 0, 255, 255, 255, 0, 255, 0],
);
}
#[test]
fn non_zero_reversed() {
let mut path = Path::new();
polygon(&mut path, &[(1.0, 3.0), (1.0, 0.0), (2.0, 0.0), (2.0, 3.0)]);
polygon(&mut path, &[(0.0, 2.0), (3.0, 2.0), (3.0, 1.0), (0.0, 1.0)]);
assert_eq!(
get_cover(3, 3, &Raster::new(&path), FillRule::NonZero),
vec![0, 255, 0, 255, 0, 255, 0, 255, 0],
);
}
#[test]
fn even_odd() {
let mut path = Path::new();
polygon(&mut path, &[(1.0, 3.0), (2.0, 3.0), (2.0, 0.0), (1.0, 0.0)]);
polygon(&mut path, &[(0.0, 2.0), (3.0, 2.0), (3.0, 1.0), (0.0, 1.0)]);
assert_eq!(
get_cover(3, 3, &Raster::new(&path), FillRule::EvenOdd),
vec![0, 255, 0, 255, 0, 255, 0, 255, 0],
);
}
fn draw_bands(
color_vertical: u32,
color_horizontal: u32,
color_background: u32,
blend_op: TileOp,
) -> Map {
let mut map = Map::new(3, 3);
let mut band_vertical = Path::new();
polygon(&mut band_vertical, &[(1.0, 3.0), (2.0, 3.0), (2.0, 0.0), (1.0, 0.0)]);
let mut band_horizontal = Path::new();
polygon(&mut band_horizontal, &[(0.0, 2.0), (3.0, 2.0), (3.0, 1.0), (0.0, 1.0)]);
map.global(0, vec![TileOp::ColorAccZero]);
map.print(
1,
Layer::new(
Raster::new(&band_vertical),
vec![
TileOp::CoverWipZero,
TileOp::CoverWipNonZero,
TileOp::ColorWipZero,
TileOp::ColorWipFillSolid(color_vertical),
blend_op,
],
),
);
map.print(
2,
Layer::new(
Raster::new(&band_horizontal),
vec![
TileOp::CoverWipZero,
TileOp::CoverWipNonZero,
TileOp::ColorWipZero,
TileOp::ColorWipFillSolid(color_horizontal),
blend_op,
],
),
);
map.global(3, vec![TileOp::ColorAccBackground(color_background)]);
map
}
#[test]
fn blend_over() {
assert_eq!(
draw_bands(0x2200_00FF, 0x0022_00FF, 0x0000_22FF, TileOp::ColorAccBlendOver)
.render_to_bitmap(),
vec![
0xFF22_0000,
0x0000_0022,
0xFF22_0000,
0x0000_2200,
0x0000_0022,
0x0000_2200,
0xFF22_0000,
0x0000_0022,
0xFF22_0000,
],
);
}
#[test]
fn blend_over_then_remove() {
let mut map = draw_bands(0x2200_00FF, 0x0022_00FF, 0x0000_22FF, TileOp::ColorAccBlendOver);
assert_eq!(
map.render_to_bitmap(),
vec![
0xFF22_0000,
0x0000_0022,
0xFF22_0000,
0x0000_2200,
0x0000_0022,
0x0000_2200,
0xFF22_0000,
0x0000_0022,
0xFF22_0000,
],
);
map.remove(1);
assert_eq!(
map.render_to_bitmap(),
vec![
0xFF22_0000,
0xFF22_0000,
0xFF22_0000,
0x0000_2200,
0x0000_2200,
0x0000_2200,
0xFF22_0000,
0xFF22_0000,
0xFF22_0000,
],
);
}
#[test]
fn subtle_opacity_accumulation() {
assert_eq!(
draw_bands(0x0000_0001, 0x0000_0001, 0x0000_0001, TileOp::ColorAccBlendOver)
.render_to_bitmap(),
vec![
0xFF00_0000,
0xFE00_0000,
0xFF00_0000,
0xFE00_0000,
0xFD00_0000,
0xFE00_0000,
0xFF00_0000,
0xFE00_0000,
0xFF00_0000,
],
);
}
#[derive(Clone)]
struct DebugBuffer {
buffer: [u8; 4],
format: PixelFormat,
}
impl DebugBuffer {
fn new(format: PixelFormat) -> Self {
Self { buffer: [0; 4], format }
}
fn write(&mut self, color: Color) -> [u8; 4] {
unsafe {
Painter::write_row(self, 0, &[color]);
}
self.buffer
}
}
impl ColorBuffer for DebugBuffer {
fn pixel_format(&self) -> PixelFormat {
self.format
}
fn stride(&self) -> usize {
0
}
unsafe fn write_at(&mut self, _: usize, mut src: *const u8, len: usize) {
for i in 0..4.min(len) {
self.buffer[i] = src.read();
src = src.add(1);
}
}
}
#[test]
fn pixel_formats() {
assert_eq!(
DebugBuffer::new(PixelFormat::RGBA8888).write(Color {
red: 10,
green: 20,
blue: 30,
alpha: 255,
}),
[10, 20, 30, 255]
);
assert_eq!(
DebugBuffer::new(PixelFormat::BGRA8888).write(Color {
red: 10,
green: 20,
blue: 30,
alpha: 255,
}),
[30, 20, 10, 255]
);
assert_eq!(
DebugBuffer::new(PixelFormat::RGB565).write(Color {
red: 10,
green: 20,
blue: 30,
alpha: 255,
}),
[163, 8, 0, 0]
);
}
}
|
// 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::fmt::Display;
use anyerror::AnyError;
use serde::Deserialize;
use serde::Serialize;
use thiserror::Error;
use tonic::Code;
// represent network related errors
#[derive(Error, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum MetaNetworkError {
#[error(transparent)]
ConnectionError(#[from] ConnectionError),
#[error("{0}")]
GetNodeAddrError(String),
#[error("{0}")]
DnsParseError(String),
#[error(transparent)]
TLSConfigError(AnyError),
#[error(transparent)]
BadAddressFormat(AnyError),
#[error(transparent)]
InvalidArgument(#[from] InvalidArgument),
#[error(transparent)]
InvalidReply(#[from] InvalidReply),
}
impl MetaNetworkError {
pub fn add_context(self, context: impl Display) -> Self {
match self {
Self::ConnectionError(e) => e.add_context(context).into(),
Self::GetNodeAddrError(e) => Self::GetNodeAddrError(format!("{}: {}", e, context)),
Self::DnsParseError(e) => Self::DnsParseError(format!("{}: {}", e, context)),
Self::TLSConfigError(e) => Self::TLSConfigError(e.add_context(|| context)),
Self::BadAddressFormat(e) => Self::BadAddressFormat(e.add_context(|| context)),
Self::InvalidArgument(e) => e.add_context(context).into(),
Self::InvalidReply(e) => e.add_context(context).into(),
}
}
}
pub type MetaNetworkResult<T> = std::result::Result<T, MetaNetworkError>;
#[derive(Error, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[error("ConnectionError: {msg} source: {source}")]
pub struct ConnectionError {
msg: String,
#[source]
source: AnyError,
}
impl ConnectionError {
pub fn new(source: impl std::error::Error + 'static, msg: impl Into<String>) -> Self {
Self {
msg: msg.into(),
source: AnyError::new(&source),
}
}
pub fn add_context(mut self, context: impl Display) -> Self {
self.msg = format!("{}: {}", self.msg, context);
self
}
}
#[derive(Error, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[error("InvalidArgument: {msg} source: {source}")]
pub struct InvalidArgument {
msg: String,
#[source]
source: AnyError,
}
impl InvalidArgument {
pub fn new(source: impl std::error::Error + 'static, msg: impl Into<String>) -> Self {
Self {
msg: msg.into(),
source: AnyError::new(&source),
}
}
pub fn add_context(mut self, context: impl Display) -> Self {
self.msg = format!("{}: {}", self.msg, context);
self
}
}
#[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[error("InvalidReply: {msg} source: {source}")]
pub struct InvalidReply {
msg: String,
#[source]
source: AnyError,
}
impl InvalidReply {
pub fn new(msg: impl Display, source: &(impl std::error::Error + 'static)) -> Self {
Self {
msg: msg.to_string(),
source: AnyError::new(source),
}
}
pub fn add_context(mut self, context: impl Display) -> Self {
self.msg = format!("{}: {}", self.msg, context);
self
}
}
impl From<std::net::AddrParseError> for MetaNetworkError {
fn from(error: std::net::AddrParseError) -> Self {
MetaNetworkError::BadAddressFormat(AnyError::new(&error))
}
}
impl From<tonic::Status> for MetaNetworkError {
fn from(status: tonic::Status) -> Self {
match status.code() {
Code::InvalidArgument => {
MetaNetworkError::InvalidArgument(InvalidArgument::new(status, ""))
}
// Code::Ok => {}
// Code::Cancelled => {}
// Code::Unknown => {}
// Code::DeadlineExceeded => {}
// Code::NotFound => {}
// Code::AlreadyExists => {}
// Code::PermissionDenied => {}
// Code::ResourceExhausted => {}
// Code::FailedPrecondition => {}
// Code::Aborted => {}
// Code::OutOfRange => {}
// Code::Unimplemented => {}
// Code::Internal => {}
// Code::Unavailable => {}
// Code::DataLoss => {}
// Code::Unauthenticated => {}
_ => MetaNetworkError::ConnectionError(ConnectionError::new(status, "")),
}
}
}
impl From<tonic::transport::Error> for MetaNetworkError {
fn from(err: tonic::transport::Error) -> Self {
MetaNetworkError::ConnectionError(ConnectionError::new(err, ""))
}
}
|
use yew::prelude::*;
// use yew_router::components::RouterAnchor;
// use crate::app::AppRoute;
pub struct SettingsSigningKeys {}
impl Component for SettingsSigningKeys {
type Message = ();
type Properties = ();
fn create(_: Self::Properties, _link: ComponentLink<Self>) -> Self {
SettingsSigningKeys {}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<div>
<div
class="mb-5"
>
<h5
class="mb-2"
>
{"Signing Keys"}
</h5>
<p>{"Securely manage signing keys used by the applications in your tenant. "}</p>
</div>
<div
class="mb-5"
>
<div
class="mb-4"
>
<h5
class="mb-2"
>
{"Rotation Settings"}
</h5>
<p>{"The actions below allow you to rotate the signing key and certificate used to validate tokens. You can see the next in queue valid signing key in the table below for updating your application’s configuration before the rotation."}</p>
</div>
<div
class="border rounded p-4 mb-4"
>
<div
class="d-flex border-bottom pb-5"
>
<div
class="flex-fill"
>
<div
class="fw-bolder mb-1"
style="font-size: 16px;"
>
{"Rotate Signing Keys"}
</div>
<div>
{"This will only rotate the currently used signing key. All tokens signed with this key will continue to be valid."}
</div>
</div>
<button type="button" class="btn btn-light">{"Rotate Key"}</button>
</div>
<div
class="d-flex pt-5 pb-5"
>
<div
class="flex-fill"
>
<div
class="fw-bolder mb-1"
style="font-size: 16px;"
>
{"Rotate & Revoke Signing Key"}
</div>
<div>
{"This will rotate and additionally revoke the currently used signing key and all tokens signed with this key will no longer be valid."}
</div>
</div>
<button type="button" class="btn btn-danger">{"Rotate & Revoke Key"}</button>
</div>
</div>
</div>
<div
class="mb-5"
>
<div
class="mb-4"
>
<h5
class="mb-2"
>
{"List of Valid Keys"}
</h5>
<p>{"This is a list of valid keys for your tenant. They are also available at the "}</p>
</div>
<table class="table">
<thead>
<tr>
<th scope="col" class="p-3">{"Status"}</th>
<th scope="col" class="p-3">{"Key ID"}</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<td
class="p-3"
>
<span
class="badge bg-primary fw-bolder"
style="text-transform: uppercase; letter-spacing: 1px; font-size: 10px;"
>{"next in queue"}</span>
</td>
<td
class="p-3 flex-fill"
>
<span
class="rounded"
style="
background-color: #eff0f2;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
font-size: 14px;
padding: 2px 6px;
font-family: 'Roboto Mono', monospace;
"
>
{"OlHlmtYtepG9mSCiEwurY"}
</span>
</td>
<td
class="p-3"
>
<div
class="d-flex justify-content-end align-items-center dropdown"
>
<button
type="button"
style="flex: 0 0 auto; width: 30px; height: 30px;"
class="btn d-flex justify-content-center align-items-center rounded border"
role="button"
id="dropdownMenuButton1"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<i class="bi bi-three-dots"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li>
<span class="dropdown-item fs-7">
{"Settings"}
</span>
</li>
</ul>
</div>
</td>
</tr>
<tr>
<td
class="p-3"
>
<span
class="badge bg-success fw-bolder"
style="text-transform: uppercase; letter-spacing: 1px; font-size: 10px;"
>{"currently used"}</span>
</td>
<td
class="p-3 flex-fill"
>
<span
class="rounded"
style="
background-color: #eff0f2;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
font-size: 14px;
padding: 2px 6px;
font-family: 'Roboto Mono', monospace;
"
>
{"4r7Fyp-RVC01VIgO5X6hc"}
</span>
</td>
<td
class="p-3"
>
<div
class="d-flex justify-content-end align-items-center dropdown"
>
<button
type="button"
style="flex: 0 0 auto; width: 30px; height: 30px;"
class="btn d-flex justify-content-center align-items-center rounded border"
role="button"
id="dropdownMenuButton1"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<i class="bi bi-three-dots"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li>
<span class="dropdown-item fs-7">
{"Settings"}
</span>
</li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div
class="mb-5"
>
<div
class="mb-4"
>
<h5
class="mb-2"
>
{"List of Revoked Keys"}
</h5>
<p>{"This is a list of the last 3 revoked keys for your tenant. Further data for revocation is available via tenant logs."}</p>
</div>
<table class="table">
<thead>
<tr>
<th scope="col" class="p-3">{"Revoked on"}</th>
<th scope="col" class="p-3">{"Key ID"}</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div
class="mt-3 p-3 text-center"
style="background-color: #eff0f2;"
>
{"There are no items to display"}
</div>
</div>
</div>
}
}
}
|
/// membership database
use std::string::String;
use std::error::Error;
use uuid::Uuid;
use argon2::{password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Argon2
};
use rand_core::OsRng;
#[derive(Debug, Serialize, Deserialize)]
pub struct MemberID (Uuid);
impl MemberID {
pub fn new() -> MemberID {
MemberID ( Uuid::new_v4() )
}
}
impl ToString for MemberID {
fn to_string( &self ) -> String {
self.0.to_simple().to_string()
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Member {
pub id: MemberID,
pub email: String,
pub pass_hash: String,
}
impl Member {
pub fn new( email: &String, password: &String ) -> Member {
Member {
id: MemberID::new(),
email: email.clone(),
pass_hash: hash_password( password ).unwrap(),
}
}
}
fn hash_password(password: &String) -> Option<String> {
match Argon2::default()
.hash_password_simple(
password.as_bytes(),
SaltString::generate(&mut OsRng).as_ref()
) {
Ok(n) => Some(n.to_string()),
Err(..) => None
}
}
pub fn authenticate_member(email: &String, password: &String) -> bool {
false
}
#[cfg(test)]
mod test{
use std::string::String;
use argon2::{Argon2, password_hash::{PasswordVerifier, PasswordHash}};
use super::{MemberID, Member};
#[test]
fn test_hash_password() {
let pwd = "password".to_string();
let password_hash_result = super::hash_password(&pwd);
assert!( password_hash_result.is_some());
let password_hash = password_hash_result.unwrap();
let parsed_hash = PasswordHash::new(&password_hash).unwrap();
assert!(Argon2::default().verify_password(&pwd.as_bytes(), &parsed_hash).is_ok());
}
#[test]
fn test_memberid_new() {
let member_id = MemberID::new().to_string();
println!("Member ID: {}", member_id);
assert_eq!(member_id.len(), 32);
}
} |
/*
Config数据结构
* addr :websocket协议的服务器地址。
* local_sign : 交易数据是否要本地签名后再发送。
* true -> 本地签名; false -> 不签名。
*/
#[derive(Debug)]
pub struct Config {
pub addr : &'static str,
pub local_sign : bool,
}
impl Config {
pub fn new(addr: &'static str, local_sign: bool) -> Self {
Config {
addr: addr,
local_sign: local_sign,
}
}
}
|
#![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 DataProtectionProvider(pub ::windows::core::IInspectable);
impl DataProtectionProvider {
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<DataProtectionProvider, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ProtectAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(&self, data: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::super::super::Storage::Streams::IBuffer>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), data.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<super::super::super::Storage::Streams::IBuffer>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn UnprotectAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(&self, data: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::super::super::Storage::Streams::IBuffer>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), data.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<super::super::super::Storage::Streams::IBuffer>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ProtectStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IInputStream>, Param1: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IOutputStream>>(&self, src: Param0, dest: Param1) -> ::windows::core::Result<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), src.into_param().abi(), dest.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn UnprotectStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IInputStream>, Param1: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IOutputStream>>(&self, src: Param0, dest: Param1) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), src.into_param().abi(), dest.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
pub fn CreateOverloadExplicit<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(protectiondescriptor: Param0) -> ::windows::core::Result<DataProtectionProvider> {
Self::IDataProtectionProviderFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), protectiondescriptor.into_param().abi(), &mut result__).from_abi::<DataProtectionProvider>(result__)
})
}
pub fn IDataProtectionProviderFactory<R, F: FnOnce(&IDataProtectionProviderFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<DataProtectionProvider, IDataProtectionProviderFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for DataProtectionProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Cryptography.DataProtection.DataProtectionProvider;{09639948-ed22-4270-bd1c-6d72c00f8787})");
}
unsafe impl ::windows::core::Interface for DataProtectionProvider {
type Vtable = IDataProtectionProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09639948_ed22_4270_bd1c_6d72c00f8787);
}
impl ::windows::core::RuntimeName for DataProtectionProvider {
const NAME: &'static str = "Windows.Security.Cryptography.DataProtection.DataProtectionProvider";
}
impl ::core::convert::From<DataProtectionProvider> for ::windows::core::IUnknown {
fn from(value: DataProtectionProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&DataProtectionProvider> for ::windows::core::IUnknown {
fn from(value: &DataProtectionProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DataProtectionProvider {
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 DataProtectionProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<DataProtectionProvider> for ::windows::core::IInspectable {
fn from(value: DataProtectionProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&DataProtectionProvider> for ::windows::core::IInspectable {
fn from(value: &DataProtectionProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DataProtectionProvider {
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 DataProtectionProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for DataProtectionProvider {}
unsafe impl ::core::marker::Sync for DataProtectionProvider {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IDataProtectionProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDataProtectionProvider {
type Vtable = IDataProtectionProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09639948_ed22_4270_bd1c_6d72c00f8787);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDataProtectionProvider_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(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, data: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, data: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, src: ::windows::core::RawPtr, dest: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, src: ::windows::core::RawPtr, dest: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IDataProtectionProviderFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDataProtectionProviderFactory {
type Vtable = IDataProtectionProviderFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xadf33dac_4932_4cdf_ac41_7214333514ca);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDataProtectionProviderFactory_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, protectiondescriptor: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
|
//! This module provides `Allocator` trait and few allocators that implements the trait.
use std::{any::Any, fmt};
mod arena;
mod dedicated;
mod dynamic;
// mod chunk;
use block::Block;
use device::Device;
use error::MemoryError;
use memory::Memory;
pub use self::{
arena::{ArenaAllocator, ArenaBlock, ArenaConfig},
dedicated::{DedicatedAllocator, DedicatedBlock},
dynamic::{DynamicAllocator, DynamicBlock, DynamicConfig},
};
/// Allocator trait implemented for various allocators.
pub trait Allocator {
/// Memory type.
type Memory: Any;
/// Block type returned by allocator.
type Block: Block<Memory = Self::Memory>;
/// Allocate block of memory.
/// On success returns allocated block and amount of memory consumed from device.
fn alloc<D>(
&mut self,
device: &D,
size: u64,
align: u64,
) -> Result<(Self::Block, u64), MemoryError>
where
D: Device<Memory = Self::Memory>;
/// Free block of memory.
/// Returns amount of memory returned to the device.
fn free<D>(&mut self, device: &D, block: Self::Block) -> u64
where
D: Device<Memory = Self::Memory>;
}
fn memory_ptr_fmt<T: fmt::Debug>(
memory: &*const Memory<T>,
fmt: &mut fmt::Formatter<'_>,
) -> Result<(), fmt::Error> {
unsafe {
if fmt.alternate() {
write!(fmt, "*const {:#?}", **memory)
} else {
write!(fmt, "*const {:?}", **memory)
}
}
}
|
use ggez::graphics::Rect;
pub fn generate_uvs(i_width: f32, i_height: f32, t_width: f32, t_height: f32) -> Vec<Rect> {
let width = t_width / i_width;
let height = t_height / i_height;
let cols = i_width / t_width;
let rows = i_height / t_height;
let mut ux: f32 = 0.0;
let mut uy: f32 = 0.0;
let mut uvs = Vec::new();
for _ in 0..(rows as u32) {
for _ in 0..(cols as u32) {
uvs.push(Rect::new(ux, uy, width, height));
ux += width;
}
ux = 0.0;
uy += height;
}
return uvs;
}
|
use std::collections::HashMap;
use crate::{ContractsStorageTree, StorageCommitmentTree};
use anyhow::Context;
use pathfinder_common::{
ClassHash, ContractAddress, ContractNonce, ContractRoot, ContractStateHash, StorageAddress,
StorageValue,
};
use pathfinder_storage::Transaction;
use stark_hash::{stark_hash, Felt};
/// Updates a contract's state with and returns the resulting [ContractStateHash].
pub fn update_contract_state(
contract_address: ContractAddress,
updates: &HashMap<StorageAddress, StorageValue>,
new_nonce: Option<ContractNonce>,
new_class_hash: Option<ClassHash>,
storage_commitment_tree: &StorageCommitmentTree<'_>,
transaction: &Transaction<'_>,
) -> anyhow::Result<ContractStateHash> {
// Update the contract state tree.
let state_hash = storage_commitment_tree
.get(contract_address)
.context("Get contract state hash from global state tree")?
.unwrap_or(ContractStateHash(Felt::ZERO));
// Fetch contract's previous root, class hash and nonce.
//
// If the contract state does not exist yet (new contract):
// Contract root defaults to ZERO because that is the default merkle tree value.
// Contract nonce defaults to ZERO because that is its historical value before being added in 0.10.
let (old_root, old_class_hash, old_nonce) = transaction
.contract_state(state_hash)
.context("Read contract root and nonce from contracts state table")?
.map_or_else(
|| (ContractRoot::ZERO, None, ContractNonce::ZERO),
|(root, class_hash, nonce)| (root, Some(class_hash), nonce),
);
let new_nonce = new_nonce.unwrap_or(old_nonce);
// Load the contract tree and insert the updates.
let new_root = if !updates.is_empty() {
let mut contract_tree = ContractsStorageTree::load(transaction, old_root);
for (key, value) in updates {
contract_tree
.set(*key, *value)
.context("Update contract storage tree")?;
}
let (contract_root, nodes) = contract_tree
.commit()
.context("Apply contract storage tree changes")?;
let count = transaction
.insert_contract_trie(contract_root, &nodes)
.context("Persisting contract trie")?;
tracing::trace!(contract=%contract_address, new_nodes=%count, "Persisted contract trie");
contract_root
} else {
old_root
};
// Calculate contract state hash, update global state tree and persist pre-image.
//
// The contract at address 0x1 is special. It was never deployed and doesn't have a class.
let class_hash = if contract_address == ContractAddress::ONE {
ClassHash::ZERO
} else {
new_class_hash
.or(old_class_hash)
.context("Class hash is unknown for new contract")?
};
let contract_state_hash = calculate_contract_state_hash(class_hash, new_root, new_nonce);
transaction
.insert_contract_state(contract_state_hash, class_hash, new_root, new_nonce)
.context("Insert constract state hash into contracts state table")?;
Ok(contract_state_hash)
}
/// Calculates the contract state hash from its preimage.
pub fn calculate_contract_state_hash(
hash: ClassHash,
root: ContractRoot,
nonce: ContractNonce,
) -> ContractStateHash {
const CONTRACT_STATE_HASH_VERSION: Felt = Felt::ZERO;
// The contract state hash is defined as H(H(H(hash, root), nonce), CONTRACT_STATE_HASH_VERSION)
let hash = stark_hash(hash.0, root.0);
let hash = stark_hash(hash, nonce.0);
let hash = stark_hash(hash, CONTRACT_STATE_HASH_VERSION);
// Compare this with the HashChain construction used in the contract_hash: the number of
// elements is not hashed to this hash, and this is supposed to be different.
ContractStateHash(hash)
}
#[cfg(test)]
mod tests {
use super::calculate_contract_state_hash;
use pathfinder_common::felt;
use pathfinder_common::{ClassHash, ContractNonce, ContractRoot, ContractStateHash};
#[test]
fn hash() {
let root = felt!("0x4fb440e8ca9b74fc12a22ebffe0bc0658206337897226117b985434c239c028");
let root = ContractRoot(root);
let hash = felt!("0x2ff4903e17f87b298ded00c44bfeb22874c5f73be2ced8f1d9d9556fb509779");
let hash = ClassHash(hash);
let nonce = ContractNonce::ZERO;
let expected = felt!("0x7161b591c893836263a64f2a7e0d829c92f6956148a60ce5e99a3f55c7973f3");
let expected = ContractStateHash(expected);
let result = calculate_contract_state_hash(hash, root, nonce);
assert_eq!(result, expected);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.