lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/language.rs
Xetera/ginkou-api
48e8cea435b477d9365dc736407159f00321b1b0
use std::fs::File; use std::io; use std::io::Write; use std::path::{Path, PathBuf}; use std::string::FromUtf8Error; extern crate dirs; #[macro_use] use rusqlite::params; use rusqlite::Connection; use structopt; use structopt::StructOpt; use mecab; use mecab::Tagger; const DAKUTEN_BYTES: [u8; 3] = [227, 128, 130]; const SQL_ADD_SENTENCE: &'static str = include_str!("sql/add_sentence.sql"); const SQL_ADD_WORD_JUNCTION: &'static str = include_str!("sql/add_word_junction.sql"); const SQL_ADD_WORD: &'static str = include_str!("sql/add_word.sql"); const SQL_ALL_WORD_SENTENCES: &'static str = include_str!("sql/all_word_sentences.sql"); const SQL_BEST_WORD_SENTENCES: &'static str = include_str!("sql/best_word_sentences.sql"); const SQL_SETUP: &'static str = include_str!("sql/setup.sql"); #[derive(Debug)] enum SentenceError { Utf8(FromUtf8Error), IO(io::Error), } impl From<FromUtf8Error> for SentenceError { fn from(err: FromUtf8Error) -> Self { SentenceError::Utf8(err) } } impl From<io::Error> for SentenceError { fn from(err: io::Error) -> Self { SentenceError::IO(err) } } struct Sentences<R> { bytes: io::Bytes<R>, done: bool, } impl<B: io::BufRead> Iterator for Sentences<B> { type Item = Result<String, SentenceError>; fn next(&mut self) -> Option<Self::Item> { if self.done { return None; } let mut buf = Vec::new(); let mut match_index = 0; while match_index < 3 { let byte = match self.bytes.next() { None => break, Some(Err(e)) => return Some(Err(e.into())), Some(Ok(b)) => b, }; buf.push(byte); if byte == DAKUTEN_BYTES[match_index] { match_index += 1; } else { match_index = 0; } } if buf.len() == 0 { self.done = true; return None; } let next = String::from_utf8(buf).map_err(SentenceError::from); Some(next.map(|x| x.replace(|x: char| x.is_whitespace(), ""))) } } fn sentences<R: io::BufRead>(reader: R) -> Sentences<R> { Sentences { bytes: reader.bytes(), done: false, } } fn create_tables(conn: &Connection) -> rusqlite::Result<()> { conn.execute_batch(SQL_SETUP)} pub fn conn_from_disk<P: AsRef<Path>>(path: P) -> rusqlite::Result<Connection> { let existed = path.as_ref().exists(); let conn = Connection::open(path)?; if !existed { create_tables(&conn)?; } Ok(conn) } fn conn_from_memory() -> rusqlite::Result<Connection> { let conn = Connection::open_in_memory()?; create_tables(&conn)?; Ok(conn) } fn add_sentence(conn: &Connection, sentence: &str) -> rusqlite::Result<u32> { conn.execute(SQL_ADD_SENTENCE, params![sentence])?; Ok(conn.last_insert_rowid() as u32) } fn add_word(conn: &Connection, word: &str, sentence_id: u32) -> rusqlite::Result<()> { conn.execute(SQL_ADD_WORD, params![word])?; conn.execute(SQL_ADD_WORD_JUNCTION, params![word, sentence_id])?; Ok(()) } pub fn matching_word(conn: &Connection, word: &str, all: bool) -> rusqlite::Result<Vec<String>> { let query = if all { SQL_ALL_WORD_SENTENCES } else { SQL_BEST_WORD_SENTENCES }; let mut stmt = conn.prepare_cached(query)?; let mut buffer = Vec::new(); let results = stmt.query_map(params![word], |row| row.get(0))?; for r in results { let s: String = r?; buffer.push(s); } Ok(buffer) } fn print_matching_words(conn: &Connection, word: &str, all: bool) -> rusqlite::Result<()> { let query = if all { SQL_ALL_WORD_SENTENCES } else { SQL_BEST_WORD_SENTENCES }; let mut stmt = conn.prepare_cached(query)?; let results = stmt.query_map(params![word], |row| row.get(0))?; for r in results { let r: String = r?; if let Err(e) = write!(io::stdout(), "{}\n", r) { if e.kind() != io::ErrorKind::BrokenPipe { panic!(e); } } } Ok(()) } fn consume_trimmed(conn: &Connection, trimmed: &str) -> rusqlite::Result<()> { let sentence_id = add_sentence(conn, trimmed)?; let mut tagger = Tagger::new(""); tagger.parse_nbest_init(trimmed); let mecab_out = tagger.next().unwrap(); for l in mecab_out.lines() { if l == "EOS" { break; } let tab_index = l.find('\t').unwrap(); let (_, rest) = l.split_at(tab_index); let rest = &rest[1..]; let root = rest.split(',').skip(6).next().unwrap(); add_word(conn, root, sentence_id)?; } Ok(()) } fn consume_sentences<R: io::BufRead>(conn: &Connection, reader: R) -> rusqlite::Result<()> { let mut i = 0; for sentence in sentences(reader) { i += 1; if sentence.is_err() { println!("Err on #{}: {:?}", i, sentence); continue; }; let sentence = sentence.unwrap(); println!("#{}: {}", i, sentence); consume_trimmed(conn, &sentence)?; } Ok(()) } #[derive(Debug, StructOpt)] #[structopt(name = "ginkou", about = "Japanese sentence bank")] enum Ginkou { #[structopt(name = "add")] Add { #[structopt(long, short = "f", parse(from_os_str))] file: Option<PathBuf>, #[structopt(long = "database", short = "d", parse(from_os_str))] db: Option<PathBuf>, }, #[structopt(name = "get")] Get { word: String, #[structopt(long = "allwords", short = "a")] all: bool, #[structopt(long = "database", short = "d", parse(from_os_str))] db: Option<PathBuf>, }, } fn default_db_path() -> PathBuf { if let Some(mut pb) = dirs::home_dir() { pb.push(".ginkoudb"); pb } else { PathBuf::from(".ginkoudb") } } fn main() { } #[cfg(test)] mod tests { use super::*; #[test] fn sentences_works_correctly() { let string = "A。\n B。\n\n XXC。"; let mut iter = sentences(std::io::BufReader::new(string.as_bytes())); let a = iter.next(); assert_eq!(String::from("A。"), a.unwrap().unwrap()); let b = iter.next(); assert_eq!(String::from("B。"), b.unwrap().unwrap()); let c = iter.next(); assert_eq!(String::from("XXC。"), c.unwrap().unwrap()); } #[test] fn bank_lookup_works_correctly() -> rusqlite::Result<()> { let conn = conn_from_memory()?; let sentence1 = String::from("A B"); let sentence2 = String::from("A B C"); let s1 = add_sentence(&conn, &sentence1)?; add_word(&conn, "A", s1)?; add_word(&conn, "B", s1)?; let s2 = add_sentence(&conn, &sentence2)?; add_word(&conn, "A", s2)?; add_word(&conn, "B", s2)?; add_word(&conn, "C", s2)?; let a_sentences = vec![sentence1.clone(), sentence2.clone()]; assert_eq!(Ok(a_sentences), matching_word(&conn, "A")); let c_sentences = vec![sentence2.clone()]; assert_eq!(Ok(c_sentences), matching_word(&conn, "C")); Ok(()) } #[test] fn sentences_can_be_consumed() -> rusqlite::Result<()> { let conn = conn_from_memory()?; let sentence1 = "猫を見た"; let sentence2 = "犬を見る"; consume_trimmed(&conn, sentence1)?; consume_trimmed(&conn, sentence2)?; let a_sentences = vec![sentence1.into(), sentence2.into()]; assert_eq!(Ok(a_sentences), matching_word(&conn, "見る")); let b_sentences = vec![sentence2.into()]; assert_eq!(Ok(b_sentences), matching_word(&conn, "犬")); let c_sentences = vec![sentence1.into()]; assert_eq!(Ok(c_sentences), matching_word(&conn, "猫")); Ok(()) } }
use std::fs::File; use std::io; use std::io::Write; use std::path::{Path, PathBuf}; use std::string::FromUtf8Error; extern crate dirs; #[macro_use] use rusqlite::params; use rusqlite::Connection; use structopt; use structopt::StructOpt; use mecab; use mecab::Tagger; const DAKUTEN_BYTES: [u8; 3] = [227, 128, 130]; const SQL_ADD_SENTENCE: &'static str = include_str!("sql/add_sentence.sql"); const SQL_ADD_WORD_JUNCTION: &'static str = include_str!("sql/add_word_junction.sql"); const SQL_ADD_WORD: &'static str = include_str!("sql/add_word.sql"); const SQL_ALL_WORD_SENTENCES: &'static str = include_str!("sql/all_word_sentences.sql"); const SQL_BEST_WORD_SENTENCES: &'static str = include_str!("sql/best_word_sentences.sql"); const SQL_SETUP: &'static str = include_str!("sql/setup.sql"); #[derive(Debug)] enum SentenceError { Utf8(FromUtf8Error), IO(io::Error), } impl From<FromUtf8Error> for SentenceError { fn from(err: FromUtf8Error) -> Self { SentenceError::Utf8(err) } } impl From<io::Error> for SentenceError { fn from(err: io::Error) -> Self { SentenceError::IO(err) } } struct Sentences<R> { bytes: io::Bytes<R>, done: bool, } impl<B: io::BufRead> Iterator for Sentences<B> { type Item = Result<String, SentenceError>; fn next(&mut self) -> Option<Self::Item> { if self.done { return None; } let mut buf = Vec::new(); let mut match_index = 0; while match_index < 3 { let byte = match self.bytes.next() { None => break, Some(Err(e)) => return Some(Err(e.into())), Some(Ok(b)) => b, }; buf.push(byte); if byte == DAKUTEN_BYTES[match_index] { match_index += 1; } else { match_index = 0; } } if buf.len() == 0 { self.done = true; return None; } let next = String::from_utf8(buf).map_err(SentenceError::from); Some(next.map(|x| x.replace(|x: char| x.is_whitespace(), ""))) } } fn sentences<R: io::BufRead>(reader: R) -> Sentences<R> { Sentences { bytes: reader.bytes(), done: false, } } fn create_tables(conn: &Connection) -> rusqlite::Result<()> { conn.execute_batch(SQL_SETUP)} pub fn conn_from_disk<P: AsRef<Path>>(path: P) -> rusqlite::Result<Connection> { let existed = path.as_ref().exists(); let conn = Connection::open(path)?; if !existed { create_tables(&conn)?; } Ok(conn) } fn conn_from_memory() -> rusqlite::Result<Connection> { let conn = Connection::open_in_memory()?; create_tables(&conn)?; Ok(conn) } fn add_sentence(conn: &Connection, sentence: &str) -> rusqlite::Result<u32> { conn.execute(SQL_ADD_SENTENCE, params![sentence])?; Ok(conn.last_insert_rowid() as u32) } fn add_word(conn: &Connection, word: &str, sentence_id: u32) -> rusqlite::Result<()> { conn.execute(SQL_ADD_WORD, params![word])?; conn.execute(SQL_ADD_WORD_JUNCTION, params![word, sentence_id])?; Ok(()) } pub fn matching_word(conn: &Connection, word: &str, all: bool) -> rusqlite::Result<Vec<String>> { let query = if all { SQL_ALL_WORD_SENTENCES } else { SQL_BEST_WORD_SENTENCES }; let mut stmt = conn.prepare_cached(query)?; let mut buffer = Vec::new(); let results = stmt.query_map(params![word], |row| row.get(0))?; for r in results { let s: String = r?; buffer.push(s); } Ok(buffer) } fn print_matching_words(conn: &Connection, word: &str, all: bool) -> rusqlite::Result<()> { let query = if all { SQL_ALL_WORD_SENTENCES } else { SQL_BEST_WORD_SENTENCES }; let mut stmt = conn.prepare_cached(query)?; let results = stmt.query_map(params![word], |row| row.get(0))?; for r in results { let r: String = r?; if let Err(e) = write!(io::stdout(), "{}\n", r) { if e.kind() != io::ErrorKind::BrokenPipe { panic!(e); } } } Ok(()) } fn consume_trimmed(conn: &Connection, trimmed: &str) -> rusqlite::Result<()> { let sentence_id = add_sentence(conn, trimmed)?; let mut tagger = Tagger::new(""); tagger.parse_nbest_init(trimmed); let mecab_out = tagger.next().unwrap(); for l in mecab_out.lines() { if l == "EOS" { break; } let tab_index = l.find('\t').unwrap(); let (_, rest) = l.split_at(tab_index); let rest = &rest[1..]; let root = rest.split(',').skip(6).next().unwrap(); add_word(conn, root, sentence_id)?; } Ok(()) } fn consume_sentences<R: io::BufRead>(conn: &Connection, reader: R) -> rusqlite::Result<()> { let mut i = 0; for sentence in sentences(reader) { i += 1; if sentence.is_err() { println!("Err on #{}: {:?}", i, sentence); continue; }; let sentence = sentence.unwrap(); println!("#{}: {}", i, sentence); consume_trimmed(conn, &sentence)?; } Ok(()) } #[derive(Debug, StructOpt)] #[structopt(name = "ginkou", about = "Japanese sentence bank")] enum Ginkou { #[structopt(name = "add")] Add { #[structopt(long, short = "f", parse(from_os_str))] file: Option<PathBuf>, #[structopt(long = "database", short = "d", parse(from_os_str))] db: Option<PathBuf>, }, #[structopt(name = "get")] Get { word: String, #[structopt(long = "allwords", short = "a")] all: bool, #[structopt(long = "database", short = "d", parse(from_os_str))] db: Option<PathBuf>, }, } fn default_db_path() -> PathBuf { if let Some(mut pb) = dirs::home_dir() { pb.push(".ginkoudb"); pb } else { PathBuf::from(".ginkoudb") } } fn main() { } #[cfg(test)] mod tests { use super::*; #[test] fn sentences_works_correctly() { let string = "A。\n B。\n\n XXC。"; let mut iter = sentences(std::io::BufReader::new(string.as_bytes())); let a = iter.next(); assert_eq!(String::from("A。"), a.unwrap().unwrap()); let b = iter.next(); assert_eq!(String::from("B。"), b.unwrap().unwrap()); let c = iter.next(); assert_eq!(String::from("XXC。"), c.unwrap().unwrap()); } #[test]
#[test] fn sentences_can_be_consumed() -> rusqlite::Result<()> { let conn = conn_from_memory()?; let sentence1 = "猫を見た"; let sentence2 = "犬を見る"; consume_trimmed(&conn, sentence1)?; consume_trimmed(&conn, sentence2)?; let a_sentences = vec![sentence1.into(), sentence2.into()]; assert_eq!(Ok(a_sentences), matching_word(&conn, "見る")); let b_sentences = vec![sentence2.into()]; assert_eq!(Ok(b_sentences), matching_word(&conn, "犬")); let c_sentences = vec![sentence1.into()]; assert_eq!(Ok(c_sentences), matching_word(&conn, "猫")); Ok(()) } }
fn bank_lookup_works_correctly() -> rusqlite::Result<()> { let conn = conn_from_memory()?; let sentence1 = String::from("A B"); let sentence2 = String::from("A B C"); let s1 = add_sentence(&conn, &sentence1)?; add_word(&conn, "A", s1)?; add_word(&conn, "B", s1)?; let s2 = add_sentence(&conn, &sentence2)?; add_word(&conn, "A", s2)?; add_word(&conn, "B", s2)?; add_word(&conn, "C", s2)?; let a_sentences = vec![sentence1.clone(), sentence2.clone()]; assert_eq!(Ok(a_sentences), matching_word(&conn, "A")); let c_sentences = vec![sentence2.clone()]; assert_eq!(Ok(c_sentences), matching_word(&conn, "C")); Ok(()) }
function_block-full_function
[ { "content": "SELECT id, ?2 FROM WORDS WHERE word=?1 AND NOT EXISTS (SELECT 1 FROM WordSentence WHERE word_id=id AND sentence_id=?2);", "file_path": "src/sql/add_word_junction.sql", "rank": 11, "score": 86279.24715323126 }, { "content": "fn main() {\n\n rocket::ignite().mount(\"/\", routes!...
Rust
corp_bot/src/main.rs
lholznagel/eve_online
7f8cc4aa46b06c0edf64f89ff5853216cf5597b7
mod asset; use appraisal::{Appraisal, Janice}; use caph_connector::{EveAuthClient, CorporationService}; use num_format::{Locale, ToFormattedString}; use reqwest::{header::{HeaderMap, HeaderValue}, Client}; use serde::Serialize; use sqlx::{PgPool, postgres::PgPoolOptions}; use tracing_subscriber::EnvFilter; const PG_ADDR: &str = "DATABASE_URL"; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { dotenv::dotenv().ok(); tracing_subscriber::fmt() .pretty() .with_env_filter(EnvFilter::from_default_env()) .init(); let pg_addr = std::env::var(PG_ADDR) .expect("Expected that a DATABASE_URL ENV is set"); let pool = PgPoolOptions::new() .max_connections(10) .connect(&pg_addr) .await?; let journal = journal(&pool).await; let asset_worth = assets(&pool).await; let wallet = wallets(&pool).await; let mut headers = HeaderMap::new(); headers.insert( "Authorization", HeaderValue::from_static("Bot OTgwMjQ1MTcyNzM2NjIyNjIy.Go7wtl.vSkXQMxjtHMZGqTM-s0MCrG5lChsGg0wIXlSAg") ); let client = Client::builder() .default_headers(headers) .build() .unwrap(); #[derive(Debug, Serialize)] struct Message { content: String, allowed_mentions: AllowedMentions } #[derive(Debug, Serialize)] struct AllowedMentions { parse: Vec<String>, } impl Default for AllowedMentions { fn default() -> Self { Self { parse: vec!["users".into(), "roles".into()] } } } client.post( "https://discord.com/api/v10/channels/980171856768270387/messages" ) .json(&Message { content: format!(r#" <@318403897972621312> Ungefährerer derzeitiger Wert der Corp wallets + Assets. ``` Master Wallet {} ISK Moon Taxes {} ISK Alliance Taxes {} ISK Assets: {} ISK Total {} ISK ``` "#, (wallet.master as u64).to_formatted_string(&Locale::de), (wallet.moon as u64).to_formatted_string(&Locale::de), (wallet.alliance as u64).to_formatted_string(&Locale::de), (asset_worth as u64).to_formatted_string(&Locale::de), ((wallet.master + wallet.moon + wallet.moon + asset_worth) as u64).to_formatted_string(&Locale::de) ), allowed_mentions: AllowedMentions::default() }) .send() .await .unwrap() .text() .await .unwrap(); Ok(()) } async fn assets(pool: &PgPool) -> f32 { let info = sqlx::query!(r#" SELECT c.corporation_id AS "corporation_id!", l.refresh_token AS "refresh_token!" FROM characters c JOIN logins l ON l.character_id = c.character_id WHERE 'esi-assets.read_corporation_assets.v1' = ANY(esi_tokens) AND c.corporation_name = 'Rip0ff Industries' AND l.refresh_token IS NOT NULL AND c.corporation_id IS NOT NULL "# ) .fetch_one(pool) .await .unwrap(); let client = EveAuthClient::new(info.refresh_token).unwrap(); let corporation_service = CorporationService::new(info.corporation_id.into()); let assets = corporation_service .assets(&client) .await .unwrap() .into_iter() .filter(|x| !x.is_blueprint_copy) .collect::<Vec<_>>(); let mut entries = Vec::new(); for asset in assets { let name = sqlx::query!(" SELECT name FROM items WHERE type_id = $1 ", *asset.type_id ) .fetch_one(pool) .await .unwrap() .name; entries.push(format!("{} {}", name, asset.quantity)); } Janice::validate().unwrap(); let janice = Janice::init().unwrap(); janice .create(false, entries) .await .unwrap() .sell_price } async fn journal(pool: &PgPool) { let info = sqlx::query!(r#" SELECT c.corporation_id AS "corporation_id!", l.refresh_token AS "refresh_token!" FROM characters c JOIN logins l ON l.character_id = c.character_id WHERE 'esi-assets.read_corporation_assets.v1' = ANY(esi_tokens) AND c.corporation_name = 'Rip0ff Industries' AND l.refresh_token IS NOT NULL AND c.corporation_id IS NOT NULL "# ) .fetch_one(pool) .await .unwrap(); let client = EveAuthClient::new(info.refresh_token).unwrap(); let corporation_service = CorporationService::new(info.corporation_id.into()); let journal = corporation_service .wallet_journal(&client) .await .unwrap(); dbg!(journal); } async fn wallets(pool: &PgPool) -> Wallets { let info = sqlx::query!(r#" SELECT c.corporation_id AS "corporation_id!", l.refresh_token AS "refresh_token!" FROM characters c JOIN logins l ON l.character_id = c.character_id WHERE 'esi-assets.read_corporation_assets.v1' = ANY(esi_tokens) AND c.corporation_name = 'Rip0ff Industries' AND l.refresh_token IS NOT NULL AND c.corporation_id IS NOT NULL "# ) .fetch_one(pool) .await .unwrap(); let client = EveAuthClient::new(info.refresh_token).unwrap(); let corporation_service = CorporationService::new(info.corporation_id.into()); let wallets = corporation_service .wallets(&client) .await .unwrap(); Wallets { master: wallets[0].balance, moon: wallets[1].balance, alliance: wallets[2].balance, } } struct Wallets { master: f32, moon: f32, alliance: f32, }
mod asset; use appraisal::{Appraisal, Janice}; use caph_connector::{EveAuthClient, CorporationService}; use num_format::{Locale, ToFormattedString}; use reqwest::{header::{HeaderMap, HeaderValue}, Client}; use serde::Serialize; use sqlx::{PgPool, postgres::PgPoolOptions}; use tracing_subscriber::EnvFilter; const PG_ADDR: &str = "DATABASE_URL"; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { dotenv::dotenv().ok(); tracing_subscriber::fmt() .pretty() .with_env_filter(EnvFilter::from_default_env()) .init(); let pg_addr = std::env::var(PG_ADDR) .expect("Expected that a DATABASE_URL ENV is set"); let pool = PgPoolOptions::new() .max_connections(10) .connect(&pg_addr) .await?; let journal = journal(&pool).await; let asset_worth = assets(&pool).await; let wallet = wallets(&pool).await; let mut headers = HeaderMap::new(); headers.insert( "Authorization", HeaderValue::from_static("Bot OTgwMjQ1MTcyNzM2NjIyNjIy.Go7wtl.vSkXQMxjtHMZGqTM-s0MCrG5lChsGg0wIXlSAg") ); let client = Client::builder() .default_headers(headers) .build() .unwrap(); #[derive(Debug, Serialize)] struct Message { content: String, allowed_mentions: AllowedMentions } #[derive(Debug, Serialize)] struct AllowedMentions { parse: Vec<String>, } impl Default for AllowedMentions { fn default() -> Self { Self { parse: vec!["users".into(), "roles".into()] } } } client.post( "https://discord.com/api/v10/channels/980171856768270387/messages" ) .json(&Message { content: format!(r#" <@318403897972621312> Ungefährerer derzeitiger Wert der Corp wallets + Assets. ``` Master Wallet {} ISK Moon Taxes {} ISK Alliance Taxes {} ISK Assets: {} ISK Total {} ISK ``` "#, (wallet.master as u64).to_formatted_string(&Locale::de), (wallet.moon as u64).to_formatted_string(&Locale::de), (wallet.alliance as u64).to_formatted_string(&Locale::de), (asset_worth as u64).to_formatted_string(&Locale::de), ((wallet.master + wallet.moon + wallet.moon + asset_worth) as u64).to_formatted_string(&Locale::de) ), allowed_mentions: AllowedMentions::default() }) .send() .await .unwrap() .text() .await .unwrap(); Ok(()) } async fn assets(pool: &PgPool) -> f32 { let info = sqlx::query!(r#" SELECT c.corporation_id AS "corporation_id!", l.refresh_token AS "refresh_token!" FROM characters c JOIN logins l ON l.character_id = c.character_id WHERE 'esi-assets.read_corporation_assets.v1' = ANY(esi_tokens) AND c.corporation_name = 'Rip0ff Industries' AND l.refresh_token IS NOT NULL AND c.corporation_id IS NOT NULL "# ) .fetch_one(pool) .await .unwrap(); let client = EveAuthClient::new(info.refresh_token).unwrap(); let corporation_service = CorporationService::new(info.corporation_id.into()); let assets = corporation_service .assets(&client) .await .unwrap() .into_iter() .filter(|x| !x.is_blueprint_copy) .collect::<Vec<_>>(); let mut entries = Vec::new(); for asset in assets { let name = sqlx::query!(" SELECT name FROM items WHERE type_id = $1 ", *asset.type_id ) .fetch_one(pool) .await .unwrap() .name; entries.push(format!("{} {}", name, asset.quantity)); } Janice::validate().unwrap(); let janice = Janice::init().unwrap(); janice .create(false, entries) .await .unwrap() .sell_price } async fn journal(pool: &PgPool) { let info = sqlx::query!(r#" SELECT c.corporation_id AS "corporation_id!", l.refresh_token AS "refresh_token!" FROM characters c JOIN logins l ON l.character_id = c.character_id WHERE 'esi-assets.read_corporation_assets.v1' = ANY(esi_tokens) AND c.corporation_name = 'Rip0ff Industries' AND l.refresh_token IS NOT NULL AND c.corporation_id IS NOT NULL "# ) .fetch_one(pool) .await .unwrap(); let client = EveAuthClient::new(info.refresh_token).unwrap(); let corporation_service = CorporationService::new(info.corporation_id.into()); let journal = corporation_service .wallet_journal(&client) .await .unwrap(); dbg!(journal); } async fn wallets(pool: &PgPool) -> Wallets { let info = sqlx::query!(r#" SELECT c.corporation_id AS "corporation_id!", l.refresh_token AS "refresh_token!" FROM characters c JOIN logins l ON l.character_id = c.character_id WHERE 'esi-assets.read_corporation_assets.v1' = ANY(esi_tokens) AND c.corporation_name = 'Rip0ff Industries' AND l.refresh_t
ration_service = CorporationService::new(info.corporation_id.into()); let wallets = corporation_service .wallets(&client) .await .unwrap(); Wallets { master: wallets[0].balance, moon: wallets[1].balance, alliance: wallets[2].balance, } } struct Wallets { master: f32, moon: f32, alliance: f32, }
oken IS NOT NULL AND c.corporation_id IS NOT NULL "# ) .fetch_one(pool) .await .unwrap(); let client = EveAuthClient::new(info.refresh_token).unwrap(); let corpo
function_block-random_span
[ { "content": "/// Generates the basic SQL-Query that is required for items.\n\n///\n\n/// # Returns\n\n///\n\n/// String containing the SQL-Query.\n\n///\n\nfn sql_header() -> String {\n\n r#\"DELETE FROM items CASCADE;\"#.into()\n\n}\n\n\n", "file_path": "sde_parser/src/items.rs", "rank": 1, "sc...
Rust
sdk/src/system_transaction.rs
sunnygleason/solana
1fb9ed98372dfaf8f9a6691e7ec6d5bc5577bd2a
use crate::hash::Hash; use crate::pubkey::Pubkey; use crate::signature::Keypair; use crate::system_instruction::SystemInstruction; use crate::system_program; use crate::transaction::{Instruction, Transaction}; pub struct SystemTransaction {} impl SystemTransaction { pub fn new_program_account( from_keypair: &Keypair, to: Pubkey, last_id: Hash, tokens: u64, space: u64, program_id: Pubkey, fee: u64, ) -> Transaction { let create = SystemInstruction::CreateAccount { tokens, space, program_id, }; Transaction::new( from_keypair, &[to], system_program::id(), &create, last_id, fee, ) } pub fn new_account( from_keypair: &Keypair, to: Pubkey, tokens: u64, last_id: Hash, fee: u64, ) -> Transaction { let program_id = system_program::id(); Self::new_program_account(from_keypair, to, last_id, tokens, 0, program_id, fee) } pub fn new_assign( from_keypair: &Keypair, last_id: Hash, program_id: Pubkey, fee: u64, ) -> Transaction { let assign = SystemInstruction::Assign { program_id }; Transaction::new( from_keypair, &[], system_program::id(), &assign, last_id, fee, ) } pub fn new_move( from_keypair: &Keypair, to: Pubkey, tokens: u64, last_id: Hash, fee: u64, ) -> Transaction { let move_tokens = SystemInstruction::Move { tokens }; Transaction::new( from_keypair, &[to], system_program::id(), &move_tokens, last_id, fee, ) } pub fn new_move_many( from: &Keypair, moves: &[(Pubkey, u64)], last_id: Hash, fee: u64, ) -> Transaction { let instructions: Vec<_> = moves .iter() .enumerate() .map(|(i, (_, amount))| { let spend = SystemInstruction::Move { tokens: *amount }; Instruction::new(0, &spend, vec![0, i as u8 + 1]) }) .collect(); let to_keys: Vec<_> = moves.iter().map(|(to_key, _)| *to_key).collect(); Transaction::new_with_instructions( &[from], &to_keys, last_id, fee, vec![system_program::id()], instructions, ) } pub fn new_spawn(from_keypair: &Keypair, last_id: Hash, fee: u64) -> Transaction { let spawn = SystemInstruction::Spawn; Transaction::new( from_keypair, &[], system_program::id(), &spawn, last_id, fee, ) } } #[cfg(test)] mod tests { use super::*; use crate::signature::KeypairUtil; #[test] fn test_move_many() { let from = Keypair::new(); let t1 = Keypair::new(); let t2 = Keypair::new(); let moves = vec![(t1.pubkey(), 1), (t2.pubkey(), 2)]; let tx = SystemTransaction::new_move_many(&from, &moves, Hash::default(), 0); assert_eq!(tx.account_keys[0], from.pubkey()); assert_eq!(tx.account_keys[1], t1.pubkey()); assert_eq!(tx.account_keys[2], t2.pubkey()); assert_eq!(tx.instructions.len(), 2); assert_eq!(tx.instructions[0].accounts, vec![0, 1]); assert_eq!(tx.instructions[1].accounts, vec![0, 2]); } }
use crate::hash::Hash; use crate::pubkey::Pubkey; use crate::signature::Keypair; use crate::system_instruction::SystemInstruction; use crate::system_program; use crate::transaction::{Instruction, Transaction}; pub struct SystemTransaction {} impl SystemTransaction { pub fn new_program_account( from_keypair: &Keypair, to: Pubkey, last_id: Hash, tokens: u64, space: u64, program_id: Pubkey, fee: u64, ) -> Transaction { let create = SystemInstruction::CreateAccount { tokens, space, program_id, }; Transaction::new( from_keypair, &[to], system_program::id(), &create, last_id, fee, ) } pub fn new_account( from_keypair: &Keypair, to: Pubkey, tokens: u64, last_id: Hash, fee: u64, ) -> Transaction { let program_id = system_program::id(); Self::new_program_account(from_keypair, to, last_id, tokens, 0, program_id, fee) } pub fn new_assign( from_keypair: &Keypair, last_id: Hash, program_id: Pubkey, fee: u64, ) -> Transaction { let assign = SystemInstruction::Assign { program_id }; Transaction::new( from_keypair, &[], system_program::id(), &assign, last_id, fee, ) } pub fn new_move( from_keypair: &Keypair, to: Pubkey, tokens: u64,
pub fn new_move_many( from: &Keypair, moves: &[(Pubkey, u64)], last_id: Hash, fee: u64, ) -> Transaction { let instructions: Vec<_> = moves .iter() .enumerate() .map(|(i, (_, amount))| { let spend = SystemInstruction::Move { tokens: *amount }; Instruction::new(0, &spend, vec![0, i as u8 + 1]) }) .collect(); let to_keys: Vec<_> = moves.iter().map(|(to_key, _)| *to_key).collect(); Transaction::new_with_instructions( &[from], &to_keys, last_id, fee, vec![system_program::id()], instructions, ) } pub fn new_spawn(from_keypair: &Keypair, last_id: Hash, fee: u64) -> Transaction { let spawn = SystemInstruction::Spawn; Transaction::new( from_keypair, &[], system_program::id(), &spawn, last_id, fee, ) } } #[cfg(test)] mod tests { use super::*; use crate::signature::KeypairUtil; #[test] fn test_move_many() { let from = Keypair::new(); let t1 = Keypair::new(); let t2 = Keypair::new(); let moves = vec![(t1.pubkey(), 1), (t2.pubkey(), 2)]; let tx = SystemTransaction::new_move_many(&from, &moves, Hash::default(), 0); assert_eq!(tx.account_keys[0], from.pubkey()); assert_eq!(tx.account_keys[1], t1.pubkey()); assert_eq!(tx.account_keys[2], t2.pubkey()); assert_eq!(tx.instructions.len(), 2); assert_eq!(tx.instructions[0].accounts, vec![0, 1]); assert_eq!(tx.instructions[1].accounts, vec![0, 2]); } }
last_id: Hash, fee: u64, ) -> Transaction { let move_tokens = SystemInstruction::Move { tokens }; Transaction::new( from_keypair, &[to], system_program::id(), &move_tokens, last_id, fee, ) }
function_block-function_prefix_line
[ { "content": "pub fn create_ticks(num_ticks: u64, mut hash: Hash) -> Vec<Entry> {\n\n let mut ticks = Vec::with_capacity(num_ticks as usize);\n\n for _ in 0..num_ticks {\n\n let new_tick = next_entry_mut(&mut hash, 1, vec![]);\n\n ticks.push(new_tick);\n\n }\n\n\n\n ticks\n\n}\n\n\n", ...
Rust
kvserver/src/server.rs
GITHUBear/KV_Server
a3532a91f50604c6d757891ceed0f457a34f2afd
extern crate protobuf; extern crate futures; extern crate grpcio; pub mod kvprotos; use std::io::Read; use std::sync::{Arc, RwLock}; use std::{io, thread}; use std::collections::{BTreeMap, HashMap}; use futures::sync::oneshot; use futures::Future; use grpcio::{Environment, RpcContext, ServerBuilder, UnarySink}; use kvprotos::kvserver::{ResponseStatus, GetRequest, GetResponse, PutRequest, PutResponse, DeleteRequest, DeleteResponse, ScanRequest, ScanResponse}; use kvprotos::kvserver_grpc::{self, Kvdb}; #[derive(Clone)] struct KvService{ engine: Arc<RwLock<BTreeMap<String,String>>>, } impl KvService { pub fn new() -> Self { println!("new KvService"); KvService{ engine: Arc::new(RwLock::new(BTreeMap::new())), } } } impl Kvdb for KvService { fn get(&mut self, ctx: RpcContext, req: GetRequest, sink: UnarySink<GetResponse>) { let mut response = GetResponse::new(); println!("Received GetRequest {{ {:?} }}", req); let mutengine = &self.engine; let req_key = &req.key; let tmp = mutengine.read().unwrap(); let res = tmp.get(req_key); println!("====>getcheck {:?}", self.engine); match res { Some(s) => { response.set_status(ResponseStatus::kSuccess); response.set_value(s.clone()); }, None => response.set_status(ResponseStatus::kNotFound), } let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response)) .map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } fn put(&mut self, ctx: RpcContext, req: PutRequest, sink: UnarySink<PutResponse>){ let mut response = PutResponse::new(); println!("Received PutRequest {{ {:?} }}", req); let mutengine = &mut self.engine; let req_key = &req.key; let req_val = &req.value; let _res = mutengine.write().unwrap().insert(req_key.clone(), req_val.clone()); println!("====>putcheck {:?}", self.engine); response.set_status(ResponseStatus::kSuccess); let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response)) .map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } fn delete(&mut self, ctx: RpcContext, req: DeleteRequest, sink: UnarySink<DeleteResponse>){ let mut response = DeleteResponse::new(); println!("Received DeleteRequest {{ {:?} }}", req); let mutengine = &mut self.engine; let req_key = &req.key; let res = mutengine.write().unwrap().remove(req_key); match res { Some(_) => response.set_status(ResponseStatus::kSuccess), None => response.set_status(ResponseStatus::kNotFound), } let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response)) .map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } fn scan(&mut self, ctx: RpcContext, req: ScanRequest, sink: UnarySink<ScanResponse>){ let mut response = ScanResponse::new(); println!("Received ScanRequest {{ {:?} }}", req); let mutengine = &self.engine; let key_start = &req.key_start; let key_end = &req.key_end; let mut resmap = HashMap::new(); for (k, v) in mutengine.read().unwrap().range(key_start.clone()..key_end.clone()){ resmap.insert(k.clone(), v.clone()); } if resmap.len() != 0 { response.set_status(ResponseStatus::kSuccess); response.set_key_value(resmap); }else{ response.set_status(ResponseStatus::kNotFound); } let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response)) .map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } } fn main(){ let env = Arc::new(Environment::new(1)); let service = kvserver_grpc::create_kvdb(KvService::new()); let mut server = ServerBuilder::new(env) .register_service(service) .bind("127.0.0.1", 20001) .build() .unwrap(); server.start(); let (tx, rx) = oneshot::channel(); thread::spawn(move || { println!("Press ENTER to exit..."); let _ = io::stdin().read(&mut [0]).unwrap(); tx.send(()) }); let _ = rx.wait(); let _ = server.shutdown().wait(); }
extern crate protobuf; extern crate futures; extern crate grpcio; pub mod kvprotos; use std::io::Read; use std::sync::{Arc, RwLock}; use std::{io, thread}; use std::collections::{BTreeMap, HashMap}; use futures::sync::oneshot; use futures::Future; use grpcio::{Environment, RpcContext, ServerBuilder, UnarySink}; use kvprotos::kvserver::{ResponseStatus, GetRequest, GetResponse, PutRequest, PutResponse, DeleteRequest, DeleteResponse, ScanRequest, ScanResponse}; use kvprotos::kvserver_grpc::{self, Kvdb}; #[derive(Clone)] struct KvService{ engine: Arc<RwLock<BTreeMap<String,String>>>, } impl KvService { pub fn new() -> Self { println!("new KvService"); KvService{ engine: Arc::new(RwLock::new(BTreeMap::new())), } } } impl Kvdb for KvService { fn get(&mut self, ctx: RpcContext, req: GetRequest, sink: UnarySink<GetResponse>) { let mut response = GetResponse::new(); println!("Received GetRequest {{ {:?} }}", req); let mutengine = &self.engine; let req_key = &req.key; let tmp = mutengine.read().unwrap(); let res = tmp.get(req_key); println!("====>getcheck {:?}", self.engine); match res { Some(s) => { response.set_status(ResponseStatus::kSuccess); response.set_value(s.clone()); }, None => response.set_status(ResponseStatus::kNotFound), } let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response))
:new(); for (k, v) in mutengine.read().unwrap().range(key_start.clone()..key_end.clone()){ resmap.insert(k.clone(), v.clone()); } if resmap.len() != 0 { response.set_status(ResponseStatus::kSuccess); response.set_key_value(resmap); }else{ response.set_status(ResponseStatus::kNotFound); } let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response)) .map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } } fn main(){ let env = Arc::new(Environment::new(1)); let service = kvserver_grpc::create_kvdb(KvService::new()); let mut server = ServerBuilder::new(env) .register_service(service) .bind("127.0.0.1", 20001) .build() .unwrap(); server.start(); let (tx, rx) = oneshot::channel(); thread::spawn(move || { println!("Press ENTER to exit..."); let _ = io::stdin().read(&mut [0]).unwrap(); tx.send(()) }); let _ = rx.wait(); let _ = server.shutdown().wait(); }
.map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } fn put(&mut self, ctx: RpcContext, req: PutRequest, sink: UnarySink<PutResponse>){ let mut response = PutResponse::new(); println!("Received PutRequest {{ {:?} }}", req); let mutengine = &mut self.engine; let req_key = &req.key; let req_val = &req.value; let _res = mutengine.write().unwrap().insert(req_key.clone(), req_val.clone()); println!("====>putcheck {:?}", self.engine); response.set_status(ResponseStatus::kSuccess); let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response)) .map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } fn delete(&mut self, ctx: RpcContext, req: DeleteRequest, sink: UnarySink<DeleteResponse>){ let mut response = DeleteResponse::new(); println!("Received DeleteRequest {{ {:?} }}", req); let mutengine = &mut self.engine; let req_key = &req.key; let res = mutengine.write().unwrap().remove(req_key); match res { Some(_) => response.set_status(ResponseStatus::kSuccess), None => response.set_status(ResponseStatus::kNotFound), } let f = sink.success(response.clone()) .map(move |_| println!("Responded with {{ {:?} }}", response)) .map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } fn scan(&mut self, ctx: RpcContext, req: ScanRequest, sink: UnarySink<ScanResponse>){ let mut response = ScanResponse::new(); println!("Received ScanRequest {{ {:?} }}", req); let mutengine = &self.engine; let key_start = &req.key_start; let key_end = &req.key_end; let mut resmap = HashMap:
random
[ { "content": "pub fn create_kvdb<S: Kvdb + Send + Clone + 'static>(s: S) -> ::grpcio::Service {\n\n let mut builder = ::grpcio::ServiceBuilder::new();\n\n let mut instance = s.clone();\n\n builder = builder.add_unary_handler(&METHOD_KVDB_GET, move |ctx, req, resp| {\n\n instance.get(ctx, req, re...
Rust
src/main.rs
rodneylab/cmessless
7ba78963aea19b3618c60215a55745207195960f
mod parser; mod utility; use atty::{is, Stream}; use clap::Parser; use std::{ fs, io::{self, BufRead}, path::{Path, PathBuf}, }; use watchexec::{ config::{Config, ConfigBuilder}, error::Result, pathop::PathOp, run::{watch, ExecHandler, Handler}, }; use parser::{author_name_from_cargo_pkg_authors, parse_mdx_file}; #[derive(Parser)] #[clap(author,version,about,long_about=None)] struct Cli { path: Vec<PathBuf>, #[clap(short, long)] check: bool, #[clap(short, long)] modified: bool, #[clap(short = 'R', long)] relative: bool, #[clap(short, long)] verbose: bool, #[clap(short = 'V', long)] version: bool, #[clap(short, long)] watch: bool, #[clap(parse(from_os_str))] #[clap(short, long)] output: std::path::PathBuf, } fn get_title() -> String { let mut the_title = String::from(env!("CARGO_PKG_NAME")); the_title.push_str(" (v"); the_title.push_str(env!("CARGO_PKG_VERSION")); the_title.push_str("), "); the_title.push_str(env!("CARGO_PKG_DESCRIPTION")); the_title } fn print_short_banner() { println!("{}", get_title()); } fn print_long_banner() { print_short_banner(); println!( "Written by: {}", author_name_from_cargo_pkg_authors().trim() ); println!("Repo: {}", env!("CARGO_PKG_REPOSITORY")); println!("Usage: {} <somefile>.mdx", env!("CARGO_PKG_NAME")); println!(" {} --watch <somefile>.mdx", env!("CARGO_PKG_NAME")); } struct CmslessHandler(ExecHandler); impl Handler for CmslessHandler { fn args(&self) -> Config { self.0.args() } fn on_manual(&self) -> Result<bool> { println!("[ INFO ] Running manually..."); self.0.on_manual() } fn on_update(&self, ops: &[PathOp]) -> Result<bool> { println!("[ INFO ] Running manually {:?}...", ops); self.0.on_update(ops) } } fn parse_then_watch(mdx_paths: &[PathBuf], output_path: &Path, verbose: bool) -> Result<()> { let output_path_str = output_path.to_string_lossy(); let mut command: Vec<String> = vec!["cmessless".into()]; command.extend(mdx_paths.iter().map(|value| value.to_string_lossy().into())); command.push("--check --output".into()); command.push(output_path.to_string_lossy().into()); command.push("| cmessless --relative".into()); if verbose { command.push("--verbose".into()); } command.push(" --output".into()); command.push(output_path_str.into()); let config = ConfigBuilder::default() .clear_screen(true) .run_initially(true) .paths(mdx_paths) .cmd(command) .build() .expect("[ ERROR ] Issue while configuring watchexec"); let handler = CmslessHandler( ExecHandler::new(config).expect("[ ERROR ] Issue while creating watchexec handler"), ); watch(&handler) } fn relative_output_path_from_input(input_path: &Path, relative_output_path: &Path) -> PathBuf { match input_path.to_string_lossy().find("/./") { Some(_) => {} None => panic!( "[ ERROR ] Using relative mode: check input paths include a \"/./\" marker to separate \ root and relative parts." ), } let mut components = input_path.components(); loop { if components.as_path().to_string_lossy().find("/./") == None { break; } components.next(); } let mut result = PathBuf::new(); result.push(relative_output_path); let tail = components.as_path(); let mut output_file_name = String::from(tail.file_stem().unwrap().to_string_lossy()); output_file_name.push_str(".astro"); relative_output_path .join(tail.parent().unwrap()) .join(PathBuf::from(output_file_name)) } fn check_modified_files(mdx_paths: &[PathBuf], relative_output_path: &Path) { let mut modified_files: Vec<String> = Vec::new(); for input_path in mdx_paths { let output_path = relative_output_path_from_input(input_path.as_path(), relative_output_path); let input_modified = match fs::metadata(input_path).unwrap().modified() { Ok(value) => Some(value), Err(_) => None, }; let output_modified = match fs::metadata(output_path) { Ok(metadata_value) => match metadata_value.modified() { Ok(value) => Some(value), Err(_) => None, }, Err(_) => None, }; if output_modified == None || input_modified == None || input_modified.unwrap() > output_modified.unwrap() { modified_files.push(String::from(input_path.to_string_lossy())); } } println!("{}", modified_files.join(" ")); } fn parse_multiple_files(mdx_paths: &[PathBuf], relative_output_path: &Path, verbose: bool) { for input_path in mdx_paths { let output_path = relative_output_path_from_input(input_path.as_path(), relative_output_path); parse_mdx_file(input_path.as_path(), output_path.as_path(), verbose); } println!("\n[ INFO ] {} files parsed.", mdx_paths.len()); } fn get_piped_input() -> Vec<PathBuf> { let mut buffer = String::new(); let stdin = io::stdin(); let mut handle = stdin.lock(); handle.read_line(&mut buffer).unwrap_or(0); let result = buffer[..buffer.len() - 1] .split(' ') .map(PathBuf::from) .collect(); result } fn main() -> Result<()> { let cli = &Cli::parse(); if cli.check { check_modified_files(&cli.path, &cli.output); return Ok(()); } let inputs = if is(Stream::Stdin) { cli.path.to_vec() } else { get_piped_input() }; if inputs.is_empty() { return Ok(()); } if cli.verbose { print_long_banner(); } else { print_short_banner(); } if cli.version { println!("{}", get_title()); return Ok(()); } if cli.watch { return parse_then_watch(&inputs, cli.output.as_path(), cli.verbose); } else if cli.path.len() > 1 { if !cli.relative { println!( "\n[ ERROR ] for multiple inputs, use the --relative flag to set a relative output path." ); } parse_multiple_files(&inputs, &cli.output, cli.verbose); } else if cli.relative { let output_path = relative_output_path_from_input(inputs[0].as_path(), &cli.output); parse_mdx_file(inputs[0].as_path(), &output_path, cli.verbose); } else { parse_mdx_file(inputs[0].as_path(), cli.output.as_path(), cli.verbose); } Ok(()) } #[cfg(test)] mod tests { use crate::relative_output_path_from_input; use std::path::PathBuf; #[test] pub fn test_relative_output_path_from_input() { let input_path = PathBuf::from("local/files/input/./day-one/morning.txt"); let relative_output_path = PathBuf::from("local/files/output"); assert_eq!( relative_output_path_from_input(input_path.as_path(), relative_output_path.as_path()), PathBuf::from("local/files/output/day-one/morning.astro") ); } #[test] #[should_panic( expected = "[ ERROR ] Using relative mode: check input paths include a \"/./\" \ marker to separate root and relative parts." )] pub fn test_relative_output_path_from_input_panic() { let input_path = PathBuf::from("local/files/input/day-one/morning.mdx"); let relative_output_path = PathBuf::from("local/files/output"); assert_eq!( relative_output_path_from_input(input_path.as_path(), relative_output_path.as_path()), PathBuf::from("local/files/output/day-one/morning.astro") ); } }
mod parser; mod utility; use atty::{is, Stream}; use clap::Parser; use std::{ fs, io::{self, BufRead}, path::{Path, PathBuf}, }; use watchexec::{ config::{Config, ConfigBuilder}, error::Result, pathop::PathOp, run::{watch, ExecHandler, Handler}, }; use parser::{author_name_from_cargo_pkg_authors, parse_mdx_file}; #[derive(Parser)] #[clap(author,version,about,long_about=None)] struct Cli { path: Vec<PathBuf>, #[clap(short, long)] check: bool, #[clap(short, long)] modified: bool, #[clap(short = 'R', long)] relative: bool, #[clap(short, long)] verbose: bool, #[clap(short = 'V', long)] version: bool, #[clap(short, long)] watch: bool, #[clap(parse(from_os_str))] #[clap(short, long)] output: std::path::PathBuf, } fn get_title() -> String { let mut the_title = String::from(env!("CARGO_PKG_NAME")); the_title.push_str(" (v"); the_title.push_str(env!("CARGO_PKG_VERSION")); the_title.push_str("), "); the_title.push_str(env!("CARGO_PKG_DESCRIPTION")); the_title } fn print_short_banner() { println!("{}", get_title()); } fn print_long_banner() { print_short_banner(); println!( "Written by: {}", author_name_from_cargo_pkg_authors().trim() ); println!("Repo: {}", env!("CARGO_PKG_REPOSITORY")); println!("Usage: {} <somefile>.mdx", env!("CARGO_PKG_NAME")); println!(" {} --watch <somefile>.mdx", env!("CARGO_PKG_NAME")); } struct CmslessHandler(ExecHandler); impl Handler for CmslessHandler { fn args(&self) -> Config { self.0.args() } fn on_manual(&self) -> Result<bool> { println!("[ INFO ] Running manually..."); self.0.on_manual() } fn on_update(&self, ops: &[PathOp]) -> Result<bool> { println!("[ INFO ] Running manually {:?}...", ops); self.0.on_update(ops) } } fn parse_then_watch(mdx_paths: &[PathBuf], output_path: &Path, verbose: bool) -> Result<()> { let output_path_str = output_path.to_string_lossy(); let mut command: Vec<String> = vec!["cmessless".into()]; command.extend(mdx_paths.iter().map(|value| value.to_string_lossy().into())); command.push("--check --output".into()); command.push(output_path.to_string_lossy().into()); command.push("| cmessless --relative".into()); if verbose { command.push("--verbose".into()); } command.push(" --output".into()); command.push(output_path_str.into()); let config = ConfigBuilder::default() .clear_screen(true) .run_initially(true) .paths(mdx_paths) .cmd(command) .build() .expect("[ ERROR ] Issue while configuring watchexec"); let handler = CmslessHandler( ExecHandler::new(config).expect("[ ERROR ] Issue while creating watchexec handler"), ); watch(&handler) } fn relative_output_path_from_input(input_path: &Path, relative_output_path: &Path) -> PathBuf { match input_path.to_string_lossy().find("/./") { Some(_) => {} None => panic!( "[ ERROR ] Using relative mode: check input paths include a \"/./\" marker to separate \ root and relative parts." ), } let mut components = input_path.components(); loop { if components.as_path().to_string_lossy().find("/./") == None { break; } components.next(); } let mut result = PathBuf::new(); result.push(relative_output_path); let tail = components.as_path(); let mut output_file_name = String::from(tail.file_stem().unwrap().to_string_lossy()); output_file_name.push_str(".astro"); relative_output_path .join(tail.parent().unwrap()) .join(PathBuf::from(output_file_name)) } fn check_modified_files(mdx_paths: &[PathBuf], relative_output_path: &Path) { let mut modified_files: Vec<String> = Vec::new(); for input_path in mdx_paths { let output_path = relative_output_path_from_input(input_path.as_path(), relative_output_path); let input_modified = match fs::metadata(input_path).unwrap().modified() { Ok(value) => Some(value), Err(_) => None, }; let output_modified =
; if output_modified == None || input_modified == None || input_modified.unwrap() > output_modified.unwrap() { modified_files.push(String::from(input_path.to_string_lossy())); } } println!("{}", modified_files.join(" ")); } fn parse_multiple_files(mdx_paths: &[PathBuf], relative_output_path: &Path, verbose: bool) { for input_path in mdx_paths { let output_path = relative_output_path_from_input(input_path.as_path(), relative_output_path); parse_mdx_file(input_path.as_path(), output_path.as_path(), verbose); } println!("\n[ INFO ] {} files parsed.", mdx_paths.len()); } fn get_piped_input() -> Vec<PathBuf> { let mut buffer = String::new(); let stdin = io::stdin(); let mut handle = stdin.lock(); handle.read_line(&mut buffer).unwrap_or(0); let result = buffer[..buffer.len() - 1] .split(' ') .map(PathBuf::from) .collect(); result } fn main() -> Result<()> { let cli = &Cli::parse(); if cli.check { check_modified_files(&cli.path, &cli.output); return Ok(()); } let inputs = if is(Stream::Stdin) { cli.path.to_vec() } else { get_piped_input() }; if inputs.is_empty() { return Ok(()); } if cli.verbose { print_long_banner(); } else { print_short_banner(); } if cli.version { println!("{}", get_title()); return Ok(()); } if cli.watch { return parse_then_watch(&inputs, cli.output.as_path(), cli.verbose); } else if cli.path.len() > 1 { if !cli.relative { println!( "\n[ ERROR ] for multiple inputs, use the --relative flag to set a relative output path." ); } parse_multiple_files(&inputs, &cli.output, cli.verbose); } else if cli.relative { let output_path = relative_output_path_from_input(inputs[0].as_path(), &cli.output); parse_mdx_file(inputs[0].as_path(), &output_path, cli.verbose); } else { parse_mdx_file(inputs[0].as_path(), cli.output.as_path(), cli.verbose); } Ok(()) } #[cfg(test)] mod tests { use crate::relative_output_path_from_input; use std::path::PathBuf; #[test] pub fn test_relative_output_path_from_input() { let input_path = PathBuf::from("local/files/input/./day-one/morning.txt"); let relative_output_path = PathBuf::from("local/files/output"); assert_eq!( relative_output_path_from_input(input_path.as_path(), relative_output_path.as_path()), PathBuf::from("local/files/output/day-one/morning.astro") ); } #[test] #[should_panic( expected = "[ ERROR ] Using relative mode: check input paths include a \"/./\" \ marker to separate root and relative parts." )] pub fn test_relative_output_path_from_input_panic() { let input_path = PathBuf::from("local/files/input/day-one/morning.mdx"); let relative_output_path = PathBuf::from("local/files/output"); assert_eq!( relative_output_path_from_input(input_path.as_path(), relative_output_path.as_path()), PathBuf::from("local/files/output/day-one/morning.astro") ); } }
match fs::metadata(output_path) { Ok(metadata_value) => match metadata_value.modified() { Ok(value) => Some(value), Err(_) => None, }, Err(_) => None, }
if_condition
[ { "content": "pub fn parse_mdx_file(input_path: &Path, output_path: &Path, verbose: bool) {\n\n println!(\"[ INFO ] Parsing {:?}...\", input_path);\n\n let start = Instant::now();\n\n\n\n let file = File::open(input_path).expect(\"[ ERROR ] Couldn't open that file!\");\n\n let frontmatter_end_line_n...
Rust
sqlx-core/src/pool/mod.rs
broomstar/sqlx
6c8fd949dd052ddbad5c4dfe343682aed9286615
use std::{ fmt, ops::{Deref, DerefMut}, sync::Arc, time::{Duration, Instant}, }; use crate::Database; use self::inner::SharedPool; pub use self::options::Builder; use self::options::Options; mod executor; mod inner; mod options; pub struct Pool<DB>(Arc<SharedPool<DB>>) where DB: Database; struct Connection<DB: Database> { live: Option<Live<DB>>, pool: Arc<SharedPool<DB>>, } struct Live<DB: Database> { raw: DB::Connection, created: Instant, } struct Idle<DB: Database> { live: Live<DB>, since: Instant, } impl<DB> Pool<DB> where DB: Database, DB::Connection: crate::Connection<Database = DB>, { pub async fn new(url: &str) -> crate::Result<Self> { Self::builder().build(url).await } async fn with_options(url: &str, options: Options) -> crate::Result<Self> { let inner = SharedPool::new_arc(url, options).await?; Ok(Pool(inner)) } pub fn builder() -> Builder<DB> { Builder::new() } pub async fn acquire(&self) -> crate::Result<impl DerefMut<Target = DB::Connection>> { self.0.acquire().await.map(|conn| Connection { live: Some(conn), pool: Arc::clone(&self.0), }) } pub fn try_acquire(&self) -> Option<impl DerefMut<Target = DB::Connection>> { self.0.try_acquire().map(|conn| Connection { live: Some(conn), pool: Arc::clone(&self.0), }) } pub async fn close(&self) { self.0.close().await; } pub fn size(&self) -> u32 { self.0.size() } pub fn idle(&self) -> usize { self.0.num_idle() } pub fn max_size(&self) -> u32 { self.0.options().max_size } pub fn connect_timeout(&self) -> Duration { self.0.options().connect_timeout } pub fn min_size(&self) -> u32 { self.0.options().min_size } pub fn max_lifetime(&self) -> Option<Duration> { self.0.options().max_lifetime } pub fn idle_timeout(&self) -> Option<Duration> { self.0.options().idle_timeout } } impl<DB> Clone for Pool<DB> where DB: Database, { fn clone(&self) -> Self { Self(Arc::clone(&self.0)) } } impl<DB: Database> fmt::Debug for Pool<DB> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Pool") .field("url", &self.0.url()) .field("size", &self.0.size()) .field("num_idle", &self.0.num_idle()) .field("is_closed", &self.0.is_closed()) .field("options", self.0.options()) .finish() } } const DEREF_ERR: &str = "(bug) connection already released to pool"; impl<DB: Database> Deref for Connection<DB> { type Target = DB::Connection; fn deref(&self) -> &Self::Target { &self.live.as_ref().expect(DEREF_ERR).raw } } impl<DB: Database> DerefMut for Connection<DB> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.live.as_mut().expect(DEREF_ERR).raw } } impl<DB: Database> Drop for Connection<DB> { fn drop(&mut self) { if let Some(live) = self.live.take() { self.pool.release(live); } } }
use std::{ fmt, ops::{Deref, DerefMut}, sync::Arc, time::{Duration, Instant}, }; use crate::Database; use self::inner::SharedPool; pub use self::options::Builder; use self::options::Options; mod executor; mod inner; mod options; pub struct Pool<DB>(Arc<SharedPool<DB>>) where DB: Database; struct Connection<DB: Database> { live: Option<Live<DB>>, pool: Arc<SharedPool<DB>>, } struct Live<DB: Database> { raw: DB::Connection, created: Instant, } struct Idle<DB: Database> { live: Live<DB>, since: Instant, } impl<DB> Pool<DB> where DB: Database, DB::Connection: crate::Connection<Database = DB>, { pub async fn new(url: &str) -> crate::Result<Self> { Self::builder().build(url).await } async fn with_options(url: &str, options: Options) -> crate::Result<Self> { let inner = SharedPool::new_arc(url, options).await?; Ok(Pool(inner)) } pub fn builder() -> Builder<DB> { Builder::new() } pub async fn acquire(&self) -> crate::Result<impl DerefMut<Target = DB::Connection>> { self.0.acquire().await.map(|conn| Connection { live: Some(conn), pool: Arc::clone(&self.0), }) } pub fn try_acquire(&self) -> Option<impl DerefMut<Target = DB::Connection>> { self.0
f::Target { &mut self.live.as_mut().expect(DEREF_ERR).raw } } impl<DB: Database> Drop for Connection<DB> { fn drop(&mut self) { if let Some(live) = self.live.take() { self.pool.release(live); } } }
.try_acquire().map(|conn| Connection { live: Some(conn), pool: Arc::clone(&self.0), }) } pub async fn close(&self) { self.0.close().await; } pub fn size(&self) -> u32 { self.0.size() } pub fn idle(&self) -> usize { self.0.num_idle() } pub fn max_size(&self) -> u32 { self.0.options().max_size } pub fn connect_timeout(&self) -> Duration { self.0.options().connect_timeout } pub fn min_size(&self) -> u32 { self.0.options().min_size } pub fn max_lifetime(&self) -> Option<Duration> { self.0.options().max_lifetime } pub fn idle_timeout(&self) -> Option<Duration> { self.0.options().idle_timeout } } impl<DB> Clone for Pool<DB> where DB: Database, { fn clone(&self) -> Self { Self(Arc::clone(&self.0)) } } impl<DB: Database> fmt::Debug for Pool<DB> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Pool") .field("url", &self.0.url()) .field("size", &self.0.size()) .field("num_idle", &self.0.num_idle()) .field("is_closed", &self.0.is_closed()) .field("options", self.0.options()) .finish() } } const DEREF_ERR: &str = "(bug) connection already released to pool"; impl<DB: Database> Deref for Connection<DB> { type Target = DB::Connection; fn deref(&self) -> &Self::Target { &self.live.as_ref().expect(DEREF_ERR).raw } } impl<DB: Database> DerefMut for Connection<DB> { fn deref_mut(&mut self) -> &mut Sel
random
[ { "content": "fn is_beyond_lifetime<DB: Database>(live: &Live<DB>, options: &Options) -> bool {\n\n // check if connection was within max lifetime (or not set)\n\n options\n\n .max_lifetime\n\n .map_or(false, |max| live.created.elapsed() > max)\n\n}\n\n\n", "file_path": "sqlx-core/src/po...
Rust
src/subcommand/launch.rs
chipsenkbeil/distant
c6c07c5c2ce6ef5c1499c08ce077a14c2c558716
use crate::{ exit::{ExitCode, ExitCodeError}, msg::{MsgReceiver, MsgSender}, opt::{CommonOpt, Format, LaunchSubcommand, SessionOutput}, session::CliSession, utils, }; use derive_more::{Display, Error, From}; use distant_core::{ PlainCodec, RelayServer, Session, SessionInfo, SessionInfoFile, Transport, TransportListener, XChaCha20Poly1305Codec, }; use log::*; use std::{path::Path, string::FromUtf8Error}; use tokio::{io, process::Command, runtime::Runtime, time::Duration}; #[derive(Debug, Display, Error, From)] pub enum Error { #[display(fmt = "Missing data for session")] MissingSessionData, Fork(#[error(not(source))] i32), Io(io::Error), Utf8(FromUtf8Error), } impl ExitCodeError for Error { fn to_exit_code(&self) -> ExitCode { match self { Self::MissingSessionData => ExitCode::NoInput, Self::Fork(_) => ExitCode::OsErr, Self::Io(x) => x.to_exit_code(), Self::Utf8(_) => ExitCode::DataErr, } } } pub fn run(cmd: LaunchSubcommand, opt: CommonOpt) -> Result<(), Error> { let rt = Runtime::new()?; let session_output = cmd.session; let format = cmd.format; let is_daemon = !cmd.foreground; let session_file = cmd.session_data.session_file.clone(); let session_socket = cmd.session_data.session_socket.clone(); let fail_if_socket_exists = cmd.fail_if_socket_exists; let timeout = opt.to_timeout_duration(); let shutdown_after = cmd.to_shutdown_after_duration(); let session = rt.block_on(async { spawn_remote_server(cmd, opt).await })?; match session_output { SessionOutput::File => { debug!("Outputting session to {:?}", session_file); rt.block_on(async { SessionInfoFile::new(session_file, session).save().await })? } SessionOutput::Keep => { debug!("Entering interactive loop over stdin"); rt.block_on(async { keep_loop(session, format, timeout).await })? } SessionOutput::Pipe => { debug!("Piping session to stdout"); println!("{}", session.to_unprotected_string()) } #[cfg(unix)] SessionOutput::Socket if is_daemon => { debug!( "Forking and entering interactive loop over unix socket {:?}", session_socket ); drop(rt); run_daemon_socket( session_socket, session, timeout, fail_if_socket_exists, shutdown_after, )?; } #[cfg(unix)] SessionOutput::Socket => { debug!( "Entering interactive loop over unix socket {:?}", session_socket ); rt.block_on(async { socket_loop( session_socket, session, timeout, fail_if_socket_exists, shutdown_after, ) .await })? } } Ok(()) } #[cfg(unix)] fn run_daemon_socket( session_socket: impl AsRef<Path>, session: SessionInfo, timeout: Duration, fail_if_socket_exists: bool, shutdown_after: Option<Duration>, ) -> Result<(), Error> { use fork::{daemon, Fork}; match daemon(false, false) { Ok(Fork::Child) => { let rt = Runtime::new()?; rt.block_on(async { socket_loop( session_socket, session, timeout, fail_if_socket_exists, shutdown_after, ) .await })? } Ok(_) => {} Err(x) => return Err(Error::Fork(x)), } Ok(()) } async fn keep_loop(info: SessionInfo, format: Format, duration: Duration) -> io::Result<()> { let addr = info.to_socket_addr().await?; let codec = XChaCha20Poly1305Codec::from(info.key); match Session::tcp_connect_timeout(addr, codec, duration).await { Ok(session) => { let cli_session = CliSession::new_for_stdin(utils::new_tenant(), session, format); cli_session.wait().await } Err(x) => Err(x), } } #[cfg(unix)] async fn socket_loop( socket_path: impl AsRef<Path>, info: SessionInfo, duration: Duration, fail_if_socket_exists: bool, shutdown_after: Option<Duration>, ) -> io::Result<()> { debug!("Connecting to {} {}", info.host, info.port); let addr = info.to_socket_addr().await?; let codec = XChaCha20Poly1305Codec::from(info.key); let session = Session::tcp_connect_timeout(addr, codec, duration).await?; if !fail_if_socket_exists && socket_path.as_ref().exists() { debug!("Removing old unix socket instance"); tokio::fs::remove_file(socket_path.as_ref()).await?; } debug!("Binding to unix socket: {:?}", socket_path.as_ref()); let listener = tokio::net::UnixListener::bind(socket_path)?; let stream = TransportListener::initialize(listener, |stream| Transport::new(stream, PlainCodec::new())) .into_stream(); let server = RelayServer::initialize(session, Box::pin(stream), shutdown_after)?; server .wait() .await .map_err(|x| io::Error::new(io::ErrorKind::Other, x)) } async fn spawn_remote_server(cmd: LaunchSubcommand, opt: CommonOpt) -> Result<SessionInfo, Error> { #[cfg(feature = "ssh2")] if cmd.external_ssh { external_spawn_remote_server(cmd, opt).await } else { native_spawn_remote_server(cmd, opt).await } #[cfg(not(feature = "ssh2"))] external_spawn_remote_server(cmd, opt).await } #[cfg(feature = "ssh2")] async fn native_spawn_remote_server( cmd: LaunchSubcommand, _opt: CommonOpt, ) -> Result<SessionInfo, Error> { trace!("native_spawn_remote_server({:?})", cmd); use distant_ssh2::{ IntoDistantSessionOpts, Ssh2AuthEvent, Ssh2AuthHandler, Ssh2Session, Ssh2SessionOpts, }; let host = cmd.host; let mut opts = Ssh2SessionOpts::default(); if let Some(path) = cmd.identity_file { opts.identity_files.push(path); } opts.port = Some(cmd.port); opts.user = Some(cmd.username); debug!("Connecting to {} {:#?}", host, opts); let mut ssh_session = Ssh2Session::connect(host.as_str(), opts)?; #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(tag = "type")] enum SshMsg { #[serde(rename = "ssh_authenticate")] Authenticate(Ssh2AuthEvent), #[serde(rename = "ssh_authenticate_answer")] AuthenticateAnswer { answers: Vec<String> }, #[serde(rename = "ssh_banner")] Banner { text: String }, #[serde(rename = "ssh_host_verify")] HostVerify { host: String }, #[serde(rename = "ssh_host_verify_answer")] HostVerifyAnswer { answer: bool }, #[serde(rename = "ssh_error")] Error { msg: String }, } debug!("Authenticating against {}", host); ssh_session .authenticate(match cmd.format { Format::Shell => Ssh2AuthHandler::default(), Format::Json => { let tx = MsgSender::from_stdout(); let tx_2 = tx.clone(); let tx_3 = tx.clone(); let tx_4 = tx.clone(); let rx = MsgReceiver::from_stdin(); let rx_2 = rx.clone(); Ssh2AuthHandler { on_authenticate: Box::new(move |ev| { let _ = tx.send_blocking(&SshMsg::Authenticate(ev)); let msg: SshMsg = rx.recv_blocking()?; match msg { SshMsg::AuthenticateAnswer { answers } => Ok(answers), x => { return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("Invalid response received: {:?}", x), )) } } }), on_banner: Box::new(move |banner| { let _ = tx_2.send_blocking(&SshMsg::Banner { text: banner.to_string(), }); }), on_host_verify: Box::new(move |host| { let _ = tx_3.send_blocking(&SshMsg::HostVerify { host: host.to_string(), })?; let msg: SshMsg = rx_2.recv_blocking()?; match msg { SshMsg::HostVerifyAnswer { answer } => Ok(answer), x => { return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("Invalid response received: {:?}", x), )) } } }), on_error: Box::new(move |err| { let _ = tx_4.send_blocking(&SshMsg::Error { msg: err.to_string(), }); }), } } }) .await?; debug!("Mapping session for {}", host); let session_info = ssh_session .into_distant_session_info(IntoDistantSessionOpts { binary: cmd.distant, args: cmd.extra_server_args.unwrap_or_default(), ..Default::default() }) .await?; Ok(session_info) } async fn external_spawn_remote_server( cmd: LaunchSubcommand, _opt: CommonOpt, ) -> Result<SessionInfo, Error> { let distant_command = format!( "{} listen --host {} {}", cmd.distant, cmd.bind_server, cmd.extra_server_args.unwrap_or_default(), ); let ssh_command = format!( "{} -o StrictHostKeyChecking=no ssh://{}@{}:{} {} '{}'", cmd.ssh, cmd.username, cmd.host.as_str(), cmd.port, cmd.identity_file .map(|f| format!("-i {}", f.as_path().display())) .unwrap_or_default(), if cmd.no_shell { distant_command.trim().to_string() } else { format!("echo {} | $SHELL -l", distant_command.trim()) }, ); let out = Command::new("sh") .arg("-c") .arg(ssh_command) .output() .await?; if !out.status.success() { return Err(Error::from(io::Error::new( io::ErrorKind::Other, String::from_utf8(out.stderr)?.trim().to_string(), ))); } let out = String::from_utf8(out.stdout)?.trim().to_string(); let mut info = out .lines() .find_map(|line| line.parse::<SessionInfo>().ok()) .ok_or(Error::MissingSessionData)?; info.host = cmd.host; Ok(info) }
use crate::{ exit::{ExitCode, ExitCodeError}, msg::{MsgReceiver, MsgSender}, opt::{CommonOpt, Format, LaunchSubcommand, SessionOutput}, session::CliSession, utils, }; use derive_more::{Display, Error, From}; use distant_core::{ PlainCodec, RelayServer, Session, SessionInfo, SessionInfoFile, Transport, TransportListener, XChaCha20Poly1305Codec, }; use log::*; use std::{path::Path, string::FromUtf8Error}; use tokio::{io, process::Command, runtime::Runtime, time::Duration}; #[derive(Debug, Display, Error, From)] pub enum Error { #[display(fmt = "Missing data for session")] MissingSessionData, Fork(#[error(not(source))] i32), Io(io::Error), Utf8(FromUtf8Error), } impl ExitCodeError for Error { fn to_exit_code(&self) -> ExitCode { match self { Self::MissingSessionData => ExitCode::NoInput, Self::Fork(_) => ExitCode::OsErr, Self::Io(x) => x.to_exit_code(), Self::Utf8(_) => ExitCode::DataErr, } } } pub fn run(cmd: LaunchSubcommand, opt: CommonOpt) -> Result<(), Error> { let rt = Runtime::new()?; let session_output = cmd.session; let format = cmd.format; let is_daemon = !cmd.foreground; let session_file = cmd.session_data.session_file.clone(); let session_socket = cmd.session_data.session_socket.clone(); let fail_if_socket_exists = cmd.fail_if_socket_exists; let timeout = opt.to_timeout_duration(); let shutdown_after = cmd.to_shutdown_after_duration(); let session = rt.block_on(async { spawn_remote_server(cmd, opt).await })?; match session_output { SessionOutput::File => { debug!("Outputting session to {:?}", session_file); rt.block_on(async { SessionInfoFile::new(session_file, session).save().await })? } SessionOutput::Keep => { debug!("Entering interactive loop over stdin"); rt.block_on(async { keep_loop(session, format, timeout).await })? } SessionOutput::Pipe => { debug!("Piping session to stdout"); println!("{}", session.to_unprotected_string()) } #[cfg(unix)] SessionOutput::Socket if is_daemon => { debug!( "Forking and entering interactive loop over unix socket {:?}", session_socket ); drop(rt); run_daemon_socket( session_socket, session, timeout, fail_if_socket_exists, shutdown_after, )?; } #[cfg(unix)] SessionOutput::Socket => { debug!( "Entering interactive loop over unix socket {:?}", session_socket ); rt.block_on(async { socket_loop( session_socket, session, timeout, fail_if_socket_exists, shutdown_after, ) .await })? } } Ok(()) } #[cfg(unix)] fn run_daemon_socket( session_socket: impl AsRef<Path>, session: SessionInfo, timeout: Duration, fail_if_socket_exists: bool, shutdown_after: Option<Duration>, ) -> Result<(), Error> { use fork::{daemon, Fork}; match daemon(false, false) { Ok(Fork::Child) => { let rt = Runtime::new()?; rt.block_on(async { socket_loop( session_socket, session, timeout, fail_if_socket_exists, shutdown_after, ) .await })? } Ok(_) => {} Err(x) => return Err(Error::Fork(x)), } Ok(()) }
#[cfg(unix)] async fn socket_loop( socket_path: impl AsRef<Path>, info: SessionInfo, duration: Duration, fail_if_socket_exists: bool, shutdown_after: Option<Duration>, ) -> io::Result<()> { debug!("Connecting to {} {}", info.host, info.port); let addr = info.to_socket_addr().await?; let codec = XChaCha20Poly1305Codec::from(info.key); let session = Session::tcp_connect_timeout(addr, codec, duration).await?; if !fail_if_socket_exists && socket_path.as_ref().exists() { debug!("Removing old unix socket instance"); tokio::fs::remove_file(socket_path.as_ref()).await?; } debug!("Binding to unix socket: {:?}", socket_path.as_ref()); let listener = tokio::net::UnixListener::bind(socket_path)?; let stream = TransportListener::initialize(listener, |stream| Transport::new(stream, PlainCodec::new())) .into_stream(); let server = RelayServer::initialize(session, Box::pin(stream), shutdown_after)?; server .wait() .await .map_err(|x| io::Error::new(io::ErrorKind::Other, x)) } async fn spawn_remote_server(cmd: LaunchSubcommand, opt: CommonOpt) -> Result<SessionInfo, Error> { #[cfg(feature = "ssh2")] if cmd.external_ssh { external_spawn_remote_server(cmd, opt).await } else { native_spawn_remote_server(cmd, opt).await } #[cfg(not(feature = "ssh2"))] external_spawn_remote_server(cmd, opt).await } #[cfg(feature = "ssh2")] async fn native_spawn_remote_server( cmd: LaunchSubcommand, _opt: CommonOpt, ) -> Result<SessionInfo, Error> { trace!("native_spawn_remote_server({:?})", cmd); use distant_ssh2::{ IntoDistantSessionOpts, Ssh2AuthEvent, Ssh2AuthHandler, Ssh2Session, Ssh2SessionOpts, }; let host = cmd.host; let mut opts = Ssh2SessionOpts::default(); if let Some(path) = cmd.identity_file { opts.identity_files.push(path); } opts.port = Some(cmd.port); opts.user = Some(cmd.username); debug!("Connecting to {} {:#?}", host, opts); let mut ssh_session = Ssh2Session::connect(host.as_str(), opts)?; #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(tag = "type")] enum SshMsg { #[serde(rename = "ssh_authenticate")] Authenticate(Ssh2AuthEvent), #[serde(rename = "ssh_authenticate_answer")] AuthenticateAnswer { answers: Vec<String> }, #[serde(rename = "ssh_banner")] Banner { text: String }, #[serde(rename = "ssh_host_verify")] HostVerify { host: String }, #[serde(rename = "ssh_host_verify_answer")] HostVerifyAnswer { answer: bool }, #[serde(rename = "ssh_error")] Error { msg: String }, } debug!("Authenticating against {}", host); ssh_session .authenticate(match cmd.format { Format::Shell => Ssh2AuthHandler::default(), Format::Json => { let tx = MsgSender::from_stdout(); let tx_2 = tx.clone(); let tx_3 = tx.clone(); let tx_4 = tx.clone(); let rx = MsgReceiver::from_stdin(); let rx_2 = rx.clone(); Ssh2AuthHandler { on_authenticate: Box::new(move |ev| { let _ = tx.send_blocking(&SshMsg::Authenticate(ev)); let msg: SshMsg = rx.recv_blocking()?; match msg { SshMsg::AuthenticateAnswer { answers } => Ok(answers), x => { return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("Invalid response received: {:?}", x), )) } } }), on_banner: Box::new(move |banner| { let _ = tx_2.send_blocking(&SshMsg::Banner { text: banner.to_string(), }); }), on_host_verify: Box::new(move |host| { let _ = tx_3.send_blocking(&SshMsg::HostVerify { host: host.to_string(), })?; let msg: SshMsg = rx_2.recv_blocking()?; match msg { SshMsg::HostVerifyAnswer { answer } => Ok(answer), x => { return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("Invalid response received: {:?}", x), )) } } }), on_error: Box::new(move |err| { let _ = tx_4.send_blocking(&SshMsg::Error { msg: err.to_string(), }); }), } } }) .await?; debug!("Mapping session for {}", host); let session_info = ssh_session .into_distant_session_info(IntoDistantSessionOpts { binary: cmd.distant, args: cmd.extra_server_args.unwrap_or_default(), ..Default::default() }) .await?; Ok(session_info) } async fn external_spawn_remote_server( cmd: LaunchSubcommand, _opt: CommonOpt, ) -> Result<SessionInfo, Error> { let distant_command = format!( "{} listen --host {} {}", cmd.distant, cmd.bind_server, cmd.extra_server_args.unwrap_or_default(), ); let ssh_command = format!( "{} -o StrictHostKeyChecking=no ssh://{}@{}:{} {} '{}'", cmd.ssh, cmd.username, cmd.host.as_str(), cmd.port, cmd.identity_file .map(|f| format!("-i {}", f.as_path().display())) .unwrap_or_default(), if cmd.no_shell { distant_command.trim().to_string() } else { format!("echo {} | $SHELL -l", distant_command.trim()) }, ); let out = Command::new("sh") .arg("-c") .arg(ssh_command) .output() .await?; if !out.status.success() { return Err(Error::from(io::Error::new( io::ErrorKind::Other, String::from_utf8(out.stderr)?.trim().to_string(), ))); } let out = String::from_utf8(out.stdout)?.trim().to_string(); let mut info = out .lines() .find_map(|line| line.parse::<SessionInfo>().ok()) .ok_or(Error::MissingSessionData)?; info.host = cmd.host; Ok(info) }
async fn keep_loop(info: SessionInfo, format: Format, duration: Duration) -> io::Result<()> { let addr = info.to_socket_addr().await?; let codec = XChaCha20Poly1305Codec::from(info.key); match Session::tcp_connect_timeout(addr, codec, duration).await { Ok(session) => { let cli_session = CliSession::new_for_stdin(utils::new_tenant(), session, format); cli_session.wait().await } Err(x) => Err(x), } }
function_block-full_function
[ { "content": "pub fn run(cmd: ActionSubcommand, opt: CommonOpt) -> Result<(), Error> {\n\n let rt = tokio::runtime::Runtime::new()?;\n\n\n\n rt.block_on(async { run_async(cmd, opt).await })\n\n}\n\n\n\nasync fn run_async(cmd: ActionSubcommand, opt: CommonOpt) -> Result<(), Error> {\n\n let method = cmd...
Rust
crates/brix_processor/tests/to_case.rs
miapolis/brix
4a3939db28fff05a7a45fa32f1a75cd9abc29be3
use lazy_static::lazy_static; use std::collections::HashMap; mod common; lazy_static! { static ref TO_CASE_CONTEXT: HashMap<String, String> = { let mut map = HashMap::new(); map.insert(String::from("one"), String::from("tHIS iS tOGGLE cASE")); map.insert(String::from("two"), String::from("ThisIsPascalCase")); map.insert(String::from("three"), String::from("thisIsCamelCase")); map.insert(String::from("four"), String::from("ThisIsUpperCamelCase")); map.insert(String::from("five"), String::from("this_is_snake_case")); map.insert( String::from("six"), String::from("THIS_IS_UPPER_SNAKE_CASE"), ); map.insert( String::from("seven"), String::from("THIS_IS_SCREAMING_SNAKE_CASE"), ); map.insert(String::from("eight"), String::from("this-is-kebab-case")); map.insert(String::from("nine"), String::from("THIS-IS-COBOL-CASE")); map.insert(String::from("ten"), String::from("This-Is-Train-Case")); map.insert(String::from("eleven"), String::from("thisisflatcase")); map.insert(String::from("twelve"), String::from("THISISUPPERFLATCASE")); map.insert( String::from("thirteen"), String::from("tHiS iS aLtErNaTiNg CaSe"), ); map }; static ref TO_CASE_ASSERTIONS: Vec<&'static str> = vec![ "t hIS i s t oGGLE c aSE", "tHIS iS pASCAL cASE", "tHIS iS cAMEL cASE", "tHIS iS uPPER cAMEL cASE", "tHIS iS sNAKE cASE", "tHIS iS uPPER sNAKE cASE", "tHIS iS sCREAMING sNAKE cASE", "tHIS iS kEBAB cASE", "tHIS iS cOBOL cASE", "tHIS iS tRAIN cASE", "tHISISFLATCASE", "tHISISUPPERFLATCASE", "t hI s i s a lT eR nA tI nG cA sE", "THisISTOggleCAse", "ThisIsPascalCase", "ThisIsCamelCase", "ThisIsUpperCamelCase", "ThisIsSnakeCase", "ThisIsUpperSnakeCase", "ThisIsScreamingSnakeCase", "ThisIsKebabCase", "ThisIsCobolCase", "ThisIsTrainCase", "Thisisflatcase", "Thisisupperflatcase", "THiSISALtErNaTiNgCaSe", "tHisISTOggleCAse", "thisIsPascalCase", "thisIsCamelCase", "thisIsUpperCamelCase", "thisIsSnakeCase", "thisIsUpperSnakeCase", "thisIsScreamingSnakeCase", "thisIsKebabCase", "thisIsCobolCase", "thisIsTrainCase", "thisisflatcase", "thisisupperflatcase", "tHiSISALtErNaTiNgCaSe", "THisISTOggleCAse", "ThisIsPascalCase", "ThisIsCamelCase", "ThisIsUpperCamelCase", "ThisIsSnakeCase", "ThisIsUpperSnakeCase", "ThisIsScreamingSnakeCase", "ThisIsKebabCase", "ThisIsCobolCase", "ThisIsTrainCase", "Thisisflatcase", "Thisisupperflatcase", "THiSISALtErNaTiNgCaSe", "t_his_i_s_t_oggle_c_ase", "this_is_pascal_case", "this_is_camel_case", "this_is_upper_camel_case", "this_is_snake_case", "this_is_upper_snake_case", "this_is_screaming_snake_case", "this_is_kebab_case", "this_is_cobol_case", "this_is_train_case", "thisisflatcase", "thisisupperflatcase", "t_hi_s_i_s_a_lt_er_na_ti_ng_ca_se", "T_HIS_I_S_T_OGGLE_C_ASE", "THIS_IS_PASCAL_CASE", "THIS_IS_CAMEL_CASE", "THIS_IS_UPPER_CAMEL_CASE", "THIS_IS_SNAKE_CASE", "THIS_IS_UPPER_SNAKE_CASE", "THIS_IS_SCREAMING_SNAKE_CASE", "THIS_IS_KEBAB_CASE", "THIS_IS_COBOL_CASE", "THIS_IS_TRAIN_CASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "T_HI_S_I_S_A_LT_ER_NA_TI_NG_CA_SE", "T_HIS_I_S_T_OGGLE_C_ASE", "THIS_IS_PASCAL_CASE", "THIS_IS_CAMEL_CASE", "THIS_IS_UPPER_CAMEL_CASE", "THIS_IS_SNAKE_CASE", "THIS_IS_UPPER_SNAKE_CASE", "THIS_IS_SCREAMING_SNAKE_CASE", "THIS_IS_KEBAB_CASE", "THIS_IS_COBOL_CASE", "THIS_IS_TRAIN_CASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "T_HI_S_I_S_A_LT_ER_NA_TI_NG_CA_SE", "t-his-i-s-t-oggle-c-ase", "this-is-pascal-case", "this-is-camel-case", "this-is-upper-camel-case", "this-is-snake-case", "this-is-upper-snake-case", "this-is-screaming-snake-case", "this-is-kebab-case", "this-is-cobol-case", "this-is-train-case", "thisisflatcase", "thisisupperflatcase", "t-hi-s-i-s-a-lt-er-na-ti-ng-ca-se", "T-HIS-I-S-T-OGGLE-C-ASE", "THIS-IS-PASCAL-CASE", "THIS-IS-CAMEL-CASE", "THIS-IS-UPPER-CAMEL-CASE", "THIS-IS-SNAKE-CASE", "THIS-IS-UPPER-SNAKE-CASE", "THIS-IS-SCREAMING-SNAKE-CASE", "THIS-IS-KEBAB-CASE", "THIS-IS-COBOL-CASE", "THIS-IS-TRAIN-CASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "T-HI-S-I-S-A-LT-ER-NA-TI-NG-CA-SE", "T-His-I-S-T-Oggle-C-Ase", "This-Is-Pascal-Case", "This-Is-Camel-Case", "This-Is-Upper-Camel-Case", "This-Is-Snake-Case", "This-Is-Upper-Snake-Case", "This-Is-Screaming-Snake-Case", "This-Is-Kebab-Case", "This-Is-Cobol-Case", "This-Is-Train-Case", "Thisisflatcase", "Thisisupperflatcase", "T-Hi-S-I-S-A-Lt-Er-Na-Ti-Ng-Ca-Se", "thisistogglecase", "thisispascalcase", "thisiscamelcase", "thisisuppercamelcase", "thisissnakecase", "thisisuppersnakecase", "thisisscreamingsnakecase", "thisiskebabcase", "thisiscobolcase", "thisistraincase", "thisisflatcase", "thisisupperflatcase", "thisisalternatingcase", "THISISTOGGLECASE", "THISISPASCALCASE", "THISISCAMELCASE", "THISISUPPERCAMELCASE", "THISISSNAKECASE", "THISISUPPERSNAKECASE", "THISISSCREAMINGSNAKECASE", "THISISKEBABCASE", "THISISCOBOLCASE", "THISISTRAINCASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "THISISALTERNATINGCASE", "t HiS i S t OgGlE c AsE", "tHiS iS pAsCaL cAsE", "tHiS iS cAmEl CaSe", "tHiS iS uPpEr CaMeL cAsE", "tHiS iS sNaKe CaSe", "tHiS iS uPpEr SnAkE cAsE", "tHiS iS sCrEaMiNg SnAkE cAsE", "tHiS iS kEbAb CaSe", "tHiS iS cObOl CaSe", "tHiS iS tRaIn CaSe", "tHiSiSfLaTcAsE", "tHiSiSuPpErFlAtCaSe", "t Hi S i S a Lt Er Na Ti Ng Ca Se", ]; } #[test] fn to_case() { let core = common::setup(); let context = brix_processor::create_context(TO_CASE_CONTEXT.clone()); let contents = common::load_file("case").unwrap(); let result = core.process(contents, context).unwrap(); assert!(common::line_assert(result, TO_CASE_ASSERTIONS.to_vec())) }
use lazy_static::lazy_static; use std::collections::HashMap; mod common; lazy_static! { static ref TO_CASE_CONTEXT: HashMap<String, String> = { let mut map = HashMap::new(); map.insert(String::from("one"), String::from("tHIS iS tOGGLE cASE")); map.insert(String::from("two"), String::from("ThisIsPascalCase")); map.insert(String::from("three"), String::from("thisIsCamelCase")); map.insert(String::from("four"), String::from("ThisIsUpperCamelCase")); map.insert(String::from("five"), String::from("this_is_snake_case")); map.insert( String::from("six"), String::from("THIS_IS_UPPER_SNAKE_CASE"), ); map.insert( String::from("seven"), String::from("THIS_IS_SCREAMING_SNAKE_CASE"), ); map.insert(String::from("eight"), String::from("this-is-kebab-case")); map.insert(String::from("nine"), String::from("THIS-IS-COBOL-CASE")); map.insert(String::from("ten"), String::from("This-Is-Train-Case")); map.insert(String::from("eleven"), String::from("thisisflatcase")); map.insert(String::from("twelve"), String::from("THISISUPPERFLATCASE")); map.insert( String::from("thirteen"), String::from("tHiS iS aLtErNaTiNg CaSe"), ); map }; static ref TO_CASE_ASSERTIONS: Vec<&'static str> = vec![ "t hIS i s t oGGLE c aSE", "tHIS iS pASCAL cASE", "tHIS iS cAMEL cASE", "tHIS iS uPPER cAMEL cASE", "tHIS iS sNAKE cASE", "tHIS iS uPPER sNAKE cASE", "tHIS iS sCREAMING sNAKE cASE", "tHIS iS kEBAB cASE", "tHIS iS cOBOL cASE", "tHIS iS tRAIN cASE", "tHISISFLATCASE", "tHISISUPPERFLATCASE", "t hI s i s a lT eR nA tI nG cA sE", "THisISTOggleCAse", "ThisIsPascalCase", "ThisIsCamelCase", "ThisIsUpperCamelCase", "ThisIsSnakeCase", "ThisIsUpperSnakeCase", "ThisIsScreamingSnakeCase", "ThisIsKebabCase", "ThisIsCobolCase", "ThisIsTrainCase", "Thisisflatcase", "Thisisupperflatcase", "THiSISALtErNaTiNgCaSe", "tHisISTOggleCAse", "thisIsPascalCase", "thisIsCamelCase", "thisIsUpperCamelCase", "thisIsSnakeCase", "thisIsUpperSnakeCase", "thisIsScreamingSnakeCase", "thisIsKebabCase", "thisIsCobolCase", "thisIsTrainCase", "thisisflatcase", "thisisupperflatcase", "tHiSISALtErNaTiNgCaSe", "THisISTOggleCAse", "ThisIsPascalCase", "ThisIsCamelCase", "ThisIsUpperCamelCase", "ThisIsSnakeCase", "ThisIsUpperSnakeCase", "ThisIsScreamingSnakeCase", "ThisIsKebabCase", "ThisIsCobolCase", "ThisIsTrainCase", "Thisisflatcase", "Thisisupperflatcase", "THiSISALtErNaTiNgCaSe", "t_his_i_s_t_oggle_c_ase", "this_is_pascal_case", "this_is_camel_case", "this_is_upper_camel_case", "this_is_snake_case", "this_is_upper_snake_case", "this_is_screaming_snake_case", "this_is_kebab_case", "this_is_cobol_case", "this_is_train_case", "thisisflatcase", "thisisupperflatcase", "t_hi_s_i_s_a_lt_er_na_ti_ng_ca_se", "T_HIS_I_S_T_OGGLE_C_ASE", "THIS_IS_PASCAL_CASE", "THIS_IS_CAMEL_CASE", "THIS_IS_UPPER_CAMEL_CASE", "THIS_IS_SNAKE_CASE", "THIS_IS_UPPER_SNAKE_CASE", "THIS_IS_SCREAMING_SNAKE_CASE", "THIS_IS_KEBAB_CASE", "THIS_IS_COBOL_CASE", "THIS_IS_TRAIN_CASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "T_HI_S_I_S_A_LT_ER_NA_TI_NG_CA_SE", "T_HIS_I_S_T_OGGLE_C_ASE", "THIS_IS_PASCAL_CASE", "THIS_IS_CAMEL_CASE", "THIS_IS_UPPER_CAMEL_CASE", "THIS_IS_SNAKE_CASE", "THIS_IS_UPPER_SNAKE_CASE", "THIS_IS_SCREAMING_SNAKE_CASE", "THIS_IS_KEBAB_CASE", "THIS_IS_COBOL_CASE", "THIS_IS_TRAIN_CASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "T_HI_S_I_S_A_LT_ER_NA_TI_NG_CA_SE", "t-his-i-s-t-oggle-c-ase", "this-is-pascal-case", "this-is-camel-case", "this-is-upper-camel-case", "this-is-snake-case", "this-is-upper-snake-case", "this-is-screaming-snake-case", "this-is-kebab-case", "this-is-cobol-case", "this-is-train-case", "thisisflatcase", "thisisupperflatcase", "t-hi-s-i-s-a-lt-er-na-ti-ng-ca-se", "T-HIS-I-S-T-OGGLE-C-ASE", "THIS-IS-PASCAL-CASE", "THIS-IS-CAMEL-CASE", "THIS-IS-UPPER-CAMEL-CASE", "THIS-IS-SNAKE-CASE", "THIS-IS-UPPER-SNAKE-CASE", "THIS-IS-SCREAMING-SNAKE-CASE", "THIS-IS-KEBAB-CASE", "THIS-IS-COBOL-CASE", "THIS-IS-TRAIN-CASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "T-HI-S-I-S-A-LT-ER-NA-TI-NG-CA-SE", "T-His-I-S-T-Oggle-C-Ase", "This-Is-Pascal-Case", "This-Is-Camel-Case", "This-Is-Upper-Camel-Case", "This-Is-Snake-Case", "This-Is-Upper-Snake-Case", "This-Is-Screaming-Snake-Case", "This-Is-Kebab-Case", "This-Is-Cobol-Case", "This-Is-Train-Case", "Thisisflatcase", "Thisisupperflatcase", "T-Hi-S-I-S-A-Lt-Er-Na-Ti-Ng-Ca-Se", "thisistogglecase", "thisispascalcase", "thisiscamelcase", "thisisuppercamelcase", "thisissnakecase", "thisisuppersnakecase", "thisisscreamingsnakecase", "thisiskebabcase", "thisiscobolcase", "thisistraincase", "thisisflatcase", "thisisupperflatcase", "thisisalternatingcase", "THISISTOGGLECASE", "THISISPASCALCASE", "THISISCAMELCASE", "THISISUPPERCAMELCASE", "THISISSNAKECASE", "THISISUPPERSNAKECASE", "THISISSCREAMINGSNAKECASE", "THISISKEBABCASE", "THISISCOBOLCASE", "THISISTRAINCASE", "THISISFLATCASE", "THISISUPPERFLATCASE", "THISISALTERNATINGCASE", "t HiS i S t OgGlE c AsE", "tHiS iS pAsCaL cAsE", "tHiS iS cAmEl CaSe", "tHiS iS uPpEr CaMeL cAsE", "tHiS iS sNaKe CaSe", "tHiS iS uPpEr SnAkE cAsE", "tHiS iS sCrEaMiNg SnAkE cAsE", "tHiS iS kEbAb CaSe", "tHiS iS cObOl CaSe", "tHiS iS tRaIn CaSe", "tHiSiSfLaTcAsE", "tHiSiSuPpErFlAtCaSe", "t Hi S i S a Lt Er Na Ti Ng Ca Se", ]; } #[test]
fn to_case() { let core = common::setup(); let context = brix_processor::create_context(TO_CASE_CONTEXT.clone()); let contents = common::load_file("case").unwrap(); let result = core.process(contents, context).unwrap(); assert!(common::line_assert(result, TO_CASE_ASSERTIONS.to_vec())) }
function_block-full_function
[ { "content": "pub fn line_assert(contents: String, assertion: Vec<&str>) -> bool {\n\n let mut itr = 0;\n\n for line in contents.lines() {\n\n if assertion[itr] != line {\n\n return false;\n\n }\n\n itr += 1;\n\n }\n\n return true;\n\n}\n", "file_path": "crates/br...
Rust
src/lib.rs
mikelma/ostrich-server
685c29502e09a5e0d668ad85cc531ea68711f1f7
use ostrich_core::*; #[macro_use] extern crate log; use tokio::sync::mpsc; use tokio::net::{TcpStream}; use tokio::io::{AsyncReadExt, AsyncWriteExt, AsyncRead}; use tokio::stream::{Stream}; use std::collections::HashMap; use std::io::{self, BufReader, prelude::*}; use std::fs::File; use core::task::{Poll, Context}; use core::pin::Pin; pub mod config; pub type Tx = mpsc::UnboundedSender<Command>; pub type Rx = mpsc::UnboundedReceiver<Command>; pub struct SharedConn { shared_conn: HashMap<String, Tx>, groups: HashMap<String, Vec<String>>, } impl SharedConn { pub fn new() -> SharedConn{ SharedConn{ shared_conn: HashMap::new(), groups: HashMap::new() } } pub fn add(&mut self, name: String, tx: Tx) -> Result<(), io::Error> { if self.shared_conn.contains_key(&name) { return Err(io::Error::new(io::ErrorKind::AlreadyExists, "A user with the same credentials is already loged in")); } self.shared_conn.insert(name, tx); Ok(()) } pub fn remove(&mut self, name: &str) -> Result<(), io::Error> { match self.shared_conn.remove(name) { Some(_) => Ok(()), None => Err(io::Error::new(io::ErrorKind::NotFound, "User not found")), } } pub async fn join_group(&mut self, group_name: &str, username: &str) -> Result<(), io::Error> { if let Some(group) = self.groups.get_mut(group_name) { if group.iter().find(|&x| *x == group_name.to_string()).is_some() { trace!("User {} wanted to join {} when already joined", username, group_name); return Ok(()) } else { group.push(username.to_string()); let notification = Command::ListUsr( group_name.to_string(), ListUsrOperation::Add, format!("\n{}", username)); self.send2group(username, group_name, None, &notification).await?; } } else { self.groups.insert(group_name.to_string(), vec![username.to_string()]); } Ok(()) } pub async fn leave_group(&mut self, username: &str, group_name: &str) -> Result<(), io::Error> { if let Some(group) = self.groups.get_mut(group_name) { if let Some(index) = group.iter().position(|name| name == username) { group.remove(index); let notification = Command::ListUsr( group_name.to_string(), ListUsrOperation::Remove, format!("\n{}", username)); self.send2group(group_name, group_name, Some(vec![&username]), &notification).await?; } else { return Err(io::Error::new(io::ErrorKind::NotFound, format!("User {} not found in {}", username, group_name))) } } else { return Err(io::Error::new(io::ErrorKind::NotFound, format!("Group {} not found", group_name))) } Ok(()) } pub async fn send(&mut self, command: Command) -> Result<(), io::Error>{ let (sender, target) = match &command { Command::Msg(s,t,_) => (s, t), _ => return Err(io::Error::new( io::ErrorKind::InvalidInput, "Wrong command type. Only MSG commands can be sended")), }; if target.starts_with("#") { return self.send2group(sender, target, None, &command).await; } let target_tx = match self.shared_conn.get_mut(&target.to_string()) { Some(t) => t, None => return Err(io::Error::new( io::ErrorKind::NotFound, format!("Target {} not connected or does not exist", target))), }; if let Err(_) = target_tx.send(command) { return Err(io::Error::new(io::ErrorKind::BrokenPipe, "Cannot transmit data to target")); } Ok(()) } async fn send2group(&mut self, sender: &str, target: &str, ignore: Option<Vec<&str>>, command: &Command) -> Result<(), io::Error>{ let group_users = match self.groups.get(target) { Some(g) => g, None => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Target group {} does not exist", target))), }; if target != sender && group_users.iter().find(|&x| x == sender).is_none() { return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("send2group error, sender {} is not a memeber of {}", sender, target))); } for name in group_users { let to_ignore = match &ignore { Some(vec) => { vec.iter().find(|&x| x == name).is_some() }, None => false, }; if name != sender && !to_ignore { let user_tx = match self.shared_conn.get_mut(name) { Some(u) => u, None => return Err(io::Error::new(io::ErrorKind::NotFound, format!("sender {} cannot find user {} in group {}", sender, name, target))), }; if let Err(err) = user_tx.send(command.clone()) { return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("Cannot send command to {} @ {}, unable to send over Tx: {}", sender, target, err))); } } } Ok(()) } pub fn list_group(&self, group_name: &str) -> Result<Vec<String>, io::Error> { let group = match self.groups.get(group_name) { Some(g) => g, None => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Group {} does not exist", group_name))), }; trace!("List of group {} is: {:?}", group_name, group); let max = ostrich_core::TXT_BYTES.len(); let mut users = vec![String::new()]; let mut count = 0; for usr in group { let name = format!("{}\n", usr); count += name.len(); let index = if count / max > 0 { (count/max) } else {0}; if index >= users.len() { users.push(String::new()); } users[index].push_str(&name); } Ok(users) } } pub struct Peer { socket: TcpStream, rx: Rx, pub groups: Vec<String>, } impl Peer { pub fn new(socket: TcpStream, rx: Rx) -> Peer { Peer{ socket, rx , groups: Vec::new()} } pub async fn send_command(&mut self, command: &Command) -> Result<usize, io::Error> { self.socket.write(&RawMessage::to_raw(command)?).await } pub async fn read_command(&mut self) -> Result<Option<Command>, io::Error> { let mut buffer = [0u8;PCK_SIZE]; let n = self.socket.read(&mut buffer).await?; if n == 0 { println!("returning ok"); return Ok(None); } let command = RawMessage::from_raw(&buffer)?; Ok(Some(command)) } } pub enum Message { ToSend(Command), Received(Command), } impl Stream for Peer { type Item = Result<Message, io::Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { if let Poll::Ready(Some(v)) = Pin::new(&mut self.rx).poll_next(cx) { return Poll::Ready(Some(Ok(Message::Received(v)))); } let mut data = [0u8; PCK_SIZE]; let n = match Pin::new(&mut self.socket).poll_read(cx, &mut data) { Poll::Ready(Ok(n)) => n, Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err))), Poll::Pending => return Poll::Pending, }; if n > 0 { let command = RawMessage::from_raw(&data)?; return Poll::Ready(Some(Ok(Message::ToSend(command)))); } else { return Poll::Ready(None); } } } #[derive(Debug)] #[derive(PartialEq)] struct User { pub name: String, password : String, } pub struct DataBase { db: Vec<User>, } impl DataBase { pub fn new(db_path: &str) -> Result<DataBase, io::Error> { let f = File::open(db_path)?; let mut buff = BufReader::new(f); let mut contents = String::new(); buff.read_to_string(&mut contents)?; let parsed = match json::parse(&contents) { Ok(db) => db, Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)), }; let mut db = Vec::new(); for user in parsed["users"].members() { let name = match user["name"].as_str() { Some(n) => n.to_string(), None => continue, }; trace!("Init user: {}", name); let password = match user["password"].as_str() { Some(s) => s.to_string(), None => continue, }; db.push(User {name, password}); } Ok(DataBase {db}) } pub fn name_exists(&self, name: &str) -> bool { self.db.iter().find(|&x| x.name == name ).is_some() } pub fn check_log_in_credentials(&self, command: Command) -> Result<String, io::Error> { let (username, password) = match &command { Command::Usr(u, p) => (u, p), _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, "Incorrect log in command")), }; let usr = User { name: username.clone().to_string(), password: password.to_string()}; match self.db.iter().position(|x| x.name == usr.name) { Some(index) => { if self.db[index] == usr { return Ok(username.to_string()); } return Err(io::Error::new(io::ErrorKind::PermissionDenied, "Wrong credentials")) }, None => return Ok(username.to_string()), } } }
use ostrich_core::*; #[macro_use] extern crate log; use tokio::sync::mpsc; use tokio::net::{TcpStream}; use tokio::io::{AsyncReadExt, AsyncWriteExt, AsyncRead}; use tokio::stream::{Stream}; use std::collections::HashMap; use std::io::{self, BufReader, prelude::*}; use std::fs::File; use core::task::{Poll, Context}; use core::pin::Pin; pub mod config; pub type Tx = mpsc::UnboundedSender<Command>; pub type Rx = mpsc::UnboundedReceiver<Command>; pub struct SharedConn { shared_conn: HashMap<String, Tx>, groups: HashMap<String, Vec<String>>, } impl SharedConn { pub fn new() -> SharedConn{ SharedConn{ shared_conn: HashMap::new(), groups: HashMap::new() } } pub fn add(&mut self, name: String, tx: Tx) -> Result<(), io::Error> { if self.shared_conn.contains_key(&name) { return Err(io::Error::new(io::ErrorKind::AlreadyExists, "A user with the same credentials is already loged in")); } self.shared_conn.insert(name, tx); Ok(()) } pub fn remove(&mut self, name: &str) -> Result<(), io::Error> { match self.shared_conn.remove(name) { Some(_) => Ok(()), None => Err(io::Error::new(io::ErrorKind::NotFound, "User not found")), } } pub async fn join_group(&mut self, group_name: &str, username: &str) -> Result<(), io::Error> { if let Some(group) = self.groups.get_mut(group_name) { if group.iter().find(|&x| *x == group_name.to_string()).is_some() { trace!("User {} wanted to join {} when already joined", username, group_name); return Ok(()) } else { group.push(username.to_string()); let notification = Command::ListUsr( group_name.to_string(), ListUsrOperation::Add, format!("\n{}", username)); self.send2group(username, group_name, None, &notification).await?; } } else { self.groups.insert(group_name.to_string(), vec![username.to_string()]); } Ok(()) } pub async fn leave_group(&mut self, username: &str, group_name: &str) -> Result<(), io::Error> { if let Some(group) = self.groups.get_mut(group_name) { if let Some(index) = group.iter().position(|name| name == username) { group.remove(index); let notification = Command::ListUsr( group_name.to_string(), ListUsrOperation::Remove, format!("\n{}", username)); self.send2group(group_name, group_name, Some(vec![&username]), &notification).await?; } else { return Err(io::Error::new(io::ErrorKind::NotFound, format!("User {} not found in {}", username, group_name))) } } else { return Err(io::Error::new(io::ErrorKind::NotFound, format!("Group {} not found", group_name))) } Ok(()) } pub async fn send(&mut self, command: Command) -> Result<(), io::Error>{ let (sender, target) = match &command { Command::Msg(s,t,_) => (s, t), _ => return Err(io::Error::new( io::ErrorKind::InvalidInput, "Wrong command type. Only MSG commands can be sended")), }; if target.starts_with("#") { return self.send2group(sender, target, None, &command).await; } let target_tx = match self.shared_conn.get_mut(&target.to_string()) { Some(t) => t, None => return Err(io::Error::new( io::ErrorKind::NotFound, format!("Target {} not connected or does not exist", target))), }; if let Err(_) = target_tx.send(command) { return Err(io::Error::new(io::ErrorKind::BrokenPipe, "Cannot transmit data to target")); } Ok(()) } async fn send2group(&mut self, sender: &str, target: &str, ignore: Option<Vec<&str>>, command: &Command) -> Result<(), io::Error>{ let group_users = match self.groups.get(target) { Some(g) => g, None => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Target group {} does not exist", target))), }; if target != sender && group_users.iter().find(|&x| x == sender).is_none() { return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("send2group error, sender {} is not a memeber of {}", sender, target))); } for name in group_users { let to_ignore = match &ignore { Some(vec) => { vec.iter().find(|&x| x == name).is_some() }, None => false, }; if name != sender && !to_ignore { let user_tx = match self.shared_conn.get_mut(name) { Some(u) => u, None => return Err(io::Error::new(io::ErrorKind::NotFound, format!("sender {} cannot find user {} in group {}", sender, name, target))), }; if let Err(err) = user_tx.send(command.clone()) { return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("Cannot send command to {} @ {}, unable to send over Tx: {}", sender, target, err))); } } } Ok(()) } pub fn list_group(&self, group_name: &str) -> Result<Vec<String>, io::Error> { let group = match self.groups.get(group_name) { Some(g) => g, None => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Group {} does not exist", group_name))), }; trace!("List of group {} is: {:?}", group_name, group); let max = ostrich_core::TXT_BYTES.len(); let mut users = vec![String::new()]; let mut count = 0; for usr in group { let name = format!("{}\n", usr); count += name.len(); let index = if count / max > 0 { (count/max) } else {0}; if index >= users.len() { users.push(String::new()); } users[index].push_str(&name); } Ok(users) } } pub struct Peer { socket: TcpStream, rx: Rx, pub groups: Vec<String>, } impl Peer { pub fn new(socket: TcpStream, rx: Rx) -> Peer { Peer{ socket, rx , groups: Vec::new()} } pub async fn send_command(&mut self, command: &Command) -> Result<usize, io::Error> { self.socket.write(&RawMessage::to_raw(command)?).await } pub async fn read_command(&mut self) -> Result<Option<Command>, io::Error> { let mut buffer = [0u8;PCK_SIZE]; let n = self.socket.read(&mut buffer).await?; if n == 0 { println!("returning ok"); return Ok(None); } let command = RawMessage::from_raw(&buffer)?; Ok(Some(command)) } } pub enum Message { ToSend(Command), Received(Command), } impl Stream for Peer { type Item = Result<Message, io::Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { if let Poll::Ready(Some(v)) = Pin::new(&mut self.rx).poll_next(cx) { return Poll::Ready(Some(Ok(Message::Received(v)))); } let mut data = [0u8; PCK_SIZE]; let n = match Pin::new(&mut self.socket).poll_read(cx, &mut data) { Poll::Ready(Ok(n)) => n, Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err))), Poll::Pending => return Poll::Pending, }; if n > 0 { let command = RawMessage::from_raw(&data)?; return Poll::Ready(Some(Ok(Message::ToSend(command)))); } else { return Poll::Ready(None); } } } #[derive(Debug)] #[derive(PartialEq)] struct User { pub name: String, password : String, } pub struct DataBase { db: Vec<User>, } impl DataBase { pub fn new(db_path: &str) -> Result<DataBase, io::Error> { let f = File::open(db_path)?; let mut buff = BufReader::new(f); let mut contents = String::new(); buff.read_to_string(&mut contents)?; let parsed = match json::parse(&contents) { Ok(db) => db, Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)), }; let mut db = Vec::new(); for user in parsed["users"].members() {
trace!("Init user: {}", name); let password = match user["password"].as_str() { Some(s) => s.to_string(), None => continue, }; db.push(User {name, password}); } Ok(DataBase {db}) } pub fn name_exists(&self, name: &str) -> bool { self.db.iter().find(|&x| x.name == name ).is_some() } pub fn check_log_in_credentials(&self, command: Command) -> Result<String, io::Error> { let (username, password) = match &command { Command::Usr(u, p) => (u, p), _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, "Incorrect log in command")), }; let usr = User { name: username.clone().to_string(), password: password.to_string()}; match self.db.iter().position(|x| x.name == usr.name) { Some(index) => { if self.db[index] == usr { return Ok(username.to_string()); } return Err(io::Error::new(io::ErrorKind::PermissionDenied, "Wrong credentials")) }, None => return Ok(username.to_string()), } } }
let name = match user["name"].as_str() { Some(n) => n.to_string(), None => continue, };
assignment_statement
[ { "content": "use serde::Deserialize;\n\nuse toml;\n\n\n\nuse std::fs::File;\n\nuse std::io::Read;\n\n\n\n#[derive(Deserialize)]\n\npub struct Config {\n\n pub ip_address: String,\n\n pub port: usize,\n\n\n\n pub logger_file: String,\n\n pub database_file: String,\n\n}\n\n\n\nimpl Config {\n\n\n\n ...
Rust
victor/src/dom/mod.rs
servo/victor
dda60efe07dd4cae0e9d93780ed661d41efb16b9
mod html; use crate::style::StyleSetBuilder; use html5ever::tendril::StrTendril; use html5ever::{Attribute, ExpandedName, LocalName, QualName}; use std::borrow::Cow; use std::fmt; pub struct Document { nodes: Vec<Node>, style_elements: Vec<NodeId>, } pub struct Node { pub(crate) parent: Option<NodeId>, pub(crate) next_sibling: Option<NodeId>, pub(crate) previous_sibling: Option<NodeId>, pub(crate) first_child: Option<NodeId>, pub(crate) last_child: Option<NodeId>, pub(crate) data: NodeData, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct NodeId(std::num::NonZeroUsize); impl Document { fn new() -> Self { let dummy = Node::new(NodeData::Document); let document_node = Node::new(NodeData::Document); Document { nodes: vec![dummy, document_node], style_elements: Vec::new(), } } fn document_node_id() -> NodeId { NodeId(std::num::NonZeroUsize::new(1).unwrap()) } pub fn parse_stylesheets(&self, style_set: &mut StyleSetBuilder) { for &id in &self.style_elements { let element = &self[id]; if let Some(type_attr) = element.as_element().unwrap().get_attr(&local_name!("type")) { if !type_attr.eq_ignore_ascii_case("text/css") { continue } } style_set.add_stylesheet(&self.child_text_content(id)) } } fn push_node(&mut self, node: Node) -> NodeId { let next_index = self.nodes.len(); self.nodes.push(node); NodeId(std::num::NonZeroUsize::new(next_index).unwrap()) } fn detach(&mut self, node: NodeId) { let (parent, previous_sibling, next_sibling) = { let node = &mut self[node]; ( node.parent.take(), node.previous_sibling.take(), node.next_sibling.take(), ) }; if let Some(next_sibling) = next_sibling { self[next_sibling].previous_sibling = previous_sibling } else if let Some(parent) = parent { self[parent].last_child = previous_sibling; } if let Some(previous_sibling) = previous_sibling { self[previous_sibling].next_sibling = next_sibling; } else if let Some(parent) = parent { self[parent].first_child = next_sibling; } } fn append(&mut self, parent: NodeId, new_child: NodeId) { self.detach(new_child); self[new_child].parent = Some(parent); if let Some(last_child) = self[parent].last_child.take() { self[new_child].previous_sibling = Some(last_child); debug_assert!(self[last_child].next_sibling.is_none()); self[last_child].next_sibling = Some(new_child); } else { debug_assert!(self[parent].first_child.is_none()); self[parent].first_child = Some(new_child); } self[parent].last_child = Some(new_child); } fn insert_before(&mut self, sibling: NodeId, new_sibling: NodeId) { self.detach(new_sibling); self[new_sibling].parent = self[sibling].parent; self[new_sibling].next_sibling = Some(sibling); if let Some(previous_sibling) = self[sibling].previous_sibling.take() { self[new_sibling].previous_sibling = Some(previous_sibling); debug_assert_eq!(self[previous_sibling].next_sibling, Some(sibling)); self[previous_sibling].next_sibling = Some(new_sibling); } else if let Some(parent) = self[sibling].parent { debug_assert_eq!(self[parent].first_child, Some(sibling)); self[parent].first_child = Some(new_sibling); } self[sibling].previous_sibling = Some(new_sibling); } fn child_text_content(&self, node: NodeId) -> Cow<StrTendril> { let mut link = self[node].first_child; let mut text = None; while let Some(child) = link { if let NodeData::Text { contents } = &self[child].data { match &mut text { None => text = Some(Cow::Borrowed(contents)), Some(text) => text.to_mut().push_tendril(&contents), } } link = self[child].next_sibling; } text.unwrap_or_else(|| Cow::Owned(StrTendril::new())) } pub(crate) fn root_element(&self) -> NodeId { let first_child; { let document_node = &self[Document::document_node_id()]; assert!(matches!(document_node.data, NodeData::Document)); assert!(document_node.parent.is_none()); assert!(document_node.next_sibling.is_none()); assert!(document_node.previous_sibling.is_none()); first_child = document_node.first_child } let mut root = None; for child in self.node_and_next_siblings(first_child.unwrap()) { match &self[child].data { NodeData::Doctype { .. } | NodeData::Comment { .. } | NodeData::ProcessingInstruction { .. } => {} NodeData::Document | NodeData::Text { .. } => { panic!("Unexpected node type under document node") } NodeData::Element(_) => { assert!(root.is_none(), "Found two root elements"); root = Some(child) } } } root.unwrap() } pub(crate) fn node_and_next_siblings<'a>( &'a self, node: NodeId, ) -> impl Iterator<Item = NodeId> + 'a { successors(Some(node), move |&node| self[node].next_sibling) } } impl std::ops::Index<NodeId> for Document { type Output = Node; #[inline] fn index(&self, id: NodeId) -> &Node { &self.nodes[id.0.get()] } } impl std::ops::IndexMut<NodeId> for Document { #[inline] fn index_mut(&mut self, id: NodeId) -> &mut Node { &mut self.nodes[id.0.get()] } } pub(crate) enum NodeData { Document, Doctype { _name: StrTendril, _public_id: StrTendril, _system_id: StrTendril, }, Text { contents: StrTendril, }, Comment { _contents: StrTendril, }, Element(ElementData), ProcessingInstruction { _target: StrTendril, _contents: StrTendril, }, } pub(crate) struct ElementData { pub(crate) name: QualName, pub(crate) attrs: Vec<Attribute>, pub(crate) mathml_annotation_xml_integration_point: bool, } impl ElementData { pub(crate) fn get_attr(&self, name: &LocalName) -> Option<&StrTendril> { let name = ExpandedName { ns: &ns!(), local: name, }; self.attrs.iter().find_map(|attr| { if attr.name.expanded() == name { Some(&attr.value) } else { None } }) } } #[test] #[cfg(target_pointer_width = "64")] fn size_of() { use std::mem::size_of; assert_eq!(size_of::<Node>(), 112); assert_eq!(size_of::<NodeData>(), 72); assert_eq!(size_of::<ElementData>(), 64); } impl Node { pub(crate) fn in_html_document(&self) -> bool { true } pub(crate) fn as_element(&self) -> Option<&ElementData> { match self.data { NodeData::Element(ref data) => Some(data), _ => None, } } pub(crate) fn as_text(&self) -> Option<&StrTendril> { match self.data { NodeData::Text { ref contents } => Some(contents), _ => None, } } fn new(data: NodeData) -> Self { Node { parent: None, previous_sibling: None, next_sibling: None, first_child: None, last_child: None, data: data, } } } impl fmt::Debug for Node { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ptr: *const Node = self; f.debug_tuple("Node").field(&ptr).finish() } } fn successors<T, F>(first: Option<T>, mut succ: F) -> impl Iterator<Item = T> where F: FnMut(&T) -> Option<T>, { unfold(first, move |next| { next.take().map(|item| { *next = succ(&item); item }) }) } fn unfold<T, St, F>(initial_state: St, f: F) -> Unfold<St, F> where F: FnMut(&mut St) -> Option<T>, { Unfold { state: initial_state, f, } } struct Unfold<St, F> { state: St, f: F, } impl<T, St, F> Iterator for Unfold<St, F> where F: FnMut(&mut St) -> Option<T>, { type Item = T; fn next(&mut self) -> Option<Self::Item> { (self.f)(&mut self.state) } }
mod html; use crate::style::StyleSetBuilder; use html5ever::tendril::StrTendril; use html5ever::{Attribute, ExpandedName, LocalName, QualName}; use std::borrow::Cow; use std::fmt; pub struct Document { nodes: Vec<Node>, style_elements: Vec<NodeId>, } pub struct Node { pub(crate) parent: Option<NodeId>, pub(crate) next_sibling: Option<NodeId>, pub(crate) previous_sibling: Option<NodeId>, pub(crate) first_child: Option<NodeId>, pub(crate) last_child: Option<NodeId>, pub(crate) data: NodeData, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct NodeId(std::num::NonZeroUsize); impl Document { fn new() -> Self { let dummy = Node::new(NodeData::Document); let document_node = Node::new(NodeData::Document); Document { nodes: vec![dummy, document_node], style_elements: Vec::new(), } } fn document_node_id() -> NodeId { NodeId(std::num::NonZeroUsize::new(1).unwrap()) } pub fn parse_stylesheets(&self, style_set: &mut StyleSetBuilder) { for &id in &self.style_elements { let element = &self[id]; if let Some(type_attr) = element.as_element().unwrap().get_attr(&local_name!("type")) { if !type_attr.eq_ignore_ascii_case("text/css") { continue } } style_set.add_stylesheet(&self.child_text_content(id)) } } fn push_node(&mut self, node: Node) -> NodeId { let next_index = self.nodes.len(); self.nodes.push(node); NodeId(std::num::NonZeroUsize::new(next_index).unwrap()) } fn detach(&mut self, node: NodeId) { let (parent, previous_sibling, next_sibling) = { let node = &mut self[node]; ( node.parent.take(), node.previous_sibling.take(), node.next_sibling.take(), ) }; if let Some(next_sibling) = next_sibling { self[next_sibling].previous_sibling = previous_sibling } else if let Some(parent) = parent { self[parent].last_child = previous_sibling; } if let Some(previous_sibling) = previous_sibling { self[previous_sibling].next_sibling = next_sibling; } else if let Some(parent) = parent { self[parent].first_child = next_sibling; } } fn append(&mut self, parent: NodeId, new_child: NodeId) { self.detach(new_child); self[new_child].parent = Some(parent); if let Some(last_child) = self[parent].last_child.take() { self[new_child].previous_sibling = Some(last_child); debug_assert!(self[last_child].next_sibling.is_none()); self[last_child].next_sibling = Some(new_child); } else { debug_assert!(self[parent].first_child.is_none()); self[parent].first_child = Some(new_child); } self[parent].last_child = Some(new_child); } fn insert_before(&mut self, sibling: NodeId, new_sibling: NodeId) { self.detach(new_sibling); self[new_sibling].parent = self[sibling].parent; self[new_sibling].next_sibling = Some(sibling); if let Some(previous_sibling) = self[sibling].previous_sibling.take() { self[new_sibling].previous_sibling = Some(previous_sibling); debug_assert_eq!(self[previous_sibling].next_sibling, Some(sibling)); self[previous_sibling].next_sibling = Some(new_sibling); } else if let Some(parent) = self[sibling].parent { debug_assert_eq!(self[parent].first_child, Some(sibling)); self[parent].first_child = Some(new_sibling); } self[sibling].previous_sibling = Some(new_sibling); } fn child_text_content(&self, node: NodeId) -> Cow<StrTendril> { let mut link = self[node].first_child; let mut text = None; while let Some(child) = link { if let NodeData::Text { contents } = &self[child].data { match &mut text { None => text = Some(Cow::Borrowed(contents)), Some(text) => text.to_mut().push_tendril(&contents), } } link = self[child].next_sibling; } text.unwrap_or_else(|| Cow::Owned(StrTendril::new())) } pub(crate) fn root_element(&self) -> NodeId { let first_child; { let document_node = &self[Document::document_node_id()]; assert!(matches!(document_node.data, NodeData::Document)); assert!(document_node.parent.is_none()); assert!(document_node.next_sibling.is_none()); assert!(document_node.previous_sibling.is_none()); first_child = document_node.first_child } let mut root = None; for child in self.node_and_next_siblings(first_child.unwrap()) { match &self[child].data { NodeData::Doctype { .. } | NodeData::Comment { .. } | NodeData::ProcessingInstruction { .. } => {} NodeData::Document | NodeData::Text { .. } => { panic!("Unexpected node type under document node") } NodeData::Element(_) => { assert!(root.is_none(), "Found two root elements"); root = Some(child) } } } root.unwrap() } pub(crate) fn node_and_next_siblings<'a>( &'a self, node: NodeId, ) -> impl Iterator<Item = NodeId> + 'a { successors(Some(node), move |&node| self[node].next_sibling) } } impl std::ops::Index<NodeId> for Document { type Output = Node; #[inline] fn index(&self, id: NodeId) -> &Node { &self.nodes[id.0.get()] } } impl std::ops::IndexMut<NodeId> for Document { #[inline] fn index_mut(&mut self, id: NodeId) -> &mut Node { &mut self.nodes[id.0.get()] } } pub(crate) enum NodeData { Document, Doctype { _name: StrTendril, _public_id: StrTendril, _system_id: StrTendril, }, Text { contents: StrTendril, }, Comment { _contents: StrTendril, }, Element(ElementData), ProcessingInstruction { _target: StrTendril, _contents: StrTendril, }, } pub(crate) struct ElementData { pub(crate) name: QualName, pub(crate) attrs: Vec<Attribute>, pub(crate) mathml_annotation_xml_integration_point: bool, } impl ElementData { pub(crate) fn get_attr(&self, name: &LocalName) -> Option<&StrTendril> { let name = ExpandedName { ns: &ns!(), local: name, }; self.attrs.iter().find_map(|attr| { if attr.name.expanded() == name { Some(&attr.value) } else { None } }) } } #[test] #[cfg(target_pointer_width = "64")] fn size_of() { use std::mem::size_of; assert_eq!(size_of::<Node>(), 112); assert_eq!(size_of::<NodeData>(), 72); assert_eq!(size_of::<ElementData>(), 64); } impl Node { pub(crate) fn in_html_document(&self) -> bool { true } pub(crate) fn as_element(&self) -> Option<&El
pub(crate) fn as_text(&self) -> Option<&StrTendril> { match self.data { NodeData::Text { ref contents } => Some(contents), _ => None, } } fn new(data: NodeData) -> Self { Node { parent: None, previous_sibling: None, next_sibling: None, first_child: None, last_child: None, data: data, } } } impl fmt::Debug for Node { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ptr: *const Node = self; f.debug_tuple("Node").field(&ptr).finish() } } fn successors<T, F>(first: Option<T>, mut succ: F) -> impl Iterator<Item = T> where F: FnMut(&T) -> Option<T>, { unfold(first, move |next| { next.take().map(|item| { *next = succ(&item); item }) }) } fn unfold<T, St, F>(initial_state: St, f: F) -> Unfold<St, F> where F: FnMut(&mut St) -> Option<T>, { Unfold { state: initial_state, f, } } struct Unfold<St, F> { state: St, f: F, } impl<T, St, F> Iterator for Unfold<St, F> where F: FnMut(&mut St) -> Option<T>, { type Item = T; fn next(&mut self) -> Option<Self::Item> { (self.f)(&mut self.state) } }
ementData> { match self.data { NodeData::Element(ref data) => Some(data), _ => None, } }
function_block-function_prefixed
[ { "content": "pub fn layout(text: &str, style: &Style) -> Result<Document, FontError> {\n\n let page_size = style.page_size * Px::per_mm();\n\n let page_margin = SideOffsets::from_length_all_same(style.page_margin * Px::per_mm());\n\n let page = Rect::new(Point::origin(), page_size);\n\n let content...
Rust
panbuild/projects.rs
louib/panbuild
2cb07ebd6c21d7f4f0fb588cb8ed4570f20d1344
use serde::{Deserialize, Serialize}; use std::path::Path; use std::process::Command; pub const CORE_PROJECTS: [&'static str; 20] = [ "https://git.savannah.gnu.org/cgit/bash.git", "https://git.savannah.gnu.org/cgit/make.git", "https://git.savannah.gnu.org/cgit/diffutils.git", "https://git.savannah.gnu.org/cgit/findutils.git", "https://git.savannah.gnu.org/cgit/gzip.git", "https://git.savannah.gnu.org/git/grep.git", "https://git.savannah.gnu.org/cgit/tar.git", "https://git.savannah.gnu.org/git/libtool.git", "https://git.lysator.liu.se/lsh/lsh.git", "https://git.savannah.gnu.org/cgit/gawk.git", "https://github.com/gwsw/less.git", "https://github.com/openbsd/src.git", "https://gcc.gnu.org/git/gcc.git", "https://git.sv.gnu.org/cgit/coreutils.git", "https://sourceware.org/git/binutils-gdb.git", "https://sourceware.org/git/glibc.git", "https://gitlab.gnome.org/GNOME/gtk.git", "https://gitlab.gnome.org/GNOME/glib.git", "https://dev.gnupg.org/source/gnupg.git", "https://gitlab.com/gnutls/gnutls.git", ]; #[derive(Serialize, Deserialize, Default)] pub struct SoftwareProject { pub id: String, pub name: String, pub summary: String, pub description: String, pub web_urls: Vec<String>, pub vcs_urls: Vec<String>, pub artifact_names: Vec<String>, pub build_systems: Vec<String>, pub maintainers: Vec<String>, pub default_branch: Option<String>, pub versions: Vec<String>, pub keywords: Vec<String>, pub root_hashes: Vec<String>, } impl SoftwareProject { pub fn harvest(repo_url: &str) -> SoftwareProject { let mut project = SoftwareProject::default(); let repo_path = crate::utils::clone_git_repo(repo_url).unwrap(); project.id = crate::utils::repo_url_to_reverse_dns(repo_url); for file_path in crate::utils::get_all_paths(Path::new(&repo_path)).unwrap() { let mut abstract_manifest = match crate::manifests::manifest::AbstractManifest::load_from_file(file_path.to_str().unwrap().to_string()) { Some(m) => m, None => continue, }; project.build_systems.push(abstract_manifest.get_type().unwrap().to_string()); } match crate::utils::get_git_repo_root_hashes(&repo_path) { Ok(root_hashes) => project.root_hashes = root_hashes, Err(e) => { log::warn!("Could not get root commit hashes for repo located at {}: {}.", &repo_path, e); } } project } pub fn merge(&mut self, other_project: &SoftwareProject) { for build_system in &other_project.build_systems { self.build_systems.push(build_system.clone()); } } } #[derive(Serialize, Deserialize, Default)] pub struct ProjectVersion { pub project_id: String, pub name: String, pub url: String, pub url_type: crate::modules::SourceType, pub tag: String, pub branch: String, pub sha256sum: String, pub dependencies: Vec<Dependency>, } #[derive(Serialize, Deserialize, Default)] pub struct Dependency { pub min_version: crate::version::SemanticVersion, pub max_version: crate::version::SemanticVersion, pub project_id: String, } pub fn get_modules() -> Vec<crate::modules::SoftwareModule> { let mut modules = vec![]; for project in crate::db::Database::get_all_projects() { for project_version in &project.versions { for artifact_name in &project.artifact_names { let mut module = crate::modules::SoftwareModule::default(); module.name = artifact_name.to_string(); module.version = project_version.to_string(); module.tag = project_version.to_string(); if project.vcs_urls.len() != 0 { module.url = project.vcs_urls[0].to_string(); } modules.push(module); } } } modules } pub fn get_project_tag_names() -> Vec<String> { return vec![]; } pub fn get_project_commit_signature() -> String { return String::from(""); }
use serde::{Deserialize, Serialize}; use std::path::Path; use std::process::Command; pub const CORE_PROJECTS: [&'static str; 20] = [ "https://git.savannah.gnu.org/cgit/bash.git", "https://git.savannah.gnu.org/cgit/make.git", "https://git.savannah.gnu.org/cgit/diffutils.git", "https://git.savannah.gnu.org/cgit/findutils.git", "https://git.savannah.gnu.org/cgit/gzip.git", "https://git.savannah.gnu.org/git/grep.git", "https://git.savannah.gnu.org/cgit/tar.git", "https://git.savannah.gnu.org/git/libtool.git", "https://git.lysator.liu.se/lsh/lsh.git", "https://git.savannah.gnu.org/cgit/gawk.git", "https://github.com/gwsw/less.git", "https://github.com/openbsd/src.git", "https://gcc.gnu.org/git/gcc.git", "https://git.sv.gnu.org/cgit/coreutils.git", "https://sourceware.org/git/binutils-gdb.git", "https://sourceware.org/git/glibc.git", "https://gitlab.gnome.org/GNOME/gtk.git", "https://gitlab.gnome.org/GNOME/glib.git", "https://dev.gnupg.org/source/gnupg.git", "https://gitlab.com/gnutls/gnutls.git", ]; #[derive(Serialize, Deserialize, Default)] pub struct SoftwareProject { pub id: String, pub name: String, pub summary: String, pub description: String, pub web_urls: Vec<String>, pub vcs_urls: Vec<String>, pub artifact_names: Vec<String>, pub build_systems: Vec<String>, pub maintainers: Vec<String>, pub default_branch: Option<String>, pub versions: Vec<String>, pub keywords: Vec<String>, pub root_hashes: Vec<String>, } impl SoftwareProject { pub fn harvest(repo_url: &str) -> SoftwareProject { let mut project = SoftwareProject::default(); let repo_path = crate::utils::clone_git_repo(repo_url).unwrap(); project.id = crate::utils::repo_url_to_reverse_dns(repo_url); for file_path in crate::utils::get_all_paths(Path::new(&repo_path)).unwrap() { let mut abstract_manifest = matc
pub fn merge(&mut self, other_project: &SoftwareProject) { for build_system in &other_project.build_systems { self.build_systems.push(build_system.clone()); } } } #[derive(Serialize, Deserialize, Default)] pub struct ProjectVersion { pub project_id: String, pub name: String, pub url: String, pub url_type: crate::modules::SourceType, pub tag: String, pub branch: String, pub sha256sum: String, pub dependencies: Vec<Dependency>, } #[derive(Serialize, Deserialize, Default)] pub struct Dependency { pub min_version: crate::version::SemanticVersion, pub max_version: crate::version::SemanticVersion, pub project_id: String, } pub fn get_modules() -> Vec<crate::modules::SoftwareModule> { let mut modules = vec![]; for project in crate::db::Database::get_all_projects() { for project_version in &project.versions { for artifact_name in &project.artifact_names { let mut module = crate::modules::SoftwareModule::default(); module.name = artifact_name.to_string(); module.version = project_version.to_string(); module.tag = project_version.to_string(); if project.vcs_urls.len() != 0 { module.url = project.vcs_urls[0].to_string(); } modules.push(module); } } } modules } pub fn get_project_tag_names() -> Vec<String> { return vec![]; } pub fn get_project_commit_signature() -> String { return String::from(""); }
h crate::manifests::manifest::AbstractManifest::load_from_file(file_path.to_str().unwrap().to_string()) { Some(m) => m, None => continue, }; project.build_systems.push(abstract_manifest.get_type().unwrap().to_string()); } match crate::utils::get_git_repo_root_hashes(&repo_path) { Ok(root_hashes) => project.root_hashes = root_hashes, Err(e) => { log::warn!("Could not get root commit hashes for repo located at {}: {}.", &repo_path, e); } } project }
function_block-function_prefixed
[ { "content": "pub fn normalize_name(name: &String) -> String {\n\n let mut response: String = \"\".to_string();\n\n for c in name.chars() {\n\n if c.is_alphabetic() || c.is_numeric() {\n\n response.push_str(&c.to_string());\n\n continue;\n\n }\n\n // We don't wan...
Rust
crates/swift-bridge-ir/src/parse/parse_struct.rs
Jomy10/swift-bridge
4a21fd134a2fd4d2418081ba962b97e6d56b155f
use crate::bridged_type::{SharedStruct, StructFields, StructSwiftRepr}; use crate::errors::{ParseError, ParseErrors}; use proc_macro2::{Ident, TokenTree}; use syn::parse::{Parse, ParseStream}; use syn::{ItemStruct, LitStr, Token}; pub(crate) struct SharedStructDeclarationParser<'a> { pub item_struct: ItemStruct, pub errors: &'a mut ParseErrors, } enum StructAttr { SwiftRepr((StructSwiftRepr, LitStr)), SwiftName(LitStr), Error(StructAttrParseError), AlreadyDeclared, } enum StructAttrParseError { InvalidSwiftRepr(LitStr), UnrecognizedAttribute(Ident), } #[derive(Default)] struct StructAttribs { swift_repr: Option<(StructSwiftRepr, LitStr)>, swift_name: Option<LitStr>, already_declared: bool, } struct ParsedAttribs(Vec<StructAttr>); impl Parse for ParsedAttribs { fn parse(input: ParseStream) -> syn::Result<Self> { if input.is_empty() { return Ok(ParsedAttribs(vec![])); } let opts = syn::punctuated::Punctuated::<_, syn::token::Comma>::parse_terminated(input)?; Ok(ParsedAttribs(opts.into_iter().collect())) } } impl Parse for StructAttr { fn parse(input: ParseStream) -> syn::Result<Self> { let key: Ident = input.parse()?; let attr = match key.to_string().as_str() { "swift_repr" => { input.parse::<Token![=]>()?; let repr: LitStr = input.parse()?; match repr.value().as_str() { "class" => StructAttr::SwiftRepr((StructSwiftRepr::Class, repr)), "struct" => StructAttr::SwiftRepr((StructSwiftRepr::Structure, repr)), _ => StructAttr::Error(StructAttrParseError::InvalidSwiftRepr(repr)), } } "swift_name" => { input.parse::<Token![=]>()?; let name = input.parse()?; StructAttr::SwiftName(name) } "already_declared" => StructAttr::AlreadyDeclared, _ => { move_input_cursor_to_next_comma(input); StructAttr::Error(StructAttrParseError::UnrecognizedAttribute(key)) } }; Ok(attr) } } impl<'a> SharedStructDeclarationParser<'a> { pub fn parse(self) -> Result<SharedStruct, syn::Error> { let item_struct = self.item_struct; let mut attribs = StructAttribs::default(); for attr in item_struct.attrs { let sections: ParsedAttribs = attr.parse_args()?; for attr in sections.0 { match attr { StructAttr::SwiftRepr((repr, lit_str)) => { attribs.swift_repr = Some((repr, lit_str)); } StructAttr::SwiftName(name) => { attribs.swift_name = Some(name); } StructAttr::Error(err) => match err { StructAttrParseError::InvalidSwiftRepr(val) => { self.errors.push(ParseError::StructInvalidSwiftRepr { swift_repr_attr_value: val.clone(), }); attribs.swift_repr = Some((StructSwiftRepr::Structure, val)); } StructAttrParseError::UnrecognizedAttribute(attribute) => { self.errors .push(ParseError::StructUnrecognizedAttribute { attribute }); } }, StructAttr::AlreadyDeclared => { attribs.already_declared = true; } }; } } let swift_repr = if item_struct.fields.len() == 0 { if let Some((swift_repr, lit_str)) = attribs.swift_repr { if swift_repr == StructSwiftRepr::Class { self.errors.push(ParseError::EmptyStructHasSwiftReprClass { struct_ident: item_struct.ident.clone(), swift_repr_attr_value: lit_str, }); } } StructSwiftRepr::Structure } else if let Some((swift_repr, _)) = attribs.swift_repr { swift_repr } else { self.errors.push(ParseError::StructMissingSwiftRepr { struct_ident: item_struct.ident.clone(), }); StructSwiftRepr::Structure }; let shared_struct = SharedStruct { name: item_struct.ident, swift_repr, fields: StructFields::from_syn_fields(item_struct.fields), swift_name: attribs.swift_name, already_declared: attribs.already_declared, }; Ok(shared_struct) } } fn move_input_cursor_to_next_comma(input: ParseStream) { if !input.peek(Token![,]) { let _ = input.step(|cursor| { let mut current_cursor = *cursor; while let Some((tt, next)) = current_cursor.token_tree() { match &tt { TokenTree::Punct(punct) if punct.as_char() == ',' => { return Ok(((), current_cursor)); } _ => current_cursor = next, } } Ok(((), current_cursor)) }); } } #[cfg(test)] mod tests { use super::*; use crate::test_utils::{parse_errors, parse_ok}; use quote::{quote, ToTokens}; #[test] fn parse_unit_struct() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { struct Foo; struct Bar(); struct Bazz {} } }; let module = parse_ok(tokens); assert_eq!(module.types.types().len(), 3); for (idx, name) in vec!["Foo", "Bar", "Bazz"].into_iter().enumerate() { let ty = &module.types.types()[idx].unwrap_shared_struct(); assert_eq!(ty.name, name); assert_eq!(ty.swift_repr, StructSwiftRepr::Structure); } } #[test] fn error_if_missing_swift_repr() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { struct Foo { bar: u8 } } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 1); match &errors[0] { ParseError::StructMissingSwiftRepr { struct_ident } => { assert_eq!(struct_ident, "Foo"); } _ => panic!(), }; } #[test] fn error_if_invalid_swift_repr() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_repr = "an-invalid-value")] struct Foo { bar: u8 } } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 1); match &errors[0] { ParseError::StructInvalidSwiftRepr { swift_repr_attr_value, } => { assert_eq!(swift_repr_attr_value.value(), "an-invalid-value"); } _ => panic!(), }; } #[test] fn error_if_empty_struct_swift_repr_set_to_class() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_repr = "class")] struct Foo; #[swift_bridge(swift_repr = "class")] struct Bar; #[swift_bridge(swift_repr = "class")] struct Buzz; } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 3); for (idx, struct_name) in vec!["Foo", "Bar", "Buzz"].into_iter().enumerate() { match &errors[idx] { ParseError::EmptyStructHasSwiftReprClass { struct_ident, swift_repr_attr_value, } => { assert_eq!(struct_ident, struct_name); assert_eq!(swift_repr_attr_value.value(), "class"); } _ => panic!(), }; } } #[test] fn parse_struct_with_named_u8_field() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_repr = "struct")] struct Foo { bar: u8 } } }; let module = parse_ok(tokens); let ty = module.types.types()[0].unwrap_shared_struct(); match &ty.fields { StructFields::Named(fields) => { let field = &fields[0]; assert_eq!(field.name, "bar"); assert_eq!(field.ty.to_token_stream().to_string(), "u8"); } _ => panic!(), }; } #[test] fn parse_swift_name_attribute() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_name = "FfiFoo")] struct Foo; } }; let module = parse_ok(tokens); let ty = module.types.types()[0].unwrap_shared_struct(); assert_eq!(ty.swift_name.as_ref().unwrap().value(), "FfiFoo"); } #[test] fn parses_multiple_struct_attributes() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_name = "FfiFoo", swift_repr = "class")] struct Foo { fied: u8 } } }; let module = parse_ok(tokens); let ty = module.types.types()[0].unwrap_shared_struct(); assert_eq!(ty.swift_name.as_ref().unwrap().value(), "FfiFoo"); assert_eq!(ty.swift_repr, StructSwiftRepr::Class); } #[test] fn parses_struct_already_declared_attribute() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(already_declared, swift_repr = "struct")] struct SomeType; } }; let module = parse_ok(tokens); let ty = module.types.types()[0].unwrap_shared_struct(); assert!(ty.already_declared); } #[test] fn error_if_attribute_unrecognized() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(unrecognized, invalid_attribute = "hi", swift_repr = "struct")] struct SomeType; } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 2); match &errors[0] { ParseError::StructUnrecognizedAttribute { attribute } => { assert_eq!(&attribute.to_string(), "unrecognized"); } _ => panic!(), }; match &errors[1] { ParseError::StructUnrecognizedAttribute { attribute } => { assert_eq!(&attribute.to_string(), "invalid_attribute"); } _ => panic!(), }; } }
use crate::bridged_type::{SharedStruct, StructFields, StructSwiftRepr}; use crate::errors::{ParseError, ParseErrors}; use proc_macro2::{Ident, TokenTree}; use syn::parse::{Parse, ParseStream}; use syn::{ItemStruct, LitStr, Token}; pub(crate) struct SharedStructDeclarationParser<'a> { pub item_struct: ItemStruct, pub errors: &'a mut ParseErrors, } enum StructAttr { SwiftRepr((StructSwiftRepr, LitStr)), SwiftName(LitStr), Error(StructAttrParseError), AlreadyDeclared, } enum StructAttrParseError { InvalidSwiftRepr(LitStr), UnrecognizedAttribute(Ident), } #[derive(Default)] struct StructAttribs { swift_repr: Option<(StructSwiftRepr, LitStr)>, swift_name: Option<LitStr>, already_declared: bool, } struct ParsedAttribs(Vec<StructAttr>); impl Parse for ParsedAttribs { fn parse(input: ParseStream) -> syn::Result<Self> { if input.is_empty() { return Ok(ParsedAttribs(vec![])); } let opts = syn::punctuated::Punctuated::<_, syn::token::Comma>::parse_terminated(input)?; Ok(ParsedAttribs(opts.into_iter().collect())) } } impl Parse for StructAttr { fn parse(input: ParseStream) -> syn::Result<Self> { let key: Ident = input.parse()?; let attr = match key.to_string().as_str() { "swift_repr" => { input.parse::<Token![=]>()?; let repr: LitStr = input.parse()?; match repr.value().as_str() { "class" => StructAttr::SwiftRepr((StructSwiftRepr::Class, repr)), "struct" => StructAttr::SwiftRepr((StructSwiftRepr::Structure, repr)), _ => StructAttr::Error(StructAttrParseError::InvalidSwiftRepr(repr)), } } "swift_name" => { input.parse::<Token![=]>()?; let name = input.parse()?; StructAttr::SwiftName(name) } "already_declared" => StructAttr::AlreadyDeclared, _ => { move_input_cursor_to_next_comma(input); StructAttr::Error(StructAttrParseError::UnrecognizedAttribute(key)) } }; Ok(attr) } } impl<'a> SharedStructDeclarationParser<'a> { pub fn parse(self) -> Result<SharedStruct, syn::Error> { let item_struct = self.item_struct; let mut attribs = StructAttribs::default(); for attr in item_struct.attrs { let sections: ParsedAttribs = attr.parse_args()?; for attr in sections.0 { match attr { StructAttr::SwiftRepr((repr, lit_str)) => { attribs.swift_repr = Some((repr, lit_str)); } StructAttr::SwiftName(name) => { attribs.swift_name = Some(name); } StructAttr::Error(err) => match err { StructAttrParseError::InvalidSwiftRepr(val) => { self.errors.push(ParseError::StructInvalidSwiftRepr { swift_repr_attr_value: val.clone(), }); attribs.swift_repr = Some((StructSwiftRepr::Structure, val)); } StructAttrParseError::UnrecognizedAttribute(attribute) => { self.errors .push(ParseError::StructUnrecognizedAttribute { attribute }); } }, StructAttr::AlreadyDeclared => { attribs.already_declared = true; } }; } } let swift_repr = if item_struct.fields.len() == 0 { if let Some((swift_repr, lit_str)) = attribs.swift_repr { if swift_repr == StructSwiftRepr::Class { self.errors.push(ParseError::EmptyStructHasSwiftReprClass { struct_ident: item_struct.ident.clone(), swift_repr_attr_value: lit_str, }); } } StructSwiftRepr::Structure } else if let Some((swift_repr, _)) = attribs.swift_repr { swift_repr } else { self.errors.push(ParseError::StructMissingSwiftRepr { struct_ident: item_struct.ident.clone(), }); StructSwiftRepr::Structure }; let shared_struct = SharedStruct { name: item_struct.ident, swift_repr, fields: StructFields::from_syn_fields(item_struct.fields), swift_name: attribs.swift_name, already_declared: attribs.already_declared, }; Ok(shared_struct) } } fn move_input_cursor_to_next_comma(input: ParseStream) { if !input.peek(Token![,]) { let _ = input.step(|cursor| { let mut current_cursor = *cursor; while let Some((tt, next)) = current_cursor.token_tree() { match &tt { TokenTree::Punct(punct) if punct.as_char() == ',' => { return Ok(((), current_cursor)); } _ => current_cursor = next, } } Ok(((), current_cursor)) }); } } #[cfg(test)] mod tests { use super::*; use crate::test_utils::{parse_errors, parse_ok}; use quote::{quote, ToTokens}; #[test] fn parse_unit_struct() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { struct Foo; struct Bar(); struct Bazz {} } }; let module = parse_ok(tokens); assert_eq!(module.types.types().len(), 3); for (idx, name) in vec!["Foo", "Bar", "Bazz"].into_iter().enumerate() { let ty = &module.types.types()[idx].unwrap_shared_struct(); assert_eq!(ty.name, name); assert_eq!(ty.swift_repr, StructSwiftRepr::Structure); } } #[test] fn error_if_missing_swift_repr() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { struct Foo { bar: u8 } } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 1); match &errors[0] { ParseError::StructMissingSwiftRepr { struct_ident } => { assert_eq!(struct_ident, "Foo"); } _ => panic!(), }; } #[test] fn error_if_invalid_swift_repr() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_repr = "an-invalid-value")] struct Foo { bar: u8 } } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 1); match &errors[0] { ParseError::StructInvalidSwiftRepr { swift_repr_attr_value, } => { assert_eq!(swift_repr_attr_value.value(), "an-invalid-value"); } _ => panic!(), }; } #[test] fn error_if_empty_struct_swift_repr_set_to_class() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_repr = "class")] struct Foo; #[swift_bridge(swift_repr = "class")] struct Bar; #[swift_bridge(swift_repr = "class")] struct Buzz; } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 3); for (idx, struct_name) in vec!["Foo", "Bar", "Buzz"].into_iter().enumerate() { match &errors[idx] { ParseError::EmptyStructHasSwiftReprClass { struct_ident, swift_repr_attr_value, } => { assert_eq!(struct_ident, struct_name); assert_eq!(swift_repr_attr_value.value(), "class"); } _ => panic!(), }; } } #[test] fn parse_struct_with_named_u8_field() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_repr = "struct")] struct Foo { bar: u8 } } }; let module = parse_ok(tokens); let ty = module.types.types()[0].unwrap_shared_struct(); match &ty.fields { StructFields::Named(fields) => { let field = &fields[0]; assert_eq!(field.name, "bar"); assert_eq!(field.ty.to_token_stream().to_string(), "u8"); } _ => panic!(), }; } #[test] fn parse_swift_name_attribute() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_name = "FfiFoo")] struct Foo; } }; let module = parse_ok(tokens);
#[test] fn parses_multiple_struct_attributes() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_name = "FfiFoo", swift_repr = "class")] struct Foo { fied: u8 } } }; let module = parse_ok(tokens); let ty = module.types.types()[0].unwrap_shared_struct(); assert_eq!(ty.swift_name.as_ref().unwrap().value(), "FfiFoo"); assert_eq!(ty.swift_repr, StructSwiftRepr::Class); } #[test] fn parses_struct_already_declared_attribute() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(already_declared, swift_repr = "struct")] struct SomeType; } }; let module = parse_ok(tokens); let ty = module.types.types()[0].unwrap_shared_struct(); assert!(ty.already_declared); } #[test] fn error_if_attribute_unrecognized() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(unrecognized, invalid_attribute = "hi", swift_repr = "struct")] struct SomeType; } }; let errors = parse_errors(tokens); assert_eq!(errors.len(), 2); match &errors[0] { ParseError::StructUnrecognizedAttribute { attribute } => { assert_eq!(&attribute.to_string(), "unrecognized"); } _ => panic!(), }; match &errors[1] { ParseError::StructUnrecognizedAttribute { attribute } => { assert_eq!(&attribute.to_string(), "invalid_attribute"); } _ => panic!(), }; } }
let ty = module.types.types()[0].unwrap_shared_struct(); assert_eq!(ty.swift_name.as_ref().unwrap().value(), "FfiFoo"); }
function_block-function_prefix_line
[ { "content": "fn swift_calls_rust_struct_with_no_fields(arg: ffi::StructWithNoFields) -> ffi::StructWithNoFields {\n\n arg\n\n}\n\n\n", "file_path": "crates/swift-integration-tests/src/shared_types/shared_struct.rs", "rank": 0, "score": 256582.61491422064 }, { "content": "fn rust_echo_mut...
Rust
mcu/bobbin-sam/samd21/src/ext/adc.rs
thomasantony/bobbin-sdk
37375ca40351352a029aceb8b0cf17650a3624f6
use periph::adc::*; use bobbin_common::bits::*; use bobbin_hal::analog::AnalogRead; use gclk; #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(u8)] pub enum Resolution { Bits12 = 0x0, Bits16 = 0x1, Bits10 = 0x2, Bits8 = 0x3, } impl AdcPeriph { pub fn init(&self) { while gclk::GCLK.status().syncbusy() != 0 {} gclk::GCLK.set_clkctrl(|r| r .set_id(0x1e) .set_gen(0x0) .set_clken(true) ); self.wait_busy(); self.set_ctrlb(|r| r.set_prescaler(0x7).set_ressel(0x2)); self.set_sampctrl(|r| r.set_samplen(0x3f)); self.wait_busy(); self.set_inputctrl(|r| r.set_muxneg(0x18)); self.set_avgctrl(|r| r.set_samplenum(0x0).set_adjres(0x0)); self.with_inputctrl(|r| r.set_gain(0xf)); self.set_refctrl(|r| r.set_refsel(0x2)); } } impl AdcPeriph { pub fn wait_busy(&self) -> &Self { while self.status().syncbusy() != 0 {} self } pub fn enabled(&self) -> bool { self.ctrla().enable() != 0 } pub fn set_enabled(&self, value: bool) -> &Self { self.with_ctrla(|r| r.set_enable(value)) } pub fn resolution(&self) -> Resolution { match self.ctrlb().ressel() { U2::B00 => Resolution::Bits12, U2::B01 => Resolution::Bits16, U2::B10 => Resolution::Bits10, U2::B11 => Resolution::Bits8, } } pub fn set_resolution(&self, value: Resolution) -> &Self { self.with_ctrlb(|r| r.set_ressel(value as u8)) } pub fn muxpos(&self) -> U5 { self.inputctrl().muxpos() } pub fn set_muxpos(&self, value: U5) -> &Self { self.with_inputctrl(|r| r.set_muxpos(value)) } pub fn muxneg(&self) -> U5 { self.inputctrl().muxneg() } pub fn set_muxneg(&self, value: U5) -> &Self { self.with_inputctrl(|r| r.set_muxneg(value)) } pub fn result_ready(&self) -> bool { self.intflag().resrdy() != 0 } pub fn clr_result_ready(&self) -> &Self { self.set_intflag(|r| r.set_resrdy(1)) } pub fn wait_result_ready(&self) -> &Self { while !self.result_ready() {} self } pub fn trigger(&self) -> &Self { self.set_swtrig(|r| r.set_start(1)) } pub fn result_16(&self) -> U16 { self.result().result_16() } pub fn result_12(&self) -> U12 { self.result().result_12() } pub fn result_10(&self) -> U10 { self.result().result_10() } pub fn result_8(&self) -> U8 { self.result().result_8() } } macro_rules! impl_analog_read { ($t:ty, $res:expr, $meth:ident) => ( impl AnalogRead<$t> for AdcCh { fn start(&self) -> &Self { self.periph .set_enabled(false) .set_resolution($res) .set_muxpos(self.index.into()) .set_enabled(true) .clr_result_ready() .trigger(); self } fn is_complete(&self) -> bool { self.periph.result_ready() } fn read(&self) -> $t { self.periph.$meth() } } ) } impl_analog_read!(U8, Resolution::Bits8, result_8); impl_analog_read!(U10, Resolution::Bits10, result_10); impl_analog_read!(U12, Resolution::Bits12, result_12);
use periph::adc::*; use bobbin_common::bits::*; use bobbin_hal::analog::AnalogRead; use gclk; #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(u8)] pub enum Resolution { Bits12 = 0x0, Bits16 = 0x1, Bits10 = 0x2, Bits8 = 0x3, } impl AdcPeriph { pub fn init(&self) { while gclk::GCLK.status().syncbusy() != 0 {} gclk::GCLK.set_clkctrl(|r| r .set_id(0x1e) .set_gen(0x0) .set_clken(true) ); self.wait_busy();
} impl AdcPeriph { pub fn wait_busy(&self) -> &Self { while self.status().syncbusy() != 0 {} self } pub fn enabled(&self) -> bool { self.ctrla().enable() != 0 } pub fn set_enabled(&self, value: bool) -> &Self { self.with_ctrla(|r| r.set_enable(value)) } pub fn resolution(&self) -> Resolution { match self.ctrlb().ressel() { U2::B00 => Resolution::Bits12, U2::B01 => Resolution::Bits16, U2::B10 => Resolution::Bits10, U2::B11 => Resolution::Bits8, } } pub fn set_resolution(&self, value: Resolution) -> &Self { self.with_ctrlb(|r| r.set_ressel(value as u8)) } pub fn muxpos(&self) -> U5 { self.inputctrl().muxpos() } pub fn set_muxpos(&self, value: U5) -> &Self { self.with_inputctrl(|r| r.set_muxpos(value)) } pub fn muxneg(&self) -> U5 { self.inputctrl().muxneg() } pub fn set_muxneg(&self, value: U5) -> &Self { self.with_inputctrl(|r| r.set_muxneg(value)) } pub fn result_ready(&self) -> bool { self.intflag().resrdy() != 0 } pub fn clr_result_ready(&self) -> &Self { self.set_intflag(|r| r.set_resrdy(1)) } pub fn wait_result_ready(&self) -> &Self { while !self.result_ready() {} self } pub fn trigger(&self) -> &Self { self.set_swtrig(|r| r.set_start(1)) } pub fn result_16(&self) -> U16 { self.result().result_16() } pub fn result_12(&self) -> U12 { self.result().result_12() } pub fn result_10(&self) -> U10 { self.result().result_10() } pub fn result_8(&self) -> U8 { self.result().result_8() } } macro_rules! impl_analog_read { ($t:ty, $res:expr, $meth:ident) => ( impl AnalogRead<$t> for AdcCh { fn start(&self) -> &Self { self.periph .set_enabled(false) .set_resolution($res) .set_muxpos(self.index.into()) .set_enabled(true) .clr_result_ready() .trigger(); self } fn is_complete(&self) -> bool { self.periph.result_ready() } fn read(&self) -> $t { self.periph.$meth() } } ) } impl_analog_read!(U8, Resolution::Bits8, result_8); impl_analog_read!(U10, Resolution::Bits10, result_10); impl_analog_read!(U12, Resolution::Bits12, result_12);
self.set_ctrlb(|r| r.set_prescaler(0x7).set_ressel(0x2)); self.set_sampctrl(|r| r.set_samplen(0x3f)); self.wait_busy(); self.set_inputctrl(|r| r.set_muxneg(0x18)); self.set_avgctrl(|r| r.set_samplenum(0x0).set_adjres(0x0)); self.with_inputctrl(|r| r.set_gain(0xf)); self.set_refctrl(|r| r.set_refsel(0x2)); }
function_block-function_prefix_line
[ { "content": "pub fn read_peripheral<R: std::io::Read>(r: &mut EventReader<R>,\n\n attrs: &[OwnedAttribute])\n\n -> Result<Peripheral, Error> {\n\n let mut p = Peripheral::default();\n\n\n\n for a in attrs.iter() {\n\n ...
Rust
src/validate.rs
nlehuby/transport-validator
ea4ed1efd10c7a4ae91ebff92e4114bd95db1a20
use crate::{issues, metadatas, validators}; use serde::Serialize; use std::collections::BTreeMap; use std::convert::TryFrom; use std::error::Error; fn create_unloadable_model_error(error: gtfs_structures::Error) -> issues::Issue { let msg = if let Some(inner) = error.source() { format!("{}: {}", error, inner) } else { format!("{}", error) }; let mut issue = issues::Issue::new( issues::Severity::Fatal, issues::IssueType::UnloadableModel, "A fatal error has occured while loading the model, many rules have not been checked", ) .details(&msg); if let gtfs_structures::Error::CSVError { file_name, source, line_in_error, } = error { issue.related_file = Some(issues::RelatedFile { file_name, line: source .position() .and_then(|p| line_in_error.map(|l| (p.line(), l))) .map(|(line_number, line_in_error)| issues::RelatedLine { line_number, headers: line_in_error.headers, values: line_in_error.values, }), }); } issue } #[derive(Serialize, Debug)] pub struct Response { pub metadata: Option<metadatas::Metadata>, pub validations: BTreeMap<issues::IssueType, Vec<issues::Issue>>, } pub fn validate_and_metadata(rgtfs: gtfs_structures::RawGtfs, max_issues: usize) -> Response { let mut validations = BTreeMap::new(); let mut issues: Vec<_> = validators::raw_gtfs::validate(&rgtfs) .into_iter() .chain(validators::invalid_reference::validate(&rgtfs)) .chain(validators::file_presence::validate(&rgtfs)) .collect(); let mut metadata = metadatas::extract_metadata(&rgtfs); match gtfs_structures::Gtfs::try_from(rgtfs) { Ok(ref gtfs) => { issues.extend( validators::unused_stop::validate(&gtfs) .into_iter() .chain(validators::duration_distance::validate(&gtfs)) .chain(validators::check_name::validate(&gtfs)) .chain(validators::check_id::validate(&gtfs)) .chain(validators::stops::validate(&gtfs)) .chain(validators::route_type::validate(&gtfs)) .chain(validators::shapes::validate(&gtfs)) .chain(validators::agency::validate(&gtfs)) .chain(validators::duplicate_stops::validate(&gtfs)) .chain(validators::fare_attributes::validate(&gtfs)) .chain(validators::feed_info::validate(&gtfs)) .chain(validators::stop_times::validate(&gtfs)) .chain(validators::interpolated_stoptimes::validate(&gtfs)), ); issues .iter_mut() .for_each(|issue| issue.push_related_geojson(&gtfs)); } Err(e) => { issues.push(create_unloadable_model_error(e)); } } for issue in issues { validations .entry(issue.issue_type) .or_insert_with(Vec::new) .push(issue); } for (issue_type, issues) in validations.iter_mut() { metadata.issues_count.insert(*issue_type, issues.len()); issues.truncate(max_issues); } Response { metadata: Some(metadata), validations, } } pub fn generate_validation(input: &str, max_issues: usize) -> Response { log::info!("Starting validation: {}", input); let raw_gtfs = gtfs_structures::RawGtfs::new(input); process(raw_gtfs, max_issues) } pub fn process( raw_gtfs: Result<gtfs_structures::RawGtfs, gtfs_structures::Error>, max_issues: usize, ) -> Response { match raw_gtfs { Ok(raw_gtfs) => self::validate_and_metadata(raw_gtfs, max_issues), Err(e) => { let mut validations = BTreeMap::new(); validations.insert( issues::IssueType::InvalidArchive, vec![issues::Issue::new( issues::Severity::Fatal, issues::IssueType::InvalidArchive, "", ) .details(format!("{}", e).as_ref())], ); Response { metadata: None, validations, } } } } pub fn generate_validation_from_reader<T: std::io::Read + std::io::Seek>( reader: T, max_issues: usize, ) -> Response { let g = gtfs_structures::RawGtfs::from_reader(reader); process(g, max_issues) } pub fn validate(input: &str, max_issues: usize) -> Result<String, anyhow::Error> { Ok(serde_json::to_string(&generate_validation( input, max_issues, ))?) } #[test] fn test_invalid_stop_points() { let issues = generate_validation("test_data/invalid_stop_file", 1000); let unloadable_model_errors = &issues.validations[&issues::IssueType::UnloadableModel]; assert_eq!(unloadable_model_errors.len(), 1); let unloadable_model_error = &unloadable_model_errors[0]; assert_eq!(unloadable_model_error, &issues::Issue { severity: issues::Severity::Fatal, issue_type: issues::IssueType::UnloadableModel, object_id: "A fatal error has occured while loading the model, many rules have not been checked".to_string(), object_type: None, object_name: None, related_objects: vec![], details: Some( "impossible to read csv file \'stops.txt\': CSV deserialize error: record 12 (line: 13, byte: 739): invalid float literal".to_string() ), related_file: Some(issues::RelatedFile { file_name: "stops.txt".to_owned(), line: Some(issues::RelatedLine { line_number: 13, headers: vec!["stop_id", "stop_name", "stop_desc", "stop_lat", "stop_lon", "zone_id", "stop_url", "location_type", "parent_station"].into_iter().map(|s| s.to_owned()).collect(), values: vec!["stop_with_bad_coord", "Moo", "", "baaaaaad_coord", "-116.40094", "", "", "", "1"].into_iter().map(|s| s.to_owned()).collect() }), }), geojson: None }); assert_eq!( issues.validations[&issues::IssueType::InvalidReference], vec![issues::Issue { severity: issues::Severity::Fatal, issue_type: issues::IssueType::InvalidReference, object_id: "AAMV".to_string(), object_type: Some(gtfs_structures::ObjectType::Route), object_name: None, related_file: None, related_objects: vec![issues::RelatedObject { id: "AAMV4".to_string(), object_type: Some(gtfs_structures::ObjectType::Trip), name: Some("route id: AAMV, service id: WE".to_string()) }], details: Some("The route is referenced by a trip but does not exists".to_string()), geojson: None }] ); }
use crate::{issues, metadatas, validators}; use serde::Serialize; use std::collections::BTreeMap; use std::convert::TryFrom; use std::error::Error; fn create_unloadable_model_error(error: gtfs_structures::Error) -> issues::Issue { let msg = if let Some(inner) = error.source() { format!("{}: {}", error, inner) } else { format!("{}", error) }; let mut issue = issues::Issue::new( issues::Severity::Fata
#[derive(Serialize, Debug)] pub struct Response { pub metadata: Option<metadatas::Metadata>, pub validations: BTreeMap<issues::IssueType, Vec<issues::Issue>>, } pub fn validate_and_metadata(rgtfs: gtfs_structures::RawGtfs, max_issues: usize) -> Response { let mut validations = BTreeMap::new(); let mut issues: Vec<_> = validators::raw_gtfs::validate(&rgtfs) .into_iter() .chain(validators::invalid_reference::validate(&rgtfs)) .chain(validators::file_presence::validate(&rgtfs)) .collect(); let mut metadata = metadatas::extract_metadata(&rgtfs); match gtfs_structures::Gtfs::try_from(rgtfs) { Ok(ref gtfs) => { issues.extend( validators::unused_stop::validate(&gtfs) .into_iter() .chain(validators::duration_distance::validate(&gtfs)) .chain(validators::check_name::validate(&gtfs)) .chain(validators::check_id::validate(&gtfs)) .chain(validators::stops::validate(&gtfs)) .chain(validators::route_type::validate(&gtfs)) .chain(validators::shapes::validate(&gtfs)) .chain(validators::agency::validate(&gtfs)) .chain(validators::duplicate_stops::validate(&gtfs)) .chain(validators::fare_attributes::validate(&gtfs)) .chain(validators::feed_info::validate(&gtfs)) .chain(validators::stop_times::validate(&gtfs)) .chain(validators::interpolated_stoptimes::validate(&gtfs)), ); issues .iter_mut() .for_each(|issue| issue.push_related_geojson(&gtfs)); } Err(e) => { issues.push(create_unloadable_model_error(e)); } } for issue in issues { validations .entry(issue.issue_type) .or_insert_with(Vec::new) .push(issue); } for (issue_type, issues) in validations.iter_mut() { metadata.issues_count.insert(*issue_type, issues.len()); issues.truncate(max_issues); } Response { metadata: Some(metadata), validations, } } pub fn generate_validation(input: &str, max_issues: usize) -> Response { log::info!("Starting validation: {}", input); let raw_gtfs = gtfs_structures::RawGtfs::new(input); process(raw_gtfs, max_issues) } pub fn process( raw_gtfs: Result<gtfs_structures::RawGtfs, gtfs_structures::Error>, max_issues: usize, ) -> Response { match raw_gtfs { Ok(raw_gtfs) => self::validate_and_metadata(raw_gtfs, max_issues), Err(e) => { let mut validations = BTreeMap::new(); validations.insert( issues::IssueType::InvalidArchive, vec![issues::Issue::new( issues::Severity::Fatal, issues::IssueType::InvalidArchive, "", ) .details(format!("{}", e).as_ref())], ); Response { metadata: None, validations, } } } } pub fn generate_validation_from_reader<T: std::io::Read + std::io::Seek>( reader: T, max_issues: usize, ) -> Response { let g = gtfs_structures::RawGtfs::from_reader(reader); process(g, max_issues) } pub fn validate(input: &str, max_issues: usize) -> Result<String, anyhow::Error> { Ok(serde_json::to_string(&generate_validation( input, max_issues, ))?) } #[test] fn test_invalid_stop_points() { let issues = generate_validation("test_data/invalid_stop_file", 1000); let unloadable_model_errors = &issues.validations[&issues::IssueType::UnloadableModel]; assert_eq!(unloadable_model_errors.len(), 1); let unloadable_model_error = &unloadable_model_errors[0]; assert_eq!(unloadable_model_error, &issues::Issue { severity: issues::Severity::Fatal, issue_type: issues::IssueType::UnloadableModel, object_id: "A fatal error has occured while loading the model, many rules have not been checked".to_string(), object_type: None, object_name: None, related_objects: vec![], details: Some( "impossible to read csv file \'stops.txt\': CSV deserialize error: record 12 (line: 13, byte: 739): invalid float literal".to_string() ), related_file: Some(issues::RelatedFile { file_name: "stops.txt".to_owned(), line: Some(issues::RelatedLine { line_number: 13, headers: vec!["stop_id", "stop_name", "stop_desc", "stop_lat", "stop_lon", "zone_id", "stop_url", "location_type", "parent_station"].into_iter().map(|s| s.to_owned()).collect(), values: vec!["stop_with_bad_coord", "Moo", "", "baaaaaad_coord", "-116.40094", "", "", "", "1"].into_iter().map(|s| s.to_owned()).collect() }), }), geojson: None }); assert_eq!( issues.validations[&issues::IssueType::InvalidReference], vec![issues::Issue { severity: issues::Severity::Fatal, issue_type: issues::IssueType::InvalidReference, object_id: "AAMV".to_string(), object_type: Some(gtfs_structures::ObjectType::Route), object_name: None, related_file: None, related_objects: vec![issues::RelatedObject { id: "AAMV4".to_string(), object_type: Some(gtfs_structures::ObjectType::Trip), name: Some("route id: AAMV, service id: WE".to_string()) }], details: Some("The route is referenced by a trip but does not exists".to_string()), geojson: None }] ); }
l, issues::IssueType::UnloadableModel, "A fatal error has occured while loading the model, many rules have not been checked", ) .details(&msg); if let gtfs_structures::Error::CSVError { file_name, source, line_in_error, } = error { issue.related_file = Some(issues::RelatedFile { file_name, line: source .position() .and_then(|p| line_in_error.map(|l| (p.line(), l))) .map(|(line_number, line_in_error)| issues::RelatedLine { line_number, headers: line_in_error.headers, values: line_in_error.values, }), }); } issue }
function_block-function_prefixed
[ { "content": "fn validate_speeds(gtfs: &gtfs_structures::Gtfs) -> Result<Vec<Issue>, gtfs_structures::Error> {\n\n let mut issues_by_stops_and_type = std::collections::HashMap::new();\n\n\n\n for trip in gtfs.trips.values() {\n\n let route = gtfs.get_route(&trip.route_id)?;\n\n for (departur...
Rust
src/conversion.rs
vilaureu/kml
6a17f7ba075e489aa6c301f9b5a3c2963e0d5b48
use std::convert::TryFrom; use crate::errors::Error; use crate::types::{ Coord, CoordType, Geometry, Kml, LineString, LinearRing, MultiGeometry, Point, Polygon, }; #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Coordinate<T>> for Coord<T> where T: CoordType, { fn from(val: geo_types::Coordinate<T>) -> Coord<T> { Coord::from((val.x, val.y)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<Coord<T>> for geo_types::Coordinate<T> where T: CoordType, { fn from(val: Coord<T>) -> geo_types::Coordinate<T> { geo_types::Coordinate::from((val.x, val.y)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Point<T>> for Point<T> where T: CoordType + Default, { fn from(val: geo_types::Point<T>) -> Point<T> { Point::from(Coord::from(val.0)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<Point<T>> for geo_types::Point<T> where T: CoordType, { fn from(val: Point<T>) -> geo_types::Point<T> { geo_types::Point::from(geo_types::Coordinate::from(val.coord)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Line<T>> for LineString<T> where T: CoordType + Default, { fn from(val: geo_types::Line<T>) -> LineString<T> { LineString::from(vec![Coord::from(val.start), Coord::from(val.end)]) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::LineString<T>> for LineString<T> where T: CoordType + Default, { fn from(val: geo_types::LineString<T>) -> LineString<T> { LineString::from( val.0 .into_iter() .map(Coord::from) .collect::<Vec<Coord<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<LineString<T>> for geo_types::LineString<T> where T: CoordType, { fn from(val: LineString<T>) -> geo_types::LineString<T> { geo_types::LineString( val.coords .into_iter() .map(geo_types::Coordinate::from) .collect(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::LineString<T>> for LinearRing<T> where T: CoordType + Default, { fn from(val: geo_types::LineString<T>) -> LinearRing<T> { LinearRing::from( val.0 .into_iter() .map(Coord::from) .collect::<Vec<Coord<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<LinearRing<T>> for geo_types::LineString<T> where T: CoordType, { fn from(val: LinearRing<T>) -> geo_types::LineString<T> { geo_types::LineString( val.coords .into_iter() .map(geo_types::Coordinate::from) .collect(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Polygon<T>> for Polygon<T> where T: CoordType + Default, { fn from(val: geo_types::Polygon<T>) -> Polygon<T> { let (outer, inner) = val.into_inner(); Polygon::new( LinearRing::from(outer), inner .into_iter() .map(LinearRing::from) .collect::<Vec<LinearRing<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Rect<T>> for Polygon<T> where T: CoordType + Default, { fn from(val: geo_types::Rect<T>) -> Polygon<T> { Polygon::from(val.to_polygon()) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Triangle<T>> for Polygon<T> where T: CoordType + Default, { fn from(val: geo_types::Triangle<T>) -> Polygon<T> { Polygon::from(val.to_polygon()) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<Polygon<T>> for geo_types::Polygon<T> where T: CoordType, { fn from(val: Polygon<T>) -> geo_types::Polygon<T> { geo_types::Polygon::new( geo_types::LineString::from(val.outer), val.inner .into_iter() .map(geo_types::LineString::from) .collect::<Vec<geo_types::LineString<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::MultiPoint<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::MultiPoint<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(|p| Geometry::Point(Point::from(p))) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::MultiLineString<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::MultiLineString<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(|l| Geometry::LineString(LineString::from(l))) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::MultiPolygon<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::MultiPolygon<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(|p| Geometry::Polygon(Polygon::from(p))) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::GeometryCollection<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::GeometryCollection<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(Geometry::from) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> TryFrom<MultiGeometry<T>> for geo_types::GeometryCollection<T> where T: CoordType, { type Error = Error; fn try_from(val: MultiGeometry<T>) -> Result<geo_types::GeometryCollection<T>, Self::Error> { Ok(geo_types::GeometryCollection( val.geometries .into_iter() .map(geo_types::Geometry::try_from) .collect::<Result<Vec<geo_types::Geometry<T>>, _>>()?, )) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Geometry<T>> for Geometry<T> where T: CoordType + Default, { fn from(val: geo_types::Geometry<T>) -> Geometry<T> { match val { geo_types::Geometry::Point(p) => Geometry::Point(Point::from(p)), geo_types::Geometry::Line(l) => Geometry::LineString(LineString::from(l)), geo_types::Geometry::LineString(l) => Geometry::LineString(LineString::from(l)), geo_types::Geometry::Polygon(p) => Geometry::Polygon(Polygon::from(p)), geo_types::Geometry::MultiPoint(p) => Geometry::MultiGeometry(MultiGeometry::from(p)), geo_types::Geometry::MultiLineString(l) => { Geometry::MultiGeometry(MultiGeometry::from(l)) } geo_types::Geometry::MultiPolygon(p) => Geometry::MultiGeometry(MultiGeometry::from(p)), geo_types::Geometry::GeometryCollection(g) => { Geometry::MultiGeometry(MultiGeometry::from(g)) } geo_types::Geometry::Rect(r) => Geometry::Polygon(Polygon::from(r)), geo_types::Geometry::Triangle(t) => Geometry::Polygon(Polygon::from(t)), } } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> TryFrom<Geometry<T>> for geo_types::Geometry<T> where T: CoordType, { type Error = Error; fn try_from(val: Geometry<T>) -> Result<geo_types::Geometry<T>, Self::Error> { match val { Geometry::Point(p) => Ok(geo_types::Geometry::Point(geo_types::Point::from(p))), Geometry::LineString(l) => Ok(geo_types::Geometry::LineString( geo_types::LineString::from(l), )), Geometry::LinearRing(l) => Ok(geo_types::Geometry::LineString( geo_types::LineString::from(l), )), Geometry::Polygon(p) => Ok(geo_types::Geometry::Polygon(geo_types::Polygon::from(p))), Geometry::MultiGeometry(g) => Ok(geo_types::Geometry::GeometryCollection( geo_types::GeometryCollection::try_from(g)?, )), _ => Err(Error::InvalidGeometry("Can't convert geometry".to_string())), } } } fn process_kml<T>(k: Kml<T>) -> Result<Vec<geo_types::Geometry<T>>, Error> where T: CoordType, { match k { Kml::KmlDocument(d) => Ok(d .elements .into_iter() .flat_map(process_kml) .flatten() .collect()), Kml::Point(p) => Ok(vec![ geo_types::Geometry::Point(geo_types::Point::from(p)); 1 ]), Kml::LineString(l) => Ok(vec![ geo_types::Geometry::LineString( geo_types::LineString::from(l), ); 1 ]), Kml::LinearRing(l) => Ok(vec![ geo_types::Geometry::LineString( geo_types::LineString::from(l), ); 1 ]), Kml::Polygon(p) => Ok(vec![ geo_types::Geometry::Polygon(geo_types::Polygon::from( p )); 1 ]), Kml::MultiGeometry(g) => Ok(geo_types::GeometryCollection::try_from(g)?.0), Kml::Placemark(p) => Ok(if let Some(g) = p.geometry { vec![geo_types::Geometry::try_from(g)?; 1] } else { vec![] }), Kml::Document { elements, .. } => Ok(elements .into_iter() .flat_map(process_kml) .flatten() .collect()), Kml::Folder { elements, .. } => Ok(elements .into_iter() .flat_map(process_kml) .flatten() .collect()), _ => Ok(vec![]), } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] pub fn quick_collection<T>(k: Kml<T>) -> Result<geo_types::GeometryCollection<T>, Error> where T: CoordType, { Ok(geo_types::GeometryCollection(process_kml(k)?)) } #[cfg(test)] mod tests { use super::*; use crate::KmlDocument; use std::collections::HashMap; #[test] fn test_quick_collection() { let k = KmlDocument { elements: vec![ Kml::Point(Point::from(Coord::from((1., 1.)))), Kml::Folder { attrs: HashMap::new(), elements: vec![ Kml::LineString(LineString::from(vec![ Coord::from((1., 1.)), Coord::from((2., 2.)), ])), Kml::Point(Point::from(Coord::from((3., 3.)))), ], }, ], ..Default::default() }; let gc = geo_types::GeometryCollection(vec![ geo_types::Geometry::Point(geo_types::Point::from((1., 1.))), geo_types::Geometry::LineString(geo_types::LineString::from(vec![(1., 1.), (2., 2.)])), geo_types::Geometry::Point(geo_types::Point::from((3., 3.))), ]); assert_eq!(quick_collection(Kml::KmlDocument(k)).unwrap(), gc); } }
use std::convert::TryFrom; use crate::errors::Error; use crate::types::{ Coord, CoordType, Geometry, Kml, LineString, LinearRing, MultiGeometry, Point, Polygon, }; #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Coordinate<T>> for Coord<T> where T: CoordType, { fn from(val: geo_types::Coordinate<T>) -> Coord<T> { Coord::from((val.x, val.y)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<Coord<T>> for geo_types::Coordinate<T> where T: CoordType, { fn from(val: Coord<T>) -> geo_types::Coordinate<T> { geo_types::Coordinate::from((val.x, val.y)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Point<T>> for Point<T> where T: CoordType + Default, { fn from(val: geo_types::Point<T>) -> Point<T> { Point::from(Coord::from(val.0)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<Point<T>> for geo_types::Point<T> where T: CoordType, { fn from(val: Point<T>) -> geo_types::Point<T> { geo_types::Point::from(geo_types::Coordinate::from(val.coord)) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Line<T>> for LineString<T> where T: CoordType + Default, { fn from(val: geo_types::Line<T>) -> LineString<T> { LineString::from(vec![Coord::from(val.start), Coord::from(val.end)]) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::LineString<T>> for LineString<T> where T: CoordType + Default, { fn from(val: geo_types::LineString<T>) -> LineString<T> { LineString::from( val.0 .into_iter() .map(Coord::from) .collect::<Vec<Coord<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<LineString<T>> for geo_types::LineString<T> where T: CoordType, { fn from(val: LineString<T>) -> geo_types::LineString<T> { geo_types::LineString( val.coords .into_iter() .map(geo_types::Coordinate::from) .collect(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::LineString<T>> for LinearRing<T> where T: CoordType + Default, { fn from(val: geo_types::LineString<T>) -> LinearRing<T> { LinearRing::from( val.0 .into_iter() .map(Coord::from) .collect::<Vec<Coord<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<LinearRing<T>> for geo_types::LineString<T> where T: CoordType, { fn from(val: LinearRing<T>) -> geo_types::LineString<T> { geo_types::LineString( val.coords .into_iter() .map(geo_types::Coordinate::from) .collect(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Polygon<T>> for Polygon<T> where T: CoordType + Default, { fn from(val: geo_types::Polygon<T>) -> Polygon<T> { let (outer, inner) = val.into_inner(); Polygon::new( LinearRing::from(outer), inner .into_iter() .map(LinearRing::from) .collect::<Vec<LinearRing<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Rect<T>> for Polygon<T> where T: CoordType + Default, { fn from(val: geo_types::Rect<T>) -> Polygon<T> { Polygon::from(val.to_polygon()) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Triangle<T>> for Polygon<T> where T: CoordType + Default, { fn from(val: geo_types::Triangle<T>) -> Polygon<T> { Polygon::from(val.to_polygon()) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<Polygon<T>> for geo_types::Polygon<T> where T: CoordType, { fn from(val: Polygon<T>) -> geo_types::Polygon<T> { geo_types::Polygon::new( geo_types::LineString::from(val.outer), val.inner .into_iter() .map(geo_types::LineString::from) .collect::<Vec<geo_types::LineString<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::MultiPoint<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::MultiPoint<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(|p| Geometry::Point(Point::from(p))) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::MultiLineString<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::MultiLineString<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(|l| Geometry::LineString(LineString::from(l))) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::MultiPolygon<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::MultiPolygon<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(|p| Geometry::Polygon(Polygon::from(p))) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::GeometryCollection<T>> for MultiGeometry<T> where T: CoordType + Default, { fn from(val: geo_types::GeometryCollection<T>) -> MultiGeometry<T> { MultiGeometry::new( val.into_iter() .map(Geometry::from) .collect::<Vec<Geometry<T>>>(), ) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> TryFrom<MultiGeometry<T>> for geo_types::GeometryCollection<T> where T: CoordType, { type Error = Error; fn try_from(val: MultiGeometry<T>) -> Result<geo_types::GeometryCollection<T>, Self::Error> { Ok(geo_types::GeometryCollection( val.geometries .into_iter() .map(geo_types::Geometry::try_from) .collect::<Result<Vec<geo_types::Geometry<T>>, _>>()?, )) } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Geometry<T>> for Geometry<T> where T: CoordType + Default, { fn from(val: geo_types::Geometry<T>) -> Geometry<T> { match val { geo_types::Geometry::Point(p) => Geometry::Point(Point::from(p)), geo_types::Geometry::Line(l) => Geometry::LineString(LineString::from(l)), geo_types::Geometry::LineString(l) => Geometry::LineString(LineString::from(l)), geo_types::Geometry::Polygon(p) => Geometry::Polygon(Polygon::from(p)), geo_types::Geometry::MultiPoint(p) => Geometry::MultiGeometry(MultiGeometry::from(p)), geo_types::Geometry::MultiLineString(l) => { Geometry::MultiGeometry(MultiGeometry::from(l)) } geo_types::Geometry::MultiPolygon(p) => Geometry::MultiGeometry(MultiGeometry::from(p)), geo_types::Geometry::GeometryCollection(g) => { Geometry::MultiGeometry(MultiGeometry::from(g)) } geo_types::Geometry::Rect(r) => Geometry::Polygon(Polygon::from(r)), geo_types::Geometry::Triangle(t) => Geometry::Polygon(Polygon::from(t)), } } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> TryFrom<Geometry<T>> for geo_types::Geometry<T> where T: CoordType, { type Error = Error; fn try_from(val: Geometry<T>) -> Result<geo_types::Geometry<T>, Self::Error> { match val { Geometry::Point(p) => Ok(geo_types::Geometry::Point(geo_types::Point::from(p))), Geometry::LineString(l) => Ok(geo_types::Geometry::LineString( geo_types::LineString::from(l), )), Geometry::LinearRing(l) => Ok(geo_types::Geometry::LineString( geo_types::LineString::from(l), )), Geometry::Polygon(p) => Ok(geo_types::Geometry::Polygon(geo_types::Polygon::from(p))), Geometry::MultiGeometry(g) => Ok(geo_types::Geometry::GeometryCollection( geo_types::GeometryCollection::try_from(g)?, )), _ => Err(Error::InvalidGeometry("Can't convert geometry".to_string())), } } } fn process_kml<T>(k: Kml<T>) -> Result<Vec<geo_types::Geometry<T>>, Error> where T: CoordType, { match k { Kml::KmlDocument(d) => Ok(d .elements .into_iter() .flat_map(process_kml) .flatten() .collect()), Kml::Point(p) => Ok(vec![ geo_types::Geometry::Point(geo_types::Point::from(p)); 1 ]), Kml::LineString(l) => Ok(vec![ geo_types::Geometry::LineString( geo_types::LineString::from(l), ); 1 ]), Kml::LinearRing(l) => Ok(vec![ geo_types::Geometry::LineString( geo_types::LineString::from(l), ); 1 ]), Kml::Polygon(p) => Ok(vec![ geo_types::Geometry::Polygon(geo_types::Polygon::from( p )); 1 ]), Kml::MultiGeometry(g) => Ok(geo_types::GeometryCollection::try_from(g)?.0), Kml::Placemark(p) => Ok(if let Some(g) = p.geometry { vec![geo_types::Geometry::try_from(g)?; 1] } else { vec![] }), Kml::Document { elements, .. } => Ok(elements .into_iter() .flat_map(process_kml) .flatten() .collect()), Kml::Folder { elements, .. } => Ok(elements .into_iter() .flat_map(process_kml) .flatten() .collect()), _ => Ok(vec![]), } } #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] pub fn quick_collection<T>(k: Kml<T>) -> Result<geo_types::GeometryCollection<T>, Error> where T: CoordType, { Ok(geo_types::GeometryCollection(process_kml(k)?)) } #[cfg(test)] mod tests { use super::*; use crate::KmlDocument; use std::collections::HashMap; #[test] fn test_quick_collection() { let k = KmlDocument { elements: vec![ Kml::Point(Point::from(Coord::from((1., 1.)))), Kml::Folder { attrs: HashMap::new(), elements: vec![ Kml::LineString(LineString::from(vec![ Coord::from((1., 1.)), Coord::from((2., 2.)), ])), Kml::Point(Point::from(Coord::from((3., 3.)))), ], }, ], ..Default::default() };
assert_eq!(quick_collection(Kml::KmlDocument(k)).unwrap(), gc); } }
let gc = geo_types::GeometryCollection(vec![ geo_types::Geometry::Point(geo_types::Point::from((1., 1.))), geo_types::Geometry::LineString(geo_types::LineString::from(vec![(1., 1.), (2., 2.)])), geo_types::Geometry::Point(geo_types::Point::from((3., 3.))), ]);
assignment_statement
[ { "content": "/// Utility method for parsing multiple coordinates according to the spec\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use kml::types::{Coord, coords_from_str};\n\n///\n\n/// let coords_str = \"1,1,0\\n\\n1,2,0 2,2,0\";\n\n/// let coords: Vec<Coord> = coords_from_str(coords_str).unwrap();\n\n...
Rust
src/search.rs
lachlan-smith/scryfall-rs
3c7a6d9258c9ad186a772094ebe5e84275e9c688
use url::Url; use crate::list::ListIter; use crate::Card; pub mod advanced; pub mod param; pub mod query; pub trait Search { fn write_query(&self, url: &mut Url) -> crate::Result<()>; #[cfg(test)] fn query_string(&self) -> crate::Result<String> { let mut url = Url::parse("http://localhost")?; self.write_query(&mut url)?; Ok(url.query().unwrap_or_default().to_string()) } fn search(&self) -> crate::Result<ListIter<Card>> { Card::search(self) } fn search_all(&self) -> crate::Result<Vec<Card>> { Card::search_all(self) } fn random(&self) -> crate::Result<Card> { Card::search_random(self) } } impl<T: Search + ?Sized> Search for &T { fn write_query(&self, url: &mut Url) -> crate::Result<()> { <T as Search>::write_query(*self, url) } } impl<T: Search + ?Sized> Search for &mut T { fn write_query(&self, url: &mut Url) -> crate::Result<()> { <T as Search>::write_query(*self, url) } } #[inline] fn write_query_string<S: ToString + ?Sized>(query: &S, url: &mut Url) -> crate::Result<()> { url.query_pairs_mut() .append_pair("q", query.to_string().as_str()); Ok(()) } impl Search for str { fn write_query(&self, url: &mut Url) -> crate::Result<()> { write_query_string(self, url) } } impl Search for String { fn write_query(&self, url: &mut Url) -> crate::Result<()> { write_query_string(self, url) } } pub mod prelude { pub use super::advanced::{SearchOptions, SortDirection, SortOrder, UniqueStrategy}; pub use super::param::compare::{eq, gt, gte, lt, lte, neq}; pub use super::param::criteria::{CardIs, PrintingIs}; pub use super::param::value::{ artist, artist_count, banned, block, border_color, cheapest, cmc, collector_number, color, color_count, color_identity, color_identity_count, cube, date, devotion, eur, flavor_text, format, frame, full_oracle_text, game, illustration_count, in_game, in_language, in_rarity, in_set, in_set_type, keyword, language, loyalty, mana, name, oracle_text, paper_print_count, paper_set_count, pow_tou, power, print_count, produces, rarity, restricted, set, set_count, set_type, tix, toughness, type_line, usd, usd_foil, watermark, year, Devotion, NumProperty, Regex, }; pub use super::param::{exact, Param}; pub use super::query::{not, Query}; pub use super::Search; } #[cfg(test)] mod tests { use super::prelude::*; use crate::Card; #[test] fn basic_search() { let cards = SearchOptions::new() .query(Query::And(vec![ name("lightning"), name("helix"), cmc(eq(2)), ])) .unique(UniqueStrategy::Prints) .search() .unwrap() .map(|c| c.unwrap()) .collect::<Vec<_>>(); assert!(cards.len() > 1); for card in cards { assert_eq!(card.name, "Lightning Helix") } } #[test] fn random_works_with_search_options() { assert!( SearchOptions::new() .query(keyword("storm")) .unique(UniqueStrategy::Art) .sort(SortOrder::Usd, SortDirection::Ascending) .extras(true) .multilingual(true) .variations(true) .random() .unwrap() .oracle_text .unwrap() .to_lowercase() .contains("storm") ); } #[test] fn finds_alpha_lotus() { let mut search = SearchOptions::new(); search .query(exact("Black Lotus")) .unique(UniqueStrategy::Prints) .sort(SortOrder::Released, SortDirection::Ascending); eprintln!("{}", search.query_string().unwrap()); assert_eq!( Card::search(&search) .unwrap() .next() .unwrap() .unwrap() .set .to_string(), "lea", ); } #[test] fn rarity_comparison() { use crate::card::Rarity; let cards = SearchOptions::new() .query(rarity(gt(Rarity::Mythic))) .search() .unwrap() .collect::<Vec<_>>(); assert!(cards.len() >= 9, "Couldn't find the Power Nine from VMA."); assert!( cards .into_iter() .map(|c| c.unwrap()) .all(|c| c.rarity > Rarity::Mythic) ); } #[test] fn numeric_property_comparison() { let card = Card::search_random(Query::And(vec![ power(eq(NumProperty::Toughness)), pow_tou(eq(NumProperty::Cmc)), not(CardIs::Funny), ])) .unwrap(); let power = card .power .and_then(|s| s.parse::<u32>().ok()) .unwrap_or_default(); let toughness = card .toughness .and_then(|s| s.parse::<u32>().ok()) .unwrap_or_default(); assert_eq!(power, toughness); assert_eq!(power + toughness, card.cmc as u32); let card = Card::search(pow_tou(gt(NumProperty::Year))) .unwrap() .map(|c| c.unwrap()) .collect::<Vec<_>>(); assert!(card.into_iter().any(|c| &c.name == "Infinity Elemental")); } #[test] fn query_string_sanity_check() { let query = cmc(4).and(name("Yargle")); assert_eq!( query.query_string().unwrap(), "q=%28cmc%3A4+AND+name%3A%22Yargle%22%29" ); } }
use url::Url; use crate::list::ListIter; use crate::Card; pub mod advanced; pub mod param; pub mod query; pub trait Search { fn write_query(&self, url: &mut Url) -> crate::Result<()>; #[cfg(test)] fn query_string(&self) -> crate::Result<String> { let mut url = Url::parse("http://localhost")?; self.write_query(&mut url)?; Ok(url.query().unwrap_or_default().to_string()) } fn search(&self) -> crate::Result<ListIter<Card>> { Card::search(self) } fn search_all(&self) -> crate::Result<Vec<Card>> { Card::search_all(self) } fn random(&self) -> crate::Result<Card> { Card::search_random(self) } } impl<T: Search + ?Sized> Search for &T { fn write_query(&self, url: &mut Url) -> crate::Result<()> { <T as Search>::write_query(*self, url) } } impl<T: Search + ?Sized> Search for &mut T { fn write_query(&self, url: &mut Url) -> crate::Result<()> { <T as Search>::write_query(*self, url) } } #[inline] fn write_query_string<S: ToString + ?Sized>(query: &S, url: &mut Url) -> crate::Result<()> { url.query_pairs_mut() .append_pair("q", query.to_string().as_str()); Ok(()) } impl Search for str { fn write_query(&self, url: &mut Url) -> crate::Result<()> { write_query_string(self, url) } } impl Search for String { fn write_query(&self, url: &mut Url) -> crate::Result<()> { write_query_string(self, url) } } pub mod prelude { pub use super::advanced::{SearchOptions, SortDirection, SortOrder, UniqueStrategy}; pub use super::param::compare::{eq, gt, gte, lt, lte, neq}; pub use super::param::criteria::{CardIs, PrintingIs}; pub use super::param::value::{ artist, artist_count, banned, block, border_color, cheapest, cmc, collector_number, color, color_count, color_identity, color_identity_count, cube, date, devotion, eur, flavor_text, format, frame, full_oracle_text, game, illustration_count, in_game, in_language, in_rarity, in_set, in_set_type, keyword, language, loyalty, mana, name, oracle_text, paper_print_count, paper_set_count, pow_tou, power, print_count, produces, rarity, restricted, set, set_count, set_type, tix, toughness, type_line, usd, usd_foil, watermark, year, Devotion, NumProperty, Regex, }; pub use super::param::{exact, Param}; pub use super::query::{not, Query}; pub use super::Search; } #[cfg(test)] mod tests { use super::prelude::*; use crate::Card; #[test] fn basic_search() { let cards = SearchOptions::new() .query(Query::And(vec![ nam
#[test] fn random_works_with_search_options() { assert!( SearchOptions::new() .query(keyword("storm")) .unique(UniqueStrategy::Art) .sort(SortOrder::Usd, SortDirection::Ascending) .extras(true) .multilingual(true) .variations(true) .random() .unwrap() .oracle_text .unwrap() .to_lowercase() .contains("storm") ); } #[test] fn finds_alpha_lotus() { let mut search = SearchOptions::new(); search .query(exact("Black Lotus")) .unique(UniqueStrategy::Prints) .sort(SortOrder::Released, SortDirection::Ascending); eprintln!("{}", search.query_string().unwrap()); assert_eq!( Card::search(&search) .unwrap() .next() .unwrap() .unwrap() .set .to_string(), "lea", ); } #[test] fn rarity_comparison() { use crate::card::Rarity; let cards = SearchOptions::new() .query(rarity(gt(Rarity::Mythic))) .search() .unwrap() .collect::<Vec<_>>(); assert!(cards.len() >= 9, "Couldn't find the Power Nine from VMA."); assert!( cards .into_iter() .map(|c| c.unwrap()) .all(|c| c.rarity > Rarity::Mythic) ); } #[test] fn numeric_property_comparison() { let card = Card::search_random(Query::And(vec![ power(eq(NumProperty::Toughness)), pow_tou(eq(NumProperty::Cmc)), not(CardIs::Funny), ])) .unwrap(); let power = card .power .and_then(|s| s.parse::<u32>().ok()) .unwrap_or_default(); let toughness = card .toughness .and_then(|s| s.parse::<u32>().ok()) .unwrap_or_default(); assert_eq!(power, toughness); assert_eq!(power + toughness, card.cmc as u32); let card = Card::search(pow_tou(gt(NumProperty::Year))) .unwrap() .map(|c| c.unwrap()) .collect::<Vec<_>>(); assert!(card.into_iter().any(|c| &c.name == "Infinity Elemental")); } #[test] fn query_string_sanity_check() { let query = cmc(4).and(name("Yargle")); assert_eq!( query.query_string().unwrap(), "q=%28cmc%3A4+AND+name%3A%22Yargle%22%29" ); } }
e("lightning"), name("helix"), cmc(eq(2)), ])) .unique(UniqueStrategy::Prints) .search() .unwrap() .map(|c| c.unwrap()) .collect::<Vec<_>>(); assert!(cards.len() > 1); for card in cards { assert_eq!(card.name, "Lightning Helix") } }
function_block-function_prefixed
[]
Rust
python_ext/pyo3/src/resolution.rs
hoodmane/sseq
0f19a29c95486a629b0d054c703ca0a58999ae97
use std::sync::Arc; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use pyo3::prelude::*; use ext::resolution::ResolutionInner as ResolutionRust; use ext::chain_complex::{AugmentedChainComplex, ChainComplex, FiniteChainComplex, FreeChainComplex}; use python_algebra::module::{ ModuleRust, FreeModule, homomorphism::{ FreeModuleHomomorphism, ModuleHomomorphismRust } }; pub type CCRust = FiniteChainComplex<ModuleRust, ModuleHomomorphismRust>; python_utils::rc_wrapper_type!(Resolution, ResolutionRust<CCRust>); #[pymethods] impl Resolution { #[new] pub fn new(module : PyObject) -> PyResult<Self> { let chain_complex = Arc::new( FiniteChainComplex::ccdz( ModuleRust::from_py_object(module)? ) ); Ok(Resolution::box_and_wrap(ResolutionRust::new(Arc::clone(&chain_complex)))) } pub fn extended_degree(&self) -> PyResult<(u32, i32)> { Ok(self.inner()?.extended_degree()) } pub fn extend_through_degree(&self, max_s : u32, max_t : i32) -> PyResult<()> { let (old_max_s, old_max_t) = self.extended_degree()?; self.inner()?.extend_through_degree(old_max_s, max_s, old_max_t, max_t); Ok(()) } pub fn graded_dimension_string(&self, max_degree : i32 , max_hom_deg : u32) -> PyResult<String> { Ok(self.inner()?.graded_dimension_string(max_degree, max_hom_deg)) } pub fn step_resolution(&self, s : u32, t : i32) -> PyResult<()> { let self_inner = self.inner()?; let (max_s, max_t) = self_inner.extended_degree(); if max_s <= s || max_t <= t { return Err(python_utils::exception!(ValueError, "You need to run res.extend_degree(>={}, >={}) before res.step_resolution({}, {})", s,t,s,t )); } let next_t = self_inner.differential(s).next_degree(); if next_t > t { return Ok(()) } python_utils::release_gil!(self_inner.step_resolution(s, t)); Ok(()) } pub fn check_has_computed_bidegree(&self, hom_deg : u32, int_deg : i32) -> PyResult<()> { if !self.inner()?.has_computed_bidegree(hom_deg, int_deg) { Err(python_utils::exception!(IndexError, "We haven't computed out to bidegree {} yet.", python_utils::bidegree_string(hom_deg, int_deg) )) } else { Ok(()) } } pub fn check_cocycle_idx(&self, hom_deg : u32, int_deg : i32, idx : usize) -> PyResult<()> { self.check_has_computed_bidegree(hom_deg, int_deg)?; if idx >= self.inner()?.number_of_gens_in_bidegree(hom_deg, int_deg) { Err(python_utils::exception!(IndexError, "Fewer than {} generators in bidegree {}.", idx + 1, python_utils::bidegree_string(hom_deg, int_deg) )) } else { Ok(()) } } pub fn cocycle_string(&self, hom_deg : u32, int_deg : i32, idx : usize) -> PyResult<String> { self.check_cocycle_idx(hom_deg, int_deg, idx)?; Ok(self.inner()?.cocycle_string(hom_deg, int_deg, idx)) } pub fn bidegree_hash(&self, hom_deg : u32, int_deg : i32) -> PyResult<u64> { self.check_has_computed_bidegree(hom_deg, int_deg)?; let self_inner = self.inner()?; let num_gens = self_inner.number_of_gens_in_bidegree(hom_deg, int_deg); let mut hasher = DefaultHasher::new(); hom_deg.hash(&mut hasher); int_deg.hash(&mut hasher); num_gens.hash(&mut hasher); let ds = self_inner.differential(hom_deg); for idx in 0 .. num_gens { ds.output(int_deg, idx).hash(&mut hasher); } Ok(hasher.finish()) } pub fn number_of_gens_in_bidegree(&self, homological_degree : u32, internal_degree : i32) -> PyResult<usize> { self.check_has_computed_bidegree(homological_degree, internal_degree)?; Ok(self.inner()?.module(homological_degree).number_of_gens_in_degree(internal_degree)) } pub fn prime(&self) -> PyResult<u32> { Ok(*self.inner()?.complex().prime()) } pub fn module(&self, homological_degree : u32) -> PyResult<FreeModule> { Ok(FreeModule::wrap_immutable(self.inner()?.module(homological_degree))) } #[getter] pub fn get_min_degree(&self) -> PyResult<i32> { Ok(self.inner()?.min_degree()) } pub fn differential(&self, s : u32) -> PyResult<FreeModuleHomomorphism> { Ok(FreeModuleHomomorphism::wrap_to_free(self.inner()?.differential(s))) } pub fn chain_map(&self, s : u32) -> PyResult<FreeModuleHomomorphism> { Ok(FreeModuleHomomorphism::wrap_to_other(self.inner()?.chain_map(s))) } } use python_algebra::module::FreeUnstableModule; use python_algebra::algebra::{AdemAlgebra, AlgebraRust}; pub fn test() -> PyResult<()> { let a = Arc::new(AdemAlgebra::new(2, false, true, None)?); let b = a.to_arc()?.clone(); let m = FreeUnstableModule::new(AlgebraRust::into_py_object(b), "i".to_string(), 0)?; Resolution::new(ModuleRust::into_py_object(m.to_arc()?.clone()))?; Ok(()) }
use std::sync::Arc; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use pyo3::prelude::*; use ext::resolution::ResolutionInner as ResolutionRust; use ext::chain_complex::{AugmentedChainComplex, ChainComplex, FiniteChainComplex, FreeChainComplex}; use python_algebra::module::{ ModuleRust, FreeModule, homomorphism::{ FreeModuleHomomorphism, ModuleHomomorphismRust } }; pub type CCRust = FiniteChainComplex<ModuleRust, ModuleHomomorphismRust>; python_utils::rc_wrapper_type!(Resolution, ResolutionRust<CCRust>); #[pymethods] impl Resolution { #[new] pub fn new(module : PyObject) -> PyResult<Self> { let chain_complex = Arc::new( FiniteChainComplex::ccdz( ModuleRust::from_py_object(module)? ) ); Ok(Resolution::box_and_wrap(ResolutionRust::new(Arc::clone(&chain_complex)))) } pub fn extended_degree(&self) -> PyResult<(u32, i32)> { Ok(self.inner()?.extended_degree()) } pub fn extend_through_degree(&self, max_s : u32, max_t : i32) -> PyResult<()> { let (old_max_s, old_max_t) = self.extended_degree()?; self.inner()?.extend_through_degree(old_max_s, max_s, old_max_t, max_t); Ok(()) } pub fn graded_dimension_string(&self, max_degree : i32 , max_hom_deg : u32) -> PyResult<String> { Ok(self.inner()?.graded_dimension_string(max_degree, max_hom_deg)) } pub fn step_resolution(&self, s : u32, t : i32) -> PyResult<()> { let self_inner = self.inner()?; let (max_s, max_t) = self_inner.extended_degree(); if max_s <= s || max_t <= t { return Err(python_utils::exception!(ValueError, "You need to run res.extend_degree(>={}, >={}) before res.step_resolution({}, {})", s,t,s,t )); } let next_t = self_inner.differential(s).next_degree(); if next_t > t { return Ok(()) } python_utils::release_gil!(self_inner.step_resolution(s, t)); Ok(()) } pub fn check_has_computed_bidegree(&self, hom_deg : u32, int_deg : i32) -> PyResult<()> { if !self.inner()?.has_computed_bidegree(hom_deg, int_deg) { Err(python_utils::exception!(IndexError, "We haven't computed out to bidegree {} yet.", python_utils::bidegree_string(hom_deg, int_deg) )) } else { Ok(()) } } pub fn check_cocycle_idx(&self, hom_deg : u32, int_deg : i32, idx : usize) -> PyResult<()> { self.check_has_computed_bidegree(hom_deg, int_deg)?; if idx >= self.inner()?.number_of_gens_in_bidegree(hom_deg, int_deg) { Err(python_utils::exception!(IndexError, "Fewer than {} generators in bidegree {}.", idx + 1, python_utils::bidegree_string(hom_deg, int_deg) )) } else { Ok(()) } } pub fn cocycle_string(&self, hom_deg : u32, int_deg : i32, idx : usize) -> PyResult<String> { self.check_cocycle_idx(hom_deg, int_deg, idx)?; Ok(self.inner()?.cocycle_string(hom_deg, int_deg, idx)) } pub fn bidegree_hash(&s
} pub fn number_of_gens_in_bidegree(&self, homological_degree : u32, internal_degree : i32) -> PyResult<usize> { self.check_has_computed_bidegree(homological_degree, internal_degree)?; Ok(self.inner()?.module(homological_degree).number_of_gens_in_degree(internal_degree)) } pub fn prime(&self) -> PyResult<u32> { Ok(*self.inner()?.complex().prime()) } pub fn module(&self, homological_degree : u32) -> PyResult<FreeModule> { Ok(FreeModule::wrap_immutable(self.inner()?.module(homological_degree))) } #[getter] pub fn get_min_degree(&self) -> PyResult<i32> { Ok(self.inner()?.min_degree()) } pub fn differential(&self, s : u32) -> PyResult<FreeModuleHomomorphism> { Ok(FreeModuleHomomorphism::wrap_to_free(self.inner()?.differential(s))) } pub fn chain_map(&self, s : u32) -> PyResult<FreeModuleHomomorphism> { Ok(FreeModuleHomomorphism::wrap_to_other(self.inner()?.chain_map(s))) } } use python_algebra::module::FreeUnstableModule; use python_algebra::algebra::{AdemAlgebra, AlgebraRust}; pub fn test() -> PyResult<()> { let a = Arc::new(AdemAlgebra::new(2, false, true, None)?); let b = a.to_arc()?.clone(); let m = FreeUnstableModule::new(AlgebraRust::into_py_object(b), "i".to_string(), 0)?; Resolution::new(ModuleRust::into_py_object(m.to_arc()?.clone()))?; Ok(()) }
elf, hom_deg : u32, int_deg : i32) -> PyResult<u64> { self.check_has_computed_bidegree(hom_deg, int_deg)?; let self_inner = self.inner()?; let num_gens = self_inner.number_of_gens_in_bidegree(hom_deg, int_deg); let mut hasher = DefaultHasher::new(); hom_deg.hash(&mut hasher); int_deg.hash(&mut hasher); num_gens.hash(&mut hasher); let ds = self_inner.differential(hom_deg); for idx in 0 .. num_gens { ds.output(int_deg, idx).hash(&mut hasher); } Ok(hasher.finish())
function_block-random_span
[ { "content": "pub fn reduce_coefficient(p : u32, c : i32) -> u32 {\n\n let p = p as i32;\n\n (((c % p) + p) % p) as u32\n\n}\n\n\n", "file_path": "python_ext/pyo3/python_utils/src/lib.rs", "rank": 0, "score": 290762.9992508795 }, { "content": "#[allow(dead_code)]\n\nfn operation_drop(a...
Rust
lib/megstd/src/drawing/color.rs
neri/toe
8442f82bce551ce27b23b24336a285f25d422e98
use core::mem::transmute; pub trait ColorTrait: Sized + Copy + Clone + PartialEq + Eq {} #[repr(transparent)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct IndexedColor(pub u8); impl ColorTrait for IndexedColor {} impl IndexedColor { pub const MIN: Self = Self(u8::MIN); pub const MAX: Self = Self(u8::MAX); pub const DEFAULT_KEY: Self = Self(u8::MAX); pub const BLACK: Self = Self(0); pub const BLUE: Self = Self(1); pub const GREEN: Self = Self(2); pub const CYAN: Self = Self(3); pub const RED: Self = Self(4); pub const MAGENTA: Self = Self(5); pub const BROWN: Self = Self(6); pub const LIGHT_GRAY: Self = Self(7); pub const DARK_GRAY: Self = Self(8); pub const LIGHT_BLUE: Self = Self(9); pub const LIGHT_GREEN: Self = Self(10); pub const LIGHT_CYAN: Self = Self(11); pub const LIGHT_RED: Self = Self(12); pub const LIGHT_MAGENTA: Self = Self(13); pub const YELLOW: Self = Self(14); pub const WHITE: Self = Self(15); pub const COLOR_PALETTE: [u32; 256] = [ 0xFF212121, 0xFF0D47A1, 0xFF1B5E20, 0xFF006064, 0xFFb71c1c, 0xFF4A148C, 0xFF795548, 0xFF9E9E9E, 0xFF616161, 0xFF2196F3, 0xFF4CAF50, 0xFF00BCD4, 0xFFf44336, 0xFF9C27B0, 0xFFFFEB3B, 0xFFFFFFFF, 0xFF000000, 0xFF330000, 0xFF660000, 0xFF990000, 0xFFCC0000, 0xFFFF0000, 0xFF003300, 0xFF333300, 0xFF663300, 0xFF993300, 0xFFCC3300, 0xFFFF3300, 0xFF006600, 0xFF336600, 0xFF666600, 0xFF996600, 0xFFCC6600, 0xFFFF6600, 0xFF009900, 0xFF339900, 0xFF669900, 0xFF999900, 0xFFCC9900, 0xFFFF9900, 0xFF00CC00, 0xFF33CC00, 0xFF66CC00, 0xFF99CC00, 0xFFCCCC00, 0xFFFFCC00, 0xFF00FF00, 0xFF33FF00, 0xFF66FF00, 0xFF99FF00, 0xFFCCFF00, 0xFFFFFF00, 0xFF000033, 0xFF330033, 0xFF660033, 0xFF990033, 0xFFCC0033, 0xFFFF0033, 0xFF003333, 0xFF333333, 0xFF663333, 0xFF993333, 0xFFCC3333, 0xFFFF3333, 0xFF006633, 0xFF336633, 0xFF666633, 0xFF996633, 0xFFCC6633, 0xFFFF6633, 0xFF009933, 0xFF339933, 0xFF669933, 0xFF999933, 0xFFCC9933, 0xFFFF9933, 0xFF00CC33, 0xFF33CC33, 0xFF66CC33, 0xFF99CC33, 0xFFCCCC33, 0xFFFFCC33, 0xFF00FF33, 0xFF33FF33, 0xFF66FF33, 0xFF99FF33, 0xFFCCFF33, 0xFFFFFF33, 0xFF000066, 0xFF330066, 0xFF660066, 0xFF990066, 0xFFCC0066, 0xFFFF0066, 0xFF003366, 0xFF333366, 0xFF663366, 0xFF993366, 0xFFCC3366, 0xFFFF3366, 0xFF006666, 0xFF336666, 0xFF666666, 0xFF996666, 0xFFCC6666, 0xFFFF6666, 0xFF009966, 0xFF339966, 0xFF669966, 0xFF999966, 0xFFCC9966, 0xFFFF9966, 0xFF00CC66, 0xFF33CC66, 0xFF66CC66, 0xFF99CC66, 0xFFCCCC66, 0xFFFFCC66, 0xFF00FF66, 0xFF33FF66, 0xFF66FF66, 0xFF99FF66, 0xFFCCFF66, 0xFFFFFF66, 0xFF000099, 0xFF330099, 0xFF660099, 0xFF990099, 0xFFCC0099, 0xFFFF0099, 0xFF003399, 0xFF333399, 0xFF663399, 0xFF993399, 0xFFCC3399, 0xFFFF3399, 0xFF006699, 0xFF336699, 0xFF666699, 0xFF996699, 0xFFCC6699, 0xFFFF6699, 0xFF009999, 0xFF339999, 0xFF669999, 0xFF999999, 0xFFCC9999, 0xFFFF9999, 0xFF00CC99, 0xFF33CC99, 0xFF66CC99, 0xFF99CC99, 0xFFCCCC99, 0xFFFFCC99, 0xFF00FF99, 0xFF33FF99, 0xFF66FF99, 0xFF99FF99, 0xFFCCFF99, 0xFFFFFF99, 0xFF0000CC, 0xFF3300CC, 0xFF6600CC, 0xFF9900CC, 0xFFCC00CC, 0xFFFF00CC, 0xFF0033CC, 0xFF3333CC, 0xFF6633CC, 0xFF9933CC, 0xFFCC33CC, 0xFFFF33CC, 0xFF0066CC, 0xFF3366CC, 0xFF6666CC, 0xFF9966CC, 0xFFCC66CC, 0xFFFF66CC, 0xFF0099CC, 0xFF3399CC, 0xFF6699CC, 0xFF9999CC, 0xFFCC99CC, 0xFFFF99CC, 0xFF00CCCC, 0xFF33CCCC, 0xFF66CCCC, 0xFF99CCCC, 0xFFCCCCCC, 0xFFFFCCCC, 0xFF00FFCC, 0xFF33FFCC, 0xFF66FFCC, 0xFF99FFCC, 0xFFCCFFCC, 0xFFFFFFCC, 0xFF0000FF, 0xFF3300FF, 0xFF6600FF, 0xFF9900FF, 0xFFCC00FF, 0xFFFF00FF, 0xFF0033FF, 0xFF3333FF, 0xFF6633FF, 0xFF9933FF, 0xFFCC33FF, 0xFFFF33FF, 0xFF0066FF, 0xFF3366FF, 0xFF6666FF, 0xFF9966FF, 0xFFCC66FF, 0xFFFF66FF, 0xFF0099FF, 0xFF3399FF, 0xFF6699FF, 0xFF9999FF, 0xFFCC99FF, 0xFFFF99FF, 0xFF00CCFF, 0xFF33CCFF, 0xFF66CCFF, 0xFF99CCFF, 0xFFCCCCFF, 0xFFFFCCFF, 0xFF00FFFF, 0xFF33FFFF, 0xFF66FFFF, 0xFF99FFFF, 0xFFCCFFFF, 0xFFFFFFFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; #[inline] pub const fn from_rgb(rgb: u32) -> Self { let b = (((rgb & 0xFF) + 25) / 51) as u8; let g = ((((rgb >> 8) & 0xFF) + 25) / 51) as u8; let r = ((((rgb >> 16) & 0xFF) + 25) / 51) as u8; Self(16 + r + g * 6 + b * 36) } #[inline] pub const fn as_rgb(self) -> u32 { Self::COLOR_PALETTE[self.0 as usize] & 0xFF_FF_FF } #[inline] pub const fn as_argb(self) -> u32 { Self::COLOR_PALETTE[self.0 as usize] } #[inline] pub const fn as_true_color(self) -> TrueColor { TrueColor::from_argb(self.as_argb()) } } impl From<u8> for IndexedColor { fn from(val: u8) -> Self { Self(val) } } impl From<IndexedColor> for TrueColor { fn from(val: IndexedColor) -> Self { val.as_true_color() } } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct TrueColor { argb: u32, } impl ColorTrait for TrueColor {} impl TrueColor { pub const TRANSPARENT: Self = Self::from_argb(0); pub const WHITE: Self = Self::from_rgb(0xFFFFFF); #[inline] pub const fn from_rgb(rgb: u32) -> Self { Self { argb: rgb | 0xFF000000, } } #[inline] pub const fn from_argb(argb: u32) -> Self { Self { argb } } #[inline] pub const fn gray(white: u8, alpha: u8) -> Self { Self { argb: white as u32 * 0x00_01_01_01 + alpha as u32 * 0x01_00_00_00, } } #[inline] pub fn components(self) -> ColorComponents { self.into() } #[inline] pub const fn rgb(self) -> u32 { self.argb & 0x00FFFFFF } #[inline] pub const fn argb(self) -> u32 { self.argb } #[inline] pub fn brightness(self) -> u8 { let cc = self.components(); ((cc.r as usize * 19589 + cc.g as usize * 38444 + cc.b as usize * 7502 + 32767) >> 16) as u8 } #[inline] pub const fn opacity(self) -> u8 { (self.argb >> 24) as u8 } #[inline] pub fn set_opacity(mut self, alpha: u8) -> Self { let mut components = self.components(); components.a = alpha; self.argb = components.into(); self } #[inline] pub const fn is_opaque(self) -> bool { self.opacity() == 0xFF } #[inline] pub const fn is_transparent(self) -> bool { self.opacity() == 0 } #[inline] pub fn blend_each<F>(self, rhs: Self, f: F) -> Self where F: Fn(u8, u8) -> u8, { self.components().blend_each(rhs.into(), f).into() } #[inline] pub fn blend_color<F1, F2>(self, rhs: Self, f_rgb: F1, f_a: F2) -> Self where F1: Fn(u8, u8) -> u8, F2: Fn(u8, u8) -> u8, { self.components().blend_color(rhs.into(), f_rgb, f_a).into() } #[inline] pub fn blend(self, other: Self) -> Self { let c = other.components(); let alpha_l = c.a as usize; let alpha_r = 255 - alpha_l; c.blend_each(self.components(), |a, b| { ((a as usize * alpha_l + b as usize * alpha_r) / 255) as u8 }) .into() } } impl From<u32> for TrueColor { fn from(val: u32) -> Self { Self::from_argb(val) } } impl From<TrueColor> for IndexedColor { fn from(val: TrueColor) -> Self { Self::from_rgb(val.rgb()) } } #[repr(C)] #[derive(Debug, Copy, Clone)] #[cfg(target_endian = "little")] pub struct ColorComponents { pub b: u8, pub g: u8, pub r: u8, pub a: u8, } impl ColorComponents { #[inline] pub fn blend_each<F>(self, rhs: Self, f: F) -> Self where F: Fn(u8, u8) -> u8, { Self { a: f(self.a, rhs.a), r: f(self.r, rhs.r), g: f(self.g, rhs.g), b: f(self.b, rhs.b), } } #[inline] pub fn blend_color<F1, F2>(self, rhs: Self, f_rgb: F1, f_a: F2) -> Self where F1: Fn(u8, u8) -> u8, F2: Fn(u8, u8) -> u8, { Self { a: f_a(self.a, rhs.a), r: f_rgb(self.r, rhs.r), g: f_rgb(self.g, rhs.g), b: f_rgb(self.b, rhs.b), } } #[inline] pub const fn is_opaque(self) -> bool { self.a == 255 } #[inline] pub const fn is_transparent(self) -> bool { self.a == 0 } } impl From<TrueColor> for ColorComponents { fn from(color: TrueColor) -> Self { unsafe { transmute(color) } } } impl From<ColorComponents> for TrueColor { fn from(components: ColorComponents) -> Self { unsafe { transmute(components) } } } impl Into<u32> for ColorComponents { fn into(self) -> u32 { unsafe { transmute(self) } } } #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DeepColor30 { rgb: u32, } impl ColorTrait for DeepColor30 {} impl DeepColor30 { #[inline] pub const fn from_rgb(rgb: u32) -> Self { Self { rgb } } #[inline] pub const fn from_true_color(val: TrueColor) -> Self { let rgb32 = val.argb(); let components = ( (rgb32 & 0xFF), ((rgb32 >> 8) & 0xFF), ((rgb32 >> 16) & 0xFF), ); Self { rgb: Self::c8c10(components.0) | (Self::c8c10(components.1) << 10) | (Self::c8c10(components.2) << 20), } } #[inline] pub const fn components(&self) -> (u32, u32, u32) { let rgb = self.rgb(); ((rgb & 0x3FF), ((rgb >> 10) & 0x3FF), ((rgb >> 20) & 0x3FF)) } #[inline] pub const fn into_true_color(&self) -> TrueColor { let components = self.components(); TrueColor::from_rgb( (components.0 >> 2) | ((components.1 >> 2) << 8) | ((components.2 >> 2) << 16), ) } const fn c8c10(c8: u32) -> u32 { (c8 * 0x0101) >> 6 } #[inline] pub const fn rgb(&self) -> u32 { self.rgb } } impl From<TrueColor> for DeepColor30 { fn from(val: TrueColor) -> Self { Self::from_true_color(val) } } impl From<DeepColor30> for TrueColor { fn from(val: DeepColor30) -> Self { val.into_true_color() } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum AmbiguousColor { Indexed(IndexedColor), Argb32(TrueColor), } impl ColorTrait for AmbiguousColor {} impl AmbiguousColor { pub const TRANSPARENT: Self = Self::Argb32(TrueColor::TRANSPARENT); pub const BLACK: Self = Self::Indexed(IndexedColor::BLACK); pub const BLUE: Self = Self::Indexed(IndexedColor::BLUE); pub const GREEN: Self = Self::Indexed(IndexedColor::GREEN); pub const CYAN: Self = Self::Indexed(IndexedColor::CYAN); pub const RED: Self = Self::Indexed(IndexedColor::RED); pub const MAGENTA: Self = Self::Indexed(IndexedColor::MAGENTA); pub const BROWN: Self = Self::Indexed(IndexedColor::BROWN); pub const LIGHT_GRAY: Self = Self::Indexed(IndexedColor::LIGHT_GRAY); pub const DARK_GRAY: Self = Self::Indexed(IndexedColor::DARK_GRAY); pub const LIGHT_BLUE: Self = Self::Indexed(IndexedColor::LIGHT_BLUE); pub const LIGHT_GREEN: Self = Self::Indexed(IndexedColor::LIGHT_GREEN); pub const LIGHT_CYAN: Self = Self::Indexed(IndexedColor::LIGHT_CYAN); pub const LIGHT_RED: Self = Self::Indexed(IndexedColor::LIGHT_RED); pub const LIGHT_MAGENTA: Self = Self::Indexed(IndexedColor::LIGHT_MAGENTA); pub const YELLOW: Self = Self::Indexed(IndexedColor::YELLOW); pub const WHITE: Self = Self::Indexed(IndexedColor::WHITE); #[inline] pub const fn from_rgb(rgb: u32) -> Self { Self::Argb32(TrueColor::from_rgb(rgb)) } #[inline] pub const fn from_argb(rgb: u32) -> Self { Self::Argb32(TrueColor::from_argb(rgb)) } #[inline] pub const fn into_argb(&self) -> TrueColor { match self { AmbiguousColor::Indexed(v) => v.as_true_color(), AmbiguousColor::Argb32(v) => *v, } } } impl Into<IndexedColor> for AmbiguousColor { fn into(self) -> IndexedColor { match self { AmbiguousColor::Indexed(v) => v, AmbiguousColor::Argb32(v) => v.into(), } } } impl Into<TrueColor> for AmbiguousColor { fn into(self) -> TrueColor { match self { AmbiguousColor::Indexed(v) => v.into(), AmbiguousColor::Argb32(v) => v, } } } impl From<IndexedColor> for AmbiguousColor { fn from(val: IndexedColor) -> Self { Self::Indexed(val) } } impl From<TrueColor> for AmbiguousColor { fn from(val: TrueColor) -> Self { Self::Argb32(val) } }
use core::mem::transmute; pub trait ColorTrait: Sized + Copy + Clone + PartialEq + Eq {} #[repr(transparent)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct IndexedColor(pub u8); impl ColorTrait for IndexedColor {} impl IndexedColor { pub const MIN: Self = Self(u8::MIN); pub const MAX: Self = Self(u8::MAX); pub const DEFAULT_KEY: Self = Self(u8::MAX); pub const BLACK: Self = Self(0); pub const BLUE: Self = Self(1); pub const GREEN: Self = Self(2); pub const CYAN: Self = Self(3); pub const RED: Self = Self(4); pub const MAGENTA: Self = Self(5); pub const BROWN: Self = Self(6); pub const LIGHT_GRAY: Self = Self(7); pub const DARK_GRAY: Self = Self(8); pub const LIGHT_BLUE: Self = Self(9); pub const LIGHT_GREEN: Self = Self(10); pub const LIGHT_CYAN: Self = Self(11); pub const LIGHT_RED: Self = Self(12); pub const LIGHT_MAGENTA: Self = Self(13); pub const YELLOW: Self = Self(14); pub const WHITE: Self = Self(15); pub const COLOR_PALETTE: [u32; 256] = [ 0xFF212121, 0xFF0D47A1, 0xFF1B5E20, 0xFF006064, 0xFFb71c1c, 0xFF4A148C, 0xFF795548, 0xFF9E9E9E, 0xFF616161, 0xFF2196F3, 0xFF4CAF50, 0xFF00BCD4, 0xFFf44336, 0xFF9C27B0, 0xFFFFEB3B, 0xFFFFFFFF, 0xFF000000, 0xFF330000, 0xFF660000, 0xFF990000, 0xFFCC0000, 0xFFFF0000, 0xFF003300, 0xFF333300, 0xFF663300, 0xFF993300, 0xFFCC3300, 0xFFFF3300, 0xFF006600, 0xFF336600, 0xFF666600, 0xFF996600, 0xFFCC6600, 0xFFFF6600, 0xFF009900, 0xFF339900, 0xFF669900, 0xFF999900, 0xFFCC9900, 0xFFFF9900, 0xFF00CC00, 0xFF33CC00, 0xFF66CC00, 0xFF99CC00, 0xFFCCCC00, 0xFFFFCC00, 0xFF00FF00, 0xFF33FF00, 0xFF66FF00, 0xFF99FF00, 0xFFCCFF00, 0xFFFFFF00, 0xFF000033, 0xFF330033, 0xFF660033, 0xFF990033, 0xFFCC0033, 0xFFFF0033, 0xFF003333, 0xFF333333, 0xFF663333, 0xFF993333, 0xFFCC3333, 0xFFFF3333, 0xFF006633, 0xFF336633, 0xFF666633, 0xFF996633, 0xFFCC6633, 0xFFFF6633, 0xFF009933, 0xFF339933, 0xFF669933, 0xFF999933, 0xFFCC9933, 0xFFFF9933, 0xFF00CC33, 0xFF33CC33, 0xFF66CC33, 0xFF99CC33, 0xFFCCCC33, 0xFFFFCC33, 0xFF00FF33, 0xFF33FF33, 0xFF66FF33, 0xFF99FF33, 0xFFCCFF33, 0xFFFFFF33, 0xFF000066, 0xFF330066, 0xFF660066, 0xFF990066, 0xFFCC0066, 0xFFFF0066, 0xFF003366, 0xFF333366, 0xFF663366, 0xFF993366, 0xFFCC3366, 0xFFFF3366, 0xFF006666, 0xFF336666, 0xFF666666, 0xFF996666, 0xFFCC6666, 0xFFFF6666, 0xFF009966, 0xFF339966, 0xFF669966, 0xFF999966, 0xFFCC9966, 0xFFFF9966, 0xFF00CC66, 0xFF33CC66, 0xFF66CC66, 0xFF99CC66, 0xFFCCCC66, 0xFFFFCC66, 0xFF00FF66, 0xFF33FF66, 0xFF66FF66, 0xFF99FF66, 0xFFCCFF66, 0xFFFFFF66, 0xFF000099, 0xFF330099, 0xFF660099, 0xFF990099, 0xFFCC0099, 0xFFFF0099, 0xFF003399, 0xFF333399, 0xFF663399, 0xFF993399, 0xFFCC3399, 0xFFFF3399, 0xFF006699, 0xFF336699, 0xFF666699, 0xFF996699, 0xFFCC6699, 0xFFFF6699, 0xFF009999, 0xFF339999, 0xFF669999, 0xFF999999, 0xFFCC9999, 0xFFFF9999, 0xFF00CC99, 0xFF33CC99, 0xFF66CC99, 0xFF99CC99, 0xFFCCCC99, 0xFFFFCC99, 0xFF00FF99, 0xFF33FF99, 0xFF66FF99, 0xFF99FF99, 0xFFCCFF99, 0xFFFFFF99, 0xFF0000CC, 0xFF3300CC, 0xFF6600CC, 0xFF9900CC, 0xFFCC00CC, 0xFFFF00CC, 0xFF0033CC, 0xFF3333CC, 0xFF6633CC, 0xFF9933CC, 0xFFCC33CC, 0xFFFF33CC, 0xFF0066CC, 0xFF3366CC, 0xFF6666CC, 0xFF9966CC, 0xFFCC66CC, 0xFFFF66CC, 0xFF0099CC, 0xFF3399CC, 0xFF6699CC, 0xFF9999CC, 0xFFCC99CC, 0xFFFF99CC, 0xFF00CCCC, 0xFF33CCCC, 0xFF66CCCC, 0xFF99CCCC, 0xFFCCCCCC, 0xFFFFCCCC, 0xFF00FFCC, 0xFF33FFCC, 0xFF66FFCC, 0xFF99FFCC, 0xFFCCFFCC, 0xFFFFFFCC, 0xFF0000FF, 0xFF3300FF, 0xFF6600FF, 0xFF9900FF, 0xFFCC00FF, 0xFFFF00FF, 0xFF0033FF, 0xFF3333FF, 0xFF6633FF, 0xFF9933FF, 0xFFCC33FF, 0xFFFF33FF, 0xFF0066FF, 0xFF3366FF, 0xFF6666FF, 0xFF9966FF, 0xFFCC66FF, 0xFFFF66FF, 0xFF0099FF, 0xFF3399FF, 0xFF6699FF, 0xFF9999FF, 0xFFCC99FF, 0xFFFF99FF, 0xFF00CCFF, 0xFF33CCFF, 0xFF66CCFF, 0xFF99CCFF, 0xFFCCCCFF, 0xFFFFCCFF, 0xFF00FFFF, 0xFF33FFFF, 0xFF66FFFF, 0xFF99FFFF, 0xFFCCFFFF, 0xFFFFFFFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; #[inline] pub const fn from_rgb(rgb: u32) -> Self { let b = (((rgb & 0xFF) + 25) / 51) as u8; let g = ((((rgb >> 8) & 0xFF) + 25) / 51) as u8; let r = ((((rgb >> 16) & 0xFF) + 25) / 51) as u8; Self(16 + r + g * 6 + b * 36) } #[inline] pub const fn as_rgb(self) -> u32 { Self::COLOR_PALETTE[self.0 as usize] & 0xFF_FF_FF } #[inline] pub const fn as_argb(self) -> u32 { Self::COLOR_PALETTE[self.0 as usize] } #[inline] pub const fn as_true_color(self) -> TrueColor { TrueColor::from_argb(self.as_argb()) } } impl From<u8> for IndexedColor { fn from(val: u8) -> Self { Self(val) } } impl From<IndexedColor> for TrueColor { fn from(val: IndexedColor) -> Self { val.as_true_color() } } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct TrueColor { argb: u32, } impl ColorTrait for TrueColor {} impl TrueColor { pub const TRANSPARENT: Self = Self::from_argb(0); pub const WHITE: Self = Self::f
f { AmbiguousColor::Indexed(v) => v.as_true_color(), AmbiguousColor::Argb32(v) => *v, } } } impl Into<IndexedColor> for AmbiguousColor { fn into(self) -> IndexedColor { match self { AmbiguousColor::Indexed(v) => v, AmbiguousColor::Argb32(v) => v.into(), } } } impl Into<TrueColor> for AmbiguousColor { fn into(self) -> TrueColor { match self { AmbiguousColor::Indexed(v) => v.into(), AmbiguousColor::Argb32(v) => v, } } } impl From<IndexedColor> for AmbiguousColor { fn from(val: IndexedColor) -> Self { Self::Indexed(val) } } impl From<TrueColor> for AmbiguousColor { fn from(val: TrueColor) -> Self { Self::Argb32(val) } }
rom_rgb(0xFFFFFF); #[inline] pub const fn from_rgb(rgb: u32) -> Self { Self { argb: rgb | 0xFF000000, } } #[inline] pub const fn from_argb(argb: u32) -> Self { Self { argb } } #[inline] pub const fn gray(white: u8, alpha: u8) -> Self { Self { argb: white as u32 * 0x00_01_01_01 + alpha as u32 * 0x01_00_00_00, } } #[inline] pub fn components(self) -> ColorComponents { self.into() } #[inline] pub const fn rgb(self) -> u32 { self.argb & 0x00FFFFFF } #[inline] pub const fn argb(self) -> u32 { self.argb } #[inline] pub fn brightness(self) -> u8 { let cc = self.components(); ((cc.r as usize * 19589 + cc.g as usize * 38444 + cc.b as usize * 7502 + 32767) >> 16) as u8 } #[inline] pub const fn opacity(self) -> u8 { (self.argb >> 24) as u8 } #[inline] pub fn set_opacity(mut self, alpha: u8) -> Self { let mut components = self.components(); components.a = alpha; self.argb = components.into(); self } #[inline] pub const fn is_opaque(self) -> bool { self.opacity() == 0xFF } #[inline] pub const fn is_transparent(self) -> bool { self.opacity() == 0 } #[inline] pub fn blend_each<F>(self, rhs: Self, f: F) -> Self where F: Fn(u8, u8) -> u8, { self.components().blend_each(rhs.into(), f).into() } #[inline] pub fn blend_color<F1, F2>(self, rhs: Self, f_rgb: F1, f_a: F2) -> Self where F1: Fn(u8, u8) -> u8, F2: Fn(u8, u8) -> u8, { self.components().blend_color(rhs.into(), f_rgb, f_a).into() } #[inline] pub fn blend(self, other: Self) -> Self { let c = other.components(); let alpha_l = c.a as usize; let alpha_r = 255 - alpha_l; c.blend_each(self.components(), |a, b| { ((a as usize * alpha_l + b as usize * alpha_r) / 255) as u8 }) .into() } } impl From<u32> for TrueColor { fn from(val: u32) -> Self { Self::from_argb(val) } } impl From<TrueColor> for IndexedColor { fn from(val: TrueColor) -> Self { Self::from_rgb(val.rgb()) } } #[repr(C)] #[derive(Debug, Copy, Clone)] #[cfg(target_endian = "little")] pub struct ColorComponents { pub b: u8, pub g: u8, pub r: u8, pub a: u8, } impl ColorComponents { #[inline] pub fn blend_each<F>(self, rhs: Self, f: F) -> Self where F: Fn(u8, u8) -> u8, { Self { a: f(self.a, rhs.a), r: f(self.r, rhs.r), g: f(self.g, rhs.g), b: f(self.b, rhs.b), } } #[inline] pub fn blend_color<F1, F2>(self, rhs: Self, f_rgb: F1, f_a: F2) -> Self where F1: Fn(u8, u8) -> u8, F2: Fn(u8, u8) -> u8, { Self { a: f_a(self.a, rhs.a), r: f_rgb(self.r, rhs.r), g: f_rgb(self.g, rhs.g), b: f_rgb(self.b, rhs.b), } } #[inline] pub const fn is_opaque(self) -> bool { self.a == 255 } #[inline] pub const fn is_transparent(self) -> bool { self.a == 0 } } impl From<TrueColor> for ColorComponents { fn from(color: TrueColor) -> Self { unsafe { transmute(color) } } } impl From<ColorComponents> for TrueColor { fn from(components: ColorComponents) -> Self { unsafe { transmute(components) } } } impl Into<u32> for ColorComponents { fn into(self) -> u32 { unsafe { transmute(self) } } } #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DeepColor30 { rgb: u32, } impl ColorTrait for DeepColor30 {} impl DeepColor30 { #[inline] pub const fn from_rgb(rgb: u32) -> Self { Self { rgb } } #[inline] pub const fn from_true_color(val: TrueColor) -> Self { let rgb32 = val.argb(); let components = ( (rgb32 & 0xFF), ((rgb32 >> 8) & 0xFF), ((rgb32 >> 16) & 0xFF), ); Self { rgb: Self::c8c10(components.0) | (Self::c8c10(components.1) << 10) | (Self::c8c10(components.2) << 20), } } #[inline] pub const fn components(&self) -> (u32, u32, u32) { let rgb = self.rgb(); ((rgb & 0x3FF), ((rgb >> 10) & 0x3FF), ((rgb >> 20) & 0x3FF)) } #[inline] pub const fn into_true_color(&self) -> TrueColor { let components = self.components(); TrueColor::from_rgb( (components.0 >> 2) | ((components.1 >> 2) << 8) | ((components.2 >> 2) << 16), ) } const fn c8c10(c8: u32) -> u32 { (c8 * 0x0101) >> 6 } #[inline] pub const fn rgb(&self) -> u32 { self.rgb } } impl From<TrueColor> for DeepColor30 { fn from(val: TrueColor) -> Self { Self::from_true_color(val) } } impl From<DeepColor30> for TrueColor { fn from(val: DeepColor30) -> Self { val.into_true_color() } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum AmbiguousColor { Indexed(IndexedColor), Argb32(TrueColor), } impl ColorTrait for AmbiguousColor {} impl AmbiguousColor { pub const TRANSPARENT: Self = Self::Argb32(TrueColor::TRANSPARENT); pub const BLACK: Self = Self::Indexed(IndexedColor::BLACK); pub const BLUE: Self = Self::Indexed(IndexedColor::BLUE); pub const GREEN: Self = Self::Indexed(IndexedColor::GREEN); pub const CYAN: Self = Self::Indexed(IndexedColor::CYAN); pub const RED: Self = Self::Indexed(IndexedColor::RED); pub const MAGENTA: Self = Self::Indexed(IndexedColor::MAGENTA); pub const BROWN: Self = Self::Indexed(IndexedColor::BROWN); pub const LIGHT_GRAY: Self = Self::Indexed(IndexedColor::LIGHT_GRAY); pub const DARK_GRAY: Self = Self::Indexed(IndexedColor::DARK_GRAY); pub const LIGHT_BLUE: Self = Self::Indexed(IndexedColor::LIGHT_BLUE); pub const LIGHT_GREEN: Self = Self::Indexed(IndexedColor::LIGHT_GREEN); pub const LIGHT_CYAN: Self = Self::Indexed(IndexedColor::LIGHT_CYAN); pub const LIGHT_RED: Self = Self::Indexed(IndexedColor::LIGHT_RED); pub const LIGHT_MAGENTA: Self = Self::Indexed(IndexedColor::LIGHT_MAGENTA); pub const YELLOW: Self = Self::Indexed(IndexedColor::YELLOW); pub const WHITE: Self = Self::Indexed(IndexedColor::WHITE); #[inline] pub const fn from_rgb(rgb: u32) -> Self { Self::Argb32(TrueColor::from_rgb(rgb)) } #[inline] pub const fn from_argb(rgb: u32) -> Self { Self::Argb32(TrueColor::from_argb(rgb)) } #[inline] pub const fn into_argb(&self) -> TrueColor { match sel
random
[]
Rust
src/vcs.rs
kascote/rpure
7b12608ad46d2d81ead01abc2655153b431c1d09
use git2::{Repository, Status}; use std::env; use std::path::Path; #[derive(Debug)] pub enum VcsDirty { WTmodified, IDmodified, Green, } #[derive(Debug)] pub struct VcsStatus { pub name: String, pub dirty: String, pub dirty_status: VcsDirty, pub ahead: usize, pub behind: usize, pub stash: bool, pub state: String, } impl VcsStatus { pub fn blank() -> VcsStatus { VcsStatus { name: String::from(""), dirty: String::from(""), dirty_status: VcsDirty::Green, ahead: 0, behind: 0, stash: false, state: String::from(""), } } } pub fn vcs_status(cfg: &super::config::Config) -> Option<VcsStatus> { let current_dir = env::var("PWD").unwrap(); let mut status = VcsStatus::blank() ; let mut repo = vcs_repo(&current_dir)?; let state: String = format!("{:?}", repo.state()); if state != "Clean" { status.state = state; } let (ahead, behind) = get_ahead_behind(&repo)?; status.ahead = ahead; status.behind = behind; let each_stash = |_idx: usize, _name: &str, _oid: &git2::Oid| -> bool { status.stash = true; false }; repo.stash_foreach(each_stash).expect("error checking stashed files"); status.name = get_repo_name(&repo); status.dirty = cfg.git_clean.to_string(); let file_stats = repo.statuses(None).unwrap(); for file in file_stats.iter() { match file.status() { Status::WT_NEW | Status::WT_MODIFIED | Status::WT_DELETED | Status::WT_TYPECHANGE | Status::WT_RENAMED => { status.dirty = cfg.git_wt_modified.to_string(); status.dirty_status = VcsDirty::WTmodified; break; } Status::INDEX_NEW | Status::INDEX_MODIFIED | Status::INDEX_DELETED | Status::INDEX_TYPECHANGE | Status::INDEX_RENAMED => { status.dirty = cfg.git_index_modified.to_string(); status.dirty_status = VcsDirty::IDmodified; } _ => { status.dirty_status = VcsDirty::Green } } } return Some(status); } fn vcs_repo(current_dir: &String) -> Option<Repository> { let mut repo: Option<Repository> = None; let current_path = Path::new(&current_dir[..]); let mut idx = 0; for path in current_path.ancestors() { match Repository::open(path) { Ok(r) => { repo = Some(r); break; } Err(_) => {} } if idx == 10 { break; } idx += 1; } return repo; } fn get_ahead_behind(repo: &Repository) -> Option<(usize, usize)> { let head = match repo.head() { Ok(h) => h, Err(_) => return Some((0, 0)) }; if !head.is_branch() { return Some((0, 0)); } let head_name = head.shorthand()?; let head_branch = (repo.find_branch(head_name, git2::BranchType::Local).ok())?; let upstream = match head_branch.upstream() { Ok(u) => u, Err(_) => { return Some((0, 0)) } }; let head_oid = head.target()?; let upstream_oid = (upstream.get().target())?; let status = match repo.graph_ahead_behind(head_oid, upstream_oid) { Ok(r) => { let mut ahead = 0; let mut behind = 0; if r.0 > 0 { ahead = r.0; } if r.1 > 0 { behind = r.1; } (ahead, behind) }, Err(_) => (0, 0) }; return Some(status); } fn get_repo_name(repo: &Repository) -> String { let head = match repo.head() { Ok(r) => r, Err(_) => return String::from(""), }; if head.is_branch() { return head.shorthand().unwrap_or("err").into(); } else { let commit = head.peel_to_commit().unwrap(); return format!("{:.6}", commit.id()); } }
use git2::{Repository, Status}; use std::env; use std::path::Path; #[derive(Debug)] pub enum VcsDirty { WTmodified, IDmodified, Green, } #[derive(Debug)] pub struct VcsStatus { pub name: String, pub dirty: String, pub dirty_status: VcsDirty, pub ahead: usize, pub behind: usize, pub stash: bool, pub state: String, } impl VcsStatus { pub fn blank() -> VcsStatus { VcsStatus { name: String::from(""), dirty: String::from(""), dirty_status: VcsDirty::Green, ahead: 0, behind: 0, stash: false, state: String::from(""), } } } pub fn vcs_status(cfg: &super::config::Config) -> Option<VcsStatus> { let current_dir = env::var("PWD").unwrap(); let mut status = VcsStatus::blank() ; let mut repo = vcs_repo(&current_dir)?; let state: String = format!("{:?}", repo.state()); if state != "Clean" { status.state = state; } let (ahead, behind) = get_ahead_behind(&repo)?; status.ahead = ahead; status.behind = behind; let each_stash = |_idx: usize, _name: &str, _oid: &git2::Oid| -> bool { status.stash = true; false }; repo.stash_foreach(each_stash).expect("error checking stashed files"); status.name = get_repo_name(&repo); status.dirty = cfg.git_clean.to_string(); let file_stats = repo.statuses(None).unwrap(); for file in file_stats.iter() { match file.status() { Status::WT_NEW | Status::WT_MODIFIED | Status::WT_DELETED | Status::WT_TYPECHANGE | Status::WT_RENAMED => { status.dirty = cfg.git_wt_modified.to_string(); status.dirty_status = VcsDirty::WTmodified; break; } Status::INDEX_NEW | Status::INDEX_MODIFIED | Status::INDEX_DELETED | Status::INDEX_TYPECHANGE | Status::INDEX_RENAMED => { status.dirty = cfg.git_index_modified.to_string(); status.dirty_status = VcsDirty::IDmodified; } _ => { status.dirty_status = VcsDirty::Green } } } return Some(status); } fn vcs_repo(current_dir: &String) -> Option<Repository> { let mut repo: Option<Repository> = None; let current_path = Path::new(&current_dir[..]); let mut idx = 0; for path in current_path.ancestors() { match Repository::open(path) { Ok(r) => { repo = Some(r); break; } Err(_) => {} } if idx == 10 { break; } idx += 1; } return repo; } fn get_ahead_behind(repo: &Repository) -> Option<(usize, usize)> { let head = match repo.head() { Ok(h) => h, Err(_) => return Some((0, 0)) }; if !head.is_branch() { re
(ahead, behind) }, Err(_) => (0, 0) }; return Some(status); } fn get_repo_name(repo: &Repository) -> String { let head = match repo.head() { Ok(r) => r, Err(_) => return String::from(""), }; if head.is_branch() { return head.shorthand().unwrap_or("err").into(); } else { let commit = head.peel_to_commit().unwrap(); return format!("{:.6}", commit.id()); } }
turn Some((0, 0)); } let head_name = head.shorthand()?; let head_branch = (repo.find_branch(head_name, git2::BranchType::Local).ok())?; let upstream = match head_branch.upstream() { Ok(u) => u, Err(_) => { return Some((0, 0)) } }; let head_oid = head.target()?; let upstream_oid = (upstream.get().target())?; let status = match repo.graph_ahead_behind(head_oid, upstream_oid) { Ok(r) => { let mut ahead = 0; let mut behind = 0; if r.0 > 0 { ahead = r.0; } if r.1 > 0 { behind = r.1; }
function_block-random_span
[ { "content": "pub fn get_name() -> String {\n\n match env::var(\"VIRTUAL_ENV\") {\n\n Ok(venv_path) => {\n\n let venv_name = Path::new(&venv_path[..]).file_name();\n\n if let Some(name) = venv_name {\n\n if let Some(valid_name) = name.to_str() {\n\n ...
Rust
utils/indigo-service-uploader/rust/src/sd_import/sd_import.rs
tsingdao-Tp/Indigo
b2d73faebb6a450e9b3d34fed553fad4f9d0012f
extern crate postgres; extern crate time; extern crate num_cpus; extern crate threadpool; extern crate flate2; extern crate yaml_rust; extern crate postgres_binary_copy; extern crate rustc_serialize; mod sd_batch_uploader; mod sd_parser; use postgres::{Connection, SslMode, ConnectParams, ConnectTarget, UserInfo}; use std::collections::BTreeMap; use time::PreciseTime; use std::sync::mpsc; use std::thread; use threadpool::ThreadPool; use std::io::prelude::*; use std::fs::File; use flate2::read::GzDecoder; use sd_batch_uploader::SdBatchUploader; use sd_parser::{SdParser, SdItem}; use yaml_rust::{Yaml, YamlLoader}; pub struct SdImport { pub db_config: BTreeMap<String, String>, pub general_config: BTreeMap<String, yaml_rust::yaml::Yaml>, pub db_conn: Connection, } fn read_config(config_name: &str) -> (BTreeMap<String, String>, BTreeMap<String, yaml_rust::yaml::Yaml>) { let mut f_config = File::open(config_name) .ok() .expect(&format!("Can not open configuration file '{}'", config_name)); let mut s = String::new(); f_config.read_to_string(&mut s) .ok() .expect(&format!("Error while reading configuration file '{}'", config_name)); let conf = YamlLoader::load_from_str(&s).unwrap(); let mut db_config: BTreeMap<String, String> = BTreeMap::new(); let mut general_config: BTreeMap<String, yaml_rust::yaml::Yaml> = BTreeMap::new(); for c in conf { let h = c.as_hash().unwrap(); let db = h.get(&Yaml::String("database".to_string())).unwrap(); let db_conf = db.as_hash().unwrap(); for (k, v) in db_conf { db_config.insert(k.as_str().unwrap().to_string(), v.as_str().unwrap().to_string()); } let general = h.get(&Yaml::String("general".to_string())).expect("no general section in config"); let general_conf = general.as_hash().unwrap(); for (k, v) in general_conf { general_config.insert(k.as_str().unwrap().to_string(), v.clone()); } } (db_config, general_config) } impl<'a> SdImport { pub fn new(config_name: &str) -> SdImport { let (db_conf, general_conf) = read_config(config_name); let params = ConnectParams { target: ConnectTarget::Tcp(db_conf.get("url").unwrap().clone()), port: Some(5432), user: Some(UserInfo { user: db_conf.get("user").unwrap().clone(), password: Some(db_conf.get("pass").unwrap().clone()), }), database: Some(db_conf.get("db").unwrap().clone()), options: vec![], }; let conn = Connection::connect(params, &SslMode::None).unwrap(); SdImport { db_config: db_conf, general_config: general_conf, db_conn: conn, } } pub fn insert(&mut self, file_name: &str, table_name: &str) { let t_name = format!("{}.{}", self.db_config.get("schema").unwrap(), table_name); self.parallel_insert(file_name, &t_name) } fn parallel_insert(&mut self, file_name: &str, table_name: &str) { println!("Start import"); let start_t = PreciseTime::now(); let mut str_count: u32 = 0; let buf_size: usize = self.general_config.get("buffer_size").unwrap().as_i64().unwrap() as usize; let (map_send, map_rec) = mpsc::sync_channel(buf_size); let (reduce_send, reduce_rec) = mpsc::sync_channel(buf_size); let reduce_sender = reduce_send.clone(); let f_name = file_name.to_string(); let sd_reader = thread::spawn(move || { let pool = ThreadPool::new(num_cpus::get()); let f = File::open(f_name).unwrap(); let mut f_str = GzDecoder::new(f).unwrap(); let parser = SdParser::new(&mut f_str); for sd in parser { reduce_sender.send(1u8).unwrap(); let map_sender = map_send.clone(); pool.execute(move || { let sd_item = SdItem::new(&sd).unwrap(); map_sender.send(sd_item).unwrap(); }); str_count += 1; } reduce_sender.send(0u8).unwrap(); }); let sd_uploader = &mut SdBatchUploader::new(&self.db_conn, table_name).unwrap(); loop { let status = reduce_rec.recv().unwrap(); match status { 1u8 => { let sd_item: SdItem = map_rec.recv().unwrap(); sd_uploader.upload(sd_item); str_count += 1; } _ => break, } } sd_reader.join().unwrap(); let end_t = PreciseTime::now(); let timer_ms = start_t.to(end_t).num_milliseconds() as f32 ; let timer_s = timer_ms / 1000f32; println!("Insert total time = {} ms ", timer_ms as i32); println!("Average insert time = {} structures per second", ((str_count as f32) / timer_s) as i32); println!("Total structures processed = {}", str_count); } }
extern crate postgres; extern crate time; extern crate num_cpus; extern crate threadpool; extern crate flate2; extern crate yaml_rust; extern crate postgres_binary_copy; extern crate rustc_serialize; mod sd_batch_uploader; mod sd_parser; use postgres::{Connection, SslMode, ConnectParams, ConnectTarget, UserInfo}; use std::collections::BTreeMap; use time::PreciseTime; use std::sync::mpsc; use std::thread; use threadpool::ThreadPool; use std::io::prelude::*; use std::fs::File; use flate2::read::GzDecoder; use sd_batch_uploader::SdBatchUploader; use sd_parser::{SdParser, SdItem}; use yaml_rust::{Yaml, YamlLoader}; pub struct SdImport { pub db_config: BTreeMap<String, String>, pub general_config: BTreeMap<String, yaml_rust::yaml::Yaml>, pub db_conn: Connection, } fn read_config(config_name: &str) -> (BTreeMap<String, String>, BTreeMap<String, yaml_rust::yaml::Yaml>) { let mut f_config = File::open(config_name) .ok() .expect(&format!("Can not open configuration file '{}'", config_name)); let mut s = String::new(); f_config.read_to_string(&mut s) .ok() .expect(&format!("Error while reading configuration file '{}'", config_name)); let conf = YamlLoader::load_from_str(&s).unwrap(); let mut db_config: BTreeMap<String, String> = BTreeMap::new(); let mut general_config: BTreeMap<String, yaml_rust::yaml::Yaml> = BTreeMap::new(); for c in conf { let h = c.as_hash().unwrap(); let db = h.get(&Yaml::String("database".to_string())).unwrap(); let db_conf = db.as_hash().unwrap(); for (k, v) in db_conf { db_config.insert(k.as_str().unwrap().to_string(), v.as_str().unwrap().to_string()); } let general = h.get(&Yaml::String("general".to_string())).expect("no general section in config"); let general_conf = general.as_hash().unwrap(); for (k, v) in general_conf { general_config.insert(k.as_str().unwrap().to_string(), v.clone()); } } (db_config, general_config) } impl<'a> SdImport { pub fn new(config_name: &str) -> SdImport { let (db_conf, general_conf) = read_config(config_name); let params = ConnectParams { target: ConnectTarget::Tcp(db_conf.get("url").unwrap().clone()), port: Some(5432), user: Some(UserInfo { user: db_conf.get("user").unwrap().clone(), password: Some(db_conf.get("pass").unwrap().clone()), }), database: Some(db_conf.get("db").unwrap().clone()), options: vec![], }; let conn = Connection::connect(params, &SslMode::None).unwrap(); SdImport { db_config: db_conf, general_config: general_conf, db_conn: conn, } } pub fn insert(&mut self, file_name: &str, table_name: &str) { let t_name = format!("{}.{}", self.db_config.get("schema").unwrap(), table_name); self.parallel_insert(file_name, &t_name) } fn parallel_insert(&mut self, file_name: &str, table_name: &str) { println!("Start import"); let start_t = PreciseTime::now(); let mut str_count: u32 = 0; let buf_size: usize = self.general_config.get("buffer_size").unwrap().as_i64().unwrap() as usize; let (map_send, map_rec) = mpsc::sync_channel(buf_size); let (reduce_send, reduce_rec) = mpsc::sync_channel(buf_size); let reduce_sender = reduce_send.clone(); let f_name = file_name.to_string(); let sd_reader = thread::spawn(move || { let pool = ThreadPool::new(num_cpus::get()); let f = File::open(f_name).unwrap(); let mut f_str = GzDecoder::new(f).unwrap(); let parser = SdParser::new(&mut f_str); for sd in parser { reduce_sender.send(1u8).unwrap(); let map_sender = map_send.clone(); pool.execute(move || { let sd_item = SdItem::new(&sd).unwrap(); map_sender.send(sd_item).unwrap(); }); str_count += 1; } reduce_sender.send(0u8).unwrap(); }); let sd_uploader = &mut SdBatchUploader::new(&self.db_conn, table_name).unwrap(); loop { let status = reduce_rec.recv().unwrap();
} sd_reader.join().unwrap(); let end_t = PreciseTime::now(); let timer_ms = start_t.to(end_t).num_milliseconds() as f32 ; let timer_s = timer_ms / 1000f32; println!("Insert total time = {} ms ", timer_ms as i32); println!("Average insert time = {} structures per second", ((str_count as f32) / timer_s) as i32); println!("Total structures processed = {}", str_count); } }
match status { 1u8 => { let sd_item: SdItem = map_rec.recv().unwrap(); sd_uploader.upload(sd_item); str_count += 1; } _ => break, }
if_condition
[ { "content": "fn import(file_name: &str, table_name: &str, config_name: Option<String>) {\n\n let conf_name = config_name.unwrap_or(\"config.yml\".to_string());\n\n let mut sd_import = SdImport::new(&conf_name);\n\n sd_import.insert(file_name, table_name);\n\n}\n\n\n", "file_path": "utils/indigo-se...
Rust
app/gui/src/ide/integration/file_system.rs
enso-org/enso
2676aa50a3cc86a1c0673a3e60a553134e350b1b
use crate::prelude::*; use crate::controller::graph::NewNodeInfo; use crate::controller::upload::pick_non_colliding_name; use engine_protocol::language_server; use engine_protocol::language_server::ContentRoot; use engine_protocol::language_server::FileSystemObject; use enso_frp as frp; use ensogl_component::file_browser::model::Entry; use ensogl_component::file_browser::model::EntryType; use ensogl_component::file_browser::model::FolderContent; use ensogl_component::file_browser::model::FolderType; use json_rpc::error::RpcError; use std::iter::once; #[derive(Clone, Debug, Fail)] #[fail(display = "Invalid path received from File Browser Component: {}", path)] struct InvalidPath { path: String, } pub fn to_file_browser_path(path: &language_server::Path) -> std::path::PathBuf { let root_id_str = path.root_id.to_string(); let segments_str = path.segments.iter().map(AsRef::<str>::as_ref); once("/").chain(once(root_id_str.as_ref())).chain(segments_str).collect() } pub fn from_file_browser_path(path: &std::path::Path) -> FallibleResult<language_server::Path> { use std::path::Component::*; let mut iter = path.components(); match (iter.next(), iter.next()) { (Some(RootDir), Some(Normal(root_id))) => { let root_id = root_id.to_string_lossy().parse()?; Ok(language_server::Path::new(root_id, iter.map(|s| s.as_os_str().to_string_lossy()))) } _ => { let path = path.to_string_lossy().to_string(); Err(InvalidPath { path }.into()) } } } #[derive(Clone, Debug)] pub struct FileProvider { connection: Rc<language_server::Connection>, content_roots: Vec<Rc<ContentRoot>>, } impl FileProvider { pub fn new(project: &model::Project) -> Self { Self { connection: project.json_rpc(), content_roots: project.content_roots() } } } impl FolderContent for FileProvider { fn request_entries( &self, entries_loaded: frp::Any<Rc<Vec<Entry>>>, _error_occurred: frp::Any<ImString>, ) { let entries = self.content_roots.iter().filter_map(|root| { let ls_path = language_server::Path::new_root(root.id()); let path = to_file_browser_path(&ls_path); let (name, folder_type) = match &**root { language_server::ContentRoot::Project { .. } => Some(("Project".to_owned(), FolderType::Project)), language_server::ContentRoot::FileSystemRoot { path, .. } => Some((path.clone(), FolderType::Root)), language_server::ContentRoot::Home { .. } => Some(("Home".to_owned(), FolderType::Home)), language_server::ContentRoot::Library { .. } => None, /* We skip libraries, as */ language_server::ContentRoot::Custom { .. } => None, /* Custom content roots are * not used. */ }?; let type_ = EntryType::Folder { type_: folder_type, content: { let connection = self.connection.clone_ref(); DirectoryView::new_from_root(connection, root.clone_ref()).into() }, }; Some(Entry { type_, name, path }) }); entries_loaded.emit(Rc::new(entries.sorted().collect_vec())); } } #[derive(Clone, CloneRef, Debug)] pub struct DirectoryView { connection: Rc<language_server::Connection>, content_root: Rc<ContentRoot>, path: Rc<language_server::Path>, } impl DirectoryView { pub fn new_from_root( connection: Rc<language_server::Connection>, content_root: Rc<ContentRoot>, ) -> Self { let path = Rc::new(language_server::Path::new_root(content_root.id())); Self { connection, content_root, path } } pub fn sub_view(&self, sub_dir: impl Str) -> DirectoryView { DirectoryView { connection: self.connection.clone_ref(), content_root: self.content_root.clone_ref(), path: Rc::new(self.path.append_im(sub_dir)), } } pub async fn get_entries_list(&self) -> Result<Vec<Entry>, RpcError> { let response = self.connection.file_list(&self.path).await?; let entries = response.paths.into_iter().map(|fs_obj| match fs_obj { FileSystemObject::Directory { name, path } | FileSystemObject::DirectoryTruncated { name, path } | FileSystemObject::SymlinkLoop { name, path, .. } => { let path = to_file_browser_path(&path).join(&name); let sub = self.sub_view(&name); let type_ = EntryType::Folder { type_: FolderType::Standard, content: sub.into() }; Entry { type_, name, path } } FileSystemObject::File { name, path } | FileSystemObject::Other { name, path } => { let path = to_file_browser_path(&path).join(&name); let type_ = EntryType::File; Entry { type_, name, path } } }); Ok(entries.sorted().collect()) } } impl FolderContent for DirectoryView { fn request_entries( &self, entries_loaded: frp::Any<Rc<Vec<Entry>>>, error_occurred: frp::Any<ImString>, ) { let this = self.clone_ref(); executor::global::spawn(async move { match this.get_entries_list().await { Ok(entries) => entries_loaded.emit(Rc::new(entries)), Err(RpcError::RemoteError(error)) => error_occurred.emit(ImString::new(error.message)), Err(error) => error_occurred.emit(ImString::new(error.to_string())), } }); } } #[derive(Clone, Debug, Fail)] #[fail(display = "Invalid source file for copy/move operation: {}", path)] struct InvalidSourceFile { path: String, } pub fn create_node_from_file( project: &model::Project, graph: &controller::Graph, path: &std::path::Path, ) -> FallibleResult { let ls_path = from_file_browser_path(path)?; let path_segments = ls_path.segments.into_iter().join("/"); let content_root = project.content_root_by_id(ls_path.root_id)?; let path = match &*content_root { ContentRoot::Project { .. } => format!("Enso_Project.root/\"{}\"", path_segments), ContentRoot::FileSystemRoot { path, .. } => format!("\"{}/{}\"", path, path_segments), ContentRoot::Home { .. } => format!("File.home/\"{}\"", path_segments), ContentRoot::Library { namespace, name, .. } => format!("{}.{}.Enso_Project.root / \"{}\"", namespace, name, path_segments), ContentRoot::Custom { .. } => "Unsupported Content Root".to_owned(), }; let expression = format!("File.read {}", path); let node_info = NewNodeInfo::new_pushed_back(expression); graph.add_node(node_info)?; Ok(()) } #[allow(missing_docs)] #[derive(Copy, Clone, Debug)] pub enum FileOperation { Copy, Move, } impl Default for FileOperation { fn default() -> Self { Self::Copy } } impl FileOperation { pub fn verb(&self) -> &'static str { match self { Self::Copy => "copy", Self::Move => "move", } } } pub async fn do_file_operation( project: &model::Project, source: &std::path::Path, dest_dir: &std::path::Path, operation: FileOperation, ) -> FallibleResult { let json_rpc = project.json_rpc(); let ls_source = from_file_browser_path(source)?; let ls_dest = from_file_browser_path(dest_dir)?; let src_name = ls_source .file_name() .ok_or_else(|| InvalidSourceFile { path: source.to_string_lossy().to_string() })?; let dest_name = pick_non_colliding_name(&*json_rpc, &ls_dest, src_name).await?; let dest_full = ls_dest.append_im(dest_name); match operation { FileOperation::Copy => json_rpc.copy_file(&ls_source, &dest_full).await?, FileOperation::Move => json_rpc.move_file(&ls_source, &dest_full).await?, } Ok(()) }
use crate::prelude::*; use crate::controller::graph::NewNodeInfo; use crate::controller::upload::pick_non_colliding_name; use engine_protocol::language_server; use engine_protocol::language_server::ContentRoot; use engine_protocol::language_server::FileSystemObject; use enso_frp as frp; use ensogl_component::file_browser::model::Entry; use ensogl_component::file_browser::model::EntryType; use ensogl_component::file_browser::model::FolderContent; use ensogl_component::file_browser::model::FolderType; use json_rpc::error::RpcError; use std::iter::once; #[derive(Clone, Debug, Fail)] #[fail(display = "Invalid path received from File Browser Component: {}", path)] struct InvalidPath { path: String, } pub fn to_file_browser_path(path: &language_server::Path) -> std::path::PathBuf { let root_id_str = path.root_id.to_string(); let segments_str = path.segments.iter().map(AsRef::<str>::as_ref); once("/").chain(once(root_id_str.as_ref())).chain(segments_str).collect() } pub fn from_file_browser_path(path: &std::path::Path) -> FallibleResult<language_server::Path> { use std::path::Component::*; let mut iter = path.components(); match (iter.next(), iter.next()) { (Some(RootDir), Some(Normal(root_id))) => { let root_id = root_id.to_string_lossy().parse()?; Ok(language_server::Path::new(root_id, iter.map(|s| s.as_os_str().to_string_lossy()))) } _ => { let path = path.to_string_lossy().to_string(); Err(InvalidPath { path }.into()) } } } #[derive(Clone, Debug)] pub struct FileProvider { connection: Rc<language_server::Connection>, content_roots: Vec<Rc<ContentRoot>>, } impl FileProvider { pub fn new(project: &model::Project) -> Self { Self { connection: project.json_rpc(), content_roots: project.content_roots() } } } impl FolderContent for FileProvider { fn request_entries( &self, entries_loaded: frp::Any<Rc<Vec<Entry>>>, _error_occurred: frp::Any<ImString>, ) { let entries = self.content_roots.iter().filter_map(|root| { let ls_path = language_server::Path::new_root(root.id()); let path = to_file_browser_path(&ls_path); let (name, folder_type) = match &**root { language_server::ContentRoot::Project { .. } => Some(("Project".to_owned(), FolderType::Project)), language_server::ContentRoot::FileSystemRoot { path, .. } => Some((path.clone(), FolderType::Root)), language_server::ContentRoot::Home { .. } => Some(("Home".to_owned(), FolderType::Home)), language_server::ContentRoot::Library { .. } => None, /* We skip libraries, as */ language_server::ContentRoot::Custom { .. } => None, /* Custom content roots are * not used. */ }?; let type_ = EntryType::Folder { type_: folder_type, content: { let connection = self.connection.clone_ref(); DirectoryView::new_from_root(connection, root.clone_ref()).into() }, }; Some(Entry { type_, name, path }) }); entries_loaded.emit(Rc::new(entries.sorted().collect_vec())); } } #[derive(Clone, CloneRef, Debug)] pub struct DirectoryView { connection: Rc<language_server::Connection>, content_root: Rc<ContentRoot>, path: Rc<language_server::Path>, } impl DirectoryView { pub fn new_from_root( connection: Rc<language_server::Connection>, content_root: Rc<ContentRoot>, ) -> Self { let path = Rc::new(language_server::Path::new_root(content_root.id())); Self { connection, content_root, path } }
pub async fn get_entries_list(&self) -> Result<Vec<Entry>, RpcError> { let response = self.connection.file_list(&self.path).await?; let entries = response.paths.into_iter().map(|fs_obj| match fs_obj { FileSystemObject::Directory { name, path } | FileSystemObject::DirectoryTruncated { name, path } | FileSystemObject::SymlinkLoop { name, path, .. } => { let path = to_file_browser_path(&path).join(&name); let sub = self.sub_view(&name); let type_ = EntryType::Folder { type_: FolderType::Standard, content: sub.into() }; Entry { type_, name, path } } FileSystemObject::File { name, path } | FileSystemObject::Other { name, path } => { let path = to_file_browser_path(&path).join(&name); let type_ = EntryType::File; Entry { type_, name, path } } }); Ok(entries.sorted().collect()) } } impl FolderContent for DirectoryView { fn request_entries( &self, entries_loaded: frp::Any<Rc<Vec<Entry>>>, error_occurred: frp::Any<ImString>, ) { let this = self.clone_ref(); executor::global::spawn(async move { match this.get_entries_list().await { Ok(entries) => entries_loaded.emit(Rc::new(entries)), Err(RpcError::RemoteError(error)) => error_occurred.emit(ImString::new(error.message)), Err(error) => error_occurred.emit(ImString::new(error.to_string())), } }); } } #[derive(Clone, Debug, Fail)] #[fail(display = "Invalid source file for copy/move operation: {}", path)] struct InvalidSourceFile { path: String, } pub fn create_node_from_file( project: &model::Project, graph: &controller::Graph, path: &std::path::Path, ) -> FallibleResult { let ls_path = from_file_browser_path(path)?; let path_segments = ls_path.segments.into_iter().join("/"); let content_root = project.content_root_by_id(ls_path.root_id)?; let path = match &*content_root { ContentRoot::Project { .. } => format!("Enso_Project.root/\"{}\"", path_segments), ContentRoot::FileSystemRoot { path, .. } => format!("\"{}/{}\"", path, path_segments), ContentRoot::Home { .. } => format!("File.home/\"{}\"", path_segments), ContentRoot::Library { namespace, name, .. } => format!("{}.{}.Enso_Project.root / \"{}\"", namespace, name, path_segments), ContentRoot::Custom { .. } => "Unsupported Content Root".to_owned(), }; let expression = format!("File.read {}", path); let node_info = NewNodeInfo::new_pushed_back(expression); graph.add_node(node_info)?; Ok(()) } #[allow(missing_docs)] #[derive(Copy, Clone, Debug)] pub enum FileOperation { Copy, Move, } impl Default for FileOperation { fn default() -> Self { Self::Copy } } impl FileOperation { pub fn verb(&self) -> &'static str { match self { Self::Copy => "copy", Self::Move => "move", } } } pub async fn do_file_operation( project: &model::Project, source: &std::path::Path, dest_dir: &std::path::Path, operation: FileOperation, ) -> FallibleResult { let json_rpc = project.json_rpc(); let ls_source = from_file_browser_path(source)?; let ls_dest = from_file_browser_path(dest_dir)?; let src_name = ls_source .file_name() .ok_or_else(|| InvalidSourceFile { path: source.to_string_lossy().to_string() })?; let dest_name = pick_non_colliding_name(&*json_rpc, &ls_dest, src_name).await?; let dest_full = ls_dest.append_im(dest_name); match operation { FileOperation::Copy => json_rpc.copy_file(&ls_source, &dest_full).await?, FileOperation::Move => json_rpc.move_file(&ls_source, &dest_full).await?, } Ok(()) }
pub fn sub_view(&self, sub_dir: impl Str) -> DirectoryView { DirectoryView { connection: self.connection.clone_ref(), content_root: self.content_root.clone_ref(), path: Rc::new(self.path.append_im(sub_dir)), } }
function_block-full_function
[ { "content": "/// Return FRP endpoints for the parameters that define a shadow.\n\npub fn frp_from_style(style: &StyleWatchFrp, path: impl Into<style::Path>) -> ParametersFrp {\n\n let path: style::Path = path.into();\n\n ParametersFrp {\n\n base_color: style.get_color(&path),\n\n fading: ...
Rust
hsp3-analyzer-mini/ham-core/src/assists/completion.rs
vain0x/hsp3-ginger
c5924b60686d4bf1769569c013c8110f7636732c
use super::*; use crate::{ analysis::{HspSymbolKind, LocalScope, Scope, SymbolRc}, assists::from_document_position, lang_service::docs::Docs, parse::{p_param_ty::PParamCategory, PToken}, source::*, token::TokenKind, }; use lsp_types::{CompletionItem, CompletionItemKind, CompletionList, Documentation, Position, Url}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashSet; pub(crate) enum ACompletionItem { Symbol(SymbolRc), } pub(crate) fn in_str_or_comment(pos: Pos16, tokens: &[PToken]) -> bool { let i = match tokens.binary_search_by_key(&pos, |t| Pos16::from(t.ahead().range.start())) { Ok(i) | Err(i) => i.saturating_sub(1), }; tokens[i..] .iter() .take_while(|t| t.ahead().start() <= pos) .flat_map(|t| t.iter()) .filter(|t| t.loc.range.contains_inclusive(pos)) .any(|t| match t.kind { TokenKind::Str => t.loc.range.start() < pos && pos < t.loc.range.end(), TokenKind::Comment => t.loc.range.start() < pos, _ => false, }) } pub(crate) fn in_preproc(pos: Pos16, tokens: &[PToken]) -> bool { let mut i = match tokens.binary_search_by_key(&pos, |token| token.body_pos16()) { Ok(i) | Err(i) => i, }; loop { match tokens.get(i).map(|t| (t.kind(), t.body_pos())) { Some((TokenKind::Hash, p)) if p <= pos => return true, Some((TokenKind::Eos, p)) if p < pos => return false, _ if i == 0 => return false, _ => i -= 1, } } } fn collect_local_completion_items( symbols: &[SymbolRc], local: &LocalScope, completion_items: &mut Vec<ACompletionItem>, ) { for s in symbols { let scope = match &s.scope_opt { Some(it) => it, None => continue, }; if scope.is_visible_to(local) { completion_items.push(ACompletionItem::Symbol(s.clone())); } } } fn collect_global_completion_items( symbols: &[SymbolRc], completion_items: &mut Vec<ACompletionItem>, ) { for s in symbols { if let Some(Scope::Global) = s.scope_opt { completion_items.push(ACompletionItem::Symbol(s.clone())); } } } pub(crate) fn collect_symbols_as_completion_items( doc: DocId, scope: LocalScope, doc_symbols: &[(DocId, &[SymbolRc])], completion_items: &mut Vec<ACompletionItem>, ) { if let Some((_, symbols)) = doc_symbols.iter().find(|&&(d, _)| d == doc) { collect_local_completion_items(symbols, &scope, completion_items); } if scope.is_outside_module() { for &(d, symbols) in doc_symbols { if d == doc { continue; } collect_local_completion_items(symbols, &scope, completion_items); } } for &(_, symbols) in doc_symbols { collect_global_completion_items(symbols, completion_items); } } fn to_completion_symbol_kind(kind: HspSymbolKind) -> CompletionItemKind { use CompletionItemKind as K; match kind { HspSymbolKind::Unresolved | HspSymbolKind::Unknown => K::TEXT, HspSymbolKind::Label => K::VALUE, HspSymbolKind::StaticVar => K::VARIABLE, HspSymbolKind::Const => K::CONSTANT, HspSymbolKind::Enum => K::ENUM_MEMBER, HspSymbolKind::Macro { ctype: false } => K::VALUE, HspSymbolKind::Macro { ctype: true } => K::FUNCTION, HspSymbolKind::DefFunc => K::METHOD, HspSymbolKind::DefCFunc => K::FUNCTION, HspSymbolKind::ModFunc => K::METHOD, HspSymbolKind::ModCFunc => K::FUNCTION, HspSymbolKind::Param(None) => K::VARIABLE, HspSymbolKind::Param(Some(param)) => match param.category() { PParamCategory::ByValue => K::VALUE, PParamCategory::ByRef => K::PROPERTY, PParamCategory::Local => K::VARIABLE, PParamCategory::Auto => K::TEXT, }, HspSymbolKind::Module => K::MODULE, HspSymbolKind::Field => K::FIELD, HspSymbolKind::LibFunc => K::FUNCTION, HspSymbolKind::PluginCmd => K::KEYWORD, HspSymbolKind::ComInterface => K::INTERFACE, HspSymbolKind::ComFunc => K::METHOD, } } fn to_lsp_completion_item(symbol: &SymbolRc) -> CompletionItem { let details = symbol.compute_details(); let detail = details.desc.map(|s| s.to_string()); let documentation = if details.docs.is_empty() { None } else { Some(Documentation::String(details.docs.join("\r\n\r\n"))) }; let sort_text = { let sort_prefix = match (&symbol.scope_opt, symbol.kind) { (Some(Scope::Local(local)), _) => match (&local.module_opt, local.deffunc_opt) { (Some(_), Some(_)) => 'a', (Some(_), None) => 'b', (None, None) => 'c', (None, Some(_)) => 'd', }, (_, HspSymbolKind::Module) => 'f', (Some(Scope::Global), _) => 'e', (None, _) => 'g', }; Some(format!("{}{}", sort_prefix, symbol.name)) }; CompletionItem { kind: Some(to_completion_symbol_kind(symbol.kind)), label: symbol.name.to_string(), detail, documentation, sort_text, ..CompletionItem::default() } } fn new_completion_list(items: Vec<CompletionItem>) -> CompletionList { CompletionList { is_incomplete: false, items, } } pub(crate) fn incomplete_completion_list() -> CompletionList { CompletionList { is_incomplete: true, items: vec![], } } fn do_completion( uri: &Url, position: Position, docs: &Docs, wa: &mut WorkspaceAnalysis, ) -> Option<CompletionList> { let mut items = vec![]; let (doc, pos) = from_document_position(uri, position, docs)?; if wa.in_str_or_comment(doc, pos).unwrap_or(true) { return None; } if wa.in_preproc(doc, pos).unwrap_or(false) { wa.require_project_for_doc(doc) .collect_preproc_completion_items(&mut items); return Some(new_completion_list(items)); } let mut completion_items = vec![]; let p = wa.require_project_for_doc(doc); p.collect_completion_items(doc, pos, &mut completion_items); for item in completion_items { match item { ACompletionItem::Symbol(symbol) => { if symbol.linked_symbol_opt.borrow().is_some() { continue; } items.push(to_lsp_completion_item(&symbol)); } } } p.collect_hsphelp_completion_items(&mut items); if let Some(i) = items.iter().position(|item| item.label == "__hspdef__") { items.swap_remove(i); } { let mut set = HashSet::new(); let retain = items .iter() .map(|item| set.insert(item.label.as_str())) .collect::<Vec<_>>(); let mut i = 0; items.retain(|_| { i += 1; retain[i - 1] }); } Some(new_completion_list(items)) } #[derive(Serialize, Deserialize)] struct CompletionData { uri: Url, position: Position, data_opt: Option<Value>, } pub(crate) fn completion( uri: Url, position: Position, docs: &Docs, wa: &mut WorkspaceAnalysis, ) -> Option<CompletionList> { let mut completion_list = do_completion(&uri, position, docs, wa)?; for item in &mut completion_list.items { if item.documentation.is_none() && item.data.is_none() { continue; } item.documentation = None; let data_opt = item.data.take(); let data = CompletionData { uri: uri.clone(), position, data_opt, }; item.data = Some(serde_json::to_value(&data).unwrap()); } Some(completion_list) } pub(crate) fn completion_resolve( mut resolved_item: CompletionItem, docs: &Docs, wa: &mut WorkspaceAnalysis, ) -> Option<CompletionItem> { let data: CompletionData = match resolved_item .data .take() .and_then(|data| serde_json::from_value(data).ok()) { Some(it) => it, None => { return Some(resolved_item); } }; let CompletionData { uri, position, data_opt, } = data; let list = do_completion(&uri, position, docs, wa)?; let item = list .items .into_iter() .find(|i| i.label == resolved_item.label)?; resolved_item.documentation = item.documentation; resolved_item.data = data_opt; Some(resolved_item) }
use super::*; use crate::{ analysis::{HspSymbolKind, LocalScope, Scope, SymbolRc}, assists::from_document_position, lang_service::docs::Docs, parse::{p_param_ty::PParamCategory, PToken}, source::*, token::TokenKind, }; use lsp_types::{CompletionItem, CompletionItemKind, CompletionList, Documentation, Position, Url}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashSet; pub(crate) enum ACompletionItem { Symbol(SymbolRc), } pub(crate) fn in_str_or_comment(pos: Pos16, tokens: &[PToken]) -> bool { let i = match tokens.binary_search_by_key(&pos, |t| Pos16::from(t.ahead().range.start())) { Ok(i) | Err(i) => i.saturating_sub(1), }; tokens[i..] .iter() .take_while(|t| t.ahead().start() <= pos) .flat_map(|t| t.iter()) .filter(|t| t.loc.range.contains_inclusive(pos)) .any(|t| match t.kind { TokenKind::Str => t.loc.range.start() < pos && pos < t.loc.range.end(), TokenKind::Comment => t.loc.range.start() < pos, _ => false, }) } pub(crate) fn in_preproc(pos: Pos16, tokens: &[PToken]) -> bool { let mut i = match tokens.binary_search_by_key(&pos, |token| token.body_pos16()) { Ok(i) | Err(i) => i, }; loop { match tokens.get(i).map(|t| (t.kind(), t.body_pos())) { Some((TokenKind::Hash, p)) if p <= pos => return true, Some((TokenKind::Eos, p)) if p < pos => return false, _ if i == 0 => return false, _ => i -= 1, } } } fn collect_local_completion_items( symbols: &[SymbolRc], local: &LocalScope, completion_items: &mut Vec<ACompletionItem>, ) { for s in symbols { let scope = match &s.scope_opt { Some(it) => it, None => continue, }; if scope.is_visible_to(local) { completion_items.push(ACompletionItem::Symbol(s.clone())); } } } fn collect_global_completion_items( symbols: &[SymbolRc], completion_items: &mut Vec<ACompletionItem>, ) { for s in symbols { if let Some(Scope::Global) = s.scope_opt { completion_items.push(ACompletionItem::Symbol(s.clone())); } } } pub(crate) fn collect_symbols_as_completion_items( doc: DocId, scope: LocalScope, doc_symbols: &[(DocId, &[SymbolRc])], completion_items: &mut Vec<ACompletionItem>, ) { if let Some((_, symbols)) = doc_symbols.iter().find(|&&(d, _)| d == doc) { collect_local_completion_items(symbols, &scope, completion_items); } if scope.is_outside_module() { for &(d, symbols) in doc_symbols { if d == doc { continue; } collect_local_completion_items(symbols, &scope, completion_items); } } for &(_, symbols) in doc_symbols { collect_global_completion_items(symbols, completion_items); } } fn to_completion_symbol_kind(kind: HspSymbolKind) -> CompletionItemKind { use CompletionItemKind as K; match kind { HspSymbolKind::Unresolved | HspSymbolKind::Unknown => K::TEXT, HspSymbolKind::Label => K::VALUE, HspSymbolKind::StaticVar => K::VARIABLE, HspSymbolKind::Const => K::CONSTANT, HspSymbolKind::Enum => K::ENUM_MEMBER, HspSymbolKind::Macro { ctype: false } => K::VALUE, HspSymbolKind::Macro { ctype: true } => K::FUNCTION, HspSymbolKind::DefFunc => K::METHOD, HspSymbolKind::DefCFunc => K::FUNCTION, HspSymbolKind::ModFunc => K::METHOD, HspSymbolKind::ModCFunc => K::FUNCTION, HspSymbolKind::Param(None) => K::VARIABLE, HspSymbolKind::Param(Some(param)) => match param.category() { PParamCategory::ByValue => K::VALUE, PParamCategory::ByRef => K::PROPERTY, PParamCategory::Local => K::VARIABLE, PParamCategory::Auto => K::TEXT, }, HspSymbolKind::Module => K::MODULE, HspSymbolKind::Field => K::FIELD, HspSymbolKind::LibFunc => K::FUNCTION, HspSymbolKind::PluginCmd => K::KEYWORD, HspSymbolKind::ComInterface => K::INTERFACE, HspSymbolKind::ComFunc => K::METHOD, } } fn to_lsp_completion_item(symbol: &SymbolRc) -> CompletionItem { let details = symbol.compute_details(); let detail = details.desc.map(|s| s.to_string()); let documentation = if details.docs.is_empty() { None } else { Some(Documentation::String(details.docs.join("\r\n\r\n"))) }; let sort_text = { let sort_prefix = match (&symbol.scope_opt, symbol.kind) { (Some(Scope::Local(local)), _) => match (&local.module_opt, local.deffunc_opt) { (Some(_), Some(_)) => 'a', (Some(_), None) => 'b', (None, None) => 'c', (None, Some(_)) => 'd', }, (_, HspSymbolKind::Module) => 'f', (Some(Scope::Global), _) => 'e', (None, _) => 'g', }; Some(format!("{}{}", sort_prefix, symbol.name)) }; CompletionItem { kind: Some(to_completion_symbol_kind(symbol.kind)), label: symbol.name.to_string(), detail, documentation, sort_text, ..CompletionItem::default() } } fn new_completion_list(items: Vec<CompletionItem>) -> CompletionList { CompletionList { is_incomplete: false, items, } } pub(crate) fn incomp
items.swap_remove(i); } { let mut set = HashSet::new(); let retain = items .iter() .map(|item| set.insert(item.label.as_str())) .collect::<Vec<_>>(); let mut i = 0; items.retain(|_| { i += 1; retain[i - 1] }); } Some(new_completion_list(items)) } #[derive(Serialize, Deserialize)] struct CompletionData { uri: Url, position: Position, data_opt: Option<Value>, } pub(crate) fn completion( uri: Url, position: Position, docs: &Docs, wa: &mut WorkspaceAnalysis, ) -> Option<CompletionList> { let mut completion_list = do_completion(&uri, position, docs, wa)?; for item in &mut completion_list.items { if item.documentation.is_none() && item.data.is_none() { continue; } item.documentation = None; let data_opt = item.data.take(); let data = CompletionData { uri: uri.clone(), position, data_opt, }; item.data = Some(serde_json::to_value(&data).unwrap()); } Some(completion_list) } pub(crate) fn completion_resolve( mut resolved_item: CompletionItem, docs: &Docs, wa: &mut WorkspaceAnalysis, ) -> Option<CompletionItem> { let data: CompletionData = match resolved_item .data .take() .and_then(|data| serde_json::from_value(data).ok()) { Some(it) => it, None => { return Some(resolved_item); } }; let CompletionData { uri, position, data_opt, } = data; let list = do_completion(&uri, position, docs, wa)?; let item = list .items .into_iter() .find(|i| i.label == resolved_item.label)?; resolved_item.documentation = item.documentation; resolved_item.data = data_opt; Some(resolved_item) }
lete_completion_list() -> CompletionList { CompletionList { is_incomplete: true, items: vec![], } } fn do_completion( uri: &Url, position: Position, docs: &Docs, wa: &mut WorkspaceAnalysis, ) -> Option<CompletionList> { let mut items = vec![]; let (doc, pos) = from_document_position(uri, position, docs)?; if wa.in_str_or_comment(doc, pos).unwrap_or(true) { return None; } if wa.in_preproc(doc, pos).unwrap_or(false) { wa.require_project_for_doc(doc) .collect_preproc_completion_items(&mut items); return Some(new_completion_list(items)); } let mut completion_items = vec![]; let p = wa.require_project_for_doc(doc); p.collect_completion_items(doc, pos, &mut completion_items); for item in completion_items { match item { ACompletionItem::Symbol(symbol) => { if symbol.linked_symbol_opt.borrow().is_some() { continue; } items.push(to_lsp_completion_item(&symbol)); } } } p.collect_hsphelp_completion_items(&mut items); if let Some(i) = items.iter().position(|item| item.label == "__hspdef__") {
random
[ { "content": "fn add_symbol(kind: HspSymbolKind, name: &PToken, def_site: bool, ctx: &mut Ctx) {\n\n let NameScopeNsTriple {\n\n basename,\n\n scope_opt,\n\n ns_opt,\n\n } = resolve_name_scope_ns_for_def(\n\n &name.body.text,\n\n ImportMode::Local,\n\n &ctx.scope,...
Rust
muse/src/instrument.rs
khonsulabs/muse
26aadbc56b3c2029b5d1740da7aa3f9873cfd66d
use crate::{ envelope::PlayingState, manager::{Device, PlayingHandle}, node::{Instantiatable, LoadedInstrument}, note::Note, sampler::PreparedSampler, }; use crossbeam::atomic::AtomicCell; use std::{ sync::{Arc, RwLock}, time::Duration, }; #[cfg(feature = "serialization")] pub mod serialization; pub struct GeneratedTone<T> { pub source: T, pub control: ControlHandle, } pub type ControlHandle = Arc<AtomicCell<PlayingState>>; #[derive(Debug, Default)] pub struct ControlHandles(Arc<RwLock<Vec<ControlHandle>>>); impl ControlHandles { pub fn new() -> Self { Self(Arc::new(RwLock::new(Vec::new()))) } pub fn push(&self, value: ControlHandle) { let mut vec = self.0.write().unwrap(); vec.push(value); } pub fn is_playing(&self) -> bool { let vec = self.0.read().unwrap(); for control in vec.iter() { if let PlayingState::Playing = control.load() { return true; } } false } fn stop(&self) { let vec = self.0.read().unwrap(); for control in vec.iter() { control.store(PlayingState::Stopping); } } fn stopped(&self) -> bool { let control_handles = self.0.read().unwrap(); control_handles .iter() .map(|control| control.load()) .all(|state| state == PlayingState::Stopped) } fn sustain(&self) { let vec = self.0.read().unwrap(); for control in vec.iter() { control.store(PlayingState::Sustaining); } } pub fn new_handle(&self) -> ControlHandle { let handle = Arc::new(AtomicCell::new(PlayingState::Playing)); let mut vec = self.0.write().unwrap(); vec.push(handle.clone()); handle } } #[derive(Debug)] pub struct InstrumentController<T> { pub control_handles: ControlHandles, _tone_generator: std::marker::PhantomData<T>, } impl<T> Default for InstrumentController<T> { fn default() -> Self { Self { control_handles: ControlHandles::new(), _tone_generator: std::marker::PhantomData::default(), } } } impl<T> InstrumentController<T> where T: ToneGenerator, T::CustomNodes: Instantiatable + Clone + 'static, { pub fn instantiate( &mut self, sampler: &LoadedInstrument<T::CustomNodes>, note: Note, ) -> Result<PreparedSampler, serialization::Error> { Ok(sampler.instantiate(&note, &self.control_handles)) } } pub trait ToneGenerator: Sized { type CustomNodes: Instantiatable + Clone + 'static; fn generate_tone( &mut self, note: Note, control: &mut InstrumentController<Self>, ) -> Result<PreparedSampler, anyhow::Error>; } pub struct PlayingNote<T> { note: Note, handle: Option<PlayingHandle>, controller: InstrumentController<T>, } impl<T> PlayingNote<T> { fn is_playing(&self) -> bool { self.controller.control_handles.is_playing() } fn stop(&self) { self.controller.control_handles.stop() } fn sustain(&self) { self.controller.control_handles.sustain() } } impl<T> Drop for PlayingNote<T> { fn drop(&mut self) { self.stop(); let handle = std::mem::take(&mut self.handle); let control_handles = std::mem::take(&mut self.controller.control_handles); std::thread::spawn(move || loop { { if control_handles.stopped() { println!("Sound stopping"); drop(handle); return; } } std::thread::sleep(Duration::from_millis(10)); }); } } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum Loudness { Fortissimo, MezzoForte, Pianissimo, } pub struct VirtualInstrument<T> { playing_notes: Vec<PlayingNote<T>>, device: Device, sustain: bool, tone_generator: T, } impl<T> VirtualInstrument<T> where T: ToneGenerator, { pub fn new(device: Device, tone_generator: T) -> Self { Self { device, tone_generator, playing_notes: Vec::new(), sustain: false, } } pub fn new_with_default_output(tone_generator: T) -> Result<Self, anyhow::Error> { let device = Device::default_output()?; Ok(Self::new(device, tone_generator)) } pub fn play_note(&mut self, note: Note) -> Result<(), anyhow::Error> { self.playing_notes .retain(|n| n.note.step() as u8 != note.step() as u8); let mut controller = InstrumentController::default(); let source = self.tone_generator.generate_tone(note, &mut controller)?; let handle = Some(self.device.play(source, note)?); self.playing_notes.push(PlayingNote { note, handle, controller, }); Ok(()) } pub fn stop_note(&mut self, step: u8) { if self.sustain { if let Some(existing_note) = self .playing_notes .iter_mut() .find(|pn| pn.note.step() as u8 == step) { existing_note.sustain(); } } else { self.playing_notes.retain(|pn| pn.note.step() as u8 != step); } } pub fn set_sustain(&mut self, active: bool) { self.sustain = active; if !active { self.playing_notes.retain(|n| n.is_playing()); } } }
use crate::{ envelope::PlayingState, manager::{Device, PlayingHandle}, node::{Instantiatable, LoadedInstrument}, note::Note, sampler::PreparedSampler, }; use crossbeam::atomic::AtomicCell; use std::{ sync::{Arc, RwLock}, time::Duration, }; #[cfg(feature = "serialization")] pub mod serialization; pub struct GeneratedTone<T> { pub source: T, pub control: ControlHandle, } pub type ControlHandle = Arc<AtomicCell<PlayingState>>; #[derive(Debug, Default)] pub struct ControlHandles(Arc<RwLock<Vec<ControlHandle>>>); impl ControlHandles { pub fn new() -> Self { Self(Arc::new(RwLock::new(Vec::new()))) } pub fn push(&self, value: ControlHandle) { let mut vec = self.0.write().unwrap(); vec.push(value); } pub fn is_playing(&self) -> bool { let vec = self.0.read().unwrap(); for control in vec.iter() { if let PlayingState::Playing = control.load() { return true; } } false } fn stop(&self) { let vec = self.0.read().unwrap(); for control in vec.iter() { control.store(PlayingState::Stopping); } } fn stopped(&self) -> bool { let control_handles = self.0.read().unwrap(); control_handles .iter() .map(|control| control.load()) .all(|state| state == PlayingState::Stopped) } fn sustain(&self) { let vec = self.0.read().unwrap(); for control in vec.iter() { control.store(PlayingState::Sustaining); } } pub fn new_handle(&self) -> ControlHandle { let handle = Arc::new(AtomicCell::new(PlayingState::Playing)); let mut vec = self.0.write().unwrap(); vec.push(handle.clone()); handle } } #[derive(Debug)] pub struct InstrumentController<T> { pub control_handles: ControlHandles, _tone_generator: std::marker::PhantomData<T>, } impl<T> Default for InstrumentController<T> { fn default() -> Self { Self { control_handles: ControlHandles::new(), _tone_generator: std::marker::PhantomData::default(), } } } impl<T> InstrumentController<T> where T: ToneGenerator, T::CustomNodes: Instantiatable + Clone + 'static, { pub fn instantiate( &mut self, sampler: &LoadedInstrument<T::CustomNodes>, note: Note, ) -> Result<PreparedSampler, serialization::Error> { Ok(sampler.instantiate(&note, &self.control_handles)) } } pub trait ToneGenerator: Sized { type CustomNodes: Instantiatable + Clone + 'static; fn generate_tone( &mut self, note: Note, control: &mut InstrumentController<Self>, ) -> Result<PreparedSampler, anyhow::Error>; } pub struct PlayingNote<T> { note: Note, handle: Option<PlayingHandle>, controller: InstrumentController<T>, } impl<T> PlayingNote<T> { fn is_playing(&self) -> bool { self.controller.control_handles.is_playing() } fn stop(&self) {
self.playing_notes.retain(|pn| pn.note.step() as u8 != step); } } pub fn set_sustain(&mut self, active: bool) { self.sustain = active; if !active { self.playing_notes.retain(|n| n.is_playing()); } } }
self.controller.control_handles.stop() } fn sustain(&self) { self.controller.control_handles.sustain() } } impl<T> Drop for PlayingNote<T> { fn drop(&mut self) { self.stop(); let handle = std::mem::take(&mut self.handle); let control_handles = std::mem::take(&mut self.controller.control_handles); std::thread::spawn(move || loop { { if control_handles.stopped() { println!("Sound stopping"); drop(handle); return; } } std::thread::sleep(Duration::from_millis(10)); }); } } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum Loudness { Fortissimo, MezzoForte, Pianissimo, } pub struct VirtualInstrument<T> { playing_notes: Vec<PlayingNote<T>>, device: Device, sustain: bool, tone_generator: T, } impl<T> VirtualInstrument<T> where T: ToneGenerator, { pub fn new(device: Device, tone_generator: T) -> Self { Self { device, tone_generator, playing_notes: Vec::new(), sustain: false, } } pub fn new_with_default_output(tone_generator: T) -> Result<Self, anyhow::Error> { let device = Device::default_output()?; Ok(Self::new(device, tone_generator)) } pub fn play_note(&mut self, note: Note) -> Result<(), anyhow::Error> { self.playing_notes .retain(|n| n.note.step() as u8 != note.step() as u8); let mut controller = InstrumentController::default(); let source = self.tone_generator.generate_tone(note, &mut controller)?; let handle = Some(self.device.play(source, note)?); self.playing_notes.push(PlayingNote { note, handle, controller, }); Ok(()) } pub fn stop_note(&mut self, step: u8) { if self.sustain { if let Some(existing_note) = self .playing_notes .iter_mut() .find(|pn| pn.note.step() as u8 == step) { existing_note.sustain(); } } else {
random
[ { "content": "/// A mapping from a Rust type to its Muse [`Type`].\n\npub trait CustomType: Send + Sync + Debug + 'static {\n\n /// Returns the Muse type for this Rust type.\n\n fn muse_type(&self) -> &TypeRef;\n\n}\n\n\n", "file_path": "src/runtime/value.rs", "rank": 0, "score": 193705.002593...
Rust
gf256-macros/src/rs.rs
geky/gf256
57675335061b18e3614376981482fd7584454fd5
extern crate proc_macro; use darling; use darling::FromMeta; use syn; use syn::parse_macro_input; use proc_macro2::*; use std::collections::HashMap; use quote::quote; use std::iter::FromIterator; use crate::common::*; const RS_TEMPLATE: &'static str = include_str!("../templates/rs.rs"); #[derive(Debug, FromMeta)] struct RsArgs { block: usize, data: usize, #[darling(default)] gf: Option<syn::Path>, #[darling(default)] u: Option<syn::Path>, } pub fn rs( args: proc_macro::TokenStream, input: proc_macro::TokenStream ) -> proc_macro::TokenStream { let __crate = crate_path(); let raw_args = parse_macro_input!(args as AttributeArgsWrapper).0; let args = match RsArgs::from_list(&raw_args) { Ok(args) => args, Err(err) => { return err.write_errors().into(); } }; assert!(args.block <= 255); assert!(args.data <= args.block); let ty = parse_macro_input!(input as syn::ItemMod); let attrs = ty.attrs; let vis = ty.vis; let rs = ty.ident; let __gf = Ident::new(&format!("__{}_gf", rs.to_string()), Span::call_site()); let __u = Ident::new(&format!("__{}_u", rs.to_string()), Span::call_site()); let mut overrides = vec![]; match args.gf.as_ref() { Some(gf) => { overrides.push(quote! { use #gf as #__gf; }) } None => { overrides.push(quote! { use #__crate::gf::gf256 as #__gf; }) } } match args.u.as_ref() { Some(u) => { overrides.push(quote! { use #u as #__u; }) } None => { overrides.push(quote! { use u8 as #__u; }); } } let replacements = HashMap::from_iter([ ("__rs".to_owned(), TokenTree::Ident(rs.clone())), ("__block_size".to_owned(), TokenTree::Literal( Literal::usize_unsuffixed(args.block) )), ("__data_size".to_owned(), TokenTree::Literal( Literal::usize_unsuffixed(args.data) )), ("__ecc_size".to_owned(), TokenTree::Literal( Literal::usize_unsuffixed(args.block-args.data) )), ("__gf".to_owned(), TokenTree::Group(Group::new(Delimiter::None, { quote! { super::#__gf } }))), ("__u".to_owned(), TokenTree::Group(Group::new(Delimiter::None, { quote! { super::#__u } }))), ("__crate".to_owned(), __crate.clone()), ]); let template = match compile_template(RS_TEMPLATE, &replacements) { Ok(template) => template, Err(err) => { return err.to_compile_error().into(); } }; let output = quote! { #(#attrs)* #vis mod #rs { #template } #(#overrides)* }; output.into() }
extern crate proc_macro; use darling; use darling::FromMeta; use syn; use syn::parse_macro_input; use proc_macro2::*; use std::collections::HashMap; use quote::quote; use std::iter::FromIterator; use crate::common::*; const RS_TEMPLATE: &'static str = include_str!("../templates/rs.rs"); #[derive(Debug, FromMeta)] struct RsArgs { block: usize, data: usize, #[darling(default)] gf: Option<syn::Path>, #[darling(default)] u: Option<syn::Path>, } pub fn rs( args: proc_macro::TokenStream, input: proc_macro::TokenStream ) -> proc_macro::TokenStream { let __crate = crate_path(); let raw_args = parse_macro_input!(args as AttributeArgsWrapper).0; let args = match RsArgs::from_list(&raw_args) { Ok(args) => args, Err(err) => { return err.write_errors().into(); } }; assert!(args.block <= 255); assert!(args.data <= args.block); let ty = parse_macro_input!(input as syn::ItemMod); let attrs = ty.attrs; let vis = ty.vis; let rs = ty.ident; let __gf = Ident::new(&format!("__{}_gf", rs.to_string()), Span::call_site()); let __u = Ident::new(&format!("__{}_u", rs.to_string()), Span::call_site()); let mut overrides = vec![]; match args.gf.as_ref() { Some(gf) => { overrides.push(quote! { use #gf as #__gf; }) } None => { overrides.push(quote! { use #__crate::gf::gf256 as #__gf; }) } } match args.u.as_ref() { Some(u) => { overrides.push(quote! {
r().into(); } }; let output = quote! { #(#attrs)* #vis mod #rs { #template } #(#overrides)* }; output.into() }
use #u as #__u; }) } None => { overrides.push(quote! { use u8 as #__u; }); } } let replacements = HashMap::from_iter([ ("__rs".to_owned(), TokenTree::Ident(rs.clone())), ("__block_size".to_owned(), TokenTree::Literal( Literal::usize_unsuffixed(args.block) )), ("__data_size".to_owned(), TokenTree::Literal( Literal::usize_unsuffixed(args.data) )), ("__ecc_size".to_owned(), TokenTree::Literal( Literal::usize_unsuffixed(args.block-args.data) )), ("__gf".to_owned(), TokenTree::Group(Group::new(Delimiter::None, { quote! { super::#__gf } }))), ("__u".to_owned(), TokenTree::Group(Group::new(Delimiter::None, { quote! { super::#__u } }))), ("__crate".to_owned(), __crate.clone()), ]); let template = match compile_template(RS_TEMPLATE, &replacements) { Ok(template) => template, Err(err) => { return err.to_compile_erro
function_block-random_span
[ { "content": "/// Generate `n` shares requiring `k` shares to reconstruct.\n\n///\n\n/// This scheme is limited to to the number of shares <= the number of\n\n/// non-zero elements in the field.\n\n///\n\npub fn generate(secret: &[__u], n: usize, k: usize) -> Vec<Vec<__u>> {\n\n // we only support up to 255 ...
Rust
src/cli/collections.rs
RekhaDS/couchbase-shell
81bdfd4a8e62bdb477857d31f7704d07d1f35da6
use crate::cli::util::{cluster_identifiers_from, validate_is_not_cloud}; use crate::client::ManagementRequest; use crate::state::State; use async_trait::async_trait; use log::debug; use nu_engine::CommandArgs; use nu_errors::ShellError; use nu_protocol::{Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value}; use nu_source::Tag; use nu_stream::OutputStream; use serde_derive::Deserialize; use std::ops::Add; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::time::Instant; pub struct Collections { state: Arc<Mutex<State>>, } impl Collections { pub fn new(state: Arc<Mutex<State>>) -> Self { Self { state } } } #[async_trait] impl nu_engine::WholeStreamCommand for Collections { fn name(&self) -> &str { "collections" } fn signature(&self) -> Signature { Signature::build("collections") .named( "bucket", SyntaxShape::String, "the name of the bucket", None, ) .named("scope", SyntaxShape::String, "the name of the scope", None) .named( "clusters", SyntaxShape::String, "the clusters to query against", None, ) } fn usage(&self) -> &str { "Fetches collections through the HTTP API" } fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { collections_get(self.state.clone(), args) } } fn collections_get( state: Arc<Mutex<State>>, args: CommandArgs, ) -> Result<OutputStream, ShellError> { let ctrl_c = args.ctrl_c(); let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?; let guard = state.lock().unwrap(); let scope: Option<String> = args.get_flag("scope")?; let mut results: Vec<Value> = vec![]; for identifier in cluster_identifiers { let active_cluster = match guard.clusters().get(&identifier) { Some(c) => c, None => { return Err(ShellError::unexpected("Cluster not found")); } }; validate_is_not_cloud( active_cluster, "collections get cannot be run against cloud clusters", )?; let bucket = match args.get_flag("bucket")? { Some(v) => v, None => match active_cluster.active_bucket() { Some(s) => s, None => { return Err(ShellError::unexpected( "Could not auto-select a bucket - please use --bucket instead".to_string(), )); } }, }; debug!( "Running collections get for bucket {:?}, scope {:?}", &bucket, &scope ); let response = active_cluster.cluster().http_client().management_request( ManagementRequest::GetCollections { bucket }, Instant::now().add(active_cluster.timeouts().management_timeout()), ctrl_c.clone(), )?; let manifest: Manifest = match response.status() { 200 => match serde_json::from_str(response.content()) { Ok(m) => m, Err(e) => { return Err(ShellError::unexpected(format!( "Failed to decode response body {}", e, ))); } }, _ => { return Err(ShellError::unexpected(response.content())); } }; for scope_res in manifest.scopes { if let Some(scope_name) = &scope { if scope_name != &scope_res.name { continue; } } let collections = scope_res.collections; if collections.is_empty() { let mut collected = TaggedDictBuilder::new(Tag::default()); collected.insert_value("scope", scope_res.name.clone()); collected.insert_value("collection", ""); collected.insert_value("max_expiry", UntaggedValue::duration(0)); collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); continue; } for collection in collections { let mut collected = TaggedDictBuilder::new(Tag::default()); collected.insert_value("scope", scope_res.name.clone()); collected.insert_value("collection", collection.name); collected.insert_value( "max_expiry", UntaggedValue::duration(Duration::from_secs(collection.max_expiry).as_nanos()), ); collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); } } } Ok(OutputStream::from(results)) } #[derive(Debug, Deserialize)] pub struct ManifestCollection { pub uid: String, pub name: String, #[serde(rename = "maxTTL")] pub max_expiry: u64, } #[derive(Debug, Deserialize)] pub struct ManifestScope { pub uid: String, pub name: String, pub collections: Vec<ManifestCollection>, } #[derive(Debug, Deserialize)] pub struct Manifest { pub uid: String, pub scopes: Vec<ManifestScope>, }
use crate::cli::util::{cluster_identifiers_from, validate_is_not_cloud}; use crate::client::ManagementRequest; use crate::state::State; use async_trait::async_trait; use log::debug; use nu_engine::CommandArgs; use nu_errors::ShellError; use nu_protocol::{Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value}; use nu_source::Tag; use nu_stream::OutputStream; use serde_derive::Deserialize; use std::ops::Add; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::time::Instant; pub struct Collections { state: Arc<Mutex<State>>, } impl Collections { pub fn new(state: Arc<Mutex<State>>) -> Self { Self { state } } } #[async_trait] impl nu_engine::WholeStreamCommand for Collections { fn name(&self) -> &str { "collections" } fn signature(&self) -> Signature { Signature::build("collections") .named( "bucket", SyntaxShape::String, "the name of the bucket", None, ) .named("scope", Synta
fn usage(&self) -> &str { "Fetches collections through the HTTP API" } fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { collections_get(self.state.clone(), args) } } fn collections_get( state: Arc<Mutex<State>>, args: CommandArgs, ) -> Result<OutputStream, ShellError> { let ctrl_c = args.ctrl_c(); let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?; let guard = state.lock().unwrap(); let scope: Option<String> = args.get_flag("scope")?; let mut results: Vec<Value> = vec![]; for identifier in cluster_identifiers { let active_cluster = match guard.clusters().get(&identifier) { Some(c) => c, None => { return Err(ShellError::unexpected("Cluster not found")); } }; validate_is_not_cloud( active_cluster, "collections get cannot be run against cloud clusters", )?; let bucket = match args.get_flag("bucket")? { Some(v) => v, None => match active_cluster.active_bucket() { Some(s) => s, None => { return Err(ShellError::unexpected( "Could not auto-select a bucket - please use --bucket instead".to_string(), )); } }, }; debug!( "Running collections get for bucket {:?}, scope {:?}", &bucket, &scope ); let response = active_cluster.cluster().http_client().management_request( ManagementRequest::GetCollections { bucket }, Instant::now().add(active_cluster.timeouts().management_timeout()), ctrl_c.clone(), )?; let manifest: Manifest = match response.status() { 200 => match serde_json::from_str(response.content()) { Ok(m) => m, Err(e) => { return Err(ShellError::unexpected(format!( "Failed to decode response body {}", e, ))); } }, _ => { return Err(ShellError::unexpected(response.content())); } }; for scope_res in manifest.scopes { if let Some(scope_name) = &scope { if scope_name != &scope_res.name { continue; } } let collections = scope_res.collections; if collections.is_empty() { let mut collected = TaggedDictBuilder::new(Tag::default()); collected.insert_value("scope", scope_res.name.clone()); collected.insert_value("collection", ""); collected.insert_value("max_expiry", UntaggedValue::duration(0)); collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); continue; } for collection in collections { let mut collected = TaggedDictBuilder::new(Tag::default()); collected.insert_value("scope", scope_res.name.clone()); collected.insert_value("collection", collection.name); collected.insert_value( "max_expiry", UntaggedValue::duration(Duration::from_secs(collection.max_expiry).as_nanos()), ); collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); } } } Ok(OutputStream::from(results)) } #[derive(Debug, Deserialize)] pub struct ManifestCollection { pub uid: String, pub name: String, #[serde(rename = "maxTTL")] pub max_expiry: u64, } #[derive(Debug, Deserialize)] pub struct ManifestScope { pub uid: String, pub name: String, pub collections: Vec<ManifestCollection>, } #[derive(Debug, Deserialize)] pub struct Manifest { pub uid: String, pub scopes: Vec<ManifestScope>, }
xShape::String, "the name of the scope", None) .named( "clusters", SyntaxShape::String, "the clusters to query against", None, ) }
function_block-function_prefixed
[ { "content": "pub fn signature_dict(signature: Signature, tag: impl Into<Tag>) -> Value {\n\n let tag = tag.into();\n\n let mut sig = TaggedListBuilder::new(&tag);\n\n\n\n for arg in signature.positional.iter() {\n\n let is_required = matches!(arg.0, PositionalType::Mandatory(_, _));\n\n\n\n ...
Rust
c-uint256-tests/src/bindings.rs
jjyr/godwoken-scripts
d983fb351410eb6fbe02bb298af909193aeb5f22
/* automatically generated by rust-bindgen 0.59.2 */ pub const true_: u32 = 1; pub const false_: u32 = 0; pub const INT8_MIN: i32 = -128; pub const INT16_MIN: i32 = -32768; pub const INT32_MIN: i32 = -2147483648; pub const INT64_MIN: i64 = -9223372036854775808; pub const INT8_MAX: u32 = 127; pub const INT16_MAX: u32 = 32767; pub const INT32_MAX: u32 = 2147483647; pub const INT64_MAX: u64 = 9223372036854775807; pub const UINT8_MAX: u32 = 255; pub const UINT16_MAX: u32 = 65535; pub const UINT32_MAX: u32 = 4294967295; pub const UINT64_MAX: i32 = -1; pub const SIZE_MAX: i32 = -1; pub type size_t = ::std::os::raw::c_ulong; pub type ssize_t = ::std::os::raw::c_long; extern "C" { pub fn memset( dest: *mut ::std::os::raw::c_void, c: ::std::os::raw::c_int, n: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn memcpy( dest: *mut ::std::os::raw::c_void, src: *const ::std::os::raw::c_void, n: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn memcmp( vl: *const ::std::os::raw::c_void, vr: *const ::std::os::raw::c_void, n: ::std::os::raw::c_ulong, ) -> ::std::os::raw::c_int; } pub type WT = size_t; extern "C" { pub fn memmove( dest: *mut ::std::os::raw::c_void, src: *const ::std::os::raw::c_void, n: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn strcpy( d: *mut ::std::os::raw::c_char, s: *const ::std::os::raw::c_char, ) -> *mut ::std::os::raw::c_char; } extern "C" { pub fn strlen(s: *const ::std::os::raw::c_char) -> ::std::os::raw::c_ulong; } extern "C" { pub fn strcmp( l: *const ::std::os::raw::c_char, r: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int; } extern "C" { pub fn malloc(size: ::std::os::raw::c_ulong) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn free(ptr: *mut ::std::os::raw::c_void); } extern "C" { pub fn calloc( nmemb: ::std::os::raw::c_ulong, size: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn realloc( ptr: *mut ::std::os::raw::c_void, size: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } pub type cmpfun = ::std::option::Option< unsafe extern "C" fn( arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, ) -> ::std::os::raw::c_int, >; extern "C" { pub fn qsort(base: *mut ::std::os::raw::c_void, nel: size_t, width: size_t, cmp: cmpfun); } extern "C" { pub fn bsearch( key: *const ::std::os::raw::c_void, base: *const ::std::os::raw::c_void, nel: size_t, width: size_t, cmp: ::std::option::Option< unsafe extern "C" fn( arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, ) -> ::std::os::raw::c_int, >, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn printf(format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; } extern "C" { pub fn _start(); } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct uint256_t { pub array: [u32; 8usize], } #[test] fn bindgen_test_layout_uint256_t() { assert_eq!( ::std::mem::size_of::<uint256_t>(), 32usize, concat!("Size of: ", stringify!(uint256_t)) ); assert_eq!( ::std::mem::align_of::<uint256_t>(), 4usize, concat!("Alignment of ", stringify!(uint256_t)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<uint256_t>())).array as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(uint256_t), "::", stringify!(array) ) ); } extern "C" { pub fn gw_uint256_zero(num: *mut uint256_t); } extern "C" { pub fn gw_uint256_one(num: *mut uint256_t); } extern "C" { pub fn gw_uint256_max(num: *mut uint256_t); } extern "C" { pub fn gw_uint256_overflow_add( a: uint256_t, b: uint256_t, sum: *mut uint256_t, ) -> ::std::os::raw::c_int; } extern "C" { pub fn gw_uint256_underflow_sub( a: uint256_t, b: uint256_t, rem: *mut uint256_t, ) -> ::std::os::raw::c_int; } pub const GW_UINT256_SMALLER: ::std::os::raw::c_int = -1; pub const GW_UINT256_EQUAL: ::std::os::raw::c_int = 0; pub const GW_UINT256_LARGER: ::std::os::raw::c_int = 1; pub type _bindgen_ty_1 = ::std::os::raw::c_int; extern "C" { pub fn gw_uint256_cmp(a: uint256_t, b: uint256_t) -> ::std::os::raw::c_int; }
/* automatically generated by rust-bindgen 0.59.2 */ pub const true_: u32 = 1; pub const false_: u32 = 0; pub const INT8_MIN: i32 = -128; pub const INT16_MIN: i32 = -32768; pub const INT32_MIN: i32 = -2147483648; pub const INT64_MIN: i64 = -9223372036854775808; pub const INT8_MAX: u32 = 127; pub const INT16_MAX: u32 = 32767; pub const INT32_MAX: u32 = 2147483647; pub const INT64_MAX: u64 = 9223372036854775807; pub const UINT8_MAX: u32 = 255; pub const UINT16_MAX: u32 = 65535; pub const UINT32_MAX: u32 = 4294967295; pub const UINT64_MAX: i32 = -1; pub const SIZE_MAX: i32 = -1; pub type size_t = ::std::os::raw::c_ulong; pub type ssize_t = ::std::os::raw::c_long; extern "C" { pub fn memset( dest: *mut ::std::os::raw::c_void, c: ::std::os::raw::c_int, n: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn memcpy( dest: *mut ::std::os::raw::c_void, src: *const ::std::os::raw::c_void, n: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn memcmp( vl: *const ::std::os::raw::c_void, vr: *const ::std::os::raw::c_void, n: ::std::os::raw::c_ulong, ) -> ::std::os::raw::c_int; } pub type WT = size_t; extern "C" { pub fn memmove( dest: *mut ::std::os::raw::c_void, src: *const ::std::os::raw::c_void, n: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn strcpy( d: *mut ::std::os::raw::c_char, s: *const ::std::os::raw::c_char, ) -> *mut ::std::os::raw::c_char; } extern "C" { pub fn strlen(s: *const ::std::os::raw::
t uint256_t { pub array: [u32; 8usize], } #[test] fn bindgen_test_layout_uint256_t() { assert_eq!( ::std::mem::size_of::<uint256_t>(), 32usize, concat!("Size of: ", stringify!(uint256_t)) ); assert_eq!( ::std::mem::align_of::<uint256_t>(), 4usize, concat!("Alignment of ", stringify!(uint256_t)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<uint256_t>())).array as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(uint256_t), "::", stringify!(array) ) ); } extern "C" { pub fn gw_uint256_zero(num: *mut uint256_t); } extern "C" { pub fn gw_uint256_one(num: *mut uint256_t); } extern "C" { pub fn gw_uint256_max(num: *mut uint256_t); } extern "C" { pub fn gw_uint256_overflow_add( a: uint256_t, b: uint256_t, sum: *mut uint256_t, ) -> ::std::os::raw::c_int; } extern "C" { pub fn gw_uint256_underflow_sub( a: uint256_t, b: uint256_t, rem: *mut uint256_t, ) -> ::std::os::raw::c_int; } pub const GW_UINT256_SMALLER: ::std::os::raw::c_int = -1; pub const GW_UINT256_EQUAL: ::std::os::raw::c_int = 0; pub const GW_UINT256_LARGER: ::std::os::raw::c_int = 1; pub type _bindgen_ty_1 = ::std::os::raw::c_int; extern "C" { pub fn gw_uint256_cmp(a: uint256_t, b: uint256_t) -> ::std::os::raw::c_int; }
c_char) -> ::std::os::raw::c_ulong; } extern "C" { pub fn strcmp( l: *const ::std::os::raw::c_char, r: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int; } extern "C" { pub fn malloc(size: ::std::os::raw::c_ulong) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn free(ptr: *mut ::std::os::raw::c_void); } extern "C" { pub fn calloc( nmemb: ::std::os::raw::c_ulong, size: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn realloc( ptr: *mut ::std::os::raw::c_void, size: ::std::os::raw::c_ulong, ) -> *mut ::std::os::raw::c_void; } pub type cmpfun = ::std::option::Option< unsafe extern "C" fn( arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, ) -> ::std::os::raw::c_int, >; extern "C" { pub fn qsort(base: *mut ::std::os::raw::c_void, nel: size_t, width: size_t, cmp: cmpfun); } extern "C" { pub fn bsearch( key: *const ::std::os::raw::c_void, base: *const ::std::os::raw::c_void, nel: size_t, width: size_t, cmp: ::std::option::Option< unsafe extern "C" fn( arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void, ) -> ::std::os::raw::c_int, >, ) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn printf(format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int; } extern "C" { pub fn _start(); } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struc
random
[ { "content": "pub fn since_timestamp(t: u64) -> Uint64 {\n\n let input_timestamp = Duration::from_millis(t).as_secs() + 1;\n\n (SINCE_BLOCK_TIMESTAMP_FLAG | input_timestamp).pack()\n\n}\n\n\n", "file_path": "tests/src/script_tests/utils/layer1.rs", "rank": 0, "score": 195985.14016819192 }, ...
Rust
src/message_decoder/mod.rs
silathdiir/pg_wire
f106d57abfd501e4f1a1f7f8c20418e2998c2be0
use crate::{ cursor::Cursor, message_decoder::state::{Payload, Tag}, messages::FrontendMessage, Result, }; use state::State; use std::mem::MaybeUninit; mod state; #[derive(Debug, PartialEq)] pub enum Status { Requesting(usize), Decoding, Done(FrontendMessage), } pub struct MessageDecoder { state: State, tag: u8, } impl Default for MessageDecoder { fn default() -> MessageDecoder { MessageDecoder::new() } } impl MessageDecoder { pub fn new() -> MessageDecoder { MessageDecoder { state: State::new(), tag: 0, } } pub fn next_stage(&mut self, payload: Option<&[u8]>) -> Result<Status> { let payload = if let Some(payload) = payload { payload } else { &[] }; let mut state = unsafe { MaybeUninit::zeroed().assume_init() }; std::mem::swap(&mut state, &mut self.state); let (new_state, prev) = state.try_step(payload)?; self.state = new_state; match prev { State::Created(_) => Ok(Status::Requesting(1)), State::RequestingTag(_) => Ok(Status::Requesting(4)), State::Tag(Tag(tag)) => { self.tag = tag; Ok(Status::Requesting((Cursor::from(payload).read_i32()? - 4) as usize)) } State::WaitingForPayload(_) => Ok(Status::Decoding), State::Payload(Payload(data)) => { let message = FrontendMessage::decode(self.tag, &data)?; Ok(Status::Done(message)) } } } } #[cfg(test)] mod tests { use super::*; use crate::messages::QUERY; const QUERY_STRING: &str = "select * from t\0"; const QUERY_BYTES: &[u8] = QUERY_STRING.as_bytes(); const LEN: i32 = QUERY_STRING.len() as i32; #[test] fn request_message_tag() { let mut decoder = MessageDecoder::default(); assert_eq!(decoder.next_stage(None), Ok(Status::Requesting(1))); } #[test] fn request_message_len() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); assert_eq!(decoder.next_stage(Some(&[QUERY])), Ok(Status::Requesting(4))); } #[test] fn request_message_payload() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); assert_eq!( decoder.next_stage(Some(&LEN.to_be_bytes())), Ok(Status::Requesting((LEN - 4) as usize)) ); } #[test] fn decoding_message() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); decoder .next_stage(Some(&LEN.to_be_bytes())) .expect("proceed to the next stage"); assert_eq!(decoder.next_stage(Some(QUERY_BYTES)), Ok(Status::Decoding)); } #[test] fn request_next_message() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); decoder .next_stage(Some(&LEN.to_be_bytes())) .expect("proceed to the next stage"); decoder .next_stage(Some(QUERY_BYTES)) .expect("proceed to the next stage"); assert_eq!( decoder.next_stage(None), Ok(Status::Done(FrontendMessage::Query { sql: "select * from t".to_owned() })) ); } #[test] fn full_cycle() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); decoder .next_stage(Some(&LEN.to_be_bytes())) .expect("proceed to the next stage"); decoder .next_stage(Some(QUERY_BYTES)) .expect("proceed to the next stage"); decoder.next_stage(None).expect("proceed to the next stage"); assert_eq!(decoder.next_stage(None), Ok(Status::Requesting(1))); } }
use crate::{ cursor::Cursor, message_decoder::state::{Payload, Tag}, messages::FrontendMessage, Result, }; use state::State; use std::mem::MaybeUninit; mod state; #[derive(Debug, PartialEq)] pub enum Status { Requesting(usize), Decoding, Done(FrontendMessage), } pub struct MessageDecoder { state: State, tag: u8, } impl Default for MessageDecoder { fn default() -> MessageDecoder { MessageDecoder::new() } } impl MessageDecoder { pub fn new() -> MessageDecoder { MessageDecoder { state: State::new(), tag: 0, } } pub fn next_stage(&mut self, payload: Option<&[u8]>) -> Result<Status> { let payload = if let Some(payload) = payload { payload } else { &[] }; let mut state = unsafe { MaybeUninit::zeroed().assume_init() }; std::mem::swap(&mut state, &mut self.state); let (new_state, prev) = state.try_step(payload)?; self.state = new_state; match prev { State::Created(_) => Ok(Status::Requesting(1)), State::RequestingTag(_) => Ok(Status::Requesting(4)), State::Tag(Tag(tag)) => { self.tag = tag; Ok(Status::Requesting((Cursor::from(payload).read_i32()? - 4) as usize)) } State::WaitingForPayload(_) => Ok(Status::Decoding), State::Payload(Payload(data)) => { let message = FrontendMessage::decode(self.tag, &data)?; Ok(Status::Done(message)) } } } } #[cfg(test)] mod tests { use super::*; use crate::messages::QUERY; const QUERY_STRING: &str = "select * from t\0"; const QUERY_BYTES: &[u8] = QUERY_STRING.as_bytes(); const LEN: i32 = QUERY_STRING.len() as i32; #[test] fn request_message_tag() { let mut decoder = MessageDecoder::default(); assert_eq!(decoder.next_stage(None), Ok(Status::Requesting(1))); } #[test] fn request_message_len() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); assert_eq!(decoder.next_stage(Some(&[QUERY])), Ok(Status::Requesting(4))); } #[test] fn request_message_payload() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); assert_eq!( decoder.next_stage(Some(&LEN.to_be_bytes())), Ok(Status::Requesting((LEN - 4) as usize)) ); } #[test] fn decoding_message() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); decoder .next_stage(Some(&LEN.to_be_bytes())) .expect("proceed to the next stage"); assert_eq!(decoder.next_stage(Some(QUERY_BYTES)), Ok(Status::Decoding)); } #[test] fn request_next_message() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); decoder .next_stage(Some(&LEN.to_be_bytes())) .expect("proceed to the next stage"); decoder .next_stage(Some(QUERY_BYTES)) .expect("proceed to the next stage"); assert_eq!( decoder.next_stage(None), Ok(Status::Done(FrontendMessage::Query { sql: "select * from t".to_owned() })) ); } #[test] fn full_cycle() { let mut decoder = MessageDecoder::default(); decoder.next_stage(None).expect("proceed to the next stage"); decoder.next_stage(Some(&[QUERY])).expect("proceed to the next stage"); decoder .next_stage(Some(&LEN.to_be_bytes())) .expect("proceed to the next stage"); decode
}
r .next_stage(Some(QUERY_BYTES)) .expect("proceed to the next stage"); decoder.next_stage(None).expect("proceed to the next stage"); assert_eq!(decoder.next_stage(None), Ok(Status::Requesting(1))); }
function_block-function_prefixed
[ { "content": "fn decode_execute(mut cursor: Cursor) -> Result<FrontendMessage> {\n\n let portal_name = cursor.read_cstr()?.to_owned();\n\n let max_rows = cursor.read_i32()?;\n\n Ok(FrontendMessage::Execute { portal_name, max_rows })\n\n}\n\n\n", "file_path": "src/messages.rs", "rank": 0, "s...
Rust
migrate/src/lib.rs
alekspickle/migrate
c0a95c0b81315e8588c58688bdb775b7dcf997d9
#![warn(missing_docs, unreachable_pub, rust_2018_idioms)] #![forbid(unsafe_code)] mod cli; mod error; pub use error::*; pub use migrate_core as core; use crate::core::MigrationRunMode; use error::{DynError, Error}; use migrate_core::{MigrationsSelection, PlanBuilder}; use structopt::StructOpt; #[cfg(doctest)] doc_comment::doctest!( concat!(env!("CARGO_MANIFEST_DIR"), "/../README.md"), root_readme ); #[derive(Debug)] pub struct MigrateCli(cli::Args); impl MigrateCli { pub fn from_cli_args() -> Self { Self(StructOpt::from_args()) } pub fn try_from_cli_args() -> Result<Self, DynError> { Ok(Self(StructOpt::from_args_safe()?)) } pub async fn run(self, plan_builder: PlanBuilder) -> Result<(), Error> { let (cli::PlanArgGroup { no_commit, no_run }, plan) = match self.0 { cli::Args::Up(cmd) => { let plan = plan_builder .build(&MigrationsSelection::Up { inclusive_bound: cmd.inclusive_bound.as_deref(), }) .await .map_err(ErrorKind::PlanBuild)?; (cmd.plan, plan) } cli::Args::Down(cmd) => { let plan = plan_builder .build(&MigrationsSelection::Down { inclusive_bound: &cmd.inclusive_bound, }) .await .map_err(ErrorKind::PlanBuild)?; (cmd.plan, plan) } cli::Args::List => { tracing::info!( "Listing registered migrations in order:\n{}", plan_builder.display().build() ); return Ok(()); } }; let run_mode = match (no_commit, no_run) { (false, false) => MigrationRunMode::Commit, (true, false) => MigrationRunMode::NoCommit, (false, true) => { let plan = plan.display(); let plan = plan.build(); tracing::info!("The following migration plan is generated:\n{}", plan); return Ok(()); } (true, true) => unreachable!( "BUG: `structopt` should have `conflicts_with` clause that \ prevents this invalid arguments state" ), }; plan.exec(run_mode).await.map_err(ErrorKind::PlanExec)?; Ok(()) } }
#![warn(missing_docs, unreachable_pub, rust_2018_idioms)] #![forbid(unsafe_code)] mod cli; mod error; pub use error::*; pub use migrate_core as core; use crate::core::MigrationRunMode; use error::{DynError, Error}; use migrate_core::{MigrationsSelection, PlanBuilder}; use structopt::StructOpt; #[cfg(doctest)] doc_comment::doctest!( concat!(env!("CARGO_MANIFEST_DIR"), "/../README.md"), root_readme ); #[derive(Debug)] pub struct MigrateCli(cli::Args); impl MigrateCli { pub fn from_cli_args() -> Self { Self(StructOpt::from_args()) } pub fn try_from_cli_args() -> Result<Self, DynError> { Ok(Self(StructOpt::from_args_safe()?)) }
}
pub async fn run(self, plan_builder: PlanBuilder) -> Result<(), Error> { let (cli::PlanArgGroup { no_commit, no_run }, plan) = match self.0 { cli::Args::Up(cmd) => { let plan = plan_builder .build(&MigrationsSelection::Up { inclusive_bound: cmd.inclusive_bound.as_deref(), }) .await .map_err(ErrorKind::PlanBuild)?; (cmd.plan, plan) } cli::Args::Down(cmd) => { let plan = plan_builder .build(&MigrationsSelection::Down { inclusive_bound: &cmd.inclusive_bound, }) .await .map_err(ErrorKind::PlanBuild)?; (cmd.plan, plan) } cli::Args::List => { tracing::info!( "Listing registered migrations in order:\n{}", plan_builder.display().build() ); return Ok(()); } }; let run_mode = match (no_commit, no_run) { (false, false) => MigrationRunMode::Commit, (true, false) => MigrationRunMode::NoCommit, (false, true) => { let plan = plan.display(); let plan = plan.build(); tracing::info!("The following migration plan is generated:\n{}", plan); return Ok(()); } (true, true) => unreachable!( "BUG: `structopt` should have `conflicts_with` clause that \ prevents this invalid arguments state" ), }; plan.exec(run_mode).await.map_err(ErrorKind::PlanExec)?; Ok(()) }
function_block-full_function
[]
Rust
wasm/lib/src/browser_module.rs
alexpantyukhin/RustPython
b0ee1947c775145db055413dce217dca1613712d
use crate::{convert, vm_class::AccessibleVM, wasm_builtins::window}; use futures::{future, Future}; use js_sys::Promise; use num_traits::cast::ToPrimitive; use rustpython_vm::obj::{objint, objstr}; use rustpython_vm::pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol}; use rustpython_vm::VirtualMachine; use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen_futures::{future_to_promise, JsFuture}; enum FetchResponseFormat { Json, Text, ArrayBuffer, } impl FetchResponseFormat { fn from_str(vm: &mut VirtualMachine, s: &str) -> Result<Self, PyObjectRef> { match s { "json" => Ok(FetchResponseFormat::Json), "text" => Ok(FetchResponseFormat::Text), "array_buffer" => Ok(FetchResponseFormat::ArrayBuffer), _ => Err(vm.new_type_error("Unkown fetch response_format".into())), } } fn get_response(&self, response: &web_sys::Response) -> Result<Promise, JsValue> { match self { FetchResponseFormat::Json => response.json(), FetchResponseFormat::Text => response.text(), FetchResponseFormat::ArrayBuffer => response.array_buffer(), } } } fn browser_fetch(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, required = [ (url, Some(vm.ctx.str_type())), (handler, Some(vm.ctx.function_type())) ], optional = [(reject_handler, Some(vm.ctx.function_type()))] ); let response_format = args.get_optional_kwarg_with_type("response_format", vm.ctx.str_type(), vm)?; let method = args.get_optional_kwarg_with_type("method", vm.ctx.str_type(), vm)?; let headers = args.get_optional_kwarg_with_type("headers", vm.ctx.dict_type(), vm)?; let body = args.get_optional_kwarg("body"); let content_type = args.get_optional_kwarg_with_type("content_type", vm.ctx.str_type(), vm)?; let response_format = match response_format { Some(s) => FetchResponseFormat::from_str(vm, &objstr::get_value(&s))?, None => FetchResponseFormat::Text, }; let mut opts = web_sys::RequestInit::new(); match method { Some(s) => opts.method(&objstr::get_value(&s)), None => opts.method("GET"), }; if let Some(body) = body { opts.body(Some(&convert::py_to_js(vm, body))); } let request = web_sys::Request::new_with_str_and_init(&objstr::get_value(url), &opts) .map_err(|err| convert::js_py_typeerror(vm, err))?; if let Some(headers) = headers { let h = request.headers(); for (key, value) in rustpython_vm::obj::objdict::get_key_value_pairs(&headers) { let key = objstr::get_value(&vm.to_str(&key)?); let value = objstr::get_value(&vm.to_str(&value)?); h.set(&key, &value) .map_err(|err| convert::js_py_typeerror(vm, err))?; } } if let Some(content_type) = content_type { request .headers() .set("Content-Type", &objstr::get_value(&content_type)) .map_err(|err| convert::js_py_typeerror(vm, err))?; } let window = window(); let request_prom = window.fetch_with_request(&request); let handler = handler.clone(); let reject_handler = reject_handler.cloned(); let acc_vm = AccessibleVM::from_vm(vm); let future = JsFuture::from(request_prom) .and_then(move |val| { let response = val .dyn_into::<web_sys::Response>() .expect("val to be of type Response"); response_format.get_response(&response) }) .and_then(JsFuture::from) .then(move |val| { let vm = &mut acc_vm .upgrade() .expect("that the VM *not* be destroyed while promise is being resolved"); match val { Ok(val) => { let val = convert::js_to_py(vm, val); let args = PyFuncArgs::new(vec![val], vec![]); let _ = vm.invoke(handler, args); } Err(val) => { if let Some(reject_handler) = reject_handler { let val = convert::js_to_py(vm, val); let args = PyFuncArgs::new(vec![val], vec![]); let _ = vm.invoke(reject_handler, args); } } } future::ok(JsValue::UNDEFINED) }); future_to_promise(future); Ok(vm.get_none()) } fn browser_request_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(func, Some(vm.ctx.function_type()))]); use std::{cell::RefCell, rc::Rc}; let f = Rc::new(RefCell::new(None)); let g = f.clone(); let func = func.clone(); let acc_vm = AccessibleVM::from_vm(vm); *g.borrow_mut() = Some(Closure::wrap(Box::new(move |time: f64| { let vm = &mut acc_vm .upgrade() .expect("that the vm is valid from inside of request_animation_frame"); let func = func.clone(); let args = PyFuncArgs { args: vec![vm.ctx.new_float(time)], kwargs: vec![], }; let _ = vm.invoke(func, args); let closure = f.borrow_mut().take(); drop(closure); }) as Box<Fn(f64)>)); let id = window() .request_animation_frame(&js_sys::Function::from( g.borrow().as_ref().unwrap().as_ref().clone(), )) .map_err(|err| convert::js_py_typeerror(vm, err))?; Ok(vm.ctx.new_int(id)) } fn browser_cancel_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(id, Some(vm.ctx.int_type()))]); let id = objint::get_value(id).to_i32().ok_or_else(|| { vm.new_exception( vm.ctx.exceptions.value_error.clone(), "Integer too large to convert to i32 for animationFrame id".into(), ) })?; window() .cancel_animation_frame(id) .map_err(|err| convert::js_py_typeerror(vm, err))?; Ok(vm.get_none()) } fn browser_alert(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(message, Some(vm.ctx.str_type()))]); window() .alert_with_message(&objstr::get_value(message)) .expect("alert() not to fail"); Ok(vm.get_none()) } fn browser_confirm(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(message, Some(vm.ctx.str_type()))]); let result = window() .confirm_with_message(&objstr::get_value(message)) .expect("confirm() not to fail"); Ok(vm.new_bool(result)) } fn browser_prompt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, required = [(message, Some(vm.ctx.str_type()))], optional = [(default, Some(vm.ctx.str_type()))] ); let result = if let Some(default) = default { window().prompt_with_message_and_default( &objstr::get_value(message), &objstr::get_value(default), ) } else { window().prompt_with_message(&objstr::get_value(message)) }; let result = match result.expect("prompt() not to fail") { Some(result) => vm.new_str(result), None => vm.get_none(), }; Ok(result) } const BROWSER_NAME: &str = "browser"; pub fn mk_module(ctx: &PyContext) -> PyObjectRef { py_module!(ctx, BROWSER_NAME, { "fetch" => ctx.new_rustfunc(browser_fetch), "request_animation_frame" => ctx.new_rustfunc(browser_request_animation_frame), "cancel_animation_frame" => ctx.new_rustfunc(browser_cancel_animation_frame), "alert" => ctx.new_rustfunc(browser_alert), "confirm" => ctx.new_rustfunc(browser_confirm), "prompt" => ctx.new_rustfunc(browser_prompt), }) } pub fn setup_browser_module(vm: &mut VirtualMachine) { vm.stdlib_inits .insert(BROWSER_NAME.to_string(), Box::new(mk_module)); }
use crate::{convert, vm_class::AccessibleVM, wasm_builtins::window}; use futures::{future, Future}; use js_sys::Promise; use num_traits::cast::ToPrimitive; use rustpython_vm::obj::{objint, objstr}; use rustpython_vm::pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol}; use rustpython_vm::VirtualMachine; use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen_futures::{future_to_promise, JsFuture}; enum FetchResponseFormat { Json, Text, ArrayBuffer, } impl FetchResponseFormat { fn from_str(vm: &mut VirtualMachine, s: &str) -> Result<Self, PyObjectRef> { match s { "json" => Ok(FetchResponseFormat::Json), "text" => Ok(FetchResponseFormat::Text), "array_buffer" => Ok(FetchResponseFormat::ArrayBuffer), _ => Err(vm.new_type_error("Unkown fetch response_format".into())), } } fn get_response(&self, response: &web_sys::Response) -> Result<Promise, JsValue> { match self { FetchResponseFormat::Json => response.json(), FetchResponseFormat::Text => response.text(), FetchResponseFormat::ArrayBuffer => response.array_buffer(), } } } fn browser_fetch(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, required = [ (url, Some(vm.ctx.str_type())), (handler, Some(vm.ctx.function_type())) ], optional = [(reject_handler, Some(vm.ctx.function_type()))] ); let response_format = args.get_optional_kwarg_with_type("response_format", vm.ctx.str_type(), vm)?; let method = args.get_optional_kwarg_with_type("method", vm.ctx.str_type(), vm)?; let headers = args.get_optional_kwarg_with_type("headers", vm.ctx.dict_type(), vm)?; let body = args.get_optional_kwarg("body"); let content_type = args.get_optional_kwarg_with_type("content_type", vm.ctx.str_type(), vm)?; let response_format = match response_format { Some(s) => FetchResponseFormat::from_str(vm, &objstr::get_value(&s))?, None => FetchResponseFormat::Text, }; let mut opts = web_sys::RequestInit::new(); match method { Some(s) => opts.method(&objstr::get_value(&s)), None => opts.method("GET"), }; if let Some(body) = body { opts.body(Some(&convert::py_to_js(vm, body))); } let request = web_sys::Request::new_with_str_and_init(&objstr::get_value(url), &opts) .map_err(|err| convert::js_py_typeerror(vm, err))?; if let Some(headers) = headers { let h = request.headers(); for (key, value) in rustpython_vm::obj::objdict::get_key_value_pairs(&headers) { let key = objstr::get_value(&vm.to_str(&key)?); let value = objstr::get_value(&vm.to_str(&value)?); h.set(&key, &value) .map_err(|err| convert::js_py_typeerror(vm, err))?; } } if let Some(content_type) = content_type { request .headers() .set("Content-Type", &objstr::get_value(&content_type)) .map_err(|err| convert::js_py_typeerror(vm, err))?; } let window = window(); let request_prom = window.fetch_with_request(&request); let handler = handler.clone(); let reject_handler = reject_handler.cloned(); let acc_vm = AccessibleVM::from_vm(vm); let future = JsFuture::from(request_prom) .and_then(move |val| { let response = val .dyn_into::<web_sys::Response>() .expect("val to be of type Response"); response_format.get_response(&response) }) .and_then(JsFuture::from) .then(move |val| { let vm = &mut acc_vm .upgrade() .expect("that the VM *not* be destroyed while promise is being resolved"); match val { Ok(val) => { let val = convert::js_to_py(vm, val); let args = PyFuncArgs::new(vec![val], vec![]); let _ = vm.invoke(handler, args); } Err(val) => { if let Some(reject_handler) = reject_handler { let val = convert::js_to_py(vm, val); let args = PyFuncArgs::new(vec![val], vec![]); let _ = vm.invoke(reject_handler, args); } } } future::ok(JsValue::UNDEFINED) }); future_to_promise(future); Ok(vm.get_none()) } fn browser_request_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(func, Some(vm.ctx.function_type()))]); use std::{cell::RefCell, rc::Rc}; let f = Rc::new(RefCell::new(None)); let g = f.clone(); let func = func.clone(); let acc_vm = AccessibleVM::from_vm(vm); *g.borrow_mut() = Some(Closure::wrap(Box::new(move |time: f64| { let vm = &mut acc_vm .upgrade() .expect("that the vm is valid from inside of request_animation_frame"); let func = func.clone(); let args = PyFuncArgs { args: vec![vm.ctx.new_float(time)], kwargs: vec![], }; let _ = vm.invoke(func, args); let closure = f.borrow_mut().take(); drop(closure); }) as Box<Fn(f64)>)); let id = window() .request_animation_frame(&js_sys::Function::from( g.borrow().as_ref().unwrap().as_ref().clone(), )) .map_err(|err| convert::js_py_typeerror(vm, err))?; Ok(vm.ctx.new_int(id)) } fn browser_cancel_animation_frame(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(id, Some(vm.ctx.int_type()))]); let id = objint::get_value(id).to_i32().ok_or_else(|| { vm.new_exception( vm.ctx.exceptions.value_error.clone(), "Integer too large to convert to i32 for animationFrame id".into(), ) })?; window() .cancel_animation_frame(id) .map_err(|err| convert::js_py_typeerror(vm, err))?; Ok(vm.get_none()) } fn browser_alert(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(message, Some(vm.ctx.str_type()))]); window() .alert_with_message(&objstr::get_value(message)) .expect("alert() not to fail"); Ok(vm.get_none()) } fn browser_confirm(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(message, Some(vm.ctx.str_type()))]); let result = window() .confirm_with_message(&objstr::get_value(message)) .expect("confirm() not to fail"); Ok(vm.new_bool(result)) } fn browser_prompt(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!( vm, args, required = [(message, Some(vm.ctx.str_type()))], optional = [(default, Some(vm.ctx.str_type()))] ); let result =
; let result = match result.expect("prompt() not to fail") { Some(result) => vm.new_str(result), None => vm.get_none(), }; Ok(result) } const BROWSER_NAME: &str = "browser"; pub fn mk_module(ctx: &PyContext) -> PyObjectRef { py_module!(ctx, BROWSER_NAME, { "fetch" => ctx.new_rustfunc(browser_fetch), "request_animation_frame" => ctx.new_rustfunc(browser_request_animation_frame), "cancel_animation_frame" => ctx.new_rustfunc(browser_cancel_animation_frame), "alert" => ctx.new_rustfunc(browser_alert), "confirm" => ctx.new_rustfunc(browser_confirm), "prompt" => ctx.new_rustfunc(browser_prompt), }) } pub fn setup_browser_module(vm: &mut VirtualMachine) { vm.stdlib_inits .insert(BROWSER_NAME.to_string(), Box::new(mk_module)); }
if let Some(default) = default { window().prompt_with_message_and_default( &objstr::get_value(message), &objstr::get_value(default), ) } else { window().prompt_with_message(&objstr::get_value(message)) }
if_condition
[ { "content": "fn str_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {\n\n arg_check!(vm, args, required = [(s, Some(vm.ctx.str_type()))]);\n\n Ok(s.clone())\n\n}\n\n\n", "file_path": "vm/src/obj/objstr.rs", "rank": 0, "score": 466286.87047549686 }, { "content": "pub fn subs...
Rust
src/serializer.rs
aep/korhal-image
6aa0cce631efe530d5f94a1b893c0efdc7712fec
use blockstore::{Block, BlockStore, BlockShard}; use chunker::*; use index::*; use pbr::ProgressBar; use readchain::{Take,Chain}; use serde::{Serialize, Deserialize}; use std::ffi::OsString; use std::io::{Stdout, Seek, SeekFrom, BufReader}; use std::path::Path; use std::fs::File; use elfkit; use sha2::{Sha256, Digest}; use std::io::Read; macro_rules! kb_fmt { ($n: ident) => {{ let kb = 1024f64; match $n as f64{ $n if $n >= kb.powf(4_f64) => format!("{:.*} TB", 2, $n / kb.powf(4_f64)), $n if $n >= kb.powf(3_f64) => format!("{:.*} GB", 2, $n / kb.powf(3_f64)), $n if $n >= kb.powf(2_f64) => format!("{:.*} MB", 2, $n / kb.powf(2_f64)), $n if $n >= kb => format!("{:.*} KB", 2, $n / kb), _ => format!("{:.*} B", 0, $n) } }} } impl Index { pub fn store_inodes(&mut self, blockstore: &mut BlockStore) { let total_bytes = self.i.iter().fold(0, |acc, ref x| acc + x.size); let mut bar = ProgressBar::new(total_bytes); bar.set_units(::pbr::Units::Bytes); let mut new_bytes = 0; let mut new_blocks = 0; let mut total_blocks = 0; let mut inodes = self.i.to_vec(); for i in &mut inodes { if i.kind != 2 { continue; } let mut host_file = File::open(&i.host_path).unwrap(); let cuts = match elfkit::Elf::from_reader(&mut host_file) { Err(_) => None, Ok(mut elf) => { let mut r = None; for sec in elf.sections.drain(..) { if sec.header.shtype == elfkit::types::SectionType(0x6fffff01) { let mut rr = Vec::new(); let mut io = &sec.content.into_raw().unwrap()[..]; while let Ok(o) = elf_read_u32!(&elf.header, io) { rr.push(o as usize); } r = Some(rr); } } r } }; match cuts { None => {}, Some(mut cuts) => { i.kind = 3; let mut at = 0; cuts.push(host_file.metadata().unwrap().len() as usize); cuts.sort_unstable(); host_file.seek(SeekFrom::Start(0)); for cut in cuts { let mut buf = vec![0;cut - at]; host_file.read_exact(&mut buf).unwrap(); let hash = Sha256::digest(&buf).as_slice().to_vec(); if blockstore.insert(hash.clone(), Block { shards: vec![BlockShard{ file: i.host_path.clone(), offset: at, size: buf.len(), }], size: buf.len(), }) { new_blocks +=1; new_bytes += buf.len(); } total_blocks += 1; bar.add(buf.len() as u64); if let None = self.i[i.inode as usize].content { self.i[i.inode as usize].content = Some(Vec::new()); } self.i[i.inode as usize].content.as_mut().unwrap().push(ContentBlockEntry{ h: hash, o: 0, l: buf.len() as u64, }); at = cut; } let mut buf = Vec::new(); assert!(host_file.read_to_end(&mut buf).unwrap() == 0); } } } let it = inodes.iter().filter(|i|i.kind == 2).map(|i| { (BufReader::new(File::open(&i.host_path).unwrap()), i.inode) }); let mut ci = Chunker::new(Box::new(it), ::rollsum::Bup::new(), 9); while let Some(c) = ci.next() { bar.add((c.len) as u64); let mut block_shards = Vec::new(); for ibr in c.parts { block_shards.push(BlockShard{ file: self.i[ibr.i as usize].host_path.clone(), offset: ibr.file_start, size: ibr.file_end - ibr.file_start, }); if let None = self.i[ibr.i as usize].content { self.i[ibr.i as usize].content = Some(Vec::new()); } self.i[ibr.i as usize].content.as_mut().unwrap().push(ContentBlockEntry{ h: c.hash.clone(), o: ibr.block_start as u64, l: (ibr.file_end - ibr.file_start) as u64, }); print_progress_bar(&mut bar, &self.i[ibr.i as usize].host_path); } if blockstore.insert(c.hash, Block{ shards: block_shards, size: c.len, }) { new_blocks +=1; new_bytes += c.len; } total_blocks += 1; } bar.finish(); println!("done indexing {} inodes to {} blocks", self.i.len(), total_blocks); println!(" + {} blocks {}", new_blocks, kb_fmt!(new_bytes)); } pub fn store_index(&mut self, blockstore: &mut BlockStore) -> Index { let mut tmpindex = ::tempfile::NamedTempFile::new_in(".").unwrap(); self.serialize(&mut ::rmps::Serializer::new(&mut tmpindex)).unwrap(); tmpindex.seek(SeekFrom::Start(0)).unwrap(); let path = OsString::from(tmpindex.path().to_str().unwrap()); let tv= vec![tmpindex]; let it = tv.iter().map(|i|(i,0)); let mut ci = Chunker::new(Box::new(it), ::rollsum::Bup::new(), 12); let mut total_blocks = 0; let mut new_blocks = 0; let mut cbrs = Vec::new(); while let Some(c) = ci.next() { let mut block_shards = Vec::new(); for ibr in c.parts { block_shards.push(BlockShard{ file: path.clone(), offset: ibr.file_start, size: ibr.file_end - ibr.file_start, }); cbrs.push(ContentBlockEntry{ h: c.hash.clone(), o: ibr.block_start as u64, l: (ibr.file_end - ibr.file_start) as u64, }); } if blockstore.insert(c.hash, Block{ shards: block_shards, size: c.len, }) { new_blocks += 1; } total_blocks += 1; } println!("done serializing index to {} blocks ({} new)", total_blocks, new_blocks); Index{ v: 1, i: Vec::new(), c: Some(cbrs), } } pub fn load_index(&self, blockstore: &BlockStore) -> Index { let it = self.c.as_ref().unwrap().iter().map(|c| { let block = blockstore.get(&c.h).expect("block not found"); let mut re = block.chain(); re.seek(SeekFrom::Current(c.o as i64)).unwrap(); Take::limit(re, c.l as usize) }); let mut f = Chain::new(Box::new(it)); Index::deserialize(&mut ::rmps::Deserializer::new(&mut f)).unwrap() } pub fn save_to_file(&mut self, path: &Path) { let mut f = File::create(path).unwrap(); self.serialize(&mut ::rmps::Serializer::new(&mut f)).unwrap(); } pub fn load_from_file(path: &Path) -> Index { let mut f = File::open(path).unwrap(); Index::deserialize(&mut ::rmps::Deserializer::new(&mut f)).unwrap() } } fn print_progress_bar(bar: &mut ProgressBar<Stdout>, path: &OsString){ let s = path.to_str().unwrap(); if s.len() > 50 { bar.message(&format!("indexing ..{:48} ", &s[s.len()-48..])); } else { bar.message(&format!("indexing {:50} ", &s)); } }
use blockstore::{Block, BlockStore, BlockShard}; use chunker::*; use index::*; use pbr::ProgressBar; use readchain::{Take,Chain}; use serde::{Serialize, Deserialize}; use std::ffi::OsString; use std::io::{Stdout, Seek, SeekFrom, BufReader}; use std::path::Path; use std::fs::File; use elfkit; use sha2::{Sha256, Digest}; use std::io::Read; macro_rules! kb_fmt { ($n: ident) => {{ let kb = 1024f64; match $n as f64{ $n if $n >= kb.powf(4_f64) => format!("{:.*} TB", 2, $n / kb.powf(4_f64)), $n if $n >= kb.powf(3_f64) => format!("{:.*} GB", 2, $n / kb.powf(3_f64)), $n if $n >= kb.powf(2_f64) => format!("{:.*} MB", 2, $n / kb.powf(2_f64)), $n if $n >= kb => format!("{:.*} KB", 2, $n / kb), _ => format!("{:.*} B", 0, $n) } }} } impl Index { pub fn store_inodes(&mut self, blockstore: &mut BlockStore) { let total_bytes = self.i.iter().fold(0, |acc, ref x| acc + x.size); let mut bar = ProgressBar::new(total_bytes); bar.set_units(::pbr::Units::Bytes); let mut new_bytes = 0; let mut new_blocks = 0; let mut total_blocks = 0; let mut inodes = self.i.to_vec(); for i in &mut inodes { if i.kind != 2 { continue; } let mut host_file = File::open(&i.host_path).unwrap(); let cuts = match elfkit::Elf::from_reader(&mut host_file) { Err(_) => None, Ok(mut elf) => { let mut r = None; for sec in elf.sections.drain(..) { if sec.header.shtype == elfkit::types::SectionType(0x6fffff01) { let mut rr = Vec::new(); let mut io = &sec.content.into_raw().unwrap()[..]; while let Ok(o) = elf_read_u32!(&elf.header, io) { rr.push(o as usize); } r = Some(rr); } } r } }; match cuts { None => {}, Some(mut cuts) => { i.kind = 3; let mut at = 0; cuts.push(host_file.metadata().unwrap().len() as usize); cuts.sort_unstable(); host_file.seek(SeekFrom::Start(0)); for cut in cuts { let mut buf = vec![0;cut - at]; host_file.read_exact(&mut buf).unwrap(); let hash = Sha256::digest(&buf).as_slice().to_vec(); if blockstore.insert(hash.clone(), Block { shards: vec![BlockShard{ file: i.host_path.clone(), offset: at, size: buf.len(), }], size: buf.len(), }) { new_blocks +=1; new_bytes += buf.len(); } total_blocks += 1; bar.add(buf.len() as u64); if let None = self.i[i.inode as usize].content { self.i[i.inode as usize].content = Some(Vec::new()); } self.i[i.inode as usize].content.as_mut().unwrap().push(ContentBlockEntry{ h: hash, o: 0, l: buf.len() as u64, }); at = cut; } let mut buf = Vec::new(); assert!(host_file.read_to_end(&mut buf).unwrap() == 0); } } } let it = inodes.iter().filter(|i|i.kind == 2).map(|i| { (BufReader::new(File::open(&i.host_path).unwrap()), i.inode) }); let mut ci = Chunker::new(Box::new(it), ::rollsum::Bup::new(), 9); while let Some(c) = ci.next() { bar.add((c.len) as u64); let mut block_shards = Vec::new(); for ibr in c.parts { block_shards.push(BlockShard{ file: self.i[ibr.i as usize].host_path.clone(), offset: ibr.file_start, size: ibr.file_end - ibr.file_start, }); if let None = self.i[ibr.i as usize].content { self.i[ibr.i as usize].content = Some(Vec::new()); } self.i[ibr.i as usize].content.as_mut().unwrap().push(ContentBlockEntry{ h: c.hash.clone(), o: ibr.block_start as u64, l: (ibr.file_end - ibr.file_start) as u64, }); print_progress_bar(&mut bar, &self.i[ibr.i as usize].host_path); } if blockstore.insert(c.hash, Block{ shards: block_shards, size: c.len, }) { new_blocks +=1; new_bytes += c.len; } total_blocks += 1; } bar.finish(); println!("done indexing {} inodes to {} blocks", self.i.len(), total_blocks); println!(" + {} blocks {}", new_blocks, kb_fmt!(new_bytes)); } pub fn store_index(&mut self, blockstore: &mut BlockStore) -> Index { let mut tmpindex = ::tempfile::NamedTempFile::new_in(".").unwrap(); self.serialize(&mut ::rmps::Serializer::new(&mut tmpindex)).unwrap(); tmpindex.seek(SeekFrom::Start(0)).unwrap(); let path = OsString::from(tmpindex.path().to_str().unwrap()); let tv= vec![tmpindex]; let it = tv.iter().map(|i|(i,0)); let mut ci = Chunker::new(Box::new(it), ::rollsum::Bup::new(), 12); let mut total_blocks = 0; let mut new_blocks = 0; let mut cbrs = Vec::new(); while let Some(c) = ci.next() { let mut block_shards = Vec::new(); for ibr in c.parts { block_shards.push(BlockShard{ file: path.clone(), offset: ibr.file_start, size: ibr.file_end - ibr.file_start, }); cbrs.push(ContentBlockEntry{ h: c.hash.clone(), o: ibr.block_start as u64, l: (ibr.file_end - ibr.file_start) as u64, }); } if blockstore.insert(c.hash, Block{ shards: block_shards, size: c.len, }) { new_blocks += 1; } total_blocks += 1; } println!("done serializing index to {} blocks ({} new)", total_blocks, new_blocks); Index{ v: 1, i: Vec::new(), c: Some(cbrs), } } pub fn load_index(&self, blockstore: &BlockStore) -> Index { let it = self.c.as_ref().unwrap().iter().map(|c| { let block = blockstore.get(&c.h).expect("block not found"); let mut re = block.chain(); re.seek(SeekFrom::Current(c.o as i64)).unwrap(); Take::limit(re, c.l as usize) }); let mut f = Chain::new(Box::new(it)); Index::deserialize(&mut ::rmps::Deserializer::new(&mut f)).unwrap() } pub fn save_to_file(&mut self, path: &Path) { let mut f = File::create(path).unwrap(); self.serialize(&mut ::rmps::Serializer::new(&mut f)).unwrap(); } pub fn load_from_file(path: &Path) -> Index { let mut f = File::open(path).unwrap(); Index::deserialize(&mut ::rmps::Deserializer::new(&mut f)).unwrap() } }
fn print_progress_bar(bar: &mut ProgressBar<Stdout>, path: &OsString){ let s = path.to_str().unwrap(); if s.len() > 50 { bar.message(&format!("indexing ..{:48} ", &s[s.len()-48..])); } else { bar.message(&format!("indexing {:50} ", &s)); } }
function_block-full_function
[ { "content": "pub fn new(path: String) -> BlockStore {\n\n let mut bs = BlockStore{\n\n path: path,\n\n blocks: HashMap::new(),\n\n };\n\n bs.load();\n\n bs\n\n}\n\n\n\n\n\nimpl BlockStore {\n\n pub fn get<'a>(&'a self, hash: &Vec<u8>) -> Option<&'a Block> {\n\n self.blocks.g...
Rust
crates/category/tests/product_bug.rs
Nertsal/categories
3fd0a8b4f5c9a3df78c35126bb4af3a9ed10bae3
use category::{axioms, Bindings}; use category::{prelude::*, Equality}; use std::fmt::Debug; #[test] fn test_bug() { let rule_product = axioms::rule_product::<&str>().unwrap(); let mut category = Category::new(); let object_a = category.new_object(Object { tags: vec![], inner: (), }); let result = category.apply_rule(&rule_product, Bindings::new(), |_| (), |_, _| (), |_| ()); assert!(result.1); print_category(&category); assert_eq!(2, category.objects.len()); assert_eq!(6, category.morphisms.len()); assert_eq!(6, category.equalities.len()); for action in result.0 { category.action_do(action); } assert_eq!(1, category.objects.len()); assert_eq!(0, category.morphisms.len()); assert_eq!(0, category.equalities.len()); let object_1 = category.new_object(Object { tags: vec![ObjectTag::Terminal], inner: (), }); let object_ax1 = category.new_object(Object { tags: vec![ObjectTag::Product(object_a, object_1)], inner: (), }); let morphism_id_a = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_a, to: object_a, }, tags: vec![MorphismTag::Identity(object_a)], inner: (), }) .unwrap(); let _morphism_id_ax1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_ax1, }, tags: vec![MorphismTag::Identity(object_ax1)], inner: (), }) .unwrap(); let morphism_a_1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_a, to: object_1, }, tags: vec![MorphismTag::Unique], inner: (), }) .unwrap(); let morphism_ax1_1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_1, }, tags: vec![MorphismTag::Unique, MorphismTag::ProductP2], inner: (), }) .unwrap(); let morphism_a_ax1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_a, to: object_ax1, }, tags: vec![], inner: (), }) .unwrap(); let morphism_ax1_a = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_a, }, tags: vec![MorphismTag::ProductP1], inner: (), }) .unwrap(); let morphism_ax1_ax1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_ax1, }, tags: vec![MorphismTag::Composition { first: morphism_ax1_a, second: morphism_a_ax1, }], inner: (), }) .unwrap(); let _morphism_ax1_ax1_1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_1, }, tags: vec![MorphismTag::Composition { first: morphism_ax1_ax1, second: morphism_ax1_1, }], inner: (), }) .unwrap(); category.equalities.new_equality( Equality::new( vec![morphism_ax1_a, morphism_a_ax1, morphism_ax1_1], vec![morphism_ax1_1], ) .unwrap(), (), ); category.equalities.new_equality( Equality::new( vec![morphism_ax1_a], vec![morphism_ax1_a, morphism_a_ax1, morphism_ax1_a], ) .unwrap(), (), ); category.equalities.new_equality( Equality::new(vec![morphism_id_a], vec![morphism_a_ax1, morphism_ax1_a]).unwrap(), (), ); category.equalities.new_equality( Equality::new(vec![morphism_a_1], vec![morphism_a_ax1, morphism_ax1_1]).unwrap(), (), ); print_category(&category); assert_eq!(3, category.objects.len()); assert_eq!(8, category.morphisms.len()); assert_eq!(4, category.equalities.len()); let bindings = Bindings::from_objects([("A", object_a), ("B", object_1)]); let result = category.apply_rule(&rule_product, bindings, |_| (), |_, _| (), |_| ()); assert!(result.1); print_category(&category); assert_eq!(3, category.objects.len()); assert_eq!(8, category.morphisms.len()); assert_eq!(5, category.equalities.len()); } fn print_category<O: Debug, M: Debug, E: Debug>(category: &Category<O, M, E>) { println!("\n----- Category -----"); println!("Objects:"); for (id, object) in category.objects.iter() { println!("{:4} - {:?}", id.raw(), object) } println!("Morphisms:"); for (id, morphism) in category.morphisms.iter() { println!("{:4} - {:?}", id.raw(), morphism) } println!("Equalities:"); for (equality, inner) in category.equalities.iter() { println!( " {:?} = {:?}: {inner:?}", equality.left(), equality.right() ); } println!(""); }
use category::{axioms, Bindings}; use category::{prelude::*, Equality}; use std::fmt::Debug; #[test] fn test_bug() { let rule_product = axioms::rule_product::<&str>().unwrap(); let mut category = Category::new(); let object_a = category.new_object(Object { tags: vec![], inner: (), }); let result = category.apply_rule(&rule_product, Bindings::new(), |_| (), |_, _| (), |_| ()); assert!(result.1); print_category(&category); assert_eq!(2, category.objects.len()); assert_eq!(6, category.morphisms.len()); assert_eq!(6, category.equalities.len()); for action in result.0 { category.action_do(action); } assert_eq!(1, category.objects.len()); assert_eq!(0, category.morphisms.len()); assert_eq!(0, category.equalities.len()); let object_1 = category.new_object(Object { tags: vec![ObjectTag::Terminal], inner: (), }); let object_ax1 = category.new_object(Object { tags: vec![ObjectTag::Product(object_a, object_1)], inner: (), }); let morphism_id_a = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_a, to: object_a, }, tags: vec![MorphismTag::Identity(object_a)], inner: (), }) .unwrap(); let _morphism_id_ax1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_ax1, }, tags: vec![MorphismTag::Identity(object_ax1)], inner: (), }) .unwrap(); let morphism_a_1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_a, to: object_1, }, tags: vec![MorphismTag::Unique], inner: (), }) .unwrap(); let morphism_ax1_1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_1, }, tags: vec![MorphismTag::Unique, MorphismTag::ProductP2], inner: (), }) .unwrap(); let morphism_a_ax1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_a, to: object_ax1, }, tags: vec![], inner: (), }) .unwrap(); let morphism_ax1_a = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_a, }, tags: vec![MorphismTag::ProductP1], inner: (), }) .unwrap(); let morphism_ax1_ax1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_ax1, }, tags: vec![MorphismTag::Composition { first: morphism_ax1_a, second: morphism_a_ax1, }], inner: (), }) .unwrap(); let _morphism_ax1_ax1_1 = category .new_morphism(Morphism { connection: MorphismConnection::Regular { from: object_ax1, to: object_1, }, tags: vec![MorphismTag::Composition { first: morphism_ax1_ax1, second: morphism_ax1_1, }], inner: (), }) .unwrap(); category.equalities.new_equality( Equality::new( vec![morphism_ax1_a, morphism_a_ax1, morphism_ax1_1], vec![morphism_ax1_1], ) .unwrap(), (), ); category.equalities.new_equality( Equality::new( vec![morphism_ax1_a], vec![morphism_ax1_a, morphism_a_ax1, morphism_ax1_a], ) .unwrap(), (), ); category.equalities.new_equality( Equality::new(vec![morphism_id_a], vec![morphism_a_ax1, morphism_ax1_a]).unwrap(), (), ); category.equalities.new_equality( Equality::new(vec![morphism_a_1], vec![morphism_a_ax1, morphism_ax1_1]).unwrap(), (), ); print_category(&category); assert_eq!(3, category.objects.len()); assert_eq!(8, category.morphisms.len()); assert_eq!(4, category.equalities.len()); let bindings = Bindings::from_objects([("A", object_a), ("B", object_1)]); let result = category.apply_rule(&rule_product, bindings, |_| (), |_, _| (), |_| ()); assert!(result.1); print_category(&category); assert_eq!(3, category.objects.len()); assert_eq!(8, category.morphisms.len()); assert_eq!(5, category.equalities.len()); } fn print_category<O: Debug, M: Debug, E: Debug>(category: &Category<O, M, E>) { println!("\n----- Category -----"); println!("Objects:"); for (id, object) in category.objects.iter() { println!("{:4} - {:?}", id.raw(), object) } println!("Morphisms:");
for (id, morphism) in category.morphisms.iter() { println!("{:4} - {:?}", id.raw(), morphism) } println!("Equalities:"); for (equality, inner) in category.equalities.iter() { println!( " {:?} = {:?}: {inner:?}", equality.left(), equality.right() ); } println!(""); }
function_block-function_prefix_line
[ { "content": "fn print_category<O: Debug, M: Debug, E: Debug>(category: &Category<O, M, E>) {\n\n println!(\"\\n----- Category -----\");\n\n println!(\"Objects:\");\n\n for (id, object) in category.objects.iter() {\n\n println!(\"{:4} - {:?}\", id.raw(), object)\n\n }\n\n println!(\"Morphi...
Rust
db/src/impls/rangestore/kvdb.rs
shogochiai/plasma-rust-framework
e72cb12d80d3e3ab080746f9fb0576a242e9d194
use crate::error::{Error, ErrorKind}; use crate::range::Range; use crate::traits::db::DatabaseTrait; use crate::traits::rangestore::RangeStore; use kvdb::{DBTransaction, KeyValueDB}; use kvdb_memorydb::{create, InMemory}; pub struct RangeDb { db: InMemory, col: u32, } impl DatabaseTrait for RangeDb { fn open(_dbname: &str) -> Self { RangeDb { db: create(8), col: 0, } } fn close(&self) {} } impl RangeDb { fn validate_range(start: u64, end: u64) -> bool { start < end } pub fn del_batch(&self, start: u64, end: u64) -> Result<Box<[Range]>, Error> { let ranges = self.get(start, end)?; let mut tr = DBTransaction::new(); for range in ranges.clone().iter() { let query = range.get_end().to_be_bytes(); tr.delete(Some(self.col), &query); } self.db.write(tr)?; if self.db.flush().is_ok() { Ok(ranges) } else { Err(Error::from(ErrorKind::Dammy)) } } pub fn put_batch(&self, ranges: &[Range]) -> Result<(), Error> { let mut tr = DBTransaction::new(); for range in ranges.iter() { let query = range.get_end().to_be_bytes(); tr.put(Some(self.col), &query, &rlp::encode(range)); } self.db.write(tr)?; if self.db.flush().is_ok() { Ok(()) } else { Err(Error::from(ErrorKind::Dammy)) } } } impl RangeStore for RangeDb { fn get(&self, start: u64, end: u64) -> Result<Box<[Range]>, Error> { let query = start.to_be_bytes(); let iter = self.db.iter_from_prefix(Some(self.col), &query); let mut result = vec![]; for (_key, value) in iter { let range: Range = rlp::decode(&value).unwrap(); if start < range.get_end() { result.push(range.clone()); if !range.intersect(start, end) { break; } } } Ok(result.into_boxed_slice()) } fn del(&self, start: u64, end: u64) -> Result<Box<[Range]>, Error> { self.del_batch(start, end) } fn put(&self, start: u64, end: u64, value: &[u8]) -> Result<(), Error> { let input_ranges = self.del_batch(start, end)?; let mut output_ranges = vec![]; if !Self::validate_range(start, end) { return Err(Error::from(ErrorKind::Dammy)); } if !input_ranges.is_empty() && input_ranges[0].get_start() < start { output_ranges.push(Range::new( input_ranges[0].get_start(), start, &input_ranges[0].get_value(), )); } if !input_ranges.is_empty() { let last_range = &input_ranges[input_ranges.len() - 1]; if end < last_range.get_end() { output_ranges.push(Range::new( end, last_range.get_end(), &last_range.get_value(), )); } } output_ranges.push(Range::new(start, end, value)); if self.put_batch(&output_ranges).is_ok() { Ok(()) } else { Err(Error::from(ErrorKind::Dammy)) } } } #[cfg(test)] mod tests { use super::RangeDb; use crate::traits::db::DatabaseTrait; use crate::traits::rangestore::RangeStore; #[test] fn test_put() { let db = RangeDb::open("test"); assert_eq!(db.put(0, 100, b"Alice is owner").is_ok(), true); assert_eq!(db.put(100, 200, b"Bob is owner").is_ok(), true); let result1 = db.get(100, 200).unwrap(); assert_eq!(result1.is_empty(), false); } #[test] fn test_get() { let db = RangeDb::open("test"); assert_eq!(db.put(0, 100, b"Alice is owner").is_ok(), true); assert_eq!(db.put(100, 120, b"Bob is owner").is_ok(), true); assert_eq!(db.put(120, 180, b"Carol is owner").is_ok(), true); let result1 = db.get(20, 50).unwrap(); assert_eq!(result1.is_empty(), true); } }
use crate::error::{Error, ErrorKind}; use crate::range::Range; use crate::traits::db::DatabaseTrait; use crate::traits::rangestore::RangeStore; use kvdb::{DBTransaction, KeyValueDB}; use kvdb_memorydb::{create, InMemory}; pub struct RangeDb { db: InMemory, col: u32, } impl DatabaseTrait for RangeDb { fn open(_dbname: &str) -> Self { RangeDb { db: create(8), col: 0, } } fn close(&self) {} } impl RangeDb { fn validate_range(start: u64, end: u64) -> bool { start < end } pub fn del_batch(&self, start: u64, end:
Dammy)) } } pub fn put_batch(&self, ranges: &[Range]) -> Result<(), Error> { let mut tr = DBTransaction::new(); for range in ranges.iter() { let query = range.get_end().to_be_bytes(); tr.put(Some(self.col), &query, &rlp::encode(range)); } self.db.write(tr)?; if self.db.flush().is_ok() { Ok(()) } else { Err(Error::from(ErrorKind::Dammy)) } } } impl RangeStore for RangeDb { fn get(&self, start: u64, end: u64) -> Result<Box<[Range]>, Error> { let query = start.to_be_bytes(); let iter = self.db.iter_from_prefix(Some(self.col), &query); let mut result = vec![]; for (_key, value) in iter { let range: Range = rlp::decode(&value).unwrap(); if start < range.get_end() { result.push(range.clone()); if !range.intersect(start, end) { break; } } } Ok(result.into_boxed_slice()) } fn del(&self, start: u64, end: u64) -> Result<Box<[Range]>, Error> { self.del_batch(start, end) } fn put(&self, start: u64, end: u64, value: &[u8]) -> Result<(), Error> { let input_ranges = self.del_batch(start, end)?; let mut output_ranges = vec![]; if !Self::validate_range(start, end) { return Err(Error::from(ErrorKind::Dammy)); } if !input_ranges.is_empty() && input_ranges[0].get_start() < start { output_ranges.push(Range::new( input_ranges[0].get_start(), start, &input_ranges[0].get_value(), )); } if !input_ranges.is_empty() { let last_range = &input_ranges[input_ranges.len() - 1]; if end < last_range.get_end() { output_ranges.push(Range::new( end, last_range.get_end(), &last_range.get_value(), )); } } output_ranges.push(Range::new(start, end, value)); if self.put_batch(&output_ranges).is_ok() { Ok(()) } else { Err(Error::from(ErrorKind::Dammy)) } } } #[cfg(test)] mod tests { use super::RangeDb; use crate::traits::db::DatabaseTrait; use crate::traits::rangestore::RangeStore; #[test] fn test_put() { let db = RangeDb::open("test"); assert_eq!(db.put(0, 100, b"Alice is owner").is_ok(), true); assert_eq!(db.put(100, 200, b"Bob is owner").is_ok(), true); let result1 = db.get(100, 200).unwrap(); assert_eq!(result1.is_empty(), false); } #[test] fn test_get() { let db = RangeDb::open("test"); assert_eq!(db.put(0, 100, b"Alice is owner").is_ok(), true); assert_eq!(db.put(100, 120, b"Bob is owner").is_ok(), true); assert_eq!(db.put(120, 180, b"Carol is owner").is_ok(), true); let result1 = db.get(20, 50).unwrap(); assert_eq!(result1.is_empty(), true); } }
u64) -> Result<Box<[Range]>, Error> { let ranges = self.get(start, end)?; let mut tr = DBTransaction::new(); for range in ranges.clone().iter() { let query = range.get_end().to_be_bytes(); tr.delete(Some(self.col), &query); } self.db.write(tr)?; if self.db.flush().is_ok() { Ok(ranges) } else { Err(Error::from(ErrorKind::
function_block-random_span
[ { "content": "fn create_object_id(start: u64, end: u64) -> Vec<u8> {\n\n let mut object_id_buf = BytesMut::with_capacity(64);\n\n object_id_buf.put_u64_le(start);\n\n object_id_buf.put_u64_le(end);\n\n object_id_buf.to_vec()\n\n}\n\n*/\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct StateObj...
Rust
crates/m-mazing-tile-util/src/main.rs
tmfink/m-mazing
e603dd081f56b897d49014dc45078db1ba9ec19b
use std::{fs::File, io::Read, path::PathBuf, sync::mpsc}; use anyhow::{Context, Result}; use clap::Parser; use m_mazing_core::bevy; use m_mazing_core::prelude::*; use notify::Watcher; use bevy::asset::AssetServerSettings; use bevy::ecs as bevy_ecs; use bevy::prelude::*; use bevy::render::camera::ScalingMode; mod gui; use crate::gui::*; const LEGEND: &str = " Arrow keys - cycle; K/U - toggle cell used; [] - rotate; P - print; R - reload; Home/End - start/end; "; #[derive(Parser, Debug, Clone)] #[clap(about, version, author)] pub struct Args { #[clap(long, short, parse(from_occurrences))] verbose: i32, #[clap(long, short, parse(from_occurrences), conflicts_with = "verbose")] quiet: i32, #[clap(long, short)] tile_file: PathBuf, #[clap(long = "start-idx", short = 'i', default_value = "0")] index: usize, } #[derive(Debug)] pub struct CurrentTile { pub tile: Tile, pub id: Entity, } #[derive(Debug, Default)] pub struct RefreshTile(pub bool); #[allow(dead_code)] #[derive(Debug)] pub struct Ctx { pub args: Args, pub tileset: Vec<(String, Tile)>, pub tile_idx: isize, pub notify_rx: mpsc::Receiver<notify::Result<notify::Event>>, pub notify_watcher: notify::RecommendedWatcher, } #[derive(Component)] pub struct TitleString; #[derive(Debug)] pub struct TileAvailability(pub CellItemAvailability); #[derive(Debug, Default)] pub struct TileRotation { pub left_turns: u8, } impl Default for TileAvailability { fn default() -> Self { Self(CellItemAvailability::Available) } } impl Ctx { fn new() -> Result<Ctx> { let args = Args::parse(); let (notify_tx, notify_rx) = mpsc::channel(); let mut notify_watcher = notify::RecommendedWatcher::new(notify_tx) .context("Failed to create notify watcher")?; notify_watcher .watch(&args.tile_file, notify::RecursiveMode::Recursive) .context(format!("Failed to watch file {:?}", args.tile_file))?; let tile_idx = args.index as isize; let mut ctx = Ctx { args, tileset: Default::default(), tile_idx, notify_rx, notify_watcher, }; ctx.refresh()?; Ok(ctx) } fn refresh(&mut self) -> Result<()> { let mut tile_input_file = File::open(&self.args.tile_file) .with_context(|| format!("Failed to open input file {:?}", &self.args.tile_file))?; let mut tile_str = String::new(); tile_input_file .read_to_string(&mut tile_str) .with_context(|| "Failed to read input")?; self.tileset = m_mazing_core::tile::tileset::tileset_from_str(&tile_str) .with_context(|| "failed to parse tileset")?; Ok(()) } } fn setup_system(mut commands: Commands) { const CAMERA_EXTENT: f32 = 3.0; let mut camera_bundle = OrthographicCameraBundle::new_2d(); camera_bundle.orthographic_projection.left = -CAMERA_EXTENT; camera_bundle.orthographic_projection.right = CAMERA_EXTENT; camera_bundle.orthographic_projection.top = CAMERA_EXTENT; camera_bundle.orthographic_projection.bottom = -CAMERA_EXTENT; camera_bundle.orthographic_projection.scaling_mode = ScalingMode::FixedVertical; camera_bundle.transform.scale = Vec3::new(3.0, 3.0, 1.0); commands.spawn_bundle(camera_bundle); } fn ui_setup(mut commands: Commands, asset_server: Res<AssetServer>) { let font = asset_server.load("fonts/FiraMono-Medium.ttf"); commands.spawn_bundle(UiCameraBundle::default()); commands .spawn_bundle(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(100.0)), justify_content: JustifyContent::SpaceBetween, ..Default::default() }, color: Color::NONE.into(), ..Default::default() }) .with_children(|parent| { parent .spawn_bundle(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(100.0)), position_type: PositionType::Absolute, justify_content: JustifyContent::Center, align_items: AlignItems::FlexEnd, ..Default::default() }, color: Color::NONE.into(), ..Default::default() }) .with_children(|parent| { parent .spawn_bundle(TextBundle { style: Style { size: Size::new(Val::Auto, Val::Auto), ..Default::default() }, text: Text::with_section( "", TextStyle { font: font.clone(), font_size: 50.0, color: Color::BLACK, }, Default::default(), ), ..Default::default() }) .insert(TitleString); }); }); commands.spawn_bundle(TextBundle { style: Style { align_self: AlignSelf::FlexEnd, position_type: PositionType::Absolute, position: Rect { top: Val::Px(5.0), left: Val::Px(15.0), ..Default::default() }, ..Default::default() }, text: Text::with_section( LEGEND.trim().to_string(), TextStyle { font, font_size: 40.0, color: Color::WHITE, }, Default::default(), ), ..Default::default() }); } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SystemLabel)] enum MySystemLabels { Input, SpawnTile, } fn frame_init(mut refresh: ResMut<RefreshTile>) { refresh.0 = false; } #[allow(unused)] fn debug_system(query: Query<Entity>) { info!("entities: {}", query.iter().count()); } fn main() -> Result<()> { let ctx = Ctx::new().with_context(|| "Failed to generate context")?; let level = log_level(ctx.args.verbose, ctx.args.quiet); println!("tileset: {:#?}", ctx.tileset); App::new() .insert_resource(Msaa { samples: 4 }) .insert_non_send_resource(ctx) .init_resource::<RenderState>() .init_resource::<TileAvailability>() .insert_resource(RefreshTile(true)) .insert_resource(AssetServerSettings { asset_folder: "../../assets".to_string(), }) .init_resource::<TileRotation>() .insert_resource(bevy::log::LogSettings { level, ..Default::default() }) .add_plugins(DefaultPlugins) .add_plugin(ShapePlugin) .add_startup_system(setup_system) .add_startup_system(ui_setup) .add_system(frame_init.before(MySystemLabels::Input)) .add_system(keyboard_input_system.label(MySystemLabels::Input)) .add_system(notify_tileset_change.label(MySystemLabels::Input)) .add_system( spawn_tile .label(MySystemLabels::SpawnTile) .after(MySystemLabels::Input), ) .add_system(print_tile.after(MySystemLabels::SpawnTile)) .run(); Ok(()) }
use std::{fs::File, io::Read, path::PathBuf, sync::mpsc}; use anyhow::{Context, Result}; use clap::Parser; use m_mazing_core::bevy; use m_mazing_core::prelude::*; use notify::Watcher; use bevy::asset::AssetServerSettings; use bevy::ecs as bevy_ecs; use bevy::prelude::*; use bevy::render::camera::ScalingMode; mod gui; use crate::gui::*; const LEGEND: &str = " Arrow keys - cycle; K/U - toggle cell used; [] - rotate; P - print; R - reload; Home/End - start/end; "; #[derive(Parser, Debug, Clone)] #[clap(about, version, author)] pub struct Args { #[clap(long, short, parse(from_occurrences))] verbose: i32, #[clap(long, short, parse(from_occurrences), conflicts_with = "verbose")] quiet: i32, #[clap(long, short)] tile_file: PathBuf, #[clap(long = "start-idx", short = 'i', default_value = "0")] index: usize, } #[derive(Debug)] pub struct CurrentTile { pub tile: Tile, pub id: Entity, } #[derive(Debug, Default)] pub struct RefreshTile(pub bool); #[allow(dead_code)] #[derive(Debug)] pub struct Ctx { pub args: Args, pub tileset: Vec<(String, Tile)>, pub tile_idx: isize, pub notify_rx: mpsc::Receiver<notify::Result<notify::Event>>, pub notify_watcher: notify::RecommendedWatcher, } #[derive(Component)] pub struct TitleString; #[derive(Debug)] pub struct TileAvailability(pub CellItemAvailability); #[derive(Debug, Default)] pub struct TileRotation { pub left_turns: u8, } impl Default for TileAvailability { fn default() -> Self { Self(CellItemAvailability::Available) } } impl Ctx { fn new() -> Result<Ctx> { let args = Args::parse(); let (notify_tx, notify_rx) = mpsc::channel(); let mut notify_watcher = notify::RecommendedWatcher::new(notify_tx) .context("Failed to create notify watcher")?; notify_watcher .watch(&args.tile_file, notify::RecursiveMode::Recursive) .context(format!("Failed to watch file {:?}", args.tile_file))?; let tile_idx = args.index as isize; let mut ctx = Ctx { args, tileset: Default::default(), tile_idx, notify_rx, notify_watcher, }; ctx.refresh()?; Ok(ctx) } fn refresh(&mut self) -> Result<()> { let mut tile_input_file = File::open(&self.args.tile_file) .with_context(|| format!("Failed to open input file {:?}", &self.args.tile_file))?; let mut tile_str = String::new(); tile_input_file .read_to_string(&mut tile_str) .with_context(|| "Failed to read input")?; self.tileset = m_mazing_core::tile::tileset::tileset_from_str(&tile_str) .with_context(|| "failed to parse tileset")?; Ok(()) } } fn setup_system(mut commands: Commands) { const CAMERA_EXTENT: f32 = 3.0; let mut camera_bundle = OrthographicCameraBundle::new_2d(); camera_bundle.orthographic_projection.left = -CAMERA_EXTENT; camera_bundle.orthographic_projection.right = CAMERA_EXTENT; camera_bundle.orthographic_projection.top = CAMERA_EXTENT; camera_bundle.orthographic_projection.bottom = -CAMERA_EXTENT; camera_bundle.orthographic_projection.scaling_mode = ScalingMode::FixedVertical; camera_bundle.transform.scale = Vec3::new(3.0, 3.0, 1.0); commands.spawn_bundle(camera_bundle); } fn ui_setup(mut commands: Commands, asset_server: Res<AssetServer>) { let font = asset_server.load("fonts/FiraMono-Medium.ttf"); commands.spawn_bundle(UiCameraBundle::default()); commands .spawn_bundle(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(100.0)), justify_content: JustifyContent::SpaceBetween, ..Default::default() }, color: Color::NONE.into(), ..Default::default() }) .with_children(|parent| { parent .spawn_bundle(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(100.0)), position_type: PositionType::Absolute, justify_content: JustifyContent::Center, align_items: AlignItems::FlexEnd, ..Default::default() }, color: Color::NONE.into(), ..Default::default() }) .with_children(|parent| { parent .spawn_bundle(TextBundle { style: Style { size: Size::new(Val::Auto, Val::Auto), ..Default::default() }, text: Text::with_section( "",
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SystemLabel)] enum MySystemLabels { Input, SpawnTile, } fn frame_init(mut refresh: ResMut<RefreshTile>) { refresh.0 = false; } #[allow(unused)] fn debug_system(query: Query<Entity>) { info!("entities: {}", query.iter().count()); } fn main() -> Result<()> { let ctx = Ctx::new().with_context(|| "Failed to generate context")?; let level = log_level(ctx.args.verbose, ctx.args.quiet); println!("tileset: {:#?}", ctx.tileset); App::new() .insert_resource(Msaa { samples: 4 }) .insert_non_send_resource(ctx) .init_resource::<RenderState>() .init_resource::<TileAvailability>() .insert_resource(RefreshTile(true)) .insert_resource(AssetServerSettings { asset_folder: "../../assets".to_string(), }) .init_resource::<TileRotation>() .insert_resource(bevy::log::LogSettings { level, ..Default::default() }) .add_plugins(DefaultPlugins) .add_plugin(ShapePlugin) .add_startup_system(setup_system) .add_startup_system(ui_setup) .add_system(frame_init.before(MySystemLabels::Input)) .add_system(keyboard_input_system.label(MySystemLabels::Input)) .add_system(notify_tileset_change.label(MySystemLabels::Input)) .add_system( spawn_tile .label(MySystemLabels::SpawnTile) .after(MySystemLabels::Input), ) .add_system(print_tile.after(MySystemLabels::SpawnTile)) .run(); Ok(()) }
TextStyle { font: font.clone(), font_size: 50.0, color: Color::BLACK, }, Default::default(), ), ..Default::default() }) .insert(TitleString); }); }); commands.spawn_bundle(TextBundle { style: Style { align_self: AlignSelf::FlexEnd, position_type: PositionType::Absolute, position: Rect { top: Val::Px(5.0), left: Val::Px(15.0), ..Default::default() }, ..Default::default() }, text: Text::with_section( LEGEND.trim().to_string(), TextStyle { font, font_size: 40.0, color: Color::WHITE, }, Default::default(), ), ..Default::default() }); }
function_block-function_prefix_line
[ { "content": "pub fn notify_tileset_change(mut should_refresh: ResMut<RefreshTile>, mut ctx: NonSendMut<Ctx>) {\n\n match ctx.notify_rx.try_recv() {\n\n Ok(Ok(event)) => {\n\n info!(\"new event {:?}\", event);\n\n should_refresh.0 = true;\n\n\n\n match ctx.refresh() {\...
Rust
common/machine.rs
camas/aoc2019
53b41dcf9990c9a4e460197b5e5031ec2158b453
use crate::common::get_digits; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::collections::HashMap; use std::ops::Range; use Instr::*; const MEM_CHUNK_SIZE: usize = 1000; pub struct Machine { memory: Memory, ip: usize, rel_base: usize, } impl Machine { pub fn new(mem: &[i64]) -> Machine { Machine { memory: Memory::from(&mem), ip: 0, rel_base: 0, } } pub fn run(&mut self, input: impl FnMut() -> i64, output: impl FnMut(i64)) { self.run_until(Instr::Halt, input, output); } #[allow(clippy::cognitive_complexity)] pub fn run_until( &mut self, halt_instr: Instr, mut input: impl FnMut() -> i64, mut output: impl FnMut(i64), ) -> bool { let mut last_instr: Option<Instr> = None; loop { if let Some(x) = last_instr { if x == halt_instr { return true; } } let raw_opcode = self.get_mem(self.ip); let digits = get_digits(raw_opcode); let opcode_i = if digits.len() == 1 { *digits.last().unwrap() } else { digits[digits.len() - 2] * 10 + digits.last().unwrap() }; let instr: Instr = FromPrimitive::from_i64(opcode_i).unwrap(); let instr_size = Machine::get_instruction_size(instr); let values: Vec<i64> = self .get_mem_range(self.ip + 1..self.ip + 1 + instr_size) .to_vec(); let mut modes = vec![0; instr_size]; if digits.len() > 2 { let diff = modes.len() + 2 - digits.len(); modes[diff..].clone_from_slice(&digits[..digits.len() - 2]); modes.reverse(); } macro_rules! read_mem { ($index:expr) => {{ let mode = modes[$index]; let val = values[$index]; match mode { 0 => self.memory.get(val as usize), 1 => val, 2 => self.memory.get((self.rel_base as i64 + val) as usize), _ => panic!("Unknown mode"), } }}; } macro_rules! write_mem { ($index:expr, $set_value:expr) => {{ let mode = modes[$index]; let val: i64 = values[$index]; match mode { 0 => self.memory.set(val as usize, $set_value), 1 => panic!("Can't write in immediate mode"), 2 => self .memory .set((self.rel_base as i64 + val) as usize, $set_value), _ => panic!("Unknown mode"), }; }}; } last_instr = Some(instr); match instr { Halt => return false, Add => { let added = read_mem!(0) + read_mem!(1); write_mem!(2, added); } Mult => { let multiplied = read_mem!(0) * read_mem!(1); write_mem!(2, multiplied); } Input => write_mem!(0, input()), Output => output(read_mem!(0)), JumpTrue => { if read_mem!(0) != 0 { self.ip = read_mem!(1) as usize; continue; } } JumpFalse => { if read_mem!(0) == 0 { self.ip = read_mem!(1) as usize; continue; } } LessThan => { if read_mem!(0) < read_mem!(1) { write_mem!(2, 1); } else { write_mem!(2, 0); } } Equals => { if read_mem!(0) == read_mem!(1) { write_mem!(2, 1); } else { write_mem!(2, 0); } } RelBase => self.rel_base = (self.rel_base as i64 + read_mem!(0)) as usize, } self.ip += instr_size + 1; } } fn get_instruction_size(instr: Instr) -> usize { match instr { Halt => 0, Add => 3, Mult => 3, Input => 1, Output => 1, JumpTrue => 2, JumpFalse => 2, LessThan => 3, Equals => 3, RelBase => 1, } } pub fn set_mem(&mut self, index: usize, value: i64) { self.memory.set(index, value); } pub fn get_mem(&mut self, index: usize) -> i64 { self.memory.get(index) } pub fn get_mem_range(&mut self, range: Range<usize>) -> Vec<i64> { let mut out = Vec::new(); for i in range { out.push(self.get_mem(i)); } out } } pub struct Memory { data: HashMap<usize, [i64; MEM_CHUNK_SIZE]>, } impl Memory { pub fn from(mem: &[i64]) -> Memory { let mut m: HashMap<usize, [i64; MEM_CHUNK_SIZE]> = HashMap::new(); for (i, chunk) in mem.to_vec().chunks(MEM_CHUNK_SIZE).enumerate() { let mut d = [0; MEM_CHUNK_SIZE]; for (i, c) in chunk.iter().enumerate() { d[i] = *c; } m.insert(i, d); } Memory { data: m } } pub fn get(&mut self, index: usize) -> i64 { let chunk_index = index / MEM_CHUNK_SIZE; let chunk_offset = index % MEM_CHUNK_SIZE; self.data.entry(chunk_index).or_insert([0; MEM_CHUNK_SIZE]); self.data[&chunk_index][chunk_offset] } pub fn set(&mut self, index: usize, value: i64) { let chunk_index = index / MEM_CHUNK_SIZE; let chunk_offset = index % MEM_CHUNK_SIZE; self.data.entry(chunk_index).or_insert([0; MEM_CHUNK_SIZE]); self.data.get_mut(&chunk_index).unwrap()[chunk_offset] = value; } } #[derive(FromPrimitive, Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Instr { Halt = 99, Add = 1, Mult = 2, Input = 3, Output = 4, JumpTrue = 5, JumpFalse = 6, LessThan = 7, Equals = 8, RelBase = 9, } #[cfg(test)] mod tests { use super::*; #[test] fn test_rel_base() { let mem = vec![ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, ]; let mut m = Machine::new(&mem); let mut output = Vec::new(); m.run(|| unreachable!(), |x| output.push(x)); assert_eq!(mem, output); } #[test] fn test_large_number() { let mem = vec![1102, 34_915_192, 34_915_192, 7, 4, 7, 99, 0]; let mut m = Machine::new(&mem); let mut output = Vec::new(); m.run(|| unreachable!(), |x| output.push(x)); assert!( output[0] == 1_219_070_632_396_864, "Result was {}", output[0] ); } #[test] fn test_large_memory() { let mem = vec![104, 1_125_899_906_842_624, 99]; let mut m = Machine::new(&mem); let mut output = Vec::new(); m.run(|| unreachable!(), |x| output.push(x)); assert!( output[0] == 1_125_899_906_842_624, "Result was {}", output[0] ); } }
use crate::common::get_digits; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::collections::HashMap; use std::ops::Range; use Instr::*; const MEM_CHUNK_SIZE: usize = 1000; pub struct Machine { memory: Memory, ip: usize, rel_base: usize, } impl Machine {
pub fn run(&mut self, input: impl FnMut() -> i64, output: impl FnMut(i64)) { self.run_until(Instr::Halt, input, output); } #[allow(clippy::cognitive_complexity)] pub fn run_until( &mut self, halt_instr: Instr, mut input: impl FnMut() -> i64, mut output: impl FnMut(i64), ) -> bool { let mut last_instr: Option<Instr> = None; loop { if let Some(x) = last_instr { if x == halt_instr { return true; } } let raw_opcode = self.get_mem(self.ip); let digits = get_digits(raw_opcode); let opcode_i = if digits.len() == 1 { *digits.last().unwrap() } else { digits[digits.len() - 2] * 10 + digits.last().unwrap() }; let instr: Instr = FromPrimitive::from_i64(opcode_i).unwrap(); let instr_size = Machine::get_instruction_size(instr); let values: Vec<i64> = self .get_mem_range(self.ip + 1..self.ip + 1 + instr_size) .to_vec(); let mut modes = vec![0; instr_size]; if digits.len() > 2 { let diff = modes.len() + 2 - digits.len(); modes[diff..].clone_from_slice(&digits[..digits.len() - 2]); modes.reverse(); } macro_rules! read_mem { ($index:expr) => {{ let mode = modes[$index]; let val = values[$index]; match mode { 0 => self.memory.get(val as usize), 1 => val, 2 => self.memory.get((self.rel_base as i64 + val) as usize), _ => panic!("Unknown mode"), } }}; } macro_rules! write_mem { ($index:expr, $set_value:expr) => {{ let mode = modes[$index]; let val: i64 = values[$index]; match mode { 0 => self.memory.set(val as usize, $set_value), 1 => panic!("Can't write in immediate mode"), 2 => self .memory .set((self.rel_base as i64 + val) as usize, $set_value), _ => panic!("Unknown mode"), }; }}; } last_instr = Some(instr); match instr { Halt => return false, Add => { let added = read_mem!(0) + read_mem!(1); write_mem!(2, added); } Mult => { let multiplied = read_mem!(0) * read_mem!(1); write_mem!(2, multiplied); } Input => write_mem!(0, input()), Output => output(read_mem!(0)), JumpTrue => { if read_mem!(0) != 0 { self.ip = read_mem!(1) as usize; continue; } } JumpFalse => { if read_mem!(0) == 0 { self.ip = read_mem!(1) as usize; continue; } } LessThan => { if read_mem!(0) < read_mem!(1) { write_mem!(2, 1); } else { write_mem!(2, 0); } } Equals => { if read_mem!(0) == read_mem!(1) { write_mem!(2, 1); } else { write_mem!(2, 0); } } RelBase => self.rel_base = (self.rel_base as i64 + read_mem!(0)) as usize, } self.ip += instr_size + 1; } } fn get_instruction_size(instr: Instr) -> usize { match instr { Halt => 0, Add => 3, Mult => 3, Input => 1, Output => 1, JumpTrue => 2, JumpFalse => 2, LessThan => 3, Equals => 3, RelBase => 1, } } pub fn set_mem(&mut self, index: usize, value: i64) { self.memory.set(index, value); } pub fn get_mem(&mut self, index: usize) -> i64 { self.memory.get(index) } pub fn get_mem_range(&mut self, range: Range<usize>) -> Vec<i64> { let mut out = Vec::new(); for i in range { out.push(self.get_mem(i)); } out } } pub struct Memory { data: HashMap<usize, [i64; MEM_CHUNK_SIZE]>, } impl Memory { pub fn from(mem: &[i64]) -> Memory { let mut m: HashMap<usize, [i64; MEM_CHUNK_SIZE]> = HashMap::new(); for (i, chunk) in mem.to_vec().chunks(MEM_CHUNK_SIZE).enumerate() { let mut d = [0; MEM_CHUNK_SIZE]; for (i, c) in chunk.iter().enumerate() { d[i] = *c; } m.insert(i, d); } Memory { data: m } } pub fn get(&mut self, index: usize) -> i64 { let chunk_index = index / MEM_CHUNK_SIZE; let chunk_offset = index % MEM_CHUNK_SIZE; self.data.entry(chunk_index).or_insert([0; MEM_CHUNK_SIZE]); self.data[&chunk_index][chunk_offset] } pub fn set(&mut self, index: usize, value: i64) { let chunk_index = index / MEM_CHUNK_SIZE; let chunk_offset = index % MEM_CHUNK_SIZE; self.data.entry(chunk_index).or_insert([0; MEM_CHUNK_SIZE]); self.data.get_mut(&chunk_index).unwrap()[chunk_offset] = value; } } #[derive(FromPrimitive, Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Instr { Halt = 99, Add = 1, Mult = 2, Input = 3, Output = 4, JumpTrue = 5, JumpFalse = 6, LessThan = 7, Equals = 8, RelBase = 9, } #[cfg(test)] mod tests { use super::*; #[test] fn test_rel_base() { let mem = vec![ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, ]; let mut m = Machine::new(&mem); let mut output = Vec::new(); m.run(|| unreachable!(), |x| output.push(x)); assert_eq!(mem, output); } #[test] fn test_large_number() { let mem = vec![1102, 34_915_192, 34_915_192, 7, 4, 7, 99, 0]; let mut m = Machine::new(&mem); let mut output = Vec::new(); m.run(|| unreachable!(), |x| output.push(x)); assert!( output[0] == 1_219_070_632_396_864, "Result was {}", output[0] ); } #[test] fn test_large_memory() { let mem = vec![104, 1_125_899_906_842_624, 99]; let mut m = Machine::new(&mem); let mut output = Vec::new(); m.run(|| unreachable!(), |x| output.push(x)); assert!( output[0] == 1_125_899_906_842_624, "Result was {}", output[0] ); } }
pub fn new(mem: &[i64]) -> Machine { Machine { memory: Memory::from(&mem), ip: 0, rel_base: 0, } }
function_block-full_function
[]
Rust
tests/admin_general.rs
gearbot/Gearbot-Animal-API
e103efc146324d411e641938617fc9eba69b5447
use animal_api::*; use animal_facts::*; mod generator; use crate::generator::*; use actix_web::web::{self, Bytes, Data}; use actix_web::{test, App}; #[actix_rt::test] async fn no_admins_loaded() { let dir = make_dir(); let mut state = gen_state(&dir); state.config.admins = Vec::new(); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("SpookyFact".to_string()), animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", state).await, RESP_BAD_AUTH ) } #[actix_rt::test] async fn invalid_key() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("SpookyFact".to_string()), animal_type: Animal::Cat, key: "BadKey".to_string(), }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_BAD_AUTH ) } #[actix_rt::test] async fn missing_permission_add() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("SpookyFact".to_string()), animal_type: Animal::Cat, key: gen_admin_delete_only().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn missing_permission_delete() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_add_only().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn missing_permission_view() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_view_only().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn missing_permission_all() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_no_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn modify_cat_unloaded() { let dir = make_dir(); let mut state = gen_state(&dir); state.fact_lists.cat_facts = None; let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: state.config.admins[0].key.clone(), }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", state).await, RESP_NOT_LOADED ) } #[actix_rt::test] async fn modify_dog_unloaded() { let dir = make_dir(); let mut state = gen_state(&dir); state.fact_lists.dog_facts = None; let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Dog, key: state.config.admins[4].key.clone(), }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", state).await, RESP_NOT_LOADED ) } #[actix_rt::test] async fn list_facts() { let dir = make_dir(); let uri = "/admin/fact/list"; let state = gen_state(&dir); let req_json = AdminFactRequest { fact_id: None, fact_content: None, animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; let raw = gen_state(&dir).fact_lists.cat_facts.unwrap(); let expected = raw.read().unwrap(); let mock_state = Data::new(state); let app = test::init_service( App::new() .app_data(mock_state.clone()) .service(web::resource(uri).route(web::post().to(admin::modify_fact))), ) .await; let req = test::TestRequest::post() .uri(uri) .set_json(&req_json) .to_request(); let received: Vec<Fact> = test::call_and_read_body_json(&app, req).await; assert_eq!(received, *expected) } #[actix_rt::test] async fn add_fact_no_content() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: None, animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_NO_CONTENT_SPECIFIED ) } #[actix_rt::test] async fn add_fact_ok() { let dir = make_dir(); let state = gen_state(&dir); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("Huzaaah, a new fact!".to_string()), animal_type: Animal::Dog, key: gen_admin_all_perms().key, }; let resp = test_admin_fact_req(req_json, "/admin/fact/add", state).await; let word = CreatedAction::Fact { animal: Animal::Dog, }; let expected = JsonResp::new(201, word.as_str()); assert_eq!(resp, expected); } #[actix_rt::test] async fn delete_fact_no_id() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: None, animal_type: Animal::Dog, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_NO_ID_SUPPLIED ) } #[actix_rt::test] async fn delete_fact_bad_id() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(3), fact_content: None, animal_type: Animal::Dog, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_ID_NOT_FOUND ) } #[actix_rt::test] async fn delete_fact_ok() { let dir = make_dir(); let uri = "/admin/fact/delete"; let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; let state = gen_state(&dir); let mock_state = Data::new(state); let app = test::init_service( App::new() .app_data(mock_state.clone()) .service(web::resource(uri).route(web::post().to(admin::modify_fact))), ) .await; let req = test::TestRequest::post() .uri(uri) .set_json(&req_json) .to_request(); let resp = test::call_and_read_body(&app, req).await; assert_eq!(resp, Bytes::from_static(b"")) }
use animal_api::*; use animal_facts::*; mod generator; use crate::generator::*; use actix_web::web::{self, Bytes, Data}; use actix_web::{test, App}; #[actix_rt::test] async fn no_admins_loaded() { let dir = make_dir(); let mut state = gen_state(&dir); state.config.admins = Vec::new(); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("SpookyFact".to_string()), animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", state).await, RESP_BAD_AUTH ) } #[actix_rt::test] async fn invalid_key() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("SpookyFact".to_string()), animal_type: Animal::Cat, key: "BadKey".to_string(), }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_BAD_AUTH ) } #[actix_rt::test] async fn missing_permission_add() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("SpookyFact".to_string()), animal_type: Animal::Cat, key: gen_admin_delete_only().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn missing_permission_delete() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_add_only().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn missing_permission_view() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_view_only().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn missing_permission_all() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_no_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_MISSING_PERMS ) } #[actix_rt::test] async fn modify_cat_unloaded() { let dir = make_dir(); let mut state = gen_state(&dir); state.fact_lists.cat_facts = None; let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: state.config.admins[0].key.clone(), }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", state).await, RESP_NOT_LOADED ) } #[actix_rt::test] async fn modify_dog_unloaded() { let dir = ma
#[actix_rt::test] async fn list_facts() { let dir = make_dir(); let uri = "/admin/fact/list"; let state = gen_state(&dir); let req_json = AdminFactRequest { fact_id: None, fact_content: None, animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; let raw = gen_state(&dir).fact_lists.cat_facts.unwrap(); let expected = raw.read().unwrap(); let mock_state = Data::new(state); let app = test::init_service( App::new() .app_data(mock_state.clone()) .service(web::resource(uri).route(web::post().to(admin::modify_fact))), ) .await; let req = test::TestRequest::post() .uri(uri) .set_json(&req_json) .to_request(); let received: Vec<Fact> = test::call_and_read_body_json(&app, req).await; assert_eq!(received, *expected) } #[actix_rt::test] async fn add_fact_no_content() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: None, animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", gen_state(&dir)).await, RESP_NO_CONTENT_SPECIFIED ) } #[actix_rt::test] async fn add_fact_ok() { let dir = make_dir(); let state = gen_state(&dir); let req_json = AdminFactRequest { fact_id: None, fact_content: Some("Huzaaah, a new fact!".to_string()), animal_type: Animal::Dog, key: gen_admin_all_perms().key, }; let resp = test_admin_fact_req(req_json, "/admin/fact/add", state).await; let word = CreatedAction::Fact { animal: Animal::Dog, }; let expected = JsonResp::new(201, word.as_str()); assert_eq!(resp, expected); } #[actix_rt::test] async fn delete_fact_no_id() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: None, fact_content: None, animal_type: Animal::Dog, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_NO_ID_SUPPLIED ) } #[actix_rt::test] async fn delete_fact_bad_id() { let dir = make_dir(); let req_json = AdminFactRequest { fact_id: Some(3), fact_content: None, animal_type: Animal::Dog, key: gen_admin_all_perms().key, }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/delete", gen_state(&dir)).await, RESP_ID_NOT_FOUND ) } #[actix_rt::test] async fn delete_fact_ok() { let dir = make_dir(); let uri = "/admin/fact/delete"; let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; let state = gen_state(&dir); let mock_state = Data::new(state); let app = test::init_service( App::new() .app_data(mock_state.clone()) .service(web::resource(uri).route(web::post().to(admin::modify_fact))), ) .await; let req = test::TestRequest::post() .uri(uri) .set_json(&req_json) .to_request(); let resp = test::call_and_read_body(&app, req).await; assert_eq!(resp, Bytes::from_static(b"")) }
ke_dir(); let mut state = gen_state(&dir); state.fact_lists.dog_facts = None; let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Dog, key: state.config.admins[4].key.clone(), }; assert_eq!( test_admin_fact_req(req_json, "/admin/fact/add", state).await, RESP_NOT_LOADED ) }
function_block-function_prefixed
[ { "content": "pub fn get_cat_fact(app_data: Data<APIState>) -> HttpResponse {\n\n if let Some(fact_list) = &app_data.fact_lists.cat_facts {\n\n let mut rng = thread_rng();\n\n let list_lock = fact_list.read().unwrap();\n\n\n\n // This should never panic since `Some()` means there is >= 1...
Rust
examples/bank-emulator/integration-tests/src/fees.rs
m10io/sdk
62f773304da0567986d5fc33c282649238c9f5c2
use m10_bank_emulator::models::*; use rust_decimal::Decimal; use super::base_url; use super::utils::*; #[tokio::test] async fn fees_routes() { let jwt = default_user_jwt().await; let client = reqwest::Client::default(); let tr_fees = FeeMetadata { schedule: FeeSchedule { fees: vec![ FeeBracket { range: 0..=10, polynomial: vec![Decimal::new(25, 0)], }, FeeBracket { range: 11..=20, polynomial: vec![Decimal::new(50, 0)], }, FeeBracket { range: 21..=501, polynomial: vec![Decimal::new(100, 0)], }, FeeBracket { range: 502..=u64::MAX, polynomial: vec![Decimal::new(125, 0)], }, ], }, split: vec![ FeeSplit { name: "M10".to_string(), percent: Decimal::new(75, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, FeeSplit { name: "DD".to_string(), percent: Decimal::new(25, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, ], }; let wd_fees = FeeMetadata { schedule: FeeSchedule { fees: vec![ FeeBracket { range: 0..=10, polynomial: vec![Decimal::new(50, 0)], }, FeeBracket { range: 11..=20, polynomial: vec![Decimal::new(75, 0)], }, FeeBracket { range: 21..=501, polynomial: vec![Decimal::new(100, 0)], }, FeeBracket { range: 502..=u64::MAX, polynomial: vec![Decimal::new(125, 0)], }, ], }, split: vec![ FeeSplit { name: "M10".to_string(), percent: Decimal::new(50, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, FeeSplit { name: "DD".to_string(), percent: Decimal::new(50, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, ], }; client .post(format!("{}/api/v1/fees/ttt/transfer", base_url())) .bearer_auth(&jwt) .json(&tr_fees) .send() .await .expect("insert/update transfer fee schedule response") .assert_json::<FeeMetadata>() .await; client .post(format!("{}/api/v1/fees/ttt/withdraw", base_url())) .bearer_auth(&jwt) .json(&wd_fees) .send() .await .expect("insert/update withdraw fee schedule response") .assert_json::<FeeMetadata>() .await; let resp = client .get(format!("{}/api/v1/fees/ttt/transfer", base_url())) .bearer_auth(&jwt) .send() .await .unwrap() .assert_json::<FeeMetadata>() .await; assert_eq!(Decimal::new(75, 2), resp.split[0].percent); let resp = client .get(format!("{}/api/v1/fees/ttt/withdraw", base_url())) .bearer_auth(&jwt) .send() .await .unwrap() .assert_json::<FeeMetadata>() .await; assert_eq!(Decimal::new(50, 2), resp.split[0].percent); let resp = client .get(format!("{}/api/v1/fees/ttt/transfer/30300", base_url())) .bearer_auth(&jwt) .send() .await .expect("get transfer fee amount response") .assert_json::<FeeResponse>() .await; assert_eq!(94, resp.fees[0].amount); let resp = client .get(format!("{}/api/v1/fees/ttt/withdraw/60600", base_url())) .bearer_auth(&jwt) .send() .await .expect("get withdraw fee amount response") .assert_json::<FeeResponse>() .await; assert_eq!(63, resp.fees[0].amount); client .get(format!("{}/api/v1/fees/ttt/deposit/60600", base_url())) .bearer_auth(&jwt) .send() .await .expect("get deposit fee amount response") .assert_status(404) .await; }
use m10_bank_emulator::models::*; use rust_decimal::Decimal; use super::base_url; use super::utils::*; #[tokio::test] async fn fees_routes() { let jwt = default_user_jwt().await; let client = reqwest::Client::default(); let tr_fees = FeeMetadata { schedule: FeeSchedule { fees: vec![ FeeBracket { range: 0..=10, polynomial: vec![Decimal::new(25, 0)], }, FeeBracket { range: 11..=20, polynomial: vec![Decimal::new(50, 0)], }, FeeBracket { range: 21..=501, polynomial: vec![Decimal::new(100, 0)], }, FeeBracket { range: 502..=u64::MAX, polynomial: vec![Decimal::new(125, 0)], }, ], }, split: vec![ FeeSplit { name: "M10".to_string(), percent: Decimal::new(75, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, FeeSplit { name: "DD".to_string(), percent: Decimal::new(25, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, ], }; let wd_fees = FeeMetadata { schedule: FeeSchedule { fees: vec![ FeeBracket { range: 0..=10, polynomial: vec![Decimal::new(50, 0)], }, FeeBracket { range: 11..=20, polynomial: vec![Decimal::new(75, 0)], }, FeeBracket { range: 21..=501, polynomial: vec![Decimal::new(100, 0)], }, FeeBracket { range: 502..=u64::MAX, polynomial: vec![Decimal::new(125, 0)], }, ], }, split: vec![ FeeSplit { name: "M10".to_string(), percent: Decimal::new(50, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, FeeSplit { name: "DD".to_string(), percent: Decimal::new(50, 2), account: [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, ], }; client .post(format!("{}/api/v1/fees/ttt/transfer", base_url())) .bearer_auth(&jwt) .json(&tr_fees) .send() .await .expect("insert/update transfer fee schedule response") .assert_json::<FeeMetadata>() .await; client .post(format!("{}/api/v1/fees/ttt/withdraw", base_url())) .bearer_auth(&jwt) .json(&wd_fees) .send() .await .expect("insert/update withdraw fee schedule response") .assert_json::<FeeMetadata>() .await; let resp = client .get(format!("{}/api/v1/fees/ttt/transfer", base_url())) .bearer_auth(&jwt) .send() .await .unwrap() .assert_json::<FeeMetadata>() .await; assert_eq!(Decimal::new(75, 2), resp.split[0].percent); let resp = client .get(format!("{}/api/v1/fees/ttt/withdraw", base_url())) .bearer_auth(&jwt) .send() .await .unwrap() .assert_json::<FeeMetadata>() .await; assert_eq!(Decimal::new(50, 2), resp.split[0].percent); let resp = client .get(format!("{}/api/v1/fees/ttt/transfer/30300", base_url())) .bearer_auth(&jwt) .send() .await .expect("get transfer fee amount response") .assert_json::<FeeResponse>() .await; assert_eq!(94, resp.fees[0].amount); let resp = client .get(format!("{}/api/v1/fees/ttt/withdraw/60600", base_url())) .bearer_auth(&jwt) .send() .awai
t .expect("get withdraw fee amount response") .assert_json::<FeeResponse>() .await; assert_eq!(63, resp.fees[0].amount); client .get(format!("{}/api/v1/fees/ttt/deposit/60600", base_url())) .bearer_auth(&jwt) .send() .await .expect("get deposit fee amount response") .assert_status(404) .await; }
function_block-function_prefixed
[ { "content": "fn with_additional_protos(mut protos: Vec<String>, additional_paths: &[&str]) -> Vec<String> {\n\n for path in additional_paths {\n\n protos.push(proto_path(path).display().to_string());\n\n }\n\n protos\n\n}\n", "file_path": "rust/protos/build.rs", "rank": 0, "score": ...
Rust
src/bin/mpc.rs
ys-nuem/rust-gurobi-example
a94bf00d1452a4753c0dc0fd6ea83d67fb0d735f
#![allow(non_snake_case)] #![allow(dead_code)] extern crate gurobi; #[macro_use] extern crate itertools; use gurobi::*; use itertools::*; struct MPCModel(gurobi::Model); impl std::ops::Deref for MPCModel { type Target = gurobi::Model; fn deref(&self) -> &gurobi::Model { &self.0 } } impl std::ops::DerefMut for MPCModel { fn deref_mut(&mut self) -> &mut gurobi::Model { &mut self.0 } } impl MPCModel { fn new(modelname: &str, env: &Env) -> Result<MPCModel> { Model::new(modelname, &env).map(|model| MPCModel(model)) } fn add_var_series(&mut self, name: &str, len: usize, start: isize) -> Result<Vec<Var>> { let mut vars = Vec::with_capacity(len); for i in start..((len as isize) - start) { let v = try!(self.add_var(&format!("{}_{}", name, i), Continuous, 0.0, -INFINITY, INFINITY, &[], &[])); vars.push(v); } Ok(vars) } } fn main() { let mut env = Env::new("receding_horizon.log").unwrap(); env.set(param::OutputFlag, 0).unwrap(); let env = env; struct Solution { status: Status, u: Vec<f64>, x: Vec<f64>, } let solve_mpc = |x_t: f64, t: usize| -> Result<Solution> { let horizon = 10; let q = 100.0; let r = 0.42; let s = 0.01; let mut model = try!(MPCModel::new(&format!("mpc_{}", t), &env)); let u = try!(model.add_var_series("u", horizon, 0)); let x = try!(model.add_var_series("x", horizon + 2, -1)); try!(model.update()); for u in u.iter() { try!(u.set(&mut model, attr::LB, -1.0)); try!(u.set(&mut model, attr::UB, 1.0)); } try!(model.add_constr("initial", 1.0 * &x[0], Equal, x_t)); for (k, (u_k, x_k, x_k1)) in Zip::new((u.iter(), x.iter(), x.iter().skip(1))).enumerate() { try!(model.add_constr(&format!("ss_{}", k), x_k1 + (-0.9 * x_k) + (-1.0 * u_k), Equal, 0.0)); } let expr = Zip::new((x.iter().skip(1), u.iter())).fold(QuadExpr::new(), |expr, (x, u)| { expr + (x * x) * q + (u * u) * r }) + try!(x.last().map(|x_T| (x_T * x_T) * s).ok_or(Error::InconsitentDims)); try!(model.set_objective(expr, Minimize)); try!(model.optimize()); match try!(model.status()) { Status::Optimal => (), status => { return Ok(Solution { status: status, u: vec![], x: vec![], }) } } let mut sol_u = Vec::with_capacity(u.len()); for u in u.into_iter() { let u = try!(u.get(&model, attr::X)); sol_u.push(u); } let mut sol_x = Vec::with_capacity(x.len()); for x in x.into_iter() { let x = try!(x.get(&model, attr::X)); sol_x.push(x); } Ok(Solution { status: Status::Optimal, u: sol_u, x: sol_x, }) }; let n_times = 100; let n_rt = 10; let x_0 = 1.0; let mut state = Vec::with_capacity(n_times * n_rt); let mut input = Vec::with_capacity(n_times * n_rt); state.push(x_0); for t in 0..(n_times * n_rt) { let x_t = state.last().cloned().unwrap(); if t % n_rt == 0 { let sol = solve_mpc(x_t, t).unwrap(); let u = match sol.status { Status::Optimal => *sol.u.get(0).unwrap(), _ => { println!("step {}: cannot retrieve an optimal MIP solution", t); 0.0 } }; input.push(u); } let u_t = input.last().cloned().unwrap(); let x_t = 0.99 * x_t + u_t + 0.01; state.push(x_t); } println!("input = {:?}", input); }
#![allow(non_snake_case)] #![allow(dead_code)] extern crate gurobi; #[macro_use] extern crate itertools; use gurobi::*; use itertools::*; struct MPCModel(gurobi::Model); impl std::ops::Deref for MPCModel { type Target = gurobi::Model; fn deref(&self) -> &gurobi::Model { &self.0 } } impl std::ops::DerefMut for MPCModel { fn deref_mut(&mut self) -> &mut gurobi::Model { &mut self.0 } } impl MPCModel { fn new(modelname: &str, env: &Env) -> Result<MPCModel> { Model::new(modelname, &env).map(|model| MPCModel(model)) } fn add_var_series(&mut self, name: &str, len: usize, start: isize) -> Result<Vec<Var>> { let mut vars = Vec::with_capacity(len); for i in start..((len as isize) - start) { let v = try!(self.add_var(&format!("{}_{}", name, i), Continuous, 0.0, -INFINITY, INFINITY, &[], &[])); vars.push(v); } Ok(vars) } } fn main() { let mut env = Env::new("receding_horizon.log").unwrap(); env.set(param::OutputFlag, 0).unwrap(); let env = env; struct Solution { status: Status, u: Vec<f64>, x: Vec<f64>, } let solve_mpc = |x_t: f64, t: usize| -> Result<Solution> { let horizon = 10; let q = 100.0; let r = 0.42; let s = 0.01; let mut model = try!(MPCModel::new(&format!("mpc_{}", t), &env)); let u = try!(model.add_var_series("u", horizon, 0)); let x = try!(model.add_var_series("x", horizon + 2, -1)); try!(model.update()); for u in u.iter() { try!(u.set(&mut model, attr::LB, -1.0)); try!(u.set(&mut model, attr::UB, 1.0)); } try!(model.add_constr("initial", 1.0 * &x[0], Equal, x_t)); for (k, (u_k, x_k, x_k1)) in Zip::new((u.iter(), x.iter(), x.iter().skip(1))).enumerate() { try!(model.add_constr(&format!("ss_{}", k), x_k1 + (-0.9 * x_k) + (-1.0 * u_k), Equal, 0.0)); } let expr = Zip::new((x.iter().skip(1), u.iter())).fold(QuadExpr::new(), |expr, (x, u)| { expr + (x * x) * q + (u * u) * r }) + try!(x.last().map(|x_T| (x_T * x_T) * s).ok_or(Error::InconsitentDims)); try!(model.set_objective(expr, Minimize)); try!(model.optimize()); match try!(model.status()) { Status::Optimal => (), status => { return Ok(Solution { status: status, u: vec![], x: vec![], }) } } let mut sol_u = Vec::with_capacity(u.len()); for u in u.into_iter() { let u = try!(u.get(&model, attr::X)); sol_u.push(u); } let mut sol_x = Vec::with_capacity(x.len()); for x in x.into_iter() { let x = try!(x.get(&model, attr::X)); sol_x.push(x); } Ok(Solution { status: Status::Optimal, u: sol_u, x: sol_x, }) }; let n_times = 100; let n_rt = 10; let x_0 = 1.0; let mut state = Vec::with_capacity(n_times * n_rt); let mut input = Vec::with_capacity(n_times * n_rt); state.push(x_0); for t in 0..(n_times * n_rt) { let x_t = state.last().cloned().unwrap(); if t % n_rt == 0 { let sol = solve_mpc(x_t, t).unwrap(); let u =
; input.push(u); } let u_t = input.last().cloned().unwrap(); let x_t = 0.99 * x_t + u_t + 0.01; state.push(x_t); } println!("input = {:?}", input); }
match sol.status { Status::Optimal => *sol.u.get(0).unwrap(), _ => { println!("step {}: cannot retrieve an optimal MIP solution", t); 0.0 } }
if_condition
[ { "content": "# rust-gurobi-example", "file_path": "README.md", "rank": 0, "score": 2911.5059799016285 } ]
Rust
nft_api/src/ingest/main.rs
jarry-xiao/merkle-wallet
079c4c7b51ee9f90ad98c13a660ff97727db7127
extern crate core; use hyper::{Body, Client, Request, Response, Server, StatusCode}; use futures_util::future::join3; use redis::streams::{StreamId, StreamKey, StreamReadOptions, StreamReadReply}; use redis::{Commands, Value}; use routerify::prelude::*; use routerify::{Middleware, Router, RouterService}; use anchor_client::anchor_lang::prelude::Pubkey; use routerify_json_response::{json_failed_resp_with_message, json_success_resp}; use std::{net::SocketAddr, thread}; use gummyroll::state::change_log::{ChangeLogEvent, PathNode}; use nft_api_lib::error::*; use nft_api_lib::events::handle_event; use sqlx; use sqlx::postgres::PgPoolOptions; use sqlx::{Pool, Postgres}; use tokio::task; #[derive(Default)] struct AppEvent { op: String, message: String, leaf: String, owner: String, tree_id: String, authority: String, } const SET_APPSQL: &str = r#"INSERT INTO app_specific (msg, leaf, owner, tree_id, revision) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (msg) DO UPDATE SET leaf = excluded.leaf, owner = excluded.owner, tree_id = excluded.tree_id, revision = excluded.revision"#; const SET_OWNERSHIP_APPSQL: &str = r#"INSERT INTO app_specific_ownership (tree_id, authority) VALUES ($1,$2) ON CONFLICT (tree_id) DO UPDATE SET authority = excluded.authority"#; const GET_APPSQL: &str = "SELECT revision FROM app_specific WHERE msg = $1 AND tree_id = $2"; const DEL_APPSQL: &str = "DELETE FROM app_specific WHERE leaf = $1 AND tree_id = $2"; const SET_CLSQL_ITEM: &str = "INSERT INTO cl_items (tree, seq, level, hash, node_idx) VALUES ($1,$2,$3,$4,$5)"; #[derive(sqlx::FromRow, Clone, Debug)] struct AppSpecificRev { revision: i64, } pub async fn cl_service(ids: &Vec<StreamId>, pool: &Pool<Postgres>) -> String { let mut last_id = "".to_string(); for StreamId { id, map } in ids { println!("\tCL STREAM ID {}", id); let pid = id.replace("-", "").parse::<i64>().unwrap(); let data = map.get("data"); if data.is_none() { println!("\tNo Data"); continue; } if let Value::Data(bytes) = data.unwrap().to_owned() { let raw_str = String::from_utf8(bytes); if !raw_str.is_ok() { continue; } let change_log_res = raw_str .map_err(|_serr| ApiError::ChangeLogEventMalformed) .and_then(|o| { let d: Result<ChangeLogEvent, ApiError> = handle_event(o); d }); if change_log_res.is_err() { println!("\tBad Data"); continue; } let change_log = change_log_res.unwrap(); println!("\tCL tree {:?}", change_log.id); let txnb = pool.begin().await; match txnb { Ok(txn) => { let mut i: i64 = 0; for p in change_log.path.into_iter() { println!("level {}, node {:?}", i, p.node.inner); let tree_id = change_log.id.as_ref(); let f = sqlx::query(SET_CLSQL_ITEM) .bind(&tree_id) .bind(&pid + i) .bind(&i) .bind(&p.node.inner.as_ref()) .bind(&(p.index as i64)) .execute(pool) .await; if f.is_err() { println!("Error {:?}", f.err().unwrap()); } i += 1; } match txn.commit().await { Ok(_r) => { println!("Saved CL"); } Err(e) => { eprintln!("{}", e.to_string()) } } } Err(e) => { eprintln!("{}", e.to_string()) } } } last_id = id.clone(); } last_id } pub async fn structured_program_event_service( ids: &Vec<StreamId>, pool: &Pool<Postgres>, ) -> String { let mut last_id = "".to_string(); for StreamId { id, map } in ids { let mut app_event = AppEvent::default(); for (k, v) in map.to_owned() { if let Value::Data(bytes) = v { let raw_str = String::from_utf8(bytes); if raw_str.is_ok() { if k == "op" { app_event.op = raw_str.unwrap(); } else if k == "tree_id" { app_event.tree_id = raw_str.unwrap(); } else if k == "msg" { app_event.message = raw_str.unwrap(); } else if k == "leaf" { app_event.leaf = raw_str.unwrap(); } else if k == "owner" { app_event.owner = raw_str.unwrap(); } else if k == "authority" { app_event.authority = raw_str.unwrap(); } } } } let pid = id.replace("-", "").parse::<i64>().unwrap(); let new_owner = map.get("new_owner").and_then(|x| { if let Value::Data(bytes) = x.to_owned() { String::from_utf8(bytes).ok() } else { None } }); println!("Op: {:?}", app_event.op); println!("leaf: {:?}", &app_event.leaf); println!("owner: {:?}", &app_event.owner); println!("tree_id: {:?}", &app_event.tree_id); println!("new_owner: {:?}", new_owner); if app_event.op == "add" || app_event.op == "tran" || app_event.op == "create" { let row = sqlx::query_as::<_, AppSpecificRev>(GET_APPSQL) .bind(&un_jank_message(&app_event.message)) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .fetch_one(pool) .await; if row.is_ok() { let res = row.unwrap(); if pid < res.revision as i64 { continue; } } } if app_event.op == "add" { sqlx::query(SET_APPSQL) .bind(&un_jank_message(&app_event.message)) .bind(&bs58::decode(&app_event.leaf).into_vec().unwrap()) .bind(&bs58::decode(&app_event.owner).into_vec().unwrap()) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .bind(&pid) .execute(pool) .await .unwrap(); } else if app_event.op == "tran" { match new_owner { Some(x) => { sqlx::query(SET_APPSQL) .bind(&un_jank_message(&app_event.message)) .bind(&bs58::decode(&app_event.leaf).into_vec().unwrap()) .bind(&bs58::decode(&x).into_vec().unwrap()) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .bind(&pid) .execute(pool) .await .unwrap(); } None => { println!("Received Transfer op with no new_owner"); continue; } }; } else if app_event.op == "rm" { sqlx::query(DEL_APPSQL) .bind(&bs58::decode(&app_event.leaf).into_vec().unwrap()) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .execute(pool) .await .unwrap(); } else if app_event.op == "create" { sqlx::query(SET_OWNERSHIP_APPSQL) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .bind(&bs58::decode(&app_event.authority).into_vec().unwrap()) .bind(&pid) .execute(pool) .await .unwrap(); } last_id = id.clone(); } last_id } fn un_jank_message(hex_str: &String) -> String { String::from_utf8(hex::decode(hex_str).unwrap()).unwrap() } #[tokio::main] async fn main() { let client = redis::Client::open("redis://redis/").unwrap(); let pool = PgPoolOptions::new() .max_connections(5) .connect("postgres://solana:solana@db/solana") .await .unwrap(); let mut cl_last_id: String = ">".to_string(); let mut gm_last_id: String = ">".to_string(); let conn_res = client.get_connection(); let mut conn = conn_res.unwrap(); let streams = vec!["GM_CL", "GMC_OP"]; let group_name = "ingester"; for key in &streams { let created: Result<(), _> = conn.xgroup_create_mkstream(*key, group_name, "$"); if let Err(e) = created { println!("Group already exists: {:?}", e) } } loop { let opts = StreamReadOptions::default() .block(1000) .count(100000) .group(group_name, "lelelelle"); let srr: StreamReadReply = conn .xread_options(streams.as_slice(), &[&cl_last_id, &gm_last_id], &opts) .unwrap(); for StreamKey { key, ids } in srr.keys { println!("{}", key); if key == "GM_CL" { cl_service(&ids, &pool).await; } else if key == "GMC_OP" { structured_program_event_service(&ids, &pool).await; } } } }
extern crate core; use hyper::{Body, Client, Request, Response, Server, StatusCode}; use futures_util::future::join3; use redis::streams::{StreamId, StreamKey, StreamReadOptions, StreamReadReply}; use redis::{Commands, Value}; use routerify::prelude::*; use routerify::{Middleware, Router, RouterService}; use anchor_client::anchor_lang::prelude::Pubkey; use routerify_json_response::{json_failed_resp_with_message, json_success_resp}; use std::{net::SocketAddr, thread}; use gummyroll::state::change_log::{ChangeLogEvent, PathNode}; use nft_api_lib::error::*; use nft_api_lib::events::handle_event; use sqlx; use sqlx::postgres::PgPoolOptions; use sqlx::{Pool, Postgres}; use tokio::task; #[derive(Default)] struct AppEvent { op: String, message: String, leaf: String, owner: String, tree_id: String, authority: String, } const SET_APPSQL: &str = r#"INSERT INTO app_specific (msg, leaf, owner, tree_id, revision) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (msg) DO UPDATE SET leaf = excluded.leaf, owner = excluded.owner, tree_id = excluded.tree_id, revision = excluded.revision"#; const SET_OWNERSHIP_APPSQL: &str = r#"INSERT INTO app_specific_ownership (tree_id, authority) VALUES ($1,$2) ON CONFLICT (tree_id) DO UPDATE SET authority = excluded.authority"#; const GET_APPSQL: &str = "SELECT revision FROM app_specific WHERE msg = $1 AND tree_id = $2"; const DEL_APPSQL: &str = "DELETE FROM app_specific WHERE leaf = $1 AND tree_id = $2"; const SET_CLSQL_ITEM: &str = "INSERT INTO cl_items (tree, seq, level, hash, node_idx) VALUES ($1,$2,$3,$4,$5)"; #[derive(sqlx::FromRow, Clone, Debug)] struct AppSpecificRev { revision: i64, } pub async fn cl_service(ids: &Vec<StreamId>, pool: &Pool<Postgres>) -> String { let mut last_id = "".to_string(); for StreamId { id, map } in ids { println!("\tCL STREAM ID {}", id); let pid = id.replace("-", "").parse::<i64>().unwrap(); let data = map.get("data"); if data.is_none() { println!("\tNo Data"); continue; } if let Value::Data(bytes) = data.unwrap().to_owned() { let raw_str = String::from_utf8(bytes); if !raw_str.is_ok() { continue; } let change_log_res = raw_str .map_err(|_serr| ApiError::ChangeLogEventMalformed) .and_then(|o| { let d: Result<ChangeLogEvent, ApiError> = handle_event(o); d }); if change_log_res.is_err() { println!("\tBad Data"); continue; } let change_log = change_log_res.unwrap(); println!("\tCL tree {:?}", change_log.id); let txnb = pool.begin().await; match txnb { Ok(txn) => { let mut i: i64 = 0; for p in change_log.path.into_iter() { println!("level {}, node {:?}", i, p.node.inner); let tree_id = change_log.id.as_ref(); let f = sqlx::query(SET_CLSQL_ITEM) .bind(&tree_id) .bind(&pid + i) .bind(&i) .bind(&p.node.inner.as_ref()) .bind(&(p.index as i64)) .execute(pool) .
let mut conn = conn_res.unwrap(); let streams = vec!["GM_CL", "GMC_OP"]; let group_name = "ingester"; for key in &streams { let created: Result<(), _> = conn.xgroup_create_mkstream(*key, group_name, "$"); if let Err(e) = created { println!("Group already exists: {:?}", e) } } loop { let opts = StreamReadOptions::default() .block(1000) .count(100000) .group(group_name, "lelelelle"); let srr: StreamReadReply = conn .xread_options(streams.as_slice(), &[&cl_last_id, &gm_last_id], &opts) .unwrap(); for StreamKey { key, ids } in srr.keys { println!("{}", key); if key == "GM_CL" { cl_service(&ids, &pool).await; } else if key == "GMC_OP" { structured_program_event_service(&ids, &pool).await; } } } }
await; if f.is_err() { println!("Error {:?}", f.err().unwrap()); } i += 1; } match txn.commit().await { Ok(_r) => { println!("Saved CL"); } Err(e) => { eprintln!("{}", e.to_string()) } } } Err(e) => { eprintln!("{}", e.to_string()) } } } last_id = id.clone(); } last_id } pub async fn structured_program_event_service( ids: &Vec<StreamId>, pool: &Pool<Postgres>, ) -> String { let mut last_id = "".to_string(); for StreamId { id, map } in ids { let mut app_event = AppEvent::default(); for (k, v) in map.to_owned() { if let Value::Data(bytes) = v { let raw_str = String::from_utf8(bytes); if raw_str.is_ok() { if k == "op" { app_event.op = raw_str.unwrap(); } else if k == "tree_id" { app_event.tree_id = raw_str.unwrap(); } else if k == "msg" { app_event.message = raw_str.unwrap(); } else if k == "leaf" { app_event.leaf = raw_str.unwrap(); } else if k == "owner" { app_event.owner = raw_str.unwrap(); } else if k == "authority" { app_event.authority = raw_str.unwrap(); } } } } let pid = id.replace("-", "").parse::<i64>().unwrap(); let new_owner = map.get("new_owner").and_then(|x| { if let Value::Data(bytes) = x.to_owned() { String::from_utf8(bytes).ok() } else { None } }); println!("Op: {:?}", app_event.op); println!("leaf: {:?}", &app_event.leaf); println!("owner: {:?}", &app_event.owner); println!("tree_id: {:?}", &app_event.tree_id); println!("new_owner: {:?}", new_owner); if app_event.op == "add" || app_event.op == "tran" || app_event.op == "create" { let row = sqlx::query_as::<_, AppSpecificRev>(GET_APPSQL) .bind(&un_jank_message(&app_event.message)) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .fetch_one(pool) .await; if row.is_ok() { let res = row.unwrap(); if pid < res.revision as i64 { continue; } } } if app_event.op == "add" { sqlx::query(SET_APPSQL) .bind(&un_jank_message(&app_event.message)) .bind(&bs58::decode(&app_event.leaf).into_vec().unwrap()) .bind(&bs58::decode(&app_event.owner).into_vec().unwrap()) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .bind(&pid) .execute(pool) .await .unwrap(); } else if app_event.op == "tran" { match new_owner { Some(x) => { sqlx::query(SET_APPSQL) .bind(&un_jank_message(&app_event.message)) .bind(&bs58::decode(&app_event.leaf).into_vec().unwrap()) .bind(&bs58::decode(&x).into_vec().unwrap()) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .bind(&pid) .execute(pool) .await .unwrap(); } None => { println!("Received Transfer op with no new_owner"); continue; } }; } else if app_event.op == "rm" { sqlx::query(DEL_APPSQL) .bind(&bs58::decode(&app_event.leaf).into_vec().unwrap()) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .execute(pool) .await .unwrap(); } else if app_event.op == "create" { sqlx::query(SET_OWNERSHIP_APPSQL) .bind(&bs58::decode(&app_event.tree_id).into_vec().unwrap()) .bind(&bs58::decode(&app_event.authority).into_vec().unwrap()) .bind(&pid) .execute(pool) .await .unwrap(); } last_id = id.clone(); } last_id } fn un_jank_message(hex_str: &String) -> String { String::from_utf8(hex::decode(hex_str).unwrap()).unwrap() } #[tokio::main] async fn main() { let client = redis::Client::open("redis://redis/").unwrap(); let pool = PgPoolOptions::new() .max_connections(5) .connect("postgres://solana:solana@db/solana") .await .unwrap(); let mut cl_last_id: String = ">".to_string(); let mut gm_last_id: String = ">".to_string(); let conn_res = client.get_connection();
random
[ { "content": "/// Recomputes root of the Merkle tree from Node & proof\n\npub fn recompute(mut leaf: Node, proof: &[Node], index: u32) -> Node {\n\n for (i, s) in proof.iter().enumerate() {\n\n if index >> i & 1 == 0 {\n\n let res = hashv(&[&leaf, s.as_ref()]);\n\n leaf.copy_from...
Rust
tapdance-rust-logic/src/util.rs
refraction-networking/tapdance
39262efa194b520f3187ad98cab8efb953eccf39
extern crate libc; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use mio::Ready; use mio::unix::UnixReady; use pnet::packet::Packet; use pnet::packet::tcp::{TcpOptionNumbers, TcpPacket}; pub fn all_unix_events() -> UnixReady { UnixReady::from(Ready::readable() | Ready::writable()) | UnixReady::hup() | UnixReady::error() } pub fn all_but_writable() -> Ready { Ready::from(UnixReady::from(Ready::readable()) | UnixReady::hup() | UnixReady::error()) } pub fn all_but_readable() -> UnixReady { UnixReady::from(Ready::writable()) | UnixReady::hup() | UnixReady::error() } pub fn hup_and_error() -> Ready { Ready::from(UnixReady::hup() | UnixReady::error()) } #[inline] pub fn inet_htoa(ip: u32) -> String { format!("{}.{}.{}.{}", (ip >> 24) & 0xff, (ip >> 16) & 0xff, (ip >> 8) & 0xff, (ip) & 0xff) } #[inline] pub fn deser_be_u32_slice(arr: &[u8]) -> u32 { if arr.len() != 4 { error!("deser_be_u32_slice given bad slice. length: {}", arr.len()); return 0; } (arr[0] as u32) << 24 | (arr[1] as u32) << 16 | (arr[2] as u32) << 8 | (arr[3] as u32) } #[inline] pub fn deser_be_u32(arr: &[u8; 4]) -> u32 { (arr[0] as u32) << 24 | (arr[1] as u32) << 16 | (arr[2] as u32) << 8 | (arr[3] as u32) } pub fn get_tcp_timestamps(tcp_pkt: &TcpPacket) -> (u32, u32) { match tcp_pkt.get_options_iter() .find(|x| x.get_number() == TcpOptionNumbers::TIMESTAMPS) { Some(p) => (deser_be_u32_slice(&p.payload()[0..4]), deser_be_u32_slice(&p.payload()[4..8])), None => (0, 0), } } pub fn tcp_seq_is_wrapped(s1: u32, s2: u32) -> bool { ((s1 as i64) - (s2 as i64)).abs() > 2147483648 } pub fn tcp_seq_lte(a: u32, b: u32) -> bool { if a == b { true } else { let res = a < b; if tcp_seq_is_wrapped(a, b) { !res } else { res } } } pub fn tcp_seq_lt(a: u32, b: u32) -> bool { if a == b { false } else { let res = a < b; if tcp_seq_is_wrapped(a, b) { !res } else { res } } } pub fn mem_used_kb() -> u64 { let my_pid: i32 = unsafe { libc::getpid() }; let f = match File::open(format!("/proc/{}/status", my_pid)) { Ok(f) => f, Err(e) => { error!("Failed to open /proc/{}/status: {:?}", my_pid, e); return 0; } }; let buf_f = BufReader::new(f); for l in buf_f.lines() { if let Ok(line) = l { if line.contains("VmRSS") { let (_, vmrss_gone) = line.split_at(6); let starts_at_number = vmrss_gone.trim_left(); if let Some(kb_ind) = starts_at_number.find("kB") { let (kb_gone, _) = starts_at_number.split_at(kb_ind); let just_number = kb_gone.trim_right(); if let Ok(as_u64) = just_number.parse::<u64>() { return as_u64; } } } } else { error!("Error reading /proc/{}/status", my_pid); return 0; } } error!("Failed to parse a VmRSS value out of /proc/{}/status!", my_pid); return 0; } #[cfg(test)] mod tests { use util; #[test] fn mem_used_kb_parses_something() { assert!(util::mem_used_kb() > 0); } }
extern crate libc; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use mio::Ready; use mio::unix::UnixReady; use pnet::packet::Packet; use pnet::packet::tcp::{TcpOptionNumbers, TcpPacket}; pub fn all_unix_events() -> UnixReady { UnixReady::from(Ready::readable() | Ready::writable()) | UnixReady::hup() | UnixReady::error() } pub fn all_but_writable() -> Ready { Ready::from(UnixReady::from(Ready::readable()) | UnixReady::hup() | UnixReady::error()) } pub fn all_but_readable() -> UnixReady { UnixReady::from(Ready::writable()) | UnixReady::hup() | UnixReady::error() } pub fn hup_and_error() -> Ready { Ready::from(UnixReady::hup() | UnixReady::error()) } #[inline] pub fn inet_htoa(ip: u32) -> String { format!("{}.{}.{}.{}", (ip >> 24) & 0xff, (ip >> 16) & 0xff, (ip >> 8) & 0xff, (ip) & 0xff) } #[inline] pub fn deser_be_u32_slice(arr: &[u8]) -> u32 { if arr.len() != 4 { error!("deser_be_u32_slice given bad slice. length: {}", arr.len()); return 0; } (arr[0] as u32) << 24 | (arr[1] as u32) << 16 | (arr[2] as u32) << 8 | (arr[3] as u32) } #[inline] pub fn deser_be_u32(arr: &[u8; 4]) -> u32 { (arr[0] as u32) << 24 | (arr[1] as u32) << 16 | (arr[2] as u32) << 8 | (arr[3] as u32) } pub fn get_tcp_timestamps(tcp_pkt: &TcpPacket) -> (u32, u32) { match tcp_pkt.get_options_iter() .find(|x| x.get_number() == TcpOptionNumbers::TIMESTAMPS) { Some(p) => (deser_be_u32_slice(&p.payload()[0..4]), deser_be_u32_slice(&p.payload()[4..8])), None => (0, 0), } } pub fn tcp_seq_is_wrapped(s1: u32, s2: u32) -> bool { ((s1 as i64) - (s2 as i64)).abs() > 2147483648 } pub fn tcp_seq_lte(a: u32, b: u32) -> bool { if a == b { true } else { let res = a < b; if tcp_seq_is_wrapped(a, b) { !res } else { res } } }
pub fn mem_used_kb() -> u64 { let my_pid: i32 = unsafe { libc::getpid() }; let f = match File::open(format!("/proc/{}/status", my_pid)) { Ok(f) => f, Err(e) => { error!("Failed to open /proc/{}/status: {:?}", my_pid, e); return 0; } }; let buf_f = BufReader::new(f); for l in buf_f.lines() { if let Ok(line) = l { if line.contains("VmRSS") { let (_, vmrss_gone) = line.split_at(6); let starts_at_number = vmrss_gone.trim_left(); if let Some(kb_ind) = starts_at_number.find("kB") { let (kb_gone, _) = starts_at_number.split_at(kb_ind); let just_number = kb_gone.trim_right(); if let Ok(as_u64) = just_number.parse::<u64>() { return as_u64; } } } } else { error!("Error reading /proc/{}/status", my_pid); return 0; } } error!("Failed to parse a VmRSS value out of /proc/{}/status!", my_pid); return 0; } #[cfg(test)] mod tests { use util; #[test] fn mem_used_kb_parses_something() { assert!(util::mem_used_kb() > 0); } }
pub fn tcp_seq_lt(a: u32, b: u32) -> bool { if a == b { false } else { let res = a < b; if tcp_seq_is_wrapped(a, b) { !res } else { res } } }
function_block-full_function
[ { "content": "// Pass in 1st, 2nd bytes of the TL (big-endian). Returns is_proto, len.\n\n// The len returned might be 0, meaning extended TL.\n\npub fn parse_typelen(byte1: u8, byte2: u8) -> (bool, usize)\n\n{\n\n let tl = unsafe { mem::transmute::<[u8;2], i16>([byte2, byte1]) };\n\n if tl >= 0 {\n\n ...
Rust
src/models/withdrawal.rs
nervina-labs/compact-nft-aggregator
f5d4afebd732fdcd55c7590ddfc5af0eb30b2eda
use super::helper::{parse_cota_id_and_token_index_pairs, parse_lock_hash}; use crate::models::block::get_syncer_tip_block_number; use crate::models::helper::{generate_crc, PAGE_SIZE}; use crate::models::scripts::get_script_map_by_ids; use crate::models::{DBResult, DBTotalResult}; use crate::schema::withdraw_cota_nft_kv_pairs::dsl::withdraw_cota_nft_kv_pairs; use crate::schema::withdraw_cota_nft_kv_pairs::*; use crate::utils::error::Error; use crate::utils::helper::{diff_time, parse_bytes_n}; use crate::POOL; use chrono::prelude::*; use diesel::*; use log::error; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Queryable, Debug, Clone)] pub struct WithdrawCotaNft { pub cota_id: String, pub token_index: u32, pub out_point: String, pub state: u8, pub configure: u8, pub characteristic: String, pub receiver_lock_script_id: i64, pub version: u8, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct WithdrawDb { pub cota_id: [u8; 20], pub token_index: [u8; 4], pub out_point: [u8; 24], pub state: u8, pub configure: u8, pub characteristic: [u8; 20], pub receiver_lock_script: Vec<u8>, pub version: u8, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct WithdrawNFTDb { pub cota_id: [u8; 20], pub token_index: [u8; 4], pub out_point: [u8; 24], pub state: u8, pub configure: u8, pub characteristic: [u8; 20], } pub fn get_withdrawal_cota_by_lock_hash( lock_hash_: [u8; 32], cota_id_and_token_index_pairs: Option<Vec<([u8; 20], [u8; 4])>>, ) -> DBResult<WithdrawDb> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let (lock_hash_hex, lock_hash_crc_) = parse_lock_hash(lock_hash_); let mut withdraw_nfts: Vec<WithdrawCotaNft> = vec![]; match cota_id_and_token_index_pairs { Some(pairs) => { let pair_vec = parse_cota_id_and_token_index_pairs(pairs); for (cota_id_str, token_index_u32) in pair_vec.into_iter() { let cota_id_crc_ = generate_crc(cota_id_str.as_bytes()); let withdrawals: Vec<WithdrawCotaNft> = withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(cota_id_crc.eq(cota_id_crc_)) .filter(token_index.eq(token_index_u32)) .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex.clone())) .filter(cota_id.eq(cota_id_str)) .order(updated_at.desc()) .limit(1) .load::<WithdrawCotaNft>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; if !withdrawals.is_empty() { let withdrawal = withdrawals.get(0).unwrap().clone(); withdraw_nfts.push(withdrawal); } } } None => { let mut page: i64 = 0; loop { let withdrawals_page: Vec<WithdrawCotaNft> = withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex.clone())) .limit(PAGE_SIZE) .offset(PAGE_SIZE * page) .load::<WithdrawCotaNft>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let length = withdrawals_page.len(); withdraw_nfts.extend(withdrawals_page); if length < (PAGE_SIZE as usize) { break; } page += 1; } } }; diff_time(start_time, "SQL get_withdrawal_cota_by_lock_hash"); parse_withdraw_db(withdraw_nfts) } pub fn get_withdrawal_cota_by_cota_ids( lock_hash_: [u8; 32], cota_ids: Vec<[u8; 20]>, page: i64, page_size: i64, ) -> DBTotalResult<WithdrawDb> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let (lock_hash_hex, lock_hash_crc_) = parse_lock_hash(lock_hash_); let cota_ids_: Vec<String> = cota_ids .into_iter() .map(|cota_id_| hex::encode(&cota_id_)) .collect(); let total: i64 = withdraw_cota_nft_kv_pairs .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex.clone())) .filter(cota_id.eq_any(cota_ids_.clone())) .count() .get_result::<i64>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let withdraw_cota_nfts: Vec<WithdrawCotaNft> = withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex)) .filter(cota_id.eq_any(cota_ids_)) .order(updated_at.desc()) .limit(page_size) .offset(page_size * page) .load::<WithdrawCotaNft>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let (withdrawals, block_height) = parse_withdraw_db(withdraw_cota_nfts)?; diff_time(start_time, "SQL get_withdrawal_cota_by_cota_ids"); Ok((withdrawals, total, block_height)) } pub fn get_withdrawal_cota_by_script_id( script_id: i64, cota_id_opt: Option<[u8; 20]>, ) -> DBTotalResult<WithdrawNFTDb> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let total_result = match cota_id_opt { Some(cota_id_) => withdraw_cota_nft_kv_pairs .filter(receiver_lock_script_id.eq(script_id)) .filter(cota_id.eq(hex::encode(&cota_id_))) .count() .get_result::<i64>(conn), None => withdraw_cota_nft_kv_pairs .filter(receiver_lock_script_id.eq(script_id)) .count() .get_result::<i64>(conn), }; let total: i64 = total_result.map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let withdraw_cota_nfts_result = match cota_id_opt { Some(cota_id_) => withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(receiver_lock_script_id.eq(script_id)) .filter(cota_id.eq(hex::encode(&cota_id_))) .order(updated_at.desc()) .load::<WithdrawCotaNft>(conn), None => withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(receiver_lock_script_id.eq(script_id)) .order(updated_at.desc()) .load::<WithdrawCotaNft>(conn), }; let withdraw_cota_nfts: Vec<WithdrawCotaNft> = withdraw_cota_nfts_result.map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let withdrawals = parse_withdraw_cota_nft(withdraw_cota_nfts); let block_height = get_syncer_tip_block_number()?; diff_time(start_time, "SQL get_withdrawal_cota_by_script_id"); Ok((withdrawals, total, block_height)) } pub fn get_sender_lock_by_script_id( script_id: i64, cota_id_: [u8; 20], token_index_: [u8; 4], ) -> Result<Option<String>, Error> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let cota_id_hex = hex::encode(cota_id_); let token_index_u32 = u32::from_be_bytes(token_index_); let cota_id_crc_u32 = generate_crc(cota_id_hex.as_bytes()); let lock_hashes: Vec<String> = withdraw_cota_nft_kv_pairs .select(lock_hash) .filter(cota_id_crc.eq(cota_id_crc_u32)) .filter(token_index.eq(token_index_u32)) .filter(cota_id.eq(cota_id_hex)) .filter(receiver_lock_script_id.eq(script_id)) .order(updated_at.desc()) .limit(1) .load::<String>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; diff_time(start_time, "SQL get_sender_lock_by_script_id"); Ok(lock_hashes.get(0).cloned()) } fn parse_withdraw_db(withdrawals: Vec<WithdrawCotaNft>) -> DBResult<WithdrawDb> { let block_height = get_syncer_tip_block_number()?; if withdrawals.is_empty() { return Ok((vec![], block_height)); } let receiver_lock_script_ids: Vec<i64> = withdrawals .iter() .map(|withdrawal| withdrawal.receiver_lock_script_id) .collect(); let mut withdraw_db_vec: Vec<WithdrawDb> = vec![]; let script_map = get_script_map_by_ids(receiver_lock_script_ids)?; for withdrawal in withdrawals { let lock_script = script_map .get(&withdrawal.receiver_lock_script_id) .ok_or(Error::DatabaseQueryError("scripts".to_owned()))? .clone(); withdraw_db_vec.push(WithdrawDb { cota_id: parse_bytes_n::<20>(withdrawal.cota_id).unwrap(), token_index: withdrawal.token_index.to_be_bytes(), configure: withdrawal.configure, state: withdrawal.state, characteristic: parse_bytes_n::<20>(withdrawal.characteristic).unwrap(), receiver_lock_script: lock_script, out_point: parse_bytes_n::<24>(withdrawal.out_point).unwrap(), version: withdrawal.version, }) } Ok((withdraw_db_vec, block_height)) } fn parse_withdraw_cota_nft(withdrawals: Vec<WithdrawCotaNft>) -> Vec<WithdrawNFTDb> { if withdrawals.is_empty() { return vec![]; } let withdraw_db_vec: Vec<WithdrawNFTDb> = withdrawals .into_iter() .map(|withdrawal| WithdrawNFTDb { cota_id: parse_bytes_n::<20>(withdrawal.cota_id).unwrap(), token_index: withdrawal.token_index.to_be_bytes(), configure: withdrawal.configure, state: withdrawal.state, characteristic: parse_bytes_n::<20>(withdrawal.characteristic).unwrap(), out_point: parse_bytes_n::<24>(withdrawal.out_point).unwrap(), }) .collect(); withdraw_db_vec } fn get_selection() -> ( cota_id, token_index, out_point, state, configure, characteristic, receiver_lock_script_id, version, ) { ( cota_id, token_index, out_point, state, configure, characteristic, receiver_lock_script_id, version, ) }
use super::helper::{parse_cota_id_and_token_index_pairs, parse_lock_hash}; use crate::models::block::get_syncer_tip_block_number; use crate::models::helper::{generate_crc, PAGE_SIZE}; use crate::models::scripts::get_script_map_by_ids; use crate::models::{DBResult, DBTotalResult}; use crate::schema::withdraw_cota_nft_kv_pairs::dsl::withdraw_cota_nft_kv_pairs; use crate::schema::withdraw_cota_nft_kv_pairs::*; use crate::utils::error::Error; use crate::utils::helper::{diff_time, parse_bytes_n}; use crate::POOL; use chrono::prelude::*; use diesel::*; use log::error; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Queryable, Debug, Clone)] pub struct WithdrawCotaNft { pub cota_id: String, pub token_index: u32, pub out_point: String, pub state: u8, pub configure: u8, pub characteristic: String, pub receiver_lock_script_id: i64, pub version: u8, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct WithdrawDb { pub cota_id: [u8; 20], pub token_index: [u8; 4], pub out_point: [u8; 24], pub state: u8, pub configure: u8, pub characteristic: [u8; 20], pub receiver_lock_script: Vec<u8>, pub version: u8, } #[derive(Debug, Clone, Eq, PartialEq)] pub struct WithdrawNFTDb { pub cota_id: [u8; 20], pub token_index: [u8; 4], pub out_point: [u8; 24], pub state: u8, pub configure: u8, pub characteristic: [u8; 20], } pub fn get_withdrawal_cota_by_lock_hash( lock_hash_: [u8; 32], cota_id_and_token_index_pairs: Option<Vec<([u8; 20], [u8; 4])>>, ) -> DBResult<WithdrawDb> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let (lock_hash_hex, lock_hash_crc_) = parse_lock_hash(lock_hash_); let mut withdraw_nfts: Vec<WithdrawCotaNft> = vec![]; match cota_id_and_token_index_pairs { Some(pairs) => { let pair_vec = parse_cota_id_and_token_index_pairs(pairs); for (cota_id_str, token_index_u32) in pair_vec.into_iter() { let cota_id_crc_ = generate_crc(cota_id_str.as_bytes()); let withdrawals: Vec<WithdrawCotaNft> = withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(cota_id_crc.eq(cota_id_crc_)) .filter(token_index.eq(token_index_u32)) .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex.clone())) .filter(cota_id.eq(cota_id_str)) .order(updated_at.desc()) .limit(1) .load::<WithdrawCotaNft>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; if !withdrawals.is_empty() { let withdrawal = withdrawals.get(0).unwrap().clone(); withdraw_nfts.push(withdrawal); } } } None => { let mut page: i64 = 0; loop { let withdrawals_page: Vec<WithdrawCotaNft> = withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex.clone())) .limit(PAGE_SIZE) .offset(PAGE_SIZE * page) .load::<WithdrawCotaNft>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let length = withdrawals_page.len(); withdraw_nfts.extend(withdrawals_page); if length < (PAGE_SIZE as usize) { break; } page += 1; } } }; diff_time(start_time, "SQL get_withdrawal_cota_by_lock_hash"); parse_withdraw_db(withdraw_nfts) } pub fn get_withdrawal_cota_by_cota_ids( lock_hash_: [u8; 32], cota_ids: Vec<[u8; 20]>, page: i64, page_size: i64, ) -> DBTotalResult<WithdrawDb> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let (lock_hash_hex, lock_hash_crc_) = parse_lock_hash(lock_hash_); let cota_ids_: Vec<String> = cota_ids .into_iter() .map(|cota_id_| hex::encode(&cota_id_)) .collect(); let total: i64 = withdraw_cota_nft_kv_pairs .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex.clone())) .filter(cota_id.eq_any(cota_ids_.clone())) .count() .get_result::<i64>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let withdraw_cota_nfts: Vec<WithdrawCotaNft> = withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(lock_hash_crc.eq(lock_hash_crc_)) .filter(lock_hash.eq(lock_hash_hex)) .filter(cota_id.eq_any(cota_ids_)) .order(updated_at.desc()) .limit(page_size) .offset(page_size * page) .load::<WithdrawCotaNft>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let (withdrawals, block_height) = parse_withdraw_db(withdraw_cota_nfts)?; diff_time(start_time, "SQL get_withdrawal_cota_by_cota_ids"); Ok((withdrawals, total, block_height)) } pub fn get_withdrawal_cota_by_script_id( script_id: i64, cota_id_opt: Option<[u8; 20]>, ) -> DBTotalResult<WithdrawNFTDb> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let total_result = match cota_id_opt { Some(cota_id_) => withdraw_cota_nft_kv_pairs .filter(receiver_lock_script_id.eq(script_id)) .filter(cota_id.eq(hex::encode(&cota_id_))) .count() .get_result::<i64>(conn), None => withdraw_cota_nft_kv_pairs .filter(receiver_lock_script_id.eq(script_id)) .count() .get_result::<i64>(conn), }; let total: i64 = total_result.map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let withdraw_cota_nfts_result = match cota_id_opt { Some(cota_id_) => withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(receiver_lock_script_id.eq(script_id)) .filter(cota_id.eq(hex::encode(&cota_id_))) .order(updated_at.desc()) .load::<WithdrawCotaNft>(conn), None => withdraw_cota_nft_kv_pairs .select(get_selection()) .filter(receiver_lock_script_id.eq(script_id)) .order(updated_at.desc()) .load::<WithdrawCotaNft>(conn), }; let withdraw_cota_nfts: Vec<WithdrawCotaNft> = withdraw_cota_nfts_result.map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; let withdrawals = parse_withdraw_cota_nft(withdraw_cota_nfts); let block_height = get_syncer_tip_block_number()?; diff_time(start_time, "SQL get_withdrawal_cota_by_script_id"); Ok((withdrawals, total, block_height)) }
fn parse_withdraw_db(withdrawals: Vec<WithdrawCotaNft>) -> DBResult<WithdrawDb> { let block_height = get_syncer_tip_block_number()?; if withdrawals.is_empty() { return Ok((vec![], block_height)); } let receiver_lock_script_ids: Vec<i64> = withdrawals .iter() .map(|withdrawal| withdrawal.receiver_lock_script_id) .collect(); let mut withdraw_db_vec: Vec<WithdrawDb> = vec![]; let script_map = get_script_map_by_ids(receiver_lock_script_ids)?; for withdrawal in withdrawals { let lock_script = script_map .get(&withdrawal.receiver_lock_script_id) .ok_or(Error::DatabaseQueryError("scripts".to_owned()))? .clone(); withdraw_db_vec.push(WithdrawDb { cota_id: parse_bytes_n::<20>(withdrawal.cota_id).unwrap(), token_index: withdrawal.token_index.to_be_bytes(), configure: withdrawal.configure, state: withdrawal.state, characteristic: parse_bytes_n::<20>(withdrawal.characteristic).unwrap(), receiver_lock_script: lock_script, out_point: parse_bytes_n::<24>(withdrawal.out_point).unwrap(), version: withdrawal.version, }) } Ok((withdraw_db_vec, block_height)) } fn parse_withdraw_cota_nft(withdrawals: Vec<WithdrawCotaNft>) -> Vec<WithdrawNFTDb> { if withdrawals.is_empty() { return vec![]; } let withdraw_db_vec: Vec<WithdrawNFTDb> = withdrawals .into_iter() .map(|withdrawal| WithdrawNFTDb { cota_id: parse_bytes_n::<20>(withdrawal.cota_id).unwrap(), token_index: withdrawal.token_index.to_be_bytes(), configure: withdrawal.configure, state: withdrawal.state, characteristic: parse_bytes_n::<20>(withdrawal.characteristic).unwrap(), out_point: parse_bytes_n::<24>(withdrawal.out_point).unwrap(), }) .collect(); withdraw_db_vec } fn get_selection() -> ( cota_id, token_index, out_point, state, configure, characteristic, receiver_lock_script_id, version, ) { ( cota_id, token_index, out_point, state, configure, characteristic, receiver_lock_script_id, version, ) }
pub fn get_sender_lock_by_script_id( script_id: i64, cota_id_: [u8; 20], token_index_: [u8; 4], ) -> Result<Option<String>, Error> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let cota_id_hex = hex::encode(cota_id_); let token_index_u32 = u32::from_be_bytes(token_index_); let cota_id_crc_u32 = generate_crc(cota_id_hex.as_bytes()); let lock_hashes: Vec<String> = withdraw_cota_nft_kv_pairs .select(lock_hash) .filter(cota_id_crc.eq(cota_id_crc_u32)) .filter(token_index.eq(token_index_u32)) .filter(cota_id.eq(cota_id_hex)) .filter(receiver_lock_script_id.eq(script_id)) .order(updated_at.desc()) .limit(1) .load::<String>(conn) .map_err(|e| { error!("Query withdraw error: {}", e.to_string()); Error::DatabaseQueryError(e.to_string()) })?; diff_time(start_time, "SQL get_sender_lock_by_script_id"); Ok(lock_hashes.get(0).cloned()) }
function_block-full_function
[ { "content": "pub fn parse_cota_id_and_token_index_pairs(pairs: Vec<([u8; 20], [u8; 4])>) -> Vec<(String, u32)> {\n\n pairs\n\n .into_iter()\n\n .map(|pair| (hex::encode(pair.0), u32::from_be_bytes(pair.1)))\n\n .collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\...
Rust
src/cluster/cut.rs
FridgeSeal/blip
0a202eb0061d8e2ac34a4bd501cfa08051cb4087
use super::{proto, Metadata, State}; use futures::stream::{unfold, Stream}; use rand::{thread_rng, Rng}; use std::{ collections::HashMap, convert::TryInto, net::SocketAddr, ops::Index, result, sync::{Arc, Weak}, }; use thiserror::Error; use tokio::sync::{ broadcast::{error::RecvError, Receiver}, RwLock, }; use tonic::transport::{self, Channel, ClientTlsConfig}; pub(crate) type Result = result::Result<(), Closed>; #[derive(Copy, Clone, Debug, Error)] #[error("closed")] pub struct Closed; pub struct Subscription { state: Weak<RwLock<State>>, rx: Receiver<MultiNodeCut>, } impl Subscription { pub(crate) fn new(state: Weak<RwLock<State>>, rx: Receiver<MultiNodeCut>) -> Self { Self { state, rx } } pub async fn recv(&mut self) -> result::Result<MultiNodeCut, Closed> { let n = match self.rx.recv().await { Ok(view_change) => { return Ok(view_change); } Err(RecvError::Closed) => { return Err(Closed); } Err(RecvError::Lagged(n)) => n, }; let state = self.state.upgrade().ok_or(Closed)?; let state = state.read().await; let mut cut = state.last_cut.clone().ok_or(Closed)?; cut.skipped = n; Ok(cut) } pub fn into_stream(self) -> impl Stream<Item = MultiNodeCut> { unfold(self, |mut s| async { Some((s.recv().await.ok()?, s)) }) } pub fn as_stream(&mut self) -> impl Stream<Item = MultiNodeCut> + '_ { unfold(self, |s| async { Some((s.recv().await.ok()?, s)) }) } } #[derive(Clone, Debug)] pub struct MultiNodeCut { pub(crate) skipped: u64, pub(crate) local_addr: SocketAddr, pub(crate) conf_id: u64, pub(crate) degraded: bool, pub(crate) members: Arc<[Member]>, pub(crate) joined: Arc<[Member]>, pub(crate) kicked: Arc<[Member]>, } impl Index<SocketAddr> for MultiNodeCut { type Output = Member; #[inline] fn index(&self, addr: SocketAddr) -> &Self::Output { self.lookup(addr).unwrap() } } impl MultiNodeCut { pub fn skipped(&self) -> u64 { self.skipped } pub fn local_addr(&self) -> SocketAddr { self.local_addr } pub fn conf_id(&self) -> u64 { self.conf_id } pub fn is_degraded(&self) -> bool { self.degraded } pub(crate) fn random_member(&self) -> &Member { &self.members[thread_rng().gen_range(0..self.members.len())] } pub fn members(&self) -> &Arc<[Member]> { &self.members } pub fn joined(&self) -> &Arc<[Member]> { &self.joined } pub fn kicked(&self) -> &Arc<[Member]> { &self.kicked } pub fn with_meta<K: AsRef<str>>(&self, key: K) -> impl Iterator<Item = (&Member, &[u8])> { self.members.iter().filter_map(move |m| { let val = m.meta.get(key.as_ref())?; Some((m, val.as_ref())) }) } pub fn lookup(&self, addr: SocketAddr) -> Option<&Member> { self.members .binary_search_by_key(&addr, |m| m.addr()) .ok() .map(|i| &self.members[i]) } } #[derive(Clone, Debug)] pub struct Member { addr: SocketAddr, tls: Option<Arc<ClientTlsConfig>>, meta: Metadata, chan: Channel, } impl From<&Member> for proto::Endpoint { #[inline] fn from(Member { addr, tls, .. }: &Member) -> Self { Self::from(*addr).tls(tls.is_some()) } } impl From<&Member> for transport::Endpoint { #[inline] fn from(Member { addr, tls, .. }: &Member) -> Self { endpoint(*addr, tls.as_deref()) } } #[inline] fn endpoint(addr: SocketAddr, tls: Option<&ClientTlsConfig>) -> transport::Endpoint { match tls.cloned() { Some(tls) => format!("https://{}", addr) .try_into() .map(|e: transport::Endpoint| e.tls_config(tls).unwrap()), None => format!("http://{}", addr).try_into(), } .unwrap() } impl Member { #[inline] pub(crate) fn new(addr: SocketAddr, tls: Option<Arc<ClientTlsConfig>>, meta: Metadata) -> Self { let chan = endpoint(addr, tls.as_deref()) .connect_lazy() .unwrap(); #[rustfmt::skip] let m = Self { addr, tls, meta, chan }; m } pub fn addr(&self) -> SocketAddr { self.addr } pub fn tls_config(&self) -> Option<&ClientTlsConfig> { self.tls.as_deref() } pub fn metadata(&self) -> &HashMap<String, Vec<u8>> { &self.meta.keys } pub fn channel(&self) -> Channel { self.chan.clone() } }
use super::{proto, Metadata, State}; use futures::stream::{unfold, Stream}; use rand::{thread_rng, Rng}; use std::{ collections::HashMap, convert::TryInto, net::SocketAddr, ops::Index, result, sync::{Arc, Weak}, }; use thiserror::Error; use tokio::sync::{ broadcast::{error::RecvError, Receiver}, RwLock, }; use tonic::transport::{self, Channel, ClientTlsConfig}; pub(crate) type Result = result::Result<(), Closed>; #[derive(Copy, Clone, Debug, Error)] #[error("closed")] pub struct Closed; pub struct Subscription { state: Weak<RwLock<State>>, rx: Receiver<MultiNodeCut>, } impl Subscription { pub(crate) fn new(state: Weak<RwLock<State>>, rx: Receiver<MultiNodeCut>) -> Self { Self { state, rx } } pub async fn recv(&mut self) -> result::Result<MultiNodeCut, Closed> { let n = match self.rx.recv().await { Ok(view_change) => { return Ok(view_change); } Err(RecvError::Closed) => { return Err(Closed); } Err(RecvError::Lagged(n)) => n, }; let state = self.state.upgrade().ok_or(Closed)?; let state = state.read().await; let mut cut = state.last_cut.clone().ok_or(Closed)?; cut.skipped = n; Ok(cut) } pub fn into_stream(self) -> impl Stream<Item = MultiNodeCut> { unfold(self, |mut s| async { Some((s.recv().await.ok()?, s)) }) } pub fn as_stream(&mut self) -> impl Stream<Item = MultiNodeCut> + '_ { unfold(self, |s| async { Some((s.recv().await.ok()?, s)) }) } } #[derive(Clone, Debug)] pub struct MultiNodeCut { pub(crate) skipped: u64, pub(crate) local_addr: SocketAddr, pub(crate) conf_id: u64, pub(crate) degraded: bool, pub(crate) members: Arc<[Member]>, pub(crate) joined: Arc<[Member]>, pub(crate) kicked: Arc<[Member]>, } impl Index<SocketAddr> for MultiNodeCut { type Output = Member; #[inline] fn index(&self, addr: SocketAddr) -> &Self::Output { self.lookup(addr).unwrap() } } impl MultiNodeCut { pub fn skipped(&self) -> u64 { self.skipped } pub fn local_addr(&self) -> SocketAddr { self.local_addr } pub fn conf_id(&self) -> u64 { self.conf_id } pub fn is_degraded(&self) -> bool { self.degraded } pub(crate) fn random_member(&self) -> &Member { &self.members[thread_rng().gen_range(0..self.members.len())] } pub fn members(&self) -> &Arc<[Member]> { &self.members } pub fn joined(&self) -> &Arc<[Member]> { &self.joined } pub fn kicked(&self) -> &Arc<[Member]> { &self.kicked } pub fn with_meta<K: AsRef<str>>(&self, key: K) -> impl Iterator<Item = (&Member, &[u8])> { self.members.iter().filter_map(move |m| { let val = m.meta.get(key.as_ref())?; Some((m, val.as_ref())) }) } pub fn lookup(&self, addr: SocketAddr) -> Option<&Member> { self.members .binary_search_by_key(&addr, |m| m.addr()) .ok() .map(|i| &self.members[i]) } } #[derive(Clone, Debug)] pub struct Member { addr: SocketAddr, tls: Option<Arc<ClientTlsConfig>>, meta: Metadata, chan: Channel, } impl From<&Member> for proto::Endpoint { #[inline] fn from(Member { addr, tls, .. }: &Member) -> Self { Self::from(*addr).tls(tls.is_some()) } } impl From<&Member> for transport::Endpoint { #[inline] fn from(Member { addr, tls, .. }: &Member) -> Self { endpoint(*addr, tls.as_deref()) } } #[inline]
impl Member { #[inline] pub(crate) fn new(addr: SocketAddr, tls: Option<Arc<ClientTlsConfig>>, meta: Metadata) -> Self { let chan = endpoint(addr, tls.as_deref()) .connect_lazy() .unwrap(); #[rustfmt::skip] let m = Self { addr, tls, meta, chan }; m } pub fn addr(&self) -> SocketAddr { self.addr } pub fn tls_config(&self) -> Option<&ClientTlsConfig> { self.tls.as_deref() } pub fn metadata(&self) -> &HashMap<String, Vec<u8>> { &self.meta.keys } pub fn channel(&self) -> Channel { self.chan.clone() } }
fn endpoint(addr: SocketAddr, tls: Option<&ClientTlsConfig>) -> transport::Endpoint { match tls.cloned() { Some(tls) => format!("https://{}", addr) .try_into() .map(|e: transport::Endpoint| e.tls_config(tls).unwrap()), None => format!("http://{}", addr).try_into(), } .unwrap() }
function_block-full_function
[ { "content": "type ResolvedMember = Result<Member, MemberResolutionError>;\n\n\n", "file_path": "src/cluster/mod.rs", "rank": 0, "score": 134911.461126479 }, { "content": "pub fn addr_in(subnet: u32, host: u32) -> SocketAddr {\n\n let mut addr = (subnet & 0x1fff) << 12; // 11 bits of subn...
Rust
src/interpreter/internal.rs
wareya/gammakit
63d217f8ebc291844b8df69db12a03b9c906bef4
use crate::interpreter::*; impl Interpreter { pub (super) fn stack_len(&mut self) -> usize { self.top_frame.len() } pub (super) fn stack_pop_val(&mut self) -> Option<Value> { self.top_frame.pop_val() } pub (super) fn stack_pop_var(&mut self) -> Option<Variable> { self.top_frame.pop_var() } pub (super) fn stack_pop(&mut self) -> Option<StackValue> { self.top_frame.pop() } pub (super) fn stack_pop_as_val(&mut self) -> Option<Value> { match self.top_frame.pop() { Some(StackValue::Var(x)) => self.evaluate_value(x).ok(), Some(StackValue::Val(x)) => Some(x), _ => None } } pub (super) fn stack_push_val(&mut self, value : Value) { self.top_frame.push_val(value) } pub (super) fn stack_push_var(&mut self, variable : Variable) { self.top_frame.push_var(variable) } pub (super) fn stack_push(&mut self, stackvalue : StackValue) { self.top_frame.push(stackvalue) } fn call_arrow_function(&mut self, subfuncval : SubFuncVal, args : Vec<Value>, isexpr : bool) -> Result<(), String> { if let Some(binding) = self.get_trivial_arrow_binding(subfuncval.name) { match subfuncval.source { StackValue::Val(val) => { let ret = binding(ValueLoc::Static(val), args)?; if isexpr { self.stack_push_val(ret); } } StackValue::Var(source) => { let val = self.evaluate(source)?; let ret = binding(val, args)?; if isexpr { self.stack_push_val(ret); } } }; } else if let Some(binding_wrapper) = self.get_arrow_binding(subfuncval.name) { let binding = &mut *binding_wrapper.try_borrow_mut().or_else(|_| plainerr("error: tried to borrow internal function while it was borrowed elsewhere"))?; match subfuncval.source { StackValue::Val(val) => { let ret = binding(ValueLoc::Static(val), args)?; if isexpr { self.stack_push_val(ret); } } StackValue::Var(source) => { let val = self.evaluate(source)?; let ret = binding(val, args)?; if isexpr { self.stack_push_val(ret); } } }; } else { return Err(format!("error: no such arrow function `{}`", subfuncval.name)) } Ok(()) } pub (super) fn handle_func_call_or_expr(&mut self, isexpr : bool) -> Result<(), String> { let argcount = self.read_usize(); if cfg!(stack_len_debugging) && argcount+1 > self.stack_len() { return plainerr("internal error: fewer values on stack than expected in FUNCEXPR/FUNCCALL"); } let mut args = vec!(Value::Null; argcount); for i in argcount-1..=0 { args[i] = self.stack_pop_val().ok_or_else(|| minierr("internal error: expected values, got variable on stack in FUNCEXPR/FUNCCALL"))?; } let funcdata = self.stack_pop_as_val().ok_or_else(|| minierr("internal error: not enough values on stack to run instruction FUNCEXPR/FUNCCALL (after args)"))?; match funcdata { Value::Func(funcdata) => self.call_function(funcdata, args, isexpr)?, Value::InternalFunc(funcdata) => self.call_internal_function(funcdata, args, isexpr)?, Value::SubFunc(subfuncval) => self.call_arrow_function(*subfuncval, args, isexpr)?, _ => return Err(format!("internal error: value meant to hold function data in FUNCEXPR/FUNCCALL was not holding function data; {:?}", funcdata)) } Ok(()) } }
use crate::interpreter::*; impl Interpreter { pub (super) fn stack_len(&mut self) -> usize { self.top_frame.len() } pub (super) fn stack_pop_val(&mut self) -> Option<Value> { self.top_frame.pop_val() } pub (super) fn stack_pop_var(&mut self) -> Option<Variable> { self.top_frame.pop_var() } pub (super) fn stack_pop(&mut self) -> Option<StackValue> { self.top_frame.pop() } pub (super) fn stack_pop_as_val(&mut self) -> Option<Value> { match self.top_frame.pop() { Some(StackValue::Var(x)) => self.evaluate_value(x).ok(), Some(StackValue::Val(x)) => Some(x), _ => None } } pub (super) fn stack_push_val(&mut self, value : Value) { self.top_frame.push_val(value) } pub (super) fn stack_push_var(&mut self, variable : Variable) { self.top_frame.push_var(variable) } pub (super) fn stack_push(&mut self, stackvalue : StackValue) { self.top_frame.push(stackvalue) } fn call_arrow_function(&mut self, subfuncval : SubFuncVal, args : Vec<Value>, isexpr : bool) -> Result<(), String> { if let Some(binding) = self.get_trivial_arrow_binding(subfuncval.name) { match subfuncval.source { StackValue::Val(val) => { let ret = binding(ValueLoc::Static(val), args)?; if isexpr { self.stack_push_val(ret); } } StackValue::Var(source) => { let val = self.evaluate(source)?; let ret = binding(val, args)?; if isexpr { self.stack_push_val(ret); } } }; } else if let Some(binding_wrapper) = self.get_arrow_binding(subfuncval.name) { let binding = &mut *binding_wrapper.try_borrow_mut().or_else(|_| plainerr("error: tried to borrow internal function while it was borrowed elsewhere"))?; match subfuncval.source { StackValue::Val(val) => { let ret = binding(ValueLoc::Static(val), args)?; if isexpr { self.stack_push_val(ret); } } StackValue::Var(source) => { let val = self.evaluate(source)?; let ret = binding(val, args)?; if isexpr { self.stack_push_val(ret); } } }; } else { return Err(format!("error: no such arrow function `{}`", subfuncval.name)) }
s not holding function data; {:?}", funcdata)) } Ok(()) } }
Ok(()) } pub (super) fn handle_func_call_or_expr(&mut self, isexpr : bool) -> Result<(), String> { let argcount = self.read_usize(); if cfg!(stack_len_debugging) && argcount+1 > self.stack_len() { return plainerr("internal error: fewer values on stack than expected in FUNCEXPR/FUNCCALL"); } let mut args = vec!(Value::Null; argcount); for i in argcount-1..=0 { args[i] = self.stack_pop_val().ok_or_else(|| minierr("internal error: expected values, got variable on stack in FUNCEXPR/FUNCCALL"))?; } let funcdata = self.stack_pop_as_val().ok_or_else(|| minierr("internal error: not enough values on stack to run instruction FUNCEXPR/FUNCCALL (after args)"))?; match funcdata { Value::Func(funcdata) => self.call_function(funcdata, args, isexpr)?, Value::InternalFunc(funcdata) => self.call_internal_function(funcdata, args, isexpr)?, Value::SubFunc(subfuncval) => self.call_arrow_function(*subfuncval, args, isexpr)?, _ => return Err(format!("internal error: value meant to hold function data in FUNCEXPR/FUNCCALL wa
random
[ { "content": "type CompilerBinding<'a> = fn(&mut CompilerState<'a>, &ASTNode) -> Result<(), String>;\n\n\n", "file_path": "src/compiler.rs", "rank": 0, "score": 132890.84490723212 }, { "content": "pub fn default_step_result() -> StepResult\n\n{\n\n Ok(())\n\n}\n\n/// Type signature of fun...
Rust
src/terrain/main.rs
fkaa/gfx_examples
dea8a8393e34d011873b9f9c39f945dc6755f3e2
extern crate cgmath; #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate glutin; extern crate time; extern crate rand; extern crate genmesh; extern crate noise; use rand::Rng; use cgmath::FixedArray; use cgmath::{Matrix4, Point3, Vector3}; use cgmath::{Transform, AffineMatrix3}; use gfx::traits::{Stream, ToIndexSlice, ToSlice, FactoryExt}; use genmesh::{Vertices, Triangulate}; use genmesh::generators::{Plane, SharedVertex, IndexedPolygon}; use time::precise_time_s; use noise::{Seed, perlin2}; gfx_vertex!( Vertex { a_Pos@ pos: [f32; 3], a_Color@ color: [f32; 3], }); gfx_parameters!( Params { u_Model@ model: [[f32; 4]; 4], u_View@ view: [[f32; 4]; 4], u_Proj@ proj: [[f32; 4]; 4], }); fn calculate_color(height: f32) -> [f32; 3] { if height > 8.0 { [0.9, 0.9, 0.9] } else if height > 0.0 { [0.7, 0.7, 0.7] } else if height > -5.0 { [0.2, 0.7, 0.2] } else { [0.2, 0.2, 0.7] } } pub fn main() { let (mut stream, mut device, mut factory) = gfx_window_glutin::init( glutin::Window::new().unwrap()); stream.out.window.set_title("Terrain example"); let rand_seed = rand::thread_rng().gen(); let seed = Seed::new(rand_seed); let plane = Plane::subdivide(256, 256); let vertex_data: Vec<Vertex> = plane.shared_vertex_iter() .map(|(x, y)| { let h = perlin2(&seed, &[x, y]) * 32.0; Vertex { pos: [25.0 * x, 25.0 * y, h], color: calculate_color(h), } }) .collect(); let index_data: Vec<u32> = plane.indexed_polygon_iter() .triangulate() .vertices() .map(|i| i as u32) .collect(); let slice = index_data.to_slice(&mut factory, gfx::PrimitiveType::TriangleList); let mesh = factory.create_mesh(&vertex_data); let program = { let vs = gfx::ShaderSource { glsl_120: Some(include_bytes!("terrain_120.glslv")), glsl_150: Some(include_bytes!("terrain_150.glslv")), .. gfx::ShaderSource::empty() }; let fs = gfx::ShaderSource { glsl_120: Some(include_bytes!("terrain_120.glslf")), glsl_150: Some(include_bytes!("terrain_150.glslf")), .. gfx::ShaderSource::empty() }; factory.link_program_source(vs, fs).unwrap() }; let data = Params { model: Matrix4::identity().into_fixed(), view: Matrix4::identity().into_fixed(), proj: cgmath::perspective(cgmath::deg(60.0f32), stream.get_aspect_ratio(), 0.1, 1000.0 ).into_fixed(), _r: std::marker::PhantomData, }; let mut batch = gfx::batch::Full::new(mesh, program, data) .unwrap(); batch.slice = slice; batch.state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true); 'main: loop { for event in stream.out.window.poll_events() { match event { glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break 'main, glutin::Event::Closed => break 'main, _ => {}, } } let time = precise_time_s() as f32; let x = time.sin(); let y = time.cos(); let view: AffineMatrix3<f32> = Transform::look_at( &Point3::new(x * 32.0, y * 32.0, 16.0), &Point3::new(0.0, 0.0, 0.0), &Vector3::unit_z(), ); batch.params.view = view.mat.into_fixed(); stream.clear(gfx::ClearData { color: [0.3, 0.3, 0.3, 1.0], depth: 1.0, stencil: 0, }); stream.draw(&batch).unwrap(); stream.present(&mut device); } }
extern crate cgmath; #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate glutin; extern crate time; extern crate rand; extern crate genmesh; extern crate noise; use rand::Rng; use cgmath::FixedArray; use cgmath::{Matrix4, Point3, Vector3}; use cgmath::{Transform, AffineMatrix3}; use gfx::traits::{Stream, ToIndexSlice, ToSlice, FactoryExt}; use genmesh::{Vertices, Triangulate}; use genmesh::generators::{Plane, SharedVertex, IndexedPolygon}; use time::precise_time_s; use noise::{Seed, perlin2}; gfx_vertex!( Vertex { a_Pos@ pos: [f32; 3], a_Color@ color: [f32; 3], }); gfx_parameters!( Params { u_Model@ model: [[f32; 4]; 4], u_View@ view: [[f32; 4]; 4], u_Proj@ proj: [[f32; 4]; 4], }); fn
pub fn main() { let (mut stream, mut device, mut factory) = gfx_window_glutin::init( glutin::Window::new().unwrap()); stream.out.window.set_title("Terrain example"); let rand_seed = rand::thread_rng().gen(); let seed = Seed::new(rand_seed); let plane = Plane::subdivide(256, 256); let vertex_data: Vec<Vertex> = plane.shared_vertex_iter() .map(|(x, y)| { let h = perlin2(&seed, &[x, y]) * 32.0; Vertex { pos: [25.0 * x, 25.0 * y, h], color: calculate_color(h), } }) .collect(); let index_data: Vec<u32> = plane.indexed_polygon_iter() .triangulate() .vertices() .map(|i| i as u32) .collect(); let slice = index_data.to_slice(&mut factory, gfx::PrimitiveType::TriangleList); let mesh = factory.create_mesh(&vertex_data); let program = { let vs = gfx::ShaderSource { glsl_120: Some(include_bytes!("terrain_120.glslv")), glsl_150: Some(include_bytes!("terrain_150.glslv")), .. gfx::ShaderSource::empty() }; let fs = gfx::ShaderSource { glsl_120: Some(include_bytes!("terrain_120.glslf")), glsl_150: Some(include_bytes!("terrain_150.glslf")), .. gfx::ShaderSource::empty() }; factory.link_program_source(vs, fs).unwrap() }; let data = Params { model: Matrix4::identity().into_fixed(), view: Matrix4::identity().into_fixed(), proj: cgmath::perspective(cgmath::deg(60.0f32), stream.get_aspect_ratio(), 0.1, 1000.0 ).into_fixed(), _r: std::marker::PhantomData, }; let mut batch = gfx::batch::Full::new(mesh, program, data) .unwrap(); batch.slice = slice; batch.state = gfx::DrawState::new().depth(gfx::state::Comparison::LessEqual, true); 'main: loop { for event in stream.out.window.poll_events() { match event { glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break 'main, glutin::Event::Closed => break 'main, _ => {}, } } let time = precise_time_s() as f32; let x = time.sin(); let y = time.cos(); let view: AffineMatrix3<f32> = Transform::look_at( &Point3::new(x * 32.0, y * 32.0, 16.0), &Point3::new(0.0, 0.0, 0.0), &Vector3::unit_z(), ); batch.params.view = view.mat.into_fixed(); stream.clear(gfx::ClearData { color: [0.3, 0.3, 0.3, 1.0], depth: 1.0, stencil: 0, }); stream.draw(&batch).unwrap(); stream.present(&mut device); } }
calculate_color(height: f32) -> [f32; 3] { if height > 8.0 { [0.9, 0.9, 0.9] } else if height > 0.0 { [0.7, 0.7, 0.7] } else if height > -5.0 { [0.2, 0.7, 0.2] } else { [0.2, 0.2, 0.7] } }
function_block-function_prefixed
[ { "content": "fn calculate_color(height: f32) -> [f32; 3] {\n\n if height > 8.0 {\n\n [0.9, 0.9, 0.9] // white\n\n } else if height > 0.0 {\n\n [0.7, 0.7, 0.7] // greay\n\n } else if height > -5.0 {\n\n [0.2, 0.7, 0.2] // green\n\n } else {\n\n [0.2, 0.2, 0.7] // blue\n\n...
Rust
src/search/aggregations/bucket/diversified_sampler_aggregation.rs
ypenglyn/elasticsearch-dsl-rs
bff3508055fb20eb54bde78edffa69da3ccbf4eb
use crate::search::*; use crate::util::*; use std::convert::TryInto; #[derive(Debug, Clone, Serialize, PartialEq)] pub struct DiversifiedSamplerAggregation { diversified_sampler: DiversifiedSamplerAggregationInner, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] aggs: Aggregations, } #[derive(Debug, Clone, Serialize, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum ExecutionHint { Map, BytesHash, GlobalOrdinals, } #[derive(Debug, Clone, Serialize, PartialEq)] struct DiversifiedSamplerAggregationInner { field: String, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] shard_size: Option<u64>, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] max_docs_per_value: Option<u64>, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] execution_hint: Option<ExecutionHint>, } impl Aggregation { pub fn diversified_sampler(field: impl Into<String>) -> DiversifiedSamplerAggregation { DiversifiedSamplerAggregation { diversified_sampler: DiversifiedSamplerAggregationInner { field: field.into(), shard_size: None, max_docs_per_value: None, execution_hint: None, }, aggs: Aggregations::new(), } } } impl DiversifiedSamplerAggregation { pub fn shard_size(mut self, shard_size: impl TryInto<u64>) -> Self { if let Ok(shard_size) = shard_size.try_into() { self.diversified_sampler.shard_size = Some(shard_size); } self } pub fn max_docs_per_value(mut self, max_docs_per_value: impl TryInto<u64>) -> Self { if let Ok(max_docs_per_value) = max_docs_per_value.try_into() { self.diversified_sampler.max_docs_per_value = Some(max_docs_per_value); } self } pub fn execution_hint(mut self, execution_hint: ExecutionHint) -> Self { self.diversified_sampler.execution_hint = Some(execution_hint); self } add_aggregate!(); } #[cfg(test)] mod tests { use super::*; #[test] fn serialization() { assert_serialize( Aggregation::diversified_sampler("catalog_id").shard_size(50), json!({ "diversified_sampler": { "field": "catalog_id", "shard_size": 50 } }), ); assert_serialize( Aggregation::diversified_sampler("catalog_id") .shard_size(50) .max_docs_per_value(2) .execution_hint(ExecutionHint::GlobalOrdinals) .aggregate("catalog", Aggregation::terms("catalog_id")) .aggregate("brand", Aggregation::terms("brand_id")), json!({ "diversified_sampler": { "field": "catalog_id", "shard_size": 50, "max_docs_per_value": 2, "execution_hint": "global_ordinals" }, "aggs": { "catalog": { "terms": { "field": "catalog_id" } }, "brand": { "terms": { "field": "brand_id" } } } }), ); } }
use crate::search::*; use crate::util::*; use std::convert::TryInto; #[derive(Debug, Clone, Serialize, PartialEq)] pub struct DiversifiedSamplerAggregation { diversified_sampler: DiversifiedSamplerAggregationInner, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] aggs: Aggregations, } #[derive(Debug, Clone, Serialize, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum ExecutionHint { Map, BytesHash, GlobalOrdinals, } #[derive(Debug, Clone, Serialize, PartialEq)] struct DiversifiedSamplerAggregationInner { field: String, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] shard_size: Option<u64>, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] max_docs_per_value: Option<u64>, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] execution_hint: Option<ExecutionHint>, } impl Aggregation { pub fn diversified_sampler(field: impl Into<String>) -> DiversifiedSamplerAggregation { DiversifiedSamplerAggregation { diversified_sampler: DiversifiedSamplerAggregationInner { field: field.into(), shard_size: None, max_docs_per_value: None, execution_hint: None, }, aggs: Aggregations::new(), } } } impl DiversifiedSamplerAggregation { pub fn shard_size(mut sel
pub fn max_docs_per_value(mut self, max_docs_per_value: impl TryInto<u64>) -> Self { if let Ok(max_docs_per_value) = max_docs_per_value.try_into() { self.diversified_sampler.max_docs_per_value = Some(max_docs_per_value); } self } pub fn execution_hint(mut self, execution_hint: ExecutionHint) -> Self { self.diversified_sampler.execution_hint = Some(execution_hint); self } add_aggregate!(); } #[cfg(test)] mod tests { use super::*; #[test] fn serialization() { assert_serialize( Aggregation::diversified_sampler("catalog_id").shard_size(50), json!({ "diversified_sampler": { "field": "catalog_id", "shard_size": 50 } }), ); assert_serialize( Aggregation::diversified_sampler("catalog_id") .shard_size(50) .max_docs_per_value(2) .execution_hint(ExecutionHint::GlobalOrdinals) .aggregate("catalog", Aggregation::terms("catalog_id")) .aggregate("brand", Aggregation::terms("brand_id")), json!({ "diversified_sampler": { "field": "catalog_id", "shard_size": 50, "max_docs_per_value": 2, "execution_hint": "global_ordinals" }, "aggs": { "catalog": { "terms": { "field": "catalog_id" } }, "brand": { "terms": { "field": "brand_id" } } } }), ); } }
f, shard_size: impl TryInto<u64>) -> Self { if let Ok(shard_size) = shard_size.try_into() { self.diversified_sampler.shard_size = Some(shard_size); } self }
function_block-function_prefixed
[ { "content": "#[doc(hidden)]\n\npub trait Origin: Debug + PartialEq + Serialize + Clone {\n\n type Scale: Debug + PartialEq + Serialize + Clone;\n\n type Offset: Debug + PartialEq + Serialize + Clone;\n\n}\n\n\n\nimpl Origin for DateTime<Utc> {\n\n type Scale = Time;\n\n type Offset = Time;\n\n}\n\n...
Rust
utoipa-gen/src/schema/component/attr.rs
juhaku/utoipa
070b00c13b41040e9605c62a0d7c3b5fcf04899c
use std::mem; use proc_macro2::{Ident, TokenStream}; use proc_macro_error::{abort, ResultExt}; use quote::{quote, ToTokens}; use syn::{ parenthesized, parse::{Parse, ParseBuffer}, Attribute, Error, ExprPath, Token, }; use crate::{ parse_utils, schema::{ComponentPart, GenericType}, AnyValue, }; use super::xml::{Xml, XmlAttr}; #[cfg_attr(feature = "debug", derive(Debug))] pub struct ComponentAttr<T> where T: Sized, { inner: T, } impl<T> AsRef<T> for ComponentAttr<T> where T: Sized, { fn as_ref(&self) -> &T { &self.inner } } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct Enum { default: Option<AnyValue>, example: Option<AnyValue>, } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct Struct { example: Option<AnyValue>, xml_attr: Option<XmlAttr>, } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct UnnamedFieldStruct { pub(super) ty: Option<Ident>, format: Option<ExprPath>, default: Option<AnyValue>, example: Option<AnyValue>, } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct NamedField { example: Option<AnyValue>, pub(super) ty: Option<Ident>, format: Option<ExprPath>, default: Option<AnyValue>, write_only: Option<bool>, read_only: Option<bool>, xml_attr: Option<XmlAttr>, pub(super) xml: Option<Xml>, } impl Parse for ComponentAttr<Enum> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: default, example"; let mut enum_attr = Enum::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*ident.to_string(); match name { "default" => { enum_attr.default = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "example" => { enum_attr.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } _ => return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: enum_attr }) } } impl ComponentAttr<Struct> { pub(super) fn from_attributes_validated(attributes: &[Attribute]) -> Option<Self> { parse_component_attr::<ComponentAttr<Struct>>(attributes).map(|attrs| { if let Some(ref wrapped_ident) = attrs .as_ref() .xml_attr .as_ref() .and_then(|xml| xml.is_wrapped.as_ref()) { abort! {wrapped_ident, "cannot use `wrapped` attribute in non slice type"; help = "Try removing `wrapped` attribute" } } attrs }) } } impl Parse for ComponentAttr<Struct> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: example, xml"; let mut struct_ = Struct::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), &format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*ident.to_string(); match name { "example" => { struct_.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_lit_str_or_json(input) })?); } "xml" => { let xml; parenthesized!(xml in input); struct_.xml_attr = Some(xml.parse()?) } _ => return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: struct_ }) } } impl Parse for ComponentAttr<UnnamedFieldStruct> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: default, example, format, value_type"; let mut unnamed_struct = UnnamedFieldStruct::default(); while !input.is_empty() { let attribute = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*attribute.to_string(); match name { "default" => { unnamed_struct.default = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "example" => { unnamed_struct.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "format" => unnamed_struct.format = Some(parse_format(input)?), "value_type" => { unnamed_struct.ty = Some(parse_utils::parse_next(input, || input.parse::<Ident>())?) } _ => return Err(Error::new(attribute.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: unnamed_struct, }) } } impl ComponentAttr<NamedField> { pub(super) fn from_attributes_validated( attributes: &[Attribute], component_part: &ComponentPart, ) -> Option<Self> { parse_component_attr::<ComponentAttr<NamedField>>(attributes) .map(|attrs| { is_valid_xml_attr(&attrs, component_part); attrs }) .map(|mut attrs| { if matches!(component_part.generic_type, Some(GenericType::Vec)) { if let Some(ref mut xml) = attrs.inner.xml_attr { let mut value_xml = mem::take(xml); let vec_xml = XmlAttr::with_wrapped( mem::take(&mut value_xml.is_wrapped), mem::take(&mut value_xml.wrap_name), ); attrs.inner.xml = Some(Xml::Slice { vec: vec_xml, value: value_xml, }); } } else if let Some(ref mut xml) = attrs.inner.xml_attr { attrs.inner.xml = Some(Xml::NonSlice(mem::take(xml))); } attrs }) } } #[inline] fn is_valid_xml_attr(attrs: &ComponentAttr<NamedField>, component_part: &ComponentPart) { if !matches!( component_part.generic_type, Some(crate::schema::GenericType::Vec) ) { if let Some(wrapped_ident) = attrs .as_ref() .xml_attr .as_ref() .and_then(|xml| xml.is_wrapped.as_ref()) { abort! {wrapped_ident, "cannot use `wrapped` attribute in non slice field type"; help = "Try removing `wrapped` attribute or make your field `Vec`" } } } } impl Parse for ComponentAttr<NamedField> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: example, format, default, write_only, read_only, xml, value_type"; let mut field = NamedField::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*ident.to_string(); match name { "example" => { field.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?); } "format" => field.format = Some(parse_format(input)?), "default" => { field.default = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "write_only" => field.write_only = Some(parse_utils::parse_bool_or_true(input)?), "read_only" => field.read_only = Some(parse_utils::parse_bool_or_true(input)?), "xml" => { let xml; parenthesized!(xml in input); field.xml_attr = Some(xml.parse()?) } "value_type" => { field.ty = Some(parse_utils::parse_next(input, || input.parse::<Ident>())?) } _ => return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: field }) } } #[inline] fn parse_format(input: &ParseBuffer) -> Result<ExprPath, Error> { let format = parse_utils::parse_next(input, || input.parse::<ExprPath>()).map_err(|error| { Error::new( error.span(), format!( "unparseable format expected expression path e.g. ComponentFormat::String, {}", error ), ) })?; if format.path.segments.first().unwrap().ident != "utoipa" { let appended_path: ExprPath = syn::parse_quote!(utoipa::openapi::#format); Ok(appended_path) } else { Ok(format) } } pub fn parse_component_attr<T: Sized + Parse>(attributes: &[Attribute]) -> Option<T> { attributes .iter() .find(|attribute| attribute.path.get_ident().unwrap() == "component") .map(|attribute| attribute.parse_args::<T>().unwrap_or_abort()) } impl<T> ToTokens for ComponentAttr<T> where T: quote::ToTokens, { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(self.inner.to_token_stream()) } } impl ToTokens for Enum { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref default) = self.default { tokens.extend(quote! { .default(Some(#default)) }) } if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } } } impl ToTokens for Struct { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } if let Some(ref xml) = self.xml_attr { tokens.extend(quote!( .xml(Some(#xml)) )) } } } impl ToTokens for UnnamedFieldStruct { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref default) = self.default { tokens.extend(quote! { .default(Some(#default)) }) } if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } if let Some(ref format) = self.format { tokens.extend(quote! { .format(Some(#format)) }) } } } impl ToTokens for NamedField { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref default) = self.default { tokens.extend(quote! { .default(Some(#default)) }) } if let Some(ref format) = self.format { tokens.extend(quote! { .format(Some(#format)) }) } if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } if let Some(ref write_only) = self.write_only { tokens.extend(quote! { .write_only(Some(#write_only)) }) } if let Some(ref read_only) = self.read_only { tokens.extend(quote! { .read_only(Some(#read_only)) }) } } }
use std::mem; use proc_macro2::{Ident, TokenStream}; use proc_macro_error::{abort, ResultExt}; use quote::{quote, ToTokens}; use syn::{ parenthesized, parse::{Parse, ParseBuffer}, Attribute, Error, ExprPath, Token, }; use crate::{ parse_utils, schema::{ComponentPart, GenericType}, AnyValue, }; use super::xml::{Xml, XmlAttr}; #[cfg_attr(feature = "debug", derive(Debug))] pub struct ComponentAttr<T> where T: Sized, { inner: T, } impl<T> AsRef<T> for ComponentAttr<T> where T: Sized, { fn as_ref(&self) -> &T { &self.inner } } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct Enum { default: Option<AnyValue>, example: Option<AnyValue>, } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct Struct { example: Option<AnyValue>, xml_attr: Option<XmlAttr>, } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct UnnamedFieldStruct { pub(super) ty: Option<Ident>, format: Option<ExprPath>, default: Option<AnyValue>, example: Option<AnyValue>, } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct NamedField { example: Option<AnyValue>, pub(super) ty: Option<Ident>, format: Option<ExprPath>, default: Option<AnyValue>, write_only: Option<bool>, read_only: Option<bool>, xml_attr: Option<XmlAttr>, pub(super) xml: Option<Xml>, } impl Parse for ComponentAttr<Enum> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: default, example"; let mut enum_attr = Enum::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*ident.to_string(); match name { "default" => { enum_attr.default = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "example" => { enum_attr.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } _ => return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: enum_attr }) } } impl ComponentAttr<Struct> { pub(super) fn from_attributes_validated(attributes: &[Attribute]) -> Option<Self> { parse_component_attr::<ComponentAttr<Struct>>(attributes).map(|attrs| { if let Some(ref wrapped_ident) = attrs .as_ref() .xml_attr .as_ref() .and_then(|xml| xml.is_wrapped.as_ref()) { abort! {wrapped_ident, "cannot use `wrapped` attribute in non slice type"; help = "Try removing `wrapped` attribute" } } attrs }) } } impl Parse for ComponentAttr<Struct> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: example, xml"; let mut struct_ = Struct::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), &format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*ident.to_string(); match name { "example" => { struct_.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_lit_str_or_json(input) })?); } "xml" => { let xml; parenthesized!(xml in input); struct_.xml_attr = Some(xml.parse()?) } _ => return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: struct_ }) } } impl Parse for ComponentAttr<UnnamedFieldStruct> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: default, example, format, value_type"; let mut unnamed_struct = UnnamedFieldStruct::default(); while !input.is_empty() { let attribute = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*attribute.to_string(); match name { "default" => { unnamed_struct.default = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "example" => { unnamed_struct.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "format" => unnamed_struct.format = Some(parse_format(input)?), "value_type" => { unnamed_struct.ty = Some(parse_utils::parse_next(input, || input.parse::<Ident>())?) } _ => return Err(Error::new(attribute.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: unnamed_struct, }) } } impl ComponentAttr<NamedField> { pub(super) fn from_attributes_validated( attributes: &[Attribute], component_part: &ComponentPart, ) -> Option<Self> { parse_component_attr::<ComponentAttr<NamedField>>(attributes) .map(|attrs| { is_valid_xml_attr(&attrs, component_part); attrs }) .map(|mut attrs| { if matches!(component_part.generic_type, Some(GenericType::Vec)) { if let Some(ref mut xml) = attrs.inner.xml_attr { let mut value_xml = mem::take(xml); let vec_xml = XmlAttr::with_wrapped( mem::take(&mut value_xml.is_wrapped), mem::take(&mut value_xml.wrap_name), ); attrs.inner.xml = Some(Xml::Slice { vec: vec_xml, value: value_xml, }); } } else if let Some(ref mut xml) = attrs.inner.xml_attr { attrs.inner.xml = Some(Xml::NonSlice(mem::take(xml))); } attrs }) } } #[inline] fn is_valid_xml_attr(attrs: &ComponentAttr<NamedField>, component_part: &ComponentPart) { if !matches!( component_part.generic_type, Some(crate::schema::GenericType::Vec) ) { if let Some(wrapped_ident) = attrs .as_ref() .xml_attr .as_ref() .and_then(|xml| xml.is_wrapped.as_ref()) { abort! {wrapped_ident, "cannot use `wrapped` attribute in non slice field type"; help = "Try removing `wrapped` attribute or make your field `Vec`" } } } } impl Parse for ComponentAttr<NamedField> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE_MESSAGE: &str = "unexpected attribute, expected any of: example, format, default, write_only, read_only, xml, value_type"; let mut field = NamedField::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new( error.span(), format!("{}, {}", EXPECTED_ATTRIBUTE_MESSAGE, error), ) })?; let name = &*ident.to_string(); match name { "example" => { field.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?); } "format" => field.format = Some(parse_format(input)?), "default" => { field.default = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) })?) } "write_only" => field.write_only = Some(parse_utils::parse_bool_or_true(input)?), "read_only" => field.read_only = Some(parse_utils::parse_bool_or_true(input)?), "xml" => { let xml; parenthesized!(xml in input); field.xml_attr = Some(xml.parse()?) } "value_type" => { field.ty = Some(parse_utils::parse_next(input, || input.parse::<Ident>())?) } _ => return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE_MESSAGE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(Self { inner: field }) } } #[inline] fn parse_format(input: &ParseBuffer) -> Result<ExprPath, Error> { let format = parse_utils::parse_next(input, || input.parse::<ExprPath>()).map_err(|error| { Error::new( error.span(), format!( "unparseable format expected expression path e.g. ComponentFormat::String, {}", error ), ) })?; if format.path.segments.first().unwrap().ident != "utoipa" { let appended_path: ExprPath = syn::parse_quote!(utoipa::openapi::#format); Ok(appended_path) } else { Ok(format) } }
impl<T> ToTokens for ComponentAttr<T> where T: quote::ToTokens, { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(self.inner.to_token_stream()) } } impl ToTokens for Enum { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref default) = self.default { tokens.extend(quote! { .default(Some(#default)) }) } if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } } } impl ToTokens for Struct { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } if let Some(ref xml) = self.xml_attr { tokens.extend(quote!( .xml(Some(#xml)) )) } } } impl ToTokens for UnnamedFieldStruct { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref default) = self.default { tokens.extend(quote! { .default(Some(#default)) }) } if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } if let Some(ref format) = self.format { tokens.extend(quote! { .format(Some(#format)) }) } } } impl ToTokens for NamedField { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref default) = self.default { tokens.extend(quote! { .default(Some(#default)) }) } if let Some(ref format) = self.format { tokens.extend(quote! { .format(Some(#format)) }) } if let Some(ref example) = self.example { tokens.extend(quote! { .example(Some(#example)) }) } if let Some(ref write_only) = self.write_only { tokens.extend(quote! { .write_only(Some(#write_only)) }) } if let Some(ref read_only) = self.read_only { tokens.extend(quote! { .read_only(Some(#read_only)) }) } } }
pub fn parse_component_attr<T: Sized + Parse>(attributes: &[Attribute]) -> Option<T> { attributes .iter() .find(|attribute| attribute.path.get_ident().unwrap() == "component") .map(|attribute| attribute.parse_args::<T>().unwrap_or_abort()) }
function_block-full_function
[]
Rust
cosmos-abci/abci/src/lib.rs
couragetec/courage_substrate_cosmos
d9b2038436ac8933e6dadda960cd66a543c851d3
mod defaults; pub mod grpc; pub mod utils; pub use defaults::*; pub use grpc::*; use lazy_static::lazy_static; use owning_ref::MutexGuardRefMut; use std::sync::Mutex; use mockall::automock; lazy_static! { static ref ABCI_INTERFACE_INSTANCE: Mutex<Option<AIType>> = Mutex::new(None); } type AIType = Box<dyn AbciInterface + Send>; type AbciResult<T> = Result<Box<T>, Box<dyn std::error::Error>>; #[automock] pub trait ResponseFlush {} #[automock] pub trait ResponseEcho { fn get_message(&self) -> String; fn set_message(&mut self, v: String); } #[automock] pub trait ResponseCheckTx { fn get_code(&self) -> u32; fn get_data(&self) -> Vec<u8>; fn get_log(&self) -> String; fn get_info(&self) -> String; fn get_gas_wanted(&self) -> i64; fn get_gas_used(&self) -> i64; fn get_codespace(&self) -> String; fn set_code(&mut self, v: u32); fn set_data(&mut self, v: Vec<u8>); fn set_log(&mut self, v: String); fn set_info(&mut self, v: String); fn set_gas_wanted(&mut self, v: i64); fn set_gas_used(&mut self, v: i64); fn set_codespace(&mut self, v: String); } #[automock] pub trait ResponseDeliverTx { fn get_code(&self) -> u32; fn get_data(&self) -> Vec<u8>; fn get_log(&self) -> String; fn get_info(&self) -> String; fn get_gas_wanted(&self) -> i64; fn get_gas_used(&self) -> i64; fn get_codespace(&self) -> String; fn set_code(&mut self, v: u32); fn set_data(&mut self, v: Vec<u8>); fn set_log(&mut self, v: String); fn set_info(&mut self, v: String); fn set_gas_wanted(&mut self, v: i64); fn set_gas_used(&mut self, v: i64); fn set_codespace(&mut self, v: String); } #[automock] pub trait ResponseInitChain { fn get_validators(&self) -> Vec<protos::tendermint::abci::ValidatorUpdate>; } #[automock] pub trait ResponseSetOption { fn get_code(&self) -> u32; fn get_log(&self) -> String; fn get_info(&self) -> String; } #[automock] pub trait ResponseBeginBlock {} #[automock] pub trait ResponseEndBlock { fn get_validator_updates(&self) -> Vec<protos::tendermint::abci::ValidatorUpdate>; fn get_events(&self) -> Vec<protos::tendermint::abci::Event>; fn set_events(&mut self, events: Vec<protos::tendermint::abci::Event>); fn set_validator_updates( &mut self, validator_updates: Vec<protos::tendermint::abci::ValidatorUpdate>, ); } #[automock] pub trait ResponseCommit { fn get_data(&self) -> Vec<u8>; fn get_retain_height(&self) -> i64; fn set_data(&mut self, v: Vec<u8>); fn set_retain_height(&mut self, v: i64); } #[automock] pub trait ResponseInfo { fn get_version(&self) -> String; fn get_app_version(&self) -> u64; fn get_data(&self) -> String; fn get_last_block_height(&self) -> i64; fn get_last_block_app_hash(&self) -> Vec<u8>; } #[automock] pub trait ResponseQuery { fn get_code(&self) -> u32; fn get_log(&self) -> String; fn get_info(&self) -> String; fn get_index(&self) -> i64; fn get_key(&self) -> Vec<u8>; fn get_value(&self) -> Vec<u8>; fn get_height(&self) -> i64; fn get_codespace(&self) -> String; fn get_proof(&self) -> Option<protos::tendermint::crypto::ProofOps>; fn set_code(&mut self, v: u32); fn set_log(&mut self, v: String); fn set_info(&mut self, v: String); fn set_index(&mut self, v: i64); fn set_key(&mut self, v: Vec<u8>); fn set_value(&mut self, v: Vec<u8>); fn set_height(&mut self, v: i64); fn set_codespace(&mut self, v: String); } #[automock] pub trait AbciInterface { fn echo(&mut self, message: String) -> AbciResult<dyn ResponseEcho>; fn check_tx(&mut self, tx: Vec<u8>) -> AbciResult<dyn ResponseCheckTx>; fn deliver_tx(&mut self, tx: Vec<u8>) -> AbciResult<dyn ResponseDeliverTx>; fn init_chain( &mut self, time_seconds: i64, time_nanos: i32, chain_id: &str, pub_key_types: Vec<String>, max_block_bytes: i64, max_evidence_bytes: i64, max_gas: i64, max_age_num_blocks: i64, max_age_duration: u64, app_state_bytes: Vec<u8>, validators: Vec<protos::tendermint::abci::ValidatorUpdate>, app_version: u64, initial_height: i64, ) -> AbciResult<dyn ResponseInitChain>; fn set_option(&mut self, key: &str, value: &str) -> AbciResult<dyn ResponseSetOption>; fn begin_block( &mut self, height: i64, hash: Vec<u8>, last_block_id: Vec<u8>, proposer_address: Vec<u8>, active_validators: Vec<protos::tendermint::abci::VoteInfo>, ) -> AbciResult<dyn ResponseBeginBlock>; fn end_block(&mut self, height: i64) -> AbciResult<dyn ResponseEndBlock>; fn commit(&mut self) -> AbciResult<dyn ResponseCommit>; fn query( &mut self, path: String, data: Vec<u8>, height: i64, prove: bool, ) -> AbciResult<dyn ResponseQuery>; fn info(&mut self) -> AbciResult<dyn ResponseInfo>; fn flush(&mut self) -> AbciResult<dyn ResponseFlush>; } pub fn set_abci_instance<'ret>( new_instance: AIType, ) -> Result<MutexGuardRefMut<'ret, Option<AIType>, AIType>, Box<dyn std::error::Error>> { let mut instance = ABCI_INTERFACE_INSTANCE.lock()?; *instance = Some(new_instance); let res = MutexGuardRefMut::new(instance).map_mut(|mg| mg.as_mut().unwrap()); Ok(res) } pub fn get_abci_instance<'ret>( ) -> Result<MutexGuardRefMut<'ret, Option<AIType>, AIType>, Box<dyn std::error::Error>> { let instance = ABCI_INTERFACE_INSTANCE.lock()?; if instance.is_none() { panic!("abci instance has not been set, execute set_abci_instance before calling this function"); } let res = MutexGuardRefMut::new(instance).map_mut(|mg| mg.as_mut().unwrap()); Ok(res) }
mod defaults; pub mod grpc; pub mod utils; pub use defaults::*; pub use grpc::*; use lazy_static::lazy_static; use owning_ref::MutexGuardRefMut; use std::sync::Mutex; use mockall::automock; lazy_static! { static ref ABCI_INTERFACE_INSTANCE: Mutex<Option<AIType>> = Mutex::new(None); } type AIType = Box<dyn AbciInterface + Send>; type AbciResult<T> = Result<Box<T>, Box<dyn std::error::Error>>; #[automock] pub trait ResponseFlush {} #[automock] pub trait ResponseEcho { fn get_message(&self) -> String; fn set_message(&mut self, v: String); } #[automock] pub trait ResponseCheckTx { fn get_code(&self) -> u32; fn get_data(&self) -> Vec<u8>; fn get_log(&self) -> String; fn get_info(&self) -> String; fn get_gas_wanted(&self) -> i64; fn get_gas_used(&self) -> i64; fn get_codespace(&self) -> String; fn set_code(&mut self, v: u32); fn set_data(&mut self, v: Vec<u8>); fn set_log(&mut self, v: String); fn set_info(&mut self, v: String); fn set_gas_wanted(&mut self, v: i64); fn set_gas_used(&mut self, v: i64); fn set_codespace(&mut self, v: String); } #[automock] pub trait ResponseDeliverTx { fn get_code(&self) -> u32; fn get_data(&self) -> Vec<u8>; fn get_log(&self) -> String; fn get_info(&self) -> String; fn get_gas_wanted(&self) -> i64; fn get_gas_used(&self) -> i64; fn get_codespace(&self) -> String; fn set_code(&mut self, v: u32); fn set_data(&mut self, v: Vec<u8>); fn set_log(&mut self, v: String); fn set_info(&mut self, v: String); fn set_gas_wanted(&mut self, v: i64); fn set_gas_used(&mut self, v: i64); fn set_codespace(&mut self, v: String); } #[automock] pub trait ResponseInitChain { fn get_validators(&self) -> Vec<protos::tendermint::abci::ValidatorUpdate>; } #[automock] pub trait ResponseSetOption { fn get_code(&self) -> u32; fn get_log(&self) -> String; fn get_info(&self) -> String; } #[automock] pub trait ResponseBeginBlock {} #[automock] pub trait ResponseEndBlock { fn get_validator_updates(&self) -> Vec<protos::tendermint::abci::ValidatorUpdate>; fn get_events(&self) -> Vec<protos::tendermint::abci::Event>; fn set_events(&mut self, events: Vec<protos::tendermint::abci::Event>); fn set_validator_updates( &mut self, validator_updates: Vec<protos::tendermint::abci::ValidatorUpdate>, ); } #[automock] pub trait ResponseCommit { fn get_data(&self) -> Vec<u8>; fn get_retain_height(&self) -> i64; fn set_data(&mut self, v: Vec<u8>); fn set_retain_height(&mut self, v: i64); } #[automock] pub trait ResponseInfo { fn get_version(&self) -> String; fn get_app_version(&self) -> u64; fn get_data(&self) -> String; fn get_last_block_height(&self) -> i64; fn get_last_block_app_hash(&self) -> Vec<u8>; } #[automock] pub trait ResponseQuery { fn get_code(&self) -> u32; fn get_log(&self) -> String; fn get_info(&self) -> String; fn get_index(&self) -> i64; fn get_key(&self) -> Vec<u8>; fn get_value(&self) -> Vec<u8>; fn get_height(&self) -> i64; fn get_codespace(&self) -> String; fn get_proof(&self) -> Option<protos::tendermint::crypto::ProofOps>; fn set_code(&mut self, v: u32); fn set_log(&mut self, v: String); fn set_info(&mut self, v: String); fn set_index(&mut self, v: i64); fn set_key(&mut self, v: Vec<u8>); fn set_value(&mut self, v: Vec<u8>); fn set_height(&mut self, v: i64); fn set_codespace(&mut self, v: String); } #[automock] pub trait AbciInterface { fn echo(&mut self, message: String) -> AbciResult<dyn ResponseEcho>; fn check_tx(&mut self, tx: Vec<u8>) -> AbciResult<dyn ResponseCheckTx>; fn deliver_tx(&mut self, tx: Vec<u8>) -> AbciResult<dyn ResponseDeliverTx>; fn init_chain( &mut self, time_seconds: i64, time_nanos: i32, chain_id: &str, pub_key_types: Vec<String>, max_block_bytes: i64, max_evidence_bytes: i64, max_gas: i64, max_age_num_blocks: i64, max_age_duration: u64, app_state_bytes: Vec<u8>, validators: Vec<protos::tendermint::abci::ValidatorUpdate>, app_version: u64, initial_height: i64, ) -> AbciResult<dyn ResponseInitChain>; fn set_option(&mut self, key: &str, value: &str) -> AbciResult<dyn ResponseSetOption>; fn begin_block( &mut self, height: i64, hash: Vec<u8>, last_block_id: Vec<u8>, proposer_address: Vec<u8>, active_validators: Vec<protos::tendermint::abci::VoteInfo>, ) -> AbciResult<dyn ResponseBeginBlock>; fn end_block(&mut self, height: i64) -> AbciResult<dyn ResponseEndBlock>; fn commit(&mut self) -> AbciResult<dyn ResponseCommit>; fn query( &mut self, path: String, data: Vec<u8>, height: i64, prove: bool, ) -> AbciResult<dyn ResponseQuery>; fn info(&mut self) -> AbciResult<dyn ResponseInfo>; fn flush(&mut self) -> AbciResult<dyn ResponseFlush>; } pub fn set_abci_instance<'ret>( new_instance: AIType, ) -> Result<MutexGuardRefMut<'ret, Option<AIType>, AIType>, Box<dyn std::error::Error>> { let mut instance = ABCI_INTERFACE_INSTANCE.lock()?; *instance = Some(new_instance); let res = MutexGuardRefMut::new(instance).map_mut(|mg| mg.as_mut().unwrap()); Ok(res) }
pub fn get_abci_instance<'ret>( ) -> Result<MutexGuardRefMut<'ret, Option<AIType>, AIType>, Box<dyn std::error::Error>> { let instance = ABCI_INTERFACE_INSTANCE.lock()?; if instance.is_none() { panic!("abci instance has not been set, execute set_abci_instance before calling this function"); } let res = MutexGuardRefMut::new(instance).map_mut(|mg| mg.as_mut().unwrap()); Ok(res) }
function_block-full_function
[ { "content": "/// Method for getting gRPC url form active env.\n\npub fn get_server_url() -> String {\n\n crate::utils::get_option_from_node_args(crate::utils::NodeOptionVariables::AbciServerUrl)\n\n .unwrap_or_else(|| DEFAULT_ABCI_URL.to_owned())\n\n}\n\n\n", "file_path": "cosmos-abci/abci/src/de...
Rust
contracts/link-token/src/contract.rs
hackbg/chainlink-terra-cosmwasm-contracts
a1a82fa5db9942f8c8e6ec5d0b8fe7effb830f84
use cosmwasm_std::{ to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, }; use cw20::{Cw20Coin, TokenInfoResponse}; use cw20_base::{ allowances::{ execute_decrease_allowance, execute_increase_allowance, execute_transfer_from, query_allowance, }, contract::{create_accounts, execute_send, execute_transfer, query_balance}, ContractError, }; use crate::{ msg::{ExecuteMsg, InstantiateMsg, QueryMsg}, state::{TokenInfo, TOKEN_INFO}, }; pub const TOKEN_NAME: &str = "Chainlink"; pub const TOKEN_SYMBOL: &str = "LINK"; pub const DECIMALS: u8 = 18; pub const TOTAL_SUPPLY: u128 = 1_000_000_000; pub fn instantiate( mut deps: DepsMut, _env: Env, info: MessageInfo, _msg: InstantiateMsg, ) -> StdResult<Response> { let main_balance = Cw20Coin { address: info.sender.into(), amount: Uint128::from(TOTAL_SUPPLY), }; let total_supply = create_accounts(&mut deps, &[main_balance])?; let data = TokenInfo { name: TOKEN_NAME.to_string(), symbol: TOKEN_SYMBOL.to_string(), decimals: DECIMALS, total_supply, }; TOKEN_INFO.save(deps.storage, &data)?; Ok(Response::default()) } pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::Transfer { recipient, amount } => { execute_transfer(deps, env, info, recipient, amount) } ExecuteMsg::TransferFrom { owner, recipient, amount, } => execute_transfer_from(deps, env, info, owner, recipient, amount), ExecuteMsg::Send { contract, amount, msg, } => execute_send(deps, env, info, contract, amount, msg), ExecuteMsg::IncreaseAllowance { spender, amount, expires, } => execute_increase_allowance(deps, env, info, spender, amount, expires), ExecuteMsg::DecreaseAllowance { spender, amount, expires, } => execute_decrease_allowance(deps, env, info, spender, amount, expires), } } pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Balance { address } => to_binary(&query_balance(deps, address)?), QueryMsg::TokenInfo {} => to_binary(&query_token_info(deps)?), QueryMsg::Allowance { owner, spender } => { to_binary(&query_allowance(deps, owner, spender)?) } } } pub fn query_token_info(deps: Deps) -> StdResult<TokenInfoResponse> { let info = TOKEN_INFO.load(deps.storage)?; Ok(info.into()) } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coins, Uint128}; #[test] fn test_query_token_info() { let mut deps = mock_dependencies(&coins(2, "test_token")); let env = mock_env(); let info = mock_info(&"creator", &[]); let _ = instantiate(deps.as_mut(), env, info, InstantiateMsg {}).unwrap(); let query_res = query_token_info(deps.as_ref()).unwrap(); assert_eq!( query_res, TokenInfoResponse { name: "Chainlink".to_string(), symbol: "LINK".to_string(), decimals: 18, total_supply: Uint128::from(1_000_000_000_u128) } ); } }
use cosmwasm_std::{ to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, }; use cw20::{Cw20Coin, TokenInfoResponse}; use cw20_base::{ allowances::{ execute_decrease_allowance, execute_increase_allowance, execute_transfer_from, query_allowance, }, contract::{create_accounts, execute_send, execute_transfer, query_balance}, ContractError, }; use crate::{ msg::{ExecuteMsg, InstantiateMsg, QueryMsg}, state::{TokenInfo, TOKEN_INFO}, }; pub const TOKEN_NAME: &str = "Chainlink"; pub const TOKEN_SYMBOL: &str = "LINK"; pub const DECIMALS: u8 = 18; pub const TOTAL_SUPPLY: u128 = 1_000_000_000; pub fn instantiate( mut deps: DepsMut, _env: Env, info: MessageInfo, _msg: InstantiateMsg, ) -> StdResult<Response> { let main_balance = Cw20Coin { address: info.sender.into(), amount: Uint128::from(TOTAL_SUPPLY), }; let total_supply = create_accounts(&mut deps, &[main_balance])?; let data = TokenInfo { name: TOKEN_NAME.to_string(), symbol: TOKEN_SYMBOL.to_string(), decimals: DECIMALS, total_supply, }; TOKEN_INFO.save(deps.storage, &data)?; Ok(Response::default()) } pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::Transfer { recipient, amount } => { execute_transfer(deps, env, info, recipient, amount) } ExecuteMsg::TransferFrom { owner, recipient, amount, } => execute_transfer_from(deps, env, info, owner, recipient, amount), ExecuteMsg::Send { contract, amount, msg, } => execute_send(deps, env, info, contract, amount, msg), ExecuteMsg::IncreaseAllowance { spender, amount, expires, } => execute_increase_allowance(deps, env, info, spender, amount, expires), ExecuteMsg::DecreaseAllowance { spender, amount, expires, } => execute_decrease_allowance(deps, env, info, spender, amount, expires), } } pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Balance { address } => to_binary(&query_balance(deps, address)?),
pub fn query_token_info(deps: Deps) -> StdResult<TokenInfoResponse> { let info = TOKEN_INFO.load(deps.storage)?; Ok(info.into()) } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coins, Uint128}; #[test] fn test_query_token_info() { let mut deps = mock_dependencies(&coins(2, "test_token")); let env = mock_env(); let info = mock_info(&"creator", &[]); let _ = instantiate(deps.as_mut(), env, info, InstantiateMsg {}).unwrap(); let query_res = query_token_info(deps.as_ref()).unwrap(); assert_eq!( query_res, TokenInfoResponse { name: "Chainlink".to_string(), symbol: "LINK".to_string(), decimals: 18, total_supply: Uint128::from(1_000_000_000_u128) } ); } }
QueryMsg::TokenInfo {} => to_binary(&query_token_info(deps)?), QueryMsg::Allowance { owner, spender } => { to_binary(&query_allowance(deps, owner, spender)?) } } }
function_block-function_prefix_line
[ { "content": "pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {\n\n match msg {\n\n QueryMsg::IsValid {\n\n previous_answer,\n\n answer,\n\n } => to_binary(&is_valid(deps, previous_answer, answer)?),\n\n QueryMsg::GetFlaggingThreshold {} => t...
Rust
merkle_tree/src/lib.rs
mikong/mori
75879172eeb7e733c62d472bafc6c6792d3b754a
use std::mem; use sha2::{Sha256, Digest}; use sha2::digest::generic_array::GenericArray; use sha2::digest::generic_array::typenum::U32; use sha2::digest::generic_array::sequence::Concat; type HashResult = GenericArray<u8, U32>; #[derive(Debug, PartialEq)] pub enum Position { Left, Right, } #[derive(Debug)] pub enum MerkleTree { Empty, NonEmpty(Box<Node>), } #[derive(Debug)] pub struct Node { element: HashResult, leaf_count: usize, left: MerkleTree, right: MerkleTree, } impl MerkleTree { fn new( element: HashResult, leaf_count: usize, left: MerkleTree, right: MerkleTree ) -> MerkleTree { MerkleTree::NonEmpty(Box::new(Node { element, leaf_count, left, right, })) } pub fn build<T: AsRef<[u8]>>(data: &[T]) -> MerkleTree { if data.len() == 0 { panic!("Merkle tree can't be empty: the len is 0"); } let mut leaf_nodes = data.iter().map(|val| { let hash = Sha256::digest(val.as_ref()); MerkleTree::new(hash, 1, MerkleTree::Empty, MerkleTree::Empty) }).collect(); MerkleTree::build_tree(&mut leaf_nodes) } fn build_tree(nodes: &mut Vec<MerkleTree>) -> MerkleTree { let mut new_nodes = vec![]; for pair in nodes.chunks_exact_mut(2) { let mut left = MerkleTree::Empty; let mut right = MerkleTree::Empty; mem::swap(&mut left, &mut pair[0]); mem::swap(&mut right, &mut pair[1]); let hash = MerkleTree::concat_and_hash(&left, &right); let leaf_count = left.leaf_count() + right.leaf_count(); let tree = MerkleTree::new(hash, leaf_count, left, right); new_nodes.push(tree); } if nodes.len() % 2 == 1 { new_nodes.push(nodes.pop().unwrap()); } if new_nodes.len() == 1 { return new_nodes.pop().unwrap(); } MerkleTree::build_tree(&mut new_nodes) } fn concat_and_hash(left: &MerkleTree, right: &MerkleTree) -> HashResult { let value = match (&left, &right) { (MerkleTree::NonEmpty(l), MerkleTree::NonEmpty(r)) => { l.element.concat(r.element) }, (_, _) => unreachable!(), }; Sha256::digest(&value) } fn leaf_count(&self) -> usize { match self { MerkleTree::NonEmpty(n) => n.leaf_count, MerkleTree::Empty => 0, } } pub fn get_proof(&self, index: usize) -> Vec<(Position, HashResult)> { if index >= self.leaf_count() { panic!( "index out of bounds: the len is {} but the index is {}", self.leaf_count(), index ); } let mut stack = Vec::new(); let mut current = self; let mut base = 0; use MerkleTree::NonEmpty; while current.leaf_count() > 1 { if let NonEmpty(node) = current { if let (NonEmpty(l), NonEmpty(r)) = (&node.left, &node.right) { if index < l.leaf_count + base { stack.push((Position::Right, r.element)); current = &node.left; } else { base += l.leaf_count; stack.push((Position::Left, l.element)); current = &node.right; } } } } stack.reverse(); stack } pub fn root_hash(&self) -> HashResult { match self { MerkleTree::NonEmpty(node) => node.element, MerkleTree::Empty => panic!("Merkle tree can't be empty"), } } pub fn validate( target: HashResult, proof: Vec<(Position, HashResult)>, root: HashResult ) -> bool { let hash = proof.iter().fold(target, |acc, (pos, h)| { match pos { Position::Right => Sha256::digest(&acc.concat(*h)), Position::Left => Sha256::digest(&h.concat(acc)), } }); hash == root } } #[cfg(test)] mod tests { use super::*; use super::MerkleTree::*; #[test] #[should_panic] fn zero_element() { let data: [String; 0] = []; MerkleTree::build(&data); } #[test] fn small_trees() { let ha = Sha256::digest(b"A"); let hb = Sha256::digest(b"B"); let hc = Sha256::digest(b"C"); let hab = Sha256::digest(&ha.concat(hb)); let habc = Sha256::digest(&hab.concat(hc)); let data = ["A"]; let tree = MerkleTree::build(&data); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&ha)); let data = ["A", "B"]; let tree = MerkleTree::build(&data); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&hab)); let data = ["A", "B", "C"]; let tree = MerkleTree::build(&data); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&habc)); } #[test] fn it_works() { let data = vec!["A", "B", "C", "D", "E"]; let tree = MerkleTree::build(&data); let ha = Sha256::digest(b"A"); let hb = Sha256::digest(b"B"); let hc = Sha256::digest(b"C"); let hd = Sha256::digest(b"D"); let he = Sha256::digest(b"E"); let hab = Sha256::digest(&ha.concat(hb)); let hcd = Sha256::digest(&hc.concat(hd)); let habcd = Sha256::digest(&hab.concat(hcd)); let root_hash = Sha256::digest(&habcd.concat(he)); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&root_hash)); if let NonEmpty(node) = tree { if let (NonEmpty(lnode), NonEmpty(rnode)) = (&node.left, &node.right) { assert_eq!(lnode.element, GenericArray::clone_from_slice(&habcd)); assert_eq!(rnode.element, GenericArray::clone_from_slice(&he)); } } else { panic!("Tree can't be empty"); } } #[test] fn leaf_count() { let tree = MerkleTree::Empty; assert_eq!(tree.leaf_count(), 0); let data = ["A"]; let tree = MerkleTree::build(&data); assert_eq!(tree.leaf_count(), 1); let data = ["A", "B", "C", "D", "E"]; let tree = MerkleTree::build(&data); assert_eq!(tree.leaf_count(), 5); } #[test] fn get_proof() { let data = ["A", "B", "C", "D", "E"]; let tree = MerkleTree::build(&data); let proof = tree.get_proof(2); let ha = Sha256::digest(b"A"); let hb = Sha256::digest(b"B"); let hd = Sha256::digest(b"D"); let he = Sha256::digest(b"E"); let hab = Sha256::digest(&ha.concat(hb)); let mut proof_iter = proof.iter(); let (pos, hash) = proof_iter.next().unwrap(); assert_eq!(pos, &Position::Right); assert_eq!(*hash, GenericArray::clone_from_slice(&hd)); let (pos, hash) = proof_iter.next().unwrap(); assert_eq!(pos, &Position::Left); assert_eq!(*hash, GenericArray::clone_from_slice(&hab)); let (pos, hash) = proof_iter.next().unwrap(); assert_eq!(pos, &Position::Right); assert_eq!(*hash, GenericArray::clone_from_slice(&he)); } #[test] fn validate() { let data = ["A"]; let tree = MerkleTree::build(&data); let root = tree.root_hash(); let ha = Sha256::digest(b"A"); let proof = tree.get_proof(0); assert_eq!(proof.len(), 0); assert_eq!(MerkleTree::validate(ha, proof, root), true); let data = ["A", "B", "C", "D", "E", "F", "G"]; let tree = MerkleTree::build(&data); let root = tree.root_hash(); let hc = Sha256::digest(b"C"); let proof = tree.get_proof(2); assert_eq!(MerkleTree::validate(hc, proof, root), true); let proof = tree.get_proof(3); assert_eq!(MerkleTree::validate(hc, proof, root), false); let hf = Sha256::digest(b"F"); let proof = tree.get_proof(5); assert_eq!(MerkleTree::validate(hf, proof, root), true); let hh = Sha256::digest(b"H"); let proof = tree.get_proof(6); assert_eq!(MerkleTree::validate(hh, proof, root), false); } }
use std::mem; use sha2::{Sha256, Digest}; use sha2::digest::generic_array::GenericArray; use sha2::digest::generic_array::typenum::U32; use sha2::digest::generic_array::sequence::Concat; type HashResult = GenericArray<u8, U32>; #[derive(Debug, PartialEq)] pub enum Position { Left, Right, } #[derive(Debug)] pub enum MerkleTree { Empty, NonEmpty(Box<Node>), } #[derive(Debug)] pub struct Node { element: HashResult, leaf_count: usize, left: MerkleTree, right: MerkleTree, } impl MerkleTree { fn new( element: HashResult, leaf_count: usize, left: MerkleTree, right: MerkleTree ) -> MerkleTree { MerkleTree::NonEmpty(Box::new(Node { element, leaf_count, left, right, })) } pub fn build<T: AsRef<[u8]>>(data: &[T]) -> MerkleTree { if data.len() == 0 { panic!("Merkle tree can't be empty: the len is 0"); } let mut leaf_nodes = data.iter().map(|val| { let hash = Sha256::digest(val.as_ref()); MerkleTree::new(hash, 1, MerkleTree::Empty, MerkleTree::Empty) }).collect(); MerkleTree::build_tree(&mut leaf_nodes) } fn build_tree(nodes: &mut Vec<MerkleTree>) -> MerkleTree { let mut new_nodes = vec![]; for pair in nodes.chunks_exact_mut(2) { let mut left = MerkleTree::Empty; let mut right = MerkleTree::Empty; mem::swap(&mut left, &mut pair[0]); mem::swap(&mut right, &mut pair[1]); let hash = MerkleTree::concat_and_hash(&left, &right); let leaf_count = left.leaf_count() + right.leaf_count(); let tree = MerkleTree::new(hash, leaf_count, left, right); new_nodes.push(tree); } if nodes.len() % 2 == 1 { new_nodes.push(nodes.pop().unwrap()); } if new_nodes.len() == 1 { return new_nodes.pop().unwrap(); } MerkleTree::build_tree(&mut new_nodes) } fn concat_and_hash(left: &MerkleTree, right: &MerkleTree) -> HashResult { let value = match (&left, &right) { (MerkleTree::NonEmpty(l), MerkleTree::NonEmpty(r)) => { l.element.concat(r.element) }, (_, _) => unreachable!(), }; Sha256::digest(&value) } fn leaf_count(&self) -> usize { match self { MerkleTree::NonEmpty(n) => n.leaf_count, MerkleTree::Empty => 0, } } pub fn get_proof(&self, index: usize) -> Vec<(Position, HashResult)> { if index >= self.leaf_count() { panic!( "index out of bounds: the len is {} but the index is {}", self.leaf_count(), index ); } let mut stack = Vec::new(); let mut current = self; let mut base = 0; use MerkleTree::NonEmpty; while current.leaf_count() > 1 { if let NonEmpty(node) = current { if let (NonEmpty(l), NonEmpty(r)) = (&node.left, &node.right) { if index < l.leaf_count + base { stack.push((Position::Right, r.element)); current = &node.left; } else { base += l.leaf_count; stack.push((Position::Left, l.element)); current = &node.right; } } } } stack.reverse(); stack }
_iter.next().unwrap(); assert_eq!(pos, &Position::Right); assert_eq!(*hash, GenericArray::clone_from_slice(&hd)); let (pos, hash) = proof_iter.next().unwrap(); assert_eq!(pos, &Position::Left); assert_eq!(*hash, GenericArray::clone_from_slice(&hab)); let (pos, hash) = proof_iter.next().unwrap(); assert_eq!(pos, &Position::Right); assert_eq!(*hash, GenericArray::clone_from_slice(&he)); } #[test] fn validate() { let data = ["A"]; let tree = MerkleTree::build(&data); let root = tree.root_hash(); let ha = Sha256::digest(b"A"); let proof = tree.get_proof(0); assert_eq!(proof.len(), 0); assert_eq!(MerkleTree::validate(ha, proof, root), true); let data = ["A", "B", "C", "D", "E", "F", "G"]; let tree = MerkleTree::build(&data); let root = tree.root_hash(); let hc = Sha256::digest(b"C"); let proof = tree.get_proof(2); assert_eq!(MerkleTree::validate(hc, proof, root), true); let proof = tree.get_proof(3); assert_eq!(MerkleTree::validate(hc, proof, root), false); let hf = Sha256::digest(b"F"); let proof = tree.get_proof(5); assert_eq!(MerkleTree::validate(hf, proof, root), true); let hh = Sha256::digest(b"H"); let proof = tree.get_proof(6); assert_eq!(MerkleTree::validate(hh, proof, root), false); } }
pub fn root_hash(&self) -> HashResult { match self { MerkleTree::NonEmpty(node) => node.element, MerkleTree::Empty => panic!("Merkle tree can't be empty"), } } pub fn validate( target: HashResult, proof: Vec<(Position, HashResult)>, root: HashResult ) -> bool { let hash = proof.iter().fold(target, |acc, (pos, h)| { match pos { Position::Right => Sha256::digest(&acc.concat(*h)), Position::Left => Sha256::digest(&h.concat(acc)), } }); hash == root } } #[cfg(test)] mod tests { use super::*; use super::MerkleTree::*; #[test] #[should_panic] fn zero_element() { let data: [String; 0] = []; MerkleTree::build(&data); } #[test] fn small_trees() { let ha = Sha256::digest(b"A"); let hb = Sha256::digest(b"B"); let hc = Sha256::digest(b"C"); let hab = Sha256::digest(&ha.concat(hb)); let habc = Sha256::digest(&hab.concat(hc)); let data = ["A"]; let tree = MerkleTree::build(&data); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&ha)); let data = ["A", "B"]; let tree = MerkleTree::build(&data); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&hab)); let data = ["A", "B", "C"]; let tree = MerkleTree::build(&data); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&habc)); } #[test] fn it_works() { let data = vec!["A", "B", "C", "D", "E"]; let tree = MerkleTree::build(&data); let ha = Sha256::digest(b"A"); let hb = Sha256::digest(b"B"); let hc = Sha256::digest(b"C"); let hd = Sha256::digest(b"D"); let he = Sha256::digest(b"E"); let hab = Sha256::digest(&ha.concat(hb)); let hcd = Sha256::digest(&hc.concat(hd)); let habcd = Sha256::digest(&hab.concat(hcd)); let root_hash = Sha256::digest(&habcd.concat(he)); assert_eq!(tree.root_hash(), GenericArray::clone_from_slice(&root_hash)); if let NonEmpty(node) = tree { if let (NonEmpty(lnode), NonEmpty(rnode)) = (&node.left, &node.right) { assert_eq!(lnode.element, GenericArray::clone_from_slice(&habcd)); assert_eq!(rnode.element, GenericArray::clone_from_slice(&he)); } } else { panic!("Tree can't be empty"); } } #[test] fn leaf_count() { let tree = MerkleTree::Empty; assert_eq!(tree.leaf_count(), 0); let data = ["A"]; let tree = MerkleTree::build(&data); assert_eq!(tree.leaf_count(), 1); let data = ["A", "B", "C", "D", "E"]; let tree = MerkleTree::build(&data); assert_eq!(tree.leaf_count(), 5); } #[test] fn get_proof() { let data = ["A", "B", "C", "D", "E"]; let tree = MerkleTree::build(&data); let proof = tree.get_proof(2); let ha = Sha256::digest(b"A"); let hb = Sha256::digest(b"B"); let hd = Sha256::digest(b"D"); let he = Sha256::digest(b"E"); let hab = Sha256::digest(&ha.concat(hb)); let mut proof_iter = proof.iter(); let (pos, hash) = proof
random
[ { "content": "type NodeId = usize;\n\n\n\nimpl<K, V> Node<K, V> {\n\n pub fn new(key: K, value: V, color: Color) -> Self {\n\n Node {\n\n key,\n\n value,\n\n left: None,\n\n right: None,\n\n color,\n\n size: 1,\n\n }\n\n }\n\n...
Rust
src/generate/generator.rs
nurmohammed840/virtue
b645e092861377a1b11b97c681de9e9acb5a0d22
use super::{GenerateMod, Impl, ImplFor, StreamBuilder}; use crate::parse::{GenericConstraints, Generics}; use crate::prelude::{Ident, TokenStream}; #[must_use] pub struct Generator { pub(crate) name: Ident, pub(crate) generics: Option<Generics>, pub(crate) generic_constraints: Option<GenericConstraints>, pub(crate) stream: StreamBuilder, } impl Generator { pub(crate) fn new( name: Ident, generics: Option<Generics>, generic_constraints: Option<GenericConstraints>, ) -> Self { Self { name, generics, generic_constraints, stream: StreamBuilder::new(), } } pub fn target_name(&self) -> Ident { self.name.clone() } pub fn r#impl(&mut self) -> Impl<Self> { Impl::with_parent_name(self) } pub fn generate_impl(&mut self) -> Impl<Self> { Impl::with_parent_name(self) } pub fn impl_for(&mut self, trait_name: impl Into<String>) -> ImplFor<Self> { ImplFor::new(self, trait_name) } pub fn impl_for_with_lifetimes<ITER, I, T>( &mut self, trait_name: T, lifetimes: ITER, ) -> ImplFor<Self> where ITER: IntoIterator<Item = I>, I: Into<String>, T: Into<String>, { ImplFor::new_with_lifetimes(self, trait_name, lifetimes) } pub fn generate_mod(&mut self, mod_name: impl Into<String>) -> GenerateMod<Self> { GenerateMod::new(self, mod_name) } pub fn export_to_file(&self, file_postfix: &str) -> bool { use std::io::Write; if let Ok(var) = std::env::var("CARGO_MANIFEST_DIR") { let mut path = std::path::PathBuf::from(var); loop { { let mut path = path.clone(); path.push("target"); if path.exists() { path.push(format!("{}_{}.rs", self.target_name(), file_postfix)); if let Ok(mut file) = std::fs::File::create(path) { let _ = file.write_all(self.stream.stream.to_string().as_bytes()); return true; } } } if let Some(parent) = path.parent() { path = parent.to_owned(); } else { break; } } } false } pub fn finish(mut self) -> crate::prelude::Result<TokenStream> { Ok(std::mem::take(&mut self.stream).stream) } } impl Drop for Generator { fn drop(&mut self) { if !self.stream.stream.is_empty() && !std::thread::panicking() { eprintln!("WARNING: Generator dropped but the stream is not empty. Please call `.finish()` on the generator"); } } } impl super::Parent for Generator { fn append(&mut self, builder: StreamBuilder) { self.stream.append(builder); } fn name(&self) -> &Ident { &self.name } fn generics(&self) -> Option<&Generics> { self.generics.as_ref() } fn generic_constraints(&self) -> Option<&GenericConstraints> { self.generic_constraints.as_ref() } }
use super::{GenerateMod, Impl, ImplFor, StreamBuilder}; use crate::parse::{GenericConstraints, Generics}; use crate::prelude::{Ident, TokenStream}; #[must_use] pub struct Generator { pub(crate) name: Ident, pub(crate) generics: Option<Generics>, pub(crate) generic_constraints: Option<GenericConstraints>, pub(crate) stream: StreamBuilder, } impl Generator { pub(crate) fn new( name: Ident, generics: Option<Generics>, generic_constraints: Option<GenericConstraints>, ) -> Self { Self { name, generics, generic_constraints, stream: StreamBuilder::new(), } } pub fn target_name(&self) -> Ident { self.name.clone() } pub fn r#impl(&mut self) -> Impl<Self> { Impl::with_parent_name(self) } pub fn generate_impl(&mut self) -> Impl<Self> { Impl::with_parent_name(self) } pub fn impl_for(&mut self, trait_name: impl Into<String>) -> ImplFor<Self> { ImplFor::new(self, trait_name) } pub fn impl_for_with_lifetimes<ITER, I, T>( &mut self, trait_name: T, lifetimes: ITER, ) -> ImplFor<Self> where ITER: IntoIterator<Item = I>, I: Into<String>, T: Into<String>, { ImplFor::new_with_lifetimes(self, trait_name, lifetimes) } pub fn generate_mod(&mut self, mod_name: impl Into<String>) -> GenerateMod<Self> { GenerateMod::new(self, mod_name) } pub fn export_to_file(&self, file_postfix: &str) -> bool { use std::io::Write; if let Ok(var) = std::env::var("CARGO_MANIFEST_DIR") { let mut path = std::path::PathBuf::from(var); loop { { let mut path = path.clone(); path.push("target"); if path.exists() { path.push(format!("{}_{}.rs", self.target_name(), file_postfix)); if let Ok(mut file) = std::fs::File::create(path) { let _ = file.write_all(self.stream.stream.to_string().as_bytes()); return true; } } }
} } false } pub fn finish(mut self) -> crate::prelude::Result<TokenStream> { Ok(std::mem::take(&mut self.stream).stream) } } impl Drop for Generator { fn drop(&mut self) { if !self.stream.stream.is_empty() && !std::thread::panicking() { eprintln!("WARNING: Generator dropped but the stream is not empty. Please call `.finish()` on the generator"); } } } impl super::Parent for Generator { fn append(&mut self, builder: StreamBuilder) { self.stream.append(builder); } fn name(&self) -> &Ident { &self.name } fn generics(&self) -> Option<&Generics> { self.generics.as_ref() } fn generic_constraints(&self) -> Option<&GenericConstraints> { self.generic_constraints.as_ref() } }
if let Some(parent) = path.parent() { path = parent.to_owned(); } else { break; }
if_condition
[]
Rust
src/smr/tests/proposal_test.rs
zeroqn/overlord
4bf43c4c4e94691e54bae586a07b82e39e13622a
use crate::smr::smr_types::{Lock, SMREvent, SMRTrigger, Step, TriggerType}; use crate::smr::tests::{gen_hash, trigger_test, InnerState, StateMachineTestCase}; use crate::{error::ConsensusError, types::Hash}; #[tokio::test(threaded_scheduler)] async fn test_proposal_trigger() { let mut index = 1; let mut test_cases: Vec<StateMachineTestCase> = Vec::new(); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(0, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 0u64, block_hash: hash, lock_round: None, }, None, None, )); let hash = Hash::new(); test_cases.push(StateMachineTestCase::new( InnerState::new(0, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 0u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Invalid lock".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, None, None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::SelfCheckErr("".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::SelfCheckErr("".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(Hash::new(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(Hash::new(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(lock_hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: Some(0), }, None, Some((0, lock_hash)), )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: lock_hash.clone(), lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), Some((0, lock_hash)), )); let hash = gen_hash(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: lock_hash.clone(), lock_round: Some(0), }, None, Some((0, lock_hash)), )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: lock_hash.clone(), lock_round: None, }, Some(ConsensusError::ProposalErr("Invalid lock".to_string())), Some((0, lock_hash)), )); let hash = gen_hash(); let lock_hash = gen_hash(); let lock = Lock::new(1, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(2, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 2u64, block_hash: lock_hash.clone(), lock_round: Some(1), }, None, Some((1, lock_hash)), )); let hash = gen_hash(); let lock_hash = gen_hash(); let lock = Lock::new(1, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(3, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(2), 0), SMREvent::PrevoteVote { height: 0u64, round: 3u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::SelfCheckErr( "Invalid proposal hash".to_string(), )), None, )); let lock_hash = gen_hash(); let lock = Lock::new(1, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(2, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(lock_hash.clone(), TriggerType::Proposal, Some(1), 0), SMREvent::PrevoteVote { height: 0u64, round: 2u64, block_hash: lock_hash.clone(), lock_round: Some(1), }, None, Some((1, lock_hash)), )); for case in test_cases.into_iter() { println!("Proposal test {}/19", index); index += 1; trigger_test( case.base, case.input, case.output, case.err, case.should_lock, ) .await; } println!("Proposal test success"); }
use crate::smr::smr_types::{Lock, SMREvent, SMRTrigger, Step, TriggerType}; use crate::smr::tests::{gen_hash, trigger_test, InnerState, StateMachineTestCase}; use crate::{error::ConsensusError, types::Hash}; #[tokio::test(threaded_scheduler)] async fn test_proposal_trigger() { let mut index = 1; let mut test_cases: Vec<StateMachineTestCase> = Vec::new(); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(0, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 0u64, block_hash: hash, lock_round: None, }, None, None, )); let hash = Hash::new(); test_cases.push(StateMachineTestCase::new( InnerState::new(0, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 0u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Invalid lock".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, Hash::new(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, None, None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::SelfCheckErr("".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::SelfCheckErr("".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(Hash::new(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = gen_hash(); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), None), SMRTrigger::new(Hash::new(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), None, )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, hash.clone(), Some(lock)), SMRTrigger::new(lock_hash.clone(), TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: hash, lock_round: Some(0), }, None, Some((0, lock_hash)), )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: lock_hash.clone(), lock_round: None, }, Some(ConsensusError::ProposalErr("Empty qc".to_string())), Some((0, lock_hash)), )); let hash = gen_hash(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, None, 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: lock_hash.clone(), lock_round: Some(0), }, None, Some((0, lock_hash)), )); let hash = Hash::new(); let lock_hash = gen_hash(); let lock = Lock::new(0, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(1, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, Some(0), 0), SMREvent::PrevoteVote { height: 0u64, round: 1u64, block_hash: lock_hash.clone(), lock_round: None, }, Some(ConsensusError::ProposalErr("Invalid lock".to_string())), Some((0, lock_hash)), )); let hash = gen_hash(); let lock_hash = gen_hash(); let lock = Lock::new(1, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(2, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash, TriggerType::Proposal, Some(0), 0), SMREvent::Pre
ash = gen_hash(); let lock = Lock::new(1, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(2, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(lock_hash.clone(), TriggerType::Proposal, Some(1), 0), SMREvent::PrevoteVote { height: 0u64, round: 2u64, block_hash: lock_hash.clone(), lock_round: Some(1), }, None, Some((1, lock_hash)), )); for case in test_cases.into_iter() { println!("Proposal test {}/19", index); index += 1; trigger_test( case.base, case.input, case.output, case.err, case.should_lock, ) .await; } println!("Proposal test success"); }
voteVote { height: 0u64, round: 2u64, block_hash: lock_hash.clone(), lock_round: Some(1), }, None, Some((1, lock_hash)), )); let hash = gen_hash(); let lock_hash = gen_hash(); let lock = Lock::new(1, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(3, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(hash.clone(), TriggerType::Proposal, Some(2), 0), SMREvent::PrevoteVote { height: 0u64, round: 3u64, block_hash: hash, lock_round: None, }, Some(ConsensusError::SelfCheckErr( "Invalid proposal hash".to_string(), )), None, )); let lock_h
random
[ { "content": "fn gen_hash() -> Hash {\n\n Hash::from((0..16).map(|_| random::<u8>()).collect::<Vec<_>>())\n\n}\n", "file_path": "tests/test_utils.rs", "rank": 0, "score": 137237.66059652547 }, { "content": "fn gen_hash() -> Hash {\n\n Hash::from((0..16).map(|_| random::<u8>()).collect:...
Rust
tracing-journald/tests/journal.rs
jswrenn/tracing
388fff8371fef1ec0f75bc495fe1ad4cfa045f7b
#![cfg(target_os = "linux")] use std::collections::HashMap; use std::process::Command; use std::time::Duration; use serde::Deserialize; use tracing::{debug, error, info, info_span, warn}; use tracing_journald::Subscriber; use tracing_subscriber::subscribe::CollectExt; use tracing_subscriber::Registry; fn journalctl_version() -> std::io::Result<String> { let output = Command::new("journalctl").arg("--version").output()?; Ok(String::from_utf8_lossy(&output.stdout).to_string()) } fn with_journald(f: impl FnOnce()) { with_journald_subscriber(Subscriber::new().unwrap().with_field_prefix(None), f) } fn with_journald_subscriber(subscriber: Subscriber, f: impl FnOnce()) { match journalctl_version() { Ok(_) => { let sub = Registry::default().with(subscriber); tracing::collect::with_default(sub, f); } Err(error) => eprintln!( "SKIPPING TEST: journalctl --version failed with error: {}", error ), } } #[derive(Debug, PartialEq, Deserialize)] #[serde(untagged)] enum Field { Text(String), Array(Vec<String>), Binary(Vec<u8>), } impl Field { fn as_array(&self) -> Option<&[String]> { match self { Field::Text(_) => None, Field::Binary(_) => None, Field::Array(v) => Some(v), } } fn as_text(&self) -> Option<&str> { match self { Field::Text(v) => Some(v.as_str()), Field::Binary(_) => None, Field::Array(_) => None, } } } impl PartialEq<&str> for Field { fn eq(&self, other: &&str) -> bool { match self { Field::Text(s) => s == other, Field::Binary(_) => false, Field::Array(_) => false, } } } impl PartialEq<[u8]> for Field { fn eq(&self, other: &[u8]) -> bool { match self { Field::Text(s) => s.as_bytes() == other, Field::Binary(data) => data == other, Field::Array(_) => false, } } } impl PartialEq<Vec<&str>> for Field { fn eq(&self, other: &Vec<&str>) -> bool { match self { Field::Text(_) => false, Field::Binary(_) => false, Field::Array(data) => data == other, } } } fn retry<T, E>(f: impl Fn() -> Result<T, E>) -> Result<T, E> { let attempts = 30; let interval = Duration::from_millis(100); for attempt in (0..attempts).rev() { match f() { Ok(result) => return Ok(result), Err(e) if attempt == 0 => return Err(e), Err(_) => std::thread::sleep(interval), } } unreachable!() } fn read_from_journal(test_name: &str) -> Vec<HashMap<String, Field>> { let stdout = String::from_utf8( Command::new("journalctl") .args(&["--user", "--output=json", "--all"]) .arg(format!("_PID={}", std::process::id())) .arg(format!("TEST_NAME={}", test_name)) .output() .unwrap() .stdout, ) .unwrap(); stdout .lines() .map(|l| serde_json::from_str(l).unwrap()) .collect() } fn retry_read_one_line_from_journal(testname: &str) -> HashMap<String, Field> { retry(|| { let mut messages = read_from_journal(testname); if messages.len() == 1 { Ok(messages.pop().unwrap()) } else { Err(format!( "one messages expected, got {} messages", messages.len() )) } }) .unwrap() } #[test] fn simple_message() { with_journald(|| { info!(test.name = "simple_message", "Hello World"); let message = retry_read_one_line_from_journal("simple_message"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); }); } #[test] fn multiline_message() { with_journald(|| { warn!(test.name = "multiline_message", "Hello\nMultiline\nWorld"); let message = retry_read_one_line_from_journal("multiline_message"); assert_eq!(message["MESSAGE"], "Hello\nMultiline\nWorld"); assert_eq!(message["PRIORITY"], "4"); }); } #[test] fn multiline_message_trailing_newline() { with_journald(|| { error!( test.name = "multiline_message_trailing_newline", "A trailing newline\n" ); let message = retry_read_one_line_from_journal("multiline_message_trailing_newline"); assert_eq!(message["MESSAGE"], "A trailing newline\n"); assert_eq!(message["PRIORITY"], "3"); }); } #[test] fn internal_null_byte() { with_journald(|| { debug!(test.name = "internal_null_byte", "An internal\x00byte"); let message = retry_read_one_line_from_journal("internal_null_byte"); assert_eq!(message["MESSAGE"], b"An internal\x00byte"[..]); assert_eq!(message["PRIORITY"], "6"); }); } #[test] fn large_message() { let large_string = "b".repeat(512_000); with_journald(|| { debug!(test.name = "large_message", "Message: {}", large_string); let message = retry_read_one_line_from_journal("large_message"); assert_eq!( message["MESSAGE"], format!("Message: {}", large_string).as_str() ); assert_eq!(message["PRIORITY"], "6"); }); } #[test] fn simple_metadata() { let sub = Subscriber::new() .unwrap() .with_field_prefix(None) .with_syslog_identifier("test_ident".to_string()); with_journald_subscriber(sub, || { info!(test.name = "simple_metadata", "Hello World"); let message = retry_read_one_line_from_journal("simple_metadata"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); assert_eq!(message["TARGET"], "journal"); assert_eq!(message["SYSLOG_IDENTIFIER"], "test_ident"); assert!(message["CODE_FILE"].as_text().is_some()); assert!(message["CODE_LINE"].as_text().is_some()); }); } #[test] fn span_metadata() { with_journald(|| { let s1 = info_span!("span1", span_field1 = "foo1"); let _g1 = s1.enter(); info!(test.name = "span_metadata", "Hello World"); let message = retry_read_one_line_from_journal("span_metadata"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); assert_eq!(message["TARGET"], "journal"); assert_eq!(message["SPAN_FIELD1"].as_text(), Some("foo1")); assert_eq!(message["SPAN_NAME"].as_text(), Some("span1")); assert!(message["CODE_FILE"].as_text().is_some()); assert!(message["CODE_LINE"].as_text().is_some()); assert!(message["SPAN_CODE_FILE"].as_text().is_some()); assert!(message["SPAN_CODE_LINE"].as_text().is_some()); }); } #[test] fn multiple_spans_metadata() { with_journald(|| { let s1 = info_span!("span1", span_field1 = "foo1"); let _g1 = s1.enter(); let s2 = info_span!("span2", span_field1 = "foo2"); let _g2 = s2.enter(); info!(test.name = "multiple_spans_metadata", "Hello World"); let message = retry_read_one_line_from_journal("multiple_spans_metadata"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); assert_eq!(message["TARGET"], "journal"); assert_eq!(message["SPAN_FIELD1"], vec!["foo1", "foo2"]); assert_eq!(message["SPAN_NAME"], vec!["span1", "span2"]); assert!(message["CODE_FILE"].as_text().is_some()); assert!(message["CODE_LINE"].as_text().is_some()); assert!(message.contains_key("SPAN_CODE_FILE")); assert_eq!(message["SPAN_CODE_LINE"].as_array().unwrap().len(), 2); }); } #[test] fn spans_field_collision() { with_journald(|| { let s1 = info_span!("span1", span_field = "foo1"); let _g1 = s1.enter(); let s2 = info_span!("span2", span_field = "foo2"); let _g2 = s2.enter(); info!( test.name = "spans_field_collision", span_field = "foo3", "Hello World" ); let message = retry_read_one_line_from_journal("spans_field_collision"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["SPAN_NAME"], vec!["span1", "span2"]); assert_eq!(message["SPAN_FIELD"], vec!["foo1", "foo2", "foo3"]); }); }
#![cfg(target_os = "linux")] use std::collections::HashMap; use std::process::Command; use std::time::Duration; use serde::Deserialize; use tracing::{debug, error, info, info_span, warn}; use tracing_journald::Subscriber; use tracing_subscriber::subscribe::CollectExt; use tracing_subscriber::Registry; fn journalctl_version() -> std::io::Result<String> { let output = Command::new("journalctl").arg("--version").output()?; Ok(String::from_utf8_lossy(&output.stdout).to_string()) } fn with_journald(f: impl FnOnce()) { with_journald_subscriber(Subscriber::new().unwrap().with_field_prefix(None), f) } fn with_journald_subscriber(subscriber: Subscriber, f: impl FnOnce()) { match journalctl_version() { Ok(_) => { let sub = Registry::default().with(subscriber); tracing::collect::with_default(sub, f); } Err(error) => eprintln!( "SKIPPING TEST: journalctl --version failed with error: {}", error ), } } #[derive(Debug, PartialEq, Deserialize)] #[serde(untagged)] enum Field { Text(String), Array(Vec<String>), Binary(Vec<u8>), } impl Field { fn as_array(&self) -> Option<&[String]> { match self { Field::Text(_) => None, Field::Binary(_) => None, Field::Array(v) => Some(v), } } fn as_text(&self) -> Option<&str> { match self { Field::Text(v) => Some(v.as_str()), Field::Binary(_) => None, Field::Array(_) => None,
) { with_journald(|| { error!( test.name = "multiline_message_trailing_newline", "A trailing newline\n" ); let message = retry_read_one_line_from_journal("multiline_message_trailing_newline"); assert_eq!(message["MESSAGE"], "A trailing newline\n"); assert_eq!(message["PRIORITY"], "3"); }); } #[test] fn internal_null_byte() { with_journald(|| { debug!(test.name = "internal_null_byte", "An internal\x00byte"); let message = retry_read_one_line_from_journal("internal_null_byte"); assert_eq!(message["MESSAGE"], b"An internal\x00byte"[..]); assert_eq!(message["PRIORITY"], "6"); }); } #[test] fn large_message() { let large_string = "b".repeat(512_000); with_journald(|| { debug!(test.name = "large_message", "Message: {}", large_string); let message = retry_read_one_line_from_journal("large_message"); assert_eq!( message["MESSAGE"], format!("Message: {}", large_string).as_str() ); assert_eq!(message["PRIORITY"], "6"); }); } #[test] fn simple_metadata() { let sub = Subscriber::new() .unwrap() .with_field_prefix(None) .with_syslog_identifier("test_ident".to_string()); with_journald_subscriber(sub, || { info!(test.name = "simple_metadata", "Hello World"); let message = retry_read_one_line_from_journal("simple_metadata"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); assert_eq!(message["TARGET"], "journal"); assert_eq!(message["SYSLOG_IDENTIFIER"], "test_ident"); assert!(message["CODE_FILE"].as_text().is_some()); assert!(message["CODE_LINE"].as_text().is_some()); }); } #[test] fn span_metadata() { with_journald(|| { let s1 = info_span!("span1", span_field1 = "foo1"); let _g1 = s1.enter(); info!(test.name = "span_metadata", "Hello World"); let message = retry_read_one_line_from_journal("span_metadata"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); assert_eq!(message["TARGET"], "journal"); assert_eq!(message["SPAN_FIELD1"].as_text(), Some("foo1")); assert_eq!(message["SPAN_NAME"].as_text(), Some("span1")); assert!(message["CODE_FILE"].as_text().is_some()); assert!(message["CODE_LINE"].as_text().is_some()); assert!(message["SPAN_CODE_FILE"].as_text().is_some()); assert!(message["SPAN_CODE_LINE"].as_text().is_some()); }); } #[test] fn multiple_spans_metadata() { with_journald(|| { let s1 = info_span!("span1", span_field1 = "foo1"); let _g1 = s1.enter(); let s2 = info_span!("span2", span_field1 = "foo2"); let _g2 = s2.enter(); info!(test.name = "multiple_spans_metadata", "Hello World"); let message = retry_read_one_line_from_journal("multiple_spans_metadata"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); assert_eq!(message["TARGET"], "journal"); assert_eq!(message["SPAN_FIELD1"], vec!["foo1", "foo2"]); assert_eq!(message["SPAN_NAME"], vec!["span1", "span2"]); assert!(message["CODE_FILE"].as_text().is_some()); assert!(message["CODE_LINE"].as_text().is_some()); assert!(message.contains_key("SPAN_CODE_FILE")); assert_eq!(message["SPAN_CODE_LINE"].as_array().unwrap().len(), 2); }); } #[test] fn spans_field_collision() { with_journald(|| { let s1 = info_span!("span1", span_field = "foo1"); let _g1 = s1.enter(); let s2 = info_span!("span2", span_field = "foo2"); let _g2 = s2.enter(); info!( test.name = "spans_field_collision", span_field = "foo3", "Hello World" ); let message = retry_read_one_line_from_journal("spans_field_collision"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["SPAN_NAME"], vec!["span1", "span2"]); assert_eq!(message["SPAN_FIELD"], vec!["foo1", "foo2", "foo3"]); }); }
} } } impl PartialEq<&str> for Field { fn eq(&self, other: &&str) -> bool { match self { Field::Text(s) => s == other, Field::Binary(_) => false, Field::Array(_) => false, } } } impl PartialEq<[u8]> for Field { fn eq(&self, other: &[u8]) -> bool { match self { Field::Text(s) => s.as_bytes() == other, Field::Binary(data) => data == other, Field::Array(_) => false, } } } impl PartialEq<Vec<&str>> for Field { fn eq(&self, other: &Vec<&str>) -> bool { match self { Field::Text(_) => false, Field::Binary(_) => false, Field::Array(data) => data == other, } } } fn retry<T, E>(f: impl Fn() -> Result<T, E>) -> Result<T, E> { let attempts = 30; let interval = Duration::from_millis(100); for attempt in (0..attempts).rev() { match f() { Ok(result) => return Ok(result), Err(e) if attempt == 0 => return Err(e), Err(_) => std::thread::sleep(interval), } } unreachable!() } fn read_from_journal(test_name: &str) -> Vec<HashMap<String, Field>> { let stdout = String::from_utf8( Command::new("journalctl") .args(&["--user", "--output=json", "--all"]) .arg(format!("_PID={}", std::process::id())) .arg(format!("TEST_NAME={}", test_name)) .output() .unwrap() .stdout, ) .unwrap(); stdout .lines() .map(|l| serde_json::from_str(l).unwrap()) .collect() } fn retry_read_one_line_from_journal(testname: &str) -> HashMap<String, Field> { retry(|| { let mut messages = read_from_journal(testname); if messages.len() == 1 { Ok(messages.pop().unwrap()) } else { Err(format!( "one messages expected, got {} messages", messages.len() )) } }) .unwrap() } #[test] fn simple_message() { with_journald(|| { info!(test.name = "simple_message", "Hello World"); let message = retry_read_one_line_from_journal("simple_message"); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["PRIORITY"], "5"); }); } #[test] fn multiline_message() { with_journald(|| { warn!(test.name = "multiline_message", "Hello\nMultiline\nWorld"); let message = retry_read_one_line_from_journal("multiline_message"); assert_eq!(message["MESSAGE"], "Hello\nMultiline\nWorld"); assert_eq!(message["PRIORITY"], "4"); }); } #[test] fn multiline_message_trailing_newline(
random
[ { "content": "#[allow(clippy::manual_async_fn)]\n\n#[instrument(level = \"debug\")]\n\nfn instrumented_manual_async() -> impl Future<Output = ()> {\n\n async move {}\n\n}\n\n\n", "file_path": "tracing/test_static_max_level_features/tests/test.rs", "rank": 1, "score": 282858.3962827644 }, { ...
Rust
src/bin/day24/main.rs
MattiasBuelens/advent-of-code-2019
01a88977bc7b6471bdc84aebd41e1e8d3920946d
use std::collections::{HashMap, HashSet}; fn main() { let grid: Grid = Grid::parse(include_str!("input")); println!("Answer to part 1: {}", part1(grid.clone())); println!("Answer to part 2: {}", part2(grid.clone())); } #[derive(Debug, Eq, PartialEq, Copy, Clone)] enum Tile { EMPTY, BUG, } impl Tile { fn parse(value: char) -> Self { match value { '.' => Tile::EMPTY, '#' => Tile::BUG, _ => panic!("invalid tile: {}", value), } } fn print(&self) -> char { match *self { Tile::EMPTY => '.', Tile::BUG => '#', } } } impl Default for Tile { fn default() -> Self { Tile::EMPTY } } const SIZE: usize = 5; #[derive(Debug, Default, Copy, Clone)] struct Grid { tiles: [[Tile; SIZE]; SIZE], } impl Grid { fn parse(input: &str) -> Self { let mut tiles: [[Tile; SIZE]; SIZE] = Default::default(); let mut y = 0; for line in input.trim().lines() { let mut x = 0; for value in line.chars() { tiles[y][x] = Tile::parse(value); x += 1; } y += 1; } Grid { tiles } } fn print(&self) { for row in &self.tiles { println!("{}", row.iter().map(|x| x.print()).collect::<String>()); } } fn get_neighbours(&self, x: usize, y: usize) -> Vec<Tile> { let mut neighbours: Vec<Tile> = Vec::new(); if y > 0 { neighbours.push(self.tiles[y - 1][x]); } if x > 0 { neighbours.push(self.tiles[y][x - 1]); } if x + 1 < SIZE { neighbours.push(self.tiles[y][x + 1]); } if y + 1 < SIZE { neighbours.push(self.tiles[y + 1][x]); } neighbours } fn step(&mut self) { let mut new_tiles: [[Tile; SIZE]; SIZE] = Default::default(); for y in 0..SIZE { for x in 0..SIZE { let neighbour_bugs = self .get_neighbours(x, y) .iter() .filter(|&x| x == &Tile::BUG) .count(); new_tiles[y][x] = match (self.tiles[y][x], neighbour_bugs) { (Tile::BUG, 1) => Tile::BUG, (Tile::BUG, _) => Tile::EMPTY, (Tile::EMPTY, 1) | (Tile::EMPTY, 2) => Tile::BUG, (Tile::EMPTY, _) => Tile::EMPTY, } } } self.tiles = new_tiles; } fn get_biodiversity_rating(&self) -> u32 { let mut rating = 0; let mut power = 1; for y in 0..SIZE { for x in 0..SIZE { if self.tiles[y][x] == Tile::BUG { rating |= power; } power <<= 1; } } rating } fn count_bugs(&self) -> usize { self.tiles .iter() .map(|row| row.iter().filter(|&x| x == &Tile::BUG).count()) .sum() } } fn part1(mut grid: Grid) -> u32 { let mut seen_ratings: HashSet<u32> = HashSet::new(); seen_ratings.insert(grid.get_biodiversity_rating()); loop { grid.step(); let rating = grid.get_biodiversity_rating(); if seen_ratings.contains(&rating) { break; } else { seen_ratings.insert(rating); } } grid.get_biodiversity_rating() } #[derive(Debug)] struct MultiGrid { grids: HashMap<isize, Grid>, } impl MultiGrid { fn new(grid: Grid) -> Self { let mut grids = HashMap::new(); grids.insert(0, grid); MultiGrid { grids } } fn print(&self) { let mut levels = self.grids.keys().collect::<Vec<_>>(); levels.sort(); for level in levels { println!("Depth {}", level); self.grids[level].print(); println!(); } } fn get_tile(&self, level: isize, x: usize, y: usize) -> Tile { assert!(x != 2 || y != 2); if let Some(grid) = self.grids.get(&level) { grid.tiles[y][x] } else { Tile::EMPTY } } fn get_neighbours(&self, level: isize, x: usize, y: usize) -> Vec<Tile> { let mut neighbours: Vec<Tile> = Vec::new(); match (x, y) { (_, 0) => { neighbours.push(self.get_tile(level - 1, 2, 1)); } (2, 3) => { for x in 0..SIZE { neighbours.push(self.get_tile(level + 1, x, SIZE - 1)); } } _ => { neighbours.push(self.get_tile(level, x, y - 1)); } } match (x, y) { (0, _) => { neighbours.push(self.get_tile(level - 1, 1, 2)); } (3, 2) => { for y in 0..SIZE { neighbours.push(self.get_tile(level + 1, SIZE - 1, y)); } } _ => { neighbours.push(self.get_tile(level, x - 1, y)); } } match (x, y) { (4, _) => { neighbours.push(self.get_tile(level - 1, 3, 2)); } (1, 2) => { for y in 0..SIZE { neighbours.push(self.get_tile(level + 1, 0, y)); } } _ => { neighbours.push(self.get_tile(level, x + 1, y)); } } match (x, y) { (_, 4) => { neighbours.push(self.get_tile(level - 1, 2, 3)); } (2, 1) => { for x in 0..SIZE { neighbours.push(self.get_tile(level + 1, x, 0)); } } _ => { neighbours.push(self.get_tile(level, x, y + 1)); } } neighbours } fn step_tile(&self, level: isize, x: usize, y: usize) -> Tile { let neighbour_bugs = self .get_neighbours(level, x, y) .iter() .filter(|&x| x == &Tile::BUG) .count(); match (self.get_tile(level, x, y), neighbour_bugs) { (Tile::BUG, 1) => Tile::BUG, (Tile::BUG, _) => Tile::EMPTY, (Tile::EMPTY, 1) | (Tile::EMPTY, 2) => Tile::BUG, (Tile::EMPTY, _) => Tile::EMPTY, } } fn step(&mut self) { let mut new_grids: HashMap<isize, Grid> = self.grids.clone(); let min_level = *self.grids.keys().min().unwrap(); let max_level = *self.grids.keys().max().unwrap(); for level in (min_level - 1)..=(max_level + 1) { for y in 0..SIZE { for x in 0..SIZE { if x == 2 && y == 2 { continue; } let new_tile = self.step_tile(level, x, y); if new_tile == Tile::BUG || self.grids.contains_key(&level) { let new_grid = new_grids.entry(level).or_insert(Default::default()); new_grid.tiles[y][x] = new_tile; } } } } self.grids = new_grids; } fn count_bugs(&self) -> usize { self.grids.values().map(|grid| grid.count_bugs()).sum() } } fn part2(grid: Grid) -> usize { let mut multi_grid = MultiGrid::new(grid); for _ in 0..200 { multi_grid.step(); } multi_grid.count_bugs() } #[cfg(test)] mod tests { use super::*; #[test] fn test_part1() { let grid = Grid::parse(include_str!("example")); assert_eq!(part1(grid), 2129920); } }
use std::collections::{HashMap, HashSet}; fn main() { let grid: Grid = Grid::parse(include_str!("input")); println!("Answer to part 1: {}", part1(grid.clone())); println!("Answer to part 2: {}", part2(grid.clone())); } #[derive(Debug, Eq, PartialEq, Copy, Clone)] enum Tile { EMPTY, BUG, } impl Tile { fn parse(value: char) -> Self { match value { '.' => Tile::EMPTY, '#' => Tile::BUG, _ => panic!("invalid tile: {}", value), } } fn print(&self) -> char { match *self { Tile::EMPTY => '.', Tile::BUG => '#', } } } impl Default for Tile { fn default() -> Self { Tile::EMPTY } } const SIZE: usize = 5; #[derive(Debug, Default, Copy, Clone)] struct Grid { tiles: [[Tile; SIZE]; SIZE], } impl Grid { fn parse(input: &str) -> Self { let mut tiles: [[Tile; SIZE]; SIZE] = Default::default(); let mut y = 0; for line in input.trim().lines() { let mut x = 0; for value in line.chars() { tiles[y][x] = Tile::parse(value); x += 1; } y += 1; } Grid { tiles } } fn print(&self) { for row in &self.tiles { println!("{}", row.iter().map(|x| x.print()).collect::<String>()); } } fn get_neighbours(&self, x: usize, y: usize) -> Vec<Tile> { let mut neighbours: Vec<Tile> = Vec::new(); if y > 0 { neighbours.push(self.tiles[y - 1][x]); } if x > 0 { neighbours.push(self.tiles[y][x - 1]); } if x + 1 < SIZE { neighbours.push(self.tiles[y][x + 1]); } if
_key(&level) { let new_grid = new_grids.entry(level).or_insert(Default::default()); new_grid.tiles[y][x] = new_tile; } } } } self.grids = new_grids; } fn count_bugs(&self) -> usize { self.grids.values().map(|grid| grid.count_bugs()).sum() } } fn part2(grid: Grid) -> usize { let mut multi_grid = MultiGrid::new(grid); for _ in 0..200 { multi_grid.step(); } multi_grid.count_bugs() } #[cfg(test)] mod tests { use super::*; #[test] fn test_part1() { let grid = Grid::parse(include_str!("example")); assert_eq!(part1(grid), 2129920); } }
y + 1 < SIZE { neighbours.push(self.tiles[y + 1][x]); } neighbours } fn step(&mut self) { let mut new_tiles: [[Tile; SIZE]; SIZE] = Default::default(); for y in 0..SIZE { for x in 0..SIZE { let neighbour_bugs = self .get_neighbours(x, y) .iter() .filter(|&x| x == &Tile::BUG) .count(); new_tiles[y][x] = match (self.tiles[y][x], neighbour_bugs) { (Tile::BUG, 1) => Tile::BUG, (Tile::BUG, _) => Tile::EMPTY, (Tile::EMPTY, 1) | (Tile::EMPTY, 2) => Tile::BUG, (Tile::EMPTY, _) => Tile::EMPTY, } } } self.tiles = new_tiles; } fn get_biodiversity_rating(&self) -> u32 { let mut rating = 0; let mut power = 1; for y in 0..SIZE { for x in 0..SIZE { if self.tiles[y][x] == Tile::BUG { rating |= power; } power <<= 1; } } rating } fn count_bugs(&self) -> usize { self.tiles .iter() .map(|row| row.iter().filter(|&x| x == &Tile::BUG).count()) .sum() } } fn part1(mut grid: Grid) -> u32 { let mut seen_ratings: HashSet<u32> = HashSet::new(); seen_ratings.insert(grid.get_biodiversity_rating()); loop { grid.step(); let rating = grid.get_biodiversity_rating(); if seen_ratings.contains(&rating) { break; } else { seen_ratings.insert(rating); } } grid.get_biodiversity_rating() } #[derive(Debug)] struct MultiGrid { grids: HashMap<isize, Grid>, } impl MultiGrid { fn new(grid: Grid) -> Self { let mut grids = HashMap::new(); grids.insert(0, grid); MultiGrid { grids } } fn print(&self) { let mut levels = self.grids.keys().collect::<Vec<_>>(); levels.sort(); for level in levels { println!("Depth {}", level); self.grids[level].print(); println!(); } } fn get_tile(&self, level: isize, x: usize, y: usize) -> Tile { assert!(x != 2 || y != 2); if let Some(grid) = self.grids.get(&level) { grid.tiles[y][x] } else { Tile::EMPTY } } fn get_neighbours(&self, level: isize, x: usize, y: usize) -> Vec<Tile> { let mut neighbours: Vec<Tile> = Vec::new(); match (x, y) { (_, 0) => { neighbours.push(self.get_tile(level - 1, 2, 1)); } (2, 3) => { for x in 0..SIZE { neighbours.push(self.get_tile(level + 1, x, SIZE - 1)); } } _ => { neighbours.push(self.get_tile(level, x, y - 1)); } } match (x, y) { (0, _) => { neighbours.push(self.get_tile(level - 1, 1, 2)); } (3, 2) => { for y in 0..SIZE { neighbours.push(self.get_tile(level + 1, SIZE - 1, y)); } } _ => { neighbours.push(self.get_tile(level, x - 1, y)); } } match (x, y) { (4, _) => { neighbours.push(self.get_tile(level - 1, 3, 2)); } (1, 2) => { for y in 0..SIZE { neighbours.push(self.get_tile(level + 1, 0, y)); } } _ => { neighbours.push(self.get_tile(level, x + 1, y)); } } match (x, y) { (_, 4) => { neighbours.push(self.get_tile(level - 1, 2, 3)); } (2, 1) => { for x in 0..SIZE { neighbours.push(self.get_tile(level + 1, x, 0)); } } _ => { neighbours.push(self.get_tile(level, x, y + 1)); } } neighbours } fn step_tile(&self, level: isize, x: usize, y: usize) -> Tile { let neighbour_bugs = self .get_neighbours(level, x, y) .iter() .filter(|&x| x == &Tile::BUG) .count(); match (self.get_tile(level, x, y), neighbour_bugs) { (Tile::BUG, 1) => Tile::BUG, (Tile::BUG, _) => Tile::EMPTY, (Tile::EMPTY, 1) | (Tile::EMPTY, 2) => Tile::BUG, (Tile::EMPTY, _) => Tile::EMPTY, } } fn step(&mut self) { let mut new_grids: HashMap<isize, Grid> = self.grids.clone(); let min_level = *self.grids.keys().min().unwrap(); let max_level = *self.grids.keys().max().unwrap(); for level in (min_level - 1)..=(max_level + 1) { for y in 0..SIZE { for x in 0..SIZE { if x == 2 && y == 2 { continue; } let new_tile = self.step_tile(level, x, y); if new_tile == Tile::BUG || self.grids.contains
random
[ { "content": "pub fn parse_list<T, E>(input: &str, separator: char) -> Vec<T>\n\nwhere\n\n T: FromStr<Err = E>,\n\n E: Debug,\n\n{\n\n return input\n\n .trim()\n\n .split(separator)\n\n .map(|x| x.parse().expect(\"invalid input\"))\n\n .collect();\n\n}\n", "file_path": "...
Rust
src/decode.rs
12101111/6502
b333d946539f04fee8680f5b1b73de40c1102b3c
use super::address::AM::{self, *}; #[derive(Debug, Clone, Copy)] #[allow(non_camel_case_types)] pub enum OP { LDA, LDX, LDY, STA, STX, STY, TAX, TAY, TXA, TYA, TSX, TXS, PHA, PHP, PLA, PLP, ADC, SBC, INX, INY, DEX, DEY, INC, DEC, AND, ORA, EOR, BIT, CMP, CPX, CPY, ASL, LSR, ROL, ROR, CLC, CLD, CLI, CLV, SEC, SED, SEI, JMP, JSR, RTS, RTI, BRK, BEQ, BNE, BCS, BCC, BVS, BVC, BMI, BPL, NOP, ALR, ANC, ARR, AXS, LAX, SAX, DCP, ISC, RLA, RRA, SLO, SRE, SHY, SHX, STP, XXA, AHX, TAS, LAS, } use self::OP::*; #[rustfmt::skip] pub static DECODE: [(OP, AM, u8); 256] = [ /*0x00*/(BRK, IMP, 7),(ORA, ZIX, 6),(STP, NON, 2),(SLO, ZIX, 8),(NOP, ZPG, 3),(ORA, ZPG, 3),(ASL, ZPG, 5),(SLO, ZPG, 5), /*0x08*/(PHP, IMP, 3),(ORA, IMM, 2),(ASL, ACC, 2),(ANC, IMM, 2),(NOP, ABS, 4),(ORA, ABS, 4),(ASL, ABS, 6),(SLO, ABS, 6), /*0x10*/(BPL, REL, 2),(ORA, ZIY, 5),(STP, NON, 2),(SLO, ZIY, 8),(NOP, ZPX, 4),(ORA, ZPX, 4),(ASL, ZPX, 6),(SLO, ZPX, 6), /*0x18*/(CLC, IMP, 2),(ORA, aby, 4),(NOP, IMP, 2),(SLO, ABY, 7),(NOP, abx, 4),(ORA, abx, 4),(ASL, ABX, 7),(SLO, ABX, 7), /*0x20*/(JSR, ABS, 6),(AND, ZIX, 6),(STP, NON, 2),(RLA, ZIX, 8),(BIT, ZPG, 3),(AND, ZPG, 3),(ROL, ZPG, 5),(RLA, ZPG, 5), /*0x28*/(PLP, IMP, 4),(AND, IMM, 2),(ROL, ACC, 2),(ANC, IMM, 2),(BIT, ABS, 4),(AND, ABS, 4),(ROL, ABS, 6),(RLA, ABS, 6), /*0x30*/(BMI, REL, 2),(AND, ZIY, 5),(STP, NON, 2),(RLA, ZIY, 8),(NOP, ZPX, 4),(AND, ZPX, 4),(ROL, ZPX, 6),(RLA, ZPX, 6), /*0x38*/(SEC, IMP, 2),(AND, aby, 4),(NOP, IMP, 2),(RLA, ABY, 7),(NOP, abx, 4),(AND, abx, 4),(ROL, ABX, 7),(RLA, ABX, 7), /*0x40*/(RTI, IMP, 6),(EOR, ZIX, 6),(STP, NON, 2),(SRE, ZIX, 8),(NOP, ZPG, 3),(EOR, ZPG, 3),(LSR, ZPG, 5),(SRE, ZPG, 5), /*0x48*/(PHA, IMP, 3),(EOR, IMM, 2),(LSR, ACC, 2),(ALR, IMM, 2),(JMP, ABS, 3),(EOR, ABS, 4),(LSR, ABS, 6),(SRE, ABS, 6), /*0x50*/(BVC, REL, 2),(EOR, ZIY, 5),(STP, NON, 2),(SRE, ZIY, 8),(NOP, ZPX, 4),(EOR, ZPX, 4),(LSR, ZPX, 6),(SRE, ZPX, 6), /*0x58*/(CLI, IMP, 2),(EOR, aby, 4),(NOP, IMP, 2),(SRE, ABY, 7),(NOP, abx, 4),(EOR, abx, 4),(LSR, ABX, 7),(SRE, ABX, 7), /*0x60*/(RTS, IMP, 6),(ADC, ZIX, 6),(STP, NON, 2),(RRA, ZIX, 8),(NOP, ZPG, 3),(ADC, ZPG, 3),(ROR, ZPG, 5),(RRA, ZPG, 5), /*0x68*/(PLA, IMP, 4),(ADC, IMM, 2),(ROR, ACC, 2),(ARR, IMM, 2),(JMP, IND, 5),(ADC, ABS, 4),(ROR, ABS, 6),(RRA, ABS, 6), /*0x70*/(BVS, REL, 2),(ADC, ziy, 5),(STP, NON, 2),(RRA, ZIY, 8),(NOP, ZPX, 4),(ADC, ZPX, 4),(ROR, ZPX, 6),(RRA, ZPX, 6), /*0x78*/(SEI, IMP, 2),(ADC, aby, 4),(NOP, IMP, 2),(RRA, ABY, 7),(NOP, abx, 4),(ADC, abx, 4),(ROR, ABX, 7),(RRA, ABX, 7), /*0x80*/(NOP, IMM, 2),(STA, ZIX, 6),(NOP, IMM, 2),(SAX, ZIX, 6),(STY, ZPG, 3),(STA, ZPG, 3),(STX, ZPG, 3),(SAX, ZPG, 3), /*0x88*/(DEY, IMP, 2),(NOP, IMM, 2),(TXA, IMP, 2),(XXA, IMM, 2),(STY, ABS, 4),(STA, ABS, 4),(STX, ABS, 4),(SAX, ABS, 4), /*0x90*/(BCC, REL, 2),(STA, ZIY, 6),(STP, NON, 2),(AHX, ZIY, 6),(STY, ZPX, 4),(STA, ZPX, 4),(STX, ZPY, 4),(SAX, ZPY, 4), /*0x98*/(TYA, IMP, 2),(STA, ABY, 5),(TXS, IMP, 2),(TAS, ABY, 5),(SHY, ABX, 5),(STA, ABX, 5),(SHX, ABY, 5),(AHX, ABY, 5), /*0xA0*/(LDY, IMM, 2),(LDA, ZIX, 6),(LDX, IMM, 2),(LAX, ZIX, 6),(LDY, ZPG, 3),(LDA, ZPG, 3),(LDX, ZPG, 3),(LAX, ZPG, 3), /*0xA8*/(TAY, IMP, 2),(LDA, IMM, 2),(TAX, IMP, 2),(LAX, IMM, 2),(LDY, ABS, 4),(LDA, ABS, 4),(LDX, ABS, 4),(LAX, ABS, 4), /*0xB0*/(BCS, REL, 2),(LDA, ziy, 5),(STP, NON, 2),(LAX, ziy, 5),(LDY, ZPX, 4),(LDA, ZPX, 4),(LDX, ZPY, 4),(LAX, ZPY, 4), /*0xB8*/(CLV, IMP, 2),(LDA, aby, 4),(TSX, IMP, 2),(LAS, ABY, 4),(LDY, abx, 4),(LDA, abx, 4),(LDX, aby, 4),(LAX, aby, 4), /*0xC0*/(CPY, IMM, 2),(CMP, ZIX, 6),(NOP, IMM, 2),(DCP, ZIX, 8),(CPY, ZPG, 3),(CMP, ZPG, 3),(DEC, ZPG, 5),(DCP, ZPG, 5), /*0xC8*/(INY, IMP, 2),(CMP, IMM, 2),(DEX, IMP, 2),(AXS, IMM, 2),(CPY, ABS, 4),(CMP, ABS, 4),(DEC, ABS, 6),(DCP, ABS, 6), /*0xD0*/(BNE, REL, 2),(CMP, ziy, 5),(STP, NON, 2),(DCP, ZIY, 8),(NOP, ZPX, 4),(CMP, ZPX, 4),(DEC, ZPX, 6),(DCP, ZPX, 6), /*0xD8*/(CLD, IMP, 2),(CMP, aby, 4),(NOP, IMP, 2),(DCP, ABY, 7),(NOP, abx, 4),(CMP, abx, 4),(DEC, ABX, 7),(DCP, ABX, 7), /*0xE0*/(CPX, IMM, 2),(SBC, ZIX, 6),(NOP, IMM, 3),(ISC, ZIX, 8),(CPX, ZPG, 3),(SBC, ZPG, 3),(INC, ZPG, 5),(ISC, ZPG, 5), /*0xE8*/(INX, IMP, 2),(SBC, IMM, 2),(NOP, IMP, 2),(SBC, IMM, 2),(CPX, ABS, 4),(SBC, ABS, 4),(INC, ABS, 6),(ISC, ABS, 6), /*0xF0*/(BEQ, REL, 2),(SBC, ZIY, 5),(STP, NON, 2),(ISC, ZIY, 8),(NOP, ZPX, 4),(SBC, ZPX, 4),(INC, ZPX, 6),(ISC, ZPX, 6), /*0xF8*/(SED, IMP, 2),(SBC, aby, 4),(NOP, IMP, 2),(ISC, ABY, 7),(NOP, abx, 4),(SBC, abx, 4),(INC, ABX, 7),(ISC, ABX, 7), ];
use super::address::AM::{self, *}; #[derive(Debug, Clone, Copy)] #[allow(non_camel_case_types)] pub enum OP { LDA, LDX, LDY, STA, STX, STY, TAX, TAY, TXA, TYA, TSX, TXS, PHA, PHP, PLA, PLP, ADC, SBC, INX, INY, DEX, DEY, INC, DEC, AND, ORA, EOR, BIT, CMP, CPX, CPY, ASL, LSR, ROL, ROR, CLC, CLD, CLI, CLV, SEC, SED, SEI, JMP, JSR, RTS, RTI, BRK, BEQ, BNE, BCS, BCC, BVS, BVC, BMI, BPL, NOP, ALR, ANC, ARR, AXS, LAX, SAX, DCP, ISC, RLA, RRA, SLO, SRE, SHY, SHX, STP, XXA, AHX, TAS, LAS, } use self::OP::*; #[rustfmt::skip] pub static DECODE: [(OP, AM, u8); 256] = [ /*0x00*/(BRK, IMP, 7),(ORA, ZIX, 6),(STP, NON, 2),(SLO, ZIX, 8),(NOP, ZPG, 3),(ORA, ZPG, 3),(ASL, ZPG, 5),(SLO, ZPG, 5), /*0x08*/(PHP, IMP, 3),(ORA, IMM, 2),(ASL, ACC, 2),(ANC, IMM, 2),(NOP, ABS, 4),(ORA, ABS, 4),(ASL, ABS, 6),(SLO, ABS, 6), /*0x10*/(BPL, REL, 2),(ORA, ZIY, 5),(STP, NON, 2),(SLO, ZIY, 8),(NOP, ZPX, 4),(ORA, ZPX, 4),(ASL, ZPX, 6),(SLO, ZPX, 6), /*0x18*/(CLC, IMP, 2),(ORA, aby, 4),(NOP, IMP, 2),(SLO, ABY, 7),(NOP, abx, 4),(ORA, abx, 4),(ASL, ABX, 7),(SLO, ABX, 7), /*0x20*/(JSR, ABS, 6),(AND, ZIX, 6),(STP, NON, 2),(RLA, ZIX,
),(STA, ZPX, 4),(STX, ZPY, 4),(SAX, ZPY, 4), /*0x98*/(TYA, IMP, 2),(STA, ABY, 5),(TXS, IMP, 2),(TAS, ABY, 5),(SHY, ABX, 5),(STA, ABX, 5),(SHX, ABY, 5),(AHX, ABY, 5), /*0xA0*/(LDY, IMM, 2),(LDA, ZIX, 6),(LDX, IMM, 2),(LAX, ZIX, 6),(LDY, ZPG, 3),(LDA, ZPG, 3),(LDX, ZPG, 3),(LAX, ZPG, 3), /*0xA8*/(TAY, IMP, 2),(LDA, IMM, 2),(TAX, IMP, 2),(LAX, IMM, 2),(LDY, ABS, 4),(LDA, ABS, 4),(LDX, ABS, 4),(LAX, ABS, 4), /*0xB0*/(BCS, REL, 2),(LDA, ziy, 5),(STP, NON, 2),(LAX, ziy, 5),(LDY, ZPX, 4),(LDA, ZPX, 4),(LDX, ZPY, 4),(LAX, ZPY, 4), /*0xB8*/(CLV, IMP, 2),(LDA, aby, 4),(TSX, IMP, 2),(LAS, ABY, 4),(LDY, abx, 4),(LDA, abx, 4),(LDX, aby, 4),(LAX, aby, 4), /*0xC0*/(CPY, IMM, 2),(CMP, ZIX, 6),(NOP, IMM, 2),(DCP, ZIX, 8),(CPY, ZPG, 3),(CMP, ZPG, 3),(DEC, ZPG, 5),(DCP, ZPG, 5), /*0xC8*/(INY, IMP, 2),(CMP, IMM, 2),(DEX, IMP, 2),(AXS, IMM, 2),(CPY, ABS, 4),(CMP, ABS, 4),(DEC, ABS, 6),(DCP, ABS, 6), /*0xD0*/(BNE, REL, 2),(CMP, ziy, 5),(STP, NON, 2),(DCP, ZIY, 8),(NOP, ZPX, 4),(CMP, ZPX, 4),(DEC, ZPX, 6),(DCP, ZPX, 6), /*0xD8*/(CLD, IMP, 2),(CMP, aby, 4),(NOP, IMP, 2),(DCP, ABY, 7),(NOP, abx, 4),(CMP, abx, 4),(DEC, ABX, 7),(DCP, ABX, 7), /*0xE0*/(CPX, IMM, 2),(SBC, ZIX, 6),(NOP, IMM, 3),(ISC, ZIX, 8),(CPX, ZPG, 3),(SBC, ZPG, 3),(INC, ZPG, 5),(ISC, ZPG, 5), /*0xE8*/(INX, IMP, 2),(SBC, IMM, 2),(NOP, IMP, 2),(SBC, IMM, 2),(CPX, ABS, 4),(SBC, ABS, 4),(INC, ABS, 6),(ISC, ABS, 6), /*0xF0*/(BEQ, REL, 2),(SBC, ZIY, 5),(STP, NON, 2),(ISC, ZIY, 8),(NOP, ZPX, 4),(SBC, ZPX, 4),(INC, ZPX, 6),(ISC, ZPX, 6), /*0xF8*/(SED, IMP, 2),(SBC, aby, 4),(NOP, IMP, 2),(ISC, ABY, 7),(NOP, abx, 4),(SBC, abx, 4),(INC, ABX, 7),(ISC, ABX, 7), ];
8),(BIT, ZPG, 3),(AND, ZPG, 3),(ROL, ZPG, 5),(RLA, ZPG, 5), /*0x28*/(PLP, IMP, 4),(AND, IMM, 2),(ROL, ACC, 2),(ANC, IMM, 2),(BIT, ABS, 4),(AND, ABS, 4),(ROL, ABS, 6),(RLA, ABS, 6), /*0x30*/(BMI, REL, 2),(AND, ZIY, 5),(STP, NON, 2),(RLA, ZIY, 8),(NOP, ZPX, 4),(AND, ZPX, 4),(ROL, ZPX, 6),(RLA, ZPX, 6), /*0x38*/(SEC, IMP, 2),(AND, aby, 4),(NOP, IMP, 2),(RLA, ABY, 7),(NOP, abx, 4),(AND, abx, 4),(ROL, ABX, 7),(RLA, ABX, 7), /*0x40*/(RTI, IMP, 6),(EOR, ZIX, 6),(STP, NON, 2),(SRE, ZIX, 8),(NOP, ZPG, 3),(EOR, ZPG, 3),(LSR, ZPG, 5),(SRE, ZPG, 5), /*0x48*/(PHA, IMP, 3),(EOR, IMM, 2),(LSR, ACC, 2),(ALR, IMM, 2),(JMP, ABS, 3),(EOR, ABS, 4),(LSR, ABS, 6),(SRE, ABS, 6), /*0x50*/(BVC, REL, 2),(EOR, ZIY, 5),(STP, NON, 2),(SRE, ZIY, 8),(NOP, ZPX, 4),(EOR, ZPX, 4),(LSR, ZPX, 6),(SRE, ZPX, 6), /*0x58*/(CLI, IMP, 2),(EOR, aby, 4),(NOP, IMP, 2),(SRE, ABY, 7),(NOP, abx, 4),(EOR, abx, 4),(LSR, ABX, 7),(SRE, ABX, 7), /*0x60*/(RTS, IMP, 6),(ADC, ZIX, 6),(STP, NON, 2),(RRA, ZIX, 8),(NOP, ZPG, 3),(ADC, ZPG, 3),(ROR, ZPG, 5),(RRA, ZPG, 5), /*0x68*/(PLA, IMP, 4),(ADC, IMM, 2),(ROR, ACC, 2),(ARR, IMM, 2),(JMP, IND, 5),(ADC, ABS, 4),(ROR, ABS, 6),(RRA, ABS, 6), /*0x70*/(BVS, REL, 2),(ADC, ziy, 5),(STP, NON, 2),(RRA, ZIY, 8),(NOP, ZPX, 4),(ADC, ZPX, 4),(ROR, ZPX, 6),(RRA, ZPX, 6), /*0x78*/(SEI, IMP, 2),(ADC, aby, 4),(NOP, IMP, 2),(RRA, ABY, 7),(NOP, abx, 4),(ADC, abx, 4),(ROR, ABX, 7),(RRA, ABX, 7), /*0x80*/(NOP, IMM, 2),(STA, ZIX, 6),(NOP, IMM, 2),(SAX, ZIX, 6),(STY, ZPG, 3),(STA, ZPG, 3),(STX, ZPG, 3),(SAX, ZPG, 3), /*0x88*/(DEY, IMP, 2),(NOP, IMM, 2),(TXA, IMP, 2),(XXA, IMM, 2),(STY, ABS, 4),(STA, ABS, 4),(STX, ABS, 4),(SAX, ABS, 4), /*0x90*/(BCC, REL, 2),(STA, ZIY, 6),(STP, NON, 2),(AHX, ZIY, 6),(STY, ZPX, 4
random
[ { "content": "pub trait Memory {\n\n fn reset(&mut self);\n\n fn loadb(&mut self, addr: u16) -> u8;\n\n fn try_loadb(&self, addr: u16) -> Option<u8>;\n\n fn storeb(&mut self, addr: u16, val: u8);\n\n fn add_cycles(&mut self, val: usize);\n\n fn get_cycles(&self) -> usize;\n\n}\n\n\n\npub struc...
Rust
src/day14/data/mod.rs
Fryuni/advent-of-code-2021
832121aba87516b4c2727eee9869348e1a5a7840
/* * MIT License * * Copyright (c) 2021 Luiz Ferraz * * 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. */ pub mod parser; use itertools::Itertools; use std::collections::HashMap; use std::fmt::{Debug, Formatter, Write}; use std::ops::AddAssign; #[derive(Clone)] pub struct Polymer(Vec<char>); #[derive(Debug)] pub struct PairCounters(HashMap<(char, char), usize>); #[derive(Debug)] pub struct PolymerizationRules { pairs: HashMap<(char, char), char>, } impl Polymer { pub fn grow(&mut self, rules: &PolymerizationRules) { let mut elements = Vec::with_capacity(2 * self.0.len() - 1); for pair in self.0.iter().copied().tuple_windows::<(_, _)>() { elements.push(pair.0); if let Some(extra) = rules.pairs.get(&pair) { elements.push(*extra); } } elements.push(*self.0.last().unwrap()); self.0 = elements; } pub fn elements(&self) -> &[char] { &self.0 } } impl From<&Polymer> for PairCounters { fn from(polymer: &Polymer) -> Self { Self( polymer .elements() .iter() .copied() .tuple_windows::<(_, _)>() .counts(), ) } } impl PairCounters { pub fn project_growth(&mut self, rules: &PolymerizationRules) { let mut new_counters: HashMap<(char, char), usize> = HashMap::with_capacity(self.0.len()); for (&(a, b), &count) in &self.0 { if let Some(&extra) = rules.pairs.get(&(a, b)) { new_counters .entry((a, extra)) .or_default() .add_assign(count); new_counters .entry((extra, b)) .or_default() .add_assign(count); } else { new_counters.entry((a, b)).or_default().add_assign(count); } } self.0 = new_counters; } pub fn into_element_counters(self) -> HashMap<char, usize> { let mut counters: HashMap<char, usize> = HashMap::new(); for ((a, _), count) in self.0 { counters.entry(a).or_default().add_assign(count); } counters } } #[derive(Debug)] pub struct Data { pub template: Polymer, pub rules: PolymerizationRules, } impl Debug for Polymer { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("Polymer(")?; for c in &self.0 { f.write_char(*c)?; } f.write_str(")") } }
/* * MIT License * * Copyright (c) 2021 Luiz Ferraz * * 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. */ pub mod parser; use itertools::Itertools; use std::collections::HashMap; use std::fmt::{Debug, Formatter, Write}; use std::ops::AddAssign; #[derive(Clone)] pub struct Polymer(Vec<char>); #[derive(Debug)] pub struct PairCounters(HashMap<(char, char), usize>); #[derive(Debug)] pub struct PolymerizationRules { pairs: HashMap<(char, char), char>, } impl Polymer { pub fn grow(&mut self, rules: &PolymerizationRules) { let mut elements = Vec::with_capacity(2 * self.0.len() - 1); for pair in self.0.iter().copied().tuple_windows::<(_, _)>() { elements.push(pair.0); if let Some(extra) = rules.pairs.get(&pair) { elements.push(*extra); } } elements.push(*self.0.last().unwrap()); self.0 = elements; } pub fn elements(&self) -> &[char] { &self.0 } } impl From<&Polymer> for PairCounters { fn from(polymer: &Polymer) -> Self { Self( polymer .elements() .iter() .copied() .tuple_windows::<(_, _)>() .counts(), ) } } impl PairCounters { pub fn project_growth(&mut self, rules: &PolymerizationRules) { let mut new_counters: HashMap<(char, char), usize> = HashMap::with_capacity(self.0.len()); for (&(a, b), &count) in &self.0 { if let Some(&extra) = rules.pairs.get(&(a, b)) { new_counters .entry((a, extra)) .or_default() .add_assign(count); new_counters .entry((extra, b)) .or_default() .add_assign(count); } else { new_counters.entry((a, b)).or_default().add_assign(count); } } self.0 = new_counters; }
} #[derive(Debug)] pub struct Data { pub template: Polymer, pub rules: PolymerizationRules, } impl Debug for Polymer { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("Polymer(")?; for c in &self.0 { f.write_char(*c)?; } f.write_str(")") } }
pub fn into_element_counters(self) -> HashMap<char, usize> { let mut counters: HashMap<char, usize> = HashMap::new(); for ((a, _), count) in self.0 { counters.entry(a).or_default().add_assign(count); } counters }
function_block-function_prefix_line
[ { "content": "fn iter_matrix() -> impl Iterator<Item = (usize, usize)> {\n\n (0..10).cartesian_product(0..10)\n\n}\n\n\n\nimpl State {\n\n const FLASHED: usize = 20;\n\n\n\n pub fn advance_state(&mut self) -> usize {\n\n // println!(\"Initial state:\\n{:?}\", self);\n\n\n\n // Advance all...
Rust
crates/melody_cli/src/main.rs
ikroeber/melody
693832f659482d100000da84d6fc55b8ff43dd07
pub mod consts; pub mod macros; pub mod output; pub mod utils; use clap::Parser; use consts::COMMAND_MARKER; use melody_compiler::{compiler, ParseError}; use output::{ print_output, print_output_pretty, print_repl_welcome, print_source_line, prompt, report_clear, report_exit, report_missing_path, report_no_lines_to_print, report_nothing_to_redo, report_nothing_to_undo, report_parse_error, report_read_file_error, report_read_input_error, report_redo, report_repl_parse_error, report_source, report_undo, report_unrecognized_command, report_write_file_error, }; use std::fs::{read_to_string, write}; use utils::{exit, read_input, ExitCode}; #[derive(Parser, Debug)] #[clap(about, version, author)] struct Args { #[clap(value_name = "INPUT_FILE_PATH", help = "Read from a file")] input_file_path: Option<String>, #[clap( short = 'o', long = "output", value_name = "OUTPUT_FILE_PATH", help = "Write to a file" )] output_file_path: Option<String>, #[clap(short = 'n', long = "no-color", help = "Print output with no color")] no_color_output: bool, #[clap(short = 'r', long = "repl", help = "Start the Melody REPL")] start_repl: bool, } enum CliError { MissingPath, ReadFileError(String), ParseError(ParseError), WriteFileError(String), ReadInputError, } fn main() { match cli() { Ok(_) => exit(ExitCode::Ok), Err(error) => { match error { CliError::MissingPath => report_missing_path(), CliError::ReadFileError(path) => report_read_file_error(path), CliError::WriteFileError(output_file_path) => { report_write_file_error(output_file_path) } CliError::ParseError(parse_error) => report_parse_error( parse_error.token, parse_error.line, parse_error.line_index + 1, ), CliError::ReadInputError => report_read_input_error(), } exit(ExitCode::Error) } }; } fn cli() -> Result<(), CliError> { let args = Args::parse(); let Args { start_repl, input_file_path, output_file_path, no_color_output, } = args; if start_repl { return repl(); } let input_file_path = input_file_path.ok_or(CliError::MissingPath)?; let source = read_to_string(input_file_path.clone()) .map_err(|_| CliError::ReadFileError(input_file_path))?; let compiler_output = compiler(&source).map_err(CliError::ParseError)?; match output_file_path { Some(output_file_path) => { write(&output_file_path, compiler_output) .map_err(|_| CliError::WriteFileError(output_file_path))?; } None => { if no_color_output { print_output(compiler_output); } else { print_output_pretty(compiler_output); } } } Ok(()) } fn repl() -> Result<(), CliError> { print_repl_welcome(); let mut valid_lines: Vec<String> = Vec::new(); let mut redo_lines: Vec<String> = Vec::new(); 'repl: loop { prompt(); let input = read_input().map_err(|_| CliError::ReadInputError)?; if input.starts_with(COMMAND_MARKER) { match input.as_str() { format_command!("u", "undo") => { if valid_lines.is_empty() { report_nothing_to_undo(); } else { report_undo(false); let latest = valid_lines.pop().unwrap(); redo_lines.push(latest); if !valid_lines.is_empty() { let source = &valid_lines.join("\n"); let raw_output = compiler(source); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")); } } } format_command!("r", "redo") => { if redo_lines.is_empty() { report_nothing_to_redo(); } else { report_redo(); let latest = redo_lines.pop().unwrap(); valid_lines.push(latest); let source = &valid_lines.join("\n"); let raw_output = compiler(source); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")); } } format_command!("s", "source") => { if valid_lines.is_empty() { report_no_lines_to_print(); } else { report_source(); for (line_index, line) in valid_lines.iter().enumerate() { print_source_line(line_index + 1, String::from(line)); } println!(); } } format_command!("c", "clear") => { report_clear(); valid_lines.clear(); redo_lines.clear(); } format_command!("e", "exit") => { report_exit(); return Ok(()); } _ => report_unrecognized_command(input.trim().to_owned()), } continue 'repl; } if input.is_empty() { let source = &valid_lines.join("\n"); let raw_output = compiler(source); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")); continue 'repl; } valid_lines.push(input); let source = &valid_lines.join("\n"); let raw_output = compiler(source); if let Err(error) = raw_output { let ParseError { token, line: _, line_index: _, } = error; report_repl_parse_error(token); valid_lines.pop(); continue 'repl; } redo_lines.clear(); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")) } }
pub mod consts; pub mod macros; pub mod output; pub mod utils; use clap::Parser; use consts::COMMAND_MARKER; use melody_compiler::{compiler, ParseError}; use output::{ print_output, print_output_pretty, print_repl_welcome, print_source_line, prompt, report_clear, report_exit, report_missing_path, report_no_lines_to_print, report_nothing_to_redo, report_nothing_to_undo, report_parse_error, report_read_file_error, report_read_input_error, report_redo, report_repl_parse_error, report_source, report_undo, report_unrecognized_command, report_write_file_error, }; use std::fs::{read_to_string, write}; use utils::{exit, read_input, ExitCode}; #[derive(Parser, Debug)] #[clap(about, version, author)] struct Args { #[clap(value_name = "INPUT_FILE_PATH", help = "Read from a file")] input_file_path: Option<String>, #[clap( short = 'o', long = "output", value_name = "OUTPUT_FILE_PATH", help = "Write to a file" )] output_file_path: Option<String>, #[clap(short = 'n', long = "no-color", help = "Print output with no color")] no_color_output: bool, #[clap(short = 'r', long = "repl", help = "Start the Melody REPL")] start_repl: bool, } enum CliError { MissingPath, ReadFileError(String), ParseError(ParseError), WriteFileError(String), ReadInputError, } fn main() { match cli() { Ok(_) => exit(ExitCode::Ok), Err(error) => { match error { CliError::MissingPath => report_missing_path(), CliError::ReadFileError(path) => report_read_file_error(path), CliError::WriteFileError(output_file_path) => { report_write_file_error(output_file_path) } CliError::ParseError(parse_error) => report_parse_error( parse_error.token, parse_error.line, parse_error.line_index + 1, ), CliError::ReadInputError => report_read_input_error(), } exit(ExitCode::Error) } }; } fn cli() -> Result<(), CliError> { let args = Args::parse(); let Args { start_repl, input_file_path, output_file_path, no_color_output, } = args; if start_repl { return repl(); } let input_file_path = input_file_path.ok_or(CliError::MissingPath)?; let source = read_to_string(input_file_path.clone()) .map_err(|_| CliError::ReadFileError(input_file_path))?; let compiler_output = compiler(&source).map_err(CliError::ParseError)?; match output_file_path { Some(output_file_path) => { write(&output_file_path, compiler_output) .map_err(|_| CliError::WriteFileError(output_file_path))?; } None => { if no_color_output { print_output(compiler_output); } else { print_output_pretty(compiler_output); } } } Ok(()) } fn repl() -> Result<(), CliError> { print_repl_welcome(); let mut valid_lines: Vec<String> = Vec::new(); let mut redo_lines: Vec<String> = Vec::new(); 'repl: loop { prompt(); let input = read_input().map_err(|_| CliError::ReadInputError)?; if input.starts_with(COMMAND_MARKER) { match input.as_str() { format_command!("u", "undo") => { if valid_lines.is_empty() { report_nothing_to_undo(); } else { report_undo(false); let latest = valid_lines.pop().unwrap(); redo_lines.push(latest); if !valid_lines.is_empty() { let source = &valid_lines.join("\n"); let raw_output = compiler(source); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")); } } } format_command!("r", "redo") => { if redo_lines.is_empty() { report_nothing_to_redo(); } else { report_redo(); let latest = redo_lines.pop().unwrap(); valid_lines.push(latest); let source = &valid_lines.join("\n"); let raw_output = compiler(source); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")); } } format_command!("s", "source") => { if valid_lines.is_empty() { report_no_lines_to_print(); } else { report_source(); for (line_index, line) in valid_lines.iter().enumerate() { print_source_line(line_index + 1, String::from(line)); } println!(); } } format_command!("c", "clear") => { report_clear(); valid_lines.clear(); redo_lines.clear(); } format_command!("e", "exit") => { report_exit(); return Ok(()); } _ => report_unrecognized_command(input.trim().to_owned()), } continue 'repl; } if input.is_empty() { let source = &valid_lines.join("\n"); let raw_output = compiler(source); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")); continue 'repl; } valid_lines.push(input); let source = &valid_lines.join("\n"); let raw_output = compiler(source);
redo_lines.clear(); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")) } }
if let Err(error) = raw_output { let ParseError { token, line: _, line_index: _, } = error; report_repl_parse_error(token); valid_lines.pop(); continue 'repl; }
if_condition
[]
Rust
crates/wasm-bindgen-cli-support/src/lib.rs
lukewagner/wasm-bindgen
7384bd1967e325101b09234753598122c71eaefe
#[macro_use] extern crate failure; extern crate parity_wasm; extern crate wasm_bindgen_shared as shared; extern crate serde_json; extern crate wasm_gc; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use failure::Error; use parity_wasm::elements::*; mod js; pub mod wasm2es6js; pub struct Bindgen { path: Option<PathBuf>, nodejs: bool, debug: bool, typescript: bool, } impl Bindgen { pub fn new() -> Bindgen { Bindgen { path: None, nodejs: false, debug: false, typescript: false, } } pub fn input_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Bindgen { self.path = Some(path.as_ref().to_path_buf()); self } pub fn nodejs(&mut self, node: bool) -> &mut Bindgen { self.nodejs = node; self } pub fn debug(&mut self, debug: bool) -> &mut Bindgen { self.debug = debug; self } pub fn typescript(&mut self, typescript: bool) -> &mut Bindgen { self.typescript = typescript; self } pub fn generate<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { self._generate(path.as_ref()) } fn _generate(&mut self, out_dir: &Path) -> Result<(), Error> { let input = match self.path { Some(ref path) => path, None => panic!("must have a path input for now"), }; let stem = input.file_stem().unwrap().to_str().unwrap(); let mut module = parity_wasm::deserialize_file(input).map_err(|e| { format_err!("{:?}", e) })?; let program = extract_program(&mut module); let (js, ts) = js::Js { globals: String::new(), imports: String::new(), typescript: format!("/* tslint:disable */\n"), exposed_globals: Default::default(), required_internal_exports: Default::default(), config: &self, module: &mut module, program: &program, }.generate(stem); let js_path = out_dir.join(stem).with_extension("js"); File::create(&js_path).unwrap() .write_all(js.as_bytes()).unwrap(); if self.typescript { let ts_path = out_dir.join(stem).with_extension("d.ts"); File::create(&ts_path).unwrap() .write_all(ts.as_bytes()).unwrap(); } let wasm_path = out_dir.join(format!("{}_wasm", stem)).with_extension("wasm"); let wasm_bytes = parity_wasm::serialize(module).map_err(|e| { format_err!("{:?}", e) })?; let bytes = wasm_gc::Config::new() .demangle(false) .gc(&wasm_bytes)?; File::create(&wasm_path)?.write_all(&bytes)?; Ok(()) } } fn extract_program(module: &mut Module) -> shared::Program { let data = module.sections_mut() .iter_mut() .filter_map(|s| { match *s { Section::Data(ref mut s) => Some(s), _ => None, } }) .next(); let mut ret = shared::Program { structs: Vec::new(), free_functions: Vec::new(), imports: Vec::new(), imported_structs: Vec::new(), custom_type_names: Vec::new(), }; let data = match data { Some(data) => data, None => return ret, }; for i in (0..data.entries().len()).rev() { { let value = data.entries()[i].value(); if !value.starts_with(b"wbg:") { continue } let json = &value[4..]; let p = match serde_json::from_slice(json) { Ok(f) => f, Err(e) => { panic!("failed to decode what looked like wasm-bindgen data: {}", e) } }; let shared::Program { structs, free_functions, imports, imported_structs, custom_type_names, } = p; ret.structs.extend(structs); ret.free_functions.extend(free_functions); ret.imports.extend(imports); ret.imported_structs.extend(imported_structs); if custom_type_names.len() > 0 { assert_eq!(ret.custom_type_names.len(), 0); } ret.custom_type_names.extend(custom_type_names); } data.entries_mut().remove(i); } return ret }
#[macro_use] extern crate failure; extern crate parity_wasm; extern crate wasm_bindgen_shared as shared; extern crate serde_json; extern crate wasm_gc; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use failure::Error; use parity_wasm::elements::*; mod js; pub mod wasm2es6js; pub struct Bindgen { path: Option<PathBuf>, nodejs: bool, debug: bool, typescript: bool, } impl Bindgen { pub fn new() -> Bindgen { Bindgen { path: None, nodejs: false, debug: false, typescript: false, } } pub fn input_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Bindgen { self.path = Some(path.as_ref().to_path_buf()); self } pub fn nodejs(&mut self, node: bool) -> &mut Bindgen { self.nodejs = node; self } pub fn debug(&mut self, debug: bool) -> &mut Bindgen { self.debug = debug; self } pub fn typescript(&mut self, typescript: bool) -> &mut Bindgen { self.typescript = typescript; self } pub fn generate<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { self._generate(path.as_ref()) } fn _generate(&mut self, out_dir: &Path) -> Result<(), Error> { let input = match self.path { Some(ref path) => path, None => panic!("must have a path input for now"), }; let stem = input.file_stem().unwrap().to_str().unwrap(); let mut module = parity_wasm::deserialize_file(input).map_err(|e| { format_err!("{:?}", e) })?; let program = extract_program(&mut module); let (js, ts) = js::Js { globals: String::new(), imports: String::new(), typescript: format!("/* tslint:disable */\n"), exposed_globals: Default::default(), required_internal_exports: Default::default(), config: &self, module: &mut module, program: &program, }.generate(stem); let js_path = out_dir.join(stem).with_extension("js"); File::create(&js_path).unwrap() .write_all(js.as_bytes()).unwrap(); if self.typescript { let ts_path = out_dir.join(stem).with_extension("d.ts"); File::create(&ts_path).unwrap() .write_all(ts.as_bytes()).unwrap(); } let wasm_path = out_dir.join(format!("{}_wasm", stem)).with_extension("wasm"); let wasm_bytes = parity_wasm::serialize(module).map_err(|e| { format_err!("{:?}", e) })?; let bytes = wasm_gc::Config::new() .demangle(false) .gc(&wasm_bytes)?; File::create(&wasm_path)?.write_all(&bytes)?; Ok(()) } } fn extract_program(module: &mut Module) -> shared::Program { let data = module.sections_mut() .iter_mut() .filter_map(|s| { match *s { Section::Data(ref mut s) => Some(s), _ => None, } }) .next(); let mut ret = shared::Program { structs: Vec::new(), free_functions: Vec::new(), imports: Vec::new(), imported_structs: Vec::new(), cus
ts, imported_structs, custom_type_names, } = p; ret.structs.extend(structs); ret.free_functions.extend(free_functions); ret.imports.extend(imports); ret.imported_structs.extend(imported_structs); if custom_type_names.len() > 0 { assert_eq!(ret.custom_type_names.len(), 0); } ret.custom_type_names.extend(custom_type_names); } data.entries_mut().remove(i); } return ret }
tom_type_names: Vec::new(), }; let data = match data { Some(data) => data, None => return ret, }; for i in (0..data.entries().len()).rev() { { let value = data.entries()[i].value(); if !value.starts_with(b"wbg:") { continue } let json = &value[4..]; let p = match serde_json::from_slice(json) { Ok(f) => f, Err(e) => { panic!("failed to decode what looked like wasm-bindgen data: {}", e) } }; let shared::Program { structs, free_functions, impor
function_block-random_span
[ { "content": "fn bindgen_imported_struct(import: &ast::ImportStruct, tokens: &mut Tokens) {\n\n let name = import.name;\n\n\n\n let mut methods = Tokens::new();\n\n\n\n for &(_is_method, ref f) in import.functions.iter() {\n\n let import_name = shared::mangled_import_name(\n\n Some(&i...
Rust
blocky-net/src/chat/component.rs
JAD3N/minecraft
cfa74fa48ca9c1399eb02cd11332f86121e7bd85
use super::{Style, TextComponent, TranslatableComponent, TranslatableComponentArg}; use crate::{AsJson, FromJson}; use thiserror::Error; #[derive(Error, Debug)] pub enum ComponentError { #[error("failed to parse json")] Parse, } pub trait ComponentClone { fn clone_box(&self) -> Box<dyn Component>; } pub trait ComponentContent { fn contents(&self) -> &str { "" } } pub trait Component: mopa::Any + AsJson + ComponentContent + ComponentClone { fn siblings(&self) -> &Vec<Box<dyn Component>>; fn siblings_mut(&mut self) -> &mut Vec<Box<dyn Component>>; fn append(&mut self, component: Box<dyn Component>) { self.siblings_mut().push(component); } fn style(&self) -> &Style; fn style_mut(&mut self) -> &mut Style; fn set_style(&mut self, style: Style) { *self.style_mut() = style; } fn get_base_json(&self) -> serde_json::Value { let mut value = json!({}); let style = self.style().as_json(); if let serde_json::Value::Object(m) = style { for entry in m { value[entry.0] = entry.1; } } if !self.siblings().is_empty() { value["extra"] = self .siblings() .iter() .map(|sibling| sibling.as_json()) .collect::<serde_json::Value>() .into(); } value } } mopafy!(Component); impl Clone for Box<dyn Component> { fn clone(&self) -> Box<dyn Component> { self.clone_box() } } impl FromJson for Box<dyn Component> { type Err = ComponentError; fn from_json(value: &serde_json::Value) -> Result<Self, Self::Err> { if value.is_string() { Ok(Box::new(TextComponent::new(value.as_str().unwrap()))) } else if value.is_object() { let obj = value.as_object().unwrap(); let mut c: Box<dyn Component> = if let Some(text) = obj.get("text") { let text = text.as_str().ok_or(ComponentError::Parse)?; Box::new(TextComponent::new(text)) } else if let Some(translate) = obj.get("translate") { let translate = translate.as_str().ok_or(ComponentError::Parse)?; let mut args = vec![]; if let Some(with) = obj.get("with") { let with = with.as_array().ok_or(ComponentError::Parse)?; for arg in with { if let Ok(sub_c) = Self::from_json(arg) { if sub_c.is::<TextComponent>() && sub_c.style().is_empty() && sub_c.siblings().is_empty() { let text = sub_c.contents().into(); args.push(TranslatableComponentArg::String(text)); } else { args.push(TranslatableComponentArg::Component(sub_c)); } } } } Box::new(TranslatableComponent::new(translate, args)) } else { return Err(ComponentError::Parse); }; if obj.contains_key("extra") && obj["extra"].is_array() { for entry in value["extra"].as_array().unwrap() { c.append(Self::from_json(entry)?); } } if let Ok(style) = Style::from_json(value) { if !style.is_empty() { c.set_style(style); } } Ok(c) } else { Err(ComponentError::Parse) } } } #[macro_export] macro_rules! component { ($svis:vis struct $name:ident { $($fvis:vis $fname:ident: $fty:ty),* $(,)? }) => { #[derive(Clone)] $svis struct $name { siblings: Vec<Box<dyn Component>>, style: Style, $($fvis $fname: $fty),* } impl $crate::chat::Component for $name { fn siblings(&self) -> &Vec<Box<dyn Component>> { self.siblings.as_ref() } fn siblings_mut(&mut self) -> &mut Vec<Box<dyn Component>> { self.siblings.as_mut() } fn style(&self) -> &Style { &self.style } fn style_mut(&mut self) -> &mut Style { &mut self.style } } }; }
use super::{Style, TextComponent, TranslatableComponent, TranslatableComponentArg}; use crate::{AsJson, FromJson}; use thiserror::Error; #[derive(Error, Debug)] pub enum ComponentError { #[error("failed to parse json")] Parse, } pub trait ComponentClone { fn clone_box(&self) -> Box<dyn Component>; } pub trait ComponentContent { fn contents(&self) -> &str { "" } } pub trait Component: mopa::Any + AsJson + ComponentContent + ComponentClone { fn siblings(&self) -> &Vec<Box<dyn Component>>; fn siblings_mut(&mut self) -> &mut Vec<Box<dyn Component>>; fn append(&mut self, component: Box<dyn Component>) { self.siblings_mut().push(component); } fn style(&self) -> &Style; fn style_mut(&mut self) -> &mut Style; fn set_style(&mut self, style: Style) { *self.style_mut() = style; } fn get_base_json(&self) -> serde_json::Value { let mut value = json!({}); let style = self.style().as_json(); if let serde_json::Value::Object(m) = style { for entry in m { value[entry.0] = entry.1; } } if !self.siblings().is_empty() { value["extra"] = self .siblings() .iter() .map(|sibling| sibling.as_json()) .collect::<serde_json::Value>() .into(); } value } } mopafy!(Component); impl Clone for Box<dyn Component> { fn clone(&self) -> Box<dyn Component> { self.clone_box() } } impl FromJson for Box<dyn Component> { type Err = ComponentError;
} #[macro_export] macro_rules! component { ($svis:vis struct $name:ident { $($fvis:vis $fname:ident: $fty:ty),* $(,)? }) => { #[derive(Clone)] $svis struct $name { siblings: Vec<Box<dyn Component>>, style: Style, $($fvis $fname: $fty),* } impl $crate::chat::Component for $name { fn siblings(&self) -> &Vec<Box<dyn Component>> { self.siblings.as_ref() } fn siblings_mut(&mut self) -> &mut Vec<Box<dyn Component>> { self.siblings.as_mut() } fn style(&self) -> &Style { &self.style } fn style_mut(&mut self) -> &mut Style { &mut self.style } } }; }
fn from_json(value: &serde_json::Value) -> Result<Self, Self::Err> { if value.is_string() { Ok(Box::new(TextComponent::new(value.as_str().unwrap()))) } else if value.is_object() { let obj = value.as_object().unwrap(); let mut c: Box<dyn Component> = if let Some(text) = obj.get("text") { let text = text.as_str().ok_or(ComponentError::Parse)?; Box::new(TextComponent::new(text)) } else if let Some(translate) = obj.get("translate") { let translate = translate.as_str().ok_or(ComponentError::Parse)?; let mut args = vec![]; if let Some(with) = obj.get("with") { let with = with.as_array().ok_or(ComponentError::Parse)?; for arg in with { if let Ok(sub_c) = Self::from_json(arg) { if sub_c.is::<TextComponent>() && sub_c.style().is_empty() && sub_c.siblings().is_empty() { let text = sub_c.contents().into(); args.push(TranslatableComponentArg::String(text)); } else { args.push(TranslatableComponentArg::Component(sub_c)); } } } } Box::new(TranslatableComponent::new(translate, args)) } else { return Err(ComponentError::Parse); }; if obj.contains_key("extra") && obj["extra"].is_array() { for entry in value["extra"].as_array().unwrap() { c.append(Self::from_json(entry)?); } } if let Ok(style) = Style::from_json(value) { if !style.is_empty() { c.set_style(style); } } Ok(c) } else { Err(ComponentError::Parse) } }
function_block-function_prefix_line
[ { "content": "pub trait FromJson {\n\n type Err;\n\n fn from_json(value: &serde_json::Value) -> Result<Self, Self::Err> where Self: Sized;\n\n}\n", "file_path": "blocky-net/src/lib.rs", "rank": 2, "score": 121584.79989159183 }, { "content": "pub trait AsJson {\n\n fn as_json(&self) ...
Rust
src/plugins.rs
ivmarkov/edge-frame
c3c8c270189d5f497180774c138de0717d919bb5
use std::collections; use enumset::*; use yew::prelude::Html; use yew::prelude::Properties; use embedded_svc::edge_config::role::Role; use crate::lambda::Lambda; #[derive(EnumSetType, Debug, PartialOrd)] #[cfg_attr(feature = "std", derive(Hash))] pub enum InsertionPoint { Drawer, Appbar, } #[derive(EnumSetType, Debug, PartialOrd)] #[cfg_attr(feature = "std", derive(Hash))] pub enum Category { Header, Regular, Settings, } #[derive(Debug, PartialEq, Clone)] pub struct APIEndpoint { pub uri: String, pub headers: collections::HashMap<String, String>, } #[derive(Properties, Clone, Default, Debug, PartialEq)] pub struct PluginProps<R> where R: PartialEq + Clone, { pub active_route: R, pub active_role: Role, pub app_bar_renderer: Option<Lambda<(), Html>>, pub api_endpoint: Option<APIEndpoint>, } impl<RAPP> PluginProps<RAPP> where RAPP: PartialEq + Clone, { pub fn map<F, R>(&self, mapper: F, api_uri_prefix: &str) -> PluginProps<R> where F: FnOnce(&RAPP) -> R, R: PartialEq + Clone, { PluginProps { active_route: mapper(&self.active_route), active_role: self.active_role, api_endpoint: self.api_endpoint.as_ref().map( |APIEndpoint { ref uri, ref headers, }| APIEndpoint { uri: crate::api::uri_utils::with_path_segment(uri, api_uri_prefix).unwrap(), headers: headers.clone(), }, ), app_bar_renderer: self.app_bar_renderer.clone(), } } } #[derive(PartialEq, Clone, Debug)] pub struct NavigationPlugin<R> where R: PartialEq + Clone, { pub category: Category, pub insertion_point: InsertionPoint, pub component: Lambda<PluginProps<R>, Html>, pub api_uri_prefix: String, } impl<R> NavigationPlugin<R> where R: PartialEq + Clone, { pub fn map<F, RAPP>(&self, mapper: F) -> NavigationPlugin<RAPP> where F: Fn(&RAPP) -> R + 'static, RAPP: PartialEq + Clone, R: 'static, { NavigationPlugin { category: self.category, insertion_point: self.insertion_point, component: map(&self.component, self.api_uri_prefix.as_str(), mapper), api_uri_prefix: "".into(), } } } #[derive(PartialEq, Clone, Debug)] pub struct ContentPlugin<R> where R: PartialEq + Clone, { pub component: Lambda<PluginProps<R>, Html>, pub api_uri_prefix: String, } impl<R> ContentPlugin<R> where R: PartialEq + Clone, { pub fn map<F, RAPP>(&self, mapper: F) -> ContentPlugin<RAPP> where F: Fn(&RAPP) -> R + 'static, RAPP: PartialEq + Clone, R: 'static, { ContentPlugin { component: map(&self.component, self.api_uri_prefix.as_str(), mapper), api_uri_prefix: "".into(), } } } fn map<F, R, RAPP>( component: &Lambda<PluginProps<R>, Html>, api_uri_prefix: &str, mapper: F, ) -> Lambda<PluginProps<RAPP>, Html> where F: Fn(&RAPP) -> R + 'static, R: PartialEq + Clone + 'static, RAPP: PartialEq + Clone, { let plugin_component = component.clone(); let plugin_api_uri_prefix: String = api_uri_prefix.into(); Lambda::from(move |props: PluginProps<RAPP>| { plugin_component.call(props.map(&mapper, plugin_api_uri_prefix.as_str())) }) }
use std::collections; use enumset::*; use yew::prelude::Html; use yew::prelude::Properties; use embedded_svc::edge_config::role::Role; use crate::lambda::Lambda; #[derive(EnumSetType, Debug, PartialOrd)] #[cfg_attr(feature = "std", derive(Hash))] pub enum InsertionPoint { Drawer, Appbar, } #[derive(EnumSetType, Debug, PartialOrd)] #[cfg_attr(feature = "std", derive(Hash))] pub enum Category { Header, Regular, Settings, } #[derive(Debug, PartialEq, Clone)] pub struct APIEndpoint { pub uri: String, pub headers: collections::HashMap<String, String>, } #[derive(Properties, Clone, Default, Debug, PartialEq)] pub struct PluginProps<R> where R: PartialEq + Clone, { pub active_route: R, pub active_role: Role, pub app_bar_renderer: Option<Lambda<(), Html>>, pub api_endpoint: Option<APIEndpoint>, } impl<RAPP> PluginProps<RAPP> where RAPP: PartialEq + Clone, { pub fn map<F, R>(&self, mapper: F, api_uri_prefix: &str) -> PluginProps<R> where F: FnOnce(&RAPP) -> R, R: PartialEq + Clone, { PluginProps { active_route: mapper(&self.active_route), active_role: self.active_role, api_endpoint: self.api_endpoint.as_ref().map( |APIEndpoint { ref uri, ref headers, }| APIEndpoint { uri: crate::api::uri_utils::with_path_segment(uri, api_uri_prefix).unwrap(), headers: headers.clone(), }, ), app_bar_renderer: self.app_bar_renderer.clone(), } } } #[derive(PartialEq, Clone, Debug)] pub struct NavigationPlugin<R> where R: PartialEq + Clone, { pub category: Category, pub insertion_point: InsertionPoint, pub component: Lambda<PluginProps<R>, Html>, pub api_uri_prefix: String, } impl<R> NavigationPlugin<R> where R: PartialEq + Clone, {
} #[derive(PartialEq, Clone, Debug)] pub struct ContentPlugin<R> where R: PartialEq + Clone, { pub component: Lambda<PluginProps<R>, Html>, pub api_uri_prefix: String, } impl<R> ContentPlugin<R> where R: PartialEq + Clone, { pub fn map<F, RAPP>(&self, mapper: F) -> ContentPlugin<RAPP> where F: Fn(&RAPP) -> R + 'static, RAPP: PartialEq + Clone, R: 'static, { ContentPlugin { component: map(&self.component, self.api_uri_prefix.as_str(), mapper), api_uri_prefix: "".into(), } } } fn map<F, R, RAPP>( component: &Lambda<PluginProps<R>, Html>, api_uri_prefix: &str, mapper: F, ) -> Lambda<PluginProps<RAPP>, Html> where F: Fn(&RAPP) -> R + 'static, R: PartialEq + Clone + 'static, RAPP: PartialEq + Clone, { let plugin_component = component.clone(); let plugin_api_uri_prefix: String = api_uri_prefix.into(); Lambda::from(move |props: PluginProps<RAPP>| { plugin_component.call(props.map(&mapper, plugin_api_uri_prefix.as_str())) }) }
pub fn map<F, RAPP>(&self, mapper: F) -> NavigationPlugin<RAPP> where F: Fn(&RAPP) -> R + 'static, RAPP: PartialEq + Clone, R: 'static, { NavigationPlugin { category: self.category, insertion_point: self.insertion_point, component: map(&self.component, self.api_uri_prefix.as_str(), mapper), api_uri_prefix: "".into(), } }
function_block-full_function
[ { "content": "pub fn with_path_segment(uri: &str, segment: &str) -> Result<String> {\n\n let mut url = url::Url::parse(uri)?;\n\n\n\n {\n\n let mut segments = url\n\n .path_segments_mut()\n\n .map_err(|_| anyhow!(\"url cannot be used as a base\"))?;\n\n segments.push(se...
Rust
src/didcomm/mod.rs
chriamue/identity-cloud-agent
810d4498b26547b28e474cdaf5d44c2481d32109
use crate::connection::{invitation::Invitation, Connections, Termination, TerminationResponse}; use crate::credential::{issue::Issuance, Credentials}; use crate::message::MessageRequest; use crate::ping::{PingRequest, PingResponse}; use crate::webhook::Webhook; use async_trait::async_trait; use reqwest::RequestBuilder; use rocket::State; use rocket::{post, serde::json::Json}; use rocket_okapi::openapi; use serde_json::{json, Value}; use uuid::Uuid; pub mod client; #[cfg(test)] pub mod test_client; pub use client::Client; #[async_trait] pub trait DidComm: Send + Sync { fn request(&self, endpoint: &str, body: &Value) -> RequestBuilder; async fn post(&self, endpoint: &str, body: &Value) -> Result<reqwest::Response, reqwest::Error>; } #[openapi(tag = "didcomm")] #[post("/", format = "application/json", data = "<data>")] pub async fn post_endpoint( webhook: &State<Box<dyn Webhook>>, connections: &State<Connections>, credentials: &State<Credentials>, data: Json<Value>, ) -> Json<Value> { match data["type"].as_str().unwrap() { "https://didcomm.org/out-of-band/2.0/invitation" => { let invitation: Invitation = serde_json::from_value(data.into_inner()).unwrap(); info!("invitation = {:?}", invitation.id); Json(json!({})) } "https://didcomm.org/trust-ping/2.0/ping" => { let ping_request: PingRequest = serde_json::from_value(data.into_inner()).unwrap(); let ping_response: PingResponse = PingResponse { type_: "https://didcomm.org/trust-ping/2.0/ping-response".to_string(), id: Uuid::new_v4().to_string(), thid: ping_request.id, }; Json(json!(ping_response)) } "iota/post/0.1/post" => { let message_request: MessageRequest = serde_json::from_value(data.into_inner()).unwrap(); info!("message: {:?}", message_request.payload); webhook .post("message", &message_request.payload) .await .unwrap(); Json(json!({})) } "iota/termination/0.1/termination" => { let termination: Termination = serde_json::from_value(data.into_inner()).unwrap(); let mut lock = connections.connections.lock().await; lock.remove(&termination.id).unwrap(); std::mem::drop(lock); let termination: TerminationResponse = TerminationResponse { typ: "application/didcomm-plain+json".to_string(), type_: "iota/termination/0.1/termination-response".to_string(), id: termination.id, body: Value::default(), }; Json(json!(termination)) } "iota/issuance/0.1/issuance" => { let issuance: Issuance = serde_json::from_value(data.into_inner()).unwrap(); let credential = issuance.signed_credential; info!("issuance: {:?}", credential); let mut lock = credentials.credentials.lock().await; lock.insert(credential.id.clone().unwrap().to_string(), credential); Json(json!({})) } _ => Json(json!({})), } } #[cfg(test)] mod tests { use crate::connection::Connection; use crate::ping::{PingRequest, PingResponse}; use crate::test_rocket; use rocket::http::{ContentType, Status}; use rocket::local::blocking::Client; use serde_json::{from_value, json, Value}; #[test] fn test_send_ping() { let client = Client::tracked(test_rocket()).expect("valid rocket instance"); let response = client.get("/connections").dispatch(); assert_eq!(response.status(), Status::Ok); let response = response.into_json::<Value>().unwrap(); let connections = response.as_array().unwrap(); assert_eq!(connections.len(), 0); let response = client.post("/out-of-band/create-invitation").dispatch(); assert_eq!(response.status(), Status::Ok); let invitation: Value = response.into_json::<Value>().unwrap(); let invitation: String = serde_json::to_string(&invitation).unwrap(); let response = client .post("/out-of-band/receive-invitation") .header(ContentType::JSON) .body(invitation) .dispatch(); assert_eq!(response.status(), Status::Ok); let response = client.get("/connections").dispatch(); assert_eq!(response.status(), Status::Ok); let response = response.into_json::<Value>().unwrap(); let _connections: Vec<Connection> = from_value(response).unwrap(); let body: Value = json!( { "response_requested": true }); let ping_request: PingRequest = PingRequest { type_: "https://didcomm.org/trust-ping/2.0/ping".to_string(), id: "foo".to_string(), from: "bar".to_string(), body, }; let ping_request: String = serde_json::to_string(&ping_request).unwrap(); let response = client .post("/") .header(ContentType::JSON) .body(ping_request) .dispatch(); assert_eq!(response.status(), Status::Ok); let response = response.into_json::<PingResponse>().unwrap(); assert_eq!(response.thid, "foo".to_string()); } }
use crate::connection::{invitation::Invitation, Connections, Termination, TerminationResponse}; use crate::credential::{issue::Issuance, Credentials}; use crate::message::MessageRequest; use crate::ping::{PingRequest, PingResponse}; use crate::webhook::Webhook; use async_trait::async_trait; use reqwest::RequestBuilder; use rocket::State; use rocket::{post, serde::json::Json}; use rocket_okapi::openapi; use serde_json::{json, Value}; use uuid::Uuid; pub mod client; #[cfg(test)] pub mod test_client; pub use client::Client; #[async_trait] pub trait DidComm: Send + Sync { fn request(&self, endpoint: &str, body: &Value) -> RequestBuilder; async fn post(&self, endpoint: &str, body: &Value) -> Result<reqwest::Response, reqwest::Error>; } #[openapi(tag = "didcomm")] #[post("/", format = "application/json", data = "<data>")] pub async fn post_endpoint( webhook: &State<Box<dyn Webhook>>, connections: &State<Connections>, credentials: &State<Credentials>, data: Json<Value>, ) -> Json<Value> { match data["type"].as_str().unwrap() { "https://didcomm.org/out-of-band/2.0/invitation" => { let invitation: Invitation = serde_json::from_value(data.into_inner()).unwrap(); info!("invitation = {:?}", invitation.id); Json(json!({})) } "https://didcomm.org/trust-ping/2.0/ping" => { let ping_request: PingRequest = serde_json::from_value(data.into_inner()).unwrap(); let ping_response: PingResponse = PingResponse { type_: "https://didcomm.org/trust-ping/2.0/ping-response".to_string(), id: Uuid::new_v4().to_string(), thid: ping_request.id, }; Json(json!(ping_response)) } "iota/post/0.1/post" => { let message_request: MessageRequest = serde_json::from_value(data.into_inner()).unwrap(); info!("message: {:?}", message_request.payload); webhook .post("message", &message_request.payload) .await .unwrap(); Json(json!({})) } "iota/termination/0.1/termination" => { let termination: Termination = serde_json::from_value(data.into_inner()).unwrap(); let mut lock = connections.connections.lock().await; lock.remove(&termination.id).unwrap(); std::mem::drop(lock); let termination: TerminationResponse = TerminationResponse { typ: "application/didcomm-plain+json".to_string(), type_: "iota/termination/0.1/termination-response".to_string(), id: termination.id, body: Value::default(), }; Json(json!(termination)) } "iota/issuance/0.1/issuance" => { let issuance: Issuance = serde_json::from_value(data.into_inner()).unwrap(); let credential = issuance.signed_credential; info!("issuance: {:?}", credential); let mut lock = credentials.credentials.lock().await; lock.insert(credential.id.clone().unwrap().to_string(), credential); Json(json!({})) } _ => Json(json!({})), } } #[cfg(test)] mod tests { use crate::connection::Connection; use crate::ping::{PingRequest, PingResponse}; use crate::test_rocket; use rocket::http::{ContentType, Status}; use rocket::local::blocking::Client; use serde_json::{from_value, json, Value}; #[test] fn test_send_ping() { let client = Client::tracked(test_rocket()).expect("valid rocket instance"); let response = client.get("/connections").dispatch(); assert_eq!(response.status(), Status::Ok); let response = response.into_json::<Value>().unwrap(); let connections = response.as_array().unwrap(); assert_eq!(connections.len(), 0); let response = client.post("/out-of-band/create-invitation").dispatch(); assert_eq!(response.status(), Status::Ok); let invitation: Value = response.into_json::<Value>().unwrap(); let invitation: String = serde_json::to_string(&invitation).unwrap(); let response = client .post("/out-of-band/receive-invitation") .header(ContentType::JSON) .body(invitation) .dispatch(); assert_eq!(response.status(), Status::Ok); let response = client.get("/connections").dispatch(); assert_eq!(response.status(), Status::Ok); let response = response.into_json::<Value>().unwrap(); let _connections: Vec<Connection> = from_value(response).unwrap(); let body: Value = json!( { "response_requested": true });
}
let ping_request: PingRequest = PingRequest { type_: "https://didcomm.org/trust-ping/2.0/ping".to_string(), id: "foo".to_string(), from: "bar".to_string(), body, }; let ping_request: String = serde_json::to_string(&ping_request).unwrap(); let response = client .post("/") .header(ContentType::JSON) .body(ping_request) .dispatch(); assert_eq!(response.status(), Status::Ok); let response = response.into_json::<PingResponse>().unwrap(); assert_eq!(response.thid, "foo".to_string()); }
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait Webhook: Send + Sync {\n\n fn request(&self, topic: &str, body: &Value) -> RequestBuilder;\n\n async fn post(&self, topic: &str, body: &Value) -> Result<reqwest::Response, reqwest::Error>;\n\n}\n", "file_path": "src/webhook/mod.rs", "rank": 0, "score":...
Rust
src/kernel/x86/x86avxbitreversal.rs
yvt/yfft-rs
2ba9934e9a3213a528e7ba4573fe08b96609d20b
use super::super::Num; use super::utils::{if_compatible, AlignInfo, AlignReqKernel, AlignReqKernelWrapper}; use super::{Kernel, KernelParams, SliceAccessor}; use packed_simd::{u32x4, u64x2, u64x4}; use std::{mem, ptr}; pub unsafe fn new_x86_avx_bit_reversal_kernel<T>(indices: &Vec<usize>) -> Option<Box<Kernel<T>>> where T: Num, { if indices.len() < 8 { return None; } if_compatible(|| { Some( Box::new(AlignReqKernelWrapper::new(AvxDWordBitReversalKernel { indices: indices.clone(), })) as Box<Kernel<f32>>, ) }) } #[derive(Debug)] struct AvxDWordBitReversalKernel { indices: Vec<usize>, } impl<T: Num> AlignReqKernel<T> for AvxDWordBitReversalKernel { fn transform<I: AlignInfo>(&self, params: &mut KernelParams<T>) { assert_eq!(mem::size_of::<T>(), 4); let indices = unsafe { SliceAccessor::new(&self.indices) }; let size = self.indices.len(); let mut data = unsafe { SliceAccessor::new(&mut params.coefs[0..size * 2]) }; let mut wa = unsafe { SliceAccessor::new(&mut params.work_area[0..size * 2]) }; wa.copy_from_slice(*data); let mut i = 0; while i + 7 < size { let index1 = indices[i]; let index2 = indices[i + 1]; let index3 = indices[i + 2]; let index4 = indices[i + 3]; let index5 = indices[i + 4]; let index6 = indices[i + 5]; let index7 = indices[i + 6]; let index8 = indices[i + 7]; let src1: *const u64 = &wa[index1 * 2] as *const T as *const u64; let src2: *const u64 = &wa[index2 * 2] as *const T as *const u64; let src3: *const u64 = &wa[index3 * 2] as *const T as *const u64; let src4: *const u64 = &wa[index4 * 2] as *const T as *const u64; let src5: *const u64 = &wa[index5 * 2] as *const T as *const u64; let src6: *const u64 = &wa[index6 * 2] as *const T as *const u64; let src7: *const u64 = &wa[index7 * 2] as *const T as *const u64; let src8: *const u64 = &wa[index8 * 2] as *const T as *const u64; let dest: *mut u64x4 = &mut data[i * 2] as *mut T as *mut u64x4; unsafe { I::write(dest, u64x4::new(*src1, *src2, *src3, *src4)); I::write(dest.offset(1), u64x4::new(*src5, *src6, *src7, *src8)); } i += 8; } while i < size { let index = indices[i]; let src: *const u64 = &wa[index * 2] as *const T as *const u64; let dest: *mut u64 = &mut data[i * 2] as *mut T as *mut u64; unsafe { *dest = *src; } i += 1; } } fn required_work_area_size(&self) -> usize { self.indices.len() * 2 } fn alignment_requirement(&self) -> usize { 32 } } pub unsafe fn new_x86_avx_radix2_bit_reversal_kernel<T>( indices: &Vec<usize>, ) -> Option<Box<Kernel<T>>> where T: Num, { if indices.len() < 8 || indices.len() % 8 != 0 { return None; } for i in 0..indices.len() / 2 { if indices[i] > (<u32>::max_value() / 2) as usize { return None; } } let (f1, f2, f3) = ( indices[1] - indices[0], indices[2] - indices[0], indices[3] - indices[0], ); for i in 0..indices.len() / 8 { let (b0, b1, b2, b3) = ( indices[i * 4], indices[i * 4 + 1], indices[i * 4 + 2], indices[i * 4 + 3], ); if b1 != b0 + f1 || b2 != b0 + f2 || b3 != b0 + f3 { return None; } } if_compatible(|| { Some(Box::new(AlignReqKernelWrapper::new( AvxDWordRadix2BitReversalKernel { indices: (0..indices.len() / 8) .map(|i| (indices[i * 4] as u32) * 2) .collect(), offs: u32x4::new(0, f1 as u32 * 2, f2 as u32 * 2, f3 as u32 * 2), }, )) as Box<Kernel<f32>>) }) } #[derive(Debug)] struct AvxDWordRadix2BitReversalKernel { indices: Vec<u32>, offs: u32x4, } impl<T: Num> AlignReqKernel<T> for AvxDWordRadix2BitReversalKernel { fn transform<I: AlignInfo>(&self, params: &mut KernelParams<T>) { assert_eq!(mem::size_of::<T>(), 4); let indices = unsafe { SliceAccessor::new(&self.indices) }; let size = self.indices.len(); let mut data = unsafe { SliceAccessor::new(&mut params.coefs[0..size * 16]) }; let mut wa = unsafe { SliceAccessor::new(&mut params.work_area[0..size * 16]) }; wa.copy_from_slice(*data); let offs = self.offs; let mut i = 0; while i < size { let index1234 = offs + u32x4::splat(indices[i]); let index1 = index1234.extract(0) as usize; let index2 = index1234.extract(1) as usize; let index3 = index1234.extract(2) as usize; let index4 = index1234.extract(3) as usize; let src1 = unsafe { ptr::read_unaligned(&wa[index1] as *const T as *const u64x2) }; let src2 = unsafe { ptr::read_unaligned(&wa[index2] as *const T as *const u64x2) }; let src3 = unsafe { ptr::read_unaligned(&wa[index3] as *const T as *const u64x2) }; let src4 = unsafe { ptr::read_unaligned(&wa[index4] as *const T as *const u64x2) }; let t1a: u64x2 = shuffle!(src1, src2, [0, 2]); let t2a: u64x2 = shuffle!(src3, src4, [0, 2]); let t1b: u64x2 = shuffle!(src1, src2, [1, 3]); let t2b: u64x2 = shuffle!(src3, src4, [1, 3]); let out1: u64x4 = shuffle!(t1a, t2a, [0, 1, 2, 3]); let out2: u64x4 = shuffle!(t1b, t2b, [0, 1, 2, 3]); let dest1: *mut u64x4 = &mut data[i * 8] as *mut T as *mut u64x4; let dest2: *mut u64x4 = &mut data[(i + size) * 8] as *mut T as *mut u64x4; unsafe { I::write(dest1, out1); I::write(dest2, out2); } i += 1; } } fn required_work_area_size(&self) -> usize { self.indices.len() * 16 } fn alignment_requirement(&self) -> usize { 32 } } pub unsafe fn new_x86_avx_radix4_bit_reversal_kernel<T>( indices: &Vec<usize>, ) -> Option<Box<Kernel<T>>> where T: Num, { if indices.len() < 32 || indices.len() % 32 != 0 { return None; } for i in 0..indices.len() / 4 { if indices[i] > (<u32>::max_value() / 2) as usize { return None; } } let (f1, f2, f3) = ( indices[1] - indices[0], indices[2] - indices[0], indices[3] - indices[0], ); for i in 0..indices.len() / 16 { let (b0, b1, b2, b3) = ( indices[i * 4], indices[i * 4 + 1], indices[i * 4 + 2], indices[i * 4 + 3], ); if b1 != b0 + f1 || b2 != b0 + f2 || b3 != b0 + f3 { return None; } } if_compatible(|| { Some(Box::new(AlignReqKernelWrapper::new( AvxDWordRadix4BitReversalKernel { indices: (0..indices.len() / 16) .map(|i| (indices[i * 4] as u32) * 2) .collect(), offs: u32x4::new(0, f1 as u32 * 2, f2 as u32 * 2, f3 as u32 * 2), }, )) as Box<Kernel<f32>>) }) } #[derive(Debug)] struct AvxDWordRadix4BitReversalKernel { indices: Vec<u32>, offs: u32x4, } impl<T: Num> AlignReqKernel<T> for AvxDWordRadix4BitReversalKernel { fn transform<I: AlignInfo>(&self, params: &mut KernelParams<T>) { assert_eq!(mem::size_of::<T>(), 4); let indices = unsafe { SliceAccessor::new(&self.indices) }; let size = self.indices.len(); let mut data = unsafe { SliceAccessor::new(&mut params.coefs[0..size * 32]) }; let mut wa = unsafe { SliceAccessor::new(&mut params.work_area[0..size * 32]) }; wa.copy_from_slice(*data); let offs = self.offs; let mut i = 0; while i + 1 < size { for _ in 0..2 { let index1234 = offs + u32x4::splat(indices[i]); let index1 = index1234.extract(0) as usize; let index2 = index1234.extract(1) as usize; let index3 = index1234.extract(2) as usize; let index4 = index1234.extract(3) as usize; let src1 = unsafe { ptr::read_unaligned(&wa[index1] as *const T as *const u64x4) }; let src2 = unsafe { ptr::read_unaligned(&wa[index2] as *const T as *const u64x4) }; let src3 = unsafe { ptr::read_unaligned(&wa[index3] as *const T as *const u64x4) }; let src4 = unsafe { ptr::read_unaligned(&wa[index4] as *const T as *const u64x4) }; let t1a: u64x4 = shuffle!(src1, src2, [0, 4, 2, 6]); let t2a: u64x4 = shuffle!(src3, src4, [0, 4, 2, 6]); let t1b: u64x4 = shuffle!(src1, src2, [1, 5, 3, 7]); let t2b: u64x4 = shuffle!(src3, src4, [1, 5, 3, 7]); let out1: u64x4 = shuffle!(t1a, t2a, [0, 1, 4, 5]); let out2: u64x4 = shuffle!(t1b, t2b, [0, 1, 4, 5]); let out3: u64x4 = shuffle!(t1a, t2a, [2, 3, 6, 7]); let out4: u64x4 = shuffle!(t1b, t2b, [2, 3, 6, 7]); let dest1: *mut u64x4 = &mut data[i * 8] as *mut T as *mut u64x4; let dest2: *mut u64x4 = &mut data[(i + size) * 8] as *mut T as *mut u64x4; let dest3: *mut u64x4 = &mut data[(i + size * 2) * 8] as *mut T as *mut u64x4; let dest4: *mut u64x4 = &mut data[(i + size * 3) * 8] as *mut T as *mut u64x4; unsafe { I::write(dest1, out1); I::write(dest2, out2); I::write(dest3, out3); I::write(dest4, out4); } i += 1; } } assert_eq!(i, size); } fn required_work_area_size(&self) -> usize { self.indices.len() * 32 } fn alignment_requirement(&self) -> usize { 32 } }
use super::super::Num; use super::utils::{if_compatible, AlignInfo, AlignReqKernel, AlignReqKernelWrapper}; use super::{Kernel, KernelParams, SliceAccessor}; use packed_simd::{u32x4, u64x2, u64x4}; use std::{mem, ptr}; pub unsafe fn new_x86_avx_bit_reversal_kernel<T>(indices: &Vec<usize>) -> Option<Box<Kernel<T>>> where T: Num, { if indices.len() < 8 { return None; } if_compatible(|| { Some( Box::new(AlignReqKernelWrapper::new(AvxD
#[derive(Debug)] struct AvxDWordBitReversalKernel { indices: Vec<usize>, } impl<T: Num> AlignReqKernel<T> for AvxDWordBitReversalKernel { fn transform<I: AlignInfo>(&self, params: &mut KernelParams<T>) { assert_eq!(mem::size_of::<T>(), 4); let indices = unsafe { SliceAccessor::new(&self.indices) }; let size = self.indices.len(); let mut data = unsafe { SliceAccessor::new(&mut params.coefs[0..size * 2]) }; let mut wa = unsafe { SliceAccessor::new(&mut params.work_area[0..size * 2]) }; wa.copy_from_slice(*data); let mut i = 0; while i + 7 < size { let index1 = indices[i]; let index2 = indices[i + 1]; let index3 = indices[i + 2]; let index4 = indices[i + 3]; let index5 = indices[i + 4]; let index6 = indices[i + 5]; let index7 = indices[i + 6]; let index8 = indices[i + 7]; let src1: *const u64 = &wa[index1 * 2] as *const T as *const u64; let src2: *const u64 = &wa[index2 * 2] as *const T as *const u64; let src3: *const u64 = &wa[index3 * 2] as *const T as *const u64; let src4: *const u64 = &wa[index4 * 2] as *const T as *const u64; let src5: *const u64 = &wa[index5 * 2] as *const T as *const u64; let src6: *const u64 = &wa[index6 * 2] as *const T as *const u64; let src7: *const u64 = &wa[index7 * 2] as *const T as *const u64; let src8: *const u64 = &wa[index8 * 2] as *const T as *const u64; let dest: *mut u64x4 = &mut data[i * 2] as *mut T as *mut u64x4; unsafe { I::write(dest, u64x4::new(*src1, *src2, *src3, *src4)); I::write(dest.offset(1), u64x4::new(*src5, *src6, *src7, *src8)); } i += 8; } while i < size { let index = indices[i]; let src: *const u64 = &wa[index * 2] as *const T as *const u64; let dest: *mut u64 = &mut data[i * 2] as *mut T as *mut u64; unsafe { *dest = *src; } i += 1; } } fn required_work_area_size(&self) -> usize { self.indices.len() * 2 } fn alignment_requirement(&self) -> usize { 32 } } pub unsafe fn new_x86_avx_radix2_bit_reversal_kernel<T>( indices: &Vec<usize>, ) -> Option<Box<Kernel<T>>> where T: Num, { if indices.len() < 8 || indices.len() % 8 != 0 { return None; } for i in 0..indices.len() / 2 { if indices[i] > (<u32>::max_value() / 2) as usize { return None; } } let (f1, f2, f3) = ( indices[1] - indices[0], indices[2] - indices[0], indices[3] - indices[0], ); for i in 0..indices.len() / 8 { let (b0, b1, b2, b3) = ( indices[i * 4], indices[i * 4 + 1], indices[i * 4 + 2], indices[i * 4 + 3], ); if b1 != b0 + f1 || b2 != b0 + f2 || b3 != b0 + f3 { return None; } } if_compatible(|| { Some(Box::new(AlignReqKernelWrapper::new( AvxDWordRadix2BitReversalKernel { indices: (0..indices.len() / 8) .map(|i| (indices[i * 4] as u32) * 2) .collect(), offs: u32x4::new(0, f1 as u32 * 2, f2 as u32 * 2, f3 as u32 * 2), }, )) as Box<Kernel<f32>>) }) } #[derive(Debug)] struct AvxDWordRadix2BitReversalKernel { indices: Vec<u32>, offs: u32x4, } impl<T: Num> AlignReqKernel<T> for AvxDWordRadix2BitReversalKernel { fn transform<I: AlignInfo>(&self, params: &mut KernelParams<T>) { assert_eq!(mem::size_of::<T>(), 4); let indices = unsafe { SliceAccessor::new(&self.indices) }; let size = self.indices.len(); let mut data = unsafe { SliceAccessor::new(&mut params.coefs[0..size * 16]) }; let mut wa = unsafe { SliceAccessor::new(&mut params.work_area[0..size * 16]) }; wa.copy_from_slice(*data); let offs = self.offs; let mut i = 0; while i < size { let index1234 = offs + u32x4::splat(indices[i]); let index1 = index1234.extract(0) as usize; let index2 = index1234.extract(1) as usize; let index3 = index1234.extract(2) as usize; let index4 = index1234.extract(3) as usize; let src1 = unsafe { ptr::read_unaligned(&wa[index1] as *const T as *const u64x2) }; let src2 = unsafe { ptr::read_unaligned(&wa[index2] as *const T as *const u64x2) }; let src3 = unsafe { ptr::read_unaligned(&wa[index3] as *const T as *const u64x2) }; let src4 = unsafe { ptr::read_unaligned(&wa[index4] as *const T as *const u64x2) }; let t1a: u64x2 = shuffle!(src1, src2, [0, 2]); let t2a: u64x2 = shuffle!(src3, src4, [0, 2]); let t1b: u64x2 = shuffle!(src1, src2, [1, 3]); let t2b: u64x2 = shuffle!(src3, src4, [1, 3]); let out1: u64x4 = shuffle!(t1a, t2a, [0, 1, 2, 3]); let out2: u64x4 = shuffle!(t1b, t2b, [0, 1, 2, 3]); let dest1: *mut u64x4 = &mut data[i * 8] as *mut T as *mut u64x4; let dest2: *mut u64x4 = &mut data[(i + size) * 8] as *mut T as *mut u64x4; unsafe { I::write(dest1, out1); I::write(dest2, out2); } i += 1; } } fn required_work_area_size(&self) -> usize { self.indices.len() * 16 } fn alignment_requirement(&self) -> usize { 32 } } pub unsafe fn new_x86_avx_radix4_bit_reversal_kernel<T>( indices: &Vec<usize>, ) -> Option<Box<Kernel<T>>> where T: Num, { if indices.len() < 32 || indices.len() % 32 != 0 { return None; } for i in 0..indices.len() / 4 { if indices[i] > (<u32>::max_value() / 2) as usize { return None; } } let (f1, f2, f3) = ( indices[1] - indices[0], indices[2] - indices[0], indices[3] - indices[0], ); for i in 0..indices.len() / 16 { let (b0, b1, b2, b3) = ( indices[i * 4], indices[i * 4 + 1], indices[i * 4 + 2], indices[i * 4 + 3], ); if b1 != b0 + f1 || b2 != b0 + f2 || b3 != b0 + f3 { return None; } } if_compatible(|| { Some(Box::new(AlignReqKernelWrapper::new( AvxDWordRadix4BitReversalKernel { indices: (0..indices.len() / 16) .map(|i| (indices[i * 4] as u32) * 2) .collect(), offs: u32x4::new(0, f1 as u32 * 2, f2 as u32 * 2, f3 as u32 * 2), }, )) as Box<Kernel<f32>>) }) } #[derive(Debug)] struct AvxDWordRadix4BitReversalKernel { indices: Vec<u32>, offs: u32x4, } impl<T: Num> AlignReqKernel<T> for AvxDWordRadix4BitReversalKernel { fn transform<I: AlignInfo>(&self, params: &mut KernelParams<T>) { assert_eq!(mem::size_of::<T>(), 4); let indices = unsafe { SliceAccessor::new(&self.indices) }; let size = self.indices.len(); let mut data = unsafe { SliceAccessor::new(&mut params.coefs[0..size * 32]) }; let mut wa = unsafe { SliceAccessor::new(&mut params.work_area[0..size * 32]) }; wa.copy_from_slice(*data); let offs = self.offs; let mut i = 0; while i + 1 < size { for _ in 0..2 { let index1234 = offs + u32x4::splat(indices[i]); let index1 = index1234.extract(0) as usize; let index2 = index1234.extract(1) as usize; let index3 = index1234.extract(2) as usize; let index4 = index1234.extract(3) as usize; let src1 = unsafe { ptr::read_unaligned(&wa[index1] as *const T as *const u64x4) }; let src2 = unsafe { ptr::read_unaligned(&wa[index2] as *const T as *const u64x4) }; let src3 = unsafe { ptr::read_unaligned(&wa[index3] as *const T as *const u64x4) }; let src4 = unsafe { ptr::read_unaligned(&wa[index4] as *const T as *const u64x4) }; let t1a: u64x4 = shuffle!(src1, src2, [0, 4, 2, 6]); let t2a: u64x4 = shuffle!(src3, src4, [0, 4, 2, 6]); let t1b: u64x4 = shuffle!(src1, src2, [1, 5, 3, 7]); let t2b: u64x4 = shuffle!(src3, src4, [1, 5, 3, 7]); let out1: u64x4 = shuffle!(t1a, t2a, [0, 1, 4, 5]); let out2: u64x4 = shuffle!(t1b, t2b, [0, 1, 4, 5]); let out3: u64x4 = shuffle!(t1a, t2a, [2, 3, 6, 7]); let out4: u64x4 = shuffle!(t1b, t2b, [2, 3, 6, 7]); let dest1: *mut u64x4 = &mut data[i * 8] as *mut T as *mut u64x4; let dest2: *mut u64x4 = &mut data[(i + size) * 8] as *mut T as *mut u64x4; let dest3: *mut u64x4 = &mut data[(i + size * 2) * 8] as *mut T as *mut u64x4; let dest4: *mut u64x4 = &mut data[(i + size * 3) * 8] as *mut T as *mut u64x4; unsafe { I::write(dest1, out1); I::write(dest2, out2); I::write(dest3, out3); I::write(dest4, out4); } i += 1; } } assert_eq!(i, size); } fn required_work_area_size(&self) -> usize { self.indices.len() * 32 } fn alignment_requirement(&self) -> usize { 32 } }
WordBitReversalKernel { indices: indices.clone(), })) as Box<Kernel<f32>>, ) }) }
function_block-function_prefixed
[ { "content": "pub trait Num:\n\n Clone\n\n + Debug\n\n + AddAssign\n\n + SubAssign\n\n + MulAssign\n\n + DivAssign\n\n + Default\n\n + num_traits::Float\n\n + num_traits::FloatConst\n\n + num_traits::Zero\n\n + 'static\n\n + Sync\n\n + Send\n\n{\n\n}\n\nimpl<T> Num for T w...
Rust
client/src/renderer/glium/traits.rs
BonsaiDen/shooter-rs
0ce5d02065be9ded30e29fdf133ad7a615f29323
use glium::{glutin, DisplayBuild, Surface}; use shared::Lithium::{ Client, ClientHandler, EntityState, EntityRegistry, Event, BaseLevel, Renderer }; use super::GliumRenderer; impl Renderer for GliumRenderer { fn run< H: ClientHandler<Self, G, L, E, S>, E: Event, S: EntityState, L: BaseLevel<S>, G: EntityRegistry<S, L, Self> >(mut client: Client<H, Self, G, L, E, S>) where Self: Sized { let (width, height) = (256, 256); let display = glutin::WindowBuilder::new() .with_multisampling(4) .with_dimensions(width, height) .build_glium().unwrap(); let mut renderer = GliumRenderer::new(display, width, height); client.init(&mut renderer); let mut last_tick_time = 0.0; let mut last_frame_time = 0.0; let mut frames_per_tick = 0; while renderer.running() { if renderer.should_draw() { let frame_time = renderer.time(); let tick_rate = renderer.tick_rate(); if frames_per_tick == 0 { if client.tick(&mut renderer) { frames_per_tick = renderer.fps() / tick_rate; last_tick_time = frame_time; } } renderer.set_delta_time((frame_time - last_frame_time) as f32); renderer.set_delta_u( 1.0 / (1.0 / tick_rate as f32) * (frame_time - last_tick_time) as f32 ); client.draw(&mut renderer); renderer.draw(); last_frame_time = frame_time; if frames_per_tick > 0 { frames_per_tick -= 1; } } renderer.events(); } client.destroy(&mut renderer); } fn time(&self) -> f64 { self.time } fn set_time(&mut self, time: f64) { self.time = time; } fn delta_time(&self) -> f32{ self.dt } fn set_delta_time(&mut self, dt: f32) { self.dt = dt; } fn delta_u(&self) -> f32 { self.u } fn set_delta_u(&mut self, u: f32) { self.u = u; } fn fps(&self) -> u32 { self.frame_rate } fn set_fps(&mut self, frame_rate: u32) { self.frame_rate = frame_rate; } fn tick_rate(&self) -> u32 { self.tick_rate } fn set_tick_rate(&mut self, tick_rate: u32) { self.tick_rate = tick_rate; } fn interpolation_ticks(&self) -> usize { self.interpolation_ticks } fn set_interpolation_ticks(&mut self, ticks: usize) { self.interpolation_ticks = ticks; } }
use glium::{glutin, DisplayBuild, Surface}; use shared::Lithium::{ Client, ClientHandler, EntityState, EntityRegistry, Event, BaseLevel, Renderer }; use super::GliumRenderer; impl Renderer for GliumRenderer { fn run< H: ClientHandler<Self, G, L, E, S>, E: Event, S: EntityState, L: BaseLevel<S>, G: EntityRegistry<S, L, Self> >(mut client: Client<H, Self, G, L, E, S>) where Self: Sized { let (width, height) = (256, 256); let display = glutin::WindowBuilder::new() .with_multisampling(4) .with_dimensions(width, height) .build_glium().unwrap(); let mut renderer = GliumRenderer::new(display, width, height); client.init(&mut renderer); let mut last_tick_time = 0.0; let mut last_frame_time = 0.0; let mut frames_per_tick = 0;
fn time(&self) -> f64 { self.time } fn set_time(&mut self, time: f64) { self.time = time; } fn delta_time(&self) -> f32{ self.dt } fn set_delta_time(&mut self, dt: f32) { self.dt = dt; } fn delta_u(&self) -> f32 { self.u } fn set_delta_u(&mut self, u: f32) { self.u = u; } fn fps(&self) -> u32 { self.frame_rate } fn set_fps(&mut self, frame_rate: u32) { self.frame_rate = frame_rate; } fn tick_rate(&self) -> u32 { self.tick_rate } fn set_tick_rate(&mut self, tick_rate: u32) { self.tick_rate = tick_rate; } fn interpolation_ticks(&self) -> usize { self.interpolation_ticks } fn set_interpolation_ticks(&mut self, ticks: usize) { self.interpolation_ticks = ticks; } }
while renderer.running() { if renderer.should_draw() { let frame_time = renderer.time(); let tick_rate = renderer.tick_rate(); if frames_per_tick == 0 { if client.tick(&mut renderer) { frames_per_tick = renderer.fps() / tick_rate; last_tick_time = frame_time; } } renderer.set_delta_time((frame_time - last_frame_time) as f32); renderer.set_delta_u( 1.0 / (1.0 / tick_rate as f32) * (frame_time - last_tick_time) as f32 ); client.draw(&mut renderer); renderer.draw(); last_frame_time = frame_time; if frames_per_tick > 0 { frames_per_tick -= 1; } } renderer.events(); } client.destroy(&mut renderer); }
function_block-function_prefix_line
[ { "content": "fn run() {\n\n\n\n let args = clap::App::new(\"shooter-client\")\n\n .version(&crate_version!())\n\n .author(\"Ivo Wetzel <ivo.wetzel@googlemail.com>\")\n\n .about(\"Shooter-Client\")\n\n .arg(clap::Arg::with_name(\"address:port\")\n\n .help(\"Remote serve...
Rust
jissen/2nd/code4/src/main.rs
Hota822/Rust
05a7756cfec474052161b3886b035a326a58f49a
fn main() { f4_2(); f4_3(); } fn f4_3() { let t1 = (88, true); assert_eq!(t1.0, 88); let mut t2 = (88, true); t2.1 = false; assert_eq!(t2.1, false); let (n1, b1) = t2; println!("({}, {})", n1, b1); let ((_, _), (n2, _)) = ((1, 2), (3, 4)); println!("{}", n2); let mut t1 = ((1, 2), (3, 4)); let ((ref mut x1_ptr, ref mut x2_ptr), _) = t1; *x1_ptr = 5; *x2_ptr = 6; println!("{:?}", t1); let a1 = [false, true, false]; let a2 = [0.0, 1.0, 0.6, -0.4]; assert_eq!(a1.len() + 1, a2.len()); let a3 = [0; 100]; assert_eq!(a3.len(), 100); let _a4 = [['a', 'b'], ['c', 'd']]; let i = 99; let mut v = vec![0; i]; assert_eq!(v.len(), 99); v.push(1); assert_eq!(v.len(), 100); assert_eq!(v.pop().unwrap(), 1); assert_eq!(v.len(), 99); let mut a1 = ['h', 'e', 'l', 'l', 'o']; println!("{}", a1[1]); a1[0] = 'H'; println!("{}", a1[0]); let i = 0; println!("{}", a1[i]); println!("{:?}", a1.get(4)); println!("{}", a1.get(4).unwrap()); println!("{:?}", a1.get(5)); let mut a4 = [1; 50]; for i in a4.iter() { print!("{}", i); } println!(); for i in a4.iter_mut() { print!("{}", i); } println!(); fn print_info(name: &str, sl: &[char]) { println!(" {:9} - {}, {}, {:?}, {:?}, {:?}", name, name, sl.len(), sl.first(), sl[1], sl.last(), ); } let a1 = ['a', 'b', 'c', 'd', 'e']; println!("a1: {:?}", a1 ); print_info("&a1[..]", &a1); print_info("&a1[..]", &a1[..]); let v1 = vec!['f', 'g', 'h', 'i', 'j']; print_info("&v1[..]", &v1); let mut a1 = [5, 4, 3, 2]; let s1 = &mut a1[1..3]; s1[0] = 6; s1[1] *= 10; s1.swap(0, 1); println!("{:?}", s1); println!("{:?}", a1); let a2: [i32; 0] = []; let s2 = &a2; assert!(s2.is_empty()); assert_eq!(s2.len(), 0); assert_eq!(s2.get(0), None); let a3 = ["Zero", "One", "Two", "Three", "Four"]; let s3 = &a3[1..4]; assert!(!s3.is_empty()); assert_eq!(s3.len(), 3); assert_eq!(s3.first(), Some(&"One")); assert_eq!(s3[1], "Two"); assert_eq!(s3.get(1), Some(&"Two")); assert_eq!(a3.get(1), Some(&"One")); assert!(a3.contains(&"One")); assert!(s3.starts_with(&["One", "Two"])); assert!(s3.ends_with(&["Two", "Three"])); let mut a4 = [1, 3, 4, 5]; println!("{:?}", a4); assert_eq!(a4.get(1).unwrap(), &3); let i1 = a4.get_mut(3).unwrap(); println!("{:?}", i1); *i1 = 10; println!("{:?}", i1); println!("{:?}", a4); let mut i2 = a4.get_mut(3).unwrap(); println!("{:?}", i2); i2 = a4.get_mut(1).unwrap(); println!("{:?}, warning is not displayed", i2); let _i3 = a4.get(1).unwrap(); let mut a4 = [6, 4, 2, 8, 0, 9, 4, 3, 7, 5, 1, 7]; a4[2..6].sort(); println!("{:?}", a4); let (s4a, s4b) = a4.split_at_mut(5); s4a.reverse(); println!("s4a: {:?}", s4a); s4b.sort_unstable(); println!("s4b: {:?}", s4b); println!("{:?}", a4); let s1 = "abc1"; let s2 = "abc2"; assert!(s1 < s2); assert!(s1 != s2); let s3 = "add new line"; let s4 = "no new \ line"; println!("{}", s3); println!("{}", s4); let s5 = "\\ add back slash by escape"; let s6 = r#"\ add back slash by row string"#; println!("{}", s5); println!("{}", s6); let s7 = r###"it's able to use # and ## in this literal"###; println!("{}", s7); println!("{}\u{1f600}",s7 ); let fruits = "red apple, green apple\nraspberry, black berry"; let mut lines = fruits.lines(); let apple_line = lines.next(); assert_eq!(Some("red apple, green apple"), apple_line); assert_eq!(Some("raspberry, black berry"), lines.next()); assert_eq!(None, lines.next()); if let Some(apples) = apple_line { assert!(apples.starts_with("red")); assert!(apples.contains("apple")); println!("{:?}", apples.find("green")); let mut apple_iter = apples.split(","); assert_eq!(apple_iter.next(), Some("red apple")); let green = apple_iter.next(); assert_eq!(Some(" green apple"), green); assert_eq!(Some("green apple"), green.map(|s| s.trim())); assert_eq!(Some("green apple"), green.map(str::trim)); } let s1 = "a"; let s2 = "あ"; let s3 = "😀"; println!("{}, {}, {}", s1.len(), s2.len(), s3.len()); let s = "abcあいう"; assert_eq!(s.get(0..1), Some("a")); assert_eq!(s.get(3..6), Some("あ")); assert_eq!(s.get(3..5), None); assert_eq!(s.get(3..=6), None ); let s = "かか\u{3099}く"; println!("{}", s); let s_iter = s.chars(); for c in s_iter { println!("{}", c); } let mut s_iter = s.chars(); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); let utf8: [u8; 4] = [0x61, 0xe3, 0x81, 0x82]; assert_eq!(std::str::from_utf8(&utf8), Ok("aあ")); let bad_utf8: [u8; 2] = [0x81, 0x33]; let result = std::str::from_utf8(&bad_utf8); assert!(result.is_err()); let mut s1 = "abc".to_string(); let s2 = s1.as_mut_str(); s2.make_ascii_uppercase(); assert_eq!("ABC", s2); let b = unsafe {s2.as_bytes_mut() }; b[0] = b'D'; b[1] = b'E'; b[2] = b'F'; println!("{}", s2); } fn f4_2() { let n = 42; let c = 'R'; println!("{}, {}", n, c); fn hello() { println!("hello"); } let hello = hello(); assert_eq!((), hello); assert_eq!(std::mem::size_of::<()>(), 0); let b1 = true; let b2 = !b1; assert_eq!(b2, false); let n1 = 8; let n2 = 12; let b3 = n1 > 10; let b4 = n2 > 10; let b5 = b3 && b4; let b6 = b3 || b4; assert_eq!(b5, false); assert_eq!(b6, true); assert_eq!(std::mem::size_of::<bool>(), 1); let n1 = 10_000; let n1_1 = 10000; let n2 = 0u8; let n2_1: u8 = 0; let n3 = -100_isize; let n3_1: isize = -100; assert_eq!(n1, n1_1); assert_eq!(n2, n2_1); assert_eq!(n3, n3_1); let n4 = 10; let n5 = n3 + n4; print_typename(n5); let n1 = 57; let h1 = 0xff; let o1 = 0o71; let b1 = 0b1111_1111; assert_eq!(h1, b1); assert_eq!(n1, o1); let n6 = b'A'; assert_eq!(n6, 65u8); let n1 = std::u8::MAX; let _n2 = 1u8; println!("{}", n1); let n1 = 200u8; let n2 = 3u8; assert!(n1.checked_mul(n2).is_none()); assert_eq!(n1.saturating_mul(n2), std::u8::MAX); assert_eq!(n1.wrapping_mul(n2), 88); assert_eq!(n1.overflowing_mul(n2), (88, true)); let _f1 = 10.0; let _f2 = -1_234.56_f32; let _f3 = 578.6E77; let c1 ='A'; let c2 = 'a'; assert!(c1 < c2); assert!(c1.is_uppercase()); let c3 = '0'; assert!(c3.is_digit(10)); let c4 = '\t'; let c5 = '\n'; let c6 = '\''; let c7 = '\\'; let c8 = '\x7F'; let c9 = '\u{1f600}'; println!("{}, {}, {}, {}, {}, {}, {}", c3, c4, c5, c6, c7, c8, c9); fn func1(mut n: u32) { println!("func1-1 {}", n); n = 1; println!("func1-2 {}", n); } fn func2(n_ptr: &mut u32) { println!("func2 *n_ptr {}", *n_ptr); println!("func2 n_ptr {}", n_ptr); *n_ptr = 10; println!("func2 *n_ptr {}", n_ptr); } let mut x = 5; func1(x); func2(&mut x); let c1 = 'A'; let c1_ptr = &c1; assert_eq!(*c1_ptr, 'A'); let mut n1 = 0; let n1_ptr = &mut n1; assert_eq!(*n1_ptr, 0); fn double (n: i32) -> i32 { n + n } fn abs(n: i32) -> i32 { if n >= 0 { n } else { -n } } let mut func: fn(i32) -> i32 = double; let x = -5; println!("{}", func(x)); func = abs; println!("{}", func(x)); let x = 4; let adder = |n| n + x ; assert_eq!(adder(2), 4 + 2); let mut state = false; let mut flipflop = || { state = !state; state }; println!("{}", flipflop()); println!("{}", flipflop()); println!("{}", flipflop()); println!("{}", state); } fn print_typename<T>(_ : T) { println!("{}", std::any::type_name::<T>()); }
fn main() { f4_2(); f4_3(); } fn f4_3() { let t1 = (88, true); assert_eq!(t1.0, 88); let mut t2 = (88, true); t2.1 = false; assert_eq!(t2.1, false); let (n1, b1) = t2; println!("({}, {})", n1, b1); let ((_, _), (n2, _)) = ((1, 2), (3, 4)); println!("{}", n2); let mut t1 = ((1, 2), (3, 4)); let ((ref mut x1_ptr, ref mut x2_ptr), _) = t1; *x1_ptr = 5; *x2_ptr = 6; println!("{:?}", t1); let a1 = [false, true, false]; let a2 = [0.0, 1.0, 0.6, -0.4]; assert_eq!(a1.len() + 1, a2.len()); let a3 = [0; 100]; assert_eq!(a3.len(), 100); let _a4 = [['a', 'b'], ['c', 'd']]; let i = 99; let mut v = vec![0; i]; assert_eq!(v.len(), 99); v.push(1); assert_eq!(v.len(), 100); assert_eq!(v.pop().unwrap(), 1); assert_eq!(v.len(), 99); let mut a1 = ['h', 'e', 'l', 'l', 'o']; println!("{}", a1[1]); a1[0] = 'H'; println!("{}", a1[0]); let i = 0; println!("{}", a1[i]); println!("{:?}", a1.get(4)); println!("{}", a1.get(4).unwrap()); println!("{:?}", a1.get(5)); let mut a4 = [1; 50]; for i in a4.iter() { print!("{}", i); } println!(); for i in a4.iter_mut() { print!("{}", i); } println!(); fn print_info(name: &str, sl: &[char]) { println!(" {:9} - {}, {}, {:?}, {:?}, {:?}", name, name, sl.len(), sl.first(), sl[1], sl.last(), ); } let a1 = ['a', 'b', 'c', 'd', 'e']; println!("a1: {:?}", a1 ); print_info("&a1[..]", &a1); print_info("&a1[..]", &a1[..]); let v1 = vec!['f', 'g', 'h', 'i', 'j']; print_info("&v1[..]", &v1); let mut a1 = [5, 4, 3, 2]; let s1 = &mut a1[1..3]; s1[0] = 6; s1[1] *= 10; s1.swap(0, 1); println!("{:?}", s1); println!("{:?}", a1); let a2: [i32; 0] = []; let s2 = &a2; assert!(s2.is_empty()); assert_eq!(s2.len(), 0); assert_eq!(s2.get(0), None); let a3 = ["Zero", "One", "Two", "Three", "Four"]; let s3 = &a3[1..4]; assert!(!s3.is_empty()); assert_eq!(s3.len(), 3); assert_eq!(s3.first(), Some(&"One")); assert_eq!(s3[1], "Two"); assert_eq!(s3.get(1), Some(&"Two")); assert_eq!(a3.get(1), Some(&"One")); assert!(a3.contains(&"One")); assert!(s3.starts_with(&["One", "Two"])); assert!(s3.ends_with(&["Two", "Three"])); let mut a4 = [1, 3, 4, 5]; println!("{:?}", a4); assert_eq!(a4.get(1).unwrap(), &3); let i1 = a4.get_mut(3).unwrap(); println!("{:?}", i1); *i1 = 10; println!("{:?}", i1); println!("{:?}", a4); let mut i2 = a4.get_mut(3).unwrap(); println!("{:?}", i2); i2 = a4.get_mut(1).unwrap(); println!("{:?}, warning is not displayed", i2); let _i3 = a4.get(1).unwrap(); let mut a4 = [6, 4, 2, 8, 0, 9, 4, 3, 7, 5, 1, 7]; a4[2..6].sort(); println!("{:?}", a4); let (s4a, s4b) = a4.split_at_mut(5); s4a.reverse(); println!("s4a: {:?}", s4a); s4b.sort_unstable(); println!("s4b: {:?}", s4b); println!("{:?}", a4); let s1 = "abc1"; let s2 = "abc2"; assert!(s1 < s2); assert!(s1 != s2); let s3 = "add new line"; let s4 = "no new \ line"; println!("{}", s3); println!("{}", s4); let s5 = "\\ add back slash by escape"; let s6 = r#"\ add back slash by row string"#; println!("{}", s5); println!("{}", s6); let s7 = r###"it's able to use # and ## in this literal"###; println!("{}", s7); println!("{}\u{1f600}",s7 ); let fruits = "red apple, green apple\nraspberry, black berry"; let mut lines = fruits.lines(); let apple_line = lines.next(); assert_eq!(Some("red apple, green apple"), apple_line); assert_eq!(Some("raspberry, black berry"), lines.next()); assert_eq!(None, lines.next());
let s1 = "a"; let s2 = "あ"; let s3 = "😀"; println!("{}, {}, {}", s1.len(), s2.len(), s3.len()); let s = "abcあいう"; assert_eq!(s.get(0..1), Some("a")); assert_eq!(s.get(3..6), Some("あ")); assert_eq!(s.get(3..5), None); assert_eq!(s.get(3..=6), None ); let s = "かか\u{3099}く"; println!("{}", s); let s_iter = s.chars(); for c in s_iter { println!("{}", c); } let mut s_iter = s.chars(); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); println!("{:?}", s_iter.next()); let utf8: [u8; 4] = [0x61, 0xe3, 0x81, 0x82]; assert_eq!(std::str::from_utf8(&utf8), Ok("aあ")); let bad_utf8: [u8; 2] = [0x81, 0x33]; let result = std::str::from_utf8(&bad_utf8); assert!(result.is_err()); let mut s1 = "abc".to_string(); let s2 = s1.as_mut_str(); s2.make_ascii_uppercase(); assert_eq!("ABC", s2); let b = unsafe {s2.as_bytes_mut() }; b[0] = b'D'; b[1] = b'E'; b[2] = b'F'; println!("{}", s2); } fn f4_2() { let n = 42; let c = 'R'; println!("{}, {}", n, c); fn hello() { println!("hello"); } let hello = hello(); assert_eq!((), hello); assert_eq!(std::mem::size_of::<()>(), 0); let b1 = true; let b2 = !b1; assert_eq!(b2, false); let n1 = 8; let n2 = 12; let b3 = n1 > 10; let b4 = n2 > 10; let b5 = b3 && b4; let b6 = b3 || b4; assert_eq!(b5, false); assert_eq!(b6, true); assert_eq!(std::mem::size_of::<bool>(), 1); let n1 = 10_000; let n1_1 = 10000; let n2 = 0u8; let n2_1: u8 = 0; let n3 = -100_isize; let n3_1: isize = -100; assert_eq!(n1, n1_1); assert_eq!(n2, n2_1); assert_eq!(n3, n3_1); let n4 = 10; let n5 = n3 + n4; print_typename(n5); let n1 = 57; let h1 = 0xff; let o1 = 0o71; let b1 = 0b1111_1111; assert_eq!(h1, b1); assert_eq!(n1, o1); let n6 = b'A'; assert_eq!(n6, 65u8); let n1 = std::u8::MAX; let _n2 = 1u8; println!("{}", n1); let n1 = 200u8; let n2 = 3u8; assert!(n1.checked_mul(n2).is_none()); assert_eq!(n1.saturating_mul(n2), std::u8::MAX); assert_eq!(n1.wrapping_mul(n2), 88); assert_eq!(n1.overflowing_mul(n2), (88, true)); let _f1 = 10.0; let _f2 = -1_234.56_f32; let _f3 = 578.6E77; let c1 ='A'; let c2 = 'a'; assert!(c1 < c2); assert!(c1.is_uppercase()); let c3 = '0'; assert!(c3.is_digit(10)); let c4 = '\t'; let c5 = '\n'; let c6 = '\''; let c7 = '\\'; let c8 = '\x7F'; let c9 = '\u{1f600}'; println!("{}, {}, {}, {}, {}, {}, {}", c3, c4, c5, c6, c7, c8, c9); fn func1(mut n: u32) { println!("func1-1 {}", n); n = 1; println!("func1-2 {}", n); } fn func2(n_ptr: &mut u32) { println!("func2 *n_ptr {}", *n_ptr); println!("func2 n_ptr {}", n_ptr); *n_ptr = 10; println!("func2 *n_ptr {}", n_ptr); } let mut x = 5; func1(x); func2(&mut x); let c1 = 'A'; let c1_ptr = &c1; assert_eq!(*c1_ptr, 'A'); let mut n1 = 0; let n1_ptr = &mut n1; assert_eq!(*n1_ptr, 0); fn double (n: i32) -> i32 { n + n } fn abs(n: i32) -> i32 { if n >= 0 { n } else { -n } } let mut func: fn(i32) -> i32 = double; let x = -5; println!("{}", func(x)); func = abs; println!("{}", func(x)); let x = 4; let adder = |n| n + x ; assert_eq!(adder(2), 4 + 2); let mut state = false; let mut flipflop = || { state = !state; state }; println!("{}", flipflop()); println!("{}", flipflop()); println!("{}", flipflop()); println!("{}", state); } fn print_typename<T>(_ : T) { println!("{}", std::any::type_name::<T>()); }
if let Some(apples) = apple_line { assert!(apples.starts_with("red")); assert!(apples.contains("apple")); println!("{:?}", apples.find("green")); let mut apple_iter = apples.split(","); assert_eq!(apple_iter.next(), Some("red apple")); let green = apple_iter.next(); assert_eq!(Some(" green apple"), green); assert_eq!(Some("green apple"), green.map(|s| s.trim())); assert_eq!(Some("green apple"), green.map(str::trim)); }
if_condition
[ { "content": "fn print_info(name: &str, sl: &[char]) {\n\n println!(\" {:9} - {}, {:?}, {:?}, {:?}\",\n\n name,\n\n sl.len(),\n\n sl.first(),\n\n sl.get(1),\n\n sl.last()\n\n );\n\n}\n\n\n", "file_path": "jissen/1st/code4/src/main.rs", "rank": 0, "score": 41...
Rust
src/lt.rs
Others/fountain_codes
798ea7240b1714958a5cf7e5af0f0c2048ce011e
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; use std::io::{self, Cursor}; use std::ops::{BitXor, BitXorAssign, Index}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::{Client, CreationError, Data, Decoder, Encoder, Metadata, Packet, PartialEncoder, Source}; use super::distributions::{Distribution, RobustSolitonDistribution}; const DEFAULT_FAILURE_PROBABILITY: f64 = 0.1; const DEFAULT_HINT_CONSTANT: f64 = 0.3; pub struct LtSource { blocks: Vec<Block>, distribution: Distribution } impl Source<LtPacket> for LtSource { fn new(metadata: Metadata, data: Data) -> Result<Self, CreationError> { let data_bytes = metadata.data_bytes(); if data_bytes == 0 { return Err(CreationError::DataZeroBytes); } if data_bytes != data.len() as u64 { return Err(CreationError::InvalidMetadata); } let extra_block = cmp::min((data_bytes % BLOCK_BYTES as u64), 1); let block_count = (data_bytes / (BLOCK_BYTES as u64)) + extra_block; if block_count > (u32::max_value() as u64) { return Err(CreationError::DataTooBig) } let mut blocks: Vec<Block> = Vec::with_capacity(block_count as usize); for chunk in data.chunks(BLOCK_BYTES) { let mut block = [0; BLOCK_BYTES]; for i in 0..chunk.len() { block[i] = chunk[i]; } blocks.push(Block::from_data(block)); } let density_function = RobustSolitonDistribution::new_using_heuristic(DEFAULT_FAILURE_PROBABILITY, DEFAULT_HINT_CONSTANT); let distribution = Distribution::new(&density_function, block_count as u32).map_err(|e| CreationError::RandomInitializationError(e))?; Ok(LtSource{ blocks: blocks, distribution: distribution }) } } fn choose_blocks_to_combine(distribution: &Distribution, blocks: &mut Vec<u32>) { let blocks_to_combine = cmp::min(blocks.len(), distribution.query() as usize); for i in 0..blocks_to_combine { let j = distribution.query_interior_rng_usize(i, blocks.len()); blocks.swap(i, j); } blocks.truncate(blocks_to_combine as usize); } impl Encoder<LtPacket> for LtSource { fn create_packet(&self) -> LtPacket { let block_count = self.blocks.len(); let mut blocks: Vec<u32> = Vec::with_capacity(block_count); for i in 0..block_count{ blocks.push(i as u32); } choose_blocks_to_combine(&self.distribution, &mut blocks); let mut new_block = Block::new(); for block_id in &blocks { new_block ^= self.blocks.index(*block_id as usize); } LtPacket::new(blocks, new_block) } } #[derive(Debug)] pub struct LtClient { metadata: Metadata, block_count: u32, distribution: Distribution, decoded_blocks: HashMap<u32, Block>, stale_packets: HashSet<LtPacket> } impl Client<LtPacket> for LtClient { fn new(metadata: Metadata) -> Result<Self, CreationError> { let data_bytes = metadata.data_bytes(); if data_bytes == 0 { return Err(CreationError::DataZeroBytes) } let extra_block = cmp::min((data_bytes % BLOCK_BYTES as u64), 1); let block_count = (data_bytes / (BLOCK_BYTES as u64)) + extra_block; if block_count > (u32::max_value() as u64) { return Err(CreationError::DataTooBig) } let density_function = RobustSolitonDistribution::new_using_heuristic(DEFAULT_FAILURE_PROBABILITY, DEFAULT_HINT_CONSTANT); let distribution = Distribution::new(&density_function, block_count as u32).map_err(|e| CreationError::RandomInitializationError(e))?; Ok(LtClient { metadata: metadata, block_count: block_count as u32, distribution: distribution, decoded_blocks: HashMap::new(), stale_packets: HashSet::new() }) } } impl PartialEncoder<LtPacket> for LtClient { fn try_create_packet(&self) -> Option<LtPacket> { let mut blocks: Vec<u32> = Vec::with_capacity(self.decoded_blocks.len()); for &key in self.decoded_blocks.keys() { blocks.push(key); } if blocks.len() == 0 { return None; } choose_blocks_to_combine(&self.distribution, &mut blocks); let mut new_block = Block::new(); for block_id in &blocks { new_block = new_block ^ self.decoded_blocks.index(block_id); } return Some(LtPacket::new(blocks, new_block)); } } impl Decoder<LtPacket> for LtClient { fn receive_packet(&mut self, packet: LtPacket) { let mut fresh_packets: Vec<LtPacket> = vec![packet]; while let Some(packet) = fresh_packets.pop() { let mut xor: Vec<u32> = Vec::with_capacity(packet.combined_blocks.len()); let mut multiple_remaining = false; let mut remainder: Option<u32> = None; for block_id in &packet.combined_blocks { if self.decoded_blocks.contains_key(&block_id) { xor.push(*block_id); } else { remainder = match remainder { Option::None => { Some(*block_id) } Option::Some(remainder) => { multiple_remaining = true; Some(remainder) } }; if multiple_remaining { break; } } } if multiple_remaining || remainder.is_none(){ self.stale_packets.insert(packet); }else { let block_id = remainder.unwrap(); if !self.decoded_blocks.contains_key(&block_id) { let mut data = packet.data; for block_id in xor { data = data ^ self.decoded_blocks.get(&block_id).expect("Blocks selected to be xor'd must exist"); } self.decoded_blocks.insert(block_id, data); let mut refreshed_packets: Vec<LtPacket> = Vec::new(); for stale_packet in &self.stale_packets { if stale_packet.combined_blocks.contains(&block_id) { refreshed_packets.push(stale_packet.clone()); } } for packet in refreshed_packets { self.stale_packets.remove(&packet); fresh_packets.push(packet); } } } } } fn get_result(&self) -> Option<Data> { if self.decoded_blocks.len() < self.block_count as usize { return None; } let mut block_bytes: Vec<u8> = Vec::with_capacity(self.metadata.data_bytes() as usize); for i in 0..self.block_count { let block_option = self.decoded_blocks.get(&i); if block_option.is_none() { return None; } block_bytes.extend_from_slice(block_option.unwrap().data()); } block_bytes.truncate(self.metadata.data_bytes() as usize); Some(block_bytes) } fn decoding_progress(&self) -> f64 { (self.decoded_blocks.len() as f64) / (self.block_count as f64) } } const BLOCK_BYTES: usize = 1024; struct Block { data: [u8; BLOCK_BYTES] } impl Block { fn new() -> Block { Block { data: [0; BLOCK_BYTES] } } fn from_data(data: [u8; BLOCK_BYTES]) -> Block { Block { data: data } } fn data(&self) -> &[u8] { &self.data[..] } } impl<'a> BitXorAssign<&'a Block> for Block { fn bitxor_assign(&mut self, rhs: &'a Block) { for i in 0..BLOCK_BYTES { self.data[i] ^= rhs.data[i] } } } impl<'a> BitXor<&'a Block> for Block { type Output = Self; fn bitxor(self, rhs: &'a Block) -> Self { let mut result = self; result ^= rhs; return result; } } impl Clone for Block { fn clone(&self) -> Self { Block { data: self.data } } } impl Debug for Block { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { fmt.write_str(&format!("{:?}", &self.data[..])) } } impl PartialEq for Block { fn eq(&self, other: &Self) -> bool { &self.data[..] == &other.data[..] } } impl Eq for Block {} impl Hash for Block { fn hash<H: Hasher>(&self, state: &mut H) { state.write(&self.data[..]) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct LtPacket { combined_blocks: Vec<u32>, data: Block } impl LtPacket { fn new(combined_blocks: Vec<u32>, data: Block) -> LtPacket { LtPacket { combined_blocks: combined_blocks, data: data } } } impl Packet for LtPacket { fn from_bytes(bytes: Vec<u8>) -> io::Result<LtPacket> { let mut rdr = Cursor::new(bytes); let block_count = rdr.read_u32::<BigEndian>()?; let mut combined_blocks = Vec::new(); for _ in 0..block_count { let block = rdr.read_u32::<BigEndian>()?; combined_blocks.push(block); } let mut block_data = [0; BLOCK_BYTES]; for i in 0..BLOCK_BYTES { block_data[i] = rdr.read_u8()?; } let block = Block::from_data(block_data); Ok(LtPacket::new(combined_blocks, block)) } fn to_bytes(&self) -> io::Result<Vec<u8>> { let mut dest = Vec::new(); dest.write_u32::<BigEndian>(self.combined_blocks.len() as u32)?; for block in &self.combined_blocks { dest.write_u32::<BigEndian>(*block)?; } for byte in self.data.data() { dest.write_u8(*byte)?; } Ok(dest) } } #[cfg(test)] mod tests { use super::super::Packet; use super::{BLOCK_BYTES, Block, LtPacket}; #[test] fn block_equals() { assert_eq!(Block::new() ^ &Block::new(), Block::new()); let one_block = Block::from_data([1; BLOCK_BYTES]); assert_eq!(one_block.clone() ^ &Block::new(), one_block); } #[test] fn packet_round_trips() { let combined_blocks = vec![1, 2, 3, 4, 5]; let block_data = [0; BLOCK_BYTES]; let packet = LtPacket::new(combined_blocks.clone(), Block::from_data(block_data).clone()); let bytes = packet.clone().to_bytes().unwrap(); assert_eq!(LtPacket::from_bytes(bytes).unwrap(), packet); } }
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; use std::io::{self, Cursor}; use std::ops::{BitXor, BitXorAssign, Index}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::{Client, CreationError, Data, Decoder, Encoder, Metadata, Packet, PartialEncoder, Source}; use super::distributions::{Distribution, RobustSolitonDistribution}; const DEFAULT_FAILURE_PROBABILITY: f64 = 0.1; const DEFAULT_HINT_CONSTANT: f64 = 0.3; pub struct LtSource { blocks: Vec<Block>, distribution: Distribution } impl Source<LtPacket> for LtSource { fn new(metadata: Metadata, data: Data) -> Result<Self, CreationError> { let data_bytes = metadata.data_bytes(); if data_bytes == 0 { return Err(CreationError::DataZeroBytes); } if data_bytes != data.len() as u64 { return Err(CreationError::InvalidMetadata); } let extra_block = cmp::min((data_bytes % BLOCK_BYTES as u64), 1); let block_count = (data_bytes / (BLOCK_BYTES as u64)) + extra_block; if block_count > (u32::max_value() as u64) { return Err(CreationError::DataTooBig) } let mut blocks: Vec<Block> = Vec::with_capacity(block_count as usize); for chunk in data.chunks(BLOCK_BYTES) { let mut block = [0; BLOCK_BYTES]; for i in 0..chunk.len() { block[i] = chunk[i]; } blocks.push(Block::from_data(block)); } let density_function = RobustSolitonDistribution::new_using_heuristic(DEFAULT_FAILURE_PROBABILITY, DEFAULT_HINT_CONSTANT); let distribution = Distribution::new(&density_function, block_count as u32).map_err(|e| CreationError::RandomInitializationError(e))?; Ok(LtSource{ blocks: blocks, distribution: distribution }) } } fn choose_blocks_to_combine(distribution: &Distribution, blocks: &mut Vec<u32>) { let blocks_to_combine = cmp::min(blocks.len(), distribution.query() as usize); fo
impl Encoder<LtPacket> for LtSource { fn create_packet(&self) -> LtPacket { let block_count = self.blocks.len(); let mut blocks: Vec<u32> = Vec::with_capacity(block_count); for i in 0..block_count{ blocks.push(i as u32); } choose_blocks_to_combine(&self.distribution, &mut blocks); let mut new_block = Block::new(); for block_id in &blocks { new_block ^= self.blocks.index(*block_id as usize); } LtPacket::new(blocks, new_block) } } #[derive(Debug)] pub struct LtClient { metadata: Metadata, block_count: u32, distribution: Distribution, decoded_blocks: HashMap<u32, Block>, stale_packets: HashSet<LtPacket> } impl Client<LtPacket> for LtClient { fn new(metadata: Metadata) -> Result<Self, CreationError> { let data_bytes = metadata.data_bytes(); if data_bytes == 0 { return Err(CreationError::DataZeroBytes) } let extra_block = cmp::min((data_bytes % BLOCK_BYTES as u64), 1); let block_count = (data_bytes / (BLOCK_BYTES as u64)) + extra_block; if block_count > (u32::max_value() as u64) { return Err(CreationError::DataTooBig) } let density_function = RobustSolitonDistribution::new_using_heuristic(DEFAULT_FAILURE_PROBABILITY, DEFAULT_HINT_CONSTANT); let distribution = Distribution::new(&density_function, block_count as u32).map_err(|e| CreationError::RandomInitializationError(e))?; Ok(LtClient { metadata: metadata, block_count: block_count as u32, distribution: distribution, decoded_blocks: HashMap::new(), stale_packets: HashSet::new() }) } } impl PartialEncoder<LtPacket> for LtClient { fn try_create_packet(&self) -> Option<LtPacket> { let mut blocks: Vec<u32> = Vec::with_capacity(self.decoded_blocks.len()); for &key in self.decoded_blocks.keys() { blocks.push(key); } if blocks.len() == 0 { return None; } choose_blocks_to_combine(&self.distribution, &mut blocks); let mut new_block = Block::new(); for block_id in &blocks { new_block = new_block ^ self.decoded_blocks.index(block_id); } return Some(LtPacket::new(blocks, new_block)); } } impl Decoder<LtPacket> for LtClient { fn receive_packet(&mut self, packet: LtPacket) { let mut fresh_packets: Vec<LtPacket> = vec![packet]; while let Some(packet) = fresh_packets.pop() { let mut xor: Vec<u32> = Vec::with_capacity(packet.combined_blocks.len()); let mut multiple_remaining = false; let mut remainder: Option<u32> = None; for block_id in &packet.combined_blocks { if self.decoded_blocks.contains_key(&block_id) { xor.push(*block_id); } else { remainder = match remainder { Option::None => { Some(*block_id) } Option::Some(remainder) => { multiple_remaining = true; Some(remainder) } }; if multiple_remaining { break; } } } if multiple_remaining || remainder.is_none(){ self.stale_packets.insert(packet); }else { let block_id = remainder.unwrap(); if !self.decoded_blocks.contains_key(&block_id) { let mut data = packet.data; for block_id in xor { data = data ^ self.decoded_blocks.get(&block_id).expect("Blocks selected to be xor'd must exist"); } self.decoded_blocks.insert(block_id, data); let mut refreshed_packets: Vec<LtPacket> = Vec::new(); for stale_packet in &self.stale_packets { if stale_packet.combined_blocks.contains(&block_id) { refreshed_packets.push(stale_packet.clone()); } } for packet in refreshed_packets { self.stale_packets.remove(&packet); fresh_packets.push(packet); } } } } } fn get_result(&self) -> Option<Data> { if self.decoded_blocks.len() < self.block_count as usize { return None; } let mut block_bytes: Vec<u8> = Vec::with_capacity(self.metadata.data_bytes() as usize); for i in 0..self.block_count { let block_option = self.decoded_blocks.get(&i); if block_option.is_none() { return None; } block_bytes.extend_from_slice(block_option.unwrap().data()); } block_bytes.truncate(self.metadata.data_bytes() as usize); Some(block_bytes) } fn decoding_progress(&self) -> f64 { (self.decoded_blocks.len() as f64) / (self.block_count as f64) } } const BLOCK_BYTES: usize = 1024; struct Block { data: [u8; BLOCK_BYTES] } impl Block { fn new() -> Block { Block { data: [0; BLOCK_BYTES] } } fn from_data(data: [u8; BLOCK_BYTES]) -> Block { Block { data: data } } fn data(&self) -> &[u8] { &self.data[..] } } impl<'a> BitXorAssign<&'a Block> for Block { fn bitxor_assign(&mut self, rhs: &'a Block) { for i in 0..BLOCK_BYTES { self.data[i] ^= rhs.data[i] } } } impl<'a> BitXor<&'a Block> for Block { type Output = Self; fn bitxor(self, rhs: &'a Block) -> Self { let mut result = self; result ^= rhs; return result; } } impl Clone for Block { fn clone(&self) -> Self { Block { data: self.data } } } impl Debug for Block { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { fmt.write_str(&format!("{:?}", &self.data[..])) } } impl PartialEq for Block { fn eq(&self, other: &Self) -> bool { &self.data[..] == &other.data[..] } } impl Eq for Block {} impl Hash for Block { fn hash<H: Hasher>(&self, state: &mut H) { state.write(&self.data[..]) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct LtPacket { combined_blocks: Vec<u32>, data: Block } impl LtPacket { fn new(combined_blocks: Vec<u32>, data: Block) -> LtPacket { LtPacket { combined_blocks: combined_blocks, data: data } } } impl Packet for LtPacket { fn from_bytes(bytes: Vec<u8>) -> io::Result<LtPacket> { let mut rdr = Cursor::new(bytes); let block_count = rdr.read_u32::<BigEndian>()?; let mut combined_blocks = Vec::new(); for _ in 0..block_count { let block = rdr.read_u32::<BigEndian>()?; combined_blocks.push(block); } let mut block_data = [0; BLOCK_BYTES]; for i in 0..BLOCK_BYTES { block_data[i] = rdr.read_u8()?; } let block = Block::from_data(block_data); Ok(LtPacket::new(combined_blocks, block)) } fn to_bytes(&self) -> io::Result<Vec<u8>> { let mut dest = Vec::new(); dest.write_u32::<BigEndian>(self.combined_blocks.len() as u32)?; for block in &self.combined_blocks { dest.write_u32::<BigEndian>(*block)?; } for byte in self.data.data() { dest.write_u8(*byte)?; } Ok(dest) } } #[cfg(test)] mod tests { use super::super::Packet; use super::{BLOCK_BYTES, Block, LtPacket}; #[test] fn block_equals() { assert_eq!(Block::new() ^ &Block::new(), Block::new()); let one_block = Block::from_data([1; BLOCK_BYTES]); assert_eq!(one_block.clone() ^ &Block::new(), one_block); } #[test] fn packet_round_trips() { let combined_blocks = vec![1, 2, 3, 4, 5]; let block_data = [0; BLOCK_BYTES]; let packet = LtPacket::new(combined_blocks.clone(), Block::from_data(block_data).clone()); let bytes = packet.clone().to_bytes().unwrap(); assert_eq!(LtPacket::from_bytes(bytes).unwrap(), packet); } }
r i in 0..blocks_to_combine { let j = distribution.query_interior_rng_usize(i, blocks.len()); blocks.swap(i, j); } blocks.truncate(blocks_to_combine as usize); }
function_block-function_prefixed
[ { "content": "pub trait Source<P: Packet> : Encoder<P> + Sized {\n\n fn new(metadata: Metadata, data: Data) -> Result<Self, CreationError>;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 2, "score": 67255.24559277261 }, { "content": "pub trait Decoder<P: Packet> {\n\n fn receive_packe...
Rust
src/xcb/xconn.rs
psychon/penrose
69912708f7982b7d6a61b9fa549040fb4c3625fb
/*! * API wrapper for talking to the X server using XCB * * The crate used by penrose for talking to the X server is rust-xcb, which * is a set of bindings for the C level XCB library that are autogenerated * from an XML spec. The XML files can be found * [here](https://github.com/rtbo/rust-xcb/tree/master/xml) and are useful * as reference for how the API works. Sections have been converted and added * to the documentation of the method calls and enums present in this module. * * [EWMH](https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html) * [Xlib manual](https://tronche.com/gui/x/xlib/) */ use crate::{ core::{ bindings::{KeyBindings, MouseBindings}, data_types::{Point, PropVal, Region, WinAttr, WinConfig, WinId, WinType}, manager::WindowManager, screen::Screen, xconnection::{ Atom, XConn, XEvent, AUTO_FLOAT_WINDOW_TYPES, EWMH_SUPPORTED_ATOMS, UNMANAGED_WINDOW_TYPES, }, }, xcb::{Api, XcbApi}, Result, }; use std::{collections::HashMap, str::FromStr}; const WM_NAME: &str = "penrose"; /** * Handles communication with an X server via the XCB library. * * XcbConnection is a minimal implementation that does not make use of the full asyc capabilities * of the underlying C XCB library. **/ #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct XcbConnection { api: Api, check_win: WinId, auto_float_types: Vec<u32>, dont_manage_types: Vec<u32>, } impl XcbConnection { pub fn new() -> Result<Self> { let api = Api::new()?; let auto_float_types: Vec<u32> = AUTO_FLOAT_WINDOW_TYPES .iter() .map(|a| api.known_atom(*a)) .collect(); let dont_manage_types: Vec<u32> = UNMANAGED_WINDOW_TYPES .iter() .map(|a| api.known_atom(*a)) .collect(); api.set_randr_notify_mask()?; let check_win = api.create_window(WinType::CheckWin, Region::new(0, 0, 1, 1), false)?; Ok(Self { api, check_win, auto_float_types, dont_manage_types, }) } fn window_has_type_in(&self, id: WinId, win_types: &[u32]) -> bool { if let Ok(atom) = self.api.get_atom_prop(id, Atom::NetWmWindowType) { return win_types.contains(&atom); } false } pub fn xcb_connection(&self) -> &xcb::Connection { &self.api.conn() } pub fn api(&self) -> &Api { &self.api } pub fn api_mut(&mut self) -> &mut Api { &mut self.api } pub fn known_atoms(&self) -> &HashMap<Atom, u32> { &self.api.known_atoms() } } impl WindowManager<XcbConnection> { pub fn xcb_connection(&self) -> &xcb::Connection { &self.conn().xcb_connection() } pub fn known_atoms(&self) -> &HashMap<Atom, u32> { &self.conn().known_atoms() } } impl XConn for XcbConnection { #[cfg(feature = "serde")] fn hydrate(&mut self) -> Result<()> { Ok(self.api.hydrate()?) } fn flush(&self) -> bool { self.api.flush() } fn wait_for_event(&self) -> Result<XEvent> { Ok(self.api.wait_for_event()?) } fn current_outputs(&self) -> Vec<Screen> { match self.api.current_screens() { Ok(screens) => screens, Err(e) => panic!("{}", e), } } fn cursor_position(&self) -> Point { self.api.cursor_position() } fn position_window(&self, id: WinId, reg: Region, border: u32, stack_above: bool) { let mut data = vec![WinConfig::Position(reg), WinConfig::BorderPx(border)]; if stack_above { data.push(WinConfig::StackAbove); } self.api.configure_window(id, &data) } fn raise_window(&self, id: WinId) { self.api.configure_window(id, &[WinConfig::StackAbove]) } fn mark_new_window(&self, id: WinId) { let data = &[WinAttr::ClientEventMask]; self.api.set_window_attributes(id, data) } fn map_window(&self, id: WinId) { self.api.map_window(id); } fn unmap_window(&self, id: WinId) { self.api.unmap_window(id); } fn send_client_event(&self, id: WinId, atom_name: &str) -> Result<()> { Ok(self.api.send_client_event(id, atom_name)?) } fn focused_client(&self) -> WinId { self.api.focused_client().unwrap_or(0) } fn focus_client(&self, id: WinId) { self.api.mark_focused_window(id); } fn set_client_border_color(&self, id: WinId, color: u32) { let data = &[WinAttr::BorderColor(color)]; self.api.set_window_attributes(id, data); } fn toggle_client_fullscreen(&self, id: WinId, client_is_fullscreen: bool) { let data = if client_is_fullscreen { 0 } else { self.api.known_atom(Atom::NetWmStateFullscreen) }; self.api .replace_prop(id, Atom::NetWmState, PropVal::Atom(&[data])); } fn grab_keys(&self, key_bindings: &KeyBindings<Self>, mouse_bindings: &MouseBindings<Self>) { self.api.grab_keys(&key_bindings.keys().collect::<Vec<_>>()); self.api.grab_mouse_buttons( &mouse_bindings .keys() .map(|(_, state)| state) .collect::<Vec<_>>(), ); let data = &[WinAttr::RootEventMask]; self.api.set_window_attributes(self.api.root(), data); self.flush(); } fn set_wm_properties(&self, workspaces: &[&str]) { let root = self.api.root(); for &win in &[self.check_win, root] { self.api.replace_prop( win, Atom::NetSupportingWmCheck, PropVal::Window(&[self.check_win]), ); let val = PropVal::Str(WM_NAME); self.api.replace_prop(win, Atom::WmName, val); } let supported = EWMH_SUPPORTED_ATOMS .iter() .map(|a| self.api.known_atom(*a)) .collect::<Vec<u32>>(); let prop = PropVal::Atom(&supported); self.api.replace_prop(root, Atom::NetSupported, prop); self.update_desktops(workspaces); self.api.delete_prop(root, Atom::NetClientList); } fn update_desktops(&self, workspaces: &[&str]) { let root = self.api.root(); self.api.replace_prop( root, Atom::NetNumberOfDesktops, PropVal::Cardinal(&[workspaces.len() as u32]), ); self.api.replace_prop( root, Atom::NetDesktopNames, PropVal::Str(&workspaces.join("\0")), ); } fn update_known_clients(&self, clients: &[WinId]) { self.api.replace_prop( self.api.root(), Atom::NetClientList, PropVal::Window(clients), ); self.api.replace_prop( self.api.root(), Atom::NetClientListStacking, PropVal::Window(clients), ); } fn set_current_workspace(&self, wix: usize) { self.api.replace_prop( self.api.root(), Atom::NetCurrentDesktop, PropVal::Cardinal(&[wix as u32]), ); } fn set_root_window_name(&self, root_name: &str) { self.api .replace_prop(self.api.root(), Atom::WmName, PropVal::Str(root_name)); } fn set_client_workspace(&self, id: WinId, workspace: usize) { self.api.replace_prop( id, Atom::NetWmDesktop, PropVal::Cardinal(&[workspace as u32]), ); } fn window_should_float(&self, id: WinId, floating_classes: &[&str]) -> bool { if let Ok(s) = self.str_prop(id, Atom::WmClass.as_ref()) { if s.split('\0').any(|c| floating_classes.contains(&c)) { return true; } } self.window_has_type_in(id, &self.auto_float_types) } fn is_managed_window(&self, id: WinId) -> bool { !self.window_has_type_in(id, &self.dont_manage_types) } fn window_geometry(&self, id: WinId) -> Result<Region> { Ok(self.api.window_geometry(id)?) } fn warp_cursor(&self, win_id: Option<WinId>, screen: &Screen) { let (x, y, id) = match win_id { Some(id) => { let (_, _, w, h) = match self.window_geometry(id) { Ok(region) => region.values(), Err(e) => { error!("error fetching window details while warping cursor: {}", e); return; } }; ((w / 2), (h / 2), id) } None => { let (x, y, w, h) = screen.region(true).values(); ((x + w / 2), (y + h / 2), self.api.root()) } }; self.api.warp_cursor(id, x as usize, y as usize); } fn query_for_active_windows(&self) -> Vec<WinId> { match self.api.current_clients() { Err(_) => Vec::new(), Ok(ids) => ids .iter() .filter(|&id| !self.window_has_type_in(*id, &self.dont_manage_types)) .cloned() .collect(), } } fn str_prop(&self, id: u32, name: &str) -> Result<String> { Ok(self.api.get_str_prop(id, name)?) } fn atom_prop(&self, id: u32, name: &str) -> Result<u32> { Ok(self.api.get_atom_prop(id, Atom::from_str(name)?)?) } fn intern_atom(&self, atom: &str) -> Result<u32> { Ok(self.api.atom(atom)?) } fn cleanup(&self) { self.api.ungrab_keys(); self.api.ungrab_mouse_buttons(); self.api.destroy_window(self.check_win); self.api.delete_prop(self.api.root(), Atom::NetActiveWindow); } }
/*! * API wrapper for talking to the X server using XCB * * The crate used by penrose for talking to the X server is rust-xcb, which * is a set of bindings for the C level XCB library that are autogenerated * from an XML spec. The XML files can be found * [here](https://github.com/rtbo/rust-xcb/tree/master/xml) and are useful * as reference for how the API works. Sections have been converted and added * to the documentation of the method calls and enums present in this module. * * [EWMH](https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html) * [Xlib manual](https://tronche.com/gui/x/xlib/) */ use crate::{ core::{ bindings::{KeyBindings, MouseBindings}, data_types::{Point, PropVal, Region, WinAttr, WinConfig, WinId, WinType}, manager::WindowManager, screen::Screen, xconnection::{ Atom, XConn, XEvent, AUTO_FLOAT_WINDOW_TYPES, EWMH_SUPPORTED_ATOMS, UNMANAGED_WINDOW_TYPES, }, }, xcb::{Api, XcbApi}, Result, }; use std::{collections::HashMap, str::FromStr}; const WM_NAME: &str = "penrose"; /** * Handles communication with an X server via the XCB library. * * XcbConnection is a minimal implementation that does not make use of the full asyc capabilities * of the underlying C XCB library. **/ #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct XcbConnection { api: Api, check_win: WinId, auto_float_types: Vec<u32>, dont_manage_types: Vec<u32>, } impl XcbConnection { pub fn new() -> Result<Self> { let api = Api::new()?; let auto_float_types: Vec<u32> = AUTO_FLOAT_WINDOW_TYPES .iter() .map(|a| api.known_atom(*a)) .collect(); let dont_manage_types: Vec<u32> = UNMANAGED_WINDOW_TYPES .iter() .map(|a| api.known_atom(*a)) .collect(); api.set_randr_notify_mask()?; let check_win = api.create_window(WinType::CheckWin, Region::new(0, 0, 1, 1), false)?; Ok(Self { api, check_win, auto_float_types, dont_manage_types, }) } fn window_has_type_in(&self, id: WinId, win_types: &[u32]) -> bool { if let Ok(atom) = self.api.get_atom_prop(id, Atom::NetWmWindowType) { return win_types.contains(&atom); } false } pub fn xcb_connection(&self) -> &xcb::Connection { &self.api.conn() } pub fn api(&self) -> &Api { &self.api } pub fn api_mut(&mut self) -> &mut Api { &mut self.api } pub fn known_atoms(&self) -> &HashMap<Atom, u32> { &self.api.known_atoms() } } impl WindowManager<XcbConnection> { pub fn xcb_connection(&self) -> &xcb::Connection { &self.conn().xcb_connection() } pub fn known_atoms(&self) -> &HashMap<Atom, u32> { &self.conn().known_atoms() } } impl XConn for XcbConnection { #[cfg(feature = "serde")] fn hydrate(&mut self) -> Result<()> { Ok(self.api.hydrate()?) } fn flush(&self) -> bool { self.api.flush() } fn wait_for_event(&self) -> Result<XEvent> { Ok(self.api.wait_for_event()?) } fn current_outputs(&self) -> Vec<Screen> { match self.api.current_screens() { Ok(screens) => screens, Err(e) => panic!("{}", e), } } fn cursor_position(&self) -> Point { self.api.cursor_position() } fn position_window(&self, id: WinId, reg: Region, border: u32, stack_above: bool) { let mut data = vec![WinConfig::Position(reg), WinConfig::BorderPx(border)]; if stack_above { data.push(WinConfig::StackAbove); } self.api.configure_window(id, &data) } fn raise_window(&self, id: WinId) { self.api.configure_window(id, &[WinConfig::StackAbove]) } fn mark_new_window(&self, id: WinId) { let data = &[WinAttr::ClientEventMask]; self.api.set_window_attributes(id, data) } fn map_window(&self, id: WinId) { self.api.map_window(id); } fn unmap_window(&self, id: WinId) { self.api.unmap_window(id); } fn send_client_event(&self, id: WinId, atom_name: &str) -> Result<()> { Ok(self.api.send_client_event(id, atom_name)?) } fn focused_client(&self) -> WinId { self.api.focused_client().unwrap_or(0) } fn focus_client(&self, id: WinId) { self.api.mark_focused_window(id); } fn set_client_border_color(&self, id: WinId, color: u32) { let data = &[WinAttr::BorderColor(color)]; self.api.set_window_attributes(id, data); } fn toggle_client_fullscreen(&self, id: WinId, client_is_fullscreen: bool) { let data = if client_is_fullscreen { 0 } else { self.api.known_atom(Atom::NetWmStateFullscreen) }; self.api .replace_prop(id, Atom::NetWmState, PropVal::Atom(&[data])); } fn grab_keys(&self, key_bindings: &KeyBindings<Self>, mouse_bindings: &MouseBindings<Self>) { self.api.grab_keys(&key_bindings.keys().collect::<Vec<_>>()); self.api.grab_mouse_buttons( &mouse_bindings .keys() .map(|(_, state)| state) .collect::<Vec<_>>(), ); let data = &[WinAttr::RootEventMask]; self.api.set_window_attributes(self.api.root(), data); self.flush(); } fn set_wm_properties(&self, workspaces: &[&str]) { let root = self.api.root(); for &win in &[self.check_win, root] { self.api.replace_prop( win, Atom::NetSupportingWmCheck, PropVal::Window(&[self.check_win]), ); let val = PropVal::Str(WM_NAME); self.api.replace_prop(win, Atom::WmName, val); } let supported = EWMH_SUPPORTED_ATOMS .iter() .map(|a| self.api.known_atom(*a)) .collect::<Vec<u32>>(); let prop = PropVal::Atom(&supported); self.api.replace_prop(root, Atom::NetSupported, prop); self.update_desktops(workspaces); self.api.delete_prop(root, Atom::NetClientList); } fn update_desktops(&self, workspaces: &[&str]) { let roo
fn update_known_clients(&self, clients: &[WinId]) { self.api.replace_prop( self.api.root(), Atom::NetClientList, PropVal::Window(clients), ); self.api.replace_prop( self.api.root(), Atom::NetClientListStacking, PropVal::Window(clients), ); } fn set_current_workspace(&self, wix: usize) { self.api.replace_prop( self.api.root(), Atom::NetCurrentDesktop, PropVal::Cardinal(&[wix as u32]), ); } fn set_root_window_name(&self, root_name: &str) { self.api .replace_prop(self.api.root(), Atom::WmName, PropVal::Str(root_name)); } fn set_client_workspace(&self, id: WinId, workspace: usize) { self.api.replace_prop( id, Atom::NetWmDesktop, PropVal::Cardinal(&[workspace as u32]), ); } fn window_should_float(&self, id: WinId, floating_classes: &[&str]) -> bool { if let Ok(s) = self.str_prop(id, Atom::WmClass.as_ref()) { if s.split('\0').any(|c| floating_classes.contains(&c)) { return true; } } self.window_has_type_in(id, &self.auto_float_types) } fn is_managed_window(&self, id: WinId) -> bool { !self.window_has_type_in(id, &self.dont_manage_types) } fn window_geometry(&self, id: WinId) -> Result<Region> { Ok(self.api.window_geometry(id)?) } fn warp_cursor(&self, win_id: Option<WinId>, screen: &Screen) { let (x, y, id) = match win_id { Some(id) => { let (_, _, w, h) = match self.window_geometry(id) { Ok(region) => region.values(), Err(e) => { error!("error fetching window details while warping cursor: {}", e); return; } }; ((w / 2), (h / 2), id) } None => { let (x, y, w, h) = screen.region(true).values(); ((x + w / 2), (y + h / 2), self.api.root()) } }; self.api.warp_cursor(id, x as usize, y as usize); } fn query_for_active_windows(&self) -> Vec<WinId> { match self.api.current_clients() { Err(_) => Vec::new(), Ok(ids) => ids .iter() .filter(|&id| !self.window_has_type_in(*id, &self.dont_manage_types)) .cloned() .collect(), } } fn str_prop(&self, id: u32, name: &str) -> Result<String> { Ok(self.api.get_str_prop(id, name)?) } fn atom_prop(&self, id: u32, name: &str) -> Result<u32> { Ok(self.api.get_atom_prop(id, Atom::from_str(name)?)?) } fn intern_atom(&self, atom: &str) -> Result<u32> { Ok(self.api.atom(atom)?) } fn cleanup(&self) { self.api.ungrab_keys(); self.api.ungrab_mouse_buttons(); self.api.destroy_window(self.check_win); self.api.delete_prop(self.api.root(), Atom::NetActiveWindow); } }
t = self.api.root(); self.api.replace_prop( root, Atom::NetNumberOfDesktops, PropVal::Cardinal(&[workspaces.len() as u32]), ); self.api.replace_prop( root, Atom::NetDesktopNames, PropVal::Str(&workspaces.join("\0")), ); }
function_block-function_prefixed
[ { "content": "fn process_property_notify(id: WinId, atom: String, is_root: bool) -> Vec<EventAction> {\n\n match Atom::from_str(&atom) {\n\n Ok(a) if [Atom::WmName, Atom::NetWmName].contains(&a) => {\n\n vec![EventAction::ClientNameChanged(id, is_root)]\n\n }\n\n _ => vec![Eve...
Rust
src/fcfg1/config_if_adc.rs
luojia65/cc2640r2f
03a5bfca3e739dbb8310e2b0dabb07a8ca572fe5
#[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::CONFIG_IF_ADC { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct FF2ADJR { bits: u8, } impl FF2ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct FF3ADJR { bits: u8, } impl FF3ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct INT3ADJR { bits: u8, } impl INT3ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct FF1ADJR { bits: u8, } impl FF1ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct AAFCAPR { bits: u8, } impl AAFCAPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct INT2ADJR { bits: u8, } impl INT2ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct IFDIGLDO_TRIM_OUTPUTR { bits: u8, } impl IFDIGLDO_TRIM_OUTPUTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct IFANALDO_TRIM_OUTPUTR { bits: u8, } impl IFANALDO_TRIM_OUTPUTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _FF2ADJW<'a> { w: &'a mut W, } impl<'a> _FF2ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FF3ADJW<'a> { w: &'a mut W, } impl<'a> _FF3ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _INT3ADJW<'a> { w: &'a mut W, } impl<'a> _INT3ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FF1ADJW<'a> { w: &'a mut W, } impl<'a> _FF1ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _AAFCAPW<'a> { w: &'a mut W, } impl<'a> _AAFCAPW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _INT2ADJW<'a> { w: &'a mut W, } impl<'a> _INT2ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _IFDIGLDO_TRIM_OUTPUTW<'a> { w: &'a mut W, } impl<'a> _IFDIGLDO_TRIM_OUTPUTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 31; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _IFANALDO_TRIM_OUTPUTW<'a> { w: &'a mut W, } impl<'a> _IFANALDO_TRIM_OUTPUTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 31; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 28:31 - 31:28\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff2adj(&self) -> FF2ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 }; FF2ADJR { bits } } #[doc = "Bits 24:27 - 27:24\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff3adj(&self) -> FF3ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }; FF3ADJR { bits } } #[doc = "Bits 20:23 - 23:20\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int3adj(&self) -> INT3ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 }; INT3ADJR { bits } } #[doc = "Bits 16:19 - 19:16\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff1adj(&self) -> FF1ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; FF1ADJR { bits } } #[doc = "Bits 14:15 - 15:14\\] Internal. Only to be used through TI provided API."] #[inline] pub fn aafcap(&self) -> AAFCAPR { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 }; AAFCAPR { bits } } #[doc = "Bits 10:13 - 13:10\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int2adj(&self) -> INT2ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 }; INT2ADJR { bits } } #[doc = "Bits 5:9 - 9:5\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifdigldo_trim_output(&self) -> IFDIGLDO_TRIM_OUTPUTR { let bits = { const MASK: u8 = 31; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) as u8 }; IFDIGLDO_TRIM_OUTPUTR { bits } } #[doc = "Bits 0:4 - 4:0\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifanaldo_trim_output(&self) -> IFANALDO_TRIM_OUTPUTR { let bits = { const MASK: u8 = 31; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; IFANALDO_TRIM_OUTPUTR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 878769152 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 28:31 - 31:28\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff2adj(&mut self) -> _FF2ADJW { _FF2ADJW { w: self } } #[doc = "Bits 24:27 - 27:24\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff3adj(&mut self) -> _FF3ADJW { _FF3ADJW { w: self } } #[doc = "Bits 20:23 - 23:20\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int3adj(&mut self) -> _INT3ADJW { _INT3ADJW { w: self } } #[doc = "Bits 16:19 - 19:16\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff1adj(&mut self) -> _FF1ADJW { _FF1ADJW { w: self } } #[doc = "Bits 14:15 - 15:14\\] Internal. Only to be used through TI provided API."] #[inline] pub fn aafcap(&mut self) -> _AAFCAPW { _AAFCAPW { w: self } } #[doc = "Bits 10:13 - 13:10\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int2adj(&mut self) -> _INT2ADJW { _INT2ADJW { w: self } } #[doc = "Bits 5:9 - 9:5\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifdigldo_trim_output(&mut self) -> _IFDIGLDO_TRIM_OUTPUTW { _IFDIGLDO_TRIM_OUTPUTW { w: self } } #[doc = "Bits 0:4 - 4:0\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifanaldo_trim_output(&mut self) -> _IFANALDO_TRIM_OUTPUTW { _IFANALDO_TRIM_OUTPUTW { w: self } } }
#[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::CONFIG_IF_ADC { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct FF2ADJR { bits: u8, } impl FF2ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct FF3ADJR { bits: u8, } impl FF3ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct INT3ADJR { bits: u8, } impl INT3ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct FF1ADJR { bits: u8, } impl FF1ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct AAFCAPR { bits: u8, } impl AAFCAPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct INT2ADJR { bits: u8, } impl INT2ADJR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct IFDIGLDO_TRIM_OUTPUTR { bits: u8, } impl IFDIGLDO_TRIM_OUTPUTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct IFANALDO_TRIM_OUTPUTR { bits: u8, } impl IFANALDO_TRIM_OUTPUTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _FF2ADJW<'a> { w: &'a mut W, } impl<'a> _FF2ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FF3ADJW<'a> { w: &'a mut W, } impl<'a> _FF3ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _INT3ADJW<'a> { w: &'a mut W, } impl<'a> _INT3ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FF1ADJW<'a> { w: &'a mut W, } impl<'a> _FF1ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _AAFCAPW<'a> { w: &'a mut W, } impl<'a> _AAFCAPW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _INT2ADJW<'a> { w: &'a mut W, } impl<'a> _INT2ADJW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _IFDIGLDO_TRIM_OUTPUTW<'a> { w: &'a mut W, } impl<'a> _IFDIGLDO_TRIM_OUTPUTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 31; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _IFANALDO_TRIM_OUTPUTW<'a> { w: &'a mut W, } impl<'a> _IFANALDO_TRIM_OUTPUTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 31; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 28:31 - 31:28\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff2adj(&self) -> FF2ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 }; FF2ADJR { bits } } #[doc = "Bits 24:27 - 27:24\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff3adj(&self) -> FF3ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }; FF3ADJR { bits } } #[doc = "Bits 20:23 - 23:20\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int3adj(&self) -> INT3ADJR {
INT3ADJR { bits } } #[doc = "Bits 16:19 - 19:16\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff1adj(&self) -> FF1ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; FF1ADJR { bits } } #[doc = "Bits 14:15 - 15:14\\] Internal. Only to be used through TI provided API."] #[inline] pub fn aafcap(&self) -> AAFCAPR { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 }; AAFCAPR { bits } } #[doc = "Bits 10:13 - 13:10\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int2adj(&self) -> INT2ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 }; INT2ADJR { bits } } #[doc = "Bits 5:9 - 9:5\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifdigldo_trim_output(&self) -> IFDIGLDO_TRIM_OUTPUTR { let bits = { const MASK: u8 = 31; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) as u8 }; IFDIGLDO_TRIM_OUTPUTR { bits } } #[doc = "Bits 0:4 - 4:0\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifanaldo_trim_output(&self) -> IFANALDO_TRIM_OUTPUTR { let bits = { const MASK: u8 = 31; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; IFANALDO_TRIM_OUTPUTR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 878769152 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 28:31 - 31:28\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff2adj(&mut self) -> _FF2ADJW { _FF2ADJW { w: self } } #[doc = "Bits 24:27 - 27:24\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff3adj(&mut self) -> _FF3ADJW { _FF3ADJW { w: self } } #[doc = "Bits 20:23 - 23:20\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int3adj(&mut self) -> _INT3ADJW { _INT3ADJW { w: self } } #[doc = "Bits 16:19 - 19:16\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff1adj(&mut self) -> _FF1ADJW { _FF1ADJW { w: self } } #[doc = "Bits 14:15 - 15:14\\] Internal. Only to be used through TI provided API."] #[inline] pub fn aafcap(&mut self) -> _AAFCAPW { _AAFCAPW { w: self } } #[doc = "Bits 10:13 - 13:10\\] Internal. Only to be used through TI provided API."] #[inline] pub fn int2adj(&mut self) -> _INT2ADJW { _INT2ADJW { w: self } } #[doc = "Bits 5:9 - 9:5\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifdigldo_trim_output(&mut self) -> _IFDIGLDO_TRIM_OUTPUTW { _IFDIGLDO_TRIM_OUTPUTW { w: self } } #[doc = "Bits 0:4 - 4:0\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ifanaldo_trim_output(&mut self) -> _IFANALDO_TRIM_OUTPUTW { _IFANALDO_TRIM_OUTPUTW { w: self } } }
let bits = { const MASK: u8 = 15; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 };
assignment_statement
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
rust/xaynet-server/src/storage/s3.rs
abargiela/xaynet
2c87c5fd3f02f68dc9aefaaeb3a0371afa005722
use crate::settings::{S3BucketsSettings, S3Settings}; use rusoto_core::{credential::StaticProvider, request::TlsError, HttpClient, RusotoError}; use rusoto_s3::{ CreateBucketError, CreateBucketOutput, CreateBucketRequest, DeleteObjectsError, ListObjectsV2Error, PutObjectError, PutObjectOutput, PutObjectRequest, S3Client, StreamingBody, S3, }; use std::sync::Arc; use thiserror::Error; use xaynet_core::mask::Model; type S3Result<T> = Result<T, S3Error>; #[derive(Debug, Error)] pub enum S3Error { #[error("upload error: {0}")] Upload(#[from] RusotoError<PutObjectError>), #[error("create bucket error: {0}")] CreateBucket(#[from] RusotoError<CreateBucketError>), #[error("list objects error: {0}")] ListObjects(#[from] RusotoError<ListObjectsV2Error>), #[error("delete objects error: {0}")] DeleteObjects(#[from] RusotoError<DeleteObjectsError>), #[error("serialization failed")] Serialization(#[from] bincode::Error), #[error("empty response error")] EmptyResponse, #[error(transparent)] HttpClient(#[from] TlsError), } #[derive(Clone)] pub struct Client { buckets: Arc<S3BucketsSettings>, s3_client: S3Client, } #[cfg(test)] impl std::fmt::Debug for Client { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Client") .field("buckets", &self.buckets) .finish() } } impl Client { pub fn new(settings: S3Settings) -> S3Result<Self> { let credentials_provider = StaticProvider::new_minimal(settings.access_key, settings.secret_access_key); let dispatcher = HttpClient::new()?; Ok(Self { buckets: Arc::new(settings.buckets), s3_client: S3Client::new_with(dispatcher, credentials_provider, settings.region), }) } pub async fn upload_global_model(&self, key: &str, global_model: &Model) -> S3Result<()> { debug!("store global model: {}", key); let data = bincode::serialize(global_model)?; self.upload(&self.buckets.global_models, key, data) .await .map_err(From::from) .map(|_| ()) } pub async fn create_global_models_bucket(&self) -> S3Result<()> { debug!("create global-models bucket"); match self.create_bucket("global-models").await { Ok(_) | Err(RusotoError::Service(CreateBucketError::BucketAlreadyExists(_))) | Err(RusotoError::Service(CreateBucketError::BucketAlreadyOwnedByYou(_))) => Ok(()), Err(err) => Err(S3Error::from(err)), } } async fn upload( &self, bucket: &str, key: &str, data: Vec<u8>, ) -> Result<PutObjectOutput, RusotoError<PutObjectError>> { let req = PutObjectRequest { bucket: bucket.to_string(), key: key.to_string(), body: Some(StreamingBody::from(data)), ..Default::default() }; self.s3_client.put_object(req).await } async fn create_bucket( &self, bucket: &str, ) -> Result<CreateBucketOutput, RusotoError<CreateBucketError>> { let req = CreateBucketRequest { bucket: bucket.to_string(), ..Default::default() }; self.s3_client.create_bucket(req).await } } #[cfg(test)] pub(in crate) mod tests { use super::*; use crate::storage::tests::create_global_model; use rusoto_core::Region; use rusoto_s3::{ Delete, DeleteObjectsOutput, DeleteObjectsRequest, GetObjectOutput, GetObjectRequest, ListObjectsV2Output, ListObjectsV2Request, ObjectIdentifier, }; use serial_test::serial; use tokio::io::AsyncReadExt; use xaynet_core::{common::RoundSeed, crypto::ByteObject}; impl Client { pub async fn clear_bucket(&self, bucket: &str) -> S3Result<()> { let mut continuation_token: Option<String> = None; loop { let list_obj_resp = self.list_objects(bucket, continuation_token).await?; if let Some(identifiers) = Self::unpack_object_identifier(&list_obj_resp) { self.delete_objects(bucket, identifiers).await?; } else { break; } continuation_token = Self::unpack_next_continuation_token(&list_obj_resp); if continuation_token.is_none() { break; } } Ok(()) } pub async fn download_global_model(&self, key: &str) -> Model { debug!("get global model {:?}", key); let object = self.download_object(&self.buckets.global_models, key).await; let content = Self::unpack_object(object).await.expect("unpack error"); bincode::deserialize(&content).expect("deserialization error") } fn unpack_object_identifier( list_obj_resp: &ListObjectsV2Output, ) -> Option<Vec<ObjectIdentifier>> { if let Some(objects) = &list_obj_resp.contents { let keys = objects .iter() .filter_map(|obj| obj.key.clone()) .map(|key| ObjectIdentifier { key, ..Default::default() }) .collect(); Some(keys) } else { None } } async fn delete_objects( &self, bucket: &str, identifiers: Vec<ObjectIdentifier>, ) -> Result<DeleteObjectsOutput, RusotoError<DeleteObjectsError>> { let req = DeleteObjectsRequest { bucket: bucket.to_string(), delete: Delete { objects: identifiers, ..Default::default() }, ..Default::default() }; self.s3_client.delete_objects(req).await.map_err(From::from) } async fn list_objects( &self, bucket: &str, continuation_token: Option<String>, ) -> Result<ListObjectsV2Output, RusotoError<ListObjectsV2Error>> { let req = ListObjectsV2Request { bucket: bucket.to_string(), continuation_token, max_keys: Some(1000), ..Default::default() }; self.s3_client .list_objects_v2(req) .await .map_err(From::from) } fn unpack_next_continuation_token(list_obj_resp: &ListObjectsV2Output) -> Option<String> { if let Some(is_truncated) = list_obj_resp.is_truncated { if is_truncated { list_obj_resp.next_continuation_token.clone() } else { None } } else { None } } async fn unpack_object(object: GetObjectOutput) -> S3Result<Vec<u8>> { let mut content = Vec::new(); object .body .ok_or(S3Error::EmptyResponse)? .into_async_read() .read_to_end(&mut content) .await .map_err(|_| S3Error::EmptyResponse)?; Ok(content) } async fn download_object(&self, bucket: &str, key: &str) -> GetObjectOutput { let req = GetObjectRequest { bucket: bucket.to_string(), key: key.to_string(), ..Default::default() }; self.s3_client .get_object(req) .await .expect("download error") } } fn create_minio_setup() -> S3Settings { let region = Region::Custom { name: String::from("minio"), endpoint: String::from("http://localhost:9000"), }; S3Settings { region, access_key: String::from("minio"), secret_access_key: String::from("minio123"), buckets: S3BucketsSettings::default(), } } pub async fn create_client() -> Client { let settings = create_minio_setup(); let client = Client::new(settings).unwrap(); client.create_global_models_bucket().await.unwrap(); client.clear_bucket("global-models").await.unwrap(); client } #[tokio::test] #[serial] async fn integration_test_upload_global_model() { let client = create_client().await; let global_model = create_global_model(10); let round_seed = hex::encode(RoundSeed::generate().as_slice()); let res = client .upload_global_model(&format!("{}_{}", 1, round_seed), &global_model) .await; assert!(res.is_ok()) } }
use crate::settings::{S3BucketsSettings, S3Settings}; use rusoto_core::{credential::StaticProvider, request::TlsError, HttpClient, RusotoError}; use rusoto_s3::{ CreateBucketError, CreateBucketOutput, CreateBucketRequest, DeleteObjectsError, ListObjectsV2Error, PutObjectError, PutObjectOutput, PutObjectRequest, S3Client, StreamingBody, S3, }; use std::sync::Arc; use thiserror::Error; use xaynet_core::mask::Model; type S3Result<T> = Result<T, S3Error>; #[derive(Debug, Error)] pub enum S3Error { #[error("upload error: {0}")] Upload(#[from] RusotoError<PutObjectError>), #[error("create bucket error: {0}")] CreateBucket(#[from] RusotoError<CreateBucketError>), #[error("list objects error: {0}")] ListObjects(#[from] RusotoError<ListObjectsV2Error>), #[error("delete objects error: {0}")] DeleteObjects(#[from] RusotoError<DeleteObjectsError>), #[error("serialization failed")] Serialization(#[from] bincode::Error), #[error("empty response error")] EmptyResponse, #[error(transparent)] HttpClient(#[from] TlsError), } #[derive(Clone)] pub struct Client { buckets: Arc<S3BucketsSettings>, s3_client: S3Client, } #[cfg(test)] impl std::fmt::Debug for Client { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Client") .field("buckets", &self.buckets) .finish() } } impl Client { pub fn new(settings: S3Settings) -> S3Result<Self> { let credentials_provider = StaticProvider::new_minimal(settings.access_key, settings.secret_a
ifiers: Vec<ObjectIdentifier>, ) -> Result<DeleteObjectsOutput, RusotoError<DeleteObjectsError>> { let req = DeleteObjectsRequest { bucket: bucket.to_string(), delete: Delete { objects: identifiers, ..Default::default() }, ..Default::default() }; self.s3_client.delete_objects(req).await.map_err(From::from) } async fn list_objects( &self, bucket: &str, continuation_token: Option<String>, ) -> Result<ListObjectsV2Output, RusotoError<ListObjectsV2Error>> { let req = ListObjectsV2Request { bucket: bucket.to_string(), continuation_token, max_keys: Some(1000), ..Default::default() }; self.s3_client .list_objects_v2(req) .await .map_err(From::from) } fn unpack_next_continuation_token(list_obj_resp: &ListObjectsV2Output) -> Option<String> { if let Some(is_truncated) = list_obj_resp.is_truncated { if is_truncated { list_obj_resp.next_continuation_token.clone() } else { None } } else { None } } async fn unpack_object(object: GetObjectOutput) -> S3Result<Vec<u8>> { let mut content = Vec::new(); object .body .ok_or(S3Error::EmptyResponse)? .into_async_read() .read_to_end(&mut content) .await .map_err(|_| S3Error::EmptyResponse)?; Ok(content) } async fn download_object(&self, bucket: &str, key: &str) -> GetObjectOutput { let req = GetObjectRequest { bucket: bucket.to_string(), key: key.to_string(), ..Default::default() }; self.s3_client .get_object(req) .await .expect("download error") } } fn create_minio_setup() -> S3Settings { let region = Region::Custom { name: String::from("minio"), endpoint: String::from("http://localhost:9000"), }; S3Settings { region, access_key: String::from("minio"), secret_access_key: String::from("minio123"), buckets: S3BucketsSettings::default(), } } pub async fn create_client() -> Client { let settings = create_minio_setup(); let client = Client::new(settings).unwrap(); client.create_global_models_bucket().await.unwrap(); client.clear_bucket("global-models").await.unwrap(); client } #[tokio::test] #[serial] async fn integration_test_upload_global_model() { let client = create_client().await; let global_model = create_global_model(10); let round_seed = hex::encode(RoundSeed::generate().as_slice()); let res = client .upload_global_model(&format!("{}_{}", 1, round_seed), &global_model) .await; assert!(res.is_ok()) } }
ccess_key); let dispatcher = HttpClient::new()?; Ok(Self { buckets: Arc::new(settings.buckets), s3_client: S3Client::new_with(dispatcher, credentials_provider, settings.region), }) } pub async fn upload_global_model(&self, key: &str, global_model: &Model) -> S3Result<()> { debug!("store global model: {}", key); let data = bincode::serialize(global_model)?; self.upload(&self.buckets.global_models, key, data) .await .map_err(From::from) .map(|_| ()) } pub async fn create_global_models_bucket(&self) -> S3Result<()> { debug!("create global-models bucket"); match self.create_bucket("global-models").await { Ok(_) | Err(RusotoError::Service(CreateBucketError::BucketAlreadyExists(_))) | Err(RusotoError::Service(CreateBucketError::BucketAlreadyOwnedByYou(_))) => Ok(()), Err(err) => Err(S3Error::from(err)), } } async fn upload( &self, bucket: &str, key: &str, data: Vec<u8>, ) -> Result<PutObjectOutput, RusotoError<PutObjectError>> { let req = PutObjectRequest { bucket: bucket.to_string(), key: key.to_string(), body: Some(StreamingBody::from(data)), ..Default::default() }; self.s3_client.put_object(req).await } async fn create_bucket( &self, bucket: &str, ) -> Result<CreateBucketOutput, RusotoError<CreateBucketError>> { let req = CreateBucketRequest { bucket: bucket.to_string(), ..Default::default() }; self.s3_client.create_bucket(req).await } } #[cfg(test)] pub(in crate) mod tests { use super::*; use crate::storage::tests::create_global_model; use rusoto_core::Region; use rusoto_s3::{ Delete, DeleteObjectsOutput, DeleteObjectsRequest, GetObjectOutput, GetObjectRequest, ListObjectsV2Output, ListObjectsV2Request, ObjectIdentifier, }; use serial_test::serial; use tokio::io::AsyncReadExt; use xaynet_core::{common::RoundSeed, crypto::ByteObject}; impl Client { pub async fn clear_bucket(&self, bucket: &str) -> S3Result<()> { let mut continuation_token: Option<String> = None; loop { let list_obj_resp = self.list_objects(bucket, continuation_token).await?; if let Some(identifiers) = Self::unpack_object_identifier(&list_obj_resp) { self.delete_objects(bucket, identifiers).await?; } else { break; } continuation_token = Self::unpack_next_continuation_token(&list_obj_resp); if continuation_token.is_none() { break; } } Ok(()) } pub async fn download_global_model(&self, key: &str) -> Model { debug!("get global model {:?}", key); let object = self.download_object(&self.buckets.global_models, key).await; let content = Self::unpack_object(object).await.expect("unpack error"); bincode::deserialize(&content).expect("deserialization error") } fn unpack_object_identifier( list_obj_resp: &ListObjectsV2Output, ) -> Option<Vec<ObjectIdentifier>> { if let Some(objects) = &list_obj_resp.contents { let keys = objects .iter() .filter_map(|obj| obj.key.clone()) .map(|key| ObjectIdentifier { key, ..Default::default() }) .collect(); Some(keys) } else { None } } async fn delete_objects( &self, bucket: &str, ident
random
[ { "content": "fn error_code_type_error(response: &Value) -> RedisError {\n\n redis_type_error(\n\n \"Response status not valid integer\",\n\n Some(format!(\"Response was {:?}\", response)),\n\n )\n\n}\n\n\n\n/// Implements ['FromRedisValue'] and ['ToRedisArgs'] for types that implement ['Byt...
Rust
src/agent/onefuzz-agent/src/local/tui.rs
henryzz0/onefuzz
cb0701b2f2daf5b7b6d71bec9acd8dc0e329e1c3
use crate::local::common::UiEvent; use anyhow::{Context, Result}; use crossterm::{ event::{self, Event, KeyCode}, execute, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use futures::{StreamExt, TryStreamExt}; use log::Level; use onefuzz::utils::try_wait_all_join_handles; use std::{ collections::HashMap, io::{self, Stdout, Write}, path::PathBuf, thread::{self, JoinHandle}, time::Duration, }; use tokio::{ sync::mpsc::{self, UnboundedReceiver}, time, }; use tui::{ backend::CrosstermBackend, layout::{Constraint, Corner, Direction, Layout}, style::{Color, Modifier, Style}, text::{Span, Spans}, widgets::{Block, Borders}, widgets::{List, ListItem, ListState}, Terminal, }; use arraydeque::{ArrayDeque, Wrapping}; #[derive(Debug, thiserror::Error)] enum UiLoopError { #[error("program exiting")] Exit, #[error("error")] Anyhow(anyhow::Error), } impl From<anyhow::Error> for UiLoopError { fn from(e: anyhow::Error) -> Self { Self::Anyhow(e) } } impl From<std::io::Error> for UiLoopError { fn from(e: std::io::Error) -> Self { Self::Anyhow(e.into()) } } const LOGS_BUFFER_SIZE: usize = 100; const TICK_RATE: Duration = Duration::from_millis(250); #[derive(Debug)] enum TerminalEvent { Input(Event), Tick, FileCount { dir: PathBuf, count: usize }, Quit, } struct UiLoopState { pub logs: ArrayDeque<[(Level, String); LOGS_BUFFER_SIZE], Wrapping>, pub file_count: HashMap<PathBuf, usize>, pub file_count_state: ListState, pub file_monitors: Vec<JoinHandle<Result<()>>>, pub log_event_receiver: mpsc::UnboundedReceiver<(Level, String)>, pub terminal: Terminal<CrosstermBackend<Stdout>>, } impl UiLoopState { fn new( terminal: Terminal<CrosstermBackend<Stdout>>, log_event_receiver: mpsc::UnboundedReceiver<(Level, String)>, ) -> Self { Self { log_event_receiver, logs: Default::default(), file_count: Default::default(), file_count_state: Default::default(), file_monitors: Default::default(), terminal, } } } pub struct TerminalUi { pub task_events: mpsc::UnboundedSender<UiEvent>, task_event_receiver: mpsc::UnboundedReceiver<UiEvent>, ui_event_tx: mpsc::UnboundedSender<TerminalEvent>, ui_event_rx: mpsc::UnboundedReceiver<TerminalEvent>, } impl TerminalUi { pub fn init() -> Result<Self> { let (task_event_sender, task_event_receiver) = mpsc::unbounded_channel(); let (ui_event_tx, ui_event_rx) = mpsc::unbounded_channel(); Ok(Self { task_events: task_event_sender, task_event_receiver, ui_event_tx, ui_event_rx, }) } pub async fn run(self, timeout: Option<Duration>) -> Result<()> { enable_raw_mode()?; let mut stdout = io::stdout(); execute!(stdout, EnterAlternateScreen)?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; terminal.clear()?; let (log_event_sender, log_event_receiver) = mpsc::unbounded_channel(); let initial_state = UiLoopState::new(terminal, log_event_receiver); env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")) .format(move |_buf, record| { let _r = log_event_sender.send((record.level(), format!("{}", record.args()))); Ok(()) }) .init(); let tick_event_tx_clone = self.ui_event_tx.clone(); let tick_event_handle = tokio::spawn(async { Self::ticking(tick_event_tx_clone).await.context("ticking") }); let keyboard_ui_event_tx = self.ui_event_tx.clone(); let _keyboard_event_handle = Self::read_keyboard_events(keyboard_ui_event_tx); let task_event_receiver = self.task_event_receiver; let ui_event_tx = self.ui_event_tx.clone(); let external_event_handle = tokio::spawn(Self::read_commands(ui_event_tx, task_event_receiver)); let ui_loop = tokio::spawn(Self::ui_loop(initial_state, self.ui_event_rx)); let mut task_handles = vec![tick_event_handle, ui_loop, external_event_handle]; if let Some(timeout) = timeout { let ui_event_tx = self.ui_event_tx.clone(); let timeout_task = tokio::spawn(async move { time::delay_for(timeout).await; let _ = ui_event_tx.send(TerminalEvent::Quit); Ok(()) }); task_handles.push(timeout_task); } try_wait_all_join_handles(task_handles) .await .context("ui_loop")?; Ok(()) } async fn ticking(ui_event_tx: mpsc::UnboundedSender<TerminalEvent>) -> Result<()> { let mut interval = tokio::time::interval(TICK_RATE); loop { interval.tick().await; if let Err(_err) = ui_event_tx.send(TerminalEvent::Tick) { break; } } Ok(()) } fn read_keyboard_events( ui_event_tx: mpsc::UnboundedSender<TerminalEvent>, ) -> JoinHandle<Result<()>> { thread::spawn(move || loop { if event::poll(Duration::from_secs(1))? { let event = event::read()?; if let Err(_err) = ui_event_tx.send(TerminalEvent::Input(event)) { return Ok(()); } } }) } async fn read_commands( ui_event_tx: mpsc::UnboundedSender<TerminalEvent>, mut external_event_rx: mpsc::UnboundedReceiver<UiEvent>, ) -> Result<()> { while let Some(UiEvent::FileCount { dir, count }) = external_event_rx.recv().await { if ui_event_tx .send(TerminalEvent::FileCount { dir, count }) .is_err() { break; } } Ok(()) } fn take_available_logs<T>( receiver: &mut UnboundedReceiver<T>, size: usize, buffer: &mut ArrayDeque<[T; LOGS_BUFFER_SIZE], Wrapping>, ) { let mut count = 0; while let Ok(v) = receiver.try_recv() { count += 1; buffer.push_front(v); if count >= size { break; } } } async fn refresh_ui(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut logs = ui_state.logs; let mut file_count_state = ui_state.file_count_state; let file_count = ui_state.file_count; let mut log_event_receiver = ui_state.log_event_receiver; let mut terminal = ui_state.terminal; Self::take_available_logs(&mut log_event_receiver, 10, &mut logs); terminal.draw(|f| { let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Percentage(25), Constraint::Percentage(75)].as_ref()) .split(f.size()); let mut sorted_file_count = file_count.iter().collect::<Vec<_>>(); sorted_file_count.sort_by(|(p1, _), (p2, _)| p1.cmp(p2)); let files = sorted_file_count .iter() .map(|(path, count)| { ListItem::new(Spans::from(vec![ Span::raw( path.file_name() .map(|f| f.to_string_lossy()) .unwrap_or_default(), ), Span::raw(": "), Span::raw(format!("{}", count)), ])) }) .collect::<Vec<_>>(); let log_list = List::new(files) .block(Block::default().borders(Borders::ALL).title("files")) .highlight_style(Style::default().add_modifier(Modifier::BOLD)) .start_corner(Corner::TopLeft); f.render_stateful_widget(log_list, chunks[0], &mut file_count_state); let log_items = logs .iter() .map(|(level, log)| { let style = match level { Level::Debug => Style::default().fg(Color::Magenta), Level::Error => Style::default().fg(Color::Red), Level::Warn => Style::default().fg(Color::Yellow), Level::Info => Style::default().fg(Color::Blue), Level::Trace => Style::default(), }; ListItem::new(Spans::from(vec![ Span::styled(format!("{:<9}", level), style), Span::raw(" "), Span::raw(log), ])) }) .collect::<Vec<_>>(); let log_list = List::new(log_items) .block(Block::default().borders(Borders::ALL).title("Logs")) .start_corner(Corner::BottomLeft); f.render_widget(log_list, chunks[1]); })?; Ok(UiLoopState { logs, file_count_state, file_count, terminal, log_event_receiver, ..ui_state }) } async fn on_key_down(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut file_count_state = ui_state.file_count_state; let count = ui_state.file_count.len(); let i = file_count_state .selected() .map(|i| { if count == 0 { 0 } else { (i + count + 1) % count } }) .unwrap_or_default(); file_count_state.select(Some(i)); Ok(UiLoopState { file_count_state, ..ui_state }) } async fn on_key_up(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut file_count_state = ui_state.file_count_state; let count = ui_state.file_count.len(); let i = file_count_state .selected() .map(|i| { if count == 0 { 0 } else { (i + count - 1) % count } }) .unwrap_or_default(); file_count_state.select(Some(i)); Ok(UiLoopState { file_count_state, ..ui_state }) } async fn on_quit(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut terminal = ui_state.terminal; disable_raw_mode().map_err(|e| anyhow!("{:?}", e))?; execute!(terminal.backend_mut(), LeaveAlternateScreen).map_err(|e| anyhow!("{:?}", e))?; terminal.show_cursor()?; Err(UiLoopError::Exit) } async fn on_file_count( ui_state: UiLoopState, dir: PathBuf, count: usize, ) -> Result<UiLoopState, UiLoopError> { let mut file_count = ui_state.file_count; file_count.insert(dir, count); Ok(UiLoopState { file_count, ..ui_state }) } async fn ui_loop( initial_state: UiLoopState, ui_event_rx: mpsc::UnboundedReceiver<TerminalEvent>, ) -> Result<()> { let loop_result = ui_event_rx .map(Ok) .try_fold(initial_state, |ui_state, event| async { match event { TerminalEvent::Tick => Self::refresh_ui(ui_state).await, TerminalEvent::Input(Event::Key(k)) => match k.code { KeyCode::Char('q') => Self::on_quit(ui_state).await, KeyCode::Down => Self::on_key_down(ui_state).await, KeyCode::Up => Self::on_key_up(ui_state).await, _ => Ok(ui_state), }, TerminalEvent::FileCount { dir, count } => { Self::on_file_count(ui_state, dir, count).await } TerminalEvent::Quit => Self::on_quit(ui_state).await, _ => Ok(ui_state), } }) .await; match loop_result { Err(UiLoopError::Exit) | Ok(_) => Ok(()), Err(UiLoopError::Anyhow(e)) => Err(e), } } }
use crate::local::common::UiEvent; use anyhow::{Context, Result}; use crossterm::{ event::{self, Event, KeyCode}, execute, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use futures::{StreamExt, TryStreamExt}; use log::Level; use onefuzz::utils::try_wait_all_join_handles; use std::{ collections::HashMap, io::{self, Stdout, Write}, path::PathBuf, thread::{self, JoinHandle}, time::Duration, }; use tokio::{ sync::mpsc::{self, UnboundedReceiver}, time, }; use tui::{ backend::CrosstermBackend, layout::{Constraint, Corner, Direction, Layout}, style::{Color, Modifier, Style}, text::{Span, Spans}, widgets::{Block, Borders}, widgets::{List, ListItem, ListState}, Terminal, }; use arraydeque::{ArrayDeque, Wrapping}; #[derive(Debug, thiserror::Error)] enum UiLoopError { #[error("program exiting")] Exit, #[error("error")] Anyhow(anyhow::Error), } impl From<anyhow::Error> for UiLoopError { fn from(e: anyhow::Error) -> Self { Self::Anyhow(e) } } impl From<std::io::Error> for UiLoopError { fn from(e: std::io::Error) -> Self { Self::Anyhow(e.into()) } } const LOGS_BUFFER_SIZE: usize = 100; const TICK_RATE: Duration = Duration::from_millis(250); #[derive(Debug)] enum TerminalEvent { Input(Event), Tick, FileCount { dir: PathBuf, count: usize }, Quit, } struct UiLoopState { pub logs: ArrayDeque<[(Level, String); LOGS_BUFFER_SIZE], Wrapping>, pub file_count: HashMap<PathBuf, usize>, pub file_count_state: ListState, pub file_monitors: Vec<JoinHandle<Result<()>>>, pub log_event_receiver: mpsc::UnboundedReceiver<(Level, String)>, pub terminal: Terminal<CrosstermBackend<Stdout>>, } impl UiLoopState { fn new( terminal: Terminal<CrosstermBackend<Stdout>>, log_event_receiver: mpsc::UnboundedReceiver<(Level, String)>, ) -> Self { Self { log_event_receiver, logs: Default::default(), file_count: Default::default(), file_count_state: Default::default(), file_monitors: Default::default(), terminal, } } } pub struct TerminalUi { pub task_events: mpsc::UnboundedSender<UiEvent>, task_event_receiver: mpsc::UnboundedReceiver<UiEvent>, ui_event_tx: mpsc::UnboundedSender<TerminalEvent>, ui_event_rx: mpsc::UnboundedReceiver<TerminalEvent>, } impl TerminalUi { pub fn init() -> Result<Self> { let (task_event_sender, task_event_receiver) = mpsc::unbounded_channel(); let (ui_event_tx, ui_event_rx) = mpsc::unbounded_channel(); Ok(Self { task_events: task_event_sender, task_event_receiver, ui_event_tx, ui_event_rx, }) }
async fn ticking(ui_event_tx: mpsc::UnboundedSender<TerminalEvent>) -> Result<()> { let mut interval = tokio::time::interval(TICK_RATE); loop { interval.tick().await; if let Err(_err) = ui_event_tx.send(TerminalEvent::Tick) { break; } } Ok(()) } fn read_keyboard_events( ui_event_tx: mpsc::UnboundedSender<TerminalEvent>, ) -> JoinHandle<Result<()>> { thread::spawn(move || loop { if event::poll(Duration::from_secs(1))? { let event = event::read()?; if let Err(_err) = ui_event_tx.send(TerminalEvent::Input(event)) { return Ok(()); } } }) } async fn read_commands( ui_event_tx: mpsc::UnboundedSender<TerminalEvent>, mut external_event_rx: mpsc::UnboundedReceiver<UiEvent>, ) -> Result<()> { while let Some(UiEvent::FileCount { dir, count }) = external_event_rx.recv().await { if ui_event_tx .send(TerminalEvent::FileCount { dir, count }) .is_err() { break; } } Ok(()) } fn take_available_logs<T>( receiver: &mut UnboundedReceiver<T>, size: usize, buffer: &mut ArrayDeque<[T; LOGS_BUFFER_SIZE], Wrapping>, ) { let mut count = 0; while let Ok(v) = receiver.try_recv() { count += 1; buffer.push_front(v); if count >= size { break; } } } async fn refresh_ui(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut logs = ui_state.logs; let mut file_count_state = ui_state.file_count_state; let file_count = ui_state.file_count; let mut log_event_receiver = ui_state.log_event_receiver; let mut terminal = ui_state.terminal; Self::take_available_logs(&mut log_event_receiver, 10, &mut logs); terminal.draw(|f| { let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Percentage(25), Constraint::Percentage(75)].as_ref()) .split(f.size()); let mut sorted_file_count = file_count.iter().collect::<Vec<_>>(); sorted_file_count.sort_by(|(p1, _), (p2, _)| p1.cmp(p2)); let files = sorted_file_count .iter() .map(|(path, count)| { ListItem::new(Spans::from(vec![ Span::raw( path.file_name() .map(|f| f.to_string_lossy()) .unwrap_or_default(), ), Span::raw(": "), Span::raw(format!("{}", count)), ])) }) .collect::<Vec<_>>(); let log_list = List::new(files) .block(Block::default().borders(Borders::ALL).title("files")) .highlight_style(Style::default().add_modifier(Modifier::BOLD)) .start_corner(Corner::TopLeft); f.render_stateful_widget(log_list, chunks[0], &mut file_count_state); let log_items = logs .iter() .map(|(level, log)| { let style = match level { Level::Debug => Style::default().fg(Color::Magenta), Level::Error => Style::default().fg(Color::Red), Level::Warn => Style::default().fg(Color::Yellow), Level::Info => Style::default().fg(Color::Blue), Level::Trace => Style::default(), }; ListItem::new(Spans::from(vec![ Span::styled(format!("{:<9}", level), style), Span::raw(" "), Span::raw(log), ])) }) .collect::<Vec<_>>(); let log_list = List::new(log_items) .block(Block::default().borders(Borders::ALL).title("Logs")) .start_corner(Corner::BottomLeft); f.render_widget(log_list, chunks[1]); })?; Ok(UiLoopState { logs, file_count_state, file_count, terminal, log_event_receiver, ..ui_state }) } async fn on_key_down(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut file_count_state = ui_state.file_count_state; let count = ui_state.file_count.len(); let i = file_count_state .selected() .map(|i| { if count == 0 { 0 } else { (i + count + 1) % count } }) .unwrap_or_default(); file_count_state.select(Some(i)); Ok(UiLoopState { file_count_state, ..ui_state }) } async fn on_key_up(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut file_count_state = ui_state.file_count_state; let count = ui_state.file_count.len(); let i = file_count_state .selected() .map(|i| { if count == 0 { 0 } else { (i + count - 1) % count } }) .unwrap_or_default(); file_count_state.select(Some(i)); Ok(UiLoopState { file_count_state, ..ui_state }) } async fn on_quit(ui_state: UiLoopState) -> Result<UiLoopState, UiLoopError> { let mut terminal = ui_state.terminal; disable_raw_mode().map_err(|e| anyhow!("{:?}", e))?; execute!(terminal.backend_mut(), LeaveAlternateScreen).map_err(|e| anyhow!("{:?}", e))?; terminal.show_cursor()?; Err(UiLoopError::Exit) } async fn on_file_count( ui_state: UiLoopState, dir: PathBuf, count: usize, ) -> Result<UiLoopState, UiLoopError> { let mut file_count = ui_state.file_count; file_count.insert(dir, count); Ok(UiLoopState { file_count, ..ui_state }) } async fn ui_loop( initial_state: UiLoopState, ui_event_rx: mpsc::UnboundedReceiver<TerminalEvent>, ) -> Result<()> { let loop_result = ui_event_rx .map(Ok) .try_fold(initial_state, |ui_state, event| async { match event { TerminalEvent::Tick => Self::refresh_ui(ui_state).await, TerminalEvent::Input(Event::Key(k)) => match k.code { KeyCode::Char('q') => Self::on_quit(ui_state).await, KeyCode::Down => Self::on_key_down(ui_state).await, KeyCode::Up => Self::on_key_up(ui_state).await, _ => Ok(ui_state), }, TerminalEvent::FileCount { dir, count } => { Self::on_file_count(ui_state, dir, count).await } TerminalEvent::Quit => Self::on_quit(ui_state).await, _ => Ok(ui_state), } }) .await; match loop_result { Err(UiLoopError::Exit) | Ok(_) => Ok(()), Err(UiLoopError::Anyhow(e)) => Err(e), } } }
pub async fn run(self, timeout: Option<Duration>) -> Result<()> { enable_raw_mode()?; let mut stdout = io::stdout(); execute!(stdout, EnterAlternateScreen)?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; terminal.clear()?; let (log_event_sender, log_event_receiver) = mpsc::unbounded_channel(); let initial_state = UiLoopState::new(terminal, log_event_receiver); env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")) .format(move |_buf, record| { let _r = log_event_sender.send((record.level(), format!("{}", record.args()))); Ok(()) }) .init(); let tick_event_tx_clone = self.ui_event_tx.clone(); let tick_event_handle = tokio::spawn(async { Self::ticking(tick_event_tx_clone).await.context("ticking") }); let keyboard_ui_event_tx = self.ui_event_tx.clone(); let _keyboard_event_handle = Self::read_keyboard_events(keyboard_ui_event_tx); let task_event_receiver = self.task_event_receiver; let ui_event_tx = self.ui_event_tx.clone(); let external_event_handle = tokio::spawn(Self::read_commands(ui_event_tx, task_event_receiver)); let ui_loop = tokio::spawn(Self::ui_loop(initial_state, self.ui_event_rx)); let mut task_handles = vec![tick_event_handle, ui_loop, external_event_handle]; if let Some(timeout) = timeout { let ui_event_tx = self.ui_event_tx.clone(); let timeout_task = tokio::spawn(async move { time::delay_for(timeout).await; let _ = ui_event_tx.send(TerminalEvent::Quit); Ok(()) }); task_handles.push(timeout_task); } try_wait_all_join_handles(task_handles) .await .context("ui_loop")?; Ok(()) }
function_block-full_function
[ { "content": "pub fn digest_file_blocking(file: impl AsRef<Path>) -> Result<String> {\n\n let file = file.as_ref();\n\n let data = std::fs::read(file)\n\n .with_context(|| format!(\"unable to read file to generate digest: {}\", file.display()))?;\n\n Ok(hex::encode(Sha256::digest(&data)))\n\n}\n...
Rust
tests/auth_test.rs
andygrove/rust-etcd
c1e51b3dff285ab62fd4424b3d4607b33721f774
use etcd::auth::{self, AuthChange, NewUser, Role, RoleUpdate, UserUpdate}; use etcd::{BasicAuth, Client}; use futures::future::Future; use tokio::runtime::Runtime; #[test] fn auth() { let client = Client::new(&["http://etcd:2379"], None).unwrap(); let client_2 = client.clone(); let client_3 = client.clone(); let basic_auth = BasicAuth { username: "root".into(), password: "secret".into(), }; let authed_client = Client::new(&["http://etcd:2379"], Some(basic_auth)).unwrap(); let authed_client_2 = authed_client.clone(); let authed_client_3 = authed_client.clone(); let authed_client_4 = authed_client.clone(); let authed_client_5 = authed_client.clone(); let authed_client_6 = authed_client.clone(); let authed_client_7 = authed_client.clone(); let authed_client_8 = authed_client.clone(); let authed_client_9 = authed_client.clone(); let root_user = NewUser::new("root", "secret"); let work: Box<dyn Future<Item = (), Error = ()> + Send> = Box::new( auth::status(&client) .then(move |res| { let response = res.unwrap(); assert_eq!(response.data, false); auth::create_user(&client_2, root_user) }) .then(move |res| { let response = res.unwrap(); assert_eq!(response.data.name(), "root"); auth::enable(&client_3) }) .then(move |res| { let response = res.unwrap(); assert_eq!(response.data, AuthChange::Changed); let mut update_guest = RoleUpdate::new("guest"); update_guest.revoke_kv_write_permission("/*"); auth::update_role(&authed_client, update_guest) }) .then(move |res| { res.unwrap(); let mut rkt_role = Role::new("rkt"); rkt_role.grant_kv_read_permission("/rkt/*"); rkt_role.grant_kv_write_permission("/rkt/*"); auth::create_role(&authed_client_2, rkt_role) }) .then(move |res| { res.unwrap(); let mut rkt_user = NewUser::new("rkt", "secret"); rkt_user.add_role("rkt"); auth::create_user(&authed_client_3, rkt_user) }) .then(move |res| { let response = res.unwrap(); let rkt_user = response.data; assert_eq!(rkt_user.name(), "rkt"); let role_name = &rkt_user.role_names()[0]; assert_eq!(role_name, "rkt"); let mut update_rkt_user = UserUpdate::new("rkt"); update_rkt_user.update_password("secret2"); update_rkt_user.grant_role("root"); auth::update_user(&authed_client_4, update_rkt_user) }) .then(move |res| { res.unwrap(); auth::get_role(&authed_client_5, "rkt") }) .then(move |res| { let response = res.unwrap(); let role = response.data; assert!(role.kv_read_permissions().contains(&"/rkt/*".to_owned())); assert!(role.kv_write_permissions().contains(&"/rkt/*".to_owned())); auth::delete_user(&authed_client_6, "rkt") }) .then(move |res| { res.unwrap(); auth::delete_role(&authed_client_7, "rkt") }) .then(move |res| { res.unwrap(); let mut update_guest = RoleUpdate::new("guest"); update_guest.grant_kv_write_permission("/*"); auth::update_role(&authed_client_8, update_guest) }) .then(move |res| { res.unwrap(); auth::disable(&authed_client_9) }) .then(|res| { let response = res.unwrap(); assert_eq!(response.data, AuthChange::Changed); Ok(()) }), ); let _ = Runtime::new() .expect("failed to create Tokio runtime") .block_on(work); }
use etcd::auth::{self, AuthChange, NewUser, Role, RoleUpdate, UserUpdate}; use etcd::{BasicAuth, Client}; use futures::future::Future; use tokio::runtime::Runtime; #[test] fn auth() { let client = Client::new(&["http://etcd:2379"], None).unwrap(); let client_2 = client.clone(); let client_3 = client.clone(); let basic_auth = BasicAuth { username: "root".into(), password: "secret".into(), }; let authed_client = Client::new(&["http://etcd:2379"], Some(basic_auth)).unwrap(); let authed_client_2 = authed_client.clone(); let authed_client_3 = authed_client.clone(); let authed_client_4 = authed_client.clone(); let authed_client_5 = authed_client.clone(); let authed_client_6 = authed_client.clone(); let authed_client_7 = authed_client.clone(); let authed_client_8 = authed_client.clone(); let authed_client_9 = authed_client.clone(); let root_user = NewUser::new("root", "secret"); let work: Box<dyn Future<Item = (), Error = ()> + Send> = Box::new( auth::status(&client) .then(move |res| { let response = res.unwrap(); assert_eq!(response.data, false); auth::create_user(&client_2, root_user) }) .then(move |res| { let response = res.unwrap(); assert_eq!(response.data.name(), "root"); auth::enable(&client_3) }) .then(move |res| { let response = res.unwrap(); assert_eq!(response.data, AuthChange::Changed); let mut update_guest = RoleUpdate::new("guest"); update_guest.revoke_kv_write_permission("/*"); auth::update_role(&authed_client, update_guest) }) .then(move |res| { res.unwrap(); let mut rkt_role = Role::new("rkt"); rkt_role.grant_kv_read_permission("/rkt/*"); rkt_role.grant_kv_write_permission("/rkt/*"); auth::create_role(&authed_client_2, rkt_role) }) .then(move |res| { res.unwrap(); let mut rkt_user = NewUser::new("rkt", "secret"); rkt_user.add_role("rkt"); auth::create_user(&authed_client_3, rkt_user) }) .then(move |res| { let response = res.unwrap(); let rkt_user = response.data; assert_eq!(rkt_user.name(), "rkt");
let role_name = &rkt_user.role_names()[0]; assert_eq!(role_name, "rkt"); let mut update_rkt_user = UserUpdate::new("rkt"); update_rkt_user.update_password("secret2"); update_rkt_user.grant_role("root"); auth::update_user(&authed_client_4, update_rkt_user) }) .then(move |res| { res.unwrap(); auth::get_role(&authed_client_5, "rkt") }) .then(move |res| { let response = res.unwrap(); let role = response.data; assert!(role.kv_read_permissions().contains(&"/rkt/*".to_owned())); assert!(role.kv_write_permissions().contains(&"/rkt/*".to_owned())); auth::delete_user(&authed_client_6, "rkt") }) .then(move |res| { res.unwrap(); auth::delete_role(&authed_client_7, "rkt") }) .then(move |res| { res.unwrap(); let mut update_guest = RoleUpdate::new("guest"); update_guest.grant_kv_write_permission("/*"); auth::update_role(&authed_client_8, update_guest) }) .then(move |res| { res.unwrap(); auth::disable(&authed_client_9) }) .then(|res| { let response = res.unwrap(); assert_eq!(response.data, AuthChange::Changed); Ok(()) }), ); let _ = Runtime::new() .expect("failed to create Tokio runtime") .block_on(work); }
function_block-function_prefix_line
[]
Rust
src/bulk_string/mod.rs
WatchDG/rust-resp-protocol
b36689915d7fd3456a80165297a14d9e1a1257b6
use crate::RespError; use bytes::{BufMut, Bytes, BytesMut}; pub const EMPTY_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$0\r\n\r\n")); pub const NULL_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$-1\r\n")); #[derive(Debug, Clone, PartialEq)] pub struct BulkString(Bytes); impl BulkString { pub fn new(input: &[u8]) -> Self { let length = input.len(); if length == 0 { return EMPTY_BULK_STRING; } let length_string = length.to_string(); let mut bytes = BytesMut::with_capacity(input.len() + length_string.len() + 5); bytes.put_u8(0x24); bytes.put_slice(length_string.as_bytes()); bytes.put_u8(0x0d); bytes.put_u8(0x0a); bytes.put_slice(input); bytes.put_u8(0x0d); bytes.put_u8(0x0a); Self::from_bytes(bytes.freeze()) } #[inline] pub fn is_empty(&self) -> bool { self == EMPTY_BULK_STRING } #[inline] pub fn is_null(&self) -> bool { self == NULL_BULK_STRING } #[inline] pub fn bytes(&self) -> Bytes { self.0.clone() } #[inline] pub fn len(&self) -> usize { self.0.len() } #[inline] pub fn from_bytes(input: Bytes) -> Self { Self(input) } #[inline] pub fn from_slice(input: &[u8]) -> Self { let bytes = Bytes::copy_from_slice(input); Self::from_bytes(bytes) } #[inline] pub unsafe fn from_raw(ptr: *mut u8, length: usize) -> Self { let vector = Vec::from_raw_parts(ptr, length, length); let bytes = Bytes::from(vector); Self::from_bytes(bytes) } pub fn while_valid(input: &[u8], start: &mut usize, end: &usize) -> Result<(), RespError> { let mut index = *start; if index + 4 >= *end { return Err(RespError::InvalidValue); } if input[index] != 0x24 { return Err(RespError::InvalidFirstChar); } index += 1; if input[index] == 0x2d { if input[index + 1] != 0x31 || input[index + 2] != 0x0d || input[index + 3] != 0x0a { return Err(RespError::InvalidNullValue); } *start = index + 4; return Ok(()); } if input[index] == 0x30 && input[index + 1] >= 0x30 && input[index + 1] <= 0x39 { return Err(RespError::InvalidLength); } while index < *end && input[index] >= 0x30 && input[index] <= 0x39 { index += 1; } if index + 1 >= *end || input[index] != 0x0d || input[index + 1] != 0x0a { return Err(RespError::InvalidLengthSeparator); } let length = unsafe { String::from_utf8_unchecked(input[*start + 1..index].to_vec()) .parse::<usize>() .unwrap() }; index += 2; let value_start_index = index; while index < *end && index - value_start_index <= length && input[index] != 0x0d && input[index] != 0x0a { index += 1; } if length != index - value_start_index { return Err(RespError::LengthsNotMatch); } if index + 1 >= *end || input[index] != 0x0d || input[index + 1] != 0x0a { return Err(RespError::InvalidTerminate); } *start = index + 2; Ok(()) } pub fn parse(input: &[u8], start: &mut usize, end: &usize) -> Result<Self, RespError> { let mut index = *start; Self::while_valid(input, &mut index, end)?; let value = Self::from_slice(&input[*start..index]); *start = index; Ok(value) } } impl<'a> PartialEq<BulkString> for &'a BulkString { fn eq(&self, other: &BulkString) -> bool { self.0 == other.bytes() } fn ne(&self, other: &BulkString) -> bool { self.0 != other.bytes() } } #[cfg(test)] mod tests_bulk_string { use crate::{BulkString, EMPTY_BULK_STRING, NULL_BULK_STRING}; use bytes::Bytes; #[test] fn test_new() { let bulk_string: BulkString = BulkString::new(b"foobar"); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$6\r\nfoobar\r\n")); } #[test] fn test_new_empty() { let bulk_string: BulkString = BulkString::new(b""); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$0\r\n\r\n")); } #[test] fn test_from_bytes() { let bulk_string: BulkString = BulkString::from_bytes(Bytes::from_static(b"$6\r\nfoobar\r\n")); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$6\r\nfoobar\r\n")); } #[test] fn test_from_slice() { let bulk_string: BulkString = BulkString::from_slice(Vec::from("$6\r\nfoobar\r\n").as_slice()); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$6\r\nfoobar\r\n")); } #[test] fn test_is_empty() { assert_eq!(EMPTY_BULK_STRING.is_empty(), true) } #[test] fn test_is_null() { assert_eq!(NULL_BULK_STRING.is_null(), true) } #[test] fn test_parse() { let string = "$6\r\nfoobar\r\n"; let mut cursor = 0; assert_eq!( BulkString::parse(string.as_bytes(), &mut cursor, &string.len()).unwrap(), BulkString::new(b"foobar") ); assert_eq!(cursor, 12); } #[test] fn test_parse_empty() { let string = "$0\r\n\r\n"; let mut cursor = 0; assert_eq!( BulkString::parse(string.as_bytes(), &mut cursor, &string.len()).unwrap(), EMPTY_BULK_STRING ); assert_eq!(cursor, 6); } #[test] fn test_parse_null() { let string = "$-1\r\n"; let mut cursor = 0; assert_eq!( BulkString::parse(string.as_bytes(), &mut cursor, &string.len()).unwrap(), NULL_BULK_STRING ); assert_eq!(cursor, 5); } }
use crate::RespError; use bytes::{BufMut, Bytes, BytesMut}; pub const EMPTY_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$0\r\n\r\n")); pub const NULL_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$-1\r\n")); #[derive(Debug, Clone, PartialEq)] pub struct BulkString(Bytes); impl BulkString { pub fn new(input: &[u8]) -> Self { let length = input.len(); if length == 0 { return EMPTY_BULK_STRING; } let length_string = length.to_string(); let mut bytes = BytesMut::with_capacity(input.len() + length_string.len() + 5); bytes.put_u8(0x24); bytes.put_slice(length_string.as_bytes()); bytes.put_u8(0x0d); bytes.put_u8(0x0a); bytes.put_slice(input); bytes.put_u8(0x0d); bytes.put_u8(0x0a); Self::from_bytes(bytes.freeze()) } #[inline] pub fn is_empty(&self) -> bool { self == EMPTY_BULK_STRING } #[inline] pub fn is_null(&self) -> bool { self == NULL_BULK_STRING } #[inline] pub fn bytes(&self) -> Bytes { self.0.clone() } #[inline] pub fn len(&self) -> usize { self.0.len() } #[inline] pub fn from_bytes(input: Bytes) -> Self { Self(input) } #[inline] pub fn from_slice(input: &[u8]) -> Self { let bytes = Bytes::copy_from_slice(input); Self::from_bytes(bytes) } #[inline] pub unsafe fn from_raw(ptr: *mut u8, length: usize) -> Self { let vector = Vec::from_raw_parts(ptr, length, length); let bytes = Bytes::from(vector); Self::from_bytes(bytes) } pub fn while_valid(input: &[u8], start: &mut usize, end: &usize) -> Result<(), RespError> { let mut index = *start; if index + 4 >= *end { return Err(RespError::InvalidValue); } if input[index] != 0x24 { return Err(RespError::InvalidFirstChar); } index += 1; if input[index] == 0x2d { if input[index + 1] != 0x31 || input[index + 2] != 0x0d || input[index + 3] != 0x0a { return Err(RespError::InvalidNullValue); } *start = index + 4; return Ok(()); } if input[index] == 0x30 && input[index + 1] >= 0x30 && input[index + 1] <= 0x39 { return Err(RespError::InvalidLength); } while index < *end && input[index] >= 0x30 && input[index] <= 0x39 { index += 1; } if index + 1 >= *end || input[index] != 0x0d || input[index + 1] != 0x0a { return Err(RespError::InvalidLengthSeparator); } let length = unsafe { String::from_utf8_unchecked(input[*start + 1..index].to_vec()) .parse::<usize>() .unwrap() }; index += 2; let value_start_index = index; while index < *end && index - value_start_index <= length && input[index] != 0x0d && input[index] != 0x0a { index += 1; } if length != index - value_start_index { return Err(RespError::LengthsNotMatch); } if index + 1 >= *end || input[index] != 0x0d || input[index + 1] != 0x0a { return Err(RespError::InvalidTerminate); } *start = index + 2; Ok(()) }
} impl<'a> PartialEq<BulkString> for &'a BulkString { fn eq(&self, other: &BulkString) -> bool { self.0 == other.bytes() } fn ne(&self, other: &BulkString) -> bool { self.0 != other.bytes() } } #[cfg(test)] mod tests_bulk_string { use crate::{BulkString, EMPTY_BULK_STRING, NULL_BULK_STRING}; use bytes::Bytes; #[test] fn test_new() { let bulk_string: BulkString = BulkString::new(b"foobar"); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$6\r\nfoobar\r\n")); } #[test] fn test_new_empty() { let bulk_string: BulkString = BulkString::new(b""); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$0\r\n\r\n")); } #[test] fn test_from_bytes() { let bulk_string: BulkString = BulkString::from_bytes(Bytes::from_static(b"$6\r\nfoobar\r\n")); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$6\r\nfoobar\r\n")); } #[test] fn test_from_slice() { let bulk_string: BulkString = BulkString::from_slice(Vec::from("$6\r\nfoobar\r\n").as_slice()); assert_eq!(bulk_string.bytes(), Bytes::from_static(b"$6\r\nfoobar\r\n")); } #[test] fn test_is_empty() { assert_eq!(EMPTY_BULK_STRING.is_empty(), true) } #[test] fn test_is_null() { assert_eq!(NULL_BULK_STRING.is_null(), true) } #[test] fn test_parse() { let string = "$6\r\nfoobar\r\n"; let mut cursor = 0; assert_eq!( BulkString::parse(string.as_bytes(), &mut cursor, &string.len()).unwrap(), BulkString::new(b"foobar") ); assert_eq!(cursor, 12); } #[test] fn test_parse_empty() { let string = "$0\r\n\r\n"; let mut cursor = 0; assert_eq!( BulkString::parse(string.as_bytes(), &mut cursor, &string.len()).unwrap(), EMPTY_BULK_STRING ); assert_eq!(cursor, 6); } #[test] fn test_parse_null() { let string = "$-1\r\n"; let mut cursor = 0; assert_eq!( BulkString::parse(string.as_bytes(), &mut cursor, &string.len()).unwrap(), NULL_BULK_STRING ); assert_eq!(cursor, 5); } }
pub fn parse(input: &[u8], start: &mut usize, end: &usize) -> Result<Self, RespError> { let mut index = *start; Self::while_valid(input, &mut index, end)?; let value = Self::from_slice(&input[*start..index]); *start = index; Ok(value) }
function_block-full_function
[ { "content": " #[inline]\n\n pub fn from_bytes(input: Bytes) -> Self {\n\n Self(input)\n\n }\n\n\n\n #[inline]\n\n pub fn from_slice(input: &[u8]) -> Self {\n\n let bytes = Bytes::copy_from_slice(input);\n\n Self::from_bytes(bytes)\n\n }\n\n\n\n #[inline]\n\n pub uns...
Rust
src/lib.rs
niuhuan/pixirust
8eeeebaf4e9cb9e7351a6f625c247375d8396644
pub mod entities; mod test; mod utils; pub use anyhow::Error; pub use anyhow::Result; pub use entities::*; use serde_json::json; use utils::*; const APP_SERVER: &'static str = "app-api.pixiv.net"; const APP_SERVER_IP: &'static str = "210.140.131.199"; const OAUTH_SERVER: &'static str = "oauth.secure.pixiv.net"; const OAUTH_SERVER_IP: &'static str = "210.140.131.199"; const IMG_SERVER: &'static str = "i.pximg.net"; const IMG_SERVER_IP: &'static str = "s.pximg.net"; struct Server { pub server: &'static str, pub ip: &'static str, } const APP: Server = Server { server: APP_SERVER, ip: APP_SERVER_IP, }; const OAUTH: Server = Server { server: OAUTH_SERVER, ip: OAUTH_SERVER_IP, }; const IMG: Server = Server { server: IMG_SERVER, ip: IMG_SERVER_IP, }; const SALT: &'static str = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"; const CLIENT_ID: &'static str = "MOBrBDS8blbauoSck0ZfDbtuzpyT"; const CLIENT_SECRET: &'static str = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj"; pub struct Client { pub access_token: String, agent: reqwest::Client, agent_free: bool, } impl Client { pub fn new() -> Self { Self { agent: reqwest::ClientBuilder::new().build().unwrap(), agent_free: false, access_token: String::default(), } } pub fn new_agent_free() -> Self { Self { agent: reqwest::ClientBuilder::new() .danger_accept_invalid_certs(true) .build() .unwrap(), agent_free: true, access_token: String::default(), } } fn base64_pixiv<T: AsRef<[u8]>>(&self, src: T) -> String { base64::encode(src) .replace("=", "") .replace("+", "-") .replace("/", "_") } fn iso_time(&self) -> String { chrono::Local::now() .format("%Y-%m-%dT%H:%M:%S%Z") .to_string() } fn code_verify(&self) -> String { self.base64_pixiv(uuid::Uuid::new_v4().to_string().replace("-", "")) } fn code_challenge(&self, code: &String) -> String { self.base64_pixiv(sha256(code.clone())) } pub fn create_login_url(&self) -> LoginUrl { let verify = self.code_verify(); let url = format!("https://app-api.pixiv.net/web/v1/login?code_challenge={}&code_challenge_method=S256&client=pixiv-android",self.code_challenge(&verify)); LoginUrl { verify, url } } pub fn create_register_url(&self) -> LoginUrl { let verify = self.code_verify(); let url = format!("https://app-api.pixiv.net/web/v1/provisional-accounts/create?code_challenge={}&code_challenge_method=S256&client=pixiv-android",self.code_challenge(&verify)); LoginUrl { verify, url } } async fn load_token(&self, body: serde_json::Value) -> Result<Token> { let req = match self.agent_free { true => self .agent .request( reqwest::Method::POST, format!("https://{}/auth/token", OAUTH.ip).as_str(), ) .header("Host", OAUTH.server), false => self.agent.request( reqwest::Method::POST, format!("https://{}/auth/token", OAUTH.server).as_str(), ), }; let rsp = req.form(&body).send().await; match rsp { Ok(resp) => { let status = resp.status(); match status.as_u16() { 200 => Ok(serde_json::from_str(resp.text().await?.as_str())?), _ => { let err: LoginErrorResponse = serde_json::from_str(resp.text().await?.as_str())?; Err(Error::msg(err.errors.system.message)) } } } Err(err) => Err(Error::msg(err)), } } pub async fn load_token_by_code(&self, code: String, verify: String) -> Result<Token> { self.load_token(json!({ "code": code, "code_verifier": verify, "redirect_uri": "https://app-api.pixiv.net/web/v1/users/auth/pixiv/callback", "grant_type": "authorization_code", "include_policy": "true", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, })) .await } pub async fn refresh_token(&self, refresh_token: &String) -> Result<Token> { self.load_token(json!({ "refresh_token": refresh_token, "grant_type": "refresh_token", "include_policy": "true", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, })) .await } fn sign_request(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder { let time = self.iso_time(); request .header("x-client-time", &time.clone()) .header("x-client-hash", hex::encode(format!("{}{}", time, SALT))) .header("accept-language", "zh-CN") .header( "User-Agent", "PixivAndroidApp/5.0.234 (Android 10.0; Pixel C)", ) .header("App-OS-Version", "Android 10.0") .header("Referer", "https://app-api.pixiv.net/") .bearer_auth(&self.access_token) } pub async fn get_from_pixiv_raw(&self, url: String) -> Result<String> { let req = match self.agent_free { true => { if url.starts_with(format!("https://{}", APP.server).as_str()) { self.agent .get(url.replacen(APP.server, APP.ip.clone(), 1)) .header("Host", APP.server) } else { self.agent.get(url) } } false => self.agent.get(url), }; let req = self.sign_request(req); let rsp = req.send().await?; match &rsp.status().as_u16() { 200 => Ok(rsp.text().await?), _ => { let ae: AppError = serde_json::from_str(rsp.text().await?.as_str())?; Err(Error::msg(ae.error.message)) } } } async fn get_from_pixiv<T: for<'de> serde::Deserialize<'de>>(&self, url: String) -> Result<T> { let text = self.get_from_pixiv_raw(url).await?; Ok(serde_json::from_str(text.as_str())?) } pub fn illust_recommended_first_url(&self) -> String { format!( "https://{}/v1/illust/recommended?filter=for_ios&include_ranking_label=true", APP.server ) } pub fn illust_rank_first_url(&self, mode: String, date: String) -> String { format!( "https://{}/v1/illust/ranking?filter=for_android&mode={}&date={}", APP.server, mode, date, ) } pub async fn illust_from_url(&self, url: String) -> Result<IllustResponse> { self.get_from_pixiv(url).await } pub fn illust_trending_tags_url(&self) -> String { format!( "https://{}/v1/trending-tags/illust?filter=for_android", APP.server, ) } pub async fn illust_trending_tags(&self) -> Result<IllustTrendingTags> { self.get_from_pixiv(self.illust_trending_tags_url()).await } pub fn illust_search_first_url(&self, word: String, mode: String) -> String { format!( "https://{}/v1/search/illust?word={}&search_target={}&filter=for_ios", APP.server, urlencoding::encode(word.as_str()), mode, ) } pub fn illust_rank_first_utl(&self, mode: String, date: String) -> String { format!( "https://{}/v1/illust/ranking?mode={}&date={}&filter={}", APP.server, mode, date, "for_android", ) } pub async fn load_image_data(&self, url: String) -> Result<bytes::Bytes> { let req = match self.agent_free { true => { if url.starts_with(format!("https://{}", IMG.server).as_str()) { self.agent .get(url.replacen(IMG.server, IMG.ip.clone(), 1)) .header("Host", IMG.server) } else { self.agent.get(url) } } false => self.agent.get(url), }; let req = self.sign_request(req); let rsp = req.send().await?; let status = rsp.status(); match status.as_u16() { 200 => Ok(rsp.bytes().await?), _ => Err(Error::msg(rsp.text().await?)), } } }
pub mod entities; mod test; mod utils; pub use anyhow::Error; pub use anyhow::Result; pub use entities::*; use serde_json::json; use utils::*; const APP_SERVER: &'static str = "app-api.pixiv.net"; const APP_SERVER_IP: &'static str = "210.140.131.199"; const OAUTH_SERVER: &'static str = "oauth.secure.pixiv.net"; const OAUTH_SERVER_IP: &'static str = "210.140.131.199"; const IMG_SERVER: &'static str = "i.pximg.net"; const IMG_SERVER_IP: &'static str = "s.pximg.net"; struct Server { pub server: &'static str, pub ip: &'static str, } const APP: Server = Server { server: APP_SERVER, ip: APP_SERVER_IP, }; const OAUTH: Server = Server { server: OAUTH_SERVER, ip: OAUTH_SERVER_IP, }; const IMG: Server = Server { server: IMG_SERVER, ip: IMG_SERVER_IP, }; const SALT: &'static str = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"; const CLIENT_ID: &'static str = "MOBrBDS8blbauoSck0ZfDbtuzpyT"; const CLIENT_SECRET: &'static str = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj"; pub struct Client { pub access_token: String, agent: reqwest::Client, agent_free: bool, } impl Client { pub fn new() -> Self { Self { agent: reqwest::ClientBuilder::new().build().unwrap(), agent_free: false, access_token: String::default(), } } pub fn new_agent_free() -> Self { Self { agent: reqwest::ClientBuilder::new() .danger_accept_invalid_certs(true) .build() .unwrap(), agent_free: true, access_token: String::default(), } } fn base64_pixiv<T: AsRef<[u8]>>(&self, src: T) -> String { base64::encode(src) .replace("=", "") .replace("+", "-") .replace("/", "_") } fn iso_time(&self) -> String { chrono::Local::now() .format("%Y-%m-%dT%H:%M:%S%Z") .to_string() } fn code_verify(&self) -> String { self.base64_pixiv(uuid::Uuid::new_v4().to_string().replace("-", "")) } fn code_challenge(&self, code: &String) -> String { self.base64_pixiv(sha256(code.clone())) } pub fn create_login_url(&self) -> LoginUrl { let verify = self.code_verify(); let url = format!("https://app-api.pixiv.net/web/v1/login?code_challenge={}&code_challenge_method=S256&client=pixiv-android",self.code_challenge(&verify)); LoginUrl { verify, url } } pub fn create_register_url(&self) -> LoginUrl { let verify = self.code_verify(); let url = format!("https://app-api.pixiv.net/web/v1/provisional-accounts/create?code_challenge={}&code_challenge_method=S256&client=pixiv-android",self.code_challenge(&verify)); LoginUrl { verify, url } } async fn load_token(&self, body: serde_json::Value) -> Result<Token> { let req = match self.agent_free { true => self .agent .request( reqwest::Method::POST, format!("https://{}/auth/token", OAUTH.ip).as_str(), ) .header("Host", OAUTH.server), false => self.agent.request( reqwest::Method::POST, format!("https://{}/auth/token", OAUTH.server).as_str(), ), }; let rsp = req.form(&body).send().await; match rsp { Ok(resp) => { let status = resp.status(); match status.as_u16() { 200 => Ok(s
/{}", APP.server).as_str()) { self.agent .get(url.replacen(APP.server, APP.ip.clone(), 1)) .header("Host", APP.server) } else { self.agent.get(url) } } false => self.agent.get(url), }; let req = self.sign_request(req); let rsp = req.send().await?; match &rsp.status().as_u16() { 200 => Ok(rsp.text().await?), _ => { let ae: AppError = serde_json::from_str(rsp.text().await?.as_str())?; Err(Error::msg(ae.error.message)) } } } async fn get_from_pixiv<T: for<'de> serde::Deserialize<'de>>(&self, url: String) -> Result<T> { let text = self.get_from_pixiv_raw(url).await?; Ok(serde_json::from_str(text.as_str())?) } pub fn illust_recommended_first_url(&self) -> String { format!( "https://{}/v1/illust/recommended?filter=for_ios&include_ranking_label=true", APP.server ) } pub fn illust_rank_first_url(&self, mode: String, date: String) -> String { format!( "https://{}/v1/illust/ranking?filter=for_android&mode={}&date={}", APP.server, mode, date, ) } pub async fn illust_from_url(&self, url: String) -> Result<IllustResponse> { self.get_from_pixiv(url).await } pub fn illust_trending_tags_url(&self) -> String { format!( "https://{}/v1/trending-tags/illust?filter=for_android", APP.server, ) } pub async fn illust_trending_tags(&self) -> Result<IllustTrendingTags> { self.get_from_pixiv(self.illust_trending_tags_url()).await } pub fn illust_search_first_url(&self, word: String, mode: String) -> String { format!( "https://{}/v1/search/illust?word={}&search_target={}&filter=for_ios", APP.server, urlencoding::encode(word.as_str()), mode, ) } pub fn illust_rank_first_utl(&self, mode: String, date: String) -> String { format!( "https://{}/v1/illust/ranking?mode={}&date={}&filter={}", APP.server, mode, date, "for_android", ) } pub async fn load_image_data(&self, url: String) -> Result<bytes::Bytes> { let req = match self.agent_free { true => { if url.starts_with(format!("https://{}", IMG.server).as_str()) { self.agent .get(url.replacen(IMG.server, IMG.ip.clone(), 1)) .header("Host", IMG.server) } else { self.agent.get(url) } } false => self.agent.get(url), }; let req = self.sign_request(req); let rsp = req.send().await?; let status = rsp.status(); match status.as_u16() { 200 => Ok(rsp.bytes().await?), _ => Err(Error::msg(rsp.text().await?)), } } }
erde_json::from_str(resp.text().await?.as_str())?), _ => { let err: LoginErrorResponse = serde_json::from_str(resp.text().await?.as_str())?; Err(Error::msg(err.errors.system.message)) } } } Err(err) => Err(Error::msg(err)), } } pub async fn load_token_by_code(&self, code: String, verify: String) -> Result<Token> { self.load_token(json!({ "code": code, "code_verifier": verify, "redirect_uri": "https://app-api.pixiv.net/web/v1/users/auth/pixiv/callback", "grant_type": "authorization_code", "include_policy": "true", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, })) .await } pub async fn refresh_token(&self, refresh_token: &String) -> Result<Token> { self.load_token(json!({ "refresh_token": refresh_token, "grant_type": "refresh_token", "include_policy": "true", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, })) .await } fn sign_request(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder { let time = self.iso_time(); request .header("x-client-time", &time.clone()) .header("x-client-hash", hex::encode(format!("{}{}", time, SALT))) .header("accept-language", "zh-CN") .header( "User-Agent", "PixivAndroidApp/5.0.234 (Android 10.0; Pixel C)", ) .header("App-OS-Version", "Android 10.0") .header("Referer", "https://app-api.pixiv.net/") .bearer_auth(&self.access_token) } pub async fn get_from_pixiv_raw(&self, url: String) -> Result<String> { let req = match self.agent_free { true => { if url.starts_with(format!("https:/
random
[ { "content": "pub fn sha256(src: String) -> Vec<u8> {\n\n let mut hasher = Sha256::new();\n\n hasher.update(src.as_bytes());\n\n hasher.finalize().to_vec()\n\n}\n\n\n\n//////////////////////////////////////////////////\n", "file_path": "src/utils.rs", "rank": 0, "score": 71134.40215482653 ...
Rust
codecs/src/aper/mod.rs
nplrkn/hampi
0b07137ecef245d462c9f942bb219ad7bac2f434
#![allow(dead_code)] pub mod error; pub use error::Error as AperCodecError; pub mod decode; pub mod encode; pub trait AperCodec { type Output; fn decode(data: &mut AperCodecData) -> Result<Self::Output, AperCodecError>; fn encode(&self, _data: &mut AperCodecData) -> Result<(), AperCodecError> { todo!(); } } use bitvec::prelude::*; #[derive(Default, Debug)] pub struct AperCodecData { bits: BitVec<Msb0, u8>, decode_offset: usize, key: Option<i128>, } impl AperCodecData { pub fn new() -> Self { Self::default() } pub fn from_slice(bytes: &[u8]) -> Self { Self { bits: BitSlice::<_, _>::from_slice(bytes).unwrap().to_bitvec(), decode_offset: 0, key: None, } } pub fn into_bytes(self) -> Vec<u8> { self.bits.into() } pub fn decode_align(&mut self) -> Result<(), AperCodecError> { if self.decode_offset % 8 == 0 { return Ok(()); } let remaining = 8 - (self.decode_offset & 0x7_usize); log::trace!("Aligning Codec Buffer with {} bits", remaining); if !self.bits[self.decode_offset..self.decode_offset + remaining] .iter() .all(|b| b == false) { Err(AperCodecError::new( format!( "{} Padding bits at Offset {} not all '0'.", remaining, self.decode_offset, ) .as_str(), )) } else { self.decode_offset += remaining; Ok(()) } } fn decode_bool(&mut self) -> Result<bool, AperCodecError> { if self.bits.len() == self.decode_offset { return Err(AperCodecError::new( "AperCodec:DecodeError:End of Bitstream reached while trying to decode bool.", )); } let bit = *self.bits.get(self.decode_offset).as_deref().unwrap(); let _ = self.advance_maybe_err(1, true)?; Ok(bit) } fn decode_bits_as_integer( &mut self, bits: usize, signed: bool, ) -> Result<i128, AperCodecError> { let remaining = self.bits.len() - self.decode_offset; if remaining < bits { Err(AperCodecError::new( format!( "AperCodec:DecodeError:Requested Bits to decode {}, Remaining bits {}", bits, remaining ) .as_str(), )) } else { log::trace!( "Decoding Bits as Integer. offset: {}, bits: {}", self.decode_offset, bits ); let value = if !signed { if bits == 0 { 0_i128 } else { self.bits[self.decode_offset..self.decode_offset + bits].load_be::<u128>() as i128 } } else { match bits { 8 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i8; inner as i128 } 16 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i16; inner as i128 } 24 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u32>() as u32; let inner = if self.bits[self.decode_offset] { inner | 0xFF000000 } else { inner & 0x00FFFFFF }; let inner = inner as i32; inner as i128 } 32 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i32; inner as i128 } 40 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u64>() as u64; let inner = if self.bits[self.decode_offset] { inner | 0xFFFFFF0000000000 } else { inner & 0x000000FFFFFFFFFF }; let inner = inner as i64; inner as i128 } 48 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u64>() as u64; let inner = if self.bits[self.decode_offset] { inner | 0xFFFF000000000000 } else { inner & 0x0000FFFFFFFFFFFF }; let inner = inner as i64; inner as i128 } 56 => { eprintln!("{}", self.decode_offset); let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u64>() as u64; let inner = if self.bits[self.decode_offset] { inner | 0xFF00000000000000 } else { inner & 0x00FFFFFFFFFFFFFF }; let inner = inner as i64; inner as i128 } 64 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i64; inner as i128 } 128 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i128; inner as i128 } _ => { return Err( AperCodecError::new( format!( "For a signed number in 2's compliment form, requested bits {} not supported!", bits))); } } }; log::trace!("Decoded Value: {:#?}", value); self.advance_maybe_err(bits, false)?; Ok(value) } } fn advance_maybe_err(&mut self, bits: usize, ignore: bool) -> Result<(), AperCodecError> { let offset = self.decode_offset + bits; if offset > self.bits.len() { if ignore { self.decode_offset = self.bits.len() } else { let remaining = self.bits.len() - self.decode_offset; return Err(AperCodecError::new( format!( "AperCodec:DecodeError:Requested Bits to advance {}, Remaining bits {}", bits, remaining ) .as_str(), )); } } else { self.decode_offset = offset } Ok(()) } fn get_bit(&self) -> Result<bool, AperCodecError> { if self.decode_offset >= self.bits.len() { return Err(AperCodecError::new( format!( "AperCodec:GetBitError:Requested Bit {}, Remaining bits {}", self.decode_offset, self.bits.len() - self.decode_offset ) .as_str(), )); } let bit = *self.bits.get(self.decode_offset).as_deref().unwrap(); Ok(bit) } fn get_bitvec(&mut self, length: usize) -> Result<BitVec<Msb0, u8>, AperCodecError> { if length + self.decode_offset >= self.bits.len() { return Err(AperCodecError::new( format!( "AperCodec:GetBitError:Requested Bit {}, Remaining bits {}", length, self.bits.len() - self.decode_offset ) .as_str(), )); } let bv = BitVec::from_bitslice(&self.bits[self.decode_offset..self.decode_offset + length]); let _ = self.advance_maybe_err(length, true)?; Ok(bv) } fn get_bytes(&mut self, length: usize) -> Result<Vec<u8>, AperCodecError> { let length = length * 8; if length + self.decode_offset >= self.bits.len() { return Err(AperCodecError::new( format!( "AperCodec:GetBitError:Requested Bits {}, Remaining bits {}", length, self.bits.len() - self.decode_offset ) .as_str(), )); } let mut bv = self.bits[self.decode_offset..self.decode_offset + length].to_bitvec(); bv.force_align(); self.advance_maybe_err(length, true)?; Ok(BitVec::into_vec(bv)) } pub fn get_inner(&self) -> Result<Vec<u8>, AperCodecError> { Ok(BitVec::into_vec(self.bits.to_bitvec())) } pub fn get_key(&self) -> Option<i128> { self.key } pub fn set_key(&mut self, key: i128) { let _ = self.key.replace(key); } #[inline] pub fn dump(&self) { log::trace!("AperCodecData: offset: {}", self.decode_offset); } #[inline] pub fn dump_encode(&self) { log::trace!("AperCodecData: current_len : {}", self.bits.len()); } #[inline] pub fn reserve(&mut self, count: usize) { self.bits.reserve(count); self.decode_offset = count; } #[inline] pub fn seek(&mut self, offset: usize) { self.decode_offset = offset; } pub fn swap_bits(&mut self, other: &mut BitSlice<Msb0, u8>, offset: usize) { self.bits[offset..other.len() + offset].swap_with_bitslice(other); } pub fn set_bit(&mut self, index: usize, value: bool) { self.bits.set(index, value); } fn encode_bool(&mut self, value: bool) { self.bits.push(value); } fn append_bits(&mut self, bits: &BitSlice<Msb0, u8>) { self.bits.extend_from_bitslice(bits); } fn align(&mut self) { let remaining = 8 - (self.bits.len() & 0x7_usize); if remaining < 8 { self.bits.resize(self.bits.len() + remaining, false); } } pub fn length_in_bytes(&self) -> usize { ((self.bits.len() - 1) / 8) + 1 } pub fn append_aligned(&mut self, other: &mut Self) { self.align(); other.align(); self.append_bits(&other.bits) } } fn bytes_needed_for_range(range: i128) -> u8 { let bits_needed: u8 = 128 - range.leading_zeros() as u8; let mut bytes_needed = bits_needed / 8; if bits_needed % 8 != 0 { bytes_needed += 1 } bytes_needed } #[cfg(test)] mod tests { use super::*; #[test] fn get_bytes_unaligned() { let mut d = AperCodecData::from_slice(&vec![0x0f, 0xf0]); let _ = d.get_bitvec(4); let bytes = d.get_bytes(1).unwrap(); assert_eq!(bytes, vec![0xff]); } #[test] fn test_encode_decode_unconstrained_whole_number() { let numbers: Vec<i128> = vec![ 140737488355328, 140737488355327, 549755813888, 549755813887, 2147483648, 2147483647, 8388608, 8388607, 32768, 32767, 128, 127, 1, 0, -1, -128, -129, -32768, -32769, -8388608, -8388609, -2147483648, -2147483649, -549755813888, -549755813889, -140737488355328, -140737488355329, ]; for num in numbers { let mut d = AperCodecData::new(); eprintln!("number: {}", num); let result = encode::encode_integer(&mut d, None, None, false, num, false); eprintln!("{:?}", d); assert!(result.is_ok(), "{:#?}", d); let value = decode::decode_integer(&mut d, None, None, false); assert!(value.is_ok(), "{:#?}", value.err()); assert!(value.unwrap().0 == num); } } }
#![allow(dead_code)] pub mod error; pub use error::Error as AperCodecError; pub mod decode; pub mod encode; pub trait AperCodec { type Output; fn decode(data: &mut AperCodecData) -> Result<Self::Output, AperCodecError>; fn encode(&self, _data: &mut AperCodecData) -> Result<(), AperCodecError> { todo!(); } } use bitvec::prelude::*; #[derive(Default, Debug)] pub struct AperCodecData { bits: BitVec<Msb0, u8>, decode_offset: usize, key: Option<i128>, } impl AperCodecData { pub fn new() -> Self { Self::default() } pub fn from_slice(bytes: &[u8]) -> Self { Self { bits: BitSlice::<_, _>::from_slice(bytes).unwrap().to_bitvec(), decode_offset: 0, key: None, } } pub fn into_bytes(self) -> Vec<u8> { self.bits.into() } pub fn decode_align(&mut self) -> Result<(), AperCodecError> { if self.decode_offset % 8 == 0 { return Ok(()); } let remaining = 8 - (self.decode_offset & 0x7_usize); log::trace!("Aligning Codec Buffer with {} bits", remaining); if !self.bits[self.decode_offset..self.decode_offset + remaining] .iter() .all(|b| b == false) { Err(AperCodecError::new( format!( "{} Padding bits at Offset {} not all '0'.", remaining, self.decode_offset, ) .as_str(), )) } else { self.decode_offset += remaining; Ok(()) } } fn decode_bool(&mut self) -> Result<bool, AperCodecError> { if self.bits.len() == self.decode_offset { return Err(AperCodecError::new( "AperCodec:DecodeError:End of Bitstream reached while trying to decode bool.", )); } let bit = *self.bits.get(self.decode_offset).a
FF }; let inner = inner as i64; inner as i128 } 64 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i64; inner as i128 } 128 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i128; inner as i128 } _ => { return Err( AperCodecError::new( format!( "For a signed number in 2's compliment form, requested bits {} not supported!", bits))); } } }; log::trace!("Decoded Value: {:#?}", value); self.advance_maybe_err(bits, false)?; Ok(value) } } fn advance_maybe_err(&mut self, bits: usize, ignore: bool) -> Result<(), AperCodecError> { let offset = self.decode_offset + bits; if offset > self.bits.len() { if ignore { self.decode_offset = self.bits.len() } else { let remaining = self.bits.len() - self.decode_offset; return Err(AperCodecError::new( format!( "AperCodec:DecodeError:Requested Bits to advance {}, Remaining bits {}", bits, remaining ) .as_str(), )); } } else { self.decode_offset = offset } Ok(()) } fn get_bit(&self) -> Result<bool, AperCodecError> { if self.decode_offset >= self.bits.len() { return Err(AperCodecError::new( format!( "AperCodec:GetBitError:Requested Bit {}, Remaining bits {}", self.decode_offset, self.bits.len() - self.decode_offset ) .as_str(), )); } let bit = *self.bits.get(self.decode_offset).as_deref().unwrap(); Ok(bit) } fn get_bitvec(&mut self, length: usize) -> Result<BitVec<Msb0, u8>, AperCodecError> { if length + self.decode_offset >= self.bits.len() { return Err(AperCodecError::new( format!( "AperCodec:GetBitError:Requested Bit {}, Remaining bits {}", length, self.bits.len() - self.decode_offset ) .as_str(), )); } let bv = BitVec::from_bitslice(&self.bits[self.decode_offset..self.decode_offset + length]); let _ = self.advance_maybe_err(length, true)?; Ok(bv) } fn get_bytes(&mut self, length: usize) -> Result<Vec<u8>, AperCodecError> { let length = length * 8; if length + self.decode_offset >= self.bits.len() { return Err(AperCodecError::new( format!( "AperCodec:GetBitError:Requested Bits {}, Remaining bits {}", length, self.bits.len() - self.decode_offset ) .as_str(), )); } let mut bv = self.bits[self.decode_offset..self.decode_offset + length].to_bitvec(); bv.force_align(); self.advance_maybe_err(length, true)?; Ok(BitVec::into_vec(bv)) } pub fn get_inner(&self) -> Result<Vec<u8>, AperCodecError> { Ok(BitVec::into_vec(self.bits.to_bitvec())) } pub fn get_key(&self) -> Option<i128> { self.key } pub fn set_key(&mut self, key: i128) { let _ = self.key.replace(key); } #[inline] pub fn dump(&self) { log::trace!("AperCodecData: offset: {}", self.decode_offset); } #[inline] pub fn dump_encode(&self) { log::trace!("AperCodecData: current_len : {}", self.bits.len()); } #[inline] pub fn reserve(&mut self, count: usize) { self.bits.reserve(count); self.decode_offset = count; } #[inline] pub fn seek(&mut self, offset: usize) { self.decode_offset = offset; } pub fn swap_bits(&mut self, other: &mut BitSlice<Msb0, u8>, offset: usize) { self.bits[offset..other.len() + offset].swap_with_bitslice(other); } pub fn set_bit(&mut self, index: usize, value: bool) { self.bits.set(index, value); } fn encode_bool(&mut self, value: bool) { self.bits.push(value); } fn append_bits(&mut self, bits: &BitSlice<Msb0, u8>) { self.bits.extend_from_bitslice(bits); } fn align(&mut self) { let remaining = 8 - (self.bits.len() & 0x7_usize); if remaining < 8 { self.bits.resize(self.bits.len() + remaining, false); } } pub fn length_in_bytes(&self) -> usize { ((self.bits.len() - 1) / 8) + 1 } pub fn append_aligned(&mut self, other: &mut Self) { self.align(); other.align(); self.append_bits(&other.bits) } } fn bytes_needed_for_range(range: i128) -> u8 { let bits_needed: u8 = 128 - range.leading_zeros() as u8; let mut bytes_needed = bits_needed / 8; if bits_needed % 8 != 0 { bytes_needed += 1 } bytes_needed } #[cfg(test)] mod tests { use super::*; #[test] fn get_bytes_unaligned() { let mut d = AperCodecData::from_slice(&vec![0x0f, 0xf0]); let _ = d.get_bitvec(4); let bytes = d.get_bytes(1).unwrap(); assert_eq!(bytes, vec![0xff]); } #[test] fn test_encode_decode_unconstrained_whole_number() { let numbers: Vec<i128> = vec![ 140737488355328, 140737488355327, 549755813888, 549755813887, 2147483648, 2147483647, 8388608, 8388607, 32768, 32767, 128, 127, 1, 0, -1, -128, -129, -32768, -32769, -8388608, -8388609, -2147483648, -2147483649, -549755813888, -549755813889, -140737488355328, -140737488355329, ]; for num in numbers { let mut d = AperCodecData::new(); eprintln!("number: {}", num); let result = encode::encode_integer(&mut d, None, None, false, num, false); eprintln!("{:?}", d); assert!(result.is_ok(), "{:#?}", d); let value = decode::decode_integer(&mut d, None, None, false); assert!(value.is_ok(), "{:#?}", value.err()); assert!(value.unwrap().0 == num); } } }
s_deref().unwrap(); let _ = self.advance_maybe_err(1, true)?; Ok(bit) } fn decode_bits_as_integer( &mut self, bits: usize, signed: bool, ) -> Result<i128, AperCodecError> { let remaining = self.bits.len() - self.decode_offset; if remaining < bits { Err(AperCodecError::new( format!( "AperCodec:DecodeError:Requested Bits to decode {}, Remaining bits {}", bits, remaining ) .as_str(), )) } else { log::trace!( "Decoding Bits as Integer. offset: {}, bits: {}", self.decode_offset, bits ); let value = if !signed { if bits == 0 { 0_i128 } else { self.bits[self.decode_offset..self.decode_offset + bits].load_be::<u128>() as i128 } } else { match bits { 8 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i8; inner as i128 } 16 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i16; inner as i128 } 24 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u32>() as u32; let inner = if self.bits[self.decode_offset] { inner | 0xFF000000 } else { inner & 0x00FFFFFF }; let inner = inner as i32; inner as i128 } 32 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i32; inner as i128 } 40 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u64>() as u64; let inner = if self.bits[self.decode_offset] { inner | 0xFFFFFF0000000000 } else { inner & 0x000000FFFFFFFFFF }; let inner = inner as i64; inner as i128 } 48 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u64>() as u64; let inner = if self.bits[self.decode_offset] { inner | 0xFFFF000000000000 } else { inner & 0x0000FFFFFFFFFFFF }; let inner = inner as i64; inner as i128 } 56 => { eprintln!("{}", self.decode_offset); let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u64>() as u64; let inner = if self.bits[self.decode_offset] { inner | 0xFF00000000000000 } else { inner & 0x00FFFFFFFFFFFF
random
[ { "content": "/// Decode a Boolean\n\n///\n\n/// Decode a Boolean value. Returns the decoded value as a `bool`.\n\npub fn decode_bool(data: &mut AperCodecData) -> Result<bool, AperCodecError> {\n\n data.decode_bool()\n\n}\n\n\n", "file_path": "codecs/src/aper/decode/mod.rs", "rank": 0, "score": 2...
Rust
sdk/finspacedata/src/json_ser.rs
StevenBlack/aws-sdk-rust
f4a1458f0154318c47d7e6a4ac55226f400fbfbc
pub fn serialize_structure_crate_input_create_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.change_type { object.key("changeType").string(var_1.as_str()); } if let Some(var_2) = &input.client_token { object.key("clientToken").string(var_2.as_str()); } if let Some(var_3) = &input.format_params { let mut object_4 = object.key("formatParams").start_object(); for (key_5, value_6) in var_3 { { object_4.key(key_5).string(value_6.as_str()); } } object_4.finish(); } if let Some(var_7) = &input.source_params { let mut object_8 = object.key("sourceParams").start_object(); for (key_9, value_10) in var_7 { { object_8.key(key_9).string(value_10.as_str()); } } object_8.finish(); } Ok(()) } pub fn serialize_structure_crate_input_create_dataset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDatasetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_11) = &input.alias { object.key("alias").string(var_11.as_str()); } if let Some(var_12) = &input.client_token { object.key("clientToken").string(var_12.as_str()); } if let Some(var_13) = &input.dataset_description { object.key("datasetDescription").string(var_13.as_str()); } if let Some(var_14) = &input.dataset_title { object.key("datasetTitle").string(var_14.as_str()); } if let Some(var_15) = &input.kind { object.key("kind").string(var_15.as_str()); } if let Some(var_16) = &input.owner_info { let mut object_17 = object.key("ownerInfo").start_object(); crate::json_ser::serialize_structure_crate_model_dataset_owner_info( &mut object_17, var_16, )?; object_17.finish(); } if let Some(var_18) = &input.permission_group_params { let mut object_19 = object.key("permissionGroupParams").start_object(); crate::json_ser::serialize_structure_crate_model_permission_group_params( &mut object_19, var_18, )?; object_19.finish(); } if let Some(var_20) = &input.schema_definition { let mut object_21 = object.key("schemaDefinition").start_object(); crate::json_ser::serialize_structure_crate_model_schema_union(&mut object_21, var_20)?; object_21.finish(); } Ok(()) } pub fn serialize_structure_crate_input_create_data_view_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDataViewInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_22) = &input.as_of_timestamp { object.key("asOfTimestamp").number( #[allow(clippy::useless_conversion)] aws_smithy_types::Number::NegInt((*var_22).into()), ); } if input.auto_update { object.key("autoUpdate").boolean(input.auto_update); } if let Some(var_23) = &input.client_token { object.key("clientToken").string(var_23.as_str()); } if let Some(var_24) = &input.destination_type_params { let mut object_25 = object.key("destinationTypeParams").start_object(); crate::json_ser::serialize_structure_crate_model_data_view_destination_type_params( &mut object_25, var_24, )?; object_25.finish(); } if let Some(var_26) = &input.partition_columns { let mut array_27 = object.key("partitionColumns").start_array(); for item_28 in var_26 { { array_27.value().string(item_28.as_str()); } } array_27.finish(); } if let Some(var_29) = &input.sort_columns { let mut array_30 = object.key("sortColumns").start_array(); for item_31 in var_29 { { array_30.value().string(item_31.as_str()); } } array_30.finish(); } Ok(()) } pub fn serialize_structure_crate_input_create_permission_group_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreatePermissionGroupInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_32) = &input.application_permissions { let mut array_33 = object.key("applicationPermissions").start_array(); for item_34 in var_32 { { array_33.value().string(item_34.as_str()); } } array_33.finish(); } if let Some(var_35) = &input.client_token { object.key("clientToken").string(var_35.as_str()); } if let Some(var_36) = &input.description { object.key("description").string(var_36.as_str()); } if let Some(var_37) = &input.name { object.key("name").string(var_37.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_create_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_38) = &input.api_access { object.key("ApiAccess").string(var_38.as_str()); } if let Some(var_39) = &input.api_access_principal_arn { object.key("apiAccessPrincipalArn").string(var_39.as_str()); } if let Some(var_40) = &input.client_token { object.key("clientToken").string(var_40.as_str()); } if let Some(var_41) = &input.email_address { object.key("emailAddress").string(var_41.as_str()); } if let Some(var_42) = &input.first_name { object.key("firstName").string(var_42.as_str()); } if let Some(var_43) = &input.last_name { object.key("lastName").string(var_43.as_str()); } if let Some(var_44) = &input.r#type { object.key("type").string(var_44.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_disable_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::DisableUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_45) = &input.client_token { object.key("clientToken").string(var_45.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_enable_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::EnableUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_46) = &input.client_token { object.key("clientToken").string(var_46.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_get_working_location_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::GetWorkingLocationInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_47) = &input.location_type { object.key("locationType").string(var_47.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_reset_user_password_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::ResetUserPasswordInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_48) = &input.client_token { object.key("clientToken").string(var_48.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_update_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_49) = &input.client_token { object.key("clientToken").string(var_49.as_str()); } if let Some(var_50) = &input.format_params { let mut object_51 = object.key("formatParams").start_object(); for (key_52, value_53) in var_50 { { object_51.key(key_52).string(value_53.as_str()); } } object_51.finish(); } if let Some(var_54) = &input.source_params { let mut object_55 = object.key("sourceParams").start_object(); for (key_56, value_57) in var_54 { { object_55.key(key_56).string(value_57.as_str()); } } object_55.finish(); } Ok(()) } pub fn serialize_structure_crate_input_update_dataset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateDatasetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_58) = &input.alias { object.key("alias").string(var_58.as_str()); } if let Some(var_59) = &input.client_token { object.key("clientToken").string(var_59.as_str()); } if let Some(var_60) = &input.dataset_description { object.key("datasetDescription").string(var_60.as_str()); } if let Some(var_61) = &input.dataset_title { object.key("datasetTitle").string(var_61.as_str()); } if let Some(var_62) = &input.kind { object.key("kind").string(var_62.as_str()); } if let Some(var_63) = &input.schema_definition { let mut object_64 = object.key("schemaDefinition").start_object(); crate::json_ser::serialize_structure_crate_model_schema_union(&mut object_64, var_63)?; object_64.finish(); } Ok(()) } pub fn serialize_structure_crate_input_update_permission_group_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdatePermissionGroupInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_65) = &input.application_permissions { let mut array_66 = object.key("applicationPermissions").start_array(); for item_67 in var_65 { { array_66.value().string(item_67.as_str()); } } array_66.finish(); } if let Some(var_68) = &input.client_token { object.key("clientToken").string(var_68.as_str()); } if let Some(var_69) = &input.description { object.key("description").string(var_69.as_str()); } if let Some(var_70) = &input.name { object.key("name").string(var_70.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_update_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_71) = &input.api_access { object.key("apiAccess").string(var_71.as_str()); } if let Some(var_72) = &input.api_access_principal_arn { object.key("apiAccessPrincipalArn").string(var_72.as_str()); } if let Some(var_73) = &input.client_token { object.key("clientToken").string(var_73.as_str()); } if let Some(var_74) = &input.first_name { object.key("firstName").string(var_74.as_str()); } if let Some(var_75) = &input.last_name { object.key("lastName").string(var_75.as_str()); } if let Some(var_76) = &input.r#type { object.key("type").string(var_76.as_str()); } Ok(()) } pub fn serialize_structure_crate_model_dataset_owner_info( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::DatasetOwnerInfo, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_77) = &input.name { object.key("name").string(var_77.as_str()); } if let Some(var_78) = &input.phone_number { object.key("phoneNumber").string(var_78.as_str()); } if let Some(var_79) = &input.email { object.key("email").string(var_79.as_str()); } Ok(()) } pub fn serialize_structure_crate_model_permission_group_params( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::PermissionGroupParams, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_80) = &input.permission_group_id { object.key("permissionGroupId").string(var_80.as_str()); } if let Some(var_81) = &input.dataset_permissions { let mut array_82 = object.key("datasetPermissions").start_array(); for item_83 in var_81 { { let mut object_84 = array_82.value().start_object(); crate::json_ser::serialize_structure_crate_model_resource_permission( &mut object_84, item_83, )?; object_84.finish(); } } array_82.finish(); } Ok(()) } pub fn serialize_structure_crate_model_schema_union( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::SchemaUnion, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_85) = &input.tabular_schema_config { let mut object_86 = object.key("tabularSchemaConfig").start_object(); crate::json_ser::serialize_structure_crate_model_schema_definition(&mut object_86, var_85)?; object_86.finish(); } Ok(()) } pub fn serialize_structure_crate_model_data_view_destination_type_params( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::DataViewDestinationTypeParams, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_87) = &input.destination_type { object.key("destinationType").string(var_87.as_str()); } if let Some(var_88) = &input.s3_destination_export_file_format { object .key("s3DestinationExportFileFormat") .string(var_88.as_str()); } if let Some(var_89) = &input.s3_destination_export_file_format_options { let mut object_90 = object .key("s3DestinationExportFileFormatOptions") .start_object(); for (key_91, value_92) in var_89 { { object_90.key(key_91).string(value_92.as_str()); } } object_90.finish(); } Ok(()) } pub fn serialize_structure_crate_model_resource_permission( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::ResourcePermission, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_93) = &input.permission { object.key("permission").string(var_93.as_str()); } Ok(()) } pub fn serialize_structure_crate_model_schema_definition( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::SchemaDefinition, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_94) = &input.columns { let mut array_95 = object.key("columns").start_array(); for item_96 in var_94 { { let mut object_97 = array_95.value().start_object(); crate::json_ser::serialize_structure_crate_model_column_definition( &mut object_97, item_96, )?; object_97.finish(); } } array_95.finish(); } if let Some(var_98) = &input.primary_key_columns { let mut array_99 = object.key("primaryKeyColumns").start_array(); for item_100 in var_98 { { array_99.value().string(item_100.as_str()); } } array_99.finish(); } Ok(()) } pub fn serialize_structure_crate_model_column_definition( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::ColumnDefinition, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_101) = &input.data_type { object.key("dataType").string(var_101.as_str()); } if let Some(var_102) = &input.column_name { object.key("columnName").string(var_102.as_str()); } if let Some(var_103) = &input.column_description { object.key("columnDescription").string(var_103.as_str()); } Ok(()) }
pub fn serialize_structure_crate_input_create_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.change_type { object.key("changeType").string(var_1.as_str()); } if let Some(var_2) = &input.client_token { object.key("clientToken").string(var_2.as_str()); } if let Some(var_3) = &input.format_params { let mut object_4 = object.key("formatParams").start_object(); for (key_5, value_6) in var_3 { { object_4.key(key_5).string(value_6.as_str()); } } object_4.finish(); } if let Some(var_7) = &input.source_params { let mut object_8 = object.key("sourceParams").start_object(); for (key_9, value_10) in var_7 { { object_8.key(key_9).string(value_10.as_str()); } } object_8.finish(); } Ok(()) } pub fn serialize_structure_crate_input_create_dataset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDatasetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_11) = &input.alias { object.key("alias").string(var_11.as_str()); } if let Some(var_12) = &input.client_token { object.key("clientToken").string(var_12.as_str()); } if let Some(var_13) = &input.dataset_description { object.key("datasetDescription").string(var_13.as_str()); } if let Some(var_14) = &input.dataset_title { object.key("datasetTitle").string(var_14.as_str()); } if let Some(var_15) = &input.kind { object.key("kind").string(var_15.as_str()); } if let Some(var_16) = &input.owner_info { let mut object_17 = object.key("ownerInfo").start_object(); crate::json_ser::serialize_structure_crate_model_dataset_owner_info( &mut object_17, var_16, )?; object_17.finish(); } if let Some(var_18) = &input.permission_group_params { let mut object_19 = object.key("permissionGroupParams").start_object(); crate::json_ser::serialize_structure_crate_model_permission_group_params( &mut object_19, var_18, )?; object_19.finish(); } if let Some(var_20) = &input.schema_definition { let mut object_21 = object.key("schemaDefinition").start_object(); crate::json_ser::serialize_structure_crate_model_schema_union(&mut object_21, var_20)?; object_21.finish(); } Ok(()) } pub fn serialize_structure_crate_input_create_data_view_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDataViewInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_22) = &input.as_of_timestamp { object.key("asOfTimestamp").number( #[allow(clippy::useless_conversion)] aws_smithy_types::Number::NegInt((*var_22).into()), ); } if input.auto_update { object.key("autoUpdate").boolean(input.auto_update); } if let Some(var_23) = &input.client_token { object.key("clientToken").string(var_23.as_str()); } if let Some(var_24) = &input.destination_type_params { let mut object_25 = object.key("destinationTypeParams").start_object(); crate::json_ser::serialize_structure_crate_model_data_view_destination_type_params( &mut object_25, var_24, )?; object_25.finish(); } if let Some(var_26) = &input.partition_columns { let mut array_27 = object.key("partitionColumns").start_array(); for item_28 in var_26 { { array_27.value().string(item_28.as_str()); } } array_27.finish(); } if let Some(var_29) = &input.sort_columns { let mut array_30 = object.key("sortColumns").start_array(); for item_31 in var_29 { { array_30.value().string(item_31.as_str()); } } array_30.finish(); } Ok(()) } pub fn serialize_structure_crate_input_create_permission_group_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreatePermissionGroupInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_32) = &input.application_permissions { let mut array_33 = object.key("applicationPermissions").start_array(); for item_34 in var_32 { { arr
r()); } Ok(()) } pub fn serialize_structure_crate_input_update_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_71) = &input.api_access { object.key("apiAccess").string(var_71.as_str()); } if let Some(var_72) = &input.api_access_principal_arn { object.key("apiAccessPrincipalArn").string(var_72.as_str()); } if let Some(var_73) = &input.client_token { object.key("clientToken").string(var_73.as_str()); } if let Some(var_74) = &input.first_name { object.key("firstName").string(var_74.as_str()); } if let Some(var_75) = &input.last_name { object.key("lastName").string(var_75.as_str()); } if let Some(var_76) = &input.r#type { object.key("type").string(var_76.as_str()); } Ok(()) } pub fn serialize_structure_crate_model_dataset_owner_info( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::DatasetOwnerInfo, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_77) = &input.name { object.key("name").string(var_77.as_str()); } if let Some(var_78) = &input.phone_number { object.key("phoneNumber").string(var_78.as_str()); } if let Some(var_79) = &input.email { object.key("email").string(var_79.as_str()); } Ok(()) } pub fn serialize_structure_crate_model_permission_group_params( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::PermissionGroupParams, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_80) = &input.permission_group_id { object.key("permissionGroupId").string(var_80.as_str()); } if let Some(var_81) = &input.dataset_permissions { let mut array_82 = object.key("datasetPermissions").start_array(); for item_83 in var_81 { { let mut object_84 = array_82.value().start_object(); crate::json_ser::serialize_structure_crate_model_resource_permission( &mut object_84, item_83, )?; object_84.finish(); } } array_82.finish(); } Ok(()) } pub fn serialize_structure_crate_model_schema_union( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::SchemaUnion, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_85) = &input.tabular_schema_config { let mut object_86 = object.key("tabularSchemaConfig").start_object(); crate::json_ser::serialize_structure_crate_model_schema_definition(&mut object_86, var_85)?; object_86.finish(); } Ok(()) } pub fn serialize_structure_crate_model_data_view_destination_type_params( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::DataViewDestinationTypeParams, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_87) = &input.destination_type { object.key("destinationType").string(var_87.as_str()); } if let Some(var_88) = &input.s3_destination_export_file_format { object .key("s3DestinationExportFileFormat") .string(var_88.as_str()); } if let Some(var_89) = &input.s3_destination_export_file_format_options { let mut object_90 = object .key("s3DestinationExportFileFormatOptions") .start_object(); for (key_91, value_92) in var_89 { { object_90.key(key_91).string(value_92.as_str()); } } object_90.finish(); } Ok(()) } pub fn serialize_structure_crate_model_resource_permission( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::ResourcePermission, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_93) = &input.permission { object.key("permission").string(var_93.as_str()); } Ok(()) } pub fn serialize_structure_crate_model_schema_definition( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::SchemaDefinition, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_94) = &input.columns { let mut array_95 = object.key("columns").start_array(); for item_96 in var_94 { { let mut object_97 = array_95.value().start_object(); crate::json_ser::serialize_structure_crate_model_column_definition( &mut object_97, item_96, )?; object_97.finish(); } } array_95.finish(); } if let Some(var_98) = &input.primary_key_columns { let mut array_99 = object.key("primaryKeyColumns").start_array(); for item_100 in var_98 { { array_99.value().string(item_100.as_str()); } } array_99.finish(); } Ok(()) } pub fn serialize_structure_crate_model_column_definition( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::ColumnDefinition, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_101) = &input.data_type { object.key("dataType").string(var_101.as_str()); } if let Some(var_102) = &input.column_name { object.key("columnName").string(var_102.as_str()); } if let Some(var_103) = &input.column_description { object.key("columnDescription").string(var_103.as_str()); } Ok(()) }
ay_33.value().string(item_34.as_str()); } } array_33.finish(); } if let Some(var_35) = &input.client_token { object.key("clientToken").string(var_35.as_str()); } if let Some(var_36) = &input.description { object.key("description").string(var_36.as_str()); } if let Some(var_37) = &input.name { object.key("name").string(var_37.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_create_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_38) = &input.api_access { object.key("ApiAccess").string(var_38.as_str()); } if let Some(var_39) = &input.api_access_principal_arn { object.key("apiAccessPrincipalArn").string(var_39.as_str()); } if let Some(var_40) = &input.client_token { object.key("clientToken").string(var_40.as_str()); } if let Some(var_41) = &input.email_address { object.key("emailAddress").string(var_41.as_str()); } if let Some(var_42) = &input.first_name { object.key("firstName").string(var_42.as_str()); } if let Some(var_43) = &input.last_name { object.key("lastName").string(var_43.as_str()); } if let Some(var_44) = &input.r#type { object.key("type").string(var_44.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_disable_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::DisableUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_45) = &input.client_token { object.key("clientToken").string(var_45.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_enable_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::EnableUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_46) = &input.client_token { object.key("clientToken").string(var_46.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_get_working_location_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::GetWorkingLocationInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_47) = &input.location_type { object.key("locationType").string(var_47.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_reset_user_password_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::ResetUserPasswordInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_48) = &input.client_token { object.key("clientToken").string(var_48.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_update_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_49) = &input.client_token { object.key("clientToken").string(var_49.as_str()); } if let Some(var_50) = &input.format_params { let mut object_51 = object.key("formatParams").start_object(); for (key_52, value_53) in var_50 { { object_51.key(key_52).string(value_53.as_str()); } } object_51.finish(); } if let Some(var_54) = &input.source_params { let mut object_55 = object.key("sourceParams").start_object(); for (key_56, value_57) in var_54 { { object_55.key(key_56).string(value_57.as_str()); } } object_55.finish(); } Ok(()) } pub fn serialize_structure_crate_input_update_dataset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateDatasetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_58) = &input.alias { object.key("alias").string(var_58.as_str()); } if let Some(var_59) = &input.client_token { object.key("clientToken").string(var_59.as_str()); } if let Some(var_60) = &input.dataset_description { object.key("datasetDescription").string(var_60.as_str()); } if let Some(var_61) = &input.dataset_title { object.key("datasetTitle").string(var_61.as_str()); } if let Some(var_62) = &input.kind { object.key("kind").string(var_62.as_str()); } if let Some(var_63) = &input.schema_definition { let mut object_64 = object.key("schemaDefinition").start_object(); crate::json_ser::serialize_structure_crate_model_schema_union(&mut object_64, var_63)?; object_64.finish(); } Ok(()) } pub fn serialize_structure_crate_input_update_permission_group_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdatePermissionGroupInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_65) = &input.application_permissions { let mut array_66 = object.key("applicationPermissions").start_array(); for item_67 in var_65 { { array_66.value().string(item_67.as_str()); } } array_66.finish(); } if let Some(var_68) = &input.client_token { object.key("clientToken").string(var_68.as_str()); } if let Some(var_69) = &input.description { object.key("description").string(var_69.as_str()); } if let Some(var_70) = &input.name { object.key("name").string(var_70.as_st
random
[]
Rust
src/view/rikai.rs
Netdex/niinii
d2fa91f3c16b1bdc20d7799a79e1d354247cd55e
use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use ichiran::romanize::*; use imgui::*; use super::deepl::DeepLView; use super::mixins::*; use super::settings::{DisplayRubyText, SettingsView}; use crate::backend::renderer::Env; use crate::gloss::Gloss; use crate::translation::Translation; use crate::view::{raw::RawView, term::TermView}; #[derive(Debug)] pub struct RikaiView { gloss: Option<Gloss>, translation: Option<Translation>, show_term_window: RefCell<HashSet<Romanized>>, selected_clause: RefCell<HashMap<Segment, i32>>, } impl RikaiView { pub fn new() -> Self { Self { gloss: None, translation: None, show_term_window: RefCell::new(HashSet::new()), selected_clause: RefCell::new(HashMap::new()), } } pub fn set_gloss(&mut self, gloss: Option<Gloss>) { self.gloss = gloss; } pub fn gloss(&self) -> Option<&Gloss> { self.gloss.as_ref() } pub fn set_translation(&mut self, translation: Option<Translation>) { self.translation = translation; } pub fn translation(&self) -> Option<&Translation> { self.translation.as_ref() } fn term_window( &self, env: &mut Env, ui: &Ui, settings: &SettingsView, romanized: &Romanized, ) -> bool { let mut opened = true; Window::new(&romanized.term().text().to_string()) .size_constraints([300.0, 100.0], [1000.0, 1000.0]) .save_settings(false) .focus_on_appearing(true) .opened(&mut opened) .build(ui, || { if let Some(gloss) = &self.gloss { TermView::new(&gloss.jmdict_data, &gloss.kanji_info, romanized, 0.0) .ui(env, ui, settings); } }); opened } fn term_tooltip(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, romanized: &Romanized) { ui.tooltip(|| { if let Some(gloss) = &self.gloss { TermView::new(&gloss.jmdict_data, &gloss.kanji_info, romanized, 30.0) .ui(env, ui, settings) } }); } fn add_skipped(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, skipped: &str) { draw_kanji_text( ui, env, skipped, false, true, UnderlineMode::None, if settings.display_ruby_text() == DisplayRubyText::None { RubyTextMode::None } else { RubyTextMode::Pad }, ); } fn add_romanized( &self, env: &mut Env, ui: &Ui, settings: &SettingsView, romanized: &Romanized, ruby_text: DisplayRubyText, underline: UnderlineMode, ) -> bool { let term = romanized.term(); let fg_text = match ruby_text { DisplayRubyText::None => RubyTextMode::None, DisplayRubyText::Furigana if term.text() != term.kana() => { RubyTextMode::Text(term.kana()) } DisplayRubyText::Romaji => RubyTextMode::Text(romanized.romaji()), _ => RubyTextMode::Pad, }; let ul_hover = draw_kanji_text( ui, env, term.text(), true, settings.stroke_text, underline, fg_text, ); if ui.is_item_hovered() { ui.set_mouse_cursor(Some(MouseCursor::Hand)); self.term_tooltip(env, ui, settings, romanized); } let mut show_term_window = self.show_term_window.borrow_mut(); if ui.is_item_clicked() { show_term_window.insert(romanized.clone()); } ul_hover } fn add_segment(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, segment: &Segment) { match segment { Segment::Skipped(skipped) => { self.add_skipped(env, ui, settings, skipped); } Segment::Clauses(clauses) => { let mut selected_clause = self.selected_clause.borrow_mut(); let mut clause_idx = selected_clause.get(segment).cloned().unwrap_or(0); let clause = clauses.get(clause_idx as usize); if let Some(clause) = clause { let romanized = clause.romanized(); for (idx, rz) in romanized.iter().enumerate() { let ul_hover = self.add_romanized( env, ui, settings, rz, settings.display_ruby_text(), if idx == romanized.len() - 1 { UnderlineMode::Normal } else { UnderlineMode::Pad }, ); if ul_hover { let scroll = ui.io().mouse_wheel as i32; clause_idx -= scroll; clause_idx = clause_idx.clamp(0, clauses.len() as i32 - 1); if scroll != 0 { selected_clause.insert(segment.clone(), clause_idx); } ui.tooltip(|| { ui.text(format!( "Alternate #{}/{} score={} (scroll to cycle)", clause_idx + 1, clauses.len(), clause.score() )); ui.separator(); let _wrap_token = ui.push_text_wrap_pos_with_pos(ui.current_font_size() * 20.0); let romaji = clause .romanized() .iter() .map(|x| x.romaji()) .collect::<Vec<&str>>() .join(" "); ui.text_wrapped(romaji); _wrap_token.pop(ui); }); } } } } } } fn add_root(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, root: &Root) { for segment in root.segments() { self.add_segment(env, ui, settings, segment); } } pub fn ui(&mut self, env: &mut Env, ui: &Ui, settings: &SettingsView, show_raw: &mut bool) { if let Some(gloss) = &self.gloss { ui.text(""); self.add_root(env, ui, settings, &gloss.root); if *show_raw { Window::new("Raw") .size([300., 110.], Condition::FirstUseEver) .opened(show_raw) .build(ui, || { RawView::new(&gloss.root).ui(env, ui); }); } } if let Some(translation) = &self.translation { ui.separator(); DeepLView::new(translation).ui(ui); ui.separator(); } self.show_term_window .borrow_mut() .retain(|romanized| self.term_window(env, ui, settings, romanized)); } }
use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use ichiran::romanize::*; use imgui::*; use super::deepl::DeepLView; use super::mixins::*; use super::settings::{DisplayRubyText, SettingsView}; use crate::backend::renderer::Env; use crate::gloss::Gloss; use crate::translation::Translation; use crate::view::{raw::RawView, term::TermView}; #[derive(Debug)] pub struct RikaiView { gloss: Option<Gloss>, translation: Option<Translation>, show_term_window: RefCell<HashSet<Romanized>>, selected_clause: RefCell<HashMap<Segment, i32>>, } impl RikaiView { pub fn new() -> Self { Self { gloss: None, translation: None, show_term_window: RefCell::new(HashSet::new()), selected_clause: RefCell::new(HashMap::new()), } } pub fn set_gloss(&mut self, gloss: Option<Gloss>) { self.gloss = gloss; } pub fn gloss(&self) -> Option<&Gloss> { self.gloss.as_ref() } pub fn set_translation(&mut self, translation: Option<Translation>) { self.translation = translation; } pub fn translation(&self) -> Option<&Translation> {
text(""); self.add_root(env, ui, settings, &gloss.root); if *show_raw { Window::new("Raw") .size([300., 110.], Condition::FirstUseEver) .opened(show_raw) .build(ui, || { RawView::new(&gloss.root).ui(env, ui); }); } } if let Some(translation) = &self.translation { ui.separator(); DeepLView::new(translation).ui(ui); ui.separator(); } self.show_term_window .borrow_mut() .retain(|romanized| self.term_window(env, ui, settings, romanized)); } }
self.translation.as_ref() } fn term_window( &self, env: &mut Env, ui: &Ui, settings: &SettingsView, romanized: &Romanized, ) -> bool { let mut opened = true; Window::new(&romanized.term().text().to_string()) .size_constraints([300.0, 100.0], [1000.0, 1000.0]) .save_settings(false) .focus_on_appearing(true) .opened(&mut opened) .build(ui, || { if let Some(gloss) = &self.gloss { TermView::new(&gloss.jmdict_data, &gloss.kanji_info, romanized, 0.0) .ui(env, ui, settings); } }); opened } fn term_tooltip(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, romanized: &Romanized) { ui.tooltip(|| { if let Some(gloss) = &self.gloss { TermView::new(&gloss.jmdict_data, &gloss.kanji_info, romanized, 30.0) .ui(env, ui, settings) } }); } fn add_skipped(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, skipped: &str) { draw_kanji_text( ui, env, skipped, false, true, UnderlineMode::None, if settings.display_ruby_text() == DisplayRubyText::None { RubyTextMode::None } else { RubyTextMode::Pad }, ); } fn add_romanized( &self, env: &mut Env, ui: &Ui, settings: &SettingsView, romanized: &Romanized, ruby_text: DisplayRubyText, underline: UnderlineMode, ) -> bool { let term = romanized.term(); let fg_text = match ruby_text { DisplayRubyText::None => RubyTextMode::None, DisplayRubyText::Furigana if term.text() != term.kana() => { RubyTextMode::Text(term.kana()) } DisplayRubyText::Romaji => RubyTextMode::Text(romanized.romaji()), _ => RubyTextMode::Pad, }; let ul_hover = draw_kanji_text( ui, env, term.text(), true, settings.stroke_text, underline, fg_text, ); if ui.is_item_hovered() { ui.set_mouse_cursor(Some(MouseCursor::Hand)); self.term_tooltip(env, ui, settings, romanized); } let mut show_term_window = self.show_term_window.borrow_mut(); if ui.is_item_clicked() { show_term_window.insert(romanized.clone()); } ul_hover } fn add_segment(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, segment: &Segment) { match segment { Segment::Skipped(skipped) => { self.add_skipped(env, ui, settings, skipped); } Segment::Clauses(clauses) => { let mut selected_clause = self.selected_clause.borrow_mut(); let mut clause_idx = selected_clause.get(segment).cloned().unwrap_or(0); let clause = clauses.get(clause_idx as usize); if let Some(clause) = clause { let romanized = clause.romanized(); for (idx, rz) in romanized.iter().enumerate() { let ul_hover = self.add_romanized( env, ui, settings, rz, settings.display_ruby_text(), if idx == romanized.len() - 1 { UnderlineMode::Normal } else { UnderlineMode::Pad }, ); if ul_hover { let scroll = ui.io().mouse_wheel as i32; clause_idx -= scroll; clause_idx = clause_idx.clamp(0, clauses.len() as i32 - 1); if scroll != 0 { selected_clause.insert(segment.clone(), clause_idx); } ui.tooltip(|| { ui.text(format!( "Alternate #{}/{} score={} (scroll to cycle)", clause_idx + 1, clauses.len(), clause.score() )); ui.separator(); let _wrap_token = ui.push_text_wrap_pos_with_pos(ui.current_font_size() * 20.0); let romaji = clause .romanized() .iter() .map(|x| x.romaji()) .collect::<Vec<&str>>() .join(" "); ui.text_wrapped(romaji); _wrap_token.pop(ui); }); } } } } } } fn add_root(&self, env: &mut Env, ui: &Ui, settings: &SettingsView, root: &Root) { for segment in root.segments() { self.add_segment(env, ui, settings, segment); } } pub fn ui(&mut self, env: &mut Env, ui: &Ui, settings: &SettingsView, show_raw: &mut bool) { if let Some(gloss) = &self.gloss { ui.
random
[ { "content": "fn add_gloss(ui: &Ui, gloss: &Gloss) {\n\n TreeNode::new(&format!(\"Gloss ({} {})\", gloss.pos(), gloss.gloss()))\n\n .default_open(false)\n\n .build(ui, || {\n\n wrap_bullet(ui, &format!(\"pos: {}\", gloss.pos()));\n\n wrap_bullet(ui, &format!(\"gloss: {}\",...
Rust
src/pixel_task.rs
SharpCoder/hexagon2
0a565a263e5a3513c15e7e10ef75a9b6cd64efdb
use teensycore::*; use teensycore::clock::*; use teensycore::debug::blink_accumulate; use teensycore::math::rand; use teensycore::system::str::Str; use teensycore::system::str::StringOps; use teensycore::system::vector::Array; use teensycore::system::vector::Vector; use crate::date_time::DateTime; use crate::get_shader_configs; use crate::get_tranasition_delay; use crate::shaders::*; use crate::effects::*; use crate::pixel_engine::color::*; use crate::pixel_engine::math::interpolate; use crate::pixel_engine::shader::*; use crate::pixel_engine::effect::*; use crate::pixel_engine::context::*; use crate::drivers::ws2812::*; const LEDS_PER_UNIT: usize = 3; const LEDS: usize = crate::HEX_UNITS * LEDS_PER_UNIT; const TRANSITION_TIME: uNano = 1000 * crate::WORLD_MUTIPLIER; enum PixelState { Loading, Transitioning, MainSequence, } pub struct PixelTask { state: PixelState, shader: Option<Shader>, next_shader: Option<Shader>, shaders: Vector<Shader>, contexts: [Context; crate::HEX_UNITS], effect: Option<Effect>, effects: Vector<Effect>, driver: WS2812Driver<LEDS>, target: uNano, day_target: uNano, day_processed: uNano, cycles: u64, randomize_target: uNano, ready: bool, color_buffer: [Color; crate::HEX_UNITS], transition_start: uNano, transition_offset: uNano, cycle_offset: uNano, } impl PixelTask { pub fn new() -> Self { return PixelTask { state: PixelState::Loading, target: 0, day_target: 0, randomize_target: 0, day_processed: 0, transition_start: 0, transition_offset: 0, cycle_offset: 0, cycles: 0, ready: false, shader: None, effect: None, next_shader: None, shaders: initialize_shaders(), effects: initialize_effects(), driver: WS2812Driver::<LEDS>::new( 18, ), color_buffer: [Color::blank(); crate::HEX_UNITS], contexts: [Context::empty(); crate::HEX_UNITS], }; } #[allow(dead_code)] fn find_effect(&self, name: &'static [u8]) -> Option<Effect> { for effect in self.effects.into_iter() { if effect.name == name { return Some(effect); } } return None; } fn find_shader(&self, name: &Str) -> Option<Shader> { for shader in self.shaders.into_iter() { let mut shader_name = Str::new(); shader_name.append(shader.name); if name.contains(&shader_name) { shader_name.drop(); return Some(shader); } shader_name.drop(); } return None; } fn cycle_next_shader(&mut self) { let idx = (self.cycles / 3) as usize % self.shaders.size(); let shader = self.shaders.get(idx).unwrap(); self.transition_to(shader); } fn get_next_shader(&self) -> Shader { if crate::USE_WIFI { let appropriate_shader = get_shader_configs().get_shader(crate::get_world_time()); match self.find_shader(&appropriate_shader) { None => return self.shaders.get(0).unwrap(), Some(shader) => { if shader.disabled { return self.get_next_shader(); } return shader; } } } else { let idx = rand() % self.shaders.size() as u64; let next_shader = self.shaders.get(idx as usize).unwrap(); if next_shader.wifi_only || next_shader.disabled { return self.get_next_shader(); } else { return next_shader; } } } fn get_next_effect(&self, shader: &Shader) -> Effect { let idx = rand() % self.effects.size() as u64; let next_effect = self.effects.get(idx as usize).unwrap(); if next_effect.disabled || next_effect.max_color_segments.unwrap_or(usize::MAX) < shader.total_segments || next_effect.min_hex_units.unwrap_or(0) > crate::HEX_UNITS { return self.get_next_effect(shader); } else { return next_effect; } } pub fn init(&mut self) { self.driver.init(); for node_id in 0 .. crate::HEX_UNITS { self.contexts[node_id].node_id = node_id as uNano; self.contexts[node_id].total_nodes = crate::HEX_UNITS as uNano; self.contexts[node_id].initialized = false; } self.day_target = nanos() + (S_TO_NANO * 60 * 30); self.shader = self.find_shader(&str!(b"Medbay")); self.effect = Some(self.find_effect(b"Randomized").unwrap()); } pub fn transition_to(&mut self, next_shader: Shader) { self.next_shader = Some(next_shader); for node_id in 0 .. crate::HEX_UNITS { self.contexts[node_id].initialized = false; self.contexts[node_id].node_id = node_id as uNano; } self.effect = Some(self.get_next_effect(&next_shader)); self.transition_start = nanos(); self.transition_offset = 0; self.state = PixelState::Transitioning; } pub fn randomize(&mut self) { self.randomize_target = nanos() + get_tranasition_delay(); self.transition_to(self.get_next_shader()); } /* This method will reset variables if the world uptime counter overflows. */ pub fn overflow_watch(&mut self) { let now = nanos(); if self.transition_offset > 0 && self.transition_start > 0 && self.randomize_target > 0 && ( now < self.transition_offset || now < self.transition_start ) { self.randomize(); } } pub fn system_loop(&mut self) { let time = nanos() - self.transition_offset; let cycle_time = (time - self.cycle_offset) / teensycore::MS_TO_NANO; let elapsed_ms = time / teensycore::MS_TO_NANO; let mut should_cycle = false; if time > self.target { let shader = self.shader.as_mut().unwrap(); let effect = self.effect.as_mut().unwrap(); match self.state { PixelState::Transitioning => { if time > (self.transition_start + TRANSITION_TIME * MS_TO_NANO) { self.state = PixelState::MainSequence; self.shader = self.next_shader; self.transition_offset = self.transition_start; } else { for node_id in 0 .. crate::HEX_UNITS { let mut ctx = self.contexts[node_id]; let next_shader = self.next_shader.as_mut().unwrap(); let transition_time_elapsed = (time - self.transition_start) / MS_TO_NANO; let (effect_time, next_context) = effect.process(&mut ctx, transition_time_elapsed); let time_t = ((effect_time as f64 / 100.0) * next_shader.total_time as f64) as uNano; let next_color = next_shader.get_color(time_t); self.contexts[node_id] = next_context; let color = rgb( interpolate(self.color_buffer[node_id].r as u32, next_color.r as u32, transition_time_elapsed, TRANSITION_TIME) as u8, interpolate(self.color_buffer[node_id].g as u32, next_color.g as u32, transition_time_elapsed, TRANSITION_TIME) as u8, interpolate(self.color_buffer[node_id].b as u32, next_color.b as u32, transition_time_elapsed, TRANSITION_TIME) as u8, ).as_hex(); for pixel_id in 0 .. LEDS_PER_UNIT { self.driver.set_color(node_id * LEDS_PER_UNIT + pixel_id, color); } } } }, PixelState::MainSequence | PixelState::Loading => { if cycle_time > effect.total_time { self.cycles += 1; self.cycle_offset = nanos() - self.transition_offset; if crate::CYCLE_MODE && self.cycles % 3 == 0 { should_cycle = true; } } for node_id in 0 .. crate::HEX_UNITS { let mut ctx = self.contexts[node_id]; let (effect_time, next_context) = effect.process(&mut ctx, elapsed_ms); let time_t = (( effect_time as f64 / 100.0) * shader.total_time as f64) as uNano; self.color_buffer[node_id] = shader.get_color(time_t); let color = self.color_buffer[node_id].as_hex(); self.contexts[node_id] = next_context; for pixel_id in 0 .. LEDS_PER_UNIT { self.driver.set_color(node_id * LEDS_PER_UNIT + pixel_id, color); } } }, } match self.state { PixelState::MainSequence => { if crate::USE_WIFI && nanos() > self.day_target { let datetime = DateTime::now(); if self.day_processed != datetime.days && datetime.hour >= 6 { self.day_processed = datetime.days; self.randomize(); } self.day_target = nanos() + S_TO_NANO; } else if nanos() > self.randomize_target { self.randomize(); } }, _ => {}, } self.driver.flush(); } if should_cycle { self.cycle_next_shader(); } self.overflow_watch(); } pub fn ready(&mut self) { if !self.ready { self.ready = true; self.randomize(); } } }
use teensycore::*; use teensycore::clock::*; use teensycore::debug::blink_accumulate; use teensycore::math::rand; use teensycore::system::str::Str; use teensycore::system::str::StringOps; use teensycore::system::vector::Array; use teensycore::system::vector::Vector; use crate::date_time::DateTime; use crate::get_shader_configs; use crate::get_tranasition_delay; use crate::shaders::*; use crate::effects::*; use crate::pixel_engine::color::*; use crate::pixel_engine::math::interpolate; use crate::pixel_engine::shader::*; use crate::pixel_engine::effect::*; use crate::pixel_engine::context::*; use crate::drivers::ws2812::*; const LEDS_PER_UNIT: usize = 3; const LEDS: usize = crate::HEX_UNITS * LEDS_PER_UNIT; const TRANSITION_TIME: uNano = 1000 * crate::WORLD_MUTIPLIER; enum PixelState { Loading, Transitioning, MainSequence, } pub struct PixelTask { state: PixelState, shader: Option<Shader>, next_shader: Option<Shader>, shaders: Vector<Shader>, contexts: [Context; crate::HEX_UNITS], effect: Option<Effect>, effects: Vector<Effect>, driver: WS2812Driver<LEDS>, target: uNano, day_target: uNano, day_processed: uNano, cycles: u64, randomize_target: uNano, ready: bool, color_buffer: [Color; crate::HEX_UNITS], transition_start: uNano, transition_offset: uNano, cycle_offset: uNano, } impl PixelTask { pub fn new() -> Self { return PixelTask { state: PixelState::Loading, target: 0, day_target: 0, randomize_target: 0, day_processed: 0, transition_start: 0, transition_offset: 0, cycle_offset: 0, cycles: 0, ready: false, shader: None, effect: None, next_shader: None, shaders: initialize_shaders(), effects: initialize_effects(), driver: WS2812Driver::<LEDS>::new( 18, ), color_buffer: [Color::blank(); crate::HEX_UNITS], contexts: [Context::empty(); crate::HEX_UNITS], }; } #[allow(dead_code)] fn find_effect(&self, name: &'static [u8]) -> Option<Effect> { for effect in self.effects.into_iter() { if effect.name == name { return Some(effect); } } return None; } fn find_shader(&self, name: &Str) -> Option<Shader> { for shader in self.shaders.into_iter() { let mut shader_name = Str::new(); shader_name.append(shader.name); if name.contains(&shader_name) { shader_name.drop(); return Some(shader); } shader_name.drop(); } return None; } fn cycle_next_shader(&mut self) { let idx = (self.cycles / 3) as usize % self.shaders.size(); let shader = self.shaders.get(idx).unwrap(); self.transition_to(shader); } fn get_next_shader(&self) -> Shader {
fn get_next_effect(&self, shader: &Shader) -> Effect { let idx = rand() % self.effects.size() as u64; let next_effect = self.effects.get(idx as usize).unwrap(); if next_effect.disabled || next_effect.max_color_segments.unwrap_or(usize::MAX) < shader.total_segments || next_effect.min_hex_units.unwrap_or(0) > crate::HEX_UNITS { return self.get_next_effect(shader); } else { return next_effect; } } pub fn init(&mut self) { self.driver.init(); for node_id in 0 .. crate::HEX_UNITS { self.contexts[node_id].node_id = node_id as uNano; self.contexts[node_id].total_nodes = crate::HEX_UNITS as uNano; self.contexts[node_id].initialized = false; } self.day_target = nanos() + (S_TO_NANO * 60 * 30); self.shader = self.find_shader(&str!(b"Medbay")); self.effect = Some(self.find_effect(b"Randomized").unwrap()); } pub fn transition_to(&mut self, next_shader: Shader) { self.next_shader = Some(next_shader); for node_id in 0 .. crate::HEX_UNITS { self.contexts[node_id].initialized = false; self.contexts[node_id].node_id = node_id as uNano; } self.effect = Some(self.get_next_effect(&next_shader)); self.transition_start = nanos(); self.transition_offset = 0; self.state = PixelState::Transitioning; } pub fn randomize(&mut self) { self.randomize_target = nanos() + get_tranasition_delay(); self.transition_to(self.get_next_shader()); } /* This method will reset variables if the world uptime counter overflows. */ pub fn overflow_watch(&mut self) { let now = nanos(); if self.transition_offset > 0 && self.transition_start > 0 && self.randomize_target > 0 && ( now < self.transition_offset || now < self.transition_start ) { self.randomize(); } } pub fn system_loop(&mut self) { let time = nanos() - self.transition_offset; let cycle_time = (time - self.cycle_offset) / teensycore::MS_TO_NANO; let elapsed_ms = time / teensycore::MS_TO_NANO; let mut should_cycle = false; if time > self.target { let shader = self.shader.as_mut().unwrap(); let effect = self.effect.as_mut().unwrap(); match self.state { PixelState::Transitioning => { if time > (self.transition_start + TRANSITION_TIME * MS_TO_NANO) { self.state = PixelState::MainSequence; self.shader = self.next_shader; self.transition_offset = self.transition_start; } else { for node_id in 0 .. crate::HEX_UNITS { let mut ctx = self.contexts[node_id]; let next_shader = self.next_shader.as_mut().unwrap(); let transition_time_elapsed = (time - self.transition_start) / MS_TO_NANO; let (effect_time, next_context) = effect.process(&mut ctx, transition_time_elapsed); let time_t = ((effect_time as f64 / 100.0) * next_shader.total_time as f64) as uNano; let next_color = next_shader.get_color(time_t); self.contexts[node_id] = next_context; let color = rgb( interpolate(self.color_buffer[node_id].r as u32, next_color.r as u32, transition_time_elapsed, TRANSITION_TIME) as u8, interpolate(self.color_buffer[node_id].g as u32, next_color.g as u32, transition_time_elapsed, TRANSITION_TIME) as u8, interpolate(self.color_buffer[node_id].b as u32, next_color.b as u32, transition_time_elapsed, TRANSITION_TIME) as u8, ).as_hex(); for pixel_id in 0 .. LEDS_PER_UNIT { self.driver.set_color(node_id * LEDS_PER_UNIT + pixel_id, color); } } } }, PixelState::MainSequence | PixelState::Loading => { if cycle_time > effect.total_time { self.cycles += 1; self.cycle_offset = nanos() - self.transition_offset; if crate::CYCLE_MODE && self.cycles % 3 == 0 { should_cycle = true; } } for node_id in 0 .. crate::HEX_UNITS { let mut ctx = self.contexts[node_id]; let (effect_time, next_context) = effect.process(&mut ctx, elapsed_ms); let time_t = (( effect_time as f64 / 100.0) * shader.total_time as f64) as uNano; self.color_buffer[node_id] = shader.get_color(time_t); let color = self.color_buffer[node_id].as_hex(); self.contexts[node_id] = next_context; for pixel_id in 0 .. LEDS_PER_UNIT { self.driver.set_color(node_id * LEDS_PER_UNIT + pixel_id, color); } } }, } match self.state { PixelState::MainSequence => { if crate::USE_WIFI && nanos() > self.day_target { let datetime = DateTime::now(); if self.day_processed != datetime.days && datetime.hour >= 6 { self.day_processed = datetime.days; self.randomize(); } self.day_target = nanos() + S_TO_NANO; } else if nanos() > self.randomize_target { self.randomize(); } }, _ => {}, } self.driver.flush(); } if should_cycle { self.cycle_next_shader(); } self.overflow_watch(); } pub fn ready(&mut self) { if !self.ready { self.ready = true; self.randomize(); } } }
if crate::USE_WIFI { let appropriate_shader = get_shader_configs().get_shader(crate::get_world_time()); match self.find_shader(&appropriate_shader) { None => return self.shaders.get(0).unwrap(), Some(shader) => { if shader.disabled { return self.get_next_shader(); } return shader; } } } else { let idx = rand() % self.shaders.size() as u64; let next_shader = self.shaders.get(idx as usize).unwrap(); if next_shader.wifi_only || next_shader.disabled { return self.get_next_shader(); } else { return next_shader; } } }
function_block-function_prefix_line
[ { "content": "pub fn parse_http_request(rx_buffer: &Str, header: &mut Str, content: &mut Str) -> bool {\n\n // Ensure buffers are setup\n\n header.clear();\n\n content.clear();\n\n\n\n debug_str(b\"HELLO YES THIS IS DOG\");\n\n \n\n let mut content_length_cmp = str!(b\"Content-Length: \");\n\n...
Rust
src/lib.rs
tickbh/td_rthreadpool
d7f23f07b56777afdef2e3c89324339d2ee97a32
extern crate libc; use std::panic; use std::panic::AssertUnwindSafe; use std::sync::mpsc::{channel, Sender, Receiver, SyncSender, sync_channel, RecvError}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; mod mutex; pub use mutex::{ReentrantMutex, ReentrantMutexGuard}; trait FnBox { fn call_box(self: Box<Self>); } impl<F: FnOnce()> FnBox for F { fn call_box(self: Box<F>) { (*self)() } } type Thunk<'a> = Box<FnBox + Send + 'a>; enum Message { NewJob(Thunk<'static>), Join, } pub struct ThreadPool { threads: Vec<ThreadData>, job_sender: Sender<Message>, job_receiver: Arc<Mutex<Receiver<Message>>>, active_count: Arc<Mutex<usize>>, max_count: Arc<Mutex<usize>>, name: String, } struct ThreadData { _thread_join_handle: JoinHandle<()>, pool_sync_rx: Receiver<()>, thread_sync_tx: SyncSender<()>, } fn create_thread(job_receiver: Arc<Mutex<Receiver<Message>>>, active_count: Arc<Mutex<usize>>, name: String) -> ThreadData { let job_receiver = job_receiver.clone(); let (pool_sync_tx, pool_sync_rx) = sync_channel::<()>(0); let (thread_sync_tx, thread_sync_rx) = sync_channel::<()>(0); let thread = thread::Builder::new() .name(name) .spawn(move || { loop { let result = panic::catch_unwind(AssertUnwindSafe(|| { let message = { let lock = job_receiver.lock().unwrap(); lock.recv() }; match message { Ok(Message::NewJob(job)) => { *active_count.lock().unwrap() += 1; job.call_box(); *active_count.lock().unwrap() -= 1; } Ok(Message::Join) => { if pool_sync_tx.send(()).is_err() { return; } if thread_sync_rx.recv().is_err() { return; } } Err(..) => { return; } } })); if result.is_err() { println!("thread error is {:?}", result); } } }) .ok() .unwrap(); ThreadData { _thread_join_handle: thread, pool_sync_rx: pool_sync_rx, thread_sync_tx: thread_sync_tx, } } impl ThreadPool { pub fn new(n: usize) -> ThreadPool { Self::new_with_name(n, "unknow".to_string()) } pub fn new_with_name(n: usize, name: String) -> ThreadPool { assert!(n >= 1); let (job_sender, job_receiver) = channel(); let job_receiver = Arc::new(Mutex::new(job_receiver)); let active_count = Arc::new(Mutex::new(0)); let max_count = Arc::new(Mutex::new(n as usize)); let mut threads = Vec::with_capacity(n as usize); for _ in 0..n { let thread = create_thread(job_receiver.clone(), active_count.clone(), name.clone()); threads.push(thread); } ThreadPool { threads: threads, job_sender: job_sender, job_receiver: job_receiver.clone(), active_count: active_count, max_count: max_count, name: name, } } pub fn thread_count(&self) -> usize { self.threads.len() } pub fn execute<F>(&self, job: F) where F: FnOnce() + Send + 'static { self.job_sender.send(Message::NewJob(Box::new(job))).unwrap(); } pub fn join_all(&self) { for _ in 0..self.threads.len() { self.job_sender.send(Message::Join).unwrap(); } let mut worker_panic = false; for thread_data in &self.threads { if let Err(RecvError) = thread_data.pool_sync_rx.recv() { worker_panic = true; } } if worker_panic { panic!("Thread pool worker panicked"); } for thread_data in &self.threads { thread_data.thread_sync_tx.send(()).unwrap(); } } pub fn active_count(&self) -> usize { *self.active_count.lock().unwrap() } pub fn max_count(&self) -> usize { *self.max_count.lock().unwrap() } pub fn set_threads(&mut self, threads: usize) -> i32 { assert!(threads >= 1); if threads <= self.thread_count() { return -1; } for _ in 0..(threads - self.thread_count()) { let thread = create_thread(self.job_receiver.clone(), self.active_count.clone(), self.name.clone()); self.threads.push(thread); } *self.max_count.lock().unwrap() = threads; 0 } }
extern crate libc; use std::panic; use std::panic::AssertUnwindSafe; use std::sync::mpsc::{channel, Sender, Receiver, SyncSender, sync_channel, RecvError}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; mod mutex; pub use mutex::{ReentrantMutex, ReentrantMutexGuard}; trait FnBox { fn call_box(self: Box<Self>); } impl<F: FnOnce()> FnBox for F { fn call_box(self: Box<F>) { (*self)() } } type Thunk<'a> = Box<FnBox + Send + 'a>; enum Message { NewJob(Thunk<'static>), Join, } pub struct ThreadPool { threads: Vec<ThreadData>, job_sender: Sender<Message>, job_receiver: Arc<Mutex<Receiver<Message>>>, active_count: Arc<Mutex<usize>>, max_count: Arc<Mutex<usize>>, name: String, } struct ThreadData { _thread_join_handle: JoinHandle<()>, pool_sync_rx: Receiver<()>, thread_sync_tx: SyncSender<()>, } fn create_thread(job_receiver: Arc<Mutex<Receiver<Message>>>, active_count: Arc<Mutex<usize>>, name: String) -> ThreadData { let job_receiver = job_receiver.clone(); let (pool_sync_tx, pool_sync_rx) = sync_channel::<()>(0); let (thread_sync_tx, thread_sync_rx) = sync_channel::<()>(0); let thread = thread::Builder::new() .name(name)
{ return; } } Err(..) => { return; } } })); if result.is_err() { println!("thread error is {:?}", result); } } }) .ok() .unwrap(); ThreadData { _thread_join_handle: thread, pool_sync_rx: pool_sync_rx, thread_sync_tx: thread_sync_tx, } } impl ThreadPool { pub fn new(n: usize) -> ThreadPool { Self::new_with_name(n, "unknow".to_string()) } pub fn new_with_name(n: usize, name: String) -> ThreadPool { assert!(n >= 1); let (job_sender, job_receiver) = channel(); let job_receiver = Arc::new(Mutex::new(job_receiver)); let active_count = Arc::new(Mutex::new(0)); let max_count = Arc::new(Mutex::new(n as usize)); let mut threads = Vec::with_capacity(n as usize); for _ in 0..n { let thread = create_thread(job_receiver.clone(), active_count.clone(), name.clone()); threads.push(thread); } ThreadPool { threads: threads, job_sender: job_sender, job_receiver: job_receiver.clone(), active_count: active_count, max_count: max_count, name: name, } } pub fn thread_count(&self) -> usize { self.threads.len() } pub fn execute<F>(&self, job: F) where F: FnOnce() + Send + 'static { self.job_sender.send(Message::NewJob(Box::new(job))).unwrap(); } pub fn join_all(&self) { for _ in 0..self.threads.len() { self.job_sender.send(Message::Join).unwrap(); } let mut worker_panic = false; for thread_data in &self.threads { if let Err(RecvError) = thread_data.pool_sync_rx.recv() { worker_panic = true; } } if worker_panic { panic!("Thread pool worker panicked"); } for thread_data in &self.threads { thread_data.thread_sync_tx.send(()).unwrap(); } } pub fn active_count(&self) -> usize { *self.active_count.lock().unwrap() } pub fn max_count(&self) -> usize { *self.max_count.lock().unwrap() } pub fn set_threads(&mut self, threads: usize) -> i32 { assert!(threads >= 1); if threads <= self.thread_count() { return -1; } for _ in 0..(threads - self.thread_count()) { let thread = create_thread(self.job_receiver.clone(), self.active_count.clone(), self.name.clone()); self.threads.push(thread); } *self.max_count.lock().unwrap() = threads; 0 } }
.spawn(move || { loop { let result = panic::catch_unwind(AssertUnwindSafe(|| { let message = { let lock = job_receiver.lock().unwrap(); lock.recv() }; match message { Ok(Message::NewJob(job)) => { *active_count.lock().unwrap() += 1; job.call_box(); *active_count.lock().unwrap() -= 1; } Ok(Message::Join) => { if pool_sync_tx.send(()).is_err() { return; } if thread_sync_rx.recv().is_err()
random
[ { "content": "#[test]\n\nfn join_all_with_thread_panic() {\n\n let mut pool = ThreadPool::new(TEST_TASKS);\n\n for _ in 0..4 {\n\n pool.execute(move || {\n\n panic!();\n\n });\n\n }\n\n\n\n sleep(Duration::from_millis(1000));\n\n\n\n let active_count = pool.active_count()...
Rust
tests/asm.rs
jonas-schievink/x87
c24fe7ee4fd51ebb8411187a7e200bd80c9ea87c
#![feature(asm, untagged_unions)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[macro_use] extern crate x87; #[macro_use] extern crate proptest; extern crate env_logger; extern crate ieee754; use x87::{X87State, f80}; use ieee754::Ieee754; union X87StateUnion { raw: [u8; 108], structured: X87State, } #[test] fn meta() { let mut backup = X87StateUnion { raw: [0; 108] }; let mut state = X87StateUnion { raw: [0; 108] }; unsafe { asm!(r" fnsave $0 fld1 fnsave $1 frstor $0 " : "=*m"(&mut backup.raw), "=*m"(&mut state.raw) :: "memory"); } let state2 = run_host_asm!("fld1" :); assert_eq!(unsafe { state.structured.scrub() }, state2); } #[test] fn add_f64_double_round_wrong() { let lhs = f64::from_bits(964674174654497230); let rhs = f64::from_bits(10131472521302454270); let mut result80 = 0.0f64; run_host_asm!(r" fldl $1 fldl $2 faddp fstpl $0 " : "=*m"(&mut result80), "=*m"(&lhs), "=*m"(&rhs)); println!("{}+{}={}", lhs, rhs, result80); let result64 = lhs + rhs; assert_eq!(result64.to_bits(), result80.to_bits() + 1, "host FPU returned wrong result"); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80sum = l80 + r80; let f80bits = f80sum.to_f64().to_bits(); assert_eq!(result80.to_bits(), f80bits, "host FPU != emulation result"); } fn add32(lhs_bits: u32, rhs_bits: u32) { let (lhs, rhs) = (f32::from_bits(lhs_bits), f32::from_bits(rhs_bits)); let mut native_f32_sum = 0.0f32; let mut native_f80_sum = [0u8; 10]; run_host_asm!(r" flds $1 flds $0 faddp fsts $2 fstpt $3 " : "=*m"(&lhs), "=*m"(&rhs), "=*m"(&mut native_f32_sum), "=*m"(&mut native_f80_sum)); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80sum = l80 + r80; let f80_f32bits = f80sum.to_f32().to_bits(); let f80native = f80::from_bytes(native_f80_sum); assert_eq!( f80_f32bits, native_f32_sum.to_bits(), "f32 sum mismatch: x87:{}={:?}={:#010X}={:?}, native:{}={:?}={:#010X}={:?}", f80sum.to_f32(), f80sum.to_f32().classify(), f80_f32bits, f80sum.to_f32().decompose(), native_f32_sum, native_f32_sum.classify(), native_f32_sum.to_bits(), native_f32_sum.decompose(), ); assert_eq!( f80sum.to_bytes(), native_f80_sum, "f80 sum mismatch: x87:{:?}={:?}, native:{:?}={:?}", f80sum, f80sum.classify(), f80native, f80native.classify(), ); } fn sub32(lhs_bits: u32, rhs_bits: u32) { let (lhs, rhs) = (f32::from_bits(lhs_bits), f32::from_bits(rhs_bits)); let mut native_f32_diff = 0.0f32; let mut native_f80_diff = [0u8; 10]; run_host_asm!(r" flds $1 flds $0 fsubp fsts $2 fstpt $3 " : "=*m"(&lhs), "=*m"(&rhs), "=*m"(&mut native_f32_diff), "=*m"(&mut native_f80_diff)); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80diff = l80 - r80; let f80_f32bits = f80diff.to_f32().to_bits(); let f80native = f80::from_bytes(native_f80_diff); assert_eq!( f80_f32bits, native_f32_diff.to_bits(), "f32 sum mismatch: x87:{}={:?}={:#010X}={:?}, native:{}={:?}={:#010X}={:?}", f80diff.to_f32(), f80diff.to_f32().classify(), f80_f32bits, f80diff.to_f32().decompose(), native_f32_diff, native_f32_diff.classify(), native_f32_diff.to_bits(), native_f32_diff.decompose(), ); assert_eq!( f80diff.to_bytes(), native_f80_diff, "f80 sum mismatch: x87:{:?}={:?}, native:{:?}={:?}", f80diff, f80diff.classify(), f80native, f80native.classify(), ); } fn mul32(lhs_bits: u32, rhs_bits: u32) { let (lhs, rhs) = (f32::from_bits(lhs_bits), f32::from_bits(rhs_bits)); let mut native_f32_prod = 0.0f32; let mut native_f80_prod = [0u8; 10]; run_host_asm!(r" flds $1 flds $0 fmulp fsts $2 fstpt $3 " : "=*m"(&lhs), "=*m"(&rhs), "=*m"(&mut native_f32_prod), "=*m"(&mut native_f80_prod)); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80prod = l80 * r80; let f80_f32bits = f80prod.to_f32().to_bits(); let f80native = f80::from_bytes(native_f80_prod); assert_eq!( f80_f32bits, native_f32_prod.to_bits(), "f32 product mismatch: x87:{}={:?}={:#010X}={:?}, native:{}={:?}={:#010X}={:?}", f80prod.to_f32(), f80prod.to_f32().classify(), f80_f32bits, f80prod.to_f32().decompose(), native_f32_prod, native_f32_prod.classify(), native_f32_prod.to_bits(), native_f32_prod.decompose(), ); assert_eq!( f80prod.to_bytes(), native_f80_prod, "f80 product mismatch: x87:{:?}={:?}, native:{:?}={:?}", f80prod, f80prod.classify(), f80native, f80native.classify(), ); } #[test] fn f32_add_nan_payload() { env_logger::try_init().ok(); add32(2139095041, 0); } #[test] fn nan_propagation() { env_logger::try_init().ok(); add32(0xff800002, 0x7f800001); add32(0x7f800002, 0xff800001); add32(0xff800002, 0xff800001); add32(0x7f800002, 0x7f800001); add32(0xff800001, 0x7f800002); add32(0x7f800001, 0xff800002); add32(0xff800001, 0xff800002); add32(0x7f800001, 0x7f800002); } #[test] fn rounding_affects_integer_bits() { env_logger::try_init().ok(); add32(1, 3976200192); } #[test] fn to_f32_postnormalizes() { env_logger::try_init().ok(); add32(3120562177, 1518338048); } #[test] fn addition_doesnt_create_signed_zero() { env_logger::try_init().ok(); add32(54623649, 2202107297); } #[test] fn infinities() { let pinf: f32 = 1.0/0.0; let minf: f32 = -1.0/0.0; add32(pinf.to_bits(), pinf.to_bits()); add32(minf.to_bits(), minf.to_bits()); add32(minf.to_bits(), pinf.to_bits()); add32(pinf.to_bits(), minf.to_bits()); } #[test] fn zero_exponent() { env_logger::try_init().ok(); add32(2147483649, 0); } #[test] fn zero_minus_nan() { env_logger::try_init().ok(); sub32(0, 2139095041); } #[test] fn mul_denormal_zero() { env_logger::try_init().ok(); mul32(0, 1); mul32(1, 0); } #[test] fn mul_f32_denormals() { env_logger::try_init().ok(); mul32(1, 3); } #[test] #[ignore] fn mul_rounding_denormal_result() { env_logger::try_init().ok(); mul32(2496593444, 706412423); } proptest! { #[test] fn add_f32(lhs_bits: u32, rhs_bits: u32) { add32(lhs_bits, rhs_bits); } } proptest! { #[test] fn sub_f32(lhs_bits: u32, rhs_bits: u32) { sub32(lhs_bits, rhs_bits); } } proptest! { #[test] fn mul_f32(lhs_bits: u32, rhs_bits: u32) { mul32(lhs_bits, rhs_bits); } }
#![feature(asm, untagged_unions)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[macro_use] extern crate x87; #[macro_use] extern crate proptest; extern crate env_logger; extern crate ieee754; use x87::{X87State, f80}; use ieee754::Ieee754; union X87StateUnion { raw: [u8; 108], structured: X87State, } #[test] fn meta() { let mut backup = X87StateUnion { raw: [0; 108] }; let mut state = X87StateUnion { raw: [0; 108] }; unsafe { asm!(r" fnsave $0 fld1 fnsave $1 frstor $0 " : "=*m"(&mut backup.raw), "=*m"(&mut state.raw) :: "memory"); } let state2 = run_host_asm!("fld1" :); assert_eq!(unsafe { state.structured.scrub() }, state2); } #[test] fn add_f64_double_round_wrong() { let lhs = f64::from_bits(964674174654497230); let rhs = f64::from_bits(10131472521302454270); let mut result80 = 0.0f64; run_host_asm!(r" fldl $1 fldl $2 fadd
fn add32(lhs_bits: u32, rhs_bits: u32) { let (lhs, rhs) = (f32::from_bits(lhs_bits), f32::from_bits(rhs_bits)); let mut native_f32_sum = 0.0f32; let mut native_f80_sum = [0u8; 10]; run_host_asm!(r" flds $1 flds $0 faddp fsts $2 fstpt $3 " : "=*m"(&lhs), "=*m"(&rhs), "=*m"(&mut native_f32_sum), "=*m"(&mut native_f80_sum)); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80sum = l80 + r80; let f80_f32bits = f80sum.to_f32().to_bits(); let f80native = f80::from_bytes(native_f80_sum); assert_eq!( f80_f32bits, native_f32_sum.to_bits(), "f32 sum mismatch: x87:{}={:?}={:#010X}={:?}, native:{}={:?}={:#010X}={:?}", f80sum.to_f32(), f80sum.to_f32().classify(), f80_f32bits, f80sum.to_f32().decompose(), native_f32_sum, native_f32_sum.classify(), native_f32_sum.to_bits(), native_f32_sum.decompose(), ); assert_eq!( f80sum.to_bytes(), native_f80_sum, "f80 sum mismatch: x87:{:?}={:?}, native:{:?}={:?}", f80sum, f80sum.classify(), f80native, f80native.classify(), ); } fn sub32(lhs_bits: u32, rhs_bits: u32) { let (lhs, rhs) = (f32::from_bits(lhs_bits), f32::from_bits(rhs_bits)); let mut native_f32_diff = 0.0f32; let mut native_f80_diff = [0u8; 10]; run_host_asm!(r" flds $1 flds $0 fsubp fsts $2 fstpt $3 " : "=*m"(&lhs), "=*m"(&rhs), "=*m"(&mut native_f32_diff), "=*m"(&mut native_f80_diff)); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80diff = l80 - r80; let f80_f32bits = f80diff.to_f32().to_bits(); let f80native = f80::from_bytes(native_f80_diff); assert_eq!( f80_f32bits, native_f32_diff.to_bits(), "f32 sum mismatch: x87:{}={:?}={:#010X}={:?}, native:{}={:?}={:#010X}={:?}", f80diff.to_f32(), f80diff.to_f32().classify(), f80_f32bits, f80diff.to_f32().decompose(), native_f32_diff, native_f32_diff.classify(), native_f32_diff.to_bits(), native_f32_diff.decompose(), ); assert_eq!( f80diff.to_bytes(), native_f80_diff, "f80 sum mismatch: x87:{:?}={:?}, native:{:?}={:?}", f80diff, f80diff.classify(), f80native, f80native.classify(), ); } fn mul32(lhs_bits: u32, rhs_bits: u32) { let (lhs, rhs) = (f32::from_bits(lhs_bits), f32::from_bits(rhs_bits)); let mut native_f32_prod = 0.0f32; let mut native_f80_prod = [0u8; 10]; run_host_asm!(r" flds $1 flds $0 fmulp fsts $2 fstpt $3 " : "=*m"(&lhs), "=*m"(&rhs), "=*m"(&mut native_f32_prod), "=*m"(&mut native_f80_prod)); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80prod = l80 * r80; let f80_f32bits = f80prod.to_f32().to_bits(); let f80native = f80::from_bytes(native_f80_prod); assert_eq!( f80_f32bits, native_f32_prod.to_bits(), "f32 product mismatch: x87:{}={:?}={:#010X}={:?}, native:{}={:?}={:#010X}={:?}", f80prod.to_f32(), f80prod.to_f32().classify(), f80_f32bits, f80prod.to_f32().decompose(), native_f32_prod, native_f32_prod.classify(), native_f32_prod.to_bits(), native_f32_prod.decompose(), ); assert_eq!( f80prod.to_bytes(), native_f80_prod, "f80 product mismatch: x87:{:?}={:?}, native:{:?}={:?}", f80prod, f80prod.classify(), f80native, f80native.classify(), ); } #[test] fn f32_add_nan_payload() { env_logger::try_init().ok(); add32(2139095041, 0); } #[test] fn nan_propagation() { env_logger::try_init().ok(); add32(0xff800002, 0x7f800001); add32(0x7f800002, 0xff800001); add32(0xff800002, 0xff800001); add32(0x7f800002, 0x7f800001); add32(0xff800001, 0x7f800002); add32(0x7f800001, 0xff800002); add32(0xff800001, 0xff800002); add32(0x7f800001, 0x7f800002); } #[test] fn rounding_affects_integer_bits() { env_logger::try_init().ok(); add32(1, 3976200192); } #[test] fn to_f32_postnormalizes() { env_logger::try_init().ok(); add32(3120562177, 1518338048); } #[test] fn addition_doesnt_create_signed_zero() { env_logger::try_init().ok(); add32(54623649, 2202107297); } #[test] fn infinities() { let pinf: f32 = 1.0/0.0; let minf: f32 = -1.0/0.0; add32(pinf.to_bits(), pinf.to_bits()); add32(minf.to_bits(), minf.to_bits()); add32(minf.to_bits(), pinf.to_bits()); add32(pinf.to_bits(), minf.to_bits()); } #[test] fn zero_exponent() { env_logger::try_init().ok(); add32(2147483649, 0); } #[test] fn zero_minus_nan() { env_logger::try_init().ok(); sub32(0, 2139095041); } #[test] fn mul_denormal_zero() { env_logger::try_init().ok(); mul32(0, 1); mul32(1, 0); } #[test] fn mul_f32_denormals() { env_logger::try_init().ok(); mul32(1, 3); } #[test] #[ignore] fn mul_rounding_denormal_result() { env_logger::try_init().ok(); mul32(2496593444, 706412423); } proptest! { #[test] fn add_f32(lhs_bits: u32, rhs_bits: u32) { add32(lhs_bits, rhs_bits); } } proptest! { #[test] fn sub_f32(lhs_bits: u32, rhs_bits: u32) { sub32(lhs_bits, rhs_bits); } } proptest! { #[test] fn mul_f32(lhs_bits: u32, rhs_bits: u32) { mul32(lhs_bits, rhs_bits); } }
p fstpl $0 " : "=*m"(&mut result80), "=*m"(&lhs), "=*m"(&rhs)); println!("{}+{}={}", lhs, rhs, result80); let result64 = lhs + rhs; assert_eq!(result64.to_bits(), result80.to_bits() + 1, "host FPU returned wrong result"); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80sum = l80 + r80; let f80bits = f80sum.to_f64().to_bits(); assert_eq!(result80.to_bits(), f80bits, "host FPU != emulation result"); }
function_block-function_prefixed
[]
Rust
05_recon/src/types.rs
lazear/types-and-programming-languages
0787493713b41639878db206e76d82fa8f29a77a
use std::collections::{HashMap, HashSet, VecDeque}; #[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Hash)] pub struct TypeVar(pub u32, pub u32); #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Hash)] pub struct Tycon { id: usize, arity: usize, } #[derive(Clone, PartialEq, PartialOrd, Eq, Hash)] pub enum Type { Var(TypeVar), Con(Tycon, Vec<Type>), } #[derive(Debug, Clone)] pub enum Scheme { Mono(Type), Poly(Vec<TypeVar>, Type), } pub trait Substitution { fn ftv(&self) -> HashSet<TypeVar>; fn apply(self, s: &HashMap<TypeVar, Type>) -> Self; } impl Substitution for Type { fn ftv(&self) -> HashSet<TypeVar> { let mut set = HashSet::new(); let mut queue = VecDeque::new(); queue.push_back(self); while let Some(ty) = queue.pop_front() { match ty { Type::Var(x) => { set.insert(*x); } Type::Con(_, tys) => { for ty in tys { queue.push_back(ty); } } } } set } fn apply(self, map: &HashMap<TypeVar, Type>) -> Type { match self { Type::Var(x) => map.get(&x).cloned().unwrap_or(Type::Var(x)), Type::Con(tc, vars) => Type::Con(tc, vars.into_iter().map(|ty| ty.apply(map)).collect()), } } } impl Type { pub fn arrow(a: Type, b: Type) -> Type { Type::Con(T_ARROW, vec![a, b]) } pub fn bool() -> Type { Type::Con(T_BOOL, vec![]) } pub fn occurs(&self, exist: TypeVar) -> bool { match self { Type::Var(x) => *x == exist, Type::Con(_, tys) => tys.iter().any(|ty| ty.occurs(exist)), } } pub fn de_arrow(&self) -> (&Type, &Type) { match self { Type::Con(T_ARROW, v) => (&v[0], &v[1]), _ => panic!("Not arrow type! {:?}", self), } } } pub fn compose(s1: HashMap<TypeVar, Type>, s2: HashMap<TypeVar, Type>) -> HashMap<TypeVar, Type> { let mut s2 = s2 .into_iter() .map(|(k, v)| (k, v.apply(&s1))) .collect::<HashMap<TypeVar, Type>>(); for (k, v) in s1 { if !s2.contains_key(&k) { s2.insert(k, v); } } s2 } impl Substitution for Scheme { fn ftv(&self) -> HashSet<TypeVar> { match self { Scheme::Mono(ty) => ty.ftv(), Scheme::Poly(vars, ty) => ty.ftv(), } } fn apply(self, map: &HashMap<TypeVar, Type>) -> Scheme { match self { Scheme::Mono(ty) => Scheme::Mono(ty.apply(map)), Scheme::Poly(vars, ty) => { let mut map: HashMap<TypeVar, Type> = map.clone(); for v in &vars { map.remove(v); } Scheme::Poly(vars, ty.apply(&map)) } } } } pub const T_ARROW: Tycon = Tycon { id: 0, arity: 2 }; pub const T_INT: Tycon = Tycon { id: 1, arity: 0 }; pub const T_UNIT: Tycon = Tycon { id: 2, arity: 0 }; pub const T_BOOL: Tycon = Tycon { id: 3, arity: 0 }; impl std::fmt::Debug for Tycon { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self.id { 0 => write!(f, "->"), 1 => write!(f, "int"), 2 => write!(f, "unit"), 3 => write!(f, "bool"), _ => write!(f, "??"), } } } fn fresh_name(x: u32) -> String { let last = ((x % 26) as u8 + 'a' as u8) as char; (0..x / 26) .map(|_| 'z') .chain(std::iter::once(last)) .collect::<String>() } impl std::fmt::Debug for TypeVar { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str(&fresh_name(self.0)) } } impl std::fmt::Debug for Type { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Type::Var(x) => write!(f, "{:?}", x), Type::Con(T_ARROW, tys) => write!(f, "({:?} -> {:?})", tys[0], tys[1]), Type::Con(tc, _) => write!(f, "{:?}", tc,), } } }
use std::collections::{HashMap, HashSet, VecDeque}; #[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Hash)] pub struct TypeVar(pub u32, pub u32); #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Hash)] pub struct Tycon { id: usize, arity: usize, } #[derive(Clone, PartialEq, PartialOrd, Eq, Hash)] pub enum Type { Var(TypeVar), Con(Tycon, Vec<Type>), } #[derive(Debug, Clone)] pub enum Scheme { Mono(Type), Poly(Vec<TypeVar>, Type), } pub trait Substitution { fn ftv(&self) -> HashSet<TypeVar>; fn apply(self, s: &HashMap<TypeVar, Type>) -> Self; } impl Substitution for Type { fn ftv(&self) -> HashSet<TypeVar> { let mut set = HashSet::new(); let mut queue = VecDeque::new(); queue.push_back(self); while let Some(ty) = queue.pop_front() { match ty { Type::Var(x) => { set.insert(*x); } Type::Con(_, tys) => { for ty in tys { queue.push_back(ty); } } } } set } fn apply(self, map: &HashMap<TypeVar, Type>) -> Type { match self { Type::Var(x) => map.get(&x).cloned().unwrap_or(Type::Var(x)), Type::Con(tc, vars) => Type::Con(tc, vars.into_iter().map(|ty| ty.apply(map)).collect()), } } } impl Type { pub fn arrow(a: Type, b: Type) -> Type { Type::Con(T_ARROW, vec![a, b]) } pub fn bool() -> Type { Type::Con(T_BOOL, vec![]) } pub fn occurs(&self, exist: TypeVar) -> bool { match self { Type::Var(x) => *x == exist, Type::Con(_, tys) => tys.iter().any(|ty| ty.occurs(exist)), } } pub fn de_arrow(&self) -> (&Type, &Type) { match self { Type::Con(T_ARROW, v) => (&v[0], &v[1]), _ => panic!("Not arrow type! {:?}", self), } } } pub fn compose(s1: HashMap<TypeVar, Type>, s2: HashMap<TypeVar, Type>) -> HashMap<TypeVar, Type> { let mut s2 = s2 .into_iter() .map(|(k, v)| (k, v.apply(&s1))) .collect::<HashMap<TypeVar, Type>>(); for (k, v) in s1 { if !s2.contains_key(&k) { s2.insert(k, v); } } s2 } impl Substitution for Scheme { fn ftv(&self) -> HashSet<TypeVar> { match self { Scheme::Mono(ty) => ty.ftv(), Scheme::Poly(vars, ty) => ty.ftv(), } } fn apply(self, map: &HashMap<TypeVar, Type>) -> Scheme { match self { Scheme::Mono(ty) => Scheme::Mono(ty.apply(map)), Scheme::Poly(vars, ty) => { let mut map: HashMap<TypeVar, Type> = map.clone(); for v in &vars { map.remove(v); } Scheme::Poly(vars, ty.apply(&map)) } } } } pub const T_ARROW: Tycon = Tycon { id: 0, arity: 2 }; pub const T_INT: Tycon = Tycon { id: 1, arity: 0 }; pub const T_UNIT: Tycon = Tycon { id: 2, arity: 0 }; pub const T_BOOL: Tycon = Tycon { id: 3, arity: 0 }; impl std::fmt::Debug for Tycon { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self.id { 0 => write!(f, "->"), 1 => write!(f, "int"), 2 => write!(f, "unit"), 3 => write!(f, "bool"), _ => write!(f, "??"), } } } fn fresh_name(x: u32) -> String { let last = ((x % 26) as u8 + 'a' as u8
TypeVar { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str(&fresh_name(self.0)) } } impl std::fmt::Debug for Type { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Type::Var(x) => write!(f, "{:?}", x), Type::Con(T_ARROW, tys) => write!(f, "({:?} -> {:?})", tys[0], tys[1]), Type::Con(tc, _) => write!(f, "{:?}", tc,), } } }
) as char; (0..x / 26) .map(|_| 'z') .chain(std::iter::once(last)) .collect::<String>() } impl std::fmt::Debug for
random
[ { "content": "fn var_bind(var: TypeVar, ty: Type) -> Result<HashMap<TypeVar, Type>, String> {\n\n if ty.occurs(var) {\n\n return Err(format!(\"Fails occurs check! {:?} {:?}\", var, ty));\n\n }\n\n let mut sub = HashMap::new();\n\n match ty {\n\n Type::Var(x) if x == var => {}\n\n ...
Rust
circuit/src/execution-delivery/src/lib.rs
xylix/t3rn
fda43863b640fae63988042addadc21a1bfa32de
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use frame_support::traits::Get; use frame_system::offchain::{AppCrypto, CreateSignedTransaction, SignedPayload, SigningTypes}; use sp_core::crypto::KeyTypeId; use sp_runtime::{ transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction}, RuntimeDebug, }; use sp_std::vec::Vec; use t3rn_primitives::*; #[cfg(test)] mod tests; pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"btc!"); pub mod crypto { use super::KEY_TYPE; use sp_core::sr25519::Signature as Sr25519Signature; use sp_runtime::{ app_crypto::{app_crypto, sr25519}, traits::Verify, }; app_crypto!(sr25519, KEY_TYPE); pub struct TestAuthId; impl frame_system::offchain::AppCrypto<<Sr25519Signature as Verify>::Signer, Sr25519Signature> for TestAuthId { type RuntimeAppPublic = Public; type GenericSignature = sp_core::sr25519::Signature; type GenericPublic = sp_core::sr25519::Public; } } pub use pallet::*; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub trait Config: CreateSignedTransaction<Call<Self>> + frame_system::Config { type AuthorityId: AppCrypto<Self::Public, Self::Signature>; type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; type Call: From<Call<Self>>; #[pallet::constant] type GracePeriod: Get<Self::BlockNumber>; #[pallet::constant] type UnsignedInterval: Get<Self::BlockNumber>; #[pallet::constant] type UnsignedPriority: Get<TransactionPriority>; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(_); #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { fn on_initialize(_n: T::BlockNumber) -> Weight { 0 } fn on_finalize(_n: T::BlockNumber) { } fn offchain_worker(_n: T::BlockNumber) { } } #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(0)] pub fn submit_composable_exec_order( origin: OriginFor<T>, io_schedule: Vec<u8>, components: Vec<Compose<T::AccountId, u64>>, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; let inter_schedule: InterExecSchedule<T::AccountId, u64> = Self::decompose_io_schedule(components, io_schedule).expect("Wrong io schedule"); for phase in inter_schedule.phases.clone() { for step in phase.steps { Self::deposit_event(Event::NewPhase(who.clone(), 0, step.compose.name.clone())); } } Ok(().into()) } #[pallet::weight(0)] pub fn dummy_check_payload_origin( origin: OriginFor<T>, _price_payload: Payload<T::Public, T::BlockNumber>, _signature: T::Signature, ) -> DispatchResultWithPostInfo { ensure_none(origin)?; Ok(().into()) } } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { NewPhase(T::AccountId, u8, Vec<u8>), } #[pallet::validate_unsigned] impl<T: Config> ValidateUnsigned for Pallet<T> { type Call = Call<T>; fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { if let Call::dummy_check_payload_origin(ref payload, ref signature) = call { let signature_valid = SignedPayload::<T>::verify::<T::AuthorityId>(payload, signature.clone()); if !signature_valid { return InvalidTransaction::BadProof.into(); } ValidTransaction::with_tag_prefix("BlankTaskOffchainWorker") .longevity(5) .propagate(true) .build() } else { InvalidTransaction::Call.into() } } } } #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] pub struct Payload<Public, BlockNumber> { block_number: BlockNumber, public: Public, } impl<T: SigningTypes> SignedPayload<T> for Payload<T::Public, T::BlockNumber> { fn public(&self) -> T::Public { self.public.clone() } } impl<T: Config> Pallet<T> { #[allow(dead_code)] pub fn say_hello() -> &'static str { "hello" } pub fn decompose_io_schedule( _components: Vec<Compose<T::AccountId, u64>>, _io_schedule: Vec<u8>, ) -> Result<InterExecSchedule<T::AccountId, u64>, &'static str> { let inter_schedule = InterExecSchedule::default(); Ok(inter_schedule) } }
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use frame_support::traits::Get; use frame_system::offchain::{AppCrypto, CreateSignedTransaction, SignedPayload, SigningTypes}; use sp_core::crypto::KeyTypeId; use sp_runtime::{ transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction}, RuntimeDebug, }; use sp_std::vec::Vec; use t3rn_primitives::*; #[cfg(test)] mod tests; pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"btc!"); pub mod crypto { use super::KEY_TYPE; use sp_core::sr25519::Signature as Sr25519Signature; use sp_runtime::{ app_crypto::{app_crypto, sr25519}, traits::Verify, }; app_crypto!(sr25519, KEY_TYPE); pub struct TestAuthId; impl frame_system::offchain::AppCrypto<<Sr25519Signature as Verify>::Signer, Sr25519Signature> for TestAuthId { type RuntimeAppPublic = Public; type GenericSignature = sp_core::sr25519::Signature; type GenericPublic = sp_core::sr25519::Public; } } pub use pallet::*; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub trait Config: CreateSignedTransaction<Call<Self>> + frame_system::Config { type AuthorityId: AppCrypto<Self::Public, Self::Signature>; type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; type Call: From<Call<Self>>; #[pallet::constant] type GracePeriod: Get<Self::BlockNumber>; #[pallet::constant] type UnsignedInterval: Get
ong io schedule"); for phase in inter_schedule.phases.clone() { for step in phase.steps { Self::deposit_event(Event::NewPhase(who.clone(), 0, step.compose.name.clone())); } } Ok(().into()) } #[pallet::weight(0)] pub fn dummy_check_payload_origin( origin: OriginFor<T>, _price_payload: Payload<T::Public, T::BlockNumber>, _signature: T::Signature, ) -> DispatchResultWithPostInfo { ensure_none(origin)?; Ok(().into()) } } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { NewPhase(T::AccountId, u8, Vec<u8>), } #[pallet::validate_unsigned] impl<T: Config> ValidateUnsigned for Pallet<T> { type Call = Call<T>; fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { if let Call::dummy_check_payload_origin(ref payload, ref signature) = call { let signature_valid = SignedPayload::<T>::verify::<T::AuthorityId>(payload, signature.clone()); if !signature_valid { return InvalidTransaction::BadProof.into(); } ValidTransaction::with_tag_prefix("BlankTaskOffchainWorker") .longevity(5) .propagate(true) .build() } else { InvalidTransaction::Call.into() } } } } #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] pub struct Payload<Public, BlockNumber> { block_number: BlockNumber, public: Public, } impl<T: SigningTypes> SignedPayload<T> for Payload<T::Public, T::BlockNumber> { fn public(&self) -> T::Public { self.public.clone() } } impl<T: Config> Pallet<T> { #[allow(dead_code)] pub fn say_hello() -> &'static str { "hello" } pub fn decompose_io_schedule( _components: Vec<Compose<T::AccountId, u64>>, _io_schedule: Vec<u8>, ) -> Result<InterExecSchedule<T::AccountId, u64>, &'static str> { let inter_schedule = InterExecSchedule::default(); Ok(inter_schedule) } }
<Self::BlockNumber>; #[pallet::constant] type UnsignedPriority: Get<TransactionPriority>; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(_); #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { fn on_initialize(_n: T::BlockNumber) -> Weight { 0 } fn on_finalize(_n: T::BlockNumber) { } fn offchain_worker(_n: T::BlockNumber) { } } #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(0)] pub fn submit_composable_exec_order( origin: OriginFor<T>, io_schedule: Vec<u8>, components: Vec<Compose<T::AccountId, u64>>, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; let inter_schedule: InterExecSchedule<T::AccountId, u64> = Self::decompose_io_schedule(components, io_schedule).expect("Wr
random
[ { "content": "#[cfg(not(test))]\n\npub trait TestAuxiliaries {}\n\n#[cfg(not(test))]\n\nimpl<T> TestAuxiliaries for T {}\n\n\n", "file_path": "gateway/pallet-escrow-gateway/escrow-engine/versatile-wasm/src/gas.rs", "rank": 1, "score": 203546.12681136615 }, { "content": "#[cfg(not(test))]\n\n...
Rust
key_config/src/old_key_map.rs
NordGeit/MMAccel
a45b2f8eecb795cb784d3a89be70ee41e60c84a9
use crate::*; use std::io::BufRead; fn str_to_vk(k: &str) -> Option<u32> { match k.trim() { "esc" => Some(VK_ESCAPE.0 as u32), "tab" => Some(VK_TAB.0 as u32), "capslock" => Some(VK_CAPITAL.0 as u32), "shift" => Some(VK_SHIFT.0 as u32), "ctrl" => Some(VK_CONTROL.0 as u32), "alt" => Some(VK_MENU.0 as u32), "backspace" => Some(VK_BACK.0 as u32), "enter" => Some(VK_RETURN.0 as u32), "space" => Some(VK_SPACE.0 as u32), "printscreen" => Some(VK_SNAPSHOT.0 as u32), "pause" => Some(VK_PAUSE.0 as u32), "insert" => Some(VK_INSERT.0 as u32), "delete" => Some(VK_DELETE.0 as u32), "home" => Some(VK_HOME.0 as u32), "end" => Some(VK_END.0 as u32), "pageup" => Some(VK_PRIOR.0 as u32), "pagedown" => Some(VK_NEXT.0 as u32), "up" => Some(VK_UP.0 as u32), "down" => Some(VK_DOWN.0 as u32), "left" => Some(VK_LEFT.0 as u32), "right" => Some(VK_RIGHT.0 as u32), "num+" => Some(VK_ADD.0 as u32), "num-" => Some(VK_SUBTRACT.0 as u32), "num*" => Some(VK_MULTIPLY.0 as u32), "num/" => Some(VK_DIVIDE.0 as u32), "num." => Some(VK_DECIMAL.0 as u32), "-" => Some(VK_OEM_MINUS.0 as u32), ";" => Some(VK_OEM_PLUS.0 as u32), "," => Some(VK_OEM_COMMA.0 as u32), "." => Some(VK_OEM_PERIOD.0 as u32), ":" => Some(VK_OEM_1.0 as u32), "/" => Some(VK_OEM_2.0 as u32), "@" => Some(VK_OEM_3.0 as u32), "[" => Some(VK_OEM_4.0 as u32), "\\" => Some(VK_OEM_5.0 as u32), "]" => Some(VK_OEM_6.0 as u32), "^" => Some(VK_OEM_7.0 as u32), "_" => Some(VK_OEM_102.0 as u32), _ if k.len() == 1 => { let c = k.chars().next().unwrap(); (!c.is_ascii_control()).then(|| c.to_ascii_uppercase() as u32) } _ if k.starts_with("num") => k .trim_matches(|c| !char::is_numeric(c)) .parse() .map(|n: u32| VK_NUMPAD0.0 as u32 + n) .ok(), _ if k.starts_with('f') => k .trim_matches(|c| !char::is_numeric(c)) .parse() .map(|n: u32| VK_F1.0 as u32 + n - 1) .ok(), _ => None, } } #[derive(Debug)] pub struct Item { pub id: String, pub keys: Option<Keys>, } #[derive(Debug)] pub struct OldKeyMap(pub Vec<Item>); impl OldKeyMap { pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, Error> { let file = std::fs::File::open(path)?; let mut reader = std::io::BufReader::new(file); let mut key_map = vec![]; let mut buffer = String::new(); loop { buffer.clear(); if reader.read_line(&mut buffer)? == 0 { break; } if buffer.is_empty() { continue; } if buffer.starts_with('#') { continue; } let ss = buffer.split('=').collect::<Vec<_>>(); if ss.len() != 2 { continue; } let keys = ss[1] .trim() .to_ascii_lowercase() .split('+') .map(|s| str_to_vk(s)) .collect::<Option<Vec<_>>>(); if keys.is_none() { continue; } key_map.push(Item { id: ss[0].trim().to_string(), keys: Some(Keys::from_slice(&keys.unwrap())), }); } Ok(Self(key_map)) } } #[cfg(test)] mod tests { use super::*; #[test] fn load_key_map() { let data = OldKeyMap::from_file("key_map.txt").unwrap(); let prev = data.0.iter().find(|item| item.id == "FramePrev").unwrap(); let mut keys = Keys::new(); keys.vk(b'A' as _); assert!(prev.keys.as_ref().unwrap() == &keys); let next = data.0.iter().find(|item| item.id == "FrameNext").unwrap(); let mut keys = Keys::new(); keys.vk(b'D' as _); assert!(next.keys.as_ref().unwrap() == &keys); } }
use crate::*; use std::io::BufRead; fn str_to_vk(k: &str) -> Option<u32> { match k.trim() { "esc" => Some(VK_ESCAPE.0 as u32), "tab" => Some(VK_TAB.0 as u32), "capslock" => Some(VK_CAPITAL.0 as u32), "shift" => Some(VK_SHIFT.0 as u32), "ctrl" => Some(VK_CO
wrap(); let prev = data.0.iter().find(|item| item.id == "FramePrev").unwrap(); let mut keys = Keys::new(); keys.vk(b'A' as _); assert!(prev.keys.as_ref().unwrap() == &keys); let next = data.0.iter().find(|item| item.id == "FrameNext").unwrap(); let mut keys = Keys::new(); keys.vk(b'D' as _); assert!(next.keys.as_ref().unwrap() == &keys); } }
NTROL.0 as u32), "alt" => Some(VK_MENU.0 as u32), "backspace" => Some(VK_BACK.0 as u32), "enter" => Some(VK_RETURN.0 as u32), "space" => Some(VK_SPACE.0 as u32), "printscreen" => Some(VK_SNAPSHOT.0 as u32), "pause" => Some(VK_PAUSE.0 as u32), "insert" => Some(VK_INSERT.0 as u32), "delete" => Some(VK_DELETE.0 as u32), "home" => Some(VK_HOME.0 as u32), "end" => Some(VK_END.0 as u32), "pageup" => Some(VK_PRIOR.0 as u32), "pagedown" => Some(VK_NEXT.0 as u32), "up" => Some(VK_UP.0 as u32), "down" => Some(VK_DOWN.0 as u32), "left" => Some(VK_LEFT.0 as u32), "right" => Some(VK_RIGHT.0 as u32), "num+" => Some(VK_ADD.0 as u32), "num-" => Some(VK_SUBTRACT.0 as u32), "num*" => Some(VK_MULTIPLY.0 as u32), "num/" => Some(VK_DIVIDE.0 as u32), "num." => Some(VK_DECIMAL.0 as u32), "-" => Some(VK_OEM_MINUS.0 as u32), ";" => Some(VK_OEM_PLUS.0 as u32), "," => Some(VK_OEM_COMMA.0 as u32), "." => Some(VK_OEM_PERIOD.0 as u32), ":" => Some(VK_OEM_1.0 as u32), "/" => Some(VK_OEM_2.0 as u32), "@" => Some(VK_OEM_3.0 as u32), "[" => Some(VK_OEM_4.0 as u32), "\\" => Some(VK_OEM_5.0 as u32), "]" => Some(VK_OEM_6.0 as u32), "^" => Some(VK_OEM_7.0 as u32), "_" => Some(VK_OEM_102.0 as u32), _ if k.len() == 1 => { let c = k.chars().next().unwrap(); (!c.is_ascii_control()).then(|| c.to_ascii_uppercase() as u32) } _ if k.starts_with("num") => k .trim_matches(|c| !char::is_numeric(c)) .parse() .map(|n: u32| VK_NUMPAD0.0 as u32 + n) .ok(), _ if k.starts_with('f') => k .trim_matches(|c| !char::is_numeric(c)) .parse() .map(|n: u32| VK_F1.0 as u32 + n - 1) .ok(), _ => None, } } #[derive(Debug)] pub struct Item { pub id: String, pub keys: Option<Keys>, } #[derive(Debug)] pub struct OldKeyMap(pub Vec<Item>); impl OldKeyMap { pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, Error> { let file = std::fs::File::open(path)?; let mut reader = std::io::BufReader::new(file); let mut key_map = vec![]; let mut buffer = String::new(); loop { buffer.clear(); if reader.read_line(&mut buffer)? == 0 { break; } if buffer.is_empty() { continue; } if buffer.starts_with('#') { continue; } let ss = buffer.split('=').collect::<Vec<_>>(); if ss.len() != 2 { continue; } let keys = ss[1] .trim() .to_ascii_lowercase() .split('+') .map(|s| str_to_vk(s)) .collect::<Option<Vec<_>>>(); if keys.is_none() { continue; } key_map.push(Item { id: ss[0].trim().to_string(), keys: Some(Keys::from_slice(&keys.unwrap())), }); } Ok(Self(key_map)) } } #[cfg(test)] mod tests { use super::*; #[test] fn load_key_map() { let data = OldKeyMap::from_file("key_map.txt").un
random
[ { "content": "fn error(msg: &str) {\n\n message_box(None, msg, \"d3d9.dll エラー\", MB_OK | MB_ICONERROR);\n\n}\n\n\n\n#[inline]\n\nunsafe fn mmaccel_run(base_addr: usize) {\n\n if let Some(mmaccel) = MMACCEL.get() {\n\n let f = mmaccel.get::<unsafe fn(usize)>(b\"mmaccel_run\").unwrap();\n\n f(...
Rust
src/processor.rs
jswh/wslexe
964319b2cb2b830c54289138db7c2deeb3b938b9
use std::borrow::Cow; use std::env; use std::io::{self, Write}; use std::path::{Component, Path, Prefix, PrefixComponent}; use std::process; use std::process::{Command, Stdio}; use regex::bytes::Regex; fn get_drive_letter(pc: &PrefixComponent) -> Option<String> { let drive_byte = match pc.kind() { Prefix::VerbatimDisk(d) => Some(d), Prefix::Disk(d) => Some(d), _ => None, }; drive_byte.map(|drive_letter| { String::from_utf8(vec![drive_letter]) .expect(&format!("Invalid drive letter: {}", drive_letter)) .to_lowercase() }) } fn get_prefix_for_drive(drive: &str) -> String { format!("/mnt/{}", drive) } fn translate_path_to_unix(argument: String) -> String { { let (argname, arg) = if argument.starts_with("--") && argument.contains('=') { let parts: Vec<&str> = argument.splitn(2, '=').collect(); (format!("{}=", parts[0]), parts[1]) } else { ("".to_owned(), argument.as_ref()) }; let win_path = Path::new(arg); if win_path.is_absolute() || win_path.exists() { let wsl_path: String = win_path.components().fold(String::new(), |mut acc, c| { match c { Component::Prefix(prefix_comp) => { let d = get_drive_letter(&prefix_comp) .expect(&format!("Cannot handle path {:?}", win_path)); acc.push_str(&get_prefix_for_drive(&d)); } Component::RootDir => {} _ => { let d = c.as_os_str() .to_str() .expect(&format!("Cannot represent path {:?}", win_path)) .to_owned(); if !acc.is_empty() && !acc.ends_with('/') { acc.push('/'); } acc.push_str(&d); } }; acc }); return format!("{}{}", &argname, &wsl_path); } } argument } fn translate_path_to_win(line: &[u8]) -> Cow<[u8]> { lazy_static! { static ref WSLPATH_RE: Regex = Regex::new(r"(?m-u)/mnt/(?P<drive>[A-Za-z])(?P<path>/\S*)") .expect("Failed to compile WSLPATH regex"); } WSLPATH_RE.replace_all(line, &b"${drive}:${path}"[..]) } fn shell_escape(arg: String) -> String { if arg.contains(" ") { return vec![String::from("\""), arg, String::from("\"")].join(""); } arg.replace("\n", "$'\n'"); arg.replace(";", "$';'") } pub fn execute(interactive: bool) { let mut exe_path = env::current_exe().unwrap(); exe_path.pop(); let wslexerc_path = format!("{}\\.wslexerc", exe_path.display()); let mut cmd_args = Vec::new(); let mut wsl_args: Vec<String> = vec![]; let wsl_cmd: String; let exe: String = env::args().next().unwrap(); let path = Path::new(&exe); let file_stem = path.file_stem().unwrap().to_str().unwrap(); wsl_args.push(String::from(file_stem)); wsl_args.extend(env::args().skip(1).map(translate_path_to_unix)); if Path::new(&wslexerc_path).exists() { wsl_cmd = format!( "source {};{}", translate_path_to_unix(wslexerc_path), if interactive { wsl_args.join(" ") }else{ wsl_args.into_iter().map(shell_escape).collect::<Vec<String>>().join(" ")} ); } else { wsl_cmd = wsl_args.join(" "); } let exe_cmd: String; if interactive { exe_cmd = "-ic".to_string(); } else { exe_cmd = "-c".to_string(); } cmd_args.push("bash".to_string()); cmd_args.push(exe_cmd); cmd_args.push(wsl_cmd.clone()); let stdin_mode = if wsl_cmd.ends_with("--version") { Stdio::null() } else { Stdio::inherit() }; let mut wsl_proc_setup = Command::new("wsl.exe"); wsl_proc_setup.args(&cmd_args).stdin(stdin_mode); let status; const TRANSLATED_CMDS: &[&str] = &["rev-parse", "remote"]; let translate_output = env::args() .skip(1) .position(|arg| { TRANSLATED_CMDS .iter() .position(|&tcmd| tcmd == arg) .is_some() }) .is_some(); if translate_output { let wsl_proc = wsl_proc_setup .stdout(Stdio::piped()) .spawn() .expect(&format!("Failed to execute command '{}'", &wsl_cmd)); let output = wsl_proc .wait_with_output() .expect(&format!("Failed to wait for wsl call '{}'", &wsl_cmd)); status = output.status; let output_bytes = output.stdout; let mut stdout = io::stdout(); stdout .write_all(&translate_path_to_win(&output_bytes)) .expect("Failed to write wsl output"); stdout.flush().expect("Failed to flush output"); } else { status = wsl_proc_setup .status() .expect(&format!("Failed to execute command '{}'", &wsl_cmd)); } if let Some(exit_code) = status.code() { process::exit(exit_code); } } #[test] fn win_to_unix_path_trans() { assert_eq!( translate_path_to_unix("d:\\test\\file.txt".to_string()), "/mnt/d/test/file.txt" ); assert_eq!( translate_path_to_unix("C:\\Users\\test\\a space.txt".to_string()), "/mnt/c/Users/test/a space.txt" ); } #[test] fn unix_to_win_path_trans() { assert_eq!( &*translate_path_to_win(b"/mnt/d/some path/a file.md"), b"d:/some path/a file.md" ); assert_eq!( &*translate_path_to_win(b"origin /mnt/c/path/ (fetch)"), b"origin c:/path/ (fetch)" ); let multiline = b"mirror /mnt/c/other/ (fetch)\nmirror /mnt/c/other/ (push)\n"; let multiline_result = b"mirror c:/other/ (fetch)\nmirror c:/other/ (push)\n"; assert_eq!( &*translate_path_to_win(&multiline[..]), &multiline_result[..] ); } #[test] fn no_path_translation() { assert_eq!( &*translate_path_to_win(b"/mnt/other/file.sh"), b"/mnt/other/file.sh" ); } #[test] fn relative_path_translation() { assert_eq!( translate_path_to_unix(".\\src\\main.rs".to_string()), "./src/main.rs" ); } #[test] fn long_argument_path_translation() { assert_eq!( translate_path_to_unix("--file=C:\\some\\path.txt".to_owned()), "--file=/mnt/c/some/path.txt" ); }
use std::borrow::Cow; use std::env; use std::io::{self, Write}; use std::path::{Component, Path, Prefix, PrefixComponent}; use std::process; use std::process::{Command, Stdio}; use regex::bytes::Regex; fn get_drive_letter(pc: &PrefixComponent) -> Option<String> { let drive_byte = match pc.kind() { Prefix::VerbatimDisk(d) => Some(d), Prefix::Disk(d) => Some(d), _ => None, }; drive_byte.map(|drive_letter| { String::from_utf8(vec![drive_letter]) .expect(&format!("Invalid drive letter: {}", drive_letter)) .to_lowercase() }) } fn get_prefix_for_drive(drive: &str) -> String { format!("/mnt/{}", drive) } fn translate_path_to_unix(argument: String) -> String { { let (argname, arg) = if argument.starts_with("--") && argument.contains('=') { let parts: Vec<&str> = argument.splitn(2, '=').collect(); (format!("{}=", parts[0]), parts[1]) } else { ("".to_owned(), argument.as_ref()) }; let win_path = Path::new(arg); if win_path.is_absolute() || win_path.exists() { let wsl_path: String = win_path.components().fold(String::new(), |mut acc, c| { match c { Component::Prefix(prefix_comp) => { let d = get_drive_letter(&prefix_comp) .expect(&format!("Cannot handle path {:?}", win_path)); acc.push_str(&get_prefix_for_drive(&d)); } Component::RootDir => {} _ => { let d = c.as_os_str() .to_str() .expect(&format!("Cannot represent path {:?}", win_path)) .to_owned(); if !acc.is_empty() && !acc.ends_with('/') { acc.push('/'); } acc.push_str(&d); } }; acc }); return format!("{}{}", &argname, &wsl_path); } } argument } f
fn shell_escape(arg: String) -> String { if arg.contains(" ") { return vec![String::from("\""), arg, String::from("\"")].join(""); } arg.replace("\n", "$'\n'"); arg.replace(";", "$';'") } pub fn execute(interactive: bool) { let mut exe_path = env::current_exe().unwrap(); exe_path.pop(); let wslexerc_path = format!("{}\\.wslexerc", exe_path.display()); let mut cmd_args = Vec::new(); let mut wsl_args: Vec<String> = vec![]; let wsl_cmd: String; let exe: String = env::args().next().unwrap(); let path = Path::new(&exe); let file_stem = path.file_stem().unwrap().to_str().unwrap(); wsl_args.push(String::from(file_stem)); wsl_args.extend(env::args().skip(1).map(translate_path_to_unix)); if Path::new(&wslexerc_path).exists() { wsl_cmd = format!( "source {};{}", translate_path_to_unix(wslexerc_path), if interactive { wsl_args.join(" ") }else{ wsl_args.into_iter().map(shell_escape).collect::<Vec<String>>().join(" ")} ); } else { wsl_cmd = wsl_args.join(" "); } let exe_cmd: String; if interactive { exe_cmd = "-ic".to_string(); } else { exe_cmd = "-c".to_string(); } cmd_args.push("bash".to_string()); cmd_args.push(exe_cmd); cmd_args.push(wsl_cmd.clone()); let stdin_mode = if wsl_cmd.ends_with("--version") { Stdio::null() } else { Stdio::inherit() }; let mut wsl_proc_setup = Command::new("wsl.exe"); wsl_proc_setup.args(&cmd_args).stdin(stdin_mode); let status; const TRANSLATED_CMDS: &[&str] = &["rev-parse", "remote"]; let translate_output = env::args() .skip(1) .position(|arg| { TRANSLATED_CMDS .iter() .position(|&tcmd| tcmd == arg) .is_some() }) .is_some(); if translate_output { let wsl_proc = wsl_proc_setup .stdout(Stdio::piped()) .spawn() .expect(&format!("Failed to execute command '{}'", &wsl_cmd)); let output = wsl_proc .wait_with_output() .expect(&format!("Failed to wait for wsl call '{}'", &wsl_cmd)); status = output.status; let output_bytes = output.stdout; let mut stdout = io::stdout(); stdout .write_all(&translate_path_to_win(&output_bytes)) .expect("Failed to write wsl output"); stdout.flush().expect("Failed to flush output"); } else { status = wsl_proc_setup .status() .expect(&format!("Failed to execute command '{}'", &wsl_cmd)); } if let Some(exit_code) = status.code() { process::exit(exit_code); } } #[test] fn win_to_unix_path_trans() { assert_eq!( translate_path_to_unix("d:\\test\\file.txt".to_string()), "/mnt/d/test/file.txt" ); assert_eq!( translate_path_to_unix("C:\\Users\\test\\a space.txt".to_string()), "/mnt/c/Users/test/a space.txt" ); } #[test] fn unix_to_win_path_trans() { assert_eq!( &*translate_path_to_win(b"/mnt/d/some path/a file.md"), b"d:/some path/a file.md" ); assert_eq!( &*translate_path_to_win(b"origin /mnt/c/path/ (fetch)"), b"origin c:/path/ (fetch)" ); let multiline = b"mirror /mnt/c/other/ (fetch)\nmirror /mnt/c/other/ (push)\n"; let multiline_result = b"mirror c:/other/ (fetch)\nmirror c:/other/ (push)\n"; assert_eq!( &*translate_path_to_win(&multiline[..]), &multiline_result[..] ); } #[test] fn no_path_translation() { assert_eq!( &*translate_path_to_win(b"/mnt/other/file.sh"), b"/mnt/other/file.sh" ); } #[test] fn relative_path_translation() { assert_eq!( translate_path_to_unix(".\\src\\main.rs".to_string()), "./src/main.rs" ); } #[test] fn long_argument_path_translation() { assert_eq!( translate_path_to_unix("--file=C:\\some\\path.txt".to_owned()), "--file=/mnt/c/some/path.txt" ); }
n translate_path_to_win(line: &[u8]) -> Cow<[u8]> { lazy_static! { static ref WSLPATH_RE: Regex = Regex::new(r"(?m-u)/mnt/(?P<drive>[A-Za-z])(?P<path>/\S*)") .expect("Failed to compile WSLPATH regex"); } WSLPATH_RE.replace_all(line, &b"${drive}:${path}"[..]) }
function_block-function_prefixed
[ { "content": "fn main() {\n\n processor::execute(false)\n\n}\n", "file_path": "src/main.rs", "rank": 10, "score": 18098.30613938591 }, { "content": "fn main() {\n\n processor::execute(true)\n\n}\n", "file_path": "src/main_i.rs", "rank": 11, "score": 18098.30613938591 }, ...
Rust
packages/server/src/middleware/tests.rs
sogrim/technion-sogrim
6d9f86266252ac0b7348725a295aabca9eba5222
use crate::{config::CONFIG, init_mongodb_client, middleware, resources::user::User}; use actix_rt::test; use actix_web::{ http::StatusCode, test::{self}, web::{self, Bytes}, App, }; use actix_web_lab::middleware::from_fn; use dotenv::dotenv; use mongodb::Client; #[test] async fn test_from_request_no_db_client() { let token_claims = jsonwebtoken_google::test_helper::TokenClaims::new(); let (jwt, parser, _server) = jsonwebtoken_google::test_helper::setup(&token_claims); dotenv().ok(); let app = test::init_service( App::new() .app_data(middleware::auth::JwtDecoder::new_with_parser(parser)) .wrap(from_fn(middleware::auth::authenticate)) .service( web::resource("/").route(web::get().to(|_: User| async { "Shouldn't get here" })), ), ) .await; let resp = test::TestRequest::get() .uri("/") .insert_header(("authorization", jwt)) .send_request(&app) .await; assert!(resp.status().is_server_error()); assert_eq!( Bytes::from("Mongodb client not found in application data"), test::read_body(resp).await ); } #[test] async fn test_from_request_no_auth_mw() { dotenv().ok(); let client = init_mongodb_client!(); let app = test::init_service(App::new().app_data(web::Data::new(client.clone())).service( web::resource("/").route(web::get().to(|_: User| async { "Shouldn't get here" })), )) .await; let resp = test::TestRequest::get() .uri("/") .insert_header(("authorization", "bugo-the-debugo")) .send_request(&app) .await; assert!(resp.status().is_server_error()); assert_eq!( Bytes::from("Middleware error: Sub not found in request extensions"), test::read_body(resp).await ); } #[test] async fn test_auth_mw_no_jwt_decoder() { dotenv().ok(); let client = init_mongodb_client!(); let app = test::init_service( App::new() .app_data(web::Data::new(client.clone())) .wrap(from_fn(middleware::auth::authenticate)) .service(web::resource("/").route(web::get().to(|| async { "Shouldn't get here" }))), ) .await; let resp = test::TestRequest::get() .uri("/") .insert_header(("authorization", "bugo-the-debugo")) .send_request(&app) .await; assert!(resp.status().is_server_error()); assert_eq!( Bytes::from("JwtDecoder not initialized"), test::read_body(resp).await ); } #[test] async fn test_auth_mw_client_errors() { let token_claims = jsonwebtoken_google::test_helper::TokenClaims::new_expired(); let (expired_jwt, parser, _server) = jsonwebtoken_google::test_helper::setup(&token_claims); dotenv().ok(); let app = test::init_service( App::new() .app_data(middleware::auth::JwtDecoder::new_with_parser(parser)) .wrap(from_fn(middleware::auth::authenticate)) .service(web::resource("/").route(web::get().to(|| async { "Shouldn't get here" }))), ) .await; let resp_no_header = test::TestRequest::get().uri("/").send_request(&app).await; assert_eq!(resp_no_header.status(), StatusCode::UNAUTHORIZED); assert_eq!( Bytes::from("No authorization header found"), test::read_body(resp_no_header).await ); let resp_bad_jwt = test::TestRequest::get() .uri("/") .insert_header(("authorization", "bad_jwt")) .send_request(&app) .await; assert_eq!(resp_bad_jwt.status(), StatusCode::UNAUTHORIZED); assert_eq!( Bytes::from("Invalid JWT: Wrong header."), test::read_body(resp_bad_jwt).await ); let resp_jwt_expired = test::TestRequest::get() .uri("/") .insert_header(("authorization", expired_jwt)) .send_request(&app) .await; assert_eq!(resp_jwt_expired.status(), StatusCode::UNAUTHORIZED); assert_eq!( Bytes::from("Invalid JWT: Wrong token format - ExpiredSignature."), test::read_body(resp_jwt_expired).await ); }
use crate::{config::CONFIG, init_mongodb_client, middleware, resources::user::User}; use actix_rt::test; use actix_web::{ http::StatusCode, test::{self}, web::{self, Bytes}, App, }; use actix_web_lab::middleware::from_fn; use dotenv::dotenv; use mongodb::Client; #[test] async fn test_from_request_no_db_client() { let token_claims = jsonwebtoken_google::test_helper::TokenClaims::new(); let (jwt, parser, _server) = jsonwebtoken_google::test_helper::setup(&token_claims); dotenv().ok(); let app = test::init_service( App::new() .app_data(middleware::auth::JwtDecoder::new_with_parser(parser)) .wrap(from_fn(middleware::auth::authenticate)) .service( web::resource("/").route(web::get().to(|_: User| async { "Shouldn't get here" })), ), ) .await; let resp = test::TestRequest::get() .uri("/") .insert_header(("authorization", jwt)) .send_request(&app) .await; assert!(resp.status().is_server_error()); assert_eq!( Bytes::from("Mongodb client not found in application data"), test::read_body(resp).await ); } #[test] async fn test_from_request_no_auth_mw() { dotenv().ok(); let client = init_mongodb_client!(); let app = test::init_service(App::new().app_data(web::Data::new(client.clone())).service( web::resource("/").route(web::get().to(|_: User| async { "Shouldn't get here" })), )) .await; let resp = test::TestRequest::get() .uri("/") .insert_header(("authorization", "bugo-the-debugo")) .send_request(&app) .await; assert!(resp.status().is_server_error()); assert_eq!( Bytes::from("Middleware error: Sub not found in request extensions"), test::read_body(resp).await ); } #[test] async fn test_auth_mw_no_jwt_decoder() { dotenv().ok(); let client = init_mongodb_client!(); let app = test::init_service( App::new() .app_data(web::Data::new(client.clone())) .wrap(from_fn(
t_header(("authorization", "bugo-the-debugo")) .send_request(&app) .await; assert!(resp.status().is_server_error()); assert_eq!( Bytes::from("JwtDecoder not initialized"), test::read_body(resp).await ); } #[test] async fn test_auth_mw_client_errors() { let token_claims = jsonwebtoken_google::test_helper::TokenClaims::new_expired(); let (expired_jwt, parser, _server) = jsonwebtoken_google::test_helper::setup(&token_claims); dotenv().ok(); let app = test::init_service( App::new() .app_data(middleware::auth::JwtDecoder::new_with_parser(parser)) .wrap(from_fn(middleware::auth::authenticate)) .service(web::resource("/").route(web::get().to(|| async { "Shouldn't get here" }))), ) .await; let resp_no_header = test::TestRequest::get().uri("/").send_request(&app).await; assert_eq!(resp_no_header.status(), StatusCode::UNAUTHORIZED); assert_eq!( Bytes::from("No authorization header found"), test::read_body(resp_no_header).await ); let resp_bad_jwt = test::TestRequest::get() .uri("/") .insert_header(("authorization", "bad_jwt")) .send_request(&app) .await; assert_eq!(resp_bad_jwt.status(), StatusCode::UNAUTHORIZED); assert_eq!( Bytes::from("Invalid JWT: Wrong header."), test::read_body(resp_bad_jwt).await ); let resp_jwt_expired = test::TestRequest::get() .uri("/") .insert_header(("authorization", expired_jwt)) .send_request(&app) .await; assert_eq!(resp_jwt_expired.status(), StatusCode::UNAUTHORIZED); assert_eq!( Bytes::from("Invalid JWT: Wrong token format - ExpiredSignature."), test::read_body(resp_jwt_expired).await ); }
middleware::auth::authenticate)) .service(web::resource("/").route(web::get().to(|| async { "Shouldn't get here" }))), ) .await; let resp = test::TestRequest::get() .uri("/") .inser
function_block-random_span
[ { "content": "pub fn parse_copy_paste_data(data: &str) -> Result<Vec<CourseStatus>, AppError> {\n\n // Sanity validation\n\n if !(data.starts_with(\"גיליון ציונים\") && data.contains(\"סוף גיליון ציונים\"))\n\n {\n\n return Err(AppError::Parser(\"Invalid copy paste data\".into()));\n\n }\n\n\...
Rust
nonebot_rs/src/matcher/matchers/action.rs
abrahum/nonebot-rs
8c090098a10f574637fcad16fd74357e875bd43e
use super::{Matchers, MatchersBTreeMap, MatchersHashMap}; use crate::event::{MessageEvent, MetaEvent, NoticeEvent, RequestEvent}; use crate::matcher::{action::MatchersAction, Matcher}; use std::collections::{BTreeMap, HashMap}; use tokio::sync::broadcast; impl Matchers { pub fn new( message: Option<MatchersBTreeMap<MessageEvent>>, notice: Option<MatchersBTreeMap<NoticeEvent>>, request: Option<MatchersBTreeMap<RequestEvent>>, meta: Option<MatchersBTreeMap<MetaEvent>>, ) -> Matchers { let (sender, _) = broadcast::channel(32); Matchers { message: unoptionb(&message), notice: unoptionb(&notice), request: unoptionb(&request), meta: unoptionb(&meta), bot_getter: None, action_sender: sender, config: HashMap::new(), } } pub fn new_empty() -> Matchers { Matchers::new(None, None, None, None) } pub fn get(&mut self, m: &Matchers) { self.message = m.message.clone(); self.notice = m.notice.clone(); self.request = m.request.clone(); self.meta = m.meta.clone(); } pub async fn run_on_connect(&self, bot: crate::bot::Bot, disconnect: bool) { async fn run_on_connect_<E>( matcherb: &MatchersBTreeMap<E>, bot: crate::bot::Bot, disconnect: bool, ) where E: Clone, { for (_, matcherh) in matcherb { for (_, matcher) in matcherh { let built_matcher = matcher.build(bot.clone()); let handler = built_matcher.get_handler(); let lock_handler = handler.read().await; if disconnect { lock_handler.on_bot_disconnect(matcher.clone()); } else { lock_handler.on_bot_connect(matcher.clone()); } } } } run_on_connect_(&self.message, bot.clone(), disconnect).await; run_on_connect_(&self.notice, bot.clone(), disconnect).await; run_on_connect_(&self.request, bot.clone(), disconnect).await; run_on_connect_(&self.meta, bot.clone(), disconnect).await; } pub async fn load_all_matcher_config(&self) { async fn f<E>( matcherb: &MatchersBTreeMap<E>, config: &HashMap<String, HashMap<String, toml::Value>>, ) where E: Clone, { for (_, matcherh) in matcherb { for (matcher_name, matcher) in matcherh { if let Some(data) = config.get(&matcher_name.to_lowercase()) { let handler = matcher.get_handler(); let mut lock_handler = handler.write().await; lock_handler.load_config(data.clone()); } } } } f(&self.message, &self.config).await; f(&self.notice, &self.config).await; f(&self.request, &self.config).await; f(&self.meta, &self.config).await; } #[doc(hidden)] fn add_matcher<E>( matcherb: &mut MatchersBTreeMap<E>, mut matcher: Matcher<E>, action_sender: broadcast::Sender<MatchersAction>, ) where E: Clone, { matcher.set_action_sender(action_sender); match matcherb.get_mut(&matcher.priority) { Some(h) => { h.insert(matcher.name.clone(), matcher); } None => { let mut hashmap: MatchersHashMap<E> = HashMap::new(); hashmap.insert(matcher.name.clone(), matcher.clone()); matcherb.insert(matcher.priority, hashmap); } } } pub fn add_message_matcher(&mut self, matcher: Matcher<MessageEvent>) -> &mut Self { Matchers::add_matcher(&mut self.message, matcher, self.action_sender.clone()); self } pub fn add_message_matchers(&mut self, matchers: Vec<Matcher<MessageEvent>>) -> &mut Self { for m in matchers { self.add_message_matcher(m); } self } pub fn add_notice_matcher(&mut self, matcher: Matcher<NoticeEvent>) -> &mut Self { Matchers::add_matcher(&mut self.notice, matcher, self.action_sender.clone()); self } pub fn add_request_matcher(&mut self, matcher: Matcher<RequestEvent>) -> &mut Self { Matchers::add_matcher(&mut self.request, matcher, self.action_sender.clone()); self } pub fn add_meta_matcher(&mut self, matcher: Matcher<MetaEvent>) -> &mut Self { Matchers::add_matcher(&mut self.meta, matcher, self.action_sender.clone()); self } pub fn remove_matcher(&mut self, name: &str) { fn remove_matcher_<E>(matcherb: &mut MatchersBTreeMap<E>, name: &str) where E: Clone, { for (_, matcherh) in matcherb.iter_mut() { if let Some(_) = matcherh.remove(name) { return; } } } remove_matcher_(&mut self.message, name); remove_matcher_(&mut self.notice, name); remove_matcher_(&mut self.request, name); remove_matcher_(&mut self.meta, name); } pub fn disable_matcher(&mut self, name: &str, disable: bool) { fn disable_matcher_<E>(matcherb: &mut MatchersBTreeMap<E>, name: &str, disable: bool) where E: Clone, { for (_, matcherh) in matcherb.iter_mut() { if let Some(matcher) = matcherh.get_mut(name) { matcher.set_disable(disable); } } } disable_matcher_(&mut self.message, name, disable); disable_matcher_(&mut self.notice, name, disable); disable_matcher_(&mut self.request, name, disable); disable_matcher_(&mut self.meta, name, disable); } } #[doc(hidden)] fn unoptionb<K, D>(input: &Option<BTreeMap<K, D>>) -> BTreeMap<K, D> where K: Clone + std::cmp::Ord, D: Clone, { match input { Some(t) => t.clone(), None => BTreeMap::new(), } }
use super::{Matchers, MatchersBTreeMap, MatchersHashMap}; use crate::event::{MessageEvent, MetaEvent, NoticeEvent, RequestEvent}; use crate::matcher::{action::MatchersAction, Matcher}; use std::collections::{BTreeMap, HashMap}; use tokio::sync::broadcast; impl Matchers { pub fn new( message: Option<MatchersBTreeMap<MessageEvent>>, notice: Option<MatchersBTreeMap<NoticeEvent>>, request: Option<MatchersBTreeMap<RequestEvent>>, meta: Option<MatchersBTreeMap<MetaEvent>>, ) -> Matchers { let (sender, _) = broadcast::channel(32); Matchers { message: unoptionb(&message), notice: unoptionb(&notice), request: unoptionb(&request), meta: unoptionb(&meta), bot_getter: None, action_sender: sender, config: HashMap::new(), } } pub fn new_empty() -> Matchers { Matchers::new(None, None, None, None) } pub fn get(&mut self, m: &Matchers) { self.message = m.message.clone(); self.notice = m.notice.clone(); self.request = m.request.clone(); self.meta = m.meta.clone(); } pub async fn run_on_connect(&self, bot: crate::bot::Bot, disconnect: bool) { async fn run_on_connect_<E>( matcherb: &MatchersBTreeMap<E>, bot: crate::bot::Bot, disconnect: bool, ) where E: Clone, { for (_, matcherh) in matcherb { for (_, matcher) in matcherh { let built_matcher = matcher.build(bot.clone()); let handler = built_matcher.get_handler(); let lock_handler = handler.read().await; if disconnect { lock_handler.on_bot_disconnect(matcher.clone()); } else { lock_handler.on_bot_connect(matcher.clone()); } } } } run_on_connect_(&self.message, bot.clone(), disconnect).await; run_on_connect_(&self.notice, bot.clone(), disconnect).await; run_on_connect_(&self.request, bot.clone(), disconnect).await; run_on_connect_(&self.meta, bot.clone(), disconnect).await; } pub async fn load_all_matcher_config(&self) { async fn f<E>( matcherb: &MatchersBTreeMap<E>, config: &HashMap<String, HashMap<String, toml::Value>>, ) where E: Clone, { for (_, matcherh) in matcherb { for (matcher_name, matcher) in matcherh { if let Some(data) = config.get(&matcher_name.to_lowercase()) { let handler = matcher.get_handler(); let mut lock_handler = handler.write(
} self } pub fn add_notice_matcher(&mut self, matcher: Matcher<NoticeEvent>) -> &mut Self { Matchers::add_matcher(&mut self.notice, matcher, self.action_sender.clone()); self } pub fn add_request_matcher(&mut self, matcher: Matcher<RequestEvent>) -> &mut Self { Matchers::add_matcher(&mut self.request, matcher, self.action_sender.clone()); self } pub fn add_meta_matcher(&mut self, matcher: Matcher<MetaEvent>) -> &mut Self { Matchers::add_matcher(&mut self.meta, matcher, self.action_sender.clone()); self } pub fn remove_matcher(&mut self, name: &str) { fn remove_matcher_<E>(matcherb: &mut MatchersBTreeMap<E>, name: &str) where E: Clone, { for (_, matcherh) in matcherb.iter_mut() { if let Some(_) = matcherh.remove(name) { return; } } } remove_matcher_(&mut self.message, name); remove_matcher_(&mut self.notice, name); remove_matcher_(&mut self.request, name); remove_matcher_(&mut self.meta, name); } pub fn disable_matcher(&mut self, name: &str, disable: bool) { fn disable_matcher_<E>(matcherb: &mut MatchersBTreeMap<E>, name: &str, disable: bool) where E: Clone, { for (_, matcherh) in matcherb.iter_mut() { if let Some(matcher) = matcherh.get_mut(name) { matcher.set_disable(disable); } } } disable_matcher_(&mut self.message, name, disable); disable_matcher_(&mut self.notice, name, disable); disable_matcher_(&mut self.request, name, disable); disable_matcher_(&mut self.meta, name, disable); } } #[doc(hidden)] fn unoptionb<K, D>(input: &Option<BTreeMap<K, D>>) -> BTreeMap<K, D> where K: Clone + std::cmp::Ord, D: Clone, { match input { Some(t) => t.clone(), None => BTreeMap::new(), } }
).await; lock_handler.load_config(data.clone()); } } } } f(&self.message, &self.config).await; f(&self.notice, &self.config).await; f(&self.request, &self.config).await; f(&self.meta, &self.config).await; } #[doc(hidden)] fn add_matcher<E>( matcherb: &mut MatchersBTreeMap<E>, mut matcher: Matcher<E>, action_sender: broadcast::Sender<MatchersAction>, ) where E: Clone, { matcher.set_action_sender(action_sender); match matcherb.get_mut(&matcher.priority) { Some(h) => { h.insert(matcher.name.clone(), matcher); } None => { let mut hashmap: MatchersHashMap<E> = HashMap::new(); hashmap.insert(matcher.name.clone(), matcher.clone()); matcherb.insert(matcher.priority, hashmap); } } } pub fn add_message_matcher(&mut self, matcher: Matcher<MessageEvent>) -> &mut Self { Matchers::add_matcher(&mut self.message, matcher, self.action_sender.clone()); self } pub fn add_message_matchers(&mut self, matchers: Vec<Matcher<MessageEvent>>) -> &mut Self { for m in matchers { self.add_message_matcher(m);
random
[ { "content": "#[doc(hidden)]\n\nfn command_start_(event: &mut MessageEvent, config: BotConfig) -> bool {\n\n let raw_message = remove_space(&event.get_raw_message());\n\n let command_starts = config.command_starts;\n\n if command_starts.is_empty() {\n\n return true;\n\n }\n\n for sc in &co...
Rust
src/bitwidth.rs
Robbepop/apin
0b863c6f5dfcee22e6c2f4ead88bce9814788fc2
use crate::{ mem::NonZeroUsize, storage::Storage, BitPos, Digit, Error, Result, ShiftAmount, }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BitWidth(NonZeroUsize); impl BitWidth { #[inline] pub fn w1() -> Self { BitWidth(NonZeroUsize::new(1).unwrap()) } #[inline] pub fn w8() -> Self { BitWidth(NonZeroUsize::new(8).unwrap()) } #[inline] pub fn w16() -> Self { BitWidth(NonZeroUsize::new(16).unwrap()) } #[inline] pub fn w32() -> Self { BitWidth(NonZeroUsize::new(32).unwrap()) } #[inline] pub fn w64() -> Self { BitWidth(NonZeroUsize::new(64).unwrap()) } #[inline] pub fn w128() -> Self { BitWidth(NonZeroUsize::new(128).unwrap()) } pub fn new(width: usize) -> Result<Self> { if width == 0 { return Err(Error::invalid_zero_bitwidth()) } Ok(BitWidth(NonZeroUsize::new(width).unwrap())) } #[inline] pub(crate) fn is_valid_pos<P>(self, pos: P) -> bool where P: Into<BitPos>, { pos.into().to_usize() < self.to_usize() } #[inline] pub(crate) fn is_valid_shift_amount<S>(self, shift_amount: S) -> bool where S: Into<ShiftAmount>, { shift_amount.into().to_usize() < self.to_usize() } #[inline] pub(crate) fn msb_pos(self) -> BitPos { BitPos::from(self.to_usize() - 1) } } impl From<usize> for BitWidth { fn from(width: usize) -> BitWidth { BitWidth::new(width).unwrap() } } impl BitWidth { #[inline] pub fn to_usize(self) -> usize { self.0.get() } pub(crate) fn excess_bits(self) -> Option<usize> { match self.to_usize() % Digit::BITS { 0 => None, n => Some(n), } } pub(crate) fn excess_width(self) -> Option<BitWidth> { NonZeroUsize::new(self.to_usize() % Digit::BITS).map(BitWidth) } #[inline] pub(crate) fn storage(self) -> Storage { Storage::from(self) } #[inline] pub(crate) fn required_digits(self) -> usize { ((self.to_usize() - 1) / Digit::BITS) + 1 } } #[cfg(test)] mod tests { use super::*; mod excess_bits { use super::*; #[test] fn powers_of_two() { assert_eq!(BitWidth::w1().excess_bits(), Some(1)); assert_eq!(BitWidth::w8().excess_bits(), Some(8)); assert_eq!(BitWidth::w16().excess_bits(), Some(16)); assert_eq!(BitWidth::w32().excess_bits(), Some(32)); assert_eq!(BitWidth::w64().excess_bits(), None); assert_eq!(BitWidth::w128().excess_bits(), None); } #[test] fn multiples_of_50() { assert_eq!(BitWidth::new(50).unwrap().excess_bits(), Some(50)); assert_eq!(BitWidth::new(100).unwrap().excess_bits(), Some(36)); assert_eq!(BitWidth::new(150).unwrap().excess_bits(), Some(22)); assert_eq!(BitWidth::new(200).unwrap().excess_bits(), Some(8)); assert_eq!(BitWidth::new(250).unwrap().excess_bits(), Some(58)); assert_eq!(BitWidth::new(300).unwrap().excess_bits(), Some(44)); } } }
use crate::{ mem::NonZeroUsize, storage::Storage, BitPos, Digit, Error, Result, ShiftAmount, }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BitWidth(NonZeroUsize); impl BitWidth { #[inline] pub fn w1() -> Self { BitWidth(NonZeroUsize::new(1).unwrap()) } #[inline] pub fn w8() -> Self { BitWidth(NonZeroUsize::new(8).unwrap()) } #[inline] pub fn w16() -> Self { BitWidth(NonZeroUsize::new(16).unwrap()) } #[inline] pub fn w32() -> Self { BitWidth(NonZeroUsize::new(32).unwrap()) } #[inline] pub fn w64() -> Self { BitWidth(NonZeroUsize::new(64).unwrap()) } #[inline] pub fn w128() -> Self { BitWidth(NonZeroUsize::new(128).unwrap()) } pub fn new(width: usize) -> Result<Self> { if widt
#[inline] pub(crate) fn is_valid_pos<P>(self, pos: P) -> bool where P: Into<BitPos>, { pos.into().to_usize() < self.to_usize() } #[inline] pub(crate) fn is_valid_shift_amount<S>(self, shift_amount: S) -> bool where S: Into<ShiftAmount>, { shift_amount.into().to_usize() < self.to_usize() } #[inline] pub(crate) fn msb_pos(self) -> BitPos { BitPos::from(self.to_usize() - 1) } } impl From<usize> for BitWidth { fn from(width: usize) -> BitWidth { BitWidth::new(width).unwrap() } } impl BitWidth { #[inline] pub fn to_usize(self) -> usize { self.0.get() } pub(crate) fn excess_bits(self) -> Option<usize> { match self.to_usize() % Digit::BITS { 0 => None, n => Some(n), } } pub(crate) fn excess_width(self) -> Option<BitWidth> { NonZeroUsize::new(self.to_usize() % Digit::BITS).map(BitWidth) } #[inline] pub(crate) fn storage(self) -> Storage { Storage::from(self) } #[inline] pub(crate) fn required_digits(self) -> usize { ((self.to_usize() - 1) / Digit::BITS) + 1 } } #[cfg(test)] mod tests { use super::*; mod excess_bits { use super::*; #[test] fn powers_of_two() { assert_eq!(BitWidth::w1().excess_bits(), Some(1)); assert_eq!(BitWidth::w8().excess_bits(), Some(8)); assert_eq!(BitWidth::w16().excess_bits(), Some(16)); assert_eq!(BitWidth::w32().excess_bits(), Some(32)); assert_eq!(BitWidth::w64().excess_bits(), None); assert_eq!(BitWidth::w128().excess_bits(), None); } #[test] fn multiples_of_50() { assert_eq!(BitWidth::new(50).unwrap().excess_bits(), Some(50)); assert_eq!(BitWidth::new(100).unwrap().excess_bits(), Some(36)); assert_eq!(BitWidth::new(150).unwrap().excess_bits(), Some(22)); assert_eq!(BitWidth::new(200).unwrap().excess_bits(), Some(8)); assert_eq!(BitWidth::new(250).unwrap().excess_bits(), Some(58)); assert_eq!(BitWidth::new(300).unwrap().excess_bits(), Some(44)); } } }
h == 0 { return Err(Error::invalid_zero_bitwidth()) } Ok(BitWidth(NonZeroUsize::new(width).unwrap())) }
function_block-function_prefixed
[]
Rust
src/borrows.rs
TimonPost/legion
43acaaa1b68e177636c618f63aaf6f5cf8f10558
use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::ops::DerefMut; use std::slice::Iter; use std::slice::IterMut; use std::sync::atomic::{AtomicIsize, Ordering}; pub enum Borrow<'a> { Read { state: &'a AtomicIsize }, Write { state: &'a AtomicIsize }, } impl<'a> Borrow<'a> { pub fn aquire_read(state: &'a AtomicIsize) -> Result<Borrow<'a>, &'static str> { loop { let read = state.load(Ordering::SeqCst); if read < 0 { return Err("resource already borrowed as mutable"); } if state.compare_and_swap(read, read + 1, Ordering::SeqCst) == read { break; } } Ok(Borrow::Read { state }) } pub fn aquire_write(state: &'a AtomicIsize) -> Result<Borrow<'a>, &'static str> { let borrowed = state.compare_and_swap(0, -1, Ordering::SeqCst); match borrowed { 0 => Ok(Borrow::Write { state }), x if x < 0 => Err("resource already borrowed as mutable"), _ => Err("resource already borrowed as immutable"), } } } impl<'a> Drop for Borrow<'a> { fn drop(&mut self) { match *self { Borrow::Read { state } => { state.fetch_sub(1, Ordering::SeqCst); } Borrow::Write { state } => { state.store(0, Ordering::SeqCst); } }; } } pub struct Borrowed<'a, T: 'a> { value: &'a T, #[allow(dead_code)] state: Borrow<'a>, } impl<'a, T: 'a> Borrowed<'a, T> { pub fn new(value: &'a T, borrow: Borrow<'a>) -> Borrowed<'a, T> { Borrowed { value, state: borrow, } } } impl<'a, 'b, T: 'a + Debug> Debug for Borrowed<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } impl<'a, 'b, T: 'a + Display> Display for Borrowed<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } impl<'a, 'b, T: 'a + PartialEq<T>> PartialEq<Borrowed<'b, T>> for Borrowed<'a, T> { fn eq(&self, other: &Borrowed<'b, T>) -> bool { self.value.eq(other.value) } } impl<'a, 'b, T: 'a + PartialEq<T>> PartialEq<T> for Borrowed<'a, T> { fn eq(&self, other: &T) -> bool { self.value.eq(other) } } impl<'a, 'b, T: 'a + Eq> Eq for Borrowed<'a, T> {} impl<'a, T: 'a> Deref for Borrowed<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.value } } impl<'a, T: 'a> AsRef<T> for Borrowed<'a, T> { fn as_ref(&self) -> &T { self.value } } impl<'a, T: 'a> std::borrow::Borrow<T> for Borrowed<'a, T> { fn borrow(&self) -> &T { self.value } } pub struct BorrowedMut<'a, T: 'a> { value: &'a mut T, #[allow(dead_code)] state: Borrow<'a>, } impl<'a, T: 'a> BorrowedMut<'a, T> { pub fn new(value: &'a mut T, borrow: Borrow<'a>) -> BorrowedMut<'a, T> { BorrowedMut { value, state: borrow, } } } impl<'a, T: 'a> Deref for BorrowedMut<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.value } } impl<'a, T: 'a> DerefMut for BorrowedMut<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.value } } impl<'a, T: 'a> AsRef<T> for BorrowedMut<'a, T> { fn as_ref(&self) -> &T { self.value } } impl<'a, T: 'a> std::borrow::Borrow<T> for BorrowedMut<'a, T> { fn borrow(&self) -> &T { self.value } } impl<'a, 'b, T: 'a + Debug> Debug for BorrowedMut<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } impl<'a, 'b, T: 'a + Display> Display for BorrowedMut<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } pub struct BorrowedSlice<'a, T: 'a> { slice: &'a [T], state: Borrow<'a>, } impl<'a, T: 'a> BorrowedSlice<'a, T> { pub fn new(slice: &'a [T], borrow: Borrow<'a>) -> BorrowedSlice<'a, T> { BorrowedSlice { slice, state: borrow, } } pub fn single(self, i: usize) -> Option<Borrowed<'a, T>> { let slice = self.slice; let state = self.state; slice.get(i).map(|x| Borrowed::new(x, state)) } } impl<'a, T: 'a> Deref for BorrowedSlice<'a, T> { type Target = [T]; fn deref(&self) -> &Self::Target { self.slice } } impl<'a, T: 'a> IntoIterator for BorrowedSlice<'a, T> { type Item = &'a T; type IntoIter = BorrowedIter<'a, Iter<'a, T>>; fn into_iter(self) -> Self::IntoIter { BorrowedIter { inner: self.slice.into_iter(), state: self.state, } } } pub struct BorrowedMutSlice<'a, T: 'a> { slice: &'a mut [T], state: Borrow<'a>, } impl<'a, T: 'a> BorrowedMutSlice<'a, T> { pub fn new(slice: &'a mut [T], borrow: Borrow<'a>) -> BorrowedMutSlice<'a, T> { BorrowedMutSlice { slice, state: borrow, } } pub fn single(self, i: usize) -> Option<BorrowedMut<'a, T>> { let slice = self.slice; let state = self.state; slice.get_mut(i).map(|x| BorrowedMut::new(x, state)) } } impl<'a, T: 'a> Deref for BorrowedMutSlice<'a, T> { type Target = [T]; fn deref(&self) -> &Self::Target { self.slice } } impl<'a, T: 'a> DerefMut for BorrowedMutSlice<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.slice } } impl<'a, T: 'a> IntoIterator for BorrowedMutSlice<'a, T> { type Item = &'a mut T; type IntoIter = BorrowedIter<'a, IterMut<'a, T>>; fn into_iter(self) -> Self::IntoIter { BorrowedIter { inner: self.slice.into_iter(), state: self.state, } } } pub struct BorrowedIter<'a, I: 'a + Iterator> { inner: I, #[allow(dead_code)] state: Borrow<'a>, } impl<'a, I: 'a + Iterator> Iterator for BorrowedIter<'a, I> { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } impl<'a, I: 'a + ExactSizeIterator> ExactSizeIterator for BorrowedIter<'a, I> {} #[cfg(test)] mod tests { use super::*; use std::sync::atomic::{AtomicIsize, Ordering}; #[test] fn borrow_read() { let state = AtomicIsize::new(0); let x = 5u8; let _borrow = Borrowed::new(&x, Borrow::aquire_read(&state).unwrap()); assert_eq!(1, state.load(Ordering::SeqCst)); } #[test] fn drop_read() { let state = AtomicIsize::new(0); let x = 5u8; { let _borrow = Borrowed::new(&x, Borrow::aquire_read(&state).unwrap()); assert_eq!(1, state.load(Ordering::SeqCst)); } assert_eq!(0, state.load(Ordering::SeqCst)); } #[test] fn borrow_write() { let state = AtomicIsize::new(0); let x = 5u8; let _borrow = Borrowed::new(&x, Borrow::aquire_write(&state).unwrap()); assert_eq!(-1, state.load(Ordering::SeqCst)); } #[test] fn drop_write() { let state = AtomicIsize::new(0); let x = 5u8; { let _borrow = Borrowed::new(&x, Borrow::aquire_write(&state).unwrap()); assert_eq!(-1, state.load(Ordering::SeqCst)); } assert_eq!(0, state.load(Ordering::SeqCst)); } #[test] fn read_while_reading() { let state = AtomicIsize::new(0); let _read = Borrow::aquire_read(&state).unwrap(); let _read2 = Borrow::aquire_read(&state).unwrap(); } #[test] #[should_panic(expected = "resource already borrowed as immutable")] fn write_while_reading() { let state = AtomicIsize::new(0); let _read = Borrow::aquire_read(&state).unwrap(); let _write = Borrow::aquire_write(&state).unwrap(); } #[test] #[should_panic(expected = "resource already borrowed as mutable")] fn read_while_writing() { let state = AtomicIsize::new(0); let _write = Borrow::aquire_write(&state).unwrap(); let _read = Borrow::aquire_read(&state).unwrap(); } #[test] #[should_panic(expected = "resource already borrowed as mutable")] fn write_while_writing() { let state = AtomicIsize::new(0); let _write = Borrow::aquire_write(&state).unwrap(); let _write2 = Borrow::aquire_write(&state).unwrap(); } }
use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::ops::DerefMut; use std::slice::Iter; use std::slice::IterMut; use std::sync::atomic::{AtomicIsize, Ordering}; pub enum Borrow<'a> { Read { state: &'a AtomicIsize }, Write { state: &'a AtomicIsize }, } impl<'a> Borrow<'a> { pub fn aquire_read(state: &'a AtomicIsize) -> Result<Borrow<'a>, &'static str> { loop { let read = state.load(Ordering::SeqCst); if read < 0 { return Err("resource already borrowed as mutable"); } if state.compare_and_swap(read, read + 1, Ordering::SeqCst) == read { break; } } Ok(Borrow::Read { state }) } pub fn aquire_write(state: &'a AtomicIsize) -> Result<Borrow<'a>, &'static str> { let borrowed = state.compare_and_swap(0, -1, Ordering::SeqCst); match borrowed { 0 => Ok(Borrow::Write { state }), x
i: usize) -> Option<BorrowedMut<'a, T>> { let slice = self.slice; let state = self.state; slice.get_mut(i).map(|x| BorrowedMut::new(x, state)) } } impl<'a, T: 'a> Deref for BorrowedMutSlice<'a, T> { type Target = [T]; fn deref(&self) -> &Self::Target { self.slice } } impl<'a, T: 'a> DerefMut for BorrowedMutSlice<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.slice } } impl<'a, T: 'a> IntoIterator for BorrowedMutSlice<'a, T> { type Item = &'a mut T; type IntoIter = BorrowedIter<'a, IterMut<'a, T>>; fn into_iter(self) -> Self::IntoIter { BorrowedIter { inner: self.slice.into_iter(), state: self.state, } } } pub struct BorrowedIter<'a, I: 'a + Iterator> { inner: I, #[allow(dead_code)] state: Borrow<'a>, } impl<'a, I: 'a + Iterator> Iterator for BorrowedIter<'a, I> { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } impl<'a, I: 'a + ExactSizeIterator> ExactSizeIterator for BorrowedIter<'a, I> {} #[cfg(test)] mod tests { use super::*; use std::sync::atomic::{AtomicIsize, Ordering}; #[test] fn borrow_read() { let state = AtomicIsize::new(0); let x = 5u8; let _borrow = Borrowed::new(&x, Borrow::aquire_read(&state).unwrap()); assert_eq!(1, state.load(Ordering::SeqCst)); } #[test] fn drop_read() { let state = AtomicIsize::new(0); let x = 5u8; { let _borrow = Borrowed::new(&x, Borrow::aquire_read(&state).unwrap()); assert_eq!(1, state.load(Ordering::SeqCst)); } assert_eq!(0, state.load(Ordering::SeqCst)); } #[test] fn borrow_write() { let state = AtomicIsize::new(0); let x = 5u8; let _borrow = Borrowed::new(&x, Borrow::aquire_write(&state).unwrap()); assert_eq!(-1, state.load(Ordering::SeqCst)); } #[test] fn drop_write() { let state = AtomicIsize::new(0); let x = 5u8; { let _borrow = Borrowed::new(&x, Borrow::aquire_write(&state).unwrap()); assert_eq!(-1, state.load(Ordering::SeqCst)); } assert_eq!(0, state.load(Ordering::SeqCst)); } #[test] fn read_while_reading() { let state = AtomicIsize::new(0); let _read = Borrow::aquire_read(&state).unwrap(); let _read2 = Borrow::aquire_read(&state).unwrap(); } #[test] #[should_panic(expected = "resource already borrowed as immutable")] fn write_while_reading() { let state = AtomicIsize::new(0); let _read = Borrow::aquire_read(&state).unwrap(); let _write = Borrow::aquire_write(&state).unwrap(); } #[test] #[should_panic(expected = "resource already borrowed as mutable")] fn read_while_writing() { let state = AtomicIsize::new(0); let _write = Borrow::aquire_write(&state).unwrap(); let _read = Borrow::aquire_read(&state).unwrap(); } #[test] #[should_panic(expected = "resource already borrowed as mutable")] fn write_while_writing() { let state = AtomicIsize::new(0); let _write = Borrow::aquire_write(&state).unwrap(); let _write2 = Borrow::aquire_write(&state).unwrap(); } }
if x < 0 => Err("resource already borrowed as mutable"), _ => Err("resource already borrowed as immutable"), } } } impl<'a> Drop for Borrow<'a> { fn drop(&mut self) { match *self { Borrow::Read { state } => { state.fetch_sub(1, Ordering::SeqCst); } Borrow::Write { state } => { state.store(0, Ordering::SeqCst); } }; } } pub struct Borrowed<'a, T: 'a> { value: &'a T, #[allow(dead_code)] state: Borrow<'a>, } impl<'a, T: 'a> Borrowed<'a, T> { pub fn new(value: &'a T, borrow: Borrow<'a>) -> Borrowed<'a, T> { Borrowed { value, state: borrow, } } } impl<'a, 'b, T: 'a + Debug> Debug for Borrowed<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } impl<'a, 'b, T: 'a + Display> Display for Borrowed<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } impl<'a, 'b, T: 'a + PartialEq<T>> PartialEq<Borrowed<'b, T>> for Borrowed<'a, T> { fn eq(&self, other: &Borrowed<'b, T>) -> bool { self.value.eq(other.value) } } impl<'a, 'b, T: 'a + PartialEq<T>> PartialEq<T> for Borrowed<'a, T> { fn eq(&self, other: &T) -> bool { self.value.eq(other) } } impl<'a, 'b, T: 'a + Eq> Eq for Borrowed<'a, T> {} impl<'a, T: 'a> Deref for Borrowed<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.value } } impl<'a, T: 'a> AsRef<T> for Borrowed<'a, T> { fn as_ref(&self) -> &T { self.value } } impl<'a, T: 'a> std::borrow::Borrow<T> for Borrowed<'a, T> { fn borrow(&self) -> &T { self.value } } pub struct BorrowedMut<'a, T: 'a> { value: &'a mut T, #[allow(dead_code)] state: Borrow<'a>, } impl<'a, T: 'a> BorrowedMut<'a, T> { pub fn new(value: &'a mut T, borrow: Borrow<'a>) -> BorrowedMut<'a, T> { BorrowedMut { value, state: borrow, } } } impl<'a, T: 'a> Deref for BorrowedMut<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.value } } impl<'a, T: 'a> DerefMut for BorrowedMut<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.value } } impl<'a, T: 'a> AsRef<T> for BorrowedMut<'a, T> { fn as_ref(&self) -> &T { self.value } } impl<'a, T: 'a> std::borrow::Borrow<T> for BorrowedMut<'a, T> { fn borrow(&self) -> &T { self.value } } impl<'a, 'b, T: 'a + Debug> Debug for BorrowedMut<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } impl<'a, 'b, T: 'a + Display> Display for BorrowedMut<'a, T> { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { self.value.fmt(formatter) } } pub struct BorrowedSlice<'a, T: 'a> { slice: &'a [T], state: Borrow<'a>, } impl<'a, T: 'a> BorrowedSlice<'a, T> { pub fn new(slice: &'a [T], borrow: Borrow<'a>) -> BorrowedSlice<'a, T> { BorrowedSlice { slice, state: borrow, } } pub fn single(self, i: usize) -> Option<Borrowed<'a, T>> { let slice = self.slice; let state = self.state; slice.get(i).map(|x| Borrowed::new(x, state)) } } impl<'a, T: 'a> Deref for BorrowedSlice<'a, T> { type Target = [T]; fn deref(&self) -> &Self::Target { self.slice } } impl<'a, T: 'a> IntoIterator for BorrowedSlice<'a, T> { type Item = &'a T; type IntoIter = BorrowedIter<'a, Iter<'a, T>>; fn into_iter(self) -> Self::IntoIter { BorrowedIter { inner: self.slice.into_iter(), state: self.state, } } } pub struct BorrowedMutSlice<'a, T: 'a> { slice: &'a mut [T], state: Borrow<'a>, } impl<'a, T: 'a> BorrowedMutSlice<'a, T> { pub fn new(slice: &'a mut [T], borrow: Borrow<'a>) -> BorrowedMutSlice<'a, T> { BorrowedMutSlice { slice, state: borrow, } } pub fn single(self,
random
[ { "content": "/// A type which can fetch a strongly-typed view of the data contained\n\n/// within a `Chunk`.\n\npub trait View<'a>: Sized + Send + Sync + 'static {\n\n /// The iterator over the chunk data.\n\n type Iter: Iterator + 'a;\n\n\n\n /// Pulls data out of a chunk.\n\n fn fetch(chunk: &'a ...
Rust
src/route.rs
quarterblue/-kademlia-dht
de82d5407922f97a6b7885c9dea4828b7ed04f55
use crate::node::{Bit, ByteString, Node, ID_LENGTH}; use std::cell::RefCell; use std::iter::Iterator; use std::rc::Rc; use std::rc::Weak; const K_BUCKET_SIZE: usize = 4; type LeafNode = Option<Rc<RefCell<Vertex>>>; #[derive(Debug)] pub struct KBucket { node_bucket: Vec<Node>, depth: usize, } impl KBucket { pub fn new() -> Self { KBucket { node_bucket: Vec::with_capacity(K_BUCKET_SIZE), depth: 0, } } pub fn sort(&mut self) {} fn split(&self) -> (Option<KBucket>, Option<KBucket>) { let mut left = KBucket::new(); let mut right = KBucket::new(); left.depth = self.depth + 1; right.depth = self.depth + 1; for node in &self.node_bucket { match node.node_id.index(self.depth + 1) { 1 => left.node_bucket.push(*node), 0 => right.node_bucket.push(*node), _ => unreachable!(), } } (Some(left), Some(right)) } } #[derive(Debug)] pub struct Vertex { bit: Bit, k_bucket: Option<KBucket>, parent: Option<Weak<RefCell<Vertex>>>, left: LeafNode, right: LeafNode, } impl Vertex { fn new(bit: Bit) -> Vertex { Vertex { bit, k_bucket: Some(KBucket::new()), parent: None, left: None, right: None, } } fn split( vertex: &Rc<RefCell<Vertex>>, ) -> (Option<Rc<RefCell<Vertex>>>, Option<Rc<RefCell<Vertex>>>) { let mut left = Vertex::new(Bit::One); let mut right = Vertex::new(Bit::Zero); let tuple = vertex.borrow().k_bucket.as_ref().unwrap().split(); vertex.borrow_mut().k_bucket = None; left.k_bucket = tuple.0; right.k_bucket = tuple.1; ( Some(Rc::new(RefCell::new(left))), Some(Rc::new(RefCell::new(right))), ) } fn add_node<I: Iterator<Item = u8>>( vertex: &Rc<RefCell<Vertex>>, node: Node, node_iter: &mut I, node_id: &ByteString, prefix_contained: bool, ) { let has_k_bucket: bool; let mut split: bool = false; { has_k_bucket = vertex.borrow().k_bucket.is_some(); } match has_k_bucket { true => { { let mut vert = vertex.borrow_mut(); let bucket = vert.k_bucket.as_mut().unwrap(); if bucket.node_bucket.len() < K_BUCKET_SIZE { bucket.node_bucket.push(node); return; } if prefix_contained { let node_iter_next: u8 = node_iter.next().unwrap(); match node_iter_next { 1 => { if !matches!(vert.bit, Bit::One) { split = false; } } 0 => { if !matches!(vert.bit, Bit::Zero) { split = false; } } _ => {} } } } if split { let (left_vert, right_vert) = Vertex::split(vertex); { left_vert.as_ref().unwrap().borrow_mut().parent = Some(Rc::downgrade(&Rc::clone(vertex))); right_vert.as_ref().unwrap().borrow_mut().parent = Some(Rc::downgrade(&Rc::clone(vertex))); } { vertex.borrow_mut().left = left_vert; vertex.borrow_mut().right = right_vert; } Vertex::add_node(vertex, node, node_iter, &node_id, false); } } false => match node_iter.next().unwrap() { 1 => match &vertex.borrow().left { Some(vert) => { Vertex::add_node(vert, node, node_iter, &node_id, prefix_contained); } None => {} }, 0 => match &vertex.borrow().right { Some(vert) => { Vertex::add_node(vert, node, node_iter, &node_id, prefix_contained); } None => {} }, _ => unreachable!(), }, } } } #[derive(Debug)] pub struct RouteTable { pub length: u64, node_id: ByteString, root: LeafNode, } impl RouteTable { pub fn empty_new(node_id: ByteString) -> Self { RouteTable { length: 0, node_id, root: Some(Rc::new(RefCell::new(Vertex::new(Bit::Root)))), } } pub fn add_vertex() {} pub fn add_node(&mut self, node: Node) { match self.root.as_mut() { Some(x) => { let mut iter = node.node_id.into_iter(); Vertex::add_node(x, node, &mut iter, &self.node_id, true); self.length += 1; } None => { panic!("Root does not exist"); } } } fn find_closest(&self, node_id: [u8; ID_LENGTH]) -> Vec<Node> { let alpha_nodes: Vec<Node> = Vec::new(); match self.root { Some(ref x) => match &x.borrow_mut().k_bucket { Some(bucket) => {} None => {} }, None => {} } return alpha_nodes; } }
use crate::node::{Bit, ByteString, Node, ID_LENGTH}; use std::cell::RefCell; use std::iter::Iterator; use std::rc::Rc; use std::rc::Weak; const K_BUCKET_SIZE: usize = 4; type LeafNode = Option<Rc<RefCell<Vertex>>>; #[derive(Debug)] pub struct KBucket { node_bucket: Vec<Node>, depth: usize, } impl KBucket { pub fn new() -> Self { KBucket { node_bucket: Vec::with_capacity(K_BUCKET_SIZE), depth: 0, } } pub fn sort(&mut self) {} fn split(&self) -> (Option<KBucket>, Option<KBucket>) { let mut left = KBucket::new(); let mut right = KBucket::new(); left.depth = self.depth + 1; right.depth = self.depth + 1; for node in &self.node_bucket { match node.node_id.index(self.depth + 1) { 1 => left.node_bucket.push(*node), 0 => right.node_bucket.push(*node), _ => unreachable!(), } } (Some(left), Some(right)) } } #[derive(Debug)] pub struct Vertex { bit: Bit, k_bucket: Option<KBucket>, parent: Option<Weak<RefCell<Vertex>>>, left: LeafNode, right: LeafNode, } impl Vertex { fn new(bit: Bit) -> Vertex { Vertex { bit, k_bucket: Some(KBucket::new()), parent: None, left: None, right: None, } } fn split( vertex: &Rc<RefCell<Vertex>>, ) -> (Option<Rc<RefCell<Vertex>>>, Option<Rc<RefCell<Vertex>>>) { let mut left = Vertex::new(Bit::One); let mut right = Vertex::new(Bit::Zero); let tuple = vertex.borrow().k_bucket.as_ref().unwrap().split(); vertex.borrow_mut().k_bucket = None; left.k_bucket = tuple.0; right.k_bucket = tuple.1; ( Some(Rc::new(RefCell::new(left))), Some(Rc::new(RefCell::new(right))), ) } fn add_node<I: Iterator<Item = u8>>( vertex: &Rc<RefCell<Vertex>>, node: Node, node_iter: &mut I, node_id: &ByteString, prefix_contained: bool, ) { let has_k_bucket: bool; let mut split: bool = false; { has_k_bucket = vertex.borrow().k_bucket.is_some(); } match has_k_bucket { true => { { let mut vert = vertex.borrow_mut(); let bucket = vert.k_bucket.as_mut().unwrap(); if bucket.node_bucket.len() < K_BUCKET_SIZE { bucket.node_bucket.push(node); return; } if prefix_contained { let node_iter_next: u8 = node_iter.next().unwrap();
vertex.borrow_mut().left = left_vert; vertex.borrow_mut().right = right_vert; } Vertex::add_node(vertex, node, node_iter, &node_id, false); } } false => match node_iter.next().unwrap() { 1 => match &vertex.borrow().left { Some(vert) => { Vertex::add_node(vert, node, node_iter, &node_id, prefix_contained); } None => {} }, 0 => match &vertex.borrow().right { Some(vert) => { Vertex::add_node(vert, node, node_iter, &node_id, prefix_contained); } None => {} }, _ => unreachable!(), }, } } } #[derive(Debug)] pub struct RouteTable { pub length: u64, node_id: ByteString, root: LeafNode, } impl RouteTable { pub fn empty_new(node_id: ByteString) -> Self { RouteTable { length: 0, node_id, root: Some(Rc::new(RefCell::new(Vertex::new(Bit::Root)))), } } pub fn add_vertex() {} pub fn add_node(&mut self, node: Node) { match self.root.as_mut() { Some(x) => { let mut iter = node.node_id.into_iter(); Vertex::add_node(x, node, &mut iter, &self.node_id, true); self.length += 1; } None => { panic!("Root does not exist"); } } } fn find_closest(&self, node_id: [u8; ID_LENGTH]) -> Vec<Node> { let alpha_nodes: Vec<Node> = Vec::new(); match self.root { Some(ref x) => match &x.borrow_mut().k_bucket { Some(bucket) => {} None => {} }, None => {} } return alpha_nodes; } }
match node_iter_next { 1 => { if !matches!(vert.bit, Bit::One) { split = false; } } 0 => { if !matches!(vert.bit, Bit::Zero) { split = false; } } _ => {} } } } if split { let (left_vert, right_vert) = Vertex::split(vertex); { left_vert.as_ref().unwrap().borrow_mut().parent = Some(Rc::downgrade(&Rc::clone(vertex))); right_vert.as_ref().unwrap().borrow_mut().parent = Some(Rc::downgrade(&Rc::clone(vertex))); } {
random
[ { "content": "pub fn deserialize_message(v: Vec<u8>) -> Message {\n\n bincode::deserialize(&v).expect(\"Could not serialize message\")\n\n}\n\n\n", "file_path": "src/rpc.rs", "rank": 1, "score": 65682.53778056285 }, { "content": "pub fn serialize_message(msg: Message) -> Vec<u8> {\n\n ...
Rust
sulis_module/src/generator/terrain_tiles.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
use std::collections::HashMap; use std::io::Error; use std::rc::Rc; use crate::{ area::tile::{EdgeRules, TerrainKind, TerrainRules, Tile}, Module, }; use sulis_core::util::unable_to_create_error; #[derive(Clone)] pub struct TerrainTiles { pub id: String, pub base: Rc<Tile>, pub base_weight: u32, pub variants: Vec<Rc<Tile>>, pub edges: EdgesList, pub borders: HashMap<usize, EdgesList>, } impl PartialEq for TerrainTiles { fn eq(&self, other: &TerrainTiles) -> bool { self.id == other.id } } impl Eq for TerrainTiles {} #[derive(Clone)] pub struct EdgesList { pub inner_nw: Option<Rc<Tile>>, pub inner_ne: Option<Rc<Tile>>, pub inner_sw: Option<Rc<Tile>>, pub inner_se: Option<Rc<Tile>>, pub outer_n: Option<Rc<Tile>>, pub outer_s: Option<Rc<Tile>>, pub outer_e: Option<Rc<Tile>>, pub outer_w: Option<Rc<Tile>>, pub outer_se: Option<Rc<Tile>>, pub outer_ne: Option<Rc<Tile>>, pub outer_sw: Option<Rc<Tile>>, pub outer_nw: Option<Rc<Tile>>, pub outer_all: Option<Rc<Tile>>, pub inner_ne_sw: Option<Rc<Tile>>, pub inner_nw_se: Option<Rc<Tile>>, } impl EdgesList { pub fn new(id: &str, prefix: &str, rules: &EdgeRules) -> Result<EdgesList, Error> { let inner_nw = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.nw_postfix); let inner_ne = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.ne_postfix); let inner_sw = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.sw_postfix); let inner_se = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.se_postfix); let outer_n = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.n_postfix); let outer_s = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.s_postfix); let outer_e = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.e_postfix); let outer_w = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.w_postfix); let outer_ne = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.ne_postfix); let outer_nw = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.nw_postfix); let outer_se = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.se_postfix); let outer_sw = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.sw_postfix); let outer_all = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.all_postfix); let inner_ne_sw = EdgesList::get_edge( prefix, id, &rules.inner_edge_postfix, &rules.ne_sw_postfix, ); let inner_nw_se = EdgesList::get_edge( prefix, id, &rules.inner_edge_postfix, &rules.nw_se_postfix, ); Ok(EdgesList { inner_nw, inner_ne, inner_sw, inner_se, outer_n, outer_s, outer_e, outer_w, outer_se, outer_ne, outer_sw, outer_nw, outer_all, inner_ne_sw, inner_nw_se, }) } fn get_edge(prefix: &str, id: &str, edge_postfix: &str, dir_postfix: &str) -> Option<Rc<Tile>> { let tile_id = format!("{}{}{}{}", prefix, id, edge_postfix, dir_postfix); match Module::tile(&tile_id) { None => { trace!( "Edge tile with '{}', '{}' not found for '{}'. Full path: '{}'", edge_postfix, dir_postfix, id, tile_id, ); None } Some(tile) => Some(tile), } } } impl TerrainTiles { pub fn new( rules: &TerrainRules, kind: &TerrainKind, all_kinds: &[TerrainKind], ) -> Result<TerrainTiles, Error> { let base_tile_id = format!("{}{}{}", rules.prefix, kind.id, rules.base_postfix); let base = match Module::tile(&base_tile_id) { None => { warn!("Base tile for terrain kind '{}' not found", kind.id); return unable_to_create_error("terrain_tiles", &kind.id); } Some(tile) => tile, }; let base_weight = match kind.base_weight { None => rules.base_weight, Some(weight) => weight, }; let mut variants = Vec::new(); for i in kind.variants.iter() { let tile_id = format!( "{}{}{}{}", rules.prefix, kind.id, rules.variant_postfix, i.to_string() ); let tile = match Module::tile(&tile_id) { None => { warn!( "Tile variant '{}' not found for terrain kind '{}'", i, kind.id ); continue; } Some(tile) => tile, }; variants.push(tile); } let mut borders = HashMap::new(); for (other_terrain, id) in kind.borders.iter() { let edges = EdgesList::new(id, &rules.prefix, &rules.edges)?; let mut index = None; for (i, other_kind) in all_kinds.iter().enumerate() { if &other_kind.id == other_terrain { index = Some(i); break; } } match index { None => { warn!( "Other terrain '{}' not found for border of '{}'", other_terrain, kind.id ); continue; } Some(index) => { borders.insert(index, edges); } } } let edges = EdgesList::new(&kind.id, &rules.prefix, &rules.edges)?; Ok(TerrainTiles { id: kind.id.clone(), base, base_weight, variants, borders, edges, }) } pub fn matching_edges(&self, index: Option<usize>) -> &EdgesList { match index { None => &self.edges, Some(index) => match self.borders.get(&index) { None => &self.edges, Some(edges) => edges, }, } } }
use std::collections::HashMap; use std::io::Error; use std::rc::Rc; use crate::{ area::tile::{EdgeRules, TerrainKind, TerrainRules, Tile}, Module, }; use sulis_core::util::unable_to_create_error; #[derive(Clone)] pub struct TerrainTiles { pub id: String, pub base: Rc<Tile>, pub base_weight: u32, pub variants: Vec<Rc<Tile>>, pub edges: EdgesList, pub borders: HashMap<usize, EdgesList>, } impl PartialEq for TerrainTiles { fn eq(&self, other: &TerrainTiles) -> bool { self.id == other.id } } impl Eq for TerrainTiles {} #[derive(Clone)] pub struct EdgesList { pub inner_nw: Option<Rc<Tile>>, pub inner_ne: Option<Rc<Tile>>, pub inner_sw: Option<Rc<Tile>>, pub inner_se: Option<Rc<Tile>>, pub outer_n: Option<Rc<Tile>>, pub outer_s: Option<Rc<Tile>>, pub outer_e: Option<Rc<Tile>>, pub outer_w: Option<Rc<Tile>>, pub outer_se: Option<Rc<Tile>>, pub outer_ne: Option<Rc<Tile>>, pub outer_sw: Option<Rc<Tile>>, pub outer_nw: Option<Rc<Tile>>, pub outer_all: Option<Rc<Tile>>, pub inner_ne_sw: Option<Rc<Tile>>, pub inner_nw_se: Option<Rc<Tile>>, } impl EdgesList { pub fn new(id: &str, prefix: &str, rules: &EdgeRules) -> Result<EdgesList, Error> { let inner_nw = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.nw_postfix); let inner_ne = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.ne_postfix); let inner_sw = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.sw_postfix); let inner_se = EdgesList::get_edge(prefix, id, &rules.inner_edge_postfix, &rules.se_postfix); let outer_n = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.n_postfix); let outer_s = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.s_postfix); let outer_e = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.e_postfix); let outer_w = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.w_postfix); let outer_ne = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.ne_postfix); let outer_nw = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.nw_postfix); let outer_se = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.se_postfix); let outer_sw = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.sw_postfix); let outer_all = EdgesList::get_edge(prefix, id, &rules.outer_edge_postfix, &rules.all_postfix); let inner_ne_sw = EdgesList::get_edge( prefix, id, &rules.inner_edge_postfix, &rules.ne_sw_postfix, ); let inner_nw_se = EdgesList::get_edge( prefix, id, &rules.inner_edge_postfix, &rules.nw_se_postfix, );
} fn get_edge(prefix: &str, id: &str, edge_postfix: &str, dir_postfix: &str) -> Option<Rc<Tile>> { let tile_id = format!("{}{}{}{}", prefix, id, edge_postfix, dir_postfix); match Module::tile(&tile_id) { None => { trace!( "Edge tile with '{}', '{}' not found for '{}'. Full path: '{}'", edge_postfix, dir_postfix, id, tile_id, ); None } Some(tile) => Some(tile), } } } impl TerrainTiles { pub fn new( rules: &TerrainRules, kind: &TerrainKind, all_kinds: &[TerrainKind], ) -> Result<TerrainTiles, Error> { let base_tile_id = format!("{}{}{}", rules.prefix, kind.id, rules.base_postfix); let base = match Module::tile(&base_tile_id) { None => { warn!("Base tile for terrain kind '{}' not found", kind.id); return unable_to_create_error("terrain_tiles", &kind.id); } Some(tile) => tile, }; let base_weight = match kind.base_weight { None => rules.base_weight, Some(weight) => weight, }; let mut variants = Vec::new(); for i in kind.variants.iter() { let tile_id = format!( "{}{}{}{}", rules.prefix, kind.id, rules.variant_postfix, i.to_string() ); let tile = match Module::tile(&tile_id) { None => { warn!( "Tile variant '{}' not found for terrain kind '{}'", i, kind.id ); continue; } Some(tile) => tile, }; variants.push(tile); } let mut borders = HashMap::new(); for (other_terrain, id) in kind.borders.iter() { let edges = EdgesList::new(id, &rules.prefix, &rules.edges)?; let mut index = None; for (i, other_kind) in all_kinds.iter().enumerate() { if &other_kind.id == other_terrain { index = Some(i); break; } } match index { None => { warn!( "Other terrain '{}' not found for border of '{}'", other_terrain, kind.id ); continue; } Some(index) => { borders.insert(index, edges); } } } let edges = EdgesList::new(&kind.id, &rules.prefix, &rules.edges)?; Ok(TerrainTiles { id: kind.id.clone(), base, base_weight, variants, borders, edges, }) } pub fn matching_edges(&self, index: Option<usize>) -> &EdgesList { match index { None => &self.edges, Some(index) => match self.borders.get(&index) { None => &self.edges, Some(edges) => edges, }, } } }
Ok(EdgesList { inner_nw, inner_ne, inner_sw, inner_se, outer_n, outer_s, outer_e, outer_w, outer_se, outer_ne, outer_sw, outer_nw, outer_all, inner_ne_sw, inner_nw_se, })
call_expression
[]
Rust
src/i2s/rx_timing.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
#[doc = "Reader of register RX_TIMING"] pub type R = crate::R<u32, super::RX_TIMING>; #[doc = "Writer for register RX_TIMING"] pub type W = crate::W<u32, super::RX_TIMING>; #[doc = "Register RX_TIMING `reset()`'s with value 0"] impl crate::ResetValue for super::RX_TIMING { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RX_BCK_IN_DM`"] pub type RX_BCK_IN_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_BCK_IN_DM`"] pub struct RX_BCK_IN_DM_W<'a> { w: &'a mut W, } impl<'a> RX_BCK_IN_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 28)) | (((value as u32) & 0x03) << 28); self.w } } #[doc = "Reader of field `RX_WS_IN_DM`"] pub type RX_WS_IN_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_WS_IN_DM`"] pub struct RX_WS_IN_DM_W<'a> { w: &'a mut W, } impl<'a> RX_WS_IN_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24); self.w } } #[doc = "Reader of field `RX_BCK_OUT_DM`"] pub type RX_BCK_OUT_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_BCK_OUT_DM`"] pub struct RX_BCK_OUT_DM_W<'a> { w: &'a mut W, } impl<'a> RX_BCK_OUT_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20); self.w } } #[doc = "Reader of field `RX_WS_OUT_DM`"] pub type RX_WS_OUT_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_WS_OUT_DM`"] pub struct RX_WS_OUT_DM_W<'a> { w: &'a mut W, } impl<'a> RX_WS_OUT_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `RX_SD_IN_DM`"] pub type RX_SD_IN_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_SD_IN_DM`"] pub struct RX_SD_IN_DM_W<'a> { w: &'a mut W, } impl<'a> RX_SD_IN_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03); self.w } } impl R { #[doc = "Bits 28:29"] #[inline(always)] pub fn rx_bck_in_dm(&self) -> RX_BCK_IN_DM_R { RX_BCK_IN_DM_R::new(((self.bits >> 28) & 0x03) as u8) } #[doc = "Bits 24:25"] #[inline(always)] pub fn rx_ws_in_dm(&self) -> RX_WS_IN_DM_R { RX_WS_IN_DM_R::new(((self.bits >> 24) & 0x03) as u8) } #[doc = "Bits 20:21"] #[inline(always)] pub fn rx_bck_out_dm(&self) -> RX_BCK_OUT_DM_R { RX_BCK_OUT_DM_R::new(((self.bits >> 20) & 0x03) as u8) } #[doc = "Bits 16:17"] #[inline(always)] pub fn rx_ws_out_dm(&self) -> RX_WS_OUT_DM_R { RX_WS_OUT_DM_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bits 0:1"] #[inline(always)] pub fn rx_sd_in_dm(&self) -> RX_SD_IN_DM_R { RX_SD_IN_DM_R::new((self.bits & 0x03) as u8) } } impl W { #[doc = "Bits 28:29"] #[inline(always)] pub fn rx_bck_in_dm(&mut self) -> RX_BCK_IN_DM_W { RX_BCK_IN_DM_W { w: self } } #[doc = "Bits 24:25"] #[inline(always)] pub fn rx_ws_in_dm(&mut self) -> RX_WS_IN_DM_W { RX_WS_IN_DM_W { w: self } } #[doc = "Bits 20:21"] #[inline(always)] pub fn rx_bck_out_dm(&mut self) -> RX_BCK_OUT_DM_W { RX_BCK_OUT_DM_W { w: self } } #[doc = "Bits 16:17"] #[inline(always)] pub fn rx_ws_out_dm(&mut self) -> RX_WS_OUT_DM_W { RX_WS_OUT_DM_W { w: self } } #[doc = "Bits 0:1"] #[inline(always)] pub fn rx_sd_in_dm(&mut self) -> RX_SD_IN_DM_W { RX_SD_IN_DM_W { w: self } } }
#[doc = "Reader of register RX_TIMING"] pub type R = crate::R<u32, super::RX_TIMING>; #[doc = "Writer for register RX_TIMING"] pub type W = crate::W<u32, super::RX_TIMING>; #[doc = "Register RX_TIMING `reset()`'s with value 0"] impl crate::ResetValue for super::RX_TIMING { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RX_BCK_IN_DM`"] pub type RX_BCK_IN_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_BCK_IN_DM`"] pub struct RX_BCK_IN_DM_W<'a> { w: &'a mut W, } impl<'a> RX_BCK_IN_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 28)) | (((value as u32) & 0x03) << 28); self.w } } #[doc = "Reader of field `RX_WS_IN_DM`"] pub type RX_WS_IN_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_WS_IN_DM`"] pub struct RX_WS_IN_DM_W<'a> { w: &'a mut W, } impl<'a> RX_WS_IN_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24); self.w } } #[doc = "Reader of field `RX_BCK_OUT_DM`"] pub type RX_BCK_OUT_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_BCK_OUT_DM`"] pub struct RX_BCK_OUT_DM_W<'a> { w: &'a mut W, } impl<'a> RX_BCK_OUT_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20); self.w } } #[doc = "Reader of field `RX_WS_OUT_DM`"] pub type RX_WS_OUT_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_WS_OUT_DM`"] pub struct RX_WS_OUT_DM_W<'a> { w: &'a mut W,
w: self } } #[doc = "Bits 16:17"] #[inline(always)] pub fn rx_ws_out_dm(&mut self) -> RX_WS_OUT_DM_W { RX_WS_OUT_DM_W { w: self } } #[doc = "Bits 0:1"] #[inline(always)] pub fn rx_sd_in_dm(&mut self) -> RX_SD_IN_DM_W { RX_SD_IN_DM_W { w: self } } }
} impl<'a> RX_WS_OUT_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `RX_SD_IN_DM`"] pub type RX_SD_IN_DM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_SD_IN_DM`"] pub struct RX_SD_IN_DM_W<'a> { w: &'a mut W, } impl<'a> RX_SD_IN_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03); self.w } } impl R { #[doc = "Bits 28:29"] #[inline(always)] pub fn rx_bck_in_dm(&self) -> RX_BCK_IN_DM_R { RX_BCK_IN_DM_R::new(((self.bits >> 28) & 0x03) as u8) } #[doc = "Bits 24:25"] #[inline(always)] pub fn rx_ws_in_dm(&self) -> RX_WS_IN_DM_R { RX_WS_IN_DM_R::new(((self.bits >> 24) & 0x03) as u8) } #[doc = "Bits 20:21"] #[inline(always)] pub fn rx_bck_out_dm(&self) -> RX_BCK_OUT_DM_R { RX_BCK_OUT_DM_R::new(((self.bits >> 20) & 0x03) as u8) } #[doc = "Bits 16:17"] #[inline(always)] pub fn rx_ws_out_dm(&self) -> RX_WS_OUT_DM_R { RX_WS_OUT_DM_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bits 0:1"] #[inline(always)] pub fn rx_sd_in_dm(&self) -> RX_SD_IN_DM_R { RX_SD_IN_DM_R::new((self.bits & 0x03) as u8) } } impl W { #[doc = "Bits 28:29"] #[inline(always)] pub fn rx_bck_in_dm(&mut self) -> RX_BCK_IN_DM_W { RX_BCK_IN_DM_W { w: self } } #[doc = "Bits 24:25"] #[inline(always)] pub fn rx_ws_in_dm(&mut self) -> RX_WS_IN_DM_W { RX_WS_IN_DM_W { w: self } } #[doc = "Bits 20:21"] #[inline(always)] pub fn rx_bck_out_dm(&mut self) -> RX_BCK_OUT_DM_W { RX_BCK_OUT_DM_W {
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/entity/manager.rs
Connicpu/conniecs
b914ff8a5ebc8214869f588aa21e2a11d695f306
use index_pool::IndexPool; use vec_map::VecMap; use std::collections::hash_map::HashMap; use std::marker::PhantomData; use std::mem; use crate::component::ComponentManager; use crate::entity::iter::{EntityIter, IndexedEntityIter}; use crate::entity::{BuildData, Entity, EntityBuilder, EntityData, Id, IndexedEntity}; use crate::services::ServiceManager; use crate::system::SystemManager; enum Event { BuildEntity(Entity), RemoveEntity(Entity), } pub struct EntityManager<C> where C: ComponentManager, { indices: IndexPool, indexed_entities: VecMap<IndexedEntity<C>>, entities: HashMap<Entity, IndexedEntity<C>>, event_queue: Vec<Event>, next_id: Id, } impl<C> EntityManager<C> where C: ComponentManager, { pub fn new() -> Self { EntityManager { indices: IndexPool::new(), indexed_entities: VecMap::new(), entities: HashMap::new(), event_queue: Vec::new(), next_id: 0, } } pub fn flush_queue<M, S>(&mut self, components: &mut C, services: &mut M, systems: &mut S) where M: ServiceManager, S: SystemManager<Components = C, Services = M>, { use self::Event::*; let mut queue = mem::replace(&mut self.event_queue, Vec::new()); for e in queue.drain(..) { match e { BuildEntity(entity) => { systems.activated(EntityData(self.indexed(entity)), components, services); } RemoveEntity(entity) => { systems.deactivated(EntityData(self.indexed(entity)), components, services); } } } self.event_queue = queue; } pub fn create_entity<B, M>( &mut self, builder: B, components: &mut C, services: &mut M, ) -> Entity where B: EntityBuilder<C, M>, M: ServiceManager, { let entity = self.create(); builder.build(BuildData(self.indexed(entity)), components, services); self.event_queue.push(Event::BuildEntity(entity)); entity } pub fn remove_entity(&mut self, entity: Entity) -> bool { if self.entities.contains_key(&entity) { self.event_queue.push(Event::RemoveEntity(entity)); true } else { false } } pub fn iter(&self) -> EntityIter<C> { EntityIter::Indexed(IndexedEntityIter { iter: self.indices.all_indices(), values: &self.indexed_entities, }) } pub fn count(&self) -> usize { self.indices.maximum() } pub fn indexed(&self, entity: Entity) -> &IndexedEntity<C> { &self.entities[&entity] } pub fn create(&mut self) -> Entity { self.next_id += 1; let entity = Entity { id: self.next_id }; let ie = IndexedEntity { index: self.indices.new_id(), entity, _marker: PhantomData, }; self.indexed_entities.insert(ie.index, ie.__clone()); self.entities.insert(entity, ie); entity } #[inline] pub fn is_valid(&self, entity: Entity) -> bool { self.entities.contains_key(&entity) } pub fn remove(&mut self, entity: Entity) { self.entities .remove(&entity) .map(|e| self.indices.return_id(e.index())); } pub fn clear(&mut self) { self.entities.clear(); self.indices = IndexPool::new(); } }
use index_pool::IndexPool; use vec_map::VecMap; use std::collections::hash_map::HashMap; use std::marker::PhantomData; use std::mem; use crate::component::ComponentManager; use crate::entity::iter::{EntityIter, IndexedEntityIter}; use crate::entity::{BuildData, Entity, EntityBuilder, EntityData, Id, IndexedEntity}; use crate::services::ServiceManager; use crate::system::SystemManager; enum Event { BuildEntity(Entity), RemoveEntity(Entity), } pub struct EntityManager<C> where C: ComponentManager, { indices: IndexPool, indexed_entities: VecMap<IndexedEntity<C>>, entities: HashMap<Entity, IndexedEntity<C>>, event_queue: Vec<Event>, next_id: Id, } impl<C> EntityManager<C> where C: ComponentManager, { pub fn new() -> Self { EntityManager { indices: IndexPool::new(), indexed_entities: VecMap::new(), entities: HashMap::new(), event_queue: Vec::new(), next_id: 0, } } pub fn flush_queue<M, S>(&mut self, components: &mut C, services: &mut M, systems: &mut S) where M: ServiceManager, S: SystemManager<Components = C, Services = M>, { use self::Event::*; let mut queue = mem::replace(&mut self.event_queue, Vec::new()); for e in queue.drain(..) { match e { BuildEntity(entity) => { systems.activated(EntityData(self.indexed(entity)), components, services); } RemoveEntity(entity) => { systems.deactivated(EntityData(self.indexed(entity)), components, services); } } } self.event_queue = queue; } pub fn create_entity<B, M>( &mut self, builder: B, components: &mut C, services: &mut M, ) -> Entity where B: EntityBuilder<C, M>, M: ServiceManager, { let entity = self.create(); builder.build(BuildData(self.indexed(entity)), components, services); self.event_queue.push(Event::BuildEntity(entity)); entity } pub fn remove_entity(&mut self, entity: Entity) -> bool {
} pub fn iter(&self) -> EntityIter<C> { EntityIter::Indexed(IndexedEntityIter { iter: self.indices.all_indices(), values: &self.indexed_entities, }) } pub fn count(&self) -> usize { self.indices.maximum() } pub fn indexed(&self, entity: Entity) -> &IndexedEntity<C> { &self.entities[&entity] } pub fn create(&mut self) -> Entity { self.next_id += 1; let entity = Entity { id: self.next_id }; let ie = IndexedEntity { index: self.indices.new_id(), entity, _marker: PhantomData, }; self.indexed_entities.insert(ie.index, ie.__clone()); self.entities.insert(entity, ie); entity } #[inline] pub fn is_valid(&self, entity: Entity) -> bool { self.entities.contains_key(&entity) } pub fn remove(&mut self, entity: Entity) { self.entities .remove(&entity) .map(|e| self.indices.return_id(e.index())); } pub fn clear(&mut self) { self.entities.clear(); self.indices = IndexPool::new(); } }
if self.entities.contains_key(&entity) { self.event_queue.push(Event::RemoveEntity(entity)); true } else { false }
if_condition
[ { "content": "fn activated(_: &mut IVSystem, _: EntityData, _: &Components, _: &mut Services) {\n\n ATOMIC_BOOP.store(true, std::sync::atomic::Ordering::SeqCst);\n\n}\n\n\n", "file_path": "tests/aspects.rs", "rank": 0, "score": 173722.56101871424 }, { "content": "pub trait EntityBuilder<C...
Rust
tests/integration.rs
saltyrtc/saltyrtc-task-relayed-data-rs
c290b4ae7e1cbed145b16c34b17e1f6bf8380465
extern crate env_logger; #[macro_use] extern crate log; extern crate saltyrtc_client; extern crate saltyrtc_task_relayed_data; extern crate tokio_core; extern crate tokio_timer; use std::boxed::Box; use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::{Arc, RwLock}; use std::time::Duration; use saltyrtc_client::{WsClient, SaltyClient, CloseCode, BoxedFuture}; use saltyrtc_client::crypto::{PublicKey, KeyPair, AuthToken}; use saltyrtc_client::dep::futures::{Future, Stream, Sink}; use saltyrtc_client::dep::futures::future; use saltyrtc_client::dep::futures::sync::mpsc; use saltyrtc_client::dep::native_tls::{Certificate, TlsConnector, Protocol}; use saltyrtc_client::dep::rmpv::Value; use saltyrtc_client::tasks::Task; use saltyrtc_task_relayed_data::{RelayedDataTask, MessageEvent, OutgoingMessage, RelayedDataError}; use tokio_core::reactor::{Core, Remote}; use tokio_timer::Timer; macro_rules! boxed { ($future:expr) => {{ Box::new($future) as BoxedFuture<_, _> }} } fn setup_initiator( keypair: KeyPair, remote: Remote, ) -> (SaltyClient, mpsc::UnboundedReceiver<MessageEvent>) { let (tx, rx) = mpsc::unbounded(); let task = RelayedDataTask::new(remote, tx); let salty = SaltyClient::build(keypair) .add_task(Box::new(task)) .initiator() .expect("Could not create initiator"); (salty, rx) } fn setup_responder( keypair: KeyPair, remote: Remote, pubkey: PublicKey, auth_token: AuthToken, ) -> (SaltyClient, mpsc::UnboundedReceiver<MessageEvent>) { let (tx, rx) = mpsc::unbounded(); let task = RelayedDataTask::new(remote, tx); let salty = SaltyClient::build(keypair) .add_task(Box::new(task)) .responder(pubkey, auth_token) .expect("Could not create initiator"); (salty, rx) } #[test] fn integration_test() { env::set_var("RUST_LOG", "saltyrtc_client=debug,saltyrtc_task_relayed_data=debug,integration=trace"); env_logger::init(); let mut core = Core::new().unwrap(); let mut server_cert_bytes: Vec<u8> = vec![]; File::open(&Path::new("saltyrtc.der")) .expect("Could not open saltyrtc.der") .read_to_end(&mut server_cert_bytes) .expect("Could not read saltyrtc.der"); let server_cert = Certificate::from_der(&server_cert_bytes) .unwrap_or_else(|e| { panic!("Problem with CA cert: {}", e); }); let tls_connector = TlsConnector::builder() .min_protocol_version(Some(Protocol::Tlsv11)) .add_root_certificate(server_cert) .build() .unwrap_or_else(|e| panic!("Could not initialize TlsConnector: {}", e)); let initiator_keypair = KeyPair::new(); let responder_keypair = KeyPair::new(); let pubkey = initiator_keypair.public_key().clone(); let (initiator, rx_initiator) = setup_initiator(initiator_keypair, core.remote()); let (responder, rx_responder) = setup_responder(responder_keypair, core.remote(), pubkey, initiator.auth_token().cloned().unwrap()); let initiator = Arc::new(RwLock::new(initiator)); let responder = Arc::new(RwLock::new(responder)); let timeout = Some(Duration::from_secs(2)); let (connect_initiator, event_channel_initiator) = saltyrtc_client::connect( "localhost", 8765, Some(tls_connector.clone()), &core.handle(), initiator.clone(), ) .unwrap(); let handshake_initiator = connect_initiator .and_then(|client| saltyrtc_client::do_handshake( client, initiator.clone(), event_channel_initiator.clone_tx(), timeout, )); let (connect_responder, event_channel_responder) = saltyrtc_client::connect( "localhost", 8765, Some(tls_connector.clone()), &core.handle(), responder.clone(), ) .unwrap(); let handshake_responder = connect_responder .and_then(|client| saltyrtc_client::do_handshake( client, responder.clone(), event_channel_responder.clone_tx(), timeout, )); let (client_initiator, client_responder): (WsClient, WsClient) = core.run( handshake_initiator.join(handshake_responder) ).unwrap(); let (task_initiator, initiator_task_loop) = saltyrtc_client::task_loop( client_initiator, initiator.clone(), event_channel_initiator.clone_tx(), ).unwrap(); let (task_responder, responder_task_loop) = saltyrtc_client::task_loop( client_responder, responder.clone(), event_channel_responder.clone_tx(), ).unwrap(); let (tx_initiator, tx_responder) = { let mut t_initiator = task_initiator.lock().expect("Could not lock task mutex"); let mut t_responder = task_responder.lock().expect("Could not lock task mutex"); let rd_task_initiator: &mut RelayedDataTask = (&mut **t_initiator as &mut dyn Task) .downcast_mut::<RelayedDataTask>() .expect("Chosen task is not a RelayedDataTask"); let rd_task_responder: &mut RelayedDataTask = (&mut **t_responder as &mut dyn Task) .downcast_mut::<RelayedDataTask>() .expect("Chosen task is not a RelayedDataTask"); let tx_initiator = rd_task_initiator.get_sender().unwrap(); let tx_responder = rd_task_responder.get_sender().unwrap(); (tx_initiator, tx_responder) }; let rx_loop_responder = rx_responder .map_err(|_| Err(RelayedDataError::Channel(("Could not read from rx_responder").into()))) .for_each(move |ev: MessageEvent| match ev { MessageEvent::Data(data) => { assert_eq!(data.as_i64(), Some(1)); debug!("R: Received 1"); let future = tx_responder .clone() .send(OutgoingMessage::Data(Value::Integer(2.into()))) .map(|tx| { debug!("R: Sent 2"); tx }) .and_then(|tx| tx.send(OutgoingMessage::Data(Value::Integer(3.into())))) .map(|_tx| { debug!("R: Sent 3"); () }) .map_err(|e| Err(RelayedDataError::Channel(format!("Could not send message to tx_responder: {}", e)))); boxed!(future) }, MessageEvent::Application(data) => { assert_eq!(data.as_i64(), Some(4)); debug!("R: Received 4 (application)"); let future = tx_responder .clone() .send(OutgoingMessage::Application(Value::Integer(5.into()))) .map(|_tx| { debug!("R: Sent 5 (application)"); () }) .map_err(|e| Err(RelayedDataError::Channel(format!("Could not send message to tx_responder: {}", e)))); boxed!(future) }, MessageEvent::Close(reason) => { assert_eq!(reason, CloseCode::WsGoingAway); boxed!(future::err(Ok(()))) }, }) .or_else(|e| e) .then(|f| { debug!("† rx_loop_responder done"); f }); let tx_initiator_clone = tx_initiator.clone(); let rx_loop_initiator = rx_initiator .map_err(|_| RelayedDataError::Channel(("Could not read from rx_initiator").into())) .for_each(move |ev: MessageEvent| match ev { MessageEvent::Data(data) => { match data.as_i64() { Some(2) => { debug!("I: Received 2"); /* Ok, wait for 3 */ boxed!(future::ok(())) }, Some(3) => { debug!("I: Received 3"); boxed!( tx_initiator_clone .clone() .send(OutgoingMessage::Application(Value::Integer(4.into()))) .map(|_| debug!("I: Sent 4 (application)")) .map_err(|e| RelayedDataError::Channel(e.to_string())) ) }, _ => panic!("I: Received invalid value: {}", data), } }, MessageEvent::Application(data) => match data.as_i64() { Some(5) => { debug!("I: Received 5 (application)"); debug!("Done, disconnecting"); task_initiator.lock().unwrap().close(CloseCode::WsGoingAway); boxed!(future::ok(())) }, _ => panic!("I: Received invalid application value: {}", data), }, MessageEvent::Close(_) => panic!("Initiator should disconnect first!"), }) .then(|f| { debug!("† rx_loop_initiator done"); f }); let start = tx_initiator .send(OutgoingMessage::Data(Value::Integer(1.into()))) .map(|_| debug!("I: Sent 1")) .map_err(|e| RelayedDataError::Channel(e.to_string())); let test_future = start .join(initiator_task_loop.from_err().select(rx_loop_initiator).map_err(|(e, _)| e)) .join(responder_task_loop.from_err().select(rx_loop_responder).map_err(|(e, _)| e)); let timer = Timer::default(); let timeout = timer.sleep(Duration::from_secs(3)); match core.run(test_future.select2(timeout)) { Ok(res) => match res { future::Either::A(_) => debug!("Success"), future::Either::B(_) => panic!("The test timed out"), }, Err(e) => match e { future::Either::A((task_error, _)) => panic!("A task error occurred: {}", task_error), future::Either::B(_) => panic!("The timeout failed"), }, }; }
extern crate env_logger; #[macro_use] extern crate log; extern crate saltyrtc_client; extern crate saltyrtc_task_relayed_data; extern crate tokio_core; extern crate tokio_timer; use std::boxed::Box; use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::{Arc, RwLock}; use std::time::Duration; use saltyrtc_client::{WsClient, SaltyClient, CloseCode, BoxedFuture}; use saltyrtc_client::crypto::{PublicKey, KeyPair, AuthToken}; use saltyrtc_client::dep::futures::{Future, Stream, Sink}; use saltyrtc_client::dep::futures::future; use saltyrtc_client::dep::futures::sync::mpsc; use saltyrtc_client::dep::native_tls::{Certificate, TlsConnector, Protocol}; use saltyrtc_client::dep::rmpv::Value; use saltyrtc_client::tasks::Task; use saltyrtc_task_relayed_data::{RelayedDataTask, MessageEvent, OutgoingMessage, RelayedDataError}; use tokio_core::reactor::{Core, Remote}; use tokio_timer::Timer; macro_rules! boxed { ($future:expr) => {{ Box::new($future) as BoxedFuture<_, _> }} } fn setup_initiator( keypair: KeyPair, remote: Remote, ) -> (SaltyClient, mpsc::UnboundedReceiver<MessageEvent>) { let (tx, rx) = mpsc::unbounded(); let task = RelayedDataTask::new(remote, tx); let salty = SaltyClient::build(keypair) .add_task(Box::new(task)) .initiator() .expect("Could not create initiator"); (salty, rx) } fn setup_responder( keypair: KeyPair, remote: Remote, pubkey: PublicKey, auth_token: AuthToken, ) -> (SaltyClient, mpsc::UnboundedReceiver<MessageEvent>) { let (tx, rx) = mpsc::unbounded(); let task = RelayedDataTask::new(remote, tx); let salty = SaltyClient::build(keypair) .add_task(Box::new(task)) .responder(pubkey, auth_token) .expect("Could not create initiator"); (salty, rx) } #[test] fn integration_test() { env::set_var("RUST_LOG", "saltyrtc_client=debug,saltyrtc_task_relayed_data=debug,integration=trace"); env_logger::init(); let mut core = Core::new().unwrap(); let mut server_cert_bytes: Vec<u8> = vec![]; File::open(&Path::new("saltyrtc.der")) .expect("Could not open saltyrtc.der") .read_to_end(&mut server_cert_bytes) .expect("Could not read saltyrtc.der"); let server_cert = Certificate::from_der(&server_cert_bytes) .unwrap_or_else(|e| { panic!("Problem with CA cert: {}", e); }); let tls_connector = TlsConnector::builder() .min_protocol_version(Some(Protocol::Tlsv11)) .add_root_certificate(server_cert) .build() .unwrap_or_else(|e| panic!("Could not initialize TlsConnector: {}", e)); let initiator_keypair = KeyPair::new(); let responder_keypair = KeyPair::new(); let pubkey = initiator_keypair.public_key().clone(); let (initiator, rx_initiator) = setup_initiator(initiator_keypair, core.remote()); let (responder, rx_responder) = setup_responder(responder_keypair, core.remote(), pubkey, initiator.auth_token().cloned().unwrap()); let initiator = Arc::new(RwLock::new(initiator)); let responder = Arc::new(RwLock::new(responder)); let timeout = Some(Duration::from_secs(2)); let (connect_initiator, event_channel_initiator) = saltyrtc_client::connect( "localhost", 8765, Some(tls_connector.clone()), &core.handle(), initiator.clone(), ) .unwrap(); let handshake_initiator = connect_initiator .and_then(|client| saltyrtc_client::do_handshake( client, initiator.clone(), event_channel_initiator.clone_tx(), timeout, )); let (connect_responder, event_channel_responder) = saltyrtc_client::connect( "localhost", 8765, Some(tls_connector.clone()), &core.handle(), responder.clone(), ) .unwrap(); let handshake_responder = connect_responder .and_then(|client| saltyrtc_client::do_handshake( client, responder.clone(), event_channel_responder.clone_tx(), timeout, )); let (client_initiator, client_responder): (WsClient, WsClient) = core.run( handshake_initiator.join(handshake_responder) ).unwrap(); let (task_initiator, initiator_task_loop) = saltyrtc_client::task_loop( client_initiator, initiator.clone(), event_channel_initiator.clone_tx(), ).unwrap(); let (task_responder, responder_task_loop) = saltyrtc_client::task_loop( client_responder, responder.clone(), event_channel_responder.clone_tx(), ).unwrap(); let (tx_initiator, tx_responder) = { let mut t_initiator = task_initiator.lock().expect("Could not lock task mutex"); let mut t_responder = task_responder.lock().expect("Could not lock task mutex");
let rd_task_responder: &mut RelayedDataTask = (&mut **t_responder as &mut dyn Task) .downcast_mut::<RelayedDataTask>() .expect("Chosen task is not a RelayedDataTask"); let tx_initiator = rd_task_initiator.get_sender().unwrap(); let tx_responder = rd_task_responder.get_sender().unwrap(); (tx_initiator, tx_responder) }; let rx_loop_responder = rx_responder .map_err(|_| Err(RelayedDataError::Channel(("Could not read from rx_responder").into()))) .for_each(move |ev: MessageEvent| match ev { MessageEvent::Data(data) => { assert_eq!(data.as_i64(), Some(1)); debug!("R: Received 1"); let future = tx_responder .clone() .send(OutgoingMessage::Data(Value::Integer(2.into()))) .map(|tx| { debug!("R: Sent 2"); tx }) .and_then(|tx| tx.send(OutgoingMessage::Data(Value::Integer(3.into())))) .map(|_tx| { debug!("R: Sent 3"); () }) .map_err(|e| Err(RelayedDataError::Channel(format!("Could not send message to tx_responder: {}", e)))); boxed!(future) }, MessageEvent::Application(data) => { assert_eq!(data.as_i64(), Some(4)); debug!("R: Received 4 (application)"); let future = tx_responder .clone() .send(OutgoingMessage::Application(Value::Integer(5.into()))) .map(|_tx| { debug!("R: Sent 5 (application)"); () }) .map_err(|e| Err(RelayedDataError::Channel(format!("Could not send message to tx_responder: {}", e)))); boxed!(future) }, MessageEvent::Close(reason) => { assert_eq!(reason, CloseCode::WsGoingAway); boxed!(future::err(Ok(()))) }, }) .or_else(|e| e) .then(|f| { debug!("† rx_loop_responder done"); f }); let tx_initiator_clone = tx_initiator.clone(); let rx_loop_initiator = rx_initiator .map_err(|_| RelayedDataError::Channel(("Could not read from rx_initiator").into())) .for_each(move |ev: MessageEvent| match ev { MessageEvent::Data(data) => { match data.as_i64() { Some(2) => { debug!("I: Received 2"); /* Ok, wait for 3 */ boxed!(future::ok(())) }, Some(3) => { debug!("I: Received 3"); boxed!( tx_initiator_clone .clone() .send(OutgoingMessage::Application(Value::Integer(4.into()))) .map(|_| debug!("I: Sent 4 (application)")) .map_err(|e| RelayedDataError::Channel(e.to_string())) ) }, _ => panic!("I: Received invalid value: {}", data), } }, MessageEvent::Application(data) => match data.as_i64() { Some(5) => { debug!("I: Received 5 (application)"); debug!("Done, disconnecting"); task_initiator.lock().unwrap().close(CloseCode::WsGoingAway); boxed!(future::ok(())) }, _ => panic!("I: Received invalid application value: {}", data), }, MessageEvent::Close(_) => panic!("Initiator should disconnect first!"), }) .then(|f| { debug!("† rx_loop_initiator done"); f }); let start = tx_initiator .send(OutgoingMessage::Data(Value::Integer(1.into()))) .map(|_| debug!("I: Sent 1")) .map_err(|e| RelayedDataError::Channel(e.to_string())); let test_future = start .join(initiator_task_loop.from_err().select(rx_loop_initiator).map_err(|(e, _)| e)) .join(responder_task_loop.from_err().select(rx_loop_responder).map_err(|(e, _)| e)); let timer = Timer::default(); let timeout = timer.sleep(Duration::from_secs(3)); match core.run(test_future.select2(timeout)) { Ok(res) => match res { future::Either::A(_) => debug!("Success"), future::Either::B(_) => panic!("The test timed out"), }, Err(e) => match e { future::Either::A((task_error, _)) => panic!("A task error occurred: {}", task_error), future::Either::B(_) => panic!("The timeout failed"), }, }; }
let rd_task_initiator: &mut RelayedDataTask = (&mut **t_initiator as &mut dyn Task) .downcast_mut::<RelayedDataTask>() .expect("Chosen task is not a RelayedDataTask");
assignment_statement
[ { "content": "fn build_tests() -> (MutexGuard<'static, ()>, PathBuf) {\n\n let guard = match C_TEST_MUTEX.lock() {\n\n Ok(guard) => guard,\n\n Err(poisoned) => poisoned.into_inner(),\n\n };\n\n\n\n let out_dir = env!(\"OUT_DIR\");\n\n let build_dir = Path::new(out_dir).join(\"build\");...
Rust
src/test/instruction_tests/instr_vdbpsadbw.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vdbpsadbw_1() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: Some(Direct(XMM2)), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 243, 69, 142, 66, 202, 93], OperandSize::Dword, ) } #[test] fn vdbpsadbw_2() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledDisplaced( EDI, Four, 1875484248, Some(OperandSize::Xmmword), None, )), operand4: Some(Literal8(97)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None, }, &[98, 243, 101, 140, 66, 4, 189, 88, 158, 201, 111, 97], OperandSize::Dword, ) } #[test] fn vdbpsadbw_3() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM13)), operand2: Some(Direct(XMM21)), operand3: Some(Direct(XMM21)), operand4: Some(Literal8(109)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None, }, &[98, 51, 85, 132, 66, 237, 109], OperandSize::Qword, ) } #[test] fn vdbpsadbw_4() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM22)), operand2: Some(Direct(XMM6)), operand3: Some(IndirectScaledDisplaced( RCX, Four, 341913354, Some(OperandSize::Xmmword), None, )), operand4: Some(Literal8(3)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 227, 77, 139, 66, 52, 141, 10, 47, 97, 20, 3], OperandSize::Qword, ) } #[test] fn vdbpsadbw_5() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM7)), operand2: Some(Direct(YMM0)), operand3: Some(Direct(YMM0)), operand4: Some(Literal8(89)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 243, 125, 175, 66, 248, 89], OperandSize::Dword, ) } #[test] fn vdbpsadbw_6() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM6)), operand2: Some(Direct(YMM0)), operand3: Some(IndirectScaledDisplaced( ESI, Four, 1441455171, Some(OperandSize::Ymmword), None, )), operand4: Some(Literal8(82)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 243, 125, 170, 66, 52, 181, 67, 220, 234, 85, 82], OperandSize::Dword, ) } #[test] fn vdbpsadbw_7() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM13)), operand2: Some(Direct(YMM29)), operand3: Some(Direct(YMM22)), operand4: Some(Literal8(51)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 51, 21, 162, 66, 238, 51], OperandSize::Qword, ) } #[test] fn vdbpsadbw_8() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM28)), operand2: Some(Direct(YMM11)), operand3: Some(IndirectScaledIndexed( RDX, RDX, Eight, Some(OperandSize::Ymmword), None, )), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 99, 37, 173, 66, 36, 210, 93], OperandSize::Qword, ) } #[test] fn vdbpsadbw_9() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM1)), operand2: Some(Direct(ZMM1)), operand3: Some(Direct(ZMM4)), operand4: Some(Literal8(36)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 243, 117, 203, 66, 204, 36], OperandSize::Dword, ) } #[test] fn vdbpsadbw_10() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM2)), operand2: Some(Direct(ZMM0)), operand3: Some(IndirectScaledIndexed( ESI, EAX, Eight, Some(OperandSize::Zmmword), None, )), operand4: Some(Literal8(73)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 243, 125, 207, 66, 20, 198, 73], OperandSize::Dword, ) } #[test] fn vdbpsadbw_11() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM26)), operand2: Some(Direct(ZMM7)), operand3: Some(Direct(ZMM27)), operand4: Some(Literal8(123)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 3, 69, 203, 66, 211, 123], OperandSize::Qword, ) } #[test] fn vdbpsadbw_12() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM12)), operand2: Some(Direct(ZMM25)), operand3: Some(IndirectScaledIndexedDisplaced( RDX, RBX, Eight, 938432062, Some(OperandSize::Zmmword), None, )), operand4: Some(Literal8(83)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 115, 53, 198, 66, 164, 218, 62, 86, 239, 55, 83], OperandSize::Qword, ) }
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vdbpsadbw_1() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: So
mask: Some(MaskReg::K7), broadcast: None, }, &[98, 243, 125, 207, 66, 20, 198, 73], OperandSize::Dword, ) } #[test] fn vdbpsadbw_11() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM26)), operand2: Some(Direct(ZMM7)), operand3: Some(Direct(ZMM27)), operand4: Some(Literal8(123)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 3, 69, 203, 66, 211, 123], OperandSize::Qword, ) } #[test] fn vdbpsadbw_12() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM12)), operand2: Some(Direct(ZMM25)), operand3: Some(IndirectScaledIndexedDisplaced( RDX, RBX, Eight, 938432062, Some(OperandSize::Zmmword), None, )), operand4: Some(Literal8(83)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 115, 53, 198, 66, 164, 218, 62, 86, 239, 55, 83], OperandSize::Qword, ) }
me(Direct(XMM2)), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 243, 69, 142, 66, 202, 93], OperandSize::Dword, ) } #[test] fn vdbpsadbw_2() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledDisplaced( EDI, Four, 1875484248, Some(OperandSize::Xmmword), None, )), operand4: Some(Literal8(97)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None, }, &[98, 243, 101, 140, 66, 4, 189, 88, 158, 201, 111, 97], OperandSize::Dword, ) } #[test] fn vdbpsadbw_3() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM13)), operand2: Some(Direct(XMM21)), operand3: Some(Direct(XMM21)), operand4: Some(Literal8(109)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None, }, &[98, 51, 85, 132, 66, 237, 109], OperandSize::Qword, ) } #[test] fn vdbpsadbw_4() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM22)), operand2: Some(Direct(XMM6)), operand3: Some(IndirectScaledDisplaced( RCX, Four, 341913354, Some(OperandSize::Xmmword), None, )), operand4: Some(Literal8(3)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 227, 77, 139, 66, 52, 141, 10, 47, 97, 20, 3], OperandSize::Qword, ) } #[test] fn vdbpsadbw_5() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM7)), operand2: Some(Direct(YMM0)), operand3: Some(Direct(YMM0)), operand4: Some(Literal8(89)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 243, 125, 175, 66, 248, 89], OperandSize::Dword, ) } #[test] fn vdbpsadbw_6() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM6)), operand2: Some(Direct(YMM0)), operand3: Some(IndirectScaledDisplaced( ESI, Four, 1441455171, Some(OperandSize::Ymmword), None, )), operand4: Some(Literal8(82)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 243, 125, 170, 66, 52, 181, 67, 220, 234, 85, 82], OperandSize::Dword, ) } #[test] fn vdbpsadbw_7() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM13)), operand2: Some(Direct(YMM29)), operand3: Some(Direct(YMM22)), operand4: Some(Literal8(51)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 51, 21, 162, 66, 238, 51], OperandSize::Qword, ) } #[test] fn vdbpsadbw_8() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM28)), operand2: Some(Direct(YMM11)), operand3: Some(IndirectScaledIndexed( RDX, RDX, Eight, Some(OperandSize::Ymmword), None, )), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 99, 37, 173, 66, 36, 210, 93], OperandSize::Qword, ) } #[test] fn vdbpsadbw_9() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM1)), operand2: Some(Direct(ZMM1)), operand3: Some(Direct(ZMM4)), operand4: Some(Literal8(36)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 243, 117, 203, 66, 204, 36], OperandSize::Dword, ) } #[test] fn vdbpsadbw_10() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM2)), operand2: Some(Direct(ZMM0)), operand3: Some(IndirectScaledIndexed( ESI, EAX, Eight, Some(OperandSize::Zmmword), None, )), operand4: Some(Literal8(73)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false,
random
[ { "content": "fn encode32_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/parser.rs
opp11/chemtool2
d8cace048c5adf2ed61ab503534c287304a57644
use std::str::CharRange; use elem::{PerElem, Molecule}; use error::{CTResult, CTError}; use error::CTErrorKind::InputError; pub struct Parser { pos: usize, input: String, paren_level: u32, } impl Parser { pub fn new(input: &str) -> Parser { Parser { pos: 0, input: String::from_str(input), paren_level: 0 } } pub fn is_done(&self) -> bool { self.input.chars().skip(self.pos).all(|ch| ch.is_whitespace()) } pub fn parse_reaction(&mut self) -> CTResult<(Vec<Molecule>, Vec<Molecule>)> { let lhs = try!(self.parse_side()); self.consume_whitespace(); if self.pos + 2 >= self.input.len() || self.consume_char() != '-' || self.consume_char() != '>' { return Err(CTError { kind: InputError, desc: "Missing arrow (->) in chemical reaction".to_string(), pos: Some((self.pos - 2, 1)) }); } self.consume_whitespace(); let rhs = try!(self.parse_side()); Ok((lhs, rhs)) } pub fn parse_side(&mut self) -> CTResult<Vec<Molecule>> { let mut out = Vec::new(); let molecule = try!(self.parse_molecule()); out.push(molecule); self.consume_whitespace(); if !self.eof() && self.peek_char() == '+' { self.consume_char(); self.consume_whitespace(); let mut rest = try!(self.parse_side()); out.append(&mut rest); } Ok(out) } pub fn parse_molecule(&mut self) -> CTResult<Molecule> { let mut out = Vec::new(); let mut per = try!(self.parse_periodic()); out.append(&mut per); if !self.eof() && (self.peek_char().is_alphabetic() || self.peek_char() == '(') { let mut molecule = try!(self.parse_molecule()); out.append(&mut molecule); } if !self.eof() && self.peek_char() == ')' && self.paren_level == 0 { Err(CTError { kind: InputError, desc: "Missing opening parentheses".to_string(), pos: Some((self.pos, 1)) }) } else if !self.eof() && !self.on_legal_char() { Err(CTError { kind: InputError, desc: "Unexpected character".to_string(), pos: Some((self.pos, 1)) }) } else { Ok(out) } } fn parse_periodic(&mut self) -> CTResult<Vec<PerElem>> { let mut elem = try!(self.parse_element()); if !self.eof() && self.peek_char().is_numeric() { let coef = try!(self.parse_coefficient()); for e in elem.iter_mut() { e.coef *= coef; } } Ok(elem) } fn parse_element(&mut self) -> CTResult<Vec<PerElem>> { if self.eof() { return Err(CTError { kind: InputError, desc: "Found no periodic element".to_string(), pos: Some((self.pos, 1)) }); } let start_pos = self.pos; let first = self.consume_char(); if first == '(' { self.paren_level += 1; let molecule = try!(self.parse_molecule()); if self.eof() || self.consume_char() != ')' { Err(CTError { kind: InputError, desc: "Missing closing parentheses".to_string(), pos: Some((self.pos - 1, 1)) }) } else { self.paren_level -= 1; Ok(molecule) } } else if first.is_uppercase() { let mut name = String::new(); name.push(first); name.push_str(self.consume_while(|ch| ch.is_lowercase()).as_slice()); let len = name.len(); Ok(vec!(PerElem { name: name, coef: 1, pos: start_pos, len: len })) } else { Err(CTError { kind: InputError, desc: "Missing uppercase letter at the beginning of the element".to_string(), pos: Some((self.pos - 1, 1)) }) } } fn parse_coefficient(&mut self) -> CTResult<u32> { let start_pos = self.pos; let num_str = self.consume_while(|ch| ch.is_numeric()); if let Ok(num) = num_str.parse::<u32>() { Ok(num) } else { Err(CTError { kind: InputError, desc: "Could not parse coefficient".to_string(), pos: Some((start_pos, num_str.len())) }) } } fn peek_char(&self) -> char { self.input.char_at(self.pos) } fn consume_char(&mut self) -> char { let CharRange { ch, next } = self.input.char_range_at(self.pos); self.pos = next; ch } fn consume_while<F>(&mut self, pred: F) -> String where F: Fn(char) -> bool { let mut out = String::new(); while !self.eof() && pred(self.peek_char()) { out.push(self.consume_char()); } out } fn consume_whitespace(&mut self) { self.consume_while(|ch| ch.is_whitespace()); } fn eof(&mut self) -> bool { self.pos >= self.input.len() } fn on_legal_char(&self) -> bool { match self.peek_char() { ch if ch.is_alphanumeric() => true, '+' | '-' | '>' | '(' | ')' | ' ' => true, _ => false, } } } #[cfg(test)] mod test { use super::*; use elem::PerElem; macro_rules! check_raw_result( ($raw:expr, $expected:expr) => ( if let Ok(result) = $raw { assert_eq!(result, $expected); } else { panic!($raw); } ) ); #[test] fn elems() { let mut parser = Parser::new("CHeH"); let raw_result = parser.parse_molecule(); let expected = vec!(PerElem { name: "C".to_string(), coef: 1, pos: 0, len: 1 }, PerElem { name: "He".to_string(), coef: 1, pos: 1, len: 2 }, PerElem { name: "H".to_string(), coef: 1, pos: 3, len: 1 }); check_raw_result!(raw_result, expected); } #[test] fn coefs() { let mut parser = Parser::new("C23"); let raw_result = parser.parse_molecule(); let expected = vec!(PerElem { name: "C".to_string(), coef: 23, pos: 0, len: 1 }); check_raw_result!(raw_result, expected); } #[test] fn parens() { let mut parser = Parser::new("(CH3)2"); let raw_result = parser.parse_molecule(); let expected = vec!(PerElem { name: "C".to_string(), coef: 2, pos: 1, len: 1 }, PerElem { name: "H".to_string(), coef: 6, pos: 2, len: 1 }); check_raw_result!(raw_result, expected); } #[test] fn multiple_elems() { let mut parser = Parser::new("C + H"); let raw_result = parser.parse_side(); let expected = vec!(vec!(PerElem { name: "C".to_string(), coef: 1, pos: 0, len: 1 }), vec!(PerElem { name: "H".to_string(), coef: 1, pos: 4, len: 1 })); check_raw_result!(raw_result, expected); } #[test] fn reaction() { let mut parser = Parser::new("C -> H"); let raw_result = parser.parse_reaction(); let expected = (vec!(vec!(PerElem { name: "C".to_string(), coef: 1, pos: 0, len: 1 })), vec!(vec!(PerElem { name: "H".to_string(), coef: 1, pos: 5, len: 1 }))); check_raw_result!(raw_result, expected); } #[test] fn empty() { let mut parser = Parser::new(""); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn no_uppercase() { let mut parser = Parser::new("c"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn missing_close_paren() { let mut parser = Parser::new("(C"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn missing_open_paren() { let mut parser = Parser::new("C)"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn invald_char() { let mut parser = Parser::new("%"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn is_done() { let parser = Parser::new(" "); assert!(parser.is_done()); } #[test] fn not_done() { let parser = Parser::new(" C"); assert!(!parser.is_done()); } #[test] fn invald_num() { let mut parser = Parser::new("C999999999999999999999"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn dangling_plus() { let mut parser = Parser::new("C + -> H"); assert!(parser.parse_reaction().is_err()); } }
use std::str::CharRange; use elem::{PerElem, Molecule}; use error::{CTResult, CTError}; use error::CTErrorKind::InputError; pub struct Parser { pos: usize, input: String, paren_level: u32, } impl Parser { pub fn new(input: &str) -> Parser { Parser { pos: 0, input: String::from_str(input), paren_level: 0 } } pub fn is_done(&self) -> bool { self.input.chars().skip(self.pos).all(|ch| ch.is_whitespace()) } pub fn parse_reaction(&mut self) -> CTResult<(Vec<Molecule>, Vec<Molecule>)> { let lhs = try!(self.parse_side()); self.consume_whitespace(); if self.pos + 2 >= self.input.len() || self.consume_char() != '-' || self.consume_char() != '>' { return Err(CTError { kind: InputError, desc: "Missing arrow (->) in chemical reaction".to_string(), pos: Some((self.pos - 2, 1)) }); } self.consume_whitespace(); let rhs = try!(self.parse_side()); Ok((lhs, rhs)) } pub fn parse_side(&mut self) -> CTResult<Vec<Molecule>> { let mut out = Vec::new(); let molecule = try!(self.parse_molecule()); out.push(molecule); self.consume_whitespace(); if !self.eof() && self.peek_char() == '+' { self.consume_char(); self.consume_whitespace(); let mut rest = try!(self.parse_side()); out.append(&mut rest); } Ok(out) } pub fn parse_molecule(&mut self) -> CTResult<Molecule> { let mut out = Vec::new(); let mut per = try!(self.parse_periodic()); out.append(&mut per); if !self.eof() && (self.peek_char().is_alphabetic() || self.peek_char() == '(') { let mut molecule = try!(self.parse_molecule()); out.append(&mut molecule); } if !self.eof() && self.peek_char() == ')' && self.paren_level == 0 { Err(CTError { kind: InputError, desc: "Missing opening parentheses".to_string(), pos: Some((self.pos, 1)) }) } else if !self.eof() && !self.on_legal_char() { Err(CTError { kind: InputError, desc: "Unexpected character".to_string(), pos: Some((self.pos, 1)) }) } else { Ok(out) } }
fn parse_element(&mut self) -> CTResult<Vec<PerElem>> { if self.eof() { return Err(CTError { kind: InputError, desc: "Found no periodic element".to_string(), pos: Some((self.pos, 1)) }); } let start_pos = self.pos; let first = self.consume_char(); if first == '(' { self.paren_level += 1; let molecule = try!(self.parse_molecule()); if self.eof() || self.consume_char() != ')' { Err(CTError { kind: InputError, desc: "Missing closing parentheses".to_string(), pos: Some((self.pos - 1, 1)) }) } else { self.paren_level -= 1; Ok(molecule) } } else if first.is_uppercase() { let mut name = String::new(); name.push(first); name.push_str(self.consume_while(|ch| ch.is_lowercase()).as_slice()); let len = name.len(); Ok(vec!(PerElem { name: name, coef: 1, pos: start_pos, len: len })) } else { Err(CTError { kind: InputError, desc: "Missing uppercase letter at the beginning of the element".to_string(), pos: Some((self.pos - 1, 1)) }) } } fn parse_coefficient(&mut self) -> CTResult<u32> { let start_pos = self.pos; let num_str = self.consume_while(|ch| ch.is_numeric()); if let Ok(num) = num_str.parse::<u32>() { Ok(num) } else { Err(CTError { kind: InputError, desc: "Could not parse coefficient".to_string(), pos: Some((start_pos, num_str.len())) }) } } fn peek_char(&self) -> char { self.input.char_at(self.pos) } fn consume_char(&mut self) -> char { let CharRange { ch, next } = self.input.char_range_at(self.pos); self.pos = next; ch } fn consume_while<F>(&mut self, pred: F) -> String where F: Fn(char) -> bool { let mut out = String::new(); while !self.eof() && pred(self.peek_char()) { out.push(self.consume_char()); } out } fn consume_whitespace(&mut self) { self.consume_while(|ch| ch.is_whitespace()); } fn eof(&mut self) -> bool { self.pos >= self.input.len() } fn on_legal_char(&self) -> bool { match self.peek_char() { ch if ch.is_alphanumeric() => true, '+' | '-' | '>' | '(' | ')' | ' ' => true, _ => false, } } } #[cfg(test)] mod test { use super::*; use elem::PerElem; macro_rules! check_raw_result( ($raw:expr, $expected:expr) => ( if let Ok(result) = $raw { assert_eq!(result, $expected); } else { panic!($raw); } ) ); #[test] fn elems() { let mut parser = Parser::new("CHeH"); let raw_result = parser.parse_molecule(); let expected = vec!(PerElem { name: "C".to_string(), coef: 1, pos: 0, len: 1 }, PerElem { name: "He".to_string(), coef: 1, pos: 1, len: 2 }, PerElem { name: "H".to_string(), coef: 1, pos: 3, len: 1 }); check_raw_result!(raw_result, expected); } #[test] fn coefs() { let mut parser = Parser::new("C23"); let raw_result = parser.parse_molecule(); let expected = vec!(PerElem { name: "C".to_string(), coef: 23, pos: 0, len: 1 }); check_raw_result!(raw_result, expected); } #[test] fn parens() { let mut parser = Parser::new("(CH3)2"); let raw_result = parser.parse_molecule(); let expected = vec!(PerElem { name: "C".to_string(), coef: 2, pos: 1, len: 1 }, PerElem { name: "H".to_string(), coef: 6, pos: 2, len: 1 }); check_raw_result!(raw_result, expected); } #[test] fn multiple_elems() { let mut parser = Parser::new("C + H"); let raw_result = parser.parse_side(); let expected = vec!(vec!(PerElem { name: "C".to_string(), coef: 1, pos: 0, len: 1 }), vec!(PerElem { name: "H".to_string(), coef: 1, pos: 4, len: 1 })); check_raw_result!(raw_result, expected); } #[test] fn reaction() { let mut parser = Parser::new("C -> H"); let raw_result = parser.parse_reaction(); let expected = (vec!(vec!(PerElem { name: "C".to_string(), coef: 1, pos: 0, len: 1 })), vec!(vec!(PerElem { name: "H".to_string(), coef: 1, pos: 5, len: 1 }))); check_raw_result!(raw_result, expected); } #[test] fn empty() { let mut parser = Parser::new(""); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn no_uppercase() { let mut parser = Parser::new("c"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn missing_close_paren() { let mut parser = Parser::new("(C"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn missing_open_paren() { let mut parser = Parser::new("C)"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn invald_char() { let mut parser = Parser::new("%"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn is_done() { let parser = Parser::new(" "); assert!(parser.is_done()); } #[test] fn not_done() { let parser = Parser::new(" C"); assert!(!parser.is_done()); } #[test] fn invald_num() { let mut parser = Parser::new("C999999999999999999999"); assert!(parser.parse_molecule().is_err()); assert!(parser.parse_reaction().is_err()); } #[test] fn dangling_plus() { let mut parser = Parser::new("C + -> H"); assert!(parser.parse_reaction().is_err()); } }
fn parse_periodic(&mut self) -> CTResult<Vec<PerElem>> { let mut elem = try!(self.parse_element()); if !self.eof() && self.peek_char().is_numeric() { let coef = try!(self.parse_coefficient()); for e in elem.iter_mut() { e.coef *= coef; } } Ok(elem) }
function_block-full_function
[ { "content": "/// Sorts the PerElems and groups those with the same name field.\n\n///\n\n/// Grouping of two (or more) PerElems means adding the coef field of the\n\n/// duplicate to the one already found, and then throwing away the duplicate.\n\n/// E.g. CH3CH3 would turn into C2H6.\n\npub fn group_elems(mut ...
Rust
rsnes/src/smp.rs
nat-rix/rsnes
05b68de39041e68fa65184c1842c1cd7108543d6
use crate::{ backend::AudioBackend as Backend, spc700::Spc700, timing::{Cycles, APU_CPU_TIMING_PROPORTION_NTSC, APU_CPU_TIMING_PROPORTION_PAL}, }; use save_state::{InSaveState, SaveStateDeserializer, SaveStateSerializer}; use save_state_macro::InSaveState; use std::sync::mpsc::{channel, Receiver, RecvError, Sender}; #[derive(Debug, Clone)] enum Action { WriteInputPort { addr: u8, data: u8 }, ReadOutputPort { addr: u8 }, } #[derive(Debug, Clone)] enum ThreadCommand { RunCycles { cycles: Cycles, action: Option<Action>, }, SaveState(Box<Spc700>), GetSaveState, KillMe, } #[derive(Debug, Clone)] enum MainCommand { Data(u8), SaveState(Box<Spc700>), } type ReturnType = Result<(), RecvError>; #[derive(Debug)] struct Thread { join_handle: Option<std::thread::JoinHandle<ReturnType>>, send: Sender<ThreadCommand>, recv: Receiver<MainCommand>, } #[derive(Debug, InSaveState)] pub struct Smp<B: Backend> { pub spc: Option<Spc700>, #[except((|_v, _s| ()), (|_v, _s| ()))] pub backend: Option<B>, #[except(Self::serialize_save_state, Self::deserialize_save_state)] thread: Option<Thread>, timing_proportion: (Cycles, Cycles), master_cycles: Cycles, } fn threaded_spc<B: Backend>( mut spc: Spc700, mut backend: B, send: Sender<MainCommand>, recv: Receiver<ThreadCommand>, ) -> ReturnType { loop { match recv.recv()? { ThreadCommand::RunCycles { cycles, action } => { for _ in 0..cycles { if let Some(sample) = spc.run_cycle() { backend.push_sample(sample) } } match action { Some(Action::WriteInputPort { addr, data }) => { spc.input[usize::from(addr & 3)] = data } Some(Action::ReadOutputPort { addr }) => { let _ = send.send(MainCommand::Data(spc.output[usize::from(addr & 3)])); } None => (), } } ThreadCommand::SaveState(new_spc) => spc = *new_spc, ThreadCommand::GetSaveState => { let _ = send.send(MainCommand::SaveState(Box::new(spc.clone()))); } ThreadCommand::KillMe => break Ok(()), } } } impl<B: Backend> Smp<B> { pub fn new(backend: B, is_pal: bool, is_threaded: bool) -> Self { let spc = Spc700::default(); let timing_proportion = if is_pal { APU_CPU_TIMING_PROPORTION_PAL } else { APU_CPU_TIMING_PROPORTION_NTSC }; if is_threaded { let ((m_send, m_recv), (t_send, t_recv)) = (channel(), channel()); let handle = std::thread::spawn(move || threaded_spc(spc, backend, m_send, t_recv)); let thread = Some(Thread { join_handle: Some(handle), send: t_send, recv: m_recv, }); Self { spc: None, backend: None, thread, timing_proportion, master_cycles: 0, } } else { Self { spc: Some(spc), backend: Some(backend), thread: None, timing_proportion, master_cycles: 0, } } } pub fn tick(&mut self, n: u16) { self.master_cycles += Cycles::from(n) * self.timing_proportion.1; } fn refresh_counters(&mut self) -> Cycles { let cycles = self.master_cycles / self.timing_proportion.0; self.master_cycles %= self.timing_proportion.0; cycles } fn refresh_no_thread(spc: &mut Spc700, backend: &mut B, cycles: Cycles) { for _ in 0..cycles { if let Some(sample) = spc.run_cycle() { backend.push_sample(sample) } } } pub fn refresh(&mut self) { let cycles = self.refresh_counters(); if let (Some(spc), Some(backend)) = (&mut self.spc, &mut self.backend) { Self::refresh_no_thread(spc, backend, cycles) } else if let Some(thread) = &mut self.thread { let _ = thread.send.send(ThreadCommand::RunCycles { cycles, action: None, }); } else { unreachable!() } } pub fn read_output_port(&mut self, addr: u8) -> u8 { let cycles = self.refresh_counters(); if let (Some(spc), Some(backend)) = (&mut self.spc, &mut self.backend) { Self::refresh_no_thread(spc, backend, cycles); spc.output[usize::from(addr & 3)] } else if let Some(thread) = &mut self.thread { let _ = thread.send.send(ThreadCommand::RunCycles { cycles, action: Some(Action::ReadOutputPort { addr }), }); match thread.recv.recv().unwrap() { MainCommand::Data(d) => d, _ => panic!(), } } else { unreachable!() } } pub fn write_input_port(&mut self, addr: u8, data: u8) { let cycles = self.refresh_counters(); if let (Some(spc), Some(backend)) = (&mut self.spc, &mut self.backend) { Self::refresh_no_thread(spc, backend, cycles); spc.input[usize::from(addr & 3)] = data } else if let Some(thread) = &mut self.thread { let _ = thread.send.send(ThreadCommand::RunCycles { cycles, action: Some(Action::WriteInputPort { addr, data }), }); } else { unreachable!() } } pub fn is_threaded(&self) -> bool { self.thread.is_some() } fn serialize_save_state(thread: &Option<Thread>, ser: &mut SaveStateSerializer) { if let Some(thread) = thread { thread.send.send(ThreadCommand::GetSaveState).unwrap(); match thread.recv.recv().unwrap() { MainCommand::SaveState(new_spc) => { new_spc.serialize(ser); } _ => panic!(), } } } fn deserialize_save_state(thread: &mut Option<Thread>, deser: &mut SaveStateDeserializer) { if let Some(thread) = thread { let mut spc = Spc700::default(); spc.deserialize(deser); let _ = thread.send.send(ThreadCommand::SaveState(Box::new(spc))); } } } impl<B: Backend> Drop for Smp<B> { fn drop(&mut self) { if let Some(thread) = &mut self.thread { drop(thread.send.send(ThreadCommand::KillMe)); if let Some(Ok(Err(err))) = thread.join_handle.take().map(|t| t.join()) { todo!("throw useful error ({})", err) } } } }
use crate::{ backend::AudioBackend as Backend, spc700::Spc700, timing::{Cycles, APU_CPU_TIMING_PROPORTION_NTSC, APU_CPU_TIMING_PROPORTION_PAL}, }; use save_
mple) } } match action { Some(Action::WriteInputPort { addr, data }) => { spc.input[usize::from(addr & 3)] = data } Some(Action::ReadOutputPort { addr }) => { let _ = send.send(MainCommand::Data(spc.output[usize::from(addr & 3)])); } None => (), } } ThreadCommand::SaveState(new_spc) => spc = *new_spc, ThreadCommand::GetSaveState => { let _ = send.send(MainCommand::SaveState(Box::new(spc.clone()))); } ThreadCommand::KillMe => break Ok(()), } } } impl<B: Backend> Smp<B> { pub fn new(backend: B, is_pal: bool, is_threaded: bool) -> Self { let spc = Spc700::default(); let timing_proportion = if is_pal { APU_CPU_TIMING_PROPORTION_PAL } else { APU_CPU_TIMING_PROPORTION_NTSC }; if is_threaded { let ((m_send, m_recv), (t_send, t_recv)) = (channel(), channel()); let handle = std::thread::spawn(move || threaded_spc(spc, backend, m_send, t_recv)); let thread = Some(Thread { join_handle: Some(handle), send: t_send, recv: m_recv, }); Self { spc: None, backend: None, thread, timing_proportion, master_cycles: 0, } } else { Self { spc: Some(spc), backend: Some(backend), thread: None, timing_proportion, master_cycles: 0, } } } pub fn tick(&mut self, n: u16) { self.master_cycles += Cycles::from(n) * self.timing_proportion.1; } fn refresh_counters(&mut self) -> Cycles { let cycles = self.master_cycles / self.timing_proportion.0; self.master_cycles %= self.timing_proportion.0; cycles } fn refresh_no_thread(spc: &mut Spc700, backend: &mut B, cycles: Cycles) { for _ in 0..cycles { if let Some(sample) = spc.run_cycle() { backend.push_sample(sample) } } } pub fn refresh(&mut self) { let cycles = self.refresh_counters(); if let (Some(spc), Some(backend)) = (&mut self.spc, &mut self.backend) { Self::refresh_no_thread(spc, backend, cycles) } else if let Some(thread) = &mut self.thread { let _ = thread.send.send(ThreadCommand::RunCycles { cycles, action: None, }); } else { unreachable!() } } pub fn read_output_port(&mut self, addr: u8) -> u8 { let cycles = self.refresh_counters(); if let (Some(spc), Some(backend)) = (&mut self.spc, &mut self.backend) { Self::refresh_no_thread(spc, backend, cycles); spc.output[usize::from(addr & 3)] } else if let Some(thread) = &mut self.thread { let _ = thread.send.send(ThreadCommand::RunCycles { cycles, action: Some(Action::ReadOutputPort { addr }), }); match thread.recv.recv().unwrap() { MainCommand::Data(d) => d, _ => panic!(), } } else { unreachable!() } } pub fn write_input_port(&mut self, addr: u8, data: u8) { let cycles = self.refresh_counters(); if let (Some(spc), Some(backend)) = (&mut self.spc, &mut self.backend) { Self::refresh_no_thread(spc, backend, cycles); spc.input[usize::from(addr & 3)] = data } else if let Some(thread) = &mut self.thread { let _ = thread.send.send(ThreadCommand::RunCycles { cycles, action: Some(Action::WriteInputPort { addr, data }), }); } else { unreachable!() } } pub fn is_threaded(&self) -> bool { self.thread.is_some() } fn serialize_save_state(thread: &Option<Thread>, ser: &mut SaveStateSerializer) { if let Some(thread) = thread { thread.send.send(ThreadCommand::GetSaveState).unwrap(); match thread.recv.recv().unwrap() { MainCommand::SaveState(new_spc) => { new_spc.serialize(ser); } _ => panic!(), } } } fn deserialize_save_state(thread: &mut Option<Thread>, deser: &mut SaveStateDeserializer) { if let Some(thread) = thread { let mut spc = Spc700::default(); spc.deserialize(deser); let _ = thread.send.send(ThreadCommand::SaveState(Box::new(spc))); } } } impl<B: Backend> Drop for Smp<B> { fn drop(&mut self) { if let Some(thread) = &mut self.thread { drop(thread.send.send(ThreadCommand::KillMe)); if let Some(Ok(Err(err))) = thread.join_handle.take().map(|t| t.join()) { todo!("throw useful error ({})", err) } } } }
state::{InSaveState, SaveStateDeserializer, SaveStateSerializer}; use save_state_macro::InSaveState; use std::sync::mpsc::{channel, Receiver, RecvError, Sender}; #[derive(Debug, Clone)] enum Action { WriteInputPort { addr: u8, data: u8 }, ReadOutputPort { addr: u8 }, } #[derive(Debug, Clone)] enum ThreadCommand { RunCycles { cycles: Cycles, action: Option<Action>, }, SaveState(Box<Spc700>), GetSaveState, KillMe, } #[derive(Debug, Clone)] enum MainCommand { Data(u8), SaveState(Box<Spc700>), } type ReturnType = Result<(), RecvError>; #[derive(Debug)] struct Thread { join_handle: Option<std::thread::JoinHandle<ReturnType>>, send: Sender<ThreadCommand>, recv: Receiver<MainCommand>, } #[derive(Debug, InSaveState)] pub struct Smp<B: Backend> { pub spc: Option<Spc700>, #[except((|_v, _s| ()), (|_v, _s| ()))] pub backend: Option<B>, #[except(Self::serialize_save_state, Self::deserialize_save_state)] thread: Option<Thread>, timing_proportion: (Cycles, Cycles), master_cycles: Cycles, } fn threaded_spc<B: Backend>( mut spc: Spc700, mut backend: B, send: Sender<MainCommand>, recv: Receiver<ThreadCommand>, ) -> ReturnType { loop { match recv.recv()? { ThreadCommand::RunCycles { cycles, action } => { for _ in 0..cycles { if let Some(sample) = spc.run_cycle() { backend.push_sample(sa
random
[ { "content": "pub trait AccessType<B: crate::backend::AudioBackend, FB: crate::backend::FrameBuffer> {\n\n fn read<D: Data>(device: &mut Device<B, FB>, addr: Addr24) -> D;\n\n fn write<D: Data>(device: &mut Device<B, FB>, addr: Addr24, val: D);\n\n fn cpu(device: &Device<B, FB>) -> &Cpu;\n\n fn cpu_...
Rust
src/serialization/database.rs
MDeiml/attomath
4aac4dad3cd776dd2cb1602aa930c04c315d5186
use crate::{error::ProofError, expression::SingleSubstitution, Identifier, Theorem}; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq)] pub struct Database { names: HashMap<String, (usize, usize)>, theorems: Vec<(Theorem, Proof<usize>, Option<String>)>, last_name: usize, } #[derive(Debug, PartialEq, Eq, Clone)] pub enum Proof<K> { Simplify(K, Identifier, Identifier), Combine(K, K, usize), Axiom(Theorem), } impl<K> Proof<K> { pub fn map_id_result<K1, F, E>(self, f: F) -> Result<Proof<K1>, E> where F: Fn(K) -> Result<K1, E>, { Ok(match self { Proof::Simplify(id, a, b) => Proof::Simplify(f(id)?, a, b), Proof::Combine(id_a, id_b, index) => Proof::Combine(f(id_a)?, f(id_b)?, index), Proof::Axiom(theorem) => Proof::Axiom(theorem), }) } pub fn map_id<K1, F>(self, f: F) -> Proof<K1> where F: Fn(K) -> K1, { self.map_id_result::<_, _, ()>(|id| Ok(f(id))).unwrap() } } #[derive(Debug)] pub enum DatabaseError { TheoremNotFound(Option<String>, Option<usize>), NameCollision(String), TheoremMismatch(Theorem, Theorem), ProofError(ProofError), } impl From<ProofError> for DatabaseError { fn from(e: ProofError) -> Self { Self::ProofError(e) } } impl Database { pub fn new() -> Self { Self { names: HashMap::new(), theorems: Vec::new(), last_name: 0, } } fn get_index(&self, name: Option<&str>, index: Option<usize>) -> Result<usize, DatabaseError> { let (start, end) = match name { Some(name) => *self .names .get(name) .ok_or(DatabaseError::TheoremNotFound(Some(name.to_owned()), index))?, None => (self.last_name, self.theorems.len()), }; match index { Some(i) => { if start + i < end { Ok(start + i) } else { Err(DatabaseError::TheoremNotFound( name.map(|s| s.to_owned()), index, )) } } None => { if start == end { Err(DatabaseError::TheoremNotFound( name.map(|s| s.to_owned()), index, )) } else { Ok(end - 1) } } } } pub fn get(&self, name: Option<&str>, index: Option<usize>) -> Result<&Theorem, DatabaseError> { Ok(&self.theorems[self.get_index(name, index)?].0) } pub fn add_name(&mut self, name: String) -> Result<(), DatabaseError> { if self.theorems.is_empty() { return Err(DatabaseError::TheoremNotFound(None, Some(0))); } let index = self.theorems.len() - 1; if self.theorems[index].2.is_some() { return Err(DatabaseError::TheoremNotFound(None, None)); } match self.names.entry(name.clone()) { std::collections::hash_map::Entry::Occupied(_) => { Err(DatabaseError::NameCollision(name)) } std::collections::hash_map::Entry::Vacant(entry) => { &entry.insert((self.last_name, index + 1)); self.last_name = index + 1; self.theorems[index].2 = Some(name.to_owned()); Ok(()) } } } pub fn add_proof<'a>( &'a mut self, proof: Proof<(Option<String>, Option<usize>)>, ) -> Result<&'a Theorem, DatabaseError> { let proof = proof.map_id_result(|id| self.get_index(id.0.as_deref(), id.1))?; let new_theorem = match proof { Proof::Simplify(id, a, b) => { let theorem = &self.theorems[id].0; let mut new_theorem = theorem.substitute(&SingleSubstitution::new(a, b).unwrap())?; new_theorem.standardize(); new_theorem } Proof::Combine(id_a, id_b, index) => { let theorem_a = &self.theorems[id_a].0; let theorem_b = &self.theorems[id_b].0; let mut new_theorem = theorem_a.combine(&theorem_b, index)?; new_theorem.standardize(); new_theorem } Proof::Axiom(ref theorem) => theorem.clone(), }; self.theorems.push((new_theorem, proof, None)); Ok(&self.theorems.last().unwrap().0) } pub fn substitute(&mut self, theorem: Theorem) -> Result<(), DatabaseError> { let last = &mut self .theorems .last_mut() .ok_or(DatabaseError::TheoremNotFound(None, None))? .0; let mut theorem_standardized = theorem.clone(); theorem_standardized.standardize(); if last == &theorem_standardized { *last = theorem; Ok(()) } else { Err(DatabaseError::TheoremMismatch(theorem, last.clone())) } } fn reverse_id(&self, id: usize, current_id: usize) -> (Option<&str>, Option<usize>) { if let Some(name) = &self.theorems[id].2 { (Some(name), None) } else if id == current_id - 1 { (None, None) } else if id >= self.last_name { (None, Some(id - self.last_name)) } else { let name = self.theorems[id..] .iter() .filter_map(|x| x.2.as_ref()) .next() .unwrap(); let (start, end) = self.names[name]; if end >= current_id { (None, Some(id - start)) } else { (Some(name), Some(id - start)) } } } pub fn proofs<'a>( &'a self, ) -> impl 'a + Iterator<Item = (&Theorem, Proof<(Option<&str>, Option<usize>)>, Option<&str>)> { self.theorems .iter() .enumerate() .map(move |(current_id, (theorem, proof, name))| { let proof = proof.clone().map_id(|id| self.reverse_id(id, current_id)); (theorem, proof, name.as_deref()) }) } }
use crate::{error::ProofError, expression::SingleSubstitution, Identifier, Theorem}; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq)] pub struct Database { names: HashMap<String, (usize, usize)>, theorems: Vec<(Theorem, Proof<usize>, Option<String>)>, last_name: usize, } #[derive(Debug, PartialEq, Eq, Clone)] pub enum Proof<K> { Simplify(K, Identifier, Identifier), Combine(K, K, usize), Axiom(Theorem), } impl<K> Proof<K> { pub fn map_id_result<K1, F, E>(self, f: F) -> Result<Proof<K1>, E> where F: Fn(K) -> Result<K1, E>, { Ok(match self { Proof::Simplify(id, a, b) => Proof::Simplify(f(id)?, a, b), Proof::Combine(id_a, id_b, index) => Proof::Combine(f(id_a)?, f(id_b)?, index), Proof::Axiom(theorem) => Proof::Axiom(theorem), }) } pub fn map_id<K1, F>(self, f: F) -> Proof<K1> where F: Fn(K) -> K1, { self.map_id_result::<_, _, ()>(|id| Ok(f(id))).unwrap() } } #[derive(Debug)] pub enum DatabaseError { TheoremNotFound(Option<String>, Option<usize>), NameCollision(String), TheoremMismatch(Theorem, Theorem), ProofError(ProofError), } impl From<ProofError> for DatabaseError { fn from(e: ProofError) -> Self { Self::ProofError(e) } } impl Database { pub fn new() -> Self { Self { names: HashMap::new(), theorems: Vec::new(), last_name: 0, } } fn get_index(&self, name: Option<&str>, index: Option<usize>) -> Result<usize, DatabaseError> { let (start, end) = match name { Some(name) => *self .names .get(name) .ok_or(DatabaseError::TheoremNotFound(Some(name.to_owned()), index))?, None => (self.last_name, self.theorems.len()), }; match index { Some(i) => { if start + i < end { Ok(start + i) } else { Err(DatabaseError::TheoremNotFound( name.map(|s| s.to_owned()), index, )) } } None => { if start == end { Err(DatabaseError::TheoremNotFound( name.map(|s| s.to_owned()), index, )) } else { Ok(end - 1) } } } } pub fn get(&self, name: Option<&str>, index: Option<usize>) -> Result<&Theorem, DatabaseError> { Ok(&self.theorems[self.get_index(name, index)?].0) } pub fn add_name(&mut self, name: String) -> Result<(), DatabaseError> { if self.theorems.is_empty() { return Err(DatabaseError::TheoremNotFound(None, Some(0))); } let index = self.theorems.len() - 1; if self.theorems[index].2.is_some() { return Err(DatabaseError::TheoremNotFound(None, None)); } match self.names.entry(name.clone()) { std::collections::hash_map::Entry::Occupied(_) => { Err(DatabaseError::NameCollision(name)) } std::collections::hash_map::Entry::Vacant(entry) => { &entry.insert((self.last_name, index + 1)); self.last_name = index + 1; self.theorems[index].2 = Some(name.to_owned()); Ok(()) } } } pub fn add_proof<'a>( &'a mut self, proof: Proof<(Option<String>, Option<usize>)>, ) -> Result<&'a Theorem, DatabaseError> { let proof = proof.map_id_result(|id| self.get_index(id.0.as_deref(), id.1))?; let new_theorem = match proof { Proof::Simplify(id, a, b) => { let theorem = &self.theorems[id].0; let mut new_theorem = theorem.substitute(&SingleSubstitution::new(a, b).unwrap())?; new_theorem.standardize(); new_theorem } Proof::Combine(id_a, id_b, index) => { let theorem_a = &self.theorems[id_a].0; let theorem_b = &self.theorems[id_b].0; let mut new_theorem = theorem_a.combine(&theorem_b, index)?; new_theorem.standardize(); new_theorem } Proof::Axiom(ref theorem) => theorem.clone(), }; self.theorems.push((new_theorem, proof, None)); Ok(&self.theorems.last().unwrap().0) }
fn reverse_id(&self, id: usize, current_id: usize) -> (Option<&str>, Option<usize>) { if let Some(name) = &self.theorems[id].2 { (Some(name), None) } else if id == current_id - 1 { (None, None) } else if id >= self.last_name { (None, Some(id - self.last_name)) } else { let name = self.theorems[id..] .iter() .filter_map(|x| x.2.as_ref()) .next() .unwrap(); let (start, end) = self.names[name]; if end >= current_id { (None, Some(id - start)) } else { (Some(name), Some(id - start)) } } } pub fn proofs<'a>( &'a self, ) -> impl 'a + Iterator<Item = (&Theorem, Proof<(Option<&str>, Option<usize>)>, Option<&str>)> { self.theorems .iter() .enumerate() .map(move |(current_id, (theorem, proof, name))| { let proof = proof.clone().map_id(|id| self.reverse_id(id, current_id)); (theorem, proof, name.as_deref()) }) } }
pub fn substitute(&mut self, theorem: Theorem) -> Result<(), DatabaseError> { let last = &mut self .theorems .last_mut() .ok_or(DatabaseError::TheoremNotFound(None, None))? .0; let mut theorem_standardized = theorem.clone(); theorem_standardized.standardize(); if last == &theorem_standardized { *last = theorem; Ok(()) } else { Err(DatabaseError::TheoremMismatch(theorem, last.clone())) } }
function_block-full_function
[ { "content": "pub fn or_fail<I, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>\n\nwhere\n\n F: Parser<I, O, E>,\n\n{\n\n move |input| {\n\n f.parse(input).map_err(|error| match error {\n\n nom::Err::Error(e) => nom::Err::Failure(e),\n\n e => e,\n\n ...
Rust
socrates-core/src/service/registry.rs
ckaran/socrates-rs
450f364e38cf663367c36991a99cd8b689d76768
use hashbrown::HashMap; use super::*; pub struct RegisteredService { core_props: ServiceCoreProps, type_id: TypeId, name: Arc<str>, owner_id: DynamodId, used_by_count: HashMap<DynamodId, u32>, service_object: Arc<dyn Service>, } impl RegisteredService { pub fn make_service_ref(&self) -> ServiceRef { ServiceRef { core: self.core_props.clone(), name: (*(self.name)).into(), type_id: self.type_id, owner_id: self.owner_id, } } } impl From<&RegisteredService> for ServiceRef { fn from(rs: &RegisteredService) -> ServiceRef { rs.make_service_ref() } } use im::OrdSet; #[derive(Default)] pub struct ServiceRegistry { curr_id: ServiceId, by_service_id: HashMap<ServiceId, RegisteredService>, by_name: HashMap<Arc<str>, OrdSet<ServiceCoreProps>>, by_type_id: HashMap<TypeId, OrdSet<ServiceCoreProps>>, zombies: HashMap<ServiceId, RegisteredService>, } impl ServiceRegistry { pub fn new() -> ServiceRegistry { Default::default() } pub fn register_service( &mut self, svc_type_id: TypeId, svc_name: &str, service_object: Arc<dyn Service>, svc_ranking: ServiceRanking, owner_id: DynamodId, ) -> ServiceRef { let new_id = self.curr_id + 1; let service = RegisteredService { core_props: ServiceCoreProps { id: new_id, ranking: svc_ranking, }, type_id: svc_type_id, name: svc_name.into(), owner_id, used_by_count: HashMap::new(), service_object, }; let service_ref = service.make_service_ref(); let svc_name = Arc::clone(&service.name); let svcs_using_name = self.by_name.entry(svc_name).or_insert(OrdSet::new()); svcs_using_name.insert(service.core_props.clone()); let svcs_using_type_id = self.by_type_id.entry(svc_type_id).or_insert(OrdSet::new()); svcs_using_type_id.insert(service.core_props.clone()); self.by_service_id.insert(new_id, service); self.curr_id = new_id; service_ref } pub fn unregister_service(&mut self, svc_id: ServiceId) -> Option<ServiceRef> { if let Some(rs) = self.by_service_id.remove(&svc_id) { self.by_name.remove(&rs.name).expect("unsynced registry!"); self.by_type_id .remove(&rs.type_id) .expect("unsynced registry!"); let svc_ref = rs.make_service_ref(); if !rs.used_by_count.is_empty() { self.zombies.insert(svc_id, rs); } else { println!("Dropping service (no users): {:?}", rs.make_service_ref()); } Some(svc_ref) } else { None } } #[inline(always)] fn get_services_id( core_props: Option<&OrdSet<ServiceCoreProps>>, ) -> impl Iterator<Item = ServiceId> { core_props .cloned() .into_iter() .flat_map(OrdSet::into_iter) .map(|cp| cp.id) } pub fn get_services_id_by_name(&self, svc_name: &str) -> impl Iterator<Item = ServiceId> { ServiceRegistry::get_services_id(self.by_name.get(svc_name)) } pub fn get_services_id_by_type_id( &self, svc_type_id: TypeId, ) -> impl Iterator<Item = ServiceId> { ServiceRegistry::get_services_id(self.by_type_id.get(&svc_type_id)) } pub fn get_service_ref(&self, svc_id: ServiceId) -> Option<ServiceRef> { self.by_service_id .get(&svc_id) .map(|rs| rs.make_service_ref()) } pub fn get_service_object( &mut self, svc_id: ServiceId, requestor: DynamodId, ) -> Option<Weak<dyn Service>> { self.by_service_id.get_mut(&svc_id).map(|rs| { let cr = rs.used_by_count.entry(requestor).or_insert(0); *cr = *cr + 1; Arc::downgrade(&rs.service_object) }) } pub fn remove_use(&mut self, svc_id: ServiceId, user_id: DynamodId) { if let Some(rs) = self.by_service_id.get_mut(&svc_id) { if ServiceRegistry::decrement_use(rs, user_id) == Some(0) { rs.used_by_count.remove(&user_id); } self.by_name .get_mut(&rs.name) .map(|v| v.remove(&rs.core_props)); } else if let Some(rs) = self.zombies.get_mut(&svc_id) { if ServiceRegistry::decrement_use(rs, user_id) == Some(0) { rs.used_by_count.remove(&user_id); if rs.used_by_count.is_empty() { println!("Dropping zombie service: {:?}", rs.make_service_ref()); self.zombies.remove(&svc_id); } } } } fn decrement_use(rs: &mut RegisteredService, owner_id: DynamodId) -> Option<u32> { rs.used_by_count.get_mut(&owner_id).map(|cr| { *cr = (*cr) - 1; *cr }) } }
use hashbrown::HashMap; use super::*; pub struct RegisteredService { core_props: ServiceCoreProps, type_id: TypeId, name: Arc<str>, owner_id: Dyn
.expect("unsynced registry!"); let svc_ref = rs.make_service_ref(); if !rs.used_by_count.is_empty() { self.zombies.insert(svc_id, rs); } else { println!("Dropping service (no users): {:?}", rs.make_service_ref()); } Some(svc_ref) } else { None } } #[inline(always)] fn get_services_id( core_props: Option<&OrdSet<ServiceCoreProps>>, ) -> impl Iterator<Item = ServiceId> { core_props .cloned() .into_iter() .flat_map(OrdSet::into_iter) .map(|cp| cp.id) } pub fn get_services_id_by_name(&self, svc_name: &str) -> impl Iterator<Item = ServiceId> { ServiceRegistry::get_services_id(self.by_name.get(svc_name)) } pub fn get_services_id_by_type_id( &self, svc_type_id: TypeId, ) -> impl Iterator<Item = ServiceId> { ServiceRegistry::get_services_id(self.by_type_id.get(&svc_type_id)) } pub fn get_service_ref(&self, svc_id: ServiceId) -> Option<ServiceRef> { self.by_service_id .get(&svc_id) .map(|rs| rs.make_service_ref()) } pub fn get_service_object( &mut self, svc_id: ServiceId, requestor: DynamodId, ) -> Option<Weak<dyn Service>> { self.by_service_id.get_mut(&svc_id).map(|rs| { let cr = rs.used_by_count.entry(requestor).or_insert(0); *cr = *cr + 1; Arc::downgrade(&rs.service_object) }) } pub fn remove_use(&mut self, svc_id: ServiceId, user_id: DynamodId) { if let Some(rs) = self.by_service_id.get_mut(&svc_id) { if ServiceRegistry::decrement_use(rs, user_id) == Some(0) { rs.used_by_count.remove(&user_id); } self.by_name .get_mut(&rs.name) .map(|v| v.remove(&rs.core_props)); } else if let Some(rs) = self.zombies.get_mut(&svc_id) { if ServiceRegistry::decrement_use(rs, user_id) == Some(0) { rs.used_by_count.remove(&user_id); if rs.used_by_count.is_empty() { println!("Dropping zombie service: {:?}", rs.make_service_ref()); self.zombies.remove(&svc_id); } } } } fn decrement_use(rs: &mut RegisteredService, owner_id: DynamodId) -> Option<u32> { rs.used_by_count.get_mut(&owner_id).map(|cr| { *cr = (*cr) - 1; *cr }) } }
amodId, used_by_count: HashMap<DynamodId, u32>, service_object: Arc<dyn Service>, } impl RegisteredService { pub fn make_service_ref(&self) -> ServiceRef { ServiceRef { core: self.core_props.clone(), name: (*(self.name)).into(), type_id: self.type_id, owner_id: self.owner_id, } } } impl From<&RegisteredService> for ServiceRef { fn from(rs: &RegisteredService) -> ServiceRef { rs.make_service_ref() } } use im::OrdSet; #[derive(Default)] pub struct ServiceRegistry { curr_id: ServiceId, by_service_id: HashMap<ServiceId, RegisteredService>, by_name: HashMap<Arc<str>, OrdSet<ServiceCoreProps>>, by_type_id: HashMap<TypeId, OrdSet<ServiceCoreProps>>, zombies: HashMap<ServiceId, RegisteredService>, } impl ServiceRegistry { pub fn new() -> ServiceRegistry { Default::default() } pub fn register_service( &mut self, svc_type_id: TypeId, svc_name: &str, service_object: Arc<dyn Service>, svc_ranking: ServiceRanking, owner_id: DynamodId, ) -> ServiceRef { let new_id = self.curr_id + 1; let service = RegisteredService { core_props: ServiceCoreProps { id: new_id, ranking: svc_ranking, }, type_id: svc_type_id, name: svc_name.into(), owner_id, used_by_count: HashMap::new(), service_object, }; let service_ref = service.make_service_ref(); let svc_name = Arc::clone(&service.name); let svcs_using_name = self.by_name.entry(svc_name).or_insert(OrdSet::new()); svcs_using_name.insert(service.core_props.clone()); let svcs_using_type_id = self.by_type_id.entry(svc_type_id).or_insert(OrdSet::new()); svcs_using_type_id.insert(service.core_props.clone()); self.by_service_id.insert(new_id, service); self.curr_id = new_id; service_ref } pub fn unregister_service(&mut self, svc_id: ServiceId) -> Option<ServiceRef> { if let Some(rs) = self.by_service_id.remove(&svc_id) { self.by_name.remove(&rs.name).expect("unsynced registry!"); self.by_type_id .remove(&rs.type_id)
random
[ { "content": "pub trait Named {\n\n fn type_name() -> &'static str;\n\n}\n\n\n", "file_path": "socrates-core/src/service/service.rs", "rank": 0, "score": 67362.85685948143 }, { "content": "#[inline(always)]\n\npub fn service_name<T: Named + ?Sized>() -> &'static str {\n\n <T>::type_nam...
Rust
src/gf/gf_num.rs
irreducible-polynoms/irrpoly-rust
b4d5e023fb02ddf32e4fd56b417a5cc89b2295f2
use crate::Gf; use std::vec::Vec; use std::fmt; use std::ops; use std::cmp; #[derive(Debug, Clone)] pub struct GfNum { field: Gf, num: usize, } impl fmt::Display for GfNum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.num) } } impl GfNum { pub fn new(field: &Gf, value: usize) -> GfNum { let field = Gf::clone(field); let value = value % field.base(); GfNum {field, num: value } } pub fn from_vec(field: &Gf, value: Vec<usize>) -> Vec<GfNum> { value.iter().map(|x| GfNum::new(field, *x) ).collect() } pub fn into_num(self) -> usize { self.num } pub fn field(&self) -> &Gf { &self.field } pub fn num(&self) -> usize { self.num } pub fn mul_inv(&self) -> Self { let field = Gf::clone(self.field()); let value = field.mul_inv(self.num) .expect("Multiplicative inverse for zero do not exist"); GfNum {field, num: value } } pub fn is_zero(&self) -> bool { self.num == 0 } } impl ops::Add<GfNum> for GfNum { type Output = GfNum; fn add(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); GfNum { field: self.field, num: (self.num + rhs.num) % base } } } impl ops::Add<usize> for GfNum { type Output = GfNum; fn add(self, rhs: usize) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: (self.num + (rhs % base)) % base } } } impl ops::Add<GfNum> for usize { type Output = GfNum; fn add(self, rhs: GfNum) -> GfNum { let base = rhs.field().base(); GfNum { field: rhs.field, num: (rhs.num + (self % base)) % base } } } impl ops::AddAssign<GfNum> for GfNum { fn add_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); self.num = (self.num + other.num) % base; } } impl ops::AddAssign<usize> for GfNum { fn add_assign(&mut self, other: usize) { let base = self.field().base(); self.num = (self.num + (other % base)) % base; } } impl ops::Sub<GfNum> for GfNum { type Output = GfNum; fn sub(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); GfNum { field: self.field, num: (base + self.num - rhs.num) % base } } } impl ops::Sub<usize> for GfNum { type Output = GfNum; fn sub(self, rhs: usize) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: (base + self.num - (rhs % base)) % base } } } impl ops::Sub<GfNum> for usize { type Output = GfNum; fn sub(self, rhs: GfNum) -> GfNum { let base = rhs.field().base(); GfNum { field: rhs.field, num: (base + rhs.num - (self % base)) % base } } } impl ops::SubAssign<GfNum> for GfNum { fn sub_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); self.num = (base + self.num - other.num) % base; } } impl ops::SubAssign<usize> for GfNum { fn sub_assign(&mut self, other: usize) { let base = self.field().base(); self.num = (base + self.num - (other % base)) % base; } } impl ops::Neg for GfNum { type Output = GfNum; fn neg(self) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: base - self.num } } } impl ops::Mul<GfNum> for GfNum { type Output = GfNum; fn mul(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); GfNum { field: self.field, num: (self.num * rhs.num) % base } } } impl ops::Mul<usize> for GfNum { type Output = GfNum; fn mul(self, rhs: usize) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: (self.num * (rhs % base)) % base } } } impl ops::Mul<GfNum> for usize { type Output = GfNum; fn mul(self, rhs: GfNum) -> GfNum { let base = rhs.field().base(); GfNum { field: rhs.field, num: (rhs.num * (self % base)) % base } } } impl ops::MulAssign<GfNum> for GfNum { fn mul_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); self.num = (self.num * other.num) % base; } } impl ops::MulAssign<usize> for GfNum { fn mul_assign(&mut self, other: usize) { let base = self.field().base(); self.num = (self.num * (other % base)) % base; } } impl ops::Div<GfNum> for GfNum { type Output = GfNum; fn div(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); let inv = self.field().mul_inv(rhs.num).unwrap(); GfNum { field: self.field, num: (self.num * inv) % base } } } impl ops::Div<usize> for GfNum { type Output = GfNum; fn div(self, rhs: usize) -> GfNum { let base = self.field().base(); let inv = self.field().mul_inv(rhs).unwrap(); GfNum { field: self.field, num: (self.num * inv) % base } } } impl ops::Div<GfNum> for usize { type Output = GfNum; fn div(self, rhs: GfNum) -> GfNum { let base = rhs.field().base(); let inv = rhs.field().mul_inv(rhs.num).unwrap(); GfNum { field: rhs.field, num: (self * inv) % base } } } impl ops::DivAssign<GfNum> for GfNum { fn div_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); let inv = self.field().mul_inv(other.num).unwrap(); self.num = (self.num * inv) % base; } } impl ops::DivAssign<usize> for GfNum { fn div_assign(&mut self, other: usize) { let base = self.field().base(); let inv = self.field().mul_inv(other).unwrap(); self.num = (self.num * inv) % base; } } impl cmp::PartialEq<GfNum> for GfNum { fn eq (&self, other: &GfNum) -> bool { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); self.num() == other.num() } } impl cmp::PartialEq<usize> for GfNum { fn eq (&self, other: &usize) -> bool { let base = self.field().base(); self.num() == other % base } } impl cmp::PartialEq<GfNum> for usize { fn eq (&self, other: &GfNum) -> bool { let base = other.field().base(); self % base == other.num() } } impl cmp::Eq for GfNum {} impl cmp::PartialOrd<GfNum> for GfNum { fn partial_cmp(&self, other: &GfNum) -> Option<cmp::Ordering> { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); self.num.partial_cmp(&other.num) } } impl cmp::PartialOrd<usize> for GfNum { fn partial_cmp(&self, other: &usize) -> Option<cmp::Ordering> { let base = self.field().base(); self.num.partial_cmp(&(other % base)) } } impl cmp::PartialOrd<GfNum> for usize { fn partial_cmp(&self, other: &GfNum) -> Option<cmp::Ordering> { let base = other.field().base(); (self % base).partial_cmp(&other.num) } } impl cmp::Ord for GfNum { fn cmp(&self, other: &GfNum) -> cmp::Ordering { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); self.num.cmp(&other.num) } }
use crate::Gf; use std::vec::Vec; use std::fmt; use std::ops; use std::cmp; #[derive(Debug, Clone)] pub struct GfNum { field: Gf, num: usize, } impl fmt::Display for GfNum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.num) } } impl GfNum { pub fn new(field: &Gf, value: usize) -> GfNum { let field = Gf::clone(field); let value = value % field.base(); GfNum {field, num: value } } pub fn from_vec(field: &Gf, value: Vec<usize>) -> Vec<GfNum> { value.iter().map(|x| GfNum::new(field, *x) ).collect() } pub fn into_num(self) -> usize { self.num } pub fn field(&self) -> &Gf { &self.field } pub fn num(&self) -> usize { self.num } pub fn mul_inv(&self) -> Self { let field = Gf::clone(self.field()); let value = field.mul_inv(self.num) .expect("Multiplicative inverse for zero do not exist"); GfNum {field, num: value } } pub fn is_zero(&self) -> bool { self.num == 0 } } impl ops::Add<GfNum> for GfNum { type Output = GfNum; fn add(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); GfNum { field: self.field, num: (self.num + rhs.num) % base } } } impl ops::Add<usize> for GfNum { type Output = GfNum; fn add(self, rhs: usize) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: (self.num + (rhs % base)) % base } } } impl ops::Add<GfNum> for usize { type Output = GfNum; fn add(self, rhs: GfNum) -> GfNum { let base = rhs.field().base(); GfNum { field: rhs.field, num: (rhs.num + (self % base)) % base } } } impl ops::AddAssign<GfNum> for GfNum { fn add_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); self.num = (self.num + other.num) % base; } } impl ops::AddAssign<usize> for GfNum { fn add_assign(&mut self, other: usize) { let base = self.field().base(); self.num = (self.num + (other % base)) % base; } } impl ops::Sub<GfNum> for GfNum { type Output = GfNum; fn sub(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); GfNum { field: self.field, num: (base + self.num - rhs.num) % base } } } impl ops::Sub<usize> for GfNum { type Output = GfNum; fn sub(self, rhs: usize) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: (base + self.num - (rhs % base)) % base } } } impl ops::Sub<GfNum> for usize { type Output = GfNum; fn sub(self, rhs: GfNum) -> GfNum { let base = rh
} impl ops::SubAssign<GfNum> for GfNum { fn sub_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); self.num = (base + self.num - other.num) % base; } } impl ops::SubAssign<usize> for GfNum { fn sub_assign(&mut self, other: usize) { let base = self.field().base(); self.num = (base + self.num - (other % base)) % base; } } impl ops::Neg for GfNum { type Output = GfNum; fn neg(self) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: base - self.num } } } impl ops::Mul<GfNum> for GfNum { type Output = GfNum; fn mul(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); GfNum { field: self.field, num: (self.num * rhs.num) % base } } } impl ops::Mul<usize> for GfNum { type Output = GfNum; fn mul(self, rhs: usize) -> GfNum { let base = self.field().base(); GfNum { field: self.field, num: (self.num * (rhs % base)) % base } } } impl ops::Mul<GfNum> for usize { type Output = GfNum; fn mul(self, rhs: GfNum) -> GfNum { let base = rhs.field().base(); GfNum { field: rhs.field, num: (rhs.num * (self % base)) % base } } } impl ops::MulAssign<GfNum> for GfNum { fn mul_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); self.num = (self.num * other.num) % base; } } impl ops::MulAssign<usize> for GfNum { fn mul_assign(&mut self, other: usize) { let base = self.field().base(); self.num = (self.num * (other % base)) % base; } } impl ops::Div<GfNum> for GfNum { type Output = GfNum; fn div(self, rhs: GfNum) -> GfNum { debug_assert_eq!(self.field(), rhs.field(), "Numbers from different fields"); let base = self.field().base(); let inv = self.field().mul_inv(rhs.num).unwrap(); GfNum { field: self.field, num: (self.num * inv) % base } } } impl ops::Div<usize> for GfNum { type Output = GfNum; fn div(self, rhs: usize) -> GfNum { let base = self.field().base(); let inv = self.field().mul_inv(rhs).unwrap(); GfNum { field: self.field, num: (self.num * inv) % base } } } impl ops::Div<GfNum> for usize { type Output = GfNum; fn div(self, rhs: GfNum) -> GfNum { let base = rhs.field().base(); let inv = rhs.field().mul_inv(rhs.num).unwrap(); GfNum { field: rhs.field, num: (self * inv) % base } } } impl ops::DivAssign<GfNum> for GfNum { fn div_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); let inv = self.field().mul_inv(other.num).unwrap(); self.num = (self.num * inv) % base; } } impl ops::DivAssign<usize> for GfNum { fn div_assign(&mut self, other: usize) { let base = self.field().base(); let inv = self.field().mul_inv(other).unwrap(); self.num = (self.num * inv) % base; } } impl cmp::PartialEq<GfNum> for GfNum { fn eq (&self, other: &GfNum) -> bool { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); self.num() == other.num() } } impl cmp::PartialEq<usize> for GfNum { fn eq (&self, other: &usize) -> bool { let base = self.field().base(); self.num() == other % base } } impl cmp::PartialEq<GfNum> for usize { fn eq (&self, other: &GfNum) -> bool { let base = other.field().base(); self % base == other.num() } } impl cmp::Eq for GfNum {} impl cmp::PartialOrd<GfNum> for GfNum { fn partial_cmp(&self, other: &GfNum) -> Option<cmp::Ordering> { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); self.num.partial_cmp(&other.num) } } impl cmp::PartialOrd<usize> for GfNum { fn partial_cmp(&self, other: &usize) -> Option<cmp::Ordering> { let base = self.field().base(); self.num.partial_cmp(&(other % base)) } } impl cmp::PartialOrd<GfNum> for usize { fn partial_cmp(&self, other: &GfNum) -> Option<cmp::Ordering> { let base = other.field().base(); (self % base).partial_cmp(&other.num) } } impl cmp::Ord for GfNum { fn cmp(&self, other: &GfNum) -> cmp::Ordering { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); self.num.cmp(&other.num) } }
s.field().base(); GfNum { field: rhs.field, num: (base + rhs.num - (self % base)) % base } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn not_a_field() {\n\n assert!(Gf::new(0).is_err());\n\n assert!(Gf::new(1).is_err());\n\n assert!(Gf::new(4).is_err());\n\n assert!(Gf::new(isize::max_value() as usize).is_err());\n\n}\n\n\n", "file_path": "src/gf/tests.rs", "rank": 0, "score": 54802.98112542429...
Rust
src/equalizer.rs
joaocarvalhoopen/Audio_filters_in_Rust
00639f0c30078a5fd3f39a690243f5742743ae02
use crate::iir_filter::ProcessingBlock; use crate::iir_filter::IIRFilter; use crate::butterworth_filter::make_peak_eq_constant_q; pub struct Equalizer { sample_rate: u32, bands_vec: Vec<f64>, bands_gain_vec: Vec<f64>, gain_max_db: f64, gain_min_db: f64, q_factor: f64, iir_filters_vec: Vec<IIRFilter>, } impl Equalizer { pub fn new(sample_rate: u32, bands_vec: & Vec<f64>, gain_max_db:f64, gain_min_db:f64, q_factor:f64 ) -> Self { let mut equalizer = Equalizer{ sample_rate, bands_vec: bands_vec.clone(), bands_gain_vec: vec![0.0; bands_vec.len()], gain_max_db, gain_min_db, q_factor, iir_filters_vec: Vec::with_capacity(bands_vec.len()) }; equalizer.gen_chain_filters(); equalizer } fn gen_chain_filters(& mut self) { for band in & self.bands_vec { let frequency_center = *band; let gain_db = 0.0; let iir_filter = make_peak_eq_constant_q(frequency_center, self.sample_rate, gain_db, Some(self.q_factor)); self.iir_filters_vec.push(iir_filter); } } fn change_filter(& mut self, index: usize) { assert!(index < self.bands_vec.len()); let frequency_center = self.bands_vec[index]; let gain_db = self.bands_gain_vec[index]; let q_factor = Some(self.q_factor); let iir_filter_tmp = make_peak_eq_constant_q(frequency_center, self.sample_rate, gain_db, q_factor); let _ = self.iir_filters_vec[index].set_coefficients(& iir_filter_tmp.a_coeffs, & iir_filter_tmp.b_coeffs); } pub fn get_bands_freq(& self, index: usize) -> f64 { assert!(index < self.bands_vec.len()); self.bands_vec[index] } pub fn get_band_gain(& self, index: usize) -> f64 { assert!(index < self.bands_vec.len()); self.bands_gain_vec[index] } pub fn set_band_gain(& mut self, index: usize, gain_db: f64) -> Result<(), String> { assert!(index < self.bands_vec.len()); if gain_db < self.gain_min_db || gain_db > self.gain_max_db { return Err(format!("Error: invalid gain value {}, must be in the interval [{}, {}]", gain_db, self.gain_min_db, self.gain_max_db)); } self.bands_gain_vec[index] = gain_db; self.change_filter(index); Ok(()) } pub fn make_equalizer_10_band(sample_rate: u32) -> Equalizer { let bands_vec = vec![ 29.0, 59.0, 119.0, 237.0, 474.0, 947.0, 1889.0, 3770.0, 7523.0, 15011.0 ]; let gain_max_db = 12.0; let gain_min_db = -24.0; let q_factor = 2.0 * f64::sqrt(2.0); let equalizer_10_band = Equalizer::new(sample_rate, & bands_vec, gain_max_db, gain_min_db, q_factor); equalizer_10_band } } impl ProcessingBlock for Equalizer { fn process(& mut self, sample: f64) -> f64 { let mut sample_t = sample; for iir_filter in & mut self.iir_filters_vec { sample_t = iir_filter.process(sample_t); } sample_t } }
use crate::iir_filter::ProcessingBlock; use crate::iir_filter::IIRFilter; use crate::butterworth_filter::make_peak_eq_constant_q; pub struct Equalizer { sample_rate: u32, bands_vec: Vec<f64>, bands_gain_vec: Vec<f64>, gain_max_db: f64, gain_min_db: f64, q_factor: f64, iir_filters_vec: Vec<IIRFilter>, } impl Equalizer { pub fn new(sample_rate: u32, bands_vec: & Vec<f64>, gain_max_db:f64, gain_min_db:f64, q_factor:f64 ) -> Self { let mut equalizer = Equalizer{ sample_rate, bands_vec: bands_vec.clone(), bands_gain_vec: vec![0.0; bands_vec.len()], gain_max_db, gain_min_db, q_factor, iir_filters_vec: Vec::with_capacity(bands_vec.len()) }; equalizer.gen_chain_filters(); equalizer } fn gen_chain_filters(& mut self) { f
self.iir_filters_vec.push(iir_filter); } } fn change_filter(& mut self, index: usize) { assert!(index < self.bands_vec.len()); let frequency_center = self.bands_vec[index]; let gain_db = self.bands_gain_vec[index]; let q_factor = Some(self.q_factor); let iir_filter_tmp = make_peak_eq_constant_q(frequency_center, self.sample_rate, gain_db, q_factor); let _ = self.iir_filters_vec[index].set_coefficients(& iir_filter_tmp.a_coeffs, & iir_filter_tmp.b_coeffs); } pub fn get_bands_freq(& self, index: usize) -> f64 { assert!(index < self.bands_vec.len()); self.bands_vec[index] } pub fn get_band_gain(& self, index: usize) -> f64 { assert!(index < self.bands_vec.len()); self.bands_gain_vec[index] } pub fn set_band_gain(& mut self, index: usize, gain_db: f64) -> Result<(), String> { assert!(index < self.bands_vec.len()); if gain_db < self.gain_min_db || gain_db > self.gain_max_db { return Err(format!("Error: invalid gain value {}, must be in the interval [{}, {}]", gain_db, self.gain_min_db, self.gain_max_db)); } self.bands_gain_vec[index] = gain_db; self.change_filter(index); Ok(()) } pub fn make_equalizer_10_band(sample_rate: u32) -> Equalizer { let bands_vec = vec![ 29.0, 59.0, 119.0, 237.0, 474.0, 947.0, 1889.0, 3770.0, 7523.0, 15011.0 ]; let gain_max_db = 12.0; let gain_min_db = -24.0; let q_factor = 2.0 * f64::sqrt(2.0); let equalizer_10_band = Equalizer::new(sample_rate, & bands_vec, gain_max_db, gain_min_db, q_factor); equalizer_10_band } } impl ProcessingBlock for Equalizer { fn process(& mut self, sample: f64) -> f64 { let mut sample_t = sample; for iir_filter in & mut self.iir_filters_vec { sample_t = iir_filter.process(sample_t); } sample_t } }
or band in & self.bands_vec { let frequency_center = *band; let gain_db = 0.0; let iir_filter = make_peak_eq_constant_q(frequency_center, self.sample_rate, gain_db, Some(self.q_factor));
function_block-random_span
[ { "content": "/// Creates a low-pass filter\n\n///\n\n/// In Python: \n\n/// >>> filter = make_lowpass(1000, 48000)\n\n/// >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n\n/// [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809,\n\n/// 0.00855...
Rust
sandbox/src/tilemap.rs
aengusmcmillin/Gouda
4aed65c94ad4147372d71c08622dacf01f5eac4e
use gouda::rendering::{drawable::{TextureDrawable, QuadDrawable}, Renderer, Scene, texture::RenderableTexture}; use gouda::ecs::{ECS, Entity, GenIndex}; use std::rc::Rc; use crate::camera::Camera; use gouda::bmp::Bitmap; use gouda::mouse_capture::{MouseCaptureArea, MouseCaptureLayer, ActiveCaptureLayer}; use gouda::types::{Bounds, Direction}; use gouda::images::Image; use gouda::images::png::PNG; use crate::hearth::Hearth; const GRASS_COLOR: [f32; 3] = [0.2, 0.4, 0.3]; const HEARTH_COLOR: [f32; 3] = [0.5, 0.2, 0.2]; const BORDER_COLOR: [f32; 3] = [0.5, 0.5, 0.5]; #[derive(Debug)] pub struct Tile { pub x: i32, pub y: i32, pub occupied: bool, neighbors: [Option<Entity>; 4], color_drawable: Option<QuadDrawable>, texture_drawable: Option<TextureDrawable>, } impl Tile { pub fn create_image_tile(image: &Image, ecs: &mut ECS, x: usize, y: usize) -> Entity { Self::create_texture_tile(ecs, image, x, y) } pub fn neighbor(&self, direction: Direction) -> Option<Entity> { self.neighbors[direction as usize] } fn create_texture_tile(ecs: &mut ECS, image: &Image, x: usize, y: usize) -> Entity { let renderer = ecs.read_res::<Rc<Renderer>>(); let drawable = TextureDrawable::new(false, renderer, RenderableTexture::new(renderer, image), [-5. + x as f32, -3. + y as f32, 0.], [0.52, 0.52, 1.], [0.; 3]); let tile = Tile { color_drawable: None, texture_drawable: Some(drawable), occupied: false, x: x as i32 - 5, y: y as i32 - 3, neighbors: [None; 4], }; ecs.build_entity().add(tile).add(MouseCaptureArea::new(Bounds{x: x as i32 * 80, y: y as i32 * 80 + 160, w: 80, h: 80})).entity() } fn create_tile(ecs: &mut ECS, color: [f32; 3], x: usize, y: usize) -> Entity { let renderer = ecs.read_res::<Rc<Renderer>>(); let quad = QuadDrawable::new(false, renderer, color, [-5. + x as f32 * 1., -3. + y as f32 * 1., 0.], [0.5, 0.5, 1.], [0.; 3]); let tile = Tile { color_drawable: Some(quad), texture_drawable: None, occupied: false, x: x as i32 - 5, y: y as i32 - 3, neighbors: [None; 4], }; ecs.build_entity().add(tile).add(MouseCaptureArea::new(Bounds{x: x as i32 * 80, y: y as i32 * 80 + 160, w: 80, h: 80})).entity() } pub fn draw(&self, scene: &Scene, camera: &Camera) { if let Some(drawable) = &self.color_drawable { drawable.draw_with_projection(&scene, &camera.projection_buffer); } if let Some(drawable) = &self.texture_drawable { drawable.draw_with_projection(&scene, &camera.projection_buffer); } } } pub struct Tilemap { tiles: Vec<Vec<Entity>>, borders: Vec<Entity>, } fn set_neighbors(tile: &mut Tile, x: usize, y: usize, tiles: &Vec<Vec<Entity>>) { tile.neighbors = [ if y > 0 { Some(tiles[x][y - 1]) } else { None }, if x < (tiles.len() - 1) { Some(tiles[x + 1][y]) } else { None }, if y < (tiles[x].len() - 1) { Some(tiles[x][y + 1]) } else { None }, if x > 0 { Some(tiles[x - 1][y]) } else { None }, ] } impl Tilemap { pub fn borders(&self) -> &Vec<Entity> { return &self.borders; } pub fn create(ecs: &mut ECS) { let mut tiles: Vec<Vec<Entity>> = vec![Vec::with_capacity(9); 11]; let mut center_tile = None; let grass = PNG::from_file("bitmap/grass.png").unwrap().image(); let border = Bitmap::new("bitmap/grass2.bmp").unwrap().image(); let mut borders = vec!(); for x in 0..11 { for y in 0..9 { let tile = if x == 0 || x == 10 || y == 0 || y == 8 { let e = Tile::create_image_tile(&border, ecs, x, y); borders.push(e); e } else { Tile::create_image_tile(&grass, ecs, x, y) }; if x == 5 && y == 4 { center_tile = Some(tile.clone()); } tiles[x].push(tile); } } let mut all_tiles = vec![]; for tiles in &tiles { for tile in tiles { all_tiles.push(tile.clone()); } } for x in 0..11 { for y in 0..9 { let t = ecs.write::<Tile>(&tiles[x][y]).unwrap(); set_neighbors(t, x, y, &tiles); } } let capture_area = MouseCaptureLayer { sort_index: 0, capture_areas: all_tiles, }; ecs.build_entity().add(capture_area).add(ActiveCaptureLayer {}); let res = Tilemap { tiles, borders }; ecs.add_res(res); Hearth::create(ecs, center_tile.unwrap()); ecs.write::<Tile>(&center_tile.unwrap()).unwrap().occupied = true; } pub fn tile_at_pos(&self, x: usize, y: usize) -> Entity { self.tiles[x][y].clone() } pub fn pos_of_tile(&self, tile: Entity) -> (f32, f32) { let mut x = 0.; for column in &self.tiles { let mut y = 0.; for t in column { if tile == *t { return (x - 5., y - 3.); } y += 1.; } x += 1.; } return (0., 0.); } }
use gouda::rendering::{drawable::{TextureDrawable, QuadDrawable}, Renderer, Scene, texture::RenderableTexture}; use gouda::ecs::{ECS, Entity, GenIndex}; use std::rc::Rc; use crate::camera::Camera; use gouda::bmp::Bitmap; use gouda::mouse_capture::{MouseCaptureArea, MouseCaptureLayer, ActiveCaptureLayer}; use gouda::types::{Bounds, Direction}; use gouda::images::Image; use gouda::images::png::PNG; use crate::hearth::Hearth; const GRASS_COLOR: [f32; 3] = [0.2, 0.4, 0.3]; const HEARTH_COLOR: [f32; 3] = [0.5, 0.2, 0.2]; const BORDER_COLOR: [f32; 3] = [0.5, 0.5, 0.5]; #[derive(Debug)] pub struct Tile { pub x: i32, pub y: i32, pub occupied: bool, neighbors: [Option<Entity>; 4], color_drawable: Option<QuadDrawable>, texture_drawable: Option<TextureDrawable>, } impl Tile { pub fn create_image_tile(image: &Image, ecs: &mut ECS, x: usize, y: usize) -> Entity { Self::create_texture_tile(ecs, image, x, y) } pub fn neighbor(&self, direction: Direction) -> Option<Entity> { self.neighbors[direction as usize] } fn create_texture_tile(ecs: &mut ECS, image: &Image, x: usize, y: usize) -> Entity { let renderer = ecs.read_res::<Rc<Renderer>>(); let drawable = TextureDrawable::new(false, renderer, RenderableTexture::new(renderer, image), [-5. + x as f32, -3. + y as f32, 0.], [0.52, 0.52, 1.], [0.; 3]); let tile = Tile { color_drawable: None, texture_drawable: Some(drawable),
fn create_tile(ecs: &mut ECS, color: [f32; 3], x: usize, y: usize) -> Entity { let renderer = ecs.read_res::<Rc<Renderer>>(); let quad = QuadDrawable::new(false, renderer, color, [-5. + x as f32 * 1., -3. + y as f32 * 1., 0.], [0.5, 0.5, 1.], [0.; 3]); let tile = Tile { color_drawable: Some(quad), texture_drawable: None, occupied: false, x: x as i32 - 5, y: y as i32 - 3, neighbors: [None; 4], }; ecs.build_entity().add(tile).add(MouseCaptureArea::new(Bounds{x: x as i32 * 80, y: y as i32 * 80 + 160, w: 80, h: 80})).entity() } pub fn draw(&self, scene: &Scene, camera: &Camera) { if let Some(drawable) = &self.color_drawable { drawable.draw_with_projection(&scene, &camera.projection_buffer); } if let Some(drawable) = &self.texture_drawable { drawable.draw_with_projection(&scene, &camera.projection_buffer); } } } pub struct Tilemap { tiles: Vec<Vec<Entity>>, borders: Vec<Entity>, } fn set_neighbors(tile: &mut Tile, x: usize, y: usize, tiles: &Vec<Vec<Entity>>) { tile.neighbors = [ if y > 0 { Some(tiles[x][y - 1]) } else { None }, if x < (tiles.len() - 1) { Some(tiles[x + 1][y]) } else { None }, if y < (tiles[x].len() - 1) { Some(tiles[x][y + 1]) } else { None }, if x > 0 { Some(tiles[x - 1][y]) } else { None }, ] } impl Tilemap { pub fn borders(&self) -> &Vec<Entity> { return &self.borders; } pub fn create(ecs: &mut ECS) { let mut tiles: Vec<Vec<Entity>> = vec![Vec::with_capacity(9); 11]; let mut center_tile = None; let grass = PNG::from_file("bitmap/grass.png").unwrap().image(); let border = Bitmap::new("bitmap/grass2.bmp").unwrap().image(); let mut borders = vec!(); for x in 0..11 { for y in 0..9 { let tile = if x == 0 || x == 10 || y == 0 || y == 8 { let e = Tile::create_image_tile(&border, ecs, x, y); borders.push(e); e } else { Tile::create_image_tile(&grass, ecs, x, y) }; if x == 5 && y == 4 { center_tile = Some(tile.clone()); } tiles[x].push(tile); } } let mut all_tiles = vec![]; for tiles in &tiles { for tile in tiles { all_tiles.push(tile.clone()); } } for x in 0..11 { for y in 0..9 { let t = ecs.write::<Tile>(&tiles[x][y]).unwrap(); set_neighbors(t, x, y, &tiles); } } let capture_area = MouseCaptureLayer { sort_index: 0, capture_areas: all_tiles, }; ecs.build_entity().add(capture_area).add(ActiveCaptureLayer {}); let res = Tilemap { tiles, borders }; ecs.add_res(res); Hearth::create(ecs, center_tile.unwrap()); ecs.write::<Tile>(&center_tile.unwrap()).unwrap().occupied = true; } pub fn tile_at_pos(&self, x: usize, y: usize) -> Entity { self.tiles[x][y].clone() } pub fn pos_of_tile(&self, tile: Entity) -> (f32, f32) { let mut x = 0.; for column in &self.tiles { let mut y = 0.; for t in column { if tile == *t { return (x - 5., y - 3.); } y += 1.; } x += 1.; } return (0., 0.); } }
occupied: false, x: x as i32 - 5, y: y as i32 - 3, neighbors: [None; 4], }; ecs.build_entity().add(tile).add(MouseCaptureArea::new(Bounds{x: x as i32 * 80, y: y as i32 * 80 + 160, w: 80, h: 80})).entity() }
function_block-function_prefix_line
[ { "content": "pub fn win32_process_keyboard(keyboard: &mut KeyboardInput, vkcode: i32, was_down: bool, is_down: bool) {\n\n if was_down != is_down {\n\n if vkcode == VK_UP {\n\n win32_process_keyboard_message(\n\n &mut keyboard.special_keys[SpecialKeys::UpArrow],\n\n ...
Rust
src/lib.rs
DownToZero-Cloud/dtz-identity-auth
a93d6ca8472680fd8d1d7f6dc4082e5726aa5438
#![deny(missing_docs)] #![feature(adt_const_params)] use serde::{Serialize,Deserialize}; use axum::{ async_trait, extract::{FromRequest, RequestParts}, http::header::HeaderValue, http::{StatusCode}, }; use uuid::Uuid; use jwt::PKeyWithDigest; use openssl::hash::MessageDigest; use openssl::pkey::PKey; use jwt::algorithm::VerifyingAlgorithm; use jwt::claims::Claims; use jwt::FromBase64; use cookie::Cookie; use hyper::{Body, Request,Client,Method}; use hyper::body; use lru_time_cache::LruCache; use std::sync::Mutex; use once_cell::sync::Lazy; const PUBLIC_KEY: &str = r#"-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0gVBfnAa7748XyjOYXQ5 Yf39yKJ/t3b2wF5F1yPUuyLanwZYTGBV804Vs0YWiiKJ1H/csI3jWX5CWkV5TzMx CIP4kCugsFH6wP8rCt8Vei+rdJFB/LrlYz8Ks8Td60c5t/Hq9yQEz6kIpa5TmZw2 DSDPvOKXW2SJRPCqj3JEk6fHsJ6nZ2BIoFvs6NMRNqgSEHr1x7lUUt9teWM2wOtF ze24D+luvXWhRUjMMvMKkPuxdS6mPbXqoyde3U9tcsC+t2tThqVaREPkj6ew1IcU RnoXLi+43p4j4cQqxRjG3DzzjqAlivFjlGR/vqfLvUrGP9opjI+zs3l4G8IYWsqM KQIDAQAB -----END PUBLIC KEY-----"#; #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct DtzProfile { pub identity_id: Uuid, pub context_id: Uuid, #[serde(skip_serializing_if = "Vec::is_empty")] pub roles: Vec<String>, } pub struct DtzRequiredRole<const N: &'static str>(pub DtzProfile); #[async_trait] impl<B, const N: &'static str> FromRequest<B> for DtzRequiredRole<N> where B: Send, { type Rejection = (StatusCode, &'static str); async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { let result = get_profile_from_request(req).await; match result { Ok(profile) => { let scope = replace_placeholder(N, &profile); if !profile.roles.contains(&scope) { return Err((StatusCode::FORBIDDEN, "no permission")); } Ok(DtzRequiredRole(profile)) }, Err(e) => Err((StatusCode::UNAUTHORIZED, &e)), } } } pub struct DtzRequiredUser(pub DtzProfile); #[async_trait] impl<B> FromRequest<B> for DtzRequiredUser where B: Send, { type Rejection = (StatusCode, &'static str); async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { let result = get_profile_from_request(req).await; match result { Ok(profile) => Ok(DtzRequiredUser(profile)), Err(e) => Err((StatusCode::UNAUTHORIZED, e)), } } } pub struct DtzOptionalUser(pub Option<DtzProfile>); #[async_trait] impl<B> FromRequest<B> for DtzOptionalUser where B: Send, { type Rejection = (StatusCode, &'static str); async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { let result = get_profile_from_request(req).await; match result { Ok(profile) => Ok(DtzOptionalUser(Some(profile))), Err(_e) => Ok(DtzOptionalUser(None)), } } } async fn get_profile_from_request<B>(req: &mut RequestParts<B>) -> Result<DtzProfile,&'static str> { let headers = req.headers().clone(); let cookie: Option<&HeaderValue> = headers.get("cookie"); let authorization: Option<&HeaderValue> = headers.get("authorization"); let header_api_key: Option<&HeaderValue> = headers.get("x-api-key"); let header_context_id: Option<&HeaderValue> = headers.get("x-dtz-context"); let profile: DtzProfile; if let Some(cookie) = cookie { match verify_token_from_cookie(cookie.clone()) { Ok(p) => { profile = p; }, Err(_) => { return Err("no valid token found in cookie"); } } }else if let Some(authorization) = authorization { match verify_token_from_bearer(authorization.clone()) { Ok(p) => { profile = p; }, Err(_) => { return Err("not authorized"); } } }else if let Some(header_api_key) = header_api_key { if header_context_id.is_some() { profile = verifiy_api_key(header_api_key.to_str().unwrap(), Some(header_context_id.unwrap().to_str().unwrap())).await.unwrap(); }else{ profile = verifiy_api_key(header_api_key.to_str().unwrap(), None).await.unwrap(); } }else { let query = req.uri().query().unwrap_or_default(); let value: GetAuthParams = serde_urlencoded::from_str(query).unwrap(); if value.api_key.is_some() { if value.context_id.is_some() { profile = verifiy_api_key(&value.api_key.unwrap(), Some(&value.context_id.unwrap())).await.unwrap(); }else{ profile = verifiy_api_key(&value.api_key.unwrap(), None).await.unwrap(); } }else{ return Err("no authorization header"); } } Ok(profile) } fn verify_token_from_cookie(cookie: HeaderValue) -> Result<DtzProfile,String> { let cookie_str = cookie.to_str().unwrap(); match Cookie::parse(cookie_str){ Ok(cookie) => { let token = cookie.value().to_string(); verify_token(token) }, Err(_) => Err("no valid token found in cookie".to_string()) } } fn verify_token_from_bearer(bearer: HeaderValue) -> Result<DtzProfile,String> { let bearer_str = bearer.to_str().unwrap(); let jwt = bearer_str.replace("Bearer ",""); verify_token(jwt) } fn verify_token(token: String) -> Result<DtzProfile,String> { if token.as_str().contains('.') { let jwt_parts: Vec<&str> = token.split('.').collect(); let jwt_alg = jwt_parts.get(0).unwrap(); let jwt_payload = jwt_parts.get(1).unwrap(); let jwt_sig = jwt_parts.get(2).unwrap(); let algorithm = PKeyWithDigest { digest: MessageDigest::sha256(), key: PKey::public_key_from_pem(PUBLIC_KEY.as_bytes()).unwrap(), }; match algorithm.verify(jwt_alg, jwt_payload, jwt_sig) { Ok(_) => { let claims = Claims::from_base64(jwt_payload).unwrap(); let roles_claim = claims.private.get("roles").unwrap(); let mut roles: Vec<String> = Vec::new(); let arr = roles_claim.as_array().unwrap(); for role in arr { roles.push(role.as_str().unwrap().to_string()); } let scope_str = claims.private.get("scope").unwrap().as_str().unwrap(); let result = DtzProfile{ identity_id: Uuid::parse_str(&claims.registered.subject.unwrap()).unwrap(), context_id: Uuid::parse_str(scope_str).unwrap(), roles, }; Ok(result) }, Err(_) => { return Err("invalid token".to_string()); } } }else{ Err("not authorized".to_string()) } } #[derive(Serialize, Deserialize, Debug)] struct TokenResponse { access_token: String, scope: Option<String>, token_type: String, expires_in: u32, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct GetAuthParams { api_key: Option<String>, context_id: Option<String>, } static KNOWN_IDENTITIES: Lazy<Mutex<LruCache::<String, DtzProfile>>> = Lazy::new(|| { let time_to_live = std::time::Duration::from_secs(3600); let m = LruCache::<String, DtzProfile>::with_expiry_duration_and_capacity(time_to_live,100); Mutex::new(m) }); async fn verifiy_api_key(api_key: &str, context_id: Option<&str>) -> Result<DtzProfile,String> { let req_data = if context_id.is_some() { format!("{{\"apiKey\":\"{}\",\"contextId\":\"{}\"}}",api_key,context_id.unwrap()) } else { format!("{{\"apiKey\":\"{}\"}}",api_key) }; { let mut x = KNOWN_IDENTITIES.lock().unwrap(); if x.contains_key(&req_data){ let profile = x.get(&req_data).unwrap().clone(); return Ok(profile); } } let hostname = std::env::var("HOSTNAME").unwrap_or("localhost".to_string()); let req = Request::builder() .method(Method::POST) .uri("https://identity.dtz.rocks/api/2021-02-21/auth/apikey") .header("content-type", "application/json") .header("X-DTZ-SOURCE", hostname) .body(Body::from(req_data.clone())).unwrap(); let https = hyper_rustls::HttpsConnectorBuilder::new() .with_native_roots() .https_only() .enable_http1() .build(); let http_client = Client::builder().build(https); let resp = http_client.request(req).await.unwrap(); if resp.status().is_success() { let bytes = body::to_bytes(resp.into_body()).await.unwrap(); let resp_str = String::from_utf8(bytes.to_vec()).expect("response was not valid utf-8"); let token_response: TokenResponse = serde_json::from_str(&resp_str).unwrap(); let jwt = token_response.access_token; let result = verify_token(jwt); { if result.is_ok() { let mut x = KNOWN_IDENTITIES.lock().unwrap(); x.insert(req_data,result.clone().unwrap()); } } result }else{ Err("not authorized".to_string()) } } fn replace_placeholder(template: &str, profile: &DtzProfile) -> String { let mut result = template.to_string(); result = result.replace("{identity_id}", &profile.identity_id.to_string()); result = result.replace("{context_id}", &profile.context_id.to_string()); result = result.replace("{roles}", &profile.roles.join(",")); result } pub fn verify_role(profile: &DtzProfile, role: &str) -> bool { profile.roles.contains(&role.to_string()) } pub fn verfify_context_role(profile: &DtzProfile, role: &str) -> bool { let replaced_role = replace_placeholder(role, profile); profile.roles.contains(&replaced_role.to_string()) } #[cfg(test)] mod tests { use uuid::Uuid; use super::*; #[test] fn test_replacement_identity() { let identity = DtzProfile{ identity_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), context_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), roles: vec!["admin".to_string()], }; let result = super::replace_placeholder("https://dtz.rocks/context/admin/{identity_id}", &identity); assert_eq!(result, "https://dtz.rocks/context/admin/00000000-0000-0000-0000-000000000000"); } #[test] fn test_replacement_context() { let identity = DtzProfile{ identity_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), context_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), roles: vec!["admin".to_string()], }; let result = super::replace_placeholder("https://dtz.rocks/context/admin/{context_id}", &identity); assert_eq!(result, "https://dtz.rocks/context/admin/00000000-0000-0000-0000-000000000000"); } #[test] fn test_replacement_nothing() { let identity = DtzProfile{ identity_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), context_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), roles: vec!["admin".to_string()], }; let result = super::replace_placeholder("https://dtz.rocks/context/admin", &identity); assert_eq!(result, "https://dtz.rocks/context/admin"); } }
#![deny(missing_docs)] #![feature(adt_const_params)] use serde::{Serialize,Deserialize}; use axum::{ async_trait, extract::{FromRequest, RequestParts}, http::header::HeaderValue, http::{StatusCode}, }; use uuid::Uuid; use jwt::PKeyWithDigest; use openssl::hash::MessageDigest; use openssl::pkey::PKey; use jwt::algorithm::VerifyingAlgorithm; use jwt::claims::Claims; use jwt::FromBase64; use cookie::Cookie; use hyper::{Body, Request,Client,Method}; use hyper::body; use lru_time_cache::LruCache; use std::sync::Mutex; use once_cell::sync::Lazy; const PUBLIC_KEY: &str = r#"-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0gVBfnAa7748XyjOYXQ5 Yf39yKJ/t3b2wF5F1yPUuyLanwZYTGBV804Vs0YWiiKJ1H/csI3jWX5CWkV5TzMx CIP4kCugsFH6wP8rCt8Vei+rdJFB/LrlYz8Ks8Td60c5t/Hq9yQEz6kIpa5TmZw2 DSDPvOKXW2SJRPCqj3JEk6fHsJ6nZ2BIoFvs6NMRNqgSEHr1x7lUUt9teWM2wOtF ze24D+luvXWhRUjMMvMKkPuxdS6mPbXqoyde3U9tcsC+t2tThqVaREPkj6ew1IcU RnoXLi+43p4j4cQqxRjG3DzzjqAlivFjlGR/vqfLvUrGP9opjI+zs3l4G8IYWsqM KQIDAQAB -----END PUBLIC KEY-----"#; #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct DtzProfile { pub identity_id: Uuid, pub context_id: Uuid, #[serde(skip_serializing_if = "Vec::is_empty")] pub roles: Vec<String>, } pub struct DtzRequiredRole<const N: &'static str>(pub DtzProfile); #[async_trait] impl<B, const N: &'static str> FromRequest<B> for DtzRequiredRole<N> where B: Send, { type Rejection = (StatusCode, &'static str); async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { let result = get_profile_from_request(req).await; match result { Ok(profile) => { let scope = replace_placeholder(N, &profile); if !profile.roles.contains(&scope) { return Err((StatusCode::FORBIDDEN, "no permission")); } Ok(DtzRequiredRole(profile)) }, Err(e) => Err((StatusCode::UNAUTHORIZED, &e)), } } } pub struct DtzRequiredUser(pub DtzProfile); #[async_trait] impl<B> FromRequest<B> for DtzRequiredUser where B: Send, { type Rejection = (StatusCode, &'static str); async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { let result = get_profile_from_request(req).await; match result { Ok(profile) => Ok(DtzRequiredUser(profile)), Err(e) => Err((StatusCode::UNAUTHORIZED, e)), } } } pub struct DtzOptionalUser(pub Option<DtzProfile>); #[async_trait] impl<B> FromRequest<B> for DtzOptionalUser where B: Send, { type Rejection = (StatusCode, &'static str); async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { let result = get_profile_from_request(req).await; match result { Ok(profile) => Ok(DtzOptionalUser(Some(profile))), Err(_e) => Ok(DtzOptionalUser(None)), } } } async fn get_profile_from_request<B>(req: &mut RequestParts<B>) -> Result<DtzProfile,&'static str> { let headers = req.headers().clone(); let cookie: Option<&HeaderValue> = headers.get("cookie"); let authorization: Option<&HeaderValue> = headers.get("authorization"); let header_api_key: Option<&HeaderValue> = headers.get("x-api-key"); let header_context_id: Option<&HeaderValue> = headers.get("x-dtz-context"); let profile: DtzProfile; if let Some(cookie) = cookie { match verify_token_from_cookie(cookie.clone()) { Ok(p) => { profile = p; }, Err(_) => { return Err("no valid token found in cookie"); } } }else if let Some(authorization) = authorization { match verify_token_from_bearer(authorization.clone()) { Ok(p) => { profile = p; }, Err(_) => { return Err("not authorized"); } } }else if let Some(header_api_key) = header_api_key {
}else { let query = req.uri().query().unwrap_or_default(); let value: GetAuthParams = serde_urlencoded::from_str(query).unwrap(); if value.api_key.is_some() { if value.context_id.is_some() { profile = verifiy_api_key(&value.api_key.unwrap(), Some(&value.context_id.unwrap())).await.unwrap(); }else{ profile = verifiy_api_key(&value.api_key.unwrap(), None).await.unwrap(); } }else{ return Err("no authorization header"); } } Ok(profile) } fn verify_token_from_cookie(cookie: HeaderValue) -> Result<DtzProfile,String> { let cookie_str = cookie.to_str().unwrap(); match Cookie::parse(cookie_str){ Ok(cookie) => { let token = cookie.value().to_string(); verify_token(token) }, Err(_) => Err("no valid token found in cookie".to_string()) } } fn verify_token_from_bearer(bearer: HeaderValue) -> Result<DtzProfile,String> { let bearer_str = bearer.to_str().unwrap(); let jwt = bearer_str.replace("Bearer ",""); verify_token(jwt) } fn verify_token(token: String) -> Result<DtzProfile,String> { if token.as_str().contains('.') { let jwt_parts: Vec<&str> = token.split('.').collect(); let jwt_alg = jwt_parts.get(0).unwrap(); let jwt_payload = jwt_parts.get(1).unwrap(); let jwt_sig = jwt_parts.get(2).unwrap(); let algorithm = PKeyWithDigest { digest: MessageDigest::sha256(), key: PKey::public_key_from_pem(PUBLIC_KEY.as_bytes()).unwrap(), }; match algorithm.verify(jwt_alg, jwt_payload, jwt_sig) { Ok(_) => { let claims = Claims::from_base64(jwt_payload).unwrap(); let roles_claim = claims.private.get("roles").unwrap(); let mut roles: Vec<String> = Vec::new(); let arr = roles_claim.as_array().unwrap(); for role in arr { roles.push(role.as_str().unwrap().to_string()); } let scope_str = claims.private.get("scope").unwrap().as_str().unwrap(); let result = DtzProfile{ identity_id: Uuid::parse_str(&claims.registered.subject.unwrap()).unwrap(), context_id: Uuid::parse_str(scope_str).unwrap(), roles, }; Ok(result) }, Err(_) => { return Err("invalid token".to_string()); } } }else{ Err("not authorized".to_string()) } } #[derive(Serialize, Deserialize, Debug)] struct TokenResponse { access_token: String, scope: Option<String>, token_type: String, expires_in: u32, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct GetAuthParams { api_key: Option<String>, context_id: Option<String>, } static KNOWN_IDENTITIES: Lazy<Mutex<LruCache::<String, DtzProfile>>> = Lazy::new(|| { let time_to_live = std::time::Duration::from_secs(3600); let m = LruCache::<String, DtzProfile>::with_expiry_duration_and_capacity(time_to_live,100); Mutex::new(m) }); async fn verifiy_api_key(api_key: &str, context_id: Option<&str>) -> Result<DtzProfile,String> { let req_data = if context_id.is_some() { format!("{{\"apiKey\":\"{}\",\"contextId\":\"{}\"}}",api_key,context_id.unwrap()) } else { format!("{{\"apiKey\":\"{}\"}}",api_key) }; { let mut x = KNOWN_IDENTITIES.lock().unwrap(); if x.contains_key(&req_data){ let profile = x.get(&req_data).unwrap().clone(); return Ok(profile); } } let hostname = std::env::var("HOSTNAME").unwrap_or("localhost".to_string()); let req = Request::builder() .method(Method::POST) .uri("https://identity.dtz.rocks/api/2021-02-21/auth/apikey") .header("content-type", "application/json") .header("X-DTZ-SOURCE", hostname) .body(Body::from(req_data.clone())).unwrap(); let https = hyper_rustls::HttpsConnectorBuilder::new() .with_native_roots() .https_only() .enable_http1() .build(); let http_client = Client::builder().build(https); let resp = http_client.request(req).await.unwrap(); if resp.status().is_success() { let bytes = body::to_bytes(resp.into_body()).await.unwrap(); let resp_str = String::from_utf8(bytes.to_vec()).expect("response was not valid utf-8"); let token_response: TokenResponse = serde_json::from_str(&resp_str).unwrap(); let jwt = token_response.access_token; let result = verify_token(jwt); { if result.is_ok() { let mut x = KNOWN_IDENTITIES.lock().unwrap(); x.insert(req_data,result.clone().unwrap()); } } result }else{ Err("not authorized".to_string()) } } fn replace_placeholder(template: &str, profile: &DtzProfile) -> String { let mut result = template.to_string(); result = result.replace("{identity_id}", &profile.identity_id.to_string()); result = result.replace("{context_id}", &profile.context_id.to_string()); result = result.replace("{roles}", &profile.roles.join(",")); result } pub fn verify_role(profile: &DtzProfile, role: &str) -> bool { profile.roles.contains(&role.to_string()) } pub fn verfify_context_role(profile: &DtzProfile, role: &str) -> bool { let replaced_role = replace_placeholder(role, profile); profile.roles.contains(&replaced_role.to_string()) } #[cfg(test)] mod tests { use uuid::Uuid; use super::*; #[test] fn test_replacement_identity() { let identity = DtzProfile{ identity_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), context_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), roles: vec!["admin".to_string()], }; let result = super::replace_placeholder("https://dtz.rocks/context/admin/{identity_id}", &identity); assert_eq!(result, "https://dtz.rocks/context/admin/00000000-0000-0000-0000-000000000000"); } #[test] fn test_replacement_context() { let identity = DtzProfile{ identity_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), context_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), roles: vec!["admin".to_string()], }; let result = super::replace_placeholder("https://dtz.rocks/context/admin/{context_id}", &identity); assert_eq!(result, "https://dtz.rocks/context/admin/00000000-0000-0000-0000-000000000000"); } #[test] fn test_replacement_nothing() { let identity = DtzProfile{ identity_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), context_id: Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(), roles: vec!["admin".to_string()], }; let result = super::replace_placeholder("https://dtz.rocks/context/admin", &identity); assert_eq!(result, "https://dtz.rocks/context/admin"); } }
if header_context_id.is_some() { profile = verifiy_api_key(header_api_key.to_str().unwrap(), Some(header_context_id.unwrap().to_str().unwrap())).await.unwrap(); }else{ profile = verifiy_api_key(header_api_key.to_str().unwrap(), None).await.unwrap(); }
if_condition
[ { "content": "# 0.4.10 2022-04-30\n\n\n\n* fix unparsable cookie\n\n\n\n# 0.4.9 2022-04-20\n\n\n\n* fail on invalid jwts\n\n\n\n# 0.4.8 2022-04-17\n\n\n\n* add verify_role functions\n\n\n\n# 0.4.7 2022-03-11\n\n\n\n* support foreign cookies\n\n\n\n# 0.4.6 2022-03-11\n\n\n\n* update deps\n\n\n\n# 0.4.4 2022-03-1...
Rust
examples/capture-test.rs
petrosagg/differential-dataflow
2e38abbb62aedf02cb9b6b5debb73c29b6e97dbb
extern crate rand; extern crate timely; extern crate differential_dataflow; extern crate serde; extern crate rdkafka; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::lattice::Lattice; type Node = u32; type Edge = (Node, Node); fn main() { let nodes: u32 = std::env::args().nth(1).unwrap().parse().unwrap(); let edges: u32 = std::env::args().nth(2).unwrap().parse().unwrap(); let batch: u32 = std::env::args().nth(3).unwrap().parse().unwrap(); let topic = std::env::args().nth(4).unwrap(); let write = std::env::args().any(|x| x == "write"); let read = std::env::args().any(|x| x == "read"); timely::execute_from_args(std::env::args(), move |worker| { let timer = ::std::time::Instant::now(); let mut probe = Handle::new(); let (mut roots, mut graph, _write_token, _read_token) = worker.dataflow(|scope| { let (root_input, roots) = scope.new_collection(); let (edge_input, graph) = scope.new_collection(); let result = bfs(&graph, &roots); let result = result.map(|(_,l)| l) .consolidate() .probe_with(&mut probe); let write_token = if write { Some(kafka::create_sink(&result.inner, "localhost:9092", &topic)) } else { None }; let read_token = if read { let (read_token, stream) = kafka::create_source(result.scope(), "localhost:9092", &topic, "group"); use differential_dataflow::AsCollection; stream .as_collection() .negate() .concat(&result) .consolidate() .inspect(|x| println!("In error: {:?}", x)) .probe_with(&mut probe) .assert_empty() ; Some(read_token) } else { None }; (root_input, edge_input, write_token, read_token) }); let seed: &[_] = &[1, 2, 3, 4]; let mut rng1: StdRng = SeedableRng::from_seed(seed); let mut rng2: StdRng = SeedableRng::from_seed(seed); roots.insert(0); roots.close(); println!("performing BFS on {} nodes, {} edges:", nodes, edges); if worker.index() == 0 { for _ in 0 .. edges { graph.insert((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes))); } } println!("{:?}\tloaded", timer.elapsed()); graph.advance_to(1); graph.flush(); worker.step_while(|| probe.less_than(graph.time())); println!("{:?}\tstable", timer.elapsed()); for round in 0 .. { if write { std::thread::sleep(std::time::Duration::from_millis(100)); } for element in 0 .. batch { if worker.index() == 0 { graph.insert((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes))); graph.remove((rng2.gen_range(0, nodes), rng2.gen_range(0, nodes))); } graph.advance_to(2 + round * batch + element); } graph.flush(); let timer2 = ::std::time::Instant::now(); worker.step_while(|| probe.less_than(&graph.time())); if worker.index() == 0 { let elapsed = timer2.elapsed(); println!("{:?}\t{:?}:\t{}", timer.elapsed(), round, elapsed.as_secs() * 1000000000 + (elapsed.subsec_nanos() as u64)); } } println!("finished; elapsed: {:?}", timer.elapsed()); }).unwrap(); } fn bfs<G: Scope>(edges: &Collection<G, Edge>, roots: &Collection<G, Node>) -> Collection<G, (Node, u32)> where G::Timestamp: Lattice+Ord { let nodes = roots.map(|x| (x, 0)); nodes.iterate(|inner| { let edges = edges.enter(&inner.scope()); let nodes = nodes.enter(&inner.scope()); inner.join_map(&edges, |_k,l,d| (*d, l+1)) .concat(&nodes) .reduce(|_, s, t| t.push((*s[0].0, 1))) }) } pub mod kafka { use serde::{Serialize, Deserialize}; use timely::scheduling::SyncActivator; use rdkafka::{ClientContext, config::ClientConfig}; use rdkafka::consumer::{BaseConsumer, ConsumerContext}; use rdkafka::error::{KafkaError, RDKafkaError}; use differential_dataflow::capture::Writer; use std::hash::Hash; use timely::progress::Timestamp; use timely::dataflow::{Scope, Stream}; use differential_dataflow::ExchangeData; use differential_dataflow::lattice::Lattice; pub fn create_source<G, D, T, R>(scope: G, addr: &str, topic: &str, group: &str) -> (Box<dyn std::any::Any>, Stream<G, (D, T, R)>) where G: Scope<Timestamp = T>, D: ExchangeData + Hash + for<'a> serde::Deserialize<'a>, T: ExchangeData + Hash + for<'a> serde::Deserialize<'a> + Timestamp + Lattice, R: ExchangeData + Hash + for<'a> serde::Deserialize<'a>, { differential_dataflow::capture::source::build(scope, |activator| { let source = KafkaSource::new(addr, topic, group, activator); differential_dataflow::capture::YieldingIter::new_from(Iter::<D,T,R>::new_from(source), std::time::Duration::from_millis(10)) }) } pub fn create_sink<G, D, T, R>(stream: &Stream<G, (D, T, R)>, addr: &str, topic: &str) -> Box<dyn std::any::Any> where G: Scope<Timestamp = T>, D: ExchangeData + Hash + Serialize + for<'a> Deserialize<'a>, T: ExchangeData + Hash + Serialize + for<'a> Deserialize<'a> + Timestamp + Lattice, R: ExchangeData + Hash + Serialize + for<'a> Deserialize<'a>, { use std::rc::Rc; use std::cell::RefCell; use differential_dataflow::hashable::Hashable; let sink = KafkaSink::new(addr, topic); let result = Rc::new(RefCell::new(sink)); let sink_hash = (addr.to_string(), topic.to_string()).hashed(); differential_dataflow::capture::sink::build( &stream, sink_hash, Rc::downgrade(&result), Rc::downgrade(&result), ); Box::new(result) } pub struct KafkaSource { consumer: BaseConsumer<ActivationConsumerContext>, } impl KafkaSource { pub fn new(addr: &str, topic: &str, group: &str, activator: SyncActivator) -> Self { let mut kafka_config = ClientConfig::new(); kafka_config.set("bootstrap.servers", &addr.to_string()); kafka_config .set("enable.auto.commit", "false") .set("auto.offset.reset", "earliest"); kafka_config.set("topic.metadata.refresh.interval.ms", "30000"); kafka_config.set("fetch.message.max.bytes", "134217728"); kafka_config.set("group.id", group); kafka_config.set("isolation.level", "read_committed"); let activator = ActivationConsumerContext(activator); let consumer = kafka_config.create_with_context::<_, BaseConsumer<_>>(activator).unwrap(); use rdkafka::consumer::Consumer; consumer.subscribe(&[topic]).unwrap(); Self { consumer, } } } pub struct Iter<D, T, R> { pub source: KafkaSource, phantom: std::marker::PhantomData<(D, T, R)>, } impl<D, T, R> Iter<D, T, R> { pub fn new_from(source: KafkaSource) -> Self { Self { source, phantom: std::marker::PhantomData, } } } impl<D, T, R> Iterator for Iter<D, T, R> where D: for<'a>Deserialize<'a>, T: for<'a>Deserialize<'a>, R: for<'a>Deserialize<'a>, { type Item = differential_dataflow::capture::Message<D, T, R>; fn next(&mut self) -> Option<Self::Item> { use rdkafka::message::Message; self.source .consumer .poll(std::time::Duration::from_millis(0)) .and_then(|result| result.ok()) .and_then(|message| { message.payload().and_then(|message| bincode::deserialize::<differential_dataflow::capture::Message<D, T, R>>(message).ok()) }) } } struct ActivationConsumerContext(SyncActivator); impl ClientContext for ActivationConsumerContext { } impl ActivationConsumerContext { fn activate(&self) { self.0.activate().unwrap(); } } impl ConsumerContext for ActivationConsumerContext { fn message_queue_nonempty_callback(&self) { self.activate(); } } use std::time::Duration; use rdkafka::producer::DefaultProducerContext; use rdkafka::producer::{BaseRecord, ThreadedProducer}; pub struct KafkaSink { topic: String, producer: ThreadedProducer<DefaultProducerContext>, buffer: Vec<u8>, } impl KafkaSink { pub fn new(addr: &str, topic: &str) -> Self { let mut config = ClientConfig::new(); config.set("bootstrap.servers", &addr); config.set("queue.buffering.max.kbytes", &format!("{}", 16 << 20)); config.set("queue.buffering.max.messages", &format!("{}", 10_000_000)); config.set("queue.buffering.max.ms", &format!("{}", 10)); let producer = config .create_with_context::<_, ThreadedProducer<_>>(DefaultProducerContext) .expect("creating kafka producer for kafka sinks failed"); Self { producer, topic: topic.to_string(), buffer: Vec::new(), } } } impl<T: Serialize> Writer<T> for KafkaSink { fn poll(&mut self, item: &T) -> Option<Duration> { self.buffer.clear(); bincode::serialize_into(&mut self.buffer, item).expect("Writing to a `Vec<u8>` cannot fail"); let record = BaseRecord::<[u8], _>::to(&self.topic).payload(&self.buffer); self.producer.send(record).err().map(|(e, _)| { if let KafkaError::MessageProduction(RDKafkaError::QueueFull) = e { Duration::from_secs(1) } else { Duration::from_secs(1) } }) } fn done(&self) -> bool { self.producer.in_flight_count() == 0 } } }
extern crate rand; extern crate timely; extern crate differential_dataflow; extern crate serde; extern crate rdkafka; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::lattice::Lattice; type Node = u32; type Edge = (Node, Node); fn main() { let nodes: u32 = std::env::args().nth(1).unwrap().parse().unwrap(); let edges: u32 = std::env::args().nth(2).unwrap().parse().unwrap(); let batch: u32 = std::env::args().nth(3).unwrap().parse().unwrap(); let topic = std::env::args().nth(4).unwrap(); let write = std::env::args().any(|x| x == "write"); let read = std::env::args().any(|x| x == "read"); timely::execute_from_args(std::env::args(), move |worker| { let timer = ::std::time::Instant::now(); let mut probe = Handle::new(); let (mut roots, mut graph, _write_token, _read_token) = worker.dataflow(|scope| { let (root_input, roots) = scope.new_collection(); let (edge_input, graph) = scope.new_collection(); let result = bfs(&graph, &roots); let result = result.map(|(_,l)| l) .consolidate() .probe_with(&mut probe); let write_token = if write { Some(kafka::create_sink(&result.inner, "localhost:9092", &topic)) } else { None }; let read_token = if read { let (read_token, stream) = kafka::create_source(result.scope(), "localhost:9092", &topic, "group"); use differential_dataflow::AsCollection; stream .as_collection() .negate() .concat(&result) .consolidate() .inspect(|x| println!("In error: {:?}", x)) .probe_with(&mut probe) .assert_empty() ; Some(read_token) } else { None }; (root_input, edge_input, write_token, read_token) }); let seed: &[_] = &[1, 2, 3, 4]; let mut rng1: StdRng = SeedableRng::from_seed(seed); let mut rng2: StdRng = SeedableRng::from_seed(seed); roots.insert(0); roots.close(); println!("performing BFS on {} nodes, {} edges:", nodes, edges); if worker.index() == 0 { for _ in 0 .. edges { graph.insert((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes))); } } println!("{:?}\tloaded", timer.elapsed()); graph.advance_to(1); graph.flush(); worker.step_while(|| probe.less_than(graph.time())); println!("{:?}\tstable", timer.elapsed()); for round in 0 .. { if write { std::thread::sleep(std::time::Duration::from_millis(100)); } for element in 0 .. batch { if worker.index() == 0 { graph.insert((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes))); graph.remove((rng2.gen_range(0, nodes), rng2.gen_range(0, nodes))); } graph.advance_to(2 + round * batch + element); } graph.flush(); let timer2 = ::std::time::Instant::now(); worker.step_while(|| probe.less_than(&graph.time())); if worker.index() == 0 { let elapsed = timer2.elapsed(); println!("{:?}\t{:?}:\t{}", timer.elapsed(), round, elapsed.as_secs() * 1000000000 + (elapsed.subsec_nanos() as u64)); } } println!("finished; elapsed: {:?}", timer.elapsed()); }).unwrap(); } fn bfs<G: Scope>(edges: &Collection<G, Edge>, roots: &Collection<G, Nod
pub mod kafka { use serde::{Serialize, Deserialize}; use timely::scheduling::SyncActivator; use rdkafka::{ClientContext, config::ClientConfig}; use rdkafka::consumer::{BaseConsumer, ConsumerContext}; use rdkafka::error::{KafkaError, RDKafkaError}; use differential_dataflow::capture::Writer; use std::hash::Hash; use timely::progress::Timestamp; use timely::dataflow::{Scope, Stream}; use differential_dataflow::ExchangeData; use differential_dataflow::lattice::Lattice; pub fn create_source<G, D, T, R>(scope: G, addr: &str, topic: &str, group: &str) -> (Box<dyn std::any::Any>, Stream<G, (D, T, R)>) where G: Scope<Timestamp = T>, D: ExchangeData + Hash + for<'a> serde::Deserialize<'a>, T: ExchangeData + Hash + for<'a> serde::Deserialize<'a> + Timestamp + Lattice, R: ExchangeData + Hash + for<'a> serde::Deserialize<'a>, { differential_dataflow::capture::source::build(scope, |activator| { let source = KafkaSource::new(addr, topic, group, activator); differential_dataflow::capture::YieldingIter::new_from(Iter::<D,T,R>::new_from(source), std::time::Duration::from_millis(10)) }) } pub fn create_sink<G, D, T, R>(stream: &Stream<G, (D, T, R)>, addr: &str, topic: &str) -> Box<dyn std::any::Any> where G: Scope<Timestamp = T>, D: ExchangeData + Hash + Serialize + for<'a> Deserialize<'a>, T: ExchangeData + Hash + Serialize + for<'a> Deserialize<'a> + Timestamp + Lattice, R: ExchangeData + Hash + Serialize + for<'a> Deserialize<'a>, { use std::rc::Rc; use std::cell::RefCell; use differential_dataflow::hashable::Hashable; let sink = KafkaSink::new(addr, topic); let result = Rc::new(RefCell::new(sink)); let sink_hash = (addr.to_string(), topic.to_string()).hashed(); differential_dataflow::capture::sink::build( &stream, sink_hash, Rc::downgrade(&result), Rc::downgrade(&result), ); Box::new(result) } pub struct KafkaSource { consumer: BaseConsumer<ActivationConsumerContext>, } impl KafkaSource { pub fn new(addr: &str, topic: &str, group: &str, activator: SyncActivator) -> Self { let mut kafka_config = ClientConfig::new(); kafka_config.set("bootstrap.servers", &addr.to_string()); kafka_config .set("enable.auto.commit", "false") .set("auto.offset.reset", "earliest"); kafka_config.set("topic.metadata.refresh.interval.ms", "30000"); kafka_config.set("fetch.message.max.bytes", "134217728"); kafka_config.set("group.id", group); kafka_config.set("isolation.level", "read_committed"); let activator = ActivationConsumerContext(activator); let consumer = kafka_config.create_with_context::<_, BaseConsumer<_>>(activator).unwrap(); use rdkafka::consumer::Consumer; consumer.subscribe(&[topic]).unwrap(); Self { consumer, } } } pub struct Iter<D, T, R> { pub source: KafkaSource, phantom: std::marker::PhantomData<(D, T, R)>, } impl<D, T, R> Iter<D, T, R> { pub fn new_from(source: KafkaSource) -> Self { Self { source, phantom: std::marker::PhantomData, } } } impl<D, T, R> Iterator for Iter<D, T, R> where D: for<'a>Deserialize<'a>, T: for<'a>Deserialize<'a>, R: for<'a>Deserialize<'a>, { type Item = differential_dataflow::capture::Message<D, T, R>; fn next(&mut self) -> Option<Self::Item> { use rdkafka::message::Message; self.source .consumer .poll(std::time::Duration::from_millis(0)) .and_then(|result| result.ok()) .and_then(|message| { message.payload().and_then(|message| bincode::deserialize::<differential_dataflow::capture::Message<D, T, R>>(message).ok()) }) } } struct ActivationConsumerContext(SyncActivator); impl ClientContext for ActivationConsumerContext { } impl ActivationConsumerContext { fn activate(&self) { self.0.activate().unwrap(); } } impl ConsumerContext for ActivationConsumerContext { fn message_queue_nonempty_callback(&self) { self.activate(); } } use std::time::Duration; use rdkafka::producer::DefaultProducerContext; use rdkafka::producer::{BaseRecord, ThreadedProducer}; pub struct KafkaSink { topic: String, producer: ThreadedProducer<DefaultProducerContext>, buffer: Vec<u8>, } impl KafkaSink { pub fn new(addr: &str, topic: &str) -> Self { let mut config = ClientConfig::new(); config.set("bootstrap.servers", &addr); config.set("queue.buffering.max.kbytes", &format!("{}", 16 << 20)); config.set("queue.buffering.max.messages", &format!("{}", 10_000_000)); config.set("queue.buffering.max.ms", &format!("{}", 10)); let producer = config .create_with_context::<_, ThreadedProducer<_>>(DefaultProducerContext) .expect("creating kafka producer for kafka sinks failed"); Self { producer, topic: topic.to_string(), buffer: Vec::new(), } } } impl<T: Serialize> Writer<T> for KafkaSink { fn poll(&mut self, item: &T) -> Option<Duration> { self.buffer.clear(); bincode::serialize_into(&mut self.buffer, item).expect("Writing to a `Vec<u8>` cannot fail"); let record = BaseRecord::<[u8], _>::to(&self.topic).payload(&self.buffer); self.producer.send(record).err().map(|(e, _)| { if let KafkaError::MessageProduction(RDKafkaError::QueueFull) = e { Duration::from_secs(1) } else { Duration::from_secs(1) } }) } fn done(&self) -> bool { self.producer.in_flight_count() == 0 } } }
e>) -> Collection<G, (Node, u32)> where G::Timestamp: Lattice+Ord { let nodes = roots.map(|x| (x, 0)); nodes.iterate(|inner| { let edges = edges.enter(&inner.scope()); let nodes = nodes.enter(&inner.scope()); inner.join_map(&edges, |_k,l,d| (*d, l+1)) .concat(&nodes) .reduce(|_, s, t| t.push((*s[0].0, 1))) }) }
function_block-function_prefixed
[ { "content": "// Type aliases for differential execution.\n\ntype Time = u32;\n", "file_path": "doop/src/main.rs", "rank": 0, "score": 294510.99856603285 }, { "content": "type Node = u32;\n\n\n", "file_path": "src/trace/implementations/graph.rs", "rank": 1, "score": 289060.656315...
Rust
src/lib.rs
incident-recipient/gherkin-rust
7668c349ced30d5332821538ce321737cdbbacec
mod parser; pub mod tagexpr; pub use peg::error::ParseError; pub use peg::str::LineCol; use typed_builder::TypedBuilder; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Background { pub steps: Vec<Step>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Examples { pub table: Table, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Feature { pub name: String, #[builder(default)] pub description: Option<String>, #[builder(default)] pub background: Option<Background>, #[builder(default)] pub scenarios: Vec<Scenario>, #[builder(default)] pub rules: Vec<Rule>, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), #[builder(default)] pub path: Option<PathBuf>, } impl PartialOrd for Feature { fn partial_cmp(&self, other: &Feature) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for Feature { fn cmp(&self, other: &Feature) -> std::cmp::Ordering { self.name.cmp(&other.name) } } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Rule { pub name: String, #[builder(default)] pub background: Option<Background>, pub scenarios: Vec<Scenario>, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Scenario { pub name: String, pub steps: Vec<Step>, #[builder(default)] pub examples: Option<Examples>, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Step { pub ty: StepType, pub raw_type: String, pub value: String, #[builder(default)] pub docstring: Option<String>, #[builder(default)] pub table: Option<Table>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, Copy, PartialEq, Hash, Eq)] pub enum StepType { Given, When, Then, } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Table { pub rows: Vec<Vec<String>>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } impl Table { pub fn row_width(&self) -> usize { self.rows .iter() .next() .map(|x| x.len()) .unwrap_or_else(|| 0) } } #[derive(Debug, thiserror::Error)] pub enum ParseFileError { #[error("Could not read path: {0}")] Reading(PathBuf, #[source] std::io::Error), #[error("Could not parse feature file: {0}")] Parsing( PathBuf, #[source] peg::error::ParseError<peg::str::LineCol>, ), } impl Feature { #[inline] pub fn parse_path<P: AsRef<Path>>(path: P) -> Result<Feature, ParseFileError> { let s = std::fs::read_to_string(path.as_ref()) .map_err(|e| ParseFileError::Reading(path.as_ref().to_path_buf(), e))?; let mut feature = parser::gherkin_parser::feature(&s, &Default::default()) .map_err(|e| ParseFileError::Parsing(path.as_ref().to_path_buf(), e))?; feature.path = Some(path.as_ref().to_path_buf()); Ok(feature) } #[inline] pub fn parse<S: AsRef<str>>(input: S) -> Result<Feature, ParseError<LineCol>> { parser::gherkin_parser::feature(input.as_ref(), &Default::default()) } } impl Step { pub fn docstring(&self) -> Option<&String> { match &self.docstring { Some(v) => Some(&v), None => None, } } pub fn table(&self) -> Option<&Table> { match &self.table { Some(v) => Some(&v), None => None, } } } impl std::fmt::Display for Step { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {}", &self.raw_type, &self.value) } }
mod parser; pub mod tagexpr; pub use peg::error::ParseError; pub use peg::str::LineCol; use typed_builder::TypedBuilder; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, TypedBuilder, P
e { Some(v) => Some(&v), None => None, } } } impl std::fmt::Display for Step { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {}", &self.raw_type, &self.value) } }
artialEq, Hash, Eq)] pub struct Background { pub steps: Vec<Step>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Examples { pub table: Table, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Feature { pub name: String, #[builder(default)] pub description: Option<String>, #[builder(default)] pub background: Option<Background>, #[builder(default)] pub scenarios: Vec<Scenario>, #[builder(default)] pub rules: Vec<Rule>, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), #[builder(default)] pub path: Option<PathBuf>, } impl PartialOrd for Feature { fn partial_cmp(&self, other: &Feature) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for Feature { fn cmp(&self, other: &Feature) -> std::cmp::Ordering { self.name.cmp(&other.name) } } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Rule { pub name: String, #[builder(default)] pub background: Option<Background>, pub scenarios: Vec<Scenario>, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Scenario { pub name: String, pub steps: Vec<Step>, #[builder(default)] pub examples: Option<Examples>, #[builder(default)] pub tags: Vec<String>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Step { pub ty: StepType, pub raw_type: String, pub value: String, #[builder(default)] pub docstring: Option<String>, #[builder(default)] pub table: Option<Table>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, Copy, PartialEq, Hash, Eq)] pub enum StepType { Given, When, Then, } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Table { pub rows: Vec<Vec<String>>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } impl Table { pub fn row_width(&self) -> usize { self.rows .iter() .next() .map(|x| x.len()) .unwrap_or_else(|| 0) } } #[derive(Debug, thiserror::Error)] pub enum ParseFileError { #[error("Could not read path: {0}")] Reading(PathBuf, #[source] std::io::Error), #[error("Could not parse feature file: {0}")] Parsing( PathBuf, #[source] peg::error::ParseError<peg::str::LineCol>, ), } impl Feature { #[inline] pub fn parse_path<P: AsRef<Path>>(path: P) -> Result<Feature, ParseFileError> { let s = std::fs::read_to_string(path.as_ref()) .map_err(|e| ParseFileError::Reading(path.as_ref().to_path_buf(), e))?; let mut feature = parser::gherkin_parser::feature(&s, &Default::default()) .map_err(|e| ParseFileError::Parsing(path.as_ref().to_path_buf(), e))?; feature.path = Some(path.as_ref().to_path_buf()); Ok(feature) } #[inline] pub fn parse<S: AsRef<str>>(input: S) -> Result<Feature, ParseError<LineCol>> { parser::gherkin_parser::feature(input.as_ref(), &Default::default()) } } impl Step { pub fn docstring(&self) -> Option<&String> { match &self.docstring { Some(v) => Some(&v), None => None, } } pub fn table(&self) -> Option<&Table> { match &self.tabl
random
[ { "content": "//! let op: TagOperation = \"@a and @b\".parse()?;\n\n//! # Ok(())\n\n//! # }\n\n//! ```\n\n\n\nuse std::str::FromStr;\n\n\n\nimpl FromStr for TagOperation {\n\n type Err = peg::error::ParseError<peg::str::LineCol>;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n crate::...