text stringlengths 8 4.13M |
|---|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use async_trait::async_trait;
use common_base::base::escape_for_key;
use common_base::base::tokio;
use common_exception::ErrorCode;
use common_management::*;
use common_meta_app::principal::AuthInfo;
use common_meta_app::principal::PasswordHashMethod;
use common_meta_app::principal::UserIdentity;
use common_meta_kvapi::kvapi;
use common_meta_kvapi::kvapi::GetKVReply;
use common_meta_kvapi::kvapi::ListKVReply;
use common_meta_kvapi::kvapi::MGetKVReply;
use common_meta_kvapi::kvapi::UpsertKVReply;
use common_meta_kvapi::kvapi::UpsertKVReq;
use common_meta_types::MatchSeq;
use common_meta_types::MetaError;
use common_meta_types::Operation;
use common_meta_types::SeqV;
use common_meta_types::TxnReply;
use common_meta_types::TxnRequest;
use mockall::predicate::*;
use mockall::*;
// and mock!
mock! {
pub KV {}
#[async_trait]
impl kvapi::KVApi for KV {
type Error = MetaError;
async fn upsert_kv(
&self,
act: UpsertKVReq,
) -> Result<UpsertKVReply, MetaError>;
async fn get_kv(&self, key: &str) -> Result<GetKVReply,MetaError>;
async fn mget_kv(
&self,
key: &[String],
) -> Result<MGetKVReply,MetaError>;
async fn prefix_list_kv(&self, prefix: &str) -> Result<ListKVReply, MetaError>;
async fn transaction(&self, txn: TxnRequest) -> Result<TxnReply, MetaError>;
}
}
fn format_user_key(username: &str, hostname: &str) -> String {
format!("'{}'@'{}'", username, hostname)
}
fn default_test_auth_info() -> AuthInfo {
AuthInfo::Password {
hash_value: Vec::from("test_password"),
hash_method: PasswordHashMethod::DoubleSha1,
}
}
mod add {
use common_meta_app::principal::UserInfo;
use common_meta_types::Operation;
use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_add_user() -> common_exception::Result<()> {
let test_user_name = "test_user";
let test_hostname = "localhost";
let user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let v = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
let value = Operation::Update(serialize_struct(
&user_info,
ErrorCode::IllegalUserInfoFormat,
|| "",
)?);
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let test_seq = MatchSeq::Exact(0);
// normal
{
let test_key = test_key.clone();
let mut api = MockKV::new();
api.expect_upsert_kv()
.with(predicate::eq(UpsertKVReq::new(
&test_key,
test_seq,
value.clone(),
None,
)))
.times(1)
.return_once(|_u| Ok(UpsertKVReply::new(None, Some(SeqV::new(1, v)))));
let api = Arc::new(api);
let user_mgr = UserMgr::create(api, "tenant1")?;
let res = user_mgr.add_user(user_info);
assert!(res.await.is_ok());
}
// already exists
{
let test_key = test_key.clone();
let mut api = MockKV::new();
api.expect_upsert_kv()
.with(predicate::eq(UpsertKVReq::new(
&test_key,
test_seq,
value.clone(),
None,
)))
.times(1)
.returning(|_u| {
Ok(UpsertKVReply::new(
Some(SeqV::new(1, vec![])),
Some(SeqV::new(1, vec![])),
))
});
let api = Arc::new(api);
let user_mgr = UserMgr::create(api, "tenant1")?;
let user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let res = user_mgr.add_user(user_info).await;
assert_eq!(
res.unwrap_err().code(),
ErrorCode::UserAlreadyExists("").code()
);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_add_builtin_user() -> common_exception::Result<()> {
let test_user_name = "default";
let test_hostname = "localhost";
let user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let api = MockKV::new();
let api = Arc::new(api);
let user_mgr = UserMgr::create(api, "tenant1")?;
let res = user_mgr.add_user(user_info);
assert_eq!(
res.await.unwrap_err().code(),
ErrorCode::UserAlreadyExists("").code()
);
Ok(())
}
}
mod get {
use common_meta_app::principal::UserInfo;
use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_user_seq_match() -> common_exception::Result<()> {
let test_user_name = "test";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let value = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
let mut kv = MockKV::new();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(Some(SeqV::new(1, value))));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.get_user(user_info.identity(), MatchSeq::Exact(1));
assert!(res.await.is_ok());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_user_do_not_care_seq() -> common_exception::Result<()> {
let test_user_name = "test";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let value = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
let mut kv = MockKV::new();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(Some(SeqV::new(100, value))));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.get_user(user_info.identity(), MatchSeq::GE(0));
assert!(res.await.is_ok());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_user_not_exist() -> common_exception::Result<()> {
let test_user_name = "test";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let mut kv = MockKV::new();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(None));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr
.get_user(
UserIdentity::new(test_user_name, test_hostname),
MatchSeq::GE(0),
)
.await;
assert!(res.is_err());
assert_eq!(res.unwrap_err().code(), ErrorCode::UnknownUser("").code());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_user_not_exist_seq_mismatch() -> common_exception::Result<()> {
let test_user_name = "test";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let mut kv = MockKV::new();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(Some(SeqV::new(1, vec![]))));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr
.get_user(
UserIdentity::new(test_user_name, test_hostname),
MatchSeq::Exact(2),
)
.await;
assert!(res.is_err());
assert_eq!(res.unwrap_err().code(), ErrorCode::UnknownUser("").code());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_user_invalid_user_info_encoding() -> common_exception::Result<()> {
let test_user_name = "test";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let mut kv = MockKV::new();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(Some(SeqV::new(1, vec![]))));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.get_user(
UserIdentity::new(test_user_name, test_hostname),
MatchSeq::GE(0),
);
assert_eq!(
res.await.unwrap_err().code(),
ErrorCode::IllegalUserInfoFormat("").code()
);
Ok(())
}
}
mod get_users {
use common_meta_app::principal::UserInfo;
use super::*;
type FakeKeys = Vec<(String, SeqV<Vec<u8>>)>;
type UserInfos = Vec<SeqV<UserInfo>>;
fn prepare() -> common_exception::Result<(FakeKeys, UserInfos)> {
let mut names = vec![];
let mut hostnames = vec![];
let mut keys = vec![];
let mut res = vec![];
let mut user_infos = vec![];
for i in 0..9 {
let name = format!("test_user_{}", i);
names.push(name.clone());
let hostname = format!("test_hostname_{}", i);
hostnames.push(hostname.clone());
let key = format!("tenant1/{}", format_user_key(&name, &hostname));
keys.push(key);
let user_info = UserInfo::new(&name, &hostname, default_test_auth_info());
res.push((
"fake_key".to_string(),
SeqV::new(
i,
serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?,
),
));
user_infos.push(SeqV::new(i, user_info));
}
Ok((res, user_infos))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_users_normal() -> common_exception::Result<()> {
let (res, user_infos) = prepare()?;
let mut kv = MockKV::new();
{
let k = "__fd_users/tenant1";
kv.expect_prefix_list_kv()
.with(predicate::eq(k))
.times(1)
.return_once(|_p| Ok(res));
}
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.get_users();
assert_eq!(res.await?, user_infos);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_get_all_users_invalid_user_info_encoding() -> common_exception::Result<()> {
let (mut res, _user_infos) = prepare()?;
res.insert(
8,
(
"fake_key".to_string(),
SeqV::new(0, b"some arbitrary str".to_vec()),
),
);
let mut kv = MockKV::new();
{
let k = "__fd_users/tenant1";
kv.expect_prefix_list_kv()
.with(predicate::eq(k))
.times(1)
.return_once(|_p| Ok(res));
}
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.get_users();
assert_eq!(
res.await.unwrap_err().code(),
ErrorCode::IllegalUserInfoFormat("").code()
);
Ok(())
}
}
mod drop {
use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_drop_user_normal_case() -> common_exception::Result<()> {
let mut kv = MockKV::new();
let test_user = "test";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user, test_hostname))?
);
kv.expect_upsert_kv()
.with(predicate::eq(UpsertKVReq::new(
&test_key,
MatchSeq::GE(1),
Operation::Delete,
None,
)))
.times(1)
.returning(|_k| Ok(UpsertKVReply::new(Some(SeqV::new(1, vec![])), None)));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.drop_user(UserIdentity::new(test_user, test_hostname), MatchSeq::GE(1));
assert!(res.await.is_ok());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_drop_user_unknown() -> common_exception::Result<()> {
let mut kv = MockKV::new();
let test_user = "test";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user, test_hostname))?
);
kv.expect_upsert_kv()
.with(predicate::eq(UpsertKVReq::new(
&test_key,
MatchSeq::GE(1),
Operation::Delete,
None,
)))
.times(1)
.returning(|_k| Ok(UpsertKVReply::new(None, None)));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.drop_user(UserIdentity::new(test_user, test_hostname), MatchSeq::GE(1));
assert_eq!(
res.await.unwrap_err().code(),
ErrorCode::UnknownUser("").code()
);
Ok(())
}
}
mod update {
use common_meta_app::principal::AuthInfo;
use common_meta_app::principal::UserInfo;
use super::*;
fn new_test_auth_info(full: bool) -> AuthInfo {
AuthInfo::Password {
hash_value: Vec::from("test_password_new"),
hash_method: if full {
PasswordHashMethod::Sha256
} else {
PasswordHashMethod::DoubleSha1
},
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_update_user_normal_update_full() -> common_exception::Result<()> {
test_update_user_normal(true).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_update_user_normal_update_partial() -> common_exception::Result<()> {
test_update_user_normal(false).await
}
async fn test_update_user_normal(full: bool) -> common_exception::Result<()> {
let test_user_name = "name";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let test_seq = MatchSeq::GE(1);
let user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let prev_value = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
// get_kv should be called
let mut kv = MockKV::new();
{
let test_key = test_key.clone();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(Some(SeqV::new(1, prev_value))));
}
// and then, update_kv should be called
let new_user_info = UserInfo::new(test_user_name, test_hostname, new_test_auth_info(full));
let new_value_with_old_salt =
serialize_struct(&new_user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
kv.expect_upsert_kv()
.with(predicate::eq(UpsertKVReq::new(
&test_key,
MatchSeq::Exact(1),
Operation::Update(new_value_with_old_salt.clone()),
None,
)))
.times(1)
.return_once(|_| Ok(UpsertKVReply::new(None, Some(SeqV::new(1, vec![])))));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.update_user_with(user_info.identity(), test_seq, |ui: &mut UserInfo| {
ui.update_auth_option(Some(new_test_auth_info(full)), None)
});
assert!(res.await.is_ok());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_update_user_with_conflict_when_writing_back() -> common_exception::Result<()> {
let test_user_name = "name";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
// if partial update, and get_kv returns None
// update_kv should NOT be called
let mut kv = MockKV::new();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(None));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.update_user_with(
UserIdentity::new(test_user_name, test_hostname),
MatchSeq::GE(0),
|ui: &mut UserInfo| ui.update_auth_option(Some(new_test_auth_info(false)), None),
);
assert_eq!(
res.await.unwrap_err().code(),
ErrorCode::UnknownUser("").code()
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_update_user_with_complete() -> common_exception::Result<()> {
let test_user_name = "name";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let prev_value = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
// - get_kv should be called
let mut kv = MockKV::new();
{
let test_key = test_key.clone();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(Some(SeqV::new(2, prev_value))));
}
// upsert should be called
kv.expect_upsert_kv()
.with(predicate::function(move |act: &UpsertKVReq| {
act.key == test_key.as_str() && act.seq == MatchSeq::Exact(2)
}))
.times(1)
.returning(|_| Ok(UpsertKVReply::new(None, None)));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let _ = user_mgr
.update_user_with(user_info.identity(), MatchSeq::GE(1), |_x| {})
.await;
Ok(())
}
}
mod set_user_privileges {
use common_meta_app::principal::GrantObject;
use common_meta_app::principal::UserInfo;
use common_meta_app::principal::UserPrivilegeSet;
use common_meta_app::principal::UserPrivilegeType;
use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_grant_user_privileges() -> common_exception::Result<()> {
let test_user_name = "name";
let test_hostname = "localhost";
let test_key = format!(
"__fd_users/tenant1/{}",
escape_for_key(&format_user_key(test_user_name, test_hostname))?
);
let mut user_info = UserInfo::new(test_user_name, test_hostname, default_test_auth_info());
let prev_value = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
// - get_kv should be called
let mut kv = MockKV::new();
{
let test_key = test_key.clone();
kv.expect_get_kv()
.with(predicate::function(move |v| v == test_key.as_str()))
.times(1)
.return_once(move |_k| Ok(Some(SeqV::new(1, prev_value))));
}
// - update_kv should be called
let mut privileges = UserPrivilegeSet::empty();
privileges.set_privilege(UserPrivilegeType::Select);
user_info
.grants
.grant_privileges(&GrantObject::Global, privileges);
let new_value = serialize_struct(&user_info, ErrorCode::IllegalUserInfoFormat, || "")?;
kv.expect_upsert_kv()
.with(predicate::eq(UpsertKVReq::new(
&test_key,
MatchSeq::Exact(1),
Operation::Update(new_value),
None,
)))
.times(1)
.return_once(|_| Ok(UpsertKVReply::new(None, Some(SeqV::new(1, vec![])))));
let kv = Arc::new(kv);
let user_mgr = UserMgr::create(kv, "tenant1")?;
let res = user_mgr.update_user_with(
user_info.identity(),
MatchSeq::GE(1),
|ui: &mut UserInfo| ui.grants.grant_privileges(&GrantObject::Global, privileges),
);
assert!(res.await.is_ok());
Ok(())
}
}
|
use anyhow::{anyhow, Context, Result};
use chrono::prelude::*;
use chrono::{DateTime, Utc};
use mysql_async::prelude::*;
use rand::Rng;
use uuid::Uuid;
pub async fn test_rw(opts: mysql_async::OptsBuilder, now: DateTime<Utc>) -> Result<String> {
let mut conn = mysql_async::Conn::new(opts).await?;
// create table
r#"CREATE TABLE IF NOT EXISTS dbpulse_rw (
id INT NOT NULL,
t1 INT(11) NOT NULL ,
t2 TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
uuid CHAR(36) CHARACTER SET ascii,
UNIQUE KEY(uuid),
PRIMARY KEY(id)
) ENGINE=InnoDB"#
.ignore(&mut conn)
.await?;
// write into table
let num: u32 = rand::thread_rng().gen_range(0, 100);
let uuid = Uuid::new_v4();
conn.exec_drop("INSERT INTO dbpulse_rw (id, t1, uuid) VALUES (:id, :t1, :uuid) ON DUPLICATE KEY UPDATE t1=:t1, uuid=:uuid", params! {
"id" => num,
"t1" => now.timestamp(),
"uuid" => uuid.to_string(),
}).await?;
// check if stored record matches
let row: Option<(i64, String)> = conn
.exec_first(
"SELECT t1, uuid FROM dbpulse_rw Where id=:id",
params! {
"id" => num,
},
)
.await?;
let (t1, v4) = row.context("Expected records")?;
if now.timestamp() != t1 || uuid.to_string() != v4 {
return Err(anyhow!(
"Records don't match: {}",
format!("({}, {}) != ({},{})", now, uuid, t1, v4)
));
}
// check transaction setting all records to 0
let mut tx = conn
.start_transaction(mysql_async::TxOpts::default())
.await?;
tx.exec_drop(
"UPDATE dbpulse_rw SET t1=:t1",
params! {
"t1" => "0"
},
)
.await?;
let rows = tx.exec("SELECT t1 FROM dbpulse_rw", ()).await?;
for row in rows {
let row = mysql_async::from_row::<u64>(row);
if row != 0 {
return Err(anyhow!(
"Records don't match: {}",
format!("{} != {}", row, 0)
));
}
}
tx.rollback().await?;
// update record 1 with now
let mut tx = conn
.start_transaction(mysql_async::TxOpts::default())
.await?;
tx.exec_drop(
"INSERT INTO dbpulse_rw (id, t1, uuid) VALUES (0, :t1, UUID()) ON DUPLICATE KEY UPDATE t1=:t1",
params!{
"t1" => now.timestamp()
},
).await?;
tx.commit().await?;
// drop table randomly
if now.minute() == num {
conn.query_drop("DROP TABLE dbpulse_rw").await?;
}
// get db version
let version: Option<String> = conn.query_first("SELECT VERSION()").await?;
drop(conn);
Ok(version.context("Expected version")?)
}
|
use std::io;
use std::io::prelude::*;
use std::collections::{HashMap, HashSet};
fn main() {
let stdin = io::stdin();
let input = stdin.lock().lines().map(|line| line.unwrap()).collect::<Vec<String>>();
let mut orbits: HashMap<String, Vec<String>> = HashMap::new();
for line in input {
let line: Vec<_> = line.split(')').collect();
let a = line[0].to_string();
let b = line[1].to_string();
orbits.entry(a).or_insert_with(Vec::new).push(b);
}
let mut part1 = 0;
let mut nodes: Vec<(&str, usize, Vec<&str>)> = vec![("COM", 0, vec!["COM"])];
let mut san: HashSet<&str> = HashSet::new();
let mut you: HashSet<&str> = HashSet::new();
while !nodes.is_empty() {
let (current, depth, ref path) = nodes.pop().unwrap();
part1 += depth;
if let Some(list) = orbits.get(current) {
for i in list {
match i.as_ref() {
"YOU" => you = path.iter().copied().collect::<HashSet<_>>(),
"SAN" => san = path.iter().copied().collect::<HashSet<_>>(),
_ => ()
};
let mut newpath = path.clone();
newpath.push(i);
nodes.push((i, depth + 1, newpath));
}
}
}
println!("Part 1: {}", part1);
let part2 = you.symmetric_difference(&san).count();
println!("Part 2: {}", part2);
}
|
use std::{net::IpAddr, str::FromStr};
use crate::{InputType, InputValueError};
pub fn ip<T: AsRef<str> + InputType>(value: &T) -> Result<(), InputValueError<T>> {
if IpAddr::from_str(value.as_ref()).is_ok() {
Ok(())
} else {
Err("invalid ip".into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ip() {
assert!(ip(&"1.1.1.1".to_string()).is_ok());
assert!(ip(&"255.0.0.0".to_string()).is_ok());
assert!(ip(&"256.1.1.1".to_string()).is_err());
assert!(ip(&"fe80::223:6cff:fe8a:2e8a".to_string()).is_ok());
assert!(ip(&"::ffff:254.42.16.14".to_string()).is_ok());
assert!(ip(&"2a02::223:6cff :fe8a:2e8a".to_string()).is_err());
}
}
|
use text_grid::{Cell, CellSource, CellStyle, CellsFormatter, CellsSource, HorizontalAlignment};
#[test]
fn impl_cell() {
struct X(String);
impl CellSource for X {
fn fmt(&self, s: &mut String) {
s.push_str(&self.0);
}
fn style(&self) -> CellStyle {
CellStyle::new().align_h(HorizontalAlignment::Right)
}
}
impl CellsSource for X {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.content(|x| Cell::new(*x));
}
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/// jemalloc allocator.
#[derive(Debug, Clone, Copy, Default)]
pub struct JEAllocator;
impl JEAllocator {
pub fn name() -> String {
"jemalloc".to_string()
}
pub fn conf() -> String {
tikv_jemalloc_ctl::config::malloc_conf::mib()
.and_then(|mib| mib.read().map(|v| v.to_owned()))
.unwrap_or_else(|e| format!("N/A: failed to read jemalloc config, {}", e))
}
}
#[cfg(target_os = "linux")]
pub mod linux {
use std::alloc::AllocError;
use std::alloc::Allocator;
use std::alloc::Layout;
use std::ptr::NonNull;
use libc::c_int;
use libc::c_void;
use tikv_jemalloc_sys as ffi;
use super::JEAllocator;
use crate::runtime::ThreadTracker;
#[cfg(all(any(
target_arch = "arm",
target_arch = "mips",
target_arch = "mipsel",
target_arch = "powerpc"
)))]
const ALIGNOF_MAX_ALIGN_T: usize = 8;
#[cfg(all(any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "powerpc64",
target_arch = "powerpc64le",
target_arch = "mips64",
target_arch = "riscv64",
target_arch = "s390x",
target_arch = "sparc64"
)))]
const ALIGNOF_MAX_ALIGN_T: usize = 16;
/// If `align` is less than `_Alignof(max_align_t)`, and if the requested
/// allocation `size` is larger than the alignment, we are guaranteed to get a
/// suitably aligned allocation by default, without passing extra flags, and
/// this function returns `0`.
///
/// Otherwise, it returns the alignment flag to pass to the jemalloc APIs.
fn layout_to_flags(align: usize, size: usize) -> c_int {
if align <= ALIGNOF_MAX_ALIGN_T && align <= size {
0
} else {
ffi::MALLOCX_ALIGN(align)
}
}
unsafe impl Allocator for JEAllocator {
#[inline(always)]
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
ThreadTracker::alloc(layout.size() as i64)?;
let data_address = if layout.size() == 0 {
unsafe { NonNull::new(layout.align() as *mut ()).unwrap_unchecked() }
} else {
let flags = layout_to_flags(layout.align(), layout.size());
unsafe {
NonNull::new(ffi::mallocx(layout.size(), flags) as *mut ()).ok_or(AllocError)?
}
};
Ok(NonNull::<[u8]>::from_raw_parts(data_address, layout.size()))
}
#[inline(always)]
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
ThreadTracker::alloc(layout.size() as i64)?;
let data_address = if layout.size() == 0 {
unsafe { NonNull::new(layout.align() as *mut ()).unwrap_unchecked() }
} else {
let flags = layout_to_flags(layout.align(), layout.size()) | ffi::MALLOCX_ZERO;
unsafe {
NonNull::new(ffi::mallocx(layout.size(), flags) as *mut ()).ok_or(AllocError)?
}
};
Ok(NonNull::<[u8]>::from_raw_parts(data_address, layout.size()))
}
#[inline(always)]
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
ThreadTracker::dealloc(layout.size() as i64);
if layout.size() == 0 {
debug_assert_eq!(ptr.as_ptr() as usize, layout.align());
} else {
let flags = layout_to_flags(layout.align(), layout.size());
ffi::sdallocx(ptr.as_ptr() as *mut _, layout.size(), flags);
}
}
unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
debug_assert_eq!(old_layout.align(), new_layout.align());
debug_assert!(old_layout.size() <= new_layout.size());
ThreadTracker::dealloc(old_layout.size() as i64);
ThreadTracker::alloc(new_layout.size() as i64)?;
let data_address = if new_layout.size() == 0 {
NonNull::new(new_layout.align() as *mut ()).unwrap_unchecked()
} else if old_layout.size() == 0 {
let flags = layout_to_flags(new_layout.align(), new_layout.size());
NonNull::new(ffi::mallocx(new_layout.size(), flags) as *mut ()).ok_or(AllocError)?
} else {
let flags = layout_to_flags(new_layout.align(), new_layout.size());
NonNull::new(ffi::rallocx(ptr.cast().as_ptr(), new_layout.size(), flags) as *mut ())
.unwrap()
};
Ok(NonNull::<[u8]>::from_raw_parts(
data_address,
new_layout.size(),
))
}
unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
debug_assert_eq!(old_layout.align(), new_layout.align());
debug_assert!(old_layout.size() <= new_layout.size());
ThreadTracker::dealloc(old_layout.size() as i64);
ThreadTracker::alloc(new_layout.size() as i64)?;
let data_address = if new_layout.size() == 0 {
NonNull::new(new_layout.align() as *mut ()).unwrap_unchecked()
} else if old_layout.size() == 0 {
let flags =
layout_to_flags(new_layout.align(), new_layout.size()) | ffi::MALLOCX_ZERO;
NonNull::new(ffi::mallocx(new_layout.size(), flags) as *mut ()).ok_or(AllocError)?
} else {
let flags = layout_to_flags(new_layout.align(), new_layout.size());
// Jemalloc doesn't support `grow_zeroed`, so it might be better to use
// mmap allocator for large frequent memory allocation and take jemalloc
// as fallback.
let raw = ffi::rallocx(ptr.cast().as_ptr(), new_layout.size(), flags) as *mut u8;
raw.add(old_layout.size())
.write_bytes(0, new_layout.size() - old_layout.size());
NonNull::new(raw as *mut ()).unwrap()
};
Ok(NonNull::<[u8]>::from_raw_parts(
data_address,
new_layout.size(),
))
}
unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
debug_assert_eq!(old_layout.align(), new_layout.align());
debug_assert!(old_layout.size() >= new_layout.size());
ThreadTracker::dealloc(old_layout.size() as i64);
ThreadTracker::alloc(new_layout.size() as i64)?;
if old_layout.size() == 0 {
debug_assert_eq!(ptr.as_ptr() as usize, old_layout.align());
let slice = std::slice::from_raw_parts_mut(ptr.as_ptr(), 0);
let ptr = NonNull::new(slice).unwrap_unchecked();
return Ok(ptr);
}
let flags = layout_to_flags(new_layout.align(), new_layout.size());
let new_ptr = if new_layout.size() == 0 {
ffi::sdallocx(ptr.as_ptr() as *mut c_void, new_layout.size(), flags);
let slice = std::slice::from_raw_parts_mut(new_layout.align() as *mut u8, 0);
NonNull::new(slice).unwrap_unchecked()
} else {
let data_address =
ffi::rallocx(ptr.cast().as_ptr(), new_layout.size(), flags) as *mut u8;
let metadata = new_layout.size();
let slice = std::slice::from_raw_parts_mut(data_address, metadata);
NonNull::new(slice).ok_or(AllocError)?
};
Ok(new_ptr)
}
}
}
/// Other target fallback to std allocator.
#[cfg(not(target_os = "linux"))]
pub mod not_linux {
use std::alloc::AllocError;
use std::alloc::Allocator;
use std::alloc::Layout;
use std::ptr::NonNull;
use super::JEAllocator;
use crate::mem_allocator::StdAllocator;
unsafe impl Allocator for JEAllocator {
#[inline(always)]
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
StdAllocator.allocate(layout)
}
#[inline(always)]
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
StdAllocator.allocate_zeroed(layout)
}
#[inline(always)]
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
StdAllocator.deallocate(ptr, layout)
}
unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
StdAllocator.grow(ptr, old_layout, new_layout)
}
unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
StdAllocator.grow_zeroed(ptr, old_layout, new_layout)
}
unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
StdAllocator.shrink(ptr, old_layout, new_layout)
}
}
}
|
macro_rules! future_err {
($e:expr) => {
Box::new(futures::future::err($e))
};
}
macro_rules! stream_err {
($e:expr) => {
Box::new(futures::stream::once(Err($e)))
};
}
macro_rules! apikey_required {
($m:expr) => {
if let crate::auth::Credentials::Token(_) = $m.credentials {
return future_err!(crate::error::apikey_required());
}
};
}
macro_rules! token_required {
($m:expr) => {
if let crate::auth::Credentials::ApiKey(_) = $m.credentials {
return future_err!(crate::error::token_required());
}
};
(s $m:expr) => {
if let crate::auth::Credentials::ApiKey(_) = $m.credentials {
return stream_err!(crate::error::token_required());
}
};
}
macro_rules! option {
($(#[$outer:meta])* $name:ident) => {
option!($(#[$outer])* $name: Into<String>);
};
($(#[$outer:meta])* $name:ident: Into<$T:ty>) => {
$(#[$outer])*
pub fn $name<T: Into<$T>>(self, value: T) -> Self {
Self {
$name: Some(value.into()),
..self
}
}
};
($(#[$outer:meta])* $name:ident: $T:ty) => {
$(#[$outer])*
pub fn $name(self, value: $T) -> Self {
Self {
$name: Some(value),
..self
}
}
};
($(#[$outer:meta])* $name:ident >> $param:expr) => {
$(#[$outer])*
pub fn $name<S: Into<String>>(self, value: S) -> Self {
let mut params = self.params;
params.insert($param, value.into());
Self { params }
}
};
($(#[$outer:meta])* $name:ident: Into<$T:ty> >> $param:expr) => {
$(#[$outer])*
pub fn $name<T: Into<$T>>(self, value: T) -> Self {
let mut params = self.params;
params.insert($param, value.into().to_string());
Self { params }
}
};
($(#[$outer:meta])* $name:ident: $T:ty >> $param:expr) => {
$(#[$outer])*
pub fn $name(self, value: $T) -> Self {
let mut params = self.params;
params.insert($param, value.to_string());
Self { params }
}
};
}
|
use crate::{osm, LaneType};
use serde_derive::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::iter;
// (original direction, reversed direction)
pub fn get_lane_types(osm_tags: &BTreeMap<String, String>) -> (Vec<LaneType>, Vec<LaneType>) {
if let Some(s) = osm_tags.get(osm::SYNTHETIC_LANES) {
if let Some(spec) = RoadSpec::parse(s.to_string()) {
return (spec.fwd, spec.back);
} else {
panic!("Bad {} RoadSpec: {}", osm::SYNTHETIC_LANES, s);
}
}
let parking_lane_fwd = osm_tags.get(osm::PARKING_LANE_FWD) == Some(&"true".to_string());
let parking_lane_back = osm_tags.get(osm::PARKING_LANE_BACK) == Some(&"true".to_string());
// Easy special cases first.
if osm_tags.get("junction") == Some(&"roundabout".to_string()) {
return (vec![LaneType::Driving, LaneType::Sidewalk], Vec::new());
}
if osm_tags.get(osm::HIGHWAY) == Some(&"footway".to_string()) {
return (vec![LaneType::Sidewalk], Vec::new());
}
// TODO Reversible roads should be handled differently?
let oneway = osm_tags.get("oneway") == Some(&"yes".to_string())
|| osm_tags.get("oneway") == Some(&"reversible".to_string());
// How many driving lanes in each direction?
let num_driving_fwd = if let Some(n) = osm_tags
.get("lanes:forward")
.and_then(|num| num.parse::<usize>().ok())
{
n
} else if let Some(n) = osm_tags
.get("lanes")
.and_then(|num| num.parse::<usize>().ok())
{
if oneway {
n
} else if n % 2 == 0 {
n / 2
} else {
// TODO Really, this is ambiguous, but...
(n / 2).max(1)
}
} else {
// TODO Grrr.
1
};
let num_driving_back = if let Some(n) = osm_tags
.get("lanes:backward")
.and_then(|num| num.parse::<usize>().ok())
{
n
} else if let Some(n) = osm_tags
.get("lanes")
.and_then(|num| num.parse::<usize>().ok())
{
if oneway {
0
} else if n % 2 == 0 {
n / 2
} else {
// TODO Really, this is ambiguous, but...
(n / 2).max(1)
}
} else {
// TODO Grrr.
if oneway {
0
} else {
1
}
};
let mut fwd_side: Vec<LaneType> = iter::repeat(LaneType::Driving)
.take(num_driving_fwd)
.collect();
let mut back_side: Vec<LaneType> = iter::repeat(LaneType::Driving)
.take(num_driving_back)
.collect();
// TODO Handle bus lanes properly.
let has_bus_lane = osm_tags.contains_key("bus:lanes");
if has_bus_lane {
fwd_side.pop();
fwd_side.push(LaneType::Bus);
if !back_side.is_empty() {
back_side.pop();
back_side.push(LaneType::Bus);
}
}
let has_bike_lane = osm_tags.get("cycleway") == Some(&"lane".to_string());
if has_bike_lane {
fwd_side.push(LaneType::Biking);
if !back_side.is_empty() {
back_side.push(LaneType::Biking);
}
}
// TODO Should we warn when a link road has parking assigned to it from the blockface?
let is_link = match osm_tags.get(osm::HIGHWAY) {
Some(hwy) => hwy.ends_with("_link"),
None => false,
};
if parking_lane_fwd && !is_link {
fwd_side.push(LaneType::Parking);
}
if parking_lane_back && !is_link && !back_side.is_empty() {
back_side.push(LaneType::Parking);
}
let has_sidewalk = osm_tags.get(osm::HIGHWAY) != Some(&"motorway".to_string())
&& osm_tags.get(osm::HIGHWAY) != Some(&"motorway_link".to_string());
if has_sidewalk {
fwd_side.push(LaneType::Sidewalk);
if oneway {
// Only residential streets have a sidewalk on the other side of a one-way.
if osm_tags.get(osm::HIGHWAY) == Some(&"residential".to_string())
|| osm_tags.get("sidewalk") == Some(&"both".to_string())
{
back_side.push(LaneType::Sidewalk);
}
} else {
back_side.push(LaneType::Sidewalk);
}
}
(fwd_side, back_side)
}
// This is a convenient way for the synthetic map editor to plumb instructions here.
#[derive(Serialize, Deserialize)]
pub struct RoadSpec {
pub fwd: Vec<LaneType>,
pub back: Vec<LaneType>,
}
impl RoadSpec {
pub fn to_string(&self) -> String {
let mut s: Vec<char> = Vec::new();
for lt in &self.fwd {
s.push(RoadSpec::lt_to_char(*lt));
}
s.push('/');
for lt in &self.back {
s.push(RoadSpec::lt_to_char(*lt));
}
s.into_iter().collect()
}
pub fn parse(s: String) -> Option<RoadSpec> {
let mut fwd: Vec<LaneType> = Vec::new();
let mut back: Vec<LaneType> = Vec::new();
let mut seen_slash = false;
for c in s.chars() {
if !seen_slash && c == '/' {
seen_slash = true;
} else if let Some(lt) = RoadSpec::char_to_lt(c) {
if seen_slash {
back.push(lt);
} else {
fwd.push(lt);
}
} else {
return None;
}
}
if seen_slash && (fwd.len() + back.len()) > 0 {
Some(RoadSpec { fwd, back })
} else {
None
}
}
fn lt_to_char(lt: LaneType) -> char {
match lt {
LaneType::Driving => 'd',
LaneType::Parking => 'p',
LaneType::Sidewalk => 's',
LaneType::Biking => 'b',
LaneType::Bus => 'u',
}
}
fn char_to_lt(c: char) -> Option<LaneType> {
match c {
'd' => Some(LaneType::Driving),
'p' => Some(LaneType::Parking),
's' => Some(LaneType::Sidewalk),
'b' => Some(LaneType::Biking),
'u' => Some(LaneType::Bus),
_ => None,
}
}
}
|
# ! [ doc = "Serial peripheral interface" ]
# [ doc = r" Register block" ]
# [ repr ( C ) ]
pub struct Spi {
# [ doc = "0x00 - control register 1" ]
pub cr1: Cr1,
# [ doc = "0x04 - control register 2" ]
pub cr2: Cr2,
# [ doc = "0x08 - status register" ]
pub sr: Sr,
# [ doc = "0x0c - data register" ]
pub dr: Dr,
# [ doc = "0x10 - CRC polynomial register" ]
pub crcpr: Crcpr,
# [ doc = "0x14 - RX CRC register" ]
pub rxcrcr: Rxcrcr,
# [ doc = "0x18 - TX CRC register" ]
pub txcrcr: Txcrcr,
# [ doc = "0x1c - I2S configuration register" ]
pub i2scfgr: I2scfgr,
# [ doc = "0x20 - I2S prescaler register" ]
pub i2spr: I2spr,
}
# [ doc = "control register 1" ]
# [ repr ( C ) ]
pub struct Cr1 {
register: ::volatile_register::RW<u32>,
}
# [ doc = "control register 1" ]
pub mod cr1 {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::Cr1 {
# [ doc = r" Modifies the contents of the register" ]
pub fn modify<F>(&mut self, f: F)
where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W
{
let bits = self.register.read();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.write(w.bits);
}
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
# [ doc = r" Writes to the register" ]
pub fn write<F>(&mut self, f: F)
where F: FnOnce(&mut W) -> &mut W
{
let mut w = W::reset_value();
f(&mut w);
self.register.write(w.bits);
}
}
# [ doc = "Value of the field BIDIMODE" ]
pub struct BidimodeR {
bits: u8,
}
impl BidimodeR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field BIDIOE" ]
pub struct BidioeR {
bits: u8,
}
impl BidioeR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CRCEN" ]
pub struct CrcenR {
bits: u8,
}
impl CrcenR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CRCNEXT" ]
pub struct CrcnextR {
bits: u8,
}
impl CrcnextR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field DFF" ]
pub struct DffR {
bits: u8,
}
impl DffR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field RXONLY" ]
pub struct RxonlyR {
bits: u8,
}
impl RxonlyR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field SSM" ]
pub struct SsmR {
bits: u8,
}
impl SsmR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field SSI" ]
pub struct SsiR {
bits: u8,
}
impl SsiR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field LSBFIRST" ]
pub struct LsbfirstR {
bits: u8,
}
impl LsbfirstR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field SPE" ]
pub struct SpeR {
bits: u8,
}
impl SpeR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field BR" ]
pub struct BrR {
bits: u8,
}
impl BrR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field MSTR" ]
pub struct MstrR {
bits: u8,
}
impl MstrR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CPOL" ]
pub struct CpolR {
bits: u8,
}
impl CpolR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CPHA" ]
pub struct CphaR {
bits: u8,
}
impl CphaR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = r" Proxy" ]
pub struct _BidimodeW<'a> {
register: &'a mut W,
}
impl<'a> _BidimodeW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 15;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _BidioeW<'a> {
register: &'a mut W,
}
impl<'a> _BidioeW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 14;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _CrcenW<'a> {
register: &'a mut W,
}
impl<'a> _CrcenW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 13;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _CrcnextW<'a> {
register: &'a mut W,
}
impl<'a> _CrcnextW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 12;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _DffW<'a> {
register: &'a mut W,
}
impl<'a> _DffW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 11;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _RxonlyW<'a> {
register: &'a mut W,
}
impl<'a> _RxonlyW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 10;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _SsmW<'a> {
register: &'a mut W,
}
impl<'a> _SsmW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 9;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _SsiW<'a> {
register: &'a mut W,
}
impl<'a> _SsiW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 8;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _LsbfirstW<'a> {
register: &'a mut W,
}
impl<'a> _LsbfirstW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _SpeW<'a> {
register: &'a mut W,
}
impl<'a> _SpeW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 6;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _BrW<'a> {
register: &'a mut W,
}
impl<'a> _BrW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 3;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _MstrW<'a> {
register: &'a mut W,
}
impl<'a> _MstrW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 2;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _CpolW<'a> {
register: &'a mut W,
}
impl<'a> _CpolW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 1;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _CphaW<'a> {
register: &'a mut W,
}
impl<'a> _CphaW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 0;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _bidimode(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 15;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 15 - Bidirectional data mode enable" ]
pub fn bidimode(&self) -> BidimodeR {
BidimodeR { bits: self._bidimode() }
}
fn _bidioe(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 14 - Output enable in bidirectional mode" ]
pub fn bidioe(&self) -> BidioeR {
BidioeR { bits: self._bidioe() }
}
fn _crcen(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 13;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 13 - Hardware CRC calculation enable" ]
pub fn crcen(&self) -> CrcenR {
CrcenR { bits: self._crcen() }
}
fn _crcnext(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 12 - CRC transfer next" ]
pub fn crcnext(&self) -> CrcnextR {
CrcnextR { bits: self._crcnext() }
}
fn _dff(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 11 - Data frame format" ]
pub fn dff(&self) -> DffR {
DffR { bits: self._dff() }
}
fn _rxonly(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 10 - Receive only" ]
pub fn rxonly(&self) -> RxonlyR {
RxonlyR { bits: self._rxonly() }
}
fn _ssm(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 9 - Software slave management" ]
pub fn ssm(&self) -> SsmR {
SsmR { bits: self._ssm() }
}
fn _ssi(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 8 - Internal slave select" ]
pub fn ssi(&self) -> SsiR {
SsiR { bits: self._ssi() }
}
fn _lsbfirst(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 7 - Frame format" ]
pub fn lsbfirst(&self) -> LsbfirstR {
LsbfirstR { bits: self._lsbfirst() }
}
fn _spe(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 6 - SPI enable" ]
pub fn spe(&self) -> SpeR {
SpeR { bits: self._spe() }
}
fn _br(&self) -> u8 {
const MASK: u8 = 7;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 3:5 - Baud rate control" ]
pub fn br(&self) -> BrR {
BrR { bits: self._br() }
}
fn _mstr(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 2 - Master selection" ]
pub fn mstr(&self) -> MstrR {
MstrR { bits: self._mstr() }
}
fn _cpol(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 1 - Clock polarity" ]
pub fn cpol(&self) -> CpolR {
CpolR { bits: self._cpol() }
}
fn _cpha(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 0 - Clock phase" ]
pub fn cpha(&self) -> CphaR {
CphaR { bits: self._cpha() }
}
}
impl W {
# [ doc = r" Reset value of the register" ]
pub fn reset_value() -> W {
W { bits: 0 }
}
# [ doc = r" Writes raw `bits` to the register" ]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
# [ doc = "Bit 15 - Bidirectional data mode enable" ]
pub fn bidimode(&mut self) -> _BidimodeW {
_BidimodeW { register: self }
}
# [ doc = "Bit 14 - Output enable in bidirectional mode" ]
pub fn bidioe(&mut self) -> _BidioeW {
_BidioeW { register: self }
}
# [ doc = "Bit 13 - Hardware CRC calculation enable" ]
pub fn crcen(&mut self) -> _CrcenW {
_CrcenW { register: self }
}
# [ doc = "Bit 12 - CRC transfer next" ]
pub fn crcnext(&mut self) -> _CrcnextW {
_CrcnextW { register: self }
}
# [ doc = "Bit 11 - Data frame format" ]
pub fn dff(&mut self) -> _DffW {
_DffW { register: self }
}
# [ doc = "Bit 10 - Receive only" ]
pub fn rxonly(&mut self) -> _RxonlyW {
_RxonlyW { register: self }
}
# [ doc = "Bit 9 - Software slave management" ]
pub fn ssm(&mut self) -> _SsmW {
_SsmW { register: self }
}
# [ doc = "Bit 8 - Internal slave select" ]
pub fn ssi(&mut self) -> _SsiW {
_SsiW { register: self }
}
# [ doc = "Bit 7 - Frame format" ]
pub fn lsbfirst(&mut self) -> _LsbfirstW {
_LsbfirstW { register: self }
}
# [ doc = "Bit 6 - SPI enable" ]
pub fn spe(&mut self) -> _SpeW {
_SpeW { register: self }
}
# [ doc = "Bits 3:5 - Baud rate control" ]
pub fn br(&mut self) -> _BrW {
_BrW { register: self }
}
# [ doc = "Bit 2 - Master selection" ]
pub fn mstr(&mut self) -> _MstrW {
_MstrW { register: self }
}
# [ doc = "Bit 1 - Clock polarity" ]
pub fn cpol(&mut self) -> _CpolW {
_CpolW { register: self }
}
# [ doc = "Bit 0 - Clock phase" ]
pub fn cpha(&mut self) -> _CphaW {
_CphaW { register: self }
}
}
}
# [ doc = "control register 2" ]
# [ repr ( C ) ]
pub struct Cr2 {
register: ::volatile_register::RW<u32>,
}
# [ doc = "control register 2" ]
pub mod cr2 {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::Cr2 {
# [ doc = r" Modifies the contents of the register" ]
pub fn modify<F>(&mut self, f: F)
where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W
{
let bits = self.register.read();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.write(w.bits);
}
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
# [ doc = r" Writes to the register" ]
pub fn write<F>(&mut self, f: F)
where F: FnOnce(&mut W) -> &mut W
{
let mut w = W::reset_value();
f(&mut w);
self.register.write(w.bits);
}
}
# [ doc = "Value of the field RXDMAEN" ]
pub struct RxdmaenR {
bits: u8,
}
impl RxdmaenR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field TXDMAEN" ]
pub struct TxdmaenR {
bits: u8,
}
impl TxdmaenR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field SSOE" ]
pub struct SsoeR {
bits: u8,
}
impl SsoeR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field NSSP" ]
pub struct NsspR {
bits: u8,
}
impl NsspR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field FRF" ]
pub struct FrfR {
bits: u8,
}
impl FrfR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field ERRIE" ]
pub struct ErrieR {
bits: u8,
}
impl ErrieR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field RXNEIE" ]
pub struct RxneieR {
bits: u8,
}
impl RxneieR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field TXEIE" ]
pub struct TxeieR {
bits: u8,
}
impl TxeieR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field DS" ]
pub struct DsR {
bits: u8,
}
impl DsR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field FRXTH" ]
pub struct FrxthR {
bits: u8,
}
impl FrxthR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field LDMA_RX" ]
pub struct LdmaRxR {
bits: u8,
}
impl LdmaRxR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field LDMA_TX" ]
pub struct LdmaTxR {
bits: u8,
}
impl LdmaTxR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = r" Proxy" ]
pub struct _RxdmaenW<'a> {
register: &'a mut W,
}
impl<'a> _RxdmaenW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 0;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _TxdmaenW<'a> {
register: &'a mut W,
}
impl<'a> _TxdmaenW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 1;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _SsoeW<'a> {
register: &'a mut W,
}
impl<'a> _SsoeW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 2;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _NsspW<'a> {
register: &'a mut W,
}
impl<'a> _NsspW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 3;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _FrfW<'a> {
register: &'a mut W,
}
impl<'a> _FrfW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 4;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _ErrieW<'a> {
register: &'a mut W,
}
impl<'a> _ErrieW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 5;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _RxneieW<'a> {
register: &'a mut W,
}
impl<'a> _RxneieW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 6;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _TxeieW<'a> {
register: &'a mut W,
}
impl<'a> _TxeieW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _DsW<'a> {
register: &'a mut W,
}
impl<'a> _DsW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 8;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _FrxthW<'a> {
register: &'a mut W,
}
impl<'a> _FrxthW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 12;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _LdmaRxW<'a> {
register: &'a mut W,
}
impl<'a> _LdmaRxW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 13;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _LdmaTxW<'a> {
register: &'a mut W,
}
impl<'a> _LdmaTxW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 14;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _rxdmaen(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 0 - Rx buffer DMA enable" ]
pub fn rxdmaen(&self) -> RxdmaenR {
RxdmaenR { bits: self._rxdmaen() }
}
fn _txdmaen(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 1 - Tx buffer DMA enable" ]
pub fn txdmaen(&self) -> TxdmaenR {
TxdmaenR { bits: self._txdmaen() }
}
fn _ssoe(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 2 - SS output enable" ]
pub fn ssoe(&self) -> SsoeR {
SsoeR { bits: self._ssoe() }
}
fn _nssp(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 3 - NSS pulse management" ]
pub fn nssp(&self) -> NsspR {
NsspR { bits: self._nssp() }
}
fn _frf(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 4 - Frame format" ]
pub fn frf(&self) -> FrfR {
FrfR { bits: self._frf() }
}
fn _errie(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 5 - Error interrupt enable" ]
pub fn errie(&self) -> ErrieR {
ErrieR { bits: self._errie() }
}
fn _rxneie(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 6 - RX buffer not empty interrupt enable" ]
pub fn rxneie(&self) -> RxneieR {
RxneieR { bits: self._rxneie() }
}
fn _txeie(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 7 - Tx buffer empty interrupt enable" ]
pub fn txeie(&self) -> TxeieR {
TxeieR { bits: self._txeie() }
}
fn _ds(&self) -> u8 {
const MASK: u8 = 15;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 8:11 - Data size" ]
pub fn ds(&self) -> DsR {
DsR { bits: self._ds() }
}
fn _frxth(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 12 - FIFO reception threshold" ]
pub fn frxth(&self) -> FrxthR {
FrxthR { bits: self._frxth() }
}
fn _ldma_rx(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 13;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 13 - Last DMA transfer for reception" ]
pub fn ldma_rx(&self) -> LdmaRxR {
LdmaRxR { bits: self._ldma_rx() }
}
fn _ldma_tx(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 14 - Last DMA transfer for transmission" ]
pub fn ldma_tx(&self) -> LdmaTxR {
LdmaTxR { bits: self._ldma_tx() }
}
}
impl W {
# [ doc = r" Reset value of the register" ]
pub fn reset_value() -> W {
W { bits: 0 }
}
# [ doc = r" Writes raw `bits` to the register" ]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
# [ doc = "Bit 0 - Rx buffer DMA enable" ]
pub fn rxdmaen(&mut self) -> _RxdmaenW {
_RxdmaenW { register: self }
}
# [ doc = "Bit 1 - Tx buffer DMA enable" ]
pub fn txdmaen(&mut self) -> _TxdmaenW {
_TxdmaenW { register: self }
}
# [ doc = "Bit 2 - SS output enable" ]
pub fn ssoe(&mut self) -> _SsoeW {
_SsoeW { register: self }
}
# [ doc = "Bit 3 - NSS pulse management" ]
pub fn nssp(&mut self) -> _NsspW {
_NsspW { register: self }
}
# [ doc = "Bit 4 - Frame format" ]
pub fn frf(&mut self) -> _FrfW {
_FrfW { register: self }
}
# [ doc = "Bit 5 - Error interrupt enable" ]
pub fn errie(&mut self) -> _ErrieW {
_ErrieW { register: self }
}
# [ doc = "Bit 6 - RX buffer not empty interrupt enable" ]
pub fn rxneie(&mut self) -> _RxneieW {
_RxneieW { register: self }
}
# [ doc = "Bit 7 - Tx buffer empty interrupt enable" ]
pub fn txeie(&mut self) -> _TxeieW {
_TxeieW { register: self }
}
# [ doc = "Bits 8:11 - Data size" ]
pub fn ds(&mut self) -> _DsW {
_DsW { register: self }
}
# [ doc = "Bit 12 - FIFO reception threshold" ]
pub fn frxth(&mut self) -> _FrxthW {
_FrxthW { register: self }
}
# [ doc = "Bit 13 - Last DMA transfer for reception" ]
pub fn ldma_rx(&mut self) -> _LdmaRxW {
_LdmaRxW { register: self }
}
# [ doc = "Bit 14 - Last DMA transfer for transmission" ]
pub fn ldma_tx(&mut self) -> _LdmaTxW {
_LdmaTxW { register: self }
}
}
}
# [ doc = "status register" ]
# [ repr ( C ) ]
pub struct Sr {
register: ::volatile_register::RW<u32>,
}
# [ doc = "status register" ]
pub mod sr {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::Sr {
# [ doc = r" Modifies the contents of the register" ]
pub fn modify<F>(&mut self, f: F)
where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W
{
let bits = self.register.read();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.write(w.bits);
}
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
# [ doc = r" Writes to the register" ]
pub fn write<F>(&mut self, f: F)
where F: FnOnce(&mut W) -> &mut W
{
let mut w = W::reset_value();
f(&mut w);
self.register.write(w.bits);
}
}
# [ doc = "Value of the field RXNE" ]
pub struct RxneR {
bits: u8,
}
impl RxneR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field TXE" ]
pub struct TxeR {
bits: u8,
}
impl TxeR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CHSIDE" ]
pub struct ChsideR {
bits: u8,
}
impl ChsideR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field UDR" ]
pub struct UdrR {
bits: u8,
}
impl UdrR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CRCERR" ]
pub struct CrcerrR {
bits: u8,
}
impl CrcerrR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field MODF" ]
pub struct ModfR {
bits: u8,
}
impl ModfR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field OVR" ]
pub struct OvrR {
bits: u8,
}
impl OvrR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field BSY" ]
pub struct BsyR {
bits: u8,
}
impl BsyR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field TIFRFE" ]
pub struct TifrfeR {
bits: u8,
}
impl TifrfeR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field FRLVL" ]
pub struct FrlvlR {
bits: u8,
}
impl FrlvlR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field FTLVL" ]
pub struct FtlvlR {
bits: u8,
}
impl FtlvlR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = r" Proxy" ]
pub struct _CrcerrW<'a> {
register: &'a mut W,
}
impl<'a> _CrcerrW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 4;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _rxne(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 0 - Receive buffer not empty" ]
pub fn rxne(&self) -> RxneR {
RxneR { bits: self._rxne() }
}
fn _txe(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 1 - Transmit buffer empty" ]
pub fn txe(&self) -> TxeR {
TxeR { bits: self._txe() }
}
fn _chside(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 2 - Channel side" ]
pub fn chside(&self) -> ChsideR {
ChsideR { bits: self._chside() }
}
fn _udr(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 3 - Underrun flag" ]
pub fn udr(&self) -> UdrR {
UdrR { bits: self._udr() }
}
fn _crcerr(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 4 - CRC error flag" ]
pub fn crcerr(&self) -> CrcerrR {
CrcerrR { bits: self._crcerr() }
}
fn _modf(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 5 - Mode fault" ]
pub fn modf(&self) -> ModfR {
ModfR { bits: self._modf() }
}
fn _ovr(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 6 - Overrun flag" ]
pub fn ovr(&self) -> OvrR {
OvrR { bits: self._ovr() }
}
fn _bsy(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 7 - Busy flag" ]
pub fn bsy(&self) -> BsyR {
BsyR { bits: self._bsy() }
}
fn _tifrfe(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 8 - TI frame format error" ]
pub fn tifrfe(&self) -> TifrfeR {
TifrfeR { bits: self._tifrfe() }
}
fn _frlvl(&self) -> u8 {
const MASK: u8 = 3;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 9:10 - FIFO reception level" ]
pub fn frlvl(&self) -> FrlvlR {
FrlvlR { bits: self._frlvl() }
}
fn _ftlvl(&self) -> u8 {
const MASK: u8 = 3;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 11:12 - FIFO transmission level" ]
pub fn ftlvl(&self) -> FtlvlR {
FtlvlR { bits: self._ftlvl() }
}
}
impl W {
# [ doc = r" Reset value of the register" ]
pub fn reset_value() -> W {
W { bits: 2 }
}
# [ doc = r" Writes raw `bits` to the register" ]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
# [ doc = "Bit 4 - CRC error flag" ]
pub fn crcerr(&mut self) -> _CrcerrW {
_CrcerrW { register: self }
}
}
}
# [ doc = "data register" ]
# [ repr ( C ) ]
pub struct Dr {
register: ::volatile_register::RW<u32>,
}
# [ doc = "data register" ]
pub mod dr {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::Dr {
# [ doc = r" Modifies the contents of the register" ]
pub fn modify<F>(&mut self, f: F)
where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W
{
let bits = self.register.read();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.write(w.bits);
}
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
# [ doc = r" Writes to the register" ]
pub fn write<F>(&mut self, f: F)
where F: FnOnce(&mut W) -> &mut W
{
let mut w = W::reset_value();
f(&mut w);
self.register.write(w.bits);
}
}
# [ doc = "Value of the field DR" ]
pub struct DrR {
bits: u16,
}
impl DrR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u16 {
self.bits
}
}
# [ doc = r" Proxy" ]
pub struct _DrW<'a> {
register: &'a mut W,
}
impl<'a> _DrW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u16) -> &'a mut W {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _dr(&self) -> u16 {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
}
# [ doc = "Bits 0:15 - Data register" ]
pub fn dr(&self) -> DrR {
DrR { bits: self._dr() }
}
}
impl W {
# [ doc = r" Reset value of the register" ]
pub fn reset_value() -> W {
W { bits: 0 }
}
# [ doc = r" Writes raw `bits` to the register" ]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
# [ doc = "Bits 0:15 - Data register" ]
pub fn dr(&mut self) -> _DrW {
_DrW { register: self }
}
}
}
# [ doc = "CRC polynomial register" ]
# [ repr ( C ) ]
pub struct Crcpr {
register: ::volatile_register::RW<u32>,
}
# [ doc = "CRC polynomial register" ]
pub mod crcpr {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::Crcpr {
# [ doc = r" Modifies the contents of the register" ]
pub fn modify<F>(&mut self, f: F)
where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W
{
let bits = self.register.read();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.write(w.bits);
}
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
# [ doc = r" Writes to the register" ]
pub fn write<F>(&mut self, f: F)
where F: FnOnce(&mut W) -> &mut W
{
let mut w = W::reset_value();
f(&mut w);
self.register.write(w.bits);
}
}
# [ doc = "Value of the field CRCPOLY" ]
pub struct CrcpolyR {
bits: u16,
}
impl CrcpolyR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u16 {
self.bits
}
}
# [ doc = r" Proxy" ]
pub struct _CrcpolyW<'a> {
register: &'a mut W,
}
impl<'a> _CrcpolyW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u16) -> &'a mut W {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _crcpoly(&self) -> u16 {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
}
# [ doc = "Bits 0:15 - CRC polynomial register" ]
pub fn crcpoly(&self) -> CrcpolyR {
CrcpolyR { bits: self._crcpoly() }
}
}
impl W {
# [ doc = r" Reset value of the register" ]
pub fn reset_value() -> W {
W { bits: 7 }
}
# [ doc = r" Writes raw `bits` to the register" ]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
# [ doc = "Bits 0:15 - CRC polynomial register" ]
pub fn crcpoly(&mut self) -> _CrcpolyW {
_CrcpolyW { register: self }
}
}
}
# [ doc = "RX CRC register" ]
# [ repr ( C ) ]
pub struct Rxcrcr {
register: ::volatile_register::RO<u32>,
}
# [ doc = "RX CRC register" ]
pub mod rxcrcr {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
impl super::Rxcrcr {
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
}
# [ doc = "Value of the field RxCRC" ]
pub struct RxCrcR {
bits: u16,
}
impl RxCrcR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u16 {
self.bits
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _rx_crc(&self) -> u16 {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
}
# [ doc = "Bits 0:15 - Rx CRC register" ]
pub fn rx_crc(&self) -> RxCrcR {
RxCrcR { bits: self._rx_crc() }
}
}
}
# [ doc = "TX CRC register" ]
# [ repr ( C ) ]
pub struct Txcrcr {
register: ::volatile_register::RO<u32>,
}
# [ doc = "TX CRC register" ]
pub mod txcrcr {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
impl super::Txcrcr {
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
}
# [ doc = "Value of the field TxCRC" ]
pub struct TxCrcR {
bits: u16,
}
impl TxCrcR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u16 {
self.bits
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _tx_crc(&self) -> u16 {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
}
# [ doc = "Bits 0:15 - Tx CRC register" ]
pub fn tx_crc(&self) -> TxCrcR {
TxCrcR { bits: self._tx_crc() }
}
}
}
# [ doc = "I2S configuration register" ]
# [ repr ( C ) ]
pub struct I2scfgr {
register: ::volatile_register::RW<u32>,
}
# [ doc = "I2S configuration register" ]
pub mod i2scfgr {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::I2scfgr {
# [ doc = r" Modifies the contents of the register" ]
pub fn modify<F>(&mut self, f: F)
where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W
{
let bits = self.register.read();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.write(w.bits);
}
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
# [ doc = r" Writes to the register" ]
pub fn write<F>(&mut self, f: F)
where F: FnOnce(&mut W) -> &mut W
{
let mut w = W::reset_value();
f(&mut w);
self.register.write(w.bits);
}
}
# [ doc = "Value of the field I2SMOD" ]
pub struct I2smodR {
bits: u8,
}
impl I2smodR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field I2SE" ]
pub struct I2seR {
bits: u8,
}
impl I2seR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field I2SCFG" ]
pub struct I2scfgR {
bits: u8,
}
impl I2scfgR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field PCMSYNC" ]
pub struct PcmsyncR {
bits: u8,
}
impl PcmsyncR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field I2SSTD" ]
pub struct I2sstdR {
bits: u8,
}
impl I2sstdR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CKPOL" ]
pub struct CkpolR {
bits: u8,
}
impl CkpolR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field DATLEN" ]
pub struct DatlenR {
bits: u8,
}
impl DatlenR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field CHLEN" ]
pub struct ChlenR {
bits: u8,
}
impl ChlenR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = r" Proxy" ]
pub struct _I2smodW<'a> {
register: &'a mut W,
}
impl<'a> _I2smodW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 11;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _I2seW<'a> {
register: &'a mut W,
}
impl<'a> _I2seW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 10;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _I2scfgW<'a> {
register: &'a mut W,
}
impl<'a> _I2scfgW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 8;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _PcmsyncW<'a> {
register: &'a mut W,
}
impl<'a> _PcmsyncW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _I2sstdW<'a> {
register: &'a mut W,
}
impl<'a> _I2sstdW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 4;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _CkpolW<'a> {
register: &'a mut W,
}
impl<'a> _CkpolW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 3;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _DatlenW<'a> {
register: &'a mut W,
}
impl<'a> _DatlenW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 1;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _ChlenW<'a> {
register: &'a mut W,
}
impl<'a> _ChlenW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 0;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _i2smod(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 11 - I2S mode selection" ]
pub fn i2smod(&self) -> I2smodR {
I2smodR { bits: self._i2smod() }
}
fn _i2se(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 10 - I2S Enable" ]
pub fn i2se(&self) -> I2seR {
I2seR { bits: self._i2se() }
}
fn _i2scfg(&self) -> u8 {
const MASK: u8 = 3;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 8:9 - I2S configuration mode" ]
pub fn i2scfg(&self) -> I2scfgR {
I2scfgR { bits: self._i2scfg() }
}
fn _pcmsync(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 7 - PCM frame synchronization" ]
pub fn pcmsync(&self) -> PcmsyncR {
PcmsyncR { bits: self._pcmsync() }
}
fn _i2sstd(&self) -> u8 {
const MASK: u8 = 3;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 4:5 - I2S standard selection" ]
pub fn i2sstd(&self) -> I2sstdR {
I2sstdR { bits: self._i2sstd() }
}
fn _ckpol(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 3 - Steady state clock polarity" ]
pub fn ckpol(&self) -> CkpolR {
CkpolR { bits: self._ckpol() }
}
fn _datlen(&self) -> u8 {
const MASK: u8 = 3;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 1:2 - Data length to be transferred" ]
pub fn datlen(&self) -> DatlenR {
DatlenR { bits: self._datlen() }
}
fn _chlen(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 0 - Channel length (number of bits per audio channel)" ]
pub fn chlen(&self) -> ChlenR {
ChlenR { bits: self._chlen() }
}
}
impl W {
# [ doc = r" Reset value of the register" ]
pub fn reset_value() -> W {
W { bits: 0 }
}
# [ doc = r" Writes raw `bits` to the register" ]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
# [ doc = "Bit 11 - I2S mode selection" ]
pub fn i2smod(&mut self) -> _I2smodW {
_I2smodW { register: self }
}
# [ doc = "Bit 10 - I2S Enable" ]
pub fn i2se(&mut self) -> _I2seW {
_I2seW { register: self }
}
# [ doc = "Bits 8:9 - I2S configuration mode" ]
pub fn i2scfg(&mut self) -> _I2scfgW {
_I2scfgW { register: self }
}
# [ doc = "Bit 7 - PCM frame synchronization" ]
pub fn pcmsync(&mut self) -> _PcmsyncW {
_PcmsyncW { register: self }
}
# [ doc = "Bits 4:5 - I2S standard selection" ]
pub fn i2sstd(&mut self) -> _I2sstdW {
_I2sstdW { register: self }
}
# [ doc = "Bit 3 - Steady state clock polarity" ]
pub fn ckpol(&mut self) -> _CkpolW {
_CkpolW { register: self }
}
# [ doc = "Bits 1:2 - Data length to be transferred" ]
pub fn datlen(&mut self) -> _DatlenW {
_DatlenW { register: self }
}
# [ doc = "Bit 0 - Channel length (number of bits per audio channel)" ]
pub fn chlen(&mut self) -> _ChlenW {
_ChlenW { register: self }
}
}
}
# [ doc = "I2S prescaler register" ]
# [ repr ( C ) ]
pub struct I2spr {
register: ::volatile_register::RW<u32>,
}
# [ doc = "I2S prescaler register" ]
pub mod i2spr {
# [ doc = r" Value read from the register" ]
pub struct R {
bits: u32,
}
# [ doc = r" Value to write to the register" ]
pub struct W {
bits: u32,
}
impl super::I2spr {
# [ doc = r" Modifies the contents of the register" ]
pub fn modify<F>(&mut self, f: F)
where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W
{
let bits = self.register.read();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.write(w.bits);
}
# [ doc = r" Reads the contents of the register" ]
pub fn read(&self) -> R {
R { bits: self.register.read() }
}
# [ doc = r" Writes to the register" ]
pub fn write<F>(&mut self, f: F)
where F: FnOnce(&mut W) -> &mut W
{
let mut w = W::reset_value();
f(&mut w);
self.register.write(w.bits);
}
}
# [ doc = "Value of the field MCKOE" ]
pub struct MckoeR {
bits: u8,
}
impl MckoeR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field ODD" ]
pub struct OddR {
bits: u8,
}
impl OddR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = "Value of the field I2SDIV" ]
pub struct I2sdivR {
bits: u8,
}
impl I2sdivR {
# [ doc = r" Value of the field as raw bits" ]
pub fn bits(&self) -> u8 {
self.bits
}
}
# [ doc = r" Proxy" ]
pub struct _MckoeW<'a> {
register: &'a mut W,
}
impl<'a> _MckoeW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 9;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _OddW<'a> {
register: &'a mut W,
}
impl<'a> _OddW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 1;
const OFFSET: u8 = 8;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
# [ doc = r" Proxy" ]
pub struct _I2sdivW<'a> {
register: &'a mut W,
}
impl<'a> _I2sdivW<'a> {
# [ doc = r" Writes raw `bits` to the field" ]
pub unsafe fn bits(self, bits: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
self.register.bits &= !((MASK as u32) << OFFSET);
self.register.bits |= ((bits & MASK) as u32) << OFFSET;
self.register
}
}
impl R {
# [ doc = r" Value of the register as raw bits" ]
pub fn bits(&self) -> u32 {
self.bits
}
fn _mckoe(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 9 - Master clock output enable" ]
pub fn mckoe(&self) -> MckoeR {
MckoeR { bits: self._mckoe() }
}
fn _odd(&self) -> u8 {
const MASK: u8 = 1;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bit 8 - Odd factor for the prescaler" ]
pub fn odd(&self) -> OddR {
OddR { bits: self._odd() }
}
fn _i2sdiv(&self) -> u8 {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
}
# [ doc = "Bits 0:7 - I2S Linear prescaler" ]
pub fn i2sdiv(&self) -> I2sdivR {
I2sdivR { bits: self._i2sdiv() }
}
}
impl W {
# [ doc = r" Reset value of the register" ]
pub fn reset_value() -> W {
W { bits: 16 }
}
# [ doc = r" Writes raw `bits` to the register" ]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
# [ doc = "Bit 9 - Master clock output enable" ]
pub fn mckoe(&mut self) -> _MckoeW {
_MckoeW { register: self }
}
# [ doc = "Bit 8 - Odd factor for the prescaler" ]
pub fn odd(&mut self) -> _OddW {
_OddW { register: self }
}
# [ doc = "Bits 0:7 - I2S Linear prescaler" ]
pub fn i2sdiv(&mut self) -> _I2sdivW {
_I2sdivW { register: self }
}
}
}
|
use crate::InputError;
pub fn partition(input: &String) -> Result<std::collections::HashMap<String, usize>, InputError> {
let mut row_range = [0, max_row_num()];
let mut column_range = [0, max_column_num()];
for instruction in input.chars() {
let new_row_count = (row_range[1] - row_range[0] + 1) / 2;
let new_column_count = (column_range[1] - column_range[0] + 1) / 2;
match instruction {
'F' => row_range = [row_range[0], row_range[1] - new_row_count],
'B' => row_range = [row_range[0] + new_row_count, row_range[1]],
'L' => column_range = [column_range[0], column_range[1] - new_column_count],
'R' => column_range = [column_range[0] + new_column_count, column_range[1]],
_ => return Err(InputError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, "Bad input string"))),
};
}
return Ok(
[(String::from("row"), row_range[0]),
(String::from("column"), column_range[0])]
.iter()
.cloned()
.collect()
);
}
fn max_row_num() -> usize {
return 127;
}
fn max_column_num() -> usize {
return 7;
}
#[cfg(test)]
mod tests {
macro_rules! partitioner_tests {
($($name:ident: $value:expr,)*) => {
$(
#[test]
fn $name() {
let (input, expected) = $value;
let result = super::partition(&String::from(input)).unwrap();
let actual = [result["row"], result["column"]];
assert_eq!(expected, actual);
}
)*
}
}
partitioner_tests! {
binary_partition_1: ("FBFBBFFRLR", [44, 5]),
binary_partition_2: ("BFFFBBFRRR", [70, 7]),
binary_partition_3: ("FFFBBBFRRR", [14, 7]),
binary_partition_4: ("BBFFBBFRLL", [102, 4]),
}
}
|
use clap::{App, AppSettings, Arg, ArgMatches};
use rustpython_vm::Settings;
use std::{env, str::FromStr};
pub enum RunMode {
ScriptInteractive(Option<String>, bool),
Command(String),
Module(String),
InstallPip(String),
}
pub fn opts_with_clap() -> (Settings, RunMode) {
let app = App::new("RustPython");
let matches = parse_arguments(app);
settings_from(&matches)
}
fn parse_arguments<'a>(app: App<'a, '_>) -> ArgMatches<'a> {
let app = app
.setting(AppSettings::TrailingVarArg)
.version(crate_version!())
.author(crate_authors!())
.about("Rust implementation of the Python language")
.usage("rustpython [OPTIONS] [-c CMD | -m MODULE | FILE] [PYARGS]...")
.arg(
Arg::with_name("script")
.required(false)
.allow_hyphen_values(true)
.multiple(true)
.value_name("script, args")
.min_values(1),
)
.arg(
Arg::with_name("c")
.short("c")
.takes_value(true)
.allow_hyphen_values(true)
.multiple(true)
.value_name("cmd, args")
.min_values(1)
.help("run the given string as a program"),
)
.arg(
Arg::with_name("m")
.short("m")
.takes_value(true)
.allow_hyphen_values(true)
.multiple(true)
.value_name("module, args")
.min_values(1)
.help("run library module as script"),
)
.arg(
Arg::with_name("install_pip")
.long("install-pip")
.takes_value(true)
.allow_hyphen_values(true)
.multiple(true)
.value_name("get-pip args")
.min_values(0)
.help("install the pip package manager for rustpython; \
requires rustpython be build with the ssl feature enabled."
),
)
.arg(
Arg::with_name("optimize")
.short("O")
.multiple(true)
.help("Optimize. Set __debug__ to false. Remove debug statements."),
)
.arg(
Arg::with_name("verbose")
.short("v")
.multiple(true)
.help("Give the verbosity (can be applied multiple times)"),
)
.arg(Arg::with_name("debug").short("d").help("Debug the parser."))
.arg(
Arg::with_name("quiet")
.short("q")
.help("Be quiet at startup."),
)
.arg(
Arg::with_name("inspect")
.short("i")
.help("Inspect interactively after running the script."),
)
.arg(
Arg::with_name("no-user-site")
.short("s")
.help("don't add user site directory to sys.path."),
)
.arg(
Arg::with_name("no-site")
.short("S")
.help("don't imply 'import site' on initialization"),
)
.arg(
Arg::with_name("dont-write-bytecode")
.short("B")
.help("don't write .pyc files on import"),
)
.arg(
Arg::with_name("safe-path")
.short("P")
.help("don’t prepend a potentially unsafe path to sys.path"),
)
.arg(
Arg::with_name("ignore-environment")
.short("E")
.help("Ignore environment variables PYTHON* such as PYTHONPATH"),
)
.arg(
Arg::with_name("isolate")
.short("I")
.help("isolate Python from the user's environment (implies -E and -s)"),
)
.arg(
Arg::with_name("implementation-option")
.short("X")
.takes_value(true)
.multiple(true)
.number_of_values(1)
.help("set implementation-specific option"),
)
.arg(
Arg::with_name("warning-control")
.short("W")
.takes_value(true)
.multiple(true)
.number_of_values(1)
.help("warning control; arg is action:message:category:module:lineno"),
)
.arg(
Arg::with_name("check-hash-based-pycs")
.long("check-hash-based-pycs")
.takes_value(true)
.number_of_values(1)
.default_value("default")
.help("always|default|never\ncontrol how Python invalidates hash-based .pyc files"),
)
.arg(
Arg::with_name("bytes-warning")
.short("b")
.multiple(true)
.help("issue warnings about using bytes where strings are usually expected (-bb: issue errors)"),
).arg(
Arg::with_name("unbuffered")
.short("u")
.help(
"force the stdout and stderr streams to be unbuffered; \
this option has no effect on stdin; also PYTHONUNBUFFERED=x",
),
);
#[cfg(feature = "flame-it")]
let app = app
.arg(
Arg::with_name("profile_output")
.long("profile-output")
.takes_value(true)
.help("the file to output the profiling information to"),
)
.arg(
Arg::with_name("profile_format")
.long("profile-format")
.takes_value(true)
.help("the profile format to output the profiling information in"),
);
app.get_matches()
}
/// Create settings by examining command line arguments and environment
/// variables.
fn settings_from(matches: &ArgMatches) -> (Settings, RunMode) {
let mut settings = Settings::default();
settings.isolated = matches.is_present("isolate");
settings.ignore_environment = matches.is_present("ignore-environment");
settings.interactive = !matches.is_present("c")
&& !matches.is_present("m")
&& (!matches.is_present("script") || matches.is_present("inspect"));
settings.bytes_warning = matches.occurrences_of("bytes-warning");
settings.no_site = matches.is_present("no-site");
let ignore_environment = settings.ignore_environment || settings.isolated;
if !ignore_environment {
settings.path_list.extend(get_paths("RUSTPYTHONPATH"));
settings.path_list.extend(get_paths("PYTHONPATH"));
}
// Now process command line flags:
if matches.is_present("debug") || (!ignore_environment && env::var_os("PYTHONDEBUG").is_some())
{
settings.debug = true;
}
if matches.is_present("inspect")
|| (!ignore_environment && env::var_os("PYTHONINSPECT").is_some())
{
settings.inspect = true;
}
if matches.is_present("optimize") {
settings.optimize = matches.occurrences_of("optimize").try_into().unwrap();
} else if !ignore_environment {
if let Ok(value) = get_env_var_value("PYTHONOPTIMIZE") {
settings.optimize = value;
}
}
if matches.is_present("verbose") {
settings.verbose = matches.occurrences_of("verbose").try_into().unwrap();
} else if !ignore_environment {
if let Ok(value) = get_env_var_value("PYTHONVERBOSE") {
settings.verbose = value;
}
}
if matches.is_present("no-user-site")
|| matches.is_present("isolate")
|| (!ignore_environment && env::var_os("PYTHONNOUSERSITE").is_some())
{
settings.no_user_site = true;
}
if matches.is_present("quiet") {
settings.quiet = true;
}
if matches.is_present("dont-write-bytecode")
|| (!ignore_environment && env::var_os("PYTHONDONTWRITEBYTECODE").is_some())
{
settings.dont_write_bytecode = true;
}
if !ignore_environment && env::var_os("PYTHONINTMAXSTRDIGITS").is_some() {
settings.int_max_str_digits = match env::var("PYTHONINTMAXSTRDIGITS").unwrap().parse() {
Ok(digits) if digits == 0 || digits >= 640 => digits,
_ => {
error!("Fatal Python error: config_init_int_max_str_digits: PYTHONINTMAXSTRDIGITS: invalid limit; must be >= 640 or 0 for unlimited.\nPython runtime state: preinitialized");
std::process::exit(1);
}
};
}
if matches.is_present("safe-path")
|| (!ignore_environment && env::var_os("PYTHONSAFEPATH").is_some())
{
settings.safe_path = true;
}
settings.check_hash_based_pycs = matches
.value_of("check-hash-based-pycs")
.unwrap_or("default")
.to_owned();
let mut dev_mode = false;
let mut warn_default_encoding = false;
if let Some(xopts) = matches.values_of("implementation-option") {
settings.xopts.extend(xopts.map(|s| {
let mut parts = s.splitn(2, '=');
let name = parts.next().unwrap().to_owned();
let value = parts.next().map(ToOwned::to_owned);
if name == "dev" {
dev_mode = true
}
if name == "warn_default_encoding" {
warn_default_encoding = true
}
if name == "no_sig_int" {
settings.no_sig_int = true;
}
if name == "int_max_str_digits" {
settings.int_max_str_digits = match value.as_ref().unwrap().parse() {
Ok(digits) if digits == 0 || digits >= 640 => digits,
_ => {
error!("Fatal Python error: config_init_int_max_str_digits: -X int_max_str_digits: invalid limit; must be >= 640 or 0 for unlimited.\nPython runtime state: preinitialized");
std::process::exit(1);
},
};
}
(name, value)
}));
}
settings.dev_mode = dev_mode;
if warn_default_encoding
|| (!ignore_environment && env::var_os("PYTHONWARNDEFAULTENCODING").is_some())
{
settings.warn_default_encoding = true;
}
if dev_mode {
settings.warnopts.push("default".to_owned())
}
if settings.bytes_warning > 0 {
let warn = if settings.bytes_warning > 1 {
"error::BytesWarning"
} else {
"default::BytesWarning"
};
settings.warnopts.push(warn.to_owned());
}
if let Some(warnings) = matches.values_of("warning-control") {
settings.warnopts.extend(warnings.map(ToOwned::to_owned));
}
let (mode, argv) = if let Some(mut cmd) = matches.values_of("c") {
let command = cmd.next().expect("clap ensure this exists");
let argv = std::iter::once("-c".to_owned())
.chain(cmd.map(ToOwned::to_owned))
.collect();
(RunMode::Command(command.to_owned()), argv)
} else if let Some(mut cmd) = matches.values_of("m") {
let module = cmd.next().expect("clap ensure this exists");
let argv = std::iter::once("PLACEHOLDER".to_owned())
.chain(cmd.map(ToOwned::to_owned))
.collect();
(RunMode::Module(module.to_owned()), argv)
} else if let Some(get_pip_args) = matches.values_of("install_pip") {
settings.isolated = true;
let mut args: Vec<_> = get_pip_args.map(ToOwned::to_owned).collect();
if args.is_empty() {
args.push("ensurepip".to_owned());
args.push("--upgrade".to_owned());
args.push("--default-pip".to_owned());
}
let installer = args[0].clone();
let mode = match installer.as_str() {
"ensurepip" | "get-pip" => RunMode::InstallPip(installer),
_ => panic!("--install-pip takes ensurepip or get-pip as first argument"),
};
(mode, args)
} else if let Some(argv) = matches.values_of("script") {
let argv: Vec<_> = argv.map(ToOwned::to_owned).collect();
let script = argv[0].clone();
(
RunMode::ScriptInteractive(Some(script), matches.is_present("inspect")),
argv,
)
} else {
(RunMode::ScriptInteractive(None, true), vec!["".to_owned()])
};
let hash_seed = match env::var("PYTHONHASHSEED") {
Ok(s) if s == "random" => Some(None),
Ok(s) => s.parse::<u32>().ok().map(Some),
Err(_) => Some(None),
};
settings.hash_seed = hash_seed.unwrap_or_else(|| {
error!("Fatal Python init error: PYTHONHASHSEED must be \"random\" or an integer in range [0; 4294967295]");
// TODO: Need to change to ExitCode or Termination
std::process::exit(1)
});
settings.argv = argv;
(settings, mode)
}
/// Get environment variable and turn it into integer.
fn get_env_var_value(name: &str) -> Result<u8, std::env::VarError> {
env::var(name).map(|value| {
if let Ok(value) = u8::from_str(&value) {
value
} else {
1
}
})
}
/// Helper function to retrieve a sequence of paths from an environment variable.
fn get_paths(env_variable_name: &str) -> impl Iterator<Item = String> + '_ {
env::var_os(env_variable_name)
.into_iter()
.flat_map(move |paths| {
split_paths(&paths)
.map(|path| {
path.into_os_string()
.into_string()
.unwrap_or_else(|_| panic!("{env_variable_name} isn't valid unicode"))
})
.collect::<Vec<_>>()
})
}
#[cfg(not(target_os = "wasi"))]
pub(crate) use env::split_paths;
#[cfg(target_os = "wasi")]
pub(crate) fn split_paths<T: AsRef<std::ffi::OsStr> + ?Sized>(
s: &T,
) -> impl Iterator<Item = std::path::PathBuf> + '_ {
use std::os::wasi::ffi::OsStrExt;
let s = s.as_ref().as_bytes();
s.split(|b| *b == b':')
.map(|x| std::ffi::OsStr::from_bytes(x).to_owned().into())
}
|
use gloo::timers::future::TimeoutFuture;
use seed::browser::url::Url;
use seed::{prelude::*, *};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use shared::lib::{prune_djs_without_queue, Input, Output, Playing, Room, Track, TrackArt, User};
mod pages;
mod spotify;
use pages::Page;
use std::sync::Arc;
use wasm_bindgen_futures::spawn_local;
const WS_URL: &str = dotenv_codegen::dotenv!("SERVER_WS_URL");
const SPOTIFY_PLAY_URL: &str = "https://api.spotify.com/v1/me/player/play";
const SPOTIFY_NEXT_URL: &str = "https://api.spotify.com/v1/me/player/next";
const SPOTIFY_QUEUE_URL: &str = "https://api.spotify.com/v1/me/player/queue";
const SPOTIFY_SEARCH_URL: &str = "https://api.spotify.com/v1/search";
#[derive(Debug)]
struct Model {
data: Data,
page: Page,
connected: bool,
services: Services,
}
#[derive(Debug)]
enum Data {
Authed(AuthedModel),
UnAuthed(UnauthedModel),
}
#[derive(Debug)]
struct AuthedModel {
session: Session,
auth: Option<SpotifyAuth>,
search: String,
search_debounce: Option<seed::app::cmd_manager::CmdHandle>,
room: Option<Room>,
search_result: Option<spotify::SpotifySearchResult>,
}
#[derive(Debug)]
struct UnauthedModel {
user_id: String,
error: Option<String>,
}
impl Default for UnauthedModel {
fn default() -> Self {
UnauthedModel {
user_id: "".into(),
error: None,
}
}
}
impl From<spotify::SpotifyImage> for TrackArt {
fn from(spotify_art: spotify::SpotifyImage) -> Self {
TrackArt {
uri: spotify_art.url,
width: spotify_art.width,
height: spotify_art.height,
}
}
}
impl From<spotify::SpotifyTrack> for Track {
fn from(spotify_track: spotify::SpotifyTrack) -> Self {
Track {
id: spotify_track.id,
name: spotify_track.name,
artist: spotify_track
.artists
.into_iter()
.map(|x| x.name)
.collect::<Vec<String>>()
.join(", "),
uri: spotify_track.uri,
duration_ms: spotify_track.duration_ms,
artwork: spotify_track
.album
.images
.last()
.map(|x| TrackArt::from(x.to_owned()))
.unwrap_or_default(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SpotifyAuth {
access_token: String,
expires_epoch: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Session {
user_id: String,
}
impl AuthedModel {
fn new(session: Session) -> Self {
AuthedModel {
session: session,
auth: None,
search: "".into(),
search_debounce: None,
room: None,
search_result: None,
}
}
}
#[derive(Debug)]
struct Services {
ws: Arc<WebSocket>,
}
fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
orders
.subscribe(Msg::UrlChanged)
.notify(subs::UrlChanged(url.clone()));
let ws = WebSocket::builder(WS_URL, orders)
.on_open(|| Msg::WebSocketConnected)
.on_close(|x| Msg::Closed(x))
.on_message(Msg::ServerMessage)
.on_error(|| Msg::Error)
.build_and_open()
.expect("Should be able to create a new webscocket to WS_URL");
let session: Option<Session> = LocalStorage::get("spotijay_session").ok();
let mut data = match session {
Some(session) => Data::Authed(AuthedModel::new(session)),
None => Data::UnAuthed(UnauthedModel::default()),
};
if is_logging_in(&url) {
match get_auth_from_url(&url) {
None => {
panic!("Init: Failed to parse auth from url {}", url);
}
Some(auth) => {
LocalStorage::insert("spotify_auth", &auth).ok();
if let Data::Authed(authed_model) = &mut data {
authed_model.auth = Some(auth);
}
}
}
} else {
let auth: Option<SpotifyAuth> = LocalStorage::get("spotify_auth").ok();
if let Data::Authed(authed_model) = &mut data {
if let Some(auth) = auth {
if !auth.access_token.is_empty() || !has_login_expired(&auth.expires_epoch) {
authed_model.auth = Some(auth);
}
};
};
}
Model {
data: data,
page: Page::Home,
connected: false,
services: Services { ws: Arc::new(ws) },
}
}
fn heartbeat_sender(ws: Arc<WebSocket>) {
if ws.state() != seed::browser::web_socket::State::Open {
// TODO: Attempt reconnect
return;
}
spawn_local(async move {
loop {
ws.send_text("ping").unwrap();
TimeoutFuture::new(2_000).await;
}
});
}
fn is_logging_in(url: &Url) -> bool {
if let Some(hash) = &url.hash() {
hash.contains("access_token")
} else {
false
}
}
fn has_login_expired(expires_epoch: &u64) -> bool {
js_sys::Date::now() as u64 > *expires_epoch
}
#[derive(Debug)]
enum AuthenticatedMsg {
Downvote,
SpotifyLogout,
WebSocketConnected,
BecomeDj,
AddTrack(String),
RemoveTrack(String),
ServerMessage(Output),
SearchChange(String),
Search,
SearchFetched(spotify::SpotifySearchResult),
}
#[derive(Debug)]
enum Msg {
UrlChanged(subs::UrlChanged),
Authenticate,
LoggingInToSpotify,
Authenticated(AuthenticatedMsg),
UsernameChange(String),
WebSocketConnected,
ServerMessage(WebSocketMessage),
Closed(CloseEvent),
Error,
Queued,
Played,
LogError(String),
}
async fn get_spotify_search(auth: SpotifyAuth, search: String) -> Result<Msg, Msg> {
if has_login_expired(&auth.expires_epoch) {
futures::future::ok(Msg::Authenticated(AuthenticatedMsg::SpotifyLogout)).await
} else {
let search = UrlSearch::new(vec![("q", vec![search]), ("type", vec!["track".into()])]);
let url = [SPOTIFY_SEARCH_URL, &search.to_string()].join("?");
Request::new(url)
.header(Header::bearer(&auth.access_token))
.fetch()
.map_err(|e| Msg::LogError(format!("{:?}", e)))
.await?
.json::<spotify::SpotifySearchResult>()
.await
.map(|x| Msg::Authenticated(AuthenticatedMsg::SearchFetched(x)))
.map_err(|e| Msg::LogError(format!("{:?}", e)))
}
}
async fn put_spotify_play(auth: SpotifyAuth, uri: String, position_ms: u32) -> Result<Msg, Msg> {
if has_login_expired(&auth.expires_epoch) {
futures::future::ok(Msg::Authenticated(AuthenticatedMsg::SpotifyLogout)).await
} else {
Request::new(SPOTIFY_PLAY_URL)
.header(Header::bearer(auth.access_token))
.method(Method::Put)
.json(&spotify::PlayRequest {
uris: vec![uri],
position_ms,
})
.map_err(|e| Msg::LogError(format!("{:?}", e)))?
.fetch()
.await
.map(|_| Msg::Played)
.map_err(|e| Msg::LogError(format!("{:?}", e)))
}
}
async fn post_spotify_next(auth: SpotifyAuth) -> Result<Msg, Msg> {
if has_login_expired(&auth.expires_epoch) {
futures::future::ok(Msg::Authenticated(AuthenticatedMsg::SpotifyLogout)).await
} else {
let response_result = Request::new(SPOTIFY_NEXT_URL)
.header(Header::bearer(auth.access_token))
.method(Method::Post)
.fetch();
match response_result.await {
Ok(_response) => Ok(Msg::Played),
Err(_error) => Err(Msg::LogError(
"failed to make spotify play next track".to_string(),
)),
}
}
}
async fn post_spotify_queue(auth: SpotifyAuth, uri: String) -> Result<Msg, Msg> {
if has_login_expired(&auth.expires_epoch) {
futures::future::ok(Msg::Authenticated(AuthenticatedMsg::SpotifyLogout)).await
} else {
let search = UrlSearch::new(vec![("uri", vec![uri])]);
let url = [SPOTIFY_QUEUE_URL, &search.to_string()].join("?");
Request::new(url)
.header(Header::bearer(auth.access_token))
.method(Method::Post)
.fetch()
.await
.map(|_| Msg::Queued)
.map_err(|e| Msg::LogError(format!("{:?}", e)))
}
}
fn unwrap_msg(result: Result<Msg, Msg>) -> Msg {
match result {
Ok(msg) => msg,
Err(msg) => msg,
}
}
fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
match msg {
Msg::UrlChanged(subs::UrlChanged(url)) => {
log!("UrlChanged:", &url);
if is_logging_in(&url) {
Url::new().go_and_replace();
}
}
Msg::WebSocketConnected => {
model.connected = true;
heartbeat_sender(model.services.ws.clone());
match &mut model.data {
Data::Authed(authed_model) => authed_update(
AuthenticatedMsg::WebSocketConnected,
&model.services,
authed_model,
orders,
),
Data::UnAuthed(_) => (),
}
}
Msg::Closed(error) => {
model.connected = false;
error!("WebSocket connection was closed", error);
}
Msg::LoggingInToSpotify => {
Url::go_and_load_with_str(&spotify::login_url());
}
Msg::ServerMessage(msg_event) => {
let txt = msg_event.text().unwrap();
if txt == "pong" {
return;
}
log!("ServerMessage", txt);
let output: Output = serde_json::from_str(&txt).unwrap();
match output {
Output::Authenticated(user_id) => {
LocalStorage::insert(
"spotijay_session",
&Session {
user_id: user_id.clone(),
},
)
.ok();
let auth = LocalStorage::get("spotify_auth").ok().and_then(
|spotify_auth: SpotifyAuth| {
if !spotify_auth.access_token.is_empty() {
Some(spotify_auth)
} else {
None
}
},
);
let mut authed_model = AuthedModel::new(Session {
user_id: user_id.clone(),
});
authed_model.auth = auth;
model.data = Data::Authed(authed_model);
&model
.services
.ws
.send_json(&Input::JoinRoom(User {
id: user_id,
queue: vec![],
last_disconnect: None,
}))
.unwrap();
}
_ => match &mut model.data {
Data::UnAuthed(_) => (),
Data::Authed(authed_model) => {
let sub_msg = AuthenticatedMsg::ServerMessage(output);
authed_update(sub_msg, &model.services, authed_model, orders)
}
},
}
}
Msg::Authenticated(sub_msg) => match &mut model.data {
Data::Authed(authed_model) => {
authed_update(sub_msg, &model.services, authed_model, orders)
}
Data::UnAuthed(_) => (),
},
_ => match &mut model.data {
Data::Authed(_) => (),
Data::UnAuthed(unauthed_model) => unauthed_update(msg, &model.services, unauthed_model),
},
};
}
fn get_auth_from_url(url: &Url) -> Option<SpotifyAuth> {
let mut query_params = HashMap::new();
for a in url.hash()?.split('&') {
let mut b = a.split('=').into_iter();
match (b.next(), b.last()) {
(Some(key), Some(val)) => {
query_params.insert(key, val);
}
_ => {}
}
}
let access_token = query_params.get("access_token").map(|x| x.to_string());
let expires_epoch = query_params
.get("expires_in")
.and_then(|x| x.parse::<u64>().ok())
.map(|x| (x * 1_000) + (js_sys::Date::now() as u64));
access_token.zip(expires_epoch).map(|(x, y)| SpotifyAuth {
access_token: x,
expires_epoch: y,
})
}
fn unauthed_update(msg: Msg, services: &Services, unauthed_model: &mut UnauthedModel) {
match msg {
Msg::Authenticate => {
if unauthed_model.user_id.trim().is_empty() {
unauthed_model.error = Some("Username cannot be blank".to_owned());
} else {
services
.ws
.send_json(&Input::Authenticate(unauthed_model.user_id.clone()))
.unwrap();
}
}
Msg::UsernameChange(user_id) => {
unauthed_model.user_id = user_id.clone();
}
Msg::Error => {
error!("WebSocket error for unauthed user");
}
_ => {
error!("Invalid Msg for unauthed user.");
}
}
}
fn authed_update(
msg: AuthenticatedMsg,
services: &Services,
authed_model: &mut AuthedModel,
orders: &mut impl Orders<Msg>,
) {
match msg {
AuthenticatedMsg::Downvote => {
services
.ws
.send_json(&Input::Downvote(authed_model.session.user_id.clone()))
.unwrap();
}
AuthenticatedMsg::SpotifyLogout => {
LocalStorage::remove("spotify_auth").unwrap();
authed_model.auth = None;
}
AuthenticatedMsg::WebSocketConnected => {
services
.ws
.send_json(&Input::Authenticate(authed_model.session.user_id.clone()))
.unwrap();
}
AuthenticatedMsg::BecomeDj => {
services
.ws
.send_json(&Input::BecomeDj(authed_model.session.clone().user_id))
.unwrap();
}
AuthenticatedMsg::AddTrack(track_id) => {
let track = authed_model
.search_result
.clone()
.unwrap()
.tracks
.items
.iter()
.find(|x| x.id == track_id)
.unwrap()
.clone();
services
.ws
.send_json(&Input::AddTrack(
authed_model.session.clone().user_id,
Track::from(track),
))
.unwrap();
authed_model.search = "".into();
authed_model.search_result = None;
}
AuthenticatedMsg::RemoveTrack(track_id) => {
match services.ws.send_json(&Input::RemoveTrack(
authed_model.session.clone().user_id,
track_id,
)) {
Ok(()) => authed_model.search_result = None,
Err(ws_error) => error!("AuthenticatedMsg::RemoveTrack", ws_error),
}
}
AuthenticatedMsg::ServerMessage(output) => match output {
Output::RoomState(room) => {
if let None = authed_model.room {
if let Some(playing) = &room.playing {
if let Some(spotify_auth) = &authed_model.auth {
let offset_ms = (js_sys::Date::now() as u64) - playing.started;
let cloned_spotify_auth = spotify_auth.clone();
let playing_uri = playing.uri.clone();
orders.perform_cmd(async move {
unwrap_msg(
put_spotify_play(
cloned_spotify_auth,
playing_uri,
offset_ms as u32,
)
.await,
)
});
}
}
}
authed_model.room = Some(room);
}
Output::TrackPlayed(playing) => {
if let Some(spotify_auth) = &authed_model.auth {
if let Some(playing) = &playing {
let offset_ms = (js_sys::Date::now() as u64) - playing.started;
let cloned_spotify_auth = spotify_auth.clone();
let playing_uri = playing.uri.clone();
orders.perform_cmd(async move {
unwrap_msg(
put_spotify_play(
cloned_spotify_auth,
playing_uri,
offset_ms as u32,
)
.await,
)
});
} else {
let cloned_spotify_auth = spotify_auth.clone();
orders.perform_cmd(async {
unwrap_msg(post_spotify_next(cloned_spotify_auth).await)
});
}
}
if let Some(room) = &mut authed_model.room {
room.playing = playing;
prune_djs_without_queue(room);
}
}
Output::NextTrackQueued(track) => {
if let Some(spotify_auth) = &authed_model.auth {
let cloned_spotify_auth = spotify_auth.clone();
let track_uri = track.uri.clone();
orders.perform_cmd(async {
unwrap_msg(post_spotify_queue(cloned_spotify_auth, track_uri).await)
});
}
}
Output::Downvoted(user_id) => {
if let Some(Room {
playing: Some(playing),
..
}) = &mut authed_model.room
{
playing.downvotes.insert(user_id);
}
}
Output::Authenticated(_) => (),
},
AuthenticatedMsg::SearchChange(val) => {
authed_model.search = val.clone();
if !val.is_empty() {
if let Some(_) = &authed_model.auth {
let search_handle = orders.perform_cmd_with_handle(cmds::timeout(500, || {
Msg::Authenticated(AuthenticatedMsg::Search)
}));
authed_model.search_debounce = Some(search_handle);
}
} else {
authed_model.search_debounce = None;
authed_model.search_result = None;
}
}
AuthenticatedMsg::Search => {
if !authed_model.search.is_empty() {
if let Some(spotify_auth) = &authed_model.auth {
let cloned_spotify_auth = spotify_auth.clone();
let cloned_search = authed_model.search.clone();
orders.perform_cmd(async {
unwrap_msg(get_spotify_search(cloned_spotify_auth, cloned_search).await)
});
}
} else {
authed_model.search_debounce = None;
authed_model.search_result = None;
}
}
AuthenticatedMsg::SearchFetched(search_results) => {
authed_model.search_result = Some(search_results)
}
}
}
fn current_user(user_id: &str, room: &Room) -> Option<User> {
room.djs
.iter()
.chain(room.users.iter())
.find(|x| x.id == user_id)
.cloned()
}
fn users_view(authed_model: &AuthedModel) -> Option<Node<Msg>> {
let room = authed_model.room.clone()?;
let items = room.users.iter().map(|x| li![&x.id]);
Some(ul![C!["users-list"], items])
}
fn playlist_view(authed_model: &AuthedModel) -> Option<Node<Msg>> {
if authed_model.auth.is_none() {
return Some(div![
id!["playlist"],
h3!["Your playlist"],
spotify_login_button()
]);
}
let mut items: Vec<Node<Msg>> = Vec::new();
let tracks = current_user(&authed_model.session.user_id, authed_model.room.as_ref()?)?
.queue
.into_iter();
for track in tracks {
let event_track = track.clone();
items.push(li![button![
C!["list-button"],
ev(Ev::Click, move |_| Msg::Authenticated(
AuthenticatedMsg::RemoveTrack(event_track.id)
)),
format!("{} - {}", track.artist, track.name),
" ❌"
]]);
}
Some(div![
id!["playlist"],
h3!["Your playlist"],
input![
attrs! {At::Value => authed_model.search},
attrs! {At::Placeholder => "Search for tracks"},
attrs! {At::Type => "search"},
input_ev(Ev::Input, |x| Msg::Authenticated(
AuthenticatedMsg::SearchChange(x)
))
],
search_result_view(authed_model).unwrap_or(ol![C!["playlist-list"], items]),
])
}
fn search_result_view(authed_model: &AuthedModel) -> Option<Node<Msg>> {
let mut items: Vec<Node<Msg>> = Vec::new();
let tracks = authed_model.search_result.clone()?.tracks.items.into_iter();
for track in tracks {
let track_id = track.id.clone();
let click_event = ev(Ev::Click, move |_| {
Msg::Authenticated(AuthenticatedMsg::AddTrack(track_id))
});
let maybe_track_image: Option<Node<Msg>> = track.album.images.last().map(|spotify_image| {
img![C!["track-art"],attrs![At::Src => spotify_image.url, At::Width => spotify_image.width,At::Height => spotify_image.height]]
});
let track_title = h5![C!["track-title"], track.name];
let track_artist = h6![
C!["track-artist"],
track
.artists
.iter()
.map(|x| x.name.to_owned())
.collect::<Vec<String>>()
.join(", ")
];
items.push(li![button![
C!["track-card"],
click_event,
maybe_track_image.unwrap_or(Node::Empty),
track_title,
track_artist,
]]);
}
Some(ul![C!["search-results-list"], items])
}
fn djs_view(room: &Room, session: &Session) -> Option<Node<Msg>> {
let mut items: Vec<Node<Msg>> = Vec::new();
for dj in room.djs.iter() {
items.push(li![div![&dj.id]]);
}
if !room.djs.iter().any(|x| x.id == session.user_id) {
items.push(li![
C!["list-button"],
ev(Ev::Click, |_| Msg::Authenticated(
AuthenticatedMsg::BecomeDj
)),
div!["Become a DJ"]
]);
}
Some(div![id!["djs"], h3!["DJs"], ol![C!["dj-list"], items]])
}
fn spotify_login_button() -> Node<Msg> {
div![button![
ev(Ev::Click, |_| Msg::LoggingInToSpotify),
"Log in to Spotify to listen and build a playlist"
]]
}
fn authed_view(authed_model: &AuthedModel) -> Node<Msg> {
let opt_playing = authed_model.room.as_ref().and_then(|x| x.playing.clone());
div![
id!["app-inner"],
header(authed_model.room.as_ref()),
now_playing(&authed_model.session.user_id, opt_playing.as_ref()),
div![
id!["content"],
div![
id!["listeners"],
h3!["Listeners"],
users_view(authed_model).unwrap_or(div!["No listeners"]),
],
playlist_view(authed_model).unwrap_or(div![]),
authed_model
.room
.as_ref()
.and_then(|x| djs_view(x, &authed_model.session))
.unwrap_or(div![]),
]
]
}
fn header(opt_room: Option<&Room>) -> Node<Msg> {
let opt_current_user = opt_room
.and_then(|x| x.djs.front().cloned());
if let Some(user) = opt_current_user {
h1![b![user.id], " is Spotijaying 😎"]
} else {
h1!["Spotijay"]
}
}
fn now_playing(user_id: &str, opt_playing: Option<&Playing>) -> Node<Msg> {
if let Some(playing) = opt_playing {
let downvoted = playing.downvotes.contains(user_id);
div![
button![
ev(Ev::Click, |_| Msg::Authenticated(
AuthenticatedMsg::Downvote
)),
C![
"button-downvote",
IF!(downvoted => "button-downvote-downvoted")
],
"👎"
],
format!("🎧 {} - {} 🎧", playing.artist, playing.name)
]
} else {
empty!()
}
}
fn unauthed_view(_unauthed_model: &UnauthedModel) -> Node<Msg> {
div![
id!["app-inner"],
div![
id!["login"],
h1![C!["login-title"], "Spotijay"],
input![
attrs! {At::Placeholder => "Username"},
input_ev(Ev::Input, Msg::UsernameChange)
],
button![ev(Ev::Click, |_| Msg::Authenticate), "Log in"],
if let Some(error) = _unauthed_model.error.as_ref() {
p![error]
} else {
empty!()
}
]
]
}
fn view(model: &Model) -> impl IntoNodes<Msg> {
if !model.connected {
div![id!["global-loading"], h2!["Connecting"]]
} else {
match &model.data {
Data::Authed(authed) => authed_view(authed),
Data::UnAuthed(unauthed_model) => unauthed_view(unauthed_model),
}
}
}
#[wasm_bindgen(start)]
pub fn start() {
console_error_panic_hook::set_once();
App::start("app", init, update, view);
}
|
#[macro_use]
extern crate rental;
pub struct Foo {
i: i32,
}
impl Foo {
fn try_borrow(&self) -> Result<&i32, ()> { Ok(&self.i) }
fn fail_borrow(&self) -> Result<&i32, ()> { Err(()) }
}
pub struct FooRef<'i> {
iref: &'i i32,
misc: i32,
}
impl<'i> ::std::ops::Deref for FooRef<'i> {
type Target = i32;
fn deref(&self) -> &i32 { self.iref }
}
rental! {
mod rentals {
use super::*;
#[rental]
pub struct SimpleRef {
foo: Box<Foo>,
fr: FooRef<'foo>,
}
}
}
#[test]
fn new() {
let foo = Foo { i: 5 };
let _ = rentals::SimpleRef::new(Box::new(foo), |foo| FooRef{ iref: &foo.i, misc: 12 });
let foo = Foo { i: 5 };
let sr: rental::RentalResult<rentals::SimpleRef, (), _> = rentals::SimpleRef::try_new(Box::new(foo), |foo| Ok(FooRef{ iref: foo.try_borrow()?, misc: 12 }));
assert!(sr.is_ok());
let foo = Foo { i: 5 };
let sr: rental::RentalResult<rentals::SimpleRef, (), _> = rentals::SimpleRef::try_new(Box::new(foo), |foo| Ok(FooRef{ iref: foo.fail_borrow()?, misc: 12 }));
assert!(sr.is_err());
}
#[test]
fn read() {
let foo = Foo { i: 5 };
let mut sr = rentals::SimpleRef::new(Box::new(foo), |foo| FooRef{ iref: &foo.i, misc: 12 });
{
let i: i32 = sr.rent(|iref| **iref);
assert_eq!(i, 5);
}
{
let iref: &i32 = sr.ref_rent(|fr| fr.iref);
assert_eq!(*iref, 5);
let iref: Option<&i32> = sr.maybe_ref_rent(|fr| Some(fr.iref));
assert_eq!(iref, Some(&5));
let iref: Result<&i32, ()> = sr.try_ref_rent(|fr| Ok(fr.iref));
assert_eq!(iref, Ok(&5));
}
{
assert_eq!(sr.head().i, 5);
assert_eq!(sr.rent_all(|borrows| borrows.foo.i), 5);
assert_eq!(sr.rent_all_mut(|borrows| borrows.foo.i), 5);
}
{
let iref: Option<&i32> = sr.maybe_ref_rent_all(|borrows| Some(borrows.fr.iref));
assert_eq!(iref, Some(&5));
let iref: Result<&i32, ()> = sr.try_ref_rent_all(|borrows| Ok(borrows.fr.iref));
assert_eq!(iref, Ok(&5));
}
{
let iref: &mut i32 = sr.ref_rent_all_mut(|borrows| &mut borrows.fr.misc);
*iref = 57;
assert_eq!(*iref, 57);
}
{
let iref: Option<&mut i32> = sr.maybe_ref_rent_all_mut(|borrows| Some(&mut borrows.fr.misc));
assert_eq!(iref, Some(&mut 57));
}
{
let iref: Result<&mut i32, ()> = sr.try_ref_rent_all_mut(|borrows| Ok(&mut borrows.fr.misc));
assert_eq!(iref, Ok(&mut 57));
}
}
|
use crate::{Req};
pub fn run(reqs: Vec<Req>) {
println!("doing requests");
} |
use super::tree::{Node, NodeBox};
impl<T> Node<T>
where
Node<T>: From<T>,
{
pub fn boxer(data: T) -> NodeBox<T> {
Some(Box::new(Self::from(data)))
}
}
impl<T: Default + PartialOrd> From<T> for Node<T> {
fn from(val: T) -> Self {
Node::new(val)
}
} |
// Translated from C++ to Rust. The original C++ code can be found at
// https://github.com/jk-jeon/dragonbox and carries the following license:
//
// Copyright 2020-2021 Junekey Jeon
//
// The contents of this file may be used under the terms of
// the Apache License v2.0 with LLVM Exceptions.
//
// (See accompanying file LICENSE-Apache or copy at
// https://llvm.org/foundation/relicensing/LICENSE.txt)
//
// Alternatively, the contents of this file may be used under the terms of
// the Boost Software License, Version 1.0.
// (See accompanying file LICENSE-Boost or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// Unless required by applicable law or agreed to in writing, this software
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
use crate::cache::EntryTypeExt as _;
pub(crate) fn umul128_upper64(x: u64, y: u64) -> u64 {
let p = x as u128 * y as u128;
(p >> 64) as u64
}
pub(crate) fn umul192_upper64(x: u64, y: u128) -> u64 {
let mut g0 = x as u128 * y.high() as u128;
g0 += umul128_upper64(x, y.low()) as u128;
g0.high()
}
pub(crate) fn umul192_middle64(x: u64, y: u128) -> u64 {
let g01 = x.wrapping_mul(y.high());
let g10 = umul128_upper64(x, y.low());
g01.wrapping_add(g10)
}
|
//! # WAL Inspect
//!
//! This crate builds on top of the WAL implementation to provide tools for
//! inspecting individual segment files and translating them to human readable
//! formats.
#![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)]
#![warn(
clippy::clone_on_ref_ptr,
clippy::dbg_macro,
clippy::explicit_iter_loop,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::todo,
clippy::use_self,
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
unused_crate_dependencies
)]
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
use std::error::Error;
use std::io::Write;
use std::{borrow::Cow, future::Future};
use data_types::{NamespaceId, TableId};
use hashbrown::{hash_map::Entry, HashMap};
use mutable_batch::MutableBatch;
use parquet_to_line_protocol::convert_to_lines;
use thiserror::Error;
/// Errors emitted by a [`TableBatchWriter`] during operation.
#[derive(Debug, Error)]
pub enum WriteError {
/// The mutable batch is in a state that prevents obtaining
/// the data needed to write to the [`TableBatchWriter`]'s
/// underlying implementation.
#[error("failed to get required data from mutable batch: {0}")]
BadMutableBatch(#[from] mutable_batch::Error),
/// The record batch could not be mapped to line protocol
#[error("failed to translate record batch: {0}")]
RecordBatchTranslationFailure(String),
/// A write failure caused by an IO error
#[error("failed to write table batch: {0}")]
IoError(#[from] std::io::Error),
}
/// The [`TableBatchWriter`] trait provides functionality to write table-ID
/// mutable batches to the implementation defined destination and format.
pub trait TableBatchWriter {
/// The bounds which [`TableBatchWriter`] implementors must adhere to when
/// returning errors for a failed write.
type WriteError: Error + Into<WriteError>;
/// Write out `table_batches` to the implementation defined destination and format.
fn write_table_batches<B>(&mut self, table_batches: B) -> Result<(), Self::WriteError>
where
B: Iterator<Item = (TableId, MutableBatch)>;
}
/// NamespaceDemultiplexer is a delegator from [`NamespaceId`] to some namespaced
/// type, lazily initialising instances as required.
#[derive(Debug)]
pub struct NamespaceDemultiplexer<T, F> {
// The map used to hold currently initialised `T` and lookup within.
demux_map: HashMap<NamespaceId, T>,
// Mechanism to initialise a new `T` when no entry is found in the
// `demux_map`.
init_new: F,
}
impl<T, F, I, E> NamespaceDemultiplexer<T, F>
where
T: Send,
F: (Fn(NamespaceId) -> I) + Send + Sync,
I: Future<Output = Result<T, E>> + Send,
{
/// Creates a [`NamespaceDemultiplexer`] that uses `F` to lazily initialise
/// instances of `T` when there is no entry in the map for a given [`NamespaceId`].
pub fn new(init_new: F) -> Self {
Self {
demux_map: Default::default(),
init_new,
}
}
/// Looks up the `T` corresponding to `namespace_id`, initialising a new
/// instance through the provided mechanism if no entry exists yet.
pub async fn get(&mut self, namespace_id: NamespaceId) -> Result<&mut T, E> {
match self.demux_map.entry(namespace_id) {
Entry::Occupied(entry) => Ok(entry.into_mut()),
Entry::Vacant(empty_entry) => {
let value = (self.init_new)(namespace_id).await?;
Ok(empty_entry.insert(value))
}
}
}
}
/// The [`LineProtoWriter`] enables rewriting table-keyed mutable batches as
/// line protocol to a [`Write`] implementation.
#[derive(Debug)]
pub struct LineProtoWriter<W>
where
W: Write,
{
sink: W,
table_name_lookup: Option<HashMap<TableId, String>>,
}
impl<W> LineProtoWriter<W>
where
W: Write,
{
/// Constructs a new [`LineProtoWriter`] that writes batches of table writes
/// to `sink` as line protocol.
///
/// If provided, `table_name_lookup` MUST contain an exhaustive mapping from
/// table ID to corresponding table name so that the correct measurement name
/// can be placed in the line proto. WAL entries store only table ID, not
/// name and thus cannot be inferred.
///
/// If no lookup is given then measurement names are written as table IDs.
pub fn new(sink: W, table_name_lookup: Option<HashMap<TableId, String>>) -> Self {
Self {
sink,
table_name_lookup,
}
}
}
impl<W> Drop for LineProtoWriter<W>
where
W: Write,
{
fn drop(&mut self) {
_ = self.sink.flush()
}
}
impl<W> TableBatchWriter for LineProtoWriter<W>
where
W: Write,
{
type WriteError = WriteError;
/// Writes the provided set of table batches as line protocol write entries
/// to the destination for the provided namespace ID.
fn write_table_batches<B>(&mut self, table_batches: B) -> Result<(), Self::WriteError>
where
B: Iterator<Item = (TableId, MutableBatch)>,
{
for (table_id, mb) in table_batches {
let schema = mb.schema(schema::Projection::All)?;
let record_batch = mb.to_arrow(schema::Projection::All)?;
let measurement_name = match &self.table_name_lookup {
Some(idx) => Cow::Borrowed(idx.get(&table_id).ok_or(
WriteError::RecordBatchTranslationFailure(format!(
"missing table name for id {}",
&table_id
)),
)?),
None => Cow::Owned(table_id.to_string()),
};
self.sink.write_all(
convert_to_lines(&measurement_name, &schema, &record_batch)
.map_err(WriteError::RecordBatchTranslationFailure)?
.as_slice(),
)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use data_types::TableId;
use dml::DmlWrite;
use generated_types::influxdata::{
iox::wal::v1::sequenced_wal_op::Op, pbdata::v1::DatabaseBatch,
};
use mutable_batch_lp::lines_to_batches;
use wal::{SequencedWalOp, WriteOpEntry, WriteOpEntryDecoder};
use super::*;
#[tokio::test]
async fn translate_valid_wal_segment() {
let test_dir = test_helpers::tmp_dir().expect("failed to create test dir");
let wal = wal::Wal::new(test_dir.path()).await.unwrap();
// Assign table IDs to the measurements and place some writes in the WAL
let (table_id_index, table_name_index) =
build_indexes([("m1", TableId::new(1)), ("m2", TableId::new(2))]);
let line1 = "m1,t=foo v=1i 1";
let line2 = r#"m2,t=bar v="arán" 1"#;
let line3 = "m1,t=foo v=2i 2";
// Generate a single entry
wal.write_op(SequencedWalOp {
table_write_sequence_numbers: [(TableId::new(1), 0)].into_iter().collect(),
op: Op::Write(encode_line(NamespaceId::new(1), &table_id_index, line1)),
});
wal.write_op(SequencedWalOp {
table_write_sequence_numbers: [(TableId::new(2), 1)].into_iter().collect(),
op: Op::Write(encode_line(NamespaceId::new(2), &table_id_index, line2)),
});
wal.write_op(SequencedWalOp {
table_write_sequence_numbers: [(TableId::new(1), 2)].into_iter().collect(),
op: Op::Write(encode_line(NamespaceId::new(1), &table_id_index, line3)),
})
.changed()
.await
.expect("WAL should have changed");
// Rotate the WAL and create the translator.
let (closed, _) = wal.rotate().expect("failed to rotate WAL");
let decoder = WriteOpEntryDecoder::from(
wal.reader_for_segment(closed.id())
.expect("failed to open reader for closed segment"),
);
let mut namespace_demux = NamespaceDemultiplexer::new(|_namespace_id| async {
let result: Result<LineProtoWriter<Vec<u8>>, WriteError> = Ok(LineProtoWriter::new(
Vec::<u8>::new(),
Some(table_name_index.clone()),
));
result
});
let decoded_entries = decoder
.into_iter()
.map(|r| r.expect("unexpected bad entry"))
.collect::<Vec<_>>();
assert_eq!(decoded_entries.len(), 1);
let decoded_ops = decoded_entries
.into_iter()
.flatten()
.collect::<Vec<WriteOpEntry>>();
assert_eq!(decoded_ops.len(), 3);
for entry in decoded_ops {
namespace_demux
.get(entry.namespace)
.await
.expect("failed to get namespaced writer")
.write_table_batches(entry.table_batches.into_iter())
.expect("should not fail to write table batches");
}
// Assert that the namespaced writes contain ONLY the following:
//
// NamespaceId 1:
//
// m1,t=foo v=1i 1
// m1,t=foo v=2i 2
//
// NamespaceId 2:
//
// m2,t=bar v="arán" 1
//
assert_eq!(namespace_demux.demux_map.len(), 2);
let ns_1_results = namespace_demux
.get(NamespaceId::new(1))
.await
.expect("failed to get namespaced writer")
.sink
.clone();
assert_eq!(
String::from_utf8(ns_1_results).unwrap().as_str(),
format!("{}\n{}\n", line1, line3)
);
let ns_2_results = namespace_demux
.get(NamespaceId::new(2))
.await
.expect("failed to get namespaced writer")
.sink
.clone();
assert_eq!(
String::from_utf8(ns_2_results).unwrap().as_str(),
format!("{}\n", line2)
);
}
#[test]
fn write_line_proto_without_index() {
let batches = BTreeMap::from_iter(
lines_to_batches(
r#"m1,t=foo v=1i 1
m2,t=bar v="arán" 1"#,
0,
)
.expect("failed to create batches from line proto")
.into_iter()
.collect::<BTreeMap<_, _>>()
.into_iter()
.enumerate()
.map(|(i, (_table_name, batch))| (TableId::new(i as i64), batch)),
);
let mut lp_writer = LineProtoWriter::new(Vec::new(), None);
lp_writer
.write_table_batches(batches.into_iter())
.expect("write back to line proto should succeed");
assert_eq!(
String::from_utf8(lp_writer.sink.clone()).expect("invalid output"),
r#"0,t=foo v=1i 1
1,t=bar v="arán" 1
"#
);
}
fn build_indexes<'a>(
iter: impl IntoIterator<Item = (&'a str, TableId)>,
) -> (HashMap<String, TableId>, HashMap<TableId, String>) {
let table_id_index: HashMap<String, TableId> =
HashMap::from_iter(iter.into_iter().map(|(s, id)| (s.to_string(), id)));
let table_name_index: HashMap<TableId, String> = table_id_index
.clone()
.into_iter()
.map(|(name, id)| (id, name))
.collect();
(table_id_index, table_name_index)
}
fn encode_line(
ns: NamespaceId,
table_id_index: &HashMap<String, TableId>,
lp: &str,
) -> DatabaseBatch {
let batches = lines_to_batches(lp, 0).unwrap();
let batches = batches
.into_iter()
.map(|(table_name, batch)| {
(
table_id_index
.get(&table_name)
.expect("table name not present in table id index")
.to_owned(),
batch,
)
})
.collect();
let write = DmlWrite::new(ns, batches, "bananas".into(), Default::default());
mutable_batch_pb::encode::encode_write(ns.get(), &write)
}
}
|
use crate::types::*;
use crossbeam_channel::Sender;
use jsonrpc_core::{self, Call, Error, Failure, Id, Output, Success, Value, Version};
use lsp_types::notification::Notification;
use lsp_types::request::*;
use lsp_types::*;
use serde::Deserialize;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs;
// Copy of Kakoune's timestamped buffer content.
pub struct Document {
// Corresponds to Kakoune's timestamp.
// It's passed to a language server as a version and is used to tag selections, highlighters and
// other timestamp sensitive parameters in commands sent to kakoune.
pub version: i32,
// Buffer content.
// It's used to translate between LSP and Kakoune coordinates.
pub text: ropey::Rope,
}
pub type ResponsesCallback = Box<dyn FnOnce(&mut Context, EditorMeta, Vec<Value>) -> ()>;
type BatchNumber = usize;
type BatchCount = BatchNumber;
pub struct Context {
batch_counter: BatchNumber,
pub batches:
HashMap<BatchNumber, (BatchCount, Vec<serde_json::value::Value>, ResponsesCallback)>,
pub capabilities: Option<ServerCapabilities>,
pub config: Config,
pub diagnostics: HashMap<String, Vec<Diagnostic>>,
pub editor_tx: Sender<EditorResponse>,
pub lang_srv_tx: Sender<ServerMessage>,
pub language_id: String,
pub pending_requests: Vec<EditorRequest>,
pub request_counter: u64,
pub response_waitlist: HashMap<Id, (EditorMeta, &'static str, BatchNumber)>,
pub root_path: String,
pub session: SessionId,
pub documents: HashMap<String, Document>,
pub offset_encoding: OffsetEncoding,
}
impl Context {
pub fn new(
language_id: &str,
initial_request: EditorRequest,
lang_srv_tx: Sender<ServerMessage>,
editor_tx: Sender<EditorResponse>,
config: Config,
root_path: String,
offset_encoding: OffsetEncoding,
) -> Self {
let session = initial_request.meta.session.clone();
Context {
batch_counter: 0,
batches: HashMap::default(),
capabilities: None,
config,
diagnostics: HashMap::default(),
editor_tx,
lang_srv_tx,
language_id: language_id.to_string(),
pending_requests: vec![initial_request],
request_counter: 0,
response_waitlist: HashMap::default(),
root_path,
session,
documents: HashMap::default(),
offset_encoding,
}
}
pub fn call<
R: Request,
F: for<'a> FnOnce(&'a mut Context, EditorMeta, R::Result) -> () + 'static,
>(
&mut self,
meta: EditorMeta,
params: R::Params,
callback: F,
) where
R::Params: ToParams,
R::Result: for<'a> Deserialize<'a>,
{
let ops: Vec<R::Params> = vec![params];
self.batch_call::<R, _>(
meta,
ops,
Box::new(
move |ctx: &mut Context, meta: EditorMeta, mut results: Vec<R::Result>| {
if let Some(result) = results.pop() {
callback(ctx, meta, result);
}
},
),
);
}
pub fn batch_call<
R: Request,
F: for<'a> FnOnce(&'a mut Context, EditorMeta, Vec<R::Result>) -> () + 'static,
>(
&mut self,
meta: EditorMeta,
ops: Vec<R::Params>,
callback: F,
) where
R::Params: ToParams,
R::Result: for<'a> Deserialize<'a>,
{
let batch_id = self.next_batch_id();
self.batches.insert(
batch_id,
(
ops.len(),
Vec::with_capacity(ops.len()),
Box::new(move |ctx, meta, vals| {
let results: Vec<R::Result> = vals
.into_iter()
.map(|val| serde_json::from_value(val).expect("Failed to parse response"))
.collect();
callback(ctx, meta, results)
}),
),
);
for params in ops {
let params = params.to_params();
if params.is_err() {
error!("Failed to convert params");
return;
}
let id = self.next_request_id();
self.response_waitlist
.insert(id.clone(), (meta.clone(), R::METHOD, batch_id));
let call = jsonrpc_core::MethodCall {
jsonrpc: Some(Version::V2),
id,
method: R::METHOD.into(),
params: params.unwrap(),
};
if self
.lang_srv_tx
.send(ServerMessage::Request(Call::MethodCall(call)))
.is_err()
{
error!("Failed to call language server");
};
}
}
pub fn reply(&mut self, id: Id, result: Result<Value, Error>) {
let output = match result {
Ok(result) => Output::Success(Success {
jsonrpc: Some(Version::V2),
id,
result,
}),
Err(error) => Output::Failure(Failure {
jsonrpc: Some(Version::V2),
id,
error,
}),
};
if self
.lang_srv_tx
.send(ServerMessage::Response(output))
.is_err()
{
error!("Failed to reply to language server");
};
}
pub fn notify<N: Notification>(&mut self, params: N::Params)
where
N::Params: ToParams,
{
let params = params.to_params();
if params.is_err() {
error!("Failed to convert params");
return;
}
let notification = jsonrpc_core::Notification {
jsonrpc: Some(Version::V2),
method: N::METHOD.into(),
params: params.unwrap(),
};
if self
.lang_srv_tx
.send(ServerMessage::Request(Call::Notification(notification)))
.is_err()
{
error!("Failed to send notification to language server");
}
}
pub fn exec<S>(&self, meta: EditorMeta, command: S)
where
S: Into<Cow<'static, str>>,
{
let command = command.into();
match meta.fifo.as_ref() {
Some(fifo) => {
debug!("To editor `{}`: {}", meta.session, command);
fs::write(fifo, command.as_bytes()).expect("Failed to write command to fifo")
}
None => {
if self
.editor_tx
.send(EditorResponse { meta, command })
.is_err()
{
error!("Failed to send command to editor");
}
}
}
}
fn next_batch_id(&mut self) -> BatchNumber {
let id = self.batch_counter;
self.batch_counter += 1;
id
}
fn next_request_id(&mut self) -> Id {
let id = Id::Num(self.request_counter);
self.request_counter += 1;
id
}
pub fn meta_for_session(&self) -> EditorMeta {
EditorMeta {
session: self.session.clone(),
client: None,
buffile: "".to_string(),
filetype: "".to_string(), // filetype is not used by ctx.exec, but it's definitely a code smell
version: 0,
fifo: None,
}
}
pub fn meta_for_buffer(&self, buffile: &str) -> Option<EditorMeta> {
let document = self.documents.get(buffile)?;
Some(EditorMeta {
session: self.session.clone(),
client: None,
buffile: buffile.to_string(),
filetype: "".to_string(), // filetype is not used by ctx.exec, but it's definitely a code smell
version: document.version,
fifo: None,
})
}
}
|
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
//! # max-sys
//!
//! `max-sys` is a Rust FFI binding to the [Cycling 74](https://cycling74.com/) [Max SDK](https://github.com/Cycling74/max-sdk).
//! It is automatically generated from the SDK source with [bindgen](https://github.com/rust-lang/rust-bindgen).
//!
//! The [Max API Docs](https://cycling74.com/sdk/max-sdk-8.0.3/html/index.html) will be useful for
//! understanding this library.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
include!("./ffi-macos-x86_64.rs");
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
include!("./ffi-macos-aarch64.rs");
#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
include!("./ffi-windows-x86_64.rs");
#[cfg(not(any(
all(target_os = "windows", target_arch = "x86_64"),
all(
target_os = "macos",
any(target_arch = "x86_64", target_arch = "aarch64")
)
)))]
compile_error!("x84_64 on windows or mac are they only supported platforms so far");
//pointer to a t_pxobject can be savely turned into a t_object
impl std::convert::From<&mut crate::t_pxobject> for &mut crate::object {
fn from(o: &mut crate::t_pxobject) -> Self {
unsafe { std::mem::transmute::<_, _>(o) }
}
}
|
use std::collections::HashMap;
use async_std::io::{Read, Write};
use crate::{Error, relay_chunked_stream, relay_sized_stream};
#[derive(Debug)]
pub struct Relay {
length: usize,
length_limit: Option<usize>,
}
impl Relay {
pub fn new() -> Self {
Self {
length: 0,
length_limit: None,
}
}
pub fn length(&self) -> usize {
self.length
}
pub fn length_limit(&self) -> Option<usize> {
self.length_limit
}
pub fn has_length_limit(&self) -> bool {
self.length_limit.is_some()
}
pub fn set_length_limit(&mut self, limit: usize) {
self.length_limit = Some(limit);
}
pub fn remove_length_limit(&mut self) {
self.length_limit = None;
}
pub async fn relay<I, O>(&mut self, input: &mut I, output: &mut O, req: &HashMap<String, String>) -> Result<usize, Error>
where
I: Write + Read + Unpin,
O: Write + Read + Unpin,
{
let length = req.get("Content-Length");
let encoding = req.get("Transfer-Encoding");
if encoding.is_some() && encoding.unwrap().contains(&String::from("chunked")) {
self.relay_chunked(input, output).await
} else {
let length = match length {
Some(length) => match length.parse::<usize>() {
Ok(length) => length,
Err(_) => return Err(Error::InvalidHeader(String::from("Content-Length"))),
},
None => return Err(Error::InvalidHeader(String::from("Content-Length"))),
};
self.relay_sized(input, output, length).await
}
}
pub async fn relay_chunked<I, O>(&mut self, input: &mut I, output: &mut O) -> Result<usize, Error>
where
I: Write + Read + Unpin,
O: Write + Read + Unpin,
{
let limit = match self.length_limit {
Some(limit) => match limit == 0 {
true => return Err(Error::SizeLimitExceeded(limit)),
false => Some(limit - self.length),
},
None => None,
};
let length = relay_chunked_stream(input, output, limit).await?;
self.length += length;
Ok(length)
}
pub async fn relay_sized<I, O>(&mut self, input: &mut I, output: &mut O, length: usize) -> Result<usize, Error>
where
I: Read + Unpin,
O: Write + Unpin,
{
match self.length_limit {
Some(limit) => match length + self.length > limit {
true => return Err(Error::SizeLimitExceeded(limit)),
false => (),
},
None => (),
};
let length = relay_sized_stream(input, output, length).await?;
self.length += length;
Ok(length)
}
pub fn clear(&mut self) {
self.length = 0;
self.length_limit = None;
}
}
|
extern crate bindgen;
extern crate cfg_if;
use bindgen::callbacks::{ EnumVariantCustomBehavior, EnumVariantValue, IntKind, MacroParsingBehavior, ParseCallbacks };
use std::fs::OpenOptions;
use std::io::Write;
use cfg_if::cfg_if;
#[derive(Debug)]
struct CustomCallbacks;
impl ParseCallbacks for CustomCallbacks {
fn will_parse_macro(&self, _name: &str) -> MacroParsingBehavior {
MacroParsingBehavior::Default
}
fn int_macro(&self, _name: &str, _value: i64) -> Option<IntKind> {
if _name.starts_with("POLL") && _value < i16::max_value() as i64 && _value > i16::min_value() as i64 {
Some(IntKind::I16)
}
else if _name.starts_with("DT_") && _value > 0 && _value < u8::max_value() as i64 {
Some(IntKind::U8)
}
else if _name.starts_with("S_IF") && _value > 0 && _value < u32::max_value() as i64 {
Some(IntKind::U32)
}
else if _value < i32::max_value() as i64 && _value > i32::min_value() as i64 {
Some(IntKind::I32)
}
else {
None
}
}
fn enum_variant_behavior(&self, _enum_name: Option<&str>, _original_variant_name: &str, _variant_value: EnumVariantValue,) -> Option<EnumVariantCustomBehavior> {
None
}
fn enum_variant_name(&self, _enum_name: Option<&str>, _original_variant_name: &str, _variant_value: EnumVariantValue,) -> Option<String> {
None
}
}
pub fn get_devkitpro() -> Option<String> {
match std::env::var("DEVKITPRO") {
Ok(_var) => {
match cfg!(windows) {
true => {
let path = std::env::var("PATH").unwrap();
let dummy_path = format!("{}devkitA64{}bin", std::path::MAIN_SEPARATOR, std::path::MAIN_SEPARATOR).to_owned();
let pathvars : Vec<&str> = path.split(';').collect();
for var in &pathvars {
if var.ends_with(&dummy_path) {
let dkp = &var[0..var.len() - dummy_path.len()];
return Some(dkp.to_string());
}
}
None
},
false => Some(String::from("/opt/devkitpro"))
}
},
_ => None
}
}
pub fn regen_bindings(input: &str, output: &str, whitelist: Option<Vec<String>>) -> Result<bindgen::Bindings, std::io::Error> {
let out_path = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap());
let out_p = out_path.join(output);
let gen_path = out_p.to_str().unwrap();
let in_path = std::path::PathBuf::from("bindgen");
let in_p = in_path.join(input);
let header_wrapper = in_p.to_str().unwrap();
// we don't care if deletion succeeds, as long as the file is gone
let _ = std::fs::remove_file(gen_path);
assert!(!std::path::Path::new(gen_path).exists());
let dkp = match get_devkitpro() {
Some(path) => path,
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Oof"))
};
let mut builder = bindgen::Builder::default().trust_clang_mangling(false).use_core().rust_target(bindgen::RustTarget::Nightly).ctypes_prefix("ctypes").generate_inline_functions(true).parse_callbacks(Box::new(CustomCallbacks{})).header(header_wrapper)
.clang_arg(format!("-I{}", std::path::Path::new(&dkp).join("libnx").join("include").to_str().unwrap()))
.clang_arg(format!("-I{}", std::path::Path::new(&dkp).join("portlibs").join("switch").join("include").to_str().unwrap()))
.clang_arg(format!("-I{}", std::path::Path::new(&dkp).join("devkitA64").join("aarch64-none-elf").join("include").to_str().unwrap()))
.clang_arg(format!("-I{}", std::path::Path::new(&dkp).join("devkitA64").join("lib").join("gcc").join("aarch64-none-elf").join("8.3.0").join("include").to_str().unwrap()))
.blacklist_type("u8").blacklist_type("u16").blacklist_type("u32").blacklist_type("u64");
if let Some(whitelist) = whitelist {
for func in whitelist {
builder = builder.whitelist_function(func);
}
}
builder.generate().map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Could not create file!")).and_then(|bnd| {
let mut file = OpenOptions::new().write(true).create(true).open(gen_path)?;
file.write_all(br#"
mod ctypes {
pub type c_void = core::ffi::c_void;
pub type c_char = u8;
pub type c_int = i32;
pub type c_long = i64;
pub type c_longlong = i64;
pub type c_schar = i8;
pub type c_short = i16;
pub type c_uchar = u8;
pub type c_uint = u32;
pub type c_ulong = u64;
pub type c_ulonglong = u64;
pub type c_ushort = u16;
pub type size_t = u64;
pub type ssize_t = i64;
pub type c_float = f32;
pub type c_double = f64;
}
"#)?;
bnd.write(Box::new(file)).map(|_| bnd)
})
}
pub fn process_bindgen(input: &str, output: &str, name: &str, whitelist: Option<Vec<String>>) {
regen_bindings(input, output, whitelist).expect(&format!("Error generating {}'s bindings!", name));
}
cfg_if! {
if #[cfg(feature = "twili")] {
pub fn process_twili() {
process_bindgen("twili.h", "twili.rs", "twili", Some(vec!["twiliWriteNamedPipe".to_string(), "twiliCreateNamedOutputPipe".to_string(), "twiliCreateNamedOutputPipe".to_string(), "twiliInitialize".to_string(), "twiliExit".to_string()]));
}
}
else {
pub fn process_twili() {
}
}
}
pub fn main() {
process_bindgen("libnx.h", "libnx.rs", "libnx", None);
process_twili();
} |
pub mod handler;
pub mod rover; |
use std::collections::HashMap;
use futures::prelude::*;
use common::{Error, GiphyGif};
use crate::{Tx, PgPoolConn};
//////////////////////////////////////////////////////////////////////////////////////////////////
// FavoriteGif ///////////////////////////////////////////////////////////////////////////////////
/// A GIF from the Giphy API which has been saved by a user.
#[derive(Clone, sqlx::FromRow)]
pub struct SavedGif {
/// Object ID.
pub id: i64,
/// The ID of the user which has saved this GIF.
pub user: i64,
/// The ID of this GIF in the Giphy system.
pub giphy_id: String,
/// The title of the GIF.
pub title: String,
/// The URL of the GIF.
pub url: String,
/// The category given to this GIF by the user.
pub category: Option<String>,
}
impl SavedGif {
/// Insert a new record.
pub async fn insert(user: i64, gif: &GiphyGif, tx: &mut Tx) -> Result<Self, Error> {
Ok(sqlx::query_as!(
SavedGif,
r#"INSERT INTO public.saved_gifs ("user", giphy_id, title, url, category) VALUES ($1, $2, $3, $4, $5) RETURNING *;"#,
user, gif.id.clone(), gif.title.clone(), gif.url.clone(), gif.category.clone(),
)
.fetch_one(tx)
.await
.map_err(Error::from)?)
}
/// Find all gifs saved by the specified user.
pub async fn all_for_user(user: i64, db: &mut PgPoolConn) -> Result<Vec<SavedGif>, Error> {
let stream = sqlx::query_as!(SavedGif, r#"SELECT * FROM public.saved_gifs WHERE "user"=$1;"#, user).fetch(db);
Ok(stream
.try_fold(vec![], |mut acc, gif| async move {
acc.push(gif);
Ok(acc)
})
.map_err(Error::from)
.await?)
}
/// Find all gifs saved by the specified user matching the set of IDs.
pub async fn for_user_matching_ids<'a>(user: i64, ids: &'a [String], db: &'a mut PgPoolConn) -> Result<HashMap<String, SavedGif>, Error> {
let stream = sqlx::query_as!(SavedGif, r#"SELECT * FROM public.saved_gifs WHERE "user"=$1 AND giphy_id=ANY($2);"#, user, ids)
.fetch(db);
Ok(stream
.try_fold(HashMap::new(), |mut acc, gif| async move {
acc.insert(gif.giphy_id.clone(), gif);
Ok(acc)
})
.map_err(Error::from)
.await?)
}
/// Set a new category for the target user's gif, returning None if the target gif does not exist for the given user.
pub async fn set_category(user: i64, gif: String, category: String, tx: &mut Tx) -> Result<Option<Self>, Error> {
Ok(sqlx::query_as!(
SavedGif,
r#"UPDATE public.saved_gifs SET category=$1 WHERE "user"=$2 AND giphy_id=$3 RETURNING *;"#,
category, user, gif,
)
.fetch_optional(tx)
.await
.map_err(Error::from)?)
}
}
impl From<SavedGif> for GiphyGif {
fn from(src: SavedGif) -> Self {
Self{
id: src.giphy_id,
title: src.title,
url: src.url,
is_saved: true,
category: src.category,
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// User //////////////////////////////////////////////////////////////////////////////////////////
/// A user of the system.
#[derive(Clone)]
pub struct User {
/// Object ID.
pub id: i64,
/// The user's email address.
pub email: String,
/// The user's password hash.
pub pwhash: String,
}
impl User {
/// Insert a new record.
pub async fn insert(email: String, pwhash: String, tx: &mut Tx) -> Result<Self, Error> {
Ok(sqlx::query_as!(User, "INSERT INTO public.users (email, pwhash) VALUES ($1, $2) RETURNING *;", email, pwhash)
.fetch_one(tx)
.await
.map_err(|err| match err {
sqlx::Error::Database(dberr) => {
match dberr.constraint_name() {
Some(constraint) if constraint == "users_email_key" => {
Error::new("That email address is already taken.", 400, None)
}
_ => Error::from(sqlx::Error::Database(dberr)), // Just resurface the error.
}
}
_ => Error::new_ise(),
})?)
}
/// Find a user record by the given email.
pub async fn find_by_email(email: String, db: &mut PgPoolConn) -> Result<Option<Self>, Error> {
Ok(sqlx::query_as!(User, "SELECT * FROM public.users WHERE email=$1;", email)
.fetch_optional(db)
.await
.map_err(Error::from)?)
}
/// Find a user record by the given id.
pub async fn find_by_id(id: i64, db: &mut PgPoolConn) -> Result<Option<Self>, Error> {
Ok(sqlx::query_as!(User, "SELECT * FROM public.users WHERE id=$1;", id)
.fetch_optional(db)
.await
.map_err(Error::from)?)
}
/// Transform into the common::User model.
pub fn into_common(self, jwt: String) -> common::User {
common::User{id: self.id, email: self.email, jwt}
}
}
|
//! Code generation for `ir::Variable`.
use crate::codegen;
use crate::ir;
use crate::search_space::*;
use fxhash::FxHashMap;
use indexmap::IndexMap;
use utils::*;
/// Wraps an `ir::Variable` to expose specified decisions.
pub struct Variable<'a> {
variable: &'a ir::Variable,
t: ir::Type,
instantiation_dims: FxHashMap<ir::DimId, usize>,
alias: Option<Alias>,
}
impl<'a> Variable<'a> {
/// Returns the ID of the variable.
pub fn id(&self) -> ir::VarId {
self.variable.id()
}
/// Returns the type of the variable.
pub fn t(&self) -> ir::Type {
self.t
}
/// Indicates if the variable aliases with another.
///
/// This just indicates a single alias. In practice, aliases can be chained so the
/// variable may alias we multiple other variables.
pub fn alias(&self) -> Option<&Alias> {
self.alias.as_ref()
}
/// Returns the dimensions (and their size) along wich the variable is instantiated.
pub fn instantiation_dims(&self) -> impl Iterator<Item = (ir::DimId, usize)> + '_ {
self.instantiation_dims
.iter()
.map(|(&key, &value)| (key, value))
}
}
/// Indicates how a variable aliases with another.
pub struct Alias {
other_variable: ir::VarId,
dim_mapping: FxHashMap<ir::DimId, Option<ir::DimId>>,
reverse_mapping: FxHashMap<ir::DimId, ir::DimId>,
}
impl Alias {
/// Indicates the variable aliased with.
pub fn other_variable(&self) -> ir::VarId {
self.other_variable
}
/// Specifies the mapping of dimensions from `other_variable` to the alias. A mapping
/// to `None` indicates the alias takes the last instance of the variable on the
/// dimension.
pub fn dim_mapping(&self) -> &FxHashMap<ir::DimId, Option<ir::DimId>> {
&self.dim_mapping
}
/// Creates a new `Alias` that takes the last value of another variable.
fn new_last(other_variable: ir::VarId, dims: &[ir::DimId]) -> Self {
Alias {
other_variable,
dim_mapping: dims.iter().map(|&dim| (dim, None)).collect(),
reverse_mapping: Default::default(),
}
}
/// Creates a new alias that takes point-to-point the values of another variable.
fn new_dim_map(
other_variable: ir::VarId,
mapping_ids: &[ir::DimMappingId],
fun: &ir::Function,
) -> Self {
let (dim_mapping, reverse_mapping) = mapping_ids
.iter()
.map(|&id| fun.dim_mapping(id).dims())
.map(|[lhs, rhs]| ((lhs, Some(rhs)), (rhs, lhs)))
.unzip();
Alias {
other_variable,
dim_mapping,
reverse_mapping,
}
}
/// Finds dimensions on which the variable must be instantiated to implement the
/// aliasing. Also returns their size.
fn find_instantiation_dims(
&self,
space: &SearchSpace,
) -> FxHashMap<ir::DimId, usize> {
self.dim_mapping
.iter()
.flat_map(|(&lhs, &rhs)| rhs.map(|rhs| (lhs, rhs)))
.filter(|&(lhs, rhs)| {
space.domain().get_order(lhs.into(), rhs.into()) != Order::MERGED
})
.map(|(_, rhs)| {
let size = space.ir_instance().dim(rhs).size();
let int_size = unwrap!(codegen::Size::from_ir(size, space).as_int());
(rhs, int_size as usize)
})
.collect()
}
}
/// Generates variables aliases.
fn generate_aliases(space: &SearchSpace) -> FxHashMap<ir::VarId, Option<Alias>> {
space
.ir_instance()
.variables()
.map(|var| {
let alias = match var.def() {
ir::VarDef::Inst(..) => None,
ir::VarDef::Last(alias, dims) => Some(Alias::new_last(*alias, dims)),
ir::VarDef::DimMap(alias, mappings) => {
Some(Alias::new_dim_map(*alias, mappings, space.ir_instance()))
}
};
(var.id(), alias)
})
.collect()
}
/// Sort variables by aliasing order.
fn sort_variables<'a>(
mut aliases: FxHashMap<ir::VarId, Option<Alias>>,
space: &'a SearchSpace,
) -> impl Iterator<Item = (&'a ir::Variable, Option<Alias>)> {
space.ir_instance().variables().flat_map(move |var| {
let mut reverse_aliases = vec![];
let mut current_var = Some(var.id());
// Each variable depends at most on one other, so we we just walk the chain of
// dependencies until we encountered an already sorted variable or a variable
// with no dependency. Then we insert them in reverse order in the sorted array.
while let Some((id, alias)) =
{ current_var.and_then(|id| aliases.remove(&id).map(|alias| (id, alias))) }
{
current_var = alias.as_ref().map(|alias| alias.other_variable);
reverse_aliases.push((space.ir_instance().variable(id), alias));
}
reverse_aliases.reverse();
reverse_aliases
})
}
/// Add a wrapper around variables to expose specified decisions. Orders variables with an
/// alias after the variable they depend on.
pub fn wrap_variables<'a>(space: &'a SearchSpace) -> Vec<Variable<'a>> {
let aliases = generate_aliases(space);
// Generate the wrappers and record the dimensions along which variables are
// instantiated. We use an `IndexMap` so that the insertion order is preserved.
let mut wrapped_vars = IndexMap::new();
for (variable, alias_opt) in sort_variables(aliases, space) {
let instantiation_dims = alias_opt
.as_ref()
.map(|alias| alias.find_instantiation_dims(space))
.unwrap_or_default();
// Register instantiation dimensions in preceeding aliases.
if let Some(ref alias) = alias_opt {
for (&iter_dim, &size) in &instantiation_dims {
let alias_iter_dim = alias.reverse_mapping[&iter_dim];
let mut current = Some((alias.other_variable, alias_iter_dim));
while let Some((var_id, iter_dim)) = current.take() {
let var: &mut Variable = &mut wrapped_vars[&var_id];
// Only continue if the dimension was not already inserted.
if var.instantiation_dims.insert(iter_dim, size).is_none() {
if let Some(ref alias) = var.alias {
let pred_dim = alias
.reverse_mapping
.get(&iter_dim)
.cloned()
.unwrap_or(iter_dim);
current = Some((alias.other_variable, pred_dim));
}
}
}
}
}
let wrapper = Variable {
variable,
t: unwrap!(space.ir_instance().device().lower_type(variable.t(), space)),
instantiation_dims,
alias: alias_opt,
};
wrapped_vars.insert(variable.id(), wrapper);
}
wrapped_vars.into_iter().map(|entry| entry.1).collect()
}
#[cfg(test)]
mod tests {
use std;
use std::sync::Arc;
use crate::device::fake;
use crate::helper;
use super::*;
fn mk_map<K, V>(content: &[(K, V)]) -> FxHashMap<K, V>
where
K: Copy + Eq + std::hash::Hash,
V: Copy,
{
content.iter().cloned().collect()
}
/// Ensures chained aliases work correctly.
#[test]
fn chained_alias() {
let _ = ::env_logger::try_init();
let device = Arc::new(fake::Device::default());
let signature = Arc::new(ir::Signature::new("test".to_string()));
let mut builder = helper::Builder::new(signature, device);
// This code builds the following function:
// ```pseudocode
// for i in 0..16:
// for j in 0..16:
// src[i] = 0;
// for i in 0..16:
// dst = src[i]
// ```
// where all loops are unrolled.
let dim0 = builder.open_dim_ex(ir::Size::new_const(4), DimKind::UNROLL);
let dim1 = builder.open_dim_ex(ir::Size::new_const(8), DimKind::UNROLL);
let src = builder.mov(&0i32);
let src_var = builder.get_inst_variable(src);
builder.close_dim(&dim1);
let last_var = builder.create_last_variable(src_var, &[&dim1]);
let dim2 = builder.open_mapped_dim(&dim0);
builder.action(Action::DimKind(dim2[0], DimKind::UNROLL));
builder.order(&dim0, &dim2, Order::BEFORE);
let mapped_var = builder.create_dim_map_variable(last_var, &[(&dim0, &dim2)]);
builder.mov(&mapped_var);
let space = builder.get();
let wrappers = wrap_variables(&space);
// `wrap_variables` orders variables according to data dependencies.
assert_eq!(wrappers[0].variable.id(), src_var);
assert_eq!(wrappers[1].variable.id(), last_var);
assert_eq!(wrappers[2].variable.id(), mapped_var);
// Check `src_var`.
assert_eq!(wrappers[0].instantiation_dims, mk_map(&[(dim0[0], 4)]));
assert!(wrappers[0].alias.is_none());
// Check `last_var`
assert_eq!(wrappers[1].instantiation_dims, mk_map(&[(dim0[0], 4)]));
if let Some(ref alias) = wrappers[1].alias {
assert_eq!(alias.other_variable, src_var);
assert_eq!(alias.dim_mapping, mk_map(&[(dim1[0], None)]));
} else {
panic!("expected an alias for last_var");
}
// Check `mapped_var`
assert_eq!(wrappers[2].instantiation_dims, mk_map(&[(dim2[0], 4)]));
if let Some(ref alias) = wrappers[2].alias {
assert_eq!(alias.other_variable, last_var);
assert_eq!(alias.dim_mapping, mk_map(&[(dim0[0], Some(dim2[0]))]));
} else {
panic!("expected an alias for mapped_var");
}
}
}
|
#[macro_use]
extern crate bitflags;
extern crate regex;
extern crate num_derive;
mod str_utils;
mod magic;
mod magic_param;
mod parse_magic_line;
mod parse_magic_aux_line;
mod parse_magic_entry;
use std::path::Path;
// use clap::{App, Arg};
fn load_one_magic(magic_file: &Path) {
// init magic_set (magic_open -> file_ms_alloc)
// load magic_set (
// load ->
// magic_load ->
// file_apprentice ->
// (for each magic-filepath)
// apprentice_1 ->
// map = apprentice_load ->
// (for each magic-file)
// load_1
// sort by apprentice_sort
// set_text_binary
// set_last_default
// coalesce_entries
// add_mlist(ms->mlist, map) )
}
fn main() {
// let path = Path::new("/usr/share/file/magic/acorn");
// load_one_magic(path).expect("Failed to load one magic file!");
println!("hello, world!");
}
|
// Copyright 2019 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.
//! Test utilities.
// These functions specifically used for FFI are missing safety documentation.
// It is probably not necessary for us to provide this for every single function
// as that would be repetitive and verbose.
#![allow(clippy::missing_safety_doc)]
use crate::repr_c::ReprC;
use crate::{ErrorCode, FfiResult};
use std::fmt::{Debug, Display};
use std::os::raw::c_void;
use std::sync::mpsc::{self, Sender};
use std::{fmt, ptr, slice};
use unwrap::unwrap;
/// User data wrapper.
pub struct UserData {
/// Common field, used by standard callbacks.
pub common: *mut c_void,
/// Custom field, used by additional callbacks.
pub custom: *mut c_void,
}
impl Default for UserData {
fn default() -> Self {
let common: *const c_void = ptr::null();
let custom: *const c_void = ptr::null();
UserData {
common: common as *mut c_void,
custom: custom as *mut c_void,
}
}
}
/// Convert a `UserData` to a void pointer which can be passed to ffi functions.
pub fn user_data_as_void(ud: &UserData) -> *mut c_void {
let ptr: *const _ = ud;
ptr as *mut c_void
}
/// Convert a `mpsc::Sender<T>` to a void ptr which is then stored in the `UserData` struct and
/// passed to ffi functions.
pub fn sender_as_user_data<T>(tx: &Sender<T>, ud: &mut UserData) -> *mut c_void {
let ptr: *const _ = tx;
ud.common = ptr as *mut c_void;
user_data_as_void(ud)
}
/// Send through a `mpsc::Sender` pointed to by the user data's common pointer.
pub unsafe fn send_via_user_data<T>(user_data: *mut c_void, value: T)
where
T: Send,
{
let ud = user_data as *mut UserData;
let tx = (*ud).common as *mut Sender<T>;
unwrap!((*tx).send(value));
}
/// Send through a `mpsc::Sender` pointed to by the user data's custom pointer.
pub unsafe fn send_via_user_data_custom<T>(user_data: *mut c_void, value: T)
where
T: Send,
{
let ud = user_data as *mut UserData;
let tx = (*ud).custom as *mut Sender<T>;
unwrap!((*tx).send(value));
}
/// Call a FFI function and block until its callback gets called.
/// Use this if the callback accepts no arguments in addition to `user_data`
/// and `error_code`.
pub fn call_0<F>(f: F) -> Result<(), i32>
where
F: FnOnce(*mut c_void, extern "C" fn(user_data: *mut c_void, result: *const FfiResult)),
{
let mut ud = Default::default();
call_0_with_custom(&mut ud, f)
}
/// Call a FFI function and block until its callback gets called.
/// Use this if the callback accepts no arguments in addition to `user_data`
/// and `error_code`.
/// This version of the function takes a `UserData` with custom inner data.
pub fn call_0_with_custom<F>(ud: &mut UserData, f: F) -> Result<(), i32>
where
F: FnOnce(*mut c_void, extern "C" fn(user_data: *mut c_void, result: *const FfiResult)),
{
let (tx, rx) = mpsc::channel::<i32>();
f(sender_as_user_data(&tx, ud), callback_0);
let error = unwrap!(rx.recv());
if error == 0 {
Ok(())
} else {
Err(error)
}
}
/// Call an FFI function and block until its callback gets called, then return
/// the argument which were passed to that callback.
/// Use this if the callback accepts one argument in addition to `user_data`
/// and `error_code`.
pub unsafe fn call_1<F, E: Debug, T>(f: F) -> Result<T, i32>
where
F: FnOnce(*mut c_void, extern "C" fn(user_data: *mut c_void, result: *const FfiResult, T::C)),
T: ReprC<Error = E>,
{
let mut ud = Default::default();
call_1_with_custom(&mut ud, f)
}
/// Call an FFI function and block until its callback gets called, then return
/// the argument which were passed to that callback.
/// Use this if the callback accepts one argument in addition to `user_data`
/// and `error_code`.
/// This version of the function takes a `UserData` with custom inner data.
pub fn call_1_with_custom<F, E: Debug, T>(ud: &mut UserData, f: F) -> Result<T, i32>
where
F: FnOnce(*mut c_void, extern "C" fn(user_data: *mut c_void, result: *const FfiResult, T::C)),
T: ReprC<Error = E>,
{
let (tx, rx) = mpsc::channel::<SendWrapper<Result<T, i32>>>();
f(sender_as_user_data(&tx, ud), callback_1::<E, T>);
unwrap!(rx.recv()).0
}
/// Call a FFI function and block until its callback gets called, then return
/// the argument which were passed to that callback.
/// Use this if the callback accepts two arguments in addition to `user_data`
/// and `error_code`.
pub unsafe fn call_2<F, E0, E1, T0, T1>(f: F) -> Result<(T0, T1), i32>
where
F: FnOnce(
*mut c_void,
extern "C" fn(user_data: *mut c_void, result: *const FfiResult, T0::C, T1::C),
),
E0: Debug,
E1: Debug,
T0: ReprC<Error = E0>,
T1: ReprC<Error = E1>,
{
let mut ud = Default::default();
call_2_with_custom(&mut ud, f)
}
/// Call a FFI function and block until its callback gets called, then return
/// the argument which were passed to that callback.
/// Use this if the callback accepts two arguments in addition to `user_data`
/// and `error_code`.
/// This version of the function takes a `UserData` with custom inner data.
pub unsafe fn call_2_with_custom<F, E0, E1, T0, T1>(
ud: &mut UserData,
f: F,
) -> Result<(T0, T1), i32>
where
F: FnOnce(
*mut c_void,
extern "C" fn(user_data: *mut c_void, result: *const FfiResult, T0::C, T1::C),
),
E0: Debug,
E1: Debug,
T0: ReprC<Error = E0>,
T1: ReprC<Error = E1>,
{
let (tx, rx) = mpsc::channel::<SendWrapper<Result<(T0, T1), i32>>>();
f(sender_as_user_data(&tx, ud), callback_2::<E0, E1, T0, T1>);
unwrap!(rx.recv()).0
}
/// Call a FFI function and block until its callback gets called, then copy
/// the array argument which was passed to `Vec<T>` and return the result.
/// Use this if the callback accepts `*const T` and `usize` (length) arguments in addition
/// to `user_data` and `error_code`.
pub unsafe fn call_vec<F, E, T, U>(f: F) -> Result<Vec<T>, i32>
where
F: FnOnce(
*mut c_void,
extern "C" fn(user_data: *mut c_void, result: *const FfiResult, T::C, usize),
),
E: Debug,
T: ReprC<C = *const U, Error = E>,
{
let mut ud = Default::default();
call_vec_with_custom(&mut ud, f)
}
/// Call a FFI function and block until its callback gets called, then copy
/// the array argument which was passed to `Vec<T>` and return the result.
/// Use this if the callback accepts `*const T` and `usize` (length) arguments in addition
/// to `user_data` and `error_code`.
/// This version of the function takes a `UserData` with custom inner data.
pub unsafe fn call_vec_with_custom<F, E, T, U>(ud: &mut UserData, f: F) -> Result<Vec<T>, i32>
where
F: FnOnce(
*mut c_void,
extern "C" fn(user_data: *mut c_void, result: *const FfiResult, T::C, usize),
),
E: Debug,
T: ReprC<C = *const U, Error = E>,
{
let (tx, rx) = mpsc::channel::<SendWrapper<Result<Vec<T>, i32>>>();
f(sender_as_user_data(&tx, ud), callback_vec::<E, T, U>);
unwrap!(rx.recv()).0
}
/// Call a FFI function and block until its callback gets called, then copy
/// the byte array argument which was passed to `Vec<u8>` and return the result.
pub unsafe fn call_vec_u8<F>(f: F) -> Result<Vec<u8>, i32>
where
F: FnOnce(
*mut c_void,
extern "C" fn(user_data: *mut c_void, result: *const FfiResult, *const u8, usize),
),
{
let mut ud = Default::default();
call_vec_u8_with_custom(&mut ud, f)
}
/// Call a FFI function and block until its callback gets called, then copy
/// the byte array argument which was passed to `Vec<u8>` and return the result.
/// This version of the function takes a `UserData` with custom inner data.
/// This version of the function takes a `UserData` with custom inner data.
pub unsafe fn call_vec_u8_with_custom<F>(ud: &mut UserData, f: F) -> Result<Vec<u8>, i32>
where
F: FnOnce(
*mut c_void,
extern "C" fn(user_data: *mut c_void, result: *const FfiResult, *const u8, usize),
),
{
let (tx, rx) = mpsc::channel::<Result<Vec<u8>, i32>>();
f(sender_as_user_data(&tx, ud), callback_vec_u8);
unwrap!(rx.recv())
}
extern "C" fn callback_0(user_data: *mut c_void, res: *const FfiResult) {
unsafe { send_via_user_data(user_data, (*res).error_code) }
}
extern "C" fn callback_1<E, T>(user_data: *mut c_void, res: *const FfiResult, arg: T::C)
where
E: Debug,
T: ReprC<Error = E>,
{
unsafe {
let result: Result<T, i32> = if (*res).error_code == 0 {
Ok(unwrap!(T::clone_from_repr_c(arg)))
} else {
Err((*res).error_code)
};
send_via_user_data(user_data, SendWrapper(result));
}
}
extern "C" fn callback_2<E0, E1, T0, T1>(
user_data: *mut c_void,
res: *const FfiResult,
arg0: T0::C,
arg1: T1::C,
) where
E0: Debug,
E1: Debug,
T0: ReprC<Error = E0>,
T1: ReprC<Error = E1>,
{
unsafe {
let result: Result<(T0, T1), i32> = if (*res).error_code == 0 {
Ok((
unwrap!(T0::clone_from_repr_c(arg0)),
unwrap!(T1::clone_from_repr_c(arg1)),
))
} else {
Err((*res).error_code)
};
send_via_user_data(user_data, SendWrapper(result))
}
}
extern "C" fn callback_vec<E, T, U>(
user_data: *mut c_void,
res: *const FfiResult,
array: *const U,
size: usize,
) where
E: Debug,
T: ReprC<C = *const U, Error = E>,
{
unsafe {
let result: Result<Vec<T>, i32> = if (*res).error_code == 0 {
let slice_ffi = slice::from_raw_parts(array, size);
let mut vec = Vec::with_capacity(slice_ffi.len());
for elt in slice_ffi {
vec.push(unwrap!(T::clone_from_repr_c(elt)));
}
Ok(vec)
} else {
Err((*res).error_code)
};
send_via_user_data(user_data, SendWrapper(result))
}
}
extern "C" fn callback_vec_u8(
user_data: *mut c_void,
res: *const FfiResult,
ptr: *const u8,
len: usize,
) {
unsafe {
let result = if (*res).error_code == 0 {
Ok(slice::from_raw_parts(ptr, len).to_vec())
} else {
Err((*res).error_code)
};
send_via_user_data(user_data, result)
}
}
/// Unsafe wrapper for passing non-Send types through mpsc channels.
/// Use with caution!
pub struct SendWrapper<T>(pub T);
unsafe impl<T> Send for SendWrapper<T> {}
/// Dummy error type for testing that implements ErrorCode.
#[derive(Debug)]
pub enum TestError {
/// Error from a string.
FromStr(String),
/// Simple test error.
Test,
}
impl<'a> From<&'a str> for TestError {
fn from(s: &'a str) -> Self {
TestError::FromStr(s.into())
}
}
impl ErrorCode for TestError {
fn error_code(&self) -> i32 {
use TestError::*;
match *self {
Test => -1,
FromStr(_) => -2,
}
}
}
impl Display for TestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use TestError::*;
match self {
Test => write!(f, "Test Error"),
FromStr(s) => write!(f, "{}", s),
}
}
}
|
pub mod loaders{
use assimp::Importer;
use glium::index::PrimitiveType;
use crate::my_game_engine::my_game_logic::my_renderer::{MyArmatureSkinVertex,VertexWeights,MyJoint,ModelRst,MyVertex,StaticMesh,AnimatedMesh};
use cgmath::Matrix3;
use cgmath::Quaternion;
pub fn load_texture(display:&mut glium::Display, path:&str) -> glium::texture::SrgbTexture2d {
let image = image::open(path).unwrap().to_rgba();
let image_dimensions = image.dimensions();
let image = glium::texture::RawImage2d::from_raw_rgba_reversed(&image.into_raw(), image_dimensions);
glium::texture::SrgbTexture2d::new(display, image).unwrap()
}
pub fn load_static_meshes(display:&mut glium::Display, path:&str) -> Vec<(ModelRst, StaticMesh)>{
let mut smv :Vec<(ModelRst, StaticMesh)> = Vec::new();
let mut importer = Importer::new();
importer.triangulate(true);
importer.generate_normals(|x| x.enable = true);
let scene = importer.read_file(path).unwrap();
for mesh in scene.mesh_iter() {
let pos:Vec<[f32;3]>= mesh.vertex_iter().map(|v| v.into()).collect();
let norm:Vec<[f32;3]>= mesh.normal_iter().map(|v| v.into()).collect();
let tex:Vec<[f32;3]>= mesh.texture_coords_iter(0).map(|v| v.into()).collect();
let mut verts:Vec<MyVertex> = Vec::new();
for i in 0..pos.len(){
verts.push(MyVertex {
position: pos[i],
normal: norm[i],
texture: [tex[i][0],tex[i][1]]
});
}
let vb = glium::VertexBuffer::new(display, &verts);
let mut indices:Vec<u16> = Vec::with_capacity(mesh.num_faces() as usize * 3);
for face in mesh.face_iter() {
indices.push(face[0] as u16);
indices.push(face[1] as u16);
indices.push(face[2] as u16);
}
let ib = glium::IndexBuffer::new(display, PrimitiveType::TrianglesList, &indices);
let rotation;
if path.ends_with(".dae"){
rotation = Matrix4::from_angle_x(cgmath::Rad(std::f32::consts::PI*3.0/2.0));
}else {
rotation = Matrix4::identity();
}
use cgmath::{Matrix4,SquareMatrix};
let m =(
ModelRst{
rotation: rotation,
scale: Matrix4::identity(),
translation: Matrix4::identity()
}, StaticMesh{
vertices: (vb.unwrap()),
indices: (ib.unwrap())
});
smv.push(m);
}
smv
}
pub fn load_animated_collada_mesh(display:&mut glium::Display, path:&str) -> (ModelRst,AnimatedMesh){
use cgmath::{Matrix4,SquareMatrix};
let cd = collada::document::ColladaDocument::from_path(std::path::Path::new(path)).unwrap();
let obj_set = cd.get_obj_set().unwrap();
let mut triangles_v :Vec<((usize,usize,usize),(usize,usize,usize),(usize,usize,usize))> = Vec::new();
let mut mesh : Vec<MyArmatureSkinVertex> = Vec::new();
let mut vertex_weights :Vec<VertexWeights> = Vec::new();
let mut indices :Vec<u16> = Vec::new();
let vertices = &obj_set.objects[0].vertices;
let normals = &obj_set.objects[0].normals;
let textures = &obj_set.objects[0].tex_vertices;
let bind_set = cd.get_bind_data_set().unwrap();
let weights = &bind_set.bind_data[0].weights;
for vw in &bind_set.bind_data[0].vertex_weights{
if vw.vertex as i16 > vertex_weights.len() as i16 -1 {
let vn = VertexWeights{
joint_i: [vw.joint,0,0,0],
weights: [vw.weight,0,0,0],
joint_c: 1
};
vertex_weights.push(vn);
}else {
let vn = vertex_weights.last_mut().unwrap();
vn.weights[vn.joint_c] = vw.weight;
vn.joint_i[vn.joint_c] = vw.joint;
vn.joint_c+=1;
}
}
let obj = &obj_set.objects[0];
for geo in &obj.geometry {
for mesh in &geo.mesh {
match mesh {
collada::PrimitiveElement::Triangles(triangles) => {
for triangle in &triangles.vertices {
let triangle_e = (((triangle.0).0,(triangle.0).2.unwrap(),(triangle.0).1.unwrap()),
((triangle.1).0,(triangle.1).2.unwrap(),(triangle.1).1.unwrap()),
((triangle.2).0,(triangle.2).2.unwrap(),(triangle.2).1.unwrap()));
triangles_v.push(triangle_e);
}
},
_ => ()
}
}
}
let mut i = 0;
for triangle in &triangles_v {
let wi = vertex_weights[(triangle.0).0].weights;
let vertex1 = MyArmatureSkinVertex {
position: [vertices[(triangle.0).0].x as f32,vertices[(triangle.0).0].y as f32,vertices[(triangle.0).0].z as f32],
normal: [normals[(triangle.0).1].x as f32,normals[(triangle.0).1].y as f32,normals[(triangle.0).1].z as f32],
texture: [textures[(triangle.0).2].x as f32,textures[(triangle.0).2].y as f32],
weights: [weights[wi[0]],weights[wi[1]],weights[wi[2]],weights[wi[3]]],
joint_mi: vertex_weights[(triangle.0).0].joint_i,
joint_c: vertex_weights[(triangle.0).0].joint_c as u8
};
indices.push(i);
i+=1;
let wi = vertex_weights[(triangle.1).0].weights;
let vertex2 = MyArmatureSkinVertex {
position: [vertices[(triangle.1).0].x as f32,vertices[(triangle.1).0].y as f32,vertices[(triangle.1).0].z as f32],
normal: [normals[(triangle.1).1].x as f32,normals[(triangle.1).1].y as f32,normals[(triangle.1).1].z as f32],
texture: [textures[(triangle.1).2].x as f32,textures[(triangle.1).2].y as f32],
weights: [weights[wi[0]],weights[wi[1]],weights[wi[2]],weights[wi[3]]],
joint_mi: vertex_weights[(triangle.1).0].joint_i,
joint_c: vertex_weights[(triangle.1).0].joint_c as u8
};
indices.push(i);
i+=1;
let wi = vertex_weights[(triangle.2).0].weights;
let vertex3 = MyArmatureSkinVertex {
position: [vertices[(triangle.2).0].x as f32,vertices[(triangle.2).0].y as f32,vertices[(triangle.2).0].z as f32],
normal: [normals[(triangle.2).1].x as f32,normals[(triangle.2).1].y as f32,normals[(triangle.2).1].z as f32],
texture: [textures[(triangle.2).2].x as f32,textures[(triangle.2).2].y as f32],
weights: [weights[wi[0]],weights[wi[1]],weights[wi[2]],weights[wi[3]]],
joint_mi: vertex_weights[(triangle.2).0].joint_i,
joint_c: vertex_weights[(triangle.2).0].joint_c as u8
};
indices.push(i);
i+=1;
mesh.push(vertex1);
mesh.push(vertex2);
mesh.push(vertex3);
}
let animations = &cd.get_animations().unwrap();
let joints = &cd.get_skeletons().unwrap()[0].joints;
let inverse_bind_poses = &bind_set.bind_data[0].inverse_bind_poses.clone();
let mut skeleton:Vec<MyJoint> = Vec::new();
for i in 0.. animations.len() {
let mut tsp_sample_poses:Vec<cgmath::Matrix4<f32>> = Vec::new();
for y in animations[i].sample_poses.clone() {
let mut nm:cgmath::Matrix4<f32> = y.into();
nm.transpose_self();
tsp_sample_poses.push(nm);
}
let mut tsp_inverse_bind_pose:cgmath::Matrix4<f32> = inverse_bind_poses[i].into();
tsp_inverse_bind_pose.transpose_self();
let translations:Vec<cgmath::Vector4<f32>> = Vec::new();
let rotations:Vec<cgmath::Quaternion<f32>> = Vec::new();
let lengths:Vec<f32> = Vec::new();
skeleton.push(MyJoint{
pose_m: tsp_sample_poses,
translations: translations,
rotations: rotations,
lengths: lengths,
time_stamps: animations[i].sample_times.clone(),
inv_bind_pos: tsp_inverse_bind_pose,
time_stamp_c: animations[i].sample_times.len() as u8,
parent_i: joints[i].parent_index as i8
});
}
let vb = glium::VertexBuffer::new(display, &mesh);
let ib = glium::IndexBuffer::new(display, PrimitiveType::TrianglesList, &indices);
let rotation = Matrix4::from_angle_x(cgmath::Rad(std::f32::consts::PI*3.0/2.0));
let c: cgmath::Matrix4<f32> = cgmath::Matrix4::identity();
let c:[[f32;4];4] = c.into();
let current_transforms= [c;64];
let mut m =(
ModelRst{
rotation: rotation,
scale: Matrix4::identity(),
translation: Matrix4::identity()
}, AnimatedMesh{
vertices: vb.unwrap(),
indices: ib.unwrap(),
skeleton: skeleton,
current_pose: current_transforms,
current_time_sec: 0.0,
running: false
}
);
let mut pose_transforms:Vec<Vec<Matrix4<f32>>> = Vec::new();
for x in 0..m.1.skeleton[0].time_stamp_c as usize{
let mut current_transforms:Vec<Matrix4<f32>> = Vec::new();
for joint in &m.1.skeleton{
let mut nm = joint.pose_m[x];
let mut current_joint = joint;
while current_joint.parent_i>=0{
current_joint = &m.1.skeleton[current_joint.parent_i as usize];
let pm = current_joint.pose_m[x];
nm = pm*nm;
}
current_transforms.push(nm);
}
pose_transforms.push(current_transforms);
}
for pose_t in &pose_transforms{
let mut y = 0;
for m1 in pose_t{
let q = Matrix3{
x: m1.x.truncate(),
y: m1.y.truncate(),
z: m1.z.truncate()
};
let q:Quaternion<f32> = q.into();
let t = m1.w;
let l = (t.x.powf(2.0)+t.y.powf(2.0)+t.z.powf(2.0)).sqrt();
m.1.skeleton[y].rotations.push(q);
m.1.skeleton[y].translations.push(t);
m.1.skeleton[y].lengths.push(l);
y+=1;
}
}
let mut i = 0;
for pose in &pose_transforms{
let mut y = 0;
for mat in pose {
println!("i:{} y:{} m:{:#?}",i,y,mat);
y+=1;
}
i+=1;
}
m
}
pub fn load_static_collada_mesh(display:&mut glium::Display, path:&str) -> (ModelRst, StaticMesh){
let cd = collada::document::ColladaDocument::from_path(std::path::Path::new(path)).unwrap();
let obj_set = cd.get_obj_set().unwrap();
let mut triangles_v :Vec<((usize,usize,usize),(usize,usize,usize),(usize,usize,usize))> = Vec::new();
let mut mesh : Vec<MyVertex> = Vec::new();
let mut indices : Vec<u16> = Vec::new();
let mut i:u16 = 0;
for obj in &obj_set.objects {
let vertices = &obj.vertices;
let normals = &obj.normals;
let textures = &obj.tex_vertices;
for geo in &obj.geometry {
for mesh in &geo.mesh {
match mesh {
collada::PrimitiveElement::Triangles(triangles) => {
for triangle in &triangles.vertices {
let triangle_e = (((triangle.0).0,(triangle.0).2.unwrap(),(triangle.0).1.unwrap()),
((triangle.1).0,(triangle.1).2.unwrap(),(triangle.1).1.unwrap()),
((triangle.2).0,(triangle.2).2.unwrap(),(triangle.2).1.unwrap()));
triangles_v.push(triangle_e);
}
},
_ => ()
}
}
}
for triangle in &triangles_v {
let vertex1 = MyVertex {
position: [vertices[(triangle.0).0].x as f32,vertices[(triangle.0).0].y as f32,vertices[(triangle.0).0].z as f32],
normal: [normals[(triangle.0).1].x as f32,normals[(triangle.0).1].y as f32,normals[(triangle.0).1].z as f32],
texture: [textures[(triangle.0).2].x as f32,textures[(triangle.0).2].y as f32],
};
indices.push(i);
i+=1;
let vertex2 = MyVertex {
position: [vertices[(triangle.1).0].x as f32,vertices[(triangle.1).0].y as f32,vertices[(triangle.1).0].z as f32],
normal: [normals[(triangle.1).1].x as f32,normals[(triangle.1).1].y as f32,normals[(triangle.1).1].z as f32],
texture: [textures[(triangle.1).2].x as f32,textures[(triangle.1).2].y as f32],
};
indices.push(i);
i+=1;
let vertex3 = MyVertex {
position: [vertices[(triangle.2).0].x as f32,vertices[(triangle.2).0].y as f32,vertices[(triangle.2).0].z as f32],
normal: [normals[(triangle.2).1].x as f32,normals[(triangle.2).1].y as f32,normals[(triangle.2).1].z as f32],
texture: [textures[(triangle.2).2].x as f32,textures[(triangle.2).2].y as f32],
};
indices.push(i);
i+=1;
mesh.push(vertex1);
mesh.push(vertex2);
mesh.push(vertex3);
}
}
let vb = glium::VertexBuffer::new(display, &mesh);
let ib = glium::IndexBuffer::new(display, PrimitiveType::TrianglesList, &indices);
let rotation = Matrix4::from_angle_x(cgmath::Rad(std::f32::consts::PI*3.0/2.0));
use cgmath::{Matrix4,SquareMatrix};
let m =(
ModelRst{
rotation: rotation,
scale: Matrix4::identity(),
translation: Matrix4::identity()
}, StaticMesh{
vertices: (vb.unwrap()),
indices: (ib.unwrap())
});
m
}
pub fn load_static_collada_mesh_rawdata(path:&str) -> (Vec<MyVertex>, Vec<u16>){
let cd = collada::document::ColladaDocument::from_path(std::path::Path::new(path)).unwrap();
let obj_set = cd.get_obj_set().unwrap();
//let anm_set = cd.get_animations().unwrap();
let mut triangles_v :Vec<((usize,usize,usize),(usize,usize,usize),(usize,usize,usize))> = Vec::new();
let mut mesh : Vec<MyVertex> = Vec::new();
let mut indices : Vec<u16> = Vec::new();
let mut i:u16 = 0;
for obj in &obj_set.objects {
let vertices = &obj.vertices;
let normals = &obj.normals;
let textures = &obj.tex_vertices;
for geo in &obj.geometry {
for mesh in &geo.mesh {
match mesh {
collada::PrimitiveElement::Triangles(triangles) => {
for triangle in &triangles.vertices {
let triangle_e = (((triangle.0).0,(triangle.0).2.unwrap(),(triangle.0).1.unwrap()),
((triangle.1).0,(triangle.1).2.unwrap(),(triangle.1).1.unwrap()),
((triangle.2).0,(triangle.2).2.unwrap(),(triangle.2).1.unwrap()));
triangles_v.push(triangle_e);
}
},
_ => ()
}
}
}
for triangle in &triangles_v {
let vertex1 = MyVertex {
position: [vertices[(triangle.0).0].x as f32,vertices[(triangle.0).0].y as f32,vertices[(triangle.0).0].z as f32],
normal: [normals[(triangle.0).1].x as f32,normals[(triangle.0).1].y as f32,normals[(triangle.0).1].z as f32],
texture: [textures[(triangle.0).2].x as f32,textures[(triangle.0).2].y as f32],
};
indices.push(i);
i+=1;
let vertex2 = MyVertex {
position: [vertices[(triangle.1).0].x as f32,vertices[(triangle.1).0].y as f32,vertices[(triangle.1).0].z as f32],
normal: [normals[(triangle.1).1].x as f32,normals[(triangle.1).1].y as f32,normals[(triangle.1).1].z as f32],
texture: [textures[(triangle.1).2].x as f32,textures[(triangle.1).2].y as f32],
};
indices.push(i);
i+=1;
let vertex3 = MyVertex {
position: [vertices[(triangle.2).0].x as f32,vertices[(triangle.2).0].y as f32,vertices[(triangle.2).0].z as f32],
normal: [normals[(triangle.2).1].x as f32,normals[(triangle.2).1].y as f32,normals[(triangle.2).1].z as f32],
texture: [textures[(triangle.2).2].x as f32,textures[(triangle.2).2].y as f32],
};
indices.push(i);
i+=1;
mesh.push(vertex1);
mesh.push(vertex2);
mesh.push(vertex3);
}
}
(mesh,indices)
}
} |
use crate::Counter;
use num_traits::Zero;
use std::hash::Hash;
use std::ops::{BitAnd, BitAndAssign};
impl<T, N> BitAnd for Counter<T, N>
where
T: Hash + Eq,
N: Ord + Zero,
{
type Output = Counter<T, N>;
/// Returns the intersection of `self` and `rhs` as a new `Counter`.
///
/// `out = c & d;` -> `out[x] == min(c[x], d[x])`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// let e = c & d;
///
/// let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(e.into_map(), expect);
/// ```
fn bitand(self, mut rhs: Counter<T, N>) -> Self::Output {
use std::cmp::min;
let mut counter = Counter::new();
for (key, lhs_count) in self.map {
if let Some(rhs_count) = rhs.remove(&key) {
let count = min(lhs_count, rhs_count);
counter.map.insert(key, count);
}
}
counter
}
}
impl<T, N> BitAndAssign for Counter<T, N>
where
T: Hash + Eq,
N: Ord + Zero,
{
/// Updates `self` with the intersection of `self` and `rhs`
///
/// `c &= d;` -> `c[x] == min(c[x], d[x])`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// c &= d;
///
/// let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(c.into_map(), expect);
/// ```
fn bitand_assign(&mut self, mut rhs: Counter<T, N>) {
for (key, rhs_count) in rhs.drain() {
if rhs_count < self[&key] {
self.map.insert(key, rhs_count);
}
}
}
}
|
pub fn reply(input: &'static str) -> &'static str {
if input.is_empty() {
"Fine. Be that way!"
} else if is_shout(input) {
"Whoa, chill out!"
} else if is_question(input) {
"Sure."
} else {
"Whatever."
}
}
fn is_shout(input: &'static str) -> bool {
input.to_uppercase() == input
}
fn is_question(input: &'static str) -> bool {
input.ends_with("?")
}
|
use aoc2018::*;
use std::ops;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Pos {
x: i64,
y: i64,
}
impl Pos {
pub fn new(x: i64, y: i64) -> Pos {
Pos { x, y }
}
pub fn neighbours(&self) -> [Pos; 8] {
let Pos { x, y } = *self;
[
Pos::new(x + 1, y - 1),
Pos::new(x + 1, y),
Pos::new(x + 1, y + 1),
Pos::new(x, y + 1),
Pos::new(x - 1, y + 1),
Pos::new(x - 1, y),
Pos::new(x - 1, y - 1),
Pos::new(x, y - 1),
]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Tile {
Wooded,
Lumberyard,
Open,
}
impl Tile {
fn as_str(&self) -> &str {
match *self {
Tile::Wooded => "|",
Tile::Lumberyard => "#",
Tile::Open => ".",
}
}
}
#[derive(Debug)]
struct Grid {
rx: ops::RangeInclusive<i64>,
ry: ops::RangeInclusive<i64>,
grid: HashMap<Pos, Tile>,
}
impl Grid {
pub fn load(input: &str) -> Result<Grid, Error> {
let mut grid = HashMap::new();
let mut rx = MinMax::default();
let mut ry = MinMax::default();
for (y, line) in input.lines().enumerate() {
let y = y as i64;
ry.sample(y);
for (x, c) in line.chars().enumerate() {
let x = x as i64;
rx.sample(x);
let pos = Pos::new(x, y);
grid.insert(
pos,
match c {
'#' => Tile::Lumberyard,
'|' => Tile::Wooded,
'.' => continue,
o => bail!("Unsupported tile: {}", o),
},
);
}
}
Ok(Grid {
grid,
rx: rx.range_inclusive(),
ry: ry.range_inclusive(),
})
}
pub fn get(&self, pos: Pos) -> Tile {
self.grid.get(&pos).cloned().unwrap_or(Tile::Open)
}
pub fn result(&self) -> usize {
let mut wooded = 0;
let mut lumberyards = 0;
for pos in self.coords() {
match self.get(pos) {
Tile::Wooded => wooded += 1,
Tile::Lumberyard => lumberyards += 1,
Tile::Open => {}
}
}
wooded * lumberyards
}
pub fn run<V>(&mut self, mut visuals: V, count: usize) -> Result<usize, Error>
where
V: Visuals,
{
use rayon::prelude::*;
let coords = self.coords().collect::<Vec<_>>();
V::setup();
visuals.draw(0, self)?;
let mut seen = HashMap::new();
let mut results = Vec::new();
for iter in 1..=count {
let result = coords
.par_iter()
.cloned()
.map(|pos| {
use self::Tile::*;
let tile = self.get(pos);
let mut wooden = 0;
let mut lumberyards = 0;
for n in pos.neighbours().iter().cloned() {
match self.get(n) {
Wooded => wooden += 1,
Lumberyard => lumberyards += 1,
Open => {}
}
}
match tile {
Open if wooden >= 3 => (pos, Wooded),
Open => (pos, tile),
Wooded if lumberyards >= 3 => (pos, Lumberyard),
Wooded => (pos, tile),
Lumberyard if lumberyards >= 1 && wooden >= 1 => (pos, Lumberyard),
Lumberyard => (pos, Open),
}
})
.collect::<Vec<_>>();
let grid = result.into_iter().collect::<HashMap<_, _>>();
let grid_vec = grid.clone().into_iter().collect::<Vec<_>>();
if let Some(prev) = seen.insert(grid_vec, iter) {
let cycle_length = iter - prev;
let offset = (count - iter) % cycle_length;
match results.get(results.len() - cycle_length + offset) {
Some(result) => return Ok(*result),
None => bail!("result not found"),
}
}
self.grid = grid;
results.push(self.result());
visuals.draw(iter, self)?;
}
V::teardown();
Ok(self.result())
}
pub fn coords(&self) -> impl Iterator<Item = Pos> + '_ {
self.ry
.clone()
.into_iter()
.flat_map(move |y| self.rx.clone().into_iter().map(move |x| Pos::new(x, y)))
}
}
fn main() -> Result<(), Error> {
// Example
assert_eq!(
Grid::load(input_str!("day18a.txt"))?.run(NcursesVisuals::default(), 10)?,
1147
);
// Part 1
assert_eq!(
Grid::load(input_str!("day18.txt"))?.run(NcursesVisuals::default(), 10)?,
606416
);
// Part 2 (fast solution)
assert_eq!(
Grid::load(input_str!("day18.txt"))?.run(NoopVisuals, 1_000_000_000)?,
210796
);
// Part 2 with nice visuals.
assert_eq!(
Grid::load(input_str!("day18.txt"))?.run(NcursesVisuals::default(), 1_000_000_000)?,
210796
);
Ok(())
}
trait Visuals {
fn setup();
fn teardown();
fn draw(&mut self, iter: usize, grid: &Grid) -> Result<(), Error>;
}
pub struct NoopVisuals;
impl Visuals for NoopVisuals {
fn setup() {}
fn teardown() {}
fn draw(&mut self, iter: usize, grid: &Grid) -> Result<(), Error> {
if iter % 1000 != 0 {
return Ok(());
}
let mut wooded = 0;
let mut lumberyards = 0;
for pos in grid.coords() {
match grid.get(pos) {
Tile::Wooded => wooded += 1,
Tile::Lumberyard => lumberyards += 1,
Tile::Open => {}
}
}
println!("iter: {}, {}", iter, wooded * lumberyards);
Ok(())
}
}
#[derive(Default)]
pub struct NcursesVisuals {
/// Only visualize once every n frame.
every: Option<usize>,
}
impl NcursesVisuals {
pub fn every(mut self, frame: usize) -> Self {
self.every = Some(frame);
self
}
}
impl Visuals for NcursesVisuals {
fn setup() {
use ncurses as n;
n::initscr();
n::noecho();
n::curs_set(n::CURSOR_VISIBILITY::CURSOR_INVISIBLE);
}
fn teardown() {
use ncurses as n;
n::mv(0, 0);
n::printw("press [enter] to exit...");
loop {
let c = n::getch();
if c == 10 {
break;
}
}
n::endwin();
}
fn draw(&mut self, iter: usize, grid: &Grid) -> Result<(), Error> {
use ncurses as n;
if let Some(every) = self.every {
n::mvprintw(0, 0, &format!("Iter: {}", iter));
n::refresh();
if iter % every != 0 {
return Ok(());
}
} else {
std::thread::sleep(std::time::Duration::from_millis(50));
}
n::erase();
n::mvprintw(0, 0, &format!("Iter: {}", iter));
for pos in grid.coords() {
n::mv(pos.y as i32 + 1, pos.x as i32);
n::printw(grid.get(pos).as_str());
}
n::refresh();
Ok(())
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use std::sync::Arc;
use common_arrow::arrow::datatypes::DataType;
use common_arrow::arrow::datatypes::Field as ArrowField;
use common_arrow::arrow::io::parquet::read::column_iter_to_arrays;
use common_arrow::parquet::compression::Compression;
use common_arrow::parquet::metadata::ColumnDescriptor;
use common_arrow::parquet::metadata::Descriptor;
use common_arrow::parquet::read::BasicDecompressor;
use common_arrow::parquet::read::PageMetaData;
use common_arrow::parquet::read::PageReader;
use common_arrow::parquet::schema::types::FieldInfo;
use common_arrow::parquet::schema::types::ParquetType;
use common_arrow::parquet::schema::types::PhysicalType;
use common_arrow::parquet::schema::types::PrimitiveType;
use common_arrow::parquet::schema::Repetition;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::Column;
use common_expression::ColumnId;
use opendal::Operator;
use storages_common_cache::CacheKey;
use storages_common_cache::InMemoryItemCacheReader;
use storages_common_cache::LoadParams;
use storages_common_cache::Loader;
use storages_common_cache_manager::CachedObject;
use storages_common_index::filters::Filter;
use storages_common_index::filters::Xor8Filter;
use storages_common_table_meta::meta::SingleColumnMeta;
use crate::metrics::metrics_inc_block_index_read_bytes;
type CachedReader = InMemoryItemCacheReader<Xor8Filter, Xor8FilterLoader>;
/// Load the filter of a given bloom index column. Also
/// - generates the proper cache key
/// - takes cares of getting the correct cache instance from [CacheManager]
pub struct BloomColumnFilterReader {
cached_reader: CachedReader,
param: LoadParams,
}
impl BloomColumnFilterReader {
pub fn new(
index_path: String,
column_id: ColumnId,
column_name: String,
column_chunk_meta: &SingleColumnMeta,
operator: Operator,
) -> Self {
let meta = column_chunk_meta;
let cache_key = format!("{index_path}-{column_id}");
// the schema of bloom filter block is fixed, as following
let base_type = PrimitiveType {
field_info: FieldInfo {
name: column_name.clone(),
repetition: Repetition::Required,
id: None,
},
logical_type: None,
converted_type: None,
physical_type: PhysicalType::ByteArray,
};
let descriptor = Descriptor {
primitive_type: base_type.clone(),
max_def_level: 0,
max_rep_level: 0,
};
let base_parquet_type = ParquetType::PrimitiveType(base_type);
let loader = Xor8FilterLoader {
offset: meta.offset,
len: meta.len,
cache_key,
operator,
column_descriptor: ColumnDescriptor::new(
descriptor,
vec![column_name],
base_parquet_type,
),
};
let cached_reader = CachedReader::new(Xor8Filter::cache(), loader);
let param = LoadParams {
location: index_path,
len_hint: None,
ver: 0,
put_cache: true,
};
BloomColumnFilterReader {
cached_reader,
param,
}
}
pub async fn read(&self) -> Result<Arc<Xor8Filter>> {
self.cached_reader.read(&self.param).await
}
}
/// Loader that fetch range of the target object with customized cache key
pub struct Xor8FilterLoader {
pub offset: u64,
pub len: u64,
pub cache_key: String,
pub operator: Operator,
pub column_descriptor: ColumnDescriptor,
}
#[async_trait::async_trait]
impl Loader<Xor8Filter> for Xor8FilterLoader {
async fn load(&self, params: &LoadParams) -> Result<Xor8Filter> {
let bytes = self
.operator
.range_read(¶ms.location, self.offset..self.offset + self.len)
.await?;
let page_meta_data = PageMetaData {
column_start: 0,
num_values: 1,
compression: Compression::Uncompressed,
descriptor: self.column_descriptor.descriptor.clone(),
};
let page_reader = PageReader::new_with_page_meta(
std::io::Cursor::new(bytes),
page_meta_data,
Arc::new(|_, _| true),
vec![],
usize::MAX,
);
let decompressor = BasicDecompressor::new(page_reader, vec![]);
let column_type = self.column_descriptor.descriptor.primitive_type.clone();
let filed_name = self.column_descriptor.path_in_schema[0].to_owned();
let field = ArrowField::new(filed_name, DataType::Binary, false);
let mut array_iter =
column_iter_to_arrays(vec![decompressor], vec![&column_type], field, None, 1)?;
if let Some(array) = array_iter.next() {
let array = array?;
let col =
Column::from_arrow(array.as_ref(), &common_expression::types::DataType::String);
let filter_bytes = col
.as_string()
.map(|str| unsafe { str.index_unchecked(0) })
.ok_or_else(|| {
// BloomPruner will log and handle this exception
ErrorCode::Internal(
"unexpected exception: load bloom filter raw data as string failed",
)
})?;
metrics_inc_block_index_read_bytes(filter_bytes.len() as u64);
let (filter, _size) = Xor8Filter::from_bytes(filter_bytes)?;
Ok(filter)
} else {
Err(ErrorCode::StorageOther(
"bloom index data not available as expected",
))
}
}
fn cache_key(&self, _params: &LoadParams) -> CacheKey {
self.cache_key.clone()
}
}
|
//! Reader-based compression/decompression streams
use std::io::prelude::*;
use std::io::{self, BufReader};
use bufread;
use super::CompressParams;
/// A compression stream which wraps an uncompressed stream of data. Compressed
/// data will be read from the stream.
pub struct BrotliEncoder<R: Read> {
inner: bufread::BrotliEncoder<BufReader<R>>,
}
/// A decompression stream which wraps a compressed stream of data. Decompressed
/// data will be read from the stream.
pub struct BrotliDecoder<R: Read> {
inner: bufread::BrotliDecoder<BufReader<R>>,
}
impl<R: Read> BrotliEncoder<R> {
/// Create a new compression stream which will compress at the given level
/// to read compress output to the give output stream.
///
/// The `level` argument here is typically 0-9 with 6 being a good default.
pub fn new(r: R, level: u32) -> BrotliEncoder<R> {
BrotliEncoder {
inner: bufread::BrotliEncoder::new(BufReader::new(r), level),
}
}
/// Configure the compression parameters of this encoder.
pub fn from_params( r: R, params: &CompressParams) -> BrotliEncoder<R> {
BrotliEncoder{
inner: bufread::BrotliEncoder::from_params(
BufReader::with_capacity(params.get_lgwin_readable(),r), params)
}
}
/// Acquires a reference to the underlying stream
pub fn get_ref(&self) -> &R {
self.inner.get_ref().get_ref()
}
/// Acquires a mutable reference to the underlying stream
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
self.inner.get_mut().get_mut()
}
/// Unwrap the underlying writer, finishing the compression stream.
pub fn into_inner(self) -> R {
self.inner.into_inner().into_inner()
}
}
impl<R: Read> Read for BrotliEncoder<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
}
impl<R: Read> BrotliDecoder<R> {
/// Create a new decompression stream, which will read compressed
/// data from the given input stream and decompress it.
pub fn new(r: R) -> BrotliDecoder<R> {
BrotliDecoder {
inner: bufread::BrotliDecoder::new(BufReader::new(r)),
}
}
/// Acquires a reference to the underlying stream
pub fn get_ref(&self) -> &R {
self.inner.get_ref().get_ref()
}
/// Acquires a mutable reference to the underlying stream
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
self.inner.get_mut().get_mut()
}
/// Unwrap the underlying writer, finishing the compression stream.
pub fn into_inner(self) -> R {
self.inner.into_inner().into_inner()
}
}
impl<R: Read> Read for BrotliDecoder<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
}
#[cfg(test)]
mod tests {
use std::io::prelude::*;
use read::{BrotliEncoder, BrotliDecoder};
use rand::{thread_rng, Rng};
#[test]
fn smoke() {
let m: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8];
let mut c = BrotliEncoder::new(m, 6);
let mut data = vec![];
c.read_to_end(&mut data).unwrap();
let mut d = BrotliDecoder::new(&data[..]);
let mut data2 = Vec::new();
d.read_to_end(&mut data2).unwrap();
assert_eq!(data2, m);
}
#[test]
fn smoke2() {
let m: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8];
let c = BrotliEncoder::new(m, 6);
let mut d = BrotliDecoder::new(c);
let mut data = vec![];
d.read_to_end(&mut data).unwrap();
assert_eq!(data, [1, 2, 3, 4, 5, 6, 7, 8]);
}
#[test]
fn smoke3() {
let m = vec![3u8; 128 * 1024 + 1];
let c = BrotliEncoder::new(&m[..], 6);
let mut d = BrotliDecoder::new(c);
let mut data = vec![];
d.read_to_end(&mut data).unwrap();
assert!(data == &m[..]);
}
#[test]
fn self_terminating() {
let m = vec![3u8; 128 * 1024 + 1];
let mut c = BrotliEncoder::new(&m[..], 6);
let mut result = Vec::new();
c.read_to_end(&mut result).unwrap();
let v = thread_rng().gen_iter::<u8>().take(1024).collect::<Vec<_>>();
for _ in 0..200 {
result.extend(v.iter().map(|x| *x));
}
let mut d = BrotliDecoder::new(&result[..]);
let mut data = Vec::with_capacity(m.len());
unsafe { data.set_len(m.len()); }
assert!(d.read(&mut data).unwrap() == m.len());
assert!(data == &m[..]);
}
#[test]
fn zero_length_read_at_eof() {
let m = Vec::new();
let mut c = BrotliEncoder::new(&m[..], 6);
let mut result = Vec::new();
c.read_to_end(&mut result).unwrap();
let mut d = BrotliDecoder::new(&result[..]);
let mut data = Vec::new();
assert!(d.read(&mut data).unwrap() == 0);
}
#[test]
fn zero_length_read_with_data() {
let m = vec![3u8; 128 * 1024 + 1];
let mut c = BrotliEncoder::new(&m[..], 6);
let mut result = Vec::new();
c.read_to_end(&mut result).unwrap();
let mut d = BrotliDecoder::new(&result[..]);
let mut data = Vec::new();
assert!(d.read(&mut data).unwrap() == 0);
}
#[test]
fn qc() {
::quickcheck::quickcheck(test as fn(_) -> _);
fn test(v: Vec<u8>) -> bool {
let r = BrotliEncoder::new(&v[..], 6);
let mut r = BrotliDecoder::new(r);
let mut v2 = Vec::new();
r.read_to_end(&mut v2).unwrap();
v == v2
}
}
}
|
use crate::key::TypedKey;
use crate::DataStore;
use crate::{cache, dir, file, filter};
use itertools::Itertools;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use thiserror::Error;
#[derive(Debug)]
pub enum DiffTarget {
FileSystem(PathBuf, Vec<String>, PathBuf),
Database(TypedKey<dir::FSItem>),
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct DeletedDiffResult {
path: PathBuf,
is_dir: bool,
original_key: Option<TypedKey<dir::FSItem>>,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct ModifiedDiffResult {
path: PathBuf,
original_key: TypedKey<dir::FSItem>,
new_key: TypedKey<dir::FSItem>,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct AddedDiffResult {
path: PathBuf,
is_dir: bool,
new_key: Option<TypedKey<dir::FSItem>>,
}
#[derive(Debug)]
pub struct DiffResult {
deleted: Vec<DeletedDiffResult>,
added: Vec<AddedDiffResult>,
modified: Vec<ModifiedDiffResult>,
}
#[derive(Debug, Error)]
pub enum CompareError {
#[error("io error: {_0}")]
IOError(#[from] std::io::Error),
#[error("error when hashing fs item: {_0}")]
HashError(#[from] dir::HashFsItemError),
#[error("error when walking database items: {_0}")]
WalkError(#[from] dir::WalkFsItemsError),
#[error("error when walking filesystem items: {_0}")]
RealWalkError(#[from] dir::WalkRealFsItemsError),
}
pub fn compare<'a>(
ds: &'a mut impl DataStore,
from: DiffTarget,
to: Option<TypedKey<dir::FSItem>>,
cache: impl Into<Option<&'a mut cache::SqliteCache>>,
) -> Result<DiffResult, CompareError> {
let cache = cache.into();
let cache = cache.as_ref();
let from_path;
let from_map = match from {
DiffTarget::FileSystem(path, filters, folder_path) => {
let exclude = filter::make_filter_fn(&filters, folder_path);
let fs_items = dir::walk_real_fs_items(&path, &exclude)?;
from_path = Some(path);
either::Left(fs_items)
}
DiffTarget::Database(key) => {
let db_items = dir::walk_fs_items(ds, key)?;
from_path = None;
either::Right(db_items)
}
};
let to_map = match to {
Some(t) => dir::walk_fs_items(ds, t)?,
None => HashMap::new(),
};
let from_keys: HashSet<PathBuf> = from_map.clone().either(
|x| x.keys().cloned().collect(),
|x| x.keys().cloned().collect(),
);
let to_keys: HashSet<PathBuf> = to_map.keys().cloned().collect();
let mut in_from_only: Vec<AddedDiffResult> = from_keys
.difference(&to_keys)
.map(|x| AddedDiffResult {
path: x.clone(),
new_key: from_map.as_ref().either(
|y| {
if !y[x] {
// this is a file
match dir::hash_fs_item(
ds,
x,
*cache.expect("you must pass a cache if you're hashing the fs"),
) {
Ok(h) => Some(h.into()),
Err(e) => panic!(e),
}
} else {
// directories don't have a hash
None
}
},
|y| Some(y[x].0),
),
is_dir: from_map.as_ref().either(|y| y[x], |y| y[x].1),
})
.collect();
let mut in_to_only: Vec<DeletedDiffResult> = to_keys
.difference(&from_keys)
.map(|x| DeletedDiffResult {
path: x.clone(),
original_key: Some(to_map[x].0),
is_dir: from_map.as_ref().either(|y| y[x], |y| y[x].1),
})
.collect();
let in_both: Vec<_> = from_keys.intersection(&to_keys).collect();
let mut modified = Vec::new();
for path in in_both {
let f;
match &from_map {
either::Left(fs_items) => {
if fs_items[path] {
continue;
}
f = dir::hash_fs_item(
ds,
&from_path
.as_ref()
.expect("should have been populated")
.join(path),
*cache.expect("you must pass a cache if you're hashing the fs"),
)?
.into();
}
either::Right(db_items) => f = db_items[path].0,
}
let t = to_map[path];
if f != t.0 {
let dr = ModifiedDiffResult {
original_key: t.0,
new_key: f,
path: path.clone(),
};
modified.push(dr);
}
}
in_from_only.sort_unstable();
in_to_only.sort_unstable();
modified.sort_unstable();
Ok(DiffResult {
deleted: in_to_only,
added: in_from_only,
modified,
})
}
pub fn simplify(r: DiffResult) -> DiffResult {
let mut deleted = Vec::new();
let mut added = Vec::new();
if !r.added.is_empty() {
for p in r.added {
if !added
.iter()
.any(|x: &AddedDiffResult| p.path.starts_with(&x.path))
{
added.push(p);
}
}
}
if !r.deleted.is_empty() {
for p in r.deleted {
if !deleted
.iter()
.any(|x: &DeletedDiffResult| p.path.starts_with(&x.path))
{
deleted.push(p);
}
}
}
DiffResult {
added,
modified: r.modified,
deleted,
}
// Directories can't be modified, so we don't need to simplify here
}
pub fn print_diff_result(r: DiffResult) {
let r = simplify(r);
use colored::*;
if !r.added.is_empty() {
println!("{}", "added:".green());
for p in r.added {
match p.new_key {
Some(_) => println!(" {}", p.path.display()),
None => println!(" {}/", p.path.display().to_string().bold()),
}
}
}
if !r.deleted.is_empty() {
println!("{}", "deleted:".red());
for p in r.deleted {
match p.original_key {
Some(_) => println!(" {}", p.path.display()),
None => println!(" {}/", p.path.display().to_string().bold()),
}
}
}
if !r.modified.is_empty() {
println!("{}", "modified:".blue());
for p in r.modified {
println!(" {}", p.path.display());
}
}
}
pub fn print_stat_diff_result(ds: &impl DataStore, r: DiffResult) {
let stat = line_stat(ds, r);
print_line_stat(stat);
}
pub fn print_patch_diff_result(ds: &impl DataStore, r: DiffResult) -> Result<(), DiffPatchError> {
println!("{}", create_diff_patch_result(ds, r)?);
Ok(())
}
#[derive(Debug)]
pub struct LineStatResult {
items: Vec<FileStatResult>,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct FileStatResult {
fname: PathBuf,
added: usize,
removed: usize,
}
pub fn line_stat(ds: &impl DataStore, r: DiffResult) -> LineStatResult {
ldbg!(&r);
let mut items = Vec::new();
for added in r.added.into_iter().filter(|x| !x.is_dir) {
if let Some(k) = added.new_key {
items.push(FileStatResult {
fname: added.path,
added: line_ct(ds, k),
removed: 0,
});
}
}
for removed in r.deleted.into_iter().filter(|x| !x.is_dir) {
if let Some(k) = removed.original_key {
items.push(FileStatResult {
fname: removed.path,
added: 0,
removed: line_ct(ds, k),
});
}
}
for modified in r.modified {
let mut before = Vec::new();
file::read_data(ds, modified.original_key.into(), &mut before).unwrap();
let mut after = Vec::new();
file::read_data(ds, modified.new_key.into(), &mut after).unwrap();
let before_str = String::from_utf8_lossy(&before);
let after_str = String::from_utf8_lossy(&after);
let lines = diff::lines(&before_str, &after_str);
let mut removed: usize = 0;
let mut added: usize = 0;
for item in lines {
match item {
diff::Result::Left(_) => removed += 1,
diff::Result::Right(_) => added += 1,
diff::Result::Both(_, _) => {}
}
}
items.push(FileStatResult {
fname: modified.path,
added,
removed,
});
}
LineStatResult { items }
}
pub fn print_line_stat(mut lsr: LineStatResult) {
lsr.items.sort_unstable();
for item in lsr.items {
println!(
"{} +{} -{}",
item.fname.display(),
item.added,
item.removed
);
}
}
pub fn line_ct(ds: &impl DataStore, key: TypedKey<dir::FSItem>) -> usize {
let mut data = Vec::new();
file::read_data(ds, key.into(), &mut data).unwrap();
#[allow(clippy::naive_bytecount)]
// This whole function will be cached in the store at some point, this is just for testing
data.iter().filter(|x| **x == b'\n').count()
}
pub fn diff_result_empty(r: &DiffResult) -> bool {
r.added.is_empty() && r.deleted.is_empty() && r.modified.is_empty()
}
pub fn format_patch(p: &patch::Patch<'_>) -> String {
format!("{}\n", p)
}
const BEFORE_CONTEXT_LINES: usize = 3;
const AFTER_CONTEXT_LINES: usize = 5;
#[derive(Debug, Error)]
pub enum DiffPatchError {
#[error("tried to make patch with non-UTF8 files")]
Binary,
}
pub fn create_diff_patch_result(
ds: &impl DataStore,
r: DiffResult,
) -> Result<String, DiffPatchError> {
let mut result = String::new();
ldbg!(&r);
for added in r.added {
if added.is_dir {
} else if let Some(k) = added.new_key {
let path = added.path.to_string_lossy();
let meta = None;
let old = patch::File {
path: path.clone(),
meta: meta.clone(),
};
let new = patch::File { path, meta }; // For now we're just saying old == new
let mut hunks = Vec::new();
let mut data = Vec::new();
file::read_data(ds, k.into(), &mut data).unwrap();
let data = std::str::from_utf8(&data);
match data {
Ok(s) => {
let mut lines = Vec::new();
for line in s.lines() {
lines.push(patch::Line::Add(line));
}
hunks.push(patch::Hunk {
old_range: patch::Range { start: 0, count: 0 },
new_range: patch::Range {
start: 0,
count: lines.len() as u64,
},
lines,
});
}
Err(_) => {
return Err(DiffPatchError::Binary);
}
}
let patch = patch::Patch {
old,
new,
hunks,
end_newline: true,
};
let formatted_patch = format_patch(&patch);
result.push_str(&formatted_patch);
}
}
for removed in r.deleted {
if removed.is_dir {
} else if let Some(k) = removed.original_key {
let path = removed.path.to_string_lossy();
let meta = None;
let old = patch::File {
path: path.clone(),
meta: meta.clone(),
};
let new = patch::File { path, meta }; // For now we're just saying old == new
let mut hunks = Vec::new();
let mut data = Vec::new();
file::read_data(ds, k.into(), &mut data).unwrap();
let data = std::str::from_utf8(&data);
match data {
Ok(s) => {
let mut lines = Vec::new();
for line in s.lines() {
lines.push(patch::Line::Remove(line));
}
hunks.push(patch::Hunk {
new_range: patch::Range { start: 0, count: 0 },
old_range: patch::Range {
start: 0,
count: lines.len() as u64,
},
lines,
});
}
Err(_) => {
return Err(DiffPatchError::Binary);
}
}
let patch = patch::Patch {
old,
new,
hunks,
end_newline: true,
};
let formatted_patch = format_patch(&patch);
result.push_str(&formatted_patch);
}
}
for modified in r.modified {
let mut before = Vec::new();
ldbg!(&modified);
file::read_data(ds, modified.original_key.into(), &mut before).unwrap();
let mut after = Vec::new();
file::read_data(ds, modified.new_key.into(), &mut after).unwrap();
let before_str = String::from_utf8_lossy(&before);
let after_str = String::from_utf8_lossy(&after);
let patch_str =
patch_from_file_string(before_str.to_string(), after_str.to_string(), modified.path);
result.push_str(&patch_str);
}
Ok(result)
}
fn patch_from_file_string(before_str: String, after_str: String, path: PathBuf) -> String {
let lines = difference::Changeset::new(&before_str, &after_str, "\n");
let mut before_lineno = 1;
let mut after_lineno = 1;
let lines_ln: Vec<_> = lines
.diffs
.into_iter()
.map(|x| {
let mut result = Vec::new();
match x {
difference::Difference::Add(s) => {
for line in s.split('\n') {
result.push((
before_lineno,
after_lineno,
difference::Difference::Add(line.to_string()),
));
after_lineno += 1;
}
}
difference::Difference::Same(s) => {
for line in s.split('\n') {
result.push((
before_lineno,
after_lineno,
difference::Difference::Same(line.to_string()),
));
before_lineno += 1;
after_lineno += 1;
}
}
difference::Difference::Rem(s) => {
for line in s.split('\n') {
result.push((
before_lineno,
after_lineno,
difference::Difference::Rem(line.to_string()),
));
before_lineno += 1;
}
}
}
result
})
.flatten()
.collect();
let mut windows_vec = Vec::new();
for (idx, item) in lines_ln.iter().enumerate() {
let context = &lines_ln[(idx.saturating_sub(BEFORE_CONTEXT_LINES))
..=(idx
.saturating_add(AFTER_CONTEXT_LINES)
.min(lines_ln.len() - 1))];
windows_vec.push((item, context));
}
let groups = windows_vec.into_iter().group_by(|x| {
x.1.iter()
.any(|y| !matches!(y.2, difference::Difference::Same(_)))
});
let mut hunks = Vec::new();
for (key, group) in &groups {
if !key {
continue;
}
let collected: Vec<_> = group.map(|x| x.0).collect();
assert!(!collected.is_empty());
let (start_before, start_after, _) = collected.first().unwrap();
let (end_before, end_after, _) = collected.last().unwrap();
let before_range = patch::Range {
start: *start_before,
count: *end_before - *start_before,
};
let after_range = patch::Range {
start: *start_after,
count: *end_after - *start_after,
};
let mut lines = Vec::new();
for item in collected.iter().map(|x| &x.2) {
let patch_item = match item {
difference::Difference::Same(x) => patch::Line::Context(&x),
difference::Difference::Add(x) => patch::Line::Add(&x),
difference::Difference::Rem(x) => patch::Line::Remove(&x),
};
lines.push(patch_item);
}
let hunk = patch::Hunk {
old_range: before_range,
new_range: after_range,
lines,
};
hunks.push(hunk);
}
let patch = patch::Patch {
old: patch::File {
path: path.to_string_lossy(),
meta: None,
},
new: patch::File {
path: path.to_string_lossy(),
meta: None,
},
hunks,
end_newline: true,
};
format_patch(&patch)
}
#[cfg(test)]
mod tests {
use super::*;
proptest::proptest! {
#[test]
fn patch_from_file_string_doesnt_panic(before: String, after: String, path: String) {
let _ = patch_from_file_string(before, after, path.into());
}
}
}
|
//! SputnikVM implementation, traits and structs.
//!
//! SputnikVM works on two different levels. It handles:
//! 1. a transaction, or
//! 2. an Ethereum execution context.
//!
//! To interact with the virtual machine, you usually only need to
//! work with [VM](trait.VM.html) methods.
//!
//! ### A SputnikVM's Lifecycle
//!
//! A VM can be started after it is given a `Transaction` (or
//! `Context`) and a `BlockHeader`. The user can then `fire` or `step`
//! to run it. [`fire`](trait.VM.html#method.fire) runs the EVM code
//! (given in field `code` of the transaction) until it finishes or
//! cannot continue. However [`step`](trait.VM.html#tymethod.step)
//! only runs at most one instruction. If the virtual machine needs
//! some information (accounts in the current block, or block hashes
//! of previous blocks) it fails, returning a
//! [`RequireError`](errors/enum.RequireError.html) enumeration. With
//! the data returned in the `RequireError` enumeration, one can use
//! the methods
//! [`commit_account`](trait.VM.html#tymethod.commit_account) and
//! [`commit_blockhash`](trait.VM.html#tymethod.commit_blockhash) to
//! commit the information to the VM. `fire` or `step` can be
//! subsequently called to restart from that point. The current VM
//! status can always be obtained using the `status` function. Again,
//! see [VM](trait.VM.html) for a list of methods that can be applied.
//!
//! ### Patch: Specifying a Network and Hard-fork
//!
//! Every VM is associated with a `Patch`. This patch tells the VM
//! which Ethereum network and which hard fork it is on. You will need
//! to specify the patch as the type parameter. To interact with
//! multiple patches at the same time, it is recommended that you use
//! trait objects.
//!
//! The example below creates a new SputnikVM and stores the object in
//! `vm` which can be used to `fire`, `step` or get status on. To do
//! this, it must first create a transaction and a block header. The
//! patch associated with the VM is either `EmbeddedPatch` or
//! `VMTestPatch` depending on an arbitrary block number value set at
//! the beginning of the program.
//!
//! ```
//! use evm::{EmbeddedPatch, VMTestPatch,
//! HeaderParams, ValidTransaction, TransactionAction,
//! VM, SeqTransactionVM};
//! use bigint::{Gas, U256, Address};
//! use std::rc::Rc;
//!
//! fn main() {
//! let block_number = 1000;
//! let transaction = ValidTransaction {
//! caller: Some(Address::default()),
//! gas_price: Gas::zero(),
//! gas_limit: Gas::max_value(),
//! action: TransactionAction::Create,
//! value: U256::zero(),
//! input: Rc::new(Vec::new()),
//! nonce: U256::zero()
//! };
//! let header = HeaderParams {
//! beneficiary: Address::default(),
//! timestamp: 0,
//! number: U256::zero(),
//! difficulty: U256::zero(),
//! gas_limit: Gas::zero()
//! };
//! let cfg_before_500 = VMTestPatch::default();
//! let cfg_after_500 = EmbeddedPatch::default();
//! let vm = if block_number < 500 {
//! SeqTransactionVM::new(
//! &cfg_before_500,
//! transaction,
//! header
//! );
//! } else {
//! SeqTransactionVM::new(
//! &cfg_after_500,
//! transaction,
//! header
//! );
//! };
//! }
//! ```
//!
//! ### Transaction Execution
//!
//! To start a VM on the Transaction level, use the `TransactionVM`
//! struct. Usually, you want to use the sequential memory module
//! which can be done using the type definition
//! `SeqTransactionVM`.
//!
//! Calling `TransactionVM::new` or `SeqTransactionVM::new` requires
//! the transaction passed in to be valid (according to the rules for
//! an Ethereum transaction). If the transaction is invalid, the VM
//! will probably panic. If you want to handle untrusted transactions,
//! you should use `SeqTransactionVM::new_untrusted`, which will not
//! panic but instead return an error if the transaction is invalid.
//!
//! ### Context Execution
//!
//! To start a VM on the Context level, use the `ContextVM`
//! struct. Usually, you use the sequential memory module with the
//! type definition `SeqContextVM`. Context execution, as with other
//! EVM implementations, will not handle transaction-level gas
//! reductions.
#![deny(
unused_import_braces,
unused_imports,
unused_comparisons,
unused_must_use,
unused_variables,
non_shorthand_field_patterns,
unreachable_code,
missing_docs
)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc))]
// extern crates below are left in code on purpose even though it's discouraged in Edition 2018
// in the event of incorrect feature setting, the error will pop up on
// extern crate statement in lib.rs, which is easier to debug
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(feature = "c-secp256k1")]
extern crate secp256k1;
#[cfg(feature = "rust-secp256k1")]
extern crate secp256k1;
#[cfg(feature = "std")]
extern crate block;
// BUG: without old-style #[macro_use] extern crate, evm-rs cannot be compiled as a dependency.
#[macro_use]
extern crate log;
mod commit;
pub mod errors;
mod eval;
mod memory;
mod params;
mod patch;
mod pc;
mod stack;
mod transaction;
mod util;
pub use crate::commit::{AccountChange, AccountCommitment, AccountState, BlockhashState, Storage};
pub use crate::errors::{CommitError, NotSupportedError, OnChainError, PreExecutionError, RequireError};
pub use crate::eval::{Machine, MachineStatus, Runtime, State};
pub use crate::memory::{Memory, SeqMemory};
pub use crate::params::*;
pub use crate::patch::*;
pub use crate::pc::{Instruction, PCMut, Valids, PC};
pub use crate::stack::Stack;
pub use crate::transaction::{TransactionVM, UntrustedTransaction, ValidTransaction};
pub use crate::util::opcode::Opcode;
pub use block_core::TransactionAction;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
use alloc::{collections::btree_map as map, collections::BTreeSet as Set};
use bigint::{Address, Gas, H256, U256};
#[cfg(not(feature = "std"))]
use core::cmp::min;
#[cfg(feature = "std")]
use std::cmp::min;
#[cfg(feature = "std")]
use std::collections::{hash_map as map, HashSet as Set};
#[derive(Debug, Clone, PartialEq)]
/// VM Status
pub enum VMStatus {
/// A running VM.
Running,
/// VM is stopped without errors.
ExitedOk,
/// VM is stopped due to an error. The state of the VM is before
/// the last failing instruction.
ExitedErr(OnChainError),
/// VM is stopped because it does not support certain
/// operations. The client is expected to either drop the
/// transaction or panic. This rarely happens unless the executor
/// agrees upon on a really large number of gas limit, so it
/// usually can be safely ignored.
ExitedNotSupported(NotSupportedError),
}
/// Represents an EVM. This is usually the main interface for clients
/// to interact with.
pub trait VM {
/// Commit an account information to this VM. This should only
/// be used when receiving `RequireError`.
fn commit_account(&mut self, commitment: AccountCommitment) -> Result<(), CommitError>;
/// Commit a block hash to this VM. This should only be used when
/// receiving `RequireError`.
fn commit_blockhash(&mut self, number: U256, hash: H256) -> Result<(), CommitError>;
/// Returns the current status of the VM.
fn status(&self) -> VMStatus;
/// Read the next instruction to be executed.
fn peek(&self) -> Option<Instruction>;
/// Read the next opcode to be executed.
fn peek_opcode(&self) -> Option<Opcode>;
/// Run one instruction and return. If it succeeds, VM status can
/// still be `Running`. If the call stack has more than one items,
/// this will only executes the last items' one single
/// instruction.
fn step(&mut self) -> Result<(), RequireError>;
/// Run instructions until it reaches a `RequireError` or
/// exits. If this function succeeds, the VM status can only be
/// either `ExitedOk` or `ExitedErr`.
fn fire(&mut self) -> Result<(), RequireError> {
loop {
match self.status() {
VMStatus::Running => self.step()?,
VMStatus::ExitedOk | VMStatus::ExitedErr(_) | VMStatus::ExitedNotSupported(_) => return Ok(()),
}
}
}
/// Returns the changed or committed accounts information up to
/// current execution status.
fn accounts(&self) -> map::Values<Address, AccountChange>;
/// Returns all fetched or modified addresses.
fn used_addresses(&self) -> Set<Address>;
/// Returns the out value, if any.
fn out(&self) -> &[u8];
/// Returns the available gas of this VM.
fn available_gas(&self) -> Gas;
/// Returns the refunded gas of this VM.
fn refunded_gas(&self) -> Gas;
/// Returns logs to be appended to the current block if the user
/// decided to accept the running status of this VM.
fn logs(&self) -> &[Log];
/// Returns all removed account addresses as for current VM execution.
fn removed(&self) -> &[Address];
/// Returns the real used gas by the transaction or the VM
/// context. Only available when the status of the VM is
/// exited. Otherwise returns zero.
fn used_gas(&self) -> Gas;
}
/// A sequential VM. It uses sequential memory representation and hash
/// map storage for accounts.
pub type SeqContextVM<'a, P> = ContextVM<'a, SeqMemory, P>;
/// A sequential transaction VM. This is same as `SeqContextVM` except
/// it runs at transaction level.
pub type SeqTransactionVM<'a, P> = TransactionVM<'a, SeqMemory, P>;
/// A VM that executes using a context and block information.
pub struct ContextVM<'a, M, P: Patch> {
runtime: Runtime,
machines: Vec<Machine<'a, M, P>>,
fresh_account_state: AccountState<'a, P::Account>,
}
impl<'a, M: Memory, P: Patch> ContextVM<'a, M, P> {
/// Create a new VM using the given context, block header and patch.
pub fn new(patch: &'a P, context: Context, block: HeaderParams) -> Self {
let mut machines = Vec::new();
let account_patch = patch.account_patch();
machines.push(Machine::new(patch, context, 1));
ContextVM {
machines,
runtime: Runtime::new(block),
fresh_account_state: AccountState::new(account_patch),
}
}
/// Create a new VM with the given account state and blockhash state.
pub fn with_states(
patch: &'a P,
context: Context,
block: HeaderParams,
account_state: AccountState<'a, P::Account>,
blockhash_state: BlockhashState,
) -> Self {
let mut machines = Vec::new();
machines.push(Machine::with_states(patch, context, 1, account_state.clone()));
ContextVM {
machines,
runtime: Runtime::with_states(block, blockhash_state),
fresh_account_state: account_state,
}
}
/// Create a new VM with customized initialization code.
pub fn with_init<F: FnOnce(&mut ContextVM<M, P>)>(
patch: &'a P,
context: Context,
block: HeaderParams,
account_state: AccountState<'a, P::Account>,
blockhash_state: BlockhashState,
f: F,
) -> Self {
let mut vm = Self::with_states(patch, context, block, account_state, blockhash_state);
f(&mut vm);
vm.fresh_account_state =
AccountState::derive_from(patch.account_patch(), &vm.machines[0].state().account_state);
vm
}
/// Create a new VM with the result of the previous VM. This is
/// usually used by transaction for chainning them.
pub fn with_previous(patch: &'a P, context: Context, block: HeaderParams, vm: &'a ContextVM<'a, M, P>) -> Self {
Self::with_states(
patch,
context,
block,
vm.machines[0].state().account_state.clone(),
vm.runtime.blockhash_state.clone(),
)
}
/// Returns the current state of the VM.
pub fn current_state(&self) -> &State<M, P> {
self.current_machine().state()
}
/// Returns the current runtime machine.
pub fn current_machine(&self) -> &Machine<M, P> {
self.machines.last().unwrap()
}
/// Add a new context history hook.
pub fn add_context_history_hook<F: 'static + Fn(&Context)>(&mut self, f: F) {
self.runtime.context_history_hooks.push(Box::new(f));
debug!("registered a new history hook");
}
}
impl<'a, M: Memory, P: Patch> VM for ContextVM<'a, M, P> {
fn commit_account(&mut self, commitment: AccountCommitment) -> Result<(), CommitError> {
for machine in &mut self.machines {
machine.commit_account(commitment.clone())?;
}
debug!("committed account info: {:?}", commitment);
Ok(())
}
fn commit_blockhash(&mut self, number: U256, hash: H256) -> Result<(), CommitError> {
self.runtime.blockhash_state.commit(number, hash)?;
debug!("committed blockhash number {}: {}", number, hash);
Ok(())
}
#[allow(clippy::single_match)]
fn status(&self) -> VMStatus {
match self.machines.last().unwrap().status().clone() {
MachineStatus::ExitedNotSupported(err) => return VMStatus::ExitedNotSupported(err),
_ => (),
}
match self.machines[0].status() {
MachineStatus::Running | MachineStatus::InvokeCreate(_) | MachineStatus::InvokeCall(_, _) => {
VMStatus::Running
}
MachineStatus::ExitedOk => VMStatus::ExitedOk,
MachineStatus::ExitedErr(err) => VMStatus::ExitedErr(err),
MachineStatus::ExitedNotSupported(err) => VMStatus::ExitedNotSupported(err),
}
}
fn peek(&self) -> Option<Instruction> {
match self.machines.last().unwrap().status().clone() {
MachineStatus::Running => self.machines.last().unwrap().peek(),
_ => None,
}
}
fn peek_opcode(&self) -> Option<Opcode> {
match self.machines.last().unwrap().status().clone() {
MachineStatus::Running => self.machines.last().unwrap().peek_opcode(),
_ => None,
}
}
fn step(&mut self) -> Result<(), RequireError> {
match self.machines.last().unwrap().status().clone() {
MachineStatus::Running => {
self.machines.last_mut().unwrap().step(&self.runtime)?;
if self.machines.len() == 1 {
match self.machines.last().unwrap().status().clone() {
MachineStatus::ExitedOk | MachineStatus::ExitedErr(_) => self
.machines
.last_mut()
.unwrap()
.finalize_context(&self.fresh_account_state),
_ => (),
}
}
Ok(())
}
MachineStatus::ExitedOk | MachineStatus::ExitedErr(_) => {
if self.machines.is_empty() {
panic!()
} else if self.machines.len() == 1 {
Ok(())
} else {
let finished = self.machines.pop().unwrap();
self.machines.last_mut().unwrap().apply_sub(finished);
Ok(())
}
}
MachineStatus::ExitedNotSupported(_) => Ok(()),
MachineStatus::InvokeCall(context, _) => {
for hook in &self.runtime.context_history_hooks {
hook(&context)
}
let mut sub = self.machines.last().unwrap().derive(context);
sub.invoke_call()?;
self.machines.push(sub);
Ok(())
}
MachineStatus::InvokeCreate(context) => {
for hook in &self.runtime.context_history_hooks {
hook(&context)
}
let mut sub = self.machines.last().unwrap().derive(context);
sub.invoke_create()?;
self.machines.push(sub);
Ok(())
}
}
}
fn fire(&mut self) -> Result<(), RequireError> {
loop {
debug!("machines status:");
for (n, machine) in self.machines.iter().enumerate() {
debug!("Machine {}: {:x?}", n, machine.status());
}
match self.status() {
VMStatus::Running => self.step()?,
VMStatus::ExitedOk | VMStatus::ExitedErr(_) | VMStatus::ExitedNotSupported(_) => return Ok(()),
}
}
}
fn accounts(&self) -> map::Values<Address, AccountChange> {
self.machines[0].state().account_state.accounts()
}
fn used_addresses(&self) -> Set<Address> {
self.machines[0].state().account_state.used_addresses()
}
fn out(&self) -> &[u8] {
self.machines[0].state().out.as_slice()
}
fn available_gas(&self) -> Gas {
self.machines[0].state().available_gas()
}
fn refunded_gas(&self) -> Gas {
self.machines[0].state().refunded_gas
}
fn logs(&self) -> &[Log] {
self.machines[0].state().logs.as_slice()
}
fn removed(&self) -> &[Address] {
self.machines[0].state().removed.as_slice()
}
fn used_gas(&self) -> Gas {
let total_used = self.machines[0].state().total_used_gas();
let refund_cap = total_used / Gas::from(2u64);
let refunded = min(refund_cap, self.machines[0].state().refunded_gas);
total_used - refunded
}
}
|
use super::session::UserSession;
use crate::auth::session::get_cookie_from_header;
use crate::init::AppConnections;
use async_session::SessionStore;
use axum::{
extract::Extension,
http::{self, HeaderMap, HeaderValue, StatusCode},
response::IntoResponse,
};
use tracing::info;
pub async fn login(user_session: UserSession) -> impl IntoResponse {
let (header, session_body) = match user_session {
UserSession::GetSession(body) => (HeaderMap::new(), body),
UserSession::CreateNewSession { body, cookie } => {
let mut header = HeaderMap::new();
header.insert(
http::header::SET_COOKIE,
HeaderValue::from_str(cookie.to_string().as_str()).unwrap(),
);
(header, body)
}
};
info!("current user: {}", session_body.username);
header
}
pub async fn logout(
header: HeaderMap,
Extension(app_connections): Extension<AppConnections>,
) -> impl IntoResponse {
let store = app_connections.session_store;
// get cookie
if let Some(mut cookie) = get_cookie_from_header(&header) {
if let Some(session) = store
.load_session(cookie.value().to_string())
.await
.unwrap()
{
if store.destroy_session(session).await.is_ok() {
cookie.set_expires(time::OffsetDateTime::now_utc());
let mut header = HeaderMap::new();
header.insert(
http::header::SET_COOKIE,
HeaderValue::from_str(cookie.to_string().as_str()).unwrap(),
);
return (StatusCode::OK, header);
// return StatusCode::ACCEPTED;
}
}
}
(StatusCode::UNAUTHORIZED, HeaderMap::new())
}
|
use proptest::arbitrary::any;
use proptest::prop_assert_eq;
use proptest::strategy::{Just, Strategy};
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::list_to_existing_atom_1::result;
use crate::test::strategy;
#[test]
fn without_list_errors_badarg() {
run!(
|arc_process| strategy::term::is_not_list(arc_process.clone()),
|list| {
prop_assert_badarg!(result(list), format!("list ({}) is not a list", list));
Ok(())
},
);
}
#[test]
fn with_empty_list() {
let list = Term::NIL;
// as `""` can only be entered into the global atom table, can't test with non-existing atom
let existing_atom = Atom::str_to_term("");
assert_eq!(result(list), Ok(existing_atom));
}
#[test]
fn with_improper_list_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_not_list(arc_process.clone()),
)
.prop_map(|(arc_process, tail)| arc_process.cons(arc_process.integer('a'), tail))
},
|list| {
prop_assert_badarg!(result(list), format!("list ({}) is improper", list));
Ok(())
},
);
}
#[test]
fn with_list_without_existing_atom_errors_badarg() {
run!(
|arc_process| {
(Just(arc_process.clone()), any::<String>()).prop_map(|(arc_process, suffix)| {
let string = strategy::term::non_existent_atom(&suffix);
let codepoint_terms: Vec<Term> =
string.chars().map(|c| arc_process.integer(c)).collect();
arc_process.list_from_slice(&codepoint_terms)
})
},
|list| {
prop_assert_badarg!(
result(list),
"tried to convert to an atom that doesn't exist"
);
Ok(())
},
);
}
#[test]
// collisions due to Unicode escapes. Could be a normalization/canonicalization issue?
#[ignore]
fn with_list_with_existing_atom_returns_atom() {
run!(
|arc_process| {
(Just(arc_process.clone()), any::<String>()).prop_map(|(arc_process, string)| {
let codepoint_terms: Vec<Term> =
string.chars().map(|c| arc_process.integer(c)).collect();
(
arc_process.list_from_slice(&codepoint_terms),
Atom::str_to_term(&string),
)
})
},
|(list, atom)| {
prop_assert_eq!(result(list), Ok(atom));
Ok(())
},
);
}
|
use std::{cell::RefCell, rc::Rc};
use crate::graphics::{Circle, Drawable, Font, Text};
use crate::gui::UiElement;
use crate::State;
use gl_bindings::{AbstractContext, Context};
use na::{Isometry3, Matrix4, Point3, Translation3, Vector3, Vector4};
use std::f32;
struct WorldPoint {
text: Text<'static>,
dot: Circle,
hovered: bool,
}
/// A simple button that can be pressed.
pub struct WorldPoints {
screensize: (f32, f32),
points: Vec<WorldPoint>,
font: Rc<RefCell<Font<'static>>>,
camera_pos: (f32, f32, f32),
target_pos: (f32, f32, f32),
view_matrix: Matrix4<f32>,
}
impl WorldPoints {
/// Creates a new button.
pub fn new(screensize: (f32, f32), font: Rc<RefCell<Font<'static>>>) -> Self {
Self {
screensize,
points: Vec::new(), // ,
font,
camera_pos: (0.0, 0.0, 0.0),
target_pos: (0.0, 0.0, 0.0),
view_matrix: Matrix4::<f32>::identity(),
}
}
pub fn set_points(&mut self, points: Vec<(f32, f32, f32)>) {
self.points.clear();
self.points.push(WorldPoint {
text: Text::new(
"Center".to_owned(),
self.font.clone(),
0.0,
0.0 + 0.03,
0.0,
self.screensize,
),
dot: Circle::new(
0.0,
0.0,
0.0,
0.005,
f32::consts::PI / 2.0,
(0.0, 1.0, 0.0),
true,
),
hovered: false,
});
let mut id = 1;
for point in points {
let (x, y, z) = point;
self.points.push(WorldPoint {
text: Text::new(
format!("point {}", id).to_owned(),
self.font.clone(),
x,
y + 0.03,
z,
self.screensize,
),
dot: Circle::new(x, y, z, 0.005, f32::consts::PI / 2.0, (0.0, 1.0, 0.0), true),
hovered: false,
});
id += 1;
}
}
pub fn set_camera_pos(&mut self, pos: (f32, f32, f32)) {
self.camera_pos = pos;
}
pub fn set_camera_target_pos(&mut self, pos: (f32, f32, f32)) {
self.target_pos = pos;
}
pub fn set_view_matrix(&mut self, view_matrix: Matrix4<f32>) {
self.view_matrix = view_matrix;
}
}
impl UiElement for WorldPoints {
fn resize(&mut self, _screensize: (f32, f32)) {
//let text_coords = self.pos.to_relative(screensize).get_coordinates();
//self.text.set_position(text_coords.x1, text_coords.y1, screensize);
}
fn is_within(&self, x: f64, y: f64) -> bool {
for point in &self.points {
let (cx, cy, cz) = point.dot.get_center();
let screen_pos = self.view_matrix * Vector4::new(cx, cy, cz, 1.0);
let dx = screen_pos.x / screen_pos.w - x as f32;
let dy = screen_pos.y / screen_pos.w - y as f32;
if dx * dx + dy * dy < 0.02 * 0.02 {
return true;
}
}
false
}
fn click(&mut self, x: f64, y: f64, state: &mut State) {
for point in &self.points {
let (cx, cy, cz) = point.dot.get_center();
let screen_pos = self.view_matrix * Vector4::new(cx, cy, cz, 1.0);
let dx = screen_pos.x / screen_pos.w - x as f32;
let dy = screen_pos.y / screen_pos.w - y as f32;
if dx * dx + dy * dy < 0.02 * 0.02 {
state.camera_target = point.dot.get_center();
return;
}
}
}
fn mouse_moved(&mut self, x: f64, y: f64, _: &mut State) {
for point in &mut self.points {
point.hovered = false;
}
for point in &mut self.points {
let (cx, cy, cz) = point.dot.get_center();
let screen_pos = self.view_matrix * Vector4::new(cx, cy, cz, 1.0);
let dx = screen_pos.x / screen_pos.w - x as f32;
let dy = screen_pos.y / screen_pos.w - y as f32;
if dx * dx + dy * dy < 0.02 * 0.02 {
point.hovered = true;
return;
}
}
}
}
impl Drawable for WorldPoints {
fn draw_transformed(&self, view_matrix: &Matrix4<f32>) {
let (tx, ty, tz) = self.target_pos;
let (px, py, pz) = self.camera_pos;
const ZOOM_FACTOR: f32 = 2.0;
Context::get_context().disable(Context::DEPTH_TEST);
for point in &self.points {
let hover_factor = if point.hovered { 0.3 } else { 1.0 };
let scale = Matrix4::new_orthographic(
-ZOOM_FACTOR - hover_factor,
ZOOM_FACTOR + hover_factor,
-ZOOM_FACTOR - hover_factor,
ZOOM_FACTOR + hover_factor,
ZOOM_FACTOR + hover_factor,
-ZOOM_FACTOR - hover_factor,
);
let (ex, ey, ez) = point.text.get_position();
let (cx, cy, cz) = point.text.get_center();
let target: Point3<f32> = Point3::new(0.0, 0.0, 0.0);
let eye = Point3::new(px - tx, py - ty, pz - tz);
let view: Isometry3<f32> = Isometry3::look_at_lh(&target, &eye, &Vector3::y());
let trans = Translation3::new(-cx, -cy, -cz);
let trans2 = Translation3::new(ex, ey + (1.0 - hover_factor) / 50.0, ez);
let projection = view_matrix
* trans2.to_homogeneous()
* scale
* view.inverse().to_homogeneous()
* trans.to_homogeneous();
point.text.draw_transformed(&projection);
}
for point in &self.points {
let hover_factor = if point.hovered { 0.3 } else { 1.0 };
let scale = Matrix4::new_orthographic(
-hover_factor,
hover_factor,
-hover_factor,
hover_factor,
hover_factor,
-hover_factor,
);
let (cx, cy, cz) = point.dot.get_center();
let target: Point3<f32> = Point3::new(0.0, 0.0, 0.0);
let eye = Point3::new(px - tx, py - ty, pz - tz);
let view: Isometry3<f32> = Isometry3::look_at_lh(&target, &eye, &Vector3::y());
let trans = Translation3::new(-cx, -cy, -cz);
let trans2 = Translation3::new(cx, cy, cz);
let projection = view_matrix
* trans2.to_homogeneous()
* scale
* view.inverse().to_homogeneous()
* trans.to_homogeneous();
point.dot.draw_transformed(&projection);
}
Context::get_context().enable(Context::DEPTH_TEST);
}
}
|
#[doc = "Reader of register SDMMC_IDMACTRLR"]
pub type R = crate::R<u32, super::SDMMC_IDMACTRLR>;
#[doc = "Writer for register SDMMC_IDMACTRLR"]
pub type W = crate::W<u32, super::SDMMC_IDMACTRLR>;
#[doc = "Register SDMMC_IDMACTRLR `reset()`'s with value 0"]
impl crate::ResetValue for super::SDMMC_IDMACTRLR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `IDMAEN`"]
pub type IDMAEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IDMAEN`"]
pub struct IDMAEN_W<'a> {
w: &'a mut W,
}
impl<'a> IDMAEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `IDMABMODE`"]
pub type IDMABMODE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IDMABMODE`"]
pub struct IDMABMODE_W<'a> {
w: &'a mut W,
}
impl<'a> IDMABMODE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `IDMABACT`"]
pub type IDMABACT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IDMABACT`"]
pub struct IDMABACT_W<'a> {
w: &'a mut W,
}
impl<'a> IDMABACT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
impl R {
#[doc = "Bit 0 - IDMA enable This bit can only be written by firmware when DPSM is inactive (DPSMACT = 0)."]
#[inline(always)]
pub fn idmaen(&self) -> IDMAEN_R {
IDMAEN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Buffer mode selection. This bit can only be written by firmware when DPSM is inactive (DPSMACT = 0)."]
#[inline(always)]
pub fn idmabmode(&self) -> IDMABMODE_R {
IDMABMODE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Double buffer mode active buffer indication This bit can only be written by firmware when DPSM is inactive (DPSMACT = 0). When IDMA is enabled this bit is toggled by hardware."]
#[inline(always)]
pub fn idmabact(&self) -> IDMABACT_R {
IDMABACT_R::new(((self.bits >> 2) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - IDMA enable This bit can only be written by firmware when DPSM is inactive (DPSMACT = 0)."]
#[inline(always)]
pub fn idmaen(&mut self) -> IDMAEN_W {
IDMAEN_W { w: self }
}
#[doc = "Bit 1 - Buffer mode selection. This bit can only be written by firmware when DPSM is inactive (DPSMACT = 0)."]
#[inline(always)]
pub fn idmabmode(&mut self) -> IDMABMODE_W {
IDMABMODE_W { w: self }
}
#[doc = "Bit 2 - Double buffer mode active buffer indication This bit can only be written by firmware when DPSM is inactive (DPSMACT = 0). When IDMA is enabled this bit is toggled by hardware."]
#[inline(always)]
pub fn idmabact(&mut self) -> IDMABACT_W {
IDMABACT_W { w: self }
}
}
|
use assembler::directive_parsers::*;
use assembler::label_parsers::*;
use assembler::opcode_parsers::*;
use assembler::operand_parsers::*;
use assembler::register_parsers::*;
use assembler::SymbolTable;
use assembler::Token;
use nom::multispace;
use nom::types::CompleteStr;
#[derive(Debug, PartialEq)]
pub struct AssemblerInstruction {
pub opcode: Option<Token>,
pub label: Option<Token>,
pub directive: Option<Token>,
pub operand1: Option<Token>,
pub operand2: Option<Token>,
pub operand3: Option<Token>,
}
impl AssemblerInstruction {
pub fn to_bytes(&self) -> Vec<u8> {
let mut results = vec![];
match self.opcode {
Some(Token::Op { ref code }) => match code {
code => {
let code = *code;
results.push(code as u8);
}
}
_ => {
println!("Non-opcode found in opcode field");
std::process::exit(1);
}
};
for operand in vec![&self.operand1, &self.operand2, &self.operand3] {
match operand {
Some(t) => AssemblerInstruction::extract_operand(t, &mut results),
None => {}
}
}
results
}
pub fn is_label(&self) -> bool {
self.label.is_some()
}
pub fn is_directive(&self) -> bool {
self.directive.is_some()
}
pub fn is_opcode(&self) -> bool { self.opcode.is_some() }
pub fn get_label_name(&self) -> Option<String> {
match self.label.as_ref() {
Some(Token::LabelDeclaration { name }) => Some(name.clone()),
_ => None
}
}
pub fn get_directive_name(&self) -> Option<String> {
match self.directive.as_ref() {
Some(Token::Directive { name }) => Some(name.clone()),
_ => None
}
}
pub fn has_operands(&self) -> bool {
self.operand1.is_some() || self.operand2.is_some() || self.operand3.is_some()
}
pub fn get_string_constant(&self) -> Option<String> {
match self.operand1.as_ref() {
Some(Token::IrString { name }) => Some(name.clone()),
_ => None
}
}
fn extract_operand(t: &Token, results: &mut Vec<u8>) {
match t {
Token::Register { reg_num } => results.push(*reg_num),
Token::IntegerOperand { value } => {
let converted = *value as u16;
let byte1 = converted;
let byte2 = converted >> 8;
results.push(byte2 as u8);
results.push(byte1 as u8);
}
_ => {
println!("Opcode found in operand field");
std::process::exit(1);
}
}
}
}
named!(pub instruction<CompleteStr, AssemblerInstruction>,
do_parse!(
ins: alt!(
instruction_combined |
directive
) >>
(
ins
)
)
);
named!(instruction_combined<CompleteStr, AssemblerInstruction>,
do_parse!(
l: opt!(label_declaration) >>
o: opcode >>
o1: opt!(operand) >>
o2: opt!(operand) >>
o3: opt!(operand) >>
(
AssemblerInstruction{
opcode: Some(o),
label: l,
directive: None,
operand1: o1,
operand2: o2,
operand3: o3,
}
)
)
);
#[cfg(test)]
mod tests {
use instruction::Opcode;
use super::*;
#[test]
fn test_parse_instruction_form_three() {
let result = instruction(CompleteStr("add $0 $1 $2\n"));
assert_eq!(
result,
Ok((
CompleteStr(""),
AssemblerInstruction {
opcode: Some(Token::Op { code: Opcode::ADD }),
label: None,
directive: None,
operand1: Some(Token::Register { reg_num: 0 }),
operand2: Some(Token::Register { reg_num: 1 }),
operand3: Some(Token::Register { reg_num: 2 }),
}
))
);
}
#[test]
fn test_parse_instruction_form_two() {
let result = instruction(CompleteStr("load $0 #100\n"));
assert_eq!(
result,
Ok((
CompleteStr(""),
AssemblerInstruction {
opcode: Some(Token::Op { code: Opcode::LOAD }),
label: None,
directive: None,
operand1: Some(Token::Register { reg_num: 0 }),
operand2: Some(Token::IntegerOperand { value: 100 }),
operand3: None,
}
))
);
}
#[test]
fn test_parse_instruction_form_one() {
let result = instruction(CompleteStr("hlt\n"));
assert_eq!(
result,
Ok((
CompleteStr(""),
AssemblerInstruction {
opcode: Some(Token::Op { code: Opcode::HLT }),
label: None,
directive: None,
operand1: None,
operand2: None,
operand3: None,
}
))
);
}
} |
use proconio::{input, marker::Chars};
fn main() {
input! {
n: usize,
a: [Chars; n],
};
let mut b = a.clone();
for j in 1..n {
b[0][j] = a[0][j - 1];
}
for i in 1..n {
b[i - 1][0] = a[i][0];
}
for j in 0..(n - 1) {
b[n - 1][j] = a[n - 1][j + 1];
}
for i in 1..n {
b[i][n - 1] = a[i - 1][n - 1];
}
for r in b {
for ch in r {
print!("{}", ch);
}
print!("\n");
}
}
|
use duct::cmd;
use rand::prelude::*;
use std::env::consts::EXE_EXTENSION;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Once;
use tempfile::tempdir;
pub fn bao_exe() -> PathBuf {
// `cargo test` doesn't automatically run `cargo build`, so we do that ourselves.
static CARGO_BUILD_ONCE: Once = Once::new();
CARGO_BUILD_ONCE.call_once(|| {
cmd!("cargo", "build", "--quiet")
.run()
.expect("build failed");
});
Path::new("target")
.join("debug")
.join("bao")
.with_extension(EXE_EXTENSION)
}
#[test]
fn test_hash_one() {
let expected = blake3::hash(b"foo").to_hex();
let output = cmd!(bao_exe(), "hash").stdin_bytes("foo").read().unwrap();
assert_eq!(&*expected, &*output);
}
#[test]
fn test_hash_many() {
let dir = tempdir().unwrap();
let file1 = dir.path().join("file1");
fs::write(&file1, b"foo").unwrap();
let file2 = dir.path().join("file2");
fs::write(&file2, b"bar").unwrap();
let output = cmd!(bao_exe(), "hash", &file1, &file2, "-")
.stdin_bytes("baz")
.read()
.unwrap();
let foo_hash = blake3::hash(b"foo");
let bar_hash = blake3::hash(b"bar");
let baz_hash = blake3::hash(b"baz");
let expected = format!(
"{} {}\n{} {}\n{} -",
foo_hash.to_hex(),
file1.to_string_lossy(),
bar_hash.to_hex(),
file2.to_string_lossy(),
baz_hash.to_hex(),
);
assert_eq!(expected, output);
}
fn assert_hash_mismatch(output: &std::process::Output) {
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(bao::decode::Error::HashMismatch.to_string().as_str()));
}
#[test]
fn test_encode_decode_combined() {
let dir = tempdir().unwrap();
let input_path = dir.path().join("input");
let input_bytes = &b"abc"[..];
fs::write(&input_path, input_bytes).unwrap();
let input_hash = cmd!(bao_exe(), "hash")
.stdin_bytes(input_bytes)
.read()
.unwrap();
let encoded_path = dir.path().join("encoded");
cmd!(bao_exe(), "encode", &input_path, &encoded_path)
.run()
.unwrap();
let encoded_bytes = fs::read(&encoded_path).unwrap();
// Test decode using stdin and stdout.
let decoded_bytes = cmd!(bao_exe(), "decode", &input_hash)
.stdin_bytes(&*encoded_bytes)
.stdout_capture()
.run()
.unwrap()
.stdout;
assert_eq!(input_bytes, &*decoded_bytes);
// Make sure decoding with the wrong hash fails.
let zero_hash = "0".repeat(input_hash.len());
let output = cmd!(bao_exe(), "decode", &zero_hash)
.stdin_bytes(&*encoded_bytes)
.stdout_capture()
.stderr_capture()
.unchecked()
.run()
.unwrap();
assert_hash_mismatch(&output);
// Test decode using files. This exercises memmapping.
let decoded_path = dir.path().join("decoded");
cmd!(
bao_exe(),
"decode",
&input_hash,
&encoded_path,
&decoded_path
)
.run()
.unwrap();
assert_eq!(input_bytes, &*decoded_bytes);
// Test decode using --start and --count. Note that --start requires that the input is a file.
let partial_output = cmd!(
bao_exe(),
"decode",
&input_hash,
&encoded_path,
"--start=1",
"--count=1"
)
.stdout_capture()
.run()
.unwrap()
.stdout;
assert_eq!(input_bytes[1..2], *partial_output);
}
#[test]
fn test_encode_decode_outboard() {
let dir = tempdir().unwrap();
let input_path = dir.path().join("input");
let input_bytes = &b"abc"[..];
fs::write(&input_path, input_bytes).unwrap();
let input_hash = cmd!(bao_exe(), "hash")
.stdin_bytes(input_bytes)
.read()
.unwrap();
let outboard_path = dir.path().join("outboard");
cmd!(
bao_exe(),
"encode",
&input_path,
"--outboard",
&outboard_path
)
.run()
.unwrap();
// Test decode using stdin and stdout.
let decoded_bytes = cmd!(
bao_exe(),
"decode",
&input_hash,
"--outboard",
&outboard_path
)
.stdin_bytes(input_bytes)
.stdout_capture()
.run()
.unwrap()
.stdout;
assert_eq!(input_bytes, &*decoded_bytes);
// Make sure decoding with the wrong hash fails.
let zero_hash = "0".repeat(input_hash.len());
let output = cmd!(
bao_exe(),
"decode",
&zero_hash,
"--outboard",
&outboard_path
)
.stdin_bytes(input_bytes)
.stdout_capture()
.stderr_capture()
.unchecked()
.run()
.unwrap();
assert_hash_mismatch(&output);
// Test decode using --start and --count. Note that --start requires that the input is a file.
// (Note that the outboard case is never memmapped, so we don't need a separate test for that.)
let partial_output = cmd!(
bao_exe(),
"decode",
&input_hash,
&input_path,
"--outboard",
&outboard_path,
"--start=1",
"--count=1"
)
.stdout_capture()
.run()
.unwrap()
.stdout;
assert_eq!(input_bytes[1..2], *partial_output);
}
#[test]
fn test_slice() {
let input_len = 1_000_000;
let slice_start = input_len / 4;
let slice_len = input_len / 2;
let mut input = vec![0; input_len];
rand::thread_rng().fill_bytes(&mut input);
let hash = cmd!(bao_exe(), "hash").stdin_bytes(&*input).read().unwrap();
let dir = tempdir().unwrap();
let encoded_path = dir.path().join("encoded");
cmd!(bao_exe(), "encode", "-", &encoded_path)
.stdin_bytes(&*input)
.run()
.unwrap();
let outboard_path = dir.path().join("outboard");
cmd!(bao_exe(), "encode", "-", "--outboard", &outboard_path)
.stdin_bytes(&*input)
.run()
.unwrap();
// Do a combined mode slice to a file.
let slice_path = dir.path().join("slice");
cmd!(
bao_exe(),
"slice",
slice_start.to_string(),
slice_len.to_string(),
&encoded_path,
&slice_path
)
.run()
.unwrap();
let slice_bytes = fs::read(&slice_path).unwrap();
// Make sure the outboard mode gives the same result. Do this one to stdout.
let outboard_slice_bytes = cmd!(
bao_exe(),
"slice",
slice_start.to_string(),
slice_len.to_string(),
&encoded_path
)
.stdout_capture()
.run()
.unwrap()
.stdout;
assert_eq!(slice_bytes, outboard_slice_bytes);
// Test decoding the slice.
let decoded = cmd!(
bao_exe(),
"decode-slice",
&hash,
slice_start.to_string(),
slice_len.to_string()
)
.stdin_bytes(&*slice_bytes)
.stdout_capture()
.run()
.unwrap()
.stdout;
assert_eq!(&input[slice_start..][..slice_len], &*decoded);
// Test that decode-slice with the wrong hash fails.
let zero_hash = "0".repeat(hash.len());
let output = cmd!(
bao_exe(),
"decode-slice",
&zero_hash,
slice_start.to_string(),
slice_len.to_string()
)
.stdin_bytes(&*slice_bytes)
.stdout_capture()
.stderr_capture()
.unchecked()
.run()
.unwrap();
assert_hash_mismatch(&output);
}
|
#![windows_subsystem = "windows"]
extern crate azul;
use azul::prelude::*;
struct OpenGlAppState { }
impl Layout for OpenGlAppState {
fn layout(&self, _info: LayoutInfo<Self>) -> Dom<Self> {
// See below for the meaning of StackCheckedPointer::new(self)
Dom::new(
NodeType::GlTexture((
GlTextureCallback(render_my_texture),
StackCheckedPointer::new(self, self).unwrap()
))
)
}
}
fn render_my_texture(
_state: &StackCheckedPointer<OpenGlAppState>,
info: LayoutInfo<OpenGlAppState>,
hi_dpi_bounds: HidpiAdjustedBounds)
-> Option<Texture>
{
use azul::azul_dependencies::glium::Surface;
let texture = info.window.read_only_window().create_texture(
hi_dpi_bounds.physical_size.width as u32,
hi_dpi_bounds.physical_size.height as u32,
);
texture.as_surface().clear_color(0.0, 1.0, 0.0, 1.0);
Some(texture)
}
fn main() {
let app = App::new(OpenGlAppState { }, AppConfig::default());
let window = Window::new(WindowCreateOptions::default(), css::native()).unwrap();
app.run(window).unwrap();
} |
// Various ways to dereference a Box.
use std::ops::DerefMut;
struct Foo {
field: Box<ToString>
}
fn use_foo(f: &mut Foo) -> String {
// Doesn't work:
// my_method(*field)
// Works:
my_method(&mut *f.field)
// Works, but needs `use`:
// my_method(f.field.deref_mut())
}
fn my_method(x: &mut ToString) -> String {
x.to_string()
}
fn main() {
println!("{}", use_foo(&mut Foo{field: Box::new(3i32)}));
}
|
use chrono::prelude::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::convert::Into;
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
pub struct Point {
pub ts: DateTime<Utc>,
pub value: f64,
pub trace_id: Uuid,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SlimPoint {
pub ts: DateTime<Utc>,
pub value: f64,
}
impl Into<SlimPoint> for Point {
fn into(self) -> SlimPoint {
SlimPoint {
ts: self.ts,
value: self.value,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Trace {
pub id: Uuid,
pub name: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Default for Trace {
fn default() -> Self {
let now = Utc::now();
Self {
id: Uuid::new_v4(),
name: "".to_owned(),
created_at: now.to_owned(),
updated_at: now.to_owned(),
}
}
}
|
use std::io::BufReader;
use std::fs::File;
use std::io::prelude::*;
fn main() {
let f = File::open("inputs/day02.in").unwrap();
let file = BufReader::new(&f);
let (paper, ribbon) = file
.lines()
.map(|l| -> Vec<u32> {
let mut x: Vec<_> = l.
unwrap().
split('x').
map(|x| -> u32 { x.parse().unwrap() }).
collect();
x.sort();
x
})
.map(|x| (
2*x[0]*x[1] + 2*x[1]*x[2] + 2*x[2]*x[0] + x[0]*x[1],
2*x[0] + 2*x[1] + x[0]*x[1]*x[2]
))
.fold((0,0), |a, b| (a.0+b.0, a.1+b.1));
println!("1: {}", paper);
println!("2: {}", ribbon);
}
|
use crate::mysql::protocol::{Capabilities, Encode};
// https://dev.mysql.com/doc/internals/en/com-quit.html
#[derive(Debug)]
pub struct Quit;
impl Encode for Quit {
fn encode(&self, buf: &mut Vec<u8>, _: Capabilities) {
buf.push(0x01); // COM_QUIT
}
}
|
/// For compiling Javascript values
pub mod compiler;
/// For executing the compiled Javascript values
pub mod executor; |
//! This module provides an easy and safe way to interact with attributes of [Elements](../struct.Element.html)
//!
//! # Note
//! In the [crate::prelude](../prelude/index.html) the name for
//! [Attribute](enum.Attribute.html) is [Attr](../prelude/index.html) and for
//! [AttributeValue](enum.AttributeValue.html) is [AttrValue](../prelude/index.html)
//!
//! # Examples
//! ## 1) Setting attributes of a circle
//! ```
//! use svg_definitions::prelude::*;
//!
//! let circle = SVGElem::new(Tag::Circle)
//! .set(Attr::Radius, 10.0)
//! .set(Attr::Cx, 15)
//! .set(Attr::Cy, 15)
//! .set(Attr::StrokeWidth, 1)
//! .set(Attr::Stroke, "#000")
//! .set(Attr::Fill, "transparent");
//! ```
//!
//! ## 2) Setting attributes of a triangle
//! ```
//! use svg_definitions::prelude::*;
//!
//! let triangle = SVGElem::new(Tag::Path)
//! .set(Attr::StrokeWidth, 1)
//! .set(Attr::Stroke, "#000")
//! .set(Attr::Fill, "transparent")
//! .set(Attr::D, PathData::new()
//! .move_to((0.0, 0.0))
//! .line_to((10.0, 0.0))
//! .line_to((0.0, 10.0))
//! .line_to((0.0, 0.0))
//! .close_path()
//! );
//! ```
use std::clone::Clone;
use std::convert::From;
use std::hash::Hash;
/// An attribute to an Element
#[derive(PartialEq, Eq, Debug, Clone, Hash)]
pub enum Attribute {
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/accent-height)
AccentHeight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/accumulate)
Accumulate,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/additive)
Additive,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/alignment-baseline)
AlignmentBaseline,
/// No MDN Documentation available for this attribute
AllowReorder,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/alphabetic)
Alphabetic,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/amplitude)
Amplitude,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/arabic-form)
ArabicForm,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/ascent)
Ascent,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/attributeName)
AttributeName,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/attributeType)
AttributeType,
/// No MDN Documentation available for this attribute
AutoReverse,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/azimuth)
Azimuth,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/baseFrequency)
BaseFrequency,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/baseline-shift)
BaselineShift,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/baseProfile)
BaseProfile,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/bbox)
Bbox,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/begin)
Begin,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/bias)
Bias,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/by)
By,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/calcMode)
CalcMode,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/cap-height)
CapHeight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/class)
Class,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip)
Clip,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clipPathUnits)
ClipPathUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-path)
ClipPath,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-rule)
ClipRule,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color)
Color,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-interpolation)
ColorInterpolation,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-interpolation-filters)
ColorInterpolationfilters,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-profile)
ColorProfile,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/color-rendering)
ColorRendering,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/contentScriptType)
ContentScriptType,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/contentStyleType)
ContentStyleType,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/cursor)
Cursor,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/cx)
Cx,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/cy)
Cy,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d)
D,
/// No MDN Documentation available for this attribute
Decelerate,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/descent)
Descent,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/diffuseConstant)
DiffuseConstant,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/direction)
Direction,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/display)
Display,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/divisor)
Divisor,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dominant-baseline)
DominantBaseline,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dur)
Dur,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dx)
Dx,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dy)
Dy,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/edgeMode)
EdgeMode,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/elevation)
Elevation,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/enable-background)
EnableBackground,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/end)
End,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/exponent)
Exponent,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/externalResourcesRequired)
ExternalResourcesRequired,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill)
Fill,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity)
FillOpacity,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule)
FillRule,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/filter)
Filter,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/filterRes)
FilterRes,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/filterUnits)
FilterUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/flood-color)
FloodColor,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/flood-opacity)
FloodOpacity,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-family)
FontFamily,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size)
FontSize,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size-adjust)
FontSizeadjust,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-stretch)
FontStretch,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-style)
FontStyle,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-variant)
FontVariant,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-weight)
FontWeight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/format)
Format,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/from)
From,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fr)
Fr,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fx)
Fx,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fy)
Fy,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/g1)
G1,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/g2)
G2,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/glyph-name)
GlyphName,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/glyph-orientation-horizontal)
GlyphOrientationhorizontal,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/glyph-orientation-vertical)
GlyphOrientationvertical,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/glyphRef)
GlyphRef,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/gradientTransform)
GradientTransform,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/gradientUnits)
GradientUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/hanging)
Hanging,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/height)
Height,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/href)
Href,
/// No MDN Documentation available for this attribute
Hreflang,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/horiz-adv-x)
HorizAdvx,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/horiz-origin-x)
HorizOriginx,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/id)
Id,
/// No MDN Documentation available for this attribute
Ideographic,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/image-rendering)
ImageRendering,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/in)
In,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/in2)
In2,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/intercept)
Intercept,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/k)
K,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/k1)
K1,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/k2)
K2,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/k3)
K3,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/k4)
K4,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/kernelMatrix)
KernelMatrix,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/kernelUnitLength)
KernelUnitLength,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/kerning)
Kerning,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/keyPoints)
KeyPoints,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/keySplines)
KeySplines,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/keyTimes)
KeyTimes,
/// No MDN Documentation available for this attribute
Lang,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/lengthAdjust)
LengthAdjust,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing)
LetterSpacing,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/lighting-color)
LightingColor,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/limitingConeAngle)
LimitingConeAngle,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/local)
Local,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/marker-end)
MarkerEnd,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/marker-mid)
MarkerMid,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/marker-start)
MarkerStart,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/markerHeight)
MarkerHeight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/markerUnits)
MarkerUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/markerWidth)
MarkerWidth,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/mask)
Mask,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/maskContentUnits)
MaskContentUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/maskUnits)
MaskUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/mathematical)
Mathematical,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/max)
Max,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/media)
Media,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/method)
Method,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/min)
Min,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/mode)
Mode,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/name)
Name,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/numOctaves)
NumOctaves,
/// No MDN Documentation available for this attribute
Offset,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/opacity)
Opacity,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/operator)
Operator,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/order)
Order,
/// No MDN Documentation available for this attribute
Orient,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/orientation)
Orientation,
/// No MDN Documentation available for this attribute
Origin,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/overflow)
Overflow,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/overline-position)
OverlinePosition,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/overline-thickness)
OverlineThickness,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/panose-1)
Panose1,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/paint-order)
PaintOrder,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/path)
Path,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/pathLength)
PathLength,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/patternContentUnits)
PatternContentUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/patternTransform)
PatternTransform,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/patternUnits)
PatternUnits,
/// No MDN Documentation available for this attribute
Ping,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/pointer-events)
PointerEvents,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/points)
Points,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/pointsAtX)
PointsAtX,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/pointsAtY)
PointsAtY,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/pointsAtZ)
PointsAtZ,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAlpha)
PreserveAlpha,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio)
PreserveAspectRatio,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/primitiveUnits)
PrimitiveUnits,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/r)
R,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/radius)
Radius,
/// No MDN Documentation available for this attribute
ReferrerPolicy,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/refX)
RefX,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/refY)
RefY,
/// No MDN Documentation available for this attribute
Rel,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/rendering-intent)
RenderingIntent,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/repeatCount)
RepeatCount,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/repeatDur)
RepeatDur,
/// No MDN Documentation available for this attribute
RequiredExtensions,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/requiredFeatures)
RequiredFeatures,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/restart)
Restart,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/result)
Result,
/// No MDN Documentation available for this attribute
Rotate,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/rx)
Rx,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/ry)
Ry,
/// No MDN Documentation available for this attribute
Slope,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/spacing)
Spacing,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/specularConstant)
SpecularConstant,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/specularExponent)
SpecularExponent,
/// No MDN Documentation available for this attribute
Speed,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/spreadMethod)
SpreadMethod,
/// No MDN Documentation available for this attribute
StartOffset,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stdDeviation)
StdDeviation,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stemh)
Stemh,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stemv)
Stemv,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stitchTiles)
StitchTiles,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stop-color)
StopColor,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stop-opacity)
StopOpacity,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/strikethrough-position)
StrikethroughPosition,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/strikethrough-thickness)
StrikethroughThickness,
/// No MDN Documentation available for this attribute
String,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke)
Stroke,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray)
StrokeDasharray,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dashoffset)
StrokeDashoffset,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linecap)
StrokeLinecap,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linejoin)
StrokeLinejoin,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit)
StrokeMiterlimit,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-opacity)
StrokeOpacity,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width)
StrokeWidth,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/style)
Style,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/surfaceScale)
SurfaceScale,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/systemLanguage)
SystemLanguage,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/tabindex)
Tabindex,
/// No MDN Documentation available for this attribute
TableValues,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/target)
Target,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/targetX)
TargetX,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/targetY)
TargetY,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor)
TextAnchor,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-decoration)
TextDecoration,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-rendering)
TextRendering,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/textLength)
TextLength,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/to)
To,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform)
Transform,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/type)
Type,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/u1)
U1,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/u2)
U2,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/underline-position)
UnderlinePosition,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/underline-thickness)
UnderlineThickness,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/unicode)
Unicode,
/// No MDN Documentation available for this attribute
UnicodeBidi,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/unicode-range)
UnicodeRange,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/units-per-em)
UnitsPerem,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/v-alphabetic)
VAlphabetic,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/v-hanging)
VHanging,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/v-ideographic)
VIdeographic,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/v-mathematical)
VMathematical,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/values)
Values,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/vector-effect)
VectorEffect,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/version)
Version,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/vert-adv-y)
VertAdvy,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/vert-origin-x)
VertOriginx,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/vert-origin-y)
VertOriginy,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox)
ViewBox,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewTarget)
ViewTarget,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/visibility)
Visibility,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/width)
Width,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/widths)
Widths,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/word-spacing)
WordSpacing,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/writing-mode)
WritingMode,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/x)
X,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/x-height)
XHeight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/x1)
X1,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/x2)
X2,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xChannelSelector)
XChannelSelector,
/// No MDN Documentation available for this attribute
XlinkActuate,
/// No MDN Documentation available for this attribute
XlinkArcrole,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href)
XlinkHref,
/// No MDN Documentation available for this attribute
XlinkRole,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:show)
XlinkShow,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:title)
XlinkTitle,
/// No MDN Documentation available for this attribute
XlinkType,
/// No MDN Documentation available for this attribute
XmlBase,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xml:lang)
XmlLang,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xml:space)
XmlSpace,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/y)
Y,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/y1)
Y1,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/y2)
Y2,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/yChannelSelector)
YChannelSelector,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/z)
Z,
/// No MDN Documentation available for this attribute
ZoomAndPan,
/// For all attributes which are not direct svg attributes
UnmappedAttribute(String),
}
// Implementation of Attribute
impl ToString for Attribute {
fn to_string(&self) -> String {
use Attribute::*;
std::string::String::from(match self {
AccentHeight => "accent-height",
Accumulate => "accumulate",
Additive => "additive",
AlignmentBaseline => "alignment-baseline",
AllowReorder => "allowReorder",
Alphabetic => "alphabetic",
Amplitude => "amplitude",
ArabicForm => "arabic-form",
Ascent => "ascent",
AttributeName => "attributeName",
AttributeType => "attributeType",
AutoReverse => "autoReverse",
Azimuth => "azimuth",
BaseFrequency => "baseFrequency",
BaselineShift => "baseline-shift",
BaseProfile => "baseProfile",
Bbox => "bbox",
Begin => "begin",
Bias => "bias",
By => "by",
CalcMode => "calcMode",
CapHeight => "cap-height",
Class => "class",
Clip => "clip",
ClipPathUnits => "clipPathUnits",
ClipPath => "clip-path",
ClipRule => "clip-rule",
Color => "color",
ColorInterpolation => "color-interpolation",
ColorInterpolationfilters => "color-interpolation-filters",
ColorProfile => "color-profile",
ColorRendering => "color-rendering",
ContentScriptType => "contentScriptType",
ContentStyleType => "contentStyleType",
Cursor => "cursor",
Cx => "cx",
Cy => "cy",
D => "d",
Decelerate => "decelerate",
Descent => "descent",
DiffuseConstant => "diffuseConstant",
Direction => "direction",
Display => "display",
Divisor => "divisor",
DominantBaseline => "dominant-baseline",
Dur => "dur",
Dx => "dx",
Dy => "dy",
EdgeMode => "edgeMode",
Elevation => "elevation",
EnableBackground => "enable-background",
End => "end",
Exponent => "exponent",
ExternalResourcesRequired => "externalResourcesRequired",
Fill => "fill",
FillOpacity => "fill-opacity",
FillRule => "fill-rule",
Filter => "filter",
FilterRes => "filterRes",
FilterUnits => "filterUnits",
FloodColor => "flood-color",
FloodOpacity => "flood-opacity",
FontFamily => "font-family",
FontSize => "font-size",
FontSizeadjust => "font-size-adjust",
FontStretch => "font-stretch",
FontStyle => "font-style",
FontVariant => "font-variant",
FontWeight => "font-weight",
Format => "format",
From => "from",
Fr => "fr",
Fx => "fx",
Fy => "fy",
G1 => "g1",
G2 => "g2",
GlyphName => "glyph-name",
GlyphOrientationhorizontal => "glyph-orientation-horizontal",
GlyphOrientationvertical => "glyph-orientation-vertical",
GlyphRef => "glyphRef",
GradientTransform => "gradientTransform",
GradientUnits => "gradientUnits",
Hanging => "hanging",
Height => "height",
Href => "href",
Hreflang => "hreflang",
HorizAdvx => "horiz-adv-x",
HorizOriginx => "horiz-origin-x",
Id => "id",
Ideographic => "ideographic",
ImageRendering => "image-rendering",
In => "in",
In2 => "in2",
Intercept => "intercept",
K => "k",
K1 => "k1",
K2 => "k2",
K3 => "k3",
K4 => "k4",
KernelMatrix => "kernelMatrix",
KernelUnitLength => "kernelUnitLength",
Kerning => "kerning",
KeyPoints => "keyPoints",
KeySplines => "keySplines",
KeyTimes => "keyTimes",
Lang => "lang",
LengthAdjust => "lengthAdjust",
LetterSpacing => "letter-spacing",
LightingColor => "lighting-color",
LimitingConeAngle => "limitingConeAngle",
Local => "local",
MarkerEnd => "marker-end",
MarkerMid => "marker-mid",
MarkerStart => "marker-start",
MarkerHeight => "markerHeight",
MarkerUnits => "markerUnits",
MarkerWidth => "markerWidth",
Mask => "mask",
MaskContentUnits => "maskContentUnits",
MaskUnits => "maskUnits",
Mathematical => "mathematical",
Max => "max",
Media => "media",
Method => "method",
Min => "min",
Mode => "mode",
Name => "name",
NumOctaves => "numOctaves",
Offset => "offset",
Opacity => "opacity",
Operator => "operator",
Order => "order",
Orient => "orient",
Orientation => "orientation",
Origin => "origin",
Overflow => "overflow",
OverlinePosition => "overline-position",
OverlineThickness => "overline-thickness",
Panose1 => "panose-1",
PaintOrder => "paint-order",
Path => "path",
PathLength => "pathLength",
PatternContentUnits => "patternContentUnits",
PatternTransform => "patternTransform",
PatternUnits => "patternUnits",
Ping => "ping",
PointerEvents => "pointer-events",
Points => "points",
PointsAtX => "pointsAtX",
PointsAtY => "pointsAtY",
PointsAtZ => "pointsAtZ",
PreserveAlpha => "preserveAlpha",
PreserveAspectRatio => "preserveAspectRatio",
PrimitiveUnits => "primitiveUnits",
R => "r",
Radius => "radius",
ReferrerPolicy => "referrerPolicy",
RefX => "refX",
RefY => "refY",
Rel => "rel",
RenderingIntent => "rendering-intent",
RepeatCount => "repeatCount",
RepeatDur => "repeatDur",
RequiredExtensions => "requiredExtensions",
RequiredFeatures => "requiredFeatures",
Restart => "restart",
Result => "result",
Rotate => "rotate",
Rx => "rx",
Ry => "ry",
Slope => "slope",
Spacing => "spacing",
SpecularConstant => "specularConstant",
SpecularExponent => "specularExponent",
Speed => "speed",
SpreadMethod => "spreadMethod",
StartOffset => "startOffset",
StdDeviation => "stdDeviation",
Stemh => "stemh",
Stemv => "stemv",
StitchTiles => "stitchTiles",
StopColor => "stop-color",
StopOpacity => "stop-opacity",
StrikethroughPosition => "strikethrough-position",
StrikethroughThickness => "strikethrough-thickness",
String => "string",
Stroke => "stroke",
StrokeDasharray => "stroke-dasharray",
StrokeDashoffset => "stroke-dashoffset",
StrokeLinecap => "stroke-linecap",
StrokeLinejoin => "stroke-linejoin",
StrokeMiterlimit => "stroke-miterlimit",
StrokeOpacity => "stroke-opacity",
StrokeWidth => "stroke-width",
Style => "style",
SurfaceScale => "surfaceScale",
SystemLanguage => "systemLanguage",
Tabindex => "tabindex",
TableValues => "tableValues",
Target => "target",
TargetX => "targetX",
TargetY => "targetY",
TextAnchor => "text-anchor",
TextDecoration => "text-decoration",
TextRendering => "text-rendering",
TextLength => "textLength",
To => "to",
Transform => "transform",
Type => "type",
U1 => "u1",
U2 => "u2",
UnderlinePosition => "underline-position",
UnderlineThickness => "underline-thickness",
Unicode => "unicode",
UnicodeBidi => "unicode-bidi",
UnicodeRange => "unicode-range",
UnitsPerem => "units-per-em",
VAlphabetic => "v-alphabetic",
VHanging => "v-hanging",
VIdeographic => "v-ideographic",
VMathematical => "v-mathematical",
Values => "values",
VectorEffect => "vector-effect",
Version => "version",
VertAdvy => "vert-adv-y",
VertOriginx => "vert-origin-x",
VertOriginy => "vert-origin-y",
ViewBox => "viewBox",
ViewTarget => "viewTarget",
Visibility => "visibility",
Width => "width",
Widths => "widths",
WordSpacing => "word-spacing",
WritingMode => "writing-mode",
X => "x",
XHeight => "x-height",
X1 => "x1",
X2 => "x2",
XChannelSelector => "xChannelSelector",
XlinkActuate => "xlink:actuate",
XlinkArcrole => "xlink:arcrole",
XlinkHref => "xlink:href",
XlinkRole => "xlink:role",
XlinkShow => "xlink:show",
XlinkTitle => "xlink:title",
XlinkType => "xlink:type",
XmlBase => "xml:base",
XmlLang => "xml:lang",
XmlSpace => "xml:space",
Y => "y",
Y1 => "y1",
Y2 => "y2",
YChannelSelector => "yChannelSelector",
Z => "z",
ZoomAndPan => "zoomAndPan",
UnmappedAttribute(attr) => &attr[..],
})
}
}
|
fn main() {
// chapter 1
let (x,y) = (1,2);
let mut z: char = 'c'; //char are 4 bytes
z = 's';
println!("{} plus {} equals {}", x, y, x+y);
println!("{}", z);
println!("{}", add(y));
println!("y after the function {}", y);
// chapter 3
let y: bool = false;
let a = [ 1, 2, 3];
let a = [ 0; 20]; //initialize an array of 20 i32 elts to 0
println!("a has {} elements", a.len());
let names = [ "Bill", "Bob", "Serge"];
println!("the second name is {}", names[1]);
let a = [ 0, 1, 2, 3, 4]; //array of fixed size
let complete = &a[..]; //slice containing all elements of a
let middle = &a[1..4]; //slice containg elements 1, 2, 3 of a
let x: (i32, &str) = (1, "Hello");
let mut y = (2, " Goodbye");
y = x;
let (x, y, z) = (1, 2, 3);
println!("x is {}", x);
// tuple indexing
let tuple = (1, 2, 3);
let x = tuple.0;
let y = tuple.1;
let z = tuple.2;
fn foo(x: i32) -> i32 {x}; //function that takes an i32 as parameter
//and returns and i32
let x : fn(i32) -> i32 = foo; //x is of type fn(i32) -> i32
// chapter 5
let x = 5;
let y = if x == 5 {10} else {8};
// chapter 6
for (index, value) in (5..10).enumerate() {
println!("index = {} and value = {}", index, value);
}
let lines = "hello\nworld".lines();
for (linenumber, line) in lines.enumerate() {
println!("{}: {}", linenumber, line);
}
for x in 0..10 {
if x % 2 == 0 {
continue;
}
println!("{}", x);
}
//choose which loop to continue
'outer: for x in 0..10 {
'inner: for y in 0..10 {
if x % 2 == 0 { continue 'outer; }
if y % 2 == 0 { continue 'inner; }
println!("x: {}, y: {}", x, y);
}
}
//chapter 7
}
// chapter 2
fn add(x: u32) -> u32{
x+2
}
|
/*
todo!()
//trait to give a more dsl feel
pub trait KotlinUtils: Sized {
#[inline]
fn also<F: Fn(&Self)>(self, f: F) -> Self {
f(&self);
self
}
#[inline]
fn run<F: Fn(&Self) -> R, R>(&self, block: F) -> R {
block(self)
}
#[inline]
fn run_owned<F: Fn(Self) -> R, R>(self, block: F) -> R {
block(self)
}
#[inline]
fn also_mut<F: Fn(&mut Self)>(mut self, f: F) -> Self {
f(&mut self);
self
}
}
impl<T> KotlinUtils for T {}*/ |
use std::{collections::HashMap, hash::Hash};
#[derive(Debug)]
pub struct Graph<T, E, ID: Hash + Eq> {
pub data: HashMap<ID, (T, Vec<ID>)>,
pub edges: HashMap<ID, (E, ID, ID)>,
}
impl<T, E, ID: Clone + Hash + Eq> Graph<T, E, ID> {
pub fn new() -> Self {
Graph {
data: HashMap::new(),
edges: HashMap::new(),
}
}
pub fn add_node(&mut self, id: ID, datum: T) {
// Edges are inserted separately, since they require nodes.
//
self.data.insert(id, (datum, vec![]));
}
// For simplicity, assume that the node exists.
//
pub fn add_edge(&mut self, edge_id: ID, from_id: ID, to_id: ID, datum: E) {
self.edges
.insert(edge_id.clone(), (datum, from_id.clone(), to_id.clone()));
let from = self.data.get_mut(&from_id).unwrap();
from.1.push(edge_id.clone());
let to = self.data.get_mut(&to_id).unwrap();
to.1.push(edge_id);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_graph() {
let mut graph = Graph::new();
for x in vec!['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] {
graph.add_node(x, ());
}
graph.add_edge('a', 'H', 'D', 6);
graph.add_edge('b', 'D', 'C', 18);
graph.add_edge('c', 'C', 'B', 10);
graph.add_edge('d', 'H', 'A', 7);
graph.add_edge('e', 'A', 'C', 4);
graph.add_edge('f', 'H', 'G', 5);
graph.add_edge('g', 'G', 'A', 8);
graph.add_edge('h', 'A', 'F', 3);
graph.add_edge('i', 'F', 'E', 15);
graph.add_edge('j', 'C', 'E', 12);
assert_eq!(graph.data[&'A'], ((), vec!['d', 'e', 'g', 'h']));
assert_eq!(graph.data[&'A'], ((), vec!['d', 'e', 'g', 'h']));
assert_eq!(graph.data[&'B'], ((), vec!['c']));
assert_eq!(graph.data[&'C'], ((), vec!['b', 'c', 'e', 'j']));
assert_eq!(graph.data[&'D'], ((), vec!['a', 'b']));
assert_eq!(graph.data[&'E'], ((), vec!['i', 'j']));
assert_eq!(graph.data[&'F'], ((), vec!['h', 'i']));
assert_eq!(graph.data[&'G'], ((), vec!['f', 'g']));
assert_eq!(graph.data[&'H'], ((), vec!['a', 'd', 'f']));
assert_eq!(graph.edges[&'a'], (6, 'H', 'D'));
assert_eq!(graph.edges[&'b'], (18, 'D', 'C'));
assert_eq!(graph.edges[&'c'], (10, 'C', 'B'));
assert_eq!(graph.edges[&'d'], (7, 'H', 'A'));
assert_eq!(graph.edges[&'e'], (4, 'A', 'C'));
assert_eq!(graph.edges[&'f'], (5, 'H', 'G'));
assert_eq!(graph.edges[&'g'], (8, 'G', 'A'));
assert_eq!(graph.edges[&'h'], (3, 'A', 'F'));
assert_eq!(graph.edges[&'i'], (15, 'F', 'E'));
assert_eq!(graph.edges[&'j'], (12, 'C', 'E'));
}
}
|
///There is no public API calls located in the strategy module. This module contains the
/// implementation details for an Order and Chaos AI.
extern crate rayon;
use crate::board::{BoardDirection, Game, GameStatus, Move, MoveType, Player, Strategy};
use rand::seq::SliceRandom;
use rayon::prelude::*;
use std::f64::INFINITY;
use std::sync::mpsc::channel;
impl Strategy for Game {
fn ai_move(&self, player: Player) -> Game {
let best_move = mini_max(&self, player).unwrap();
match self.make_move(best_move) {
Some(g) => g,
None => {
println!("Illegal move");
unreachable!();
}
}
}
}
fn possible_moves(game: &Game) -> impl ParallelIterator<Item = (MoveType, usize, usize)> + '_ {
game.open_indices()
.map(|(row, col)| (MoveType::X, row, col))
.chain(
game.open_indices()
.map(|(row, col)| (MoveType::O, row, col)),
)
.par_bridge()
}
fn mini_max(game: &Game, player: Player) -> Option<Move> {
let depth = match player {
Player::Order => 5,
Player::Chaos => 4,
};
if game.get_status() != GameStatus::InProgress {
println!("Game not in progress");
return None;
}
let (sender, receiver) = channel();
possible_moves(game).for_each_with(sender, |s, (move_type, row, col)| {
let curr_move = Move::new(move_type, row, col);
let curr_game = game.make_move(curr_move).unwrap();
let score = alphabeta(curr_game, depth, -INFINITY, INFINITY, player.other_player());
s.send((score, curr_move)).unwrap();
});
let mut best_score = match player {
Player::Order => -INFINITY,
Player::Chaos => INFINITY,
};
let mut best_moves = Vec::new();
for (score, curr_move) in receiver {
let status = game.make_move(curr_move).unwrap().get_status();
if player == Player::Order && status == GameStatus::OrderWins {
return Some(curr_move);
}
if score == best_score {
best_moves.push(Some(curr_move));
continue;
}
match player {
Player::Order => {
if score > best_score {
best_moves.clear();
best_score = score;
best_moves.push(Some(curr_move));
}
}
Player::Chaos => {
if best_score > score {
best_moves.clear();
best_score = score;
best_moves.push(Some(curr_move));
}
}
}
}
*best_moves.choose(&mut rand::thread_rng()).unwrap()
}
fn alphabeta(game: Game, depth: usize, mut alpha: f64, mut beta: f64, player: Player) -> f64 {
if depth == 0 || game.get_status() != GameStatus::InProgress {
return eval(&game);
}
let mut value = match player {
Player::Order => -INFINITY,
Player::Chaos => INFINITY,
};
for (row, col) in game.open_indices() {
for &move_type in &[MoveType::X, MoveType::O] {
let curr_move = Move::new(move_type, row, col);
let next_game = game.make_move(curr_move).expect("Failed to make move");
let new_val = alphabeta(next_game, depth - 1, alpha, beta, player.other_player());
match player {
Player::Order => {
value = value.max(new_val);
alpha = alpha.max(new_val);
}
Player::Chaos => {
value = value.min(new_val);
beta = beta.min(new_val);
}
}
if alpha >= beta {
return value;
}
}
}
value
}
fn eval(game: &Game) -> f64 {
let mut score = match game.get_status() {
GameStatus::OrderWins => return INFINITY,
GameStatus::ChaosWins => return -INFINITY,
GameStatus::InProgress => 0.,
};
let (col, row) = game
.last_move()
.expect("Eval should never be called on an empty board");
let counts = &[
game.count_direction(BoardDirection::Row, row, col),
game.count_direction(BoardDirection::Column, row, col),
game.count_direction(BoardDirection::Diagonal, row, col),
game.count_direction(BoardDirection::AntiDiagonal, row, col),
];
for count in counts {
score += match count {
4 => 25.,
3 => 10.,
2 => 5.,
_ => 0.,
}
}
score
}
#[cfg(test)]
mod minmax_tests {
use super::{eval, Player};
use crate::board::{Game, GameStatus, Move, MoveType, Strategy};
#[test]
fn score_order_board() {
let mut game = Game::new();
let mut score;
let x = MoveType::X;
game = game.make_move(Move::new(x, 1, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
score = eval(&game);
assert_eq!(score, 0.);
game = game.make_move(Move::new(x, 2, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
score = eval(&game);
assert_eq!(score, 5.);
game = game.make_move(Move::new(x, 0, 1)).unwrap();
score = eval(&game);
assert_eq!(score, 0.);
game = game.make_move(Move::new(x, 0, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
score = eval(&game);
assert_eq!(score, 5.);
game = game.make_move(Move::new(x, 0, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
score = eval(&game);
assert_eq!(score, 20.);
}
/* The following tests take too long to run on Travis */
#[test]
#[ignore]
fn test_order_clear_win_horizontal() {
let mut game = Game::new();
let x = MoveType::X;
game = game.make_move(Move::new(x, 0, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.ai_move(Player::Order);
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
#[ignore]
fn test_order_clear_win_vertical() {
let mut game = Game::new();
let x = MoveType::X;
let o = MoveType::O;
game = game.make_move(Move::new(o, 0, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 2, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 4, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.ai_move(Player::Order);
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
#[ignore]
fn test_chaos_clear_block() {
let mut game = Game::new();
let x = MoveType::X;
let o = MoveType::O;
game = game.make_move(Move::new(x, 5, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 4, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 2, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(o, 0, 5)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
println!("{}", game);
game = game.ai_move(Player::Chaos);
println!("{}", game);
assert_eq!(game.get_status(), GameStatus::InProgress);
assert_eq!(game.last_move().unwrap().1, 1);
assert_eq!(game.last_move().unwrap().0, 4);
}
#[test]
#[ignore]
fn test_open_clear_win_anti_diag() {
let mut game = Game::new();
let x = MoveType::X;
let o = MoveType::O;
game = game.make_move(Move::new(o, 0, 0)).unwrap();
game = game.make_move(Move::new(x, 0, 4)).unwrap();
game = game.make_move(Move::new(x, 1, 1)).unwrap();
game = game.make_move(Move::new(x, 1, 2)).unwrap();
game = game.make_move(Move::new(x, 1, 4)).unwrap();
game = game.make_move(Move::new(x, 2, 1)).unwrap();
game = game.make_move(Move::new(o, 2, 2)).unwrap();
game = game.make_move(Move::new(x, 2, 3)).unwrap();
game = game.make_move(Move::new(o, 2, 4)).unwrap();
game = game.make_move(Move::new(o, 3, 1)).unwrap();
game = game.make_move(Move::new(x, 3, 2)).unwrap();
game = game.make_move(Move::new(x, 4, 1)).unwrap();
game = game.make_move(Move::new(o, 5, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.ai_move(Player::Order);
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_open_indices() {
let mut game = Game::new();
let x = MoveType::X;
let o = MoveType::O;
game = game.make_move(Move::new(x, 0, 0)).unwrap();
game = game.make_move(Move::new(x, 1, 0)).unwrap();
game = game.make_move(Move::new(o, 3, 2)).unwrap();
game = game.make_move(Move::new(x, 2, 3)).unwrap();
game = game.make_move(Move::new(o, 2, 4)).unwrap();
game = game.make_move(Move::new(x, 4, 2)).unwrap();
let mut count = 0;
for cell in game.open_indices() {
count += 1;
assert_ne!(cell, (0, 0));
assert_ne!(cell, (1, 0));
assert_ne!(cell, (3, 2));
assert_ne!(cell, (2, 3));
assert_ne!(cell, (2, 4));
assert_ne!(cell, (4, 2));
}
assert_eq!(count, 30);
}
}
|
fn main() {
let mut user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com");
let mut user2 = build_user(String::from("someemail@intenet.com"),
String::from("aNewuser"));
user2 = User {
email: String::from("newEmail"), // update email
username: String::from("newName"), // update username
..user1 // copies rest of fields from user1 over user 2
};
struct Color(i32, i32, i32); // tuple struct
let black = Color(0, 0, 0);
}
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn build_user(email: String, username: String) -> User {
User {
email, // implicit assignment
username, // implicit assignment
active: true,
sign_in_count: 1,
}
} |
use super::LifetimeIndex;
use std::fmt::{self, Debug};
/// A set of lifetime indices.
pub(crate) struct LifetimeCounters {
set: Vec<u8>,
}
const MASK: u8 = 0b11;
const MAX_VAL: u8 = 3;
impl LifetimeCounters {
pub fn new() -> Self {
Self { set: Vec::new() }
}
/// Increments the counter for the `lifetime` lifetime,stopping at 3.
pub fn increment(&mut self, lifetime: LifetimeIndex) -> u8 {
let (i, shift) = Self::get_index_shift(lifetime.bits);
if i >= self.set.len() {
self.set.resize(i + 1, 0);
}
let bits = &mut self.set[i];
let mask = MASK << shift;
if (*bits & mask) == mask {
MAX_VAL
} else {
*bits += 1 << shift;
(*bits >> shift) & MASK
}
}
pub fn get(&self, lifetime: LifetimeIndex) -> u8 {
let (i, shift) = Self::get_index_shift(lifetime.bits);
match self.set.get(i) {
Some(&bits) => (bits >> shift) & MASK,
None => 0,
}
}
fn get_index_shift(lt: usize) -> (usize, u8) {
(lt >> 2, ((lt & 3) << 1) as u8)
}
}
impl Debug for LifetimeCounters {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.set.iter().cloned().map(U8Wrapper))
.finish()
}
}
#[repr(transparent)]
struct U8Wrapper(u8);
impl fmt::Debug for U8Wrapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Binary::fmt(&self.0, f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_counting() {
let mut counters = LifetimeCounters::new();
let lts = vec![
LifetimeIndex::Param(0),
LifetimeIndex::Param(1),
LifetimeIndex::Param(2),
LifetimeIndex::Param(3),
LifetimeIndex::Param(4),
LifetimeIndex::Param(5),
LifetimeIndex::Param(6),
LifetimeIndex::Param(7),
LifetimeIndex::Param(8),
LifetimeIndex::Param(9),
LifetimeIndex::Param(999),
LifetimeIndex::ANONYMOUS,
LifetimeIndex::STATIC,
LifetimeIndex::NONE,
];
for lt in lts {
for i in 1..=3 {
assert_eq!(counters.get(lt), i - 1);
assert_eq!(counters.increment(lt), i);
assert_eq!(counters.get(lt), i);
}
}
}
}
|
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::kademlia::memory_store::{MultiRecord, MultiRecordKind};
use libp2p::kad::record::Record;
use libp2p::PeerId;
use once_cell::sync::Lazy;
use prost::Message;
use std::collections::HashMap;
use std::convert::TryInto;
use std::error::Error;
use std::ops::Deref;
use std::time::{Duration, Instant};
#[derive(Clone, PartialEq, Message)]
#[prost(tags = "sequential")]
pub struct MultiRecordProto {
#[prost(bytes, required)]
key: Vec<u8>,
#[prost(message, repeated)]
values: Vec<ValueProto>,
#[prost(uint32, optional)]
ttl: Option<u32>,
}
impl From<MultiRecord> for MultiRecordProto {
fn from(mrec: MultiRecord) -> Self {
#[rustfmt::skip]
let MultiRecord { key, values, expires, kind } = mrec;
debug_assert_eq!(
kind,
MultiRecordKind::MultiRecord,
"serializing simple multirec to proto"
);
let values: Vec<_> = values
.into_iter()
.map(|(v, p)| ValueProto::new(v, p.into_bytes()))
.collect();
let ttl = expires.map(|t| {
let now = Instant::now();
if t > now {
(t - now).as_secs() as u32
} else {
1 // "1" means "already expired", "0" means "does not expire at all"
}
});
Self {
// TODO: unneeded copy, could be eliminated
key: key.to_vec(),
values,
ttl,
}
}
}
impl TryInto<MultiRecord> for MultiRecordProto {
type Error = Box<dyn Error>;
fn try_into(self) -> Result<MultiRecord, Self::Error> {
use std::io::{Error, ErrorKind};
#[rustfmt::skip]
let MultiRecordProto { key, values, ttl } = self;
fn peer_id(data: Vec<u8>) -> Result<PeerId, Error> {
PeerId::from_bytes(data).map_err(|_| ErrorKind::InvalidData.into())
}
let values = values
.into_iter()
.map(|v| {
let publisher = peer_id(v.publisher)?;
let result: (Vec<u8>, PeerId) = (v.value, publisher);
Ok(result)
})
.collect::<Result<_, _>>()
.map_err(|e: Error| Box::new(e))?; // TODO: get rid of explicit boxing
let expires = ttl
.filter(|&ttl| ttl > 0)
.map(|ttl| Instant::now() + Duration::from_secs(ttl as u64));
Ok(MultiRecord {
key: key.into(),
values,
expires,
kind: MultiRecordKind::MultiRecord,
})
}
}
#[derive(Clone, PartialEq, Message)]
#[prost(tags = "sequential")]
pub struct ValueProto {
#[prost(bytes, required)]
value: Vec<u8>,
#[prost(bytes, required)]
publisher: Vec<u8>,
}
impl ValueProto {
pub fn new(value: Vec<u8>, publisher: Vec<u8>) -> Self {
Self { value, publisher }
}
}
// base58: 1UMULTPLExxRECRDSxxSTREDxxHERExx
pub const MULTIPLE_RECORD_PEER_ID_BYTES: [u8; 24] = [
0, 22, 213, 69, 194, 41, 34, 127, 226, 180, 218, 134, 129, 165, 129, 4, 46, 90, 180, 248, 241,
86, 134, 81,
];
pub static MULTIPLE_RECORD_PEER_ID: Lazy<PeerId> =
Lazy::new(|| PeerId::from_bytes(MULTIPLE_RECORD_PEER_ID_BYTES.to_vec()).unwrap());
pub fn is_multiple_record(record: &Record) -> bool {
record
.publisher
.as_ref()
.map_or(false, |p| p == MULTIPLE_RECORD_PEER_ID.deref())
}
pub fn multirecord_from_bytes(bytes: Vec<u8>) -> Result<MultiRecord, Box<dyn Error>> {
let proto = MultiRecordProto::decode(bytes.as_slice())?;
let mrec: MultiRecord = proto.try_into()?;
Ok(mrec)
}
pub fn try_to_multirecord(record: Record) -> Result<MultiRecord, Box<dyn std::error::Error>> {
use std::io::{Error, ErrorKind};
if is_multiple_record(&record) {
multirecord_from_bytes(record.value)
} else {
let mut values = HashMap::new();
let publisher = match record.publisher {
Some(p) => p,
None => {
log::warn!(
"publisher undefined in simple record key {:?} value {:?}",
bs58::encode(record.key).into_string(),
bs58::encode(record.value).into_string()
);
// TODO: get rid of Box::new
return Err(Box::new(Error::from(ErrorKind::NotFound)));
}
};
values.insert(record.value, publisher);
Ok(MultiRecord {
key: record.key,
values,
expires: record.expires,
kind: MultiRecordKind::MultiRecord,
})
}
}
pub fn reduce_multirecord(mrec: MultiRecord) -> Record {
use MultiRecordKind::*;
debug_assert!(!mrec.values.is_empty(), "mrec.values can't be empty here");
match &mrec.kind {
MultiRecord => {
let key = mrec.key.clone();
let expires = mrec.expires;
let proto: MultiRecordProto = mrec.into();
let mut value = Vec::with_capacity(proto.encoded_len());
proto.encode(&mut value).expect("enough capacity");
Record {
key,
value,
publisher: Some(MULTIPLE_RECORD_PEER_ID.clone()),
expires,
}
}
SimpleRecord => {
let (value, publisher) = mrec
.values
.into_iter()
.next()
.expect("simple record.values can't be empty");
Record {
key: mrec.key,
value,
publisher: Some(publisher),
expires: mrec.expires,
}
}
}
}
|
pub const INTERSECTION_EPSILON: f64 = 0.00001;
|
/// du -h . --max-depth=0
///
// use std::process::Command;
use std::fs;
use std::path::Path;
use std::process::Command;
use std::io::{self, Write};
fn main() {
if let Ok(files) = get_files("/home/susilo/var/Rust") {
for file in files {
let path_name = format!("{}/Cargo.toml", &file);
let path_exist = Path::new(&path_name).exists();
// let base_name = Path::new(&file).file_name().unwrap().to_str().unwrap();
if path_exist {
duh(&file);
// println!("{}", base_name);
}
}
}
}
fn duh(path_name: &str) {
let output = Command::new("du")
.arg("-h")
.arg("--max-depth=0")
.arg(path_name)
.output()
.expect("Gagal menjalankan perintah");
io::stdout().write_all(&output.stdout).unwrap();
}
fn get_files(dirname: &str) -> std::io::Result<Vec<String>> {
let mut res: Vec<String> = Vec::new();
for entry in fs::read_dir(dirname)? {
let dir = entry?;
res.push(dir.path().display().to_string());
}
Ok(res)
}
|
#![allow(dead_code)]
use std::io;
use std::slice;
use std::str;
use crate::other;
// Keywords for PAX extended header records.
pub const PAX_NONE: &str = ""; // Indicates that no PAX key is suitable
pub const PAX_PATH: &str = "path";
pub const PAX_LINKPATH: &str = "linkpath";
pub const PAX_SIZE: &str = "size";
pub const PAX_UID: &str = "uid";
pub const PAX_GID: &str = "gid";
pub const PAX_UNAME: &str = "uname";
pub const PAX_GNAME: &str = "gname";
pub const PAX_MTIME: &str = "mtime";
pub const PAX_ATIME: &str = "atime";
pub const PAX_CTIME: &str = "ctime"; // Removed from later revision of PAX spec, but was valid
pub const PAX_CHARSET: &str = "charset"; // Currently unused
pub const PAX_COMMENT: &str = "comment"; // Currently unused
pub const PAX_SCHILYXATTR: &str = "SCHILY.xattr.";
// Keywords for GNU sparse files in a PAX extended header.
pub const PAX_GNUSPARSE: &str = "GNU.sparse.";
pub const PAX_GNUSPARSENUMBLOCKS: &str = "GNU.sparse.numblocks";
pub const PAX_GNUSPARSEOFFSET: &str = "GNU.sparse.offset";
pub const PAX_GNUSPARSENUMBYTES: &str = "GNU.sparse.numbytes";
pub const PAX_GNUSPARSEMAP: &str = "GNU.sparse.map";
pub const PAX_GNUSPARSENAME: &str = "GNU.sparse.name";
pub const PAX_GNUSPARSEMAJOR: &str = "GNU.sparse.major";
pub const PAX_GNUSPARSEMINOR: &str = "GNU.sparse.minor";
pub const PAX_GNUSPARSESIZE: &str = "GNU.sparse.size";
pub const PAX_GNUSPARSEREALSIZE: &str = "GNU.sparse.realsize";
/// An iterator over the pax extensions in an archive entry.
///
/// This iterator yields structures which can themselves be parsed into
/// key/value pairs.
pub struct PaxExtensions<'entry> {
data: slice::Split<'entry, u8, fn(&u8) -> bool>,
}
impl<'entry> PaxExtensions<'entry> {
/// Create new pax extensions iterator from the given entry data.
pub fn new(a: &'entry [u8]) -> Self {
fn is_newline(a: &u8) -> bool {
*a == b'\n'
}
PaxExtensions {
data: a.split(is_newline),
}
}
}
/// A key/value pair corresponding to a pax extension.
pub struct PaxExtension<'entry> {
key: &'entry [u8],
value: &'entry [u8],
}
pub fn pax_extensions_value(a: &[u8], key: &str) -> Option<u64> {
for extension in PaxExtensions::new(a) {
let current_extension = match extension {
Ok(ext) => ext,
Err(_) => return None,
};
if current_extension.key() != Ok(key) {
continue;
}
let value = match current_extension.value() {
Ok(value) => value,
Err(_) => return None,
};
let result = match value.parse::<u64>() {
Ok(result) => result,
Err(_) => return None,
};
return Some(result);
}
None
}
impl<'entry> Iterator for PaxExtensions<'entry> {
type Item = io::Result<PaxExtension<'entry>>;
fn next(&mut self) -> Option<io::Result<PaxExtension<'entry>>> {
let line = match self.data.next() {
Some(line) if line.is_empty() => return None,
Some(line) => line,
None => return None,
};
Some(
line.iter()
.position(|b| *b == b' ')
.and_then(|i| {
str::from_utf8(&line[..i])
.ok()
.and_then(|len| len.parse::<usize>().ok().map(|j| (i + 1, j)))
})
.and_then(|(kvstart, reported_len)| {
if line.len() + 1 == reported_len {
line[kvstart..]
.iter()
.position(|b| *b == b'=')
.map(|equals| (kvstart, equals))
} else {
None
}
})
.map(|(kvstart, equals)| PaxExtension {
key: &line[kvstart..kvstart + equals],
value: &line[kvstart + equals + 1..],
})
.ok_or_else(|| other("malformed pax extension")),
)
}
}
impl<'entry> PaxExtension<'entry> {
/// Returns the key for this key/value pair parsed as a string.
///
/// May fail if the key isn't actually utf-8.
pub fn key(&self) -> Result<&'entry str, str::Utf8Error> {
str::from_utf8(self.key)
}
/// Returns the underlying raw bytes for the key of this key/value pair.
pub fn key_bytes(&self) -> &'entry [u8] {
self.key
}
/// Returns the value for this key/value pair parsed as a string.
///
/// May fail if the value isn't actually utf-8.
pub fn value(&self) -> Result<&'entry str, str::Utf8Error> {
str::from_utf8(self.value)
}
/// Returns the underlying raw bytes for this value of this key/value pair.
pub fn value_bytes(&self) -> &'entry [u8] {
self.value
}
}
|
extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::TextureCreator;
use sdl2::ttf::Font;
use sdl2::video::WindowContext;
use crate::common::make_title_texture;
use crate::sdl_main::{SCR_WIDTH};
use self::sdl2::render::{Canvas, Texture};
use self::sdl2::video::Window;
pub(crate) struct StartScreen<'a> {
bernie_soft_title: Texture<'a>,
car_maze_title: Texture<'a>,
instructions: Vec<&'a str>,
pub(crate) bernie_x: i32,
}
impl<'a> StartScreen<'a> {
pub(crate) fn new(texture_creator: &'a TextureCreator<WindowContext>, font: &Font) -> StartScreen<'a> {
let get_pixels_surface1 = font.render("Berniesoft").blended(Color::WHITE).map_err(|e| e.to_string()).unwrap();
let get_pixels_surface2 = font.render("Bi-plane vs Alien...").blended(Color::WHITE).map_err(|e| e.to_string()).unwrap();
let title1 = make_title_texture(200,
Color::YELLOW,
&texture_creator,
get_pixels_surface1);
let title2 = make_title_texture(200,
Color::GREEN,
&texture_creator,
get_pixels_surface2);
let instructions = vec![
"Fly your bi-plane and shoot as many aliens as possible. If more than 30 aliens remain",
"on land game over.",
"You will need to refuel by landing on the grey landing strip",
"Arrow keys to fly, left shift faster Z slower"
];
StartScreen {
bernie_soft_title: title1,
car_maze_title: title2,
instructions: instructions,
bernie_x: 0,
}
}
pub fn update(&mut self) {
self.bernie_x = self.bernie_x + 1;
}
pub fn draw_on_canvas(self, canvas: &mut Canvas<Window>, font: &Font, texture_creator: &'a TextureCreator<WindowContext>) -> StartScreen<'a> {
canvas.copy(&self.bernie_soft_title, None, Some(Rect::new(self.bernie_x, 100, SCR_WIDTH, 200))).unwrap();
canvas.copy(&self.car_maze_title, None, Some(Rect::new(0, 300, SCR_WIDTH, 200))).unwrap();
let mut y = 450;
for line in self.instructions.iter() {
let font_surface = font.render(line).blended(Color::YELLOW).unwrap();
let instructions_texture = font_surface.as_texture(&texture_creator).unwrap();
canvas.copy(&instructions_texture, None, Some(Rect::new(64, y, font_surface.width(), 48))).unwrap();
y = y + 48;
}
self
}
}
|
extern crate pine;
// use pine::error::PineError;
use pine::ast::input::*;
use pine::ast::name::*;
use pine::ast::stat_expr_types::*;
use pine::ast::string::*;
const TEXT_WITH_COMMENT: &str = "//@version=4
study(\"Test\")
// This line is a comment
a = close // This is also a comment
plot(a)
";
#[test]
fn comment_test() {
assert_eq!(
pine::parse_ast(TEXT_WITH_COMMENT),
Ok(Block::new(
vec![
// Statement::None(StrRange::from_start("//@version=4\n", Position::new(0, 0))),
Statement::Exp(Exp::FuncCall(Box::new(FunctionCall::new_no_ctxid(
Exp::VarName(RVVarName::new_with_start("study", Position::new(1, 0))),
vec![Exp::Str(StringNode::new(
String::from("Test"),
StrRange::from_start("Test", Position::new(1, 7))
))],
vec![],
StrRange::from_start("study(\"Test\")", Position::new(1, 0))
)))),
// Statement::None(StrRange::from_start(
// "// This line is a comment\n",
// Position::new(2, 0)
// )),
Statement::Assignment(Box::new(Assignment::new(
vec![VarName::new_with_start("a", Position::new(3, 0))],
Exp::VarName(RVVarName::new_with_start("close", Position::new(3, 4))),
false,
None,
StrRange::from_start("a = close", Position::new(3, 0))
))),
Statement::Exp(Exp::FuncCall(Box::new(FunctionCall::new_no_ctxid(
Exp::VarName(RVVarName::new_with_start("plot", Position::new(4, 0))),
vec![Exp::VarName(RVVarName::new_with_start(
"a",
Position::new(4, 5)
))],
vec![],
StrRange::from_start("plot(a)", Position::new(4, 0))
))))
],
None,
StrRange::new(Position::new(1, 0), Position::new(4, 7))
))
)
}
|
use binary_search_range::BinarySearchRange;
use proconio::input;
fn main() {
input! {
n: usize,
q: usize,
mut a: [u64; n],
xs: [u64; q],
};
a.sort();
let mut cum_sum = vec![0; n + 1];
for i in 0..n {
cum_sum[i + 1] = cum_sum[i] + a[i];
}
for x in xs {
let mut ans = 0;
let less = a.range(0..x);
ans += less.len() as u64 * x - cum_sum[less.len()];
let greater = a.range((x + 1)..std::u64::MAX);
ans += (cum_sum[n] - cum_sum[n - greater.len()]) - greater.len() as u64 * x;
println!("{}", ans);
}
}
|
#![allow(clippy::comparison_chain)]
#![allow(clippy::collapsible_if)]
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{BTreeSet, BinaryHeap, HashMap, HashSet};
use std::fmt::Debug;
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const inv2ten97: u128 = 500_000_004;
// bit毎に処理して数え上げるときにはprodするだけで場合の数になる
fn main() {
let (n, q): (usize, usize) = parse_line().unwrap();
let mut stst: Vec<Vec<(usize, usize, usize, bool)>> = vec![vec![]; 60];
for _ in 0..q {
let (x, y, z, w): (usize, usize, usize, usize) = parse_line().unwrap();
for (i, c) in format!("{:060b}", w).char_indices() {
let wb = if c.to_digit(2).unwrap() == 0 {
false
} else {
true
};
stst[i].push((x - 1, y - 1, z - 1, wb));
}
}
let mut ans = 1;
for i in 0..60 {
let mut tmp = 0;
for mut bits in 0..2_u64.pow(n as u32) {
let mut vv = vec![];
for ii in 0..n {
if bits % 2 == 1 {
vv.push(false);
} else {
vv.push(true)
}
bits /= 2;
}
// check
if stst[i]
.iter()
.all(|(x, y, z, wb)| (vv[*x] || vv[*y] || vv[*z]) == *wb)
{
tmp += 1;
}
}
tmp %= ten97;
ans *= tmp;
ans %= ten97;
}
println!("{}", ans);
}
|
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const inv2ten97: u128 = 500_000_004;
fn main() {
let n: usize = parse_line().unwrap();
let hh: Vec<isize> = parse_line().unwrap();
let mut dp: Vec<usize> = vec![];
dp.push(0);
dp.push((hh[0] - hh[1]).abs() as usize);
for i in 2..n {
dp.push(min(
dp[i - 1] + (hh[i] - hh[i - 1]).abs() as usize,
dp[i - 2] + (hh[i] - hh[i - 2]).abs() as usize,
));
}
println!("{}", dp[n - 1]);
}
|
//! Error type for this crate.
use std::error::Error;
/// Error generated while parsing UCUM strings.
#[derive(Debug)]
pub struct UcumError<'a> {
message: &'static str,
txt: &'a [u8],
position: usize,
cause: Option<Box<dyn Error>>,
}
impl<'a> UcumError<'a> {
/// Build a new error with a given message, parsed string and position.
pub fn new(message: &'static str, txt: &'a [u8], position: usize) -> Self {
assert!(position <= txt.len());
UcumError {
message,
txt,
position,
cause: None,
}
}
/// Add parsed string and position to an existing `UcumError`.
pub fn at_location(mut self, txt: &'a [u8], position: usize) -> Self {
if self.txt.is_empty() {
self.txt = txt;
self.position = position;
}
self
}
/// Add a cause error to an existing `UcumError`.
pub fn with_cause(mut self, cause: Box<dyn Error>) -> Self {
self.cause = Some(cause);
self
}
}
impl From<&'static str> for UcumError<'_> {
fn from(message: &'static str) -> Self {
UcumError {
message,
txt: &b""[..],
position: 0,
cause: None,
}
}
}
impl std::fmt::Display for UcumError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.txt.is_empty() {
write!(f, "UcumError: {}", self.message)?;
} else {
writeln!(f, "UcumError at {}: {}", self.position, self.message)?;
let inf = if self.position < 10 {
0
} else {
self.position - 10
};
let sup = if self.txt.len() < self.position + 10 {
self.txt.len()
} else {
self.position + 10
};
let prefix = if inf == 0 { "" } else { "..." };
let suffix = if sup < self.txt.len() { "..." } else { "" };
let printable = String::from_utf8_lossy(&self.txt[inf..sup]);
writeln!(f, "{}{}{}", prefix, printable, suffix)?;
let spaces = vec![b' '; prefix.len() + self.position.min(10)];
let spaces = unsafe { String::from_utf8_unchecked(spaces) };
writeln!(f, "{}^", spaces)?;
}
if let Some(cause) = &self.cause {
writeln!(f, "\ncaused by:\n{}", cause)?;
}
Ok(())
}
}
impl Error for UcumError<'_> {}
/// Extend `Result<_, UcumError>` with methods to enrich the error.
pub trait ResultExt<'a> {
/// See [`UcumError::at_location`](./struct.UcumError.html#method.at_location)
fn at_location(self, txt: &'a [u8], position: usize) -> Self;
/// See [`UcumError::at_location`](./struct.UcumError.html#method.with_cause)
fn with_cause(self, cause: Box<dyn Error>) -> Self;
}
impl<'a, T> ResultExt<'a> for Result<T, UcumError<'a>> {
fn at_location(self, txt: &'a [u8], position: usize) -> Self {
self.map_err(|e| e.at_location(txt, position))
}
fn with_cause(self, cause: Box<dyn Error>) -> Self {
self.map_err(|e| e.with_cause(cause))
}
}
/// Type alias for result whose error type is [`UcumError`](./struct.UcumError.html).
pub type UcumResult<'a, T> = std::result::Result<T, UcumError<'a>>;
#[cfg(test)]
mod test {
use super::*;
#[test]
fn display_no_txt() {
let err: UcumError = "simple message".into();
assert_eq!(&format!("{}", err), "UcumError: simple message");
}
#[test]
fn display_short_txt_zero() {
let err = UcumError::new("unexpected token", b"0123456789", 0);
assert_eq!(
&format!("{}", err),
"UcumError at 0: unexpected token
0123456789
^\n"
);
}
#[test]
fn display_short_txt_near() {
let err = UcumError::new("unexpected token", b"0123456789", 4);
assert_eq!(
&format!("{}", err),
"UcumError at 4: unexpected token
0123456789
^\n"
);
}
#[test]
fn display_long_txt_zero() {
let err = UcumError::new("unexpected token", b"0123456789ABCDEFGH", 0);
assert_eq!(
&format!("{}", err),
"UcumError at 0: unexpected token
0123456789...
^\n"
);
}
#[test]
fn display_long_txt_near() {
let err = UcumError::new("unexpected token", b"0123456789ABCDEFGH", 4);
assert_eq!(
&format!("{}", err),
"UcumError at 4: unexpected token
0123456789ABCD...
^\n"
);
}
#[test]
fn display_long_txt_ten() {
let err = UcumError::new("unexpected token", b"0123456789ABCDEFGH", 10);
assert_eq!(
&format!("{}", err),
"UcumError at 10: unexpected token
0123456789ABCDEFGH
^\n"
);
}
#[test]
fn display_long_txt_far() {
let err = UcumError::new("unexpected token", b"0123456789ABCDEFGH", 12);
assert_eq!(
&format!("{}", err),
"UcumError at 12: unexpected token
...23456789ABCDEFGH
^\n"
);
}
#[test]
fn display_longer_txt_ten() {
let err = UcumError::new("unexpected token", b"0123456789ABCDEFGHIJKLMNOP", 10);
assert_eq!(
&format!("{}", err),
"UcumError at 10: unexpected token
0123456789ABCDEFGHIJ...
^\n"
);
}
#[test]
fn display_longer_txt_far() {
let err = UcumError::new("unexpected token", b"0123456789ABCDEFGHIJKLMNOP", 12);
assert_eq!(
&format!("{}", err),
"UcumError at 12: unexpected token
...23456789ABCDEFGHIJKL...
^\n"
);
}
#[test]
fn display_longer_txt_further() {
let err = UcumError::new("unexpected token", b"0123456789ABCDEFGHIJKLMNOP", 25);
assert_eq!(
&format!("{}", err),
"UcumError at 25: unexpected token
...FGHIJKLMNOP
^\n"
);
}
}
|
use prost::Message;
mod item {
include!(concat!(env!("OUT_DIR"), "/sample.item.rs"));
}
fn create(id: &str, price: i32) -> item::Item {
let mut d = item::Item::default();
d.item_id = id.to_string();
d.price = price;
d
}
fn main() {
let d = create("item-1", 100);
println!("{:?}", d);
let mut buf = Vec::with_capacity(d.encoded_len());
d.encode(&mut buf).unwrap();
println!("{:?}", buf);
let d2 = item::Item::decode(buf.as_slice()).unwrap();
println!("restored: {:?}", d2);
}
|
fn main() {
let a = 1;
let b = a; // copy
println!("a = {}", a);
println!("b = {}", b);
let x = Box::new(2);
let y = x;
//println!("x = {}", x); // compile error : moved x value
println!("y = {}", y);
}
|
#![feature(convert)]
#![feature(vecmap)]
use std::collections::VecMap;
fn sort_word(word: &str) -> String {
let mut wordvec = word.chars().collect::<Vec<char>>();
let mut puncmap = VecMap::new();
for (i, c) in wordvec.iter().enumerate() {
if !c.is_alphabetic() { puncmap.insert(i, c.clone()); } }
wordvec.retain(|c| c.is_alphabetic());
let mut uppermap = Vec::new();
for (i, c) in wordvec.iter().enumerate() {
if c.is_uppercase() { uppermap.push(i); } }
for n in uppermap.iter() { wordvec[*n] = wordvec[*n].to_lowercase().next().unwrap(); }
wordvec.sort();
for n in uppermap.iter() { wordvec[*n] = wordvec[*n].to_uppercase().next().unwrap(); }
for (n, c) in puncmap { wordvec.insert(n, c); }
wordvec.into_iter().collect::<String>()
}
fn sort(phrase: &String) -> String {
let words = phrase.split_whitespace().collect::<Vec<&str>>();
let mut sorted_phrase = words.iter()
.map(|word| sort_word(word))
.fold(String::new(), |phrase, word| phrase + word.as_str() + " ");
sorted_phrase.pop();
sorted_phrase
}
fn main() {
let args: Vec<String> = std::env::args().collect();
for arg in args.iter().skip(1) {
println!("{}\n{}\n", arg, sort(arg))
}
}
|
#![allow(unused)]
mod document;
mod error;
mod session;
mod text;
pub use document::*;
pub use error::*;
pub use session::*;
pub use text::*;
pub use wasm_lsp_parsers::core::{
language::{self, Language},
NodeExt,
};
|
use num::range_step;
use sdl2;
use sdl2::event::Event;
use sdl2::pixels::Color;
use sdl2::rect::{Point, Rect};
use setup;
const SCREEN_WIDTH: u32 = 640;
const SCREEN_HEIGHT: u32 = 480;
pub fn point_drawer() {
let basic_window_setup = setup::init("Geometry Rendering", SCREEN_WIDTH, SCREEN_HEIGHT);
let mut events = basic_window_setup.sdl_context.event_pump().unwrap();
let mut renderer = basic_window_setup.window
.renderer()
.present_vsync()
.accelerated()
.build()
.unwrap();
let black = Color::RGB(0, 0, 0);
let white = Color::RGB(0xff, 0xff, 0xff);
let red = Color::RGB(0xff, 0, 0);
let green = Color::RGB(0, 0xff, 0);
let blue = Color::RGB(0, 0, 0xff);
let yellow = Color::RGB(0xff, 0xff, 0);
let mut bright = false;
let mut frame = 0;
// loop until we receive a QuitEvent
'event: loop {
for event in events.poll_iter() {
match event {
Event::Quit{..} => break 'event,
// keycode: Option<KeyCode>
// https://doc.rust-lang.org/book/patterns.html
Event::KeyDown{keycode: Some(sdl2::keyboard::Keycode::Q), ..} => break 'event,
_ => continue,
}
}
// Clear screen - white clear colour on each frame
// SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
// SDL_RenderClear( gRenderer );
renderer.set_draw_color(if bright {
white
} else {
black
});
frame += 1;
if frame % 60 == 0 {
bright = !bright;
}
renderer.clear(); // clear with current draw color
let rect = Rect::new(SCREEN_WIDTH as i32 / 4,
SCREEN_HEIGHT as i32 / 4,
SCREEN_WIDTH / 2,
SCREEN_HEIGHT / 2);
renderer.set_draw_color(red);
renderer.fill_rect(rect).expect("fill rect failed");
let unfilled_rect = Rect::new(SCREEN_WIDTH as i32 / 6,
SCREEN_HEIGHT as i32 / 6,
SCREEN_WIDTH * 2 / 3,
SCREEN_HEIGHT * 2 / 3);
renderer.set_draw_color(green);
renderer.draw_rect(unfilled_rect).expect("draw rect failed");;
renderer.set_draw_color(blue);
renderer.draw_line(Point::new(0, SCREEN_HEIGHT as i32 / 2),
Point::new(SCREEN_WIDTH as i32, SCREEN_HEIGHT as i32 / 2)).expect("draw line failed");
renderer.set_draw_color(yellow);
// future (nightly) rust has `step_by` instead of the extern num crate `range_step`
for i in range_step(0, SCREEN_HEIGHT, 4) {
renderer.draw_point(Point::new(SCREEN_WIDTH as i32 / 2, i as i32)).expect("draw point failed");;
}
renderer.present(); // screen update from the backbuffer
}
setup::quit();
}
|
use std::io::Read;
fn read<T: std::str::FromStr>() -> T {
let token: String = std::io::stdin()
.bytes()
.map(|c| c.ok().unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().unwrap()
}
fn main() {
let n: usize = read();
let mut x: Vec<f64> = vec![0.0; n];
for i in 0..n {
x[i] = read();
}
let ave = x.iter().sum::<f64>() / n as f64;
for x in x {
let d = 50.0 - (ave - x) / 2.0;
println!("{}", d.floor());
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::HB16CFG {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = "Possible values of the field `EPI_HB16CFG_MODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG_MODER {
#[doc = "ADMUX - AD\\[15:0\\]"]
EPI_HB16CFG_MODE_ADMUX,
#[doc = "ADNONMUX - D\\[15:0\\]"]
EPI_HB16CFG_MODE_ADNMUX,
#[doc = "Continuous Read - D\\[15:0\\]"]
EPI_HB16CFG_MODE_SRAM,
#[doc = "XFIFO - D\\[15:0\\]"]
EPI_HB16CFG_MODE_XFIFO,
}
impl EPI_HB16CFG_MODER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_ADMUX => 0,
EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_ADNMUX => 1,
EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_SRAM => 2,
EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_XFIFO => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_HB16CFG_MODER {
match value {
0 => EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_ADMUX,
1 => EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_ADNMUX,
2 => EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_SRAM,
3 => EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_XFIFO,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_MODE_ADMUX`"]
#[inline(always)]
pub fn is_epi_hb16cfg_mode_admux(&self) -> bool {
*self == EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_ADMUX
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_MODE_ADNMUX`"]
#[inline(always)]
pub fn is_epi_hb16cfg_mode_adnmux(&self) -> bool {
*self == EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_ADNMUX
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_MODE_SRAM`"]
#[inline(always)]
pub fn is_epi_hb16cfg_mode_sram(&self) -> bool {
*self == EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_SRAM
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_MODE_XFIFO`"]
#[inline(always)]
pub fn is_epi_hb16cfg_mode_xfifo(&self) -> bool {
*self == EPI_HB16CFG_MODER::EPI_HB16CFG_MODE_XFIFO
}
}
#[doc = "Values that can be written to the field `EPI_HB16CFG_MODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG_MODEW {
#[doc = "ADMUX - AD\\[15:0\\]"]
EPI_HB16CFG_MODE_ADMUX,
#[doc = "ADNONMUX - D\\[15:0\\]"]
EPI_HB16CFG_MODE_ADNMUX,
#[doc = "Continuous Read - D\\[15:0\\]"]
EPI_HB16CFG_MODE_SRAM,
#[doc = "XFIFO - D\\[15:0\\]"]
EPI_HB16CFG_MODE_XFIFO,
}
impl EPI_HB16CFG_MODEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_ADMUX => 0,
EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_ADNMUX => 1,
EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_SRAM => 2,
EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_XFIFO => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_MODEW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_MODEW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_HB16CFG_MODEW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "ADMUX - AD\\[15:0\\]"]
#[inline(always)]
pub fn epi_hb16cfg_mode_admux(self) -> &'a mut W {
self.variant(EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_ADMUX)
}
#[doc = "ADNONMUX - D\\[15:0\\]"]
#[inline(always)]
pub fn epi_hb16cfg_mode_adnmux(self) -> &'a mut W {
self.variant(EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_ADNMUX)
}
#[doc = "Continuous Read - D\\[15:0\\]"]
#[inline(always)]
pub fn epi_hb16cfg_mode_sram(self) -> &'a mut W {
self.variant(EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_SRAM)
}
#[doc = "XFIFO - D\\[15:0\\]"]
#[inline(always)]
pub fn epi_hb16cfg_mode_xfifo(self) -> &'a mut W {
self.variant(EPI_HB16CFG_MODEW::EPI_HB16CFG_MODE_XFIFO)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 0);
self.w.bits |= ((value as u32) & 3) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_BSELR {
bits: bool,
}
impl EPI_HB16CFG_BSELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_BSELW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_BSELW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = "Possible values of the field `EPI_HB16CFG_RDWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG_RDWSR {
#[doc = "Active RDn is 2 EPI clocks"]
EPI_HB16CFG_RDWS_2,
#[doc = "Active RDn is 4 EPI clocks"]
EPI_HB16CFG_RDWS_4,
#[doc = "Active RDn is 6 EPI clocks"]
EPI_HB16CFG_RDWS_6,
#[doc = "Active RDn is 8 EPI clocks"]
EPI_HB16CFG_RDWS_8,
}
impl EPI_HB16CFG_RDWSR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_2 => 0,
EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_4 => 1,
EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_6 => 2,
EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_8 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_HB16CFG_RDWSR {
match value {
0 => EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_2,
1 => EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_4,
2 => EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_6,
3 => EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_8,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_RDWS_2`"]
#[inline(always)]
pub fn is_epi_hb16cfg_rdws_2(&self) -> bool {
*self == EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_2
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_RDWS_4`"]
#[inline(always)]
pub fn is_epi_hb16cfg_rdws_4(&self) -> bool {
*self == EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_4
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_RDWS_6`"]
#[inline(always)]
pub fn is_epi_hb16cfg_rdws_6(&self) -> bool {
*self == EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_6
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_RDWS_8`"]
#[inline(always)]
pub fn is_epi_hb16cfg_rdws_8(&self) -> bool {
*self == EPI_HB16CFG_RDWSR::EPI_HB16CFG_RDWS_8
}
}
#[doc = "Values that can be written to the field `EPI_HB16CFG_RDWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG_RDWSW {
#[doc = "Active RDn is 2 EPI clocks"]
EPI_HB16CFG_RDWS_2,
#[doc = "Active RDn is 4 EPI clocks"]
EPI_HB16CFG_RDWS_4,
#[doc = "Active RDn is 6 EPI clocks"]
EPI_HB16CFG_RDWS_6,
#[doc = "Active RDn is 8 EPI clocks"]
EPI_HB16CFG_RDWS_8,
}
impl EPI_HB16CFG_RDWSW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_2 => 0,
EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_4 => 1,
EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_6 => 2,
EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_8 => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_RDWSW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_RDWSW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_HB16CFG_RDWSW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Active RDn is 2 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_rdws_2(self) -> &'a mut W {
self.variant(EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_2)
}
#[doc = "Active RDn is 4 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_rdws_4(self) -> &'a mut W {
self.variant(EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_4)
}
#[doc = "Active RDn is 6 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_rdws_6(self) -> &'a mut W {
self.variant(EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_6)
}
#[doc = "Active RDn is 8 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_rdws_8(self) -> &'a mut W {
self.variant(EPI_HB16CFG_RDWSW::EPI_HB16CFG_RDWS_8)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 4);
self.w.bits |= ((value as u32) & 3) << 4;
self.w
}
}
#[doc = "Possible values of the field `EPI_HB16CFG_WRWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG_WRWSR {
#[doc = "Active WRn is 2 EPI clocks"]
EPI_HB16CFG_WRWS_2,
#[doc = "Active WRn is 4 EPI clocks"]
EPI_HB16CFG_WRWS_4,
#[doc = "Active WRn is 6 EPI clocks"]
EPI_HB16CFG_WRWS_6,
#[doc = "Active WRn is 8 EPI clocks"]
EPI_HB16CFG_WRWS_8,
}
impl EPI_HB16CFG_WRWSR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_2 => 0,
EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_4 => 1,
EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_6 => 2,
EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_8 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_HB16CFG_WRWSR {
match value {
0 => EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_2,
1 => EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_4,
2 => EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_6,
3 => EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_8,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_WRWS_2`"]
#[inline(always)]
pub fn is_epi_hb16cfg_wrws_2(&self) -> bool {
*self == EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_2
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_WRWS_4`"]
#[inline(always)]
pub fn is_epi_hb16cfg_wrws_4(&self) -> bool {
*self == EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_4
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_WRWS_6`"]
#[inline(always)]
pub fn is_epi_hb16cfg_wrws_6(&self) -> bool {
*self == EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_6
}
#[doc = "Checks if the value of the field is `EPI_HB16CFG_WRWS_8`"]
#[inline(always)]
pub fn is_epi_hb16cfg_wrws_8(&self) -> bool {
*self == EPI_HB16CFG_WRWSR::EPI_HB16CFG_WRWS_8
}
}
#[doc = "Values that can be written to the field `EPI_HB16CFG_WRWS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_HB16CFG_WRWSW {
#[doc = "Active WRn is 2 EPI clocks"]
EPI_HB16CFG_WRWS_2,
#[doc = "Active WRn is 4 EPI clocks"]
EPI_HB16CFG_WRWS_4,
#[doc = "Active WRn is 6 EPI clocks"]
EPI_HB16CFG_WRWS_6,
#[doc = "Active WRn is 8 EPI clocks"]
EPI_HB16CFG_WRWS_8,
}
impl EPI_HB16CFG_WRWSW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_2 => 0,
EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_4 => 1,
EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_6 => 2,
EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_8 => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_WRWSW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_WRWSW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_HB16CFG_WRWSW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Active WRn is 2 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_wrws_2(self) -> &'a mut W {
self.variant(EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_2)
}
#[doc = "Active WRn is 4 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_wrws_4(self) -> &'a mut W {
self.variant(EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_4)
}
#[doc = "Active WRn is 6 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_wrws_6(self) -> &'a mut W {
self.variant(EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_6)
}
#[doc = "Active WRn is 8 EPI clocks"]
#[inline(always)]
pub fn epi_hb16cfg_wrws_8(self) -> &'a mut W {
self.variant(EPI_HB16CFG_WRWSW::EPI_HB16CFG_WRWS_8)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 6);
self.w.bits |= ((value as u32) & 3) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_MAXWAITR {
bits: u8,
}
impl EPI_HB16CFG_MAXWAITR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_MAXWAITW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_MAXWAITW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(255 << 8);
self.w.bits |= ((value as u32) & 255) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_BURSTR {
bits: bool,
}
impl EPI_HB16CFG_BURSTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_BURSTW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_BURSTW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 16);
self.w.bits |= ((value as u32) & 1) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_RDCRER {
bits: bool,
}
impl EPI_HB16CFG_RDCRER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_RDCREW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_RDCREW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 17);
self.w.bits |= ((value as u32) & 1) << 17;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_WRCRER {
bits: bool,
}
impl EPI_HB16CFG_WRCRER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_WRCREW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_WRCREW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 18);
self.w.bits |= ((value as u32) & 1) << 18;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_ALEHIGHR {
bits: bool,
}
impl EPI_HB16CFG_ALEHIGHR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_ALEHIGHW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_ALEHIGHW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 19);
self.w.bits |= ((value as u32) & 1) << 19;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_RDHIGHR {
bits: bool,
}
impl EPI_HB16CFG_RDHIGHR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_RDHIGHW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_RDHIGHW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 20);
self.w.bits |= ((value as u32) & 1) << 20;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_WRHIGHR {
bits: bool,
}
impl EPI_HB16CFG_WRHIGHR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_WRHIGHW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_WRHIGHW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 21);
self.w.bits |= ((value as u32) & 1) << 21;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_XFEENR {
bits: bool,
}
impl EPI_HB16CFG_XFEENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_XFEENW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_XFEENW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 22);
self.w.bits |= ((value as u32) & 1) << 22;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_XFFENR {
bits: bool,
}
impl EPI_HB16CFG_XFFENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_XFFENW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_XFFENW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 23);
self.w.bits |= ((value as u32) & 1) << 23;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_IRDYINVR {
bits: bool,
}
impl EPI_HB16CFG_IRDYINVR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_IRDYINVW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_IRDYINVW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 27);
self.w.bits |= ((value as u32) & 1) << 27;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_RDYENR {
bits: bool,
}
impl EPI_HB16CFG_RDYENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_RDYENW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_RDYENW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 28);
self.w.bits |= ((value as u32) & 1) << 28;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_CLKINVR {
bits: bool,
}
impl EPI_HB16CFG_CLKINVR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_CLKINVW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_CLKINVW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 29);
self.w.bits |= ((value as u32) & 1) << 29;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_CLKGATEIR {
bits: bool,
}
impl EPI_HB16CFG_CLKGATEIR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_CLKGATEIW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_CLKGATEIW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 30);
self.w.bits |= ((value as u32) & 1) << 30;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_HB16CFG_CLKGATER {
bits: bool,
}
impl EPI_HB16CFG_CLKGATER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_HB16CFG_CLKGATEW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_HB16CFG_CLKGATEW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 31);
self.w.bits |= ((value as u32) & 1) << 31;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - Host Bus Sub-Mode"]
#[inline(always)]
pub fn epi_hb16cfg_mode(&self) -> EPI_HB16CFG_MODER {
EPI_HB16CFG_MODER::_from(((self.bits >> 0) & 3) as u8)
}
#[doc = "Bit 2 - Byte Select Configuration"]
#[inline(always)]
pub fn epi_hb16cfg_bsel(&self) -> EPI_HB16CFG_BSELR {
let bits = ((self.bits >> 2) & 1) != 0;
EPI_HB16CFG_BSELR { bits }
}
#[doc = "Bits 4:5 - Read Wait States"]
#[inline(always)]
pub fn epi_hb16cfg_rdws(&self) -> EPI_HB16CFG_RDWSR {
EPI_HB16CFG_RDWSR::_from(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - Write Wait States"]
#[inline(always)]
pub fn epi_hb16cfg_wrws(&self) -> EPI_HB16CFG_WRWSR {
EPI_HB16CFG_WRWSR::_from(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bits 8:15 - Maximum Wait"]
#[inline(always)]
pub fn epi_hb16cfg_maxwait(&self) -> EPI_HB16CFG_MAXWAITR {
let bits = ((self.bits >> 8) & 255) as u8;
EPI_HB16CFG_MAXWAITR { bits }
}
#[doc = "Bit 16 - Burst Mode"]
#[inline(always)]
pub fn epi_hb16cfg_burst(&self) -> EPI_HB16CFG_BURSTR {
let bits = ((self.bits >> 16) & 1) != 0;
EPI_HB16CFG_BURSTR { bits }
}
#[doc = "Bit 17 - PSRAM Configuration Register Read"]
#[inline(always)]
pub fn epi_hb16cfg_rdcre(&self) -> EPI_HB16CFG_RDCRER {
let bits = ((self.bits >> 17) & 1) != 0;
EPI_HB16CFG_RDCRER { bits }
}
#[doc = "Bit 18 - PSRAM Configuration Register Write"]
#[inline(always)]
pub fn epi_hb16cfg_wrcre(&self) -> EPI_HB16CFG_WRCRER {
let bits = ((self.bits >> 18) & 1) != 0;
EPI_HB16CFG_WRCRER { bits }
}
#[doc = "Bit 19 - ALE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg_alehigh(&self) -> EPI_HB16CFG_ALEHIGHR {
let bits = ((self.bits >> 19) & 1) != 0;
EPI_HB16CFG_ALEHIGHR { bits }
}
#[doc = "Bit 20 - READ Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg_rdhigh(&self) -> EPI_HB16CFG_RDHIGHR {
let bits = ((self.bits >> 20) & 1) != 0;
EPI_HB16CFG_RDHIGHR { bits }
}
#[doc = "Bit 21 - WRITE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg_wrhigh(&self) -> EPI_HB16CFG_WRHIGHR {
let bits = ((self.bits >> 21) & 1) != 0;
EPI_HB16CFG_WRHIGHR { bits }
}
#[doc = "Bit 22 - External FIFO EMPTY Enable"]
#[inline(always)]
pub fn epi_hb16cfg_xfeen(&self) -> EPI_HB16CFG_XFEENR {
let bits = ((self.bits >> 22) & 1) != 0;
EPI_HB16CFG_XFEENR { bits }
}
#[doc = "Bit 23 - External FIFO FULL Enable"]
#[inline(always)]
pub fn epi_hb16cfg_xffen(&self) -> EPI_HB16CFG_XFFENR {
let bits = ((self.bits >> 23) & 1) != 0;
EPI_HB16CFG_XFFENR { bits }
}
#[doc = "Bit 27 - Input Ready Invert"]
#[inline(always)]
pub fn epi_hb16cfg_irdyinv(&self) -> EPI_HB16CFG_IRDYINVR {
let bits = ((self.bits >> 27) & 1) != 0;
EPI_HB16CFG_IRDYINVR { bits }
}
#[doc = "Bit 28 - Input Ready Enable"]
#[inline(always)]
pub fn epi_hb16cfg_rdyen(&self) -> EPI_HB16CFG_RDYENR {
let bits = ((self.bits >> 28) & 1) != 0;
EPI_HB16CFG_RDYENR { bits }
}
#[doc = "Bit 29 - Invert Output Clock Enable"]
#[inline(always)]
pub fn epi_hb16cfg_clkinv(&self) -> EPI_HB16CFG_CLKINVR {
let bits = ((self.bits >> 29) & 1) != 0;
EPI_HB16CFG_CLKINVR { bits }
}
#[doc = "Bit 30 - Clock Gated Idle"]
#[inline(always)]
pub fn epi_hb16cfg_clkgatei(&self) -> EPI_HB16CFG_CLKGATEIR {
let bits = ((self.bits >> 30) & 1) != 0;
EPI_HB16CFG_CLKGATEIR { bits }
}
#[doc = "Bit 31 - Clock Gated"]
#[inline(always)]
pub fn epi_hb16cfg_clkgate(&self) -> EPI_HB16CFG_CLKGATER {
let bits = ((self.bits >> 31) & 1) != 0;
EPI_HB16CFG_CLKGATER { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - Host Bus Sub-Mode"]
#[inline(always)]
pub fn epi_hb16cfg_mode(&mut self) -> _EPI_HB16CFG_MODEW {
_EPI_HB16CFG_MODEW { w: self }
}
#[doc = "Bit 2 - Byte Select Configuration"]
#[inline(always)]
pub fn epi_hb16cfg_bsel(&mut self) -> _EPI_HB16CFG_BSELW {
_EPI_HB16CFG_BSELW { w: self }
}
#[doc = "Bits 4:5 - Read Wait States"]
#[inline(always)]
pub fn epi_hb16cfg_rdws(&mut self) -> _EPI_HB16CFG_RDWSW {
_EPI_HB16CFG_RDWSW { w: self }
}
#[doc = "Bits 6:7 - Write Wait States"]
#[inline(always)]
pub fn epi_hb16cfg_wrws(&mut self) -> _EPI_HB16CFG_WRWSW {
_EPI_HB16CFG_WRWSW { w: self }
}
#[doc = "Bits 8:15 - Maximum Wait"]
#[inline(always)]
pub fn epi_hb16cfg_maxwait(&mut self) -> _EPI_HB16CFG_MAXWAITW {
_EPI_HB16CFG_MAXWAITW { w: self }
}
#[doc = "Bit 16 - Burst Mode"]
#[inline(always)]
pub fn epi_hb16cfg_burst(&mut self) -> _EPI_HB16CFG_BURSTW {
_EPI_HB16CFG_BURSTW { w: self }
}
#[doc = "Bit 17 - PSRAM Configuration Register Read"]
#[inline(always)]
pub fn epi_hb16cfg_rdcre(&mut self) -> _EPI_HB16CFG_RDCREW {
_EPI_HB16CFG_RDCREW { w: self }
}
#[doc = "Bit 18 - PSRAM Configuration Register Write"]
#[inline(always)]
pub fn epi_hb16cfg_wrcre(&mut self) -> _EPI_HB16CFG_WRCREW {
_EPI_HB16CFG_WRCREW { w: self }
}
#[doc = "Bit 19 - ALE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg_alehigh(&mut self) -> _EPI_HB16CFG_ALEHIGHW {
_EPI_HB16CFG_ALEHIGHW { w: self }
}
#[doc = "Bit 20 - READ Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg_rdhigh(&mut self) -> _EPI_HB16CFG_RDHIGHW {
_EPI_HB16CFG_RDHIGHW { w: self }
}
#[doc = "Bit 21 - WRITE Strobe Polarity"]
#[inline(always)]
pub fn epi_hb16cfg_wrhigh(&mut self) -> _EPI_HB16CFG_WRHIGHW {
_EPI_HB16CFG_WRHIGHW { w: self }
}
#[doc = "Bit 22 - External FIFO EMPTY Enable"]
#[inline(always)]
pub fn epi_hb16cfg_xfeen(&mut self) -> _EPI_HB16CFG_XFEENW {
_EPI_HB16CFG_XFEENW { w: self }
}
#[doc = "Bit 23 - External FIFO FULL Enable"]
#[inline(always)]
pub fn epi_hb16cfg_xffen(&mut self) -> _EPI_HB16CFG_XFFENW {
_EPI_HB16CFG_XFFENW { w: self }
}
#[doc = "Bit 27 - Input Ready Invert"]
#[inline(always)]
pub fn epi_hb16cfg_irdyinv(&mut self) -> _EPI_HB16CFG_IRDYINVW {
_EPI_HB16CFG_IRDYINVW { w: self }
}
#[doc = "Bit 28 - Input Ready Enable"]
#[inline(always)]
pub fn epi_hb16cfg_rdyen(&mut self) -> _EPI_HB16CFG_RDYENW {
_EPI_HB16CFG_RDYENW { w: self }
}
#[doc = "Bit 29 - Invert Output Clock Enable"]
#[inline(always)]
pub fn epi_hb16cfg_clkinv(&mut self) -> _EPI_HB16CFG_CLKINVW {
_EPI_HB16CFG_CLKINVW { w: self }
}
#[doc = "Bit 30 - Clock Gated Idle"]
#[inline(always)]
pub fn epi_hb16cfg_clkgatei(&mut self) -> _EPI_HB16CFG_CLKGATEIW {
_EPI_HB16CFG_CLKGATEIW { w: self }
}
#[doc = "Bit 31 - Clock Gated"]
#[inline(always)]
pub fn epi_hb16cfg_clkgate(&mut self) -> _EPI_HB16CFG_CLKGATEW {
_EPI_HB16CFG_CLKGATEW { w: self }
}
}
|
//! CallExpression
use serde::{Deserialize, Serialize};
/// Represents a function call
#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CallExpression {
/// Type of AST node
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub r#type: Option<String>,
/// Callee
#[serde(skip_serializing_if = "Option::is_none")]
pub callee: Option<Box<crate::models::ast::Expression>>,
/// Function arguments
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub arguments: Vec<crate::models::ast::Expression>,
}
impl CallExpression {
/// Represents a function call
pub fn new() -> Self {
Self::default()
}
}
|
use std::env;
use std::fmt;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process;
use std::str::FromStr;
use std::sync::atomic;
use std::time::Duration;
use csv;
use Csv;
static XSV_INTEGRATION_TEST_DIR: &'static str = "xit";
static NEXT_ID: atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT;
pub struct Workdir {
root: PathBuf,
dir: PathBuf,
flexible: bool,
}
impl Workdir {
pub fn new(name: &str) -> Workdir {
let id = NEXT_ID.fetch_add(1, atomic::Ordering::SeqCst);
let mut root = env::current_exe().unwrap()
.parent()
.expect("executable's directory")
.to_path_buf();
if root.ends_with("deps") {
root.pop();
}
let dir = root.join(XSV_INTEGRATION_TEST_DIR)
.join(name)
.join(&format!("test-{}", id));
if let Err(err) = create_dir_all(&dir) {
panic!("Could not create '{:?}': {}", dir, err);
}
Workdir { root: root, dir: dir, flexible: false }
}
pub fn flexible(mut self, yes: bool) -> Workdir {
self.flexible = yes;
self
}
pub fn create<T: Csv>(&self, name: &str, rows: T) {
let mut wtr = csv::Writer::from_file(&self.path(name))
.unwrap().flexible(self.flexible);
for row in rows.to_vecs().into_iter() {
wtr.write(row.iter()).unwrap();
}
wtr.flush().unwrap();
}
pub fn create_indexed<T: Csv>(&self, name: &str, rows: T) {
self.create(name, rows);
let mut cmd = self.command("index");
cmd.arg(name);
self.run(&mut cmd);
}
pub fn read_stdout<T: Csv>(&self, cmd: &mut process::Command) -> T {
let stdout: String = self.stdout(cmd);
let mut rdr = csv::Reader::from_string(stdout).has_headers(false);
Csv::from_vecs(rdr.records().collect::<Result<_, _>>().unwrap())
}
pub fn command(&self, sub_command: &str) -> process::Command {
let mut cmd = process::Command::new(&self.xsv_bin());
cmd.current_dir(&self.dir).arg(sub_command);
cmd
}
pub fn output(&self, cmd: &mut process::Command) -> process::Output {
debug!("[{}]: {:?}", self.dir.display(), cmd);
let o = cmd.output().unwrap();
if !o.status.success() {
panic!("\n\n===== {:?} =====\n\
command failed but expected success!\
\n\ncwd: {}\
\n\nstatus: {}\
\n\nstdout: {}\n\nstderr: {}\
\n\n=====\n",
cmd, self.dir.display(), o.status,
String::from_utf8_lossy(&o.stdout),
String::from_utf8_lossy(&o.stderr))
}
o
}
pub fn run(&self, cmd: &mut process::Command) {
self.output(cmd);
}
pub fn stdout<T: FromStr>(&self, cmd: &mut process::Command) -> T {
let o = self.output(cmd);
let stdout = String::from_utf8_lossy(&o.stdout);
stdout.trim_matches(&['\r', '\n'][..]).parse().ok().expect(
&format!("Could not convert from string: '{}'", stdout))
}
pub fn assert_err(&self, cmd: &mut process::Command) {
let o = cmd.output().unwrap();
if o.status.success() {
panic!("\n\n===== {:?} =====\n\
command succeeded but expected failure!\
\n\ncwd: {}\
\n\nstatus: {}\
\n\nstdout: {}\n\nstderr: {}\
\n\n=====\n",
cmd, self.dir.display(), o.status,
String::from_utf8_lossy(&o.stdout),
String::from_utf8_lossy(&o.stderr));
}
}
pub fn from_str<T: FromStr>(&self, name: &Path) -> T {
let mut o = String::new();
fs::File::open(name).unwrap().read_to_string(&mut o).unwrap();
o.parse().ok().expect("fromstr")
}
pub fn path(&self, name: &str) -> PathBuf {
self.dir.join(name)
}
pub fn xsv_bin(&self) -> PathBuf {
self.root.join("xsv")
}
}
impl fmt::Debug for Workdir {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "path={}", self.dir.display())
}
}
// For whatever reason, `fs::create_dir_all` fails intermittently on Travis
// with a weird "file exists" error. Despite my best efforts to get to the
// bottom of it, I've decided a try-wait-and-retry hack is good enough.
fn create_dir_all<P: AsRef<Path>>(p: P) -> io::Result<()> {
let mut last_err = None;
for _ in 0..10 {
if let Err(err) = fs::create_dir_all(&p) {
last_err = Some(err);
::std::thread::sleep(Duration::from_millis(500));
} else {
return Ok(())
}
}
Err(last_err.unwrap())
}
|
use crate::player_connection::PlayerConnection;
use serde::{Deserialize, Serialize};
pub type PlayerName = String;
pub type PlayerNameRef<'a> = &'a str;
#[derive(Clone, Serialize, Deserialize)]
pub struct Player<PC: PlayerConnection> {
name: PlayerName,
pub connection: Option<PC>,
pub state: PlayerState,
pub role: Role,
pub secret: String,
}
impl<PC: PlayerConnection> Player<PC> {
pub fn new(name: String, secret: String) -> Self {
Player {
name,
connection: None,
state: PlayerState::Alive,
role: Role::Townie,
secret,
}
}
pub fn get_name(&self) -> PlayerNameRef {
self.name.as_ref()
}
}
#[derive(Clone, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
pub enum PlayerState {
Alive,
Dead,
}
impl PlayerState {
pub fn is_alive(&self) -> bool {
*self == PlayerState::Alive
}
}
#[derive(Clone, Serialize, Deserialize)]
pub enum Role {
Townie,
Mafioso,
Doctor,
Bartender,
Detective,
}
|
use crate::{HdbResult, ServerError};
#[cfg(feature = "sync")]
use byteorder::{LittleEndian, ReadBytesExt};
/// Describes the success of a command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExecutionResult {
/// Number of rows that were affected by the successful execution.
RowsAffected(usize),
/// Command was successful.
SuccessNoInfo, // -2
/// Execution failed with given ServerError.
Failure(Option<ServerError>), // -3
}
impl ExecutionResult {
#[cfg(feature = "sync")]
pub(crate) fn parse_sync(count: usize, rdr: &mut dyn std::io::Read) -> HdbResult<Vec<Self>> {
let mut vec = Vec::<Self>::with_capacity(count);
for _ in 0..count {
match rdr.read_i32::<LittleEndian>()? {
-2 => vec.push(Self::SuccessNoInfo),
-3 => vec.push(Self::Failure(None)),
#[allow(clippy::cast_sign_loss)]
i => vec.push(Self::RowsAffected(i as usize)),
}
}
Ok(vec)
}
#[cfg(feature = "async")]
pub(crate) async fn parse_async<R: std::marker::Unpin + tokio::io::AsyncReadExt>(
count: usize,
rdr: &mut R,
) -> HdbResult<Vec<Self>> {
let mut vec = Vec::<Self>::with_capacity(count);
for _ in 0..count {
match rdr.read_i32_le().await? {
-2 => vec.push(Self::SuccessNoInfo),
-3 => vec.push(Self::Failure(None)),
#[allow(clippy::cast_sign_loss)]
i => vec.push(Self::RowsAffected(i as usize)),
}
}
Ok(vec)
}
/// True if it is an instance of `Self::Failure`.
pub fn is_failure(&self) -> bool {
matches!(self, Self::Failure(_))
}
/// True if it is an instance of `Self::RowsAffected`.
pub fn is_rows_affected(&self) -> bool {
matches!(self, Self::RowsAffected(_))
}
}
impl std::fmt::Display for ExecutionResult {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
Self::RowsAffected(count) => writeln!(fmt, "Number of affected rows: {count}, ")?,
Self::SuccessNoInfo => writeln!(
fmt,
"Command successfully executed but number of affected rows cannot be determined"
)?,
Self::Failure(Some(ref server_error)) => writeln!(
fmt,
"Execution of statement or processing of row has failed with {server_error:?}",
)?,
Self::Failure(None) => writeln!(
fmt,
"Execution of statement or processing of row has failed"
)?,
}
Ok(())
}
}
|
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//! Corrections for nutation
use angle;
use time;
use coords;
/**
Computes nutation in ecliptic longitude and obliquity
# Returns
`(nut_in_long, nut_in_oblq)`
* `nut_in_long`: Nutation in ecliptic longitude *| in radians*
* `nut_in_oblq`: Nutation in obliquity of the ecliptic *| in radians*
# Arguments
`JD`: Julian (Ephemeris) day
**/
pub fn nutation(JD: f64) -> (f64, f64)
{
struct terms(i8, i8, i8, i8, i8, i32, i32, i32, i16);
let terms_for_nutation = [
terms( 0, 0, 0, 0, 1, -171996, -1742, 92025, 89),
terms(-2, 0, 0, 2, 2, -13187, -16, 5736, -31),
terms( 0, 0, 0, 2, 2, -2274, -2, 977, -5),
terms( 0, 0, 0, 0, 2, 2062, 2, -895, 5),
terms( 0, 1, 0, 0, 0, 1426, -34, 54, -1),
terms( 0, 0, 1, 0, 0, 712, 1, -7, 0),
terms(-2, 1, 0, 2, 2, -517, 12, 224, -6),
terms( 0, 0, 0, 2, 1, -386, -4, 200, 0),
terms( 0, 0, 1, 2, 2, -301, 0, 129, -1),
terms(-2, -1, 0, 2, 2, 217, -5, -95, 3),
terms(-2, 0, 1, 0, 0, -158, 0, 0, 0),
terms(-2, 0, 0, 2, 1, 129, 1, -70, 0),
terms( 0, 0, -1, 2, 2, 123, 0, -53, 0),
terms( 2, 0, 0, 0, 0, 63, 0, 0, 0),
terms( 0, 0, 1, 0, 1, 63, 1, -33, 0),
terms( 2, 0, -1, 2, 2, -59, 0, 26, 0),
terms( 0, 0, -1, 0, 1, -58, -1, 32, 0),
terms( 0, 0, 1, 2, 1, -51, 0, 27, 0),
terms(-2, 0, 2, 0, 0, 48, 0, 0, 0),
terms( 0, 0, -2, 2, 1, 46, 0, -24, 0),
terms( 2, 0, 0, 2, 2, -38, 0, 16, 0),
terms( 0, 0, 2, 2, 2, -31, 0, 13, 0),
terms( 0, 0, 2, 0, 0, 29, 0, 0, 0),
terms(-2, 0, 1, 2, 2, 29, 0, -12, 0),
terms( 0, 0, 0, 2, 0, 26, 0, 0, 0),
terms(-2, 0, 0, 2, 0, -22, 0, 0, 0),
terms( 0, 0, -1, 2, 1, 21, 0, -10, 0),
terms( 0, 2, 0, 0, 0, 17, -1, 0, 0),
terms( 2, 0, -1, 0, 1, 16, 0, -8, 0),
terms(-2, 2, 0, 2, 2, -16, 1, 7, 0),
terms( 0, 1, 0, 0, 1, -15, 0, 9, 0),
terms(-2, 0, 1, 0, 1, -13, 0, 7, 0),
terms( 0, -1, 0, 0, 1, -12, 0, 6, 0),
terms( 0, 0, 2, -2, 0, 11, 0, 0, 0),
terms( 2, 0, -1, 2, 1, -10, 0, 5, 0),
terms( 2, 0, 1, 2, 2, -8, 0, 3, 0),
terms( 0, 1, 0, 2, 2, 7, 0, -3, 0),
terms(-2, 1, 1, 0, 0, -7, 0, 0, 0),
terms( 0, -1, 0, 2, 2, -7, 0, 3, 0),
terms( 2, 0, 0, 2, 1, -7, 0, 3, 0),
terms( 2, 0, 1, 0, 0, 6, 0, 0, 0),
terms(-2, 0, 2, 2, 2, 6, 0, -3, 0),
terms(-2, 0, 1, 2, 1, 6, 0, -3, 0),
terms( 2, 0, -2, 0, 1, -6, 0, 3, 0),
terms( 2, 0, 0, 0, 1, -6, 0, 3, 0),
terms( 0, -1, 1, 0, 0, 5, 0, 0, 0),
terms(-2, -1, 0, 2, 1, -5, 0, 3, 0),
terms(-2, 0, 0, 0, 1, -5, 0, 3, 0),
terms( 0, 0, 2, 2, 1, -5, 0, 3, 0),
terms(-2, 0, 2, 0, 1, 4, 0, 0, 0),
terms(-2, 1, 0, 2, 1, 4, 0, 0, 0),
terms( 0, 0, 1, -2, 0, 4, 0, 0, 0),
terms(-1, 0, 1, 0, 0, -4, 0, 0, 0),
terms(-2, 1, 0, 0, 0, -4, 0, 0, 0),
terms( 1, 0, 0, 0, 0, -4, 0, 0, 0),
terms( 0, 0, 1, 2, 0, 3, 0, 0, 0),
terms( 0, 0, -2, 2, 2, -3, 0, 0, 0),
terms(-1, -1, 1, 0, 0, -3, 0, 0, 0),
terms( 0, 1, 1, 0, 0, -3, 0, 0, 0),
terms( 0, -1, 1, 2, 2, -3, 0, 0, 0),
terms( 2, -1, -1, 2, 2, -3, 0, 0, 0),
terms( 0, 0, 3, 2, 2, -3, 0, 0, 0),
terms( 2, -1, 0, 2, 2, -3, 0, 0, 0),
];
let t = time::julian_cent(JD);
let M1 = angle::limit_to_360(
134.96298 + t*(477198.867398 + t*(0.0086972 + t/56250.0))
).to_radians();
let M = angle::limit_to_360(
357.52772 + t*(35999.05034 - t*(0.0001603 + t/300000.0))
).to_radians();
let D = angle::limit_to_360(
297.85036 + t*(445267.11148 - t*(0.0019142 - t/189474.0))
).to_radians();
let F = angle::limit_to_360(
93.27191 + t*(483202.017538 - t*(0.0036825 - t/327270.0))
).to_radians();
let om = angle::limit_to_360(
125.04452 - t*(1934.136261 - t*(0.0020708 + t/450000.0))
).to_radians();
let mut nut_in_long = 0.0;
let mut nut_in_oblq = 0.0;
let div = 0.0001/3600.0;
for x in terms_for_nutation.iter() {
let arg =
(x.0 as f64) * D +
(x.1 as f64) * M +
(x.2 as f64) * M1 +
(x.3 as f64) * F +
(x.4 as f64) * om;
nut_in_long += ((x.5 as f64) + t*(x.6 as f64)/10.0) * arg.sin() * div;
nut_in_oblq += ((x.7 as f64) + t*(x.8 as f64)/10.0) * arg.cos() * div;
}
(nut_in_long.to_radians(), nut_in_oblq.to_radians())
}
/**
Computes nutation in equatorial coordinates
# Returns
`(nut_in_asc, nut_in_dec)`
* `nut_in_asc`: Nutation in right ascension *| in radians*
* `nut_in_dec`: Nutation in declination *| in radians*
# Arguments
* `eq_point` : Equatorial point uncorrected for nutation *| in radians*
* `nut_in_long`: Nutation in longitude *| in radians*
* `nut_in_oblq`: Nutation in obliquity *| in radians*
* `tru_oblq` : True obliquity of the ecliptic *| in radians*
The declination of `eq_point` should not be close to either of the
two of the celestial poles, as the values of nutation returned here
are only from first-order corrections.
**/
pub fn nutation_in_eq_coords(eq_point: &coords::EqPoint, nut_in_long: f64,
nut_in_oblq : f64, tru_oblq: f64) -> (f64, f64)
{
let (asc, dec) = (eq_point.asc, eq_point.dec);
let nut_asc = nut_in_long * (
tru_oblq.cos()
+ tru_oblq.sin() * asc.sin() * dec.tan()
) - asc.cos() * dec.tan() * nut_in_oblq;
let nut_dec =
tru_oblq.sin() * asc.cos() * nut_in_long
+ asc.sin() * nut_in_oblq;
(nut_asc, nut_dec)
}
|
use std::collections::HashMap;
use opencv::core::{CV_PI, Point, Scalar, Vector, Size, MatTrait, Point2f, BORDER_CONSTANT, MatTraitManual, Mat};
use opencv::imgcodecs::{imread, imwrite, IMREAD_GRAYSCALE, IMREAD_COLOR};
use opencv::imgproc::{canny, hough_lines_p, line, warp_affine, get_rotation_matrix_2d, WARP_INVERSE_MAP, threshold, THRESH_OTSU};
use opencv::types::{VectorOfVec4i};
use ang::atan2;
const SOURCE_IMAGE_PATH: &str = "src_img.png";
fn main() {
// 処理元の画像を定義
let src_img = imread(SOURCE_IMAGE_PATH, IMREAD_GRAYSCALE).unwrap();
if src_img.data().is_err() {
panic!("Failed to read image.")
};
// 出力先の画像を定義
let output_img;
let result_read_img = imread(SOURCE_IMAGE_PATH, IMREAD_COLOR);
match result_read_img {
Ok(img) => output_img = img,
Err(code) => {
panic!("code: {:?}", code);
}
};
let width = src_img.cols();
let height = src_img.rows();
// エッジ検出で使用する閾値の計算
let max_thresh_val = threshold(&src_img, &mut Mat::default(), 0.0, 255.0, THRESH_OTSU).unwrap();
let min_thresh_val = max_thresh_val * 0.5;
// エッジ検出
let mut edge_img = src_img.clone();
let result_find_edge = canny(&src_img, &mut edge_img, min_thresh_val, max_thresh_val, 3, false);
match result_find_edge {
Ok(_) => imwrite("edge.png", &edge_img, &Vector::new()).ok(),
Err(code) => {
panic!("code: {:?}", code);
}
};
// ハフ変換による直線検出
let mut line_img = output_img.clone();
let max_line_gap = (((width * width) + (height * height)) as f64).sqrt();
let mut lines= VectorOfVec4i::default();
let threshold_val_for_hough = (max_thresh_val * 2.0) as i32;
let result_hough_lines= hough_lines_p(&edge_img, &mut lines, 1.0, CV_PI / 180.0, threshold_val_for_hough, 0.0, max_line_gap);
match result_hough_lines {
Ok(_) => {
// 線分を描画する
for line_vec in lines.to_vec() {
line(&mut line_img,
Point::new(line_vec[0], line_vec[1]),
Point::new(line_vec[2], line_vec[3]),
Scalar::new(0.0, 0.0, 255.0, 1.0),
1,
0,
0
).ok();
}
imwrite("line.png", &line_img, &Vector::new()).ok();
},
Err(code) => {
panic!("code: {:?}", code);
}
}
// 線分の角度の配列を作成する
let mut angles = vec![];
for line_vec in lines.to_vec() {
let x1 = line_vec[0] as f64;
let y1 = line_vec[1] as f64;
let x2 = line_vec[2] as f64;
let y2 = line_vec[3] as f64;
let angle = atan2(y2 - y1, x1 - x2).in_degrees().round() as i32;
angles.push(angle);
}
// 角度の配列から最頻値を取得(複数ある場合は最初の要素を選択)
let angle = get_mode(&angles).first().unwrap().clone();
// 角度が0or90の場合は何もしない。
// それ以外はアフィン変換
let result_img = if angle.abs() == 0 || angle.abs() == 90 {
src_img
} else {
let mut dst_img = src_img.clone();
let center = Point2f::new((width/2) as f32, (height/2) as f32); // 回転中心
let rotation_angle = (angle - 180) as f64; // 回転する角度
let m =
get_rotation_matrix_2d(center, rotation_angle, 1.0)
.unwrap_or_else(|code| {
panic!("code: {}", code)
});
let size = Size::new(width, height); // 出力画像のサイズ
let result_affine = warp_affine(&src_img, &mut dst_img, &m, size, WARP_INVERSE_MAP, BORDER_CONSTANT, Scalar::default());
match result_affine {
Ok(_) => {
dst_img
},
Err(code) => {
panic!("code: {}", code);
}
}
};
imwrite("result.png", &result_img, &Vector::new())
.unwrap_or_else(|e| panic!("code: {}", e));
}
pub fn get_mode(numbers: &Vec<i32>) -> Vec<i32> {
let mut map = HashMap::new();
for integer in numbers {
let count = map.entry(integer).or_insert(0);
*count += 1;
}
let max_value = map.values().cloned().max().unwrap_or(0);
map.into_iter()
.filter(|&(_, v)| v == max_value)
.map(|(&k, _)| k)
.collect()
}
|
use std::io::{self, Read};
use std::io::prelude::*;
use std::collections::BTreeSet;
use std::collections::HashSet;
use std::collections::HashMap;
fn main(){
let stdin = std::io::stdin();
let mut it = stdin.lock().lines();
let mut s:HashSet<char> = HashSet::new();
let mut m:HashMap<String,f64> = HashMap::new();
let a = &it.next().unwrap().unwrap();
let a = a.parse::<i32>();
for i in 0..a.unwrap() {
//println!("{}", i);
let a = &it.next().unwrap().unwrap();
let bs = a.split(' ').collect::<Vec<_>>();
let cn = String::from(bs[0]);
let pn = bs[1].parse::<f64>().unwrap();
m.insert(cn, pn);
}
let mut acc:f64 = 0.0;
for (cn, pn) in &m {
//println!("{}", cn);
acc += pn.clone();
}
let mut r:Option<String> = None;
for (cn, pn) in &m {
if pn/acc > 0.5 {
r = Some(cn.clone());
}
}
match r {
Some(x) => println!("{}", x),
None => println!("atcoder"),
}
}
|
use std::process::Output;
mod cache;
use cache::CheckPackmanCache;
pub trait UseCase {
fn id(&self) -> String;
fn name(&self) -> String;
fn description(&self) -> String;
fn execute(&self) -> Output;
}
pub fn items() -> [impl UseCase; 1] {
let usecases: [CheckPackmanCache; 1] = [
CheckPackmanCache::new()
];
return usecases;
}
#[cfg(test)]
mod tests {
use super::UseCase;
use super::items;
#[test]
fn test_number_of_use_cases() {
assert_eq!(1, items().len());
}
#[test]
fn test_order_of_elements() {
use std::convert::TryInto;
let usecases = items();
for (i, item) in usecases.iter().enumerate() {
let current_element_plus_one: u32 = (i + 1).try_into().unwrap();
let item_id = item.id().parse::<u32>();
assert_eq!(item_id, Ok(current_element_plus_one));
}
}
} |
use crate::connectionInfo::ContactInfo;
use bincode::serialize;
use morgan_interface::pubkey::Pubkey;
use morgan_interface::signature::{Keypair, Signable, Signature};
use morgan_interface::transaction::Transaction;
use std::collections::BTreeSet;
use std::fmt;
/// CrdsValue that is replicated across the cluster
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum CrdsValue {
/// * Merge Strategy - Latest wallclock is picked
ContactInfo(ContactInfo),
/// * Merge Strategy - Latest wallclock is picked
Vote(Vote),
/// * Merge Strategy - Latest wallclock is picked
EpochSlots(EpochSlots),
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct EpochSlots {
pub from: Pubkey,
pub root: u64,
pub slots: BTreeSet<u64>,
pub signature: Signature,
pub wallclock: u64,
}
impl EpochSlots {
pub fn new(from: Pubkey, root: u64, slots: BTreeSet<u64>, wallclock: u64) -> Self {
Self {
from,
root,
slots,
signature: Signature::default(),
wallclock,
}
}
}
impl Signable for EpochSlots {
fn pubkey(&self) -> Pubkey {
self.from
}
fn signable_data(&self) -> Vec<u8> {
#[derive(Serialize)]
struct SignData<'a> {
root: u64,
slots: &'a BTreeSet<u64>,
wallclock: u64,
}
let data = SignData {
root: self.root,
slots: &self.slots,
wallclock: self.wallclock,
};
serialize(&data).expect("unable to serialize EpochSlots")
}
fn get_signature(&self) -> Signature {
self.signature
}
fn set_signature(&mut self, signature: Signature) {
self.signature = signature;
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Vote {
pub from: Pubkey,
pub transaction: Transaction,
pub signature: Signature,
pub wallclock: u64,
}
impl Vote {
pub fn new(from: &Pubkey, transaction: Transaction, wallclock: u64) -> Self {
Self {
from: *from,
transaction,
signature: Signature::default(),
wallclock,
}
}
}
impl Signable for Vote {
fn pubkey(&self) -> Pubkey {
self.from
}
fn signable_data(&self) -> Vec<u8> {
#[derive(Serialize)]
struct SignData<'a> {
transaction: &'a Transaction,
wallclock: u64,
}
let data = SignData {
transaction: &self.transaction,
wallclock: self.wallclock,
};
serialize(&data).expect("unable to serialize Vote")
}
fn get_signature(&self) -> Signature {
self.signature
}
fn set_signature(&mut self, signature: Signature) {
self.signature = signature
}
}
/// Type of the replicated value
/// These are labels for values in a record that is associated with `Pubkey`
#[derive(PartialEq, Hash, Eq, Clone, Debug)]
pub enum CrdsValueLabel {
ContactInfo(Pubkey),
Vote(Pubkey),
EpochSlots(Pubkey),
}
impl fmt::Display for CrdsValueLabel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CrdsValueLabel::ContactInfo(_) => write!(f, "ContactInfo({})", self.pubkey()),
CrdsValueLabel::Vote(_) => write!(f, "Vote({})", self.pubkey()),
CrdsValueLabel::EpochSlots(_) => write!(f, "EpochSlots({})", self.pubkey()),
}
}
}
impl CrdsValueLabel {
pub fn pubkey(&self) -> Pubkey {
match self {
CrdsValueLabel::ContactInfo(p) => *p,
CrdsValueLabel::Vote(p) => *p,
CrdsValueLabel::EpochSlots(p) => *p,
}
}
}
impl CrdsValue {
/// Totally unsecure unverfiable wallclock of the node that generated this message
/// Latest wallclock is always picked.
/// This is used to time out push messages.
pub fn wallclock(&self) -> u64 {
match self {
CrdsValue::ContactInfo(contact_info) => contact_info.wallclock,
CrdsValue::Vote(vote) => vote.wallclock,
CrdsValue::EpochSlots(vote) => vote.wallclock,
}
}
pub fn label(&self) -> CrdsValueLabel {
match self {
CrdsValue::ContactInfo(contact_info) => {
CrdsValueLabel::ContactInfo(contact_info.pubkey())
}
CrdsValue::Vote(vote) => CrdsValueLabel::Vote(vote.pubkey()),
CrdsValue::EpochSlots(slots) => CrdsValueLabel::EpochSlots(slots.pubkey()),
}
}
pub fn contact_info(&self) -> Option<&ContactInfo> {
match self {
CrdsValue::ContactInfo(contact_info) => Some(contact_info),
_ => None,
}
}
pub fn vote(&self) -> Option<&Vote> {
match self {
CrdsValue::Vote(vote) => Some(vote),
_ => None,
}
}
pub fn epoch_slots(&self) -> Option<&EpochSlots> {
match self {
CrdsValue::EpochSlots(slots) => Some(slots),
_ => None,
}
}
/// Return all the possible labels for a record identified by Pubkey.
pub fn record_labels(key: &Pubkey) -> [CrdsValueLabel; 3] {
[
CrdsValueLabel::ContactInfo(*key),
CrdsValueLabel::Vote(*key),
CrdsValueLabel::EpochSlots(*key),
]
}
}
impl Signable for CrdsValue {
fn sign(&mut self, keypair: &Keypair) {
match self {
CrdsValue::ContactInfo(contact_info) => contact_info.sign(keypair),
CrdsValue::Vote(vote) => vote.sign(keypair),
CrdsValue::EpochSlots(epoch_slots) => epoch_slots.sign(keypair),
};
}
fn verify(&self) -> bool {
match self {
CrdsValue::ContactInfo(contact_info) => contact_info.verify(),
CrdsValue::Vote(vote) => vote.verify(),
CrdsValue::EpochSlots(epoch_slots) => epoch_slots.verify(),
}
}
fn pubkey(&self) -> Pubkey {
match self {
CrdsValue::ContactInfo(contact_info) => contact_info.pubkey(),
CrdsValue::Vote(vote) => vote.pubkey(),
CrdsValue::EpochSlots(epoch_slots) => epoch_slots.pubkey(),
}
}
fn signable_data(&self) -> Vec<u8> {
unimplemented!()
}
fn get_signature(&self) -> Signature {
match self {
CrdsValue::ContactInfo(contact_info) => contact_info.get_signature(),
CrdsValue::Vote(vote) => vote.get_signature(),
CrdsValue::EpochSlots(epoch_slots) => epoch_slots.get_signature(),
}
}
fn set_signature(&mut self, _: Signature) {
unimplemented!()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::connectionInfo::ContactInfo;
use crate::testTx::test_tx;
use bincode::deserialize;
use morgan_interface::signature::{Keypair, KeypairUtil};
use morgan_interface::timing::timestamp;
#[test]
fn test_labels() {
let mut hits = [false; 3];
// this method should cover all the possible labels
for v in &CrdsValue::record_labels(&Pubkey::default()) {
match v {
CrdsValueLabel::ContactInfo(_) => hits[0] = true,
CrdsValueLabel::Vote(_) => hits[1] = true,
CrdsValueLabel::EpochSlots(_) => hits[2] = true,
}
}
assert!(hits.iter().all(|x| *x));
}
#[test]
fn test_keys_and_values() {
let v = CrdsValue::ContactInfo(ContactInfo::default());
assert_eq!(v.wallclock(), 0);
let key = v.clone().contact_info().unwrap().id;
assert_eq!(v.label(), CrdsValueLabel::ContactInfo(key));
let v = CrdsValue::Vote(Vote::new(&Pubkey::default(), test_tx(), 0));
assert_eq!(v.wallclock(), 0);
let key = v.clone().vote().unwrap().from;
assert_eq!(v.label(), CrdsValueLabel::Vote(key));
let v = CrdsValue::EpochSlots(EpochSlots::new(Pubkey::default(), 0, BTreeSet::new(), 0));
assert_eq!(v.wallclock(), 0);
let key = v.clone().epoch_slots().unwrap().from;
assert_eq!(v.label(), CrdsValueLabel::EpochSlots(key));
}
#[test]
fn test_signature() {
let keypair = Keypair::new();
let wrong_keypair = Keypair::new();
let mut v =
CrdsValue::ContactInfo(ContactInfo::new_localhost(&keypair.pubkey(), timestamp()));
verify_signatures(&mut v, &keypair, &wrong_keypair);
v = CrdsValue::Vote(Vote::new(&keypair.pubkey(), test_tx(), timestamp()));
verify_signatures(&mut v, &keypair, &wrong_keypair);
let btreeset: BTreeSet<u64> = vec![1, 2, 3, 6, 8].into_iter().collect();
v = CrdsValue::EpochSlots(EpochSlots::new(keypair.pubkey(), 0, btreeset, timestamp()));
verify_signatures(&mut v, &keypair, &wrong_keypair);
}
fn test_serialize_deserialize_value(value: &mut CrdsValue, keypair: &Keypair) {
let num_tries = 10;
value.sign(keypair);
let original_signature = value.get_signature();
for _ in 0..num_tries {
let serialized_value = serialize(value).unwrap();
let deserialized_value: CrdsValue = deserialize(&serialized_value).unwrap();
// Signatures shouldn't change
let deserialized_signature = deserialized_value.get_signature();
assert_eq!(original_signature, deserialized_signature);
// After deserializing, check that the signature is still the same
assert!(deserialized_value.verify());
}
}
fn verify_signatures(
value: &mut CrdsValue,
correct_keypair: &Keypair,
wrong_keypair: &Keypair,
) {
assert!(!value.verify());
value.sign(&correct_keypair);
assert!(value.verify());
value.sign(&wrong_keypair);
assert!(!value.verify());
test_serialize_deserialize_value(value, correct_keypair);
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{Error, ResultExt},
fidl_fuchsia_test_echos::{EchoExposedBySiblingRequest, EchoExposedBySiblingRequestStream},
fuchsia_async as fasync,
fuchsia_component::server::ServiceFs,
futures::prelude::*,
};
fn echo_sibling_server(stream: EchoExposedBySiblingRequestStream) -> impl Future<Output = ()> {
stream
.err_into::<failure::Error>()
.try_for_each(|EchoExposedBySiblingRequest::Echo { value, responder }| async move {
responder.send(value * 2).context("sending response")?;
Ok(())
})
.unwrap_or_else(|e: failure::Error| panic!("error running echo server: {:?}", e))
}
#[fasync::run_singlethreaded]
async fn main() -> Result<(), Error> {
// Expose fuchsia.test.echos.EchoExposedBySibling FIDL service that multiplies all inputs by 2.
let mut fs = ServiceFs::new();
fs.dir("svc").add_fidl_service(|stream| stream);
fs.take_and_serve_directory_handle()?;
// spawn server to respond to FIDL requests
fs.for_each_concurrent(None, echo_sibling_server).await;
Ok(())
}
|
use std::io::Write;
pub mod env;
pub mod functions;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AST {
Nil,
Const(i64),
Lit(String),
Let(String, Box<AST>, Box<AST>),
Def(String, Box<AST>),
Function(String, Box<AST>),
Apply(Box<AST>, Box<AST>),
Native1(String, Box<AST>),
Native2(String, Box<AST>, Box<AST>),
Cond(Box<AST>, Box<AST>, Box<AST>),
}
fn TRUE() -> AST {
AST::Lit("true".to_string())
}
fn FALSE() -> AST {
AST::Lit("false".to_string())
}
fn eval(env: &mut env::Env, value: AST) -> Result<AST, String> {
if env.debug() {
println!("{:?}", value.clone());
}
return match value {
AST::Nil => Ok(AST::Nil),
AST::Const(v) => Ok(AST::Const(v)),
AST::Lit(name) => match env.get_var(name.clone()) {
Some(expr) => Result::Ok(eval(env, expr.clone())?),
None => Ok(AST::Lit(name)),
},
AST::Let(name, head, body) => {
let define = eval(env, *head)?;
env.add_var(name.clone(), define);
let res = eval(env, *body)?;
env.del_var(name);
Ok(res)
}
AST::Def(name, defined) => {
env.add_var(name.clone(), *defined);
Ok(AST::Nil)
}
AST::Function(argname, body) => Ok(AST::Function(argname, body)),
AST::Apply(func, argvalue) => match eval(env, *func)? {
AST::Function(argname, funcbody) => {
let computed_arg = eval(env, *argvalue)?;
env.frame_push();
env.add_var(argname.clone(), computed_arg.clone());
let computed = eval(env, *funcbody)?;
let res = match computed {
AST::Function(arg, body) => AST::Function(
arg,
Box::new(AST::Let(argname.clone(), Box::new(computed_arg), body)),
),
other => other,
};
env.del_var(argname.clone());
env.frame_pop();
Ok(res)
}
other => {
Result::Err(format!("calling {:?} which is not a function", other).to_string())
}
},
AST::Native1(name, arg0) => {
let mut nenv = env.clone();
match env.get_native(name.clone()) {
Some(f) => {
let _arg0 = eval(&mut nenv, *arg0)?;
f(vec![_arg0])
}
None => Err(format!("native function {} not defined", name)),
}
}
AST::Native2(name, arg0, arg1) => {
let mut nenv = env.clone();
match env.get_native(name.clone()) {
Some(f) => {
let _arg0 = eval(&mut nenv, *arg0)?;
let _arg1 = eval(&mut nenv, *arg1)?;
f(vec![_arg0, _arg1])
}
None => Err(format!("native function {} not defined", name)),
}
}
AST::Cond(cond, body, fallback) => {
if eval(env, *cond) == Ok(AST::Lit("true".to_string())) {
eval(env, *body)
} else {
eval(env, *fallback)
}
}
};
}
fn parse_iter<Tokens>(tokens: &mut Tokens) -> Option<AST>
where
Tokens: Iterator<Item = String>,
{
match tokens.next()?.as_str() {
"let" => {
let name = tokens.next()?.to_string();
tokens.next().filter(|x| x == "=");
let head = parse_iter(tokens)?;
tokens.next().filter(|x| x == "in");
let body = parse_iter(tokens)?;
Some(AST::Let(name.to_string(), Box::new(head), Box::new(body)))
}
"@" => {
let func = parse_iter(tokens)?;
let arg = parse_iter(tokens)?;
Some(AST::Apply(Box::new(func), Box::new(arg)))
}
"native1" => {
let name = tokens.next()?.to_string();
let arg0 = parse_iter(tokens)?;
Some(AST::Native1(name, Box::new(arg0)))
}
"native2" => {
let name = tokens.next()?.to_string();
let arg0 = parse_iter(tokens)?;
let arg1 = parse_iter(tokens)?;
Some(AST::Native2(name, Box::new(arg0), Box::new(arg1)))
}
"fn" => {
let argname = tokens.next()?.to_string();
tokens.next().filter(|x| x == "->");
let funcbody = parse_iter(tokens)?;
Some(AST::Function(argname.to_string(), Box::new(funcbody)))
}
"def" => {
let name = tokens.next()?.to_string();
tokens.next().filter(|x| x == "=");
let defined = parse_iter(tokens)?;
Some(AST::Def(name.to_string(), Box::new(defined)))
}
"if" => {
let cond = parse_iter(tokens)?;
tokens.next().filter(|x| x == "then");
let body = parse_iter(tokens)?;
tokens.next().filter(|x| x == "else");
let fallback = parse_iter(tokens)?;
Some(AST::Cond(
Box::new(cond),
Box::new(body),
Box::new(fallback),
))
}
token => match token.parse::<i64>() {
Ok(value) => Some(AST::Const(value)),
Err(_) => Some(AST::Lit(token.to_string())),
},
}
}
fn parse(code: String) -> AST {
let mut tokens = code.split_whitespace().map(|x| x.to_string());
parse_iter(&mut tokens).unwrap()
}
fn repr(value: AST) -> String {
match value {
AST::Nil => "Nil".to_string(),
AST::Const(v) => format!("{}", v),
AST::Lit(s) => s,
AST::Let(name, head, body) => format!("let {} = {} in {}", name, repr(*head), repr(*body)),
AST::Def(name, _) => format!("def {} = <code>", name),
AST::Function(argname, body) => format!("fn {} -> {}", argname, repr(*body)),
AST::Apply(f, arg) => format!("@ {} {}", repr(*f), repr(*arg)),
AST::Native1(name, arg0) => format!("native {} {}", name, repr(*arg0)),
AST::Native2(name, arg0, arg1) => {
format!("native {} {} {}", name, repr(*arg0), repr(*arg1))
}
AST::Cond(cond, body, fallback) => format!(
"if {} then {} else {}",
repr(*cond),
repr(*body),
repr(*fallback)
),
}
}
fn read() -> String {
print!("spirit> ");
std::io::stdout().flush().unwrap();
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).unwrap();
return buffer;
}
fn print(res: Result<AST, String>) -> () {
print!("> ");
match res {
Ok(result) => println!("{:?}", result),
Err(err) => println!("ERROR : {:?}", err),
}
}
fn builtin(env: &mut env::Env, name: &str, code: &str) -> () {
env.add_var(name.to_string(), parse(code.to_string()));
}
fn main() {
let mut env = env::Env::new(false);
env.add_native("native:print".to_string(), functions::print);
builtin(&mut env, "print", "fn x -> native1 native:print x");
env.add_native("native:add".to_string(), functions::add);
env.add_native("native:sub".to_string(), functions::sub);
env.add_native("native:mul".to_string(), functions::mul);
env.add_native("native:eq".to_string(), functions::eq);
env.add_native("native:lt".to_string(), functions::lt);
env.add_native("native:gt".to_string(), functions::gt);
builtin(&mut env, "add", "fn x -> fn y -> native2 native:add x y");
builtin(&mut env, "sub", "fn x -> fn y -> native2 native:sub x y");
builtin(&mut env, "mul", "fn x -> fn y -> native2 native:mul x y");
builtin(&mut env, "eq", "fn x -> fn y -> native2 native:eq x y");
builtin(&mut env, "gt", "fn x -> fn y -> native2 native:gt x y");
builtin(&mut env, "lt", "fn x -> fn y -> native2 native:lt x y");
loop {
print(eval(&mut env, parse(read())));
}
}
|
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate clap;
extern crate libc;
extern crate nasl_sys;
use std::fs;
use std::env;
use std::ptr;
use std::mem;
use std::ffi::{ CStr, CString };
use std::net::{ Ipv4Addr, IpAddr, };
pub fn c_str<T: Into<Vec<u8>>>(t: T) -> *mut libc::c_char {
CString::new(t).unwrap().into_raw()
}
pub struct Vm {
}
impl Vm {
pub fn new() -> Result<Self, ()> {
unsafe {
nasl_sys::gcrypt_init();
nasl_sys::openvas_SSL_init();
}
Ok( Vm {} )
}
pub fn version(&self) -> String {
unsafe {
CStr::from_ptr(nasl_sys::nasl_version())
.to_str().unwrap().to_string()
}
}
pub fn add_include_dir(&self, dirname: &str) -> Result<(), ()> {
let include_dir = fs::canonicalize(dirname).unwrap().display().to_string();
unsafe {
if nasl_sys::add_nasl_inc_dir(c_str(include_dir)) != 0 {
return Err(())
} else {
return Ok(())
}
}
}
pub fn parse(&self, _target: &IpAddr, _script_name: &str) -> Result<(), ()> {
unimplemented!()
}
pub fn description(&self, script_name: &str) -> Result<(), ()> {
unsafe {
let mut ip6: libc::in6_addr = mem::zeroed();
ip6.s6_addr = Ipv4Addr::new(127, 0, 0, 1).to_ipv6_mapped().octets();
let vclass = *nasl_sys::KBDefaultOperations;
assert_eq!(vclass.kb_new.is_some(), true);
let kb_new = vclass.kb_new.unwrap();
let mut kb: nasl_sys::kb_t = ptr::null_mut();
if kb_new(&mut kb, c_str(nasl_sys::KB_PATH_DEFAULT)) > 0 {
error!("kb_new failed.");
return Err(());
}
let mut script_infos = nasl_sys::init(&mut ip6, ptr::null_mut(), kb);
(*script_infos).name = c_str(script_name);
let nvti: *mut nasl_sys::nvti_t = nasl_sys::parse_script_infos(script_infos);
if nvti.is_null() {
error!("parse_script_infos failed.");
return Err(());
}
}
Ok(())
}
pub fn attack(&self, target: &IpAddr, script_name: &str) -> Result<(), ()> {
unsafe {
let mut ip6: libc::in6_addr = mem::zeroed();
let v6_octets = match target {
IpAddr::V4(v4_addr) => v4_addr.to_ipv6_mapped().octets(),
IpAddr::V6(v6_addr) => v6_addr.octets(),
};
ip6.s6_addr = v6_octets;
let vclass = *nasl_sys::KBDefaultOperations;
assert_eq!(vclass.kb_new.is_some(), true);
let kb_new = vclass.kb_new.unwrap();
let mut kb: nasl_sys::kb_t = ptr::null_mut();
if kb_new(&mut kb, c_str(nasl_sys::KB_PATH_DEFAULT)) > 0 {
error!("kb_new failed.");
return Err(());
}
let mut script_infos = nasl_sys::init(&mut ip6, ptr::null_mut(), kb);
(*script_infos).name = c_str(script_name);
let ret_code = nasl_sys::exec_nasl_script(script_infos, nasl_sys::NASL_COMMAND_LINE);
if ret_code != 0 {
error!("exec_nasl_script ret code: {:?}", ret_code);
return Err(());
}
}
Ok(())
}
}
pub struct Host {
inner: *mut nasl_sys::gvm_host_t
}
impl Host {
pub fn get_in6_addr(&self) -> libc::in6_addr {
unsafe {
let mut ip6: libc::in6_addr = mem::zeroed();
nasl_sys::gvm_host_get_addr6(self.inner, &mut ip6);
ip6
}
}
}
pub unsafe fn get_hosts(target: &str) -> Vec<Host> {
let hosts = nasl_sys::gvm_hosts_new(c_str(target));
nasl_sys::gvm_hosts_resolve(hosts);
let mut hosts2 = Vec::new();
loop {
let host = nasl_sys::gvm_hosts_next (hosts);
if host.is_null() {
break;
}
hosts2.push( Host { inner: host as _ });
}
hosts2
}
// set_kb_item(name:"Settings/disable_cgi_scanning", value:FALSE);
// set_kb_item(name:"Services/www", value:80);
// set_kb_item(name:"Host/scanned", value:TRUE);
// set_kb_item(name:"Ports/tcp/80", value:TRUE);
// set_kb_item(name:"Transports/TCP/80", value:TRUE);
fn boot() {
use clap::{ Arg, App };
let matches = App::new("NASL Interpreter")
.version("5.06")
.author("Luozijun <luozijun.assistant@gmail.com>")
.about("Does awesome things")
.arg(
Arg::with_name("include_dir")
.short("i")
.long("include_dir")
.help("Sets a custom config file")
.required(true)
.takes_value(true)
)
.arg(
Arg::with_name("mode")
.short("m")
.long("mode")
.possible_values(&["exec", "parse", "descr"])
.required(true)
.help("Sets a custom config file")
.takes_value(true)
)
.arg(
Arg::with_name("FILENAME")
.help("Sets the input file to use")
.required(true)
)
.arg(
Arg::with_name("TARGET")
.help("Sets the input file to use")
.required(true)
)
.get_matches();
let include_dir = matches.value_of("include_dir").unwrap_or("./");
let mode = {
let m = matches.value_of("mode").unwrap();
if m == "exec" {
0 | nasl_sys::NASL_COMMAND_LINE
} else if m == "parse" {
0 | nasl_sys::NASL_EXEC_PARSE_ONLY
} else if m == "descr" {
0 | nasl_sys::NASL_EXEC_DESCR
} else {
unreachable!();
}
};
let filename = matches.value_of("FILENAME").unwrap();
let target = {
let target_str = matches.value_of("TARGET").unwrap();
match target_str.parse::<IpAddr>() {
Ok(ip_addr) => ip_addr,
Err(e) => {
error!("{:?}", e);
return ();
}
}
};
let vm = Vm::new().unwrap();
vm.add_include_dir(include_dir).unwrap();
vm.add_include_dir("./").unwrap();
vm.add_include_dir("./nasl_scripts").unwrap();
info!("nasl version: {:?}", vm.version());
info!("Exec description ...");
vm.description(filename).unwrap();
info!("Attack ...");
vm.attack(&target, filename).unwrap();
}
fn main() {
env::set_var("RUST_LOG", "info");
env_logger::init();
boot();
}
|
#[doc = "Reader of register I2C_BUFOUT"]
pub type R = crate::R<u32, super::I2C_BUFOUT>;
#[doc = "Writer for register I2C_BUFOUT"]
pub type W = crate::W<u32, super::I2C_BUFOUT>;
#[doc = "Register I2C_BUFOUT `reset()`'s with value 0"]
impl crate::ResetValue for super::I2C_BUFOUT {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `I2C4SCL`"]
pub type I2C4SCL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `I2C4SCL`"]
pub struct I2C4SCL_W<'a> {
w: &'a mut W,
}
impl<'a> I2C4SCL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `I2C4SDA`"]
pub type I2C4SDA_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `I2C4SDA`"]
pub struct I2C4SDA_W<'a> {
w: &'a mut W,
}
impl<'a> I2C4SDA_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
impl R {
#[doc = "Bit 0 - I2C4SCL"]
#[inline(always)]
pub fn i2c4scl(&self) -> I2C4SCL_R {
I2C4SCL_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - I2C4SDA"]
#[inline(always)]
pub fn i2c4sda(&self) -> I2C4SDA_R {
I2C4SDA_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - I2C4SCL"]
#[inline(always)]
pub fn i2c4scl(&mut self) -> I2C4SCL_W {
I2C4SCL_W { w: self }
}
#[doc = "Bit 1 - I2C4SDA"]
#[inline(always)]
pub fn i2c4sda(&mut self) -> I2C4SDA_W {
I2C4SDA_W { w: self }
}
}
|
extern crate tree_index as tree;
use tree::{Change, TreeIndex, Verification};
#[test]
fn set_and_get() {
let mut index = TreeIndex::default();
assert_eq!(index.get(0), false);
assert_eq!(index.set(0), Change::Changed);
assert_eq!(index.get(0), true);
assert_eq!(index.set(0), Change::Unchanged);
assert_eq!(index.set(2), Change::Changed);
assert_eq!(index.get(2), true);
assert_eq!(index.get(1), true, "parent of 0 and 2 is set");
let mut index = TreeIndex::default();
for i in (0..32).step_by(2) {
index.set(i);
}
assert_eq!(index.get(7), true);
assert_eq!(index.get(23), true);
assert_eq!(index.get(15), true);
}
#[test]
fn digest() {
let mut index;
index = TreeIndex::default();
assert_eq!(index.digest(0), 0b0, "has nothing");
index = TreeIndex::default();
index.set(0);
assert_eq!(index.digest(0), 0b1, "has all");
index = TreeIndex::default();
index.set(1);
assert_eq!(index.digest(0), 0b101, "rooted, no sibling, no parent");
index = TreeIndex::default();
index.set(2);
assert_eq!(index.digest(0), 0b10, "not rooted, has sibling");
index = TreeIndex::default();
index.set(1);
index.set(2);
assert_eq!(index.digest(0), 0b1, "has all");
index = TreeIndex::default();
index.set(3);
index.set(2);
let left = index.digest(0);
let right = 0b1011;
assert_eq!(left, right, "rooted, sibling, no uncle, grand parents");
index = TreeIndex::default();
index.set(5);
assert_eq!(index.digest(1), 0b10, "not rooted, has sibling");
}
#[test]
fn verified_by() {
let mut index = TreeIndex::default();
verify(&mut index, 0, 0, 0);
index.set(0);
verify(&mut index, 0, 2, 0);
index.set(2);
verify(&mut index, 0, 4, 4);
index.set(5);
verify(&mut index, 0, 8, 8);
index.set(8);
verify(&mut index, 0, 10, 8);
let mut index = TreeIndex::default();
index.set(10);
index.set(8);
index.set(13);
index.set(3);
index.set(17);
verify(&mut index, 10, 20, 20);
let mut index = TreeIndex::default();
index.set(7);
index.set(16);
index.set(18);
index.set(21);
index.set(25);
index.set(28);
verify(&mut index, 16, 30, 28);
verify(&mut index, 18, 30, 28);
verify(&mut index, 17, 30, 28);
fn verify(tree: &mut TreeIndex, index: u64, node: u64, top: u64) {
assert_eq!(tree.verified_by(index), Verification { node, top });
}
}
#[test]
fn proof_without_a_digest_1() {
let mut index = TreeIndex::default();
{
let mut nodes = vec![];
let proof = index.proof(0, false, &mut nodes, &mut TreeIndex::default());
assert_eq!(proof, None);
}
{
index.set(0);
let mut nodes = vec![];
let proof = index
.proof(0, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![].as_slice());
assert_eq!(proof.verified_by(), 2);
}
{
index.set(2);
let mut nodes = vec![];
let proof = index
.proof(0, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![2].as_slice());
assert_eq!(proof.verified_by(), 4);
}
{
index.set(5);
let mut nodes = vec![];
let proof = index
.proof(0, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![2, 5].as_slice());
assert_eq!(proof.verified_by(), 8);
}
{
index.set(8);
let mut nodes = vec![];
let proof = index
.proof(0, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![2, 5, 8].as_slice());
assert_eq!(proof.verified_by(), 10);
}
}
#[test]
fn proof_without_a_digest_2() {
let mut index = TreeIndex::default();
index.set(10);
index.set(8);
index.set(13);
index.set(3);
index.set(17);
let mut nodes = vec![];
let proof = index
.proof(10, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![8, 13, 3, 17].as_slice());
assert_eq!(proof.verified_by(), 20);
}
#[test]
fn proof_without_a_digest_3() {
let mut index = TreeIndex::default();
index.set(7);
index.set(16);
index.set(18);
index.set(21);
index.set(25);
index.set(28);
{
let mut nodes = vec![];
let proof = index
.proof(16, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![18, 21, 7, 25, 28].as_slice());
assert_eq!(proof.verified_by(), 30);
}
{
let mut nodes = vec![];
let proof = index
.proof(18, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![16, 21, 7, 25, 28].as_slice());
assert_eq!(proof.verified_by(), 30);
}
{
let mut nodes = vec![];
let proof = index
.proof(17, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![21, 7, 25, 28].as_slice());
assert_eq!(proof.verified_by(), 30);
}
}
#[test]
fn proof_with_a_digest_1() {
let mut index = TreeIndex::default();
{
let mut nodes = vec![];
let proof = index.proof(0, false, &mut nodes, &mut TreeIndex::default());
assert!(proof.is_none());
}
index.set(0);
index.set(2);
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(0, 0b1, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![].as_slice());
assert_eq!(proof.verified_by(), 0);
}
index.set(5);
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(0, 0b10, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![5].as_slice());
assert_eq!(proof.verified_by(), 8);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(0, 0b110, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![].as_slice());
assert_eq!(proof.verified_by(), 8);
}
index.set(8);
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(0, 0b101, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![2].as_slice());
assert_eq!(proof.verified_by(), 0);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(0, 0b10, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![5, 8].as_slice());
assert_eq!(proof.verified_by(), 10);
}
}
#[test]
fn proof_with_a_digest_2() {
let mut index = TreeIndex::default();
index.set(10);
index.set(8);
index.set(13);
index.set(3);
index.set(17);
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(
10,
0b1000001,
false,
&mut nodes,
&mut TreeIndex::default(),
)
.unwrap();
assert_eq!(proof.nodes(), vec![8, 13, 3, 17].as_slice());
assert_eq!(proof.verified_by(), 20);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(
10,
0b10001,
false,
&mut nodes,
&mut TreeIndex::default(),
)
.unwrap();
assert_eq!(proof.nodes(), vec![8, 13, 3].as_slice());
assert_eq!(proof.verified_by(), 0);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(
10,
0b1001,
false,
&mut nodes,
&mut TreeIndex::default(),
)
.unwrap();
assert_eq!(proof.nodes(), vec![8, 13].as_slice());
assert_eq!(proof.verified_by(), 0);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(
10,
0b1000,
false,
&mut nodes,
&mut TreeIndex::default(),
)
.unwrap();
assert_eq!(proof.nodes(), vec![8, 13, 17].as_slice());
assert_eq!(proof.verified_by(), 20);
}
}
#[test]
fn proof_with_a_digest_3() {
let mut index = TreeIndex::default();
index.set(7);
index.set(16);
index.set(18);
index.set(21);
index.set(25);
index.set(28);
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(16, 0b1, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![].as_slice());
assert_eq!(proof.verified_by(), 0);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(
18,
0b100,
false,
&mut nodes,
&mut TreeIndex::default(),
)
.unwrap();
assert_eq!(proof.nodes(), vec![16, 7, 25, 28].as_slice());
assert_eq!(proof.verified_by(), 30);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(18, 0b10, false, &mut nodes, &mut TreeIndex::default())
.unwrap();
assert_eq!(proof.nodes(), vec![21, 7, 25, 28].as_slice());
assert_eq!(proof.verified_by(), 30);
}
{
let mut nodes = vec![];
let proof = index
.proof_with_digest(
17,
0b101,
false,
&mut nodes,
&mut TreeIndex::default(),
)
.unwrap();
assert_eq!(proof.nodes(), vec![21].as_slice());
assert_eq!(proof.verified_by(), 0);
}
}
// Test things don't crash.
#[test]
fn digest_sanity_checks() {
let mut tree = TreeIndex::default();
tree.set(0);
let index = 0;
let mut nodes = vec![];
let mut remote_tree = TreeIndex::default();
let digest = 999_999_999_999_999;
tree.proof_with_digest(index, digest, false, &mut nodes, &mut remote_tree);
}
|
mod git_monitor;
use tauri::Manager;
#[derive(Clone, serde::Serialize)]
struct Payload {
message: String,
}
fn print_type_of<T>(_: &T) {
println!("{}", std::any::type_name::<T>())
}
fn main() {
tauri::Builder::default().setup(|app| {
println!("Is this working ?");
//example of communicating
let id = app.listen_global("click", |event| {
println!("got event-name with payload {:?}", event.payload());
});
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
|
use byteorder::{ByteOrder, LittleEndian};
use leb128;
mod name_section;
#[derive(Debug, Clone)]
pub struct FuncType {
pub params: Vec<u8>,
pub results: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct FuncExport {
pub name: String,
pub func: Func,
}
#[derive(PartialEq, Clone)]
pub enum ExportType {
Func,
Mem,
Global,
}
#[derive(PartialEq, Clone)]
pub enum ImportType {
Func,
}
#[derive(Debug, Clone)]
pub struct FuncCode {
pub opcode: u8,
pub immediates: Vec<Imm>,
pub return_type: Option<u8>,
}
#[derive(Debug, Clone, Copy)]
pub enum Imm {
// Some intruction have reserved bytes, which must be a single 0 byte.
// Using a long leb128 encoding of 0 is not valid
RESERVED,
I64(i64),
I32(i32),
F64(f64),
}
impl From<i64> for Imm {
#[inline]
fn from(v: i64) -> Self {
Imm::I64(v)
}
}
impl FuncCode {
pub fn new0(opcode: u8) -> FuncCode {
FuncCode {
opcode,
immediates: vec![],
return_type: None,
}
}
pub fn new_control(opcode: u8, rt: u8) -> FuncCode {
FuncCode {
opcode,
immediates: vec![],
return_type: Some(rt),
}
}
pub fn new1(opcode: u8, imm: Imm) -> FuncCode {
FuncCode {
opcode,
immediates: vec![imm],
return_type: None,
}
}
pub fn new2(opcode: u8, imm1: Imm, imm2: Imm) -> FuncCode {
FuncCode {
opcode,
immediates: vec![imm1, imm2],
return_type: None,
}
}
}
#[derive(Debug, Clone)]
pub struct Element {
pub table: u32,
pub offset: u32,
pub funcs: Vec<u32>,
}
#[derive(Debug, Clone)]
pub struct Table {
pub elemtype: TableElemType,
pub limits: (u32, u32), // (min, max)
}
#[derive(Debug, Clone, Copy)]
pub enum TableElemType {
Funcref = 0x70,
}
#[derive(Debug, Clone)]
pub struct Func {
pub sig: FuncType,
pub locals: Vec<FuncLocal>,
pub code: Vec<FuncCode>,
}
type Export = (String, usize, ExportType);
type Import = (String, String, ImportType, usize);
type Global = (u8, u8, u32); // (type, mutability, init)
type FuncLocal = (usize, u8);
pub const HEADER_MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6D];
pub const HEADER_VERSION: [u8; 4] = [0x01, 0x00, 0x00, 0x00];
pub const CUSTOM_SECTION: u8 = 0;
pub const TYPE_SECTION: u8 = 1;
pub const IMPORT_SECTION: u8 = 2;
pub const FUNCTION_SECTION: u8 = 3;
pub const TABLE_SECTION: u8 = 4;
pub const MEMORY_SECTION: u8 = 5;
pub const GLOBAL_SECTION: u8 = 6;
pub const EXPORT_SECTION: u8 = 7;
pub const START_SECTION: u8 = 8;
pub const ELEMENT_SECTION: u8 = 9;
pub const CODE_SECTION: u8 = 10;
pub const DATA_SECTION: u8 = 11;
pub const UNREACHABLE: u8 = 0x00;
pub const NONE: u8 = 0x40;
pub const I32: u8 = 0x7F;
pub const I64: u8 = 0x7E;
pub const F32: u8 = 0x7D;
pub const F64: u8 = 0x7C;
pub const I32_CONST: u8 = 0x41;
pub const I64_CONST: u8 = 0x42;
pub const F32_CONST: u8 = 0x43;
pub const F64_CONST: u8 = 0x44;
pub const I32_EQZ: u8 = 0x45;
pub const I32_EQ: u8 = 0x46;
pub const I32_NE: u8 = 0x47;
pub const I32_AND: u8 = 0x71;
pub const I32_OR: u8 = 0x72;
pub const I32_SHL: u8 = 0x74;
pub const I32_SHR_U: u8 = 0x76;
pub const I32_LT_S: u8 = 0x48;
pub const I32_LT_U: u8 = 0x49;
pub const I32_GT_S: u8 = 0x4A;
pub const I32_GT_U: u8 = 0x4B;
pub const I32_LE_S: u8 = 0x4C;
pub const I32_LE_U: u8 = 0x4D;
pub const I32_GE_S: u8 = 0x4E;
pub const I32_ADD: u8 = 0x6A;
pub const I32_SUB: u8 = 0x6B;
pub const I32_MUL: u8 = 0x6C;
pub const I32_DIV_S: u8 = 0x6D;
pub const I32_REM_S: u8 = 0x6F;
pub const F32_DIV: u8 = 0x95;
pub const F64_ADD: u8 = 0xA0;
pub const F64_SUB: u8 = 0xA1;
pub const F64_MUL: u8 = 0xA2;
pub const F64_DIV: u8 = 0xA3;
pub const F64_LE: u8 = 0x65;
pub const F64_GE: u8 = 0x66;
pub const I32_TRUNC_F32_S: u8 = 0xA8;
pub const I32_TRUNC_F64_S: u8 = 0xAA;
pub const F64_CONVERT_I32_S: u8 = 0xB7;
pub const DROP: u8 = 0x1A;
pub const LOCAL_GET: u8 = 0x20;
pub const LOCAL_SET: u8 = 0x21;
pub const LOCAL_TEE: u8 = 0x22;
pub const GLOBAL_GET: u8 = 0x23;
pub const GLOBAL_SET: u8 = 0x24;
pub const I32_LOAD: u8 = 0x28;
pub const I32_LOAD8_U: u8 = 0x2D;
pub const I32_STORE: u8 = 0x36;
pub const I32_STORE8: u8 = 0x3A;
pub const BLOCK: u8 = 0x02;
pub const LOOP: u8 = 0x03;
pub const IF: u8 = 0x04;
pub const ELSE: u8 = 0x05;
pub const BR: u8 = 0x0C;
pub const BR_IF: u8 = 0x0D;
pub const END: u8 = 0x0B;
pub const RETURN: u8 = 0x0F;
pub const CALL: u8 = 0x10;
pub const CALL_INDIRECT: u8 = 0x11;
pub struct WasmCodeGen {
funcs: Vec<(usize, Func)>,
types: Vec<FuncType>,
exports: Vec<Export>,
elements: Vec<Element>,
tables: Vec<Table>,
memories: Vec<(u32, u32)>,
data: Vec<(u32, Vec<u8>)>, // (offset, bytes)
imports: Vec<Import>,
globals: Vec<Global>,
/// Custom name section for funcs
func_names: Vec<name_section::Naming>,
}
fn write_name(bytes: &mut Vec<u8>, name: String) {
write_unsigned_leb128(bytes, name.len() as u64);
// TODO(sven): is this UTF8?
bytes.extend(name.into_bytes());
}
fn write_unsigned_leb128(bytes: &mut Vec<u8>, n: u64) {
leb128::write::unsigned(bytes, n).expect("could not write LEB128");
}
fn write_signed_leb128(bytes: &mut Vec<u8>, n: i64) {
leb128::write::signed(bytes, n).expect("could not write LEB128");
}
fn write_float(bytes: &mut Vec<u8>, n: f64) {
let mut b = [0; 8];
LittleEndian::write_f64(&mut b, n);
bytes.extend(b.iter())
}
fn write_unsigned_leb128_at_offset(bytes: &mut Vec<u8>, offset: usize, n: usize) {
// remove placeholder
bytes.remove(offset);
let mut buffer = vec![];
leb128::write::unsigned(&mut buffer, n as u64).expect("could not write LEB128");
let mut i = 0;
for byte in buffer {
bytes.insert(offset + i, byte);
i += 1;
}
}
fn write_vec_len<T>(bytes: &mut Vec<u8>, vec: &Vec<T>) {
write_unsigned_leb128(bytes, vec.len() as u64);
}
fn write_type_section(bytes: &mut Vec<u8>, types: &Vec<FuncType>) {
write_vec_len(bytes, types); // vec length
for functype in types {
bytes.push(0x60); // functype
write_vec_len(bytes, &functype.params); // vec length
for b in &functype.params {
bytes.push(*b);
}
write_vec_len(bytes, &functype.results); // vec length
for b in &functype.results {
bytes.push(*b);
}
}
}
fn write_func_section(bytes: &mut Vec<u8>, funcs: &Vec<(usize, Func)>) {
write_vec_len(bytes, funcs); // vec length
for func in funcs {
write_unsigned_leb128(bytes, func.0 as u64);
}
}
fn write_element_section(bytes: &mut Vec<u8>, elements: &Vec<Element>) {
write_vec_len(bytes, elements); // vec length
for element in elements {
write_unsigned_leb128(bytes, element.table as u64);
let offset_expr = vec![FuncCode::new1(I32_CONST, Imm::I64(element.offset as i64))];
write_code_expr(bytes, &offset_expr);
write_vec_len(bytes, &element.funcs); // vec length
for func in &element.funcs {
write_unsigned_leb128(bytes, func.clone() as u64);
}
}
}
fn write_table_section(bytes: &mut Vec<u8>, tables: &Vec<Table>) {
write_vec_len(bytes, tables); // vec length
for table in tables {
bytes.push(table.elemtype as u8);
let (min, max) = table.limits;
bytes.push(0x01);
write_unsigned_leb128(bytes, min as u64);
write_unsigned_leb128(bytes, max as u64);
}
}
fn write_imports_section(bytes: &mut Vec<u8>, imports: &Vec<Import>) {
write_vec_len(bytes, imports); // vec length
for import in imports {
write_name(bytes, import.0.clone());
write_name(bytes, import.1.clone());
match import.2 {
ImportType::Func => bytes.push(0x0),
}
write_unsigned_leb128(bytes, import.3 as u64);
}
}
fn write_code_local(bytes: &mut Vec<u8>, locals: &Vec<FuncLocal>) {
write_vec_len(bytes, locals); // vec length
for local in locals {
write_unsigned_leb128(bytes, local.0 as u64);
bytes.push(local.1);
}
}
fn write_code_expr(bytes: &mut Vec<u8>, codes: &Vec<FuncCode>) {
for code in codes {
bytes.push(code.opcode);
if let Some(rt) = code.return_type {
write_unsigned_leb128(bytes, rt as u64);
}
for imm in &code.immediates {
match imm {
Imm::I64(n) => write_signed_leb128(bytes, *n),
Imm::I32(n) => write_signed_leb128(bytes, *n as i64),
Imm::F64(f) => write_float(bytes, *f),
Imm::RESERVED => bytes.push(0x0),
};
}
}
bytes.push(END); // end
}
fn write_code_section(bytes: &mut Vec<u8>, funcs: &Vec<(usize, Func)>) {
write_vec_len(bytes, funcs); // vec length
for func in funcs {
let before_offset = bytes.len();
bytes.push(0x0); // func size
write_code_local(bytes, &func.1.locals);
write_code_expr(bytes, &func.1.code);
let after_offset = bytes.len();
// func size fixup
let func_len = after_offset - before_offset - 1;
write_unsigned_leb128_at_offset(bytes, before_offset, func_len);
}
}
fn write_data_section(bytes: &mut Vec<u8>, datum: &Vec<(u32, Vec<u8>)>) {
write_vec_len(bytes, datum); // vec length
for data in datum {
bytes.push(0x0); // memidx
bytes.push(I32_CONST);
write_signed_leb128(bytes, data.0 as i64); // offset
bytes.push(END);
write_vec_len(bytes, &data.1); // vec length
for b in &data.1 {
bytes.push(*b);
}
}
}
fn write_custom_name_section(bytes: &mut Vec<u8>, names: &Vec<name_section::Naming>) {
write_name(bytes, "name".to_string());
// Assigns names to functions
name_section::write_var_uint7(1, bytes);
// need to store the current office to fixup later
let name_payload_len_offset = bytes.len();
// push 0 for now
bytes.push(0);
name_section::write_var_uint32(names.len() as u32, bytes);
for name in names {
name_section::write_var_uint32(name.index as u32, bytes);
name_section::write_var_uint32(name.name.len() as u32, bytes);
bytes.extend_from_slice(&name.name.as_bytes())
}
let after_offset = bytes.len();
let section_len = after_offset - name_payload_len_offset - 1;
// fixup section len
write_unsigned_leb128_at_offset(bytes, name_payload_len_offset, section_len);
}
pub fn write_custom_section(bytes: &mut Vec<u8>, name: &str, content: &[u8]) {
bytes.push(0); // section type: custom
let start = bytes.len();
// 0 size for now, we'll fix once we know the exact size
bytes.push(0);
write_name(bytes, name.to_owned());
bytes.extend_from_slice(content);
let after_offset = bytes.len();
let section_len = after_offset - start - 1;
// fixup section len
write_unsigned_leb128_at_offset(bytes, start, section_len);
}
fn write_export_section(bytes: &mut Vec<u8>, exports: &Vec<Export>) {
write_vec_len(bytes, exports); // vec length
for export in exports {
let (name, idx, export_type) = export;
write_name(bytes, name.clone());
match *export_type {
ExportType::Func => bytes.push(0x0),
ExportType::Mem => bytes.push(0x2),
ExportType::Global => bytes.push(0x3),
}
write_unsigned_leb128(bytes, *idx as u64);
}
}
fn write_memory_section(bytes: &mut Vec<u8>, memories: &Vec<(u32, u32)>) {
write_vec_len(bytes, memories); // vec length
for mem in memories {
let (min, max) = mem;
bytes.push(0x01);
write_unsigned_leb128(bytes, *min as u64);
write_unsigned_leb128(bytes, *max as u64);
}
}
fn write_global_section(bytes: &mut Vec<u8>, globals: &Vec<Global>) {
write_vec_len(bytes, globals); // vec length
for data in globals {
let (t, mutability, init) = data;
bytes.push(*t);
bytes.push(*mutability);
let expr = vec![FuncCode::new1(I32_CONST, Imm::I64(*init as i64))];
write_code_expr(bytes, &expr);
}
}
macro_rules! write_section {
($b: expr, $o:expr, $id:expr, $write_fn:expr) => {
if $o.len() > 0 {
$b.push($id); // section id
let before_offset = $b.len();
$b.push(0x0); // section bytes
$write_fn(&mut $b, &$o);
let after_offset = $b.len();
// section fixup
let section_len = after_offset - before_offset - 1;
// section length - fixup
write_unsigned_leb128_at_offset(&mut $b, before_offset, section_len);
}
};
}
impl WasmCodeGen {
pub fn new() -> WasmCodeGen {
WasmCodeGen {
types: vec![],
funcs: vec![],
tables: vec![],
exports: vec![],
elements: vec![],
memories: vec![],
data: vec![],
imports: vec![],
globals: vec![],
func_names: vec![],
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = vec![];
bytes.extend(&HEADER_MAGIC);
bytes.extend(&HEADER_VERSION);
write_section!(bytes, self.types, TYPE_SECTION, write_type_section);
write_section!(bytes, self.imports, IMPORT_SECTION, write_imports_section);
write_section!(bytes, self.funcs, FUNCTION_SECTION, write_func_section);
write_section!(bytes, self.tables, TABLE_SECTION, write_table_section);
write_section!(bytes, self.memories, MEMORY_SECTION, write_memory_section);
write_section!(bytes, self.globals, GLOBAL_SECTION, write_global_section);
write_section!(bytes, self.exports, EXPORT_SECTION, write_export_section);
write_section!(bytes, self.elements, ELEMENT_SECTION, write_element_section);
write_section!(bytes, self.funcs, CODE_SECTION, write_code_section);
write_section!(bytes, self.data, DATA_SECTION, write_data_section);
write_section!(
bytes,
self.func_names,
CUSTOM_SECTION,
write_custom_name_section
);
bytes
}
pub fn set_name(&mut self, idx: usize, name: String) {
self.func_names.push(name_section::Naming {
index: idx as u32,
name,
});
}
pub fn add_type(&mut self, t: FuncType) -> usize {
let idx = self.types.len();
self.types.push(t);
idx
}
pub fn add_export(&mut self, name: String, idx: usize, export_type: ExportType) {
self.exports.push((name, idx, export_type));
}
pub fn add_func(&mut self, f: Func) -> usize {
let funcidx = self.funcs.len() + self.imports.len();
self.funcs.push((self.types.len(), f.clone()));
self.add_type(f.sig);
funcidx
}
pub fn add_func_with_type(&mut self, f: Func, t: u32) -> usize {
let funcidx = self.funcs.len() + self.imports.len();
self.funcs.push((t as usize, f.clone()));
funcidx
}
pub fn replace_code_func(&mut self, idx: usize, code: Vec<FuncCode>) {
// we don't store the imports in the funcs map and the result of add_func includes it, so remove them.
let idx = idx - self.imports.len();
let (type_idx, old_func) = self.funcs[idx].clone();
let new_func = Func {
sig: old_func.sig,
locals: old_func.locals,
code,
};
self.funcs[idx] = (type_idx, new_func);
}
pub fn add_table(&mut self, elemtype: TableElemType, min: u32, max: u32) -> usize {
let idx = self.tables.len();
self.tables.push(Table {
elemtype,
limits: (min, max),
});
idx
}
pub fn add_element(&mut self, table: u32, offset: u32, funcs: Vec<u32>) -> usize {
let idx = self.elements.len();
self.elements.push(Element {
table,
offset,
funcs,
});
idx
}
pub fn add_memory(&mut self, min: u32, max: u32) -> usize {
assert!(self.memories.len() == 0);
self.memories.push((min, max));
0
}
pub fn add_data(&mut self, offset: u32, bytes: Vec<u8>) -> u32 {
self.data.push((offset, bytes.clone()));
bytes.len() as u32
}
pub fn add_import(
&mut self,
module: String,
name: String,
import_type: ImportType,
typeidx: usize,
) -> usize {
let importidex = self.imports.len();
self.imports.push((module, name, import_type, typeidx));
importidex
}
pub fn add_mutable_global(&mut self, valtype: u8, init: u32) -> usize {
let idx = self.globals.len();
self.globals.push((valtype, 0x01, init));
idx
}
}
|
use super::base_helper::{to_utf16, from_utf16};
use super::high_dpi;
use winapi::shared::windef::{HFONT, HWND, HMENU};
use winapi::shared::minwindef::{UINT, WPARAM, LPARAM, LRESULT};
use winapi::um::winuser::WM_USER;
use winapi::ctypes::c_int;
use std::{ptr, mem};
#[cfg(feature = "rich-textbox")]
use winapi::um::winuser::WNDCLASSEXW;
pub const NOTICE_MESSAGE: UINT = WM_USER+100;
pub const NWG_INIT: UINT = WM_USER + 101;
pub const NWG_TRAY: UINT = WM_USER + 102;
pub const NWG_TIMER_TICK: UINT = WM_USER + 103;
pub const NWG_TIMER_STOP: UINT = WM_USER + 104;
/// Returns the class info of a hwnd handle
#[cfg(feature = "rich-textbox")]
pub fn get_class_info(hwnd: HWND) -> Result<WNDCLASSEXW, ()> {
use winapi::um::winuser::{GetClassInfoExW, GetClassNameW};
use winapi::um::libloaderapi::GetModuleHandleW;
use winapi::shared::ntdef::WCHAR;
unsafe {
let mut info: WNDCLASSEXW = mem::zeroed();
let hinst = GetModuleHandleW(ptr::null_mut());
let mut class_name_raw: [WCHAR; 100] = [0; 100];
let count = GetClassNameW(hwnd, class_name_raw.as_mut_ptr(), 100) as usize;
if count == 0 {
return Err(());
}
let result = GetClassInfoExW(hinst, class_name_raw.as_ptr(), &mut info);
match result == 0 {
true => Err(()),
false => Ok(info)
}
}
}
/// Reeturn the background color of a window
#[cfg(feature = "rich-textbox")]
pub fn get_background_color(hwnd: HWND) -> Result<[u8; 3], ()> {
use winapi::um::winuser::GetSysColorBrush;
use winapi::um::wingdi::{GetRValue, GetGValue, GetBValue, LOGBRUSH, GetObjectW, GetStockObject};
match get_class_info(hwnd) {
Ok(info) => unsafe {
let brush = {
let stock_handle = info.hbrBackground as usize as i32;
let stock = GetStockObject(info.hbrBackground as usize as i32);
match stock.is_null() {
true => info.hbrBackground,
false => if stock_handle > 0 {
// Windows use (stock handle - 1) for the real background color ¯\_(ツ)_/¯
GetSysColorBrush(stock_handle - 1)
} else {
GetSysColorBrush(0)
}
}
};
let mut brush_data: LOGBRUSH = mem::zeroed();
GetObjectW(brush as _, mem::size_of::<LOGBRUSH>() as _, &mut brush_data as *mut LOGBRUSH as _);
let col = brush_data.lbColor;
Ok([GetRValue(col), GetGValue(col), GetBValue(col)])
},
Err(_) => Err(())
}
}
/// Haha you maybe though that destroying windows would be easy right? WRONG.
/// The window children must first be destroyed otherwise `DestroyWindow` will free them and the associated rust value will be ~CORRUPTED~
pub fn destroy_window(hwnd: HWND) {
use winapi::um::winuser::{SetParent, DestroyWindow};
// Remove the children from the window
iterate_window_children(hwnd, |child| {
unsafe {
set_window_visibility(child, false);
SetParent(child, ptr::null_mut());
}
});
unsafe { DestroyWindow(hwnd); }
}
pub fn destroy_menu_item(parent: HMENU, item_id: u32) {
use winapi::um::winuser::{DeleteMenu, GetMenuItemCount, GetMenuItemID, MF_BYPOSITION};
unsafe {
let count = GetMenuItemCount(parent);
let mut index = 0;
while index < count {
let id = GetMenuItemID(parent, index);
match id == item_id {
true => {
DeleteMenu(parent, index as u32, MF_BYPOSITION);
index = count;
},
false => {
index += 1;
}
}
}
}
}
pub fn destroy_menu(menu: HMENU) {
use winapi::um::winuser::DestroyMenu;
unsafe { DestroyMenu(menu); }
}
/// Execute the callback for each first level children of the window
pub fn iterate_window_children<F>(hwnd_parent: HWND, cb: F)
where F: FnMut(HWND) -> ()
{
use winapi::um::winuser::EnumChildWindows;
use winapi::shared::minwindef::BOOL;
struct EnumChildData<F> {
parent: HWND,
callback: F,
}
unsafe extern "system" fn enum_child<F>(hwnd: HWND, p: LPARAM) -> BOOL
where F: FnMut(HWND) -> ()
{
// Only iterate over the top level children
let enum_data_ptr = p as *mut EnumChildData<F>;
let enum_data = &mut *enum_data_ptr;
if get_window_parent(hwnd) == enum_data.parent {
(enum_data.callback)(hwnd);
};
1
}
unsafe {
let mut data = EnumChildData {
parent: hwnd_parent,
callback: cb
};
EnumChildWindows(hwnd_parent, Some(enum_child::<F>), &mut data as *mut EnumChildData<F> as _);
}
}
#[cfg(any(feature="timer", feature="animation-timer", feature="notice"))]
pub fn window_valid(hwnd: HWND) -> bool {
use winapi::um::winuser::IsWindow;
unsafe {
IsWindow(hwnd) != 0
}
}
pub fn get_window_parent(hwnd: HWND) -> HWND {
use winapi::um::winuser::GetParent;
unsafe { GetParent(hwnd) }
}
pub fn get_window_font(handle: HWND) -> HFONT {
use winapi::um::winuser::{ WM_GETFONT };
unsafe {
let h = send_message(handle, WM_GETFONT, 0, 0);
mem::transmute(h)
}
}
pub fn maximize_window(handle: HWND) {
use winapi::um::winuser::{ShowWindow, SW_MAXIMIZE};
unsafe {
ShowWindow(handle, SW_MAXIMIZE);
}
}
pub fn minimize_window(handle: HWND) {
use winapi::um::winuser::{ShowWindow, SW_MINIMIZE};
unsafe {
ShowWindow(handle, SW_MINIMIZE);
}
}
pub fn restore_window(handle: HWND) {
use winapi::um::winuser::{ShowWindow, SW_RESTORE};
unsafe {
ShowWindow(handle, SW_RESTORE);
}
}
/// Set the font of a window
pub unsafe fn set_window_font(handle: HWND, font_handle: Option<HFONT>, redraw: bool) {
use winapi::um::winuser::WM_SETFONT;
use winapi::um::winuser::SendMessageW;
let font_handle = font_handle.unwrap_or(ptr::null_mut());
SendMessageW(handle, WM_SETFONT, mem::transmute(font_handle), redraw as LPARAM);
}
#[cfg(feature = "timer")]
pub fn kill_timer(hwnd: HWND, id: u32) {
use winapi::um::winuser::KillTimer;
use winapi::shared::basetsd::UINT_PTR;
unsafe {
KillTimer(hwnd, id as UINT_PTR);
}
}
#[cfg(feature = "timer")]
pub fn start_timer(hwnd: HWND, id: u32, interval: u32) {
use winapi::um::winuser::SetTimer;
use winapi::shared::basetsd::UINT_PTR;
unsafe {
SetTimer(hwnd, id as UINT_PTR, interval, None);
}
}
pub fn get_style(handle: HWND) -> UINT {
use ::winapi::um::winuser::GWL_STYLE;
get_window_long(handle, GWL_STYLE) as UINT
}
#[cfg(any(feature = "list-view", feature = "progress-bar"))]
pub fn set_style(handle: HWND, style: u32) {
use ::winapi::um::winuser::GWL_STYLE;
set_window_long(handle, GWL_STYLE, style as usize);
}
pub fn send_message(hwnd: HWND, msg: UINT, w: WPARAM, l: LPARAM) -> LRESULT {
unsafe { ::winapi::um::winuser::SendMessageW(hwnd, msg, w, l) }
}
pub fn post_message(hwnd: HWND, msg: UINT, w: WPARAM, l: LPARAM) {
unsafe { ::winapi::um::winuser::PostMessageW(hwnd, msg, w, l) };
}
pub unsafe fn set_focus(handle: HWND) {
::winapi::um::winuser::SetFocus(handle);
}
pub unsafe fn get_focus(handle: HWND) -> bool {
::winapi::um::winuser::GetFocus() == handle
}
pub unsafe fn get_window_text(handle: HWND) -> String {
use winapi::um::winuser::{GetWindowTextW, GetWindowTextLengthW};
let buffer_size = GetWindowTextLengthW(handle) as usize + 1;
if buffer_size == 0 { return String::new(); }
let mut buffer: Vec<u16> = vec![0; buffer_size];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as c_int) == 0 {
String::new()
} else {
from_utf16(&buffer[..])
}
}
pub unsafe fn set_window_text<'a>(handle: HWND, text: &'a str) {
use winapi::um::winuser::SetWindowTextW;
let text = to_utf16(text);
SetWindowTextW(handle, text.as_ptr());
}
pub unsafe fn set_window_position(handle: HWND, x: i32, y: i32) {
use winapi::um::winuser::SetWindowPos;
use winapi::um::winuser::{SWP_NOZORDER, SWP_NOSIZE, SWP_NOACTIVATE, SWP_NOOWNERZORDER};
let (x, y) = high_dpi::logical_to_physical(x, y);
SetWindowPos(handle, ptr::null_mut(), x as c_int, y as c_int, 0, 0, SWP_NOZORDER|SWP_NOSIZE|SWP_NOACTIVATE|SWP_NOOWNERZORDER);
}
pub unsafe fn set_window_after(handle: HWND, after: Option<HWND>) {
use winapi::um::winuser::SetWindowPos;
use winapi::um::winuser::{HWND_TOP, SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, SWP_NOOWNERZORDER};
let after_handle = match after {
None => HWND_TOP,
Some(w) => w
};
SetWindowPos(handle, after_handle, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE|SWP_NOOWNERZORDER);
}
pub unsafe fn get_window_position(handle: HWND) -> (i32, i32) {
use winapi::um::winuser::{GetWindowRect, ScreenToClient, GetParent};
use winapi::shared::windef::{RECT, POINT};
let mut r: RECT = mem::zeroed();
GetWindowRect(handle, &mut r);
let parent = GetParent(handle);
let (x, y) = if !parent.is_null() {
let mut pt = POINT{x: r.left, y: r.top};
ScreenToClient(parent, &mut pt);
(pt.x as i32, pt.y as i32)
} else {
(r.left as i32, r.top as i32)
};
high_dpi::physical_to_logical(x, y)
}
pub unsafe fn set_window_size(handle: HWND, w: u32, h: u32, fix: bool) {
use winapi::um::winuser::{SetWindowPos, AdjustWindowRectEx, GetWindowLongW};
use winapi::um::winuser::{SWP_NOZORDER, SWP_NOMOVE, SWP_NOACTIVATE, SWP_NOCOPYBITS, GWL_STYLE, GWL_EXSTYLE, SWP_NOOWNERZORDER};
use winapi::shared::windef::RECT;
let (mut w, mut h) = high_dpi::logical_to_physical(w as i32, h as i32);
if fix {
let flags = GetWindowLongW(handle, GWL_STYLE) as u32;
let ex_flags = GetWindowLongW(handle, GWL_EXSTYLE) as u32;
let mut rect = RECT {left: 0, top: 0, right: w, bottom: h};
AdjustWindowRectEx(&mut rect, flags, 0, ex_flags);
w = rect.right - rect.left;
h = rect.bottom - rect.top;
}
SetWindowPos(handle, ptr::null_mut(), 0, 0, w, h, SWP_NOZORDER|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOOWNERZORDER);
}
pub unsafe fn get_window_size(handle: HWND) -> (u32, u32) {
get_window_size_impl(handle, false)
}
#[allow(unused)]
pub unsafe fn get_window_physical_size(handle: HWND) -> (u32, u32) {
get_window_size_impl(handle, true)
}
unsafe fn get_window_size_impl(handle: HWND, return_physical: bool) -> (u32, u32) {
use winapi::um::winuser::GetClientRect;
use winapi::shared::windef::RECT;
let mut r: RECT = mem::zeroed();
GetClientRect(handle, &mut r);
let (w, h) = if return_physical {
(r.right, r.bottom)
} else {
high_dpi::physical_to_logical(r.right, r.bottom)
};
(w as u32, h as u32)
}
pub unsafe fn set_window_visibility(handle: HWND, visible: bool) {
use winapi::um::winuser::ShowWindow;
use winapi::um::winuser::{SW_HIDE, SW_SHOW};
let visible = if visible { SW_SHOW } else { SW_HIDE };
ShowWindow(handle, visible);
}
pub unsafe fn get_window_visibility(handle: HWND) -> bool {
use winapi::um::winuser::IsWindowVisible;
IsWindowVisible(handle) != 0
}
pub unsafe fn get_window_enabled(handle: HWND) -> bool {
use winapi::um::winuser::{GWL_STYLE, WS_DISABLED};
let style = get_window_long(handle, GWL_STYLE) as UINT;
(style & WS_DISABLED) != WS_DISABLED
}
pub unsafe fn set_window_enabled(handle: HWND, enabled: bool) {
use winapi::um::winuser::{GWL_STYLE, WS_DISABLED};
use winapi::um::winuser::{UpdateWindow, InvalidateRect};
let old_style = get_window_long(handle, GWL_STYLE) as usize;
if enabled {
set_window_long(handle, GWL_STYLE, old_style&(!WS_DISABLED as usize) );
} else {
set_window_long(handle, GWL_STYLE, old_style|(WS_DISABLED as usize));
}
// Tell the control to redraw itself to show the new style.
InvalidateRect(handle, ptr::null(), 1);
UpdateWindow(handle);
}
#[cfg(feature = "tabs")]
pub unsafe fn get_window_class_name(handle: HWND) -> String {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use winapi::shared::ntdef::WCHAR;
use winapi::um::winuser::GetClassNameW;
let mut class_name_raw: Vec<WCHAR> = Vec::with_capacity(100);
class_name_raw.set_len(100);
let count = GetClassNameW(handle, class_name_raw.as_mut_ptr(), 100) as usize;
OsString::from_wide(&class_name_raw[..count]).into_string().unwrap_or("".to_string())
}
#[cfg(target_pointer_width = "32")] use winapi::shared::ntdef::LONG;
#[cfg(target_pointer_width = "64")] use winapi::shared::basetsd::LONG_PTR;
#[inline(always)]
#[cfg(target_pointer_width = "64")]
pub fn get_window_long(handle: HWND, index: c_int) -> LONG_PTR {
unsafe{ ::winapi::um::winuser::GetWindowLongPtrW(handle, index) }
}
#[inline(always)]
#[cfg(target_pointer_width = "32")]
pub fn get_window_long(handle: HWND, index: c_int) -> LONG {
unsafe { ::winapi::um::winuser::GetWindowLongW(handle, index) }
}
#[inline(always)]
#[cfg(target_pointer_width = "64")]
pub fn set_window_long(handle: HWND, index: c_int, v: usize) {
unsafe{ ::winapi::um::winuser::SetWindowLongPtrW(handle, index, v as LONG_PTR); }
}
#[inline(always)]
#[cfg(target_pointer_width = "32")]
pub fn set_window_long(handle: HWND, index: c_int, v: usize) {
unsafe { ::winapi::um::winuser::SetWindowLongW(handle, index, v as LONG); }
}
// Helper to wrap DeferWindowPos somewhat safely
// Mostly to streamline the usage of the returned HWDP from DeferWindowPos
pub struct DeferredWindowPositioner {
handle: winapi::um::winuser::HDWP,
}
impl DeferredWindowPositioner {
const MEM_FAIL: &'static str = "Insufficient system resources";
/// Initialises a new DeferredWindowPositioner with memory for `item_count` windows
pub fn new(item_count: i32) -> Result<DeferredWindowPositioner, &'static str> {
use ::winapi::um::winuser::BeginDeferWindowPos;
let handle = unsafe { BeginDeferWindowPos(item_count) };
if handle.is_null() {
Err(DeferredWindowPositioner::MEM_FAIL)
}
else {
Ok(DeferredWindowPositioner {
handle
})
}
}
/// Defers a window positioning
pub fn defer_pos(
&mut self,
hwnd: HWND,
hwnd_insertafter: HWND,
x: i32,
y: i32,
cx: i32,
cy: i32,
) -> Result<(), &'static str> {
use ::winapi::um::winuser::DeferWindowPos;
let handle = unsafe {
DeferWindowPos(self.handle, hwnd, hwnd_insertafter, x, y, cx, cy, 0)
};
self.handle = handle;
if handle.is_null() {
Err(DeferredWindowPositioner::MEM_FAIL)
}
else {
Ok(())
}
}
/// Ends the deferred operation list
/// This will apply the batched changes, unless an internal error occured in a defer_pos call
pub fn end(self) {} // Handled by drop impl
}
impl std::ops::Drop for DeferredWindowPositioner {
fn drop(&mut self) {
use ::winapi::um::winuser::EndDeferWindowPos;
// In case of previous error, no-op
if !self.handle.is_null() {
unsafe { EndDeferWindowPos(self.handle) };
}
}
} |
use log;
use actix_web::{error, error::BlockingError, web, HttpResponse, Result, dev::HttpResponseBuilder, http::header, http::StatusCode};
use derive_more::{Display, Error};
use tera::{Context, Tera};
use serde::Deserialize;
use crate::db::{self, DatabaseError};
#[derive(Debug, Display, Error)]
pub enum ServerError {
#[display(fmt = "An internal error ocurred. Please try again later.")]
InternalError,
#[display(fmt = "The post you are looking for does not exist.")]
PostNotFound,
}
impl error::ResponseError for ServerError {
fn error_response(&self) -> HttpResponse {
HttpResponseBuilder::new(self.status_code())
.set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.body(self.to_string())
}
fn status_code(&self) -> StatusCode {
match *self {
ServerError::PostNotFound => StatusCode::NOT_FOUND,
ServerError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
#[derive(Deserialize)]
pub struct PageQuery {
page: Option<i64>,
}
pub async fn blog(
pool: web::Data<db::PgPool>,
query: web::Query<PageQuery>,
tmpl: web::Data<Tera>,
) -> Result<HttpResponse, ServerError> {
let page = query.page.unwrap_or(1);
let conn = db::get_conn(&pool)
.map_err(|e| {
log::error!("Database error: {}", e);
ServerError::InternalError
})?;
let posts = web::block(move || db::select_last_n_posts(20, (page - 1) * 15, conn))
.await
.map_err(|e| {
match e {
BlockingError::Error(DatabaseError::ConnectionPoolError(_)) => {
log::error!("Error with connection pool: {}", e);
ServerError::InternalError
},
_ => {
log::error!("Database error: {}", e);
ServerError::InternalError
}
}
})?;
let conn = db::get_conn(&pool)
.map_err(|e| {
log::error!("Database error: {}", e);
ServerError::InternalError
})?;
let total_posts = web::block(move || db::count_total_posts(conn))
.await
.map_err(|e| {
match e {
BlockingError::Error(DatabaseError::ConnectionPoolError(_)) => {
log::error!("Error with connection pool: {}", e);
ServerError::InternalError
},
_ => {
log::error!("Database error: {}", e);
ServerError::InternalError
}
}
})?;
let total_pages = total_posts / 15;
let mut context = Context::new();
context.insert("posts", &posts);
context.insert("page", &page);
context.insert("total_pages", &total_pages);
let rendered = tmpl
.render("blog.html.tera", &context)
.map_err(|e| {
log::error!("Failed to render template: {}", e);
ServerError::InternalError
})?;
Ok(HttpResponse::Ok().body(rendered))
}
#[derive(Deserialize)]
pub struct SearchQuery {
tag: Option<String>,
page: Option<i64>,
}
pub async fn search(
pool: web::Data<db::PgPool>,
tmpl: web::Data<Tera>,
query: web::Query<SearchQuery>,
) -> Result<HttpResponse, ServerError> {
let page = query.page.unwrap_or(1);
let mut context = Context::new();
let conn = db::get_conn(&pool)
.map_err(|e| {
log::error!("Database error: {}", e);
ServerError::InternalError
})?;
let posts = if query.tag.is_some() {
let search_tag = query.tag.as_ref().unwrap().to_string();
context.insert("search_tag", &search_tag);
web::block(move || db::select_n_posts_with_tag(&search_tag, 20, (page - 1) * 15, conn))
.await
.map_err(|e| {
match e {
BlockingError::Error(DatabaseError::ConnectionPoolError(_)) => {
log::error!("Error with connection pool: {}", e);
ServerError::InternalError
},
_ => {
log::error!("Database error: {}", e);
ServerError::InternalError
}
}
})?
} else {
Vec::new()
};
let conn = db::get_conn(&pool)
.map_err(|e| {
log::error!("Database error: {}", e);
ServerError::InternalError
})?;
let total_posts = web::block(move || db::count_total_posts(conn))
.await
.map_err(|e| {
match e {
BlockingError::Error(DatabaseError::ConnectionPoolError(_)) => {
log::error!("Error with connection pool: {}", e);
ServerError::InternalError
},
_ => {
log::error!("Database error: {}", e);
ServerError::InternalError
}
}
})?;
let total_pages = total_posts / 15;
context.insert("posts", &posts);
context.insert("page", &page);
context.insert("total_pages", &total_pages);
let rendered = tmpl
.render("blog.html.tera", &context)
.map_err(|e| {
log::error!("Failed to render template: {}", e);
ServerError::InternalError
})?;
Ok(HttpResponse::Ok().body(rendered))
}
pub async fn post(
pool: web::Data<db::PgPool>,
tmpl: web::Data<Tera>,
post_slug: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
let conn = db::get_conn(&pool)
.map_err(|e| {
log::error!("Database error: {}", e);
ServerError::InternalError
})?;
let post = web::block(move || db::select_post_with_slug(&post_slug, conn))
.await
.map_err(|e| {
match e {
BlockingError::Error(DatabaseError::ConnectionPoolError(_)) => {
log::error!("Error with connection pool: {}", e);
ServerError::InternalError
},
BlockingError::Error(DatabaseError::NotFound(_)) => {
log::error!("Post not found: {}", e);
ServerError::PostNotFound
},
_ => {
log::error!("Database error: {}", e);
ServerError::InternalError
}
}
})?;
let mut context = Context::new();
context.insert("post", &post);
let rendered = tmpl
.render("post.html.tera", &context)
.map_err(|e| {
log::error!("Failed to render template: {}", e);
ServerError::InternalError
})?;
Ok(HttpResponse::Ok().body(rendered))
}
|
pub fn goodbye() -> String {
"バイバイ".to_string()
}
|
fn main() {
let s1 = "a=1&b=2&c";
println!("\"{}\" -> {:?}", s1, parse_params(s1));
// "a=1&b=2&c" -> [("a", "1"), ("b", "2")]
let s2 = "a=1&b=";
println!("\"{}\" -> {:?}", s2, parse_params(s2));
// "a=1&b=" -> [("a", "1"), ("b", "")]
let s3 = "a=1";
println!("\"{}\" -> {:?}", s3, parse_params(s3));
// "a=1" -> [("a", "1")]
let s4 = "a";
println!("\"{}\" -> {:?}", s4, parse_params(s4));
// "a" -> []
}
fn parse_params(s: &str) -> Vec<(&str, &str)> {
s.split("&")
.filter(|t| t.contains("="))
.map(|t| {
let v = t.split("=").collect::<Vec<_>>();
(v[0], v[1])
})
.collect()
}
|
use std::f32;
use cgmath::InnerSpace;
use Vector3;
#[derive(PartialEq)]
pub struct Camera {
pub pos: Vector3,
dir_top_left: Vector3,
screen_du: Vector3,
screen_dv: Vector3,
img: (u32, u32),
}
impl Camera {
pub fn look_dir(pos: Vector3, dir: Vector3, up: Vector3, fov: f32, img: (u32, u32)) -> Camera {
let dz = dir.normalize();
let dx = -dz.cross(up).normalize();
let dy = dx.cross(dz).normalize();
let dim_y = 2.0 * f32::tan((fov / 2.0) * f32::consts::PI / 180.0);
let aspect_ratio = img.0 as f32 / img.1 as f32;
let dim_x = dim_y * aspect_ratio;
let screen_du = dx * dim_x;
let screen_dv = dy * dim_y;
let dir_top_left = dz - 0.5 * screen_du - 0.5 * screen_dv;
Camera {
pos: pos,
dir_top_left: dir_top_left,
screen_du: screen_du,
screen_dv: screen_dv,
img: img,
}
}
pub fn look_at(pos: Vector3, at: Vector3, up: Vector3, fov: f32, img: (u32, u32)) -> Camera {
let dir = at - pos;
Camera::look_dir(pos, dir, up, fov, img)
}
/// Compute the ray direction going through the pixel passed
pub fn ray_dir(&self, px: (f32, f32)) -> Vector3 {
(self.dir_top_left
+ px.0 / (self.img.0 as f32) * self.screen_du
+ px.1 / (self.img.1 as f32) * self.screen_dv)
.normalize()
}
}
|
/// Sign of Y, magnitude of X (f32)
///
/// Constructs a number with the magnitude (absolute value) of its
/// first argument, `x`, and the sign of its second argument, `y`.
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn copysignf(x: f32, y: f32) -> f32 {
let mut ux = x.to_bits();
let uy = y.to_bits();
ux &= 0x7fffffff;
ux |= uy & 0x80000000;
f32::from_bits(ux)
}
|
mod msg;
mod msg_types;
mod raw_msg;
pub use msg::*;
pub use raw_msg::*;
|
//! The `blob_fetch_stage` pulls blobs from UDP sockets and sends it to a channel.
use crate::service::Service;
use crate::streamer::{self, BlobSender};
use std::net::UdpSocket;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::thread::{self, JoinHandle};
pub struct BlobFetchStage {
thread_hdls: Vec<JoinHandle<()>>,
}
impl BlobFetchStage {
pub fn new(socket: Arc<UdpSocket>, sender: &BlobSender, exit: &Arc<AtomicBool>) -> Self {
Self::new_multi_socket(vec![socket], sender, exit)
}
pub fn new_multi_socket(
sockets: Vec<Arc<UdpSocket>>,
sender: &BlobSender,
exit: &Arc<AtomicBool>,
) -> Self {
let thread_hdls: Vec<_> = sockets
.into_iter()
.map(|socket| streamer::blob_receiver(socket, &exit, sender.clone()))
.collect();
Self { thread_hdls }
}
}
impl Service for BlobFetchStage {
type JoinReturnType = ();
fn join(self) -> thread::Result<()> {
for thread_hdl in self.thread_hdls {
thread_hdl.join()?;
}
Ok(())
}
}
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
blocks::{
genesis_block::{
get_mainnet_block_hash,
get_mainnet_genesis_block,
get_rincewind_block_hash,
get_rincewind_genesis_block,
},
Block,
},
chain_storage::ChainStorageError,
consensus::{emission::EmissionSchedule, network::Network, ConsensusConstants},
proof_of_work::DifficultyAdjustmentError,
transactions::tari_amount::MicroTari,
};
use derive_error::Error;
use std::sync::Arc;
use tari_crypto::tari_utilities::hash::Hashable;
#[derive(Debug, Error, Clone, PartialEq)]
pub enum ConsensusManagerError {
/// Difficulty adjustment encountered an error
DifficultyAdjustmentError(DifficultyAdjustmentError),
/// Problem with the DB backend storage
ChainStorageError(ChainStorageError),
/// There is no blockchain to query
EmptyBlockchain,
/// RwLock access broken.
#[error(non_std, no_from)]
PoisonedAccess(String),
/// No Difficulty adjustment manager present
MissingDifficultyAdjustmentManager,
}
/// This is the consensus manager struct. This manages all state-full consensus code.
/// The inside is wrapped inside of an ARC so that it can safely and cheaply be cloned.
/// The code is multi-thread safe and so only one instance is required. Inner objects are wrapped inside of RwLocks.
pub struct ConsensusManager {
inner: Arc<ConsensusManagerInner>,
}
impl ConsensusManager {
/// Returns the genesis block for the selected network.
pub fn get_genesis_block(&self) -> Block {
match self.inner.network {
Network::MainNet => get_mainnet_genesis_block(),
Network::Rincewind => get_rincewind_genesis_block(),
Network::LocalNet => (self.inner.gen_block.clone().unwrap_or_else(get_rincewind_genesis_block)),
}
}
/// Returns the genesis block hash for the selected network.
pub fn get_genesis_block_hash(&self) -> Vec<u8> {
match self.inner.network {
Network::MainNet => get_mainnet_block_hash(),
Network::Rincewind => get_rincewind_block_hash(),
Network::LocalNet => (self.inner.gen_block.clone().unwrap_or_else(get_rincewind_genesis_block)).hash(),
}
}
/// Get a pointer to the emission schedule
pub fn emission_schedule(&self) -> &EmissionSchedule {
&self.inner.emission
}
/// Get a pointer to the consensus constants
pub fn consensus_constants(&self) -> &ConsensusConstants {
&self.inner.consensus_constants
}
/// Creates a total_coinbase offset containing all fees for the validation from block
pub fn calculate_coinbase_and_fees(&self, block: &Block) -> MicroTari {
let coinbase = self.emission_schedule().block_reward(block.header.height);
coinbase + block.calculate_fees()
}
/// This is the currently configured chain network.
pub fn network(&self) -> Network {
self.inner.network
}
}
impl Clone for ConsensusManager {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
/// This is the used to control all consensus values.
struct ConsensusManagerInner {
/// This is the inner struct used to control all consensus values.
pub consensus_constants: ConsensusConstants,
/// The configured chain network.
pub network: Network,
/// The configuration for the emission schedule.
pub emission: EmissionSchedule,
/// This allows the user to set a custom Genesis block
pub gen_block: Option<Block>,
}
/// Constructor for the consensus manager struct
pub struct ConsensusManagerBuilder {
/// This is the inner struct used to control all consensus values.
pub consensus_constants: Option<ConsensusConstants>,
/// The configured chain network.
pub network: Network,
/// This allows the user to set a custom Genesis block
pub gen_block: Option<Block>,
}
impl ConsensusManagerBuilder {
/// Creates a new ConsensusManagerBuilder with the specified network
pub fn new(network: Network) -> Self {
ConsensusManagerBuilder {
consensus_constants: None,
network,
gen_block: None,
}
}
/// Adds in a custom consensus constants to be used
pub fn with_consensus_constants(mut self, consensus_constants: ConsensusConstants) -> Self {
self.consensus_constants = Some(consensus_constants);
self
}
/// Adds in a custom block to be used. This will be overwritten if the network is anything else than localnet
pub fn with_block(mut self, block: Block) -> Self {
self.gen_block = Some(block);
self
}
/// Builds a consensus manager
#[allow(clippy::or_fun_call)]
pub fn build(self) -> ConsensusManager {
let consensus_constants = self
.consensus_constants
.unwrap_or(self.network.create_consensus_constants());
let emission = EmissionSchedule::new(
consensus_constants.emission_initial,
consensus_constants.emission_decay,
consensus_constants.emission_tail,
);
let inner = ConsensusManagerInner {
consensus_constants,
network: self.network,
emission,
gen_block: self.gen_block,
};
ConsensusManager { inner: Arc::new(inner) }
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::string::String;
use simplelog::LevelFilter;
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
pub enum DebugLevel {
Debug,
Info,
Trace,
}
impl DebugLevel {
pub fn FromLevelFilter(level: &LevelFilter) -> Self {
match level {
LevelFilter::Debug => Self::Debug,
LevelFilter::Info => Self::Info,
_ => Self::Trace,
}
}
pub fn ToLevelFilter(&self) -> LevelFilter {
match self {
DebugLevel::Debug => LevelFilter::Debug,
DebugLevel::Info => LevelFilter::Info,
DebugLevel::Trace => LevelFilter::Trace,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct GlobalConfig {
// RootDir is the runtime root directory.
pub RootDir: String,
pub DebugLevel: DebugLevel,
// DebugLog is the path to log debug information to, if not empty.
pub DebugLog: String,
// FileAccess indicates how the filesystem is accessed.
pub FileAccess: FileAccessType,
// Network indicates what type of network to use.
pub Network: NetworkType,
}
impl Default for GlobalConfig {
fn default() -> Self {
return Self {
RootDir: String::default(),
DebugLevel: DebugLevel::Info,
DebugLog: String::default(),
FileAccess: FileAccessType::default(),
Network: NetworkType::default(),
}
}
}
impl GlobalConfig {
pub fn Copy(&self) -> Self {
return Self {
RootDir: self.RootDir.to_string(),
DebugLevel: self.DebugLevel,
DebugLog: self.DebugLog.to_string(),
FileAccess: self.FileAccess,
Network: self.Network,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Copy)]
pub enum FileAccessType {
FileAccessShared,
FileAccessCached,
}
impl Default for FileAccessType {
fn default() -> FileAccessType {
FileAccessType::FileAccessShared
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Copy)]
pub enum NetworkType {
// NetworkHost redirects network related syscalls to the host network.
NetworkHost,
// NetworkNone sets up just loopback using netstack.
NetworkNone,
}
impl Default for NetworkType {
fn default() -> NetworkType {
NetworkType::NetworkHost
}
}
|
use std::{
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use bitflags::bitflags;
use futures_core::ready;
use smallvec::SmallVec;
use crate::{
actor::{Actor, ActorContext, ActorState, AsyncContext, Running, SpawnHandle, Supervised},
address::{Addr, AddressSenderProducer},
contextitems::ActorWaitItem,
fut::ActorFuture,
mailbox::Mailbox,
};
bitflags! {
/// Internal context state.
#[derive(Debug)]
struct ContextFlags: u8 {
const STARTED = 0b0000_0001;
const RUNNING = 0b0000_0010;
const STOPPING = 0b0000_0100;
const STOPPED = 0b0001_0000;
const MB_CAP_CHANGED = 0b0010_0000;
}
}
type Item<A> = (SpawnHandle, Pin<Box<dyn ActorFuture<A, Output = ()>>>);
pub trait AsyncContextParts<A>: ActorContext + AsyncContext<A>
where
A: Actor<Context = Self>,
{
fn parts(&mut self) -> &mut ContextParts<A>;
}
pub struct ContextParts<A>
where
A: Actor,
A::Context: AsyncContext<A>,
{
addr: AddressSenderProducer<A>,
flags: ContextFlags,
wait: SmallVec<[ActorWaitItem<A>; 2]>,
items: SmallVec<[Item<A>; 3]>,
handles: SmallVec<[SpawnHandle; 2]>,
}
impl<A> fmt::Debug for ContextParts<A>
where
A: Actor,
A::Context: AsyncContext<A>,
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("ContextParts")
.field("flags", &self.flags)
.finish()
}
}
impl<A> ContextParts<A>
where
A: Actor,
A::Context: AsyncContext<A>,
{
#[inline]
/// Create new [`ContextParts`] instance
pub fn new(addr: AddressSenderProducer<A>) -> Self {
ContextParts {
addr,
flags: ContextFlags::RUNNING,
wait: SmallVec::new(),
items: SmallVec::new(),
handles: SmallVec::from_slice(&[SpawnHandle::default(), SpawnHandle::default()]),
}
}
#[inline]
/// Initiate stop process for actor execution
///
/// Actor could prevent stopping by returning `false` from
/// `Actor::stopping()` method.
pub fn stop(&mut self) {
if self.flags.contains(ContextFlags::RUNNING) {
self.flags.remove(ContextFlags::RUNNING);
self.flags.insert(ContextFlags::STOPPING);
}
}
#[inline]
/// Terminate actor execution
pub fn terminate(&mut self) {
self.flags = ContextFlags::STOPPED;
}
#[inline]
/// Actor execution state
pub fn state(&self) -> ActorState {
if self.flags.contains(ContextFlags::RUNNING) {
ActorState::Running
} else if self.flags.contains(ContextFlags::STOPPED) {
ActorState::Stopped
} else if self.flags.contains(ContextFlags::STOPPING) {
ActorState::Stopping
} else {
ActorState::Started
}
}
#[inline]
/// Is context waiting for future completion
pub fn waiting(&self) -> bool {
!self.wait.is_empty()
|| self
.flags
.intersects(ContextFlags::STOPPING | ContextFlags::STOPPED)
}
#[inline]
/// Handle of the running future
pub fn curr_handle(&self) -> SpawnHandle {
self.handles[1]
}
#[inline]
/// Spawn new future to this context.
pub fn spawn<F>(&mut self, fut: F) -> SpawnHandle
where
F: ActorFuture<A, Output = ()> + 'static,
{
let handle = self.handles[0].next();
self.handles[0] = handle;
let fut: Box<dyn ActorFuture<A, Output = ()>> = Box::new(fut);
self.items.push((handle, Pin::from(fut)));
handle
}
#[inline]
/// Spawn new future to this context and wait future completion.
///
/// During wait period actor does not receive any messages.
pub fn wait<F>(&mut self, f: F)
where
F: ActorFuture<A, Output = ()> + 'static,
{
self.wait.push(ActorWaitItem::new(f));
}
#[inline]
/// Cancel previously scheduled future.
pub fn cancel_future(&mut self, handle: SpawnHandle) -> bool {
self.handles.push(handle);
true
}
#[inline]
pub fn capacity(&mut self) -> usize {
self.addr.capacity()
}
#[inline]
pub fn set_mailbox_capacity(&mut self, cap: usize) {
self.flags.insert(ContextFlags::MB_CAP_CHANGED);
self.addr.set_capacity(cap);
}
#[inline]
pub fn address(&self) -> Addr<A> {
Addr::new(self.addr.sender())
}
/// Restart context. Cleanup all futures, except address queue.
#[inline]
pub(crate) fn restart(&mut self) {
self.flags = ContextFlags::RUNNING;
self.wait = SmallVec::new();
self.items = SmallVec::new();
self.handles[0] = SpawnHandle::default();
}
#[inline]
pub fn started(&mut self) -> bool {
self.flags.contains(ContextFlags::STARTED)
}
/// Are any senders connected
#[inline]
pub fn connected(&self) -> bool {
self.addr.connected()
}
}
pub struct ContextFut<A, C>
where
C: AsyncContextParts<A> + Unpin,
A: Actor<Context = C>,
{
ctx: C,
act: A,
mailbox: Mailbox<A>,
wait: SmallVec<[ActorWaitItem<A>; 2]>,
items: SmallVec<[Item<A>; 3]>,
}
impl<A, C> fmt::Debug for ContextFut<A, C>
where
C: AsyncContextParts<A> + Unpin,
A: Actor<Context = C>,
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "ContextFut {{ /* omitted */ }}")
}
}
impl<A, C> Drop for ContextFut<A, C>
where
C: AsyncContextParts<A> + Unpin,
A: Actor<Context = C>,
{
fn drop(&mut self) {
if self.alive() {
self.ctx.parts().stop();
let waker = futures_task::noop_waker();
let mut cx = std::task::Context::from_waker(&waker);
let _ = Pin::new(self).poll(&mut cx);
}
}
}
impl<A, C> ContextFut<A, C>
where
C: AsyncContextParts<A> + Unpin,
A: Actor<Context = C>,
{
pub fn new(ctx: C, act: A, mailbox: Mailbox<A>) -> Self {
ContextFut {
ctx,
act,
mailbox,
wait: SmallVec::new(),
items: SmallVec::new(),
}
}
#[inline]
pub fn ctx(&mut self) -> &mut C {
&mut self.ctx
}
#[inline]
pub fn address(&self) -> Addr<A> {
self.mailbox.address()
}
#[inline]
fn stopping(&mut self) -> bool {
self.ctx
.parts()
.flags
.intersects(ContextFlags::STOPPING | ContextFlags::STOPPED)
}
#[inline]
pub fn alive(&mut self) -> bool {
if self.ctx.parts().flags.contains(ContextFlags::STOPPED) {
false
} else {
!self.ctx.parts().flags.contains(ContextFlags::STARTED)
|| self.mailbox.connected()
|| !self.items.is_empty()
|| !self.wait.is_empty()
}
}
/// Restart context. Cleanup all futures, except address queue.
#[inline]
pub(crate) fn restart(&mut self) -> bool
where
A: Supervised,
{
if self.mailbox.connected() {
self.wait = SmallVec::new();
self.items = SmallVec::new();
self.ctx.parts().restart();
self.act.restarting(&mut self.ctx);
true
} else {
false
}
}
fn merge(&mut self) -> bool {
let mut modified = false;
let parts = self.ctx.parts();
if !parts.wait.is_empty() {
modified = true;
self.wait.extend(parts.wait.drain(0..));
}
if !parts.items.is_empty() {
modified = true;
self.items.extend(parts.items.drain(0..));
}
//
if parts.flags.contains(ContextFlags::MB_CAP_CHANGED) {
modified = true;
parts.flags.remove(ContextFlags::MB_CAP_CHANGED);
}
if parts.handles.len() > 2 {
modified = true;
}
modified
}
fn clean_canceled_handle(&mut self) {
fn remove_item_by_handle<C>(
items: &mut SmallVec<[Item<C>; 3]>,
handle: &SpawnHandle,
) -> bool {
let mut idx = 0;
let mut removed = false;
while idx < items.len() {
if &items[idx].0 == handle {
items.swap_remove(idx);
removed = true;
} else {
idx += 1;
}
}
removed
}
while self.ctx.parts().handles.len() > 2 {
let handle = self.ctx.parts().handles.pop().unwrap();
// remove item from ContextFut.items in case associated item is already merged
if !remove_item_by_handle(&mut self.items, &handle) {
// item is not merged into ContextFut.items yet,
// so it should be in ContextParts.items
remove_item_by_handle(&mut self.ctx.parts().items, &handle);
}
}
}
}
#[doc(hidden)]
impl<A, C> Future for ContextFut<A, C>
where
C: AsyncContextParts<A> + Unpin,
A: Actor<Context = C>,
{
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
if !this.ctx.parts().flags.contains(ContextFlags::STARTED) {
this.ctx.parts().flags.insert(ContextFlags::STARTED);
Actor::started(&mut this.act, &mut this.ctx);
// check cancelled handles, just in case
if this.merge() {
this.clean_canceled_handle();
}
}
'outer: loop {
// check wait futures. order does matter
// ctx.wait() always add to the back of the list
// and we always have to check most recent future
while !this.wait.is_empty() && !this.stopping() {
let idx = this.wait.len() - 1;
let item = this.wait.last_mut().unwrap();
ready!(Pin::new(item).poll(&mut this.act, &mut this.ctx, cx));
this.wait.remove(idx);
this.merge();
}
// process mailbox
this.mailbox.poll(&mut this.act, &mut this.ctx, cx);
if !this.wait.is_empty() && !this.stopping() {
continue;
}
// process items
let mut idx = 0;
while idx < this.items.len() && !this.stopping() {
this.ctx.parts().handles[1] = this.items[idx].0;
match Pin::new(&mut this.items[idx].1).poll(&mut this.act, &mut this.ctx, cx) {
Poll::Pending => {
// got new waiting item. merge
if this.ctx.waiting() {
this.merge();
}
// check cancelled handles
if this.ctx.parts().handles.len() > 2 {
// this code is not very efficient, relaying on fact that
// cancellation should be rear also number of futures
// in actor context should be small
this.clean_canceled_handle();
continue 'outer;
}
// item scheduled wait future
if !this.wait.is_empty() && !this.stopping() {
// move current item to end of poll queue
// otherwise it is possible that same item generate wait
// future and prevents polling
// of other items
let next = this.items.len() - 1;
if idx != next {
this.items.swap(idx, next);
}
continue 'outer;
} else {
idx += 1;
}
}
Poll::Ready(()) => {
this.items.swap_remove(idx);
// got new waiting item. merge
if this.ctx.waiting() {
this.merge();
}
// one of the items scheduled wait future
if !this.wait.is_empty() && !this.stopping() {
continue 'outer;
}
}
}
}
this.ctx.parts().handles[1] = SpawnHandle::default();
// merge returns true if context contains new items or handles to be cancelled
if this.merge() && !this.ctx.parts().flags.contains(ContextFlags::STOPPING) {
// if we have no item to process, cancelled handles wouldn't be
// reaped in the above loop. this means this.merge() will never
// be false and the poll() never ends. so, discard the handles
// as we're sure there are no more items to be cancelled.
if this.items.is_empty() {
this.ctx.parts().handles.truncate(2);
}
continue;
}
// check state
if this.ctx.parts().flags.contains(ContextFlags::RUNNING) {
// possible stop condition
if !this.alive() && Actor::stopping(&mut this.act, &mut this.ctx) == Running::Stop {
this.ctx.parts().flags = ContextFlags::STOPPED | ContextFlags::STARTED;
Actor::stopped(&mut this.act, &mut this.ctx);
return Poll::Ready(());
}
} else if this.ctx.parts().flags.contains(ContextFlags::STOPPING) {
if Actor::stopping(&mut this.act, &mut this.ctx) == Running::Stop {
this.ctx.parts().flags = ContextFlags::STOPPED | ContextFlags::STARTED;
Actor::stopped(&mut this.act, &mut this.ctx);
return Poll::Ready(());
} else {
this.ctx.parts().flags.remove(ContextFlags::STOPPING);
this.ctx.parts().flags.insert(ContextFlags::RUNNING);
continue;
}
} else if this.ctx.parts().flags.contains(ContextFlags::STOPPED) {
Actor::stopped(&mut this.act, &mut this.ctx);
return Poll::Ready(());
}
return Poll::Pending;
}
}
}
|
mod surface;
mod functions;
fn main() {
//Small example to check that everything is working nicely: I have a plane which has already been
// traslated to the origin and rotated such that it is parallel to the xy plane. Then I can call
// my checking function to see if my point is in the bounded region.
let point3D = surface::Point3D::new(1.0,1.0,0.0);
let my_rect = surface::Rectangle::new(0.0,0.0,3.4,0.0,5.0,3.0);
let result = functions::is_point_on_rectangle(point3D,my_rect);
//Another example involving the rotation matrix:
let to_be_rotated = surface::Rectangle::new(1.0,2.0,3.0,0.0,3.0,7.0);
let rotation_matrix = functions::rotation_to_xy_plane(to_be_rotated);
//The inverse is the tranpose
let inverse = rotation_matrix.transpose();
println!("Everything is working nicely!");
}
|
use sqlx::mysql::{MySqlRow, MySqlConnectOptions};
use sqlx::Connection;
use futures::TryStreamExt;
use crate::mysqlaccessor::{MySQLAccessor, MySQLAccessorError, MySQLAccessorErrorType};
macro_rules! check_conn_open {
($ins:expr) => {
{
if $ins.conn.is_none() {
return Err(MySQLAccessorError {
err_type: MySQLAccessorErrorType::ConnNotOpen
});
}
}
};
}
pub struct MySQLAccessorAsync<'a> {
pub(crate) host: &'a str,
pub(crate) port: u16,
pub(crate) user: &'a str,
pub(crate) passwd: &'a str,
pub(crate) db: &'a str,
pub(crate) charset: &'a str,
is_open_connection: bool,
pub(crate) conn: Option<sqlx::MySqlConnection>
}
impl<'a> MySQLAccessor for MySQLAccessorAsync<'a> {
}
impl<'a> MySQLAccessorAsync<'a> {
pub fn new() -> Self {
Self {
host: "localhost",
port: 3308,
user: "root",
passwd: "",
db: "",
charset: "utf8",
is_open_connection: false,
conn: None,
}
}
pub fn host(mut self, host: &'a str) -> Self {
self.host = host;
self
}
pub fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
pub fn user(mut self, user: &'a str) -> Self {
self.user = user;
self
}
pub fn passwd(mut self, passwd: &'a str) -> Self {
self.passwd = passwd;
self
}
pub fn db(mut self, db: &'a str) -> Self {
self.db = db;
self
}
pub fn charset(mut self, charset: &'a str) -> Self {
self.charset = charset;
self
}
fn get_connect_option(&self) -> MySqlConnectOptions {
sqlx::mysql::MySqlConnectOptions::new()
.username(self.user)
.password(self.passwd)
.host(self.host)
.port(self.port)
.database(self.db)
.charset(self.charset)
}
pub async fn open_connection(&mut self) -> Result<(), MySQLAccessorError> {
self.is_open_connection = true;
if self.conn.is_none() {
let connect_options = self.get_connect_option();
println!("{:?}", connect_options);
self.conn = match sqlx::MySqlConnection::connect_with(&connect_options).await {
Ok(conn) => Some(conn),
Err(e) => {
println!("{:?}", e);
None
}
};
}
Ok(())
}
pub async fn do_sql(&mut self, sql: &str) -> Result<Option<Vec<sqlx::mysql::MySqlRow>>, MySQLAccessorError> {
if self.conn.is_none() && !self.is_open_connection {
self.open_connection().await?;
}
check_conn_open!(self);
let map_fetch_row_err: fn(sqlx::Error) -> MySQLAccessorError = move |e| MySQLAccessorError { err_type: MySQLAccessorErrorType::SqlFetchRowError(e) };
let mut rows = sqlx::query(sql)
.fetch(self.conn.as_mut().unwrap());
let mut rst: Vec<MySqlRow> = Vec::new();
while let Some(row) = rows.try_next().await.map_err(map_fetch_row_err)? {
rst.push(row);
}
Ok(Some(rst))
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.