text stringlengths 8 4.13M |
|---|
#[macro_use]
extern crate hyper;
extern crate hyper_tls;
extern crate clap;
extern crate futures;
extern crate tokio_core;
use std::fmt::Display;
use clap::{App, Arg};
use futures::{Future};
use hyper_tls::HttpsConnector;
use hyper::Client;
use hyper::header::{Header, Headers};
use hyper::header::StrictTransportSecurity;
use tokio_core::reactor::Core;
header! { (XFrameOptions, "X-Frame-Options") => [String] }
header! { (ContentSecurityPolicy, "Content-Security-Policy") => [String] }
header! { (XContentTypeOptions, "X-Content-Type-Options") => [String] }
header! { (XXssProtection, "X-Xss-Protection") => [String] }
struct HeaderCheckResult {
name: String,
ok: bool,
msg: Option<String>,
}
impl HeaderCheckResult {
fn create_success(name: &str) -> Self {
HeaderCheckResult {
name: String::from(name),
ok: true,
msg: None,
}
}
fn create_failure(name: &str, msg: &str) -> Self {
HeaderCheckResult {
name: String::from(name),
ok: false,
msg: Some(String::from(msg)),
}
}
}
fn main() {
let matches = App::new("security-headers-rs")
.version("1.0.0")
.about("Performs security headers checks")
.author("Guillem Llompart Piza")
.arg(Arg::with_name("applications")
.short("a")
.long("applications")
.value_name("https://wwww.example.com/")
.required(true)
.help("Sets the application/s to test. Values should be comma separated"))
.get_matches();
let applications: Vec<&str> = matches
.value_of("applications")
.unwrap_or("")
.split(',')
.collect();
println!("[>] Start");
let mut core = Core::new().unwrap();
let handle = &core.handle();
let client = Client::configure()
.connector(HttpsConnector::new(4, &handle).unwrap())
.build(&handle);
for url in applications {
let uri = url.parse();
match uri {
Ok(r) => {
let work = client.get(r).map(|res| {
println!("[>] Check {}", url);
let results = check_headers(&res.headers());
for result in results {
if result.ok {
println!("[ ] {} OK", result.name);
}else {
println!("[!] {} => {}", result.name, result.msg.unwrap_or(String::from("")));
}
}
});
let result = core.run(work);
match result {
Ok(_) => println!("[>] End"),
Err(err) => println!("[>] End with errors: {}", err)
}
},
Err(err) => {
println!("[!] Error parsing url: {}", err);
continue;
}
}
}
}
fn check_headers(headers: &Headers) -> Vec<HeaderCheckResult> {
let mut result: Vec<HeaderCheckResult> = Vec::new();
result.push(check_header::<XFrameOptions>("X-Frame-Options", headers, Some("DENY")));
result.push(check_header::<XContentTypeOptions>("X-Content-Type-Options", headers, Some("nosniff")));
result.push(check_header::<XXssProtection>("X-Xss-Protection", headers, Some("1;mode=block")));
result.push(check_header::<ContentSecurityPolicy>("Content-Security-Policy", headers, None));
result.push(check_header::<StrictTransportSecurity>("Strict-Transport-Security", headers, None));
return result;
}
fn check_header<T>(name: &str, headers: &Headers, expected_value: Option<&str>) -> HeaderCheckResult
where T: Header + Display
{
let has_header = headers.has::<T>();
if !has_header {
return HeaderCheckResult::create_failure(name, "Couldn't find header");
}
if expected_value.is_none() {
return HeaderCheckResult::create_success(name);
}
let match_value = expected_value.unwrap();
let header_value = headers
.get::<T>()
.map_or(String::from(""), |h| h.to_string());
if header_value == match_value {
return HeaderCheckResult::create_success(name);
}
return HeaderCheckResult::create_failure(name, &format!("Expected value to be {}. Found: {}",
match_value,
header_value));
}
|
// Copyright (c) 2020 ESRLabs
//
// 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 super::model;
use bytes::{Buf, BufMut};
use futures::Stream;
use std::{
cmp::min,
io::ErrorKind,
pin::Pin,
task::{self, Poll},
};
use task::Context;
use tokio::io::{self, AsyncRead, AsyncWrite};
use tokio_util::codec::{Decoder, Encoder, FramedParts};
/// Newline delimited json codec for api::Message that on top implementes AsyncRead and Write
pub struct Framed<T> {
inner: tokio_util::codec::Framed<T, Codec>,
}
impl<T> Framed<T> {
/// Consumes the Framed, returning its underlying I/O stream, the buffer with unprocessed data, and the codec.
pub fn into_parts(self) -> FramedParts<T, Codec> {
self.inner.into_parts()
}
/// Consumes the Framed, returning its underlying I/O stream.
pub fn into_inner(self) -> T {
self.inner.into_inner()
}
}
/// Constructs a new Framed with Codec from `io`
pub fn framed<T: AsyncRead + AsyncWrite>(io: T) -> Framed<T> {
Framed {
inner: tokio_util::codec::Framed::new(io, Codec {}),
}
}
/// Newline delimited json
pub struct Codec;
impl Decoder for Codec {
type Item = model::Message;
type Error = io::Error;
fn decode(&mut self, src: &mut bytes::BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if let Some(position) = src.iter().position(|b| *b == b'\n') {
let buf = src.split_to(position);
// Consume the newline
src.advance(1);
match serde_json::from_slice::<model::Message>(&buf) {
Ok(message) => Ok(Some(message)),
Err(e) => Err(io::Error::new(ErrorKind::InvalidData, e)),
}
} else {
Ok(None)
}
}
}
impl Encoder<model::Message> for Codec {
type Error = io::Error;
fn encode(
&mut self,
item: model::Message,
dst: &mut bytes::BytesMut,
) -> Result<(), Self::Error> {
dst.extend_from_slice(serde_json::to_string(&item)?.as_bytes());
dst.reserve(1);
dst.put_u8(b'\n');
Ok(())
}
}
impl<T: Unpin + AsyncRead + AsyncWrite> AsyncWrite for Framed<T> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
let t: &mut T = self.inner.get_mut();
AsyncWrite::poll_write(Pin::new(t), cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let t: &mut T = self.inner.get_mut();
AsyncWrite::poll_flush(Pin::new(t), cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), io::Error>> {
let t: &mut T = self.inner.get_mut();
AsyncWrite::poll_shutdown(Pin::new(t), cx)
}
}
impl<T: Unpin + AsyncRead + AsyncWrite> AsyncRead for Framed<T> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut io::ReadBuf<'_>,
) -> Poll<io::Result<()>> {
if self.inner.read_buffer().is_empty() {
let t: &mut T = self.inner.get_mut();
AsyncRead::poll_read(Pin::new(t), cx, buf)
} else {
let n = min(buf.remaining(), self.inner.read_buffer().len());
buf.put_slice(&self.inner.read_buffer_mut().split_to(n));
Poll::Ready(Ok(()))
}
}
}
impl<T: Unpin + AsyncWrite + AsyncRead> Stream for Framed<T> {
type Item = Result<model::Message, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let framed = Pin::new(&mut self.inner);
framed.poll_next(cx)
}
}
impl<T: Unpin + AsyncRead + AsyncWrite> futures::sink::Sink<model::Message> for Framed<T> {
type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner).poll_ready(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: model::Message) -> Result<(), Self::Error> {
Pin::new(&mut self.inner).start_send(item)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner).poll_close(cx)
}
}
|
use serde::{Deserialize, Serialize, Serializer};
use std::collections::HashMap;
use std::error::Error;
use std::io;
pub struct TransactionProcessor {
/// Keep track of all client accounts and associated values
accounts: HashMap<u16, ClientAccount>,
/// Keep basic info on deposit and withdrawal transactions so that we can handle disputes/chargebacks
transaction_log: HashMap<u32, Record>,
}
impl TransactionProcessor {
pub fn new() -> TransactionProcessor {
TransactionProcessor {
accounts: HashMap::new(),
transaction_log: HashMap::new(),
}
}
pub fn stream_csv(&mut self, filename: &String) -> Result<(), Box<dyn Error>> {
let mut rdr = csv::Reader::from_path(filename)
.expect(format!("Unable to open {}", filename).as_str());
for result in rdr.deserialize() {
let record: Record = result?;
match record.action {
Action::Deposit => self.handle_deposit(record),
Action::Withdrawal => self.handle_withdrawal(record),
Action::Dispute => self.handle_dispute(record),
Action::Resolve => self.handle_resolve(record),
Action::Chargeback => self.handle_chargeback(record),
}
}
Ok(())
}
// Increase clients available and total by deposit amount. If client account does not exist, create it.
fn handle_deposit(&mut self, deposit: Record) {
let client = self.accounts.get_mut(&deposit.client);
let deposit_amount = deposit.amount.unwrap();
match client {
Some(client) => {
client.available += deposit_amount;
client.total += deposit_amount;
}
None => {
self.accounts.insert(
deposit.client,
ClientAccount {
client: deposit.client,
available: deposit_amount,
held: 0.0,
total: deposit_amount,
locked: false,
},
);
}
}
self.transaction_log.insert(deposit.transaction, deposit);
}
fn handle_withdrawal(&mut self, withdrawal: Record) {
let account = self.accounts.get_mut(&withdrawal.client);
let withdrawal_amount = withdrawal
.amount
.expect("Withdrawal transaction did not have a value.");
if let Some(account) = account {
if account.available - withdrawal_amount >= 0.0 {
account.available -= withdrawal_amount;
account.total -= withdrawal_amount;
}
}
self.transaction_log
.insert(withdrawal.transaction, withdrawal);
}
fn handle_dispute(&mut self, dispute: Record) {
let account = self.accounts.get_mut(&dispute.client);
if let Some(account) = account {
if let Some(tx) = self.transaction_log.get(&dispute.transaction) {
account.held += tx
.amount
.expect("Transaction referenced in a dispute did not have a value.");
account.available -= tx
.amount
.expect("Transaction referenced in a dispute did not have a value.");
}
}
}
fn handle_resolve(&mut self, resolve: Record) {
let account = self.accounts.get_mut(&resolve.client);
if let Some(account) = account {
if let Some(tx) = self.transaction_log.get(&resolve.transaction) {
account.held -= tx
.amount
.expect("Transaction referenced in a resolution did not have a value.");
account.available += tx
.amount
.expect("Transaction referenced in a resolution did not have a value.");
}
}
}
fn handle_chargeback(&mut self, chargeback: Record) {
let account = self.accounts.get_mut(&chargeback.client);
if let Some(account) = account {
if let Some(tx) = self.transaction_log.get(&chargeback.transaction) {
account.held -= tx
.amount
.expect("Transaction referenced in a chargeback did not have a value.");
account.total -= tx
.amount
.expect("Transaction referenced in a chargeback did not have a value.");
account.locked = true;
}
}
}
pub fn print_client_accounts(&self) -> Result<(), Box<dyn Error>> {
let mut writer = csv::Writer::from_writer(io::stdout());
for (_, account) in &self.accounts {
writer.serialize(account)?;
}
writer.flush()?;
Ok(())
}
}
#[derive(Debug, Deserialize)]
struct Record {
#[serde(rename = "type")]
action: Action,
client: u16,
#[serde(rename = "tx")]
transaction: u32,
amount: Option<f32>,
}
#[derive(Serialize)]
struct ClientAccount {
/// Client Id
client: u16,
/// Total funds available for trading. available = total - held.
#[serde(serialize_with = "four_decimal_serializer")]
available: f32,
/// Total funds held for dispute. held = total - available
#[serde(serialize_with = "four_decimal_serializer")]
held: f32,
/// Total funds available or held. Total = available + held.
#[serde(serialize_with = "four_decimal_serializer")]
total: f32,
/// Account is locked if charge back occurs
locked: bool,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
enum Action {
Deposit,
Withdrawal,
Dispute,
Resolve,
Chargeback,
}
fn four_decimal_serializer<S>(x: &f32, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(format!("{:.4}", x).as_str())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deposit_increments_correct_amount() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
1,
ClientAccount {
client: 1,
available: 100.0,
total: 100.0,
held: 0.0,
locked: false,
},
);
let deposit = Record {
client: 1,
action: Action::Deposit,
transaction: 1,
amount: Some(20.0),
};
// Act
tx_processor.handle_deposit(deposit);
// Assert
assert!(tx_processor.accounts.contains_key(&1));
assert_eq!(tx_processor.accounts.get(&1).unwrap().available, 120.0);
assert_eq!(tx_processor.accounts.get(&1).unwrap().total, 120.0);
}
#[test]
fn test_deposit_inserts_new_client() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
let deposit = Record {
client: 1,
action: Action::Deposit,
transaction: 1,
amount: Some(20.0),
};
// Act
tx_processor.handle_deposit(deposit);
// Assert
assert!(tx_processor.accounts.contains_key(&1));
assert_eq!(tx_processor.accounts.get(&1).unwrap().available, 20.0);
assert_eq!(tx_processor.accounts.get(&1).unwrap().total, 20.0);
}
#[test]
fn test_withdrawal_subtracts_correct_amount() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 100.0,
total: 100.0,
held: 0.0,
locked: false,
},
);
let withdrawal = Record {
client: 2,
action: Action::Withdrawal,
transaction: 1,
amount: Some(20.0),
};
// Act
tx_processor.handle_withdrawal(withdrawal);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 80.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 80.0);
}
#[test]
fn test_withdrawal_fails_if_account_does_not_have_enough_funds() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 100.0,
total: 100.0,
held: 0.0,
locked: false,
},
);
let withdrawal = Record {
client: 2,
action: Action::Withdrawal,
transaction: 1,
amount: Some(250.0),
};
// Act
tx_processor.handle_withdrawal(withdrawal);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 100.0);
}
#[test]
fn test_dispute_ignores_dispute_for_non_existing_transaction() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 100.0,
total: 100.0,
held: 0.0,
locked: false,
},
);
let dispute = Record {
client: 2,
action: Action::Dispute,
transaction: 1,
amount: None,
};
// Act
tx_processor.handle_dispute(dispute);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().held, 0.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().locked, false);
assert_eq!(tx_processor.accounts.get(&2).unwrap().client, 2);
}
#[test]
fn test_dispute_changes_available_and_held_values() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 100.0,
total: 100.0,
held: 0.0,
locked: false,
},
);
let withdrawal = Record {
client: 2,
action: Action::Withdrawal,
transaction: 1,
amount: Some(25.0),
};
let dispute = Record {
client: 2,
action: Action::Dispute,
transaction: 1,
amount: None,
};
tx_processor.transaction_log.insert(1, withdrawal);
// Act
tx_processor.handle_dispute(dispute);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 75.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().held, 25.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().locked, false);
assert_eq!(tx_processor.accounts.get(&2).unwrap().client, 2);
}
#[test]
fn test_resolve_reimburses_client() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 75.0,
total: 100.0,
held: 25.0,
locked: false,
},
);
let withdrawal = Record {
client: 2,
action: Action::Withdrawal,
transaction: 1,
amount: Some(25.0),
};
tx_processor.transaction_log.insert(1, withdrawal);
let resolve = Record {
action: Action::Resolve,
client: 2,
transaction: 1,
amount: None,
};
// Act
tx_processor.handle_resolve(resolve);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().held, 0.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().locked, false);
}
#[test]
fn test_resolve_ignores_resolve_for_non_existing_transaction() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 100.0,
total: 100.0,
held: 0.0,
locked: false,
},
);
let resolve = Record {
client: 2,
action: Action::Resolve,
transaction: 1,
amount: None,
};
// Act
tx_processor.handle_resolve(resolve);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().held, 0.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().locked, false);
assert_eq!(tx_processor.accounts.get(&2).unwrap().client, 2);
}
#[test]
fn test_chargeback_ignores_chargeback_for_non_existing_transaction() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 100.0,
total: 100.0,
held: 0.0,
locked: false,
},
);
let chargeback = Record {
client: 2,
action: Action::Chargeback,
transaction: 1,
amount: None,
};
// Act
tx_processor.handle_chargeback(chargeback);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 100.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().held, 0.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().locked, false);
assert_eq!(tx_processor.accounts.get(&2).unwrap().client, 2);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 100.0);
}
#[test]
fn test_chargeback_locks_account_and_changes_values() {
// Arrange
let mut tx_processor = TransactionProcessor::new();
tx_processor.accounts.insert(
2,
ClientAccount {
client: 2,
available: 75.0,
total: 100.0,
held: 25.0,
locked: false,
},
);
let withdrawal = Record {
client: 2,
action: Action::Withdrawal,
transaction: 1,
amount: Some(25.0),
};
tx_processor.transaction_log.insert(1, withdrawal);
let chargeback = Record {
client: 2,
action: Action::Resolve,
transaction: 1,
amount: None,
};
// Act
tx_processor.handle_chargeback(chargeback);
// Assert
assert_eq!(tx_processor.accounts.get(&2).unwrap().available, 75.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().held, 0.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().locked, true);
assert_eq!(tx_processor.accounts.get(&2).unwrap().total, 75.0);
assert_eq!(tx_processor.accounts.get(&2).unwrap().client, 2);
}
}
|
pub fn brackets_are_balanced(string: &str) -> bool {
let delimiters = "()[]{}";
let mut stack = Vec::new();
for char in string.chars() {
match delimiters.find(char) {
None => (),
Some(index) => match index % 2 {
0 => stack.push(index + 1),
_ => match stack.pop() {
None => return false,
Some(value) => match index == value {
true => (),
false => return false,
},
},
},
}
}
stack.is_empty()
}
|
use super::prelude::*;
use super::rest_client::{AZURE_VERSION, HEADER_DATE, HEADER_VERSION};
use crate::PerformRequestResponse;
use azure_core::errors::AzureError;
use azure_core::util::{format_header_value, RequestBuilderExt};
use http::request::Builder;
use hyper::{header, Method};
use hyper_rustls::HttpsConnector;
use std::borrow::Cow;
#[derive(Debug, Clone)]
pub struct BearerTokenClient<'a> {
account: Cow<'a, str>,
bearer_token: Cow<'a, str>,
hc: hyper::Client<HttpsConnector<hyper::client::HttpConnector>>,
blob_uri: String,
table_uri: String,
queue_uri: String,
filesystem_uri: String,
}
impl<'a> BearerTokenClient<'a> {
#[inline]
pub(crate) fn new(
account: Cow<'a, str>,
bearer_token: Cow<'a, str>,
hc: hyper::Client<HttpsConnector<hyper::client::HttpConnector>>,
) -> Self {
let blob_uri = format!("https://{}.blob.core.windows.net", account);
let table_uri = format!("https://{}.table.core.windows.net", account);
let queue_uri = format!("https://{}.queue.core.windows.net", account);
let filesystem_uri = format!("https://{}.dfs.core.windows.net", account);
Self {
account,
bearer_token,
queue_uri,
hc,
blob_uri,
table_uri,
filesystem_uri,
}
}
fn perform_request_internal(
&self,
uri: &str,
method: &Method,
http_header_adder: &dyn Fn(Builder) -> Builder,
request_body: Option<&[u8]>,
) -> Result<PerformRequestResponse, AzureError> {
let dt = chrono::Utc::now();
let time = format!("{}", dt.format("%a, %d %h %Y %T GMT"));
let mut request = hyper::Request::builder();
request = request.method(method).uri(uri);
let uri = url::Url::parse(uri)?;
// let's add content length to avoid "chunking" errors.
match request_body {
Some(ref b) => {
request = request.header(header::CONTENT_LENGTH, &b.len().to_string() as &str)
}
None => request = request.header_static(header::CONTENT_LENGTH, "0"),
};
// This will give the caller the ability to add custom headers.
// The closure is needed to because request.headers_mut().set_raw(...) requires
// a Cow with 'static lifetime...
request = http_header_adder(request);
request = request
.header_bytes(HEADER_DATE, time)
.header_static(HEADER_VERSION, AZURE_VERSION);
let b = request_body
.map(|v| Vec::from(v).into())
.unwrap_or_else(hyper::Body::empty);
let mut request = request.body(b)?;
request.headers_mut().insert(
header::AUTHORIZATION,
format_header_value(format!("Bearer {}", self.bearer_token))?,
);
Ok((uri, self.hc.request(request)).into())
}
}
impl<'a> Client for BearerTokenClient<'a> {
#[inline]
fn blob_uri(&self) -> &str {
&self.blob_uri
}
#[inline]
fn table_uri(&self) -> &str {
&self.table_uri
}
#[inline]
fn queue_uri(&self) -> &str {
&self.queue_uri
}
#[inline]
fn filesystem_uri(&self) -> &str {
&self.filesystem_uri
}
#[inline]
fn perform_request(
&self,
uri: &str,
method: &Method,
http_header_adder: &dyn Fn(Builder) -> Builder,
request_body: Option<&[u8]>,
) -> Result<PerformRequestResponse, AzureError> {
self.perform_request_internal(uri, method, http_header_adder, request_body)
}
#[inline]
fn perform_table_request(
&self,
segment: &str,
method: &Method,
http_header_adder: &dyn Fn(Builder) -> Builder,
request_body: Option<&[u8]>,
) -> Result<PerformRequestResponse, AzureError> {
self.perform_request_internal(segment, method, http_header_adder, request_body)
}
}
|
use ast::abstract_syntax_tree::Ast;
use lang_result::LangError;
use s_expression::SExpression;
use std::collections::HashMap;
/// Shorthand for a HashMap that maps Strings to Mutability enums
pub type MutabilityMap = HashMap<String, Mutability>;
// The Void indicates that check was successful without any errors, the MutabilityError will descibe the error that was encountered while checking mutability.
pub type MutabilityResult = Result<(), MutabilityError>;
/// Mutability values variables can have.
#[derive(Debug, Clone)]
pub enum Mutability {
Mutable,
Immutable
}
/// Types of errors that can be generated by the mutability checker.
#[derive(Debug, Clone)]
pub enum MutabilityError {
CanNotAssignToConstVariable,
CanNotRedeclareConst,
VariableDoesNotExist,
IsNotAVariable,
CanNotRedeclareFunction,
CanNotRedeclareStruct
}
impl Ast {
/// Checks assignments and declarations to prevent duplicate use of variables of different mutability states.
/// This will prevent declaring a function and then reassigning it to be a variable
/// or preventing altering a constant value.
///
/// This has the stipulation that for every expression list it encounters, the function will assume that
/// it should create a new scope. This leads to the requirement that REPL input
/// (which is known to always be a list with a single element)
/// needs to be hoisted out of its list, as each new input would otherwise be given a new scope,
/// breaking the mutability checker.
pub fn check_mutability_semantics(&self, map: &mut MutabilityMap) -> Result<(), MutabilityError> {
match *self {
Ast::ExpressionList( ref expressions) => {
let mut cloned_map = map.clone(); // Clone the map, so you can use different mutability rules in sibling scopes.
for expression in expressions {
let _ = expression.check_mutability_semantics(&mut cloned_map)?;
}
return Ok(())
}
Ast::SExpr(ref s_expression) => {
match *s_expression {
SExpression::Assignment{ref identifier, ref ast} => { // a := 5
let resolved_id: String = match **identifier {
Ast::ValueIdentifier(ref id) => id.clone(),
_ => return Err(MutabilityError::IsNotAVariable) // Error, AST malformed, couldn't resolve the id
};
if let Some(mutability) = map.get(&resolved_id) {
match *mutability {
Mutability::Mutable => Ok(()),
Mutability::Immutable => Err(MutabilityError::CanNotAssignToConstVariable) // tried to assign a value to immutable value
}
} else {
Err(MutabilityError::VariableDoesNotExist) // variable doesn't exist yet
}
}
SExpression::ConstDeclaration {ref identifier, ref ast} => { // const a := 5
let resolved_id: String = match **identifier {
Ast::ValueIdentifier(ref id) => id.clone(),
_ => return Err(MutabilityError::IsNotAVariable) // Error, AST malformed, couldn't resolve the id
};
if let Some(_) = map.get(&resolved_id) {
Err(MutabilityError::CanNotRedeclareConst) // tried to assign a value to immutable value
} else {
map.insert(resolved_id, Mutability::Immutable); // prevent reassignment of the fn
Ok(())
}
},
SExpression::VariableDeclaration { ref identifier, ref ast } => {
// let a := 5
let resolved_id: String = match **identifier {
Ast::ValueIdentifier(ref id) => id.clone(),
_ => return Err(MutabilityError::IsNotAVariable) // Error, AST malformed, couldn't resolve the id
};
{
if let Some(mutability) = map.get(&resolved_id) {
match *mutability {
Mutability::Mutable => return Ok(()), // You are allowed to reassign other let variables, although there isn't really a reason to.
Mutability::Immutable => return Err(MutabilityError::CanNotRedeclareConst) // tried to assign a value to immutable value
}
}
}
map.insert(resolved_id, Mutability::Mutable); // prevent reassignment of the fn
Ok(())
}
SExpression::DeclareFunction { ref identifier, ref function_datatype } => {
let resolved_id: String = match **identifier {
Ast::ValueIdentifier(ref id) => id.clone(),
_ => return Err(MutabilityError::IsNotAVariable) // Error, AST malformed, couldn't resolve the id
};
if let Some(_) = map.get(&resolved_id) {
Err(MutabilityError::CanNotRedeclareFunction) // can't reassign functions
} else {
map.insert(resolved_id, Mutability::Immutable); // prevent reassignment of the fn
Ok(())
}
},
SExpression::StructDeclaration { ref identifier, ref struct_type_info} => {
let resolved_id: String = match **identifier {
Ast::ValueIdentifier(ref id) => id.clone(),
_ => return Err(MutabilityError::IsNotAVariable) // Error, AST malformed, couldn't resolve the id
};
if let Some(_) = map.get(&resolved_id) {
Err(MutabilityError::CanNotRedeclareStruct) // can't reassign struct type
} else {
map.insert(resolved_id, Mutability::Immutable); // prevent reassignment of the struct
Ok(())
}
}
_ => {
Ok(()) // if the expression doesn't add anything to the variable store, we don't care about it.
}
}
}
_ => Ok(())
}
}
} |
#[doc = "Register `MPCBB1_VCTR32` reader"]
pub type R = crate::R<MPCBB1_VCTR32_SPEC>;
#[doc = "Register `MPCBB1_VCTR32` writer"]
pub type W = crate::W<MPCBB1_VCTR32_SPEC>;
#[doc = "Field `B1024` reader - B1024"]
pub type B1024_R = crate::BitReader;
#[doc = "Field `B1024` writer - B1024"]
pub type B1024_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1025` reader - B1025"]
pub type B1025_R = crate::BitReader;
#[doc = "Field `B1025` writer - B1025"]
pub type B1025_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1026` reader - B1026"]
pub type B1026_R = crate::BitReader;
#[doc = "Field `B1026` writer - B1026"]
pub type B1026_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1027` reader - B1027"]
pub type B1027_R = crate::BitReader;
#[doc = "Field `B1027` writer - B1027"]
pub type B1027_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1028` reader - B1028"]
pub type B1028_R = crate::BitReader;
#[doc = "Field `B1028` writer - B1028"]
pub type B1028_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1029` reader - B1029"]
pub type B1029_R = crate::BitReader;
#[doc = "Field `B1029` writer - B1029"]
pub type B1029_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1030` reader - B1030"]
pub type B1030_R = crate::BitReader;
#[doc = "Field `B1030` writer - B1030"]
pub type B1030_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1031` reader - B1031"]
pub type B1031_R = crate::BitReader;
#[doc = "Field `B1031` writer - B1031"]
pub type B1031_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1032` reader - B1032"]
pub type B1032_R = crate::BitReader;
#[doc = "Field `B1032` writer - B1032"]
pub type B1032_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1033` reader - B1033"]
pub type B1033_R = crate::BitReader;
#[doc = "Field `B1033` writer - B1033"]
pub type B1033_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1034` reader - B1034"]
pub type B1034_R = crate::BitReader;
#[doc = "Field `B1034` writer - B1034"]
pub type B1034_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1035` reader - B1035"]
pub type B1035_R = crate::BitReader;
#[doc = "Field `B1035` writer - B1035"]
pub type B1035_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1036` reader - B1036"]
pub type B1036_R = crate::BitReader;
#[doc = "Field `B1036` writer - B1036"]
pub type B1036_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1037` reader - B1037"]
pub type B1037_R = crate::BitReader;
#[doc = "Field `B1037` writer - B1037"]
pub type B1037_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1038` reader - B1038"]
pub type B1038_R = crate::BitReader;
#[doc = "Field `B1038` writer - B1038"]
pub type B1038_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1039` reader - B1039"]
pub type B1039_R = crate::BitReader;
#[doc = "Field `B1039` writer - B1039"]
pub type B1039_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1040` reader - B1040"]
pub type B1040_R = crate::BitReader;
#[doc = "Field `B1040` writer - B1040"]
pub type B1040_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1041` reader - B1041"]
pub type B1041_R = crate::BitReader;
#[doc = "Field `B1041` writer - B1041"]
pub type B1041_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1042` reader - B1042"]
pub type B1042_R = crate::BitReader;
#[doc = "Field `B1042` writer - B1042"]
pub type B1042_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1043` reader - B1043"]
pub type B1043_R = crate::BitReader;
#[doc = "Field `B1043` writer - B1043"]
pub type B1043_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1044` reader - B1044"]
pub type B1044_R = crate::BitReader;
#[doc = "Field `B1044` writer - B1044"]
pub type B1044_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1045` reader - B1045"]
pub type B1045_R = crate::BitReader;
#[doc = "Field `B1045` writer - B1045"]
pub type B1045_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1046` reader - B1046"]
pub type B1046_R = crate::BitReader;
#[doc = "Field `B1046` writer - B1046"]
pub type B1046_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1047` reader - B1047"]
pub type B1047_R = crate::BitReader;
#[doc = "Field `B1047` writer - B1047"]
pub type B1047_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1048` reader - B1048"]
pub type B1048_R = crate::BitReader;
#[doc = "Field `B1048` writer - B1048"]
pub type B1048_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1049` reader - B1049"]
pub type B1049_R = crate::BitReader;
#[doc = "Field `B1049` writer - B1049"]
pub type B1049_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1050` reader - B1050"]
pub type B1050_R = crate::BitReader;
#[doc = "Field `B1050` writer - B1050"]
pub type B1050_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1051` reader - B1051"]
pub type B1051_R = crate::BitReader;
#[doc = "Field `B1051` writer - B1051"]
pub type B1051_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1052` reader - B1052"]
pub type B1052_R = crate::BitReader;
#[doc = "Field `B1052` writer - B1052"]
pub type B1052_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1053` reader - B1053"]
pub type B1053_R = crate::BitReader;
#[doc = "Field `B1053` writer - B1053"]
pub type B1053_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1054` reader - B1054"]
pub type B1054_R = crate::BitReader;
#[doc = "Field `B1054` writer - B1054"]
pub type B1054_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1055` reader - B1055"]
pub type B1055_R = crate::BitReader;
#[doc = "Field `B1055` writer - B1055"]
pub type B1055_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - B1024"]
#[inline(always)]
pub fn b1024(&self) -> B1024_R {
B1024_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - B1025"]
#[inline(always)]
pub fn b1025(&self) -> B1025_R {
B1025_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - B1026"]
#[inline(always)]
pub fn b1026(&self) -> B1026_R {
B1026_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - B1027"]
#[inline(always)]
pub fn b1027(&self) -> B1027_R {
B1027_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - B1028"]
#[inline(always)]
pub fn b1028(&self) -> B1028_R {
B1028_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - B1029"]
#[inline(always)]
pub fn b1029(&self) -> B1029_R {
B1029_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - B1030"]
#[inline(always)]
pub fn b1030(&self) -> B1030_R {
B1030_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - B1031"]
#[inline(always)]
pub fn b1031(&self) -> B1031_R {
B1031_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - B1032"]
#[inline(always)]
pub fn b1032(&self) -> B1032_R {
B1032_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - B1033"]
#[inline(always)]
pub fn b1033(&self) -> B1033_R {
B1033_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - B1034"]
#[inline(always)]
pub fn b1034(&self) -> B1034_R {
B1034_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - B1035"]
#[inline(always)]
pub fn b1035(&self) -> B1035_R {
B1035_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - B1036"]
#[inline(always)]
pub fn b1036(&self) -> B1036_R {
B1036_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - B1037"]
#[inline(always)]
pub fn b1037(&self) -> B1037_R {
B1037_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - B1038"]
#[inline(always)]
pub fn b1038(&self) -> B1038_R {
B1038_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - B1039"]
#[inline(always)]
pub fn b1039(&self) -> B1039_R {
B1039_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - B1040"]
#[inline(always)]
pub fn b1040(&self) -> B1040_R {
B1040_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - B1041"]
#[inline(always)]
pub fn b1041(&self) -> B1041_R {
B1041_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - B1042"]
#[inline(always)]
pub fn b1042(&self) -> B1042_R {
B1042_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - B1043"]
#[inline(always)]
pub fn b1043(&self) -> B1043_R {
B1043_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - B1044"]
#[inline(always)]
pub fn b1044(&self) -> B1044_R {
B1044_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - B1045"]
#[inline(always)]
pub fn b1045(&self) -> B1045_R {
B1045_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - B1046"]
#[inline(always)]
pub fn b1046(&self) -> B1046_R {
B1046_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - B1047"]
#[inline(always)]
pub fn b1047(&self) -> B1047_R {
B1047_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - B1048"]
#[inline(always)]
pub fn b1048(&self) -> B1048_R {
B1048_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - B1049"]
#[inline(always)]
pub fn b1049(&self) -> B1049_R {
B1049_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - B1050"]
#[inline(always)]
pub fn b1050(&self) -> B1050_R {
B1050_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - B1051"]
#[inline(always)]
pub fn b1051(&self) -> B1051_R {
B1051_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - B1052"]
#[inline(always)]
pub fn b1052(&self) -> B1052_R {
B1052_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - B1053"]
#[inline(always)]
pub fn b1053(&self) -> B1053_R {
B1053_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - B1054"]
#[inline(always)]
pub fn b1054(&self) -> B1054_R {
B1054_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - B1055"]
#[inline(always)]
pub fn b1055(&self) -> B1055_R {
B1055_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - B1024"]
#[inline(always)]
#[must_use]
pub fn b1024(&mut self) -> B1024_W<MPCBB1_VCTR32_SPEC, 0> {
B1024_W::new(self)
}
#[doc = "Bit 1 - B1025"]
#[inline(always)]
#[must_use]
pub fn b1025(&mut self) -> B1025_W<MPCBB1_VCTR32_SPEC, 1> {
B1025_W::new(self)
}
#[doc = "Bit 2 - B1026"]
#[inline(always)]
#[must_use]
pub fn b1026(&mut self) -> B1026_W<MPCBB1_VCTR32_SPEC, 2> {
B1026_W::new(self)
}
#[doc = "Bit 3 - B1027"]
#[inline(always)]
#[must_use]
pub fn b1027(&mut self) -> B1027_W<MPCBB1_VCTR32_SPEC, 3> {
B1027_W::new(self)
}
#[doc = "Bit 4 - B1028"]
#[inline(always)]
#[must_use]
pub fn b1028(&mut self) -> B1028_W<MPCBB1_VCTR32_SPEC, 4> {
B1028_W::new(self)
}
#[doc = "Bit 5 - B1029"]
#[inline(always)]
#[must_use]
pub fn b1029(&mut self) -> B1029_W<MPCBB1_VCTR32_SPEC, 5> {
B1029_W::new(self)
}
#[doc = "Bit 6 - B1030"]
#[inline(always)]
#[must_use]
pub fn b1030(&mut self) -> B1030_W<MPCBB1_VCTR32_SPEC, 6> {
B1030_W::new(self)
}
#[doc = "Bit 7 - B1031"]
#[inline(always)]
#[must_use]
pub fn b1031(&mut self) -> B1031_W<MPCBB1_VCTR32_SPEC, 7> {
B1031_W::new(self)
}
#[doc = "Bit 8 - B1032"]
#[inline(always)]
#[must_use]
pub fn b1032(&mut self) -> B1032_W<MPCBB1_VCTR32_SPEC, 8> {
B1032_W::new(self)
}
#[doc = "Bit 9 - B1033"]
#[inline(always)]
#[must_use]
pub fn b1033(&mut self) -> B1033_W<MPCBB1_VCTR32_SPEC, 9> {
B1033_W::new(self)
}
#[doc = "Bit 10 - B1034"]
#[inline(always)]
#[must_use]
pub fn b1034(&mut self) -> B1034_W<MPCBB1_VCTR32_SPEC, 10> {
B1034_W::new(self)
}
#[doc = "Bit 11 - B1035"]
#[inline(always)]
#[must_use]
pub fn b1035(&mut self) -> B1035_W<MPCBB1_VCTR32_SPEC, 11> {
B1035_W::new(self)
}
#[doc = "Bit 12 - B1036"]
#[inline(always)]
#[must_use]
pub fn b1036(&mut self) -> B1036_W<MPCBB1_VCTR32_SPEC, 12> {
B1036_W::new(self)
}
#[doc = "Bit 13 - B1037"]
#[inline(always)]
#[must_use]
pub fn b1037(&mut self) -> B1037_W<MPCBB1_VCTR32_SPEC, 13> {
B1037_W::new(self)
}
#[doc = "Bit 14 - B1038"]
#[inline(always)]
#[must_use]
pub fn b1038(&mut self) -> B1038_W<MPCBB1_VCTR32_SPEC, 14> {
B1038_W::new(self)
}
#[doc = "Bit 15 - B1039"]
#[inline(always)]
#[must_use]
pub fn b1039(&mut self) -> B1039_W<MPCBB1_VCTR32_SPEC, 15> {
B1039_W::new(self)
}
#[doc = "Bit 16 - B1040"]
#[inline(always)]
#[must_use]
pub fn b1040(&mut self) -> B1040_W<MPCBB1_VCTR32_SPEC, 16> {
B1040_W::new(self)
}
#[doc = "Bit 17 - B1041"]
#[inline(always)]
#[must_use]
pub fn b1041(&mut self) -> B1041_W<MPCBB1_VCTR32_SPEC, 17> {
B1041_W::new(self)
}
#[doc = "Bit 18 - B1042"]
#[inline(always)]
#[must_use]
pub fn b1042(&mut self) -> B1042_W<MPCBB1_VCTR32_SPEC, 18> {
B1042_W::new(self)
}
#[doc = "Bit 19 - B1043"]
#[inline(always)]
#[must_use]
pub fn b1043(&mut self) -> B1043_W<MPCBB1_VCTR32_SPEC, 19> {
B1043_W::new(self)
}
#[doc = "Bit 20 - B1044"]
#[inline(always)]
#[must_use]
pub fn b1044(&mut self) -> B1044_W<MPCBB1_VCTR32_SPEC, 20> {
B1044_W::new(self)
}
#[doc = "Bit 21 - B1045"]
#[inline(always)]
#[must_use]
pub fn b1045(&mut self) -> B1045_W<MPCBB1_VCTR32_SPEC, 21> {
B1045_W::new(self)
}
#[doc = "Bit 22 - B1046"]
#[inline(always)]
#[must_use]
pub fn b1046(&mut self) -> B1046_W<MPCBB1_VCTR32_SPEC, 22> {
B1046_W::new(self)
}
#[doc = "Bit 23 - B1047"]
#[inline(always)]
#[must_use]
pub fn b1047(&mut self) -> B1047_W<MPCBB1_VCTR32_SPEC, 23> {
B1047_W::new(self)
}
#[doc = "Bit 24 - B1048"]
#[inline(always)]
#[must_use]
pub fn b1048(&mut self) -> B1048_W<MPCBB1_VCTR32_SPEC, 24> {
B1048_W::new(self)
}
#[doc = "Bit 25 - B1049"]
#[inline(always)]
#[must_use]
pub fn b1049(&mut self) -> B1049_W<MPCBB1_VCTR32_SPEC, 25> {
B1049_W::new(self)
}
#[doc = "Bit 26 - B1050"]
#[inline(always)]
#[must_use]
pub fn b1050(&mut self) -> B1050_W<MPCBB1_VCTR32_SPEC, 26> {
B1050_W::new(self)
}
#[doc = "Bit 27 - B1051"]
#[inline(always)]
#[must_use]
pub fn b1051(&mut self) -> B1051_W<MPCBB1_VCTR32_SPEC, 27> {
B1051_W::new(self)
}
#[doc = "Bit 28 - B1052"]
#[inline(always)]
#[must_use]
pub fn b1052(&mut self) -> B1052_W<MPCBB1_VCTR32_SPEC, 28> {
B1052_W::new(self)
}
#[doc = "Bit 29 - B1053"]
#[inline(always)]
#[must_use]
pub fn b1053(&mut self) -> B1053_W<MPCBB1_VCTR32_SPEC, 29> {
B1053_W::new(self)
}
#[doc = "Bit 30 - B1054"]
#[inline(always)]
#[must_use]
pub fn b1054(&mut self) -> B1054_W<MPCBB1_VCTR32_SPEC, 30> {
B1054_W::new(self)
}
#[doc = "Bit 31 - B1055"]
#[inline(always)]
#[must_use]
pub fn b1055(&mut self) -> B1055_W<MPCBB1_VCTR32_SPEC, 31> {
B1055_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "MPCBBx vector register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mpcbb1_vctr32::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mpcbb1_vctr32::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MPCBB1_VCTR32_SPEC;
impl crate::RegisterSpec for MPCBB1_VCTR32_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mpcbb1_vctr32::R`](R) reader structure"]
impl crate::Readable for MPCBB1_VCTR32_SPEC {}
#[doc = "`write(|w| ..)` method takes [`mpcbb1_vctr32::W`](W) writer structure"]
impl crate::Writable for MPCBB1_VCTR32_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MPCBB1_VCTR32 to value 0"]
impl crate::Resettable for MPCBB1_VCTR32_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::prelude::*;
use crate::resources::ResourceType;
use crate::responses::ListPermissionsResponse;
use azure_core::prelude::*;
use futures::stream::{unfold, Stream};
use http::StatusCode;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct ListPermissionsBuilder<'a, 'b> {
user_client: &'a UserClient,
user_agent: Option<UserAgent<'b>>,
activity_id: Option<ActivityId<'b>>,
consistency_level: Option<ConsistencyLevel>,
continuation: Option<Continuation<'b>>,
max_item_count: MaxItemCount,
}
impl<'a, 'b> ListPermissionsBuilder<'a, 'b> {
pub(crate) fn new(user_client: &'a UserClient) -> Self {
Self {
user_client,
user_agent: None,
activity_id: None,
consistency_level: None,
continuation: None,
max_item_count: MaxItemCount::new(-1),
}
}
setters! {
user_agent: &'b str => Some(UserAgent::new(user_agent)),
activity_id: &'b str => Some(ActivityId::new(activity_id)),
consistency_level: ConsistencyLevel => Some(consistency_level),
continuation: &'b str => Some(Continuation::new(continuation)),
max_item_count: i32 => MaxItemCount::new(max_item_count),
}
pub async fn execute(&self) -> crate::Result<ListPermissionsResponse<'a>> {
trace!("ListPermissionsBuilder::execute called");
let request = self.user_client.cosmos_client().prepare_request(
&format!(
"dbs/{}/users/{}/permissions",
self.user_client.database_client().database_name(),
self.user_client.user_name()
),
http::Method::GET,
ResourceType::Permissions,
);
let request = azure_core::headers::add_optional_header(&self.user_agent, request);
let request = azure_core::headers::add_optional_header(&self.activity_id, request);
let request = azure_core::headers::add_optional_header(&self.consistency_level, request);
let request = azure_core::headers::add_optional_header(&self.continuation, request);
let request = azure_core::headers::add_mandatory_header(&self.max_item_count, request);
let request = request.body(bytes::Bytes::from_static(EMPTY_BODY))?;
debug!("\nrequest == {:#?}", request);
Ok(self
.user_client
.http_client()
.execute_request_check_status(request, StatusCode::OK)
.await?
.try_into()?)
}
pub fn stream(&self) -> impl Stream<Item = crate::Result<ListPermissionsResponse<'a>>> + '_ {
#[derive(Debug, Clone, PartialEq)]
enum States {
Init,
Continuation(String),
}
unfold(
Some(States::Init),
move |continuation_token: Option<States>| {
async move {
debug!("continuation_token == {:?}", &continuation_token);
let response = match continuation_token {
Some(States::Init) => self.execute().await,
Some(States::Continuation(continuation_token)) => {
self.clone()
.continuation(continuation_token.as_str())
.execute()
.await
}
None => return None,
};
// the ? operator does not work in async move (yet?)
// so we have to resort to this boilerplate
let response = match response {
Ok(response) => response,
Err(err) => return Some((Err(err), None)),
};
let continuation_token = response
.continuation_token
.as_ref()
.map(|ct| States::Continuation(ct.to_owned()));
Some((Ok(response), continuation_token))
}
},
)
}
}
|
mod gates;
mod wire;
pub use self::wire::wiring;
pub use self::gates::NANDGate;
pub use self::gates::NOTGate;
pub use self::gates::ANDGate;
pub use self::gates::ORGate;
pub use self::gates::XORGate;
pub use self::gates::NORGate;
mod components {}
|
use super::*;
pub trait SDLConsuming: Clone {
const JOYPAD: bool;
const CONTROLLER: bool;
const GESTURE: bool;
const FINGER: bool;
const APP: bool;
const WINDOW: bool;
const KEYBOARD: bool;
const TEXT_OP: bool;
const MOUSE: bool;
const WHEEL: bool;
const CLIPBOARD_UPDATE: bool;
const DND: bool;
const USER: bool;
const UNKNOWN: bool;
#[inline]
fn consuming_of(e: &SDLEvent) -> bool {
match e {
SDLEvent::Quit{..} => Self::APP,
SDLEvent::AppTerminating{..} => Self::APP,
SDLEvent::AppLowMemory{..} => Self::APP,
SDLEvent::AppWillEnterBackground{..} => Self::APP,
SDLEvent::AppDidEnterBackground{..} => Self::APP,
SDLEvent::AppWillEnterForeground{..} => Self::APP,
SDLEvent::AppDidEnterForeground{..} => Self::APP,
SDLEvent::Window{..} => Self::WINDOW,
SDLEvent::KeyDown{..} => Self::KEYBOARD,
SDLEvent::KeyUp{..} => Self::KEYBOARD,
SDLEvent::TextEditing{..} => Self::TEXT_OP,
SDLEvent::TextInput{..} => Self::TEXT_OP,
SDLEvent::MouseMotion{..} => Self::MOUSE,
SDLEvent::MouseButtonDown{..} => Self::MOUSE,
SDLEvent::MouseButtonUp{..} => Self::MOUSE,
SDLEvent::MouseWheel{..} => Self::WHEEL,
SDLEvent::JoyAxisMotion{..} => Self::JOYPAD,
SDLEvent::JoyBallMotion{..} => Self::JOYPAD,
SDLEvent::JoyHatMotion{..} => Self::JOYPAD,
SDLEvent::JoyButtonDown{..} => Self::JOYPAD,
SDLEvent::JoyButtonUp{..} => Self::JOYPAD,
SDLEvent::JoyDeviceAdded{..} => Self::JOYPAD,
SDLEvent::JoyDeviceRemoved{..} => Self::JOYPAD,
SDLEvent::ControllerAxisMotion{..} => Self::CONTROLLER,
SDLEvent::ControllerButtonDown{..} => Self::CONTROLLER,
SDLEvent::ControllerButtonUp{..} => Self::CONTROLLER,
SDLEvent::ControllerDeviceAdded{..} => Self::CONTROLLER,
SDLEvent::ControllerDeviceRemoved{..} => Self::CONTROLLER,
SDLEvent::ControllerDeviceRemapped{..} => Self::CONTROLLER,
SDLEvent::FingerDown{..} => Self::FINGER,
SDLEvent::FingerUp{..} => Self::FINGER,
SDLEvent::FingerMotion{..} => Self::FINGER,
SDLEvent::DollarGesture{..} => Self::GESTURE,
SDLEvent::DollarRecord{..} => Self::GESTURE,
SDLEvent::MultiGesture{..} => Self::GESTURE,
SDLEvent::ClipboardUpdate{..} => Self::CLIPBOARD_UPDATE,
SDLEvent::DropFile{..} => Self::DND,
SDLEvent::DropText{..} => Self::DND,
SDLEvent::DropBegin{..} => Self::DND,
SDLEvent::DropComplete{..} => Self::DND,
SDLEvent::AudioDeviceAdded{..} => Self::APP,
SDLEvent::AudioDeviceRemoved{..} => Self::APP,
SDLEvent::RenderTargetsReset{..} => Self::APP,
SDLEvent::RenderDeviceReset{..} => Self::APP,
SDLEvent::User{..} => Self::USER,
SDLEvent::Unknown{..} => Self::UNKNOWN,
}
}
}
#[derive(Clone)]
pub struct StdConsuming;
impl SDLConsuming for StdConsuming {
const JOYPAD: bool = false;
const CONTROLLER: bool = false;
const GESTURE: bool = false;
const FINGER: bool = true;
const APP: bool = false;
const WINDOW: bool = false;
const KEYBOARD: bool = false;
const TEXT_OP: bool = false;
const MOUSE: bool = true;
const WHEEL: bool = true;
const CLIPBOARD_UPDATE: bool = false;
const DND: bool = true;
const USER: bool = false;
const UNKNOWN: bool = false;
}
|
use crate::prelude::*;
use derive_new::new;
use getset::Getters;
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(
Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Getters, Serialize, Deserialize, new,
)]
#[get = "pub(crate)"]
pub struct ExternalCommand {
name: Tag,
}
impl ToDebug for ExternalCommand {
fn fmt_debug(&self, f: &mut fmt::Formatter, source: &str) -> fmt::Result {
write!(f, "{}", self.name.slice(source))?;
Ok(())
}
}
|
use crate::{candidate_type::CandidateType, ice_candidate::IceCandidate};
use regex::Regex;
pub struct Sdp {
pub ufrag: String,
pub pwd: String,
}
impl Default for Sdp {
fn default() -> Self {
Sdp {
ufrag: "".into(),
pwd: "".into(),
}
}
}
impl From<&str> for Sdp {
fn from(raw: &str) -> Self {
let mut sdp = Sdp::default();
for line in raw.split("\r\n") {
if line.contains("ice-ufrag") {
// a=ice-pwd:99ad05513f44705637769b05c7e86c0b
// a=ice-ufrag:ae11196c
let re = Regex::new(r"a=ice-ufrag:([a-z0-9]+)").unwrap();
let caps = re.captures(line).unwrap();
sdp.ufrag = caps.get(1).unwrap().as_str().into();
continue;
}
if line.contains("ice-pwd") {
let re = Regex::new(r"a=ice-pwd:([a-z0-9]+)").unwrap();
let caps = re.captures(line).unwrap();
sdp.pwd = caps.get(1).unwrap().as_str().into();
continue;
}
if line.contains("candidate") {
parse_candidate(line).unwrap();
}
}
sdp
}
}
pub fn parse_candidate(line: &str) -> Result<IceCandidate, String> {
// candidate:0 1 UDP 2122187007 9971baf2-00e6-4bb3-b954-7a61b4eb8daf.local 48155 typ host
// candidate:2 1 UDP 2122252543 475400ac-4273-4245-90fb-7b6c97fe06f7.local 53547 typ host
// candidate:4 1 TCP 2105458943 9971baf2-00e6-4bb3-b954-7a61b4eb8daf.local 9 typ host tcptype active
// candidate:5 1 TCP 2105524479 475400ac-4273-4245-90fb-7b6c97fe06f7.local 9 typ host tcptype active
// candidate:1 1 UDP 1685987327 103.208.69.28 19828 typ srflx raddr 0.0.0.0 rport 0
//
// int res = sscanf(candidate, "%32s %30u %3s %30u %49s %30u typ %5s %*s %39s %*s %30u",
// let re = Regex::new(r"candidate:([0-9]+)\s([0-9]+)\s(UDP|TCP)\s([0-9]+)\s([a-z0-9\-\.]+)\s([0-9]+)\styp\s(host|srflx|prflx)\s(raddr|tcptype)\s([a-z]+|[0-9\.]+)\s(rport)\s([0-9]+)").unwrap();
let re = Regex::new(r"candidate:([0-9]+)\s([0-9]+)\s(UDP|TCP)\s([0-9]+)\s([a-z0-9\-\.]+)\s([0-9]+)\styp\s(host|srflx|prflx)\s*(raddr|tcptype)*\s*([a-z]+|[0-9\.]+)*\s*(rport)*\s*([0-9]+)*").unwrap();
if let Some(caps) = re.captures(line) {
let foundation = caps
.get(1)
.ok_or::<String>("can't parse foundation".into())?;
let component = caps
.get(2)
.ok_or::<String>("can't parse component".into())?;
let transport = caps
.get(3)
.ok_or::<String>("can't parse transport".into())?;
let priority = caps.get(4).ok_or::<String>("can't parse priority".into())?;
let ip = caps.get(5).ok_or::<String>("can't parse ip".into())?;
let port = caps.get(6).ok_or::<String>("can't parse port".into())?;
let typ = caps.get(7).ok_or::<String>("can't parse typ".into())?;
let typ = match typ.as_str() {
"host" if transport.as_str() == "UDP" => CandidateType::HostUdp,
"host" if transport.as_str() == "TCP" => CandidateType::HostTcp(ip.as_str().into()),
"srflx" => {
let rip = caps.get(9).ok_or::<String>("can't parse rip".into())?;
let rport = caps.get(11).ok_or::<String>("can't parse rport".into())?;
CandidateType::ServerReflexive(rip.as_str().into(), rport.as_str().parse().unwrap())
}
_ => return Err(format!("unknown type: {}", typ.as_str())),
};
IceCandidate::new(
foundation.as_str().parse().unwrap(),
component.as_str().parse().unwrap(),
transport.as_str().into(),
priority.as_str().parse().unwrap(),
ip.as_str().into(),
port.as_str().parse().unwrap(),
typ,
)
} else {
Err("candidate cant be parsed".into())
}
}
pub fn create_sdp(sdp: &Sdp) -> String {
format!(concat!("v=0\\r\\n",
"o=- 1625733337583270 1 IN IP4 192.168.1.2\\r\\n",
"s=Mountpoint 99\\r\\n",
"t=0 0\\r\\n",
"a=group:BUNDLE video\\r\\n",
"a=msid-semantic: WMS cloverleaf\\r\\n",
"m=video 9 UDP/TLS/RTP/SAVPF 96 97\\r\\n",
"c=IN IP4 192.168.1.2\\r\\n",
"a=sendonly\\r\\n",
"a=mid:video\\r\\n",
"a=rtcp-mux\\r\\n",
"a=ice-ufrag:{}\\r\\n",
"a=ice-pwd:{}\\r\\n",
"a=ice-options:trickle\\r\\n",
"a=fingerprint:sha-256 5B:F5:FC:7E:5F:1B:21:86:37:A4:06:EF:48:A1:E0:E5:DB:93:5F:4F:05:B3:89:9A:11:E5:1E:15:81:D7:11:13\\r\\n",
"a=setup:actpass\\r\\n",
"a=rtpmap:96 H264/90000\\r\\n",
"a=fmtp:96 profile-level-id=42e01f;packetization-mode=1\\r\\n",
"a=rtcp-fb:96 nack\\r\\n",
"a=rtcp-fb:96 nack pli\\r\\n",
"a=rtcp-fb:96 goog-remb\\r\\n",
"a=extmap:1 urn:ietf:params:rtp-hdrext:sdes:mid\\r\\n",
"a=rtpmap:97 rtx/90000\\r\\n",
"a=fmtp:97 apt=96\\r\\n",
"a=ssrc-group:FID 1811295701 180905187\\r\\n",
"a=msid:cloverleaf cloverleafv0\\r\\n",
"a=ssrc:1811295701 cname:cloverleaf\\r\\n",
"a=ssrc:1811295701 msid:cloverleaf cloverleafv0\\r\\n",
"a=ssrc:1811295701 mslabel:cloverleaf\\r\\n",
"a=ssrc:1811295701 label:cloverleafv0\\r\\n",
"a=ssrc:180905187 cname:cloverleaf\\r\\n",
"a=ssrc:180905187 msid:cloverleaf cloverleafv0\\r\\n",
"a=ssrc:180905187 mslabel:cloverleaf\\r\\n",
"a=ssrc:180905187 label:cloverleafv0\\r\\n",
"a=candidate:1 1 udp 2015363327 192.168.1.2 42933 typ host\\r\\n",
"a=end-of-candidates\\r\\n",
), sdp.ufrag, sdp.pwd)
}
|
use core::{fmt, iter::*, marker::PhantomData, mem, ptr};
use std::os::windows::ffi::OsStringExt;
use std::{ffi::*, io};
use winapi::{
shared::{guiddef::GUID, minwindef::*, windef::HWND, winerror::*},
um::{errhandlingapi::*, handleapi::*, heapapi::*, setupapi::*, winnt::*},
};
pub use winapi::um::setupapi::HDEVINFO;
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct InfoHandle<'h> {
handle_dev_info: HDEVINFO,
_lifetime_of_handle: PhantomData<&'h ()>
}
impl<'h> InfoHandle<'h> {
#[inline]
pub fn iter<'a>(&self, guid: &GUID) -> InfoIter<'a> {
InfoIter::from_handle_guid(self.handle_dev_info, guid)
}
}
impl<'h> Drop for InfoHandle<'h> {
#[inline]
fn drop(&mut self) {
// println!("Drop called");
unsafe { SetupDiDestroyDeviceInfoList(self.handle_dev_info) };
}
}
#[derive(Clone, Hash, Eq, PartialEq)]
pub struct Info<'p> {
path_ptr: LPCWSTR,
path_len_in_u16: DWORD,
_lifetime_of_path: PhantomData<&'p ()>,
}
impl<'p> Info<'p> {
fn from_device_path(path_ptr: LPCWSTR, path_len_in_u16: DWORD) -> Self {
Info {
path_ptr,
path_len_in_u16,
_lifetime_of_path: PhantomData,
}
}
/// Copies the path slice into an owned OsString.
pub fn to_os_string(&self) -> OsString {
OsString::from_wide(unsafe { core::slice::from_raw_parts(
self.path_ptr,
self.path_len_in_u16 as usize
) })
}
pub fn path_ptr(&self) -> LPCWSTR {
self.path_ptr
}
}
impl fmt::Debug for Info<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.to_os_string())
}
}
/// This iterator also manages a tiny heap buffer
///
/// TODO: is this exact sized?
#[derive(Clone)]
pub struct InfoIter<'iter> {
handle_dev_info: HDEVINFO, // maybe reused, do NOT free here
iter_index: DWORD,
interface_class_guid: *const GUID, // must be non-null
_lifetime_of_guid: PhantomData<&'iter ()>,
dev_interface_data: SP_DEVICE_INTERFACE_DATA,
detail_ptr: PSP_DEVICE_INTERFACE_DETAIL_DATA_W,
detail_len: DWORD, // size in u8, not in u16
detail_cap: DWORD,
_lifetime_of_detail: PhantomData<&'iter ()>,
}
impl<'iter> InfoIter<'iter> {
fn from_handle_guid(handle_dev_info: HDEVINFO, guid: &GUID) -> InfoIter<'iter> {
InfoIter {
handle_dev_info: handle_dev_info,
iter_index: 0,
interface_class_guid: guid as *const _,
_lifetime_of_guid: PhantomData,
dev_interface_data: create_sp_dev_interface_data(),
detail_ptr: core::ptr::null_mut(),
detail_len: 0,
detail_cap: 0,
_lifetime_of_detail: PhantomData,
}
}
}
impl fmt::Debug for InfoIter<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("InfoIter")
.field("handle_dev_info", &self.handle_dev_info)
.field("iter_index", &self.iter_index)
.field("detail_ptr", &self.detail_ptr)
.field("detail_len", &self.detail_len)
.field("detail_cap", &self.detail_cap)
.finish()
}
}
// todo: const fn
#[inline]
fn create_sp_dev_interface_data() -> SP_DEVICE_INTERFACE_DATA {
let mut ans: SP_DEVICE_INTERFACE_DATA =
unsafe { mem::MaybeUninit::uninit().assume_init() };
ans.cbSize = mem::size_of::<SP_DEVICE_INTERFACE_DATA>() as DWORD;
ans
}
impl<'iter> Drop for InfoIter<'iter> {
fn drop(&mut self) {
if self.detail_ptr != core::ptr::null_mut() {
let heap_handle = unsafe { GetProcessHeap() };
unsafe { HeapFree(heap_handle, 0, self.detail_ptr as *mut _) };
}
}
}
impl<'iter> Iterator for InfoIter<'iter> {
type Item = io::Result<Info<'iter>>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let ans = unsafe {
SetupDiEnumDeviceInterfaces(
self.handle_dev_info,
core::ptr::null_mut(),
self.interface_class_guid,
self.iter_index,
&self.dev_interface_data as *const _ as *mut _,
)
};
if ans == FALSE {
return if unsafe { GetLastError() } == ERROR_NO_MORE_ITEMS {
None
} else {
Some(Err(io::Error::last_os_error()))
};
}
loop {
let ans = unsafe {
SetupDiGetDeviceInterfaceDetailW(
self.handle_dev_info,
&self.dev_interface_data as *const _ as *mut _,
self.detail_ptr,
self.detail_cap,
&self.detail_len as *const _ as *mut _,
core::ptr::null_mut(),
)
};
if ans == TRUE {
break;
}
if unsafe { GetLastError() } == ERROR_INSUFFICIENT_BUFFER {
let heap_handle = unsafe { GetProcessHeap() };
self.detail_ptr = unsafe {
if self.detail_ptr == core::ptr::null_mut() {
HeapAlloc(heap_handle, 0, self.detail_len as usize) as *mut _
} else {
HeapReAlloc(
heap_handle,
0,
self.detail_ptr as *mut _,
self.detail_len as usize,
) as *mut _
}
};
unsafe {
(*self.detail_ptr).cbSize =
core::mem::size_of::<PSP_DEVICE_INTERFACE_DETAIL_DATA_W>() as DWORD
};
self.detail_cap = self.detail_len;
} else {
return Some(Err(io::Error::last_os_error()));
}
}
self.iter_index += 1;
let ret = Info::from_device_path(
unsafe { &(*self.detail_ptr).DevicePath as *const _ },
(self.detail_len / 2) - 3, // path_len_in_u16
);
Some(Ok(ret))
}
}
impl<'iter> FusedIterator for InfoIter<'iter> {}
/// Typestate struct
pub struct Device;
/// Typestate struct
pub struct Interface;
#[derive(Debug)]
pub struct ListOptions<'g, TYPE, OUTPUT> {
class_guid: *const GUID,
_lifetime_of_guid: PhantomData<&'g ()>,
enumerator: PCWSTR,
hwnd_parent: HWND,
flags: DWORD,
_typestate_setup_type: PhantomData<TYPE>,
_typestate_output: PhantomData<OUTPUT>,
}
impl<TYPE, OUTPUT> ListOptions<'_, TYPE, OUTPUT> {
#[inline]
pub const unsafe fn new_unchecked() -> Self {
Self {
class_guid: ptr::null(),
_lifetime_of_guid: PhantomData,
enumerator: ptr::null(),
hwnd_parent: ptr::null_mut(),
flags: 0,
_typestate_setup_type: PhantomData,
_typestate_output: PhantomData,
}
}
#[inline]
pub unsafe fn flags(&mut self, flags: DWORD) -> &mut Self {
self.flags = flags;
self
}
#[inline]
pub unsafe fn class_guid(&mut self, class_guid: &GUID) -> &mut Self {
self.class_guid = class_guid as *const _;
self
}
#[inline]
pub fn hwnd_parent(&mut self, hwnd_parent: HWND) -> &mut Self {
self.hwnd_parent = hwnd_parent;
self
}
#[inline]
pub fn present(&mut self) -> &mut Self {
self.flags |= DIGCF_PRESENT;
self
}
#[inline]
pub fn profile(&mut self) -> &mut Self {
self.flags |= DIGCF_PROFILE;
self
}
#[inline]
pub fn enumerator(&mut self, enumerator: &OsStr) -> &mut Self {
self.enumerator = enumerator as *const _ as *const u16;
self
}
}
impl<'h, TYPE, OUTPUT> ListOptions<'_, TYPE, OUTPUT>
where
OUTPUT: From<InfoHandle<'h>>
{
#[inline]
pub fn list(&self) -> io::Result<OUTPUT> {
let handle_dev_info = unsafe {
SetupDiGetClassDevsW(
self.class_guid,
self.enumerator,
self.hwnd_parent,
self.flags,
)
};
if handle_dev_info == INVALID_HANDLE_VALUE {
Err(io::Error::last_os_error())
} else {
Ok(OUTPUT::from(InfoHandle {
handle_dev_info,
_lifetime_of_handle: PhantomData
}))
}
}
}
impl<'g, OUTPUT> ListOptions<'g, Device, OUTPUT> {
#[inline]
pub const fn all_devices() -> ListOptions<'g, Device, OUTPUT> {
Self {
class_guid: ptr::null(),
_lifetime_of_guid: PhantomData,
enumerator: ptr::null(),
hwnd_parent: ptr::null_mut(),
flags: DIGCF_ALLCLASSES,
_typestate_setup_type: PhantomData,
_typestate_output: PhantomData,
}
}
#[inline]
pub const fn device_by_class(class_guid: &'g GUID) -> Self {
Self {
class_guid: class_guid as *const _,
_lifetime_of_guid: PhantomData,
enumerator: ptr::null(),
hwnd_parent: ptr::null_mut(),
flags: 0,
_typestate_setup_type: PhantomData,
_typestate_output: PhantomData,
}
}
}
impl<'g, OUTPUT> ListOptions<'g, Interface, OUTPUT> {
#[inline]
pub const fn all_interfaces() -> ListOptions<'g, Interface, OUTPUT> {
Self {
class_guid: ptr::null(),
_lifetime_of_guid: PhantomData,
enumerator: ptr::null(),
hwnd_parent: ptr::null_mut(),
flags: DIGCF_DEVICEINTERFACE | DIGCF_ALLCLASSES,
_typestate_setup_type: PhantomData,
_typestate_output: PhantomData,
}
}
#[inline]
pub const fn interface_by_class(class_guid: &'g GUID) -> ListOptions<'g, Interface, OUTPUT> {
Self {
class_guid: class_guid as *const _,
_lifetime_of_guid: PhantomData,
enumerator: ptr::null(),
hwnd_parent: ptr::null_mut(),
flags: DIGCF_DEVICEINTERFACE,
_typestate_setup_type: PhantomData,
_typestate_output: PhantomData,
}
}
#[inline]
pub fn supports_default(&mut self) -> &mut Self {
self.flags |= DIGCF_DEFAULT;
self
}
}
|
// CPU affinity using the `core_affinity` crate.
#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
mod affinity_core_affinity;
#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
pub use affinity_core_affinity::bind_to_single_core;
// CPU affinity using the `hwloc` library.
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
mod affinity_hwloc;
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
pub use affinity_hwloc::bind_to_single_core;
|
use std::error::Error as StdError;
use std::fmt;
use std::time::SystemTimeError;
/// Represents an Error that occurred while interacting with the Last.fm API
///
/// `ScrobblerError` contains an error message, which is set when an error occurs and exposed via Trait standard error
/// Trait implementations.
///
/// Most error handling for clients can operate off the `Ok`/`Err` signaling from the `Result` types of API operations,
/// however this error type is exposed in case you want to implement more complex error handling.
#[derive(Debug)]
pub struct ScrobblerError {
err_msg: String,
}
impl ScrobblerError {
pub fn new(err_msg: String) -> Self {
ScrobblerError { err_msg }
}
}
impl fmt::Display for ScrobblerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.err_msg)
}
}
impl StdError for ScrobblerError {}
impl From<SystemTimeError> for ScrobblerError {
fn from(error: SystemTimeError) -> Self {
Self::new(error.to_string())
}
}
impl From<String> for ScrobblerError {
fn from(error: String) -> Self {
Self::new(error)
}
}
|
//! This crate implements code for computing a tree-child sequence of a collection of trees.
pub mod clusters;
pub mod network;
pub mod newick;
pub mod tree;
pub mod tree_child_sequence;
|
/// My fizzbuzz for rust cause...
use std::env::args;
use std::fmt::{Display, Error, Formatter};
use std::ops::Add;
struct FizzBuzz(i32);
impl FizzBuzz {
fn new(n: i32) -> FizzBuzz {
FizzBuzz(n)
}
}
impl Display for FizzBuzz {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match (self.0, self.0 % 3, self.0 % 5) {
(_, 0, 0) => write!(f, "FizzBuzz"),
(_, 0, _) => write!(f, "Fizz"),
(_, _, 0) => write!(f, "Buzz"),
(i, _, _) => write!(f, "{}", i),
}
}
}
impl Add<i32> for FizzBuzz {
type Output = FizzBuzz;
fn add(self, other: i32) -> FizzBuzz {
FizzBuzz(self.0 + other)
}
}
fn main() {
let max: i32 = match args().nth(1) {
Some(n) => n.parse().unwrap(),
None => {
println!("usage: fizzbuzz <num>");
::std::process::exit(1)
}
};
let mut num = FizzBuzz::new(0);
for _ in 0..max {
num = num + 1;
println!("{}", num);
}
}
|
struct Solution();
// impl Solution {
// pub fn find_kth_largest(nums: Vec<i32>, k: i32) -> i32 {
// let mut nums=nums;
// nums.sort();
// nums[nums.len()-k as usize]
// }
// }
use std::collections::BinaryHeap ;
impl Solution {
pub fn find_kth_largest(nums: Vec<i32>, k: i32) -> i32 {
let mut bt: BinaryHeap<i32> = BinaryHeap::new();
for i in nums {
bt.push(i);
}
for i in 1.. {
if let Some(val)=bt.pop(){
if i == k {
return val;
}
}
}
0
}
}
fn main(){
println!("{}",Solution::find_kth_largest(vec![3,2,1,5,6,4],2));
} |
use crate::components::PathCacheComponent;
use crate::indices::EntityId;
use serde::{Deserialize, Serialize};
/// Update the path cache
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CachePathIntent {
pub bot: EntityId,
pub cache: PathCacheComponent,
}
/// Remove the top item from the path cache
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MutPathCacheIntent {
pub bot: EntityId,
pub action: PathCacheIntentAction,
}
impl Default for MutPathCacheIntent {
fn default() -> Self {
MutPathCacheIntent {
action: PathCacheIntentAction::Del,
bot: EntityId::default(),
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum PathCacheIntentAction {
Pop,
Del,
}
|
use syn::{Expr, ExprUnary, ExprBinary, UnOp, BinOp, ExprParen};
use syn::spanned::Spanned;
use proc_macro2::Span;
// Negate an expression.
pub fn negate(expr: &Expr) -> Expr {
match expr {
Expr::Unary(ExprUnary { op: UnOp::Neg(_), expr, .. }) => {
*expr.clone()
}
_ => ExprUnary {
attrs: vec!(),
op: UnOp::Neg(syn::token::Sub(Span::call_site())),
expr: Box::new(expr.clone()),
}.into()
}
}
// Strip parentheses.
pub fn deparen(expr: &Expr) -> &Expr {
match expr {
Expr::Paren(ExprParen { expr, .. }) => {
&*expr
}
_ => {
expr
}
}
}
// Convert a vector of expressions to a sum.
pub fn make_sum(sum: &[Expr]) -> Expr {
let right = &sum[sum.len()-1];
if sum.len() == 1 {
right.clone()
} else {
let left = Box::new(make_sum(&sum[0..sum.len()-1]));
if is_negated(&right) {
let right = Box::new(negate(&right));
let op = BinOp::Sub(syn::token::Sub(Span::call_site()));
Expr::Binary(ExprBinary { attrs: vec![], left, op, right })
} else {
let right = Box::new(right.clone());
let op = BinOp::Add(syn::token::Add(Span::call_site()));
Expr::Binary(ExprBinary { attrs: vec![], left, op, right })
}
}
}
pub fn is_negated(expr: &Expr) -> bool {
match expr {
Expr::Unary(ExprUnary { op: UnOp::Neg(_), .. }) => true,
_ => false
}
}
pub fn _is_paren(expr: &Expr) -> bool {
match expr {
Expr::Paren(_) => true,
_ => false
}
}
pub fn make_paren(expr: Expr) -> Expr {
ExprParen {
attrs: vec![],
paren_token: syn::token::Paren(expr.span()),
expr: Box::new(expr),
}
.into()
}
pub fn make_binary(left: Expr, op: BinOp, right: Expr) -> Expr {
ExprBinary {
attrs: vec![],
left: Box::new(left),
op: op,
right: Box::new(right),
}.into()
}
pub fn make_unary(op: UnOp, expr: Expr) -> Expr {
ExprUnary {
attrs: vec![],
op: op,
expr: Box::new(expr),
}.into()
}
|
use futures::Future;
use warp::{path, Filter};
use reqwest;
mod score;
use score::{ScoreRepo, ScoreView};
fn main() {
env_logger::init();
let help = path::end()
.and_then(|| {
let config = match ScoreRepo::new() {
Some(c) => c,
None => panic!("Error"),
};
config.get_competitions()
.map(|resp| resp)
.map_err(|err| warp::reject::custom(err))
})
.and_then(|mut resp: reqwest::r#async::Response| {
resp.json()
.map(|json| json)
.map_err(|err| warp::reject::custom(err))
})
.map(|json| match ScoreView::competitions(json) {
Some(s) => s,
None => String::from("No matches found today."),
});
let comps = path::param()
.and_then(|code: String| {
let config = match ScoreRepo::new() {
Some(c) => c,
None => panic!("Error"),
};
config
.get_scores(code)
.map(|resp| resp)
.map_err(|err| warp::reject::custom(err))
})
.and_then(|mut resp: reqwest::r#async::Response| {
resp.json()
.map(|json| json)
.map_err(|err| warp::reject::custom(err))
})
.map(|json| match ScoreView::scores(json) {
Some(s) => s,
None => String::from("No matches found today."),
});
let addr = if cfg!(debug_assertions) {
([127, 0, 0, 1], 3030)
} else {
([0, 0, 0, 0], 80)
};
warp::serve(help.or(comps)).run(addr);
}
|
use actix_web::http::HeaderValue;
use url::Url;
mod support;
#[actix_rt::test]
async fn health_check_works() {
// Arrange
let address = support::spawn_app(Url::parse("http://example.com/").unwrap());
// Act
let response = support::client()
.get(&format!("{}/health_check", &address))
.send()
.await
.expect("Failed to execute request.");
// Assert
assert!(response.status().is_success());
assert_eq!(
response.headers().get("Content-Length").unwrap(),
HeaderValue::from(0)
);
}
|
use github_v3::IssueCommenter;
use github_v3::types::repos::Repository;
use github_v3::types::comments::CreateIssueComment;
use types::SimplifiedIssueCommentEvent;
use rand::{thread_rng, sample};
use itertools::Itertools;
pub struct ReviewTagger {
reviewers: Vec<String>
}
impl ReviewTagger {
pub fn new(reviewers: Vec<String>) -> ReviewTagger {
ReviewTagger { reviewers: reviewers }
}
}
pub trait Tagger {
fn tag<T:IssueCommenter>(&self, event: &SimplifiedIssueCommentEvent, client: &T);
}
impl Tagger for ReviewTagger {
fn tag<T:IssueCommenter>(&self, event: &SimplifiedIssueCommentEvent, client: &T) {
let issue_id = event.issue_number.clone();
let repo_name = event.full_repo_name.clone();
let owner_name = event.owner_name.clone();
let sender_name = event.sender_name.clone();
let contained_comment = Some(event.comment_body.clone());
let _ = contained_comment
.into_iter()
.filter(|comment| comment.contains("pt r?"))
.map(|comment| {
match comment.matches("@").count() {
0 => (comment, 2),
1 => (comment, 1),
_ => (comment, 0)
}
})
.filter(|&(_, rec_count)| rec_count != 0)
.map(|(comment, rec_count)| {
let filtered_reviewers = self.reviewers.iter()
.filter(|reviewer| **reviewer != sender_name)
.filter(|reviewer| !comment.contains(*reviewer))
// TODO: No clone & collect here, must solve the is_empty() problem for iterator
.map(|reviewer| reviewer.clone())
.collect::<Vec<String>>();
(rec_count, filtered_reviewers)
})
.filter(|&(_, ref available_reviewers)| !available_reviewers.is_empty())
.foreach(|(rec_count, available_reviewers)| {
let repo = Repository{ owner: owner_name.clone(), repo_name: repo_name.clone() };
let mut rng = thread_rng();
let sample = sample(&mut rng, available_reviewers.iter(), rec_count);
let reviewers = sample.into_iter().fold("".to_owned(), |acc, ref reviewer| acc + "@" + &reviewer + " ");
let response = CreateIssueComment { body: "PTBOT: Assigning ".to_owned() + &reviewers + "to this PR" };
println!("LOG: Received a request for reviewers on issue {}, assigning {}", issue_id, reviewers);
let _ = client.create_comment(repo, issue_id, response);
});
}
}
#[cfg(test)]
mod tests {
use rusty_mock::*;
use expectest::core::expect;
use expectest::matchers::be_equal_to;
use super::*;
use github_v3::IssueCommenter;
use github_v3::types::repos::Repository;
use types::SimplifiedIssueCommentEvent;
use github_v3::types::{
GitErr,
IssueId,
};
use github_v3::types::comments::{
CommentId,
ListIssueCommentsQuery,
ListRepoCommentsQuery,
CreateIssueComment,
EditComment,
DeleteCommentStatus,
IssueComment,
};
struct IssueCommenterStub {
create_comment: ArgWatchingStub<Result<IssueComment, GitErr>, (Repository, IssueId, CreateIssueComment)>
}
impl IssueCommenterStub {
fn new() -> IssueCommenterStub {
IssueCommenterStub {
create_comment: ArgWatchingStub::new()
}
}
}
instrument_stub! {
IssueCommenterStub as IssueCommenter {
{ArgWatchingStub: create_comment(&self, repo: Repository, issue_id: IssueId, details: CreateIssueComment) -> Result<IssueComment, GitErr>}
{nostub: list_in_issue(&self, repo: Repository, issue_id: IssueId, query: Option<ListIssueCommentsQuery>) -> Result<Vec<IssueComment>, GitErr>}
{nostub: list_in_repo(&self, repo: Repository, query: Option<ListRepoCommentsQuery>) -> Result<Vec<IssueComment>, GitErr>}
{nostub: get_comment(&self, repo: Repository, comment_id: CommentId) -> Result<IssueComment, GitErr>}
{nostub: edit_comment(&self, repo: Repository, comment_id: CommentId, details: EditComment) -> Result<IssueComment, GitErr>}
{nostub: delete_comment(&self, repo: Repository, comment_id: CommentId) -> Result<DeleteCommentStatus, GitErr>}
}
}
fn default_stub() -> IssueCommenterStub {
let mut stub = IssueCommenterStub::new();
stub.create_comment.returns(Err(GitErr::NotImplemented("Testing".to_owned())));
stub
}
fn issue_comment_event_with_comment(comment: &str) -> SimplifiedIssueCommentEvent {
issue_comment_event_with_comment_and_commenter(comment, "sender_name")
}
fn issue_comment_event_with_comment_and_commenter(comment: &str, commenter: &str) -> SimplifiedIssueCommentEvent {
SimplifiedIssueCommentEvent::new("repo_name".to_owned(), 1, "user_name".to_owned(), commenter.to_owned(), comment.to_owned())
}
#[test]
fn it_does_nothing_when_the_review_caller_string_is_not_present() {
let stub = default_stub();
let event = issue_comment_event_with_comment("comment");
ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]).tag(&event, &stub);
expect!(stub.create_comment.was_called()).to(be_equal_to(false));
}
#[test]
fn it_calls_create_comment_with_the_issue() {
let stub = default_stub();
let event = issue_comment_event_with_comment("pt r?");
ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]).tag(&event, &stub);
expect!(stub.create_comment.was_called_once()).to(be_equal_to(true));
let (_, issue_id, _) = stub.create_comment.get_args_for_call(0).unwrap();
expect!(issue_id).to(be_equal_to(1));
}
#[test]
fn it_calls_create_comment_with_the_repo() {
let stub = default_stub();
let event = issue_comment_event_with_comment("pt r?");
ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]).tag(&event, &stub);
expect!(stub.create_comment.was_called_once()).to(be_equal_to(true));
let (repo, _, _) = stub.create_comment.get_args_for_call(0).unwrap();
let expected_repo = Repository { owner: "user_name".to_owned(), repo_name: "repo_name".to_owned() };
expect!(repo).to(be_equal_to(expected_repo));
}
#[test]
fn it_does_nothing_when_two_people_already_tagged() {
let stub = default_stub();
let event = issue_comment_event_with_comment("@acmcarther, @someone_else pt r?");
ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]).tag(&event, &stub);
expect!(stub.create_comment.was_called()).to(be_equal_to(false));
}
#[test]
fn it_tags_someone_if_one_person_was_tagged() {
let stub = default_stub();
let event = issue_comment_event_with_comment("pt r? @1");
ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]).tag(&event, &stub);
expect!(stub.create_comment.was_called_once()).to(be_equal_to(true));
let (_, _, call_comment) = stub.create_comment.get_args_for_call(0).unwrap();
// Since it's random who gets called, we have to check for both
expect!(call_comment.body.contains("@acmcarther") || call_comment.body.contains("@seanstrom")).to(be_equal_to(true));
}
#[test]
fn it_tags_two_people_if_nobody_was_tagged() {
let stub = default_stub();
let event = issue_comment_event_with_comment("pt r?");
ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]).tag(&event, &stub);
expect!(stub.create_comment.was_called()).to(be_equal_to(true));
let (_, _, call_comment) = stub.create_comment.get_args_for_call(0).unwrap();
expect!(call_comment.body.contains("@acmcarther") && call_comment.body.contains("@seanstrom")).to(be_equal_to(true));
}
#[test]
fn it_does_not_retag_people_already_tagged() {
let stub = default_stub();
let tagger = ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]);
// Since tagging is randomized, we should get a "significant" sample to verify this test
for call_idx in 0..10 {
let event = issue_comment_event_with_comment("@acmcarther pt r?");
tagger.tag(&event, &stub);
expect!(stub.create_comment.was_called_n_times(call_idx + 1)).to(be_equal_to(true));
let (_, _, call_comment) = stub.create_comment.get_args_for_call(call_idx as usize).unwrap();
expect!(call_comment.body.clone()).to(be_equal_to("PTBOT: Assigning @seanstrom to this PR"));
}
}
#[test]
fn it_does_not_tag_the_commenter() {
let stub = default_stub();
let tagger = ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]);
// Since tagging is randomized, we should get a "significant" sample to verify this test
for call_idx in 0..10 {
let event = issue_comment_event_with_comment_and_commenter("@someone_else pt r?", "seanstrom");
tagger.tag(&event, &stub);
expect!(stub.create_comment.was_called_n_times(call_idx + 1)).to(be_equal_to(true));
let (_, _, call_comment) = stub.create_comment.get_args_for_call(call_idx as usize).unwrap();
expect!(call_comment.body.clone()).to(be_equal_to("PTBOT: Assigning @acmcarther to this PR"));
}
}
#[test]
fn it_does_not_tag_anyone_if_theres_nobody_left_to_tag() {
let stub = default_stub();
let event = issue_comment_event_with_comment_and_commenter("@acmcarther pt r?", "seanstrom");
ReviewTagger::new(vec!["acmcarther".to_owned(), "seanstrom".to_owned()]).tag(&event, &stub);
expect!(stub.create_comment.was_called()).to(be_equal_to(false));
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SchemaId {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SchemaGroups {
#[serde(rename = "schemaGroups", default, skip_serializing_if = "Vec::is_empty")]
pub schema_groups: Vec<SchemaGroup>,
}
pub type SchemaGroup = String;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SchemaVersions {
#[serde(rename = "schemaVersions", default, skip_serializing_if = "Vec::is_empty")]
pub schema_versions: Vec<SchemaVersion>,
}
pub type SchemaVersion = i64;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Error {
pub error: ErrorDetail,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDetail>,
}
|
#[doc = "Reader of register INIT_WINDOW_NI_ANCHOR_PT"]
pub type R = crate::R<u32, super::INIT_WINDOW_NI_ANCHOR_PT>;
#[doc = "Reader of field `INIT_INT_OFF_CAPT`"]
pub type INIT_INT_OFF_CAPT_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Initiator interval offset captured at conn request. The value indicates the master connection anchor point. This value is in 625us slots"]
#[inline(always)]
pub fn init_int_off_capt(&self) -> INIT_INT_OFF_CAPT_R {
INIT_INT_OFF_CAPT_R::new((self.bits & 0xffff) as u16)
}
}
|
use std::ffi::OsStr;
use anyhow::{bail, format_err, Context as _, Result};
use camino::{Utf8Path, Utf8PathBuf};
use cargo_config2::Config;
use crate::{
cli::{ManifestOptions, Subcommand},
context::Context,
env,
process::ProcessBuilder,
};
pub(crate) struct Workspace {
pub(crate) name: String,
pub(crate) config: Config,
pub(crate) metadata: cargo_metadata::Metadata,
pub(crate) current_manifest: Utf8PathBuf,
pub(crate) target_dir: Utf8PathBuf,
pub(crate) output_dir: Utf8PathBuf,
pub(crate) doctests_dir: Utf8PathBuf,
pub(crate) profdata_file: Utf8PathBuf,
rustc: ProcessBuilder,
pub(crate) target_for_config: cargo_config2::TargetTriple,
pub(crate) target_for_cli: Option<String>,
pub(crate) rustc_version: RustcVersion,
/// Whether `-C instrument-coverage` is available.
pub(crate) stable_coverage: bool,
/// Whether `-Z doctest-in-workspace` is needed.
pub(crate) need_doctest_in_workspace: bool,
}
impl Workspace {
pub(crate) fn new(
options: &ManifestOptions,
target: Option<&str>,
doctests: bool,
show_env: bool,
) -> Result<Self> {
// Metadata and config
let config = Config::load()?;
let current_manifest = package_root(config.cargo(), options.manifest_path.as_deref())?;
let metadata = metadata(config.cargo(), ¤t_manifest)?;
let mut target_for_config = config.build_target_for_config(target)?;
if target_for_config.len() != 1 {
bail!("cargo-llvm-cov doesn't currently supports multi-target builds: {target_for_config:?}");
}
let target_for_config = target_for_config.pop().unwrap();
let target_for_cli = config.build_target_for_cli(target)?.pop();
let rustc = ProcessBuilder::from(config.rustc().clone());
let rustc_version = rustc_version(&rustc)?;
if doctests && !rustc_version.nightly {
bail!("--doctests flag requires nightly toolchain; consider using `cargo +nightly llvm-cov`")
}
let stable_coverage =
rustc.clone().args(["-C", "help"]).read()?.contains("instrument-coverage");
if !stable_coverage && !rustc_version.nightly {
bail!(
"cargo-llvm-cov requires rustc 1.60+; consider updating toolchain (`rustup update`)
or using nightly toolchain (`cargo +nightly llvm-cov`)"
);
}
let mut need_doctest_in_workspace = false;
if doctests {
need_doctest_in_workspace = cmd!(config.cargo(), "-Z", "help")
.read()
.map_or(false, |s| s.contains("doctest-in-workspace"));
}
let target_dir =
if let Some(path) = env::var("CARGO_LLVM_COV_TARGET_DIR")?.map(Utf8PathBuf::from) {
let mut base: Utf8PathBuf = env::current_dir()?.try_into()?;
base.push(path);
base
} else if show_env {
metadata.target_directory.clone()
} else {
// If we change RUSTFLAGS, all dependencies will be recompiled. Therefore,
// use a subdirectory of the target directory as the actual target directory.
metadata.target_directory.join("llvm-cov-target")
};
let output_dir = metadata.target_directory.join("llvm-cov");
let doctests_dir = target_dir.join("doctestbins");
let name = metadata.workspace_root.file_name().unwrap().to_owned();
let profdata_file = target_dir.join(format!("{name}.profdata"));
Ok(Self {
name,
config,
metadata,
current_manifest,
target_dir,
output_dir,
doctests_dir,
profdata_file,
rustc,
target_for_config,
target_for_cli,
rustc_version,
stable_coverage,
need_doctest_in_workspace,
})
}
pub(crate) fn cargo(&self, verbose: u8) -> ProcessBuilder {
let mut cmd = cmd!(self.config.cargo());
// cargo displays env vars only with -vv.
if verbose > 1 {
cmd.display_env_vars();
}
cmd
}
pub(crate) fn rustc(&self) -> ProcessBuilder {
self.rustc.clone()
}
// https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#--print-print-compiler-information
pub(crate) fn rustc_print(&self, kind: &str) -> Result<String> {
Ok(self
.rustc()
.args(["--print", kind])
.read()
.with_context(|| format!("failed to get {kind}"))?
.trim()
.into())
}
pub(crate) fn trybuild_target_dir(&self) -> Utf8PathBuf {
// https://github.com/dtolnay/trybuild/pull/219
let mut trybuild_target_dir = self.metadata.target_directory.join("tests").join("trybuild");
if !trybuild_target_dir.is_dir() {
trybuild_target_dir.pop();
trybuild_target_dir.push("target");
}
trybuild_target_dir
}
}
pub(crate) struct RustcVersion {
pub(crate) minor: u32,
pub(crate) nightly: bool,
}
fn rustc_version(rustc: &ProcessBuilder) -> Result<RustcVersion> {
let mut cmd = rustc.clone();
cmd.args(["--version", "--verbose"]);
let verbose_version = cmd.read()?;
let release = verbose_version
.lines()
.find_map(|line| line.strip_prefix("release: "))
.ok_or_else(|| format_err!("unexpected version output from `{cmd}`: {verbose_version}"))?;
let (version, channel) = release.split_once('-').unwrap_or((release, ""));
let mut digits = version.splitn(3, '.');
let minor = (|| {
let major = digits.next()?.parse::<u32>().ok()?;
if major != 1 {
return None;
}
let minor = digits.next()?.parse::<u32>().ok()?;
let _patch = digits.next().unwrap_or("0").parse::<u32>().ok()?;
Some(minor)
})()
.ok_or_else(|| format_err!("unable to determine rustc version"))?;
let nightly = channel == "nightly"
|| channel == "dev"
|| env::var("RUSTC_BOOTSTRAP")?.as_deref() == Some("1");
Ok(RustcVersion { minor, nightly })
}
fn package_root(cargo: &OsStr, manifest_path: Option<&Utf8Path>) -> Result<Utf8PathBuf> {
let package_root = if let Some(manifest_path) = manifest_path {
manifest_path.to_owned()
} else {
locate_project(cargo)?.into()
};
Ok(package_root)
}
// https://doc.rust-lang.org/nightly/cargo/commands/cargo-locate-project.html
fn locate_project(cargo: &OsStr) -> Result<String> {
cmd!(cargo, "locate-project", "--message-format", "plain").read()
}
// https://doc.rust-lang.org/nightly/cargo/commands/cargo-metadata.html
fn metadata(cargo: &OsStr, manifest_path: &Utf8Path) -> Result<cargo_metadata::Metadata> {
let mut cmd = cmd!(cargo, "metadata", "--format-version=1", "--manifest-path", manifest_path);
serde_json::from_str(&cmd.read()?).with_context(|| format!("failed to parse output from {cmd}"))
}
// https://doc.rust-lang.org/nightly/cargo/commands/cargo-test.html
// https://doc.rust-lang.org/nightly/cargo/commands/cargo-run.html
pub(crate) fn test_or_run_args(cx: &Context, cmd: &mut ProcessBuilder) {
if matches!(cx.args.subcommand, Subcommand::None | Subcommand::Test) && !cx.args.doctests {
let has_target_selection_options = cx.args.lib
| cx.args.bins
| cx.args.examples
| cx.args.tests
| cx.args.benches
| cx.args.all_targets
| cx.args.doc
| !cx.args.bin.is_empty()
| !cx.args.example.is_empty()
| !cx.args.test.is_empty()
| !cx.args.bench.is_empty();
if !has_target_selection_options {
cmd.arg("--tests");
}
}
for exclude in &cx.args.exclude_from_test {
cmd.arg("--exclude");
cmd.arg(exclude);
}
cmd.arg("--manifest-path");
cmd.arg(&cx.ws.current_manifest);
cmd.arg("--target-dir");
cmd.arg(&cx.ws.target_dir);
for cargo_arg in &cx.args.cargo_args {
cmd.arg(cargo_arg);
}
if !cx.args.rest.is_empty() {
cmd.arg("--");
cmd.args(&cx.args.rest);
}
}
// https://doc.rust-lang.org/nightly/cargo/commands/cargo-clean.html
pub(crate) fn clean_args(cx: &Context, cmd: &mut ProcessBuilder) {
if cx.args.release {
cmd.arg("--release");
}
if let Some(profile) = &cx.args.profile {
cmd.arg("--profile");
cmd.arg(profile);
}
if let Some(target) = &cx.args.target {
cmd.arg("--target");
cmd.arg(target);
}
if let Some(color) = cx.args.color {
cmd.arg("--color");
cmd.arg(color.cargo_color());
}
cmd.arg("--manifest-path");
cmd.arg(&cx.ws.current_manifest);
cmd.arg("--target-dir");
cmd.arg(&cx.ws.target_dir);
cx.args.manifest.cargo_args(cmd);
// If `-vv` is passed, propagate `-v` to cargo.
if cx.args.verbose > 1 {
cmd.arg(format!("-{}", "v".repeat(cx.args.verbose as usize - 1)));
}
}
|
use advent_of_code_2019::intcode_computer;
use std::fs;
fn main() {
let mut input = fs::read_to_string("resources/day2.input").unwrap();
input.pop();
let instructions = input
.split(",")
.map(|s| s.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
const PROGRAM_OUTPUT: i32 = 19690720;
'outer: for i in 0..100 {
for j in 0..100 {
let mut clone = intcode_computer::Program::new(instructions.clone(), None);
clone.instructions[1] = i;
clone.instructions[2] = j;
intcode_computer::process(&mut clone);
if i == 12 && j == 2 {
println!("program output at 1202 : {}", clone.instructions[0]);
}
if clone.instructions[0] == PROGRAM_OUTPUT {
let code = 100 * i + j;
println!("code for output {} : {}", PROGRAM_OUTPUT, code);
break 'outer;
}
}
}
}
|
use criterion::{criterion_group, criterion_main};
mod page_bench;
mod sm_bench;
criterion_group!(benches, page_bench::page_benchmark, sm_bench::sm_ins_bench);
criterion_main!(benches);
|
use crate::gui::make_dropdown_list_option;
use crate::sidebar::make_section;
use crate::{
gui::{BuildContext, Ui, UiMessage, UiNode},
physics::{Collider, Joint, RigidBody},
scene::commands::CommandGroup,
scene::{
commands::{
physics::{
AddJointCommand, DeleteBodyCommand, DeleteColliderCommand, DeleteJointCommand,
SetBallRadiusCommand, SetBodyCommand, SetColliderCommand,
SetColliderPositionCommand, SetCuboidHalfExtentsCommand,
SetCylinderHalfHeightCommand, SetCylinderRadiusCommand,
},
SceneCommand,
},
EditorScene, Selection,
},
send_sync_message,
sidebar::{
make_text_mark,
physics::{
ball::BallSection, body::BodySection, capsule::CapsuleSection,
collider::ColliderSection, cone::ConeSection, cuboid::CuboidSection,
cylinder::CylinderSection, joint::JointSection,
},
COLUMN_WIDTH, ROW_HEIGHT,
},
GameEngine, Message,
};
use rg3d::{
core::{
algebra::Matrix4, algebra::Vector3, math::aabb::AxisAlignedBoundingBox, pool::Handle,
scope_profile,
},
gui::{
button::ButtonBuilder,
dropdown_list::DropdownListBuilder,
grid::{Column, GridBuilder, Row},
message::{
ButtonMessage, DropdownListMessage, MessageDirection, UiMessageData, WidgetMessage,
},
stack_panel::StackPanelBuilder,
widget::WidgetBuilder,
Orientation, Thickness,
},
physics3d::desc::{
BallDesc, BallJointDesc, CapsuleDesc, ColliderShapeDesc, ConeDesc, CuboidDesc,
CylinderDesc, FixedJointDesc, HeightfieldDesc, JointParamsDesc, PrismaticJointDesc,
RevoluteJointDesc, RigidBodyTypeDesc, RoundCylinderDesc, SegmentDesc, TriangleDesc,
TrimeshDesc,
},
scene::{graph::Graph, node::Node},
};
use std::sync::mpsc::Sender;
mod ball;
mod body;
mod capsule;
mod collider;
mod cone;
mod cuboid;
mod cylinder;
mod joint;
mod segment;
mod triangle;
mod trimesh;
pub struct PhysicsSection {
pub section: Handle<UiNode>,
body: Handle<UiNode>,
collider: Handle<UiNode>,
collider_text: Handle<UiNode>,
joint: Handle<UiNode>,
joint_text: Handle<UiNode>,
fit: Handle<UiNode>,
sender: Sender<Message>,
pub body_section: BodySection,
pub collider_section: ColliderSection,
pub cylinder_section: CylinderSection,
pub cone_section: ConeSection,
pub cuboid_section: CuboidSection,
pub capsule_section: CapsuleSection,
pub ball_section: BallSection,
pub joint_section: JointSection,
}
impl PhysicsSection {
pub fn new(ctx: &mut BuildContext, sender: Sender<Message>) -> Self {
let body;
let collider;
let collider_text;
let joint;
let joint_text;
let fit;
let body_section = BodySection::new(ctx, sender.clone());
let collider_section = ColliderSection::new(ctx, sender.clone());
let cylinder_section = CylinderSection::new(ctx, sender.clone());
let cone_section = ConeSection::new(ctx, sender.clone());
let cuboid_section = CuboidSection::new(ctx, sender.clone());
let capsule_section = CapsuleSection::new(ctx, sender.clone());
let ball_section = BallSection::new(ctx, sender.clone());
let joint_section = JointSection::new(ctx, sender.clone());
let section = make_section(
"Physics Properties",
StackPanelBuilder::new(
WidgetBuilder::new()
.with_child(
GridBuilder::new(
WidgetBuilder::new()
.with_child(make_text_mark(ctx, "Body", 0))
.with_child({
body = DropdownListBuilder::new(
WidgetBuilder::new()
.on_row(0)
.on_column(1)
.with_margin(Thickness::uniform(1.0)),
)
.with_close_on_selection(true)
.with_items(vec![
make_dropdown_list_option(ctx, "None"),
make_dropdown_list_option(ctx, "Dynamic"),
make_dropdown_list_option(ctx, "Static"),
make_dropdown_list_option(ctx, "KinematicPositionBased"),
make_dropdown_list_option(ctx, "KinematicVelocityBased"),
])
.build(ctx);
body
})
.with_child({
collider_text = make_text_mark(ctx, "Collider", 1);
collider_text
})
.with_child({
collider = DropdownListBuilder::new(
WidgetBuilder::new()
.on_row(1)
.on_column(1)
.with_margin(Thickness::uniform(1.0)),
)
.with_close_on_selection(true)
.with_items(vec![
make_dropdown_list_option(ctx, "Ball"),
make_dropdown_list_option(ctx, "Cylinder"),
make_dropdown_list_option(ctx, "Round Cylinder"),
make_dropdown_list_option(ctx, "Cone"),
make_dropdown_list_option(ctx, "Cuboid"),
make_dropdown_list_option(ctx, "Capsule"),
make_dropdown_list_option(ctx, "Segment"),
make_dropdown_list_option(ctx, "Triangle"),
make_dropdown_list_option(ctx, "Trimesh"),
make_dropdown_list_option(ctx, "Heightfield"),
])
.build(ctx);
collider
})
.with_child({
joint_text = make_text_mark(ctx, "Joint", 2);
joint_text
})
.with_child({
joint = DropdownListBuilder::new(
WidgetBuilder::new()
.on_row(2)
.on_column(1)
.with_margin(Thickness::uniform(1.0)),
)
.with_close_on_selection(true)
.with_items(vec![
make_dropdown_list_option(ctx, "None"),
make_dropdown_list_option(ctx, "Ball Joint"),
make_dropdown_list_option(ctx, "Fixed Joint"),
make_dropdown_list_option(ctx, "Prismatic Joint"),
make_dropdown_list_option(ctx, "Revolute Joint"),
])
.build(ctx);
joint
})
.with_child({
fit = ButtonBuilder::new(
WidgetBuilder::new()
.with_margin(Thickness::uniform(1.0))
.on_row(3)
.on_column(1),
)
.with_text("Fit Collider")
.build(ctx);
fit
}),
)
.add_column(Column::strict(COLUMN_WIDTH))
.add_column(Column::stretch())
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.add_row(Row::strict(ROW_HEIGHT))
.build(ctx),
)
.with_children([
body_section.section,
collider_section.section,
cylinder_section.section,
cone_section.section,
cuboid_section.section,
capsule_section.section,
ball_section.section,
joint_section.section,
]),
)
.with_orientation(Orientation::Vertical)
.build(ctx),
ctx,
);
Self {
body_section,
collider_section,
cylinder_section,
cone_section,
cuboid_section,
capsule_section,
ball_section,
section,
body,
collider,
collider_text,
sender,
joint_section,
joint,
joint_text,
fit,
}
}
pub fn sync_to_model(&mut self, editor_scene: &EditorScene, engine: &mut GameEngine) {
if let Selection::Graph(selection) = &editor_scene.selection {
let scene = &engine.scenes[editor_scene.scene];
if selection.is_single_selection() {
let node_handle = selection.nodes()[0];
if scene.graph.is_valid_handle(node_handle) {
let ui = &mut engine.user_interface;
// Sync physical body info.
let mut body_index = 0;
let mut joint = Handle::NONE;
if let Some(&body_handle) = editor_scene.physics.binder.value_of(&node_handle) {
let body = &editor_scene.physics.bodies[body_handle];
body_index = match body.status {
RigidBodyTypeDesc::Dynamic => 1,
RigidBodyTypeDesc::Static => 2,
RigidBodyTypeDesc::KinematicPositionBased => 3,
RigidBodyTypeDesc::KinematicVelocityBased => 4,
};
for (h, j) in editor_scene.physics.joints.pair_iter() {
if j.body1 == body_handle.into() {
joint = h;
break;
}
}
}
send_sync_message(
ui,
DropdownListMessage::selection(
self.body,
MessageDirection::ToWidget,
Some(body_index),
),
);
fn toggle_visibility(ui: &mut Ui, destination: Handle<UiNode>, value: bool) {
send_sync_message(
ui,
WidgetMessage::visibility(
destination,
MessageDirection::ToWidget,
value,
),
);
}
toggle_visibility(ui, self.collider, body_index != 0);
toggle_visibility(ui, self.collider_text, body_index != 0);
toggle_visibility(ui, self.joint_text, body_index != 0);
toggle_visibility(ui, self.joint, body_index != 0);
toggle_visibility(ui, self.joint_section.section, joint.is_some());
toggle_visibility(ui, self.collider_section.section, false);
toggle_visibility(ui, self.cylinder_section.section, false);
toggle_visibility(ui, self.cone_section.section, false);
toggle_visibility(ui, self.cuboid_section.section, false);
toggle_visibility(ui, self.capsule_section.section, false);
toggle_visibility(ui, self.ball_section.section, false);
toggle_visibility(ui, self.body_section.section, false);
toggle_visibility(ui, self.fit, false);
if joint.is_some() {
let joint = &editor_scene.physics.joints[joint];
self.joint_section.sync_to_model(
joint,
&scene.graph,
&editor_scene.physics.binder,
ui,
);
let joint_index = match joint.params {
JointParamsDesc::BallJoint(_) => 1,
JointParamsDesc::FixedJoint(_) => 2,
JointParamsDesc::PrismaticJoint(_) => 3,
JointParamsDesc::RevoluteJoint(_) => 4,
};
send_sync_message(
ui,
DropdownListMessage::selection(
self.joint,
MessageDirection::ToWidget,
Some(joint_index),
),
);
} else {
send_sync_message(
ui,
DropdownListMessage::selection(
self.joint,
MessageDirection::ToWidget,
Some(0),
),
);
}
if let Some(&body_handle) = editor_scene.physics.binder.value_of(&node_handle) {
let body = &editor_scene.physics.bodies[body_handle];
if let Some(&collider_handle) = body.colliders.first() {
let collider = &editor_scene.physics.colliders[collider_handle.into()];
toggle_visibility(ui, self.collider_section.section, true);
toggle_visibility(ui, self.fit, true);
self.collider_section.sync_to_model(collider, ui);
}
self.body_section.sync_to_model(body, ui);
toggle_visibility(ui, self.body_section.section, true);
if let Some(&collider) = body.colliders.get(0) {
let collider_index =
match &editor_scene.physics.colliders[collider.into()].shape {
ColliderShapeDesc::Ball(ball) => {
toggle_visibility(ui, self.ball_section.section, true);
self.ball_section.sync_to_model(ball, ui);
0
}
ColliderShapeDesc::Cylinder(cylinder) => {
toggle_visibility(ui, self.cylinder_section.section, true);
self.cylinder_section.sync_to_model(cylinder, ui);
1
}
ColliderShapeDesc::RoundCylinder(_) => 2,
ColliderShapeDesc::Cone(cone) => {
toggle_visibility(ui, self.cone_section.section, true);
self.cone_section.sync_to_model(cone, ui);
3
}
ColliderShapeDesc::Cuboid(cuboid) => {
toggle_visibility(ui, self.cuboid_section.section, true);
self.cuboid_section.sync_to_model(cuboid, ui);
4
}
ColliderShapeDesc::Capsule(capsule) => {
toggle_visibility(ui, self.capsule_section.section, true);
self.capsule_section.sync_to_model(capsule, ui);
5
}
ColliderShapeDesc::Segment(_) => {
// TODO
6
}
ColliderShapeDesc::Triangle(_) => {
// TODO
7
}
ColliderShapeDesc::Trimesh(_) => {
// Nothing to edit.
8
}
ColliderShapeDesc::Heightfield(_) => {
// Nothing to edit.
9
}
};
send_sync_message(
ui,
DropdownListMessage::selection(
self.collider,
MessageDirection::ToWidget,
Some(collider_index),
),
);
} else {
send_sync_message(
ui,
DropdownListMessage::selection(
self.collider,
MessageDirection::ToWidget,
None,
),
);
}
}
}
}
}
}
pub fn handle_ui_message(
&mut self,
message: &UiMessage,
editor_scene: &EditorScene,
engine: &GameEngine,
) {
scope_profile!();
if let Selection::Graph(selection) = &editor_scene.selection {
let scene = &engine.scenes[editor_scene.scene];
let graph = &scene.graph;
if selection.is_single_selection() {
let node_handle = selection.nodes()[0];
if message.direction() == MessageDirection::FromWidget {
self.subsections_handle_ui_message(message, editor_scene, node_handle);
}
match message.data() {
UiMessageData::DropdownList(DropdownListMessage::SelectionChanged(index))
if message.direction() == MessageDirection::FromWidget =>
{
if message.destination() == self.collider {
self.select_collider(editor_scene, node_handle, *index);
}
if let Some(index) = index {
if message.destination() == self.body {
self.select_body(editor_scene, node_handle, graph, *index);
} else if message.destination() == self.joint {
self.select_joint(editor_scene, node_handle, *index);
}
}
}
UiMessageData::Button(ButtonMessage::Click)
if message.destination() == self.fit =>
{
self.fit_collider(editor_scene, node_handle, graph);
}
_ => {}
}
}
}
}
fn subsections_handle_ui_message(
&mut self,
message: &UiMessage,
editor_scene: &EditorScene,
node_handle: Handle<Node>,
) {
if let Some(&body_handle) = editor_scene.physics.binder.value_of(&node_handle) {
let body = &editor_scene.physics.bodies[body_handle];
self.body_section.handle_message(message, body, body_handle);
if let Some(&collider_handle) = body.colliders.first() {
let collider = &editor_scene.physics.colliders[collider_handle.into()];
self.collider_section
.handle_message(message, collider, collider_handle.into());
}
if let Some(&collider) = body.colliders.get(0) {
match &editor_scene.physics.colliders[collider.into()].shape {
ColliderShapeDesc::Ball(ball) => {
self.ball_section
.handle_message(message, ball, collider.into());
}
ColliderShapeDesc::Cylinder(cylinder) => {
self.cylinder_section
.handle_message(message, cylinder, collider.into());
}
ColliderShapeDesc::RoundCylinder(_) => {
// TODO
}
ColliderShapeDesc::Cone(cone) => {
self.cone_section
.handle_message(message, cone, collider.into());
}
ColliderShapeDesc::Cuboid(cuboid) => {
self.cuboid_section
.handle_message(message, cuboid, collider.into());
}
ColliderShapeDesc::Capsule(capsule) => {
self.capsule_section
.handle_message(message, capsule, collider.into());
}
ColliderShapeDesc::Segment(_) => {
// TODO
}
ColliderShapeDesc::Triangle(_) => {
// TODO
}
ColliderShapeDesc::Trimesh(_) => {
// Nothing to edit.
}
ColliderShapeDesc::Heightfield(_) => {
// Nothing to edit.
}
};
}
let mut joint = Handle::NONE;
for (h, j) in editor_scene.physics.joints.pair_iter() {
if j.body1 == body_handle.into() {
joint = h;
break;
}
}
if joint.is_some() {
self.joint_section.handle_message(
message,
&editor_scene.physics.joints[joint],
joint,
);
}
}
}
fn select_body(
&self,
editor_scene: &EditorScene,
node_handle: Handle<Node>,
graph: &Graph,
index: usize,
) {
match index {
0 => {
// Remove body.
if let Some(&body_handle) = editor_scene.physics.binder.value_of(&node_handle) {
let mut commands = Vec::new();
for &collider in editor_scene.physics.bodies[body_handle].colliders.iter() {
commands.push(SceneCommand::DeleteCollider(DeleteColliderCommand::new(
collider.into(),
)))
}
commands.push(SceneCommand::DeleteBody(DeleteBodyCommand::new(
body_handle,
)));
self.sender
.send(Message::DoSceneCommand(SceneCommand::CommandGroup(
CommandGroup::from(commands),
)))
.unwrap();
}
}
1 | 2 | 3 | 4 => {
let mut current_status = 0;
if let Some(&body) = editor_scene.physics.binder.value_of(&node_handle) {
current_status = match editor_scene.physics.bodies[body].status {
RigidBodyTypeDesc::Dynamic => 1,
RigidBodyTypeDesc::Static => 2,
RigidBodyTypeDesc::KinematicPositionBased => 3,
RigidBodyTypeDesc::KinematicVelocityBased => 4,
};
}
if index != current_status {
// Create body.
let node = &graph[node_handle];
let body = RigidBody {
position: node.global_position(),
rotation: **node.local_transform().rotation(),
status: match index {
1 => RigidBodyTypeDesc::Dynamic,
2 => RigidBodyTypeDesc::Static,
3 => RigidBodyTypeDesc::KinematicPositionBased,
4 => RigidBodyTypeDesc::KinematicVelocityBased,
_ => unreachable!(),
},
..Default::default()
};
let mut commands = Vec::new();
if let Some(&body) = editor_scene.physics.binder.value_of(&node_handle) {
for &collider in editor_scene.physics.bodies[body].colliders.iter() {
commands.push(SceneCommand::DeleteCollider(DeleteColliderCommand::new(
collider.into(),
)))
}
commands.push(SceneCommand::DeleteBody(DeleteBodyCommand::new(body)));
}
commands.push(SceneCommand::SetBody(SetBodyCommand::new(
node_handle,
body,
)));
self.sender
.send(Message::DoSceneCommand(SceneCommand::CommandGroup(
CommandGroup::from(commands),
)))
.unwrap();
}
}
_ => unreachable!(),
};
}
fn select_collider(
&self,
editor_scene: &EditorScene,
node_handle: Handle<Node>,
index: Option<usize>,
) {
if let Some(&body) = editor_scene.physics.binder.value_of(&node_handle) {
let current_index =
editor_scene.physics.bodies[body]
.colliders
.first()
.map(|&first_collider| {
editor_scene.physics.colliders[first_collider.into()]
.shape
.id() as usize
});
let (can_switch, index) = match (current_index, index) {
(Some(current_index), Some(index)) if current_index != index => (true, index),
(None, Some(index)) => (true, index),
_ => (false, 0),
};
if can_switch {
let collider = match index {
0 => Collider {
shape: ColliderShapeDesc::Ball(BallDesc { radius: 0.5 }),
..Default::default()
},
1 => Collider {
shape: ColliderShapeDesc::Cylinder(CylinderDesc {
half_height: 0.5,
radius: 0.5,
}),
..Default::default()
},
2 => Collider {
shape: ColliderShapeDesc::RoundCylinder(RoundCylinderDesc {
half_height: 0.5,
radius: 0.5,
border_radius: 0.1,
}),
..Default::default()
},
3 => Collider {
shape: ColliderShapeDesc::Cone(ConeDesc {
half_height: 0.5,
radius: 0.5,
}),
..Default::default()
},
4 => Collider {
shape: ColliderShapeDesc::Cuboid(CuboidDesc {
half_extents: Vector3::new(0.5, 0.5, 0.5),
}),
..Default::default()
},
5 => Collider {
shape: ColliderShapeDesc::Capsule(CapsuleDesc {
begin: Vector3::new(0.0, 0.0, 0.0),
end: Vector3::new(0.0, 1.0, 0.0),
radius: 0.5,
}),
..Default::default()
},
6 => Collider {
shape: ColliderShapeDesc::Segment(SegmentDesc {
begin: Vector3::new(0.0, 0.0, 0.0),
end: Vector3::new(1.0, 0.0, 0.0),
}),
..Default::default()
},
7 => Collider {
shape: ColliderShapeDesc::Triangle(TriangleDesc {
a: Vector3::new(0.0, 0.0, 0.0),
b: Vector3::new(1.0, 0.0, 0.0),
c: Vector3::new(1.0, 0.0, 1.0),
}),
..Default::default()
},
8 => Collider {
shape: ColliderShapeDesc::Trimesh(TrimeshDesc),
..Default::default()
},
9 => Collider {
shape: ColliderShapeDesc::Heightfield(HeightfieldDesc),
..Default::default()
},
_ => unreachable!(),
};
let mut commands = Vec::new();
// For now only one collider per body is supported.
// It is easy to add more.
if let Some(&first_collider) = editor_scene.physics.bodies[body].colliders.first() {
commands.push(SceneCommand::DeleteCollider(DeleteColliderCommand::new(
first_collider.into(),
)))
}
commands.push(SceneCommand::SetCollider(SetColliderCommand::new(
body, collider,
)));
self.sender
.send(Message::DoSceneCommand(SceneCommand::CommandGroup(
CommandGroup::from(commands),
)))
.unwrap();
}
}
}
fn select_joint(&self, editor_scene: &EditorScene, node_handle: Handle<Node>, index: usize) {
if let Some(&body_handle) = editor_scene.physics.binder.value_of(&node_handle) {
let mut joint = Handle::NONE;
for (h, j) in editor_scene.physics.joints.pair_iter() {
if j.body1 == body_handle.into() {
joint = h;
break;
}
}
let current_value = if joint.is_some() {
let joint = &editor_scene.physics.joints[joint];
match joint.params {
JointParamsDesc::BallJoint(_) => 1,
JointParamsDesc::FixedJoint(_) => 2,
JointParamsDesc::PrismaticJoint(_) => 3,
JointParamsDesc::RevoluteJoint(_) => 4,
}
} else {
0
};
if current_value != index {
let mut commands = Vec::new();
if joint.is_some() {
commands.push(SceneCommand::DeleteJoint(DeleteJointCommand::new(joint)));
}
match index {
0 => {
// Do nothing
}
1 => commands.push(SceneCommand::AddJoint(AddJointCommand::new(Joint {
body1: body_handle.into(),
body2: Default::default(),
params: JointParamsDesc::BallJoint(BallJointDesc {
local_anchor1: Default::default(),
local_anchor2: Default::default(),
}),
}))),
2 => commands.push(SceneCommand::AddJoint(AddJointCommand::new(Joint {
body1: body_handle.into(),
body2: Default::default(),
params: JointParamsDesc::FixedJoint(FixedJointDesc {
local_anchor1_translation: Default::default(),
local_anchor1_rotation: Default::default(),
local_anchor2_translation: Default::default(),
local_anchor2_rotation: Default::default(),
}),
}))),
3 => commands.push(SceneCommand::AddJoint(AddJointCommand::new(Joint {
body1: body_handle.into(),
body2: Default::default(),
params: JointParamsDesc::PrismaticJoint(PrismaticJointDesc {
local_anchor1: Default::default(),
local_axis1: Vector3::y(),
local_anchor2: Default::default(),
local_axis2: Vector3::x(),
}),
}))),
4 => commands.push(SceneCommand::AddJoint(AddJointCommand::new(Joint {
body1: body_handle.into(),
body2: Default::default(),
params: JointParamsDesc::RevoluteJoint(RevoluteJointDesc {
local_anchor1: Default::default(),
local_axis1: Vector3::y(),
local_anchor2: Default::default(),
local_axis2: Vector3::x(),
}),
}))),
_ => unreachable!(),
};
self.sender
.send(Message::DoSceneCommand(SceneCommand::CommandGroup(
CommandGroup::from(commands),
)))
.unwrap();
}
}
}
fn fit_collider(&self, editor_scene: &EditorScene, node_handle: Handle<Node>, graph: &Graph) {
if let Some(&body_handle) = editor_scene.physics.binder.value_of(&node_handle) {
let body = &editor_scene.physics.bodies[body_handle];
if let Some(&collider_handle) = body.colliders.first() {
let collider = &editor_scene.physics.colliders[collider_handle.into()];
let mut bounding_box = AxisAlignedBoundingBox::default();
for descendant in graph.traverse_handle_iter(node_handle) {
if let Node::Mesh(mesh) = &graph[descendant] {
let mut mesh_bb = mesh.bounding_box();
let scale = graph.global_scale_matrix(descendant);
let position = Matrix4::new_translation(&mesh.global_position());
mesh_bb.transform(position * scale);
bounding_box.add_box(mesh_bb);
}
}
let node_position = graph[node_handle].global_position();
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetColliderPosition(
SetColliderPositionCommand::new(
collider_handle.into(),
bounding_box.center() - node_position,
),
)))
.unwrap();
match &collider.shape {
ColliderShapeDesc::Ball(_) => {
let d = (bounding_box.max - bounding_box.min).scale(0.5);
let radius = d.x.max(d.y).max(d.z);
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetBallRadius(
SetBallRadiusCommand::new(collider_handle.into(), radius),
)))
.unwrap();
}
ColliderShapeDesc::Cylinder(_) => {
let d = (bounding_box.max - bounding_box.min).scale(0.5);
let radius = d.x.max(d.z);
let height = bounding_box.max.y - bounding_box.min.y;
let commands = CommandGroup::from(vec![
SceneCommand::SetCylinderRadius(SetCylinderRadiusCommand::new(
collider_handle.into(),
radius,
)),
SceneCommand::SetCylinderHalfHeight(SetCylinderHalfHeightCommand::new(
collider_handle.into(),
height * 0.5,
)),
]);
self.sender
.send(Message::DoSceneCommand(SceneCommand::CommandGroup(
commands,
)))
.unwrap();
}
ColliderShapeDesc::Cone(_) => {
// TODO
}
ColliderShapeDesc::Cuboid(_) => {
self.sender
.send(Message::DoSceneCommand(SceneCommand::SetCuboidHalfExtents(
SetCuboidHalfExtentsCommand::new(
collider_handle.into(),
(bounding_box.max - bounding_box.min).scale(0.5),
),
)))
.unwrap();
}
ColliderShapeDesc::Capsule(_) => {
// TODO
}
// Rest are not convex shapes, so there is no volume that can fit
// mesh's vertices.
_ => (),
}
}
}
}
}
|
use std::path::PathBuf;
use common::computer::{read_program_file, computer};
use std::collections::VecDeque;
pub fn part_1() -> i64 {
let path = PathBuf::from("./assets/boost.txt");
let memory = read_program_file(path).unwrap();
let (_, buffer) = computer(memory, Some(VecDeque::from(vec![1])));
buffer.last().unwrap().to_owned()
}
pub fn part_2() -> i64 {
let path = PathBuf::from("./assets/boost.txt");
let memory = read_program_file(path).unwrap();
let (_, buffer) = computer(memory, Some(VecDeque::from(vec![2])));
buffer.last().unwrap().to_owned()
} |
//! The `Document` struct represents an entire org file.
use super::*;
/// A complete org document/file.
///
/// Contains the global document properties and section before the first headline as well as the
/// list of all top level headlines.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Document {
pub preface: Option<greater_elements::Section>,
pub headlines: Vec<greater_elements::Headline>,
}
impl Document {
/// Gets an iterator over all keywords in the documents preface.
///
/// TODO maybe make this iterate over all keywords (not affiliated keywords) in the whole
/// document not just in the preface.
pub fn keywords(&self) -> Keywords<'_> {
unimplemented!()
}
}
use crate::parsing::Rule;
use pest::iterators::Pair;
use std::iter::FromIterator;
impl<'a> FromIterator<Pair<'a, Rule>> for Document {
fn from_iter<I: IntoIterator<Item = Pair<'a, Rule>>>(_iter: I) -> Self {
unimplemented!();
}
}
/// An iterator over all [`Keyword`]s in the [`Document::preface`].
///
/// This `struct` is currently only created by the [`keywords`] method on [`Document`]. In the
/// future it may be renamed and generated by methods on other elements.
///
/// [`Keyword`]: `elements::Keyword`
/// [`keywords`]: `Document::keywords`
#[derive(Debug, Clone)]
pub struct Keywords<'a> {
// TODO actually implement this iterator maybe as abstraction over other iterators
document: &'a Document,
}
impl<'a> Iterator for Keywords<'a> {
type Item = &'a elements::Keyword;
fn next(&mut self) -> Option<Self::Item> {
unimplemented!()
}
}
|
#![allow(unused_imports)]
pub mod glr_lex;
pub mod glr_grammar;
pub mod glr;
|
pub enum NetworkId {
// Germany
VVO,
}
|
use crate::errors::*;
use crate::types::*;
use uuid::Uuid;
/// Contains part of the list of user photos
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UserProfilePhotos {
#[doc(hidden)]
#[serde(rename(serialize = "@type", deserialize = "@type"))]
td_name: String,
#[doc(hidden)]
#[serde(rename(serialize = "@extra", deserialize = "@extra"))]
extra: Option<String>,
/// Total number of user profile photos
total_count: i64,
/// A list of photos
photos: Vec<UserProfilePhoto>,
}
impl RObject for UserProfilePhotos {
#[doc(hidden)]
fn td_name(&self) -> &'static str {
"userProfilePhotos"
}
#[doc(hidden)]
fn extra(&self) -> Option<String> {
self.extra.clone()
}
fn to_json(&self) -> RTDResult<String> {
Ok(serde_json::to_string(self)?)
}
}
impl UserProfilePhotos {
pub fn from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> {
Ok(serde_json::from_str(json.as_ref())?)
}
pub fn builder() -> RTDUserProfilePhotosBuilder {
let mut inner = UserProfilePhotos::default();
inner.td_name = "userProfilePhotos".to_string();
inner.extra = Some(Uuid::new_v4().to_string());
RTDUserProfilePhotosBuilder { inner }
}
pub fn total_count(&self) -> i64 {
self.total_count
}
pub fn photos(&self) -> &Vec<UserProfilePhoto> {
&self.photos
}
}
#[doc(hidden)]
pub struct RTDUserProfilePhotosBuilder {
inner: UserProfilePhotos,
}
impl RTDUserProfilePhotosBuilder {
pub fn build(&self) -> UserProfilePhotos {
self.inner.clone()
}
pub fn total_count(&mut self, total_count: i64) -> &mut Self {
self.inner.total_count = total_count;
self
}
pub fn photos(&mut self, photos: Vec<UserProfilePhoto>) -> &mut Self {
self.inner.photos = photos;
self
}
}
impl AsRef<UserProfilePhotos> for UserProfilePhotos {
fn as_ref(&self) -> &UserProfilePhotos {
self
}
}
impl AsRef<UserProfilePhotos> for RTDUserProfilePhotosBuilder {
fn as_ref(&self) -> &UserProfilePhotos {
&self.inner
}
}
|
extern crate petgraph;
extern crate onig;
use petgraph::graph::NodeIndex;
use onig::*;
use std::collections::HashMap;
use petgraph::Graph;
use petgraph::dot::{Dot, Config};
pub fn convert_horizontal_patterns_to_graph(graph: &mut Graph::<(usize, usize), u32, petgraph::Undirected>,
lines: &[&str],
delimiter: char,
continous: char) -> (Graph::<(usize, usize), u32, petgraph::Undirected>, HashMap<(usize, usize), NodeIndex>) {
let deps = graph;
let mut node_index: HashMap<(usize, usize), NodeIndex> = HashMap::new();
for (index, line) in lines.iter().enumerate() {
let re = Regex::new(&"\\-1[-2]*\\-1"
.replace("-1", &delimiter.to_string())
.replace("-2", &continous.to_string()))
.unwrap();
let re_with_lookfwd = Regex::new(&"(?=(\\-1[-1-2]*\\-1))"
.replace("-1", &delimiter.to_string())
.replace("-2", &continous.to_string()))
.unwrap();
let input_string_line = line.clone();
for ch in re_with_lookfwd.find_iter(&input_string_line) {
let mut end_marker = 0;
for (tempindex, iter) in input_string_line[ch.0 ..= input_string_line.len() - 1].chars().enumerate() {
// println!("Find the onwards pattern : {:?} {:?}", ch, end_marker);
if iter != continous && iter != delimiter {
end_marker = ch.0 + tempindex - 1;
break;
} else {
end_marker = ch.0 + tempindex;
}
if iter == delimiter && tempindex > 0 {
end_marker = ch.0 + tempindex;
// println!("++++++++++++++ {:?} -> {:?}", (index, ch.0), (index, end_marker));
let node_left;
let node_right;
match node_index.contains_key(&(index, ch.0)) {
true => {
node_left = *node_index.get(&(index, ch.0)).unwrap();
}, false => {
node_left = deps.add_node((index, ch.0));
node_index.insert((index, ch.0), node_left);
}
}
match node_index.contains_key(&(index, end_marker)) {
true => {
node_right = *node_index.get(&(index, end_marker)).unwrap();
}, false => {
node_right = deps.add_node((index, end_marker));
node_index.insert((index, end_marker), node_right);
}
}
let edge_weight = end_marker as u32 - ch.0 as u32;
match deps.contains_edge(node_left, node_right) {
true => {
// ignore adding the edge.
},
false => {
deps.add_edge(node_left, node_right, edge_weight);
}
}
println!("Horizontal {:?} -> {:?}, {:?}, {:?} {}",
end_marker, deps.node_weight(node_left),
deps.node_weight(node_right),
ch,
&input_string_line[ch.0..=end_marker]);
}
}
let node_left;
let node_right;
match node_index.contains_key(&(index, ch.0)) {
true => {
node_left = *node_index.get(&(index, ch.0)).unwrap();
}, false => {
node_left = deps.add_node((index, ch.0));
node_index.insert((index, ch.0), node_left);
}
}
match node_index.contains_key(&(index, end_marker)) {
true => {
node_right = *node_index.get(&(index, end_marker)).unwrap();
}, false => {
node_right = deps.add_node((index, end_marker));
node_index.insert((index, end_marker), node_right);
}
}
let edge_weight = end_marker as u32 - ch.0 as u32;
match deps.contains_edge(node_left, node_right) {
true => {
// ignore adding the edge.
},
false => {
deps.add_edge(node_left, node_right, edge_weight);
}
}
println!("Horizontal {:?} -> {:?}, {:?}, {:?} {}",
end_marker, deps.node_weight(node_left),
deps.node_weight(node_right),
ch,
&input_string_line[ch.0..=end_marker]);
}
let mut marker = 0;
while marker < line.len() {
// println!("Line -> {:?}", (line, marker));
match re.find(&line[marker..=line.len()-1]) {
Some(x) => {
// println!("String found {:?}", x);
println!("String found {:?} -> {:?}", (marker + x.0, marker + x.1 - 1), &line[marker + x.0..= marker + x.1-1]);
let node_left;
let node_right;
match node_index.contains_key(&(index, marker + x.0)) {
true => {
node_left = *node_index.get(&(index, marker + x.0)).unwrap();
}, false => {
node_left = deps.add_node((index, marker + x.0));
node_index.insert((index, marker + x.0), node_left);
}
}
match node_index.contains_key(&(index, marker+ x.1 -1)) {
true => {
node_right = *node_index.get(&(index, marker+ x.1 -1)).unwrap();
}, false => {
node_right = deps.add_node((index, marker+ x.1 -1));
node_index.insert((index, marker+ x.1 -1), node_right);
}
}
let edge_weight = (marker + x.1 - 1) as u32 - (marker + x.0) as u32;
match deps.contains_edge(node_left, node_right) {
true => {
// ignore adding the edge.
},
false => {
deps.add_edge(node_left, node_right, edge_weight);
}
}
marker += x.1 - 1;
},
None => {
break;
}
}
}
}
(deps.clone(), node_index.clone())
}
pub fn convert_vertical_patterns_to_graph(graph: &mut Graph::<(usize, usize), u32, petgraph::Undirected>,
lines: &[&str],
delimiter: char,
continous: char,
node_index: &mut HashMap<(usize, usize), NodeIndex>) -> Graph::<(usize, usize), u32, petgraph::Undirected> {
let deps = graph;
let colsize = match lines.len() {
0 => 0,
_ => lines[0].len()
};
for index in 0..colsize {
let mut line = String::new();
for rowindex in 0..lines.len() {
line.push(lines[rowindex].chars().nth(index).unwrap());
}
let re = Regex::new(&"\\-1[-2]*\\-1".replace("-1", &delimiter.to_string()).replace("-2", &continous.to_string())).unwrap();
let re_with_lookfwd = Regex::new(&"(?=(\\-1[-1-2]*\\-1))".replace("-1", &delimiter.to_string()).replace("-2", &continous.to_string())).unwrap();
let input_string_line = line.clone();
for ch in re_with_lookfwd.find_iter(&input_string_line) {
let mut end_marker = 0;
for (rowindex, iter) in input_string_line[ch.0 ..= input_string_line.len() - 1].chars().enumerate() {
if iter != continous && iter != delimiter {
end_marker = ch.0 + rowindex - 1;
break;
}
if iter == delimiter && rowindex > 0{
end_marker = ch.0 + rowindex;
let node_left;
let node_right;
match node_index.contains_key(&(ch.0, index)) {
true => {
node_left = *node_index.get(&(ch.0, index)).unwrap();
}, false => {
node_left = deps.add_node((ch.0, index));
node_index.insert((ch.0, index), node_left);
}
}
match node_index.contains_key(&(end_marker, index)) {
true => {
node_right = *node_index.get(&(end_marker, index)).unwrap();
}, false => {
node_right = deps.add_node((end_marker, index));
node_index.insert((end_marker, index), node_right);
}
}
let edge_weight = end_marker as u32 - ch.0 as u32;
match deps.contains_edge(node_left, node_right) {
true => {
// ignore adding the edge.
},
false => {
deps.extend_with_edges(&[(node_left, node_right, edge_weight)]);
}
}
}
}
let node_left;
let node_right;
match node_index.contains_key(&(ch.0, index)) {
true => {
node_left = *node_index.get(&(ch.0, index)).unwrap();
}, false => {
node_left = deps.add_node((ch.0, index));
node_index.insert((ch.0, index), node_left);
}
}
match node_index.contains_key(&(end_marker, index)) {
true => {
node_right = *node_index.get(&(end_marker, index)).unwrap();
}, false => {
node_right = deps.add_node((end_marker, index));
node_index.insert((end_marker, index), node_right);
}
}
let edge_weight = end_marker as u32 - ch.0 as u32;
match deps.contains_edge(node_left, node_right) {
true => {
// ignore adding the edge.
},
false => {
deps.extend_with_edges(&[(node_left, node_right, edge_weight)]);
}
}
}
let mut marker = 0;
let line_cloned = &line.clone();
while marker < line_cloned.len() {
// println!("Line -> {:?}", (line_cloned, marker));
match re.find(&line_cloned[marker..=line_cloned.len()-1]) {
Some(x) => {
let node_left;
let node_right;
match node_index.contains_key(&(marker + x.0, index)) {
true => {
node_left = *node_index.get(&(marker + x.0, index)).unwrap();
}, false => {
node_left = deps.add_node((marker + x.0, index));
node_index.insert((marker + x.0, index), node_left);
}
}
match node_index.contains_key(&(marker+ x.1 -1, index)) {
true => {
node_right = *node_index.get(&(marker+ x.1 -1, index)).unwrap();
}, false => {
node_right = deps.add_node((marker+ x.1 -1, index));
node_index.insert((marker+ x.1 -1, index), node_right);
}
}
let edge_weight = (marker + x.1 - 1) as u32 - (marker + x.0) as u32;
match deps.contains_edge(node_left, node_right) {
true => {
// ignore adding the edge.
},
false => {
deps.extend_with_edges(&[(node_left, node_right, edge_weight)]);
}
}
marker += x.1-1;
},
None => {
break;
}
}
}
}
deps.clone()
}
extern crate itertools;
use itertools::Itertools;
pub fn count(lines: &[&str]) -> u32 {
let mut deps = Graph::<(usize, usize), u32, petgraph::Undirected>::new_undirected();
let (mut graph, mut node_index) = convert_horizontal_patterns_to_graph(&mut deps, lines, '+', '-');
let graph_w_h = convert_vertical_patterns_to_graph(&mut graph, lines, '+', '|', &mut node_index);
let indexes = graph_w_h.node_indices().collect::<Vec<_>>();
let mut output_vector = Vec::new();
for start in indexes {
let root_node_weight = graph_w_h.node_weight(start).unwrap();
let neighbors = graph_w_h.neighbors_undirected(start).collect::<Vec<_>>();
if neighbors.len() >= 2 {
for neighbor in neighbors.iter().combinations(2) {
let node_start = neighbor[0];
let node_end = neighbor[1];
let node_start_neighbor_node_weight = graph_w_h.node_weight(*node_start).unwrap();
let node_start_neighbor_edge = graph_w_h.find_edge_undirected(start, *node_start).unwrap();
let node_start_neighbor_edge_weight = graph_w_h.edge_weight(node_start_neighbor_edge.0).unwrap();
let node_end_neighbor_node_weight = graph_w_h.node_weight(*node_end).unwrap();
let node_end_neighbor_edge = graph_w_h.find_edge_undirected(start, *node_end).unwrap();
let node_end_neighbor_edge_weight = graph_w_h.edge_weight(node_end_neighbor_edge.0).unwrap();
let target_weight_start = node_end_neighbor_edge_weight;
let target_weight_end = node_start_neighbor_edge_weight;
pub fn pursuit (graph_w_h: &Graph::<(usize, usize), u32, petgraph::Undirected>,
node: NodeIndex,
path: Vec<(usize, usize)>,
sum: u32,
goal: u32,
node_end: NodeIndex,
node_start: NodeIndex,
output_vector: &mut std::vec::Vec<std::vec::Vec<(usize, usize)>>) -> Option<(Vec<(usize, usize)>, u32)> {
let mut res: Option<(Vec<(usize, usize)>, u32)> = None;
if sum == goal {
let node_neighbor_edge_end = graph_w_h.find_edge_undirected(node, node_end);
let node_neighbor_edge_orig_start = graph_w_h.find_edge_undirected(node, node_start);
if node_neighbor_edge_end != None && node_neighbor_edge_orig_start != None {
//println!("End pursuit : path = {:?} sum = {:?} goal = {:?} ", path, sum, goal);
let mut temp_entry = path.clone();
temp_entry.sort();
temp_entry.dedup();
if temp_entry.len() == 4 {
output_vector.push(temp_entry);
}
res = Some((path, sum));
}
} else if sum > goal || path.contains(graph_w_h.node_weight(node).unwrap()) && sum != 0 {
res = None;
}
else {
let neighbors_node = graph_w_h.neighbors_undirected(node).collect::<Vec<_>>();
if neighbors_node.len() >= 2 {
for neighbour_node in neighbors_node {
let node_neighbor_node_weight = graph_w_h.node_weight(neighbour_node).unwrap();
let node_neighbor_node_weight_end = graph_w_h.node_weight(node_end).unwrap();
let node_neighbor_edge_start = graph_w_h.find_edge_undirected(node, neighbour_node).unwrap();
let node_neighbor_edge_weight = graph_w_h.edge_weight(node_neighbor_edge_start.0).unwrap();
let node_neighbor_edge_end = graph_w_h.find_edge_undirected(neighbour_node, node_end);
let node_neighbor_edge_orig_start = graph_w_h.find_edge_undirected(neighbour_node, node_start);
if node_neighbor_edge_end != None { // && node_neighbor_edge_orig_start != None {
if !path.contains(node_neighbor_node_weight) {
let mut path = path.clone();
path.push(*node_neighbor_node_weight);
res = pursuit(&graph_w_h, neighbour_node, path, sum + node_neighbor_edge_weight, goal, node_end, node_start, output_vector);
}
} else {
res = None
}
}
}
}
res
};
let mut path = Vec::new();
path.push(*root_node_weight);
path.push(*node_start_neighbor_node_weight);
path.push(*node_end_neighbor_node_weight);
pursuit(&graph_w_h, *node_start, path, 0, *target_weight_start, *node_end, *node_start, &mut output_vector);
let mut path = Vec::new();
path.push(*root_node_weight);
path.push(*node_start_neighbor_node_weight);
path.push(*node_end_neighbor_node_weight);
pursuit(&graph_w_h, *node_end, path, 0, *target_weight_end, *node_end, *node_start, &mut output_vector);
}
}
}
println!("Captured rectangles ... ");
for out in output_vector.clone() {
//println!("--> {:?}", out);
}
output_vector.sort();
output_vector.dedup();
let mut count = 0;
for out in output_vector {
let distance_left: f64 = ((out[1].0 as f64 - out[0].0 as f64).powf(2.0) + (out[1].1 as f64 - out[0].1 as f64).powf(2.0)).sqrt();
let distance_right: f64 = ((out[3].0 as f64 - out[2].0 as f64).powf(2.0) + (out[3].1 as f64 - out[2].1 as f64).powf(2.0)).sqrt();
let distance_top: f64 = ((out[3].0 as f64 - out[0].0 as f64).powf(2.0) + (out[3].1 as f64- out[2].1 as f64).powf(2.0)).sqrt();
let distance_down: f64 = ((out[2].0 as f64 - out[1].0 as f64).powf(2.0) + (out[2].1 as f64- out[1].1 as f64).powf(2.0)).sqrt();
if (distance_left == distance_right) && (distance_top == distance_down) {
count += 1;
} else {
println!("Dropped rectangles {:?} -> {:?} {:?}", out, (distance_left, distance_right), (distance_top, distance_down));
}
}
println!("{:?}", Dot::with_config(&graph_w_h, &[]));
count
}
|
fn main() {
println!("{}", farenheit_to_celcius(68.00));
println!("{}", fibonaaci(5))
}
fn farenheit_to_celcius(temprature: f64) -> f64 {
(temprature - 32.0) * 5.0/9.0
}
fn fibonaaci(n: i64) -> i64 {
if n == 0 {
return 0;
} else if n == 1 {
return 1;
} else {
return fibonaaci(n - 1) + fibonaaci(n - 2);
}
} |
use super::super::*;
use math::*;
use glium;
use glium::{
glutin::{
event_loop::{
EventLoop,
ControlFlow,
},
event::{
Event,
StartCause,
WindowEvent,
ElementState,
},
window::WindowBuilder,
ContextBuilder,
},
Display,
Program,
Surface,
};
use std::time::{Instant, Duration};
use std::collections::{HashMap, HashSet};
use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::sync_channel;
use std::sync::atomic::AtomicBool;
/// This is the struct responsible for running the program.
pub struct Application {
pub(crate) title: &'static str,
pub(crate) frame_time: Duration,
pub(crate) aspect_ratio: Option<f32>,
pub(crate) resizable: bool,
pub(crate) window_size: Vec2<u32>,
pub(crate) frame_size: Option<Vec2<f32>>,
pub(crate) pixel_window_size: Option<Vec2<u32>>,
pub(crate) depth_sorting: bool,
}
impl Application {
/// Creates a new application
pub fn new() -> Application {
Application {
title: "gui application",
frame_time: Duration::from_secs_f32(1.0/60.0),
aspect_ratio: None,
resizable: true,
frame_size: None,
window_size: Vec2::new(800, 600),
pixel_window_size: None,
depth_sorting: false,
}
}
/// Sets the title of the application
pub fn with_title(mut self, title: &'static str) -> Application {
self.title = title;
self
}
/// Sets the fps of the application
pub fn with_fps(mut self, fps: f32) -> Application {
self.frame_time = Duration::from_secs_f32(1.0/fps);
self
}
/// Sets the fame size
pub fn with_frame_size(mut self, width: f32, height: f32) -> Application {
self.frame_size = Some(Vec2::new(width, height));
self
}
/// Sets the window of the application to non-resizable
pub fn not_resizable(mut self) -> Application {
self.resizable = false;
self
}
/// Sets the window size of the application
pub fn with_window_size(mut self, width: u32, height: u32) -> Application {
self.window_size = Vec2::new(width, height);
self
}
/// Starts the application in pixel-mode with a given size
pub fn with_pixel_window_size(mut self, width: u32, height: u32) -> Application {
self.pixel_window_size = Some(Vec2::new(width, height));
self
}
/// Enables depth sorting
pub fn with_depth_sorting(mut self, depth_sorting: bool) -> Application {
self.depth_sorting = depth_sorting;
self
}
/// Runs the application and takes a closure that returns a Box containing the first state
pub fn run<F>(self, mut start: F)
where F: FnMut(&mut super::super::Loader) -> Box<dyn State>
{
//
// initialization
//
#[cfg(debug_assertions)]
println!("GUI::INITIALIZATION Initializing OPEN_GL");
let event_loop = EventLoop::new();
let wb = WindowBuilder::new()
.with_resizable(self.resizable)
.with_inner_size(
glium::glutin::dpi::LogicalSize::new(self.window_size.x as f64, self.window_size.y as f64)
)
.with_title(self.title);
let cb = ContextBuilder::new();
let display = Display::new(wb, cb, &event_loop)
.expect("GUI::INITIALIZATION Failed to create glium::Display");
// programs
#[cfg(debug_assertions)]
println!("GUI::INITIALIZATION Loading Shaders");
let simple_transform_fill = Program::from_source(
&display,
include_str!("../shaders/vertex/simple_transform.glsl"),
include_str!("../shaders/fragment/fill.glsl"),
None
);
if let Err(err) = &simple_transform_fill {
println!("{:?}", err)
}
let simple_transform_fill = simple_transform_fill.unwrap();
#[cfg(debug_assertions)]
println!("GUI::APPLICATION Starting Application");
let mut mouse_position = Vec2::new(0.0, 0.0);
let mut scaled_mouse_position = Vec2::new(0.0, 0.0);
// calculate buffer_dimensions
let buffer_dimensions = display.get_framebuffer_dimensions();
let buffer_dimensions_u32 = Vec2::new(buffer_dimensions.0, buffer_dimensions.1);
let buffer_dimensions = Vec2::new(buffer_dimensions.0 as f32, buffer_dimensions.1 as f32);
// calculate window_dimensions set by the application
let window_dimensions = Vec2::new(self.window_size.x as f32, self.window_size.y as f32);
let frame_size = self.frame_size.unwrap_or(window_dimensions/window_dimensions.y * 2.0);
// in some cases the size of the window generated by the OS would match the dimensions
// specified by the application, a window_dimensions_multiplier is therefore calculated to
// insure everything is drawn as expected
let window_dimensions_multiplier = buffer_dimensions / window_dimensions;
// calculate the aspect ratio
let aspect_ratio = frame_size.x / frame_size.y;
//
// inputs
//
let mut keys_held = HashSet::new();
let mut mouse_buttons_held = HashSet::new();
let mut keys_pressed = HashSet::new();
let mut keys_released = HashSet::new();
let mut mouse_buttons_pressed = HashSet::new();
let mut mouse_buttons_released = HashSet::new();
#[cfg(debug_assertions)]
println!("GUI::APPLICATION Running start function");
//
// loader
//
let mut image_indecies = HashMap::new();
let mut image_dimensions = Vec::new();
let mut font_indecies = HashMap::new();
let mut font_character_infos = Vec::new();
let mut font_dimensions = Vec::new();
let mut text_inputs = Vec::new();
let mut loader = super::super::Loader {
display: &display,
image_indecies: &mut image_indecies,
font_indecies: &mut font_indecies,
images: Vec::new(),
fonts: Vec::new(),
image_dimensions: &mut image_dimensions,
font_dimensions: &mut font_dimensions,
font_character_infos: &mut font_character_infos,
text_inputs: &mut text_inputs,
};
let states: Arc<Mutex<Vec<Box<dyn State>>>> = Arc::new(Mutex::new(vec![start(&mut loader)]));
let (image_atlas, image_positions, image_atlas_dimensions) = crate::texture_atlas::crate_atlas(&display, &mut loader.images, &mut loader.image_dimensions);
let (font_atlas, font_positions, font_atlas_dimensions) = crate::texture_atlas::crate_atlas(&display, &mut loader.fonts, &mut loader.font_dimensions);
// if pixel mode is set, there is no reason to keep remaking the frame buffer every frame
// therefore we make it now and clear it every frame which is considerably faster
let size = self.pixel_window_size.unwrap_or(buffer_dimensions_u32);
// create texture_buffer
let mut texture_buffer = glium::texture::texture2d::Texture2d::empty(
&display,
size.x,
size.y
).expect("failed to create texture buffer");
// used to ensure that we don't go above the desired frame rate
let mut next_frame_time = Instant::now() + self.frame_time;
// init buffers
let mut line_point_buffer = glium::buffer::Buffer::<[[f32; 4]]>::new(
&display,
&[],
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
let mut line_width_buffer = glium::buffer::Buffer::<[f32]>::new(
&display,
&[],
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
let mut vertex_buffer = glium::VertexBuffer::new(&display, &[]).unwrap();
let state_data = Arc::new(Mutex::new(StateData {
delta_time: 0.016,
frame_dimensions: Vec2::new(aspect_ratio * 2.0, 2.0),
scaled_frame_dimensions: Vec2::new(aspect_ratio * 2.0, 2.0),
window_dimensions: Vec2::new(self.window_size.x as f32, self.window_size.y as f32),
aspect_ratio,
mouse_position,
scaled_mouse_position,
keys_pressed: keys_pressed.clone(),
keys_held: keys_held.clone(),
keys_released: keys_released.clone(),
mouse_buttons_pressed: mouse_buttons_pressed.clone(),
mouse_buttons_held: mouse_buttons_held.clone(),
mouse_buttons_released: mouse_buttons_released.clone(),
}));
#[cfg(debug_assertions)]
println!("GUI::APPLICATION Starting threads");
let running = Arc::new(AtomicBool::new(true));
//
// drawing thread
//
let (drawing_data_sender, drawing_data_receiver) = sync_channel::<DrawingData>(1);
let (main_drawing_data_sender, main_drawing_data_receiver) = sync_channel::<DrawingData>(1);
// honestly this code is garbage, I hate it
let draw_thread = {
let drawing_data = DrawingData {
frame_size,
line_points: Vec::new(),
line_widths: Vec::new(),
verts: Vec::new(),
mask_shapes: Vec::new(),
rect_mask_positions: Vec::new(),
rect_mask_sizes: Vec::new(),
rect_mask_rotations: Vec::new(),
// FIXME: cloning is bad, find another way
image_indecies: image_indecies.clone(),
image_dimensions: image_dimensions.clone(),
font_indecies: font_indecies.clone(),
font_dimensions: font_dimensions.clone(),
font_character_infos: font_character_infos.clone(),
scaled_aspect_ratio: aspect_ratio,
aspect_ratio: aspect_ratio,
font_atlas_dimensions: font_atlas_dimensions,
font_positions: font_positions.clone(),
image_atlas_dimensions: image_atlas_dimensions,
image_positions: image_positions.clone(),
};
let states = states.clone();
let state_data = state_data.clone();
let mut last_frame_vertex_count = 0;
let frame_time = self.frame_time.clone();
let running = running.clone();
// running drawing thread
thread::spawn(move || {
while running.load(std::sync::atomic::Ordering::SeqCst) {
let draw_start = Instant::now();
{
let states = {
states.lock().unwrap().clone()
};
let mut drawing_data = main_drawing_data_receiver.try_recv().unwrap_or_else(|_| drawing_data.clone());
let state_data = {
state_data.lock().unwrap().clone()
};
drawing_data.verts = Vec::with_capacity(last_frame_vertex_count);
let index = states.len() - 1;
let mut frame = Frame {
drawing_data: &mut drawing_data,
};
// run draw for current state
states[index].draw(
&mut frame,
&state_data,
);
// run shadow draw for all states
states.iter().for_each(|state| state.shadow_draw(
&mut frame,
&state_data,
));
// set last frame vertex count
last_frame_vertex_count = drawing_data.verts.len();
let _ = drawing_data_sender.try_send(drawing_data);
}
frame_time.checked_sub(Instant::now().duration_since(draw_start)).map(|duration| {
thread::sleep(duration);
});
}
})
};
//
// update thread
//
let update_thread = {
let states = states.clone();
let state_data = state_data.clone();
let mut last_update_time = Instant::now();
let running = running.clone();
// running update thread
thread::spawn(move || {
while running.load(std::sync::atomic::Ordering::SeqCst) {
let update_start = Instant::now();
{
let delta_time = Instant::now().duration_since(last_update_time).as_secs_f32();
last_update_time = Instant::now();
let mut states = states.lock().unwrap();
let mut state_data = {
state_data.lock().unwrap()
};
let index = states.len() - 1;
// run update for current state
let trans = states[index].update(&state_data);
// run shadow update for all states
states.iter_mut().for_each(|state| state.shadow_update(&state_data));
match trans {
Transition::Trans(state) => {
*states = vec![state];
},
Transition::Push(state) => {
states.push(state);
},
Transition::Pop => {
states.pop();
if states.len() == 0 {
running.store(false, std::sync::atomic::Ordering::SeqCst);
}
},
Transition::None => (),
}
state_data.delta_time = delta_time;
}
std::time::Duration::from_secs_f32(1.0/60.0).checked_sub(Instant::now().duration_since(update_start)).map(|duration| {
thread::sleep(duration);
});
}
})
};
let mut draw_thread = Some(draw_thread);
let mut update_thread = Some(update_thread);
let mut join_threads = move || {
let draw_thread = std::mem::replace(&mut draw_thread, None);
let update_thread = std::mem::replace(&mut update_thread, None);
draw_thread.map(|thread| thread.join());
update_thread.map(|thread| thread.join());
};
#[cfg(debug_assertions)]
println!("GUI::APPLICATION Running main loop");
// main loop
event_loop.run(move |event, _, flow| {
if !running.load(std::sync::atomic::Ordering::SeqCst) {
join_threads();
*flow = ControlFlow::Exit;
return;
}
// update next_frame_time
if next_frame_time <= Instant::now() {
next_frame_time = Instant::now() + self.frame_time;
}
// set ControlFlow as to wait until the time for the next frame is reached before
// redrawing
*flow = ControlFlow::WaitUntil(next_frame_time);
// get window dimensions
let dims = display.get_framebuffer_dimensions();
// dims as f32
let w = dims.0 as f32;
let h = dims.1 as f32;
let window_dimensions = Vec2::new(w, h);
// used for scaling shapes
let scaled_aspect_ratio = w / h;
// event handling
match event {
Event::WindowEvent {event, ..} => match event {
// if the window requests closing it, do so
WindowEvent::CloseRequested => {
running.store(false,std::sync::atomic::Ordering::SeqCst);
join_threads();
*flow = ControlFlow::Exit;
return;
},
// update cursor position when it is moved
WindowEvent::CursorMoved {position, ..} => {
mouse_position = (Vec2::new(
position.x as f32,
position.y as f32
) * window_dimensions_multiplier
/ window_dimensions * 2.0 - 1.0) * (frame_size.y / 2.0);
mouse_position.y = -mouse_position.y;
scaled_mouse_position = mouse_position;
scaled_mouse_position.x *= scaled_aspect_ratio;
mouse_position.x *= aspect_ratio;
return;
},
// record keyboard inputs
WindowEvent::KeyboardInput {input, ..} => {
match input.state {
ElementState::Pressed => {
input.virtual_keycode.map(|key| {
keys_held.insert(key);
keys_pressed.insert(key);
});
},
ElementState::Released => {
input.virtual_keycode.map(|key| {
keys_held.remove(&key);
keys_released.insert(key);
});
}
}
return;
},
// record mouse inputs
WindowEvent::MouseInput {button, state, ..} => {
match state {
ElementState::Pressed => {
mouse_buttons_held.insert(button);
mouse_buttons_pressed.insert(button);
},
ElementState::Released => {
mouse_buttons_held.remove(&button);
mouse_buttons_released.insert(button);
},
}
return;
},
WindowEvent::ReceivedCharacter(c) => {
// go through each text inputs and modify their text according to the given
// character input
text_inputs.iter_mut().for_each(|input| {
// since the inputs are of the type Rc<RefCell<(String, bool)>> we need
// to use borrow_mut to mutate it
let mut s = input.borrow_mut();
// if the text input is not reading, do not modify its text
if !s.1 {
return;
}
match c as u8 {
// ignore carriage returns
13 => {
},
// in the case of backspace pop a character from the text
08 => {
s.0.pop();
},
// default to pushing the character to the String
_ => {
s.0.push(c);
}
}
});
return;
},
WindowEvent::Resized(size) => {
if self.pixel_window_size.is_none() {
texture_buffer = glium::texture::texture2d::Texture2d::empty(
&display,
size.width as u32,
size.height as u32,
).expect("failed to create texture buffer for resized window");
}
},
_ => return,
},
Event::NewEvents(cause) => match cause {
// update the screen if the time limit is reached
StartCause::ResumeTimeReached { .. } => (),
StartCause::Init => (),
_ => return,
},
_ => return,
}
let (_, _, aspect_ratio) = if let Some(size) = self.pixel_window_size {
(size.x, size.y, size.x as f32/size.y as f32)
} else {
(dims.0, dims.1, aspect_ratio)
};
// run state functions
{
// FIXME: all of the is bad, please clean this up later
let _ = main_drawing_data_sender.try_send(DrawingData {
frame_size,
line_points: Vec::new(),
line_widths: Vec::new(),
verts: Vec::new(),
// masks
mask_shapes: Vec::new(),
rect_mask_positions: Vec::new(),
rect_mask_sizes: Vec::new(),
rect_mask_rotations: Vec::new(),
// FIXME: cloning is bad, find another way
image_indecies: image_indecies.clone(),
image_dimensions: image_dimensions.clone(),
font_indecies: font_indecies.clone(),
font_dimensions: font_dimensions.clone(),
font_character_infos: font_character_infos.clone(),
scaled_aspect_ratio: scaled_aspect_ratio,
aspect_ratio: aspect_ratio,
font_atlas_dimensions: font_atlas_dimensions,
font_positions: font_positions.clone(),
image_atlas_dimensions: image_atlas_dimensions,
image_positions: image_positions.clone(),
});
// something something state_data
{
let mut data = state_data.lock().unwrap();
*data = StateData {
delta_time: 0.016,
frame_dimensions: if let Some(size) = self.pixel_window_size {
Vec2::new(size.x as f32, size.y as f32)
} else {
Vec2::new(aspect_ratio * 2.0, 2.0)
},
scaled_frame_dimensions: Vec2::new(aspect_ratio * 2.0, 2.0),
window_dimensions: Vec2::new(self.window_size.x as f32, self.window_size.y as f32),
aspect_ratio,
mouse_position,
scaled_mouse_position,
keys_pressed: keys_pressed.clone(),
keys_held: keys_held.clone(),
keys_released: keys_released.clone(),
mouse_buttons_pressed: mouse_buttons_pressed.clone(),
mouse_buttons_held: mouse_buttons_held.clone(),
mouse_buttons_released: mouse_buttons_released.clone(),
};
}
let drawing_data = drawing_data_receiver.try_recv();
if drawing_data.is_err() {
return;
}
let mut drawing_data = drawing_data.unwrap();
// clear color
texture_buffer.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
// line buffers only remake buffers if needed
if line_point_buffer.len() == drawing_data.line_points.len() &&
drawing_data.line_points.len() != 0
{
line_point_buffer.write(&drawing_data.line_points);
} else if drawing_data.line_points.len() > 0 || line_point_buffer.len() > 0 {
line_point_buffer = glium::buffer::Buffer::<[[f32; 4]]>::new(
&display,
&drawing_data.line_points,
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
}
if line_width_buffer.len() == drawing_data.line_widths.len() &&
drawing_data.line_widths.len() != 0
{
line_width_buffer.write(&drawing_data.line_widths);
} else if drawing_data.line_widths.len() > 0 || line_width_buffer.len() > 0 {
line_width_buffer = glium::buffer::Buffer::<[f32]>::new(
&display,
&drawing_data.line_widths,
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
}
// masks
let mask_shape_buffer = glium::buffer::Buffer::<[[i32; 2]]>::new(
&display,
&drawing_data.mask_shapes,
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
let rect_mask_position_buffer = glium::buffer::Buffer::<[[f32; 2]]>::new(
&display,
&drawing_data.rect_mask_positions,
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
let rect_mask_size_buffer = glium::buffer::Buffer::<[[f32; 2]]>::new(
&display,
&drawing_data.rect_mask_sizes,
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
let rect_mask_rotation_buffer = glium::buffer::Buffer::<[[[f32; 2]; 2]]>::new(
&display,
&drawing_data.rect_mask_rotations,
glium::buffer::BufferType::ArrayBuffer,
glium::buffer::BufferMode::Default,
).unwrap();
// uniforms for scaling draw call
let uniforms = uniform!{
window_dimensions: window_dimensions.as_array(),
aspect_ratio: aspect_ratio,
// line buffers
line_point_buffer: &line_point_buffer,
line_width_buffer: &line_width_buffer,
// image
image_atlas: &image_atlas,
image_atlas_dimensions: image_atlas_dimensions.as_array(),
// text
font_atlas: &font_atlas,
font_atlas_dimensions: font_atlas_dimensions.as_array(),
// masks
mask_shape_buffer: &mask_shape_buffer,
// rect mask
rect_mask_position_buffer: &rect_mask_position_buffer,
rect_mask_size_buffer: &rect_mask_size_buffer,
rect_mask_rotation_buffer: &rect_mask_rotation_buffer,
};
if drawing_data.verts.len() > 0 {
if self.depth_sorting {
drawing_data.verts.sort_by(|a, b| a.depth.partial_cmp(&b.depth).unwrap());
}
if vertex_buffer.len() == drawing_data.verts.len() && drawing_data.verts.len() > 0 {
vertex_buffer.write(&drawing_data.verts);
} else if drawing_data.verts.len() > 0 || vertex_buffer.len() > 0 {
vertex_buffer = glium::VertexBuffer::new(&display, &drawing_data.verts).unwrap();
}
let draw_parameters = glium::draw_parameters::DrawParameters {
blend: glium::Blend::alpha_blending(),
.. Default::default()
};
let mut frame = display.draw();
// draw the frame buffer to the window and handle errors
let _ = texture_buffer.as_surface().draw(&vertex_buffer,
&glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList),
&simple_transform_fill,
&uniforms,
&draw_parameters);
texture_buffer.as_surface().blit_whole_color_to(
&frame,
&glium::BlitTarget {
left: 0,
bottom: 0,
width: dims.0 as i32,
height: dims.1 as i32
},
glium::uniforms::MagnifySamplerFilter::Nearest
);
frame.finish()
.expect("GUI::APPLICATION Failed to finish frame");
}
};
// reset keypressed and released
keys_pressed = HashSet::new();
keys_released = HashSet::new();
// reset mousepressed and released
mouse_buttons_pressed = HashSet::new();
mouse_buttons_released = HashSet::new();
});
}
}
|
use std::collections::HashSet;
use std::env;
use std::path::PathBuf;
// https://github.com/rust-lang/rust-bindgen/issues/687#issuecomment-450750547
#[derive(Debug)]
struct IgnoreMacros(HashSet<String>);
impl bindgen::callbacks::ParseCallbacks for IgnoreMacros {
fn will_parse_macro(&self, name: &str) -> bindgen::callbacks::MacroParsingBehavior {
if self.0.contains(name) {
bindgen::callbacks::MacroParsingBehavior::Ignore
} else {
bindgen::callbacks::MacroParsingBehavior::Default
}
}
}
fn main() {
println!("cargo:rerun-if-changed=wrapper.h");
println!("cargo:rerun-if-changed=build.rs");
let wand_config = pkg_config::Config::new()
.atleast_version("7.0.10")
.probe("MagickWand")
.expect("pkg-config MagickWand should be probed");
let ignored_macros = IgnoreMacros(
vec![
"FP_INT_UPWARD".into(),
"FP_INT_DOWNWARD".into(),
"FP_INT_TOWARDZERO".into(),
"FP_INT_TONEARESTFROMZERO".into(),
"FP_INT_TONEAREST".into(),
"FP_NAN".into(),
"FP_INFINITE".into(),
"FP_ZERO".into(),
"FP_NORMAL".into(),
"FP_SUBNORMAL".into(),
"IPPORT_RESERVED".into(),
]
.into_iter()
.collect(),
);
let mut bindgen_builder = bindgen::Builder::default()
.header("wrapper.h")
.rustfmt_bindings(true)
.parse_callbacks(Box::new(ignored_macros));
for include_path in &wand_config.include_paths {
bindgen_builder = bindgen_builder.clang_arg(format!("-I{}", include_path.display()));
}
for (macro_name, value) in &wand_config.defines {
if let Some(value) = value {
bindgen_builder = bindgen_builder.clang_arg(format!("-D{}={}", macro_name, value));
}
}
let bindings = bindgen_builder
.generate()
.expect("Unable to generate MagickWand bindings");
// Write the bindings to the $OUT_DIR/bindings.rs file.
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
|
use crate::pong::{ARENA_HEIGHT, ARENA_WIDTH};
use amethyst::{
assets::Handle,
core::transform::Transform,
ecs::{Component, DenseVecStorage, Entity},
prelude::*,
renderer::{SpriteRender, SpriteSheet},
};
pub const BALL_VELOCITY_X: f32 = 75.0 * 2.;
pub const BALL_VELOCITY_Y: f32 = 50.0 * 2.;
pub const BALL_RADIUS: f32 = 2.0;
pub struct Ball {
pub velocity: [f32; 2],
pub radius: f32,
}
impl Component for Ball {
type Storage = DenseVecStorage<Self>;
}
pub struct Dead {
pub time: f32,
}
impl Component for Dead {
type Storage = DenseVecStorage<Self>;
}
pub fn init_ball(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) -> Entity {
let mut transform = Transform::default();
transform.set_translation_xyz(ARENA_WIDTH / 2.0, ARENA_HEIGHT / 2.0, 0.0);
let sprite_render = SpriteRender::new(sprite_sheet_handle, 1);
let ball = world
.create_entity()
.with(sprite_render)
.with(Ball {
radius: BALL_RADIUS,
velocity: [BALL_VELOCITY_X, BALL_VELOCITY_Y],
})
.with(transform)
.build();
ball
}
|
use bson;
use ron;
use serde::{Deserialize, Serialize};
use serde_json;
use std::io::{Read, Result, Seek, SeekFrom, Write};
fn main() {
json_with_file();
ron_with_buffer();
let f = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open("/tmp/b.bson")
.unwrap();
multi_bson(f);
multi_bson(MyBuffer::default());
}
fn multi_bson<T: Read + Write + Seek>(mut buf: T) {
for i in 0..1000 {
let a = match i % 4 {
0 => Move::Up(i),
1 => Move::Down(i),
2 => Move::Left(i),
_ => Move::Right(i),
};
let b = bson::to_bson(&a).unwrap();
let doc = b.as_document().unwrap();
bson::encode_document(&mut buf, doc).unwrap();
}
buf.flush().unwrap();
let len = buf.seek(SeekFrom::End(0)).unwrap();
buf.seek(SeekFrom::Start(0)).unwrap();
for i in 0..std::usize::MAX {
let cur = buf.seek(SeekFrom::Current(0)).unwrap();
if cur == len as u64 {
println!("Break at {}", i);
break;
}
bson::decode_document(&mut buf).unwrap();
}
}
#[derive(Debug, Serialize, Deserialize)]
enum Move {
Up(i32),
Down(i32),
Left(i32),
Right(i32),
}
struct MyBuffer(Vec<u8>, usize);
impl Default for MyBuffer {
fn default() -> Self {
MyBuffer(vec![], 0)
}
}
impl Write for MyBuffer {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
if self.0.len() == self.1 {
self.0.extend(buf);
self.1 += buf.len();
} else {
let cnt = (&mut self.0[self.1..]).write(buf).unwrap();
self.1 += cnt;
if cnt < buf.len() {
self.0.extend(&buf[cnt..]);
self.1 += buf.len() - cnt;
}
}
Ok(buf.len())
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
impl Read for MyBuffer {
fn read(&mut self, mut buf: &mut [u8]) -> Result<usize> {
let n = if self.1 + buf.len() > self.0.len() {
buf.write(&self.0[self.1..]).unwrap()
} else {
buf.write(&self.0[self.1..self.1 + buf.len()]).unwrap()
};
self.1 += n;
Ok(n)
}
}
impl Seek for MyBuffer {
fn seek(&mut self, s: SeekFrom) -> Result<u64> {
let (from, offset) = match s {
SeekFrom::Current(i) => (self.1 as i64, i as i64),
SeekFrom::End(i) => (self.0.len() as i64, i as i64),
SeekFrom::Start(i) => (0, i as i64),
};
let pos = (from + offset).min(self.0.len() as i64).max(0);
self.1 = pos as usize;
Ok(pos as u64)
}
}
fn json_with_file() {
let mut f = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open("/tmp/a.json")
.unwrap();
let a = Move::Up(1);
serde_json::to_writer(&mut f, &a).unwrap();
f.flush().unwrap();
f.seek(SeekFrom::Start(0)).unwrap();
let b: Move = serde_json::from_reader(f).unwrap();
println!("{:?}, {:?}", a, b);
}
fn ron_with_buffer() {
let a = Move::Up(1);
let bytes = ron::ser::to_string(&a).unwrap().into_bytes();
let b: Move = ron::de::from_bytes(&bytes).unwrap();
println!("{:?}, {:?}", a, b);
}
|
fn main() {
let (m, n, first_n) = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let mut ws = line.trim_end().split_whitespace();
let n1: usize = ws.next().unwrap().parse().unwrap();
let n2: usize = ws.next().unwrap().parse().unwrap();
let n3: usize = ws.next().unwrap().parse().unwrap();
(n1, n2, n3)
};
for o in solve(m, n, first_n) {
println!("{}", o);
}
}
fn solve(m: usize, n: usize, first_n: usize) -> Vec<String> {
let mut total = first_n;
let mut stocks = first_n;
while stocks >= m {
let (p, s) = make_pencil(m, n, stocks);
total += p;
stocks = p + s;
}
let mut buf = Vec::new();
buf.push(format!("{}", total));
buf
}
fn make_pencil(m: usize, n: usize, stocks: usize) -> (usize, usize) {
let producsts = stocks / m * n;
let new_stocks = stocks % m;
(producsts, new_stocks)
}
#[test]
fn test_solve_1() {
assert_eq!(solve(2, 1, 8), vec!("15"));
}
#[test]
fn test_solve_2() {
assert_eq!(solve(7, 4, 30), vec!("62"));
}
#[test]
fn test_solve_3() {
assert_eq!(solve(100, 99, 1000), vec!("90199"));
}
#[test]
fn test_solve_4() {
assert_eq!(solve(2, 1, 1), vec!("1"));
}
#[test]
fn test_solve_5() {
assert_eq!(solve(2, 1, 2), vec!("3"));
}
|
#[cfg(test)]
#[path = "../../../tests/unit/solver/objectives/total_value_test.rs"]
mod total_value_test;
use crate::construction::constraints::*;
use crate::construction::heuristics::{RouteContext, SolutionContext};
use crate::models::problem::{Job, TargetConstraint, TargetObjective};
use crate::solver::objectives::GenericValue;
use std::ops::Deref;
use std::sync::Arc;
/// A type which provides functionality needed to maximize total value of served jobs.
pub struct TotalValue {}
impl TotalValue {
/// Creates _(constraint, objective)_ type pair which provides logic to maximize total value.
pub fn maximize(
max_value: f64,
reduction_factor: f64,
value_func: Arc<dyn Fn(&Job) -> f64 + Send + Sync>,
) -> (TargetConstraint, TargetObjective) {
assert!(max_value > 0.);
let get_route_value = {
let value_func = value_func.clone();
Arc::new(move |rc: &RouteContext| rc.route.tour.jobs().map(|job| -value_func.deref()(&job)).sum())
};
GenericValue::new_constrained_objective(
None,
None,
get_route_value.clone(),
Arc::new(move |ctx: &SolutionContext| ctx.routes.iter().map(|rc| get_route_value(rc)).sum()),
Arc::new(move |_, _, job, max_cost| {
let job_value = -value_func.deref()(job);
if max_cost > 0. {
(job_value / max_value) * max_cost * reduction_factor
} else {
job_value * reduction_factor
}
}),
TOTAL_VALUE_KEY,
)
}
}
|
use std::{collections::BTreeMap, iter::Extend, sync::Arc};
use rosu_v2::model::user::User;
use twilight_model::channel::Message;
use crate::{
custom_client::{OsuStatsParams, OsuStatsScore},
embeds::OsuStatsGlobalsEmbed,
BotResult, Context,
};
use super::{Pages, Pagination, ReactionVec};
pub struct OsuStatsGlobalsPagination {
msg: Message,
pages: Pages,
user: User,
scores: BTreeMap<usize, OsuStatsScore>,
total: usize,
params: OsuStatsParams,
ctx: Arc<Context>,
}
impl OsuStatsGlobalsPagination {
pub fn new(
ctx: Arc<Context>,
msg: Message,
user: User,
scores: BTreeMap<usize, OsuStatsScore>,
total: usize,
params: OsuStatsParams,
) -> Self {
Self {
pages: Pages::new(5, total),
msg,
user,
scores,
total,
params,
ctx,
}
}
}
#[async_trait]
impl Pagination for OsuStatsGlobalsPagination {
type PageData = OsuStatsGlobalsEmbed;
fn msg(&self) -> &Message {
&self.msg
}
fn pages(&self) -> Pages {
self.pages
}
fn pages_mut(&mut self) -> &mut Pages {
&mut self.pages
}
fn reactions() -> ReactionVec {
Self::arrow_reactions_full()
}
fn single_step(&self) -> usize {
5
}
fn multi_step(&self) -> usize {
25
}
async fn build_page(&mut self) -> BotResult<Self::PageData> {
let entries = self
.scores
.range(self.pages.index..self.pages.index + self.pages.per_page);
let count = entries.count();
if count < self.pages.per_page && self.total - self.pages.index > count {
let osustats_page = (self.pages.index / 24) + 1;
self.params.page = osustats_page;
let (scores, _) = self
.ctx
.clients
.custom
.get_global_scores(&self.params)
.await?;
let iter = scores
.into_iter()
.enumerate()
.map(|(i, s)| ((osustats_page - 1) * 24 + i, s));
self.scores.extend(iter);
}
let fut = OsuStatsGlobalsEmbed::new(
&self.user,
&self.scores,
self.total,
&self.ctx,
(self.page(), self.pages.total_pages),
);
Ok(fut
.await)
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
use reqwest;
use crate::apis::ResponseContent;
use super::{Error, configuration};
/// struct for typed errors of method `get_metric_metadata`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetMetricMetadataError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `list_active_metrics`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListActiveMetricsError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `list_metrics`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListMetricsError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `query_metrics`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum QueryMetricsError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `submit_metrics`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SubmitMetricsError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status408(crate::models::ApiErrorResponse),
Status413(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `update_metric_metadata`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateMetricMetadataError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// Get metadata about a specific metric.
pub async fn get_metric_metadata(configuration: &configuration::Configuration, metric_name: &str) -> Result<crate::models::MetricMetadata, Error<GetMetricMetadataError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/metrics/{metric_name}", configuration.base_path, metric_name=crate::apis::urlencode(metric_name));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetMetricMetadataError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the list of actively reporting metrics from a given time until now.
pub async fn list_active_metrics(configuration: &configuration::Configuration, from: i64, host: Option<&str>, tag_filter: Option<&str>) -> Result<crate::models::MetricsListResponse, Error<ListActiveMetricsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/metrics", configuration.base_path);
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
local_var_req_builder = local_var_req_builder.query(&[("from", &from.to_string())]);
if let Some(ref local_var_str) = host {
local_var_req_builder = local_var_req_builder.query(&[("host", &local_var_str.to_string())]);
}
if let Some(ref local_var_str) = tag_filter {
local_var_req_builder = local_var_req_builder.query(&[("tag_filter", &local_var_str.to_string())]);
}
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<ListActiveMetricsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Search for metrics from the last 24 hours in Datadog.
pub async fn list_metrics(configuration: &configuration::Configuration, q: &str) -> Result<crate::models::MetricSearchResponse, Error<ListMetricsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/search", configuration.base_path);
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
local_var_req_builder = local_var_req_builder.query(&[("q", &q.to_string())]);
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<ListMetricsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Query timeseries points.
pub async fn query_metrics(configuration: &configuration::Configuration, from: i64, to: i64, query: &str) -> Result<crate::models::MetricsQueryResponse, Error<QueryMetricsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/query", configuration.base_path);
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
local_var_req_builder = local_var_req_builder.query(&[("from", &from.to_string())]);
local_var_req_builder = local_var_req_builder.query(&[("to", &to.to_string())]);
local_var_req_builder = local_var_req_builder.query(&[("query", &query.to_string())]);
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<QueryMetricsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// The metrics end-point allows you to post time-series data that can be graphed on Datadog’s dashboards. The maximum payload size is 3.2 megabytes (3200000). Compressed payloads must have a decompressed size of up to 62 megabytes (62914560). If you’re submitting metrics directly to the Datadog API without using DogStatsD, expect - 64 bits for the timestamp - 32 bits for the value - 20 bytes for the metric names - 50 bytes for the timeseries - The full payload is approximately ~ 100 bytes. However, with the DogStatsD API, compression is applied, which reduces the payload size.
pub async fn submit_metrics(configuration: &configuration::Configuration, body: crate::models::MetricsPayload) -> Result<crate::models::IntakePayloadAccepted, Error<SubmitMetricsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/series", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<SubmitMetricsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Edit metadata of a specific metric. Find out more about [supported types](https://docs.datadoghq.com/developers/metrics).
pub async fn update_metric_metadata(configuration: &configuration::Configuration, metric_name: &str, body: crate::models::MetricMetadata) -> Result<crate::models::MetricMetadata, Error<UpdateMetricMetadataError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/metrics/{metric_name}", configuration.base_path, metric_name=crate::apis::urlencode(metric_name));
let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<UpdateMetricMetadataError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
|
use plotters::prelude::*;
fn main() {
// 画像サイズが600 x 400の画像を`./images/`配下に作成
let root_area = BitMapBackend::new("images/2.5.png", (600, 400)).into_drawing_area();
// 背景を白に設定
root_area.fill(&WHITE).unwrap();
let mut ctx = ChartBuilder::on(&root_area)
// グラフのラベルを設定
.set_label_area_size(LabelAreaPosition::Left, 40)
.set_label_area_size(LabelAreaPosition::Bottom, 40)
.caption("Line Plot Demo", ("sans-serif", 40))
.build_cartesian_2d(-10..10, 0..100)
.unwrap();
ctx.configure_mesh().draw().unwrap();
ctx.draw_series(
LineSeries::new((-10..=10).map(|x| (x, x * x)), &GREEN)
).unwrap();
}
|
use std::fmt;
use std::rc::Rc;
#[allow(dead_code)]
pub enum LTL<A> {
Top,
Bottom(String),
// Accept rules take a state which is global to the aggregate LTL<A> formula.
// There is no way to "scope" information using closures, such as there is
// in Coq or Haskell, so intermediate states must be represented the
// old-fashioned way.
Accept(Box<dyn Fn(A) -> Rc<LTL<A>>>),
And(Rc<LTL<A>>, Rc<LTL<A>>),
Or(Rc<LTL<A>>, Rc<LTL<A>>),
Next(Rc<LTL<A>>),
Until(Rc<LTL<A>>, Rc<LTL<A>>),
Release(Rc<LTL<A>>, Rc<LTL<A>>),
}
pub type Formula<A> = Rc<LTL<A>>;
pub fn top<A>() -> Formula<A> {
Rc::new(LTL::Top)
}
pub fn bottom<A>(reason: String) -> Formula<A> {
Rc::new(LTL::Bottom(reason))
}
pub fn accept<A>(f: Box<dyn Fn(A) -> Rc<LTL<A>>>) -> Formula<A> {
Rc::new(LTL::Accept(f))
}
pub fn with<A, T>(f: &'static T) -> Formula<A>
where
T: Fn(A) -> Formula<A>,
{
accept(Box::new(f))
}
pub fn and<A>(p: Formula<A>, q: Formula<A>) -> Formula<A> {
Rc::new(LTL::And(p, q))
}
pub fn or<A>(p: Formula<A>, q: Formula<A>) -> Formula<A> {
Rc::new(LTL::Or(p, q))
}
#[allow(dead_code)]
pub fn next<A>(p: Formula<A>) -> Formula<A> {
Rc::new(LTL::Next(p))
}
#[allow(dead_code)]
pub fn until<A>(p: Formula<A>, q: Formula<A>) -> Formula<A> {
Rc::new(LTL::Until(p, q))
}
#[allow(dead_code)]
pub fn release<A>(p: Formula<A>, q: Formula<A>) -> Formula<A> {
Rc::new(LTL::Release(p, q))
}
#[allow(dead_code)]
pub fn eventually<A>(p: Formula<A>) -> Formula<A> {
until(top(), p)
}
#[allow(dead_code)]
pub fn always<A>(p: Formula<A>) -> Formula<A> {
release(bottom("always".to_string()), p)
}
/// True if the given Haskell boolean is true.
#[allow(dead_code)]
pub fn truth<A>(b: bool) -> Formula<A> {
if b {
top()
} else {
bottom("truth".to_string())
}
}
/// True if the given predicate on the input is true.
#[allow(dead_code)]
pub fn is<A: 'static, T>(f: &'static T) -> Formula<A>
where
T: Fn(A) -> bool,
{
accept(Box::new(move |x: A| truth(f(x))))
}
/// Another name for 'is'.
#[allow(dead_code)]
pub fn test<A: 'static, T>(f: &'static T) -> Formula<A>
where
T: Fn(A) -> bool,
{
is(f)
}
/// Check for equality with the input.
#[allow(dead_code)]
pub fn eq<A: 'static + PartialEq>(x: A) -> Formula<A> {
accept(Box::new(move |y| truth(x == y)))
}
impl<A> fmt::Display for LTL<A> {
fn fmt(&self, dest: &mut fmt::Formatter) -> fmt::Result {
match self {
LTL::Top => write!(dest, "Top"),
LTL::Bottom(s) => write!(dest, "Bottom {}", s),
LTL::Accept(_) => write!(dest, "Accept"),
LTL::And(p, q) => write!(dest, "(And {} {})", p, q),
LTL::Or(p, q) => write!(dest, "(Or {} {})", p, q),
LTL::Next(p) => write!(dest, "(Next {})", p),
LTL::Until(p, q) => write!(dest, "(Until {} {})", p, q),
LTL::Release(p, q) => write!(dest, "(Release {} {})", p, q),
}
}
}
#[allow(dead_code)]
#[derive(Clone)]
pub enum Failed {
HitBottom(String),
EndOfTrace,
Both(Box<Failed>, Box<Failed>),
Left(Box<Failed>),
Right(Box<Failed>),
}
impl fmt::Display for Failed {
fn fmt(&self, dest: &mut fmt::Formatter) -> fmt::Result {
match self {
Failed::HitBottom(reason) => write!(dest, "HitBottom {}", reason),
Failed::EndOfTrace => write!(dest, "EndOfTrace"),
Failed::Both(p, q) => write!(dest, "(Both {} {})", p, q),
Failed::Left(p) => write!(dest, "(Left {})", p),
Failed::Right(q) => write!(dest, "(Right {})", q),
}
}
}
pub enum Result<A> {
Failure(Failed),
Continue(Formula<A>),
Success,
}
impl<A: fmt::Display> fmt::Display for Result<A> {
fn fmt(&self, dest: &mut fmt::Formatter) -> fmt::Result {
match self {
Result::Failure(f) => write!(dest, "Failure {}", f),
Result::Continue(l) => write!(dest, "Continue {}", l),
Result::Success => write!(dest, "Success"),
}
}
}
fn compile<A: Copy>(l: Formula<A>, mx: Option<A>) -> Result<A> {
match &*l {
LTL::Top => Result::Success,
LTL::Bottom(s) => Result::Failure(Failed::HitBottom(s.clone())),
LTL::Accept(v) => match mx {
None => Result::Success,
Some(x) => compile(v(x), mx),
},
LTL::And(p, q) => match compile(Rc::clone(p), mx) {
Result::Failure(e) => Result::Failure(Failed::Left(Box::new(e))),
Result::Success => compile(Rc::clone(q), mx),
Result::Continue(f2) => match compile(Rc::clone(q), mx) {
Result::Failure(e) => Result::Failure(Failed::Right(Box::new(e))),
Result::Success => Result::Continue(f2),
Result::Continue(g2) => Result::Continue(and(f2, g2)),
},
},
LTL::Or(p, q) => match compile(Rc::clone(p), mx) {
Result::Success => Result::Success,
Result::Failure(e1) => match compile(Rc::clone(q), mx) {
Result::Failure(e2) => Result::Failure(Failed::Both(Box::new(e1), Box::new(e2))),
g2 => g2,
},
Result::Continue(f2) => match compile(Rc::clone(q), mx) {
Result::Success => Result::Success,
Result::Failure(_) => Result::Continue(f2),
Result::Continue(g2) => Result::Continue(or(f2, g2)),
},
},
LTL::Next(p) => match mx {
None => compile(Rc::clone(p), mx),
Some(_) => Result::Continue(Rc::clone(p)),
},
LTL::Until(p, q) => match mx {
None => compile(Rc::clone(q), mx),
Some(_) => compile(or(Rc::clone(q), and(Rc::clone(p), next(l))), mx),
},
LTL::Release(p, q) => match mx {
None => compile(Rc::clone(q), mx),
Some(_) => compile(and(Rc::clone(q), and(Rc::clone(p), next(l))), mx),
},
}
}
pub fn step<A: Copy>(m: Result<A>, x: A) -> Result<A> {
match m {
Result::Continue(l) => compile(l, Some(x)),
r => r,
}
}
#[allow(dead_code)]
pub fn run<A: Copy>(m: Formula<A>, xs: &[A]) -> Result<A> {
if xs.len() == 0 {
compile(m, None)
} else {
match compile(m, Some(xs[0])) {
Result::Continue(l) => run(l, &xs[1..]),
r => r,
}
}
}
|
use std::collections::HashMap;
fn main() {
let input = include_str!("../data/2015-07.txt");
println!("Part 1: {}", part1(input));
println!("Part 2: {}", part2(input));
}
fn part1(input: &str) -> u16 {
let mut wires = parse(input);
calc(&mut wires, "a")
}
fn part2(input: &str) -> u16 {
let mut wires1 = parse(input);
let mut wires2 = wires1.clone();
let a1 = calc(&mut wires1, "a");
wires2.insert("b", Computed(a1));
calc(&mut wires2, "a")
}
fn parse(input: &str) -> HashMap<&str, Op> {
let mut wires = HashMap::new();
for line in input.lines() {
let parts: Vec<_> = line.split(' ').collect();
let op = match parts[1] {
"AND" => And(parts[0], parts[2]),
"OR" => Or(parts[0], parts[2]),
"LSHIFT" => LShift(parts[0], parts[2]),
"RSHIFT" => RShift(parts[0], parts[2]),
"->" => Assign(parts[0]),
_ => Not(parts[1])
};
wires.insert(parts[parts.len()-1], op);
}
wires
}
fn calc<'a>(wires: &mut HashMap<&'a str, Op<'a>>, id: &'a str) -> u16 {
if let Ok(num) = id.parse() {
return num
}
let op = wires[id];
let res = match op {
Computed(n) => return n,
Assign(x) => calc(wires, x),
Not(x) => !calc(wires, x),
And(x, y) => calc(wires, x) & calc(wires, y),
Or(x, y) => calc(wires, x) | calc(wires, y),
LShift(x, y) => calc(wires, x) << calc(wires, y),
RShift(x, y) => calc(wires, x) >> calc(wires, y)
};
//println!("memoizing {}={:?} into {}=Computed({})", id, op, id, res);
wires.insert(id, Computed(res));
res
}
use Op::*;
#[derive(Copy, Clone, Debug)]
enum Op<'a> {
Computed(u16),
Assign(&'a str),
Not(&'a str),
And(&'a str, &'a str),
Or(&'a str, &'a str),
LShift(&'a str, &'a str),
RShift(&'a str, &'a str)
}
#[test]
fn test1() {
aoc::test(part1, [
("123 -> a", 123),
("NOT 0 -> a", 65535),
("1 AND 1 -> a", 1),
("0 OR 1 -> a", 1),
("1 LSHIFT 2 -> a", 4),
("4 RSHIFT 2 -> a", 1),
("b -> a\n2 -> b", 2),
("123 -> x\n456 -> y\nx AND y -> a", 72),
("123 -> x\n456 -> y\nx OR y -> a", 507),
("123 -> x\n456 -> y\nx LSHIFT 2 -> a", 492),
("123 -> x\n456 -> y\ny RSHIFT 2 -> a", 114),
("123 -> x\n456 -> y\nNOT x -> a", 65412),
])
}
|
//! A one-time send - receive channel.
use std::cell::UnsafeCell;
use std::future::Future;
use std::marker::PhantomData;
use std::rc::Rc;
use std::task::{Poll, Waker};
use thiserror::Error;
/// Error returned by awaiting the [`Receiver`].
#[derive(Debug, Error)]
#[error("channel has been closed.")]
pub struct RecvError {
_marker: PhantomData<()>,
}
#[derive(Debug)]
struct Inner<T> {
rx_waker: Option<Waker>,
closed: bool,
item: Option<T>,
}
/// The receiver of a oneshot channel.
#[derive(Debug)]
pub struct Receiver<T> {
inner: Rc<UnsafeCell<Inner<T>>>,
}
impl<T> Future for Receiver<T> {
type Output = Result<T, RecvError>;
fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
// SAFETY:
//
// We can acquire a mutable reference without checking as:
//
// - This type is !Sync and !Send.
// - This function is not used by any other functions and hence uniquely owns the
// mutable reference.
// - The mutable reference is dropped at the end of this function.
let inner = unsafe { &mut *self.inner.get() };
// Implementation Note:
//
// It might be neater to use a match pattern here.
// However, this will slow down the polling process by 10%.
if let Some(m) = inner.item.take() {
return Poll::Ready(Ok(m));
}
if inner.closed {
return Poll::Ready(Err(RecvError {
_marker: PhantomData,
}));
}
inner.rx_waker = Some(cx.waker().clone());
Poll::Pending
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
// SAFETY:
//
// We can acquire a mutable reference without checking as:
//
// - This type is !Sync and !Send.
// - This function is not used by any other functions and hence uniquely owns the
// mutable reference.
// - The mutable reference is dropped at the end of this function.
let inner = unsafe { &mut *self.inner.get() };
inner.closed = true;
}
}
/// The sender of a oneshot channel.
#[derive(Debug)]
pub struct Sender<T> {
inner: Rc<UnsafeCell<Inner<T>>>,
}
impl<T> Sender<T> {
/// Send an item to the other side of the channel, consumes the sender.
pub fn send(self, item: T) -> Result<(), T> {
// SAFETY:
//
// We can acquire a mutable reference without checking as:
//
// - This type is !Sync and !Send.
// - This function is not used by any other functions and hence uniquely owns the
// mutable reference.
// - The mutable reference is dropped at the end of this function.
let inner = unsafe { &mut *self.inner.get() };
if inner.closed {
return Err(item);
}
inner.item = Some(item);
if let Some(ref m) = inner.rx_waker {
m.wake_by_ref();
}
Ok(())
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// SAFETY:
//
// We can acquire a mutable reference without checking as:
//
// - This type is !Sync and !Send.
// - This function is not used by any other functions and hence uniquely owns the
// mutable reference.
// - The mutable reference is dropped at the end of this function.
let inner = unsafe { &mut *self.inner.get() };
inner.closed = true;
if inner.item.is_none() {
if let Some(ref m) = inner.rx_waker {
m.wake_by_ref();
}
}
}
}
/// Creates a oneshot channel.
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let inner = Rc::new(UnsafeCell::new(Inner {
rx_waker: None,
closed: false,
item: None,
}));
(
Sender {
inner: inner.clone(),
},
Receiver { inner },
)
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "tokio")]
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Barrier;
use tokio::task::LocalSet;
use tokio::test;
use super::*;
use crate::platform::spawn_local;
use crate::platform::time::sleep;
#[test]
async fn oneshot_works() {
let (tx, rx) = channel();
tx.send(0).expect("failed to send.");
assert_eq!(rx.await.expect("failed to receive."), 0);
}
#[test]
async fn oneshot_drops_sender() {
let local_set = LocalSet::new();
local_set
.run_until(async {
let (tx, rx) = channel::<usize>();
spawn_local(async move {
sleep(Duration::from_millis(1)).await;
drop(tx);
});
rx.await.expect_err("successful to receive.");
})
.await;
}
#[test]
async fn oneshot_drops_receiver() {
let local_set = LocalSet::new();
local_set
.run_until(async {
let (tx, rx) = channel::<usize>();
let bar = Arc::new(Barrier::new(2));
{
let bar = bar.clone();
spawn_local(async move {
sleep(Duration::from_millis(1)).await;
drop(rx);
bar.wait().await;
});
}
bar.wait().await;
tx.send(0).expect_err("successful to send.");
})
.await;
}
}
|
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Config {
#[serde(default)]
pub option: ConfigOption,
#[serde(default)]
pub verilog: ConfigVerilog,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConfigOption {
#[serde(default = "default_as_true")]
pub linter: bool,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConfigVerilog {
#[serde(default)]
pub include_paths: Vec<PathBuf>,
#[serde(default)]
pub defines: Vec<String>,
#[serde(default)]
pub plugins: Vec<PathBuf>,
}
impl Default for Config {
fn default() -> Self {
toml::from_str("").unwrap()
}
}
impl Default for ConfigOption {
fn default() -> Self {
toml::from_str("").unwrap()
}
}
impl Default for ConfigVerilog {
fn default() -> Self {
toml::from_str("").unwrap()
}
}
#[allow(dead_code)]
fn default_as_true() -> bool {
true
}
#[allow(dead_code)]
fn default_as_false() -> bool {
false
}
|
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer};
use std::fmt;
use std::str::FromStr;
use uuid::Uuid;
use chrono::{Utc};
struct F64InQuotes;
impl<'de> Visitor<'de> for F64InQuotes {
type Value = f64;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("f64 as a number or string")
}
fn visit_f64<E>(self, id: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(id)
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
s.parse().map_err(de::Error::custom)
}
}
pub fn f64_from_string<'de, D>(d: D) -> Result<f64, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_any(F64InQuotes)
}
pub fn f64_opt_from_string<'de, D>(d: D) -> Result<Option<f64>, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_any(F64InQuotes).map(Some).or(Ok(None))
}
pub fn uuid_opt_from_string<'de, D>(d: D) -> Result<Option<Uuid>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(d)?;
if s.len() == 0 {
Ok(None)
} else {
Uuid::from_str(&s).map_err(de::Error::custom).map(Some)
}
}
pub fn f64_nan_from_string<'de, D>(d: D) -> Result<f64, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_any(F64InQuotes).or(Ok(std::f64::NAN)) // not sure that 100% correct
}
struct UsizeInQuotes;
impl<'de> Visitor<'de> for UsizeInQuotes {
type Value = usize;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("usize as a number or string")
}
fn visit_u64<E>(self, id: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(id as usize)
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
s.parse().map_err(de::Error::custom)
}
}
pub fn usize_from_string<'de, D>(d: D) -> Result<usize, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_any(UsizeInQuotes)
}
pub fn datetime_from_string<'de, D>(d: D) -> Result<super::structs::DateTime, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(d)?;
(s + "").parse().map_err(de::Error::custom)
}
pub fn datetime_with_tz_from_string<'de, D>(d: D) -> Result<super::structs::DateTime, D::Error>
where
D: Deserializer<'de>,
{
const FORMAT: &str = "%Y-%m-%d %H:%M:%S%.f%#z";
let s = String::deserialize(d)?;
match chrono::DateTime::parse_from_str(&s, FORMAT).map_err(de::Error::custom) {
Ok(dt) => Ok(dt.with_timezone(&Utc)),
Err(err) => Err(err),
}
}
pub fn option_datetime_with_tz_from_string<'de, D>(d: D) -> Result<Option<super::structs::DateTime>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct Wrapper(#[serde(deserialize_with = "datetime_with_tz_from_string")] super::structs::DateTime);
let v = Option::deserialize(d)?;
Ok(v.map(|Wrapper(a)| a))
}
#[cfg(test)]
static DELAY_TIMEOUT: u64 = 200;
#[cfg(test)]
pub fn delay() {
std::thread::sleep(std::time::Duration::from_millis(DELAY_TIMEOUT));
}
|
use crate::renderer::render;
use image::codecs::tiff::TiffEncoder;
use std::fs::File;
use std::io::BufReader;
pub mod primitive;
pub mod renderer;
pub mod scene;
fn main() {
// Rendering images
std::fs::create_dir("rendered");
let file = File::open("./assets/cornell2.ron").unwrap();
let buf_reader = BufReader::new(file);
let scene = scene::Scene::parse(buf_reader).unwrap();
let image = render(&scene);
image.save("rendered/rendered2.tiff"); // Change this line for
// Rendering videos
/*
std::fs::create_dir_all("rendered/video");
let file = File::open("./assets/cornell1.ron").unwrap();
let buf_reader = BufReader::new(file);
let mut scene = scene::Scene::parse(buf_reader).unwrap();
let p0 = scene.spheres[0].position;
let p1 = scene.spheres[1].position;
let p2 = scene.spheres[2].position;
let p3 = scene.spheres[3].position;
let l0 = scene.lights[0].position;
for i in 0..600 {
println!("Rendering frame {}", i);
scene.spheres[0].position = p0;
scene.spheres[0].position.x += (i as f32 / 30.0).sin() * 70.0;
scene.spheres[0].position.y += (i as f32 / 45.0).cos() * 30.0;
scene.spheres[1].position = p1;
scene.spheres[1].position.x += (i as f32 / 90.0).sin() * 70.0;
scene.spheres[1].position.y += (i as f32 / 45.0).sin() * 30.0;
scene.spheres[1].position.z += (i as f32 / 60.0).cos() * 50.0;
scene.spheres[2].position = p2;
scene.spheres[2].position.x += (i as f32 / 90.0).sin() * 12.0;
scene.spheres[2].position.y += (i as f32 / 45.0).sin() * 38.0;
scene.spheres[2].position.z += (i as f32 / 60.0).cos() * 79.0;
scene.spheres[3].position = p3;
scene.spheres[3].position.x += (i as f32 / 29.0).sin() * 36.0;
scene.spheres[3].position.y += (i as f32 / 58.0).sin() * 14.0;
scene.spheres[3].position.z += (i as f32 / 47.0).cos() * 100.0;
scene.lights[0].position = l0;
scene.lights[0].position.x += (i as f32 / 78.0).sin() * 88.0;
let image = render(&scene);
image.save(format!("rendered/video/{}.tiff", i)); // Change this line for
}
*/
}
|
#[doc = "Register `HASH_MID` reader"]
pub type R = crate::R<HASH_MID_SPEC>;
#[doc = "Field `MID` reader - MID"]
pub type MID_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - MID"]
#[inline(always)]
pub fn mid(&self) -> MID_R {
MID_R::new(self.bits)
}
}
#[doc = "HASH Hardware Magic ID\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hash_mid::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct HASH_MID_SPEC;
impl crate::RegisterSpec for HASH_MID_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`hash_mid::R`](R) reader structure"]
impl crate::Readable for HASH_MID_SPEC {}
#[doc = "`reset()` method sets HASH_MID to value 0xa3c5_dd01"]
impl crate::Resettable for HASH_MID_SPEC {
const RESET_VALUE: Self::Ux = 0xa3c5_dd01;
}
|
use chess::{Board, Color, Square, Piece, Rank, File};
use std::fmt::Write;
const EMPTY_SQUARE: &str = " _ ";
const BLACK_MARKER: &str = "*";
const BOARD_HEADER: &str = " A B C D E F G H ";
pub fn board_to_string(board: &Board, perspective: Color) -> String {
let (iter_order, actual_header) = if perspective == Color::White {
(vec![7, 6, 5, 4, 3, 2, 1, 0], String::from(BOARD_HEADER))
} else {
(vec![0, 1, 2, 3, 4, 5, 6, 7], BOARD_HEADER.chars().rev().collect())
};
let mut res = String::from(format!("{}\n\n", actual_header));
for row in iter_order.iter() {
write!(&mut res, "{} ", (row + 1).to_string());
for col in iter_order.iter().rev() {
let square = to_square(*row, *col);
let piece = board.piece_on(square);
let color = board.color_on(square);
if piece.is_some() && color.is_some() {
write!(&mut res, "{}", piece_to_string(piece.unwrap(), color.unwrap()));
} else {
write!(&mut res, "{}", EMPTY_SQUARE);
}
}
write!(&mut res, "\n");
}
return res;
}
pub fn piece_to_string(piece: Piece, color: Color) -> String {
let marker = if color == Color::Black {
BLACK_MARKER
} else {
" "
};
let base = match piece {
Piece::Bishop => " B",
Piece::King => " K",
Piece::Knight => " N",
Piece::Pawn => " P",
Piece::Queen => " Q",
Piece::Rook => " R"
};
return [base, marker].join("");
}
pub fn to_square(row: i32, col: i32) -> Square {
return Square::make_square(make_rank(row), make_file(col));
}
fn make_rank(row: i32) -> Rank {
return Rank::from_index(row as usize);
}
fn make_file(col: i32) -> File {
return File::from_index(col as usize);
} |
#[doc = "Register `CFR` writer"]
pub type W = crate::W<CFR_SPEC>;
#[doc = "Field `CSOF0` writer - Clear synchronization overrun event flag"]
pub type CSOF0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF1` writer - Clear synchronization overrun event flag"]
pub type CSOF1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF2` writer - Clear synchronization overrun event flag"]
pub type CSOF2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF3` writer - Clear synchronization overrun event flag"]
pub type CSOF3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF4` writer - Clear synchronization overrun event flag"]
pub type CSOF4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF5` writer - Clear synchronization overrun event flag"]
pub type CSOF5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF6` writer - Clear synchronization overrun event flag"]
pub type CSOF6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF7` writer - Clear synchronization overrun event flag"]
pub type CSOF7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF8` writer - Clear synchronization overrun event flag"]
pub type CSOF8_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF9` writer - Clear synchronization overrun event flag"]
pub type CSOF9_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF10` writer - Clear synchronization overrun event flag"]
pub type CSOF10_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF11` writer - Clear synchronization overrun event flag"]
pub type CSOF11_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF12` writer - Clear synchronization overrun event flag"]
pub type CSOF12_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF13` writer - Clear synchronization overrun event flag"]
pub type CSOF13_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bit 0 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof0(&mut self) -> CSOF0_W<CFR_SPEC, 0> {
CSOF0_W::new(self)
}
#[doc = "Bit 1 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof1(&mut self) -> CSOF1_W<CFR_SPEC, 1> {
CSOF1_W::new(self)
}
#[doc = "Bit 2 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof2(&mut self) -> CSOF2_W<CFR_SPEC, 2> {
CSOF2_W::new(self)
}
#[doc = "Bit 3 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof3(&mut self) -> CSOF3_W<CFR_SPEC, 3> {
CSOF3_W::new(self)
}
#[doc = "Bit 4 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof4(&mut self) -> CSOF4_W<CFR_SPEC, 4> {
CSOF4_W::new(self)
}
#[doc = "Bit 5 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof5(&mut self) -> CSOF5_W<CFR_SPEC, 5> {
CSOF5_W::new(self)
}
#[doc = "Bit 6 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof6(&mut self) -> CSOF6_W<CFR_SPEC, 6> {
CSOF6_W::new(self)
}
#[doc = "Bit 7 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof7(&mut self) -> CSOF7_W<CFR_SPEC, 7> {
CSOF7_W::new(self)
}
#[doc = "Bit 8 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof8(&mut self) -> CSOF8_W<CFR_SPEC, 8> {
CSOF8_W::new(self)
}
#[doc = "Bit 9 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof9(&mut self) -> CSOF9_W<CFR_SPEC, 9> {
CSOF9_W::new(self)
}
#[doc = "Bit 10 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof10(&mut self) -> CSOF10_W<CFR_SPEC, 10> {
CSOF10_W::new(self)
}
#[doc = "Bit 11 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof11(&mut self) -> CSOF11_W<CFR_SPEC, 11> {
CSOF11_W::new(self)
}
#[doc = "Bit 12 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof12(&mut self) -> CSOF12_W<CFR_SPEC, 12> {
CSOF12_W::new(self)
}
#[doc = "Bit 13 - Clear synchronization overrun event flag"]
#[inline(always)]
#[must_use]
pub fn csof13(&mut self) -> CSOF13_W<CFR_SPEC, 13> {
CSOF13_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "clear flag register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CFR_SPEC;
impl crate::RegisterSpec for CFR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`cfr::W`](W) writer structure"]
impl crate::Writable for CFR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CFR to value 0"]
impl crate::Resettable for CFR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::*;
/// A babel call element.
///
/// # Sematics
///
/// Used to execute [`SrcBlock`]s and put their results into the org file.
///
/// # Syntax
///
/// ```text
/// #+CALL: FUNCTION[INSIDE-HEADER](ARGUMENTS) END-HEADER
/// ```
///
/// `FUNCTION` is the name of a [`SrcBlock`] to execute. `INSIDE-HEADER`, `ARGUEMENTS` and
/// `END-HEADER` can contain everything except a newline (and their respective closing char).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BabelCall {
affiliated_keywords: Option<Spanned<AffiliatedKeywords>>,
/// The code block to call
pub call: String,
pub inside_header: String,
pub arguments: String,
pub end_header: String,
}
|
extern crate termion;
use termion::input::TermRead;
use termion::event::Key;
use termion::raw::IntoRawMode;
use termion::screen::ToMainScreen;
use std::{io::{Write, stdout, stdin},
sync::mpsc,
thread
};
use termion::screen::AlternateScreen;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[derive(Serialize, Deserialize)]
pub enum Source {
Key (String),
Quit,
Join,
Backspace,
Stream,
Net (String),
}
#[allow(unused_variables)]
pub trait Events {
fn on_key_press(&mut self, s:&str);
fn on_key_backspace(&mut self);
fn on_screen_refresh(&self) -> (String,usize);
fn on_key_quit(&self) {}
fn on_join_conn(&mut self) -> Vec<std::net::SocketAddr>;
fn on_new_incomming_conn(&mut self) -> Vec<std::net::SocketAddr>;
fn on_net_package(&mut self, s:&str);
}
pub struct Terminal {
screen: termion::screen::AlternateScreen<termion::raw::RawTerminal<std::io::Stdout>>,
// screen: termion::raw::RawTerminal<std::io::Stdout>,
hooks: Vec<Box<Events>>,
rx: std::sync::mpsc::Receiver<String>,
tx: std::sync::mpsc::Sender<String>,
}
impl Terminal {
pub fn new() -> Self {
let (tx, rx) = mpsc::channel();
Self {
// screen: stdout().into_raw_mode().unwrap(),
screen: AlternateScreen::from(stdout().into_raw_mode().unwrap()),
hooks: Vec::new(),
rx: rx,
tx: tx,
}
}
pub fn add_event_hook<E: Events + 'static>(&mut self, hook: E) {
self.hooks.push(Box::new(hook));
}
pub fn screen_tx_channel(&self) -> std::sync::mpsc::Sender<String> {
self.tx.clone()
}
pub fn clear(&mut self) {
write!(self.screen, "{}", termion::clear::All ).unwrap();
}
pub fn done(&mut self) {
self.screen.flush().unwrap();
}
pub fn top_bar(&mut self) {
let termsize = termion::terminal_size().ok();
let termwidth = termsize.map(|(w,_)| w - 2).unwrap();
// let termheight = termsize.map(|(_,h)| h - 2).unwrap();
write!(self.screen,
"{}{}====== Colaborative editor ====== ESC to exit ",
termion::cursor::Goto(1, 1),
termion::style::Bold,
).unwrap();
write!(self.screen,"{}",termion::cursor::Goto(47, 1)).unwrap();
for _ in 44..termwidth {
write!(self.screen,"=").unwrap();
}
write!(self.screen, "{}{}",
termion::style::Reset,
termion::cursor::Goto(1, 2)
).unwrap();
}
pub fn bottom_bar(&mut self, s:String) {
let termsize = termion::terminal_size().ok();
let termwidth = termsize.map(|(w,_)| w - 2).unwrap() + 2;
let termheight = termsize.map(|(_,h)| h - 2).unwrap() + 2;
let text = format!("====== Connected to [ {} ] ",s);
write!(self.screen,"{}{}{}",
termion::cursor::Goto(1, termheight),
termion::style::Bold,
&text,
).unwrap();
for _ in (text.len() as u16)..termwidth {
write!(self.screen,"=").unwrap();
}
write!(self.screen, "{}{}",
termion::style::Reset,
termion::cursor::Goto(1, 2)
).unwrap();
}
pub fn keys(&mut self) {
let stdin = stdin();
let ksx = self.tx.clone();
thread::spawn(move || {
for c in stdin.keys() {
let package = match c.unwrap() {
Key::Esc => Source::Quit,
Key::Char(c) => Source::Key(format!("{}", c)),
Key::Backspace => Source::Backspace,
// Key::Alt(c) => format!("Alt-{}", c),
// Key::Ctrl(c) => format!("Ctrl-{}", c),
// Key::Left => "<left>".to_string(),
// Key::Right => "<right>".to_string(),
// Key::Up => "<up>".to_string(),
// Key::Down => "<down>".to_string(),
_ => Source::Key( "".to_string() ),
};
let st = serde_json::to_string( &package ).unwrap();
ksx.send( st ).unwrap();
}
});
}
pub fn screen(&mut self) {
let mut list:Vec<std::net::SocketAddr> = Vec::new();
for c in self.rx.iter() {
match serde_json::from_str(&c).unwrap() {
Source::Key(key_pressed) => {
for hook in &mut self.hooks {
hook.on_key_press(&key_pressed);
}
}
Source::Backspace => {
for hook in &mut self.hooks {
hook.on_key_backspace();
}
}
Source::Join => {
for hook in &mut self.hooks {
list = hook.on_join_conn();
}
}
Source::Quit => {
for hook in &self.hooks {
hook.on_key_quit();
}
break
}
Source::Stream => {
for hook in &mut self.hooks {
list = hook.on_new_incomming_conn();
}
}
Source::Net(json_string) => {
for hook in &mut self.hooks {
hook.on_net_package(&json_string);
}
}
};
let mut scr = "".to_string();
let mut index = 0;
for hook in &self.hooks {
let h = hook.on_screen_refresh();
scr = h.0;
index = h.1;
}
let termsize = termion::terminal_size().ok();
let termwidth = termsize.map(|(w,_)| w - 2).unwrap();
let termheight = termsize.map(|(_,h)| h).unwrap();
let mut text_list = String::new();
for addr in &list {
text_list = text_list + &format!("{:?}",&addr);
}
let text = format!("====== Connected to [ {} ] ", text_list);
write!(self.screen,"{}{}{}",
termion::cursor::Goto(1, termheight),
termion::style::Bold,
&text,
).unwrap();
for _ in (text.len() as u16)..termwidth {
write!(self.screen,"=").unwrap();
}
write!(self.screen, "{}{}",
termion::style::Reset,
termion::cursor::Goto(1, 2)).unwrap();
for i in 2..(termheight-1) {
write!(self.screen,
"{}{}",
termion::cursor::Goto(1, i),
termion::clear::CurrentLine
).unwrap();
}
write!(self.screen, "{}",
termion::cursor::Goto(1, 2)
).unwrap();
let split = scr.split("\n");
let mut row:u16 = 1;
let mut cursor:(u16,u16) = (1,1);
for s in split {
write!(self.screen, "{}{}", termion::cursor::Goto(1,row+1),s).unwrap();
row = row + 1;
if index > s.len() {
index = index - (s.len() + 1);
} else {
cursor = ((index as u16) + 1, row);
}
}
write!(self.screen, "{}", termion::cursor::Goto(cursor.0,cursor.1)).unwrap();
self.screen.flush().unwrap();
}
}
pub fn exit(&mut self) {
write!(self.screen, "{}", ToMainScreen ).unwrap();
self.screen.flush().unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(Terminal::new(), Terminal);
}
}
|
pub fn is_literal_bash_string(command: &[u8]) -> bool {
let mut previous = None;
for &c in command {
if b"\t\n !\"$&'()*,;<>?[\\]^`{|}".contains(&c) {
return false;
}
if previous.is_none() && b"#-~".contains(&c) {
// Special case: `-` isn't a part of bash syntax, but it is treated
// as an argument of `exec`.
return false;
}
if (previous == Some(b':') || previous == Some(b'=')) && c == b'~' {
return false;
}
previous = Some(c);
}
true
}
pub fn quote(arg: &[u8]) -> Vec<u8> {
let mut result = vec![b'\''];
for &i in arg {
if i == b'\'' {
result.extend_from_slice(br#"'\''"#)
} else {
result.push(i)
}
}
result.push(b'\'');
result
}
|
/// x86 page directory
///
/// for details:
/// Intel@ 64 and IA-32 Architectures Software Developer's Manual,
/// Vol.3: System Programming Guide - 4.3 (32-bit Paging)
pub mod pg_dir {
use alloc::boxed::Box;
use utils::address::{PAddr, VAddr};
/// # directory entries per page directory
pub const NPDENTRIES: usize = 1024;
/// # PTEs per page table
pub const NPTENTRIES: usize = 1024;
#[repr(C, align(4096))]
pub struct PageDirectory(pub [PageDirEntry; NPDENTRIES]);
impl PageDirectory {
pub fn zero_boxed() -> Box<Self> {
unsafe { Box::new_zeroed().assume_init() }
}
}
impl core::ops::Deref for PageDirectory {
type Target = [PageDirEntry; NPDENTRIES];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for PageDirectory {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[repr(C, align(4096))]
pub struct PageTable(pub [PageTableEntry; NPTENTRIES]);
impl PageTable {
pub fn zero_boxed() -> Box<Self> {
unsafe { Box::new_zeroed().assume_init() }
}
}
impl core::ops::Deref for PageTable {
type Target = [PageTableEntry; NPTENTRIES];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for PageTable {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct PageDirEntry(u32);
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct PageTableEntry(u32);
const DIR_ENT_FLAG_MASK: u32 = 0b111110111111;
const TAB_ENT_FLAG_MASK: u32 = 0b111101111111;
// A virtual address 'va' has a three-part structure as follows:
//
// +--------10------+-------10-------+---------12----------+
// | Page Directory | Page Table | Offset within Page |
// | Index | Index | |
// +----------------+----------------+---------------------+
// \--- PDX(va) --/ \--- PTX(va) --/
#[inline]
pub fn pdx<T>(va: VAddr<T>) -> usize {
(va.raw() >> 22) & 0x3FF
}
#[inline]
pub fn ptx<T>(va: VAddr<T>) -> usize {
(va.raw() >> 12) & 0x3FF
}
impl PageDirEntry {
/// Creates new entry.
/// `page_table_addr` must be 4KiB aligned (lower 12 bit must be zero)
pub const fn new_table(page_table_addr: u32, flags: u32) -> Self {
Self(page_table_addr | flags & DIR_ENT_FLAG_MASK)
}
/// Creates new entry (direct address of 4MiB page).
/// `page_table_addr` must be 4MiB aligned (lower 22 bit must be zero)
pub const fn new_large_page(page_addr: PAddr<super::Page>, flags: u32) -> Self {
Self(page_addr.raw() as u32 | ent_flag::PAGE_SIZE_4MIB | flags & DIR_ENT_FLAG_MASK)
}
pub const fn zero() -> Self {
Self(0)
}
#[inline]
pub fn set_flags(&mut self, flags: u32) {
self.0 |= flags & DIR_ENT_FLAG_MASK;
}
#[inline]
pub fn addr(self) -> PAddr<PageTable> {
PAddr::from_raw((self.0 & !DIR_ENT_FLAG_MASK) as usize)
}
#[inline]
pub fn flags(self) -> u32 {
self.0 & DIR_ENT_FLAG_MASK
}
#[inline]
pub fn flags_check(self, mask: u32) -> bool {
(self.0 & DIR_ENT_FLAG_MASK & mask) == mask
}
}
impl PageTableEntry {
#[inline]
pub fn new(page_addr: PAddr<super::Page>, flags: u32) -> Self {
Self(page_addr.raw() as u32 | flags & TAB_ENT_FLAG_MASK)
}
#[inline]
pub fn set_flags(&mut self, flags: u32) {
self.0 |= flags & TAB_ENT_FLAG_MASK;
}
#[inline]
pub fn addr(self) -> PAddr<super::Page> {
PAddr::from_raw((self.0 & !TAB_ENT_FLAG_MASK) as usize)
}
#[inline]
pub fn flags(self) -> u32 {
self.0 & TAB_ENT_FLAG_MASK
}
#[inline]
pub fn flags_check(self, mask: u32) -> bool {
(self.0 & TAB_ENT_FLAG_MASK & mask) == mask
}
}
#[allow(dead_code)]
pub mod ent_flag {
/// If the bit is set, then pages are 4 MiB in size. Otherwise, they are 4 KiB.
/// Please note that 4-MiB pages require PSE to be enabled.
pub const PAGE_SIZE_4MIB: u32 = 0b000010000000;
/// If the bit is set, the page will not be cached. Otherwise, it will be.
pub const CACHE_DISABLE: u32 = 0b000000010000;
/// If the bit is set, write-through caching is enabled. If not, then write-back is enabled instead.
pub const WRITE_THROUGH: u32 = 0b000000001000;
/// If the bit is set, then the page may be accessed by all;
/// if the bit is not set, however, only the supervisor can access it.
/// For a page directory entry, the user bit controls access to all the pages referenced by the page directory entry.
pub const USER: u32 = 0b000000000100;
/// If the bit is set, the page is read/write. Otherwise when it is not set, the page is read-only.
pub const WRITABLE: u32 = 0b000000000010;
/// If the bit is set, the page is actually in physical memory at the moment.
pub const PRESENT: u32 = 0b000000000001;
}
}
pub mod seg {
// various segment selectors.
/// kernel code
pub const SEG_KCODE: usize = 1;
/// kernel data+stack
pub const SEG_KDATA: usize = 2;
/// user code
pub const SEG_UCODE: usize = 3;
/// user data+stack
pub const SEG_UDATA: usize = 4;
/// this process's task state
pub const SEG_TSS: usize = 5;
/// CPU.gdt[SegDesc; NSEGS]; holds the above segments
pub const NSEGS: usize = 6;
/// GDT initial value
pub const GDT_ZERO: [SegDesc; NSEGS] = [
SegDesc::new(),
SegDesc::new(),
SegDesc::new(),
SegDesc::new(),
SegDesc::new(),
SegDesc::new(),
];
pub mod seg_type {
// Application segment type bits
/// Executable segment
pub const STA_X: u8 = 0x8;
/// Writeable (non-executable segments)
pub const STA_W: u8 = 0x2;
/// Readable (executable segments)
pub const STA_R: u8 = 0x2;
// System segment type bits
/// Available 32-bit TSS
pub const STS_T32A: u8 = 0x9;
/// 32-bit Interrupt Gate
pub const STS_IG32: u8 = 0xE;
/// 32-bit Trap Gate
pub const STS_TG32: u8 = 0xF;
}
pub mod dpl {
/// Ring-3 (User DPL)
pub const USER: u8 = 0x3;
}
#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct SegDesc {
f1: u32,
f2: u32,
}
impl SegDesc {
#[inline]
pub const fn new() -> Self {
Self { f1: 0, f2: 0 }
}
#[inline]
pub const fn from_raw(f1: u32, f2: u32) -> Self {
Self { f1, f2 }
}
#[inline]
pub const fn set_lim(mut self, limit: u32) -> Self {
let lim_00_15 = limit & 0x0000FFFF;
let lim_16_19 = limit & 0x000F0000;
self.f1 = (self.f1 & 0xFFFF0000) | lim_00_15;
self.f2 = (self.f2 & 0xFFF0FFFF) | lim_16_19;
self
}
#[inline]
pub const fn set_base(mut self, base: u32) -> Self {
let base_00_15 = base & 0x0000FFFF;
let base_16_23 = base & 0x00FF0000;
let base_24_31 = base & 0xFF000000;
self.f1 = (self.f1 & 0x0000FFFF) | (base_00_15 << 16);
self.f2 = (self.f2 & 0x00FFFF00) | base_24_31 | (base_16_23 >> 16);
self
}
#[inline]
pub const fn set_flags(mut self, flags: u8) -> Self {
let flags = (flags & 0x0F) as u32; // [gr, sz, 0, 0]
self.f2 = (self.f2 & 0xFF0FFFFF) | (flags << 20);
self
}
#[inline]
pub const fn set_access_byte(mut self, access: u8) -> Self {
self.f2 = (self.f2 & 0xFFFF00FF) | ((access as u32) << 8);
self
}
/// Normal segment (limit is in 4 KiB blocks)
#[inline]
pub const fn seg(ty: u8, base: u32, lim: u32, dpl: u8) -> Self {
Self::new()
.set_base(base)
.set_lim(lim >> 12)
.set_access_byte(0b10010000 | ((dpl & 0b11) << 5) | ty)
.set_flags(0b1100)
}
/// Task State Segment (limit is in 1B blocks)
#[inline]
pub fn tss(ty: u8, base: u32, lim: u32, dpl: u8) -> Self {
Self::new()
.set_base(base)
.set_lim(lim)
.set_access_byte(0b10000000 | ((dpl & 0b11) << 5) | ty)
.set_flags(0b0100)
}
}
}
pub mod gate {
#[derive(Copy, Clone)]
pub struct GateDesc {
f1: u32,
f2: u32,
}
impl GateDesc {
pub const fn new() -> Self {
Self { f1: 0, f2: 0 }
}
pub fn set_offset(mut self, offset: u32) -> Self {
let offset_00_15 = offset & 0x0000FFFF;
let offset_16_31 = offset & 0xFFFF0000;
self.f1 = (self.f1 & 0xFFFF0000) | offset_00_15;
self.f2 = (self.f2 & 0x0000FFFF) | offset_16_31;
self
}
pub fn set_selector(mut self, selector: u16) -> Self {
self.f1 = (self.f1 & 0x0000FFFF) | ((selector as u32) << 16);
self
}
pub fn set_type_attribute(mut self, type_attr: u8) -> Self {
self.f2 = (self.f2 & 0xFFFF00FF) | ((type_attr as u32) << 8);
self
}
/// Set up a normal interrupt/trap gate descriptor.
/// - is_trap: true for a trap (= exception) gate, false for an interrupt gate.
/// interrupt gate clears FL_IF, trap gate leaves FL_IF alone
/// - selector: Code segment selector for interrupt/trap handler
/// - offset: Offset in code segment for interrupt/trap handler
/// - dpl: Descriptor Privilege Level -
/// the privilege level required for software to invoke
/// this interrupt/trap gate explicitly using an int instruction.
pub fn set(&mut self, is_trap: bool, selector: u16, offset: u32, dpl: u8) {
use super::seg::seg_type::{STS_IG32, STS_TG32};
let present = 1;
let dpl = dpl & 0x03;
let s = 0; // Storage Segment : Set to 0 for interrupt and trap gates
let ty = (if is_trap { STS_TG32 } else { STS_IG32 }) & 0x0F;
let attr_ty = (present << 7) | (dpl << 5) | (s << 4) | ty;
// 7 0
// +---+---+---+---+---+---+---+---+
// | P | DPL | S | GateType |
// +---+---+---+---+---+---+---+---+
*self = Self::new()
.set_offset(offset)
.set_selector(selector)
.set_type_attribute(attr_ty);
}
}
}
pub type Page = [u8; PAGE_SIZE];
/// Page size
pub const PAGE_SIZE: usize = 4096;
/// Kernel stack size
pub const KSTACKSIZE: usize = 4096;
/// First kernel virtual address
pub const KERNBASE: VAddr<Page> = unsafe { VAddr::from_raw_unchecked(0x80000000) };
/// Address where kernel is linked (KERNBASE + EXTMEM)
pub const KERNLINK: VAddr<Page> = unsafe { VAddr::from_raw_unchecked(0x80100000) };
/// Start of extended memory
pub const EXTMEM: PAddr<Page> = unsafe { PAddr::from_raw_unchecked(0x100000) };
/// Top physical memory
pub const PHYSTOP: PAddr<Page> = unsafe { PAddr::from_raw_unchecked(0xE000000) };
/// Other devices are at high addresses
pub const DEVSPACE: VAddr<Page> = unsafe { VAddr::from_raw_unchecked(0xFE000000) };
use utils::prelude::*;
#[inline]
pub const fn p2v<T>(pa: PAddr<T>) -> VAddr<T> {
let raw = pa.raw();
unsafe { VAddr::from_raw_unchecked(raw + KERNBASE.raw()) }
}
#[inline]
pub const fn v2p<T>(pa: VAddr<T>) -> PAddr<T> {
let raw = pa.raw();
unsafe { PAddr::from_raw_unchecked(raw - KERNBASE.raw()) }
}
|
use std::fmt;
use std::hash::Hash;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct BlockId {
filename: String,
blknum: u64,
}
impl BlockId {
pub fn new(filename: impl Into<String>, blknum: u64) -> BlockId {
BlockId {
filename: filename.into(),
blknum,
}
}
pub fn filename(&self) -> &str {
&self.filename
}
pub fn number(&self) -> u64 {
self.blknum
}
}
impl fmt::Display for BlockId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[file {}, block {}]", self.filename, self.blknum)
}
}
|
use chrono::Duration;
use once_cell::sync::Lazy;
use prometheus::{
register_histogram, register_int_counter_vec, Histogram, HistogramTimer, IntCounter,
};
use prometheus_static_metric::make_static_metric;
use super::error::Error;
make_static_metric! {
struct MqttStats: IntCounter {
"method" => {
room_close,
room_upload,
room_adjust,
task_complete,
room_dump_events,
edition_commit,
},
"status" => {
success,
failure,
},
}
}
pub struct AuthMetrics;
impl AuthMetrics {
pub fn start_timer() -> HistogramTimer {
METRICS.authz_time.start_timer()
}
}
pub struct MqttMetrics;
impl MqttMetrics {
pub fn observe_disconnect() {
METRICS.disconnect.inc()
}
pub fn observe_reconnect() {
METRICS.reconnection.inc()
}
pub fn observe_connection_error() {
METRICS.connection_error.inc()
}
pub fn observe_event_result(result: &Result<(), Error>, label: Option<&str>) {
match label {
Some("room.close") => {
if result.is_err() {
METRICS.stats.room_close.failure.inc();
} else {
METRICS.stats.room_close.success.inc();
}
}
Some("room.upload") => {
if result.is_err() {
METRICS.stats.room_upload.failure.inc();
} else {
METRICS.stats.room_upload.success.inc();
}
}
Some("room.adjust") => {
if result.is_err() {
METRICS.stats.room_adjust.failure.inc();
} else {
METRICS.stats.room_adjust.success.inc();
}
}
Some("task.complete") => {
if result.is_err() {
METRICS.stats.task_complete.failure.inc();
} else {
METRICS.stats.task_complete.success.inc();
}
}
Some("room.dump_events") => {
if result.is_err() {
METRICS.stats.room_dump_events.failure.inc();
} else {
METRICS.stats.room_dump_events.success.inc();
}
}
Some("edition.commit") => {
if result.is_err() {
METRICS.stats.edition_commit.failure.inc();
} else {
METRICS.stats.edition_commit.success.inc();
}
}
_ => {}
}
}
}
pub trait AuthorizeMetrics {
fn measure(self) -> Self;
}
impl AuthorizeMetrics for Result<Duration, svc_authz::error::Error> {
fn measure(self) -> Self {
if let Ok(Ok(d)) = self.as_ref().map(|d| d.to_std()) {
let nanos = f64::from(d.subsec_nanos()) / 1e9;
METRICS.authz_time.observe(d.as_secs() as f64 + nanos)
}
self
}
}
static METRICS: Lazy<Metrics> = Lazy::new(Metrics::new);
struct Metrics {
stats: MqttStats,
connection_error: IntCounter,
disconnect: IntCounter,
reconnection: IntCounter,
authz_time: Histogram,
}
impl Metrics {
pub fn new() -> Self {
let mqtt_stats =
register_int_counter_vec!("mqtt_stats", "Mqtt stats", &["method", "status"])
.expect("Can't create stats metrics");
let mqtt_errors =
register_int_counter_vec!("mqtt_messages", "Mqtt message types", &["status"])
.expect("Bad mqtt messages metric");
Metrics {
stats: MqttStats::from(&mqtt_stats),
connection_error: mqtt_errors.with_label_values(&["connection_error"]),
disconnect: mqtt_errors.with_label_values(&["disconnect"]),
reconnection: mqtt_errors.with_label_values(&["reconnect"]),
authz_time: register_histogram!("auth_time", "Authorization time")
.expect("Bad authz hist"),
}
}
}
|
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
use std::u32;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
const LINEBREAK: &'static str = include_str!("unicode-data/LineBreak-11.0.0.txt");
const UNICODEDATA: &'static str = include_str!("unicode-data/UnicodeData.txt");
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("convert_to_break_class");
let mut f = File::create(&dest_path).unwrap();
// Extract all codepoints that belong to the general category of Mn or Mc
let re1 = Regex::new(r"(?P<codepoint>[0-9A-F]+);[^;]+;(?P<category>(Mn)|(Mc))").unwrap();
let mut mn = Vec::new();
let mut mc = Vec::new();
for caps in re1.captures_iter(UNICODEDATA) {
let number =
u32::from_str_radix(&caps["codepoint"], 16).expect("Could not parse codepoint");
match &caps["category"] {
"Mn" => mn.push((number, None)),
"Mc" => mc.push((number, None)),
_ => unreachable!(),
};
}
let compact_mn = squish(mn);
let compact_mc = squish(mc);
let re2 = Regex::new(
r"(?P<left_n>[0-9A-F]+)(\.\.(?P<right_n>[0-9A-F]+))?;(?P<class>[A-Z0-9]+)",
).unwrap();
let mut hash: HashMap<&str, Vec<(u32, Option<u32>)>> = HashMap::new();
for caps in re2.captures_iter(LINEBREAK) {
// (u32, Some(u32)): 123A..123F
// (u32, None) : 123A
let numbers: (u32, Option<u32>) = match &caps.name("right_n") {
Some(right_n_match) => {
let left_n_str = &caps["left_n"];
let left_n =
u32::from_str_radix(left_n_str, 16).expect("Could not parse left of range");
let right_n_str = right_n_match.as_str();
let right_n =
u32::from_str_radix(right_n_str, 16).expect("Could not parse right of range");
(left_n, Some(right_n))
}
None => {
let n =
u32::from_str_radix(&caps["left_n"], 16).expect("Could not parse codepoint");
(n, None)
}
};
let class = caps.name("class").unwrap().as_str();
hash.entry(class).or_insert(Vec::new()).push(numbers);
}
write!(f, "match n as u32 {{").unwrap();
for (key, value) in hash.into_iter().map(|(key, list)| (key, squish(list))) {
match key {
"SA" => write!(
f,
"0x{} => match n as u32 {{0x{}|0x{} => Class::CM,_ => Class::AL}}",
value.join(" | 0x"),
compact_mn.join(" | 0x"),
compact_mc.join(" | 0x")
).unwrap(),
"XX" | "SG" | "AI" => write!(f, "0x{} => Class::AL,", value.join(" | 0x")).unwrap(),
"CJ" => write!(f, "0x{} => Class::NS,", value.join(" | 0x")).unwrap(),
_ => write!(f, "0x{} => Class::{},", value.join(" | 0x"), key).unwrap(),
}
}
write!(
f,
"0x1F000...0x1FFFD => Class::ID, 0x20A0...0x20CF => Class::PR, _ => Class::AL}}"
).unwrap();
let dest_path = Path::new(&out_dir).join("states");
let mut f = File::create(&dest_path).unwrap();
write_states(&mut f);
}
// Convert a list of codepoints / ranges of codepoints into a list with the
// minimal number of entries to represent the same codepoints
fn squish(values: Vec<(u32, Option<u32>)>) -> Vec<String> {
let mut lower = values[0].0;
let mut higher = values[0].1;
let mut out = Vec::new();
for window in values.windows(2) {
let (left_0, right_0) = window[0];
let (left_1, right_1) = window[1];
match (right_0, right_1) {
(Some(right_0_value), Some(right_1_value)) => {
if right_0_value == left_1 - 1 {
higher = Some(right_1_value);
} else {
out.push(format_codepoints(lower, higher));
higher = Some(right_1_value);
lower = left_1;
}
}
(Some(right_0_value), None) => {
if right_0_value == left_1 - 1 {
higher = Some(left_1);
} else {
out.push(format_codepoints(lower, higher));
higher = None;
lower = left_1;
}
}
(None, Some(right_1_value)) => {
if left_0 == left_1 - 1 {
higher = Some(right_1_value);
} else {
out.push(format_codepoints(lower, higher));
higher = Some(right_1_value);
lower = left_1;
}
}
(None, None) => {
if left_0 == left_1 - 1 {
higher = Some(left_1);
} else {
out.push(format_codepoints(lower, higher));
higher = None;
lower = left_1;
}
}
}
}
out.push(format_codepoints(lower, higher));
out
}
fn format_codepoints(lower: u32, higher: Option<u32>) -> String {
match higher {
Some(x) => format!("{:X}...0x{:X}", lower, x),
None => format!("{:X}", lower),
}
}
#[derive(Debug, Clone, Copy)]
pub enum Break {
Mandatory,
Opportunity,
Prohibited,
}
const NUM_OF_CLASSES: usize = 39;
fn write_states(f: &mut File) {
const BK: usize = 0;
const CR: usize = 1;
const LF: usize = 2;
const CM: usize = 3;
const NL: usize = 4;
const WJ: usize = 5;
const ZW: usize = 6;
const GL: usize = 7;
const SP: usize = 8;
const ZWJ: usize = 9;
const B2: usize = 10;
const BA: usize = 11;
const BB: usize = 12;
const HY: usize = 13;
const CB: usize = 14;
const CL: usize = 15;
const CP: usize = 16;
const EX: usize = 17;
const IN: usize = 18;
const NS: usize = 19;
const OP: usize = 20;
const QU: usize = 21;
const IS: usize = 22;
const NU: usize = 23;
const PO: usize = 24;
const PR: usize = 25;
const SY: usize = 26;
const AL: usize = 27;
const EB: usize = 28;
const EM: usize = 29;
const H2: usize = 30;
const H3: usize = 31;
const HL: usize = 32;
const ID: usize = 33;
const JL: usize = 34;
const JV: usize = 35;
const JT: usize = 36;
const RI: usize = 37;
const XX: usize = 38;
const LB8_STATE: usize = NUM_OF_CLASSES + 1;
const LB14_STATE: usize = NUM_OF_CLASSES + 2;
const LB15_STATE: usize = NUM_OF_CLASSES + 3;
const LB16_STATE: usize = NUM_OF_CLASSES + 4;
const LB17_STATE: usize = NUM_OF_CLASSES + 5;
const LB21A_HY_STATE: usize = NUM_OF_CLASSES + 6;
const LB21A_BA_STATE: usize = NUM_OF_CLASSES + 7;
const LB30A_EVEN_STATE: usize = NUM_OF_CLASSES + 8;
const LB9_EXCEPTIONS: [usize; 8] = [BK, CR, LF, NL, SP, ZW, ZWJ, 39];
fn break_before(class: usize, b: Break, states: &mut Vec<[(usize, Break); NUM_OF_CLASSES]>) {
for state in states.iter_mut() {
state[class].1 = b;
}
}
fn break_after(state: usize, b: Break, states: &mut Vec<[(usize, Break); NUM_OF_CLASSES]>) {
for c in states[state].iter_mut() {
c.1 = b;
}
}
fn not_allowed_between(
c1: usize,
c2: usize,
states: &mut Vec<[(usize, Break); NUM_OF_CLASSES]>,
) {
states[c1][c2].1 = Break::Prohibited;
}
const LB12A_EXCEPTIONS: [usize; 3] = [SP, BA, HY];
let mut states: Vec<[(usize, Break); NUM_OF_CLASSES]> = Vec::new();
let mut extra_states: Vec<[(usize, Break); NUM_OF_CLASSES]> = Vec::new();
for _ in 0..(NUM_OF_CLASSES + 1) {
states.push([
(0, Break::Opportunity),
(1, Break::Opportunity),
(2, Break::Opportunity),
(3, Break::Opportunity),
(4, Break::Opportunity),
(5, Break::Opportunity),
(6, Break::Opportunity),
(7, Break::Opportunity),
(8, Break::Opportunity),
(9, Break::Opportunity),
(10, Break::Opportunity),
(11, Break::Opportunity),
(12, Break::Opportunity),
(13, Break::Opportunity),
(14, Break::Opportunity),
(15, Break::Opportunity),
(16, Break::Opportunity),
(17, Break::Opportunity),
(18, Break::Opportunity),
(19, Break::Opportunity),
(20, Break::Opportunity),
(21, Break::Opportunity),
(22, Break::Opportunity),
(23, Break::Opportunity),
(24, Break::Opportunity),
(25, Break::Opportunity),
(26, Break::Opportunity),
(27, Break::Opportunity),
(28, Break::Opportunity),
(29, Break::Opportunity),
(30, Break::Opportunity),
(31, Break::Opportunity),
(32, Break::Opportunity),
(33, Break::Opportunity),
(34, Break::Opportunity),
(35, Break::Opportunity),
(36, Break::Opportunity),
(37, Break::Opportunity),
(38, Break::Opportunity),
]);
}
// LB30b
not_allowed_between(EB, EM, &mut states);
// LB30a
not_allowed_between(RI, RI, &mut states);
states[RI][RI].0 = LB30A_EVEN_STATE;
// LB30
not_allowed_between(AL, OP, &mut states);
not_allowed_between(HL, OP, &mut states);
not_allowed_between(NU, OP, &mut states);
not_allowed_between(CP, AL, &mut states);
not_allowed_between(CP, HL, &mut states);
not_allowed_between(CP, NU, &mut states);
// LB29
not_allowed_between(IS, AL, &mut states);
not_allowed_between(IS, HL, &mut states);
// LB28
not_allowed_between(AL, AL, &mut states);
not_allowed_between(AL, HL, &mut states);
not_allowed_between(HL, AL, &mut states);
not_allowed_between(HL, HL, &mut states);
// LB27
not_allowed_between(JL, IN, &mut states);
not_allowed_between(JV, IN, &mut states);
not_allowed_between(JT, IN, &mut states);
not_allowed_between(H2, IN, &mut states);
not_allowed_between(H3, IN, &mut states);
not_allowed_between(JL, PO, &mut states);
not_allowed_between(JV, PO, &mut states);
not_allowed_between(JT, PO, &mut states);
not_allowed_between(H2, PO, &mut states);
not_allowed_between(H3, PO, &mut states);
not_allowed_between(PR, JL, &mut states);
not_allowed_between(PR, JV, &mut states);
not_allowed_between(PR, JT, &mut states);
not_allowed_between(PR, H2, &mut states);
not_allowed_between(PR, H3, &mut states);
// LB26
not_allowed_between(JL, JL, &mut states);
not_allowed_between(JL, JV, &mut states);
not_allowed_between(JL, H2, &mut states);
not_allowed_between(JL, H3, &mut states);
not_allowed_between(JV, JV, &mut states);
not_allowed_between(JV, JT, &mut states);
not_allowed_between(H2, JV, &mut states);
not_allowed_between(H2, JT, &mut states);
not_allowed_between(JT, JT, &mut states);
not_allowed_between(H3, JT, &mut states);
// LB25
not_allowed_between(CL, PO, &mut states);
not_allowed_between(CP, PO, &mut states);
not_allowed_between(CL, PR, &mut states);
not_allowed_between(CP, PR, &mut states);
not_allowed_between(NU, PO, &mut states);
not_allowed_between(NU, PR, &mut states);
not_allowed_between(PO, OP, &mut states);
not_allowed_between(PO, NU, &mut states);
not_allowed_between(PR, OP, &mut states);
not_allowed_between(PR, NU, &mut states);
not_allowed_between(HY, NU, &mut states);
not_allowed_between(IS, NU, &mut states);
not_allowed_between(NU, NU, &mut states);
not_allowed_between(SY, NU, &mut states);
// LB24
not_allowed_between(PR, AL, &mut states);
not_allowed_between(PR, HL, &mut states);
not_allowed_between(PO, AL, &mut states);
not_allowed_between(PO, HL, &mut states);
not_allowed_between(AL, PR, &mut states);
not_allowed_between(AL, PO, &mut states);
not_allowed_between(HL, PR, &mut states);
not_allowed_between(HL, PO, &mut states);
// LB23a
not_allowed_between(PR, ID, &mut states);
not_allowed_between(PR, EB, &mut states);
not_allowed_between(PR, EM, &mut states);
not_allowed_between(ID, PO, &mut states);
not_allowed_between(EB, PO, &mut states);
not_allowed_between(EM, PO, &mut states);
// LB23
not_allowed_between(AL, NU, &mut states);
not_allowed_between(HL, NU, &mut states);
not_allowed_between(NU, AL, &mut states);
not_allowed_between(NU, HL, &mut states);
// LB22
not_allowed_between(AL, IN, &mut states);
not_allowed_between(HL, IN, &mut states);
not_allowed_between(EX, IN, &mut states);
not_allowed_between(ID, IN, &mut states);
not_allowed_between(EB, IN, &mut states);
not_allowed_between(EM, IN, &mut states);
not_allowed_between(IN, IN, &mut states);
not_allowed_between(NU, IN, &mut states);
// LB21b
not_allowed_between(SY, HL, &mut states);
// LB21a
states[HL][HY].0 = LB21A_HY_STATE;
states[HL][BA].0 = LB21A_BA_STATE;
// LB21
break_before(BA, Break::Prohibited, &mut states);
break_before(HY, Break::Prohibited, &mut states);
break_before(NS, Break::Prohibited, &mut states);
break_after(BB, Break::Prohibited, &mut states);
// LB20
break_before(CB, Break::Opportunity, &mut states);
break_after(CB, Break::Opportunity, &mut states);
// LB19
break_before(QU, Break::Prohibited, &mut states);
break_after(QU, Break::Prohibited, &mut states);
// LB18
break_after(SP, Break::Opportunity, &mut states);
// LB17
not_allowed_between(B2, B2, &mut states);
states[B2][B2].1 = Break::Prohibited;
states[B2][SP].0 = LB17_STATE;
// LB16
not_allowed_between(CL, NS, &mut states);
states[CL][SP].0 = LB16_STATE;
not_allowed_between(CP, NS, &mut states);
states[CP][SP].0 = LB16_STATE;
// LB15
states[QU][OP].1 = Break::Prohibited;
states[QU][SP].0 = LB15_STATE;
// LB14
break_after(OP, Break::Prohibited, &mut states);
states[OP][SP].0 = LB14_STATE;
// LB13
break_before(CL, Break::Prohibited, &mut states);
break_before(CP, Break::Prohibited, &mut states);
break_before(EX, Break::Prohibited, &mut states);
break_before(IS, Break::Prohibited, &mut states);
break_before(SY, Break::Prohibited, &mut states);
// LB12a
for state in states.iter_mut().enumerate().filter_map(|(index, state)| {
if LB12A_EXCEPTIONS.contains(&index) {
None
} else {
Some(state)
}
}) {
state[GL].1 = Break::Prohibited;
}
// LB12
break_after(GL, Break::Prohibited, &mut states);
// LB11
break_after(WJ, Break::Prohibited, &mut states);
break_before(WJ, Break::Prohibited, &mut states);
// LB10
states[AL][CM].1 = Break::Prohibited;
states[AL][ZWJ].1 = Break::Prohibited;
states[CM] = states[AL];
states[ZWJ] = states[AL];
// LB9
for (i, state) in states.iter_mut().enumerate().filter_map(|(index, state)| {
if LB9_EXCEPTIONS.contains(&index) {
None
} else {
Some((index, state))
}
}) {
state[CM] = (i, Break::Prohibited);
state[ZWJ] = (i, Break::Prohibited);
}
// LB8a
break_after(ZWJ, Break::Prohibited, &mut states);
// LB8
break_after(ZW, Break::Opportunity, &mut states);
states[ZW][SP].0 = LB8_STATE;
// LB7
break_before(SP, Break::Prohibited, &mut states);
break_before(ZW, Break::Prohibited, &mut states);
// LB6
break_before(BK, Break::Prohibited, &mut states);
break_before(CR, Break::Prohibited, &mut states);
break_before(LF, Break::Prohibited, &mut states);
break_before(NL, Break::Prohibited, &mut states);
// LB5
break_after(CR, Break::Mandatory, &mut states);
break_after(LF, Break::Mandatory, &mut states);
break_after(NL, Break::Mandatory, &mut states);
not_allowed_between(CR, LF, &mut states);
// LB4
break_after(BK, Break::Mandatory, &mut states);
// LB2
break_after(NUM_OF_CLASSES, Break::Prohibited, &mut states);
// Special extra states
// LB8
let mut new_state = states[SP].clone();
for part in new_state.iter_mut().enumerate().filter_map(|(i, s)| {
if [BK, CR, LF, NL, SP, ZW].contains(&i) {
None
} else {
Some(s)
}
}) {
part.1 = Break::Opportunity;
}
extra_states.push(new_state);
// LB14
let mut new_state = states[SP].clone();
for part in new_state.iter_mut() {
part.1 = Break::Prohibited;
}
extra_states.push(new_state);
// LB15
let mut new_state = states[SP].clone();
new_state[OP].1 = Break::Prohibited;
extra_states.push(new_state);
// LB16
let mut new_state = states[SP].clone();
new_state[NS].1 = Break::Prohibited;
extra_states.push(new_state);
// LB17
let mut new_state = states[SP].clone();
new_state[B2].1 = Break::Prohibited;
extra_states.push(new_state);
// LB21a
let mut hy_state = states[HY].clone();
for part in hy_state.iter_mut() {
part.1 = Break::Prohibited;
}
let mut ba_state = states[BA].clone();
for part in ba_state.iter_mut() {
part.1 = Break::Prohibited;
}
extra_states.push(hy_state);
extra_states.push(ba_state);
// LB30a
let mut even_state = states[RI].clone();
even_state[RI] = (RI, Break::Opportunity);
extra_states.push(even_state);
states.extend(extra_states.into_iter());
write!(f, "const NUM_OF_CLASSES: usize = {};\nconst STATES: [[(usize, Break); NUM_OF_CLASSES]; {}] = [", NUM_OF_CLASSES, states.len()).unwrap();
for state in states {
write!(f, "[").unwrap();
for value in state.iter() {
write!(f, "({}, Break::{:?}),", value.0, value.1).unwrap();
}
write!(f, "],").unwrap();
}
write!(f, "];").unwrap();
}
|
use crate::normal::Normal;
use crate::points::HasPoints;
use crate::suit::Suit;
use crate::suit_value::SuitValue;
use crate::traits::{Discardable, Power, Representation};
use crate::trump::Trump;
use colored::ColoredString;
use ordered_float::OrderedFloat;
use std::fmt;
#[derive(Copy, Ord, Clone, Debug, Eq, PartialEq, PartialOrd)]
pub enum Card {
Trump(Trump),
Normal(Normal),
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Trump(t) => write!(f, "{t}"),
Self::Normal(n) => write!(f, "{n}"),
}
}
}
impl HasPoints for Card {
fn points(&self) -> OrderedFloat<f64> {
match self {
Self::Trump(v) => v.points(),
Self::Normal(n) => n.points(),
}
}
}
impl Power for Card {
fn power(&self) -> usize {
match self {
Self::Trump(v) => *v as usize + SuitValue::King as usize,
Self::Normal(n) => n.power(),
}
}
}
impl Discardable for Card {
fn discardable(&self) -> bool {
match self {
Self::Trump(t) => t.discardable(),
Self::Normal(n) => n.discardable(),
}
}
fn discardable_forced(&self) -> bool {
match self {
Self::Trump(t) => t.discardable_forced(),
Self::Normal(n) => n.discardable_forced(),
}
}
}
impl Card {
#[must_use]
pub fn normal(suit: Suit, value: SuitValue) -> Self {
Self::Normal(Normal::new(suit, value))
}
#[must_use]
pub const fn is_fool(self) -> bool {
matches!(self, Self::Trump(Trump::Fool))
}
#[must_use]
pub const fn is_trump(self) -> bool {
matches!(self, Self::Trump(_))
}
#[must_use]
pub const fn is_oudler(self) -> bool {
match self {
Self::Trump(c) => c.is_oudler(),
Self::Normal(_) => false,
}
}
#[must_use]
pub fn master(self, arg: Self) -> bool {
match (&self, &arg) {
(Self::Trump(c), Self::Normal(_)) => c != &Trump::Fool,
(Self::Normal(_), Self::Trump(c)) => c == &Trump::Fool,
(Self::Normal(n1), Self::Normal(n2)) => {
n1.suit() != n2.suit() || n1.value() > n2.value()
}
(Self::Trump(v1), Self::Trump(v2)) => v1 > v2,
}
}
}
impl Representation for Card {
fn symbol(&self) -> &'static str {
match self {
Self::Normal(n) => n.symbol(),
Self::Trump(t) => t.symbol(),
}
}
fn colored_symbol(&self) -> ColoredString {
match self {
Self::Normal(n) => n.colored_symbol(),
Self::Trump(t) => t.colored_symbol(),
}
}
fn color(&self) -> &'static str {
match self {
Self::Normal(n) => n.color(),
Self::Trump(t) => t.color(),
}
}
fn repr(&self) -> ColoredString {
match self {
Self::Normal(n) => n.repr(),
Self::Trump(t) => t.repr(),
}
}
fn full_repr(&self) -> ColoredString {
match self {
Self::Normal(n) => n.full_repr(),
Self::Trump(t) => t.full_repr(),
}
}
}
#[test]
fn card_tests() {
let trump_2 = Card::Trump(Trump::_2);
println!("{}", trump_2.repr());
let petit = Card::Trump(Trump::Petit);
println!("{}", petit.repr());
let fool = Card::Trump(Trump::Fool);
println!("{}", fool.repr());
let unassailable = Card::Trump(Trump::_21);
let spade_1 = Card::normal(Suit::Spade, SuitValue::_1);
let spade_2 = Card::normal(Suit::Spade, SuitValue::_2);
let spade_3 = Card::normal(Suit::Spade, SuitValue::_3);
let spade_10 = Card::normal(Suit::Spade, SuitValue::_10);
println!("{}", spade_10.repr());
let diamond_3 = Card::normal(Suit::Diamond, SuitValue::_3);
println!("{}", diamond_3.repr());
let heart_4 = Card::normal(Suit::Heart, SuitValue::_4);
println!("{}", heart_4.repr());
let club_king = Card::normal(Suit::Club, SuitValue::King);
println!("{}", club_king.repr());
assert!(!spade_3.master(spade_10));
assert!(!petit.master(trump_2));
assert!(petit.master(spade_1));
assert!(!spade_1.master(petit));
assert!(spade_2.master(spade_1));
assert!(diamond_3.master(spade_2));
assert!(diamond_3.master(fool));
assert!(!fool.master(spade_1));
assert!(!petit.discardable());
assert!(!fool.discardable());
assert!(!unassailable.discardable());
assert!(!petit.discardable_forced());
assert!(!fool.discardable_forced());
assert!(!unassailable.discardable_forced());
assert_eq!(unassailable.points(), 4.5);
}
|
use std::mem;
use std::ptr;
use messages::Message;
use libc::{c_char, size_t};
use assets::TradeAsset;
use capi::common::*;
use transactions::ask_offer::AskOfferWrapper;
use error::{Error, ErrorKind};
ffi_fn! {
fn dmbc_tx_ask_offer_create(
public_key: *const c_char,
asset: *mut TradeAsset,
seed: u64,
memo: *const c_char,
error: *mut Error,
) -> *mut AskOfferWrapper {
let public_key = match parse_public_key(public_key) {
Ok(public_key) => public_key,
Err(err) => {
unsafe {
if !error.is_null() {
*error = err;
}
return ptr::null_mut();
}
}
};
if asset.is_null() {
unsafe {
if !error.is_null() {
*error = Error::new(ErrorKind::Text("Invalid asset pointer.".to_string()));
}
return ptr::null_mut();
}
}
let asset = TradeAsset::from_ptr(asset);
let memo = match parse_str(memo) {
Ok(info) => info,
Err(err) => {
unsafe {
if !error.is_null() {
*error = err;
}
return ptr::null_mut();
}
}
};
let wrapper = AskOfferWrapper::new(&public_key, asset.clone(), seed, memo);
Box::into_raw(Box::new(wrapper))
}
}
ffi_fn! {
fn dmbc_tx_ask_offer_free(wrapper: *const AskOfferWrapper) {
if !wrapper.is_null() {
unsafe { Box::from_raw(wrapper as *mut AskOfferWrapper); }
}
}
}
ffi_fn! {
fn dmbc_tx_ask_offer_into_bytes(
wrapper: *mut AskOfferWrapper,
length: *mut size_t,
error: *mut Error
) -> *const u8 {
let wrapper = match AskOfferWrapper::from_ptr(wrapper) {
Ok(wrapper) => wrapper,
Err(err) => {
unsafe {
if !error.is_null() {
*error = err;
}
return ptr::null();
}
}
};
let bytes = wrapper.unwrap().raw().body().to_vec();
assert!(bytes.len() == bytes.capacity());
let length = unsafe { &mut *length };
let len = bytes.len() as size_t;
*length = len;
let ptr = bytes.as_ptr();
mem::forget(bytes);
ptr
}
} |
use std::collections::HashSet;
pub fn part1(input: &HashSet<i64>) -> Option<i64> {
for num in input.iter() {
let find = 2020 - num;
if input.contains(&find) {
return Some(num * find);
}
}
None
}
pub fn part2(input: &HashSet<i64>) -> Option<i64> {
for (a_index, a) in input.iter().enumerate() {
for b in input.iter().skip(a_index) {
if a == b {
continue;
}
let c = 2020 - a - b;
if c > 0 && input.contains(&c) {
return Some(a * b * c);
}
}
}
None
}
|
use crate::features::syntax::StatementFeature;
use crate::parse::visitor::tests::assert_no_stmt_feature;
use crate::parse::visitor::tests::assert_stmt_feature;
#[test]
fn continue_no_label() {
assert_stmt_feature(
"while (cond) {
continue;
}",
StatementFeature::ContinueStatement,
);
}
#[test]
fn continue_with_label() {
assert_stmt_feature(
"lbl: while (cond) {
continue lbl;
}",
StatementFeature::ContinueLabelStatement,
);
}
#[test]
fn distinct() {
assert_no_stmt_feature(
"while (true) { continue }",
StatementFeature::ContinueLabelStatement,
);
assert_no_stmt_feature(
"label: for(;;) { continue label; }",
StatementFeature::ContinueStatement,
);
}
|
// Copyright (c) 2017 oic developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! [NOT IMPL]
//! This structure is used to represent the unique identifier of a row in the database and is
//! available by handle to a calling application or driver. Rowids cannot be created or set directly
//! but are created implicitly when a variable of type DPI_ORACLE_TYPE_ROWID is created. They are
//! destroyed when the last reference is released by a call to the function `Rowid::release()`. All
//! of the attributes of the structure `ODPIBaseType` are included in this structure in addition to
//! the ones specific to this structure described below.
// use error::{ErrorKind, Result};
// use odpi::externs;
use odpi::opaque::ODPIRowid;
/// This structure is used to represent the unique identifier of a row in the database and is
/// available by handle to a calling application or driver.
pub struct Rowid {
/// The ODPI-C rowid
inner: *mut ODPIRowid,
}
impl Rowid {
/// Get the `inner` value.
#[doc(hidden)]
pub fn inner(&self) -> *mut ODPIRowid {
self.inner
}
}
impl From<*mut ODPIRowid> for Rowid {
fn from(inner: *mut ODPIRowid) -> Rowid {
Rowid { inner: inner }
}
}
|
use crate::memory::Memory;
pub fn update_dma(mem: &mut Memory) {
if mem.read(0xff46) != 0 {
//println!("/!\\ DMA HAS OCCURRED");
let source: u16 = (mem.read(0xff46) as u16) << 8;
let dest: u16 = 0xFE00;
for i in 0..0xA0 {
mem.write(dest + i, mem.read(source + i));
}
mem.write(0xff46, 0);
}
}
|
pub mod oauth2;
pub mod client;
pub mod util;
pub mod senum;
pub mod model;
|
/// # RESP2
/// This module provides utilities to parse the RESP2 protocol.
use nom::branch::alt;
use nom::multi::many_m_n;
use nom::{bytes::streaming::tag, IResult};
use crate::utils::{parse_bytes_with_length, parse_integer_with_prefix, parse_str_with_prefix};
/// Resp2Type represents all possible response types from the RESP2 protocol.
#[derive(Debug, PartialEq)]
pub enum Resp2Type<'a> {
String(&'a str),
Error(&'a str),
Integer(usize),
BulkString(&'a [u8]),
Null,
Array(Vec<Resp2Type<'a>>),
}
fn parse_simple_string(input: &[u8]) -> IResult<&[u8], Resp2Type> {
let (input, string) = parse_str_with_prefix(input, '+')?;
Ok((input, Resp2Type::String(string)))
}
fn parse_error(input: &[u8]) -> IResult<&[u8], Resp2Type> {
let (input, string) = parse_str_with_prefix(input, '-')?;
Ok((input, Resp2Type::Error(string)))
}
fn parse_integer(input: &[u8]) -> IResult<&[u8], Resp2Type> {
let (input, int) = parse_integer_with_prefix(input, ':')?;
Ok((input, Resp2Type::Integer(int)))
}
fn parse_bulk_string(input: &[u8]) -> IResult<&[u8], Resp2Type> {
let (input, length) = parse_integer_with_prefix(input, '$')?;
let (input, bytes) = parse_bytes_with_length(input, length)?;
Ok((input, Resp2Type::BulkString(bytes)))
}
fn parse_null_string(input: &[u8]) -> IResult<&[u8], Resp2Type> {
let (input, _) = tag("$-1\r\n")(input)?;
Ok((input, Resp2Type::Null))
}
fn parse_array(input: &[u8]) -> IResult<&[u8], Resp2Type> {
let (input, length) = parse_integer_with_prefix(input, '*')?;
let (input, result) = many_m_n(length, length, parse)(input)?;
Ok((input, Resp2Type::Array(result)))
}
/// Parse bytes into a `Resp2Type` enum
pub fn parse(input: &[u8]) -> IResult<&[u8], Resp2Type> {
alt((
parse_simple_string,
parse_error,
parse_integer,
parse_bulk_string,
parse_null_string,
parse_array,
))(input)
}
#[cfg(test)]
mod tests {
use crate::resp2::{parse, Resp2Type};
#[test]
fn test_parse_simple_string() {
assert_eq!(
parse(&b"+OK\r\n"[..]),
Ok((&b""[..], Resp2Type::String("OK")))
);
}
#[test]
fn test_parse_error() {
assert_eq!(
parse(&b"-Error message\r\n"[..]),
Ok((&b""[..], Resp2Type::Error("Error message")))
);
}
#[test]
fn test_parse_integer() {
assert_eq!(
parse(&b":100\r\n"[..]),
Ok((&b""[..], Resp2Type::Integer(100)))
);
}
#[test]
fn test_parse_bulk_string() {
assert_eq!(
parse(&b"$10\r\n1234567890\r\n"[..]),
Ok((&b""[..], Resp2Type::BulkString(&b"1234567890"[..])))
);
}
#[test]
fn test_parse_null_string() {
assert_eq!(parse(&b"$-1\r\n"[..]), Ok((&b""[..], Resp2Type::Null)));
}
#[test]
fn test_parse_array_empty() {
assert_eq!(
parse(&b"*0\r\n"[..]),
Ok((&b""[..], Resp2Type::Array(vec![])))
);
}
#[test]
fn test_parse_array_mixed_objecs() {
assert_eq!(
parse(&b"*3\r\n:1\r\n:2\r\n$3\r\nfoo\r\n"[..]),
Ok((
&b""[..],
Resp2Type::Array(vec![
Resp2Type::Integer(1),
Resp2Type::Integer(2),
Resp2Type::BulkString(&b"foo"[..])
])
))
);
}
}
|
// Copyright (C) 2021 Subspace Labs, Inc.
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Runtime primitives for Subspace Network.
#![cfg_attr(not(feature = "std"), no_std)]
use sp_runtime::traits::{IdentifyAccount, Verify};
use sp_runtime::MultiSignature;
use sp_std::vec::Vec;
pub use subspace_core_primitives::BlockNumber;
/// Minimum desired number of replicas of the blockchain to be stored by the network,
/// impacts storage fees.
// TODO: Proper value here
pub const MIN_REPLICATION_FACTOR: u16 = 1;
/// How much (ratio) of storage fees escrow should be given to farmer each block as a reward.
// TODO: Proper value here
pub const STORAGE_FEES_ESCROW_BLOCK_REWARD: (u64, u64) = (1, 10000);
/// How much (ratio) of storage fees collected in a block should be put into storage fees escrow
/// (with remaining issued to farmer immediately).
// TODO: Proper value here
pub const STORAGE_FEES_ESCROW_BLOCK_TAX: (u64, u64) = (1, 10);
/// The smallest unit of the token is called Shannon.
pub const SHANNON: Balance = 1;
/// Subspace Credits have 18 decimal places.
pub const DECIMAL_PLACES: u8 = 18;
/// One Subspace Credit.
pub const SSC: Balance = (10 * SHANNON).pow(DECIMAL_PLACES as u32);
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Balance of an account.
pub type Balance = u128;
/// Index of a transaction in the chain.
pub type Index = u32;
/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;
/// Type used for expressing timestamp.
pub type Moment = u64;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
use super::BlockNumber;
use sp_runtime::generic;
use sp_runtime::traits::BlakeTwo256;
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
/// Opaque block header type.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Opaque block type.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
}
/// A trait for finding the address for a block reward based on the `PreRuntime` digests contained within it.
pub trait FindBlockRewardAddress<RewardAddress> {
/// Find the address for a block rewards based on the pre-runtime digests.
fn find_block_reward_address() -> Option<RewardAddress>;
}
/// A trait for finding the addresses for voting reward based on transactions found in the block.
pub trait FindVotingRewardAddresses<RewardAddress> {
/// Find the addresses for voting rewards based on transactions found in the block.
fn find_voting_reward_addresses() -> Vec<RewardAddress>;
}
|
#[doc = "Register `CFGR` reader"]
pub type R = crate::R<CFGR_SPEC>;
#[doc = "Register `CFGR` writer"]
pub type W = crate::W<CFGR_SPEC>;
#[doc = "Field `SW` reader - System clock Switch"]
pub type SW_R = crate::FieldReader<SW_A>;
#[doc = "System clock Switch\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SW_A {
#[doc = "0: HSI selected as system clock"]
Hsi = 0,
#[doc = "1: HSE selected as system clock"]
Hse = 1,
#[doc = "2: PLL selected as system clock"]
Pll = 2,
}
impl From<SW_A> for u8 {
#[inline(always)]
fn from(variant: SW_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for SW_A {
type Ux = u8;
}
impl SW_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SW_A> {
match self.bits {
0 => Some(SW_A::Hsi),
1 => Some(SW_A::Hse),
2 => Some(SW_A::Pll),
_ => None,
}
}
#[doc = "HSI selected as system clock"]
#[inline(always)]
pub fn is_hsi(&self) -> bool {
*self == SW_A::Hsi
}
#[doc = "HSE selected as system clock"]
#[inline(always)]
pub fn is_hse(&self) -> bool {
*self == SW_A::Hse
}
#[doc = "PLL selected as system clock"]
#[inline(always)]
pub fn is_pll(&self) -> bool {
*self == SW_A::Pll
}
}
#[doc = "Field `SW` writer - System clock Switch"]
pub type SW_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, SW_A>;
impl<'a, REG, const O: u8> SW_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "HSI selected as system clock"]
#[inline(always)]
pub fn hsi(self) -> &'a mut crate::W<REG> {
self.variant(SW_A::Hsi)
}
#[doc = "HSE selected as system clock"]
#[inline(always)]
pub fn hse(self) -> &'a mut crate::W<REG> {
self.variant(SW_A::Hse)
}
#[doc = "PLL selected as system clock"]
#[inline(always)]
pub fn pll(self) -> &'a mut crate::W<REG> {
self.variant(SW_A::Pll)
}
}
#[doc = "Field `SWS` reader - System Clock Switch Status"]
pub type SWS_R = crate::FieldReader<SWSR_A>;
#[doc = "System Clock Switch Status\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SWSR_A {
#[doc = "0: HSI oscillator used as system clock"]
Hsi = 0,
#[doc = "1: HSE oscillator used as system clock"]
Hse = 1,
#[doc = "2: PLL used as system clock"]
Pll = 2,
}
impl From<SWSR_A> for u8 {
#[inline(always)]
fn from(variant: SWSR_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for SWSR_A {
type Ux = u8;
}
impl SWS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SWSR_A> {
match self.bits {
0 => Some(SWSR_A::Hsi),
1 => Some(SWSR_A::Hse),
2 => Some(SWSR_A::Pll),
_ => None,
}
}
#[doc = "HSI oscillator used as system clock"]
#[inline(always)]
pub fn is_hsi(&self) -> bool {
*self == SWSR_A::Hsi
}
#[doc = "HSE oscillator used as system clock"]
#[inline(always)]
pub fn is_hse(&self) -> bool {
*self == SWSR_A::Hse
}
#[doc = "PLL used as system clock"]
#[inline(always)]
pub fn is_pll(&self) -> bool {
*self == SWSR_A::Pll
}
}
#[doc = "Field `HPRE` reader - AHB prescaler"]
pub type HPRE_R = crate::FieldReader<HPRE_A>;
#[doc = "AHB prescaler\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum HPRE_A {
#[doc = "0: SYSCLK not divided"]
Div1 = 0,
#[doc = "8: SYSCLK divided by 2"]
Div2 = 8,
#[doc = "9: SYSCLK divided by 4"]
Div4 = 9,
#[doc = "10: SYSCLK divided by 8"]
Div8 = 10,
#[doc = "11: SYSCLK divided by 16"]
Div16 = 11,
#[doc = "12: SYSCLK divided by 64"]
Div64 = 12,
#[doc = "13: SYSCLK divided by 128"]
Div128 = 13,
#[doc = "14: SYSCLK divided by 256"]
Div256 = 14,
#[doc = "15: SYSCLK divided by 512"]
Div512 = 15,
}
impl From<HPRE_A> for u8 {
#[inline(always)]
fn from(variant: HPRE_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for HPRE_A {
type Ux = u8;
}
impl HPRE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<HPRE_A> {
match self.bits {
0 => Some(HPRE_A::Div1),
8 => Some(HPRE_A::Div2),
9 => Some(HPRE_A::Div4),
10 => Some(HPRE_A::Div8),
11 => Some(HPRE_A::Div16),
12 => Some(HPRE_A::Div64),
13 => Some(HPRE_A::Div128),
14 => Some(HPRE_A::Div256),
15 => Some(HPRE_A::Div512),
_ => None,
}
}
#[doc = "SYSCLK not divided"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == HPRE_A::Div1
}
#[doc = "SYSCLK divided by 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == HPRE_A::Div2
}
#[doc = "SYSCLK divided by 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == HPRE_A::Div4
}
#[doc = "SYSCLK divided by 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == HPRE_A::Div8
}
#[doc = "SYSCLK divided by 16"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == HPRE_A::Div16
}
#[doc = "SYSCLK divided by 64"]
#[inline(always)]
pub fn is_div64(&self) -> bool {
*self == HPRE_A::Div64
}
#[doc = "SYSCLK divided by 128"]
#[inline(always)]
pub fn is_div128(&self) -> bool {
*self == HPRE_A::Div128
}
#[doc = "SYSCLK divided by 256"]
#[inline(always)]
pub fn is_div256(&self) -> bool {
*self == HPRE_A::Div256
}
#[doc = "SYSCLK divided by 512"]
#[inline(always)]
pub fn is_div512(&self) -> bool {
*self == HPRE_A::Div512
}
}
#[doc = "Field `HPRE` writer - AHB prescaler"]
pub type HPRE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, HPRE_A>;
impl<'a, REG, const O: u8> HPRE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "SYSCLK not divided"]
#[inline(always)]
pub fn div1(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div1)
}
#[doc = "SYSCLK divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div2)
}
#[doc = "SYSCLK divided by 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div4)
}
#[doc = "SYSCLK divided by 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div8)
}
#[doc = "SYSCLK divided by 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div16)
}
#[doc = "SYSCLK divided by 64"]
#[inline(always)]
pub fn div64(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div64)
}
#[doc = "SYSCLK divided by 128"]
#[inline(always)]
pub fn div128(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div128)
}
#[doc = "SYSCLK divided by 256"]
#[inline(always)]
pub fn div256(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div256)
}
#[doc = "SYSCLK divided by 512"]
#[inline(always)]
pub fn div512(self) -> &'a mut crate::W<REG> {
self.variant(HPRE_A::Div512)
}
}
#[doc = "Field `PPRE1` reader - APB Low speed prescaler (APB1)"]
pub type PPRE1_R = crate::FieldReader<PPRE1_A>;
#[doc = "APB Low speed prescaler (APB1)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PPRE1_A {
#[doc = "0: HCLK not divided"]
Div1 = 0,
#[doc = "4: HCLK divided by 2"]
Div2 = 4,
#[doc = "5: HCLK divided by 4"]
Div4 = 5,
#[doc = "6: HCLK divided by 8"]
Div8 = 6,
#[doc = "7: HCLK divided by 16"]
Div16 = 7,
}
impl From<PPRE1_A> for u8 {
#[inline(always)]
fn from(variant: PPRE1_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for PPRE1_A {
type Ux = u8;
}
impl PPRE1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<PPRE1_A> {
match self.bits {
0 => Some(PPRE1_A::Div1),
4 => Some(PPRE1_A::Div2),
5 => Some(PPRE1_A::Div4),
6 => Some(PPRE1_A::Div8),
7 => Some(PPRE1_A::Div16),
_ => None,
}
}
#[doc = "HCLK not divided"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == PPRE1_A::Div1
}
#[doc = "HCLK divided by 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == PPRE1_A::Div2
}
#[doc = "HCLK divided by 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == PPRE1_A::Div4
}
#[doc = "HCLK divided by 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == PPRE1_A::Div8
}
#[doc = "HCLK divided by 16"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == PPRE1_A::Div16
}
}
#[doc = "Field `PPRE1` writer - APB Low speed prescaler (APB1)"]
pub type PPRE1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O, PPRE1_A>;
impl<'a, REG, const O: u8> PPRE1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "HCLK not divided"]
#[inline(always)]
pub fn div1(self) -> &'a mut crate::W<REG> {
self.variant(PPRE1_A::Div1)
}
#[doc = "HCLK divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(PPRE1_A::Div2)
}
#[doc = "HCLK divided by 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(PPRE1_A::Div4)
}
#[doc = "HCLK divided by 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(PPRE1_A::Div8)
}
#[doc = "HCLK divided by 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut crate::W<REG> {
self.variant(PPRE1_A::Div16)
}
}
#[doc = "Field `PPRE2` reader - APB high speed prescaler (APB2)"]
pub use PPRE1_R as PPRE2_R;
#[doc = "Field `PPRE2` writer - APB high speed prescaler (APB2)"]
pub use PPRE1_W as PPRE2_W;
#[doc = "Field `ADCPRE` reader - ADC prescaler"]
pub type ADCPRE_R = crate::FieldReader<ADCPRE_A>;
#[doc = "ADC prescaler\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum ADCPRE_A {
#[doc = "0: PCLK divided by 2"]
Div2 = 0,
#[doc = "1: PCLK divided by 4"]
Div4 = 1,
#[doc = "2: PCLK divided by 6"]
Div6 = 2,
#[doc = "3: PCLK divided by 8"]
Div8 = 3,
}
impl From<ADCPRE_A> for u8 {
#[inline(always)]
fn from(variant: ADCPRE_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for ADCPRE_A {
type Ux = u8;
}
impl ADCPRE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ADCPRE_A {
match self.bits {
0 => ADCPRE_A::Div2,
1 => ADCPRE_A::Div4,
2 => ADCPRE_A::Div6,
3 => ADCPRE_A::Div8,
_ => unreachable!(),
}
}
#[doc = "PCLK divided by 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == ADCPRE_A::Div2
}
#[doc = "PCLK divided by 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == ADCPRE_A::Div4
}
#[doc = "PCLK divided by 6"]
#[inline(always)]
pub fn is_div6(&self) -> bool {
*self == ADCPRE_A::Div6
}
#[doc = "PCLK divided by 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == ADCPRE_A::Div8
}
}
#[doc = "Field `ADCPRE` writer - ADC prescaler"]
pub type ADCPRE_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, ADCPRE_A>;
impl<'a, REG, const O: u8> ADCPRE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PCLK divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(ADCPRE_A::Div2)
}
#[doc = "PCLK divided by 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(ADCPRE_A::Div4)
}
#[doc = "PCLK divided by 6"]
#[inline(always)]
pub fn div6(self) -> &'a mut crate::W<REG> {
self.variant(ADCPRE_A::Div6)
}
#[doc = "PCLK divided by 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(ADCPRE_A::Div8)
}
}
#[doc = "Field `PLLSRC` reader - PLL entry clock source"]
pub type PLLSRC_R = crate::BitReader<PLLSRC_A>;
#[doc = "PLL entry clock source\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PLLSRC_A {
#[doc = "0: HSI divided by 2 selected as PLL input clock"]
HsiDiv2 = 0,
#[doc = "1: HSE divided by PREDIV selected as PLL input clock"]
HseDivPrediv = 1,
}
impl From<PLLSRC_A> for bool {
#[inline(always)]
fn from(variant: PLLSRC_A) -> Self {
variant as u8 != 0
}
}
impl PLLSRC_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLSRC_A {
match self.bits {
false => PLLSRC_A::HsiDiv2,
true => PLLSRC_A::HseDivPrediv,
}
}
#[doc = "HSI divided by 2 selected as PLL input clock"]
#[inline(always)]
pub fn is_hsi_div2(&self) -> bool {
*self == PLLSRC_A::HsiDiv2
}
#[doc = "HSE divided by PREDIV selected as PLL input clock"]
#[inline(always)]
pub fn is_hse_div_prediv(&self) -> bool {
*self == PLLSRC_A::HseDivPrediv
}
}
#[doc = "Field `PLLSRC` writer - PLL entry clock source"]
pub type PLLSRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PLLSRC_A>;
impl<'a, REG, const O: u8> PLLSRC_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "HSI divided by 2 selected as PLL input clock"]
#[inline(always)]
pub fn hsi_div2(self) -> &'a mut crate::W<REG> {
self.variant(PLLSRC_A::HsiDiv2)
}
#[doc = "HSE divided by PREDIV selected as PLL input clock"]
#[inline(always)]
pub fn hse_div_prediv(self) -> &'a mut crate::W<REG> {
self.variant(PLLSRC_A::HseDivPrediv)
}
}
#[doc = "Field `PLLXTPRE` reader - HSE divider for PLL entry"]
pub type PLLXTPRE_R = crate::BitReader<PLLXTPRE_A>;
#[doc = "HSE divider for PLL entry\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PLLXTPRE_A {
#[doc = "0: HSE clock not divided"]
Div1 = 0,
#[doc = "1: HSE clock divided by 2"]
Div2 = 1,
}
impl From<PLLXTPRE_A> for bool {
#[inline(always)]
fn from(variant: PLLXTPRE_A) -> Self {
variant as u8 != 0
}
}
impl PLLXTPRE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLXTPRE_A {
match self.bits {
false => PLLXTPRE_A::Div1,
true => PLLXTPRE_A::Div2,
}
}
#[doc = "HSE clock not divided"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == PLLXTPRE_A::Div1
}
#[doc = "HSE clock divided by 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == PLLXTPRE_A::Div2
}
}
#[doc = "Field `PLLXTPRE` writer - HSE divider for PLL entry"]
pub type PLLXTPRE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PLLXTPRE_A>;
impl<'a, REG, const O: u8> PLLXTPRE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "HSE clock not divided"]
#[inline(always)]
pub fn div1(self) -> &'a mut crate::W<REG> {
self.variant(PLLXTPRE_A::Div1)
}
#[doc = "HSE clock divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(PLLXTPRE_A::Div2)
}
}
#[doc = "Field `PLLMUL` reader - PLL Multiplication Factor"]
pub type PLLMUL_R = crate::FieldReader<PLLMUL_A>;
#[doc = "PLL Multiplication Factor\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PLLMUL_A {
#[doc = "0: PLL input clock x2"]
Mul2 = 0,
#[doc = "1: PLL input clock x3"]
Mul3 = 1,
#[doc = "2: PLL input clock x4"]
Mul4 = 2,
#[doc = "3: PLL input clock x5"]
Mul5 = 3,
#[doc = "4: PLL input clock x6"]
Mul6 = 4,
#[doc = "5: PLL input clock x7"]
Mul7 = 5,
#[doc = "6: PLL input clock x8"]
Mul8 = 6,
#[doc = "7: PLL input clock x9"]
Mul9 = 7,
#[doc = "8: PLL input clock x10"]
Mul10 = 8,
#[doc = "9: PLL input clock x11"]
Mul11 = 9,
#[doc = "10: PLL input clock x12"]
Mul12 = 10,
#[doc = "11: PLL input clock x13"]
Mul13 = 11,
#[doc = "12: PLL input clock x14"]
Mul14 = 12,
#[doc = "13: PLL input clock x15"]
Mul15 = 13,
#[doc = "14: PLL input clock x16"]
Mul16 = 14,
#[doc = "15: PLL input clock x16"]
Mul16x = 15,
}
impl From<PLLMUL_A> for u8 {
#[inline(always)]
fn from(variant: PLLMUL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for PLLMUL_A {
type Ux = u8;
}
impl PLLMUL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PLLMUL_A {
match self.bits {
0 => PLLMUL_A::Mul2,
1 => PLLMUL_A::Mul3,
2 => PLLMUL_A::Mul4,
3 => PLLMUL_A::Mul5,
4 => PLLMUL_A::Mul6,
5 => PLLMUL_A::Mul7,
6 => PLLMUL_A::Mul8,
7 => PLLMUL_A::Mul9,
8 => PLLMUL_A::Mul10,
9 => PLLMUL_A::Mul11,
10 => PLLMUL_A::Mul12,
11 => PLLMUL_A::Mul13,
12 => PLLMUL_A::Mul14,
13 => PLLMUL_A::Mul15,
14 => PLLMUL_A::Mul16,
15 => PLLMUL_A::Mul16x,
_ => unreachable!(),
}
}
#[doc = "PLL input clock x2"]
#[inline(always)]
pub fn is_mul2(&self) -> bool {
*self == PLLMUL_A::Mul2
}
#[doc = "PLL input clock x3"]
#[inline(always)]
pub fn is_mul3(&self) -> bool {
*self == PLLMUL_A::Mul3
}
#[doc = "PLL input clock x4"]
#[inline(always)]
pub fn is_mul4(&self) -> bool {
*self == PLLMUL_A::Mul4
}
#[doc = "PLL input clock x5"]
#[inline(always)]
pub fn is_mul5(&self) -> bool {
*self == PLLMUL_A::Mul5
}
#[doc = "PLL input clock x6"]
#[inline(always)]
pub fn is_mul6(&self) -> bool {
*self == PLLMUL_A::Mul6
}
#[doc = "PLL input clock x7"]
#[inline(always)]
pub fn is_mul7(&self) -> bool {
*self == PLLMUL_A::Mul7
}
#[doc = "PLL input clock x8"]
#[inline(always)]
pub fn is_mul8(&self) -> bool {
*self == PLLMUL_A::Mul8
}
#[doc = "PLL input clock x9"]
#[inline(always)]
pub fn is_mul9(&self) -> bool {
*self == PLLMUL_A::Mul9
}
#[doc = "PLL input clock x10"]
#[inline(always)]
pub fn is_mul10(&self) -> bool {
*self == PLLMUL_A::Mul10
}
#[doc = "PLL input clock x11"]
#[inline(always)]
pub fn is_mul11(&self) -> bool {
*self == PLLMUL_A::Mul11
}
#[doc = "PLL input clock x12"]
#[inline(always)]
pub fn is_mul12(&self) -> bool {
*self == PLLMUL_A::Mul12
}
#[doc = "PLL input clock x13"]
#[inline(always)]
pub fn is_mul13(&self) -> bool {
*self == PLLMUL_A::Mul13
}
#[doc = "PLL input clock x14"]
#[inline(always)]
pub fn is_mul14(&self) -> bool {
*self == PLLMUL_A::Mul14
}
#[doc = "PLL input clock x15"]
#[inline(always)]
pub fn is_mul15(&self) -> bool {
*self == PLLMUL_A::Mul15
}
#[doc = "PLL input clock x16"]
#[inline(always)]
pub fn is_mul16(&self) -> bool {
*self == PLLMUL_A::Mul16
}
#[doc = "PLL input clock x16"]
#[inline(always)]
pub fn is_mul16x(&self) -> bool {
*self == PLLMUL_A::Mul16x
}
}
#[doc = "Field `PLLMUL` writer - PLL Multiplication Factor"]
pub type PLLMUL_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O, PLLMUL_A>;
impl<'a, REG, const O: u8> PLLMUL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PLL input clock x2"]
#[inline(always)]
pub fn mul2(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul2)
}
#[doc = "PLL input clock x3"]
#[inline(always)]
pub fn mul3(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul3)
}
#[doc = "PLL input clock x4"]
#[inline(always)]
pub fn mul4(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul4)
}
#[doc = "PLL input clock x5"]
#[inline(always)]
pub fn mul5(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul5)
}
#[doc = "PLL input clock x6"]
#[inline(always)]
pub fn mul6(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul6)
}
#[doc = "PLL input clock x7"]
#[inline(always)]
pub fn mul7(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul7)
}
#[doc = "PLL input clock x8"]
#[inline(always)]
pub fn mul8(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul8)
}
#[doc = "PLL input clock x9"]
#[inline(always)]
pub fn mul9(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul9)
}
#[doc = "PLL input clock x10"]
#[inline(always)]
pub fn mul10(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul10)
}
#[doc = "PLL input clock x11"]
#[inline(always)]
pub fn mul11(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul11)
}
#[doc = "PLL input clock x12"]
#[inline(always)]
pub fn mul12(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul12)
}
#[doc = "PLL input clock x13"]
#[inline(always)]
pub fn mul13(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul13)
}
#[doc = "PLL input clock x14"]
#[inline(always)]
pub fn mul14(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul14)
}
#[doc = "PLL input clock x15"]
#[inline(always)]
pub fn mul15(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul15)
}
#[doc = "PLL input clock x16"]
#[inline(always)]
pub fn mul16(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul16)
}
#[doc = "PLL input clock x16"]
#[inline(always)]
pub fn mul16x(self) -> &'a mut crate::W<REG> {
self.variant(PLLMUL_A::Mul16x)
}
}
#[doc = "Field `USBPRE` reader - USB prescaler"]
pub type USBPRE_R = crate::BitReader<USBPRE_A>;
#[doc = "USB prescaler\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum USBPRE_A {
#[doc = "0: PLL clock is divided by 1.5"]
Div15 = 0,
#[doc = "1: PLL clock is not divided"]
Div1 = 1,
}
impl From<USBPRE_A> for bool {
#[inline(always)]
fn from(variant: USBPRE_A) -> Self {
variant as u8 != 0
}
}
impl USBPRE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> USBPRE_A {
match self.bits {
false => USBPRE_A::Div15,
true => USBPRE_A::Div1,
}
}
#[doc = "PLL clock is divided by 1.5"]
#[inline(always)]
pub fn is_div1_5(&self) -> bool {
*self == USBPRE_A::Div15
}
#[doc = "PLL clock is not divided"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == USBPRE_A::Div1
}
}
#[doc = "Field `USBPRE` writer - USB prescaler"]
pub type USBPRE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, USBPRE_A>;
impl<'a, REG, const O: u8> USBPRE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "PLL clock is divided by 1.5"]
#[inline(always)]
pub fn div1_5(self) -> &'a mut crate::W<REG> {
self.variant(USBPRE_A::Div15)
}
#[doc = "PLL clock is not divided"]
#[inline(always)]
pub fn div1(self) -> &'a mut crate::W<REG> {
self.variant(USBPRE_A::Div1)
}
}
#[doc = "Field `MCO` reader - Microcontroller clock output"]
pub type MCO_R = crate::FieldReader<MCO_A>;
#[doc = "Microcontroller clock output\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum MCO_A {
#[doc = "0: MCO output disabled, no clock on MCO"]
NoMco = 0,
#[doc = "2: Internal low speed (LSI) oscillator clock selected"]
Lsi = 2,
#[doc = "3: External low speed (LSE) oscillator clock selected"]
Lse = 3,
#[doc = "4: System clock selected"]
Sysclk = 4,
#[doc = "5: Internal RC 8 MHz (HSI) oscillator clock selected"]
Hsi = 5,
#[doc = "6: External 4-32 MHz (HSE) oscillator clock selected"]
Hse = 6,
#[doc = "7: PLL clock selected (divided by 1 or 2, depending en PLLNODIV)"]
Pll = 7,
}
impl From<MCO_A> for u8 {
#[inline(always)]
fn from(variant: MCO_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for MCO_A {
type Ux = u8;
}
impl MCO_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<MCO_A> {
match self.bits {
0 => Some(MCO_A::NoMco),
2 => Some(MCO_A::Lsi),
3 => Some(MCO_A::Lse),
4 => Some(MCO_A::Sysclk),
5 => Some(MCO_A::Hsi),
6 => Some(MCO_A::Hse),
7 => Some(MCO_A::Pll),
_ => None,
}
}
#[doc = "MCO output disabled, no clock on MCO"]
#[inline(always)]
pub fn is_no_mco(&self) -> bool {
*self == MCO_A::NoMco
}
#[doc = "Internal low speed (LSI) oscillator clock selected"]
#[inline(always)]
pub fn is_lsi(&self) -> bool {
*self == MCO_A::Lsi
}
#[doc = "External low speed (LSE) oscillator clock selected"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == MCO_A::Lse
}
#[doc = "System clock selected"]
#[inline(always)]
pub fn is_sysclk(&self) -> bool {
*self == MCO_A::Sysclk
}
#[doc = "Internal RC 8 MHz (HSI) oscillator clock selected"]
#[inline(always)]
pub fn is_hsi(&self) -> bool {
*self == MCO_A::Hsi
}
#[doc = "External 4-32 MHz (HSE) oscillator clock selected"]
#[inline(always)]
pub fn is_hse(&self) -> bool {
*self == MCO_A::Hse
}
#[doc = "PLL clock selected (divided by 1 or 2, depending en PLLNODIV)"]
#[inline(always)]
pub fn is_pll(&self) -> bool {
*self == MCO_A::Pll
}
}
#[doc = "Field `MCO` writer - Microcontroller clock output"]
pub type MCO_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O, MCO_A>;
impl<'a, REG, const O: u8> MCO_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "MCO output disabled, no clock on MCO"]
#[inline(always)]
pub fn no_mco(self) -> &'a mut crate::W<REG> {
self.variant(MCO_A::NoMco)
}
#[doc = "Internal low speed (LSI) oscillator clock selected"]
#[inline(always)]
pub fn lsi(self) -> &'a mut crate::W<REG> {
self.variant(MCO_A::Lsi)
}
#[doc = "External low speed (LSE) oscillator clock selected"]
#[inline(always)]
pub fn lse(self) -> &'a mut crate::W<REG> {
self.variant(MCO_A::Lse)
}
#[doc = "System clock selected"]
#[inline(always)]
pub fn sysclk(self) -> &'a mut crate::W<REG> {
self.variant(MCO_A::Sysclk)
}
#[doc = "Internal RC 8 MHz (HSI) oscillator clock selected"]
#[inline(always)]
pub fn hsi(self) -> &'a mut crate::W<REG> {
self.variant(MCO_A::Hsi)
}
#[doc = "External 4-32 MHz (HSE) oscillator clock selected"]
#[inline(always)]
pub fn hse(self) -> &'a mut crate::W<REG> {
self.variant(MCO_A::Hse)
}
#[doc = "PLL clock selected (divided by 1 or 2, depending en PLLNODIV)"]
#[inline(always)]
pub fn pll(self) -> &'a mut crate::W<REG> {
self.variant(MCO_A::Pll)
}
}
#[doc = "Field `SDPRE` reader - SDADC prescaler"]
pub type SDPRE_R = crate::FieldReader<SDPRE_A>;
#[doc = "SDADC prescaler\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SDPRE_A {
#[doc = "0: SYSCLK divided by 2"]
Div2 = 0,
#[doc = "17: SYSCLK divided by 4"]
Div4 = 17,
#[doc = "18: SYSCLK divided by 6"]
Div6 = 18,
#[doc = "19: SYSCLK divided by 8"]
Div8 = 19,
#[doc = "20: SYSCLK divided by 10"]
Div10 = 20,
#[doc = "21: SYSCLK divided by 12"]
Div12 = 21,
#[doc = "22: SYSCLK divided by 14"]
Div14 = 22,
#[doc = "23: SYSCLK divided by 16"]
Div16 = 23,
#[doc = "24: SYSCLK divided by 20"]
Div20 = 24,
#[doc = "25: SYSCLK divided by 24"]
Div24 = 25,
#[doc = "26: SYSCLK divided by 28"]
Div28 = 26,
#[doc = "27: SYSCLK divided by 32"]
Div32 = 27,
#[doc = "28: SYSCLK divided by 36"]
Div36 = 28,
#[doc = "29: SYSCLK divided by 40"]
Div40 = 29,
#[doc = "30: SYSCLK divided by 44"]
Div44 = 30,
#[doc = "31: SYSCLK divided by 48"]
Div48 = 31,
}
impl From<SDPRE_A> for u8 {
#[inline(always)]
fn from(variant: SDPRE_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for SDPRE_A {
type Ux = u8;
}
impl SDPRE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SDPRE_A> {
match self.bits {
0 => Some(SDPRE_A::Div2),
17 => Some(SDPRE_A::Div4),
18 => Some(SDPRE_A::Div6),
19 => Some(SDPRE_A::Div8),
20 => Some(SDPRE_A::Div10),
21 => Some(SDPRE_A::Div12),
22 => Some(SDPRE_A::Div14),
23 => Some(SDPRE_A::Div16),
24 => Some(SDPRE_A::Div20),
25 => Some(SDPRE_A::Div24),
26 => Some(SDPRE_A::Div28),
27 => Some(SDPRE_A::Div32),
28 => Some(SDPRE_A::Div36),
29 => Some(SDPRE_A::Div40),
30 => Some(SDPRE_A::Div44),
31 => Some(SDPRE_A::Div48),
_ => None,
}
}
#[doc = "SYSCLK divided by 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == SDPRE_A::Div2
}
#[doc = "SYSCLK divided by 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == SDPRE_A::Div4
}
#[doc = "SYSCLK divided by 6"]
#[inline(always)]
pub fn is_div6(&self) -> bool {
*self == SDPRE_A::Div6
}
#[doc = "SYSCLK divided by 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == SDPRE_A::Div8
}
#[doc = "SYSCLK divided by 10"]
#[inline(always)]
pub fn is_div10(&self) -> bool {
*self == SDPRE_A::Div10
}
#[doc = "SYSCLK divided by 12"]
#[inline(always)]
pub fn is_div12(&self) -> bool {
*self == SDPRE_A::Div12
}
#[doc = "SYSCLK divided by 14"]
#[inline(always)]
pub fn is_div14(&self) -> bool {
*self == SDPRE_A::Div14
}
#[doc = "SYSCLK divided by 16"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == SDPRE_A::Div16
}
#[doc = "SYSCLK divided by 20"]
#[inline(always)]
pub fn is_div20(&self) -> bool {
*self == SDPRE_A::Div20
}
#[doc = "SYSCLK divided by 24"]
#[inline(always)]
pub fn is_div24(&self) -> bool {
*self == SDPRE_A::Div24
}
#[doc = "SYSCLK divided by 28"]
#[inline(always)]
pub fn is_div28(&self) -> bool {
*self == SDPRE_A::Div28
}
#[doc = "SYSCLK divided by 32"]
#[inline(always)]
pub fn is_div32(&self) -> bool {
*self == SDPRE_A::Div32
}
#[doc = "SYSCLK divided by 36"]
#[inline(always)]
pub fn is_div36(&self) -> bool {
*self == SDPRE_A::Div36
}
#[doc = "SYSCLK divided by 40"]
#[inline(always)]
pub fn is_div40(&self) -> bool {
*self == SDPRE_A::Div40
}
#[doc = "SYSCLK divided by 44"]
#[inline(always)]
pub fn is_div44(&self) -> bool {
*self == SDPRE_A::Div44
}
#[doc = "SYSCLK divided by 48"]
#[inline(always)]
pub fn is_div48(&self) -> bool {
*self == SDPRE_A::Div48
}
}
#[doc = "Field `SDPRE` writer - SDADC prescaler"]
pub type SDPRE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O, SDPRE_A>;
impl<'a, REG, const O: u8> SDPRE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "SYSCLK divided by 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div2)
}
#[doc = "SYSCLK divided by 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div4)
}
#[doc = "SYSCLK divided by 6"]
#[inline(always)]
pub fn div6(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div6)
}
#[doc = "SYSCLK divided by 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div8)
}
#[doc = "SYSCLK divided by 10"]
#[inline(always)]
pub fn div10(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div10)
}
#[doc = "SYSCLK divided by 12"]
#[inline(always)]
pub fn div12(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div12)
}
#[doc = "SYSCLK divided by 14"]
#[inline(always)]
pub fn div14(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div14)
}
#[doc = "SYSCLK divided by 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div16)
}
#[doc = "SYSCLK divided by 20"]
#[inline(always)]
pub fn div20(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div20)
}
#[doc = "SYSCLK divided by 24"]
#[inline(always)]
pub fn div24(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div24)
}
#[doc = "SYSCLK divided by 28"]
#[inline(always)]
pub fn div28(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div28)
}
#[doc = "SYSCLK divided by 32"]
#[inline(always)]
pub fn div32(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div32)
}
#[doc = "SYSCLK divided by 36"]
#[inline(always)]
pub fn div36(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div36)
}
#[doc = "SYSCLK divided by 40"]
#[inline(always)]
pub fn div40(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div40)
}
#[doc = "SYSCLK divided by 44"]
#[inline(always)]
pub fn div44(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div44)
}
#[doc = "SYSCLK divided by 48"]
#[inline(always)]
pub fn div48(self) -> &'a mut crate::W<REG> {
self.variant(SDPRE_A::Div48)
}
}
impl R {
#[doc = "Bits 0:1 - System clock Switch"]
#[inline(always)]
pub fn sw(&self) -> SW_R {
SW_R::new((self.bits & 3) as u8)
}
#[doc = "Bits 2:3 - System Clock Switch Status"]
#[inline(always)]
pub fn sws(&self) -> SWS_R {
SWS_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:7 - AHB prescaler"]
#[inline(always)]
pub fn hpre(&self) -> HPRE_R {
HPRE_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:10 - APB Low speed prescaler (APB1)"]
#[inline(always)]
pub fn ppre1(&self) -> PPRE1_R {
PPRE1_R::new(((self.bits >> 8) & 7) as u8)
}
#[doc = "Bits 11:13 - APB high speed prescaler (APB2)"]
#[inline(always)]
pub fn ppre2(&self) -> PPRE2_R {
PPRE2_R::new(((self.bits >> 11) & 7) as u8)
}
#[doc = "Bits 14:15 - ADC prescaler"]
#[inline(always)]
pub fn adcpre(&self) -> ADCPRE_R {
ADCPRE_R::new(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bit 16 - PLL entry clock source"]
#[inline(always)]
pub fn pllsrc(&self) -> PLLSRC_R {
PLLSRC_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - HSE divider for PLL entry"]
#[inline(always)]
pub fn pllxtpre(&self) -> PLLXTPRE_R {
PLLXTPRE_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bits 18:21 - PLL Multiplication Factor"]
#[inline(always)]
pub fn pllmul(&self) -> PLLMUL_R {
PLLMUL_R::new(((self.bits >> 18) & 0x0f) as u8)
}
#[doc = "Bit 22 - USB prescaler"]
#[inline(always)]
pub fn usbpre(&self) -> USBPRE_R {
USBPRE_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bits 24:26 - Microcontroller clock output"]
#[inline(always)]
pub fn mco(&self) -> MCO_R {
MCO_R::new(((self.bits >> 24) & 7) as u8)
}
#[doc = "Bits 27:31 - SDADC prescaler"]
#[inline(always)]
pub fn sdpre(&self) -> SDPRE_R {
SDPRE_R::new(((self.bits >> 27) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - System clock Switch"]
#[inline(always)]
#[must_use]
pub fn sw(&mut self) -> SW_W<CFGR_SPEC, 0> {
SW_W::new(self)
}
#[doc = "Bits 4:7 - AHB prescaler"]
#[inline(always)]
#[must_use]
pub fn hpre(&mut self) -> HPRE_W<CFGR_SPEC, 4> {
HPRE_W::new(self)
}
#[doc = "Bits 8:10 - APB Low speed prescaler (APB1)"]
#[inline(always)]
#[must_use]
pub fn ppre1(&mut self) -> PPRE1_W<CFGR_SPEC, 8> {
PPRE1_W::new(self)
}
#[doc = "Bits 11:13 - APB high speed prescaler (APB2)"]
#[inline(always)]
#[must_use]
pub fn ppre2(&mut self) -> PPRE2_W<CFGR_SPEC, 11> {
PPRE2_W::new(self)
}
#[doc = "Bits 14:15 - ADC prescaler"]
#[inline(always)]
#[must_use]
pub fn adcpre(&mut self) -> ADCPRE_W<CFGR_SPEC, 14> {
ADCPRE_W::new(self)
}
#[doc = "Bit 16 - PLL entry clock source"]
#[inline(always)]
#[must_use]
pub fn pllsrc(&mut self) -> PLLSRC_W<CFGR_SPEC, 16> {
PLLSRC_W::new(self)
}
#[doc = "Bit 17 - HSE divider for PLL entry"]
#[inline(always)]
#[must_use]
pub fn pllxtpre(&mut self) -> PLLXTPRE_W<CFGR_SPEC, 17> {
PLLXTPRE_W::new(self)
}
#[doc = "Bits 18:21 - PLL Multiplication Factor"]
#[inline(always)]
#[must_use]
pub fn pllmul(&mut self) -> PLLMUL_W<CFGR_SPEC, 18> {
PLLMUL_W::new(self)
}
#[doc = "Bit 22 - USB prescaler"]
#[inline(always)]
#[must_use]
pub fn usbpre(&mut self) -> USBPRE_W<CFGR_SPEC, 22> {
USBPRE_W::new(self)
}
#[doc = "Bits 24:26 - Microcontroller clock output"]
#[inline(always)]
#[must_use]
pub fn mco(&mut self) -> MCO_W<CFGR_SPEC, 24> {
MCO_W::new(self)
}
#[doc = "Bits 27:31 - SDADC prescaler"]
#[inline(always)]
#[must_use]
pub fn sdpre(&mut self) -> SDPRE_W<CFGR_SPEC, 27> {
SDPRE_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Clock configuration register (RCC_CFGR)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CFGR_SPEC;
impl crate::RegisterSpec for CFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cfgr::R`](R) reader structure"]
impl crate::Readable for CFGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cfgr::W`](W) writer structure"]
impl crate::Writable for CFGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CFGR to value 0"]
impl crate::Resettable for CFGR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub struct PrefixExpr {
pub ope: Operator,
pub right: Box<Expr>,
}
impl Display for PrefixExpr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "({}{})", self.ope, self.right.as_ref())
}
}
impl TryFrom<Expr> for PrefixExpr {
type Error = Error;
fn try_from(value: Expr) -> Result<Self> {
match value {
Expr::PrefixExpr(prefix_expr) => Ok(prefix_expr),
expr => Err(ParserError::Convert(format!("{:?}", expr), "PrefixExpr".into()).into()),
}
}
}
|
use byteorder::{LittleEndian, ByteOrder};
use scroll_derive::Pread;
#[derive(Debug, Pread)]
pub(crate) struct ArcHeader {
pub music_file_section_offset: u64,
pub file_section_offset: u64,
pub music_section_offset: u64,
pub node_section_offset: u64,
pub unk_section_offset: u64,
}
pub(crate) const ARC_HEADER_SIZE: usize = 0x28;
#[derive(Debug, Pread)]
pub(crate) struct CompressedNodeHeader {
pub data_start: u32,
pub decomp_size: u32,
pub comp_size: u32,
pub zstd_comp_size: u32,
}
pub(crate) const COMPRESSED_NODE_HEADER_SIZE: usize = 0x10;
#[derive(Debug, Pread)]
pub(crate) struct NodeHeader {
pub file_size: u32,
pub folder_count: u32,
pub file_count1: u32,
pub tree_count: u32,
pub sub_files1_count: u32,
pub file_lookup_count: u32,
pub hash_folder_count: u32,
pub file_information_count: u32,
pub file_count2: u32,
pub sub_files2_count: u32,
pub unk1: u32,
pub unk2: u32,
pub another_hash_table_size: u8,
pub unk3: u8,
pub unk4: u16,
pub movie_count: u32,
pub part1_count: u32,
pub part2_count: u32,
pub music_file_count: u32,
}
pub(crate) const NODE_HEADER_SIZE: usize = 0x44;
#[derive(Debug)]
pub(crate) struct EntryTriplet {
pub hash: u64, // 0x28 bits
pub meta: u32, // 0x18 bits
pub meta2: u32,
}
pub(crate) const ENTRY_TRIPLET_SIZE: usize = 0xc;
pub(crate) fn read_triplet(data: &[u8]) -> EntryTriplet {
let hash = LittleEndian::read_u64(&[data[0], data[1], data[2], data[3], data[4], 0, 0, 0]);
let meta = LittleEndian::read_u32(&[data[5], data[6], data[7], 0]);
let meta2 = LittleEndian::read_u32(&data[0x8..]);
EntryTriplet { hash, meta, meta2 }
}
#[derive(Debug)]
pub(crate) struct EntryPair {
pub hash: u64, // 0x28 bits
pub meta: u32, // 0x18 bits
}
pub(crate) const ENTRY_PAIR_SIZE: usize = 0x8;
pub(crate) fn read_pair(data: &[u8]) -> EntryPair {
let hash = LittleEndian::read_u64(&[data[0], data[1], data[2], data[3], data[4], 0, 0, 0]);
let meta = LittleEndian::read_u32(&[data[5], data[6], data[7], 0]);
EntryPair { hash, meta }
}
#[derive(Debug)]
pub(crate) struct BigHashEntry {
pub path: EntryPair,
pub folder: EntryPair,
pub parent: EntryPair,
pub hash4: EntryPair,
pub suboffset_start: u32,
pub num_files: u32,
pub unk3: u32,
pub unk4: u16,
pub unk5: u16,
pub unk6: u8,
pub unk7: u8,
pub unk8: u8,
pub unk9: u8,
}
pub(crate) const BIG_HASH_ENTRY_SIZE: usize = 0x34;
pub(crate) fn read_big_hash_entry(data: &[u8]) -> BigHashEntry {
BigHashEntry {
path: read_pair(&data[0x00..]),
folder: read_pair(&data[0x08..]),
parent: read_pair(&data[0x10..]),
hash4: read_pair(&data[0x18..]),
suboffset_start: LittleEndian::read_u32(&data[0x20..]),
num_files: LittleEndian::read_u32(&data[0x24..]),
unk3: LittleEndian::read_u32(&data[0x28..]),
unk4: LittleEndian::read_u16(&data[0x2c..]),
unk5: LittleEndian::read_u16(&data[0x2e..]),
unk6: data[0x30],
unk7: data[0x31],
unk8: data[0x32],
unk9: data[0x33],
}
}
#[derive(Debug)]
pub(crate) struct TreeEntry {
pub path: EntryPair,
pub ext: EntryPair,
pub folder: EntryPair,
pub file: EntryPair,
pub suboffset_index: u32,
pub flags: u32,
}
pub(crate) const TREE_ENTRY_SIZE: usize = 0x28;
pub(crate) fn read_tree_entry(data: &[u8]) -> TreeEntry {
TreeEntry {
path: read_pair(&data[0x00..]),
ext: read_pair(&data[0x08..]),
folder: read_pair(&data[0x10..]),
file: read_pair(&data[0x18..]),
suboffset_index: LittleEndian::read_u32(&data[0x20..]),
flags: LittleEndian::read_u32(&data[0x24..]),
}
}
const TREE_SUBOFFSET_MASK: u32 = 0b11;
impl TreeEntry {
pub fn redirect(&self) -> bool {
self.flags & 0x200000 != 0
}
pub fn suboffset_index(&self) -> bool {
self.flags & TREE_SUBOFFSET_MASK == 0
}
}
#[derive(Debug, Pread)]
pub(crate) struct FilePair {
pub size: u64,
pub offset: u64,
}
pub(crate) const FILE_PAIR_SIZE: usize = 0x10;
#[derive(Debug, Pread)]
pub(crate) struct BigFileEntry {
pub offset: u64,
pub decomp_size: u32,
pub comp_size: u32,
pub suboffset_index: u32,
pub files: u32,
pub unk3: u32,
}
pub(crate) const BIG_FILE_ENTRY_SIZE: usize = 0x1c;
#[derive(Debug, Pread)]
pub(crate) struct FileEntry {
pub offset: u32,
pub comp_size: u32,
pub decomp_size: u32,
pub flags: u32,
}
pub(crate) const FILE_ENTRY_SIZE: usize = 0x10;
impl FileEntry {
pub fn suboffset_redir(&self) -> bool {
unimplemented!()
}
pub fn suboffset_tree_index(&self) -> usize {
unimplemented!()
}
pub fn suboffset_decompressed(&self) -> bool {
self.flags & 0x07000000 == 0
}
pub fn suboffset_compressed_zstd(&self) -> bool {
self.flags & 0x07000000 == 0x03000000
}
}
#[derive(Debug, Pread)]
pub(crate) struct HashBucket {
pub index: u32,
pub num_entries: u32,
}
pub(crate) const HASH_BUCKET_SIZE: usize = 0x08;
|
#[macro_export]
macro_rules! leak {
($name:expr) => {
Box::into_raw(Box::new($name)) as *mut c_void
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control"]
pub ctl: CTL,
_reserved1: [u8; 12usize],
#[doc = "0x10 - Clock control"]
pub clock_ctl: CLOCK_CTL,
#[doc = "0x14 - Mode control"]
pub mode_ctl: MODE_CTL,
#[doc = "0x18 - Data control"]
pub data_ctl: DATA_CTL,
_reserved4: [u8; 4usize],
#[doc = "0x20 - Command"]
pub cmd: CMD,
_reserved5: [u8; 28usize],
#[doc = "0x40 - Trigger control"]
pub tr_ctl: TR_CTL,
_reserved6: [u8; 700usize],
#[doc = "0x300 - RX FIFO control"]
pub rx_fifo_ctl: RX_FIFO_CTL,
#[doc = "0x304 - RX FIFO status"]
pub rx_fifo_status: RX_FIFO_STATUS,
#[doc = "0x308 - RX FIFO read"]
pub rx_fifo_rd: RX_FIFO_RD,
#[doc = "0x30c - RX FIFO silent read"]
pub rx_fifo_rd_silent: RX_FIFO_RD_SILENT,
_reserved10: [u8; 3056usize],
#[doc = "0xf00 - Interrupt register"]
pub intr: INTR,
#[doc = "0xf04 - Interrupt set register"]
pub intr_set: INTR_SET,
#[doc = "0xf08 - Interrupt mask register"]
pub intr_mask: INTR_MASK,
#[doc = "0xf0c - Interrupt masked register"]
pub intr_masked: INTR_MASKED,
}
#[doc = "Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ctl](ctl) module"]
pub type CTL = crate::Reg<u32, _CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTL;
#[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"]
impl crate::Readable for CTL {}
#[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"]
impl crate::Writable for CTL {}
#[doc = "Control"]
pub mod ctl;
#[doc = "Clock control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [clock_ctl](clock_ctl) module"]
pub type CLOCK_CTL = crate::Reg<u32, _CLOCK_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLOCK_CTL;
#[doc = "`read()` method returns [clock_ctl::R](clock_ctl::R) reader structure"]
impl crate::Readable for CLOCK_CTL {}
#[doc = "`write(|w| ..)` method takes [clock_ctl::W](clock_ctl::W) writer structure"]
impl crate::Writable for CLOCK_CTL {}
#[doc = "Clock control"]
pub mod clock_ctl;
#[doc = "Mode control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mode_ctl](mode_ctl) module"]
pub type MODE_CTL = crate::Reg<u32, _MODE_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MODE_CTL;
#[doc = "`read()` method returns [mode_ctl::R](mode_ctl::R) reader structure"]
impl crate::Readable for MODE_CTL {}
#[doc = "`write(|w| ..)` method takes [mode_ctl::W](mode_ctl::W) writer structure"]
impl crate::Writable for MODE_CTL {}
#[doc = "Mode control"]
pub mod mode_ctl;
#[doc = "Data control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [data_ctl](data_ctl) module"]
pub type DATA_CTL = crate::Reg<u32, _DATA_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DATA_CTL;
#[doc = "`read()` method returns [data_ctl::R](data_ctl::R) reader structure"]
impl crate::Readable for DATA_CTL {}
#[doc = "`write(|w| ..)` method takes [data_ctl::W](data_ctl::W) writer structure"]
impl crate::Writable for DATA_CTL {}
#[doc = "Data control"]
pub mod data_ctl;
#[doc = "Command\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmd](cmd) module"]
pub type CMD = crate::Reg<u32, _CMD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMD;
#[doc = "`read()` method returns [cmd::R](cmd::R) reader structure"]
impl crate::Readable for CMD {}
#[doc = "`write(|w| ..)` method takes [cmd::W](cmd::W) writer structure"]
impl crate::Writable for CMD {}
#[doc = "Command"]
pub mod cmd;
#[doc = "Trigger control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tr_ctl](tr_ctl) module"]
pub type TR_CTL = crate::Reg<u32, _TR_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TR_CTL;
#[doc = "`read()` method returns [tr_ctl::R](tr_ctl::R) reader structure"]
impl crate::Readable for TR_CTL {}
#[doc = "`write(|w| ..)` method takes [tr_ctl::W](tr_ctl::W) writer structure"]
impl crate::Writable for TR_CTL {}
#[doc = "Trigger control"]
pub mod tr_ctl;
#[doc = "RX FIFO control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_ctl](rx_fifo_ctl) module"]
pub type RX_FIFO_CTL = crate::Reg<u32, _RX_FIFO_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_FIFO_CTL;
#[doc = "`read()` method returns [rx_fifo_ctl::R](rx_fifo_ctl::R) reader structure"]
impl crate::Readable for RX_FIFO_CTL {}
#[doc = "`write(|w| ..)` method takes [rx_fifo_ctl::W](rx_fifo_ctl::W) writer structure"]
impl crate::Writable for RX_FIFO_CTL {}
#[doc = "RX FIFO control"]
pub mod rx_fifo_ctl;
#[doc = "RX FIFO status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_status](rx_fifo_status) module"]
pub type RX_FIFO_STATUS = crate::Reg<u32, _RX_FIFO_STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_FIFO_STATUS;
#[doc = "`read()` method returns [rx_fifo_status::R](rx_fifo_status::R) reader structure"]
impl crate::Readable for RX_FIFO_STATUS {}
#[doc = "RX FIFO status"]
pub mod rx_fifo_status;
#[doc = "RX FIFO read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_rd](rx_fifo_rd) module"]
pub type RX_FIFO_RD = crate::Reg<u32, _RX_FIFO_RD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_FIFO_RD;
#[doc = "`read()` method returns [rx_fifo_rd::R](rx_fifo_rd::R) reader structure"]
impl crate::Readable for RX_FIFO_RD {}
#[doc = "RX FIFO read"]
pub mod rx_fifo_rd;
#[doc = "RX FIFO silent read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_rd_silent](rx_fifo_rd_silent) module"]
pub type RX_FIFO_RD_SILENT = crate::Reg<u32, _RX_FIFO_RD_SILENT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_FIFO_RD_SILENT;
#[doc = "`read()` method returns [rx_fifo_rd_silent::R](rx_fifo_rd_silent::R) reader structure"]
impl crate::Readable for RX_FIFO_RD_SILENT {}
#[doc = "RX FIFO silent read"]
pub mod rx_fifo_rd_silent;
#[doc = "Interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"]
pub type INTR = crate::Reg<u32, _INTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR;
#[doc = "`read()` method returns [intr::R](intr::R) reader structure"]
impl crate::Readable for INTR {}
#[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"]
impl crate::Writable for INTR {}
#[doc = "Interrupt register"]
pub mod intr;
#[doc = "Interrupt set register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"]
pub type INTR_SET = crate::Reg<u32, _INTR_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_SET;
#[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"]
impl crate::Readable for INTR_SET {}
#[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"]
impl crate::Writable for INTR_SET {}
#[doc = "Interrupt set register"]
pub mod intr_set;
#[doc = "Interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"]
pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASK;
#[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"]
impl crate::Readable for INTR_MASK {}
#[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"]
impl crate::Writable for INTR_MASK {}
#[doc = "Interrupt mask register"]
pub mod intr_mask;
#[doc = "Interrupt masked register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"]
pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASKED;
#[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"]
impl crate::Readable for INTR_MASKED {}
#[doc = "Interrupt masked register"]
pub mod intr_masked;
|
pub struct Delay {
buffer: Vec<f64>,
index: usize,
}
impl Delay {
pub fn new(length: usize) -> Delay {
Delay {
buffer: vec![0.; length],
index: 0,
}
}
pub fn read(&self) -> f64 {
self.buffer[self.index]
}
pub fn write_and_advance(&mut self, s: f64) {
self.buffer[self.index] = s;
self.index = (self.index + 1) % self.buffer.len();
}
}
mod tests {
use super::*;
#[test]
fn test_delay() {
let mut d = Delay::new(3);
let results = (1..=10)
.map(|i| {
let s = d.read();
d.write_and_advance(i as f64);
s
})
.collect::<Vec<f64>>();
assert_eq!(results, vec![0., 0., 0., 1., 2., 3., 4., 5., 6., 7.]);
}
}
|
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::time::timeout;
use tokio_io_timeout::TimeoutStream;
use hyper::client::connect::{Connected, Connection};
use hyper::{service::Service, Uri};
mod stream;
use stream::TimeoutConnectorStream;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
/// A connector that enforces as connection timeout
#[derive(Debug, Clone)]
pub struct TimeoutConnector<T> {
/// A connector implementing the `Connect` trait
connector: T,
/// Amount of time to wait connecting
connect_timeout: Option<Duration>,
/// Amount of time to wait reading response
read_timeout: Option<Duration>,
/// Amount of time to wait writing request
write_timeout: Option<Duration>,
}
impl<T> TimeoutConnector<T>
where
T: Service<Uri> + Send,
T::Response: AsyncRead + AsyncWrite + Send + Unpin,
T::Future: Send + 'static,
T::Error: Into<BoxError>,
{
/// Construct a new TimeoutConnector with a given connector implementing the `Connect` trait
pub fn new(connector: T) -> Self {
TimeoutConnector {
connector,
connect_timeout: None,
read_timeout: None,
write_timeout: None,
}
}
}
impl<T> Service<Uri> for TimeoutConnector<T>
where
T: Service<Uri> + Send,
T::Response: AsyncRead + AsyncWrite + Connection + Send + Unpin,
T::Future: Send + 'static,
T::Error: Into<BoxError>,
{
type Response = Pin<Box<TimeoutConnectorStream<T::Response>>>;
type Error = BoxError;
#[allow(clippy::type_complexity)]
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.connector.poll_ready(cx).map_err(Into::into)
}
fn call(&mut self, dst: Uri) -> Self::Future {
let connect_timeout = self.connect_timeout;
let read_timeout = self.read_timeout;
let write_timeout = self.write_timeout;
let connecting = self.connector.call(dst);
let fut = async move {
let stream = match connect_timeout {
None => {
let io = connecting.await.map_err(Into::into)?;
TimeoutStream::new(io)
}
Some(connect_timeout) => {
let timeout = timeout(connect_timeout, connecting);
let connecting = timeout
.await
.map_err(|e| io::Error::new(io::ErrorKind::TimedOut, e))?;
let io = connecting.map_err(Into::into)?;
TimeoutStream::new(io)
}
};
let mut tm = TimeoutConnectorStream::new(stream);
tm.set_read_timeout(read_timeout);
tm.set_write_timeout(write_timeout);
Ok(Box::pin(tm))
};
Box::pin(fut)
}
}
impl<T> TimeoutConnector<T> {
/// Set the timeout for connecting to a URL.
///
/// Default is no timeout.
#[inline]
pub fn set_connect_timeout(&mut self, val: Option<Duration>) {
self.connect_timeout = val;
}
/// Set the timeout for the response.
///
/// Default is no timeout.
#[inline]
pub fn set_read_timeout(&mut self, val: Option<Duration>) {
self.read_timeout = val;
}
/// Set the timeout for the request.
///
/// Default is no timeout.
#[inline]
pub fn set_write_timeout(&mut self, val: Option<Duration>) {
self.write_timeout = val;
}
}
impl<T> Connection for TimeoutConnector<T>
where
T: AsyncRead + AsyncWrite + Connection + Service<Uri> + Send + Unpin,
T::Response: AsyncRead + AsyncWrite + Send + Unpin,
T::Future: Send + 'static,
T::Error: Into<BoxError>,
{
fn connected(&self) -> Connected {
self.connector.connected()
}
}
#[cfg(test)]
mod tests {
use std::error::Error;
use std::io;
use std::time::Duration;
use hyper::client::HttpConnector;
use hyper::Client;
use super::TimeoutConnector;
#[tokio::test]
async fn test_timeout_connector() {
// 10.255.255.1 is a not a routable IP address
let url = "http://10.255.255.1".parse().unwrap();
let http = HttpConnector::new();
let mut connector = TimeoutConnector::new(http);
connector.set_connect_timeout(Some(Duration::from_millis(1)));
let client = Client::builder().build::<_, hyper::Body>(connector);
let res = client.get(url).await;
match res {
Ok(_) => panic!("Expected a timeout"),
Err(e) => {
if let Some(io_e) = e.source().unwrap().downcast_ref::<io::Error>() {
assert_eq!(io_e.kind(), io::ErrorKind::TimedOut);
} else {
panic!("Expected timeout error");
}
}
}
}
#[tokio::test]
async fn test_read_timeout() {
let url = "http://example.com".parse().unwrap();
let http = HttpConnector::new();
let mut connector = TimeoutConnector::new(http);
// A 1 ms read timeout should be so short that we trigger a timeout error
connector.set_read_timeout(Some(Duration::from_millis(1)));
let client = Client::builder().build::<_, hyper::Body>(connector);
let res = client.get(url).await;
match res {
Ok(_) => panic!("Expected a timeout"),
Err(e) => {
if let Some(io_e) = e.source().unwrap().downcast_ref::<io::Error>() {
assert_eq!(io_e.kind(), io::ErrorKind::TimedOut);
} else {
panic!("Expected timeout error");
}
}
}
}
}
|
use crate::page::{self, route, Page, Route};
use seed::prelude::*;
use seed::{a, attrs, log, C};
pub struct Model {
route: Route,
page: Page,
}
#[derive(Debug)]
pub enum Msg {
NavigateTo(Route),
RepoListMsg(page::repo_list::Msg),
RepoMsg(page::repo::Msg),
}
pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
// set up routing
orders
.subscribe(|subs::UrlChanged(url)| Msg::NavigateTo(route(url)))
.notify(subs::UrlChanged(url));
Model {
page: Page::NotFound,
route: Route::NotFound,
}
}
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
log!(&msg);
match msg {
Msg::NavigateTo(route) => {
model.route = route;
model.page = match &model.route {
Route::NotFound => Page::NotFound,
Route::Help => Page::Help,
Route::RepoList => {
Page::RepoList(page::repo_list::init(&mut orders.proxy(Msg::RepoListMsg)))
}
Route::Repo(name) => Page::Repo(page::repo::init(
name.clone(),
&mut orders.proxy(Msg::RepoMsg),
)),
};
}
Msg::RepoListMsg(msg) => {
if let Page::RepoList(model) = &mut model.page {
page::repo_list::update(msg, model, &mut orders.proxy(Msg::RepoListMsg));
}
}
Msg::RepoMsg(msg) => {
if let Page::Repo(model) = &mut model.page {
page::repo::update(msg, model, &mut orders.proxy(Msg::RepoMsg));
}
}
}
}
pub fn view(model: &Model) -> Vec<Node<Msg>> {
vec![
seed::div![
C!["header"],
a![
C!["header_text"],
"dockerBoi",
attrs! {
At::Href => "/"
},
]
],
seed::a![
C!["help_button"],
attrs! {
At::Href => "/help",
},
"?",
],
match &model.page {
Page::Repo(model) => page::repo::view(model).map_msg(Msg::RepoMsg),
Page::RepoList(model) => page::repo_list::view(model).map_msg(Msg::RepoListMsg),
Page::Help => page::help::view(),
Page::NotFound => seed::h1!["Not Found"],
},
]
}
|
#[doc = "Register `DFSDM_FLT2ICR` reader"]
pub type R = crate::R<DFSDM_FLT2ICR_SPEC>;
#[doc = "Register `DFSDM_FLT2ICR` writer"]
pub type W = crate::W<DFSDM_FLT2ICR_SPEC>;
#[doc = "Field `CLRJOVRF` reader - Clear the injected conversion overrun flag"]
pub type CLRJOVRF_R = crate::BitReader;
#[doc = "Field `CLRJOVRF` writer - Clear the injected conversion overrun flag"]
pub type CLRJOVRF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CLRROVRF` reader - Clear the regular conversion overrun flag"]
pub type CLRROVRF_R = crate::BitReader;
#[doc = "Field `CLRROVRF` writer - Clear the regular conversion overrun flag"]
pub type CLRROVRF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CLRCKABF` reader - Clear the clock absence flag"]
pub type CLRCKABF_R = crate::FieldReader;
#[doc = "Field `CLRCKABF` writer - Clear the clock absence flag"]
pub type CLRCKABF_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `CLRSCDF` reader - Clear the short-circuit detector flag"]
pub type CLRSCDF_R = crate::FieldReader;
#[doc = "Field `CLRSCDF` writer - Clear the short-circuit detector flag"]
pub type CLRSCDF_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bit 2 - Clear the injected conversion overrun flag"]
#[inline(always)]
pub fn clrjovrf(&self) -> CLRJOVRF_R {
CLRJOVRF_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Clear the regular conversion overrun flag"]
#[inline(always)]
pub fn clrrovrf(&self) -> CLRROVRF_R {
CLRROVRF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bits 16:23 - Clear the clock absence flag"]
#[inline(always)]
pub fn clrckabf(&self) -> CLRCKABF_R {
CLRCKABF_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - Clear the short-circuit detector flag"]
#[inline(always)]
pub fn clrscdf(&self) -> CLRSCDF_R {
CLRSCDF_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bit 2 - Clear the injected conversion overrun flag"]
#[inline(always)]
#[must_use]
pub fn clrjovrf(&mut self) -> CLRJOVRF_W<DFSDM_FLT2ICR_SPEC, 2> {
CLRJOVRF_W::new(self)
}
#[doc = "Bit 3 - Clear the regular conversion overrun flag"]
#[inline(always)]
#[must_use]
pub fn clrrovrf(&mut self) -> CLRROVRF_W<DFSDM_FLT2ICR_SPEC, 3> {
CLRROVRF_W::new(self)
}
#[doc = "Bits 16:23 - Clear the clock absence flag"]
#[inline(always)]
#[must_use]
pub fn clrckabf(&mut self) -> CLRCKABF_W<DFSDM_FLT2ICR_SPEC, 16> {
CLRCKABF_W::new(self)
}
#[doc = "Bits 24:31 - Clear the short-circuit detector flag"]
#[inline(always)]
#[must_use]
pub fn clrscdf(&mut self) -> CLRSCDF_W<DFSDM_FLT2ICR_SPEC, 24> {
CLRSCDF_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "interrupt flag clear register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dfsdm_flt2icr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dfsdm_flt2icr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DFSDM_FLT2ICR_SPEC;
impl crate::RegisterSpec for DFSDM_FLT2ICR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dfsdm_flt2icr::R`](R) reader structure"]
impl crate::Readable for DFSDM_FLT2ICR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dfsdm_flt2icr::W`](W) writer structure"]
impl crate::Writable for DFSDM_FLT2ICR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DFSDM_FLT2ICR to value 0"]
impl crate::Resettable for DFSDM_FLT2ICR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//Solving first with brute force
pub fn find_error_part_one(expenses: Vec<i32>) -> i32 {
for first in &expenses {
for second in &expenses {
let sum = first + second;
if sum == 2020 {
return first * second
}
}
}
return 0;
}
pub fn find_error_part_two(expenses: Vec<i32>) -> i32 {
for first in &expenses {
for second in &expenses {
for third in &expenses {
let sum = first + second + third;
if sum == 2020 {
return first * second * third
}
}
}
}
return 0;
} |
// unihernandez22
// https://codeforces.com/problemset/problem/1195/c
// dp
use std::io::stdin;
use std::cmp::max;
fn main() {
let mut n = String::new();
stdin().read_line(&mut n).unwrap();
let n: i64 = n.trim().parse().unwrap();
let mut line = String::new();
stdin().read_line(&mut line).unwrap();
let a: Vec<i64> = line
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
line = String::new();
stdin().read_line(&mut line).unwrap();
let b: Vec<i64> = line
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
let mut x = 0;
let mut y = 0;
let mut z = 0;
let mut tempx;
let mut tempy;
for i in 0..n as usize {
tempx = x;
tempy = y;
x = max(y+a[i], z+a[i]);
y = max(tempx+b[i], z+b[i]);
z = max(tempx, tempy);
}
println!("{}", max(x, max(y, z)));
}
|
mod core;
mod messages;
mod transaction;
mod transport;
pub use self::core::{
CapabilitiesSnitch, CorePanic, CoreSnitch, RegistrarSnitch, ReqProcessorPanic,
};
pub use self::transaction::{TransactionEmptySnitch, TransactionPanic};
pub use self::transport::{TransportErrorSnitch, TransportPanic, TransportSnitch};
pub use messages::Messages;
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use crate::decl_parser_options::DeclParserOptions;
use crate::parser_options::ParserOptions;
impl DeclParserOptions<'_> {
pub const DEFAULT: &'static DeclParserOptions<'static> =
&DeclParserOptions::from_parser_options(ParserOptions::DEFAULT);
}
impl Default for &DeclParserOptions<'_> {
fn default() -> Self {
DeclParserOptions::DEFAULT
}
}
impl DeclParserOptions<'_> {
pub const fn from_parser_options<'a>(opts: &ParserOptions<'a>) -> DeclParserOptions<'a> {
DeclParserOptions {
auto_namespace_map: opts.po_auto_namespace_map,
disable_xhp_element_mangling: opts.po_disable_xhp_element_mangling,
interpret_soft_types_as_like_types: opts.po_interpret_soft_types_as_like_types,
everything_sdt: opts.tco_everything_sdt,
}
}
}
impl<'a> From<&ParserOptions<'a>> for DeclParserOptions<'a> {
fn from(opts: &ParserOptions<'a>) -> Self {
DeclParserOptions::from_parser_options(opts)
}
}
|
use std;
pub unsafe fn cast_slice<A, B>(slice_ref: &[A]) -> &[B] {
use std::slice;
let raw_len = std::mem::size_of::<A>().wrapping_mul(slice_ref.len());
let len = raw_len / std::mem::size_of::<B>();
assert_eq!(raw_len, std::mem::size_of::<B>().wrapping_mul(len));
slice::from_raw_parts(slice_ref.as_ptr() as *const B, len)
}
pub unsafe fn cast_boxed_slice<A, B>(slice_box: Box<[A]>) -> Box<[B]> {
// What happens when the capacity is bigger than the Vec's size?
let raw_len = std::mem::size_of::<A>().wrapping_mul(slice_box.len());
let slice_ptr = Box::into_raw(slice_box);
let len = raw_len / std::mem::size_of::<B>();
assert_eq!(raw_len, std::mem::size_of::<B>().wrapping_mul(len));
Vec::from_raw_parts((*slice_ptr).as_ptr() as *mut B, len, len).into_boxed_slice()
}
|
use envy;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Config {
mins: u64,
title: String,
}
fn main() {
match envy::from_env::<Config>() {
Ok(config) => println!("{:#?}", config),
Err(error) => eprintln!("{:#?}", error),
}
}
|
/// A platform system independent window identifier.
///
/// This allows other crates to reference windows without needing to
/// specify what platform crate is being used.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub struct WindowId {
riddle_window_id: u32,
}
impl WindowId {
pub fn new(id: u32) -> Self {
Self {
riddle_window_id: id,
}
}
}
|
struct FunctionalTable<C> {
priv name : ~str,
priv map : ~::std::hashmap::HashMap<Entity, C>
}
impl<C : ToStr + Clone> FunctionalTable<C> {
pub fn new(name : ~str) -> FunctionalTable<C>{
info!("create_table name={}",name);
FunctionalTable{
name : name,
map : ~::std::hashmap::HashMap::new()
}
}
pub fn set(&mut self, e : Entity, v : C) {
info!("set id={} cmpt={} val={}", e, self.name, v.to_str() );
self.map.swap(e,v);
}
/* fail if the entity e does not have a component */
pub fn get<'a>(&'a self, e : Entity) -> &'a C {
self.map.get(&e)
}
/* TODO create an own iterator type (or re-use some trait) */
pub fn iter<'a>(&'a self) -> ::std::hashmap::HashMapIterator<'a, Entity, C> {
self.map.iter()
}
pub fn apply(&mut self, f : &fn(Entity, &C) -> C) {
let copy = self.map.clone();
// TODO do I really need to copy all the map ?
for (&e,c) in copy.iter() {
let new_c = f(e, c);
info!("set id={} cmpt={} val={}", e, self.name, new_c.to_str() );
self.map.swap(e, new_c);
}
}
}
#[test]
fn test_FunctionalTable_get_set(){
let mut table : FunctionalTable<int> = FunctionalTable::new(~"test");
let val = 1;
let entity = 42;
table.set(entity,val);
assert!( val == *table.get(entity) );
}
/* We need a type for the entities, which is just an identifier. */
pub type Entity = uint; |
use subspace_codec::Spartan;
#[test]
fn test_random_piece() {
let public_key = rand::random::<[u8; 32]>();
let nonce = rand::random();
let spartan = Spartan::new(public_key.as_ref());
let encoding = spartan.encode(nonce);
assert!(spartan.is_encoding_valid(encoding, nonce));
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct CH {
#[doc = "0x00 - channel configuration y register"]
pub cfgr1: CFGR1,
#[doc = "0x04 - channel configuration y register"]
pub cfgr2: CFGR2,
#[doc = "0x08 - analog watchdog and short-circuit detector register"]
pub awscdr: AWSCDR,
#[doc = "0x0c - channel watchdog filter data register"]
pub wdatr: WDATR,
#[doc = "0x10 - channel data input register"]
pub datinr: DATINR,
_reserved_end: [u8; 0x0c],
}
#[doc = "CFGR1 (rw) register accessor: channel configuration y register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfgr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfgr1`]
module"]
pub type CFGR1 = crate::Reg<cfgr1::CFGR1_SPEC>;
#[doc = "channel configuration y register"]
pub mod cfgr1;
#[doc = "CFGR2 (rw) register accessor: channel configuration y register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfgr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfgr2`]
module"]
pub type CFGR2 = crate::Reg<cfgr2::CFGR2_SPEC>;
#[doc = "channel configuration y register"]
pub mod cfgr2;
#[doc = "AWSCDR (rw) register accessor: analog watchdog and short-circuit detector register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`awscdr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`awscdr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`awscdr`]
module"]
pub type AWSCDR = crate::Reg<awscdr::AWSCDR_SPEC>;
#[doc = "analog watchdog and short-circuit detector register"]
pub mod awscdr;
#[doc = "WDATR (rw) register accessor: channel watchdog filter data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wdatr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`wdatr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`wdatr`]
module"]
pub type WDATR = crate::Reg<wdatr::WDATR_SPEC>;
#[doc = "channel watchdog filter data register"]
pub mod wdatr;
#[doc = "DATINR (rw) register accessor: channel data input register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`datinr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`datinr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`datinr`]
module"]
pub type DATINR = crate::Reg<datinr::DATINR_SPEC>;
#[doc = "channel data input register"]
pub mod datinr;
|
use crate::bit_set::ops::*;
#[test]
fn access() {
let slice = [1u64, 0b10101100001, 0b0000100000];
assert!(slice.access(0));
assert!(slice.access(70));
}
#[test]
fn count() {
let slice = [0u64, 0b10101100000, 0b0000100000];
assert_eq!(slice.count1(), 5);
}
#[test]
fn rank() {
let slice = [0u8, 0b0110_0000, 0b0001_0000];
assert_eq!(slice.rank1(10), 0);
assert_eq!(slice.rank1(14), 1);
assert_eq!(slice.rank1(15), 2);
assert_eq!(slice.rank1(16), 2);
assert_eq!(slice.rank1(10), 10 - slice.rank0(10)); // rank1(i) + rank0(i) == i
assert_eq!(slice.rank1(slice.size()), slice.count1());
}
#[test]
fn select() {
let w: u64 = 0b_0000_0100_1001_0000;
assert_eq!(w.select1(0), 4);
assert_eq!(w.select1(1), 7);
assert_eq!(w.select1(2), 10);
assert_eq!(w.rank1(w.select1(2)), 2);
let w: u128 = (0b_00001100_u128 << 64) | 0b_00000100_u128;
assert_eq!(w.select1(0), 2);
assert_eq!(w.select1(1), 66);
assert_eq!(w.select1(2), 67);
let slice = [0b_0000_u64, 0b_0100, 0b_1001];
assert_eq!(slice.select1(0), 66);
assert_eq!(slice.select1(1), 128);
assert_eq!(slice.select1(2), 131);
let slice = [0b_11110111_u8, 0b_11111110, 0b_10010011];
assert_eq!(slice.select0(0), 3);
assert_eq!(slice.select0(1), 8);
assert_eq!(slice.select0(2), 18);
}
#[test]
fn insert() {
let mut slice = [0u64, 0b10101100000, 0b0000100000];
assert!(!slice.insert(0));
assert!(slice.insert(0));
assert!(slice.access(0));
}
#[test]
fn remove() {
let mut slice = [0u64, 0b10101100001, 0b0000100000];
assert!(slice.remove(64));
assert!(!slice.remove(64));
assert!(!slice.access(64));
}
|
use actix_web::{middleware::Logger, web, App, HttpServer, Responder};
use anyhow::Result;
use dotenv;
use std::env;
mod errors;
mod init;
mod models;
mod routes;
mod validation;
async fn helo() -> impl Responder {
"yeeeeeeeeee"
}
#[actix_web::main]
async fn main() -> Result<()> {
dotenv::dotenv().expect(".env file not found");
pretty_env_logger::init();
let address = env::var("ADDRESS").expect("ADDRESS env var unset");
let (db_pool, redis_pool) = init::init().await?;
HttpServer::new(move || {
App::new()
.data(db_pool.clone())
.data(redis_pool.clone())
.service(
web::scope("/api").route("/", web::get().to(helo)).service(
web::scope("/users/auth")
.service(routes::auth::register)
.service(routes::auth::login),
),
)
.wrap(Logger::default())
})
.bind(address)?
.run()
.await?;
Ok(())
}
|
pub use crate::common::{Const, Id, Op2};
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub enum Expr {
Var(Id),
Const(Const),
Op2(Op2, Box<Expr>, Box<Expr>),
Fun(Id, Box<Expr>),
App(Box<Expr>, Box<Expr>),
If(Box<Expr>, Box<Expr>, Box<Expr>),
Let(Id, Box<Expr>, Box<Expr>),
Fix(Id, Box<Expr>),
MkArray(Box<Expr>, Box<Expr>),
GetArray(Box<Expr>, Box<Expr>),
SetArray(Box<Expr>, Box<Expr>, Box<Expr>),
// liquid-type constructs
Star,
V,
}
|
use christmas_tree::{
fold::{folder, Control, Folder},
visit::{visitor, Visitor},
DefaultNode, DefaultTreeFactory, FromDiscriminantError, GreenNode, GreenTree, GreenTreeFactory,
NodeType, OwnedRoot, RefRoot, TreeNode,
};
use core::{convert::TryFrom, ops::Range as OpsRange};
#[cfg(feature = "serialization")]
mod types {
use super::*;
use serde_derive as serded;
#[derive(Debug, Clone)]
pub struct Addition<'a> {
pub arith_node: ArithNode<'a>,
}
#[derive(Debug, Clone)]
pub struct Multiplication<'a> {
pub arith_node: ArithNode<'a>,
}
#[derive(Debug, Clone)]
pub struct Literal<'a> {
pub arith_node: ArithNode<'a>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, serded::Serialize, serded::Deserialize)]
pub enum ArithKind {
Literal,
Add,
Multiply,
}
}
#[cfg(not(feature = "serialization"))]
mod types {
use super::*;
#[derive(Debug, Clone)]
pub struct Addition<'a> {
pub arith_node: ArithNode<'a>,
}
#[derive(Debug, Clone)]
pub struct Multiplication<'a> {
pub arith_node: ArithNode<'a>,
}
#[derive(Debug, Clone)]
pub struct Literal<'a> {
pub arith_node: ArithNode<'a>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ArithKind {
Literal,
Add,
Multiply,
}
}
use types::*;
impl<'a> TryFrom<ArithNode<'a>> for Addition<'a> {
type Error = FromDiscriminantError;
fn try_from(arith_node: ArithNode<'a>) -> Result<Self, FromDiscriminantError> {
if arith_node.green().node_data() == ArithKind::Add {
Ok(Addition { arith_node })
} else {
Err(FromDiscriminantError)
}
}
}
impl<'a> TryFrom<ArithNode<'a>> for Multiplication<'a> {
type Error = FromDiscriminantError;
fn try_from(arith_node: ArithNode<'a>) -> Result<Self, FromDiscriminantError> {
if arith_node.green().node_data() == ArithKind::Multiply {
Ok(Multiplication { arith_node })
} else {
Err(FromDiscriminantError)
}
}
}
impl<'a> TryFrom<ArithNode<'a>> for Literal<'a> {
type Error = FromDiscriminantError;
fn try_from(arith_node: ArithNode<'a>) -> Result<Self, FromDiscriminantError> {
if arith_node.green().node_data() == ArithKind::Literal {
Ok(Literal { arith_node })
} else {
Err(FromDiscriminantError)
}
}
}
impl PartialEq<ArithKind> for &ArithKind {
fn eq(&self, rhs: &ArithKind) -> bool {
use self::ArithKind::*;
match (self, rhs) {
(Literal, Literal) => true,
(Add, Add) => true,
(Multiply, Multiply) => true,
_ => false,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ArithTree {}
impl GreenTree for ArithTree {
type BranchData = ();
type Factory = DefaultTreeFactory<Self>;
type GlobalData = ();
type LeafData = i32;
type Node = DefaultNode<Self>;
type NodeData = ArithKind;
type Range = OpsRange<u32>;
fn new_leaf(node_data: ArithKind, leaf: i32, width: u32) -> Self::Node {
DefaultNode::new_leaf(node_data, leaf, width)
}
fn new_branch(
node_data: ArithKind,
_branch_data: (),
children: Box<[Self::Node]>,
) -> Self::Node {
let width = children.iter().map(|c| c.width()).sum();
DefaultNode::new_branch(node_data, (), children, width)
}
}
type ArithInnerNode = <ArithTree as GreenTree>::Node;
type ArithRoot = TreeNode<ArithTree, OwnedRoot<ArithTree>>;
type ArithNode<'a> = TreeNode<ArithTree, RefRoot<'a, ArithTree>>;
type ArithTreeFactory = <ArithTree as GreenTree>::Factory;
#[test]
fn build_inner_tree() {
let mut factory = ArithTreeFactory::default();
let _: ArithInnerNode = factory
.start_branch(ArithKind::Add, ())
.leaf(ArithKind::Literal, -23, 1)
.leaf(ArithKind::Literal, 20, 1)
.start_branch(ArithKind::Multiply, ())
.leaf(ArithKind::Literal, 1, 1)
.leaf(ArithKind::Literal, 3, 1)
.finish_branch()
.finish_branch()
.finish();
}
#[test]
#[should_panic]
fn build_empty_inner_tree() {
let mut factory = ArithTreeFactory::default();
let _inner_expr: ArithInnerNode = factory.finish();
}
#[test]
fn build_tree() {
let mut factory = ArithTreeFactory::default();
let inner_expr: ArithInnerNode = factory
.start_branch(ArithKind::Add, ())
.leaf(ArithKind::Literal, -23, 1)
.leaf(ArithKind::Literal, 20, 1)
.start_branch(ArithKind::Multiply, ())
.leaf(ArithKind::Literal, 1, 1)
.leaf(ArithKind::Literal, 3, 1)
.finish_branch()
.finish_branch()
.finish();
let root = ArithRoot::new(inner_expr, 0, ());
let current: ArithNode = root.borrowed();
let num_descendants = current
.descendants()
.inspect(|n| match n.green().specific_data() {
NodeType::Branch(_) => println!("{:?}", n.green().node_data()),
NodeType::Leaf(lit) => println!("{:?}: {}", n.green().node_data(), lit),
})
.count();
assert_eq!(num_descendants, 6);
}
#[test]
fn visit_tree() {
let mut factory = ArithTreeFactory::default();
let inner_expr: ArithInnerNode = factory
.start_branch(ArithKind::Add, ())
.leaf(ArithKind::Literal, -23, 1)
.leaf(ArithKind::Literal, 20, 1)
.start_branch(ArithKind::Multiply, ())
.leaf(ArithKind::Literal, 1, 1)
.leaf(ArithKind::Literal, 3, 1)
.finish_branch()
.finish_branch()
.finish();
let root = ArithRoot::new(inner_expr, 0, ());
let current: ArithNode = root.borrowed();
let tree_it = current.descendants();
fn get_literal_values<'a>(lit: Literal<'a>) -> Option<i32> {
Some(*lit.arith_node.green().specific_data().unwrap_leaf())
}
let visitor = visitor().visit(get_literal_values);
let literal_values: Vec<_> = tree_it.filter_map(|n| visitor.accept(n)).collect();
assert_eq!(literal_values, vec![-23, 20, 1, 3])
}
#[test]
fn fold_tree() {
let mut factory = ArithTreeFactory::default();
let inner_expr: ArithInnerNode = factory
.start_branch(ArithKind::Add, ())
.leaf(ArithKind::Literal, -23, 1)
.leaf(ArithKind::Literal, 20, 1)
.start_branch(ArithKind::Multiply, ())
.leaf(ArithKind::Literal, 1, 1)
.leaf(ArithKind::Literal, 3, 1)
.finish_branch()
.finish_branch()
.finish();
let root = ArithRoot::new(inner_expr, 0, ());
let current: ArithNode = root.borrowed();
let tree_it = current.postorder_dfs();
fn accum_literal(lit: Literal, mut accum: Vec<i32>) -> (Control, Vec<i32>) {
accum.push(*lit.arith_node.green().specific_data().unwrap_leaf());
(Control::Break, accum)
}
fn accum_multiplication(mult: Multiplication, mut accum: Vec<i32>) -> (Control, Vec<i32>) {
let num_child = mult.arith_node.green().num_children();
assert!(accum.len() >= num_child);
let mut inner_accum: i32 = 1;
for _ in 0..num_child {
let arg = accum.pop().unwrap();
inner_accum *= arg;
}
accum.push(inner_accum);
(Control::Break, accum)
}
fn accum_addition(add: Addition, mut accum: Vec<i32>) -> (Control, Vec<i32>) {
let num_child = add.arith_node.green().num_children();
assert!(accum.len() >= num_child);
let mut inner_accum: i32 = 0;
for _ in 0..num_child {
let arg = accum.pop().unwrap();
inner_accum += arg;
}
accum.push(inner_accum);
(Control::Break, accum)
}
let f = folder()
.fold_with(accum_literal)
.fold_with(accum_multiplication)
.fold_with(accum_addition);
let mut eval_stack = tree_it.fold(vec![], |accum, n| f.accept(n, accum).1);
assert_eq!(eval_stack.pop(), Some(0));
}
#[cfg(feature = "serialization")]
#[test]
fn test_serialize_tree() {
use christmas_tree::SerdeTreeWrapper;
let mut factory = ArithTreeFactory::default();
let inner_expr: ArithInnerNode = factory
.start_branch(ArithKind::Add, ())
.leaf(ArithKind::Literal, -23, 1)
.leaf(ArithKind::Literal, 20, 1)
.start_branch(ArithKind::Multiply, ())
.leaf(ArithKind::Literal, 1, 1)
.leaf(ArithKind::Literal, 3, 1)
.finish_branch()
.finish_branch()
.finish();
let ser_wrapper = SerdeTreeWrapper::from(inner_expr);
let json_str = serde_json::to_string(&ser_wrapper).unwrap();
println!("{}", json_str);
let temp: Result<SerdeTreeWrapper<ArithInnerNode>, _> = serde_json::from_str(&json_str);
let new_inner: ArithInnerNode = temp.unwrap().into_inner();
assert_eq!(ser_wrapper.into_inner(), new_inner);
}
|
use radix::tree::Tree;
use std::mem;
pub struct Node<T> {
pub key: Vec<u8>,
pub value: Option<T>,
pub next: Tree<T>,
pub child: Tree<T>,
}
impl<T> Node<T> {
pub fn new(key: Vec<u8>, value: Option<T>) -> Self {
Self {
key,
value,
next: None,
child: None,
}
}
pub fn contains(&self, byte: u8) -> bool {
self.get(byte).is_some()
}
pub fn get(&self, byte: u8) -> &Tree<T> {
fn get_inner<T>(tree: &Tree<T>, byte: u8) -> &Tree<T> {
match tree {
Some(ref node) if node.key[0] != byte => get_inner(&node.next, byte),
_ => tree,
}
}
get_inner(&self.child, byte)
}
pub fn get_mut(&mut self, byte: u8) -> &mut Tree<T> {
fn get_mut_inner<T>(tree: &mut Tree<T>, byte: u8) -> &mut Tree<T> {
match tree {
Some(ref mut node) if node.key[0] != byte => get_mut_inner(&mut node.next, byte),
_ => tree,
}
}
get_mut_inner(&mut self.child, byte)
}
pub fn insert_child(&mut self, child: Node<T>) {
fn insert_inner<T>(tree: &mut Tree<T>, mut new_node: Box<Node<T>>) {
match tree {
Some(ref mut node) => {
if node.key[0] > new_node.key[0] {
mem::swap(node, &mut new_node);
node.next = Some(new_node);
} else {
insert_inner(&mut node.next, new_node);
}
},
None => *tree = Some(new_node),
}
}
insert_inner(&mut self.child, Box::new(child));
}
pub fn merge(&mut self) {
if let Some(mut child_node) = self.child.take() {
if self.value.is_none() && child_node.next.is_none() {
self.key.extend(child_node.key.iter());
self.value = child_node.value.take();
self.child = child_node.child.take();
} else {
self.child = Some(child_node);
}
}
}
pub fn min(&self) -> &Tree<T> {
&self.child
}
pub fn max(&self) -> &Tree<T> {
let mut curr_tree = &self.child;
while let Some(ref curr_node) = curr_tree {
if (*curr_node).next.is_none() {
return curr_tree;
}
curr_tree = &curr_node.next;
}
&None
}
}
|
fn m() {
// single
let server = Server::new();
server.start();
client.connect(server);
// multi
// server
let server = Server::new();
server.start();
//client
let address = input!(address);
client.connect(address);
}
fn server() {
loop {
let data = receive_from_clients();
calc_damage(data);
calc_put_block(data);
culc_new_geometry(data);
broadcast(data);
}
}
fn client() {
loop {
draw_gui();
get_input();
}
}
|
use _const::DAMAGE_RANGE;
use component::{Component, Health};
use entity::Entity;
pub fn hit_once(health: &mut Health, damage_taken: Option<i32>) {
health.0 -= match &damage_taken {
None => DAMAGE_RANGE,
Some(v) => v.clone(),
};
}
pub fn get(entity: &Entity) -> &Health {
match entity
.get_component(|c| {
if let Component::Health(_) = c {
true
} else {
false
}
})
.unwrap()
{
Component::Health(value) => value,
_ => panic!("No health component found."),
}
}
pub fn get_mutable(entity: &mut Entity) -> &mut Health {
match entity
.get_component_mutable(|c| {
if let Component::Health(_) = c {
true
} else {
false
}
})
.unwrap()
{
Component::Health(value) => value,
_ => panic!("No health component found."),
}
}
|
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
use ui::*;
use render::Canvas;
use draw::Shape;
pub const TRANSPARENT: u32 = 0x000000_00;
pub static PAL_GAMEBOY: &[u32] = &[
0xCADC9F_FF,
0x0F380F_FF,
0x306230_FF,
0x8BAC0F_FF,
0x9BBC0F_FF,
];
pub const GRID_COLOR: u32 = 0xFF0000_AA;
pub const CORNER_COLOR: u32 = 0x00FF00_AA;
pub const ICON_TOOL_FREEHAND: usize = 1000_0;
pub const ICON_TOOL_FILL: usize = 1000_1;
pub const ICON_TOOL_CIRC: usize = 1000_2;
pub const ICON_TOOL_RECT: usize = 1000_3;
pub const ICON_TOOL_PIP: usize = 1000_4;
pub const ICON_EYE: usize = 1100_0;
pub const ICON_EYE_OFF: usize = 1100_1;
pub const ICON_LOCK: usize = 1100_2;
pub const ICON_LOCK_OFF: usize = 1100_3;
pub const ICON_UNDO: usize = 2000_0;
pub const ICON_REDO: usize = 2000_1;
pub const ICON_CHECK_ON: usize = 2000_2;
pub const ICON_CHECK_OFF: usize = 2000_3;
pub const EDITOR_SPRITE_ID: usize = 4000;
pub const fn rgba(c: u32) -> u32 {
((c >> 24) & 0xFF) << 0 |
((c >> 16) & 0xFF) << 8 |
((c >> 8) & 0xFF) << 16 |
((c >> 0) & 0xFF) << 24
}
pub const WHITE: u32 = rgba(0xFFFFFF_FF);
pub const MENUBAR_BG: u32 = rgba(0x222833_FF);
pub const MENUBAR_HEIGHT: f32 = 20.0;
pub const TOOLBAR_HEIGHT: f32 = 32.0;
pub const TOOLBAR_BG: u32 = BAR_BG;
pub const STATUSBAR_BG: u32 = rgba(0x3F4350_FF);
pub const STATUSBAR_HEIGHT: f32 = 20.0;
pub const BAR_BG: u32 = rgba(0x3F4957_FF);
pub const BAR_TITLE_BG: u32 = rgba(0x525b68_FF);
pub const BAR_TITLE_HEIGHT: f32 = 20.0;
pub const BTN_NORMAL: u32 = rgba(0x4E5763_FF);
pub const BTN_HOVERED: u32 = rgba(0x3E4855_FF);
pub const BTN_PRESSED: u32 = rgba(0x0076FF_FF);
/*
pub const WINDOW_BG: u32 = 0x20242F_FF;
pub const STATUSBAR_BG: u32 = 0x3F4350_FF;
pub const STATUSBAR_COLOR: u32 = 0xA7A8AE_FF;
pub const MENUBAR_BG: u32 = 0x222833_FF;
pub const BAR_BG: u32 = 0x3f4957_FF;
pub const BTN_BORDER: u32 = ;
*/
pub const TIMELINE_BG: u32 = rgba(0x3A4351_FF);
pub const HEADER_BG: u32 = rgba(0x525b68_FF);
/*
pub const LABEL_COLOR: u32 = 0xFFFFFF_FF;
pub const INSET_X: i16 = FONT_HEIGHT as i16 / 2;
*/
const background: ColorDrawer<Canvas> = ColorDrawer(rgba(0xFFFFFF_CC));
const fill: ColorDrawer<Canvas> = ColorDrawer(rgba(0x000000_CC));
const normal: ColorDrawer<Canvas> = ColorDrawer(rgba(0xFF00FF_FF));
const hovered: ColorDrawer<Canvas> = ColorDrawer(rgba(0xFF00FF_CC));
const pressed: ColorDrawer<Canvas> = ColorDrawer(rgba(0xFF0000_FF));
pub const HPROGRESS: Progress<ColorDrawer<Canvas>, ColorDrawer<Canvas>> = Progress { background, fill, axis: Axis::Horizontal };
pub const VPROGRESS: Progress<ColorDrawer<Canvas>, ColorDrawer<Canvas>> = Progress { background, fill, axis: Axis::Vertical };
pub const HSLIDER: Slider<ColorDrawer<Canvas>> = Slider { normal, hovered, pressed, axis: Axis::Horizontal };
pub const VSLIDER: Slider<ColorDrawer<Canvas>> = Slider { normal, hovered, pressed, axis: Axis::Vertical };
pub const CHECK_ON: TextureDrawer<Canvas> = TextureDrawer(ICON_CHECK_ON);
pub const CHECK_OFF: TextureDrawer<Canvas> = TextureDrawer(ICON_CHECK_OFF);
pub const BTN: ColorButton<Canvas> = ColorButton {
normal: ColorDrawer(BTN_NORMAL),
hovered: ColorDrawer(BTN_HOVERED),
pressed: ColorDrawer(BTN_PRESSED),
};
pub const TOGGLE_BTN: ColorTransparentButton<Canvas> = ColorTransparentButton {
normal: NoDrawer,
hovered: ColorDrawer(BTN_HOVERED),
pressed: ColorDrawer(BTN_PRESSED),
};
pub const TOGGLE: ColorTransparentToggle<Canvas> = ColorTransparentToggle {
checked: TOGGLE_BTN,
unchecked: TOGGLE_BTN,
};
pub const MENUBAR: MenuBar<Canvas> = MenuBar {
normal_color: rgba(0xFFFFFF_FF),
hover_color: rgba(0x000000_FF),
hover_bg: rgba(0xCCCCCC_CC),
};
#[derive(Clone, Debug)]
pub enum Command {
New, Open, Recent,
Save, SaveAs,
Quit,
}
const MENU_STYLE: MenuStyle<Canvas> = MenuStyle {
normal: ItemStyle {
label: rgba(0x000000_FF),
shortcut: rgba(0x000000_88),
bg: rgba(0xFFFFFF_FF),
},
hovered: ItemStyle {
label: rgba(0x000000_FF),
shortcut: rgba(0x000000_88),
bg: rgba(0xAAAAAA_FF),
},
separator: rgba(0x000000_99),
width: 200.0,
text_height: 20.0,
text_inset: 8.0,
sep_height: 5.0,
sep_inset: 2.0,
};
pub const FILE_ITEMS: [Item<Command>; 8] = [
Item::Text(Command::New, "New", "Ctrl-N"),
Item::Text(Command::Open, "Open", "Ctrl-O"),
Item::Text(Command::Recent, "Recent", ">"),
Item::Separator,
Item::Text(Command::Save, "Save", "Ctrl-S"),
Item::Text(Command::SaveAs, "Save as...", "Shift-Ctrl-S"),
Item::Separator,
Item::Text(Command::Quit, "Quit", "Ctrl-Q"),
];
pub const BRUSH_ITEMS: [Item<Shape>; 13] = [
Item::Text(Shape::Round, "Round", ""),
Item::Text(Shape::Square, "Square", ""),
Item::Text(Shape::HorizontalBar, "HorizontalBar", ""),
Item::Text(Shape::VerticalBar, "VerticalBar", ""),
Item::Text(Shape::Slash, "Slash", ""),
Item::Text(Shape::Antislash, "Antislash", ""),
Item::Text(Shape::Cross, "Cross", ""),
Item::Text(Shape::Plus, "Plus", ""),
Item::Text(Shape::Diamond, "Diamond", ""),
Item::Text(Shape::SieveRound, "SieveRound", ""),
Item::Text(Shape::SieveSquare, "SieveSquare", ""),
Item::Separator,
Item::Text(Shape::Custom, "Custom", ""),
];
pub const MENU: Menu<Canvas, Command> = Menu {
marker: ::std::marker::PhantomData,
style: MENU_STYLE,
};
pub const MENU_BRUSH: Menu<Canvas, ::draw::Shape> = Menu {
marker: ::std::marker::PhantomData,
style: MENU_STYLE,
};
|
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(untagged)]
pub enum MaterialParameterType {
Scalar(f32),
Vector([f32; 3]),
}
impl MaterialParameterType {
pub fn as_vec3(&self) -> [f32; 3] {
match self {
Self::Scalar(c) => [*c; 3],
Self::Vector(v) => *v,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(untagged)]
pub enum MaterialParameterTexture {
Single(String),
Multi { horz: String, vert: String },
}
impl MaterialParameterTexture {
pub fn horz_texture(&self) -> &str {
match self {
Self::Single(texture) => texture,
Self::Multi { horz, .. } => horz,
}
}
pub fn vert_texture(&self) -> &str {
match self {
Self::Single(texture) => texture,
Self::Multi { vert, .. } => vert,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TexturedMaterialParameter {
pub base: MaterialParameterType,
pub factor: MaterialParameterType,
pub texture: MaterialParameterTexture,
pub contrast: f32,
pub uv_scale: f32,
pub uv_offset: [f32; 2],
pub uv_rotation: f32,
pub stochastic: bool,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(untagged)]
pub enum MaterialParameter {
Constant(MaterialParameterType),
Textured(TexturedMaterialParameter),
}
impl Default for MaterialParameter {
fn default() -> MaterialParameter {
MaterialParameter::Constant(MaterialParameterType::Scalar(0.0))
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Materials {
pub list: Vec<Material>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum Material {
Lambertian {
albedo: MaterialParameter,
},
IdealReflection {
reflectance: MaterialParameter,
},
IdealRefraction {
transmittance: MaterialParameter,
},
Phong {
albedo: MaterialParameter,
shininess: MaterialParameter,
},
Dielectric {
base_color: MaterialParameter,
#[serde(default)]
roughness: MaterialParameter,
},
}
impl Material {
pub fn has_delta_bsdf(&self) -> bool {
match self {
Self::Lambertian { .. } => false,
Self::IdealReflection { .. } => true,
Self::IdealRefraction { .. } => true,
Self::Phong { .. } => false,
Self::Dielectric { .. } => true,
}
}
pub fn is_photon_receiver(&self) -> bool {
matches!(self, Self::Lambertian { .. })
}
/// Returns a list of parameters referenced by this material.
pub fn parameters(&self) -> Vec<(&str, &MaterialParameter)> {
match self {
Self::Lambertian { albedo } => vec![("albedo", &albedo)],
Self::IdealReflection { reflectance } => vec![("reflectance", &reflectance)],
Self::IdealRefraction { transmittance } => vec![("transmittance", &transmittance)],
Self::Phong { albedo, shininess } => {
vec![("albedo", &albedo), ("shininess", &shininess)]
}
Self::Dielectric {
base_color,
roughness,
} => vec![("base_color", &base_color), ("roughness", &roughness)],
}
}
}
|
extern crate game;
use std::env;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let config = game::app::safety::Config::new(&args);
config.run().unwrap_or_else(|err| {
eprintln!("Error: {}", err);
process::exit(1);
});
}
|
use std::sync::Arc;
use vulkano::command_buffer::SubpassContents;
use vulkano::buffer::{CpuAccessibleBuffer, BufferUsage};
use vulkano::pipeline::{GraphicsPipeline, GraphicsPipelineAbstract};
use gristmill::renderer::{LoadContext, RenderContext, scene};
// -------------------------------------------------------------------------------------------------
// This is a pipeline and renderer that just draws a static red triangle. Useful for testing.
mod vs {
vulkano_shaders::shader! {
ty: "vertex",
src: "
#version 450
layout(location = 0) in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
"
}
}
mod fs {
vulkano_shaders::shader! {
ty: "fragment",
src: "
#version 450
layout(location = 0) out vec4 f_color;
void main() {
f_color = vec4(1.0, 0.0, 0.0, 1.0);
}
"
}
}
#[derive(Default, Clone)]
pub struct Vertex {
pub position: [f32; 2],
}
vulkano::impl_vertex!(Vertex, position);
pub struct BasicGeoPipeline {
pipeline: Arc<dyn GraphicsPipelineAbstract + Send + Sync>,
vertex_buffer: Arc<CpuAccessibleBuffer<[Vertex]>>,
}
impl BasicGeoPipeline {
pub fn new(context: &mut LoadContext) -> BasicGeoPipeline {
let vs = vs::Shader::load(context.device()).unwrap();
let fs = fs::Shader::load(context.device()).unwrap();
let pipeline = Arc::new(
GraphicsPipeline::start()
.vertex_input_single_buffer::<Vertex>()
.vertex_shader(vs.main_entry_point(), ())
.triangle_list()
//.cull_mode_front()
.viewports_dynamic_scissors_irrelevant(1)
.fragment_shader(fs.main_entry_point(), ())
.depth_stencil_simple_depth()
.render_pass(context.subpass())
.build(context.device())
.unwrap(),
);
let vertex_buffer = CpuAccessibleBuffer::from_iter(
context.device(),
BufferUsage::all(),
false,
[
Vertex { position: [-0.5, -0.25] },
Vertex { position: [0.0, 0.5] },
Vertex { position: [0.25, -0.1] },
].iter().cloned(),
).unwrap();
BasicGeoPipeline { pipeline, vertex_buffer }
}
}
// -------------------------------------------------------------------------------------------------
pub struct BasicGeoRenderer(BasicGeoPipeline);
impl scene::SceneRenderer for BasicGeoRenderer {
type RenderType = scene::Geometry3D;
type Scene = ();
fn contents() -> SubpassContents { SubpassContents::Inline }
fn new(context: &mut LoadContext) -> Self {
BasicGeoRenderer(BasicGeoPipeline::new(context))
}
fn pre_render(&mut self, _context: &mut RenderContext, _scene: &mut Self::Scene) {}
fn render(&mut self, context: &mut RenderContext, _scene: &mut Self::Scene) {
context.draw(
self.0.pipeline.clone(),
vec![self.0.vertex_buffer.clone()],
(),
()
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.