text
stringlengths
8
4.13M
fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn fanc(n: u64) -> u64 { if n == 0 { 1 } else { (n * fanc(n - 1)) % 1000000007 } } fn main() { let n: u64 = read(); println!("{}", fanc(n)); }
// This is the main algorithm. // // It loops over the current state of the sandpile and updates it on-the-fly. fn advance(field: &mut Vec<Vec<usize>>, boundary: &mut [usize; 4]) -> bool { // This variable is used to check whether we changed anything in the array. If no, the loop terminates. let mut done = false; for y in boundary[0]..boundary[2] { for x in boundary[1]..boundary[3] { if field[y][x] >= 4 { // This part was heavily inspired by the Pascal version. We subtract 4 as many times as we can // and distribute it to the neighbors. Also, in case we have outgrown the current boundary, we // update it to once again contain the entire sandpile. // The amount that gets added to the neighbors is the amount here divided by four and (implicitly) floored. // The remaining sand is just current modulo 4. let rem: usize = field[y][x] / 4; field[y][x] %= 4; // The isize casts are necessary because usize can not go below 0. // Also, the reason why x and y are compared to boundary[2]-1 and boundary[3]-1 is because for loops in // Rust are upper bound exclusive. This means a loop like 0..5 will only go over 0,1,2,3 and 4. if y as isize - 1 >= 0 {field[y-1][x] += rem; if y == boundary[0] {boundary[0]-=1;}} if x as isize - 1 >= 0 {field[y][x-1] += rem; if x == boundary[1] {boundary[1]-=1;}} if y+1 < field.len() {field[y+1][x] += rem; if x == boundary[2]-1 {boundary[2]+=1;}} if x+1 < field.len() {field[y][x+1] += rem; if y == boundary[3]-1 {boundary[3]+=1;}} done = true; } } } done } // This function can be used to display the sandpile in the console window. // // Each row is mapped onto chars and those characters are then collected into a string. // These are then printed to the console. // // Eg.: [0,1,1,2,3,0] -> [' ','░','░','▒','▓',' ']-> " ░░▒▓ " fn display(field: &Vec<Vec<usize>>) { for row in field { let char_row = { row.iter().map(|c| {match c { 0 => ' ', 1 => '░', 2 => '▒', 3 => '▓', _ => '█' }}).collect::<String>() }; println!("{}", char_row); } } // This function writes the end result to a file called "output.ppm". // // PPM is a very simple image format, however, it entirely uncompressed which leads to huge image sizes. // Even so, for demonstrative purposes it's perfectly good to use. For something more robust, look into PNG libraries. // // Read more about the format here: http://netpbm.sourceforge.net/doc/ppm.html fn write_pile(pile: &Vec<Vec<usize>>) { use std::fs::File; use std::io::Write; // We first create the file (or erase its contents if it already existed). let mut file = File::create("./output.ppm").unwrap(); // Then we add the image signature, which is "P3 <newline>[width of image] [height of image]<newline>[maximum value of color]<newline>". write!(file, "P3\n{} {}\n255\n", pile.len(), pile.len()).unwrap(); for row in pile { // For each row, we create a new string which has more or less enough capacity to hold the entire row. // This is for performance purposes, but shouldn't really matter much. let mut line = String::with_capacity(row.len() * 14); // We map each value in the field to a color. // These are just simple RGB values, 0 being the background, the rest being the "sand" itself. for elem in row { line.push_str(match elem { 0 => "100 40 15 ", 1 => "117 87 30 ", 2 => "181 134 47 ", 3 => "245 182 66 ", _ => unreachable!(), }); } // Finally we write this string into the file. write!(file, "{}\n", line).unwrap(); } } fn main() { // This is how big the final image will be. Currently the end result would be a 16x16 picture. let field_size = 16; let mut playfield = vec![vec![0; field_size]; field_size]; // We put the initial sand in the exact middle of the field. // This isn't necessary per se, but it ensures that sand can fully topple. // // The boundary is initially just the single tile which has the sand in it, however, as the algorithm // progresses, this will grow larger too. let mut boundary = [field_size/2-1, field_size/2-1, field_size/2, field_size/2]; playfield[field_size/2 - 1][field_size/2 - 1] = 16; // This is the main loop. We update the field until it returns false, signalling that the pile reached its // final state. while advance(&mut playfield, &mut boundary) {}; // Once this happens, we simply display the result. Uncomment the line below to write it to a file. // Calling display with large field sizes is not recommended as it can easily become too large for the console. display(&playfield); //write_pile(&playfield); }
#![allow(deprecated, clippy::panic, clippy::unwrap_used)] use std::collections::{BTreeSet, HashMap}; use async_std::test; use expect_test::expect; use lspower::{lsp, LanguageServer}; use serde_json::json; use super::*; /// Finds a `// ^` comment in `source` and returns the `lsp::Position` that the comment points /// at fn position_of(source: &str) -> lsp::Position { source .lines() .enumerate() .find_map(|(line, line_str)| { line_str.find("// ^").map(|j| lsp::Position { // The marker is on the line after the position we indicate line: line as u32 - 1, character: (line_str[..j].chars().count() + "// ^".len()) as u32, }) }) .unwrap_or_else(|| { panic!( "Could not find the position marker `// ^` in `{}`", source ) }) } fn create_server() -> LspServer { let _ = env_logger::try_init(); LspServer::new(None) } async fn open_file( server: &LspServer, text: String, filename: Option<&str>, ) { let name = match filename { Some(name) => name, None => "file:///home/user/file.flux", }; let params = lsp::DidOpenTextDocumentParams { text_document: lsp::TextDocumentItem::new( lsp::Url::parse(name).unwrap(), "flux".to_string(), 1, text, ), }; server.did_open(params).await; } #[test] async fn test_initialized() { let server = create_server(); let params = lsp::InitializeParams { capabilities: lsp::ClientCapabilities { workspace: None, text_document: None, window: None, general: None, experimental: None, }, client_info: None, initialization_options: None, locale: None, process_id: None, root_path: None, root_uri: None, trace: None, workspace_folders: None, }; let result = server.initialize(params).await.unwrap(); let server_info = result.server_info.unwrap(); assert_eq!(server_info.name, "flux-lsp".to_string()); assert_eq!( server_info.version, Some(env!("CARGO_PKG_VERSION").into()) ); } #[test] async fn test_shutdown() { let server = create_server(); server.shutdown().await.unwrap(); } #[test] async fn test_did_open() { let server = create_server(); let params = lsp::DidOpenTextDocumentParams { text_document: lsp::TextDocumentItem::new( lsp::Url::parse("file:///home/user/file.flux").unwrap(), "flux".to_string(), 1, "from(".to_string(), ), }; server.did_open(params).await; let uri = lsp::Url::parse("file:///home/user/file.flux").unwrap(); let contents = server.store.get(&uri).unwrap(); assert_eq!("from(", contents); } #[test] async fn test_did_change() { let server = create_server(); open_file( &server, r#"from(bucket: "bucket") |> first()"#.to_string(), None, ) .await; let params = lsp::DidChangeTextDocumentParams { text_document: lsp::VersionedTextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), version: -2, }, content_changes: vec![lsp::TextDocumentContentChangeEvent { range: None, range_length: None, text: r#"from(bucket: "bucket")"#.to_string(), }], }; server.did_change(params).await; let uri = lsp::Url::parse("file:///home/user/file.flux").unwrap(); let contents = server.store.get(&uri).unwrap(); assert_eq!(r#"from(bucket: "bucket")"#, contents); } /// When a `textDocument/didChange` presents a file change for a file /// using composition, the updated file gets saved on the stateful composition. #[test] async fn test_did_change_updates_composition_file() { let server = create_server(); open_file(&server, "".to_string(), None).await; let uri = lsp::Url::parse("file:///home/user/file.flux").unwrap(); match server.state.lock() { Ok(mut state) => { let ast = flux::parser::parse_string("".to_string(), ""); let composition = composition::Composition::new( ast, "bucket".to_string(), Some("myMeasurement".to_string()), vec![], vec![], ); state.set_composition(uri.clone(), composition); let composition_state = state.get_mut_composition(&uri); assert!(composition_state.is_some()); assert_eq!( composition_state.unwrap().to_string(), r#"from(bucket: "bucket") |> range(start: v.timeRangeStart, stop: v.timeRangeStop) |> filter(fn: (r) => r._measurement == "myMeasurement") "# .to_string(), ); } Err(err) => panic!("{}", err), } let changed_text = r#"from(bucket: "bucket") |> range(start: -30m) |> filter(fn: (r) => r._measurement == "myMeasurement") |> first() "# .to_string(); let params = lsp::DidChangeTextDocumentParams { text_document: lsp::VersionedTextDocumentIdentifier { uri: uri.clone(), version: -2, }, content_changes: vec![lsp::TextDocumentContentChangeEvent { range: None, range_length: None, text: changed_text.clone(), }], }; server.did_change(params).await; match server.state.lock() { Ok(mut state) => { assert!(state.get_mut_composition(&uri).is_some()); assert_eq!( state.get_mut_composition(&uri).unwrap().to_string(), changed_text, ); } Err(err) => panic!("{}", err), }; } /// When a `textDocument/didChange` presents a file change for a file /// using composition, and that file makes an ambiguous composition, the /// composition is vacated from the server state. #[test] async fn test_did_change_vacates_composition() { let server = create_server(); open_file( &server, r#"from(bucket: "bucket") |> first()"#.to_string(), None, ) .await; match server.state.lock() { Ok(mut state) => { let ast = flux::parser::parse_string( "".to_string(), &r#"from(bucket: "bucket") |> first()"#, ); let composition = composition::Composition::new( ast, "bucket".to_string(), None, vec![], vec![], ); state.set_composition( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), composition, ); } Err(err) => panic!("{}", err), } let params = lsp::DidChangeTextDocumentParams { text_document: lsp::VersionedTextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), version: -2, }, content_changes: vec![lsp::TextDocumentContentChangeEvent { range: None, range_length: None, text: r#"from(bucket: "bucket") from(bucket: "bucket") |> range(start: -12m) "# .to_string(), }], }; server.did_change(params).await; match server.state.lock() { Ok(mut state) => { let key = lsp::Url::parse("file:///home/user/file.flux") .unwrap(); assert!(state.get_mut_composition(&key).is_none()) } Err(err) => panic!("{}", err), }; } /// When the user is mid-change, and the script isn't a parseable /// AST, don't try to modify the composition state at all. #[test] async fn test_did_change_bad_ast_doesnt_vacate_composition() { let server = create_server(); open_file( &server, r#"from(bucket: "bucket") |> first()"#.to_string(), None, ) .await; match server.state.lock() { Ok(mut state) => { let ast = flux::parser::parse_string( "".to_string(), &r#"from(bucket: "bucket") |> first()"#, ); let composition = composition::Composition::new( ast, "bucket".to_string(), None, vec![], vec![], ); state.set_composition( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), composition, ); } Err(err) => panic!("{}", err), } let params = lsp::DidChangeTextDocumentParams { text_document: lsp::VersionedTextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), version: -2, }, content_changes: vec![lsp::TextDocumentContentChangeEvent { range: None, range_length: None, text: r#"from(bucket: "bucket") from(bucket: "bucket") |> range(start: "# .to_string(), }], }; server.did_change(params).await; match server.state.lock() { Ok(mut state) => { let key = lsp::Url::parse("file:///home/user/file.flux") .unwrap(); assert!(state.get_mut_composition(&key).is_some()) } Err(err) => panic!("{}", err), }; } #[test] async fn test_did_change_multiple() { let server = create_server(); open_file( &server, r#"from(bucket: "bucket") |> first()"#.to_string(), None, ) .await; let params = lsp::DidChangeTextDocumentParams { text_document: lsp::VersionedTextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), version: -2, }, content_changes: vec![ lsp::TextDocumentContentChangeEvent { range: None, range_length: None, text: r#"from(bucket: "bucket")"#.to_string(), }, lsp::TextDocumentContentChangeEvent { range: None, range_length: None, text: r#"from(bucket: "data")"#.to_string(), }, ], }; server.did_change(params).await; let uri = lsp::Url::parse("file:///home/user/file.flux").unwrap(); let contents = server.store.get(&uri).unwrap(); assert_eq!(r#"from(bucket: "data")"#, contents); } #[test] async fn test_did_close() { let server = create_server(); open_file(&server, "from(".to_string(), None).await; assert!(server .store .get(&lsp::Url::parse("file:///home/user/file.flux").unwrap()) .is_ok()); let params = lsp::DidCloseTextDocumentParams { text_document: lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux").unwrap(), ), }; server.did_close(params).await; assert!(server .store .get(&lsp::Url::parse("file:///home/user/file.flux").unwrap()) .is_err()); } // If the file hasn't been opened on the server get, return an error. #[test] async fn test_signature_help_not_opened() { let server = create_server(); let params = lsp::SignatureHelpParams { context: None, text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), lsp::Position::new(0, 0), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.signature_help(params).await; assert!(result.is_err()); } #[test] async fn test_signature_help() { let server = create_server(); let fluxscript = r#"from( // ^"#; open_file(&server, fluxscript.into(), None).await; let params = lsp::SignatureHelpParams { context: None, text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), position_of(fluxscript), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.signature_help(params).await.unwrap().unwrap(); let expected_signature_labels: Vec<String> = vec![ "from()", "from(bucket: $bucket)", "from(bucketID: $bucketID)", "from(host: $host)", "from(org: $org)", "from(orgID: $orgID)", "from(token: $token)", "from(bucket: $bucket , bucketID: $bucketID)", "from(bucket: $bucket , host: $host)", "from(bucket: $bucket , org: $org)", "from(bucket: $bucket , orgID: $orgID)", "from(bucket: $bucket , token: $token)", "from(bucketID: $bucketID , host: $host)", "from(bucketID: $bucketID , org: $org)", "from(bucketID: $bucketID , orgID: $orgID)", "from(bucketID: $bucketID , token: $token)", "from(host: $host , org: $org)", "from(host: $host , orgID: $orgID)", "from(host: $host , token: $token)", "from(org: $org , orgID: $orgID)", "from(org: $org , token: $token)", "from(orgID: $orgID , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , host: $host)", "from(bucket: $bucket , bucketID: $bucketID , org: $org)", "from(bucket: $bucket , bucketID: $bucketID , orgID: $orgID)", "from(bucket: $bucket , bucketID: $bucketID , token: $token)", "from(bucket: $bucket , host: $host , org: $org)", "from(bucket: $bucket , host: $host , orgID: $orgID)", "from(bucket: $bucket , host: $host , token: $token)", "from(bucket: $bucket , org: $org , orgID: $orgID)", "from(bucket: $bucket , org: $org , token: $token)", "from(bucket: $bucket , orgID: $orgID , token: $token)", "from(bucketID: $bucketID , host: $host , org: $org)", "from(bucketID: $bucketID , host: $host , orgID: $orgID)", "from(bucketID: $bucketID , host: $host , token: $token)", "from(bucketID: $bucketID , org: $org , orgID: $orgID)", "from(bucketID: $bucketID , org: $org , token: $token)", "from(bucketID: $bucketID , orgID: $orgID , token: $token)", "from(host: $host , org: $org , orgID: $orgID)", "from(host: $host , org: $org , token: $token)", "from(host: $host , orgID: $orgID , token: $token)", "from(org: $org , orgID: $orgID , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , host: $host , org: $org)", "from(bucket: $bucket , bucketID: $bucketID , host: $host , orgID: $orgID)", "from(bucket: $bucket , bucketID: $bucketID , host: $host , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , org: $org , orgID: $orgID)", "from(bucket: $bucket , bucketID: $bucketID , org: $org , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , orgID: $orgID , token: $token)", "from(bucket: $bucket , host: $host , org: $org , orgID: $orgID)", "from(bucket: $bucket , host: $host , org: $org , token: $token)", "from(bucket: $bucket , host: $host , orgID: $orgID , token: $token)", "from(bucket: $bucket , org: $org , orgID: $orgID , token: $token)", "from(bucketID: $bucketID , host: $host , org: $org , orgID: $orgID)", "from(bucketID: $bucketID , host: $host , org: $org , token: $token)", "from(bucketID: $bucketID , host: $host , orgID: $orgID , token: $token)", "from(bucketID: $bucketID , org: $org , orgID: $orgID , token: $token)", "from(host: $host , org: $org , orgID: $orgID , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , host: $host , org: $org , orgID: $orgID)", "from(bucket: $bucket , bucketID: $bucketID , host: $host , org: $org , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , host: $host , orgID: $orgID , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , org: $org , orgID: $orgID , token: $token)", "from(bucket: $bucket , host: $host , org: $org , orgID: $orgID , token: $token)", "from(bucketID: $bucketID , host: $host , org: $org , orgID: $orgID , token: $token)", "from(bucket: $bucket , bucketID: $bucketID , host: $host , org: $org , orgID: $orgID , token: $token)", ].into_iter().map(|x| x.into()).collect::<Vec<String>>(); assert_eq!( expected_signature_labels, result .signatures .iter() .map(|x| x.label.clone()) .collect::<Vec<String>>() ); assert_eq!(None, result.active_signature); assert_eq!(None, result.active_parameter); } /// Signature help on stdlib functions is provided. #[test] async fn test_signature_help_stdlib() { let server = create_server(); let fluxscript = r#"import "csv" csv.from( // ^"#; open_file(&server, fluxscript.into(), None).await; let params = lsp::SignatureHelpParams { context: None, text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), position_of(fluxscript), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.signature_help(params).await.unwrap().unwrap(); let expected_signature_labels: Vec<String> = vec![ "from()", "from(csv: $csv)", "from(file: $file)", "from(mode: $mode)", "from(csv: $csv , file: $file)", "from(csv: $csv , mode: $mode)", "from(file: $file , mode: $mode)", "from(csv: $csv , file: $file , mode: $mode)", ] .into_iter() .map(|x| x.into()) .collect::<Vec<String>>(); assert_eq!( expected_signature_labels, result .signatures .iter() .map(|x| x.label.clone()) .collect::<Vec<String>>() ); assert_eq!(None, result.active_signature); assert_eq!(None, result.active_parameter); } // If the file hasn't been opened on the server, return an error. #[test] async fn test_formatting_not_opened() { let server = create_server(); let params = lsp::DocumentFormattingParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file::///home/user/file.flux") .unwrap(), }, options: lsp::FormattingOptions { tab_size: 0, insert_spaces: false, properties: HashMap::<String, lsp::FormattingProperty>::new(), trim_trailing_whitespace: None, insert_final_newline: None, trim_final_newlines: None, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.formatting(params).await; assert!(result.is_err()); } #[test] async fn test_formatting() { let fluxscript = r#" import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls"))"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::DocumentFormattingParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, options: lsp::FormattingOptions { tab_size: 0, insert_spaces: false, properties: HashMap::<String, lsp::FormattingProperty>::new(), trim_trailing_whitespace: None, insert_final_newline: None, trim_final_newlines: None, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.formatting(params).await.unwrap().unwrap(); let expected = lsp::TextEdit::new( lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 15, character: 96, }, }, flux::formatter::format(fluxscript).unwrap(), ); assert_eq!(vec![expected], result); } #[test] async fn test_formatting_insert_final_newline() { let fluxscript = r#" import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls")) "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::DocumentFormattingParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, options: lsp::FormattingOptions { tab_size: 0, insert_spaces: false, properties: HashMap::<String, lsp::FormattingProperty>::new(), trim_trailing_whitespace: None, insert_final_newline: Some(true), trim_final_newlines: None, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.formatting(params).await.unwrap().unwrap(); let formatted_text = flux::formatter::format(fluxscript).unwrap(); let expected = lsp::TextEdit::new( lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 17, character: 0, }, }, formatted_text, ); assert_eq!(vec![expected], result); } #[test] async fn test_folding_not_opened() { let server = create_server(); let params = lsp::FoldingRangeParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.folding_range(params).await; assert!(result.is_err()); } #[test] async fn test_folding() { let fluxscript = r#"import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls"))"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::FoldingRangeParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.folding_range(params).await.unwrap().unwrap(); let expected = vec![ lsp::FoldingRange { start_line: 6, start_character: Some(26), end_line: 9, end_character: Some(38), kind: Some(lsp::FoldingRangeKind::Region), }, lsp::FoldingRange { start_line: 15, start_character: Some(26), end_line: 15, end_character: Some(96), kind: Some(lsp::FoldingRangeKind::Region), }, ]; assert_eq!(expected, result); } #[test] async fn test_document_symbol_not_opened() { let server = create_server(); let params = lsp::DocumentSymbolParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.document_symbol(params).await; assert!(result.is_err()); } #[test] async fn test_document_symbol() { let expected_symbol_names: Vec<String> = vec![ "strings", "env", "prod01-us-west-2", "errorCounts", "from", "bucket", "kube-infra/monthly", "range", "start", "filter", "fn", "r._measurement", "query_log", "r.error", "", "r._field", "responseSize", "r.env", "env", "group", "columns", "[]", "env", "error", "count", "group", "columns", "[]", "env", "_stop", "_start", "filter", "fn", "strings.containsStr", "v", "r.error", "substr", "AppendMappedRecordWithNulls", ] .into_iter() .map(|x| x.into()) .collect::<Vec<String>>(); let fluxscript = r#"import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls"))"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::DocumentSymbolParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let symbol_response = server.document_symbol(params).await.unwrap().unwrap(); match symbol_response { lsp::DocumentSymbolResponse::Flat(symbols) => { assert_eq!( expected_symbol_names, symbols .iter() .map(|x| x.name.clone()) .collect::<Vec<String>>() ); } _ => unreachable!(), } } #[test] async fn test_goto_definition_not_opened() { let server = create_server(); let params = lsp::GotoDefinitionParams { text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), lsp::Position::new(1, 1), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.goto_definition(params).await; assert!(result.is_err()); } #[test] async fn test_goto_definition() { let fluxscript = r#"import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) // ^ |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls"))"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::GotoDefinitionParams { text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), position_of(fluxscript), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.goto_definition(params).await.unwrap().unwrap(); let expected = lsp::GotoDefinitionResponse::Scalar(lsp::Location { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), range: lsp::Range { start: lsp::Position { line: 1, character: 0, }, end: lsp::Position { line: 1, character: 24, }, }, }); assert_eq!(expected, result); } #[test] async fn test_goto_definition_builtin() { let fluxscript = r#" builtin func : (x: A) => A func(x: 1) // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::GotoDefinitionParams { text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), position_of(fluxscript), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.goto_definition(params).await.unwrap(); expect_test::expect![[r#" { "uri": "file:///home/user/file.flux", "range": { "start": { "line": 1, "character": 8 }, "end": { "line": 1, "character": 12 } } }"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn test_goto_definition_shadowed() { let fluxscript = r#" env = "prod01-us-west-2" f = (env) => { return env // ^ } "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::GotoDefinitionParams { text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), position_of(fluxscript), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.goto_definition(params).await.unwrap(); expect![[r#" { "uri": "file:///home/user/file.flux", "range": { "start": { "line": 3, "character": 5 }, "end": { "line": 3, "character": 8 } } }"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn test_rename() { let fluxscript = r#"import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls"))"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::RenameParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 1, character: 1, }, }, new_name: "environment".to_string(), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.rename(params).await.unwrap().unwrap(); let edits = vec![ lsp::TextEdit { new_text: "environment".to_string(), range: lsp::Range { start: lsp::Position { line: 1, character: 0, }, end: lsp::Position { line: 1, character: 3, }, }, }, lsp::TextEdit { new_text: "environment".to_string(), range: lsp::Range { start: lsp::Position { line: 8, character: 34, }, end: lsp::Position { line: 8, character: 37, }, }, }, ]; let mut changes: HashMap<lsp::Url, Vec<lsp::TextEdit>> = HashMap::new(); changes.insert( lsp::Url::parse("file:///home/user/file.flux").unwrap(), edits, ); let expected = lsp::WorkspaceEdit { changes: Some(changes), document_changes: None, change_annotations: None, }; assert_eq!(expected, result); } #[test] async fn test_references() { let fluxscript = r#"import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls"))"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::ReferenceParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 1, character: 1, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: lsp::ReferenceContext { // declaration is included whether this is true or false include_declaration: true, }, }; let result = server.references(params.clone()).await.unwrap().unwrap(); let expected = vec![ lsp::Location { uri: params .text_document_position .text_document .uri .clone(), range: lsp::Range { start: lsp::Position { line: 1, character: 0, }, end: lsp::Position { line: 1, character: 3, }, }, }, lsp::Location { uri: params .text_document_position .text_document .uri .clone(), range: lsp::Range { start: lsp::Position { line: 8, character: 34, }, end: lsp::Position { line: 8, character: 37, }, }, }, ]; assert_eq!(expected, result); } #[test] async fn test_references_duplicates() { let fluxscript = r#" t = (x) => { x = 1 return x // ^ }"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::ReferenceParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: lsp::ReferenceContext { // declaration is included whether this is true or false include_declaration: true, }, }; let result = server.references(params.clone()).await.unwrap().unwrap(); expect![[r#" [ { "uri": "file:///home/user/file.flux", "range": { "start": { "line": 2, "character": 4 }, "end": { "line": 2, "character": 5 } } }, { "uri": "file:///home/user/file.flux", "range": { "start": { "line": 3, "character": 11 }, "end": { "line": 3, "character": 12 } } } ]"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn test_document_highlight() { let fluxscript = r#"import "strings" env = "prod01-us-west-2" errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls"))"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::DocumentHighlightParams { text_document_position_params: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse( "file:///home/user/file.flux", ) .unwrap(), }, position: lsp::Position { line: 1, character: 1, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server .document_highlight(params.clone()) .await .unwrap() .unwrap(); let expected = vec![ lsp::DocumentHighlight { kind: Some(lsp::DocumentHighlightKind::TEXT), range: lsp::Range { start: lsp::Position { line: 1, character: 0, }, end: lsp::Position { line: 1, character: 3, }, }, }, lsp::DocumentHighlight { kind: Some(lsp::DocumentHighlightKind::TEXT), range: lsp::Range { start: lsp::Position { line: 8, character: 34, }, end: lsp::Position { line: 8, character: 37, }, }, }, ]; assert_eq!(expected, result); } fn hover_params(pos: lsp::Position) -> lsp::HoverParams { lsp::HoverParams { text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), pos, ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, } } #[test] async fn test_hover() { let fluxscript = r#"x = 1 x + 1 "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = hover_params(lsp::Position::new(1, 1)); let result = server.hover(params).await.unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String("int".to_string()) ), range: None, }) ); } #[test] async fn test_hover_with_markdown() { let fluxscript = r#"x = 1 x + 1 "#; let server = create_server(); let params = lsp::InitializeParams { capabilities: lsp::ClientCapabilities { workspace: None, text_document: Some( lsp::TextDocumentClientCapabilities { hover: Some(lsp::HoverClientCapabilities { dynamic_registration: Some(true), content_format: Some(vec![ lsp::MarkupKind::PlainText, lsp::MarkupKind::Markdown, ]), }), ..Default::default() }, ), window: None, general: None, experimental: None, }, client_info: None, initialization_options: None, locale: None, process_id: None, root_path: None, root_uri: None, trace: None, workspace_folders: None, }; server.initialize(params).await.unwrap(); open_file(&server, fluxscript.to_string(), None).await; let params = hover_params(lsp::Position::new(1, 1)); let result = server.hover(params).await.unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Markup( lsp::MarkupContent { kind: lsp::MarkupKind::Markdown, value: String::from("```flux\nint\n```") } ), range: None, }) ); } #[test] async fn test_hover_binding() { let fluxscript = r#"x = "asd" builtin builtin_ : (v: A) => A where A: Numeric option option_ = 123 1 "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let result = server .hover(hover_params(lsp::Position::new(0, 1))) .await .unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String("string".to_string()) ), range: None, }) ); let result = server .hover(hover_params(lsp::Position::new(1, 12))) .await .unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String( "(v: A) => A where A: Numeric".to_string() ) ), range: None, }) ); let result = server .hover(hover_params(lsp::Position::new(2, 10))) .await .unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String("int".to_string()) ), range: None, }) ); } #[test] async fn test_hover_argument() { let fluxscript = r#" (x) => x + 1 "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = hover_params(lsp::Position::new(1, 1)); let result = server.hover(params).await.unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String("int".to_string()) ), range: None, }) ); } #[test] async fn test_hover_call_property() { let fluxscript = r#" f = (x) => x + 1 y = f(x: 1) // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = hover_params(position_of(fluxscript)); let result = server.hover(params).await.unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String("int".to_string()) ), range: None, }) ); } #[test] async fn test_hover_record_property() { let fluxscript = r#" { abc: "" } // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = hover_params(position_of(fluxscript)); let result = server.hover(params).await.unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String("string".to_string()) ), range: None, }) ); } #[test] async fn test_hover_on_semantic_error() { let fluxscript = r#" y = 1 + "" x = 1 1 + x // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = hover_params(position_of(fluxscript)); let result = server.hover(params).await.unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String("int".to_string()) ), range: None, }) ); } #[test] async fn test_hover_on_polymorphic_identifier() { let fluxscript = r#" f = (x) => x + x // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = hover_params(position_of(fluxscript)); let result = server.hover(params).await.unwrap(); assert_eq!( result, Some(lsp::Hover { contents: lsp::HoverContents::Scalar( lsp::MarkedString::String( "A where A: Addable".to_string() ) ), range: None, }) ); } #[test] async fn test_package_completion() { let fluxscript = r#"import "sql" sql. // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::TRIGGER_CHARACTER, trigger_character: Some(".".to_string()), }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let expected_labels: Vec<String> = vec!["to", "from"] .into_iter() .map(|x| x.into()) .collect::<Vec<String>>(); match result { lsp::CompletionResponse::List(l) => { assert_eq!( expected_labels, l.items .iter() .map(|x| x.label.clone()) .collect::<Vec<String>>() ); } _ => unreachable!(), }; } /// When completing package member names, support import aliases. #[test] async fn test_package_completion_with_alias() { let fluxscript = r#"import sekwel "sql" sekwel. // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::TRIGGER_CHARACTER, trigger_character: Some(".".to_string()), }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let expected_labels: Vec<String> = vec!["to", "from"] .into_iter() .map(|x| x.into()) .collect::<Vec<String>>(); match result { lsp::CompletionResponse::List(l) => { assert_eq!( expected_labels, l.items .iter() .map(|x| x.label.clone()) .collect::<Vec<String>>() ); } _ => unreachable!(), }; } #[test] async fn test_import_completion() { let fluxscript = r#" import " // ^ x = 1 "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); match result { lsp::CompletionResponse::List(l) => { expect![[r#" [ "\"array\"", "\"bitwise\"", "\"contrib/RohanSreerama5/naiveBayesClassifier\"", "\"contrib/anaisdg/anomalydetection\"", "\"contrib/anaisdg/statsmodels\"", "\"contrib/bonitoo-io/alerta\"", "\"contrib/bonitoo-io/hex\"", "\"contrib/bonitoo-io/servicenow\"", "\"contrib/bonitoo-io/tickscript\"", "\"contrib/bonitoo-io/victorops\"", "\"contrib/bonitoo-io/zenoss\"", "\"contrib/chobbs/discord\"", "\"contrib/jsternberg/influxdb\"", "\"contrib/qxip/clickhouse\"", "\"contrib/qxip/hash\"", "\"contrib/qxip/logql\"", "\"contrib/rhajek/bigpanda\"", "\"contrib/sranka/opsgenie\"", "\"contrib/sranka/sensu\"", "\"contrib/sranka/teams\"", "\"contrib/sranka/telegram\"", "\"contrib/sranka/webexteams\"", "\"contrib/tomhollingworth/events\"", "\"csv\"", "\"date\"", "\"date/boundaries\"", "\"dict\"", "\"experimental\"", "\"experimental/aggregate\"", "\"experimental/array\"", "\"experimental/bigtable\"", "\"experimental/bitwise\"", "\"experimental/csv\"", "\"experimental/date/boundaries\"", "\"experimental/dynamic\"", "\"experimental/geo\"", "\"experimental/http\"", "\"experimental/http/requests\"", "\"experimental/influxdb\"", "\"experimental/iox\"", "\"experimental/json\"", "\"experimental/mqtt\"", "\"experimental/oee\"", "\"experimental/polyline\"", "\"experimental/prometheus\"", "\"experimental/query\"", "\"experimental/record\"", "\"experimental/table\"", "\"experimental/usage\"", "\"generate\"", "\"http\"", "\"http/requests\"", "\"influxdata/influxdb\"", "\"influxdata/influxdb/monitor\"", "\"influxdata/influxdb/sample\"", "\"influxdata/influxdb/schema\"", "\"influxdata/influxdb/secrets\"", "\"influxdata/influxdb/tasks\"", "\"influxdata/influxdb/v1\"", "\"internal/boolean\"", "\"internal/debug\"", "\"internal/gen\"", "\"internal/influxql\"", "\"internal/location\"", "\"internal/promql\"", "\"internal/testing\"", "\"internal/testutil\"", "\"interpolate\"", "\"join\"", "\"json\"", "\"kafka\"", "\"math\"", "\"pagerduty\"", "\"planner\"", "\"profiler\"", "\"pushbullet\"", "\"regexp\"", "\"runtime\"", "\"sampledata\"", "\"slack\"", "\"socket\"", "\"sql\"", "\"strings\"", "\"system\"", "\"testing\"", "\"testing/expect\"", "\"timezone\"", "\"types\"", "\"universe\"", ] "#]] .assert_debug_eq( &l.items.iter().map(|x| &x.label).collect::<Vec<_>>(), ); } _ => unreachable!(), }; } #[test] async fn test_variable_completion() { let fluxscript = r#"import "strings" import "csv" cal = 10 env = "prod01-us-west-2" cool = (a) => a + 1 c errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls")) "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 8, character: 1, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; let got: BTreeSet<&str> = items.iter().map(|i| i.label.as_str()).collect(); let want: BTreeSet<&str> = vec![ "buckets", "cardinality", "chandeMomentumOscillator", "columns", "contains", "contrib/RohanSreerama5/naiveBayesClassifier", "contrib/anaisdg/anomalydetection", "contrib/bonitoo-io/servicenow", "contrib/bonitoo-io/tickscript", "contrib/bonitoo-io/victorops", "contrib/chobbs/discord", "contrib/qxip/clickhouse", "count", "cov", "covariance", "csv", "cumulativeSum", "dict", "difference", "distinct", "duplicate", "experimental/csv", "experimental/dynamic", "experimental/record", "findColumn", "findRecord", "getColumn", "getRecord", "highestCurrent", "hourSelection", "increase", "influxdata/influxdb/schema", "influxdata/influxdb/secrets", "internal/location", "logarithmicBins", "lowestCurrent", "reduce", "slack", "socket", "stateCount", "stateTracking", "testing/expect", "truncateTimeColumn", ] .drain(..) .collect(); assert_eq!( want, got, "\nextra:\n {:?}\n missing:\n {:?}\n", got.difference(&want), want.difference(&got) ); } #[test] async fn test_option_object_members_completion() { let fluxscript = r#"import "strings" import "csv" cal = 10 env = "prod01-us-west-2" cool = (a) => a + 1 option task = { name: "foo", // Name is required. every: 1h, // Task should be run at this interval. delay: 10m, // Delay scheduling this task by this duration. cron: "0 2 * * *", // Cron is a more sophisticated way to schedule. 'every' and 'cron' are mutually exclusive. retry: 5, // Number of times to retry a failed query. } task. // ^ ab = 10 "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::TRIGGER_CHARACTER, trigger_character: Some(".".to_string()), }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; let labels: Vec<&str> = items.iter().map(|item| item.label.as_str()).collect(); let expected = vec![ "name (self)", "every (self)", "delay (self)", "cron (self)", "retry (self)", ]; assert_eq!(expected, labels); } /// Function parameter snippets are returned with the snippet syntax /// for completion on a a function already written, e.g. from an /// automated process. #[test] async fn test_function_completion_snippet() { let fluxscript = r#" from() // ^"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(&fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; expect![[r#" [ { "label": "bucket", "kind": 5, "detail": "string", "insertText": "bucket: \"$1\"", "insertTextFormat": 2 }, { "label": "bucketID", "kind": 5, "detail": "string", "insertText": "bucketID: \"$2\"", "insertTextFormat": 2 }, { "label": "host", "kind": 5, "detail": "string", "insertText": "host: \"$3\"", "insertTextFormat": 2 }, { "label": "org", "kind": 5, "detail": "string", "insertText": "org: \"$4\"", "insertTextFormat": 2 }, { "label": "orgID", "kind": 5, "detail": "string", "insertText": "orgID: \"$5\"", "insertTextFormat": 2 }, { "label": "token", "kind": 5, "detail": "string", "insertText": "token: \"$6\"", "insertTextFormat": 2 } ]"#]] .assert_eq(&serde_json::to_string_pretty(&items).unwrap()); } // XXX: rockstar (6 Jul 2022) - Is this test correct? I think it's not. It's // saying that when there's a `now`, and you type `n` it should complete to // literally everything? That makes no sense. #[test] async fn test_option_function_completion() { let fluxscript = r#"import "strings" import "csv" cal = 10 env = "prod01-us-west-2" cool = (a) => a + 1 option now = () => 2020-02-20T23:00:00Z n ab = 10 "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 10, character: 1, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; let got: BTreeSet<&str> = items.iter().map(|i| i.label.as_str()).collect(); expect![[r#" [ "aggregateWindow", "cardinality", "chandeMomentumOscillator", "columns", "contains", "contrib/RohanSreerama5/naiveBayesClassifier", "contrib/anaisdg/anomalydetection", "contrib/bonitoo-io/servicenow", "contrib/bonitoo-io/zenoss", "contrib/jsternberg/influxdb", "contrib/rhajek/bigpanda", "contrib/sranka/opsgenie", "contrib/sranka/sensu", "contrib/tomhollingworth/events", "count", "covariance", "date/boundaries", "difference", "distinct", "duration", "experimental", "experimental/date/boundaries", "experimental/dynamic", "experimental/influxdb", "experimental/json", "experimental/polyline", "exponentialMovingAverage", "findColumn", "findRecord", "generate", "getColumn", "highestCurrent", "histogramQuantile", "holtWinters", "hourSelection", "increase", "inf (prelude)", "influxdata/influxdb", "influxdata/influxdb/monitor", "int", "integral", "internal/boolean", "internal/gen", "internal/influxql", "internal/location", "internal/testing", "interpolate", "join", "json", "kaufmansAMA", "kaufmansER", "length", "linearBins", "logarithmicBins", "lowestCurrent", "lowestMin", "mean", "median", "min", "movingAverage", "now", "pearsonr", "planner", "quantile", "range", "relativeStrengthIndex", "rename", "runtime", "stateCount", "stateDuration", "stateTracking", "string", "strings", "tableFind", "testing", "timedMovingAverage", "timezone", "toInt", "toString", "toUInt", "tripleExponentialDerivative", "truncateTimeColumn", "uint", "union", "unique", "universe", "window" ]"#]] .assert_eq(&serde_json::to_string_pretty(&got).unwrap()); } #[test] async fn test_object_param_completion() { let fluxscript = r#"obj = { func: (name, age) => name + age } obj.func( // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::TRIGGER_CHARACTER, trigger_character: Some("(".to_string()), }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; let labels: Vec<&str> = items.iter().map(|item| item.label.as_str()).collect(); let expected = vec!["name", "age"]; assert_eq!(expected, labels); } #[test] async fn test_param_completion() { let fluxscript = r#"import "csv" csv.from( // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::TRIGGER_CHARACTER, trigger_character: Some("(".to_string()), }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); expect![[r#" { "isIncomplete": false, "items": [ { "label": "csv", "kind": 5, "detail": "string", "insertText": "csv: \"$1\"", "insertTextFormat": 2 }, { "label": "file", "kind": 5, "detail": "string", "insertText": "file: \"$2\"", "insertTextFormat": 2 }, { "label": "mode", "kind": 5, "detail": "string", "insertText": "mode: \"$3\"", "insertTextFormat": 2 } ] }"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn test_param_completion_2() { let fluxscript = r#"import "csv" csv.from( "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 3, character: 0, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; let labels: Vec<&str> = items.iter().map(|item| item.label.as_str()).collect(); let expected = vec!["csv", "file", "mode"]; assert_eq!(expected, labels); } #[test] async fn test_param_completion_3() { let fluxscript = r#"import "csv" csv.from(mode: "raw", // ^ x = 1 "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; let labels: Vec<&str> = items.iter().map(|item| item.label.as_str()).collect(); let expected = vec!["csv", "file"]; assert_eq!(expected, labels); } #[test] async fn test_options_completion() { let fluxscript = r#"import "strings" import "csv" cal = 10 env = "prod01-us-west-2" cool = (a) => a + 1 option task = { name: "foo", // Name is required. every: 1h, // Task should be run at this interval. delay: 10m, // Delay scheduling this task by this duration. cron: "0 2 * * *", // Cron is a more sophisticated way to schedule. 'every' and 'cron' are mutually exclusive. retry: 5, // Number of times to retry a failed query. } newNow = t errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d ) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls")) "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 16, character: 10, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); let items = match result { lsp::CompletionResponse::List(l) => l.items, _ => unreachable!(), }; let got: BTreeSet<&str> = items.iter().map(|i| i.label.as_str()).collect(); let want: BTreeSet<&str> = vec![ "aggregateWindow", "bitwise", "bottom", "buckets", "bytes", "cardinality", "chandeMomentumOscillator", "contains", "contrib/anaisdg/anomalydetection", "contrib/anaisdg/statsmodels", "contrib/bonitoo-io/alerta", "contrib/bonitoo-io/tickscript", "contrib/bonitoo-io/victorops", "contrib/sranka/teams", "contrib/sranka/telegram", "contrib/sranka/webexteams", "contrib/tomhollingworth/events", "count", "cumulativeSum", "date", "derivative", "dict", "distinct", "duplicate", "duration", "experimental", "experimental/aggregate", "experimental/bigtable", "experimental/bitwise", "experimental/http", "experimental/http/requests", "experimental/mqtt", "experimental/prometheus", "experimental/table", "exponentialMovingAverage", "filter", "first", "float", "generate", "getColumn", "getRecord", "highestAverage", "highestCurrent", "highestMax", "histogram", "histogramQuantile", "holtWinters", "hourSelection", "http", "http/requests", "influxdata/influxdb/monitor", "influxdata/influxdb/secrets", "influxdata/influxdb/tasks", "int", "integral", "internal/testutil", "internal/location", "internal/testing", "interpolate", "last", "length", "limit", "logarithmicBins", "lowestAverage", "lowestCurrent", "lowestMin", "math", "pagerduty", "pivot", "pushbullet", "quantile", "relativeStrengthIndex", "runtime", "sampledata", "set", "socket", "sort", "stateCount", "stateDuration", "stateTracking", "stddev", "string", "strings", "system", "tableFind", "tail", "testing", "testing/expect", "time", "timeShift", "timeWeightedAvg", "timedMovingAverage", "timezone", "to", "toBool", "toFloat", "toInt", "toString", "toTime", "toUInt", "today", "top", "tripleEMA", "tripleExponentialDerivative", "true (prelude)", "truncateTimeColumn", "types", "uint", "wideTo", ] .drain(..) .collect(); assert_eq!( want, got, "\nextra:\n {:?}\n missing:\n {:?}\n", got.difference(&want), want.difference(&got) ); } #[test] async fn test_signature_help_invalid() { let fluxscript = r#"bork |>"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::SignatureHelpParams { context: None, text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), lsp::Position::new(0, 5), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.signature_help(params).await; assert_eq!(result, Ok(None)); } #[test] async fn test_folding_range_invalid() { let fluxscript = r#"bork |>"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::FoldingRangeParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.folding_range(params).await; assert_eq!(result, Ok(None)); } #[test] async fn test_document_symbol_invalid() { let fluxscript = r#"bork |>"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::DocumentSymbolParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.document_symbol(params).await; assert_eq!(result, Ok(None)); } #[test] async fn test_goto_definition_invalid() { let fluxscript = r#"bork |>"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::GotoDefinitionParams { text_document_position_params: lsp::TextDocumentPositionParams::new( lsp::TextDocumentIdentifier::new( lsp::Url::parse("file:///home/user/file.flux") .unwrap(), ), lsp::Position::new(8, 35), ), work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.goto_definition(params).await; assert!(matches!(result, Ok(None))); } #[test] async fn test_rename_invalid() { let fluxscript = r#"bork |>"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::ReferenceParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 1, character: 1, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: lsp::ReferenceContext { // declaration is included whether this is true or false include_declaration: true, }, }; let result = server.references(params.clone()).await; assert_eq!(result, Ok(None)); } // Historically, the completion of a package also brought with it an additional edit // that would import the stdlib module it was referring to. This test asserts that we // don't add it back in, but also serves as documentation that this was a conscious // choice, as the user experience was not good. #[test] async fn test_package_completion_when_it_is_not_imported() { let fluxscript = r#"sql"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 0, character: 2, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); expect_test::expect![[r#" { "isIncomplete": false, "items": [ { "label": "sql", "kind": 9, "detail": "Package", "documentation": "sql", "sortText": "sql", "filterText": "sql", "insertText": "sql", "insertTextFormat": 1 } ] }"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn test_package_completion_when_it_is_imported() { let fluxscript = r#"import "sql" sql"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 2, character: 2, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); expect_test::expect![[r#" { "isIncomplete": false, "items": [ { "label": "sql", "kind": 9, "detail": "Package", "documentation": "sql", "sortText": "sql", "filterText": "sql", "insertText": "sql", "insertTextFormat": 1 } ] }"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn test_member_completion() { let fluxscript = r#" import "json" from(bucket: "bucket") |> range(start: v.timeRangeStart, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "measurement") |> filter(fn: (r) => r["_field"] == "request") |> map(fn: (r) => (json.(v: r._value))) // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); expect_test::expect![[r#" { "isIncomplete": false, "items": [ { "label": "encode", "kind": 3, "detail": "(v:A) -> bytes", "sortText": "encode", "filterText": "encode", "insertTextFormat": 2 } ] }"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn test_member_completion_2() { let fluxscript = r#" import "json" from(bucket: "bucket") |> range(start: v.timeRangeStart, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "measurement") |> filter(fn: (r) => r["_field"] == "request") |> map(fn: (r) => (json.(v: r._value))) // ^ "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: position_of(fluxscript), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; let result = server.completion(params.clone()).await.unwrap().unwrap(); expect_test::expect![[r#" { "isIncomplete": false, "items": [ { "label": "experimental/json", "kind": 9, "detail": "Package", "documentation": "experimental/json", "sortText": "experimental/json", "filterText": "json", "insertText": "experimental/json", "insertTextFormat": 1 }, { "label": "json", "kind": 9, "detail": "Package", "documentation": "json", "sortText": "json", "filterText": "json", "insertText": "json", "insertTextFormat": 1 } ] }"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } use crate::visitors::ast::{ SEMANTIC_TOKEN_KEYWORD, SEMANTIC_TOKEN_NUMBER, SEMANTIC_TOKEN_STRING, }; #[test] async fn test_semantic_tokens_full() { let fluxscript = r#"package "my-package" import "csv" myVar = from(bucket: "my-bucket") |> range(start: 30m) csv.from(file: "my.csv") |> filter(fn: (row) => row.field == 0.9) "#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::SemanticTokensParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.semantic_tokens_full(params).await.unwrap(); assert!(result.is_some()); let token_result = result.unwrap(); if let lsp::SemanticTokensResult::Tokens(tokens) = token_result { let expected = lsp::SemanticTokens { result_id: None, data: vec![ // package lsp::SemanticToken { delta_line: 1, delta_start: 1, length: 7, token_type: SEMANTIC_TOKEN_KEYWORD, token_modifiers_bitset: 0, }, // "my-package" lsp::SemanticToken { delta_line: 1, delta_start: 9, length: 0, token_type: SEMANTIC_TOKEN_STRING, token_modifiers_bitset: 0, }, // import lsp::SemanticToken { delta_line: 1, delta_start: 9, length: 12, token_type: SEMANTIC_TOKEN_STRING, token_modifiers_bitset: 0, }, // "csv" lsp::SemanticToken { delta_line: 2, delta_start: 8, length: 5, token_type: SEMANTIC_TOKEN_STRING, token_modifiers_bitset: 0, }, // "my-bucket" lsp::SemanticToken { delta_line: 4, delta_start: 22, length: 11, token_type: SEMANTIC_TOKEN_STRING, token_modifiers_bitset: 0, }, // 30m lsp::SemanticToken { delta_line: 5, delta_start: 21, length: 3, token_type: SEMANTIC_TOKEN_NUMBER, token_modifiers_bitset: 0, }, // my.csv lsp::SemanticToken { delta_line: 7, delta_start: 16, length: 8, token_type: SEMANTIC_TOKEN_STRING, token_modifiers_bitset: 0, }, // 0.9 lsp::SemanticToken { delta_line: 8, delta_start: 41, length: 3, token_type: SEMANTIC_TOKEN_NUMBER, token_modifiers_bitset: 0, }, ], }; assert_eq!(expected, tokens) } else { panic!("Result was not a token result"); } } // A code action for importing a package when an undefined identifier // is found. #[test] async fn test_code_action_import_insertion() { let fluxscript = r#"sql"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CodeActionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, context: lsp::CodeActionContext { diagnostics: vec![lsp::Diagnostic { code: None, code_description: None, data: None, related_information: None, severity: Some(lsp::DiagnosticSeverity::ERROR), source: Some("flux".into()), tags: None, message: "undefined identifier sql".into(), range: lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 0, character: 0, }, }, }], only: None, }, range: lsp::Range { start: lsp::Position { line: 0, character: 2, }, end: lsp::Position { line: 0, character: 2, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.code_action(params).await.unwrap(); expect_test::expect![[r#" [ { "title": "Import `sql`", "kind": "quickfix", "edit": { "changes": { "file:///home/user/file.flux": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }, "newText": "import \"sql\"\n" } ] } }, "isPreferred": true } ]"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } // When inserting a package import, don't clobber the package statement at the beginning. #[test] async fn test_code_action_import_insertion_with_package() { let fluxscript = "package anPackage\n\nsql"; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CodeActionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, context: lsp::CodeActionContext { diagnostics: vec![lsp::Diagnostic { code: None, code_description: None, data: None, related_information: None, severity: Some(lsp::DiagnosticSeverity::ERROR), source: Some("flux".into()), tags: None, message: "undefined identifier sql".into(), range: lsp::Range { start: lsp::Position { line: 2, character: 0, }, end: lsp::Position { line: 2, character: 0, }, }, }], only: None, }, range: lsp::Range { start: lsp::Position { line: 2, character: 2, }, end: lsp::Position { line: 2, character: 2, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.code_action(params).await.unwrap(); expect_test::expect![[r#" [ { "title": "Import `sql`", "kind": "quickfix", "edit": { "changes": { "file:///home/user/file.flux": [ { "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }, "newText": "import \"sql\"\n" } ] } }, "isPreferred": true } ]"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } /// If the identifier matches multiple potential imports, multiple code /// actions should be offered to the user. #[test] async fn test_code_action_import_insertion_multiple_actions() { let fluxscript = r#"array"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CodeActionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, context: lsp::CodeActionContext { diagnostics: vec![lsp::Diagnostic { code: None, code_description: None, data: None, related_information: None, severity: Some(lsp::DiagnosticSeverity::ERROR), source: Some("flux".into()), tags: None, message: "undefined identifier array".into(), range: lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 0, character: 0, }, }, }], only: None, }, range: lsp::Range { start: lsp::Position { line: 0, character: 4, }, end: lsp::Position { line: 0, character: 4, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.code_action(params).await.unwrap(); expect_test::expect![[r#" [ { "title": "Import `array`", "kind": "quickfix", "edit": { "changes": { "file:///home/user/file.flux": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }, "newText": "import \"array\"\n" } ] } }, "isPreferred": true }, { "title": "Import `experimental/array`", "kind": "quickfix", "edit": { "changes": { "file:///home/user/file.flux": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }, "newText": "import \"experimental/array\"\n" } ] } }, "isPreferred": true } ]"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } /// If the import requires a full path, that the action suggests the full path. #[test] async fn test_code_action_import_insertion_full_path() { let fluxscript = r#"schema"#; let server = create_server(); open_file(&server, fluxscript.to_string(), None).await; let params = lsp::CodeActionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, context: lsp::CodeActionContext { diagnostics: vec![lsp::Diagnostic { code: None, code_description: None, data: None, related_information: None, severity: Some(lsp::DiagnosticSeverity::ERROR), source: Some("flux".into()), tags: None, message: "undefined identifier schema".into(), range: lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 0, character: 0, }, }, }], only: None, }, range: lsp::Range { start: lsp::Position { line: 0, character: 5, }, end: lsp::Position { line: 0, character: 5, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }; let result = server.code_action(params).await.unwrap(); expect_test::expect![[r#" [ { "title": "Import `influxdata/influxdb/schema`", "kind": "quickfix", "edit": { "changes": { "file:///home/user/file.flux": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }, "newText": "import \"influxdata/influxdb/schema\"\n" } ] } }, "isPreferred": true } ]"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } #[test] async fn compute_diagnostics_multi_file() { let server = create_server(); let filename: String = "file:///path/to/script.flux".into(); let fluxscript = r#"from(bucket: "my-bucket") |> range(start: -100d) |> filter(fn: (r) => r.anTag == v.a)"#; open_file(&server, fluxscript.into(), Some(&filename)).await; let diagnostics = server .compute_diagnostics(&lsp::Url::parse(&filename).unwrap()); assert_eq!( HashMap::from([( lsp::Url::parse("file:///path/to/script.flux").unwrap(), vec![lsp::Diagnostic { code: None, code_description: None, data: None, message: "undefined identifier v".into(), range: lsp::Range { start: lsp::Position { line: 2, character: 32 }, end: lsp::Position { line: 2, character: 33 }, }, related_information: None, severity: Some(lsp::DiagnosticSeverity::ERROR), source: Some("flux".into()), tags: None, }] ),]), diagnostics ); open_file( &server, r#"v = {a: "b"}"#.to_string(), Some("file:///path/to/an_vars.flux"), ) .await; let diagnostics_again = server .compute_diagnostics(&lsp::Url::parse(&filename).unwrap()); let expected: HashMap<lsp::Url, Vec<lsp::Diagnostic>> = HashMap::from([ (lsp::Url::parse("file:///path/to/script.flux").unwrap(), vec![]), (lsp::Url::parse("file:///path/to/an_vars.flux").unwrap(), vec![lsp::Diagnostic { range: lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 0, character: 1, } }, severity: Some(lsp::DiagnosticSeverity::WARNING), message: "Avoid using `v` as an identifier name. In some InfluxDB contexts, it may be provided at runtime.".to_string(), ..lsp::Diagnostic::default() }]), ]); // We are interested in the error from the original file being fixed, not in // the lints introduced by the new file. assert_eq!(expected, diagnostics_again); } #[test] async fn compute_diagnostics_non_errors() { let server = create_server(); let filename: String = "file:///path/to/script.flux".into(); let fluxscript = r#"import "experimental" from(bucket: "my-bucket") |> range(start: -100d) |> filter(fn: (r) => r.value == "b") |> experimental.to(bucket: "out-bucket", org: "abc123", host: "https://myhost.example.com", token: "123abc")"#; open_file(&server, fluxscript.into(), Some(&filename)).await; let diagnostics_again = server .compute_diagnostics(&lsp::Url::parse(&filename).unwrap()); assert!(!diagnostics_again.is_empty()); } // All commands require key/value pairs as params, not positional /// arguments. #[test] async fn execute_command_too_many_args() { let server = create_server(); let params = lsp::ExecuteCommandParams { command: "notActuallyAValidCommand".into(), arguments: vec![ serde_json::value::to_value("arg1").unwrap(), serde_json::value::to_value("arg2").unwrap(), ], work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.execute_command(params).await; assert!(result.is_err()); } // Attempting to execute a command that doesn't exist results in an Err response. #[test] async fn execute_command_unknown_command() { let server = create_server(); let params = lsp::ExecuteCommandParams { command: "notActuallyAValidCommand".into(), arguments: vec![serde_json::json!({"foo": "bar"})], work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result = server.execute_command(params).await; assert!(result.is_err()); } #[test] async fn execute_command_get_function_list() { let server = create_server(); let params = lsp::ExecuteCommandParams { command: "getFunctionList".into(), arguments: vec![], work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, }; let result: Vec<String> = serde_json::from_value( server.execute_command(params).await.unwrap().unwrap(), ) .unwrap(); expect_test::expect![[r#" [ "aggregateWindow", "bool", "bottom", "buckets", "bytes", "cardinality", "chandeMomentumOscillator", "columns", "contains", "count", "cov", "covariance", "cumulativeSum", "derivative", "die", "difference", "display", "distinct", "doubleEMA", "drop", "duplicate", "duration", "elapsed", "exponentialMovingAverage", "fill", "filter", "findColumn", "findRecord", "first", "float", "from", "getColumn", "getRecord", "group", "highestAverage", "highestCurrent", "highestMax", "histogram", "histogramQuantile", "holtWinters", "hourSelection", "increase", "int", "integral", "join", "kaufmansAMA", "kaufmansER", "keep", "keyValues", "keys", "last", "length", "limit", "linearBins", "logarithmicBins", "lowestAverage", "lowestCurrent", "lowestMin", "map", "max", "mean", "median", "min", "mode", "movingAverage", "now", "pearsonr", "pivot", "quantile", "range", "reduce", "relativeStrengthIndex", "rename", "sample", "set", "skew", "sort", "spread", "stateCount", "stateDuration", "stateTracking", "stddev", "string", "sum", "tableFind", "tail", "time", "timeShift", "timeWeightedAvg", "timedMovingAverage", "to", "toBool", "toFloat", "toInt", "toString", "toTime", "toUInt", "today", "top", "tripleEMA", "tripleExponentialDerivative", "truncateTimeColumn", "uint", "union", "unique", "wideTo", "window", "yield" ]"#]] .assert_eq(&serde_json::to_string_pretty(&result).unwrap()); } /// When the client notifies the server of new buckets, those buckets are /// stored and able to be queried. #[test] async fn workspace_state_buckets() { let server = create_server(); server.did_change_configuration(lsp::DidChangeConfigurationParams { settings: json!({"settings": {"buckets": ["my-bucket", "your-bucket", "our-bucket"]}}) }).await; let buckets = server.state.lock().unwrap().buckets().clone(); let expected: Vec<String> = vec!["my-bucket", "your-bucket", "our-bucket"] .iter() .map(|item| item.to_string()) .collect(); assert_eq!(expected, buckets); }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::channel::{AccessingResource, Channel, GetPendingTxn}; use anyhow::Result; use coerce_rt::actor::ActorRef; use libra_types::{ access_path::{AccessPath, DataPath}, account_address::AccountAddress, libra_resource::{make_resource, LibraResource}, }; use serde::de::DeserializeOwned; use sgtypes::pending_txn::PendingTransaction; use std::collections::BTreeSet; #[derive(Debug)] pub struct ChannelHandle { channel_address: AccountAddress, account_address: AccountAddress, participant_addresses: BTreeSet<AccountAddress>, channel_ref: ActorRef<Channel>, } impl ChannelHandle { // constructor is private to pub(crate) fn new( channel_address: AccountAddress, account_address: AccountAddress, participant_addresses: BTreeSet<AccountAddress>, channel_ref: ActorRef<Channel>, ) -> Self { Self { channel_address, account_address, participant_addresses, channel_ref, } } pub fn account_address(&self) -> &AccountAddress { &self.account_address } pub fn channel_address(&self) -> &AccountAddress { &self.channel_address } pub fn participant_addresses(&self) -> &BTreeSet<AccountAddress> { &self.participant_addresses } pub fn channel_ref(&self) -> ActorRef<Channel> { self.channel_ref.clone() } #[allow(dead_code)] pub async fn stop(&self) -> Result<()> { self.channel_ref.clone().stop().await?; Ok(()) } pub async fn get_pending_txn(&self) -> Result<Option<PendingTransaction>> { Ok(self.channel_ref.clone().send(GetPendingTxn).await?) } pub async fn get_channel_resource<R: LibraResource + DeserializeOwned>( &self, data_path: DataPath, // address: AccountAddress, // struct_tag: StructTag, ) -> Result<Option<R>> { // let data_path = DataPath::channel_resource_path(address, struct_tag); let blob = self .channel_ref .clone() .send(AccessingResource { path: AccessPath::new_for_data_path(self.channel_address, data_path), }) .await??; blob.map(|b| make_resource::<R>(&b)).transpose() } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct JobDetailsList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<JobDetails>, #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i64>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct JobDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "containerUri")] pub container_uri: String, #[serde(rename = "inputDataUri", default, skip_serializing_if = "Option::is_none")] pub input_data_uri: Option<String>, #[serde(rename = "inputDataFormat")] pub input_data_format: String, #[serde(rename = "inputParams", default, skip_serializing_if = "Option::is_none")] pub input_params: Option<serde_json::Value>, #[serde(rename = "providerId")] pub provider_id: String, pub target: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option<serde_json::Value>, #[serde(rename = "outputDataUri", default, skip_serializing_if = "Option::is_none")] pub output_data_uri: Option<String>, #[serde(rename = "outputDataFormat", default, skip_serializing_if = "Option::is_none")] pub output_data_format: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<job_details::Status>, #[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")] pub creation_time: Option<String>, #[serde(rename = "beginExecutionTime", default, skip_serializing_if = "Option::is_none")] pub begin_execution_time: Option<String>, #[serde(rename = "endExecutionTime", default, skip_serializing_if = "Option::is_none")] pub end_execution_time: Option<String>, #[serde(rename = "cancellationTime", default, skip_serializing_if = "Option::is_none")] pub cancellation_time: Option<String>, #[serde(rename = "errorData", default, skip_serializing_if = "Option::is_none")] pub error_data: Option<ErrorData>, } pub mod job_details { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Waiting, Executing, Succeeded, Failed, Cancelled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BlobDetails { #[serde(rename = "containerName")] pub container_name: String, #[serde(rename = "blobName", default, skip_serializing_if = "Option::is_none")] pub blob_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SasUriResponse { #[serde(rename = "sasUri", default, skip_serializing_if = "Option::is_none")] pub sas_uri: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProviderStatusList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ProviderStatus>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProviderStatus { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "currentAvailability", default, skip_serializing_if = "Option::is_none")] pub current_availability: Option<provider_status::CurrentAvailability>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub targets: Vec<TargetStatus>, } pub mod provider_status { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CurrentAvailability { Available, Degraded, Unavailable, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TargetStatus { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "currentAvailability", default, skip_serializing_if = "Option::is_none")] pub current_availability: Option<target_status::CurrentAvailability>, #[serde(rename = "averageQueueTime", default, skip_serializing_if = "Option::is_none")] pub average_queue_time: Option<i64>, #[serde(rename = "statusPage", default, skip_serializing_if = "Option::is_none")] pub status_page: Option<String>, } pub mod target_status { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CurrentAvailability { Available, Degraded, Unavailable, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Quota>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Quota { #[serde(default, skip_serializing_if = "Option::is_none")] pub dimension: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<quota::Scope>, #[serde(rename = "providerId", default, skip_serializing_if = "Option::is_none")] pub provider_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub utilization: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub holds: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub period: Option<quota::Period>, } pub mod quota { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Scope { Workspace, Subscription, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Period { None, Monthly, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RestError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorData { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, }
use std::cell::RefCell; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; use std::rc::Rc; #[derive(Default)] struct Node { parent_id: Option<String>, children: Vec<Rc<RefCell<Node>>>, } impl Node { fn set_parent(&mut self, parent_id: &str) { self.parent_id.replace(parent_id.into()); } fn add_child(&mut self, child: Rc<RefCell<Node>>) { self.children.push(child); } } pub(crate) fn day06() { let input = File::open("data/day06.txt").expect("Failed to open input"); let buffered = BufReader::new(input); let lines = buffered.lines().map(|line| line.unwrap()); // Build our graph. let mut nodes: HashMap<String, Rc<RefCell<Node>>> = HashMap::new(); for line in lines { let centre = &line[..3]; let orbiter = &line[4..]; let centre_node = nodes .entry(centre.into()) .or_insert_with(|| Rc::new(RefCell::new(Node::default()))) .clone(); let orbiting_node = nodes .entry(orbiter.into()) .or_insert_with(|| Rc::new(RefCell::new(Node::default()))); centre_node.borrow_mut().add_child(orbiting_node.clone()); orbiting_node.borrow_mut().set_parent(centre); } // Find the root. let root = nodes.get("COM").expect("Failed to find centre of mass"); // Solve part one, via depth-first search. let mut total = 0; let mut stack = vec![(root.clone(), 0)]; while let Some((node, depth)) = stack.pop() { total += depth; for child in &node.borrow().children { stack.push((child.clone(), depth + 1)); } } println!("Part one answer is: {}", total); // Solve part two - the shortest path will take us up to our common parent and down again. // So find that common parent, and do the maths. let mut you_ancestors = get_ancestors(&nodes, "YOU"); let mut santa_ancestors = get_ancestors(&nodes, "SAN"); while you_ancestors.pop() == santa_ancestors.pop() {} let you_distance = you_ancestors.len() + 1; let santa_distance = santa_ancestors.len() + 1; let answer = you_distance + santa_distance; println!("Part two answer is: {}", answer); } fn get_ancestors(nodes: &HashMap<String, Rc<RefCell<Node>>>, id: &str) -> Vec<String> { let mut ancestors = vec![]; let mut node = nodes.get(id).expect("Failed to find node!"); while let Some(parent_id) = &node.borrow().parent_id { ancestors.push(parent_id.clone()); node = nodes.get(parent_id).expect("Failed to find parent node!"); } ancestors }
#[doc = "Register `RCC_MC_AHB5ENCLRR` reader"] pub type R = crate::R<RCC_MC_AHB5ENCLRR_SPEC>; #[doc = "Register `RCC_MC_AHB5ENCLRR` writer"] pub type W = crate::W<RCC_MC_AHB5ENCLRR_SPEC>; #[doc = "Field `GPIOZEN` reader - GPIOZEN"] pub type GPIOZEN_R = crate::BitReader; #[doc = "Field `GPIOZEN` writer - GPIOZEN"] pub type GPIOZEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CRYP1EN` reader - CRYP1EN"] pub type CRYP1EN_R = crate::BitReader; #[doc = "Field `CRYP1EN` writer - CRYP1EN"] pub type CRYP1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HASH1EN` reader - HASH1EN"] pub type HASH1EN_R = crate::BitReader; #[doc = "Field `HASH1EN` writer - HASH1EN"] pub type HASH1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RNG1EN` reader - RNG1EN"] pub type RNG1EN_R = crate::BitReader; #[doc = "Field `RNG1EN` writer - RNG1EN"] pub type RNG1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BKPSRAMEN` reader - BKPSRAMEN"] pub type BKPSRAMEN_R = crate::BitReader; #[doc = "Field `BKPSRAMEN` writer - BKPSRAMEN"] pub type BKPSRAMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - GPIOZEN"] #[inline(always)] pub fn gpiozen(&self) -> GPIOZEN_R { GPIOZEN_R::new((self.bits & 1) != 0) } #[doc = "Bit 4 - CRYP1EN"] #[inline(always)] pub fn cryp1en(&self) -> CRYP1EN_R { CRYP1EN_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - HASH1EN"] #[inline(always)] pub fn hash1en(&self) -> HASH1EN_R { HASH1EN_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - RNG1EN"] #[inline(always)] pub fn rng1en(&self) -> RNG1EN_R { RNG1EN_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 8 - BKPSRAMEN"] #[inline(always)] pub fn bkpsramen(&self) -> BKPSRAMEN_R { BKPSRAMEN_R::new(((self.bits >> 8) & 1) != 0) } } impl W { #[doc = "Bit 0 - GPIOZEN"] #[inline(always)] #[must_use] pub fn gpiozen(&mut self) -> GPIOZEN_W<RCC_MC_AHB5ENCLRR_SPEC, 0> { GPIOZEN_W::new(self) } #[doc = "Bit 4 - CRYP1EN"] #[inline(always)] #[must_use] pub fn cryp1en(&mut self) -> CRYP1EN_W<RCC_MC_AHB5ENCLRR_SPEC, 4> { CRYP1EN_W::new(self) } #[doc = "Bit 5 - HASH1EN"] #[inline(always)] #[must_use] pub fn hash1en(&mut self) -> HASH1EN_W<RCC_MC_AHB5ENCLRR_SPEC, 5> { HASH1EN_W::new(self) } #[doc = "Bit 6 - RNG1EN"] #[inline(always)] #[must_use] pub fn rng1en(&mut self) -> RNG1EN_W<RCC_MC_AHB5ENCLRR_SPEC, 6> { RNG1EN_W::new(self) } #[doc = "Bit 8 - BKPSRAMEN"] #[inline(always)] #[must_use] pub fn bkpsramen(&mut self) -> BKPSRAMEN_W<RCC_MC_AHB5ENCLRR_SPEC, 8> { BKPSRAMEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "This register is used to clear the peripheral clock enable bit If TZEN = , this register can only be modified in secure mode.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_mc_ahb5enclrr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_mc_ahb5enclrr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RCC_MC_AHB5ENCLRR_SPEC; impl crate::RegisterSpec for RCC_MC_AHB5ENCLRR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rcc_mc_ahb5enclrr::R`](R) reader structure"] impl crate::Readable for RCC_MC_AHB5ENCLRR_SPEC {} #[doc = "`write(|w| ..)` method takes [`rcc_mc_ahb5enclrr::W`](W) writer structure"] impl crate::Writable for RCC_MC_AHB5ENCLRR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets RCC_MC_AHB5ENCLRR to value 0"] impl crate::Resettable for RCC_MC_AHB5ENCLRR_SPEC { const RESET_VALUE: Self::Ux = 0; }
// Copyright 2020 <盏一 w@hidva.com> // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::access::ckpt::PendingFileOps; use crate::access::slru; use crate::guc; use crate::guc::GucState; use crate::utils::Xid; use crate::utils::{SessionState, WorkerState}; use crate::KB_BLCKSZ; use anyhow; use lru::LruCache; use std::cell::RefCell; use std::sync::atomic::Ordering::Relaxed; pub struct GlobalStateExt { d: slru::Slru, } impl GlobalStateExt { fn new(l2cache_size: usize, pending_ops: &'static PendingFileOps) -> GlobalStateExt { GlobalStateExt { d: slru::Slru::new( l2cache_size, slru::CommonData { pending_ops, dir: "kb_xact", }, ), } } } pub fn init(gucstate: &GucState, pending_ops: &'static PendingFileOps) -> GlobalStateExt { let clog_l2cache_size = guc::get_int(gucstate, guc::ClogL2cacheSize) as usize; GlobalStateExt::new(clog_l2cache_size, pending_ops) } #[derive(Copy, Clone)] pub struct WorkerStateExt { g: &'static GlobalStateExt, } type L1CacheT = LruCache<Xid, XidStatus>; thread_local! { static L1CACHE: RefCell<L1CacheT> = RefCell::new(LruCache::new(32)); } fn resize_l1cache(gucstate: &GucState) { let newsize = guc::get_int(gucstate, guc::ClogL1cacheSize) as usize; L1CACHE.with(|l1cache| { let cache = &mut l1cache.borrow_mut(); cache.resize(newsize); }) } fn u8_get_xid_status(byteval: u8, bidx: u64) -> XidStatus { let bshift = bidx * BITS_PER_XACT; ((byteval >> bshift) & XACT_BITMASK).into() } impl WorkerStateExt { pub fn new(g: &'static GlobalStateExt) -> WorkerStateExt { WorkerStateExt { g } } pub fn set_xid_status(&self, xid: Xid, status: XidStatus) -> anyhow::Result<()> { let xid = xid.get(); let byteno = xid_to_byte(xid); let bidx = xid_to_bidx(xid); let bshift = bidx * BITS_PER_XACT; let andbits = !(XACT_BITMASK << bshift); let orbits = (status as u8) << bshift; self.g.d.writable_load(xid_to_pageno(xid), |buff| { let byteval = &buff.0[byteno]; let mut state = byteval.load(Relaxed); loop { let newstate = (state & andbits) | orbits; let res = byteval.compare_exchange_weak(state, newstate, Relaxed, Relaxed); match res { Ok(_) => break, Err(s) => state = s, } } }) } fn get_xid_status(&self, cache: &mut L1CacheT, xid: Xid) -> anyhow::Result<XidStatus> { if let Some(&v) = cache.get(&xid) { return Ok(v); } let pageno = xid_to_pageno(xid.get()); let xidstatus = self.g.d.try_readonly_load(pageno, |buff| -> XidStatus { let byteno = xid_to_byte(xid.get()); let bidx = xid_to_bidx(xid.get()); return u8_get_xid_status(buff.0[byteno].load(Relaxed), bidx); })?; if xidstatus != XidStatus::InProgress { cache.put(xid, xidstatus); } return Ok(xidstatus); } pub fn xid_status(&self, xid: Xid) -> anyhow::Result<XidStatus> { L1CACHE.with(|l1cache| -> anyhow::Result<XidStatus> { let cache = &mut l1cache.borrow_mut(); self.get_xid_status(cache, xid) }) } } #[repr(u8)] #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum XidStatus { InProgress = 0x00, Committed, Aborted, } impl std::convert::From<u8> for XidStatus { fn from(val: u8) -> Self { match val { 0 => XidStatus::InProgress, 1 => XidStatus::Committed, 2 => XidStatus::Aborted, _ => panic!("u8 -> XidStatus failed. val={}", val), } } } const BITS_PER_XACT: u64 = 2; pub const XACTS_PER_BYTE: u64 = 4; const XACTS_PER_PAGE: u64 = KB_BLCKSZ as u64 * XACTS_PER_BYTE; const XACT_BITMASK: u8 = (1 << BITS_PER_XACT) - 1; const fn xid_to_pageno(xid: u64) -> slru::Pageno { xid / XACTS_PER_PAGE } const fn xid_to_pgidx(xid: u64) -> u64 { xid % XACTS_PER_PAGE } const fn xid_to_byte(xid: u64) -> usize { (xid_to_pgidx(xid) / XACTS_PER_BYTE) as usize } const fn xid_to_bidx(xid: u64) -> u64 { xid % XACTS_PER_BYTE } pub trait SessionExt { fn resize_clog_l1cache(&self); } impl SessionExt for SessionState { fn resize_clog_l1cache(&self) { resize_l1cache(&self.gucstate); } } pub trait WorkerExt { fn resize_clog_l1cache(&self); } impl WorkerExt for WorkerState { fn resize_clog_l1cache(&self) { resize_l1cache(&self.gucstate); } }
extern crate num; extern crate fnv; extern crate nock; use std::rc::Rc; use std::collections::HashMap; use nock::{Nock, Noun, NockError, NockResult, Shape, FromNoun}; use jet::Jet; mod jet; mod jets; /// An Urbit virtual machine. pub struct VM { jets: HashMap<Noun, jet::Jet>, } impl Nock for VM { fn call(&mut self, subject: &Noun, formula: &Noun) -> Option<NockResult> { if let Some(jet) = self.jets.get_mut(formula) { jet.calls += 1; if let Some(f) = jet.jet { return Some(f(subject)); } } None } fn hint(&mut self, subject: &Noun, hint: &Noun, c: &Noun) -> Result<(), NockError> { let (id, clue) = match hint.get() { Shape::Cell(ref p, ref q) => { (*p, try!(self.nock_on((*subject).clone(), (*q).clone()))) } Shape::Atom(_) => (hint, Noun::from(0u32)), }; // TODO: Handle other hint types than %fast. if String::from_noun(id).unwrap() == "fast" { let core = try!(self.nock_on((*subject).clone(), (*c).clone())); if let Ok((name, axis, hooks)) = parse_fast_clue(&clue) { if let Shape::Cell(ref battery, _) = core.get() { if !self.jets.contains_key(battery) { let jet = Jet::new(name, (*battery).clone(), axis, hooks); self.jets.insert((*battery).clone(), jet); } } else { return Err(NockError(format!("hint"))); } } else { // println!("Unparseable clue..."); } } Ok(()) } } impl VM { pub fn new() -> VM { VM { jets: HashMap::new() } } pub fn print_status(&self) { let mut total_count = 0; let mut jets: Vec<&Jet> = self.jets.iter().map(|(_, x)| x).collect(); jets.sort_by(|a, b| b.calls.cmp(&a.calls)); for jet in &jets { if jet.calls < 100 || (jet.calls as f32) / (total_count as f32) < 1e-6 { // Don't care about the little things println!(" ..."); break; } println!("{}{} called {} times", if jet.jet.is_some() { '*' } else { ' ' }, jet.name, jet.calls); total_count += jet.calls; } } } fn parse_fast_clue(clue: &Noun) -> Result<(String, u32, Vec<(String, Noun)>), NockError> { if let Some((ref name, ref axis_formula, ref hooks)) = clue.get_122() { let chum = try!(String::from_noun(name).map_err(|_| NockError(format!("hint")))); let axis = if let Shape::Cell(ref a, ref b) = axis_formula.get() { if let (Some(1), Some(0)) = (a.as_u32(), b.as_u32()) { 0 } else if let (Some(0), Some(axis)) = (a.as_u32(), b.as_u32()) { axis } else { return Err(NockError(format!("hint"))); } } else { return Err(NockError(format!("hint"))); }; let hooks: Vec<(String, Noun)> = try!(FromNoun::from_noun(hooks) .map_err(|_| NockError(format!("hint")))); Ok((chum, axis, hooks)) } else { Err(NockError(format!("hint"))) } } /// A human-readable hash version. pub fn symhash(noun: &Noun) -> String { fn proquint(buf: &mut String, mut b: u16) { const C: [char; 16] = ['b', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'z']; const V: [char; 4] = ['a', 'i', 'o', 'u']; buf.push(C[(b % 16) as usize]); b >>= 4; buf.push(V[(b % 4) as usize]); b >>= 2; buf.push(C[(b % 16) as usize]); b >>= 4; buf.push(V[(b % 4) as usize]); b >>= 2; buf.push(C[(b % 16) as usize]); } let mut hash = noun.mug(); let mut ret = String::new(); proquint(&mut ret, (hash % 0xFFFF) as u16); hash >>= 16; ret.push('-'); proquint(&mut ret, (hash % 0xFFFF) as u16); ret } /// Unpack the data of an Urbit pillfile into a Nock noun. pub fn unpack_pill(mut buf: Vec<u8>) -> jet::JetResult<Noun> { // Guarantee that the buffer is made of 32-bit chunks. while buf.len() % 4 != 0 { buf.push(0); } jets::cue(Rc::new(buf)) } #[cfg(test)] mod test { use nock::Noun; #[test] fn test_read_pill() { use super::unpack_pill; let noun: Noun = "[18.446.744.073.709.551.616 8 [1 0] 8 [1 6 [5 [0 7] 4 0 6] [0 6] 9 2 [0 \ 2] [4 0 6] 0 7] 9 2 0 1]" .parse() .expect("Nock parse error"); let pill: &[u8] = &[0x01, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0xc1, 0x62, 0x83, 0x60, 0x71, 0xd8, 0x85, 0x5b, 0xe2, 0x87, 0x99, 0xd8, 0x0d, 0xc1, 0x1a, 0x24, 0x43, 0x96, 0xc8, 0x86, 0x10, 0x1d, 0xc2, 0x32, 0x48, 0x86, 0x4c, 0x06]; let unpacked = unpack_pill(pill.to_vec()).expect("Pill unpack failed"); assert_eq!(noun, unpacked); } #[test] fn test_cue_stack() { use super::unpack_pill; let noun: Noun = "[1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]" .parse() .expect("Nock parse error"); let pill: &[u8] = "qffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffj" .as_bytes(); let unpacked = unpack_pill(pill.to_vec()).expect("Pill unpack failed"); assert_eq!(noun, unpacked); } }
use assembly_data::{ fdb::{ common::{self, Latin1String}, core, store, }, xml::{ common::{expect_decl, expect_end}, database::{ expect_column_or_end_columns, expect_columns, expect_database, expect_row_or_end_rows, expect_rows, expect_table, ValueType, }, quick::Reader, }, }; use color_eyre::eyre::WrapErr; use std::{ collections::HashMap, fs::File, io::{BufReader, BufWriter}, path::PathBuf, time::Instant, }; use structopt::StructOpt; #[derive(Debug, StructOpt)] /// Converts an XML database into a FDB file struct Options { /// The XML database file src: PathBuf, /// The FDB file dest: PathBuf, } fn main() -> color_eyre::Result<()> { color_eyre::install()?; let opts = Options::from_args(); let src_file = File::open(&opts.src) .wrap_err_with(|| format!("Failed to open input file '{}'", opts.src.display()))?; let reader = BufReader::new(src_file); let dest_file = File::create(&opts.dest) .wrap_err_with(|| format!("Failed to crate output file '{}'", opts.dest.display()))?; let mut dest_out = BufWriter::new(dest_file); println!("Copying file, this may take a few seconds..."); let start = Instant::now(); let mut dest_db = store::Database::new(); let mut xml = Reader::from_reader(reader); let xml = xml.trim_text(true); let mut buf = Vec::new(); let buf = &mut buf; expect_decl(xml, buf)?; let db_name = expect_database(xml, buf)?.unwrap(); println!("Loading database: '{}'", db_name); while let Some(table_name) = expect_table(xml, buf)? { println!("table '{}'", table_name); let mut dest_table = store::Table::new(128); expect_columns(xml, buf)?; let mut col_map = HashMap::new(); while let Some(col) = expect_column_or_end_columns(xml, buf)? { let data_type = match col.r#type { ValueType::Bit => common::ValueType::Boolean, ValueType::Float => common::ValueType::Float, ValueType::Real => common::ValueType::Float, ValueType::Int => common::ValueType::Integer, ValueType::BigInt => common::ValueType::BigInt, ValueType::SmallInt => common::ValueType::Integer, ValueType::TinyInt => common::ValueType::Integer, ValueType::Binary => common::ValueType::Text, ValueType::VarBinary => common::ValueType::Text, ValueType::Char => common::ValueType::Text, ValueType::VarChar => common::ValueType::Text, ValueType::NChar => common::ValueType::Text, ValueType::NVarChar => common::ValueType::Text, ValueType::NText => common::ValueType::VarChar, ValueType::Text => common::ValueType::VarChar, ValueType::Image => common::ValueType::VarChar, ValueType::DateTime => common::ValueType::BigInt, ValueType::Xml => common::ValueType::VarChar, ValueType::Null => common::ValueType::Nothing, }; if col_map.is_empty() { // first col if data_type == common::ValueType::Float { let id_col_name = format!("{}ID", table_name); dest_table.push_column( Latin1String::encode(&id_col_name), common::ValueType::Integer, ); col_map.insert(id_col_name, col_map.len()); } } dest_table.push_column(Latin1String::encode(&col.name), data_type); col_map.insert(col.name, col_map.len()); } expect_rows(xml, buf)?; let col_count = dest_table.columns().len(); let mut auto_inc = 0; while let Some(row) = expect_row_or_end_rows(xml, buf, true)? { let mut fields = vec![core::Field::Nothing; col_count]; let mut pk = None; for (key, src_value) in row { let col_index = *col_map.get(&key).unwrap(); let value_type = dest_table.columns().get(col_index).unwrap().value_type(); let dest_value = match value_type { common::ValueType::Nothing => core::Field::Nothing, common::ValueType::Integer => core::Field::Integer(src_value.parse().unwrap()), common::ValueType::Float => core::Field::Float(src_value.parse().unwrap()), common::ValueType::Text => core::Field::Text(src_value), common::ValueType::Boolean => core::Field::Boolean(&src_value != "0"), common::ValueType::BigInt => core::Field::BigInt(src_value.parse().unwrap()), common::ValueType::VarChar => core::Field::VarChar(src_value), }; if col_index == 0 { match &dest_value { core::Field::Integer(i) => { pk = Some((*i % 128) as usize); } core::Field::BigInt(i) => { pk = Some((*i % 128) as usize); } core::Field::Text(text) => { let lat1 = Latin1String::encode(text); pk = Some((lat1.hash() % 128) as usize); } core::Field::VarChar(var_char) => { let lat1 = Latin1String::encode(var_char); pk = Some((lat1.hash() % 128) as usize); } _ => panic!("Can't use {:?} as PK", &dest_value), } } fields[col_index] = dest_value; } let pk = if let Some(pk) = pk { pk } else { auto_inc += 1; fields[0] = core::Field::Integer(auto_inc); (auto_inc as usize) % 128 }; dest_table.push_row(pk, &fields); } expect_end(xml, buf, "table")?; dest_db.push_table(Latin1String::encode(&table_name), dest_table); } dest_db .write(&mut dest_out) .wrap_err("Failed to write copied database")?; let duration = start.elapsed(); println!( "Finished in {}.{}s", duration.as_secs(), duration.subsec_millis() ); Ok(()) }
#![allow(dead_code)] mod utils; mod p001_multiples; mod p002_even_fib; mod p003_largest_prime; mod p004_largest_palindrome; mod p005_smallest_mult;
use std::str::FromStr; use std::fmt::{Debug, Formatter}; #[derive(PartialEq, Eq, Debug, Clone)] pub struct Entry { pub lhs: String, pub rhs: String, } pub struct SideMissingError {} impl Debug for SideMissingError { fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { f.write_str("One side missing (marker ' = ' not found)") } } impl FromStr for Entry { type Err = SideMissingError; fn from_str(s: &str) -> Result<Entry, <Entry as FromStr>::Err> { // split let sides: Vec<&str> = s.split(" = ").collect(); // check that there are two sides if sides.len() < 2 { return Err(SideMissingError{}); } Ok(Entry { lhs: String::from(sides[0]), rhs: String::from(sides[1]), }) } }
#[doc = "Register `DDRPHYC_DLLGCR` reader"] pub type R = crate::R<DDRPHYC_DLLGCR_SPEC>; #[doc = "Register `DDRPHYC_DLLGCR` writer"] pub type W = crate::W<DDRPHYC_DLLGCR_SPEC>; #[doc = "Field `DRES` reader - DRES"] pub type DRES_R = crate::FieldReader; #[doc = "Field `DRES` writer - DRES"] pub type DRES_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `IPUMP` reader - IPUMP"] pub type IPUMP_R = crate::FieldReader; #[doc = "Field `IPUMP` writer - IPUMP"] pub type IPUMP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `TESTEN` reader - TESTEN"] pub type TESTEN_R = crate::BitReader; #[doc = "Field `TESTEN` writer - TESTEN"] pub type TESTEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DTC` reader - DTC"] pub type DTC_R = crate::FieldReader; #[doc = "Field `DTC` writer - DTC"] pub type DTC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `ATC` reader - ATC"] pub type ATC_R = crate::FieldReader; #[doc = "Field `ATC` writer - ATC"] pub type ATC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `TESTSW` reader - TESTSW"] pub type TESTSW_R = crate::BitReader; #[doc = "Field `TESTSW` writer - TESTSW"] pub type TESTSW_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MBIAS` reader - MBIAS"] pub type MBIAS_R = crate::FieldReader; #[doc = "Field `MBIAS` writer - MBIAS"] pub type MBIAS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `SBIAS2_0` reader - SBIAS2_0"] pub type SBIAS2_0_R = crate::FieldReader; #[doc = "Field `SBIAS2_0` writer - SBIAS2_0"] pub type SBIAS2_0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `BPS200` reader - BPS200"] pub type BPS200_R = crate::BitReader; #[doc = "Field `BPS200` writer - BPS200"] pub type BPS200_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SBIAS5_3` reader - SBIAS5_3"] pub type SBIAS5_3_R = crate::FieldReader; #[doc = "Field `SBIAS5_3` writer - SBIAS5_3"] pub type SBIAS5_3_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `FDTRMSL` reader - FDTRMSL"] pub type FDTRMSL_R = crate::FieldReader; #[doc = "Field `FDTRMSL` writer - FDTRMSL"] pub type FDTRMSL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `LOCKDET` reader - LOCKDET"] pub type LOCKDET_R = crate::BitReader; #[doc = "Field `LOCKDET` writer - LOCKDET"] pub type LOCKDET_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DLLRSVD2` reader - DLLRSVD2"] pub type DLLRSVD2_R = crate::FieldReader; #[doc = "Field `DLLRSVD2` writer - DLLRSVD2"] pub type DLLRSVD2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bits 0:1 - DRES"] #[inline(always)] pub fn dres(&self) -> DRES_R { DRES_R::new((self.bits & 3) as u8) } #[doc = "Bits 2:4 - IPUMP"] #[inline(always)] pub fn ipump(&self) -> IPUMP_R { IPUMP_R::new(((self.bits >> 2) & 7) as u8) } #[doc = "Bit 5 - TESTEN"] #[inline(always)] pub fn testen(&self) -> TESTEN_R { TESTEN_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bits 6:8 - DTC"] #[inline(always)] pub fn dtc(&self) -> DTC_R { DTC_R::new(((self.bits >> 6) & 7) as u8) } #[doc = "Bits 9:10 - ATC"] #[inline(always)] pub fn atc(&self) -> ATC_R { ATC_R::new(((self.bits >> 9) & 3) as u8) } #[doc = "Bit 11 - TESTSW"] #[inline(always)] pub fn testsw(&self) -> TESTSW_R { TESTSW_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bits 12:19 - MBIAS"] #[inline(always)] pub fn mbias(&self) -> MBIAS_R { MBIAS_R::new(((self.bits >> 12) & 0xff) as u8) } #[doc = "Bits 20:22 - SBIAS2_0"] #[inline(always)] pub fn sbias2_0(&self) -> SBIAS2_0_R { SBIAS2_0_R::new(((self.bits >> 20) & 7) as u8) } #[doc = "Bit 23 - BPS200"] #[inline(always)] pub fn bps200(&self) -> BPS200_R { BPS200_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bits 24:26 - SBIAS5_3"] #[inline(always)] pub fn sbias5_3(&self) -> SBIAS5_3_R { SBIAS5_3_R::new(((self.bits >> 24) & 7) as u8) } #[doc = "Bits 27:28 - FDTRMSL"] #[inline(always)] pub fn fdtrmsl(&self) -> FDTRMSL_R { FDTRMSL_R::new(((self.bits >> 27) & 3) as u8) } #[doc = "Bit 29 - LOCKDET"] #[inline(always)] pub fn lockdet(&self) -> LOCKDET_R { LOCKDET_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bits 30:31 - DLLRSVD2"] #[inline(always)] pub fn dllrsvd2(&self) -> DLLRSVD2_R { DLLRSVD2_R::new(((self.bits >> 30) & 3) as u8) } } impl W { #[doc = "Bits 0:1 - DRES"] #[inline(always)] #[must_use] pub fn dres(&mut self) -> DRES_W<DDRPHYC_DLLGCR_SPEC, 0> { DRES_W::new(self) } #[doc = "Bits 2:4 - IPUMP"] #[inline(always)] #[must_use] pub fn ipump(&mut self) -> IPUMP_W<DDRPHYC_DLLGCR_SPEC, 2> { IPUMP_W::new(self) } #[doc = "Bit 5 - TESTEN"] #[inline(always)] #[must_use] pub fn testen(&mut self) -> TESTEN_W<DDRPHYC_DLLGCR_SPEC, 5> { TESTEN_W::new(self) } #[doc = "Bits 6:8 - DTC"] #[inline(always)] #[must_use] pub fn dtc(&mut self) -> DTC_W<DDRPHYC_DLLGCR_SPEC, 6> { DTC_W::new(self) } #[doc = "Bits 9:10 - ATC"] #[inline(always)] #[must_use] pub fn atc(&mut self) -> ATC_W<DDRPHYC_DLLGCR_SPEC, 9> { ATC_W::new(self) } #[doc = "Bit 11 - TESTSW"] #[inline(always)] #[must_use] pub fn testsw(&mut self) -> TESTSW_W<DDRPHYC_DLLGCR_SPEC, 11> { TESTSW_W::new(self) } #[doc = "Bits 12:19 - MBIAS"] #[inline(always)] #[must_use] pub fn mbias(&mut self) -> MBIAS_W<DDRPHYC_DLLGCR_SPEC, 12> { MBIAS_W::new(self) } #[doc = "Bits 20:22 - SBIAS2_0"] #[inline(always)] #[must_use] pub fn sbias2_0(&mut self) -> SBIAS2_0_W<DDRPHYC_DLLGCR_SPEC, 20> { SBIAS2_0_W::new(self) } #[doc = "Bit 23 - BPS200"] #[inline(always)] #[must_use] pub fn bps200(&mut self) -> BPS200_W<DDRPHYC_DLLGCR_SPEC, 23> { BPS200_W::new(self) } #[doc = "Bits 24:26 - SBIAS5_3"] #[inline(always)] #[must_use] pub fn sbias5_3(&mut self) -> SBIAS5_3_W<DDRPHYC_DLLGCR_SPEC, 24> { SBIAS5_3_W::new(self) } #[doc = "Bits 27:28 - FDTRMSL"] #[inline(always)] #[must_use] pub fn fdtrmsl(&mut self) -> FDTRMSL_W<DDRPHYC_DLLGCR_SPEC, 27> { FDTRMSL_W::new(self) } #[doc = "Bit 29 - LOCKDET"] #[inline(always)] #[must_use] pub fn lockdet(&mut self) -> LOCKDET_W<DDRPHYC_DLLGCR_SPEC, 29> { LOCKDET_W::new(self) } #[doc = "Bits 30:31 - DLLRSVD2"] #[inline(always)] #[must_use] pub fn dllrsvd2(&mut self) -> DLLRSVD2_W<DDRPHYC_DLLGCR_SPEC, 30> { DLLRSVD2_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "DDRPHYC DDR global control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrphyc_dllgcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ddrphyc_dllgcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DDRPHYC_DLLGCR_SPEC; impl crate::RegisterSpec for DDRPHYC_DLLGCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ddrphyc_dllgcr::R`](R) reader structure"] impl crate::Readable for DDRPHYC_DLLGCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`ddrphyc_dllgcr::W`](W) writer structure"] impl crate::Writable for DDRPHYC_DLLGCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DDRPHYC_DLLGCR to value 0x0373_7000"] impl crate::Resettable for DDRPHYC_DLLGCR_SPEC { const RESET_VALUE: Self::Ux = 0x0373_7000; }
pub trait Drawable { fn draw(&self, dpy: &glium::Display, target: &mut glium::Frame); }
extern crate rgsl; use rgsl::{RngType}; use std::f64; #[warn(unused_variables)] fn main() { rgsl::RngType::env_setup(); let t : RngType = rgsl::rng::default(); let r = rgsl::Rng::new(&t).unwrap(); println!("Iter x y"); let mut x = 0.0; let mut y = 0.0; for i in 0..50000 { for thin in 0..1000 { x = rgsl::randist::gamma::gamma(&r, 3.0, 1.0 / (y*y + 4.0)); y = 1.0/(x+1.0) + rgsl::randist::gaussian::gaussian(&r, 1.0/(2.0*x+2.0).sqrt()); } println!("{} {} {}", i, x, y); } }
use std::path::PathBuf; use config::{Config, ConfigError, File}; use serde::{Deserialize, Serialize}; /// Configuration for Wikipedia data sources. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Data { /// Path to the wikipedia dump. pub dump: PathBuf, /// Path to the wikipedia dump's indices. pub index: PathBuf, } /// Configuration for Wikipedia data sources. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Indices { #[serde(default = "Indices::default_indices_path")] pub pages: PathBuf, #[serde(default = "Indices::default_template_indices_path")] pub templates: PathBuf, } impl Indices { pub fn default_indices_path() -> PathBuf { "indices".into() } pub fn default_template_indices_path() -> PathBuf { "template_indices".into() } } impl Default for Indices { fn default() -> Self { Indices { pages: Indices::default_indices_path(), templates: Indices::default_template_indices_path(), } } } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct SearchIndex { pub index_dir: PathBuf, } /// Configuration for anchor summary files. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Anchors { #[serde(default = "Anchors::default_anchors_path")] pub anchors: PathBuf, #[serde(default = "Anchors::default_anchor_counts_path")] pub anchor_counts: PathBuf, } impl Anchors { pub fn default_anchors_path() -> PathBuf { "anchors.tsv".into() } pub fn default_anchor_counts_path() -> PathBuf { "anchor_counts.tsv".into() } } /// Settings aggregate. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Settings { pub data: Data, #[serde(default)] pub indices: Indices, #[serde(default = "Settings::default_templates_path")] pub templates: PathBuf, pub anchors: Anchors, pub search_index: SearchIndex, } impl Settings { pub fn new(path: &str) -> Result<Self, ConfigError> { let mut settings = Config::new(); settings.merge(File::with_name(path))?; settings.try_into() } pub fn default_templates_path() -> PathBuf { "templates.xml".into() } }
use std::thread; use std::env; use std::collections::HashMap; use std::process; use std::fs; use std::sync::{Mutex, RwLock}; use std::sync::mpsc; use std::sync::Arc; use std::time; use std::path::Path; use rusqlite::{params, Connection, Result}; use rusqlite::NO_PARAMS; use strsim::{levenshtein}; use regex::Regex; use serenity::{ model::{channel::Message, gateway::Ready, id::ChannelId, user::CurrentUser}, prelude::*, utils::MessageBuilder, http::AttachmentType, }; pub fn strip_stylization(s: &str) -> String { let re = Regex::new(r"[!?. …',’-]*").unwrap(); let sr = s.to_lowercase(); let sr = re.replace_all(&sr, "").into_owned().to_string(); sr } pub struct Handler { states: Arc<Vec<State>>, statusMap: Arc<Mutex<HashMap<u64, Option<std::sync::mpsc::Sender<Message>>>>>, db: Arc<Mutex<Connection>>, } impl Handler { pub fn new() -> Handler { let conn = Connection::open("attrs.db").unwrap(); Handler { states: Arc::new(Handler::gen_state()), statusMap: Arc::new(Mutex::new(HashMap::new())), db: Arc::new(Mutex::new(conn)), } } fn gen_state() -> Vec<State> { let mut args = env::args(); args.next(); let flow_file = args.next().unwrap_or_else(|| { eprintln!("flow file not specified"); process::exit(1); }); println!("Reading from {}", flow_file); let contents = fs::read_to_string(flow_file) .unwrap_or_else(|e| { eprintln!("error reading flow file: {:?}", e); process::exit(1); }); let mut states = Vec::new(); let commands = contents.split("\n").map(|v| v.trim().to_owned()).filter(|v| v != ""); let command_matcher = Regex::new(r"^([a-zA-Z_]*?)!(?:\[?)(.*?)(?:\]?)\+([0-9.]*)$").unwrap(); for c in commands { let matched = command_matcher.captures_iter(&c).next().unwrap(); let cmd_type: String = matched.get(1).unwrap().as_str().to_owned(); let data: String = matched.get(2).unwrap().as_str().to_owned(); let timeout: String = matched.get(3).unwrap().as_str().to_owned(); let timeout: f32 = timeout.parse().unwrap(); states.push(match cmd_type.as_str() { "R" => State::Display(data, timeout), "IMG" => State::DisplayImage(data, timeout), "T" => State::Trigger(Requirement::new(data), timeout), "GO_OFFLINE" => State::GoOffline(timeout), "GO_ONLINE" => State::GoOnline(timeout), &_ => { eprintln!("Invalid command: {}", cmd_type); process::exit(1); } }); } states.push(State::End); states } } impl EventHandler for Handler { fn message(&self, ctx: Context, msg: Message) { let entry = &mut self.statusMap.lock().unwrap(); let entry = entry.entry(msg.channel_id.0).or_insert(None); let mut timeout = 0.0; if let None = entry { let (continue_or_not, t) = (&self.states[0]).check(&msg.content); if continue_or_not { timeout = t; let mut i = 0; let states = self.states.clone(); let db = self.db.clone(); let statusMap = self.statusMap.clone(); let mut channel_id = msg.channel_id; let guard = db.lock().unwrap(); let original_user = format!("u{}", msg.author.id.0.to_string()); guard.execute( &format!( "create table if not exists {} ( id TEXT PRIMARY KEY, val TEXT NOT NULL )" , original_user), NO_PARAMS, ).unwrap(); std::mem::drop(guard); let (tx, rx) = mpsc::channel::<Message>(); tx.send(msg); *entry = Some(tx); let var_def = regex::Regex::new(";;(.*?);;").unwrap(); let var_val = regex::Regex::new("<(.*?)>").unwrap(); thread::spawn(move || { loop { match &states[i] { State::Trigger(req, t) => { let mut msg = rx.recv().unwrap_or_else(|e| { process::exit(1); }); let mut required = vec![]; for m in var_def.captures_iter(&req.original()) { required.push(m.get(1).unwrap().as_str().to_owned()); } if required.len() > 0 { let mut success = false; while !success { while msg.author.id.0 == ctx.cache.read().user.id.0 { msg = rx.recv().unwrap_or_else(|e| { process::exit(1); }); } let mut new_pat = Regex::new(&var_def.replace_all(&regex::escape(&req.original()), "(.*?)").into_owned().to_string()); let new_pat = match new_pat { Ok(p) => p, Err(e) => { return; } }; let guard = db.lock().unwrap(); let mut number_of_matches = 0; for (c, n) in new_pat.captures_iter(&msg.content).zip(required.iter()) { number_of_matches += 1; let c = c.get(1).unwrap().as_str().to_owned(); guard.execute( &format!( "INSERT OR IGNORE INTO {} VALUES (?, ?)" , original_user), params![n, &c], ).unwrap(); guard.execute( &format!( "UPDATE {} SET val=? WHERE id=?" , original_user), params![&c, n], ).unwrap(); } std::mem::drop(guard); if required.len() == number_of_matches { success = true; } } } else { while (msg.author.id.0 == ctx.cache.read().user.id.0) || !req.check(&msg.content) { msg = rx.recv().unwrap_or_else(|e| { process::exit(1); }); } } timeout = *t; }, State::Display(s, t) => { let guard = db.lock().unwrap(); let s = var_val.replace_all(&s, |caps: &regex::Captures| { let mut stmt = guard.prepare( &format!( "SELECT val FROM {} WHERE id=?" , original_user) ).unwrap(); let mut replace_with = String::from(""); let attr_iter = stmt.query_map(params![caps.get(1).unwrap().as_str()], |row| { row.get(0) }).unwrap(); for attr in attr_iter { replace_with = attr.unwrap(); } replace_with }); std::mem::drop(guard); if let Err(why) = channel_id.say(&ctx.http, &s) { eprintln!("Error sending reply: {:?}", why); } timeout = *t; }, State::DisplayImage(u, t) => { let res = channel_id.send_message(&ctx.http, |m| { m.add_file(AttachmentType::Path(Path::new(u))); m }); if let Err(why) = res { eprintln!("Error sending reply: {:?}", why); } timeout = *t; }, State::GoOffline(t) => { ctx.invisible(); timeout = *t; }, State::GoOnline(t) => { ctx.online(); timeout = *t; }, State::End => { let entry = &mut statusMap.lock().unwrap(); let entry = entry.entry(channel_id.0).or_insert(None); *entry = None; break; } } i += 1; thread::sleep(time::Duration::from_millis((1000.0 * timeout).round() as u64)); } }); } } else if let Some(tx) = entry { tx.send(msg); } } fn ready(&self, _: Context, ready: Ready) { println!("What is this Discord thingy?"); } } pub enum State { Trigger(Requirement, f32), Display(String, f32), DisplayImage(String, f32), GoOffline(f32), GoOnline(f32), End, } impl State { fn check(&self, input: &str) -> (bool, f32) { match self { State::Trigger(req, t) => (req.check(input), *t), State::Display(_s, t) => (true, *t), State::DisplayImage(_s, t) => (true, *t), State::GoOffline(t) => (true, *t), State::GoOnline(t) => (true, *t), State::End => (true, 0.0) } } } pub struct Requirement { original: String, original_stripped: String } impl Requirement { fn new(original: String) -> Requirement { Requirement { original_stripped: strip_stylization(&original), original, } } fn original(&self) -> String { self.original.clone() } fn check(&self, input: &str) -> bool { let similarity = levenshtein(&strip_stylization(input), &self.original_stripped); let diff = similarity as f32 / self.original_stripped.len() as f32; diff < 0.3 } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ //! An example that tracks thread pedigree using local state use clap::Parser; use reverie::syscalls::Syscall; use reverie::Error; use reverie::Guest; use reverie::Pid; use reverie::Tool; use reverie_util::pedigree::Pedigree; use reverie_util::CommonToolArguments; use serde::Deserialize; use serde::Serialize; use tracing::debug; use tracing::trace; // TODO: Add handle pedigree forking, initialization, etc. to tool. // This tool is NOT FUNCTIONAL in its current state. #[derive(Debug, Serialize, Deserialize, Default, Clone)] struct PedigreeLocal(Pedigree); #[reverie::tool] impl Tool for PedigreeLocal { type GlobalState = (); type ThreadState = PedigreeLocal; fn new(pid: Pid, _cfg: &()) -> Self { debug!("[pedigree] initialize pedigree for pid {}", pid); PedigreeLocal(Pedigree::new()) } fn init_thread_state( &self, _tid: Pid, parent: Option<(Pid, &Self::ThreadState)>, ) -> Self::ThreadState { if let Some((_, state)) = parent { let mut parent = state.clone(); let child = parent.0.fork_mut(); trace!("child pedigree: {:?}", child); PedigreeLocal(child) } else { PedigreeLocal(Pedigree::new()) } } async fn handle_syscall_event<T: Guest<Self>>( &self, guest: &mut T, syscall: Syscall, ) -> Result<i64, Error> { match syscall { #[cfg(target_arch = "x86_64")] Syscall::Fork(_) | Syscall::Vfork(_) => self.handle_fork(syscall, guest).await, Syscall::Clone(_) => self.handle_fork(syscall, guest).await, Syscall::Getpid(_) | Syscall::Getppid(_) | Syscall::Gettid(_) | Syscall::Getpgid(_) => { let pid = guest.inject(syscall).await?; let vpid = nix::unistd::Pid::try_from(&self.0).unwrap(); trace!("getpid returned {:?} vpid: {:?}", pid, vpid); Ok(pid) } Syscall::Setpgid(_) => { panic!("[pedigree] setpgid is not allowed."); } _ => guest.tail_inject(syscall).await, } } } impl PedigreeLocal { async fn handle_fork( &self, syscall: Syscall, guest: &mut impl Guest<Self>, ) -> Result<i64, Error> { let retval = guest.inject(syscall).await?; let pedigree = guest.thread_state_mut().0.fork_mut(); trace!( "got new pedigree: {:?} => {:x?}", pedigree, nix::unistd::Pid::try_from(&pedigree) ); Ok(retval) } } #[tokio::main] async fn main() -> Result<(), Error> { let args = CommonToolArguments::from_args(); let log_guard = args.init_tracing(); let tracer = reverie_ptrace::TracerBuilder::<PedigreeLocal>::new(args.into()) .spawn() .await?; let (status, _global_state) = tracer.wait().await?; drop(log_guard); // Flush logs before exiting. status.raise_or_exit() }
use std::collections::HashMap; static URL_PREFIX: &str = "short.ly/"; static ASCII_LOWER: [char; 26] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ]; fn generate_short_link_postfix(generated_links: usize) -> String { let mut remainder: usize = generated_links; let mut modulo: usize = remainder % 26; let mut div: usize = remainder / 26; let mut result: String = ASCII_LOWER[modulo].to_string(); loop { if div == 0 { return result; } else { remainder = div - 1; modulo = remainder % 26; div = remainder / 26; let mut temp = ASCII_LOWER[modulo].to_string(); temp.push_str(&result); result = temp; } } } struct UrlShortener { url_database_sl: HashMap<String, String>, url_database_ls: HashMap<String, String>, generated_links: usize, } impl UrlShortener { fn new() -> Self { Self { url_database_sl: HashMap::new(), url_database_ls: HashMap::new(), generated_links: 0, } } fn shorten(&mut self, long_url: &str) -> String { match self.url_database_ls.get(long_url) { Some(short_url) => short_url.to_string(), None => { let prefix: String = URL_PREFIX.to_string().clone(); let postfix: String = generate_short_link_postfix(self.generated_links); let short_url: String = prefix + &postfix; self.generated_links = self.generated_links + 1; self.url_database_sl.insert(short_url.clone(), long_url.to_string()); self.url_database_ls.insert(long_url.to_string(), short_url.clone()); short_url } } } fn redirect(&self, short_url: &str) -> String { self.url_database_sl[short_url].to_string() } } fn main() { let mut url_shortener = UrlShortener::new(); let test = url_shortener.shorten("www.benkio.github.io/"); println!("simple test: {}", test); for i in 0..1000 { let result: String = generate_short_link_postfix(i); println!("{}: {}", i, result); } } #[cfg(test)] mod tests { use super::UrlShortener; use crate::assert_valid_short_url; use crate::generate_short_link_postfix; #[test] fn generate_short_link_postfix_test() { let mut result: String = generate_short_link_postfix(0); assert_eq!(result, "a"); result = generate_short_link_postfix(25); assert_eq!(result, "z"); result = generate_short_link_postfix(26); assert_eq!(result, "aa"); result = generate_short_link_postfix(27); assert_eq!(result, "ab"); result = generate_short_link_postfix(702); assert_eq!(result, "aaa"); } #[test] fn two_different_urls() { let mut url_shortener = UrlShortener::new(); let short_url_1 = url_shortener.shorten("https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e"); assert_valid_short_url!(&short_url_1); let short_url_2 = url_shortener.shorten("https://www.codewars.com/kata/5efae11e2d12df00331f91a6"); assert_valid_short_url!(&short_url_2); assert_eq!(url_shortener.redirect(&short_url_1), "https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e"); assert_eq!(url_shortener.redirect(&short_url_2), "https://www.codewars.com/kata/5efae11e2d12df00331f91a6"); } #[test] fn same_urls() { let mut url_shortener = UrlShortener::new(); let short_url_1 = url_shortener.shorten("https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f"); assert_valid_short_url!(&short_url_1); let short_url_2 = url_shortener.shorten("https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f"); assert_valid_short_url!(&short_url_2); assert_eq!(short_url_1, short_url_2, "Should work with the same long URLs"); assert_eq!( url_shortener.redirect(&short_url_1), "https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f", "{} should redirect to https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f", &short_url_1, ); } #[macro_export] macro_rules! assert_valid_short_url { ($url:expr) => { assert!( $url.starts_with("short.ly/"), "URL format is incorrect: should start with \"short.ly/\", got: {}", $url, ); assert!( $url.len() < 14, "URL format is incorrect: length should be < 14 characters, got: {}", $url, ); // As the URL contains "short.ly/", we can safely index using [9..] assert!( $url[9..].bytes().all(|b| b.is_ascii_lowercase()), "URL format is incorrect: should contain lowercase letters at the end, got: {}", $url, ); } } }
use crate::{ auth::UserDetail, server::{ controlchan::{error::ControlChanError, middleware::ControlChanMiddleware}, session::SharedSession, {Command, Event, Reply, ReplyCode, SessionState}, }, storage::{Metadata, StorageBackend}, }; use crate::server::controlchan::commands::Opt; use async_trait::async_trait; // AuthMiddleware ensures the user is authenticated before he can do much else. pub struct AuthMiddleware<Storage, User, Next> where User: UserDetail + 'static, Storage: StorageBackend<User> + 'static, Storage::Metadata: Metadata, Next: ControlChanMiddleware, { pub session: SharedSession<Storage, User>, pub next: Next, } #[async_trait] impl<Storage, User, Next> ControlChanMiddleware for AuthMiddleware<Storage, User, Next> where User: UserDetail + 'static, Storage: StorageBackend<User> + 'static, Storage::Metadata: Metadata, Next: ControlChanMiddleware, { async fn handle(&mut self, event: Event) -> Result<Reply, ControlChanError> { match event { // internal messages and the below commands are exempt from auth checks. Event::InternalMsg(_) | Event::Command(Command::Help) | Event::Command(Command::User { .. }) | Event::Command(Command::Pass { .. }) | Event::Command(Command::Auth { .. }) | Event::Command(Command::Prot { .. }) | Event::Command(Command::Pbsz { .. }) | Event::Command(Command::Feat) | Event::Command(Command::Noop) | Event::Command(Command::Opts { option: Opt::Utf8 { .. } }) | Event::Command(Command::Quit) => self.next.handle(event).await, _ => { let session_state = async { let session = self.session.lock().await; session.state } .await; if session_state != SessionState::WaitCmd { Ok(Reply::new(ReplyCode::NotLoggedIn, "Please authenticate")) } else { self.next.handle(event).await } } } } }
#![crate_type="staticlib"] #![allow(unused_features)] #![feature(alloc)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(core_slice_ext)] #![feature(no_std)] #![feature(vec_push_all)] #![feature(vec_resize)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; #[macro_use] extern crate redox; use application::main; #[path="APPLICATION_PATH"] mod application; use redox::*; use redox::syscall::sys_exit; #[inline(never)] unsafe fn _start_stack(stack: *const u32) { let argc = ptr::read(stack); let mut args: Vec<String> = Vec::new(); for i in 0..argc as isize { let arg = ptr::read(stack.offset(1 + i)) as *const u8; if arg as usize > 0 { let mut utf8: Vec<u8> = Vec::new(); for j in 0..4096 /* Max arg length */ { let b = ptr::read(arg.offset(j)); if b == 0 { break; }else{ utf8.push(b); } } args.push(String::from_utf8_unchecked(utf8)); } else { args.push(String::new()); } } args_init(args); console_init(); main(); console_destroy(); args_destroy(); sys_exit(0); } #[cold] #[no_mangle] pub unsafe fn _start() { let stack: *const u32; asm!("" : "={esp}"(stack) : : "memory" : "intel", "volatile"); _start_stack(stack); }
extern crate env_logger; extern crate lambda_punter; #[macro_use] extern crate log; #[macro_use] extern crate clap; use std::process; use clap::{Arg, SubCommand}; use lambda_punter::{client, game, solvers}; use lambda_punter::game::GameState; fn main() { env_logger::init().unwrap(); match run() { Ok(()) => info!("graceful shutdown"), Err(e) => { error!("fatal error: {:?}", e); process::exit(1); }, } } #[derive(Debug)] enum Error { MissingParameter(&'static str), AlwaysPassSolver(client::Error<()>), NearestSolver(client::Error<()>), LinkMinesSolver(client::Error<()>), GNSolver(client::Error<()>), } fn run() -> Result<(), Error> { let matches = app_from_crate!() .arg(Arg::with_name("hello-name") .display_order(1) .short("n") .long("hello-name") .value_name("NAME") .help("welcome name for Handshake packet") .default_value("skobochka") .takes_value(true)) .subcommand(SubCommand::with_name("always_pass") .display_order(1) .about("solvers::always_pass")) .subcommand(SubCommand::with_name("nearest") .display_order(2) .about("solvers::nearest")) .subcommand(SubCommand::with_name("link_mines") .display_order(3) .about("solvers::link_mines")) .subcommand(SubCommand::with_name("gn") .display_order(4) .about("solvers::gn")) .get_matches(); let hello_name = matches.value_of("hello-name") .ok_or(Error::MissingParameter("hello-name"))?; info!("initializing as [ {} ]", hello_name); if let Some(..) = matches.subcommand_matches("always_pass") { debug!("using solvers::always_pass"); proceed_with_solver(hello_name, solvers::always_pass::AlwaysPassGameStateBuilder, Error::AlwaysPassSolver) } else if let Some(..) = matches.subcommand_matches("nearest") { debug!("using solvers::nearest"); proceed_with_solver(hello_name, solvers::nearest::NearestGameStateBuilder, Error::NearestSolver) } else if let Some(..) = matches.subcommand_matches("link_mines") { debug!("using solvers::link_mines"); proceed_with_solver(hello_name, solvers::link_mines::LinkMinesGameStateBuilder, Error::LinkMinesSolver) } else if let Some(..) = matches.subcommand_matches("gn") { debug!("using solvers::gn"); proceed_with_solver(hello_name, solvers::gn::GNGameStateBuilder, Error::GNSolver) } else { debug!("using solvers::link_mines"); proceed_with_solver(hello_name, solvers::link_mines::LinkMinesGameStateBuilder, Error::LinkMinesSolver) } } fn proceed_with_solver<GB, EF>( hello_name: &str, gs_builder: GB, err_map: EF) -> Result<(), Error> where GB: game::GameStateBuilder, EF: Fn(client::Error<<GB::GameState as game::GameState>::Error>) -> Error { let maybe_results = client::run_offline(hello_name, gs_builder) .map_err(err_map)?; info!("all done"); if let Some((scores, game_state)) = maybe_results { let my_punter = game_state.get_punter(); info!("Game over! Total server scores:"); for score in scores { info!(" Punter: {}{}, score: {}", score.punter, if score.punter == my_punter { " (it's me)" } else { "" }, score.score); } } Ok(()) }
/* * Rustパターン(記法)。 * CreatedAt: 2019-07-07 */ struct Point { x: i32, y: i32, } fn main() { let points = vec![ Point { x: 0, y: 0 }, Point { x: 1, y: 5 }, Point { x: 10, y: -3 }, ]; let sum_of_squares: i32 = points .iter() .map(|&Point { x, y }| x * x + y * y) .sum(); }
extern crate dcpu16; use dcpu16::VirtualMachine; use dcpu16::hardware::Clock; const disasm:[u16;27] = [0x7c01, 0x0030, 0x7fc1, 0x0020, 0x1000, 0x7803, 0x1000, 0xc413, 0x7f81, 0x0019, 0xacc1, 0x7c01, 0x2000, 0x22c1, 0x2000, 0x88c3, 0x84d3, 0xbb81, 0x9461, 0x7c20, 0x0017, 0x7f81, 0x0019, 0x946f, 0x6381, 0xeb81, 0x0000]; fn main() { let mut vm = VirtualMachine::new() .attach_hardware(Box::new(Clock::new())) .load_program(&disasm.to_vec(), 0); vm.step(); vm.step(); println!("{:?}", vm.get_registers()); }
fn main() { variable_test(100, 5, 0); let f: fn(i32, i32) -> i32 = plus_number_100; println!("4+5+100={}", f(4, 5)); loop_test(5); } fn plus_number_100(x: i32, y: i32) -> i32 { x + y + 100 } fn variable_test(x: i32, y: i32, z: i32) { if x >= 100 { println!("invalid number."); } println!("z={}", z); { let mut z = 0; println!("z={}", z); z = 10; println!("z={}", z); } println!("x={}, y={}, z={}", x, y, z); } fn loop_test(mut x: i32) { let mut done = false; while !done { x += x - 3; println!("{}", x); if x % 5 == 0 { done = true; } } }
//! A set of files that have been read from disk. use std::error::Error; use std::fs::File; use std::io::{Error as IOError, Read}; use std::path::Path; use vec_map::{VecMap, Iter}; use base::ParseTree; use base::tokens::TokenPos; use languages::LanguageMethods; /// A set of files that have been read from disk. /// /// Each file is given an index after it has been read, starting from zero and /// incrementing. These indices can then be used to refer to individual files /// later on. pub struct LoadedFiles { /// The index to give to the next loaded file. index: usize, /// Collection of files that are currently in memory. files: VecMap<LoadedFile> } impl LoadedFiles { /// Create a new, empty set. pub fn empty() -> LoadedFiles { LoadedFiles { index: 0, files: VecMap::new() } } pub fn load(&mut self, filename: &str, methods: LanguageMethods) -> Result<(), Box<Error>> { let contents = try!(read_file(filename)); let tokens = (*methods.tokenise)(&contents[..]); let root = (*methods.parse)(&tokens[..]); self.files.insert(self.index, LoadedFile { filename: filename.into(), tokens: tokens, parse_tree: root }); self.index += 1; Ok(()) } /// Try to find a file by its ID. pub fn find_by_id(&self, id: usize) -> Option<&LoadedFile> { self.files.get(&id) } /// Try to find a file by its ID, returning a mutable reference. pub fn find_by_id_mut(&mut self, id: usize) -> Option<&mut LoadedFile> { self.files.get_mut(&id) } /// Return an iterator over every currently-loaded file. pub fn iter(&self) -> Iter<LoadedFile> { self.files.iter() } } pub fn read_file(filename: &str) -> Result<String, IOError> { let mut file = try!(File::open(&Path::new(&filename))); let mut contents = String::new(); try!(file.read_to_string(&mut contents)); Ok(contents) } pub struct LoadedFile { pub filename: String, pub tokens: Vec<TokenPos>, pub parse_tree: Box<ParseTree>, }
use crate::util::misc::*; #[derive(Debug, Clone, Copy)] struct CpuidRet { eax: u32, ebx: u32, ecx: u32, edx: u32, } fn cpuid(n: u32) -> CpuidRet { let eax: u32; let ebx: u32; let ecx: u32; let edx: u32; unsafe { asm!("push rbx", "cpuid", "mov edi, ebx", "pop rbx", inout("eax") n => eax, out("edi") ebx, out("ecx") ecx, out("edx") edx, options(nomem, nostack)); } CpuidRet { eax, ebx, ecx, edx, } } pub fn has_apic() -> bool { get_bits(cpuid(1).edx as usize, 9..10) == 1 } pub fn apic_id() -> u8 { get_bits(cpuid(1).ebx as usize, 24..32) as u8 } pub fn core_clock_freq() -> u32 { cpuid(0x15).ecx }
#[path="events.rs"] mod events; #[path="weather.rs"] mod weather; mod lib; use std::thread; use envfile; use envfile::EnvFile; use std::io; use std::path::Path; fn main()-> io::Result<()> { //https://docs.rs/envfile/0.2.1/envfile/ let envfile = EnvFile::new(&Path::new(".env"))?; let weather_api_secret = envfile.get("APP_ID").expect("failed to unwrap APP_ID").to_owned(); let event_api_secret = envfile.get("PREDICT_SECRET").expect("failed to unwrap PREDICT_SECRET").to_owned(); println!("24"); let events_thread = thread::Builder::new() .name(String::from("Event Thread")) .spawn(||{events::events(event_api_secret)}).expect("Even thread failed to spawn"); println!("28"); let weather_thread = thread::Builder::new() .name(String::from("Event Thread")) .spawn(||{weather::forecast(weather_api_secret)}).expect("Even thread failed to spawn"); let forecast = weather_thread.join().unwrap(); println!("Weather {:?}", forecast.weather.details.description); let events = events_thread.join().expect("failed to join event thread"); let all_events:Vec<&String> = events.results.iter().map(|x| { &x.title }).collect(); let cloudy_events:Vec<&&String> = all_events.iter().filter(|x| !x.contains("outdoor") && x.len() < 25 ).collect(); if forecast.weather.details.description.contains("clouds"){ println!(" here are some Potential event for a cloudy day: {:?}", cloudy_events); } else { println!("here are some potential events:{:?}", all_events); } Ok(()) }
#[doc = "Register `DMAMUX_RGSR` reader"] pub type R = crate::R<DMAMUX_RGSR_SPEC>; #[doc = "Field `OF0` reader - OF0"] pub type OF0_R = crate::BitReader; #[doc = "Field `OF1` reader - OF1"] pub type OF1_R = crate::BitReader; #[doc = "Field `OF2` reader - OF2"] pub type OF2_R = crate::BitReader; #[doc = "Field `OF3` reader - OF3"] pub type OF3_R = crate::BitReader; #[doc = "Field `OF4` reader - OF4"] pub type OF4_R = crate::BitReader; #[doc = "Field `OF5` reader - OF5"] pub type OF5_R = crate::BitReader; #[doc = "Field `OF6` reader - OF6"] pub type OF6_R = crate::BitReader; #[doc = "Field `OF7` reader - OF7"] pub type OF7_R = crate::BitReader; impl R { #[doc = "Bit 0 - OF0"] #[inline(always)] pub fn of0(&self) -> OF0_R { OF0_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - OF1"] #[inline(always)] pub fn of1(&self) -> OF1_R { OF1_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - OF2"] #[inline(always)] pub fn of2(&self) -> OF2_R { OF2_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - OF3"] #[inline(always)] pub fn of3(&self) -> OF3_R { OF3_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - OF4"] #[inline(always)] pub fn of4(&self) -> OF4_R { OF4_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - OF5"] #[inline(always)] pub fn of5(&self) -> OF5_R { OF5_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - OF6"] #[inline(always)] pub fn of6(&self) -> OF6_R { OF6_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - OF7"] #[inline(always)] pub fn of7(&self) -> OF7_R { OF7_R::new(((self.bits >> 7) & 1) != 0) } } #[doc = "DMAMUX request generator interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmamux_rgsr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DMAMUX_RGSR_SPEC; impl crate::RegisterSpec for DMAMUX_RGSR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`dmamux_rgsr::R`](R) reader structure"] impl crate::Readable for DMAMUX_RGSR_SPEC {} #[doc = "`reset()` method sets DMAMUX_RGSR to value 0"] impl crate::Resettable for DMAMUX_RGSR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use clap::{clap_app, crate_version}; use std::sync::Arc; #[cfg(feature = "gui-support")] use minifb::{Key, Window, WindowOptions}; use weekend_tracer_rs::{ bvh::BVH, camera::Camera, hittable::Hittable, renderer, scenes, vec3, vec3::Vec3, }; // Some defaults #[cfg(debug_assertions)] const WIDTH: usize = 100; #[cfg(not(debug_assertions))] const WIDTH: usize = 400; #[cfg(debug_assertions)] const HEIGHT: usize = 100; #[cfg(not(debug_assertions))] const HEIGHT: usize = 400; const SAMPLES_PER_PIXEL: usize = 100; const MAX_REFLECTION_DEPTH: usize = 50; const BACKGROUND_COLOR: Vec3 = vec3!(); fn main() { #[allow(unused_mut)] let mut app = clap_app!(weekend_tracer_rs => (version: crate_version!()) (author: "Johann M. Barnard <johann.b@telus.net>") (about: "A simple ray-tracing renderer. If no options are passed, the \ image is outputted in some image format to \ <OUTPUT_FILE> (e.g. image.png, image.JPEG, etc...). The output \ format is deduced from the file name extension. JPEG, PNG, \ GIF, BMP, TIFF, ICO, and PPM (the binary version) formats are \ supported.") (@group image_output +multiple => (@arg OUTPUT_FILE: required_unless[gui compute_pi compute_int_x_squared] "The file to be outputted to.") (@arg ppm: -p --ppm "Output to an ASCII PPM file (e.g. test.ppm, image.ppm, etc...).") ) (@arg dimensions: -d --dimensions <WIDTH> <HEIGHT> !required "Set the dimensions for the render. 300x300 by default.") (@arg samples: -s --samples <SAMPLES_PER_PIXEL> !required "Sets the number of samples to be taken per pixel.") (@arg reflections: -r --max_reflection_depth <DEPTH> !required "Sets the maximum reflection depth.") (@arg compute_pi: --compute_pi conflicts_with[dimensions samples reflections image_output gui compute_int_x_squared] "Computes pi (because why not?).") (@arg compute_int_x_squared: --compute_int_x_squared conflicts_with[dimensions samples reflections image_output gui compute_pi] "Computes the integral of x^2 between x=0 and x=2.") ); #[cfg(feature = "gui-support")] { app = app.arg( clap::Arg::with_name("gui") .short("g") .long("gui") .help("Render to a window instead of to stdout.") .conflicts_with("image_output"), ); } let matches = app.get_matches(); if matches.is_present("compute_pi") { compute_pi(); } if matches.is_present("compute_int_x_squared") { compute_int_x_squared(); } let dimensions = if let Some(v) = matches.values_of("dimensions") { v.map(str::parse::<usize>) .map(|x| { x.unwrap_or_else(|e| { panic!( "<WIDTH> or <HEIGHT> could not be parsed into a positive integer!\n{}", e ) }) }) .collect::<Vec<_>>() } else { vec![WIDTH, HEIGHT] }; let width = dimensions[0]; let height = dimensions[1]; let aspect_ratio = (width as f32) / (height as f32); let samples_per_pixel = matches .value_of("samples") .unwrap_or(&SAMPLES_PER_PIXEL.to_string()) .parse::<usize>() .unwrap_or_else(|e| { panic!( "Could not parse <SAMPLES_PER_PIXEL> into a positive integer!\n{}", e ) }); let max_reflection_depth = matches .value_of("reflections") .unwrap_or(&MAX_REFLECTION_DEPTH.to_string()) .parse::<usize>() .unwrap_or_else(|e| panic!("Could not parse <DEPTH> into a positive integer!\n{}", e)); let (world, lights, camera) = scenes::cornell_box(aspect_ratio); let lights = Arc::new(lights); let bvh = BVH::new(world.objects, 0.0, 1.0); // let lookfrom = vec3!(478.0, 278.0, -600.0); // let lookat = vec3!(278.0, 278.0, 0.0); // let vup = vec3!(0.0, 1.0); // let dist_to_focus = (vec3!(260.0, 150.0, 45.0) - lookfrom).length(); // let aperture = 0.5; // let vfov = 40.0; // degrees // let camera = Camera::new( // lookfrom, // lookat, // vup, // vfov, // aspect_ratio, // aperture, // dist_to_focus, // 0.0, // 1.0, // ); if matches.is_present("gui") { #[cfg(feature = "gui-support")] gui_output( bvh, lights, camera, width, height, samples_per_pixel, max_reflection_depth, ); } else { // Calling .unwrap() is safe here because we require that the OUTPUT_FILE // is present if --gui/-g is not present. let output_file = matches.value_of("OUTPUT_FILE").unwrap(); if matches.is_present("ppm") { ppm_output( output_file, bvh, lights, camera, width, height, samples_per_pixel, max_reflection_depth, ) .unwrap(); } else { image_output( output_file, bvh, lights, camera, width, height, samples_per_pixel, max_reflection_depth, ); } } } /// Render to a simple cross-platform window using the `minifb` crate. #[cfg(feature = "gui-support")] fn gui_output( bvh: BVH, lights: Arc<dyn Hittable>, camera: Camera, width: usize, height: usize, samples_per_pixel: usize, max_reflection_depth: usize, ) { let buffer: Vec<u32> = renderer::convert_to_argb(renderer::render( width, height, samples_per_pixel, max_reflection_depth, bvh, lights, camera, BACKGROUND_COLOR, )) .collect(); let mut window = Window::new( "weekend-tracer-rs - ESC to exit", width, height, WindowOptions::default(), ) .unwrap_or_else(|e| panic!("{}", e)); // Limit to max ~60 fps update rate window.limit_update_rate(Some(std::time::Duration::from_micros(16600))); while window.is_open() && !window.is_key_down(Key::Escape) { window.update_with_buffer(&buffer, width, height).unwrap(); } } /// Render to an ASCII PPM `.ppm` file. #[allow(clippy::too_many_arguments)] fn ppm_output( filename: &str, bvh: BVH, lights: Arc<dyn Hittable>, camera: Camera, width: usize, height: usize, samples_per_pixel: usize, max_reflection_depth: usize, ) -> std::io::Result<()> { let output = renderer::render( width, height, samples_per_pixel, max_reflection_depth, bvh, lights, camera, BACKGROUND_COLOR, ) .into_iter() .map(|(r, g, b)| format!("{} {} {}", r, g, b)) .fold(format!("P3\n{} {}\n255\n", width, height), |s, pixel| { s + &pixel + "\n" }); std::fs::write(filename, output) } /// Render to some arbritrary image file type. Whatever the `image` crate /// supports. #[allow(clippy::too_many_arguments)] fn image_output( filename: &str, bvh: BVH, lights: Arc<dyn Hittable>, camera: Camera, width: usize, height: usize, samples_per_pixel: usize, max_reflection_depth: usize, ) { let rendered = renderer::render( width, height, samples_per_pixel, max_reflection_depth, bvh, lights, camera, BACKGROUND_COLOR, ) .into_iter() .map(|(r, g, b)| vec![r as u8, g as u8, b as u8]) .flatten() .collect::<Vec<_>>(); image::save_buffer( filename, &rendered[..], width as u32, height as u32, image::ColorType::Rgb8, ) .unwrap(); } /// Compute pi (for reasons) fn compute_pi() -> ! { use rand::prelude::*; let mut rng = thread_rng(); let mut inside_circle: u64 = 0; let mut inside_circle_stratified: u64 = 0; let sqrt_n = 10_000; for i in 0..sqrt_n { for j in 0..sqrt_n { let mut x: f64 = rng.gen_range(-1.0, 1.0); let mut y: f64 = rng.gen_range(-1.0, 1.0); if x * x + y * y < 1.0 { inside_circle += 1; } x = 2.0 * ((i as f64 + rng.gen::<f64>()) / sqrt_n as f64) - 1.0; y = 2.0 * ((j as f64 + rng.gen::<f64>()) / sqrt_n as f64) - 1.0; if x * x + y * y < 1.0 { inside_circle_stratified += 1; } } } let n = (sqrt_n * sqrt_n) as f64; println!( "\ Regular estimate of Pi = {:.12}\n\ Stratified estimate of Pi = {:.12}", 4.0 * (inside_circle as f64) / n, 4.0 * (inside_circle_stratified as f64) / n, ); std::process::exit(0) } /// Computes the integral of x^2 between x=0.0 and x=2.0. fn compute_int_x_squared() -> ! { use rand::prelude::*; let mut rng = thread_rng(); #[inline] fn pdf(_x: f64) -> f64 { 0.5 } let n = 1_000_000; let mut sum = 0.0; for _ in 0..n { let x = rng.gen_range(0.0_f64, 2.0_f64).sqrt(); sum += x * x / pdf(x); } println!( " 2 I = ∫ x^2 dx ≈ {:.12} 0", sum / (n as f64), ); std::process::exit(0) }
/*fn saludar_usuario(){ println!("Hola, desde una funcion"); }*/ fn suma(numero_uno: i32, numero_dos: i32) -> i32 { numero_uno + numero_dos } fn factorial(numero: u32) -> u32 { if numero == 1 { numero } else { factorial(numero - 1) * numero } } fn main() { let resultado = factorial(5); println!("El factorial es: {}", resultado); /*saludar_usuario(); let resultado = suma(10, 20); println!("El resultado es: {}", resultado);*/ }
use std::fs; use std::fs::{File, OpenOptions}; use std::io; use std::io::prelude::*; use std::os::unix; use std::path::Path; // `% echo s > path`の簡単な実装 fn echo(s: &str, path: &Path) -> io::Result<()> { let mut f = try!(File::create(path)); f.write_all(s.as_bytes()) } fn main() { println!("`echo hello > a/b.txt`"); // 上のmatchは`unwrap_or_else`をメソッドを用いて簡略化できる。 echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); }
use thiserror::Error; use solana_program::program_error::ProgramError; #[derive(Error, Debug, Copy, Clone)] pub enum StateError { /// Invalid instruction #[error("Invalid Instruction")] InvalidInstruction, #[error("Not Rent Exent")] NotRentExempt, #[error("NFT Mismach Mint of Token Account")] NFTMismatchMint, #[error("Expected Amount Mismatch")] ExpectedAmountMismatch } impl From<StateError> for ProgramError { fn from(e: StateError) -> Self { ProgramError::Custom(e as u32) } }
extern crate dependency; fn main() { dependency::f(); }
use crate::paths::{hooks_dir, storage_dir}; use anyhow::{anyhow, Result}; use std::fs; use std::path::Path; use std::process::Command; /// Represents callable scripts which can be triggered at certain times pub enum Hook { PreLoad, PostSave, } impl Hook { fn name(&self) -> String { match *self { Self::PreLoad => "pre_load".to_string(), Self::PostSave => "post_save".to_string(), } } } /// Represents events which can trigger hooks #[derive(Debug)] pub enum HookEvent { NewEntry, ListEntries, ShowEntry, EditEntry, RemoveEntry, } impl HookEvent { fn name(&self) -> String { match *self { Self::NewEntry => "new_entry".to_string(), Self::ListEntries => "list_entries".to_string(), Self::ShowEntry => "show_entry".to_string(), Self::EditEntry => "edit_entry".to_string(), Self::RemoveEntry => "remove_entry".to_string(), } } } pub fn run_hook(hook: &Hook, event: &HookEvent) -> Result<()> { let path = Path::new(&hooks_dir()?) .join(hook.name()) .display() .to_string(); if fs::metadata(&path).is_ok() { println!("Running {} hook", hook.name()); let storage_dir = storage_dir()?; let output = Command::new(path) .args(&[event.name()]) .current_dir(storage_dir) .output()?; let stdout = String::from_utf8(output.stdout)?; let stderr = String::from_utf8(output.stderr)?; for line in stdout.lines() { println!("{}: {}", hook.name(), line); } for line in stderr.lines() { println!("{}: {}", hook.name(), line); } if !output.status.success() { anyhow!("{} hook failed", hook.name()); } } Ok(()) }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Timerx Control Register"] pub timacr: TIMACR, #[doc = "0x04 - Timerx Interrupt Status Register"] pub timaisr: TIMAISR, #[doc = "0x08 - Timerx Interrupt Clear Register"] pub timaicr: TIMAICR, #[doc = "0x0c - TIMxDIER5"] pub timadier5: TIMADIER5, #[doc = "0x10 - Timerx Counter Register"] pub cntar: CNTAR, #[doc = "0x14 - Timerx Period Register"] pub perar: PERAR, #[doc = "0x18 - Timerx Repetition Register"] pub repar: REPAR, #[doc = "0x1c - Timerx Compare 1 Register"] pub cmp1ar: CMP1AR, #[doc = "0x20 - Timerx Compare 1 Compound Register"] pub cmp1car: CMP1CAR, #[doc = "0x24 - Timerx Compare 2 Register"] pub cmp2ar: CMP2AR, #[doc = "0x28 - Timerx Compare 3 Register"] pub cmp3ar: CMP3AR, #[doc = "0x2c - Timerx Compare 4 Register"] pub cmp4ar: CMP4AR, #[doc = "0x30 - Timerx Capture 1 Register"] pub cpt1ar: CPT1AR, #[doc = "0x34 - Timerx Capture 2 Register"] pub cpt2ar: CPT2AR, #[doc = "0x38 - Timerx Deadtime Register"] pub dtar: DTAR, #[doc = "0x3c - Timerx Output1 Set Register"] pub seta1r: SETA1R, #[doc = "0x40 - Timerx Output1 Reset Register"] pub rsta1r: RSTA1R, #[doc = "0x44 - Timerx Output2 Set Register"] pub seta2r: SETA2R, #[doc = "0x48 - Timerx Output2 Reset Register"] pub rsta2r: RSTA2R, #[doc = "0x4c - Timerx External Event Filtering Register 1"] pub eefar1: EEFAR1, #[doc = "0x50 - Timerx External Event Filtering Register 2"] pub eefar2: EEFAR2, #[doc = "0x54 - TimerA Reset Register"] pub rstar: RSTAR, #[doc = "0x58 - Timerx Chopper Register"] pub chpar: CHPAR, #[doc = "0x5c - Timerx Capture 2 Control Register"] pub cpt1acr: CPT1ACR, #[doc = "0x60 - CPT2xCR"] pub cpt2acr: CPT2ACR, #[doc = "0x64 - Timerx Output Register"] pub outar: OUTAR, #[doc = "0x68 - Timerx Fault Register"] pub fltar: FLTAR, } #[doc = "TIMACR (rw) register accessor: Timerx Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timacr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`timacr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timacr`] module"] pub type TIMACR = crate::Reg<timacr::TIMACR_SPEC>; #[doc = "Timerx Control Register"] pub mod timacr; #[doc = "TIMAISR (r) register accessor: Timerx Interrupt Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timaisr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timaisr`] module"] pub type TIMAISR = crate::Reg<timaisr::TIMAISR_SPEC>; #[doc = "Timerx Interrupt Status Register"] pub mod timaisr; #[doc = "TIMAICR (w) register accessor: Timerx Interrupt Clear Register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`timaicr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timaicr`] module"] pub type TIMAICR = crate::Reg<timaicr::TIMAICR_SPEC>; #[doc = "Timerx Interrupt Clear Register"] pub mod timaicr; #[doc = "TIMADIER5 (rw) register accessor: TIMxDIER5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timadier5::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`timadier5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timadier5`] module"] pub type TIMADIER5 = crate::Reg<timadier5::TIMADIER5_SPEC>; #[doc = "TIMxDIER5"] pub mod timadier5; #[doc = "CNTAR (rw) register accessor: Timerx Counter Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cntar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cntar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cntar`] module"] pub type CNTAR = crate::Reg<cntar::CNTAR_SPEC>; #[doc = "Timerx Counter Register"] pub mod cntar; #[doc = "PERAR (rw) register accessor: Timerx Period Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`perar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`perar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`perar`] module"] pub type PERAR = crate::Reg<perar::PERAR_SPEC>; #[doc = "Timerx Period Register"] pub mod perar; #[doc = "REPAR (rw) register accessor: Timerx Repetition Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`repar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`repar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`repar`] module"] pub type REPAR = crate::Reg<repar::REPAR_SPEC>; #[doc = "Timerx Repetition Register"] pub mod repar; #[doc = "CMP1AR (rw) register accessor: Timerx Compare 1 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp1ar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cmp1ar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp1ar`] module"] pub type CMP1AR = crate::Reg<cmp1ar::CMP1AR_SPEC>; #[doc = "Timerx Compare 1 Register"] pub mod cmp1ar; #[doc = "CMP1CAR (rw) register accessor: Timerx Compare 1 Compound Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp1car::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cmp1car::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp1car`] module"] pub type CMP1CAR = crate::Reg<cmp1car::CMP1CAR_SPEC>; #[doc = "Timerx Compare 1 Compound Register"] pub mod cmp1car; #[doc = "CMP2AR (rw) register accessor: Timerx Compare 2 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp2ar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cmp2ar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp2ar`] module"] pub type CMP2AR = crate::Reg<cmp2ar::CMP2AR_SPEC>; #[doc = "Timerx Compare 2 Register"] pub mod cmp2ar; #[doc = "CMP3AR (rw) register accessor: Timerx Compare 3 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp3ar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cmp3ar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp3ar`] module"] pub type CMP3AR = crate::Reg<cmp3ar::CMP3AR_SPEC>; #[doc = "Timerx Compare 3 Register"] pub mod cmp3ar; #[doc = "CMP4AR (rw) register accessor: Timerx Compare 4 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp4ar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cmp4ar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp4ar`] module"] pub type CMP4AR = crate::Reg<cmp4ar::CMP4AR_SPEC>; #[doc = "Timerx Compare 4 Register"] pub mod cmp4ar; #[doc = "CPT1AR (r) register accessor: Timerx Capture 1 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt1ar::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt1ar`] module"] pub type CPT1AR = crate::Reg<cpt1ar::CPT1AR_SPEC>; #[doc = "Timerx Capture 1 Register"] pub mod cpt1ar; #[doc = "CPT2AR (r) register accessor: Timerx Capture 2 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt2ar::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt2ar`] module"] pub type CPT2AR = crate::Reg<cpt2ar::CPT2AR_SPEC>; #[doc = "Timerx Capture 2 Register"] pub mod cpt2ar; #[doc = "DTAR (rw) register accessor: Timerx Deadtime Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dtar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dtar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dtar`] module"] pub type DTAR = crate::Reg<dtar::DTAR_SPEC>; #[doc = "Timerx Deadtime Register"] pub mod dtar; #[doc = "SETA1R (rw) register accessor: Timerx Output1 Set Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seta1r::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`seta1r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`seta1r`] module"] pub type SETA1R = crate::Reg<seta1r::SETA1R_SPEC>; #[doc = "Timerx Output1 Set Register"] pub mod seta1r; #[doc = "RSTA1R (rw) register accessor: Timerx Output1 Reset Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rsta1r::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rsta1r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rsta1r`] module"] pub type RSTA1R = crate::Reg<rsta1r::RSTA1R_SPEC>; #[doc = "Timerx Output1 Reset Register"] pub mod rsta1r; #[doc = "SETA2R (rw) register accessor: Timerx Output2 Set Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seta2r::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`seta2r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`seta2r`] module"] pub type SETA2R = crate::Reg<seta2r::SETA2R_SPEC>; #[doc = "Timerx Output2 Set Register"] pub mod seta2r; #[doc = "RSTA2R (rw) register accessor: Timerx Output2 Reset Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rsta2r::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rsta2r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rsta2r`] module"] pub type RSTA2R = crate::Reg<rsta2r::RSTA2R_SPEC>; #[doc = "Timerx Output2 Reset Register"] pub mod rsta2r; #[doc = "EEFAR1 (rw) register accessor: Timerx External Event Filtering Register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eefar1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`eefar1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eefar1`] module"] pub type EEFAR1 = crate::Reg<eefar1::EEFAR1_SPEC>; #[doc = "Timerx External Event Filtering Register 1"] pub mod eefar1; #[doc = "EEFAR2 (rw) register accessor: Timerx External Event Filtering Register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eefar2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`eefar2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eefar2`] module"] pub type EEFAR2 = crate::Reg<eefar2::EEFAR2_SPEC>; #[doc = "Timerx External Event Filtering Register 2"] pub mod eefar2; #[doc = "RSTAR (rw) register accessor: TimerA Reset Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rstar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rstar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rstar`] module"] pub type RSTAR = crate::Reg<rstar::RSTAR_SPEC>; #[doc = "TimerA Reset Register"] pub mod rstar; #[doc = "CHPAR (rw) register accessor: Timerx Chopper Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`chpar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`chpar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`chpar`] module"] pub type CHPAR = crate::Reg<chpar::CHPAR_SPEC>; #[doc = "Timerx Chopper Register"] pub mod chpar; #[doc = "CPT1ACR (rw) register accessor: Timerx Capture 2 Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt1acr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpt1acr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt1acr`] module"] pub type CPT1ACR = crate::Reg<cpt1acr::CPT1ACR_SPEC>; #[doc = "Timerx Capture 2 Control Register"] pub mod cpt1acr; #[doc = "CPT2ACR (rw) register accessor: CPT2xCR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt2acr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpt2acr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt2acr`] module"] pub type CPT2ACR = crate::Reg<cpt2acr::CPT2ACR_SPEC>; #[doc = "CPT2xCR"] pub mod cpt2acr; #[doc = "OUTAR (rw) register accessor: Timerx Output Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`outar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`outar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`outar`] module"] pub type OUTAR = crate::Reg<outar::OUTAR_SPEC>; #[doc = "Timerx Output Register"] pub mod outar; #[doc = "FLTAR (rw) register accessor: Timerx Fault Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fltar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fltar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fltar`] module"] pub type FLTAR = crate::Reg<fltar::FLTAR_SPEC>; #[doc = "Timerx Fault Register"] pub mod fltar;
/* chapter 4 syntax and semantics copy types */ fn main() { let a = 5; let b = double(a); println!("{}", a); println!("{}", b); } fn double(n: i32) -> i32 { n * 2 } // output should be: /* 5 10 */
use crate::globalconstants::*; use crate::operationtype::*; use std::fmt::Display; pub struct PlayfairConfiguration { pub unused_char: char, pub replace_char_for_unused_char: char, pub surrogate_char: char, pub key: String, pub operation_type: OperationType, } impl PlayfairConfiguration { pub fn new() -> Self { PlayfairConfiguration { unused_char: UNUSED_CHAR, replace_char_for_unused_char: REPLACE_CHAR_FOR_UNUSED_CHAR, surrogate_char: CHAR_SURROGATE, key: String::new(), operation_type: OperationType::Decrypt, } } pub fn is_encrypt(&self) -> bool { self.operation_type == OperationType::Encrypt } pub fn is_decrypt(&self) -> bool { !self.is_encrypt() } } impl Display for PlayfairConfiguration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { write!( f, "(unused_char='{}', replace_char_for_unused_char='{}', surrogate_char='{}', key='{}', operation_type='{:?}')", self.unused_char, self.replace_char_for_unused_char, self.surrogate_char, self.key, self.operation_type ) } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Interrupt and Status Register"] pub lptim_isr: LPTIM_ISR, #[doc = "0x04 - Interrupt Clear Register"] pub lptim_icr: LPTIM_ICR, #[doc = "0x08 - Interrupt Enable Register"] pub lptim_ier: LPTIM_IER, #[doc = "0x0c - Configuration Register"] pub lptim_cfgr: LPTIM_CFGR, #[doc = "0x10 - Control Register"] pub lptim_cr: LPTIM_CR, #[doc = "0x14 - Compare Register"] pub lptim_cmp: LPTIM_CMP, #[doc = "0x18 - Autoreload Register"] pub lptim_arr: LPTIM_ARR, #[doc = "0x1c - Counter Register"] pub lptim_cnt: LPTIM_CNT, _reserved8: [u8; 0x04], #[doc = "0x24 - LPTIM configuration register 2"] pub lptim_cfgr2: LPTIM_CFGR2, } #[doc = "LPTIM_ISR (r) register accessor: Interrupt and Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_isr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_isr`] module"] pub type LPTIM_ISR = crate::Reg<lptim_isr::LPTIM_ISR_SPEC>; #[doc = "Interrupt and Status Register"] pub mod lptim_isr; #[doc = "LPTIM_ICR (w) register accessor: Interrupt Clear Register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`lptim_icr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_icr`] module"] pub type LPTIM_ICR = crate::Reg<lptim_icr::LPTIM_ICR_SPEC>; #[doc = "Interrupt Clear Register"] pub mod lptim_icr; #[doc = "LPTIM_IER (rw) register accessor: Interrupt Enable Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_ier::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`lptim_ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_ier`] module"] pub type LPTIM_IER = crate::Reg<lptim_ier::LPTIM_IER_SPEC>; #[doc = "Interrupt Enable Register"] pub mod lptim_ier; #[doc = "LPTIM_CFGR (rw) register accessor: Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_cfgr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`lptim_cfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_cfgr`] module"] pub type LPTIM_CFGR = crate::Reg<lptim_cfgr::LPTIM_CFGR_SPEC>; #[doc = "Configuration Register"] pub mod lptim_cfgr; #[doc = "LPTIM_CR (rw) register accessor: Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`lptim_cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_cr`] module"] pub type LPTIM_CR = crate::Reg<lptim_cr::LPTIM_CR_SPEC>; #[doc = "Control Register"] pub mod lptim_cr; #[doc = "LPTIM_CMP (rw) register accessor: Compare Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_cmp::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`lptim_cmp::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_cmp`] module"] pub type LPTIM_CMP = crate::Reg<lptim_cmp::LPTIM_CMP_SPEC>; #[doc = "Compare Register"] pub mod lptim_cmp; #[doc = "LPTIM_ARR (rw) register accessor: Autoreload Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_arr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`lptim_arr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_arr`] module"] pub type LPTIM_ARR = crate::Reg<lptim_arr::LPTIM_ARR_SPEC>; #[doc = "Autoreload Register"] pub mod lptim_arr; #[doc = "LPTIM_CNT (r) register accessor: Counter Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_cnt::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_cnt`] module"] pub type LPTIM_CNT = crate::Reg<lptim_cnt::LPTIM_CNT_SPEC>; #[doc = "Counter Register"] pub mod lptim_cnt; #[doc = "LPTIM_CFGR2 (rw) register accessor: LPTIM configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_cfgr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`lptim_cfgr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`lptim_cfgr2`] module"] pub type LPTIM_CFGR2 = crate::Reg<lptim_cfgr2::LPTIM_CFGR2_SPEC>; #[doc = "LPTIM configuration register 2"] pub mod lptim_cfgr2;
use crate::rtb_type_strict; rtb_type_strict! { AmpHtmlRenderingType, EarlyLoading=1; StandardLoading = 2 }
use serde::*; #[derive(Debug, Clone, Deserialize)] pub struct Flight { #[serde(rename = "icao24")] pub icao24: String, #[serde(rename = "firstSeen")] pub first_seen: i64, #[serde(rename = "estDepartureAirport")] pub est_departure_airport: String, #[serde(rename = "lastSeen")] pub last_seen: i64, #[serde(rename = "estArrivalAirport")] pub est_arrival_airport: String, #[serde(rename = "callsign")] pub callsign: String, #[serde(rename = "estDepartureAirportHorizDistance")] pub est_departure_airport_horiz_distance: i64, #[serde(rename = "estDepartureAirportVertDistance")] pub est_departure_airport_vert_distance: i64, #[serde(rename = "estArrivalAirportHorizDistance")] pub est_arrival_airport_horiz_distance: i64, #[serde(rename = "estArrivalAirportVertDistance")] pub est_arrival_airport_vert_distance: i64, #[serde(rename = "departureAirportCandidatesCount")] pub departure_airport_candidates_count: i64, #[serde(rename = "arrivalAirportCandidatesCount")] pub arrival_airport_candidates_count: i64 } // Collection type returned in queries pub type FlightData = Vec<Flight>;
use godot::ToVariant; use serde_derive::{Deserialize, Serialize}; use std::net::SocketAddr; use std::convert::From; use bincode::{deserialize, serialize}; use std::io::Error; #[derive(Clone)] #[derive(Serialize, Deserialize)] pub enum VariantType { Vector2 { x: f32, y: f32 }, Vector3 { x: f32, y: f32, z: f32 }, GDString { string: String }, Int { int: i64 }, FloatArray { vec: Vec<f32> }, GodotBool { boolean: bool }, StringArr { vec: Vec<String> }, Unknown {}, } #[derive(Clone)] #[derive(Serialize, Deserialize)] pub enum MetaMessage { Heartbeat, Ack, } pub enum DeliveryType { RelOrd, RelSeq, RelUnord, Unrel, UnrelSeq, } trait SerializableEvent { fn to_packet(&self) -> Option<laminar::Packet>; } pub struct SendEvent { pub addr: SocketAddr, pub delivery: DeliveryType, pub pack: Option<EventData>, pub meta: Option<MetaMessage>, } impl SendEvent { pub fn to_packet(&self) -> Option<laminar::Packet> { if let Some(packet_data) = &self.pack { let delivery = &self.delivery; let serialized = match serialize(&packet_data) { Ok(data) => data, Err(e) => return None, }; let packet = match delivery { RelOrd => laminar::Packet::reliable_ordered(self.addr, serialized, None), RelSeq => laminar::Packet::reliable_sequenced(self.addr, serialized, None), RelUnord => laminar::Packet::reliable_unordered(self.addr, serialized), Unrel => laminar::Packet::unreliable(self.addr, serialized), UnrelSeq => laminar::Packet::unreliable_sequenced(self.addr, serialized, None), }; Some(packet) } else if let Some(meta) = &self.meta { let delivery = &self.delivery; let serialized = match serialize(&meta) { Ok(data) => data, Err(e) => return None, }; let packet = match delivery { RelOrd => laminar::Packet::reliable_ordered(self.addr, serialized, None), RelSeq => laminar::Packet::reliable_sequenced(self.addr, serialized, None), RelUnord => laminar::Packet::reliable_unordered(self.addr, serialized), Unrel => laminar::Packet::unreliable(self.addr, serialized), UnrelSeq => laminar::Packet::unreliable_sequenced(self.addr, serialized, None), }; Some(packet) } else { None } } } impl From<godot::Variant> for VariantType { fn from(variant: godot::Variant) -> Self { match variant.get_type() { godot::VariantType::Vector2 => VariantType::Vector2 { x: variant.to_vector2().x, y: variant.to_vector2().y, }, godot::VariantType::Vector3 => VariantType::Vector3 { x: variant.to_vector3().x, y: variant.to_vector3().y, z: variant.to_vector3().z, }, godot::VariantType::GodotString => VariantType::GDString { string: variant.to_string(), }, godot::VariantType::I64 => VariantType::Int { int: variant.to_i64(), }, godot::VariantType::Float32Array => { let float_arr = variant.to_float32_array(); let vec: Vec<f32> = (0..float_arr.len()).map(|i| float_arr.get(i)).collect(); VariantType::FloatArray { vec } } godot::VariantType::Bool => VariantType::GodotBool { boolean: variant.to_bool(), }, godot::VariantType::StringArray => { let string_arr: godot::StringArray = variant.to_string_array(); let vec: Vec<String> = (0..string_arr.len()) .map(|i| string_arr.get(i).to_string()) .collect(); VariantType::StringArr { vec } } _ => VariantType::Unknown {}, } } } #[derive(Clone)] #[derive(Serialize, Deserialize)] pub struct VariantTypes(pub Vec<VariantType>); impl From<godot::Variant> for VariantTypes { fn from(variant: godot::Variant) -> Self { let mut variant_array = godot::VariantArray::from_variant(&variant).unwrap(); let data_types: Vec<VariantType> = (0..variant_array.len()) .map(|i| { let var = variant_array.get_val(i); let data_type = VariantType::from(var); data_type }) .collect(); VariantTypes(data_types) } } impl VariantType { pub fn to_variant(&self) -> godot::Variant { match self { VariantType::Vector3 { x, y, z } => { godot::Variant::from_vector3(&godot::Vector3::new(*x, *y, *z)) } VariantType::Vector2 { x, y } => { godot::Variant::from_vector2(&godot::Vector2::new(*x, *y)) } VariantType::GDString { string } => godot::Variant::from_str(string), VariantType::Int { int } => godot::Variant::from_i64(*int), VariantType::FloatArray { vec } => { let mut float_arr = godot::Float32Array::new(); vec.iter().for_each(|f| float_arr.push(*f)); godot::Variant::from_float32_array(&float_arr) } VariantType::GodotBool { boolean } => godot::Variant::from_bool(*boolean), VariantType::StringArr { vec } => { let mut str_arr = godot::StringArray::new(); vec.iter() .for_each(|s| str_arr.push(&godot::GodotString::from_str(s))); godot::Variant::from_string_array(&str_arr) } _ => godot::Variant::new(), } } } #[derive(Clone)] #[derive(Serialize, Deserialize)] pub struct EventData { pub node_path: String, pub method: String, pub variants: VariantTypes, }
use gl; use gl::types::*; use gl_context::*; use shader::*; use std::cell::RefCell; use std::mem; use std::ptr; use std::rc::Rc; use vertex; // TODO: Don't 1-1 vertex array objects with vertex buffers /// Gets the id number for a given input of the shader program. #[allow(non_snake_case)] pub fn glGetAttribLocation(shader_program: GLuint, name: &str) -> GLint { name.with_c_str(|ptr| unsafe { gl::GetAttribLocation(shader_program, ptr) }) } /// Fixed-size VRAM buffer for individual bytes. pub struct GLByteBuffer { pub gl_id: u32, /// number of bytes in the buffer. pub length: uint, /// maximum number of bytes in the buffer. pub capacity: uint, } impl GLByteBuffer { /// Creates a new array of objects on the GPU. /// capacity is provided in units of size slice_span. pub fn new(capacity: uint) -> GLByteBuffer { let mut gl_id = 0; unsafe { gl::GenBuffers(1, &mut gl_id); } assert!(gl_id != 0); gl::BindBuffer(gl::ARRAY_BUFFER, gl_id); unsafe { gl::BufferData( gl::ARRAY_BUFFER, capacity as GLsizeiptr, ptr::null(), gl::DYNAMIC_DRAW, ); } match gl::GetError() { gl::NO_ERROR => {}, gl::OUT_OF_MEMORY => panic!("Out of VRAM"), err => panic!("OpenGL error 0x{:x}", err), } GLByteBuffer { gl_id: gl_id, length: 0, capacity: capacity, } } /// Add more data into this buffer. pub unsafe fn push(&mut self, vs: *const u8, count: uint) { assert!( self.length + count <= self.capacity, "GLByteBuffer::push {} into a {}/{} full GLByteBuffer", count, self.length, self.capacity ); self.update_inner(self.length, vs, count); self.length += count; } pub fn swap_remove(&mut self, i: uint, count: uint) { assert!(count <= self.length); self.length -= count; assert!(i <= self.length); match gl::GetError() { gl::NO_ERROR => {}, err => panic!("OpenGL error 0x{:x} in update", err), } // In the `i == self.length` case, we don't bother with the swap; // decreasing `self.length` is enough. if i < self.length { assert!( i <= self.length - count, "GLByteBuffer::swap_remove would cause copy in overlapping regions" ); gl::BindBuffer(gl::ARRAY_BUFFER, self.gl_id); match gl::GetError() { gl::NO_ERROR => {}, err => panic!("OpenGL error 0x{:x} in update", err), } gl::CopyBufferSubData( gl::ARRAY_BUFFER, gl::ARRAY_BUFFER, self.length as i64, i as i64, count as i64, ); match gl::GetError() { gl::NO_ERROR => {}, err => panic!("OpenGL error 0x{:x} in update", err), } } } pub unsafe fn update(&self, idx: uint, vs: *const u8, count: uint) { assert!(idx + count <= self.length); self.update_inner(idx, vs, count); } unsafe fn update_inner(&self, idx: uint, vs: *const u8, count: uint) { assert!(idx + count <= self.capacity); match gl::GetError() { gl::NO_ERROR => {}, err => panic!("OpenGL error 0x{:x} in GLByteBuffer::update", err), } gl::BindBuffer(gl::ARRAY_BUFFER, self.gl_id); gl::BufferSubData( gl::ARRAY_BUFFER, idx as i64, count as i64, mem::transmute(vs) ); gl::Finish(); match gl::GetError() { gl::NO_ERROR => {}, err => panic!("OpenGL error 0x{:x} in GLByteBuffer::update_inner", err), } } } #[unsafe_destructor] impl Drop for GLByteBuffer { #[inline] fn drop(&mut self) { unsafe { gl::DeleteBuffers(1, &self.gl_id); } } } /// Fixed-size typed VRAM buffer, optimized for bulk inserts. pub struct GLBuffer<T> { pub byte_buffer: GLByteBuffer, pub length: uint, } impl<T> GLBuffer<T> { pub fn new(capacity: uint) -> GLBuffer<T> { GLBuffer { byte_buffer: GLByteBuffer::new(capacity * mem::size_of::<T>()), length: 0, } } pub fn push(&mut self, vs: &[T]) { unsafe { self.byte_buffer.push( mem::transmute(vs.as_ptr()), mem::size_of::<T>() * vs.len() ); } self.length += vs.len(); } pub fn update(&mut self, idx: uint, vs: &[T]) { unsafe { self.byte_buffer.update( mem::size_of::<T>() * idx, mem::transmute(vs.as_ptr()), mem::size_of::<T>() * vs.len(), ); } } pub fn swap_remove(&mut self, idx: uint, count: uint) { self.byte_buffer.swap_remove( mem::size_of::<T>() * idx, mem::size_of::<T>() * count, ); self.length -= count; } } pub enum DrawMode { Lines, Triangles, Points, } impl DrawMode { fn to_enum(&self) -> GLenum { match self { &Lines => gl::LINES, &Triangles => gl::TRIANGLES, &Points => gl::POINTS, } } } /// A fixed-capacity array of bytes passed to OpenGL. pub struct GLArray<T> { pub buffer: GLBuffer<T>, pub gl_id: u32, /// How to draw this buffer. Ex: gl::LINES, gl::TRIANGLES, etc. pub mode: GLenum, /// size of T in vertices pub attrib_span: uint, /// length in vertices pub length: uint, } impl<T> GLArray<T> { #[inline] /// Creates a new array of objects on the GPU. /// capacity is provided in units of size slice_span. pub fn new( _gl: &GLContext, shader_program: Rc<RefCell<Shader>>, attribs: &[vertex::AttribData], mode: DrawMode, buffer: GLBuffer<T>, ) -> GLArray<T> { let mut gl_id = 0; // TODO(cgaebel): Error checking? unsafe { gl::GenVertexArrays(1, &mut gl_id); } gl::BindVertexArray(gl_id); let mut offset = 0; let attrib_span = { let mut attrib_span = 0; for attrib in attribs.iter() { attrib_span += attrib.size * attrib.unit.size(); } attrib_span }; for attrib in attribs.iter() { let shader_attrib = glGetAttribLocation(shader_program.deref().borrow().id, attrib.name) as GLuint; assert!(shader_attrib != -1, "shader attribute \"{}\" not found", attrib.name); gl::EnableVertexAttribArray(shader_attrib); unsafe { if attrib.unit.is_integral() { gl::VertexAttribIPointer( shader_attrib, attrib.size as i32, attrib.unit.gl_enum(), attrib_span as i32, ptr::null().offset(offset), ); } else { gl::VertexAttribPointer( shader_attrib, attrib.size as i32, attrib.unit.gl_enum(), gl::FALSE as GLboolean, attrib_span as i32, ptr::null().offset(offset), ); } } offset += (attrib.size * attrib.unit.size()) as int; } match gl::GetError() { gl::NO_ERROR => {}, err => panic!("OpenGL error 0x{:x}", err), } assert!(mem::size_of::<T>() % attrib_span == 0); GLArray { buffer: buffer, gl_id: gl_id, mode: mode.to_enum(), attrib_span: mem::size_of::<T>() / attrib_span, length: 0, } } pub fn push(&mut self, vs: &[T]) { self.buffer.push(vs); self.length += vs.len() * self.attrib_span; } pub fn swap_remove(&mut self, idx: uint, count: uint) { self.buffer.swap_remove(idx, count); self.length -= count * self.attrib_span; } #[inline] /// Draws all the queued triangles to the screen. pub fn draw(&self, gl: &GLContext) { self.draw_slice(gl, 0, self.buffer.length); } /// Draw some subset of the triangle array. pub fn draw_slice(&self, _gl: &GLContext, start: uint, len: uint) { assert!(start + len <= self.length); gl::BindVertexArray(self.gl_id); gl::BindBuffer(gl::ARRAY_BUFFER, self.buffer.byte_buffer.gl_id); gl::DrawArrays(self.mode, (start * self.attrib_span) as i32, (len * self.attrib_span) as i32); match gl::GetError() { gl::NO_ERROR => {}, err => panic!("OpenGL error 0x{:x}", err), } } } #[unsafe_destructor] impl<T> Drop for GLArray<T> { #[inline] fn drop(&mut self) { unsafe { gl::DeleteVertexArrays(1, &self.gl_id); } } }
// SPDX-License-Identifier: MIT use std::fs; use std::path::Path; pub const PY_EXT: &str = ".py"; pub const INPUT_EXT: &str = ".txt"; pub const OUTPUT_EXT: &str = ".out.txt"; pub const TEST_PREFIX: &str = "t"; pub fn get_prog_filename(name: &str) -> String { format!("{}{}", name, PY_EXT) } pub fn get_input_filename(name: &str) -> String { format!("{}{}", name, INPUT_EXT) } pub fn get_output_filename(name: &str) -> String { format!("{}{}", name, OUTPUT_EXT) } pub fn get_test_prefix(name: &str) -> String { format!("{}{}", TEST_PREFIX, name) } pub fn remove_ext(filename: &str, ext: &str) -> String { match filename.strip_suffix(ext) { Some(val) => val.to_string(), None => filename.to_string(), } } pub fn file_exists(filename: &str) -> bool { Path::new(&format!("./{}", filename)).exists() } pub fn get_all_input_filenames_with_prefix(prefix: &str) -> Result<Vec<String>, String> { let mut result = vec![]; let entries = match fs::read_dir(".") { Ok(entries) => entries, Err(err) => return Err(format!("Fail to read file listing for cwd. {}", err)), }; for entry in entries { if let Ok(entry) = entry { let filename = entry.file_name(); let filename = filename.to_str().unwrap_or(""); if filename.starts_with(prefix) && filename.ends_with(INPUT_EXT) && !filename.ends_with(OUTPUT_EXT) { result.push(filename.to_string()); } } } // filesystem does not guarantee files are in any particular order result.sort(); Ok(result) }
use std::convert::TryInto; use std::mem; use std::io::{self, Write, Seek, SeekFrom}; use byteorder::{LE, ByteOrder, WriteBytesExt}; use crate::elab::environment::{ Environment, Type, Expr, Proof, SortID, TermID, ThmID, TermVec, ExprNode, ProofNode, StmtTrace, DeclKey, Modifiers}; use crate::util::FileRef; use crate::lined_string::LinedString; enum Value { U32(u32), U64(u64), Box(Box<[u8]>), } const DATA_8: u8 = 0x40; const DATA_16: u8 = 0x80; const DATA_32: u8 = 0xC0; const STMT_SORT: u8 = 0x04; const STMT_AXIOM: u8 = 0x02; const STMT_TERM: u8 = 0x05; const STMT_DEF: u8 = 0x05; const STMT_THM: u8 = 0x06; const STMT_LOCAL: u8 = 0x08; const PROOF_TERM: u8 = 0x10; const PROOF_TERM_SAVE: u8 = 0x11; const PROOF_REF: u8 = 0x12; const PROOF_DUMMY: u8 = 0x13; const PROOF_THM: u8 = 0x14; const PROOF_THM_SAVE: u8 = 0x15; const PROOF_HYP: u8 = 0x16; const PROOF_CONV: u8 = 0x17; const PROOF_REFL: u8 = 0x18; const PROOF_SYMM: u8 = 0x19; const PROOF_CONG: u8 = 0x1A; const PROOF_UNFOLD: u8 = 0x1B; const PROOF_CONV_CUT: u8 = 0x1C; const PROOF_CONV_REF: u8 = 0x1D; const PROOF_CONV_SAVE: u8 = 0x1E; const PROOF_SAVE: u8 = 0x1F; const UNIFY_TERM: u8 = 0x30; const UNIFY_TERM_SAVE: u8 = 0x31; const UNIFY_REF: u8 = 0x32; const UNIFY_DUMMY: u8 = 0x33; const UNIFY_HYP: u8 = 0x36; enum ProofCmd { Term(TermID), TermSave(TermID), Ref(u32), Dummy(SortID), Thm(ThmID), ThmSave(ThmID), Hyp, Conv, Refl, Sym, Cong, Unfold, ConvCut, ConvRef(u32), ConvSave, Save, } enum UnifyCmd { Term(TermID), TermSave(TermID), Ref(u32), Dummy(SortID), Hyp, } struct Reorder<T=u32> { map: Box<[Option<T>]>, idx: u32, } impl<T: Clone> Reorder<T> { fn new(nargs: u32, len: usize, mut f: impl FnMut(u32) -> T) -> Reorder<T> { let mut map: Box<[Option<T>]> = vec![None; len].into(); for i in 0..nargs {map[i as usize] = Some(f(i))} Reorder {map, idx: nargs} } } struct IndexHeader<'a> { sorts: &'a mut [[u8; 8]], terms: &'a mut [[u8; 8]], thms: &'a mut [[u8; 8]] } impl<'a> IndexHeader<'a> { fn sort(&mut self, i: SortID) -> &mut [u8; 8] { &mut self.sorts[i.0 as usize] } fn term(&mut self, i: TermID) -> &mut [u8; 8] { &mut self.terms[i.0 as usize] } fn thm(&mut self, i: ThmID) -> &mut [u8; 8] { &mut self.thms[i.0 as usize] } } pub struct Exporter<'a, W: Write + Seek + ?Sized> { file: FileRef, source: &'a LinedString, env: &'a Environment, w: &'a mut W, pos: u64, term_reord: TermVec<Option<Reorder>>, fixups: Vec<(u64, Value)>, } #[must_use] struct Fixup32(u64); #[must_use] struct Fixup64(u64); #[must_use] struct FixupLarge(u64, Box<[u8]>); impl Fixup32 { fn commit_val<'a, W: Write + Seek + ?Sized>(self, e: &mut Exporter<'a, W>, val: u32) { e.fixups.push((self.0, Value::U32(val))) } fn commit<'a, W: Write + Seek + ?Sized>(self, e: &mut Exporter<'a, W>) { let val = e.pos.try_into().unwrap(); self.commit_val(e, val) } } impl Fixup64 { fn commit_val<'a, W: Write + Seek + ?Sized>(self, e: &mut Exporter<'a, W>, val: u64) { e.fixups.push((self.0, Value::U64(val))) } fn commit<'a, W: Write + Seek + ?Sized>(self, e: &mut Exporter<'a, W>) { let val = e.pos; self.commit_val(e, val) } } impl FixupLarge { fn commit<'a, W: Write + Seek + ?Sized>(self, e: &mut Exporter<'a, W>) { e.fixups.push((self.0, Value::Box(self.1))) } } impl<'a, W: Write + Seek + ?Sized> Write for Exporter<'a, W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.write_all(buf)?; Ok(buf.len()) } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.pos += buf.len() as u64; self.w.write_all(buf)?; Ok(()) } fn flush(&mut self) -> io::Result<()> {self.w.flush()} } fn write_cmd(w: &mut impl Write, cmd: u8, data: u32) -> io::Result<()> { if data == 0 {w.write_u8(cmd)} else if let Ok(data) = data.try_into() { w.write_u8(cmd | DATA_8)?; w.write_u8(data) } else if let Ok(data) = data.try_into() { w.write_u8(cmd | DATA_16)?; w.write_u16::<LE>(data) } else { w.write_u8(cmd | DATA_32)?; w.write_u32::<LE>(data) } } fn write_cmd_bytes(w: &mut impl Write, cmd: u8, vec: &[u8]) -> io::Result<()> { if let Ok(data) = (vec.len() + 2).try_into() { w.write_u8(cmd | DATA_8)?; w.write_u8(data)?; w.write_all(vec) } else if let Ok(data) = (vec.len() + 3).try_into() { w.write_u8(cmd | DATA_16)?; w.write_u16::<LE>(data)?; w.write_all(vec) } else { w.write_u8(cmd | DATA_32)?; w.write_u32::<LE>((vec.len() + 5).try_into().unwrap())?; w.write_all(vec) } } impl UnifyCmd { fn write_to(self, w: &mut impl Write) -> io::Result<()> { match self { UnifyCmd::Term(tid) => write_cmd(w, UNIFY_TERM, tid.0), UnifyCmd::TermSave(tid) => write_cmd(w, UNIFY_TERM_SAVE, tid.0), UnifyCmd::Ref(n) => write_cmd(w, UNIFY_REF, n), UnifyCmd::Dummy(sid) => write_cmd(w, UNIFY_DUMMY, sid.0 as u32), UnifyCmd::Hyp => w.write_u8(UNIFY_HYP), } } } impl ProofCmd { fn write_to(self, w: &mut impl Write) -> io::Result<()> { match self { ProofCmd::Term(tid) => write_cmd(w, PROOF_TERM, tid.0), ProofCmd::TermSave(tid) => write_cmd(w, PROOF_TERM_SAVE, tid.0), ProofCmd::Ref(n) => write_cmd(w, PROOF_REF, n), ProofCmd::Dummy(sid) => write_cmd(w, PROOF_DUMMY, sid.0 as u32), ProofCmd::Thm(tid) => write_cmd(w, PROOF_THM, tid.0), ProofCmd::ThmSave(tid) => write_cmd(w, PROOF_THM_SAVE, tid.0), ProofCmd::Hyp => w.write_u8(PROOF_HYP), ProofCmd::Conv => w.write_u8(PROOF_CONV), ProofCmd::Refl => w.write_u8(PROOF_REFL), ProofCmd::Sym => w.write_u8(PROOF_SYMM), ProofCmd::Cong => w.write_u8(PROOF_CONG), ProofCmd::Unfold => w.write_u8(PROOF_UNFOLD), ProofCmd::ConvCut => w.write_u8(PROOF_CONV_CUT), ProofCmd::ConvRef(n) => write_cmd(w, PROOF_CONV_REF, n), ProofCmd::ConvSave => w.write_u8(PROOF_CONV_SAVE), ProofCmd::Save => w.write_u8(PROOF_SAVE), } } } fn write_expr_proof(w: &mut impl Write, heap: &[ExprNode], reorder: &mut Reorder, head: &ExprNode, save: bool ) -> io::Result<u32> { Ok(match head { &ExprNode::Ref(i) => match reorder.map[i] { None => { let n = write_expr_proof(w, heap, reorder, &heap[i], true)?; reorder.map[i] = Some(n); n } Some(n) => { ProofCmd::Ref(n.try_into().unwrap()).write_to(w)?; n } } &ExprNode::Dummy(_, s) => { ProofCmd::Dummy(s).write_to(w)?; (reorder.idx, reorder.idx += 1).0 } &ExprNode::App(t, ref es) => { for e in es {write_expr_proof(w, heap, reorder, e, false)?;} if save { ProofCmd::TermSave(t).write_to(w)?; (reorder.idx, reorder.idx += 1).0 } else {ProofCmd::Term(t).write_to(w)?; 0} } }) } impl<'a, W: Write + Seek + ?Sized> Exporter<'a, W> { pub fn new(file: FileRef, source: &'a LinedString, env: &'a Environment, w: &'a mut W) -> Self { Self { term_reord: TermVec(Vec::with_capacity(env.terms.len())), file, source, env, w, pos: 0, fixups: vec![] } } fn write_u32(&mut self, n: u32) -> io::Result<()> { WriteBytesExt::write_u32::<LE>(self, n) } fn write_u64(&mut self, n: u64) -> io::Result<()> { WriteBytesExt::write_u64::<LE>(self, n) } fn fixup32(&mut self) -> io::Result<Fixup32> { let f = Fixup32(self.pos); self.write_u32(0)?; Ok(f) } fn fixup64(&mut self) -> io::Result<Fixup64> { let f = Fixup64(self.pos); self.write_u64(0)?; Ok(f) } fn fixup_large(&mut self, size: usize) -> io::Result<FixupLarge> { let f = FixupLarge(self.pos, vec![0; size].into()); self.write(&f.1)?; Ok(f) } #[inline] fn align_to(&mut self, n: u8) -> io::Result<u64> { let i = n.wrapping_sub(self.pos as u8) & (n - 1); self.write(&vec![0; i as usize])?; Ok(self.pos) } #[inline] fn write_sort_deps(&mut self, bound: bool, sort: SortID, deps: u64) -> io::Result<()> { self.write_u64( if bound {1} else {0} << 63 | (sort.0 as u64) << 56 | deps) } #[inline] fn write_term_header(header: &mut [u8], nargs: u16, sort: SortID, has_def: bool, p_term: u32) { LE::write_u16(&mut header[0..], nargs); header[2] = sort.0 | if has_def {0x80} else {0}; LE::write_u32(&mut header[4..], p_term); } fn write_binders<T>(&mut self, args: &[(T, Type)]) -> io::Result<()> { let mut bv = 1; for (_, ty) in args { match ty { &Type::Bound(s) => { if bv >= (1 << 55) {panic!("more than 55 bound variables")} self.write_sort_deps(true, s, bv)?; bv *= 2; } &Type::Reg(s, deps) => self.write_sort_deps(false, s, deps)?, } } Ok(()) } fn write_expr_unify(&mut self, heap: &[ExprNode], reorder: &mut Reorder, head: &ExprNode, save: &mut Vec<usize> ) -> io::Result<()> { macro_rules! commit {($n:expr) => { for i in save.drain(..) {reorder.map[i] = Some($n)} }} match head { &ExprNode::Ref(i) => match reorder.map[i] { None => { save.push(i); self.write_expr_unify(heap, reorder, &heap[i], save) } Some(n) => { UnifyCmd::Ref(n).write_to(self)?; Ok(commit!(n)) } } &ExprNode::Dummy(_, s) => { commit!(reorder.idx); reorder.idx += 1; UnifyCmd::Dummy(s).write_to(self) } &ExprNode::App(t, ref es) => { if save.is_empty() { UnifyCmd::Term(t).write_to(self)?; } else { commit!(reorder.idx); reorder.idx += 1; UnifyCmd::TermSave(t).write_to(self)?; } for e in es {self.write_expr_unify(heap, reorder, e, save)?} Ok(()) } } } fn write_proof(&self, w: &mut impl Write, heap: &[ProofNode], reorder: &mut Reorder, hyps: &[u32], head: &ProofNode, save: bool ) -> io::Result<u32> { Ok(match head { &ProofNode::Ref(i) => match reorder.map[i] { None => { let n = self.write_proof(w, heap, reorder, hyps, &heap[i], true)?; reorder.map[i] = Some(n); n } Some(n) => {ProofCmd::Ref(n).write_to(w)?; n} } &ProofNode::Dummy(_, s) => { ProofCmd::Dummy(s).write_to(w)?; (reorder.idx, reorder.idx += 1).0 } &ProofNode::Term {term, ref args} => { for e in &**args {self.write_proof(w, heap, reorder, hyps, e, false)?;} if save { ProofCmd::TermSave(term).write_to(w)?; (reorder.idx, reorder.idx += 1).0 } else {ProofCmd::Term(term).write_to(w)?; 0} } &ProofNode::Hyp(n, _) => { ProofCmd::Ref(hyps[n]).write_to(w)?; hyps[n] } &ProofNode::Thm {thm, ref args, ref res} => { let (args, hs) = args.split_at(self.env.thms[thm].args.len()); for e in hs {self.write_proof(w, heap, reorder, hyps, e, false)?;} for e in args {self.write_proof(w, heap, reorder, hyps, e, false)?;} self.write_proof(w, heap, reorder, hyps, res, false)?; if save { ProofCmd::ThmSave(thm).write_to(w)?; (reorder.idx, reorder.idx += 1).0 } else {ProofCmd::Thm(thm).write_to(w)?; 0} } ProofNode::Conv(p) => { let (e1, c, p) = &**p; self.write_proof(w, heap, reorder, hyps, e1, false)?; self.write_proof(w, heap, reorder, hyps, p, false)?; ProofCmd::Conv.write_to(w)?; self.write_conv(w, heap, reorder, hyps, c)?; if save { ProofCmd::Save.write_to(w)?; (reorder.idx, reorder.idx += 1).0 } else {0} } ProofNode::Refl(_) | ProofNode::Sym(_) | ProofNode::Cong {..} | ProofNode::Unfold {..} => unreachable!(), }) } fn write_conv(&self, w: &mut impl Write, heap: &[ProofNode], reorder: &mut Reorder, hyps: &[u32], head: &ProofNode, ) -> io::Result<()> { Ok(match head { &ProofNode::Ref(i) => match reorder.map[i] { None => { let e = &heap[i]; match e { ProofNode::Refl(_) | ProofNode::Ref(_) => self.write_conv(w, heap, reorder, hyps, e)?, _ => { ProofCmd::ConvCut.write_to(w)?; self.write_conv(w, heap, reorder, hyps, e)?; ProofCmd::ConvSave.write_to(w)?; reorder.map[i] = Some(reorder.idx); reorder.idx += 1; } }; } Some(n) => ProofCmd::ConvRef(n).write_to(w)?, } ProofNode::Dummy(_, _) | ProofNode::Term {..} | ProofNode::Hyp(_, _) | ProofNode::Thm {..} | ProofNode::Conv(_) => unreachable!(), ProofNode::Refl(_) => ProofCmd::Refl.write_to(w)?, ProofNode::Sym(c) => { ProofCmd::Sym.write_to(w)?; self.write_conv(w, heap, reorder, hyps, c)?; } ProofNode::Cong {args, ..} => { ProofCmd::Cong.write_to(w)?; for a in &**args {self.write_conv(w, heap, reorder, hyps, a)?} } ProofNode::Unfold {res, ..} => { let (l, l2, c) = &**res; self.write_proof(w, heap, reorder, hyps, l, false)?; self.write_proof(w, heap, reorder, hyps, l2, false)?; ProofCmd::Unfold.write_to(w)?; self.write_conv(w, heap, reorder, hyps, c)?; } }) } #[inline] fn write_thm_header(header: &mut [u8], nargs: u16, p_thm: u32) { LE::write_u16(&mut header[0..], nargs); LE::write_u32(&mut header[4..], p_thm); } fn write_index_entry(&mut self, header: &mut IndexHeader, il: u64, ir: u64, (s, cmd): (StmtTrace, u64)) -> io::Result<u64> { let n = self.align_to(8)?; let (sp, ix, k, name) = match s { StmtTrace::Sort(a) => { let ad = &self.env.data[a]; let s = ad.sort.unwrap(); LE::write_u64(header.sort(s), n); (&self.env.sorts[s].span, s.0 as u32, STMT_SORT, &ad.name) } StmtTrace::Decl(a) => { let ad = &self.env.data[a]; match ad.decl.unwrap() { DeclKey::Term(t) => { let td = &self.env.terms[t]; LE::write_u64(header.term(t), n); (&td.span, t.0, if td.val.is_none() {STMT_TERM} else if td.vis == Modifiers::LOCAL {STMT_DEF | STMT_LOCAL} else {STMT_DEF}, &ad.name) } DeclKey::Thm(t) => { let td = &self.env.thms[t]; LE::write_u64(header.thm(t), n); (&td.span, t.0, if td.proof.is_none() {STMT_AXIOM} else if td.vis == Modifiers::PUB {STMT_THM} else {STMT_THM | STMT_LOCAL}, &ad.name) } } } StmtTrace::Global(_) => unreachable!() }; let pos = if sp.file.ptr_eq(&self.file) { self.source.to_pos(sp.span.start) } else {Default::default()}; self.write_u64(il)?; self.write_u64(ir)?; self.write_u32(pos.line as u32)?; self.write_u32(pos.character as u32)?; self.write_u64(cmd)?; self.write_u32(ix)?; self.write_u8(k)?; self.write_all(name.as_bytes())?; self.write_u8(0)?; Ok(n) } fn write_index(&mut self, header: &mut IndexHeader, left: &[(StmtTrace, u64)], map: &[(StmtTrace, u64)]) -> io::Result<u64> { let mut lo = map.len() / 2; let a = match map.get(lo) { None => { let mut n = 0; for &t in left.iter().rev() { n = self.write_index_entry(header, 0, n, t)? } return Ok(n) } Some((k, _)) => k.atom() }; let mut hi = lo + 1; loop { match lo.checked_sub(1) { Some(i) if map[i].0.atom() == a => lo = i, _ => break, } } loop { match map.get(hi) { Some(k) if k.0.atom() == a => hi += 1, _ => break, } } let il = self.write_index(header, left, &map[..lo])?; let ir = self.write_index(header, &map[lo+1..hi], &map[hi..])?; self.write_index_entry(header, il, ir, map[lo]) } pub fn run(&mut self, index: bool) -> io::Result<()> { self.write_all("MM0B".as_bytes())?; // magic let num_sorts = self.env.sorts.len(); if num_sorts > 128 {panic!("too many sorts (max 128)")} self.write_u32( 1 | // version ((num_sorts as u32) << 8) // num_sorts )?; // two bytes reserved self.write_u32(self.env.terms.len().try_into().unwrap())?; // num_terms self.write_u32(self.env.thms.len().try_into().unwrap())?; // num_thms let p_terms = self.fixup32()?; let p_thms = self.fixup32()?; let p_proof = self.fixup64()?; let p_index = self.fixup64()?; self.write_all( // sort data &self.env.sorts.0.iter().map(|s| { // 1 = PURE, 2 = STRICT, 4 = PROVABLE, 8 = FREE s.mods.bits() }).collect::<Vec<u8>>())?; self.align_to(8)?; p_terms.commit(self); let mut term_header = self.fixup_large(self.env.terms.len() * 8)?; for (head, t) in term_header.1.chunks_exact_mut(8).zip(&self.env.terms.0) { Self::write_term_header(head, t.args.len().try_into().expect("term has more than 65536 args"), t.ret.0, t.val.is_some(), self.align_to(8)?.try_into().unwrap()); self.write_binders(&t.args)?; self.write_sort_deps(false, t.ret.0, t.ret.1)?; if let Some(val) = &t.val { let Expr {heap, head} = val.as_ref().unwrap_or_else(|| panic!("def {} missing value", self.env.data[t.atom].name)); let mut reorder = Reorder::new( t.args.len().try_into().unwrap(), heap.len(), |i| i); self.write_expr_unify(heap, &mut reorder, head, &mut vec![])?; self.write_u8(0)?; self.term_reord.push(Some(reorder)); } else { self.term_reord.push(None) } } term_header.commit(self); self.align_to(8)?; p_thms.commit(self); let mut thm_header = self.fixup_large(self.env.thms.len() * 8)?; for (head, t) in thm_header.1.chunks_exact_mut(8).zip(&self.env.thms.0) { Self::write_thm_header(head, t.args.len().try_into().expect("theorem has more than 65536 args"), self.align_to(8)?.try_into().unwrap()); self.write_binders(&t.args)?; let nargs = t.args.len().try_into().unwrap(); let mut reorder = Reorder::new(nargs, t.heap.len(), |i| i); let save = &mut vec![]; self.write_expr_unify(&t.heap, &mut reorder, &t.ret, save)?; for (_, h) in t.hyps.iter().rev() { UnifyCmd::Hyp.write_to(self)?; self.write_expr_unify(&t.heap, &mut reorder, h, save)?; } self.write_u8(0)?; } thm_header.commit(self); p_proof.commit(self); let mut vec = vec![]; let mut index_map = if index { Vec::with_capacity(self.env.sorts.len() + self.env.terms.len() + self.env.thms.len()) } else {vec![]}; for &s in &self.env.stmts { match s { StmtTrace::Sort(_) => { if index {index_map.push((s, self.pos))} write_cmd(self, STMT_SORT, 2)? // this takes 2 bytes } StmtTrace::Decl(a) => { if index {index_map.push((s, self.pos))} match self.env.data[a].decl.unwrap() { DeclKey::Term(t) => { let td = &self.env.terms[t]; match &td.val { None => write_cmd(self, STMT_TERM, 2)?, // this takes 2 bytes Some(None) => unreachable!(), Some(Some(Expr {heap, head})) => { let mut reorder = Reorder::new( td.args.len().try_into().unwrap(), heap.len(), |i| i); write_expr_proof(&mut vec, heap, &mut reorder, head, false)?; vec.write_u8(0)?; let cmd = STMT_DEF | if td.vis == Modifiers::LOCAL {STMT_LOCAL} else {0}; write_cmd_bytes(self, cmd, &vec)?; vec.clear(); } } } DeclKey::Thm(t) => { let td = &self.env.thms[t]; let cmd = match &td.proof { None => { let mut reorder = Reorder::new( td.args.len().try_into().unwrap(), td.heap.len(), |i| i); for (_, h) in &td.hyps { write_expr_proof(&mut vec, &td.heap, &mut reorder, h, false)?; ProofCmd::Hyp.write_to(&mut vec)?; } write_expr_proof(&mut vec, &td.heap, &mut reorder, &td.ret, false)?; STMT_AXIOM } Some(None) => panic!("proof {} missing", self.env.data[td.atom].name), Some(Some(Proof {heap, hyps, head})) => { let mut reorder = Reorder::new( td.args.len().try_into().unwrap(), heap.len(), |i| i); let mut ehyps = Vec::with_capacity(hyps.len()); for mut h in hyps { while let &ProofNode::Ref(i) = h {h = &heap[i]} if let ProofNode::Hyp(_, e) = h { self.write_proof(&mut vec, heap, &mut reorder, &ehyps, e, false)?; ProofCmd::Hyp.write_to(&mut vec)?; ehyps.push(reorder.idx); reorder.idx += 1; } else {unreachable!()} } self.write_proof(&mut vec, &heap, &mut reorder, &ehyps, head, false)?; STMT_THM | if td.vis == Modifiers::PUB {0} else {STMT_LOCAL} } }; vec.write_u8(0)?; write_cmd_bytes(self, cmd, &vec)?; vec.clear(); } } } StmtTrace::Global(_) => {} } } self.write_u8(0)?; if index { self.align_to(8)?; p_index.commit(self); index_map.sort_unstable_by_key(|k| &*self.env.data[k.0.atom()].name); let mut index_header = self.fixup_large(8 * (1 + self.env.sorts.len() + self.env.terms.len() + self.env.thms.len()))?; let (root, header) = index_header.1.split_at_mut(8); let mut header = { let header: &mut [[u8; 8]] = unsafe {mem::transmute(header)}; let (sorts, header) = header.split_at_mut(self.env.sorts.len()); let (terms, thms) = header.split_at_mut(self.env.terms.len()); IndexHeader {sorts, terms, thms} }; LE::write_u64(root, self.write_index(&mut header, &[], &index_map)?); index_header.commit(self) } else { self.write_u32(0)?; // padding } Ok(()) } pub fn finish(self) -> io::Result<()> { let Self {w, fixups, ..} = self; for (pos, f) in fixups { w.seek(SeekFrom::Start(pos))?; match f { Value::U32(n) => w.write_u32::<LE>(n)?, Value::U64(n) => w.write_u64::<LE>(n)?, Value::Box(buf) => w.write_all(&buf)?, } } Ok(()) } }
pub mod prelude; pub mod puzzle; pub mod run; pub mod system; pub mod task; pub use crate::prelude::Result; pub use crate::run::run;
use std::fmt; use problem::{Problem, solve}; use smallbitvec::SmallBitVec; fn solve_2(values: &[i32], target: i32) -> Option<(i32, i32)> { let half = target / 2 + 1; let mut bits = SmallBitVec::from_elem(half as usize, false); for &value in values.iter() { let index = if value < half { value } else { target - value }; if index >= 0 { if bits[index as usize] { return Some((index, target - index)) } else { bits.set(index as usize, true); } } } None } struct Solution<T>(T); impl<T: AsRef<[i32]>> fmt::Display for Solution<T> { fn fmt<'a>(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut product = 1; for &v in self.0.as_ref().iter() { product *= v; } write!(f, "{}", product)?; for (i, &v) in self.0.as_ref().iter().enumerate() { if i == 0 { write!(f, " = {}", v)?; } else { write!(f, " * {}", v)?; } } Ok(()) } } #[derive(Debug)] enum Error { NoSolution, } const TARGET: i32 = 2020; struct Day1; impl Problem for Day1 { type Input = Vec<i32>; type Part1Output = Solution<[i32; 2]>; type Part2Output = Solution<[i32; 3]>; type Error = Error; fn part_1(input: &Self::Input) -> Result<Self::Part1Output, Self::Error> { let (a, b) = solve_2(input.as_slice(), TARGET).ok_or(Error::NoSolution)?; Ok(Solution([a, b])) } fn part_2(input: &Self::Input) -> Result<Self::Part2Output, Self::Error> { for (i, &v) in input.iter().enumerate() { if let Some((a, b)) = solve_2(&input[i + 1..], TARGET - v) { return Ok(Solution([v, a, b])); } } Err(Error::NoSolution) } } fn main() { solve::<Day1>("input").unwrap(); }
use super::lexer::{Location, Token}; use std::fmt; use std::string::String as RString; type Result<T> = std::result::Result<T, RString>; #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub(crate) struct Span { start: Location, end: Location, } impl Span { pub(crate) fn new(start: Location, end: Location) -> Self { Self { start, end } } } impl fmt::Display for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} to {}", self.start, self.end) } } #[derive(Clone, Debug, PartialEq)] pub(crate) struct Comment { span: Span, comment: RString, } impl Comment { fn new(span: Span, comment: RString) -> Self { Self { span, comment } } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub(crate) struct Keyword { span: Span, name: RString, } impl Keyword { pub(crate) fn new(span: Span, name: RString) -> Self { Self { span, name } } fn span(&self) -> &Span { &self.span } } impl fmt::Display for Keyword { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, ":{}", self.name) } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub(crate) struct Integer { span: Span, value: i32, } impl Integer { pub(crate) fn new(span: Span, value: i32) -> Self { Self { span, value } } fn span(&self) -> &Span { &self.span } } impl fmt::Display for Integer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.value) } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub(crate) struct String { span: Span, value: RString, } impl String { pub(crate) fn new(span: Span, value: RString) -> Self { Self { span, value } } fn span(&self) -> &Span { &self.span } } impl fmt::Display for String { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\"{}\"", self.value) } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub(crate) struct Symbol { span: Span, name: RString, } impl Symbol { pub(crate) fn new(span: Span, name: RString) -> Self { Self { span, name } } pub(crate) fn name(&self) -> &str { &self.name } fn span(&self) -> &Span { &self.span } } impl fmt::Display for Symbol { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name) } } #[derive(Clone, Debug, PartialEq)] pub(crate) enum ReaderData { Commented { comments: Vec<Comment>, data: Box<Self>, }, Integer(Integer), Keyword(Keyword), List { span: Span, items: Vec<Self>, }, Map { span: Span, items: Vec<Self>, }, String(String), Symbol(Symbol), Vector { span: Span, items: Vec<Self>, }, } impl ReaderData { fn commented(data: Self, comments: &mut Vec<Comment>) -> Self { if comments.is_empty() { data } else { Self::Commented { comments: comments.drain(..).collect(), data: Box::new(data), } } } fn integer(span: Span, value: i32) -> Self { Self::Integer(Integer::new(span, value)) } fn keyword(span: Span, name: RString) -> Self { Self::Keyword(Keyword::new(span, name)) } fn list(span: Span, items: Vec<Self>) -> Self { Self::List { span, items } } fn map(span: Span, items: Vec<Self>) -> Self { Self::Map { span, items } } fn string(span: Span, value: RString) -> Self { Self::String(String::new(span, value)) } fn symbol(span: Span, name: RString) -> Self { Self::Symbol(Symbol::new(span, name)) } fn vector(span: Span, items: Vec<Self>) -> Self { Self::Vector { span, items } } fn fmt_list(f: &mut fmt::Formatter<'_>, _: &Span, items: &[ReaderData]) -> fmt::Result { let mut output: RString = "(".to_owned(); if !items.is_empty() { output.push_str(&items[0].to_string()); for item in &items[1..] { output.push(' '); output.push_str(&item.to_string()); } } output.push(')'); write!(f, "{}", output) } fn fmt_map(f: &mut fmt::Formatter<'_>, _: &Span, items: &[ReaderData]) -> fmt::Result { let mut output: RString = "{".to_owned(); if !items.is_empty() { output.push_str(&items[0].to_string()); for item in &items[1..] { output.push(' '); output.push_str(&item.to_string()); } } output.push('}'); write!(f, "{}", output) } fn fmt_vector(f: &mut fmt::Formatter<'_>, _: &Span, items: &[ReaderData]) -> fmt::Result { let mut output: RString = "[".to_owned(); if !items.is_empty() { output.push_str(&items[0].to_string()); for item in &items[1..] { output.push(' '); output.push_str(&item.to_string()); } } output.push(']'); write!(f, "{}", output) } pub(crate) fn span(&self) -> &Span { match self { Self::Commented { data, .. } => data.span(), Self::Integer(integer) => integer.span(), Self::Keyword(keyword) => keyword.span(), Self::List { span, .. } => span, Self::Map { span, .. } => span, Self::String(string) => string.span(), Self::Symbol(symbol) => symbol.span(), Self::Vector { span, .. } => span, } } } impl fmt::Display for ReaderData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Commented { data, .. } => write!(f, "{}", data), Self::Integer(integer) => write!(f, "{}", integer), Self::Keyword(keyword) => write!(f, "{}", keyword), Self::List { span, items } => Self::fmt_list(f, span, items), Self::Map { span, items } => Self::fmt_map(f, span, items), Self::String(string) => write!(f, "{}", string), Self::Symbol(symbol) => write!(f, "{}", symbol), Self::Vector { span, items } => Self::fmt_vector(f, span, items), } } } pub(super) struct Parser; impl Parser { pub(super) fn parse(tokens: &mut Vec<Token>) -> Result<ReaderData> { let mut comments = Vec::new(); tokens.reverse(); loop { match tokens.pop() { Some(Token::StartList { start }) => { tokens.reverse(); return Ok(ReaderData::commented( Self::parse_list(tokens, start)?, &mut comments, )); } Some(Token::StartMap { start }) => { tokens.reverse(); return Ok(ReaderData::commented( Self::parse_map(tokens, start)?, &mut comments, )); } Some(Token::StartVector { start }) => { tokens.reverse(); return Ok(ReaderData::commented( Self::parse_vector(tokens, start)?, &mut comments, )); } Some(Token::Symbol { name, start, end }) => { tokens.reverse(); return Ok(ReaderData::commented( Self::parse_symbol(name, start, end)?, &mut comments, )); } Some(Token::Integer { value, start, end }) => { tokens.reverse(); return Ok(ReaderData::commented( Self::parse_integer(value, start, end)?, &mut comments, )); } Some(Token::Keyword { name, start, end }) => { tokens.reverse(); return Ok(ReaderData::commented( Self::parse_keyword(name, start, end)?, &mut comments, )); } Some(Token::String { value, start, end }) => { tokens.reverse(); return Ok(ReaderData::commented( Self::parse_string(value, start, end)?, &mut comments, )); } Some(Token::LineComment { comment, start, end, }) => { comments.push(Comment::new(Span::new(start, end), comment)); } Some(Token::EndList { start }) => { return Err(format!("ParseError: unexpected ')' at {}", start)); } Some(Token::EndMap { start }) => { return Err(format!("ParseError: unexpected '}}' at {}", start)); } Some(Token::EndVector { start }) => { return Err(format!("ParseError: unexpected ']' at {}", start)); } None => return Err("ParseError: empty input".to_owned()), } } } fn parse_integer(value: RString, start: Location, end: Location) -> Result<ReaderData> { let span = Span::new(start, end); match value.parse() { Ok(value) => Ok(ReaderData::integer(span, value)), Err(err) => Err(format!( "ParseError: unexpected invalid integer literal at {}: {}", span, err )), } } fn parse_keyword(name: RString, start: Location, end: Location) -> Result<ReaderData> { Ok(ReaderData::keyword(Span::new(start, end), name)) } fn parse_list(tokens: &mut Vec<Token>, start: Location) -> Result<ReaderData> { let mut comments = Vec::new(); let mut items: Vec<ReaderData> = Vec::new(); tokens.reverse(); while let Some(token) = tokens.pop() { match token { Token::Symbol { name, start, end } => { items.push(Self::parse_symbol(name, start, end)?) } Token::Integer { value, start, end } => { items.push(Self::parse_integer(value, start, end)?) } Token::Keyword { name, start, end } => { items.push(Self::parse_keyword(name, start, end)?) } Token::String { value, start, end } => { items.push(Self::parse_string(value, start, end)?) } Token::EndList { start: end } => { tokens.reverse(); return Ok(ReaderData::list(Span::new(start, end), items)); } Token::StartList { start } => { tokens.reverse(); items.push(Self::parse_list(tokens, start)?); tokens.reverse(); } Token::StartMap { start } => { tokens.reverse(); items.push(Self::parse_map(tokens, start)?); tokens.reverse(); } Token::StartVector { start } => { tokens.reverse(); items.push(Self::parse_vector(tokens, start)?); tokens.reverse(); } Token::LineComment { comment, start, end, } => { comments.push(Comment::new(Span::new(start, end), comment)); } Token::EndMap { start: end } => { return Err(format!( "ParseError: list starting at {} expected ')', found lone '}}' at {}", start, end )) } Token::EndVector { start: end } => { return Err(format!( "ParseError: list starting at {} expected ')', found lone ']' at {}", start, end )) } } } Err("ParseError: expected ')', found end of input".to_owned()) } fn parse_map(tokens: &mut Vec<Token>, start: Location) -> Result<ReaderData> { let mut comments = Vec::new(); let mut items: Vec<ReaderData> = Vec::new(); tokens.reverse(); while let Some(token) = tokens.pop() { match token { Token::Symbol { name, start, end } => { items.push(ReaderData::commented( Self::parse_symbol(name, start, end)?, &mut comments, )); } Token::Integer { value, start, end } => { items.push(ReaderData::commented( Self::parse_integer(value, start, end)?, &mut comments, )); } Token::Keyword { name, start, end } => { items.push(ReaderData::commented( Self::parse_keyword(name, start, end)?, &mut comments, )); } Token::String { value, start, end } => { items.push(ReaderData::commented( Self::parse_string(value, start, end)?, &mut comments, )); } Token::EndMap { start: end } => { tokens.reverse(); if items.len() % 2 == 0 { return Ok(ReaderData::commented( ReaderData::map(Span::new(start, end), items), &mut comments, )); } else { let last_key = items.pop().unwrap(); return Err(format!("ParseError: map starting at {} expected key value pairs, found lone key {} at {}", start, last_key, last_key.span())); } } Token::StartList { start } => { tokens.reverse(); items.push(ReaderData::commented( Self::parse_list(tokens, start)?, &mut comments, )); tokens.reverse(); } Token::StartMap { start } => { tokens.reverse(); items.push(ReaderData::commented( Self::parse_map(tokens, start)?, &mut comments, )); tokens.reverse(); } Token::StartVector { start } => { tokens.reverse(); items.push(ReaderData::commented( Self::parse_vector(tokens, start)?, &mut comments, )); tokens.reverse(); } Token::LineComment { comment, start, end, } => { comments.push(Comment::new(Span::new(start, end), comment)); } Token::EndList { start: end } => { return Err(format!( "ParseError: map starting at {} expected '}}', found lone ')' at {}", start, end )) } Token::EndVector { start: end } => { return Err(format!( "ParseError: map starting at {} expected '}}', found lone ']' at {}", start, end )) } } } Err("ParseError: expected '}', found end of input".to_owned()) } fn parse_string(value: RString, start: Location, end: Location) -> Result<ReaderData> { Ok(ReaderData::string(Span::new(start, end), value)) } fn parse_symbol(name: RString, start: Location, end: Location) -> Result<ReaderData> { Ok(ReaderData::symbol(Span::new(start, end), name)) } fn parse_vector(tokens: &mut Vec<Token>, start: Location) -> Result<ReaderData> { let mut comments = Vec::new(); let mut items: Vec<ReaderData> = Vec::new(); tokens.reverse(); while let Some(token) = tokens.pop() { match token { Token::Symbol { name, start, end } => { items.push(ReaderData::commented( Self::parse_symbol(name, start, end)?, &mut comments, )); } Token::Integer { value, start, end } => { items.push(ReaderData::commented( Self::parse_integer(value, start, end)?, &mut comments, )); } Token::Keyword { name, start, end } => { items.push(ReaderData::commented( Self::parse_keyword(name, start, end)?, &mut comments, )); } Token::String { value, start, end } => { items.push(ReaderData::commented( Self::parse_string(value, start, end)?, &mut comments, )); } Token::EndVector { start: end } => { tokens.reverse(); return Ok(ReaderData::commented( ReaderData::vector(Span::new(start, end), items), &mut comments, )); } Token::StartList { start } => { tokens.reverse(); items.push(ReaderData::commented( Self::parse_list(tokens, start)?, &mut comments, )); tokens.reverse(); } Token::StartMap { start } => { tokens.reverse(); items.push(ReaderData::commented( Self::parse_map(tokens, start)?, &mut comments, )); tokens.reverse(); } Token::StartVector { start } => { tokens.reverse(); items.push(ReaderData::commented( Self::parse_vector(tokens, start)?, &mut comments, )); tokens.reverse(); } Token::LineComment { comment, start, end, } => { comments.push(Comment::new(Span::new(start, end), comment)); } Token::EndList { start: end } => { return Err(format!( "ParseError: vector starting at {} expected ']', found lone ')' at {}", start, end )) } Token::EndMap { start: end } => { return Err(format!( "ParseError: vector starting at {} expected ']', found lone '}}' at {}", start, end )) } } } Err("ParseError: expected ']', found end of input".to_owned()) } } #[cfg(test)] pub(in crate::reader) mod tests { use super::super::lexer::tests::{self as token}; use super::*; pub(in crate::reader) fn comment( comment: impl Into<RString>, start: usize, end: usize, ) -> Comment { Comment::new( Span::new(Location::new(start), Location::new(end)), comment.into(), ) } pub(in crate::reader) fn commented(comments: Vec<Comment>, data: ReaderData) -> ReaderData { let mut comments = comments; ReaderData::commented(data, &mut comments) } pub(in crate::reader) fn integer(value: i32, start: usize, end: usize) -> ReaderData { ReaderData::integer(Span::new(Location::new(start), Location::new(end)), value) } pub(in crate::reader) fn keyword( name: impl Into<RString>, start: usize, end: usize, ) -> ReaderData { ReaderData::keyword( Span::new(Location::new(start), Location::new(end)), name.into(), ) } pub(in crate::reader) fn list(items: Vec<ReaderData>, start: usize, end: usize) -> ReaderData { ReaderData::list(Span::new(Location::new(start), Location::new(end)), items) } pub(in crate::reader) fn map(items: Vec<ReaderData>, start: usize, end: usize) -> ReaderData { ReaderData::map(Span::new(Location::new(start), Location::new(end)), items) } pub(in crate::reader) fn string( value: impl Into<RString>, start: usize, end: usize, ) -> ReaderData { ReaderData::string( Span::new(Location::new(start), Location::new(end)), value.into(), ) } pub(in crate::reader) fn symbol( name: impl Into<RString>, start: usize, end: usize, ) -> ReaderData { ReaderData::symbol( Span::new(Location::new(start), Location::new(end)), name.into(), ) } pub(in crate::reader) fn vector( items: Vec<ReaderData>, start: usize, end: usize, ) -> ReaderData { ReaderData::vector(Span::new(Location::new(start), Location::new(end)), items) } #[test] fn test_integer() { let mut tokens = vec![token::integer("0", 0, 1)]; assert_eq!(Parser::parse(&mut tokens), Ok(integer(0, 0, 1))); let mut tokens = vec![token::integer("123", 5, 8)]; assert_eq!(Parser::parse(&mut tokens), Ok(integer(123, 5, 8))); } #[test] fn test_keyword() { let mut tokens = vec![token::keyword("keyword", 1, 8)]; assert_eq!(Parser::parse(&mut tokens), Ok(keyword("keyword", 1, 8))); let mut tokens = vec![ token::keyword("too", 7, 11), token::keyword("many", 13, 18), token::keyword("keywords", 21, 30), token::keyword("right", 31, 37), token::keyword("now", 39, 43), ]; assert_eq!(Parser::parse(&mut tokens), Ok(keyword("too", 7, 11))); assert_eq!(Parser::parse(&mut tokens), Ok(keyword("many", 13, 18))); assert_eq!(Parser::parse(&mut tokens), Ok(keyword("keywords", 21, 30))); assert_eq!(Parser::parse(&mut tokens), Ok(keyword("right", 31, 37))); assert_eq!(Parser::parse(&mut tokens), Ok(keyword("now", 39, 43))); } #[test] fn test_list() { let mut tokens = vec![token::start_list(0), token::end_list(1)]; assert_eq!(Parser::parse(&mut tokens), Ok(list(Vec::new(), 0, 1))); let mut tokens = vec![ token::start_list(0), token::start_list(1), token::end_list(2), token::end_list(3), ]; assert_eq!( Parser::parse(&mut tokens), Ok(list(vec![list(Vec::new(), 1, 2)], 0, 3)) ); let mut tokens = vec![ token::start_list(0), token::end_list(1), token::start_list(2), token::end_list(3), ]; assert_eq!(Parser::parse(&mut tokens), Ok(list(Vec::new(), 0, 1))); assert_eq!(Parser::parse(&mut tokens), Ok(list(Vec::new(), 2, 3))); let mut tokens = vec![ token::start_list(0), token::symbol("symbol", 1, 7), token::end_list(7), ]; assert_eq!( Parser::parse(&mut tokens), Ok(list(vec![symbol("symbol", 1, 7)], 0, 7)) ); let mut tokens = vec![ token::start_list(0), token::integer("1", 1, 2), token::integer("23", 3, 5), token::end_list(6), ]; assert_eq!( Parser::parse(&mut tokens), Ok(list(vec![integer(1, 1, 2), integer(23, 3, 5)], 0, 6)) ); } #[test] fn test_map() { let mut tokens = vec![token::start_map(0), token::end_map(1)]; assert_eq!(Parser::parse(&mut tokens), Ok(map(Vec::new(), 0, 1))); let mut tokens = vec![ token::start_map(0), token::start_map(1), token::end_map(2), token::start_map(4), token::end_map(5), token::end_map(6), ]; assert_eq!( Parser::parse(&mut tokens), Ok(map( vec![map(Vec::new(), 1, 2), map(Vec::new(), 4, 5)], 0, 6 )) ); let mut tokens = vec![ token::start_map(0), token::end_map(1), token::start_map(2), token::end_map(3), ]; assert_eq!(Parser::parse(&mut tokens), Ok(map(Vec::new(), 0, 1))); assert_eq!(Parser::parse(&mut tokens), Ok(map(Vec::new(), 2, 3))); let mut tokens = vec![ token::start_map(0), token::symbol("key", 1, 4), token::symbol("value", 5, 10), token::end_map(10), ]; assert_eq!( Parser::parse(&mut tokens), Ok(map( vec![symbol("key", 1, 4), symbol("value", 5, 10)], 0, 10 )) ); let mut tokens = vec![ token::start_map(0), token::integer("1", 1, 2), token::integer("23", 3, 5), token::integer("456", 6, 9), token::integer("7890", 10, 14), token::end_map(14), ]; assert_eq!( Parser::parse(&mut tokens), Ok(map( vec![ integer(1, 1, 2), integer(23, 3, 5), integer(456, 6, 9), integer(7890, 10, 14), ], 0, 14 )) ); } #[test] fn test_string() { let mut tokens = vec![token::string("", 0, 2)]; assert_eq!(Parser::parse(&mut tokens), Ok(string("", 0, 2))); let mut tokens = vec![token::string("string", 0, 8)]; assert_eq!(Parser::parse(&mut tokens), Ok(string("string", 0, 8))); let mut tokens = vec![ token::string("one", 7, 12), token::string("string", 14, 22), token::string("then", 25, 31), token::string("a", 34, 37), token::string("second", 39, 47), token::string("finally", 48, 57), token::string("a", 61, 64), token::string("third", 66, 73), ]; assert_eq!(Parser::parse(&mut tokens), Ok(string("one", 7, 12))); assert_eq!(Parser::parse(&mut tokens), Ok(string("string", 14, 22))); assert_eq!(Parser::parse(&mut tokens), Ok(string("then", 25, 31))); assert_eq!(Parser::parse(&mut tokens), Ok(string("a", 34, 37))); assert_eq!(Parser::parse(&mut tokens), Ok(string("second", 39, 47))); assert_eq!(Parser::parse(&mut tokens), Ok(string("finally", 48, 57))); assert_eq!(Parser::parse(&mut tokens), Ok(string("a", 61, 64))); assert_eq!(Parser::parse(&mut tokens), Ok(string("third", 66, 73))); } #[test] fn test_symbol() { let mut tokens = vec![token::symbol("symbol", 0, 6)]; assert_eq!(Parser::parse(&mut tokens), Ok(symbol("symbol", 0, 6))); let mut tokens = vec![ token::symbol("many", 7, 11), token::symbol("symbols", 13, 20), token::symbol("one", 23, 26), token::symbol("at", 28, 30), token::symbol("a", 34, 35), token::symbol("time", 36, 40), ]; assert_eq!(Parser::parse(&mut tokens), Ok(symbol("many", 7, 11))); assert_eq!(Parser::parse(&mut tokens), Ok(symbol("symbols", 13, 20))); assert_eq!(Parser::parse(&mut tokens), Ok(symbol("one", 23, 26))); assert_eq!(Parser::parse(&mut tokens), Ok(symbol("at", 28, 30))); assert_eq!(Parser::parse(&mut tokens), Ok(symbol("a", 34, 35))); assert_eq!(Parser::parse(&mut tokens), Ok(symbol("time", 36, 40))); } #[test] fn test_vector() { let mut tokens = vec![token::start_vector(0), token::end_vector(1)]; assert_eq!(Parser::parse(&mut tokens), Ok(vector(Vec::new(), 0, 1))); let mut tokens = vec![ token::start_vector(0), token::start_vector(1), token::end_vector(2), token::end_vector(3), ]; assert_eq!( Parser::parse(&mut tokens), Ok(vector(vec![vector(Vec::new(), 1, 2)], 0, 3)) ); let mut tokens = vec![ token::start_vector(0), token::end_vector(1), token::start_vector(2), token::end_vector(3), ]; assert_eq!(Parser::parse(&mut tokens), Ok(vector(Vec::new(), 0, 1))); assert_eq!(Parser::parse(&mut tokens), Ok(vector(Vec::new(), 2, 3))); let mut tokens = vec![ token::start_vector(0), token::symbol("symbol", 1, 7), token::end_vector(7), ]; assert_eq!( Parser::parse(&mut tokens), Ok(vector(vec![symbol("symbol", 1, 7)], 0, 7)) ); let mut tokens = vec![ token::start_vector(0), token::integer("1", 1, 2), token::integer("23", 3, 5), token::end_vector(6), ]; assert_eq!( Parser::parse(&mut tokens), Ok(vector(vec![integer(1, 1, 2), integer(23, 3, 5)], 0, 6)) ); } }
#[allow(unused_imports)] use super::prelude::*; use super::intcode::{DeviceStatus, IntcodeDevice}; type Input = IntcodeDevice; pub fn input_generator(input: &str) -> Input { input.parse().expect("Error parsing the IntcodeDevice") } pub fn part1(input: &Input) -> i64 { let device = input; let mut max = std::i64::MIN; for (a,b,c,d,e) in permutations_iter() { let mut input = 0; for n in &[a,b,c,d,e] { let mut device = device.clone(); device.input.push_back(*n); device.input.push_back(input); device.execute(); input = device.output.pop_back().expect("No output from IntcodeDevice"); } max = if input > max { input } else { max }; } max } pub fn part2(input: &Input) -> i64 { let device = input; let mut max = std::i64::MIN; for (a,b,c,d,e) in permutations_iter() { let mut devices = [device.clone(), device.clone(), device.clone(), device.clone(), device.clone()]; for (device, phase) in devices.iter_mut().zip([a,b,c,d,e].iter()) { device.input.push_back(phase+5); } let mut buffer = vec![0]; let output = 'output: loop { for (i, device) in devices.iter_mut().enumerate() { device.input.append(&mut buffer.into()); let execute_result = device.execute(); buffer = device.output.drain(..).collect(); if let DeviceStatus::Halt = execute_result { if i == 4 { break 'output buffer.get(0).cloned().expect("No output from IntcodeDevice"); } } } }; max = if output > max { output } else { max }; } max } fn permutations_iter() -> impl Iterator<Item = (i64, i64, i64, i64, i64)> { (0..5) .flat_map(|a| (0..5).filter(move|&b| b != a).map(move|b| (a,b))) .flat_map(|(a,b)| (0..5).filter(move|&c| c != b && c != a).map(move|c|(a,b,c))) .flat_map(|(a,b,c)| (0..5).filter(move|&d| d != a && d != b && d != c).map(move|d|(a,b,c,d))) .flat_map(|(a,b,c,d)| (0..5).filter(move|&e| e != a && e != b && e != c && e != d).map(move|e|(a,b,c,d,e))) }
#[doc = "Register `MACMDIODR` reader"] pub type R = crate::R<MACMDIODR_SPEC>; #[doc = "Register `MACMDIODR` writer"] pub type W = crate::W<MACMDIODR_SPEC>; #[doc = "Field `MD` reader - MII Data"] pub type MD_R = crate::FieldReader<u16>; #[doc = "Field `MD` writer - MII Data"] pub type MD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; #[doc = "Field `RA` reader - Register Address"] pub type RA_R = crate::FieldReader<u16>; #[doc = "Field `RA` writer - Register Address"] pub type RA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; impl R { #[doc = "Bits 0:15 - MII Data"] #[inline(always)] pub fn md(&self) -> MD_R { MD_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - Register Address"] #[inline(always)] pub fn ra(&self) -> RA_R { RA_R::new(((self.bits >> 16) & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - MII Data"] #[inline(always)] #[must_use] pub fn md(&mut self) -> MD_W<MACMDIODR_SPEC, 0> { MD_W::new(self) } #[doc = "Bits 16:31 - Register Address"] #[inline(always)] #[must_use] pub fn ra(&mut self) -> RA_W<MACMDIODR_SPEC, 16> { RA_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "MDIO data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`macmdiodr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`macmdiodr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MACMDIODR_SPEC; impl crate::RegisterSpec for MACMDIODR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`macmdiodr::R`](R) reader structure"] impl crate::Readable for MACMDIODR_SPEC {} #[doc = "`write(|w| ..)` method takes [`macmdiodr::W`](W) writer structure"] impl crate::Writable for MACMDIODR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets MACMDIODR to value 0"] impl crate::Resettable for MACMDIODR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Reader of register SW_SHIELD_SEL"] pub type R = crate::R<u32, super::SW_SHIELD_SEL>; #[doc = "Writer for register SW_SHIELD_SEL"] pub type W = crate::W<u32, super::SW_SHIELD_SEL>; #[doc = "Register SW_SHIELD_SEL `reset()`'s with value 0"] impl crate::ResetValue for super::SW_SHIELD_SEL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SW_HCAV`"] pub type SW_HCAV_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SW_HCAV`"] pub struct SW_HCAV_W<'a> { w: &'a mut W, } impl<'a> SW_HCAV_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 & !0x07) | ((value as u32) & 0x07); self.w } } #[doc = "Reader of field `SW_HCAG`"] pub type SW_HCAG_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SW_HCAG`"] pub struct SW_HCAG_W<'a> { w: &'a mut W, } impl<'a> SW_HCAG_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 & !(0x07 << 4)) | (((value as u32) & 0x07) << 4); self.w } } #[doc = "Reader of field `SW_HCBV`"] pub type SW_HCBV_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SW_HCBV`"] pub struct SW_HCBV_W<'a> { w: &'a mut W, } impl<'a> SW_HCBV_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 & !(0x07 << 8)) | (((value as u32) & 0x07) << 8); self.w } } #[doc = "Reader of field `SW_HCBG`"] pub type SW_HCBG_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SW_HCBG`"] pub struct SW_HCBG_W<'a> { w: &'a mut W, } impl<'a> SW_HCBG_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 & !(0x07 << 12)) | (((value as u32) & 0x07) << 12); self.w } } #[doc = "Reader of field `SW_HCCV`"] pub type SW_HCCV_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SW_HCCV`"] pub struct SW_HCCV_W<'a> { w: &'a mut W, } impl<'a> SW_HCCV_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `SW_HCCG`"] pub type SW_HCCG_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SW_HCCG`"] pub struct SW_HCCG_W<'a> { w: &'a mut W, } impl<'a> SW_HCCG_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } impl R { #[doc = "Bits 0:2 - N/A"] #[inline(always)] pub fn sw_hcav(&self) -> SW_HCAV_R { SW_HCAV_R::new((self.bits & 0x07) as u8) } #[doc = "Bits 4:6 - Select waveform for corresponding switch"] #[inline(always)] pub fn sw_hcag(&self) -> SW_HCAG_R { SW_HCAG_R::new(((self.bits >> 4) & 0x07) as u8) } #[doc = "Bits 8:10 - N/A"] #[inline(always)] pub fn sw_hcbv(&self) -> SW_HCBV_R { SW_HCBV_R::new(((self.bits >> 8) & 0x07) as u8) } #[doc = "Bits 12:14 - Select waveform for corresponding switch, using csd_shield as base"] #[inline(always)] pub fn sw_hcbg(&self) -> SW_HCBG_R { SW_HCBG_R::new(((self.bits >> 12) & 0x07) as u8) } #[doc = "Bit 16 - Set corresponding switch"] #[inline(always)] pub fn sw_hccv(&self) -> SW_HCCV_R { SW_HCCV_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 20 - Set corresponding switch If the ADC is enabled then this switch is directly controlled by the ADC sequencer."] #[inline(always)] pub fn sw_hccg(&self) -> SW_HCCG_R { SW_HCCG_R::new(((self.bits >> 20) & 0x01) != 0) } } impl W { #[doc = "Bits 0:2 - N/A"] #[inline(always)] pub fn sw_hcav(&mut self) -> SW_HCAV_W { SW_HCAV_W { w: self } } #[doc = "Bits 4:6 - Select waveform for corresponding switch"] #[inline(always)] pub fn sw_hcag(&mut self) -> SW_HCAG_W { SW_HCAG_W { w: self } } #[doc = "Bits 8:10 - N/A"] #[inline(always)] pub fn sw_hcbv(&mut self) -> SW_HCBV_W { SW_HCBV_W { w: self } } #[doc = "Bits 12:14 - Select waveform for corresponding switch, using csd_shield as base"] #[inline(always)] pub fn sw_hcbg(&mut self) -> SW_HCBG_W { SW_HCBG_W { w: self } } #[doc = "Bit 16 - Set corresponding switch"] #[inline(always)] pub fn sw_hccv(&mut self) -> SW_HCCV_W { SW_HCCV_W { w: self } } #[doc = "Bit 20 - Set corresponding switch If the ADC is enabled then this switch is directly controlled by the ADC sequencer."] #[inline(always)] pub fn sw_hccg(&mut self) -> SW_HCCG_W { SW_HCCG_W { w: self } } }
use nmp::models::task::{Task, TaskPriority, TaskState}; mod test_data; #[test] fn to_org() { let org = "* DONE [#C] Test\nLorem ipsum dolor"; let task = test_data::get_testable_task(TaskPriority::C, TaskState::DONE); assert_eq!(task.to_org(), org); } #[test] fn toggle_state() { let mut task = test_data::get_testable_task(TaskPriority::B, TaskState::TODO); task.toggle_state(); assert_eq!(task.state, TaskState::DONE); } #[test] fn increment_priority() { let mut task = test_data::get_testable_task(TaskPriority::B, TaskState::TODO); task.increment_priority(); assert_eq!(task.priority, TaskPriority::A); }
use crate::features::syntax::MiscFeature; use crate::features::syntax::StatementFeature; use crate::parse::visitor::tests::assert_misc_feature; use crate::parse::visitor::tests::assert_no_misc_feature; use crate::parse::visitor::tests::assert_stmt_feature; #[test] fn switch() { assert_stmt_feature( "switch (b) { case true: return false; case false: return true; }", StatementFeature::SwitchStatement, ); } #[test] fn case_clause() { assert_misc_feature( "switch (b) { case true: return false; case false: return true; }", MiscFeature::CaseClause, ); } #[test] fn default_clause() { assert_misc_feature( "switch (b) { case true: return false; default: { return true; } }", MiscFeature::DefaultClause, ); } #[test] fn distinct() { assert_no_misc_feature( "switch (0) { default: { return true; } }", MiscFeature::CaseClause, ); assert_no_misc_feature( "switch (0) { case 100: { return true; } }", MiscFeature::DefaultClause, ); }
struct L { head: i32, next: Vec<L> } fn get(l: &L, i: i32) -> i32 { if i == 0 { l.head } else { get(&l.next[0], i-1) } } fn set(l: &mut L, i: i32, v: i32) { if i == 0 { l.head = v; } else { set(&mut l.next[0], i-1, v); } } fn make(n: i32) -> L { if n == 1 { let r = L { head:0, next: vec![] }; r } else { let r = L { head:0, next: vec![make(n-1)] }; r } } fn print_row(mut r: &L, i: i32) { let mut j = 0; while j <= i { if r.head != 0 { print!("*"); } else { print!("0"); } r = &r.next[0]; j = j+1; } print!("\n"); } fn compute_row(r: &mut L, j: i32) { let mut v = 0; if j == 0 { v = 1; } else { v = (get(& *r, j) + get(& *r, j-1)) % 7; } set(&mut *r, j, v); if j > 0 { compute_row(r, j-1); } } fn main() { let h = 42; let mut r = make(h+1); let mut i = 0; while i < h { set(&mut r, i, 0); compute_row(&mut r, i); print_row(&r, i); i = i+1; } }
use op_gen::make_library; use std::fs::File; use std::io::prelude::*; fn main() { let mut file = File::create("test1.rs").unwrap(); file.write_all(b"#![allow(dead_code)]\n").unwrap(); file.write_all(b"#![allow(non_camel_case_types)]\n").unwrap(); file.write_all(make_library().as_ref()).unwrap(); }
use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; fn get_input() -> i32 { let mut file = File::open("input.txt").unwrap(); let mut content = String::new(); file.read_to_string(&mut content).unwrap(); content.parse().unwrap() } #[derive(Copy, Clone, Debug)] enum Direction { XPos, XNeg, YPos, YNeg } #[derive(Copy, Clone, Debug)] struct State { stride: i32, left: i32, x: i32, y: i32, dir: Direction } impl State { fn move_next(self: &mut State) { if self.left > 0 { match self.dir { Direction::XPos => self.x += 1, Direction::XNeg => self.x -= 1, Direction::YPos => self.y += 1, Direction::YNeg => self.y -= 1 } self.left -= 1; } else { match self.dir { Direction::XPos => { self.dir = Direction::YPos; self.y += 1; }, Direction::YPos => { self.stride += 1; self.dir = Direction::XNeg; self.x -= 1; }, Direction::XNeg => { self.dir = Direction::YNeg; self.y -= 1; }, Direction::YNeg => { self.stride += 1; self.dir = Direction::XPos; self.x += 1; } } self.left = self.stride - 1; } } fn move_next_value(self: &mut State, grid: &mut HashMap<(i32, i32), i32>) -> i32 { self.move_next(); let mut v = 0; v += grid.get(&(self.x + 1, self.y)).unwrap_or(&0); v += grid.get(&(self.x - 1, self.y)).unwrap_or(&0); v += grid.get(&(self.x, self.y + 1)).unwrap_or(&0); v += grid.get(&(self.x, self.y - 1)).unwrap_or(&0); v += grid.get(&(self.x + 1, self.y + 1)).unwrap_or(&0); v += grid.get(&(self.x + 1, self.y - 1)).unwrap_or(&0); v += grid.get(&(self.x - 1, self.y + 1)).unwrap_or(&0); v += grid.get(&(self.x - 1, self.y - 1)).unwrap_or(&0); grid.insert((self.x, self.y), v); v } } fn part_1(input: i32) -> i32 { let mut state = State { stride: 1, left: 1, x: 0, y: 0, dir: Direction::XPos }; for _ in 1 .. input { state.move_next(); } state.x.abs() + state.y.abs() } fn part_2(input: i32) -> i32 { let mut state = State { stride: 1, left: 1, x: 0, y: 0, dir: Direction::XPos }; let mut grid = HashMap::new(); grid.insert((0, 0), 1); let mut v = 1; while v <= input { v = state.move_next_value(&mut grid); } v } fn main() { let input = get_input(); println!("Part 1 distance: {}", part_1(input)); println!("Part 2 value: {}", part_2(input)); }
use std::time::Duration; use std::sync::{Arc, Mutex}; fn with_arc() -> String { let content = Arc::new(Mutex::new(String::new())); let cloned = content.clone(); std::thread::spawn(move || { let mut s = cloned.lock().unwrap(); s.push_str("thread"); }); std::thread::sleep(Duration::from_millis(1000)); let mut s = content.lock().unwrap(); s.push_str("hello"); String::from(s.as_str()) } fn with_channels() { let (sender, receiver) = std::sync::mpsc::channel::<Box<dyn Fn(&mut String) + Send>>(); let (done_s, done_r) = std::sync::mpsc::channel::<()>(); std::thread::spawn(move || { let mut hidden = String::new(); loop { match receiver.recv() { Ok(f) => { f(&mut hidden); println!("{}", hidden); }, Err(_) => { done_s.send(()).unwrap(); return; } }; } }); sender.send(Box::new(|s: &mut String| { s.push_str("foo"); })).unwrap(); let sender2 = sender.clone(); sender2.send(Box::new(|s: &mut String| { s.push_str("bar"); })).unwrap(); drop(sender); drop(sender2); done_r.recv().ok(); } #[cfg(test)] mod test { use super::*; struct Writer { s: String } unsafe impl Send for Writer {} impl Default for Writer { fn default() -> Self { Writer {s: String::new()} } } impl std::fmt::Write for Writer { fn write_str(&mut self, _s: &str) -> core::fmt::Result { self.s.push_str(_s); Ok(()) } } #[test] fn test_with_arc() { assert_eq!("threadhello", with_arc()); } #[test] fn test_with_channels() { //TODO: test something with_channels(); } }
use friday_error::FridayError; #[derive(Debug, Clone)] pub enum Prediction { Result { class: String, }, Silence, Inconclusive } pub trait Model { fn reset(&mut self) -> Result<(), FridayError>; fn predict(&mut self, v :&Vec<i16>) -> Result<Prediction, FridayError>; fn expected_frame_size(&self) -> usize; } pub struct DummyModel { ret: Prediction } impl DummyModel { pub fn new(c: String) -> DummyModel { return DummyModel{ ret: Prediction::Result { class: c, } } } } impl Model for DummyModel { fn predict(&mut self, _ :&Vec<i16>) -> Result<Prediction, FridayError> { return Ok(self.ret.clone()); } fn expected_frame_size(&self) -> usize { return 16000; } fn reset(&mut self) -> Result<(), FridayError> { Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn try_dummy() { let mut dummy = DummyModel::new(String::from("Hello")); let v: Vec<i16> = vec![0]; assert_eq!(dummy.predict(&v).unwrap().class, String::from("Hello")); } }
use crate::{event::InternalEvent, *}; use std::ops::Deref; /// The platform system context provided to the application main thread. /// /// It is used to allow the application to deal with platform events, and /// perform actions which must be done on the main thread (eg. creating windows). /// /// To acquire a context when using `riddle` (the **recommended** approach): /// /// * ` RiddleLib::context()` returns a `RiddleContext` which implements `Borrow<PlatformContext>`. /// * ` RiddleLib::run()` passes a `RiddleContext` to the application callback. /// /// To acquire a context when using this crate directly: /// /// * [`PlatformMainThreadState::borrow_context()`] /// * [`PlatformMainThreadState::run`] passes it to application callback /// /// # Example /// /// ```no_run /// use riddle::{*, platform::*}; /// /// fn main() -> Result<(), RiddleError> { /// let rdl = RiddleLib::new()?; /// /// // Get a context before the application starts the main event loop. /// let window_a: Window = WindowBuilder::new().build(rdl.context())?; /// let mut window_b: Option<Window> = None; /// /// rdl.run(move |rdl| { /// if window_b.is_none() { /// // rdl: RiddleContext, is used to build the second window. /// window_b = Some(WindowBuilder::new().build(rdl).unwrap()); /// } else { /// rdl.quit(); /// } /// # std::thread::sleep(std::time::Duration::from_secs(1)); /// }) /// } /// ``` pub struct PlatformContext<'a> { pub(crate) main_thread_state: &'a PlatformMainThreadState, pub(crate) event_loop: Option<&'a winit::event_loop::EventLoopWindowTarget<InternalEvent>>, pub(crate) triggering_event: PlatformEvent, } impl<'a> PlatformContext<'a> { pub(crate) fn with_event_loop<T, F>(&self, f: F) -> Result<T> where F: FnOnce(&winit::event_loop::EventLoopWindowTarget<InternalEvent>) -> Result<T>, { match self.event_loop { Some(el) => f(el), None => { let el_ref = self.main_thread_state.event_loop.borrow(); let el = el_ref.deref(); match el { Some(el) => f(el), None => Err(PlatformError::InvalidContext), } } } } /// Issue a quit request to the underlying platform system. /// /// The application will quit when that message is processed by the /// main event loop. pub fn quit(&self) -> Result<()> { self.main_thread_state .system .internal .event_proxy .lock() .unwrap() .send_event(InternalEvent::QuitRequested) .map_err(|_| PlatformError::MessageDispatch) } /// Get the event associated with the context. /// /// This will be the platform event that triggered the application closure, or /// [`PlatformEvent::Unknown`] if the context was created before the main event loop /// has started. pub fn event(&self) -> &PlatformEvent { &self.triggering_event } /// The platform system associated with this context. pub fn system(&self) -> &PlatformSystem { &self.main_thread_state.system } }
//! Contexts are the heart of both OpenCL and CUDA applications. Contexts provide a container for //! objects such as memory, command-queues, programs/modules and kernels. //! //! You can create a context encapsulating a selection of hardware via a [`Backend`]. //! //! [`Backend`]: ./struct.Backend.html use super::compute_device::ComputeDevice; use super::error::Result; use super::extension_package::ExtensionPackage; use super::hardware::Hardware; /// A trait implemented by all contexts. pub trait Context: 'static { /// The extension package built for the framework's context. type Package: ExtensionPackage; /// Returns the active device. fn active_codev(&self) -> &ComputeDevice; /// Returns the package extension. fn extension(&self) -> &<Self::Package as ExtensionPackage>::Extension; /// Set the device at the specified `index` as the active device. /// /// Only one device can be the _active_ device - the device in which operations are executed - /// if used through the context. fn activate(&mut self, index: usize) -> Result; } /// The non-object-safe part of the `Context`. /// /// todo: generic associated types may help here.. pub trait ContextCtor<Package> where Self: Context<Package=Package> + Sized, Package: ExtensionPackage { /// The framework representation for the context. type F; /// Constructs a new context from the `framework` and the `selection` of hardware. fn new(framework: &Self::F, selection: &[Hardware]) -> Result<Self>; }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedClusterList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ConnectedCluster>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedCluster { #[serde(flatten)] pub tracked_resource: TrackedResource, pub identity: ConnectedClusterIdentity, pub properties: ConnectedClusterProperties, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedClusterIdentity { #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "type")] pub type_: connected_cluster_identity::Type, } pub mod connected_cluster_identity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { None, SystemAssigned, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedClusterProperties { #[serde(rename = "agentPublicKeyCertificate")] pub agent_public_key_certificate: String, #[serde(rename = "kubernetesVersion", default, skip_serializing_if = "Option::is_none")] pub kubernetes_version: Option<String>, #[serde(rename = "totalNodeCount", default, skip_serializing_if = "Option::is_none")] pub total_node_count: Option<i64>, #[serde(rename = "totalCoreCount", default, skip_serializing_if = "Option::is_none")] pub total_core_count: Option<i32>, #[serde(rename = "agentVersion", default, skip_serializing_if = "Option::is_none")] pub agent_version: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<ConnectedClusterProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub distribution: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub infrastructure: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub offering: Option<String>, #[serde( rename = "managedIdentityCertificateExpirationTime", default, skip_serializing_if = "Option::is_none" )] pub managed_identity_certificate_expiration_time: Option<String>, #[serde(rename = "lastConnectivityTime", default, skip_serializing_if = "Option::is_none")] pub last_connectivity_time: Option<String>, #[serde(rename = "connectivityStatus", default, skip_serializing_if = "Option::is_none")] pub connectivity_status: Option<connected_cluster_properties::ConnectivityStatus>, } pub mod connected_cluster_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConnectivityStatus { Connecting, Connected, Offline, Expired, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CredentialResults { #[serde(rename = "hybridConnectionConfig", default, skip_serializing_if = "Option::is_none")] pub hybrid_connection_config: Option<HybridConnectionConfig>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub kubeconfigs: Vec<CredentialResult>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CredentialResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConnectedClusterProvisioningState { Succeeded, Failed, Canceled, Provisioning, Updating, Deleting, Accepted, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedClusterPatch { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ConnectedClusterPatchProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedClusterPatchProperties {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HybridConnectionConfig { #[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")] pub expiration_time: Option<i64>, #[serde(rename = "hybridConnectionName", default, skip_serializing_if = "Option::is_none")] pub hybrid_connection_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub relay: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub token: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ListClusterUserCredentialProperties { #[serde(rename = "authenticationMethod")] pub authentication_method: list_cluster_user_credential_properties::AuthenticationMethod, #[serde(rename = "clientProxy")] pub client_proxy: bool, } pub mod list_cluster_user_credential_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationMethod { Token, #[serde(rename = "AAD")] Aad, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SystemData { #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<String>, #[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")] pub created_by_type: Option<system_data::CreatedByType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")] pub last_modified_by_type: Option<system_data::LastModifiedByType>, #[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")] pub last_modified_at: Option<String>, } pub mod system_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CreatedByType { User, Application, ManagedIdentity, Key, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorDetail>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDetail { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<ErrorDetail>, #[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")] pub additional_info: Vec<ErrorAdditionalInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorAdditionalInfo { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub info: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrackedResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, pub location: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, }
use aoc_runner_derive::{aoc, aoc_generator}; use regex::Regex; pub struct Entry { min: usize, max: usize, letter: char, password: String, } #[aoc_generator(day2)] pub fn generator(input: &str) -> Vec<Entry> { let re = Regex::new(r"(\d*)-(\d*) (\w): (\w*)").unwrap(); input.lines() .map(|e| { let caps = re.captures(e).unwrap(); Entry { min: caps.get(1).unwrap().as_str().parse().unwrap(), max: caps.get(2).unwrap().as_str().parse().unwrap(), letter: caps.get(3).unwrap().as_str().chars().next().unwrap(), password: caps.get(4).unwrap().as_str().into(), } }) .collect() } #[aoc(day2, part1)] pub fn part1(input: &Vec<Entry>) -> usize { let mut count = 0; for e in input.iter() { let num = e.password.chars().filter(|c| *c == e.letter).count(); if num >= e.min && num <= e.max { count += 1; } } count } #[aoc(day2, part2)] pub fn part2(input: &Vec<Entry>) -> usize { let mut count = 0; for e in input.iter() { let num = e.password.chars() .enumerate() .filter(|&(i, _)| i+1 == e.min || i+1 == e.max) .map(|(_, e)| e) .filter(|c| *c == e.letter) .count(); if num == 1 { count += 1; } } count }
#![allow(dead_code)] use std::path::Path; use draw::*; use tool::Receiver; use image::math::nq::NeuQuant as NQ; fn get_pal(nq: &NQ) -> Vec<u32> { #[derive(Clone, Copy)] struct Quad<T> { r: T, g: T, b: T, a: T, } type Neuron = Quad<f64>; type Color = Quad<i32>; /// Neural network based color quantizer. pub struct NeuQuant { network: Vec<Neuron>, colormap: Vec<Color>, netindex: Vec<usize>, bias: Vec<f64>, // bias and freq arrays for learning freq: Vec<f64>, samplefac: i32, netsize: usize, } let nq: &NeuQuant = unsafe { ::std::mem::transmute(nq) }; let pal: Vec<_> = nq.colormap.iter() .map(|c| { ((c.r as u32) << 24) | ((c.g as u32) << 16) | ((c.b as u32) << 8) | ((c.a as u32) << 0) }) .collect(); pal } pub fn load_sprite<P: AsRef<Path>>(filename: P) -> Option<Receiver> { use image::{load, ImageFormat}; use image::imageops::{index_colors, dither}; use image::math::nq::NeuQuant; use std::fs::File; use std::io::BufReader; let format = { let ext = filename.as_ref().extension() .and_then(|s| s.to_str()) .map_or("".to_string(), |s| s.to_ascii_lowercase()); match &*ext { "gif" => ImageFormat::GIF, "png" => ImageFormat::PNG, "jpeg" | "jpg" => ImageFormat::JPEG, _ => unimplemented!(), } }; let name = filename .as_ref().file_name().unwrap() .to_str().unwrap() .to_string(); let reader = File::open(filename).unwrap(); let reader = BufReader::new(reader); let m = load(reader, format).unwrap(); let mut m = m.to_rgba(); let (w, h) = (m.width() as usize, m.height() as usize); let mut sprite = Receiver::new(&name, w, h); let data: Vec<u8> = m.pixels() .flat_map(|c| c.data.iter().map(|&u| u)) .collect(); let map = NeuQuant::new(10, 256, &data); dither(&mut m, &map); let m = index_colors(&m, &map); let mut page = Frame::new(w, h); for (i, p) in m.pixels().enumerate() { page.page[i] = p.data[0]; } sprite.add_layer_page("load", page); let pal = get_pal(&map); for (i, &c) in pal.iter().enumerate() { if i < 256 { sprite.palette[i as u8] = c; } } Some(sprite) } pub fn open_file() -> Option<String> { use nfd::{self, Response}; let result = nfd::dialog().filter("gif,png,jpg,jpeg").open().unwrap(); let result = match result { Response::Okay(file) => Some(file), Response::OkayMultiple(files) => Some(files[0].clone()), Response::Cancel => None, }; /* if let Some(filename) = result.clone() { // Open the file use std::fs::File; use gif; use gif::SetParameter; let file = File::open(filename).unwrap(); let mut decoder = gif::Decoder::new(file); // Configure the decoder such that it will expand the image to RGBA. decoder.set(gif::ColorOutput::Indexed); // Read the file header let mut decoder = decoder.read_info().unwrap(); println!("{}x{} has_pal: {} bg: {:?}", decoder.width(), decoder.height(), decoder.global_palette().is_some(), decoder.bg_color(), ); while let Some(frame) = decoder.read_next_frame().unwrap() { // Process every frame println!("frame[{}]: {}x{} {}x{}, transparent: {:?} dis: {:?}", frame.palette.is_some(), frame.top, frame.left, frame.width, frame.height, frame.transparent, frame.dispose); } } */ result }
use addressing; use addressing::AddressTypeError; use sphinx::route::{Destination, DestinationAddressBytes, SURBIdentifier}; use sphinx::SphinxPacket; use std::net::SocketAddr; use std::time; use topology::{NymTopology, NymTopologyError}; pub const LOOP_COVER_MESSAGE_PAYLOAD: &[u8] = b"The cake is a lie!"; #[derive(Debug)] pub enum SphinxPacketEncapsulationError { NoValidProvidersError, InvalidTopologyError, SphinxEncapsulationError(sphinx::header::SphinxUnwrapError), InvalidFirstMixAddress, } impl From<topology::NymTopologyError> for SphinxPacketEncapsulationError { fn from(_: NymTopologyError) -> Self { use SphinxPacketEncapsulationError::*; InvalidTopologyError } } // it is correct error we're converting from, it just has an unfortunate name // related issue: https://github.com/nymtech/sphinx/issues/40 impl From<sphinx::header::SphinxUnwrapError> for SphinxPacketEncapsulationError { fn from(err: sphinx::header::SphinxUnwrapError) -> Self { use SphinxPacketEncapsulationError::*; SphinxEncapsulationError(err) } } impl From<AddressTypeError> for SphinxPacketEncapsulationError { fn from(_: AddressTypeError) -> Self { use SphinxPacketEncapsulationError::*; InvalidFirstMixAddress } } #[deprecated(note = "please use loop_cover_message_route instead")] pub fn loop_cover_message<T: NymTopology>( our_address: DestinationAddressBytes, surb_id: SURBIdentifier, topology: &T, average_delay: time::Duration, ) -> Result<(SocketAddr, SphinxPacket), SphinxPacketEncapsulationError> { let destination = Destination::new(our_address, surb_id); #[allow(deprecated)] encapsulate_message( destination, LOOP_COVER_MESSAGE_PAYLOAD.to_vec(), topology, average_delay, ) } pub fn loop_cover_message_route( our_address: DestinationAddressBytes, surb_id: SURBIdentifier, route: Vec<sphinx::route::Node>, average_delay: time::Duration, ) -> Result<(SocketAddr, SphinxPacket), SphinxPacketEncapsulationError> { let destination = Destination::new(our_address, surb_id); encapsulate_message_route( destination, LOOP_COVER_MESSAGE_PAYLOAD.to_vec(), route, average_delay, ) } #[deprecated(note = "please use encapsulate_message_route instead")] pub fn encapsulate_message<T: NymTopology>( recipient: Destination, message: Vec<u8>, topology: &T, average_delay: time::Duration, ) -> Result<(SocketAddr, SphinxPacket), SphinxPacketEncapsulationError> { let mut providers = topology.providers(); if providers.is_empty() { return Err(SphinxPacketEncapsulationError::NoValidProvidersError); } // unwrap is fine here as we asserted there is at least single provider let provider = providers.pop().unwrap().into(); let route = topology.route_to(provider)?; let delays = sphinx::header::delays::generate_from_average_duration(route.len(), average_delay); // build the packet let packet = sphinx::SphinxPacket::new(message, &route[..], &recipient, &delays)?; // we know the mix route must be valid otherwise we would have already returned an error let first_node_address = addressing::socket_address_from_encoded_bytes(route.first().unwrap().address.to_bytes())?; Ok((first_node_address, packet)) } pub fn encapsulate_message_route( recipient: Destination, message: Vec<u8>, route: Vec<sphinx::route::Node>, average_delay: time::Duration, ) -> Result<(SocketAddr, SphinxPacket), SphinxPacketEncapsulationError> { let delays = sphinx::header::delays::generate_from_average_duration(route.len(), average_delay); // build the packet let packet = sphinx::SphinxPacket::new(message, &route[..], &recipient, &delays)?; let first_node_address = addressing::socket_address_from_encoded_bytes(route.first().unwrap().address.to_bytes())?; Ok((first_node_address, packet)) }
use clap::{App, Arg}; use reqwest; use serde_json::{Map, Value}; use std::io::{self, BufRead}; use threadpool::ThreadPool; fn main() { let args = App::new("Check Domain Availability") .version("0.1") .author("Mohamed Elbadry <me@melbadry9.xyz>") .arg( Arg::with_name("threads") .short("t") .long("threads") .value_name("THREADS") .help("Sets number of threads") .takes_value(true), ) .arg( Arg::with_name("domain") .short("d") .long("domain") .value_name("DOMAIN") .help("Sets domain to check") .takes_value(true), ) .get_matches(); if !(args.is_present("domain")) { let stream = io::stdin(); let pool = ThreadPool::new( args.value_of("threads") .unwrap_or("3") .parse::<usize>() .unwrap_or(3), ); for domain in stream.lock().lines() { pool.execute(|| check_av(&domain.unwrap())); } pool.join(); } else { check_av(&args.value_of("domain").unwrap().to_string()) } } fn check_av(domain: &String) { let url = format!("https://ae.godaddy.com/domainfind/v1/search/exact?key=dpp_search&partialQuery={}&q={}&req_id=1616029383106&solution_set_ids=dpp-us-solution-tier1%2Cdpp-intl-solution-tier4%2Cdpp-intl-solution-tier6%2Co365-solutionset-tier3%2Cdpp-us-solution-fixed-tier4&itc=dpp_absol1", &domain, &domain); let res = reqwest::blocking::get(url); match res { Ok(res) => { if res.status().is_success() { let js: Value = res.json().unwrap(); let obj: Map<String, Value> = js.as_object().unwrap().clone(); println!( "{}: {}", &domain, &obj["ExactMatchDomain"]["AvailabilityLabel"] .as_str() .unwrap() ) } } Err(_err) => println!("{}: Request Faild", &domain), }; }
//! Ethereum (Solidity) derivation for rust contracts (compiled to wasm or otherwise) #![recursion_limit = "128"] #![deny(unused)] extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate syn; #[macro_use] extern crate quote; extern crate byteorder; extern crate serde_json; extern crate tiny_keccak; #[macro_use(construct_fixed_hash)] extern crate fixed_hash; #[macro_use] extern crate serde_derive; mod error; mod items; mod utils; mod json; use proc_macro2::{Span}; use json::write_json_abi; use items::Item; use error::{Result, Error}; /// Arguments given to the `eth_abi` attribute macro. struct Args { /// The required name of the endpoint. endpoint_name: String, /// The optional name of the client. client_name: Option<String>, } impl Args { /// Extracts `eth_abi` argument information from the given `syn::AttributeArgs`. pub fn from_attribute_args(attr_args: syn::AttributeArgs) -> Result<Args> { if attr_args.len() == 0 || attr_args.len() > 2 { return Err(Error::invalid_number_of_arguments(0)); } let endpoint_name = if let syn::NestedMeta::Meta(syn::Meta::Word(ident)) = attr_args.get(0).unwrap() { Ok(ident.to_string()) } else { Err(Error::malformatted_argument(0)) }?; let client_name = attr_args .get(1) .map(|meta| { if let syn::NestedMeta::Meta(syn::Meta::Word(ident)) = meta { Ok(ident.to_string()) } else { Err(Error::malformatted_argument(1)) } }) .map(|meta| meta.unwrap()); Ok(Args { endpoint_name, client_name, }) } /// Returns the given endpoint name. pub fn endpoint_name(&self) -> &str { &self.endpoint_name } /// Returns the optional client name. pub fn client_name(&self) -> Option<&str> { self.client_name.as_ref().map(|s| s.as_str()) } } /// Derive of the Ethereum/Solidity ABI for the given trait interface. /// /// The first parameter represents the identifier of the generated endpoint /// implementation. The seconds parameter is optional and represents the /// identifier of the generated client implementation. /// /// # System Description /// /// ## Endpoint /// /// Converts ABI encoded payload into a called function with its parameters. /// /// ## Client /// /// Opposite of an endpoint that allows users (clients) to build up queries /// in the form of a payload to functions of a contract by a generated interface. /// /// # Example: Using just one argument /// /// ``` /// # #![feature(custom_attribute)] /// #[eth_abi(Endpoint)] /// trait Contract { } /// ``` /// /// Creates an endpoint implementation named `Endpoint` for the /// interface defined in the `Contract` trait. /// /// # Example: Using two arguments /// /// ``` /// # #![feature(custom_attribute)] /// #[eth_abi(Endpoint2, Client2)] /// trait Contract2 { } /// ``` /// /// Creates an endpoint implementation named `Endpoint2` and a /// client implementation named `Client2` for the interface /// defined in the `Contract2` trait. #[proc_macro_attribute] pub fn eth_abi( args: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let args_toks = parse_macro_input!(args as syn::AttributeArgs); let input_toks = parse_macro_input!(input as syn::Item); let output = match impl_eth_abi(args_toks, input_toks) { Ok(output) => output, Err(err) => panic!("[eth_abi] encountered error: {}", err), }; output.into() } /// Implementation of `eth_abi`. /// /// This convenience function is mainly used to better handle the results of token stream. fn impl_eth_abi(args: syn::AttributeArgs, input: syn::Item) -> Result<proc_macro2::TokenStream> { let args = Args::from_attribute_args(args)?; let intf = items::Interface::from_item(input); write_json_abi(&intf)?; match args.client_name() { None => generate_eth_endpoint_wrapper(&intf, args.endpoint_name()), Some(client_name) => { generate_eth_endpoint_and_client_wrapper(&intf, args.endpoint_name(), client_name) } } } /// Generates the eth abi code in case of a single provided endpoint. fn generate_eth_endpoint_wrapper( intf: &items::Interface, endpoint_name: &str, ) -> Result<proc_macro2::TokenStream> { // FIXME: Code duplication with `generate_eth_endpoint_and_client_wrapper` // We might want to fix this, however it is not critical. // >>> let name_ident_use = syn::Ident::new(intf.name(), Span::call_site()); let mod_name = format!("pwasm_abi_impl_{}", &intf.name().clone()); let mod_name_ident = syn::Ident::new(&mod_name, Span::call_site()); // FIXME: <<< let endpoint_toks = generate_eth_endpoint(endpoint_name, intf); let endpoint_ident = syn::Ident::new(endpoint_name, Span::call_site()); Ok(quote! { #intf #[allow(non_snake_case)] mod #mod_name_ident { extern crate pwasm_ethereum; extern crate pwasm_abi; use pwasm_abi::types::{H160, H256, U256, Address, Vec, String}; use super::#name_ident_use; #endpoint_toks } pub use self::#mod_name_ident::#endpoint_ident; }) } /// Generates the eth abi code in case of a provided endpoint and client. fn generate_eth_endpoint_and_client_wrapper( intf: &items::Interface, endpoint_name: &str, client_name: &str, ) -> Result<proc_macro2::TokenStream> { // FIXME: Code duplication with `generate_eth_endpoint_and_client_wrapper` // We might want to fix this, however it is not critical. // >>> let name_ident_use = syn::Ident::new(intf.name(), Span::call_site()); let mod_name = format!("pwasm_abi_impl_{}", &intf.name().clone()); let mod_name_ident = syn::Ident::new(&mod_name, Span::call_site()); // FIXME: <<< let endpoint_toks = generate_eth_endpoint(endpoint_name, &intf); let client_toks = generate_eth_client(client_name, &intf); let endpoint_name_ident = syn::Ident::new(endpoint_name, Span::call_site()); let client_name_ident = syn::Ident::new(&client_name, Span::call_site()); Ok(quote! { #intf #[allow(non_snake_case)] mod #mod_name_ident { extern crate pwasm_ethereum; extern crate pwasm_abi; use pwasm_abi::types::{H160, H256, U256, Address, Vec, String}; use super::#name_ident_use; #endpoint_toks #client_toks } pub use self::#mod_name_ident::#endpoint_name_ident; pub use self::#mod_name_ident::#client_name_ident; }) } fn generate_eth_client(client_name: &str, intf: &items::Interface) -> proc_macro2::TokenStream { let client_ctor = intf.constructor().map( |signature| utils::produce_signature( &signature.name, &signature.method_sig, quote! { #![allow(unused_mut)] #![allow(unused_variables)] unimplemented!() } ) ); let calls: Vec<proc_macro2::TokenStream> = intf.items().iter().filter_map(|item| { match *item { Item::Signature(ref signature) => { let hash_literal = syn::Lit::Int( syn::LitInt::new(signature.hash as u64, syn::IntSuffix::U32, Span::call_site())); let argument_push: Vec<proc_macro2::TokenStream> = utils::iter_signature(&signature.method_sig) .map(|(pat, _)| quote! { sink.push(#pat); }) .collect(); let argument_count_literal = syn::Lit::Int( syn::LitInt::new(argument_push.len() as u64, syn::IntSuffix::Usize, Span::call_site())); let result_instance = match signature.method_sig.decl.output { syn::ReturnType::Default => quote!{ let mut result = Vec::new(); }, syn::ReturnType::Type(_, _) => quote!{ let mut result = [0u8; 32]; }, }; let result_pop = match signature.method_sig.decl.output { syn::ReturnType::Default => None, syn::ReturnType::Type(_, _) => Some( quote!{ let mut stream = pwasm_abi::eth::Stream::new(&result); stream.pop().expect("failed decode call output") } ), }; Some(utils::produce_signature( &signature.name, &signature.method_sig, quote!{ #![allow(unused_mut)] #![allow(unused_variables)] let mut payload = Vec::with_capacity(4 + #argument_count_literal * 32); payload.push((#hash_literal >> 24) as u8); payload.push((#hash_literal >> 16) as u8); payload.push((#hash_literal >> 8) as u8); payload.push(#hash_literal as u8); let mut sink = pwasm_abi::eth::Sink::new(#argument_count_literal); #(#argument_push)* sink.drain_to(&mut payload); #result_instance pwasm_ethereum::call(self.gas.unwrap_or(200000), &self.address, self.value.clone().unwrap_or(U256::zero()), &payload, &mut result[..]) .expect("Call failed; todo: allow handling inside contracts"); #result_pop } )) }, Item::Event(ref event) => { Some(utils::produce_signature( &event.name, &event.method_sig, quote!{ #![allow(unused_variables)] panic!("cannot use event in client interface"); } )) }, _ => None, } }).collect(); let client_ident = syn::Ident::new(client_name, Span::call_site()); let name_ident = syn::Ident::new(intf.name(), Span::call_site()); quote! { pub struct #client_ident { gas: Option<u64>, address: Address, value: Option<U256>, } impl #client_ident { pub fn new(address: Address) -> Self { #client_ident { gas: None, address: address, value: None, } } pub fn gas(mut self, gas: u64) -> Self { self.gas = Some(gas); self } pub fn value(mut self, val: U256) -> Self { self.value = Some(val); self } } impl #name_ident for #client_ident { #client_ctor #(#calls)* } } } fn generate_eth_endpoint(endpoint_name: &str, intf: &items::Interface) -> proc_macro2::TokenStream { fn check_value_if_payable_toks(is_payable: bool) -> proc_macro2::TokenStream { if is_payable { return quote!{} } quote!{ if pwasm_ethereum::value() > 0.into() { panic!("Unable to accept value in non-payable constructor call"); } } } let ctor_branch = intf.constructor().map( |signature| { let arg_types = signature.arguments.iter().map(|&(_, ref ty)| quote! { #ty }); let check_value_if_payable = check_value_if_payable_toks(signature.is_payable); quote! { #check_value_if_payable let mut stream = pwasm_abi::eth::Stream::new(payload); self.inner.constructor( #(stream.pop::<#arg_types>().expect("argument decoding failed")),* ); } } ); let branches: Vec<proc_macro2::TokenStream> = intf.items().iter().filter_map(|item| { match *item { Item::Signature(ref signature) => { let hash_literal = syn::Lit::Int( syn::LitInt::new(signature.hash as u64, syn::IntSuffix::U32, Span::call_site())); let ident = &signature.name; let arg_types = signature.arguments.iter().map(|&(_, ref ty)| quote! { #ty }); let check_value_if_payable = check_value_if_payable_toks(signature.is_payable); if !signature.return_types.is_empty() { let return_count_literal = syn::Lit::Int( syn::LitInt::new(signature.return_types.len() as u64, syn::IntSuffix::Usize, Span::call_site())); Some(quote! { #hash_literal => { #check_value_if_payable let mut stream = pwasm_abi::eth::Stream::new(method_payload); let result = inner.#ident( #(stream.pop::<#arg_types>().expect("argument decoding failed")),* ); let mut sink = pwasm_abi::eth::Sink::new(#return_count_literal); sink.push(result); sink.finalize_panicking() } }) } else { Some(quote! { #hash_literal => { #check_value_if_payable let mut stream = pwasm_abi::eth::Stream::new(method_payload); inner.#ident( #(stream.pop::<#arg_types>().expect("argument decoding failed")),* ); Vec::new() } }) } }, _ => None, } }).collect(); let endpoint_ident = syn::Ident::new(endpoint_name, Span::call_site()); let name_ident = syn::Ident::new(&intf.name(), Span::call_site()); quote! { pub struct #endpoint_ident<T: #name_ident> { pub inner: T, } impl<T: #name_ident> From<T> for #endpoint_ident<T> { fn from(inner: T) -> #endpoint_ident<T> { #endpoint_ident { inner: inner, } } } impl<T: #name_ident> #endpoint_ident<T> { pub fn new(inner: T) -> Self { #endpoint_ident { inner: inner, } } pub fn instance(&self) -> &T { &self.inner } } impl<T: #name_ident> pwasm_abi::eth::EndpointInterface for #endpoint_ident<T> { #[allow(unused_mut)] #[allow(unused_variables)] fn dispatch(&mut self, payload: &[u8]) -> Vec<u8> { let inner = &mut self.inner; if payload.len() < 4 { panic!("Invalid abi invoke"); } let method_id = ((payload[0] as u32) << 24) + ((payload[1] as u32) << 16) + ((payload[2] as u32) << 8) + (payload[3] as u32); let method_payload = &payload[4..]; match method_id { #(#branches,)* _ => panic!("Invalid method signature"), } } #[allow(unused_variables)] #[allow(unused_mut)] fn dispatch_ctor(&mut self, payload: &[u8]) { #ctor_branch } } } }
//! TCP connection. use bytecodec::io::BufferedIo; use fibers::net::TcpStream; use futures::Future; use std::net::SocketAddr; use Error; pub use connection_pool::{ ConnectionPool, ConnectionPoolBuilder, ConnectionPoolHandle, RentedConnection, }; const BUF_SIZE: usize = 4096; // FIXME: parameterize /// This trait allows for acquiring TCP connections. pub trait AcquireConnection { /// TCP connection. type Connection: AsMut<Connection>; /// `Future` for acquiring a connection to communicate with the specified TCP server. type Future: Future<Item = Self::Connection, Error = Error>; /// Returns a `Future` for acquiring a connection to communicate with the specified TCP server. fn acquire_connection(&mut self, addr: SocketAddr) -> Self::Future; } /// An implementation of [`AcquireConnection`] that always establishes new TCP connection /// when `acqurie_connection` method called. /// /// [`AcquireConnection`]: ./trait.AcquireConnection.html #[derive(Debug, Default, Clone)] pub struct Oneshot; impl AcquireConnection for Oneshot { type Connection = Connection; type Future = Box<Future<Item = Connection, Error = Error> + Send + 'static>; fn acquire_connection(&mut self, addr: SocketAddr) -> Self::Future { let future = TcpStream::connect(addr) .map_err(move |e| track!(Error::from(e); addr)) .map(move |stream| Connection::new(addr, stream)); Box::new(future) } } /// TCP connection. #[derive(Debug)] pub struct Connection { stream: BufferedIo<TcpStream>, peer_addr: SocketAddr, state: ConnectionState, } impl Connection { /// Makes a new `Connection` instance. pub fn new(peer_addr: SocketAddr, stream: TcpStream) -> Self { let _ = stream.set_nodelay(true); Connection { peer_addr, stream: BufferedIo::new(stream, BUF_SIZE, BUF_SIZE), state: ConnectionState::InUse, } } /// Returns the TCP address of the peer. pub fn peer_addr(&self) -> SocketAddr { self.peer_addr } pub(crate) fn state(&self) -> ConnectionState { self.state } pub(crate) fn set_state(&mut self, state: ConnectionState) { self.state = state; } pub(crate) fn stream_mut(&mut self) -> &mut BufferedIo<TcpStream> { &mut self.stream } } impl AsMut<Connection> for Connection { fn as_mut(&mut self) -> &mut Self { self } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum ConnectionState { InUse, Recyclable, Closed, }
#[macro_export] macro_rules! rtb_type_strict { ($type_name: ident, $($name: ident = $v:expr);*) => { #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum $type_name { $( $name, )* } impl $type_name { pub fn value(&self) -> i32 { match self { $( Self::$name => $v, )* } } pub fn from_value_opt(n: i32) -> Option<Self> { match n { $( $v => Some(Self::$name), )* _n => None } } } impl serde::Serialize for $type_name { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let v = self.value(); serializer.serialize_i32(v) } } impl<'de> serde::Deserialize<'de> for $type_name { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let parsed = i32::deserialize(deserializer)?; let var_opt = $type_name::from_value_opt(parsed); match var_opt { Some(v) => Ok(v), None => { let s = format!("invalid value: {}. type_name: {}", parsed, stringify!($type_name)); Err(serde::de::Error::custom(s)) } } // Ok(v) } } }; } #[cfg(test)] mod test { rtb_type_strict! { TypeStrict, One = 1; Two = 2} #[test] fn base() { assert!(TypeStrict::One.value() == 1); assert!(TypeStrict::Two.value() == 2); assert!(TypeStrict::from_value_opt(1) == Some(TypeStrict::One)); assert!(TypeStrict::from_value_opt(2) == Some(TypeStrict::Two)); assert!(TypeStrict::from_value_opt(500) == None); } #[test] fn json() -> serde_json::Result<()> { assert!(serde_json::from_str::<TypeStrict>("3").is_err()); assert!(serde_json::from_str::<TypeStrict>("499").is_err()); assert!(serde_json::from_str::<TypeStrict>("500").is_err()); assert!(serde_json::from_str::<TypeStrict>("1").unwrap() == TypeStrict::One); assert!(serde_json::from_str::<TypeStrict>("2").unwrap() == TypeStrict::Two); Ok(()) } }
use crate::parser::{Pair, Rule}; use crate::Result; fn clean_parsed_string(s: &str) -> String { if s.starts_with("'") || s.starts_with("\"") { s[1..s.len() - 1].replace("\\", "") } else { s.to_string() } } fn parse_column(pair: Pair) -> TableColumn { let mut name = None; let mut data_type = None; let mut comment = None; for part in pair.into_inner() { match part.as_rule() { Rule::column_name => name = Some(part.as_str()), Rule::data_type => data_type = Some(part.as_str()), Rule::ddl_comment => comment = Some(part.into_inner().next().unwrap().as_str()), rule => unreachable!("Bad column parse! Rule::{:?}", rule), } } TableColumn { name: name.unwrap(), data_type: data_type.unwrap(), comment, } } impl<'l> From<Pair<'l>> for RowFormat<'l> { fn from(pair: Pair<'l>) -> Self { fn parse_serde(pair: Pair) -> RowFormat { let mut type_name = None; let mut properties = Vec::new(); for serde_part in pair.into_inner() { match serde_part.as_rule() { Rule::serde_name => type_name = Some(serde_part.as_str()), Rule::serde_properties => { for part in serde_part.into_inner() { match part.as_rule() { Rule::serde_property => { properties.push((part.as_str(), part.as_str())) } _ => unreachable!(), } } } _ => unreachable!(), } } RowFormat::Serde { type_name: type_name.unwrap(), properties, } } for part in pair.into_inner() { return match part.as_rule() { Rule::row_format_serde => parse_serde(part), _ => unreachable!("Unsupported format "), }; } unreachable!() } } impl<'l> From<Pair<'l>> for StoredAs<'l> { fn from(pair: Pair<'l>) -> Self { fn parse_file_formats(pair: Pair) -> StoredAs { let mut input_type = None; let mut output_type = None; for part in pair.into_inner() { match part.as_rule() { Rule::input_format_classname => input_type = Some(part.as_str()), Rule::output_format_classname => output_type = Some(part.as_str()), _ => unreachable!(), } } StoredAs::InputOutputFormat { input_type: input_type.unwrap(), output_type: output_type.unwrap(), } } for part in pair.into_inner() { return match part.as_rule() { Rule::file_format => parse_file_formats(part), _ => unreachable!("Unsupported format "), }; } unreachable!() } } impl<'l> From<Pair<'l>> for PropertyPair<'l> { fn from(pair: Pair<'l>) -> Self { let mut pairs = pair.into_inner(); Self( pairs.next().unwrap().as_str(), pairs.next().unwrap().as_str(), ) } } impl<'l> From<Pair<'l>> for TableColumn<'l> { fn from(pair: Pair<'l>) -> Self { parse_column(pair) } } pub fn parse_hive_create_table(ddl: &str) -> Result<CreateTableStatement> { let mut database_name = None; let mut table_name = None; let mut columns = Vec::new(); let mut partition_keys = Vec::new(); let mut row_format = None; let mut stored_as = None; let mut location = None; let mut table_properties = Vec::new(); let parse_result = crate::parser::parse_create_table_only(ddl)?; for pair in parse_result.into_inner() { match pair.as_rule() { Rule::table_name => table_name = Some(pair.as_str()), Rule::database_name => database_name = Some(pair.as_str()), Rule::table_column => columns.push(parse_column(pair)), Rule::row_format => row_format = Some(pair.into()), Rule::stored_as => stored_as = Some(pair.into()), Rule::table_location => location = Some(pair.into_inner().next().unwrap().as_str()), Rule::table_properties => { table_properties = pair.into_inner().map(Into::into).collect() } Rule::partitioned_by => partition_keys = pair.into_inner().map(Into::into).collect(), _ => unimplemented!("Unimplemented for rule: {:?}", pair), } } Ok(CreateTableStatement { database_name, table_name: table_name.expect("A table name is required, and parsing should have failed."), columns, partition_keys, row_format, stored_as, location, table_properties, }) } #[derive(Debug, Default, Eq, Ord, PartialOrd, PartialEq)] pub struct PropertyPair<'l>(&'l str, &'l str); impl<'l> PropertyPair<'l> { pub fn key(&self) -> String { clean_parsed_string(self.0) } pub fn value(&self) -> String { clean_parsed_string(self.1) } } #[derive(Debug, Default, Eq, PartialEq, Ord, PartialOrd)] pub struct TableColumn<'p> { name: &'p str, data_type: &'p str, comment: Option<&'p str>, } impl<'p> TableColumn<'p> { pub fn name(&self) -> &'p str { self.name } pub fn data_type(&self) -> &'p str { self.data_type } pub fn comment(&self) -> Option<&'p str> { self.comment } } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum RowFormat<'p> { Serde { type_name: &'p str, properties: Vec<(&'p str, &'p str)>, }, } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum StoredAs<'p> { InputOutputFormat { input_type: &'p str, output_type: &'p str, }, } #[derive(Debug, Default, Eq, PartialEq, Ord, PartialOrd)] pub struct CreateTableStatement<'p> { database_name: Option<&'p str>, table_name: &'p str, columns: Vec<TableColumn<'p>>, partition_keys: Vec<TableColumn<'p>>, row_format: Option<RowFormat<'p>>, stored_as: Option<StoredAs<'p>>, location: Option<&'p str>, table_properties: Vec<PropertyPair<'p>>, } impl<'p> CreateTableStatement<'p> { pub fn database_name(&self) -> Option<&'p str> { self.database_name } pub fn table_name(&self) -> &'p str { self.table_name } pub fn columns(&self) -> &[TableColumn<'p>] { &self.columns } pub fn partition_keys(&self) -> &[TableColumn<'p>] { &self.partition_keys } pub fn row_format(&self) -> &Option<RowFormat<'p>> { &self.row_format } pub fn stored_as(&self) -> &Option<StoredAs<'p>> { &self.stored_as } pub fn location(&self) -> Option<&'p str> { self.location } pub fn table_properties(&self) -> &[PropertyPair<'p>] { &self.table_properties } } #[cfg(test)] mod tests { use super::*; #[test] fn create_table_no_db() { let create = parse_hive_create_table("CREATE TABLE `test`").unwrap(); assert_eq!(create.database_name, None); assert_eq!(create.table_name, "`test`") } #[test] fn create_table_with_db() { let create = parse_hive_create_table("CREATE TABLE `db`.`test`").unwrap(); assert_eq!(create.database_name, Some("`db`")); assert_eq!(create.table_name, "`test`") } #[test] fn parser_with_column() { let create = parse_hive_create_table("CREATE TABLE `db`.`test` (test INT)").unwrap(); assert_eq!(create.database_name, Some("`db`")); assert_eq!(create.table_name, "`test`"); assert_eq!( create.columns, vec![TableColumn { name: "test", data_type: "INT", comment: None }] ) } #[test] fn table_with_multiple_columns() { let create = parse_hive_create_table("CREATE TABLE `db`.`test` (test INT, other DECIMAL(18, 2));") .unwrap(); assert_eq!(create.database_name, Some("`db`")); assert_eq!(create.table_name, "`test`"); assert_eq!( create.columns, vec![ TableColumn { name: "test", data_type: "INT", comment: None }, TableColumn { name: "other", data_type: "DECIMAL(18, 2)", comment: None } ] ) } #[test] fn table_with_row_format_and_file_format() { let create = parse_hive_create_table( "CREATE EXTERNAL TABLE `hive_example`.`example`( `source` string COMMENT '', `table_name` string COMMENT '', `action` string COMMENT '', `created_at` timestamp COMMENT '', `row_id` binary COMMENT '', `event_time` timestamp COMMENT '', `group` int COMMENT 'Group', `group_name` string COMMENT 'group name', `description` string COMMENT 'description' ) ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.orc.OrcSerde' STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat' ", ) .unwrap(); assert_eq!(create.columns.len(), 9); assert_eq!( create.row_format, Some(RowFormat::Serde { type_name: "'org.apache.hadoop.hive.ql.io.orc.OrcSerde'", properties: vec![] }) ); assert_eq!( create.stored_as, Some(StoredAs::InputOutputFormat { input_type: "'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'", output_type: "'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'" }) ); } #[test] fn with_location() { let create = parse_hive_create_table( "CREATE EXTERNAL TABLE db.test LOCATION 's3://location/' ", ) .unwrap(); assert_eq!(create.location, Some("'s3://location/'")) } #[test] fn table_properties() { let create = parse_hive_create_table( "CREATE EXTERNAL TABLE db.test TBLPROPERTIES ( 'pk.cols'='this, that', 'provisioned.by.class'='Snappy', 'lastDdlTime'='214123523') ", ) .unwrap(); assert_eq!( create.table_properties, vec![ PropertyPair("'pk.cols'", "'this, that'"), PropertyPair("'provisioned.by.class'", "'Snappy'"), PropertyPair("'lastDdlTime'", "'214123523'") ] ); } #[test] fn table_with_partitions() { let create = parse_hive_create_table( "CREATE EXTERNAL TABLE `hive_example`.`example`( `source` string COMMENT '', `table_name` string COMMENT '', `action` string COMMENT '') PARTITIONED BY ( `created_at` timestamp COMMENT 'create time', group int )", ) .unwrap(); assert_eq!( create.partition_keys, vec![ TableColumn { name: "`created_at`", data_type: "timestamp", comment: Some("'create time'") }, TableColumn { name: "group", data_type: "int", comment: None } ] ) } }
#[macro_use] extern crate clap; extern crate dirs; extern crate reqwest; extern crate rusqlite; extern crate select; extern crate webbrowser; use clap::{App, AppSettings}; use std::process; mod cmd; mod bookmark; mod database; mod utils; fn main() { let args = App::new("bkm") .version(crate_version!()) .author(crate_authors!()) .about("Bookmark manager") .setting(AppSettings::GlobalVersion) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::DeriveDisplayOrder) .subcommand(cmd::print::make_subcommand()) .subcommand(cmd::add::make_subcommand()) .subcommand(cmd::delete::make_subcommand()) .subcommand(cmd::update::make_subcommand()) .subcommand(cmd::open::make_subcommand()) .subcommand(cmd::search::make_subcommand()) .subcommand(cmd::import::make_subcommand()) .get_matches(); match args.subcommand() { ("print", Some(args)) => cmd::print::execute(args), ("add" , Some(args)) => cmd::add::execute(args), ("delete", Some(args)) => cmd::delete::execute(args), ("update", Some(args)) => cmd::update::execute(args), ("open", Some(args)) => cmd::open::execute(args), ("search", Some(args)) => cmd::search::execute(args), ("import", Some(args)) => cmd::import::execute(args), _ => process::exit(1), } }
use types::Move; use std; pub struct Board { b: [[bool; 16]; 16], player_position: [(u32, u32); 2] } impl Board { pub fn legal_moves(&self, player: u32) -> std::vec::IntoIter<Move> { let pos = self.player_position[player as usize]; let mut moves = vec![]; if pos.1 > 0 && self.b[pos.0 as usize][(pos.1 - 1) as usize] { moves.push(Move::Up); } if pos.1 < 15 && self.b[pos.0 as usize][(pos.1 + 1) as usize] { moves.push(Move::Down); } if pos.0 > 0 && self.b[(pos.0 - 1) as usize][pos.1 as usize] { moves.push(Move::Left); } if pos.0 < 15 && self.b[(pos.0 + 1) as usize][pos.1 as usize] { moves.push(Move::Right); } moves.into_iter() } } impl<'a> From<&'a str> for Board { fn from(text: &'a str) -> Board { let mut x = 0; let mut y = 0; let mut b = [[false; 16]; 16]; let mut player_position = [(0, 0); 2]; for c in text.split(',') { b[x as usize][y as usize] = c == "."; if c == "0" { player_position[0] = (x, y); } else if c == "1" { player_position[1] = (x, y); } x = (x+1) % 16; if x == 0 { y += 1; } } Board { b: b, player_position: player_position } } }
use { crate::{ client::{self, RequestType}, entities::*, Client, }, std::error::Error, }; /// Adds a song to the playback queue (only works when you have requests remaining) pub async fn request_song(client: &Client, id: i64) -> Result<(), Box<dyn Error>> { let request = RequestType::Post(Vec::new()); let endpoint = format!("/requests/{}", id); match client::perform_request::<GeneralMessage>(request, endpoint, Some(client)).await { Ok((status, msg)) if status != 204 => Err(failure::err_msg(msg.message).into()), Ok(_) => Ok(()), Err(e) => Err(e), } } /// Remove a song requested by you from the queue pub async fn remove_request(client: &Client, id: i64) -> Result<(), Box<dyn Error>> { let endpoint = format!("/requests/{}", id); match client::perform_request::<GeneralMessage>(RequestType::Delete, endpoint, Some(client)) .await { Ok((status, msg)) if status != 204 => Err(failure::err_msg(msg.message).into()), Ok(_) => Ok(()), Err(e) => Err(e), } }
pub(crate) mod bit_op { pub fn set_bit(number: u8, bit: u8) -> u8 { if bit > 7 { panic!("invalid bit (>7)"); } number | (0b1 << bit) } pub fn clear_bit(number: u8, bit: u8) -> u8 { if bit > 7 { panic!("invalid bit (>7)"); } number & !(0b1 << bit) } pub fn toggle_bit(number: u8, bit: u8) -> u8 { if bit > 7 { panic!("invalid bit (>7)"); } number ^ 0b1 << bit } pub fn change_bit_to(number: u8, bit: u8, value: u8) -> u8 { if bit > 7 { panic!("invalid bit (>7)"); } if value > 1 { panic!("bit can only be set to 0 or 1 {}", value); } number & !(1 << bit) | (value << bit) } } pub(crate) mod memory_op { use crate::mem::memory::MapsMemory; pub fn write_memory(memory: &mut dyn MapsMemory, address: u16, value: u8) { memory.write(address, value).unwrap() } pub fn read_memory(memory: &dyn MapsMemory, address: u16) -> u8 { memory.read(address).unwrap() } pub fn read_memory_following_u8(memory: &dyn MapsMemory, address: u16) -> u8 { memory.read(address + 1).unwrap() } pub fn read_memory_following_u16(memory: &dyn MapsMemory, address: u16) -> u16 { (u16::from(memory.read(address + 2).unwrap()) << 8) + u16::from(memory.read(address + 1).unwrap()) } pub fn push_u16_stack(memory: &mut dyn MapsMemory, value: u16, sp: u16) { memory.write(sp - 1, ((value >> 8) & 0xFF) as u8).unwrap(); memory.write(sp - 2, (value & 0xFF) as u8).unwrap(); } pub fn pop_u16_stack(memory: &mut dyn MapsMemory, sp: u16) -> u16 { let val_lo = memory.read(sp).unwrap(); let val_hi = memory.read(sp + 1).unwrap(); (u16::from(val_hi) << 8) + u16::from(val_lo) } }
use crate::binds::BindCount; use crate::binds::{BindsInternal, CollectBinds}; use crate::write_sql::WriteSql; use std::fmt::{self, Write}; #[derive(Clone, Copy, Debug)] pub struct RowLocking { pub for_update: bool, pub skip_locked: bool, pub for_key_share: bool, pub for_no_key_update: bool, pub for_share: bool, pub no_wait: bool, } impl RowLocking { pub fn new() -> Self { Self { for_update: false, skip_locked: false, for_key_share: false, for_no_key_update: false, for_share: false, no_wait: false, } } pub fn or(self, other: RowLocking) -> Self { Self { for_update: self.for_update || other.for_update, skip_locked: self.skip_locked || other.skip_locked, for_key_share: self.for_key_share || other.for_key_share, for_no_key_update: self.for_no_key_update || other.for_no_key_update, for_share: self.for_share || other.for_share, no_wait: self.no_wait || other.no_wait, } } } impl CollectBinds for RowLocking { fn collect_binds(&self, _: &mut BindsInternal) {} } impl WriteSql for &RowLocking { fn write_sql<W: Write>(self, f: &mut W, _: &mut BindCount) -> fmt::Result { if self.for_update { write!(f, " FOR UPDATE")?; } if self.for_no_key_update { write!(f, " FOR NO KEY UPDATE")?; } if self.for_share { write!(f, " FOR SHARE")?; } if self.for_key_share { write!(f, " FOR KEY SHARE")?; } if self.no_wait { write!(f, " NO WAIT")?; } if self.skip_locked { write!(f, " SKIP LOCKED")?; } Ok(()) } }
use actix_web::{post, Responder, web}; use log::{debug, trace}; use crate::app; use crate::app::map_rover_status_to_response; use libdriver::api::AsyncLooker; use libapi_http::api::LookRequest; pub fn config(cfg: &mut web::ServiceConfig) { cfg.service(look_at); } #[post("")] pub async fn look_at(req: web::Json<LookRequest>, state: web::Data<app::State>) -> impl Responder { debug!("Requested to look at ({}, {})", req.h, req.v); let r = map_rover_status_to_response(state.rover_client.lock().await.look_at(req.h, req.v).await); trace!("Returning {:#?}", r); r }
use core::cmp::{max, min}; use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use core::cell::Cell; pub use libutil::mem::Allocation; use crate::uses::*; use crate::util::{IMutex, LinkedList, MemOwner, UniqueRef}; use crate::mb2::{BootInfo, MemoryRegionType}; use super::{PhysRange, PAGE_SIZE}; use super::virt_alloc::FrameAllocator; const MAX_ORDER: usize = 32; pub const MAX_ZONES: usize = 4; pub static zm: ZoneManager = ZoneManager::new(); #[derive(Debug)] pub struct Node { next: AtomicPtr<Node>, prev: AtomicPtr<Node>, size: Cell<usize>, } impl Node { pub unsafe fn new(addr: usize, size: usize) -> MemOwner<Self> { let ptr = addr as *mut Node; let out = Node { prev: AtomicPtr::new(null_mut()), next: AtomicPtr::new(null_mut()), size: Cell::new(size), }; ptr.write(out); MemOwner::from_raw(ptr) } pub fn size(&self) -> usize { self.size.get() } pub fn set_size(&self, size: usize) { self.size.set(size); } } libutil::impl_list_node!(Node, prev, next); #[derive(Debug)] pub struct BuddyAllocator { start: usize, meta_start: *mut u8, olist: [LinkedList<Node>; MAX_ORDER], max_order: usize, min_order_size: usize, // the number of bits long that min_order_size is min_order_bits: usize, free_space: usize, } impl BuddyAllocator { // NOTE: start and end are aligned to min_order_size's allignment pub unsafe fn new(start: VirtAddr, end: VirtAddr, min_order_size: usize) -> Self { let min_order_size = max(align_up(min_order_size, PAGE_SIZE), PAGE_SIZE); let start = start.align_up(min_order_size as u64).as_u64() as usize; let end = end.as_u64() as usize; if end <= start { panic!("allocator passed invalid memory region"); } let meta_size = ((end - start) / (8 * min_order_size)) + 1; let meta_start = align_down(end - meta_size, min_order_size); let meta_startp = meta_start as *mut u8; memset(meta_startp, meta_size, 0); let mut out = BuddyAllocator { start, meta_start: meta_startp, olist: init_array!(LinkedList<Node>, MAX_ORDER, LinkedList::new()), max_order: 0, min_order_size, min_order_bits: log2(min_order_size), free_space: meta_start - start, }; out.init_orders(); out } unsafe fn init_orders(&mut self) { let mut a = self.start; let ms = self.meta_start as usize; while a < ms { let len = min(align_of(a), 1 << log2(ms - a)); let order = self.get_order(len); let node = Node::new(a, len); if order > MAX_ORDER { panic!( "MAX_ORDER for buddy allocator was smaller than order {}", order ); } self.olist[order].push(node); if order > self.max_order { self.max_order = order; } a += len; } } fn get_order(&self, size: usize) -> usize { let bits = log2_up(size); if bits <= self.min_order_bits { 0 } else { bits - self.min_order_bits } } // might panic if order is to big fn get_order_size(&self, order: usize) -> usize { 1 << (order + self.min_order_bits) } fn is_alloced(&self, addr: usize) -> bool { if addr < self.start || addr >= self.meta_start as usize { return false; } let i = (addr - self.start) / self.min_order_size; let b = unsafe { *self.meta_start.add(i / 8) }; b & (1 << (i % 8)) > 0 } fn set_is_alloced(&self, addr: usize, alloced: bool) { if addr < self.start || addr >= self.meta_start as usize { return; } let i = (addr - self.start) / self.min_order_size; let ptr = unsafe { self.meta_start.add(i / 8) }; let mut b = unsafe { *ptr }; if alloced { b |= 1 << (i % 8); } else { b &= !(1 << (i % 8)); } unsafe { *ptr = b; } } fn split_order(&mut self, order: usize) -> bool { if order > self.max_order || order == 0 { return false; } if self.olist[order].len() != 0 || self.split_order(order + 1) { let node = self.olist[order].pop_front().unwrap(); node.set_size(node.size().wrapping_shr(1)); let addr = node.addr() ^ node.size(); let node2 = unsafe { Node::new(addr, node.size()) }; self.olist[order - 1].push_front(node2); self.olist[order - 1].push_front(node); return true; } false } // safety: address must point to a valid, unallocated node unsafe fn split_order_at(&mut self, addr: usize, order: usize) { if order >= self.max_order { return; } let size = self.get_order_size(order); let addr2 = addr ^ size; if !self.ucontains(addr2, size) || self.is_alloced(addr2) { return; } let min_addr = min(addr, addr2); let max_addr = max(addr, addr2); self.split_order_at(min_addr, order + 1); let old_node = UniqueRef::new((min_addr as *const Node).as_ref().unwrap()); let node = self.olist[order + 1].remove_node(old_node); node.set_size(size); let node2 = Node::new(max_addr, size); self.olist[order].push(node); self.olist[order].push(node2); } fn insert_node(&mut self, mut node: MemOwner<Node>) { let mut order = self.get_order(node.size()); loop { let addr2 = node.addr() ^ node.size(); if addr2 < node.addr() || addr2 > self.start || addr2 + node.size() > self.meta_start as usize || self.is_alloced(addr2) { break; } let node2 = unsafe { UniqueRef::new((addr2 as *const Node).as_ref().unwrap()) }; if node.size() != node2.size() { break; } let node2 = self.olist[order].remove_node(node2); // make borrow checker happy node = if addr2 < node.addr() { //node = node2; node2 } else { node }; node.set_size(node.size() << 1); order += 1; if order == self.max_order { break; } } self.olist[order].push_front(node); } fn order_expand_cap(&self, addr: usize, mut size: usize) -> usize { let mut out = 0; loop { let addr2 = addr ^ size; if addr2 < addr || (addr2 + size) > self.meta_start as usize || self.is_alloced(addr2) { break; } out += 1; size <<= 1; } out } pub fn contains(&self, mem: Allocation) -> bool { self.ucontains(mem.as_usize(), mem.len()) } fn contains_addr(&self, addr: usize) -> bool { addr >= self.start && addr < self.meta_start as usize } fn ucontains(&self, addr: usize, size: usize) -> bool { addr >= self.start && addr + size <= self.meta_start as usize && align_of(addr) >= self.min_order_size } // size is in bytes pub fn alloc(&mut self, size: usize) -> Option<Allocation> { if size == 0 { return None; } let order = self.get_order(size); self.oalloc(order) } pub fn oalloc(&mut self, order: usize) -> Option<Allocation> { if order > self.max_order { return None; } if self.olist[order].len() == 0 && !self.split_order(order + 1) { return None; } // list is guarunteed to contain a node let node = self.olist[order].pop_front().unwrap(); let out = Allocation::new(node.addr(), node.size()); self.set_is_alloced(node.addr(), true); self.free_space -= node.size(); Some(out) } // size is in bytes pub fn alloc_at(&mut self, addr: VirtAddr, size: usize) -> Option<Allocation> { if size == 0 { return None; } let order = self.get_order(size); self.oalloc_at(addr, order) } pub fn oalloc_at(&mut self, at_addr: VirtAddr, order: usize) -> Option<Allocation> { if order > self.max_order { return None; } let at_addr = at_addr.as_u64() as usize; let size = self.get_order_size(order); if !self.ucontains(at_addr, size) { return None; } if self.is_alloced(at_addr) || order > self.order_expand_cap(at_addr, self.min_order_size) { return None; } unsafe { self.split_order_at(at_addr, order); } let old_node = unsafe { UniqueRef::new((at_addr as *const Node).as_ref().unwrap()) }; self.olist[order].remove_node(old_node); self.set_is_alloced(at_addr, true); self.free_space -= size; Some(Allocation::new(at_addr, size)) } pub unsafe fn realloc(&mut self, mem: Allocation, size: usize) -> Option<Allocation> { if size == 0 { return None; } let order = self.get_order(size); self.orealloc(mem, order) } // if none is returned, the original allocation is still valid pub unsafe fn orealloc(&mut self, mem: Allocation, order: usize) -> Option<Allocation> { if order > self.max_order { return None; } let addr = mem.as_usize(); let len = mem.len(); if addr < self.start || addr + len > self.meta_start as usize { return None; } if !self.is_alloced(addr) { panic!( "memory region {:?} was already freed, could not be realloced", mem ); } let mut old = self.get_order(len); if order == old { Some(mem) } else if order < old { let odiff = old - order; let mut size = self.get_order_size(old); while old > order { size >>= 1; old -= 1; // should already have its metadata marked as free let node = Node::new(addr ^ size, size); self.olist[old].push_front(node); } self.free_space += self.get_order_size(odiff); Some(Allocation::new(addr, size)) } else { let odiff = order - old; if self.order_expand_cap(addr, len) >= odiff { // no need to check if each zone we are expanding to is valid for order in old..order { let size2 = self.get_order_size(order); let addr2 = addr ^ size2; let node = UniqueRef::new((addr2 as *const Node).as_ref().unwrap()); self.olist[order].remove_node(node); } self.free_space += self.get_order_size(odiff); Some(Allocation::new(addr, self.get_order_size(order))) } else { let mut out = self.oalloc(order)?; let src_slice = mem.as_slice(); out.as_mut_slice()[..src_slice.len()].copy_from_slice(src_slice); self.dealloc(mem); self.free_space += self.get_order_size(odiff); Some(out) } } } pub unsafe fn dealloc(&mut self, mem: Allocation) { let addr = mem.as_usize(); if addr < self.start || addr + mem.len() > self.meta_start as usize { return; } if !self.is_alloced(addr) { panic!("double free on memory region {:?}", mem); } self.set_is_alloced(addr, false); let node = Node::new(addr, mem.len()); self.free_space += node.size(); self.insert_node(node); } } #[derive(Debug)] pub struct ZoneManager { zones: RefCell<[Option<IMutex<BuddyAllocator>>; MAX_ZONES]>, zlen: Cell<usize>, selnum: AtomicUsize, } impl ZoneManager { pub const fn new() -> ZoneManager { ZoneManager { //zones: init_array! (Option<Mutex<BuddyAllocator>>, MAX_ZONES, None), // TODO: make this automatically follow MAX_ZONES zones: RefCell::new([None, None, None, None]), zlen: Cell::new(0), selnum: AtomicUsize::new(0), } } pub unsafe fn init(&self, boot_info: &BootInfo) { let mut zlen = self.zlen.get(); for region in &*boot_info.memory_map { if let MemoryRegionType::Usable(mem) = region { let start = mem.addr(); let end = mem.addr() + mem.size(); if zlen >= MAX_ZONES { panic! ("MAX_ZONES is not big enough to store an allocator for all the physical memory zones"); } self.zones.borrow_mut()[zlen] = Some(IMutex::new(BuddyAllocator::new( phys_to_virt(start), phys_to_virt(end), PAGE_SIZE, ))); zlen += 1; } } self.zlen.set(zlen); } fn allocer_action<F>(&self, mut f: F) -> Option<Allocation> where F: FnMut(&mut BuddyAllocator) -> Option<Allocation>, { let selnum = self.selnum.fetch_add(1, Ordering::Relaxed); let start = selnum % self.zlen.get(); let mut i = start; let mut flag = true; while i != start || flag { if let Some(mut allocation) = f(&mut self.zones.borrow()[i].as_ref().unwrap().lock()) { allocation.zindex = i; return Some(allocation); } flag = false; i += 1; i %= self.zlen.get(); } None } fn allocer_action_contains<F>(&self, addr: usize, f: F) -> Option<Allocation> where F: FnOnce(&mut BuddyAllocator) -> Option<Allocation> { let zones = self.zones.borrow(); for bm in zones.iter() { let mut guard = bm.as_ref().unwrap().lock(); if guard.contains_addr(addr) { return f(&mut guard); } } None } pub fn alloc(&self, size: usize) -> Option<Allocation> { self.allocer_action(|allocer| allocer.alloc(size)) } pub fn allocz(&self, size: usize) -> Option<Allocation> { let mut out = self.alloc(size)?; unsafe { memset(out.as_mut_ptr(), out.len(), 0); } Some(out) } pub fn oalloc(&self, order: usize) -> Option<Allocation> { self.allocer_action(|allocer| allocer.oalloc(order)) } pub fn oallocz(&self, order: usize) -> Option<Allocation> { let mut out = self.alloc(order)?; unsafe { memset(out.as_mut_ptr(), out.len(), 0); } Some(out) } pub fn alloc_at(&self, addr: VirtAddr, size: usize) -> Option<Allocation> { self.allocer_action_contains(addr.as_u64() as usize, |allocer| allocer.alloc_at(addr, size)) } pub fn allocz_at(&self, addr: VirtAddr, size: usize) -> Option<Allocation> { let mut out = self.alloc_at(addr, size)?; unsafe { memset(out.as_mut_ptr(), out.len(), 0); } Some(out) } pub fn oalloc_at(&self, addr: VirtAddr, order: usize) -> Option<Allocation> { self.allocer_action_contains(addr.as_u64() as usize, |allocer| allocer.oalloc_at(addr, order)) } pub fn oallocz_at(&self, addr: VirtAddr, order: usize) -> Option<Allocation> { let mut out = self.oalloc_at(addr, order)?; unsafe { memset(out.as_mut_ptr(), out.len(), 0); } Some(out) } // TODO: support reallocating to a different zone if new size doesn't fit pub unsafe fn realloc(&self, mem: Allocation, size: usize) -> Option<Allocation> { let new_mem = self.zones.borrow()[mem.zindex] .as_ref() .unwrap() .lock() .realloc(mem, size) .map(|mut out| { out.zindex = mem.zindex; out }); if new_mem.is_none() { let mut out = self.alloc(size)?; out.copy_from_mem(mem.as_slice()); Some(out) } else { new_mem } } pub unsafe fn orealloc(&self, mem: Allocation, order: usize) -> Option<Allocation> { let new_mem = self.zones.borrow()[mem.zindex] .as_ref() .unwrap() .lock() .orealloc(mem, order) .map(|mut out| { out.zindex = mem.zindex; out }); if new_mem.is_none() { let mut out = self.oalloc(order)?; out.copy_from_mem(mem.as_slice()); Some(out) } else { new_mem } } pub unsafe fn dealloc(&self, mem: Allocation) { self.zones.borrow()[mem.zindex] .as_ref() .unwrap() .lock() .dealloc(mem); } } unsafe impl FrameAllocator for ZoneManager { fn alloc_frame(&self) -> Allocation { self.alloc(PAGE_SIZE).unwrap() } unsafe fn dealloc_frame(&self, frame: Allocation) { let zones = self.zones.borrow(); for i in 0..self.zlen.get() { let mut z = zones[i].as_ref().unwrap().lock(); if z.contains(frame) { z.dealloc(frame); break; } } } } unsafe impl Send for ZoneManager {} unsafe impl Sync for ZoneManager {} pub fn init(boot_info: &BootInfo) { unsafe { zm.init(boot_info); } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use anyhow::Error; use futures::{Future, Poll}; use std::error::Error as StdError; use std::fmt::Display; /// "Context" support for futures where the error is anyhow::Error. pub trait FutureFailureErrorExt: Future + Sized { /// Add context to the error returned by this future fn context<D>(self, context: D) -> ContextErrorFut<Self, D> where D: Display + Send + Sync + 'static; /// Add context created by provided function to the error returned by this future fn with_context<D, F>(self, f: F) -> WithContextErrorFut<Self, F> where D: Display + Send + Sync + 'static, F: FnOnce() -> D; } impl<F> FutureFailureErrorExt for F where F: Future<Error = Error> + Sized, { fn context<D>(self, displayable: D) -> ContextErrorFut<Self, D> where D: Display + Send + Sync + 'static, { ContextErrorFut::new(self, displayable) } fn with_context<D, O>(self, f: O) -> WithContextErrorFut<Self, O> where D: Display + Send + Sync + 'static, O: FnOnce() -> D, { WithContextErrorFut::new(self, f) } } pub struct WithContextErrorFut<A, F> { inner: A, displayable: Option<F>, } impl<A, F, D> WithContextErrorFut<A, F> where A: Future<Error = Error>, D: Display + Send + Sync + 'static, F: FnOnce() -> D, { pub fn new(future: A, displayable: F) -> Self { Self { inner: future, displayable: Some(displayable), } } } impl<A, F, D> Future for WithContextErrorFut<A, F> where A: Future<Error = Error>, D: Display + Send + Sync + 'static, F: FnOnce() -> D, { type Item = A::Item; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.inner.poll() { Err(err) => { let f = self .displayable .take() .expect("poll called after future completion"); let context = f(); Err(err.context(context)) } Ok(item) => Ok(item), } } } pub struct ContextErrorFut<A, D> { inner: A, displayable: Option<D>, } impl<A, D> ContextErrorFut<A, D> where A: Future<Error = Error>, D: Display + Send + Sync + 'static, { pub fn new(future: A, displayable: D) -> Self { Self { inner: future, displayable: Some(displayable), } } } impl<A, D> Future for ContextErrorFut<A, D> where A: Future<Error = Error>, D: Display + Send + Sync + 'static, { type Item = A::Item; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.inner.poll() { Err(err) => Err(err.context( self.displayable .take() .expect("poll called after future completion"), )), Ok(item) => Ok(item), } } } /// "Context" support for futures where the error is an implementation of std::error::Error. pub trait FutureFailureExt: Future + Sized { /// Add context to the error returned by this future fn context<D>(self, context: D) -> ContextFut<Self, D> where D: Display + Send + Sync + 'static; /// Add context created by provided function to the error returned by this future fn with_context<D, F>(self, f: F) -> WithContextFut<Self, F> where D: Display + Send + Sync + 'static, F: FnOnce() -> D; } impl<F> FutureFailureExt for F where F: Future + Sized, F::Error: StdError + Send + Sync + 'static, { fn context<D>(self, displayable: D) -> ContextFut<Self, D> where D: Display + Send + Sync + 'static, { ContextFut::new(self, displayable) } fn with_context<D, O>(self, f: O) -> WithContextFut<Self, O> where D: Display + Send + Sync + 'static, O: FnOnce() -> D, { WithContextFut::new(self, f) } } pub struct ContextFut<A, D> { inner: A, displayable: Option<D>, } impl<A, D> ContextFut<A, D> where A: Future, A::Error: StdError + Send + Sync + 'static, D: Display + Send + Sync + 'static, { pub fn new(future: A, displayable: D) -> Self { Self { inner: future, displayable: Some(displayable), } } } impl<A, D> Future for ContextFut<A, D> where A: Future, A::Error: StdError + Send + Sync + 'static, D: Display + Send + Sync + 'static, { type Item = A::Item; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.inner.poll() { Err(err) => Err(Error::new(err).context( self.displayable .take() .expect("poll called after future completion"), )), Ok(item) => Ok(item), } } } pub struct WithContextFut<A, F> { inner: A, displayable: Option<F>, } impl<A, D, F> WithContextFut<A, F> where A: Future, A::Error: StdError + Send + Sync + 'static, D: Display + Send + Sync + 'static, F: FnOnce() -> D, { pub fn new(future: A, displayable: F) -> Self { Self { inner: future, displayable: Some(displayable), } } } impl<A, D, F> Future for WithContextFut<A, F> where A: Future, A::Error: StdError + Send + Sync + 'static, D: Display + Send + Sync + 'static, F: FnOnce() -> D, { type Item = A::Item; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.inner.poll() { Err(err) => { let f = self .displayable .take() .expect("poll called after future completion"); let context = f(); Err(Error::new(err).context(context)) } Ok(item) => Ok(item), } } } #[cfg(test)] mod test { use super::*; use anyhow::format_err; use futures::future::err; #[test] #[should_panic] fn poll_after_completion_fail() { let err = err::<(), _>(format_err!("foo").context("bar")); let mut err = err.context("baz"); let _ = err.poll(); let _ = err.poll(); } #[test] #[should_panic] fn poll_after_completion_fail_with_context() { let err = err::<(), _>(format_err!("foo").context("bar")); let mut err = err.with_context(|| "baz"); let _ = err.poll(); let _ = err.poll(); } #[test] #[should_panic] fn poll_after_completion_error() { let err = err::<(), _>(format_err!("foo")); let mut err = err.context("baz"); let _ = err.poll(); let _ = err.poll(); } #[test] #[should_panic] fn poll_after_completion_error_with_context() { let err = err::<(), _>(format_err!("foo")); let mut err = err.with_context(|| "baz"); let _ = err.poll(); let _ = err.poll(); } }
use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use serde::Deserialize; use crate::utils::formatted_strings::APP_VERSION; #[derive(Deserialize, Debug)] struct AppVersion { name: String, } /// Calls a method to check if a newer release of Sniffnet is available on GitHub /// and updates application status accordingly pub fn set_newer_release_status(newer_release_available: &Arc<Mutex<Result<bool, String>>>) { let result = is_newer_release_available(6, 30); *newer_release_available.lock().unwrap() = result; } /// Checks if a newer release of Sniffnet is available on GitHub fn is_newer_release_available( max_retries: u8, seconds_between_retries: u8, ) -> Result<bool, String> { let client = reqwest::blocking::Client::new(); let response = client .get("https://api.github.com/repos/GyulyVGC/Sniffnet/releases/latest") .header("User-agent", "GyulyVGC") .header("Accept", "application/vnd.github+json") .header("X-GitHub-Api-Version", "2022-11-28") .send(); if let Ok(result) = response { let result_json = result.json::<AppVersion>(); #[cfg(test)] if result_json.is_err() { let response2 = client .get("https://api.github.com/repos/GyulyVGC/Sniffnet/releases/latest") .header("User-agent", "GyulyVGC") .header("Accept", "application/vnd.github+json") .header("X-GitHub-Api-Version", "2022-11-28") .send(); println!("\nResponse text: {:?}", response2.unwrap()); println!("JSON result: {result_json:?}\n"); } let mut latest_version = result_json .unwrap_or(AppVersion { name: String::from(":-("), }) .name; latest_version = latest_version.trim().to_string(); // release name sample: v1.1.2 let latest_version_as_bytes = latest_version.as_bytes(); if latest_version.len() == 6 && latest_version.starts_with('v') && char::from(latest_version_as_bytes[1]).is_numeric() && char::from(latest_version_as_bytes[2]).eq(&'.') && char::from(latest_version_as_bytes[3]).is_numeric() && char::from(latest_version_as_bytes[4]).eq(&'.') && char::from(latest_version_as_bytes[5]).is_numeric() { latest_version.remove(0); return if latest_version.gt(&APP_VERSION.to_string()) { Ok(true) } else { Ok(false) }; } Err(format!("Cannot parse latest version name {latest_version}")) } else { let retries_left = max_retries - 1; if retries_left > 0 { // sleep seconds_between_retries and retries the request thread::sleep(Duration::from_secs(u64::from(seconds_between_retries))); is_newer_release_available(retries_left, seconds_between_retries) } else { Err(response.err().unwrap().to_string()) } } } #[cfg(all(test, not(target_os = "macos")))] mod tests { use super::*; #[test] fn fetch_latest_release_from_github() { let result = is_newer_release_available(6, 2); result.expect("Latest release request from GitHub error"); } }
#[derive(Clone, Debug)] pub struct LineComposer<I> { words: I, width: usize, current: Option<String>, } impl<I> LineComposer<I> { pub(crate) fn new<S>(words: I, width: usize) -> Self where I: Iterator<Item = S>, S: AsRef<str>, { LineComposer { words, width, current: None, } } } impl<I, S> Iterator for LineComposer<I> where I: Iterator<Item = S>, S: AsRef<str>, { type Item = String; fn next(&mut self) -> Option<Self::Item> { let mut next = match self.words.next() { None => return self.current.take(), Some(value) => value, }; let mut current = self.current.take().unwrap_or_else(String::new); loop { let word = next.as_ref(); if self.width <= current.len() + word.len() { self.current = Some(String::from(word)); // If the first word itself is too long, avoid producing an // empty line. Continue instead with the next word. if !current.is_empty() { return Some(current); } } if !current.is_empty() { current.push_str(" ") } current.push_str(word); match self.words.next() { None => return Some(current), // Last line, current remains None Some(word) => next = word, } } } } // This part is just to extend all suitable iterators with LineComposer pub trait ComposeLines: Iterator { fn compose_lines(self, width: usize) -> LineComposer<Self> where Self: Sized, Self::Item: AsRef<str>, { LineComposer::new(self, width) } } impl<T, S> ComposeLines for T where T: Iterator<Item = S>, S: AsRef<str>, { } fn main() { let text = r" In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything."; text.split_whitespace() .compose_lines(80) .for_each(|line| println!("{}", line)); }
#![no_std] mod platformio; use platformio::Arduino_h::{pinMode, digitalWrite, delay, LED_BUILTIN, HIGH, LOW, OUTPUT}; #[no_mangle] pub extern "C" fn setup() { unsafe { pinMode(LED_BUILTIN as u8, OUTPUT as u8); } } #[no_mangle] pub extern "C" fn r#loop() { unsafe { digitalWrite(LED_BUILTIN as u8, HIGH as u8); delay(2000); digitalWrite(LED_BUILTIN as u8, LOW as u8); delay(100); } } #[panic_handler] fn my_panic(_info: &core::panic::PanicInfo) -> ! { loop {} }
fn main() { let x = 1 + 2; let mut y = x; println!("y={}", y); y = 5; let z = y; println!("結果={}", z); } // x => 3 => // y => x => 3 // z => y => x => 3
mod facts; use datafrog::{Iteration, Relation, RelationLeaper}; use facts::{Variable, Point}; fn main() { let mut iteration = Iteration::new(); let edge: Relation<(Point, Point)> = vec![ (Point::from(1), Point::from(2)), (Point::from(2), Point::from(3)), (Point::from(6), Point::from(3)), (Point::from(3), Point::from(4)), (Point::from(4), Point::from(5)), (Point::from(4), Point::from(7)), (Point::from(5), Point::from(6)), (Point::from(6), Point::from(8)), (Point::from(7), Point::from(8)), ] .iter() .collect(); let rev_edge:Relation<(Point,Point)> = Relation::from_iter(edge.elements.iter().map(|&(u,v)|(v,u))); // definition at Point let def: Relation<(Variable,Point)> = vec![ (Variable::from('x' as usize),Point::from(1) ), (Variable::from('y' as usize),Point::from(2) ), (Variable::from('m' as usize),Point::from(3) ), (Variable::from('y' as usize),Point::from(4) ), (Variable::from('x' as usize),Point::from(5) ), (Variable::from('q' as usize),Point::from(6) ), (Variable::from('x' as usize),Point::from(7) ), (Variable::from('z' as usize),Point::from(8) ), ] .iter() .collect(); let live= iteration.variable::<(Point, Variable)>("live"); live.extend(vec![ (Point::from(1),Variable::from('p' as usize)), (Point::from(2),Variable::from('q' as usize)), (Point::from(2),Variable::from('z' as usize)), (Point::from(3),Variable::from('k' as usize)), (Point::from(4),Variable::from('m' as usize)), (Point::from(6),Variable::from('y' as usize)), (Point::from(7),Variable::from('x' as usize)), (Point::from(8),Variable::from('p' as usize)), ].iter()); while iteration.changed() { // live(point1, variable) :- // live(point2, variable), // rev_edge(point2, point1), // not def(variable, point1). // live.from_leapjoin( &live, ( rev_edge.extend_with(|&(point2, variable)| point2), def.extend_anti(|&(point2, variable)| variable), ), |&(point1, variable), &point2| (point2, variable), ); } let x = live.complete(); println!("{:?}", x.elements.len()); println!("{:?}", x.elements); } // |-----------| // | p1 | // | x=p+1; | // | p2 | // | y=q+z; | // |-----------| // | // | // |-----------| // | p3 | // |----------| m=k; | // | | p4 | // | | y=m-1; | // | |-----------| // | / \ // | / \ // | / \ // | / \ // | |-----------| |-----------| // | | p5 | | p7 | // | | x=4; | | x=x-3; | // |------| p6 | |-----------| // | q=y; | / // |-----------| / // \ / // \ / // \ / // \ / // |-----------| // | p8 | // | z=2p; | // |-----------| //
#[derive(Debug, PartialEq)] pub struct Xmas { numbers: Vec<usize>, first_valid_idx: usize, } impl Xmas { pub fn check_next(&mut self) -> Option<(usize, usize)> { // For 25 inputs brute-forcing should be fine for i in self.first_valid_idx - 25..self.first_valid_idx - 1 { for j in i + 1..self.first_valid_idx { if self.numbers[i] + self.numbers[j] == self.numbers[self.first_valid_idx] { self.first_valid_idx += 1; return Some((i, j)); } } } self.first_valid_idx += 1; None } } pub fn input_generator(input: &str) -> Xmas { let mut numbers = Vec::new(); for l in input.lines() { numbers.push(l.parse::<usize>().unwrap()); } Xmas { numbers, first_valid_idx: 25, } } #[aoc(day9, part1)] pub fn part1(input: &str) -> usize { let mut code = input_generator(input); while code.first_valid_idx < code.numbers.len() { match code.check_next() { Some(_) => (), None => return code.numbers[code.first_valid_idx - 1], } } panic!("All inputs were valid!"); } #[aoc(day9, part2)] pub fn part2(input: &str) -> usize { let code = input_generator(input); let mut i: usize = 0; let mut curr: usize = code.numbers[i]; let target: usize = 675280050; for j in 1..code.numbers.len() { while curr > target && i < j - 1 { curr -= code.numbers[i]; i += 1; } if curr == target { let mut max = 0; let mut min = 4294967296; for k in i..j { if code.numbers[k] > max { max = code.numbers[k]; } if code.numbers[k] < min { min = code.numbers[k]; } } return min + max; } if j < code.numbers.len() { curr += code.numbers[j]; } } panic!("No sequence sums to the target!"); } #[cfg(test)] mod tests { use super::*; #[test] fn test_input() { assert_eq!( input_generator("35\n20\n15\n25"), Xmas { numbers: vec![35, 20, 15, 25], first_valid_idx: 25, } ); } }
#![no_std] #[macro_use] extern crate veos_std; #[allow(unused_extern_crates)] extern crate rlibc; use core::time::Duration; #[no_mangle] pub fn main() { loop { veos_std::thread::sleep(Duration::from_millis(1000)); println!("Nest"); } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::serde_ext::*, char_collection::CharCollection, fidl_fuchsia_fonts::{GenericFontFamily, Slant, Width, WEIGHT_NORMAL}, fuchsia_url::pkg_url::PkgUrl, offset_string::OffsetString, serde::{ de::{Deserialize, Deserializer, Error}, ser::{Serialize, Serializer}, }, serde_derive::{Deserialize, Serialize}, std::{convert::TryFrom, path::PathBuf}, }; /// Version 2 of the Font Manifest schema. /// /// Less duplication than v1 schema. Intended for generation using a Rust tool, not for writing by /// hand. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct FontsManifest { /// List of families in the manifest. pub families: Vec<Family>, } /// Represents a font family, its metadata, and its font files. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Family { pub name: String, #[serde(skip_serializing_if = "Vec::is_empty")] pub aliases: Vec<String>, /// The generic font family that this font belongs to. If this is a specialty font (e.g. for /// custom icons), this should be set to `None`. #[serde(with = "OptGenericFontFamily")] pub generic_family: Option<GenericFontFamily>, /// Whether this family can be used as a fallback for other fonts (within the same generic /// family, or as a last resort). pub fallback: bool, /// Collection of font files that make up the font family. pub assets: Vec<Asset>, } /// Represents a single font file, which contains one or more [`Typeface`]s. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Asset { /// Asset identifier. Should be a valid file name, e.g. `"Roboto-Regular.ttf`. pub file_name: String, /// Where to find the file pub location: AssetLocation, /// List of typefaces in the file pub typefaces: Vec<Typeface>, } impl Asset { /// If the asset represents a local file, returns the package-relative path to the file. /// Otherwise, returns `None`. pub fn local_path(&self) -> Option<PathBuf> { match &self.location { AssetLocation::LocalFile(locator) => { Some(locator.directory.join(self.file_name.clone())) } _ => None, } } } /// Describes the location of a font asset. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub enum AssetLocation { /// Indicates that the file is accessible through a file path in the font server's namespace /// (e.g. at `/config/data/fonts/`). #[serde(rename = "local")] LocalFile(LocalFileLocator), /// Indicates that the file is accessible in a separate font package (e.g. /// `fuchsia-pkg://fuchsia.com/font-package-roboto-regular-ttf`). #[serde(rename = "package")] Package(PackageLocator), } /// Describes the location of a local file asset. Used in conjunction with [`Asset::file_name`]. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct LocalFileLocator { /// Package-relative path to the file, excluding the file name pub directory: PathBuf, } /// Describes the location of a font asset that's part of a Fuchsia package. Used in conjunction /// with [`Asset::file_name`]. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct PackageLocator { /// URL of just the package (not including the file name) pub package: PkgUrl, /// Type of package pub package_set: PackageSet, } /// Describes which set of dependencies a font package belongs to. /// /// See https://fuchsia.dev/fuchsia-src/development/build/boards_and_products#dependency_sets. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PackageSet { /// Package is in the device's base image (the "base set" of packages) Base, /// Package is available ephemerally (the "universe set" of packages) Universe, } /// Describes a single typeface within a font file #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Typeface { /// Index of the typeface in the file. If the file only contains a single typeface, this will /// always be `0`. #[serde(default = "Typeface::default_index")] pub index: u32, /// List of languages that the typeface supports, in BCP-47 format. /// /// Example: `["en", "zh-Hant", "sr-Cyrl"]` #[serde(default = "Typeface::default_languages", skip_serializing_if = "Vec::is_empty")] pub languages: Vec<String>, /// Text style of the typeface. #[serde(flatten)] pub style: Style, /// List of Unicode code points supported by the typeface. #[serde(with = "code_points_serde")] pub code_points: CharCollection, } impl Typeface { fn default_index() -> u32 { 0 } fn default_languages() -> Vec<String> { vec![] } } /// Used for de/serializing a `CharCollection`. mod code_points_serde { use super::*; pub fn deserialize<'d, D>(deserializer: D) -> Result<CharCollection, D::Error> where D: Deserializer<'d>, { let offset_string = OffsetString::deserialize(deserializer)?; CharCollection::try_from(offset_string).map_err(|e| D::Error::custom(format!("{:?}", e))) } pub fn serialize<S>(code_points: &CharCollection, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let offset_string: OffsetString = code_points.into(); offset_string.serialize(serializer) } } /// Describes a typeface's style properties. Equivalent to [`fidl_fuchsia_fonts::Style2`], but all /// fields are required. #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Style { #[serde(default = "Style::default_slant", with = "SlantDef")] pub slant: Slant, #[serde(default = "Style::default_weight")] pub weight: u16, #[serde(default = "Style::default_width", with = "WidthDef")] pub width: Width, } impl Style { fn default_slant() -> Slant { Slant::Upright } fn default_weight() -> u16 { WEIGHT_NORMAL } fn default_width() -> Width { Width::Normal } }
use std::net::{TcpListener, TcpStream}; pub fn listen_and_serve(port: i32, handle_func: &Fn(TcpStream)) { let addr = format!("127.0.0.1:{}", port); let listener = TcpListener::bind(addr).unwrap(); for s in listener.incoming() { let s = match s { Ok(stream) => handle_func(stream), Err(error) => panic!("You fool! {}", error), }; } }
use crate::parser::hir::Expression; use crate::parser::Flag; use crate::prelude::*; use derive_new::new; use indexmap::IndexMap; use log::trace; use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum NamedValue { AbsentSwitch, PresentSwitch(Tag), AbsentValue, Value(Expression), } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, new)] pub struct NamedArguments { #[new(default)] pub(crate) named: IndexMap<String, NamedValue>, } impl ToDebug for NamedArguments { fn fmt_debug(&self, f: &mut fmt::Formatter, source: &str) -> fmt::Result { for (name, value) in &self.named { match value { NamedValue::AbsentSwitch => continue, NamedValue::PresentSwitch(tag) => write!(f, " --{}", tag.slice(source))?, NamedValue::AbsentValue => continue, NamedValue::Value(expr) => write!(f, " --{} {}", name, expr.debug(source))?, } } Ok(()) } } impl NamedArguments { pub fn insert_switch(&mut self, name: impl Into<String>, switch: Option<Flag>) { let name = name.into(); trace!("Inserting switch -- {} = {:?}", name, switch); match switch { None => self.named.insert(name.into(), NamedValue::AbsentSwitch), Some(flag) => self .named .insert(name, NamedValue::PresentSwitch(*flag.name())), }; } pub fn insert_optional(&mut self, name: impl Into<String>, expr: Option<Expression>) { match expr { None => self.named.insert(name.into(), NamedValue::AbsentValue), Some(expr) => self.named.insert(name.into(), NamedValue::Value(expr)), }; } pub fn insert_mandatory(&mut self, name: impl Into<String>, expr: Expression) { self.named.insert(name.into(), NamedValue::Value(expr)); } }
use std::collections::HashMap; use std::fmt::{Debug, Display, Formatter}; use std::iter::zip; use std::mem; use std::path::Path; use std::sync::Arc; use chrono::{DateTime, Duration, Utc}; use command_data_derive::{CommandDataChoices, MenuCommand}; use discorsd::{async_trait, BotState}; use discorsd::commands::{AppCommandData, ButtonCommand, InteractionPayload, InteractionUse, MenuCommand, MenuData, Unused, Usability, Used}; use discorsd::errors::BotError; use discorsd::http::{ClientError, ClientResult, DiscordClient}; use discorsd::http::channel::{create_message, embed, MessageChannelExt, RichEmbed}; use discorsd::http::interaction::{webhook_message, WebhookMessage}; use discorsd::model::components::{ButtonStyle, make_button}; use discorsd::model::guild::GuildMember; use discorsd::model::ids::{ChannelId, GuildId, Id, MessageId, UserId}; use discorsd::model::interaction::{ButtonPressData, MenuSelectData, Token}; use discorsd::model::interaction_response::{InteractionMessage, message}; use discorsd::model::message::{Color, Message, TextMarkup, TimestampMarkup, TimestampStyle}; use discorsd::model::user::UserMarkup; use itertools::{Either, Itertools}; use rand::seq::SliceRandom; use crate::Bot; use crate::utils::ListIterGrammatically; async fn send_error<S, D, F>( state: S, interaction: InteractionUse<D, Unused>, embed: F, ) -> Result<InteractionUse<D, Used>, BotError> where S: AsRef<DiscordClient> + Send, D: InteractionPayload, F: FnOnce(&mut RichEmbed) + Send, { interaction.respond(state, message(|m| { m.ephemeral(); m.embed(embed); })).await.map_err(Into::into) } async fn send_game_error<D: InteractionPayload, S: AsRef<DiscordClient> + Send>( state: S, interaction: InteractionUse<D, Unused>, ) -> Result<InteractionUse<D, Used>, BotError> { send_error(state, interaction, |e| { e.title("Coup has already started in this server!"); e.description("Each server can only have one game of Coup at a time"); e.color(Color::RED); }).await } async fn send_config_error<D: InteractionPayload, S: AsRef<DiscordClient> + Send>( state: S, interaction: InteractionUse<D, Unused>, ) -> Result<InteractionUse<D, Used>, BotError> { send_error(state, interaction, |e| { e.title("Coup has not yet started in this server!"); e.description("Each server can only have one game of Coup at a time"); e.color(Color::RED); }).await } async fn send_non_player_error<D, S, U>( state: S, interaction: InteractionUse<D, Unused>, user: U, ) -> Result<InteractionUse<D, Used>, BotError> where D: InteractionPayload, S: AsRef<DiscordClient> + Send, U: Id<Id=UserId> + Send + Sync { send_error(state, interaction, |e| { e.title("Invalid target"); e.description(format!("{} is not in the game!", user.ping())); e.color(Color::RED); }).await } #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug, CommandDataChoices, MenuCommand)] #[menu(skip_display)] pub enum StartingCoins { Zero, One, #[command(default)] Two, } pub async fn start_setup( state: &BotState<Bot>, starting_coins: StartingCoins, guild: GuildId, interaction: InteractionUse<AppCommandData, Unused>, ) -> Result<InteractionUse<AppCommandData, Used>, BotError> { let mut game_guard = state.bot.coup_games.write().await; let coup = game_guard .entry(guild) .or_default(); let Coup::Config(config) = coup else { return send_game_error(&state, interaction).await; }; let interaction = interaction.delete(state).await?; config.starting_coins = starting_coins; let member = interaction.source .guild_ref() .cloned() .expect("Guild Command") .member; config.players.insert( member.id(), (member, interaction.token.clone()), ); config.update_settings_message(state, interaction.channel).await?; Ok(interaction) } #[derive(Debug)] pub enum Coup { Config(CoupConfig), // boxed because its a much bigger variant Game(Box<CoupGame>), } impl Default for Coup { fn default() -> Self { Self::Config(Default::default()) } } #[derive(Debug, Default)] pub struct CoupConfig { pub players: HashMap<UserId, (GuildMember, Token)>, pub starting_coins: StartingCoins, pub settings_display: Option<Message>, } impl CoupConfig { fn can_start(&self) -> bool { let n_players = self.players.len(); (2..=6).contains(&n_players) } pub async fn update_settings_message( &mut self, state: &BotState<Bot>, channel: ChannelId, ) -> ClientResult<()> { let message = create_message(|m| { m.embed(|e| { e.title("__Coup Setup__"); e.color(Color::GOLD); let players_list = self.players.keys() .map(UserId::ping) .join("\n"); e.add_field( format!("Players ({})", self.players.len()), if players_list.is_empty() { "None yet".into() } else { players_list }, ); e.add_field( "Starting Coins", self.starting_coins, ); }); m.menu(state, StartingCoinsMenu, |m| { m.min_values(1); m.default_options(|value| value == self.starting_coins.to_string()); }); m.buttons(state, [ (Box::new(JoinLeaveButton(true)) as _, make_button(|b| b.label("Join game"))), (Box::new(JoinLeaveButton(false)) as _, make_button(|b| { b.label("Leave game"); b.style(ButtonStyle::Danger); })), ]); m.button(state, StartButton, |b| { b.label("Start!"); b.style(ButtonStyle::Success); if !self.can_start() { b.disable(); } }); }); match &mut self.settings_display { Some(settings) if settings.channel == channel => { // todo edit message or resend? // setting message already exists in this channel, so just update it settings.edit(&state, message).await?; // let new = settings.channel.send(&state, message).await?; // let old = mem::replace(settings, new); // old.delete(&state.client).await?; } no_settings => { let new = channel.send(state, message).await?; *no_settings = Some(new); } } Ok(()) } async fn start_game(&mut self, state: Arc<BotState<Bot>>) -> ClientResult<CoupGame> { let starting_coins = self.starting_coins as usize; let mut cards = (0..15).map(|i| Card::from_int(i % 5)).collect_vec(); { let mut rng = rand::thread_rng(); cards.shuffle(&mut rng); } let mut cards = cards.chunks(2); let mut players = mem::take(&mut self.players) .into_iter() .map(|(_, (member, interaction_token))| CoupPlayer { member, token: interaction_token, coins: starting_coins, cards: cards.next().expect("6 (max players) * 2 < 15 (num_cards)").to_vec(), lost_cards: Vec::new(), cards_display: None, is_exchanging: None, }) .collect_vec(); { let mut rng = rand::thread_rng(); players.shuffle(&mut rng); if players.len() == 2 { players[0].coins -= 1; } } let mut handles = Vec::new(); for mut player in players.clone() { let state = Arc::clone(&state); let handle = tokio::spawn(async move { let msg = player.roles_message(&state).await?; let message = player.token.followup(&state, msg).await?; Ok(message.id) }); handles.push(handle); } let messages = futures::future::join_all(handles) .await .into_iter() .map(|res| res.expect("awaiting response does not panic")) .collect::<ClientResult<Vec<_>>>()?; for (player, message) in zip(&mut players, messages) { player.cards_display = Some((player.token.clone(), message)); } if let Some(settings) = &mut self.settings_display { settings.delete(&state).await?; } let coins = 50 - players.iter().map(|p| p.coins).sum::<usize>(); let mut game = CoupGame { players, starting_coins: self.starting_coins, card_pile: cards.flatten().copied().collect_vec(), coins, idx: 0, wait_state: Default::default(), wait_idx: 0, start_game: None, start_turn: None, contest: None, block: None, contest_block: None, lose_influence: None, lost_influence: None, influence_pic: None, exchange_menu: None, ability_use: None, }; game.get_edit_start_game(&state).await?; Ok(game) } } #[derive(Clone, Debug)] struct StartingCoinsMenu; #[async_trait] impl MenuCommand for StartingCoinsMenu { type Bot = Bot; type Data = StartingCoins; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<MenuSelectData, Unused>, mut data: Vec<Self::Data>, ) -> Result<InteractionUse<MenuSelectData, Used>, BotError> { { let guild = interaction.guild().unwrap(); let mut games_guard = state.bot.coup_games.write().await; let coup = games_guard.get_mut(&guild) .expect("Coup setup has started"); let Coup::Config(config) = coup else { return send_game_error(&state, interaction).await; }; config.starting_coins = data.remove(0); config.update_settings_message(&state, interaction.channel).await?; } interaction.defer_update(state).await.map_err(Into::into) } } #[derive(Clone, Debug)] struct JoinLeaveButton(bool); #[async_trait] impl ButtonCommand for JoinLeaveButton { type Bot = Bot; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<ButtonPressData, Unused>, ) -> Result<InteractionUse<ButtonPressData, Used>, BotError> { let guild = interaction.guild().unwrap(); let mut games_guard = state.bot.coup_games.write().await; let coup = games_guard.get_mut(&guild) .expect("Coup setup has started"); let Coup::Config(config) = coup else { return send_game_error(&state, interaction).await; }; let member = interaction.source.guild_ref() .cloned() .expect("This button only exists in guilds") .member; if self.0 { config.players.insert( member.id(), (member, interaction.token.clone()), ); } else { let was_not_in_game = config.players.remove(&member.id()).is_none(); if was_not_in_game { return send_error(&state, interaction, |e| { e.title("You weren't in the game, so you weren't removed"); e.color(Color::RED); }).await; } } config.update_settings_message(&state, interaction.channel).await?; drop(games_guard); interaction.defer_update(state).await.map_err(Into::into) } } #[derive(Clone, Debug)] struct StartButton; #[async_trait] impl ButtonCommand for StartButton { type Bot = Bot; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<ButtonPressData, Unused>, ) -> Result<InteractionUse<ButtonPressData, Used>, BotError> { let guild = interaction.guild().unwrap(); let mut games_guard = state.bot.coup_games.write().await; let coup = games_guard.get_mut(&guild) .expect("Game/Config must exist for StartButton to be shown"); let Coup::Config(config) = coup else { return interaction.respond(&state, message(|m| { m.ephemeral(); m.embed(|e| { e.title("Coup has already started!"); e.color(Color::RED); }); })).await.map_err(Into::into); }; if !config.can_start() { let n_players = config.players.len(); return interaction.respond(&state, message(|m| { m.embed(|e| { e.title(if n_players < 2 { "Not enough players to start" } else { "Too many players to start" }); e.color(Color::RED); }); })).await.map_err(Into::into); } let interaction = interaction.defer(&state).await?; let mut game = config.start_game(Arc::clone(&state)).await?; game.start_turn(&state).await?; *coup = Coup::Game(Box::new(game)); interaction.delete(&state) .await .map_err(Into::into) } } #[derive(Debug)] pub struct CoupGame { players: Vec<CoupPlayer>, starting_coins: StartingCoins, card_pile: Vec<Card>, coins: usize, idx: usize, wait_state: WaitState, wait_idx: usize, start_game: Option<(Token, MessageId)>, start_turn: Option<(Token, MessageId)>, contest: Option<(Token, MessageId)>, block: Option<(Token, MessageId)>, contest_block: Option<Token>, lose_influence: Option<(Token, MessageId)>, lost_influence: Option<Token>, influence_pic: Option<Token>, exchange_menu: Option<(Token, MessageId)>, ability_use: Option<(Token, MessageId)>, } impl CoupGame { fn take_into_setup(&mut self) -> CoupConfig { let players = self.players .drain(..) .map(|p| (p.id(), (p.member, p.token))) .collect(); CoupConfig { players, starting_coins: self.starting_coins, settings_display: None, } } fn current_player(&self) -> &CoupPlayer { &self.players[self.idx % self.players.len()] } fn current_player_mut(&mut self) -> &mut CoupPlayer { let len = self.players.len(); &mut self.players[self.idx % len] } fn get_player(&self, user: UserId) -> Option<&CoupPlayer> { self.players.iter() .find(|p| p.id() == user) } fn get_player_mut(&mut self, user: UserId) -> Option<&mut CoupPlayer> { self.players.iter_mut() .find(|p| p.id() == user) } fn wait(&mut self, interactions: Vec<(Token, MessageId, UserId)>) -> usize { self.wait_state = WaitState::Waiting(interactions); self.wait_idx += 1; self.wait_idx } fn update_token<D, U>(&mut self, interaction: &InteractionUse<D, U>) where D: InteractionPayload, U: Usability { let player = self.players.iter_mut() .find(|p| p.id() == interaction.user().id); match player { Some(player) => { // println!("setting {} = {}", player.member.user.username, interaction.token); player.token = interaction.token.clone(); } None => todo!("send error for user not in game using it") } } async fn delete_message(state: &BotState<Bot>, message: Option<(Token, MessageId)>) -> ClientResult<()> { if let Some((token, id)) = message { // println!("delete {token}"); state.client.delete_followup_message(state.application_id(), token, id).await?; } Ok(()) } async fn get_edit_start_game(&mut self, state: &BotState<Bot>) -> ClientResult<()> { let player = self.current_player(); let embed = embed(|e| { e.title("Coup!"); e.color(Color::GOLD); e.add_field( "Turn order", self.players.iter() .enumerate() .map(|(i, player)| { let field_description = format!( "{}: {} {} coin{}{}", i + 1, player.ping(), player.coins, if player.coins == 1 { "" } else { "s" }, if player.lost_cards.is_empty() { String::new() } else { format!(" Revealed: {}", player.lost_cards.iter().list_grammatically(Card::to_string, "and")) } ); if player.cards.is_empty() { field_description.strikethrough() } else { field_description } }) .join("\n"), ); e.add_inline_field( "Cards in Court Deck", self.card_pile.len(), ); e.add_blank_inline_field(); e.add_inline_field( "Coins left", self.coins, ); e.description(format!("{}, take your turn!", player.ping())); }); if let Some((token, id)) = &self.start_game { // already exists, so edit the message state.client.edit_followup_message( state.application_id(), token.clone(), *id, embed.into(), ).await?; } else { // first time, so send the message // todo handle if someone deletes the message let message = player.token .followup(&state, embed) .await?; self.start_game = Some((player.token.clone(), message.id)); } Ok(()) } fn start_turn_message(state: &BotState<Bot>, coins: usize, get_target_for: Option<Ability>) -> InteractionMessage { message(|m| { m.ephemeral(); m.content(format!("Take an action! You have {} coins.", coins.to_string().bold())); m.menu(state, AbilityMenu, |m| { m.placeholder("Pick an ability"); m.options(Ability::all() .into_iter() .filter(|a| a.needed_coins() <= coins) .map(Ability::into_option) .collect() ); if let Some(ability) = get_target_for { m.default_options(|s| s == ability.to_string()); } }); if let Some(ability) = get_target_for { m.menu(state, AbilityTargetMenu(ability), |m| { m.placeholder("Target of the ability"); }); } }) } async fn start_turn(&mut self, state: &BotState<Bot>) -> ClientResult<()> { let player = self.current_player(); let message = player.token .followup(state, Self::start_turn_message(state, player.coins, None)) .await?; self.start_turn = Some((player.token.clone(), message.id)); Ok(()) } // todo check if game is over async fn next_turn(&mut self, state: &BotState<Bot>) -> ClientResult<()> { self.idx += 1; while self.current_player().cards.is_empty() { self.idx += 1; } if self.players.iter().filter(|p| !p.cards.is_empty()).count() == 1 { // only one player left, game is over! let winner = self.current_player(); winner.token.followup(&state, winner.win_message(state, true)).await?; } else { Self::delete_message(state, self.start_turn.take()).await?; self.get_edit_start_game(state).await?; self.start_turn(state).await?; } Ok(()) } async fn resolve_ability( &mut self, state: &BotState<Bot>, ability: FullAbility, ) -> ClientResult<()> { Self::delete_message(state, self.ability_use.take()).await?; match ability { FullAbility::Use(ability) => match ability.ability { AbilityTargeted::Income => { if let Some(coins) = self.coins.checked_sub(1) { // only take a coin if there was a coin left self.coins = coins; self.current_player_mut().coins += 1; } let player = self.current_player(); let message = player.token.followup(&state, ability.to_string()).await?; self.ability_use = Some((player.token.clone(), message.id)); self.next_turn(state).await?; Ok(()) } AbilityTargeted::ForeignAid => { if let Some(coins) = self.coins.checked_sub(2) { // only take 2 coins if there are 2 coins left self.coins = coins; self.current_player_mut().coins += 2; } else { self.current_player_mut().coins += self.coins; self.coins = 0; } let player = self.current_player(); let message = player.token.followup(&state, ability.to_string()).await?; self.ability_use = Some((player.token.clone(), message.id)); self.next_turn(state).await?; Ok(()) } AbilityTargeted::Tax => { if let Some(coins) = self.coins.checked_sub(3) { // only take 3 coins if there are 3 coins left self.coins = coins; self.current_player_mut().coins += 3; } else { self.current_player_mut().coins += self.coins; self.coins = 0; } let player = self.current_player(); let message = player.token.followup(&state, ability.to_string()).await?; self.ability_use = Some((player.token.clone(), message.id)); self.next_turn(state).await?; Ok(()) } AbilityTargeted::Coup(target) => { self.current_player_mut().coins -= 7; let target = self.get_player(target).expect("Target in game"); let message = LostInfluenceMenu::create(state, target, None).await?; self.lose_influence = Some((target.token.clone(), message.id)); let player = self.current_player(); let message = player.token.followup(&state, ability.to_string()).await?; self.ability_use = Some((player.token.clone(), message.id)); Ok(()) } AbilityTargeted::Assassinate(target) => { self.current_player_mut().coins -= 3; let target = self.get_player(target).expect("Target in game"); let message = LostInfluenceMenu::create(state, target, None).await?; self.lose_influence = Some((target.token.clone(), message.id)); let player = self.current_player(); let message = player.token.followup(&state, ability.to_string()).await?; self.ability_use = Some((player.token.clone(), message.id)); Ok(()) } AbilityTargeted::Exchange => { let cards = mem::take(&mut self.current_player_mut().cards) .into_iter() .chain(self.card_pile.drain(..2)) .collect_vec(); let n_keep = cards.len() - 2; let player = self.current_player_mut(); let message = player.token.followup(&state, format!("{} is choosing cards to Exchange...", player.ping())) .await?; player.is_exchanging = Some((player.token.clone(), message.id)); let message = player.token .followup(&state, webhook_message(|m| { m.ephemeral(); m.content(format!("Choose {n_keep} roles to **keep**:")); cards.iter() .copied() .map(Card::image) .enumerate() // named so that all attachments appear if any cards are the same .for_each(|(i, path)| m.attach((format!("role{i}.png"), path))); let options = cards.iter() .enumerate() .map(|(i, c)| { let mut option = c.into_option(); option.label = format!("{i}: {}", option.label); option.value = i.to_string(); option }) .collect(); m.menu(state, ExchangeMenu(cards), |m| { m.min_max_values(n_keep, n_keep); m.options(options); }); })) .await?; self.exchange_menu = Some((player.token.clone(), message.id)); Ok(()) } AbilityTargeted::Steal(target) => { let target = self.get_player_mut(target).expect("Target in game"); if let Some(coins) = target.coins.checked_sub(2) { // only take 2 coins if target has 2 coins target.coins = coins; self.current_player_mut().coins += 2; } else { let target_coins = target.coins; target.coins = 0; self.current_player_mut().coins += target_coins; } let player = self.current_player(); let message = player.token.followup(&state, ability.to_string()).await?; self.ability_use = Some((player.token.clone(), message.id)); self.next_turn(state).await?; Ok(()) } } FullAbility::Block(_, _, _) => { let player = self.current_player(); let message = player.token.followup(&state, ability.to_string()).await?; self.ability_use = Some((player.token.clone(), message.id)); self.next_turn(state).await?; Ok(()) } } } } #[derive(Clone, Debug)] struct RestartButton; #[async_trait] impl ButtonCommand for RestartButton { type Bot = Bot; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<ButtonPressData, Unused>, ) -> Result<InteractionUse<ButtonPressData, Used>, BotError> { let guild = interaction.guild().unwrap(); let mut game_guard = state.bot.coup_games.write().await; let coup = game_guard.get_mut(&guild).unwrap(); let Coup::Game(game) = coup else { return send_config_error(&state, interaction).await; }; // game.update_token(&interaction);2 let win_message = game.current_player().win_message(&state, false); let mut config = game.take_into_setup(); config.update_settings_message(&state, interaction.channel).await?; *coup = Coup::Config(config); interaction.update(&state, win_message).await.map_err(Into::into) } } #[derive(Clone, Debug)] struct ExchangeMenu(Vec<Card>); #[async_trait] impl MenuCommand for ExchangeMenu { type Bot = Bot; type Data = String; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<MenuSelectData, Unused>, data: Vec<Self::Data>, ) -> Result<InteractionUse<MenuSelectData, Used>, BotError> { let guild = interaction.guild().unwrap(); let mut game_guard = state.bot.coup_games.write().await; let Coup::Game(game) = game_guard.get_mut(&guild).unwrap() else { return send_config_error(&state, interaction).await; }; let (mut keep, mut retrn) = (Vec::new(), Vec::new()); for (i, &card) in self.0.iter().enumerate() { match data.contains(&i.to_string()) { true => keep.push(card), false => retrn.push(card), } } game.card_pile.extend(retrn); let player = game.current_player_mut(); player.cards = keep; player.send_roles(&state).await?; CoupGame::delete_message(&state, player.is_exchanging.take()).await?; let message = player.token .followup(&state, AbilityResolved { user: player.id(), ability: AbilityTargeted::Exchange }.to_string()) .await?; let token = player.token.clone(); let ability_use = &mut game.ability_use; CoupGame::delete_message(&state, ability_use.take()).await?; *ability_use = Some((token, message.id)); CoupGame::delete_message(&state, game.exchange_menu.take()).await?; game.next_turn(&state).await?; interaction.defer_update(&state).await.map_err(Into::into) } } #[derive(Debug, Default, Clone)] enum WaitState { /// Not waiting. Starts like this, and when a contest/block happens, gets reset to this #[default] None, /// Counting down, players have a button to pause Waiting(Vec<(Token, MessageId, UserId)>), /// Someone pressed the pause button Paused(Vec<(Token, MessageId, UserId)>), /// The countdown is done, and if unpaused, don't have to keep waiting PausedDone(Vec<(Token, MessageId, UserId)>), } impl WaitState { async fn delete_messages(&mut self, state: &BotState<Bot>) -> ClientResult<()> { match self { Self::None => {} Self::Waiting(interactions) | Self::Paused(interactions) | Self::PausedDone(interactions) => { let app = state.application_id(); for (token, id, _) in interactions.drain(..) { state.client.delete_followup_message(app, token, id).await?; } } }; *self = Self::None; Ok(()) } } #[derive(Debug, Clone)] struct AbilityMenu; #[derive(MenuCommand, Copy, Clone, Debug, PartialEq, Eq)] enum Ability { #[menu(desc = "Take 1 coin")] Income, #[menu(label = "Foreign Aid", desc = "Take 2 coins. Can be blocked by Duke")] ForeignAid, #[menu(desc = "Pay 7 coins. Choose player to lose influence")] Coup, #[menu(desc = "Take 3 coins")] Tax, #[menu(desc = "Pay 3 coins. Choose player to lose influence. Can be blocked by Contessa")] Assassinate, #[menu(desc = "Exchange cards with Court Deck")] Exchange, #[menu(desc = "Take 2 coins from another player. Can be blocked by Ambassador or Captain")] Steal, } impl Ability { fn needed_coins(self) -> usize { match self { Self::Income | Self::ForeignAid | Self::Tax | Self::Exchange | Self::Steal => 0, Self::Assassinate => 3, Self::Coup => 7, } } fn target(self, target: Option<UserId>) -> Option<AbilityTargeted> { Some(match self { Self::Income => AbilityTargeted::Income, Self::ForeignAid => AbilityTargeted::ForeignAid, Self::Coup => AbilityTargeted::Coup(target?), Self::Tax => AbilityTargeted::Tax, Self::Assassinate => AbilityTargeted::Assassinate(target?), Self::Exchange => AbilityTargeted::Exchange, Self::Steal => AbilityTargeted::Steal(target?), }) } /// resolve this ability to state that it can then be countered/contested async fn get_target( &self, state: &BotState<Bot>, interaction: InteractionUse<MenuSelectData, Unused>, coins: usize, ) -> ClientResult<InteractionUse<MenuSelectData, Used>> { match self { &ability @ Self::Coup | &ability @ Self::Assassinate | &ability @ Self::Steal => // enable target box interaction .update(state, CoupGame::start_turn_message(state, coins, Some(ability))) .await, Self::Income | Self::ForeignAid | Self::Tax | Self::Exchange => interaction.defer_update(state).await, } } fn contest_block_embed<F: FnOnce(&mut WebhookMessage)>( state: &BotState<Bot>, ability_desc: &str, countdown_or_pauser: Either<DateTime<Utc>, UserId>, button: Either<WaitButton, UnpauseButton>, send_pause_button: bool, make_components: F, ) -> WebhookMessage { webhook_message(|m| { m.ephemeral(); let content = match countdown_or_pauser { Either::Left(expire_time) => format!( "{ability_desc}. The action will go through {}", (expire_time).timestamp_styled(TimestampStyle::Relative) ), Either::Right(pauser) => format!( "{ability_desc}. {} paused the countdown", pauser.ping() ) }; m.content(content); if send_pause_button { // skip sending button to the player what is being blocked/contested/etc match button { Either::Left(wait) => m.button(state, wait, |b| { b.label("Wait!!!"); }), Either::Right(unpause) => m.button(state, unpause, |b| { b.label("Proceed!"); }), } make_components(m); } }) } } #[derive(Debug, Copy, Clone)] enum AbilityTargeted { Income, ForeignAid, Coup(UserId), Tax, Assassinate(UserId), Exchange, Steal(UserId), } #[derive(Debug, Copy, Clone)] struct AbilityResolved { user: UserId, ability: AbilityTargeted, } impl AbilityResolved { fn counter_roles(self) -> Option<&'static [Card]> { match self.ability { AbilityTargeted::Income | AbilityTargeted::Coup(_) | AbilityTargeted::Tax | AbilityTargeted::Exchange => None, AbilityTargeted::ForeignAid => Some(&[Card::Duke]), AbilityTargeted::Assassinate(_) => Some(&[Card::Contessa]), AbilityTargeted::Steal(_) => Some(&[Card::Ambassador, Card::Captain]), } } fn needed_card(self) -> Option<Card> { match self.ability { AbilityTargeted::Income | AbilityTargeted::ForeignAid | AbilityTargeted::Coup(_) => None, AbilityTargeted::Tax => Some(Card::Duke), AbilityTargeted::Assassinate(_) => Some(Card::Assassin), AbilityTargeted::Exchange => Some(Card::Ambassador), AbilityTargeted::Steal(_) => Some(Card::Captain), } } } impl Display for AbilityResolved { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let user = self.user.ping(); match self.ability { AbilityTargeted::Income => write!(f, "{user} took Income"), AbilityTargeted::ForeignAid => write!(f, "{user} took Foreign Aid"), AbilityTargeted::Coup(target) => write!(f, "{user} Couped {}", target.ping()), AbilityTargeted::Tax => write!(f, "{user} Taxed"), AbilityTargeted::Assassinate(target) => write!(f, "{user} Assassinated {}", target.ping()), AbilityTargeted::Exchange => write!(f, "{user} Exchanged with the court deck"), AbilityTargeted::Steal(target) => write!(f, "{user} Stole from {}", target.ping()), } } } #[derive(Debug, Copy, Clone)] enum FullAbility { Use(AbilityResolved), Block(AbilityResolved, UserId, Card), } impl Display for FullAbility { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Use(ability) => write!(f, "{ability}"), Self::Block(ability, user, claim) => { write!(f, "{ability}\n{} blocks with {claim}", user.ping()) } } } } impl FullAbility { fn is_use(self) -> bool { matches!(self, Self::Use(_)) } fn is_block(self) -> bool { matches!(self, Self::Block(_, _, _)) } fn ability(self) -> AbilityResolved { match self { Self::Use(a) | Self::Block(a, _, _) => a, } } fn user(self) -> UserId { match self { Self::Use(a) => a.user, Self::Block(_, u, _) => u, } } fn counter_roles(self) -> Option<&'static [Card]> { match self { Self::Use(a) => a.counter_roles(), Self::Block(_, _, _) => None, } } fn needed_card(self) -> Option<Card> { match self { Self::Use(a) => a.needed_card(), Self::Block(_, _, c) => Some(c), } } async fn prompt_response( self, state: &Arc<BotState<Bot>>, game: &mut CoupGame, interaction: InteractionUse<MenuSelectData, Unused>, ) -> Result<InteractionUse<MenuSelectData, Used>, BotError> { let guild = interaction.guild().unwrap(); CoupGame::delete_message(state, game.start_turn.take()).await?; if let Some(token) = game.influence_pic.take() { state.client.delete_interaction_response(state.application_id(), token).await?; } if self.counter_roles().is_some() || self.needed_card().is_some() { let current_player = &game.current_player().member; let current_player_id = current_player.id(); let current_player_name = current_player.nick.clone().unwrap_or_else(|| current_player.user.username.clone()); // give all players 5 seconds to either block, contest, or click the "considering" button let wait_time = Duration::seconds(6); let expire_time = Utc::now() + wait_time; let mut handles = Vec::new(); for player in game.players.clone() { let state = Arc::clone(state); let current_player_name = current_player_name.clone(); let handle = tokio::spawn(async move { let message = player.token.followup(&state, Ability::contest_block_embed( &state, &self.to_string(), Either::Left(expire_time), Either::Left(WaitButton { ability: self, }), current_player_id != player.id(), |m| { if let Some(counter_roles) = self.counter_roles() { m.menu( &state, BlockMenu { ability: self.ability() }, |m| { m.placeholder("Block with..."); m.options(counter_roles.iter().copied().map(Card::into_option).collect()); }, ); } if let Some(claim) = self.needed_card() { m.button(&state, ContestButton { ability: self, claim, claimer: current_player_id, }, |b| { b.label(format!("Contest that {} has {claim}", current_player_name)); b.style(ButtonStyle::Danger); }); } }, )).await?; Ok((player.token.clone(), message.id, player.id())) }); handles.push(handle); } let interactions = futures::future::join_all(handles) .await .into_iter() .map(|res| res.expect("awaiting response does not panic")) .collect::<ClientResult<Vec<_>>>()?; let wait_idx = game.wait(interactions); tokio::spawn({ let state = Arc::clone(state); async move { tokio::time::sleep(wait_time.to_std().unwrap()).await; let mut game_guard = state.bot.coup_games.write().await; let Coup::Game(game) = game_guard.get_mut(&guild).unwrap() else { todo!() // send_config_error(&state, interaction).await?; }; if game.wait_idx != wait_idx { return Ok(()); } match &mut game.wait_state { WaitState::None => { // someone already used something, so don't do anything } wait_state @ WaitState::Waiting(_) => { // if the game is still waiting, we're now done waiting wait_state.delete_messages(&state).await?; CoupGame::delete_message(&state, game.contest.take()).await?; CoupGame::delete_message(&state, game.block.take()).await?; game.resolve_ability(&state, Self::Use(self.ability())).await?; } WaitState::Paused(interactions) => { // its currently paused, so just mark that the countdown is done game.wait_state = WaitState::PausedDone(mem::take(interactions)); } WaitState::PausedDone(_) => { unreachable!("Can only be here done was paused before sleep finished") } }; Ok::<(), ClientError>(()) } }); } else { game.resolve_ability(state, Self::Use(self.ability())).await?; } interaction.defer_update(&state).await.map_err(Into::into) } } #[async_trait] impl MenuCommand for AbilityMenu { type Bot = Bot; type Data = Ability; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<MenuSelectData, Unused>, mut data: Vec<Self::Data>, ) -> Result<InteractionUse<MenuSelectData, Used>, BotError> { let guild = interaction.guild().unwrap(); let ability = data.remove(0); let mut games_guard = state.bot.coup_games.write().await; let coup = games_guard.get_mut(&guild).unwrap(); let Coup::Game(game) = coup else { return send_config_error(&state, interaction).await; }; // todo for some reason this token doesn't work // game.update_token(&interaction); game.wait_state.delete_messages(&state).await?; if let Some(ability) = ability.target(None) { // retargeted let ability = FullAbility::Use(AbilityResolved { user: interaction.user().id, ability }); ability.prompt_response(&state, game, interaction) .await } else { // get target ability.get_target(&state, interaction, game.current_player().coins) .await .map_err(Into::into) } } } #[derive(Debug, Clone)] struct WaitButton { ability: FullAbility, } #[async_trait] impl ButtonCommand for WaitButton { type Bot = Bot; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<ButtonPressData, Unused>, ) -> Result<InteractionUse<ButtonPressData, Used>, BotError> { let guild = interaction.guild().unwrap(); let interaction_user = interaction.user().id; let mut game_guard = state.bot.coup_games.write().await; let Coup::Game(game) = game_guard.get_mut(&guild).unwrap() else { return send_config_error(&state, interaction).await; }; game.update_token(&interaction); let ability_user_name = game.get_player(self.ability.ability().user).unwrap().name(); match &mut game.wait_state { WaitState::None => { println!("WS None!"); // means a user clicked the button before it was deleted but after we send to req // to delete it, aka they were too slow. so don't do anything } WaitState::Paused(_) => todo!(), WaitState::PausedDone(_) => todo!(), WaitState::Waiting(interactions) => { let mut handles = Vec::new(); let app = state.application_id(); for (token, id, receiver) in interactions.clone() { let state = Arc::clone(&state); let ability = self.ability; let ability_user_name = ability_user_name.clone(); let handle = tokio::spawn(async move { state.client.edit_followup_message( app, token.clone(), id, Ability::contest_block_embed( &state, &ability.to_string(), Either::Right(interaction_user), Either::Right(UnpauseButton(ability)), receiver != ability.user(), |m| { if let Some(counter_roles) = ability.counter_roles() { m.menu(&state, BlockMenu { ability: ability.ability() }, |m| { m.placeholder("Block with..."); m.options(counter_roles.iter().copied().map(Card::into_option).collect()); }); } if let Some(claim) = ability.needed_card() { m.button(&state, ContestButton { ability, claim, claimer: ability.ability().user, }, |b| { b.label(format!("Contest that {} has {claim}", ability_user_name)); b.style(ButtonStyle::Danger); }); } }, ), ).await?; Ok(()) }); handles.push(handle); } futures::future::join_all(handles) .await .into_iter() .map(|res| res.expect("awaiting response does not panic")) .collect::<ClientResult<Vec<()>>>()?; game.wait_state = WaitState::Paused(mem::take(interactions)); } } interaction.defer_update(&state) .await .map_err(Into::into) } } #[derive(Debug, Clone)] struct UnpauseButton(FullAbility); #[async_trait] impl ButtonCommand for UnpauseButton { type Bot = Bot; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<ButtonPressData, Unused>, ) -> Result<InteractionUse<ButtonPressData, Used>, BotError> { let guild = interaction.guild().unwrap(); let mut game_guard = state.bot.coup_games.write().await; let Coup::Game(game) = game_guard.get_mut(&guild).unwrap() else { return send_config_error(&state, interaction).await; }; // todo this doesn't work??? // game.update_token(&interaction); match &mut game.wait_state { WaitState::None => todo!(), WaitState::Waiting(_) => unreachable!("?"), WaitState::Paused(interactions) => { game.wait_state = WaitState::Waiting(mem::take(interactions)); interaction.defer_update(&state).await.map_err(Into::into) } wait_state @ WaitState::PausedDone(_) => { wait_state.delete_messages(&state).await?; game.resolve_ability(&state, FullAbility::Use(self.0.ability())).await?; interaction.defer_update(&state).await.map_err(Into::into) } } } } #[derive(Debug, Clone)] struct AbilityTargetMenu(Ability); #[async_trait] impl MenuCommand for AbilityTargetMenu { type Bot = Bot; type Data = UserId; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<MenuSelectData, Unused>, mut data: Vec<Self::Data>, ) -> Result<InteractionUse<MenuSelectData, Used>, BotError> { let guild = interaction.guild().unwrap(); let target = data.remove(0); let mut games_guard = state.bot.coup_games.write().await; let Coup::Game(game) = games_guard.get_mut(&guild).unwrap() else { return send_config_error(&state, interaction).await; }; // game.update_token(&interaction); if !game.players.iter().any(|p| p.id() == target) { return send_error(&state, interaction, |e| { e.color(Color::RED); e.title("Choose someone in the game!"); }).await; } if target == game.current_player().id() { return send_error(&state, interaction, |e| { e.color(Color::RED); e.title("You can't target yourself!"); }).await; } let ability = self.0.target(Some(target)).unwrap(); let ability = FullAbility::Use(AbilityResolved { user: interaction.user().id, ability }); ability.prompt_response(&state, game, interaction) .await } } #[derive(Debug, Clone, Copy)] struct BlockMenu { ability: AbilityResolved, } #[async_trait] impl MenuCommand for BlockMenu { type Bot = Bot; type Data = Card; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<MenuSelectData, Unused>, mut data: Vec<Self::Data>, ) -> Result<InteractionUse<MenuSelectData, Used>, BotError> { let guild = interaction.guild().unwrap(); let blocker = interaction.user().id; let claim = data.remove(0); let mut games_guard = state.bot.coup_games.write().await; let Coup::Game(game) = games_guard.get_mut(&guild).unwrap() else { return send_config_error(&state, interaction).await; }; // game.update_token(&interaction); game.wait_state.delete_messages(&state).await?; let Some(blocker) = game.get_player(blocker) else { return send_non_player_error(&state, interaction, blocker).await; }; let blocker_id = blocker.id(); let ability = FullAbility::Block(self.ability, blocker_id, claim); // give all players 5 seconds to either block, contest, or click the "considering" button let wait_time = Duration::seconds(6); let expire_time = Utc::now() + wait_time; let mut handles = Vec::new(); for player in game.players.clone() { let state = Arc::clone(&state); let blocker_name = blocker.member.nick.clone().unwrap_or_else(|| blocker.member.user.username.clone()); let player_id = player.id(); let handle = tokio::spawn(async move { let message = player.token.followup( &state, Ability::contest_block_embed( &state, &ability.to_string(), Either::Left(expire_time), Either::Left(WaitButton { ability }), blocker_id != player_id, |m| { m.button(&state, ContestButton { ability, claim, claimer: blocker_id, }, |b| { b.label(format!("Contest that {} has {claim}", blocker_name)); b.style(ButtonStyle::Danger); }); }, ), ).await?; Ok((player.token.clone(), message.id, player.id())) }); handles.push(handle); }; let interactions = futures::future::join_all(handles) .await .into_iter() .map(|res| res.expect("awaiting response does not panic")) .collect::<ClientResult<Vec<_>>>()?; let wait_idx = game.wait(interactions); tokio::spawn({ let state = Arc::clone(&state); async move { tokio::time::sleep(wait_time.to_std().unwrap()).await; let mut game_guard = state.bot.coup_games.write().await; let Coup::Game(game) = game_guard.get_mut(&guild).unwrap() else { todo!() // send_config_error(&state, interaction).await?; }; if game.wait_idx != wait_idx { return Ok(()); } match &mut game.wait_state { WaitState::None => { // someone already used something, so don't do anything } wait_state @ WaitState::Waiting(_) => { // if the game is still waiting, we're now done waiting wait_state.delete_messages(&state).await?; CoupGame::delete_message(&state, game.contest.take()).await?; CoupGame::delete_message(&state, game.block.take()).await?; game.resolve_ability(&state, ability).await?; } WaitState::Paused(interactions) => { // its currently paused, so just mark that the countdown is done game.wait_state = WaitState::PausedDone(mem::take(interactions)); } WaitState::PausedDone(_) => { unreachable!("Can only be here done was paused before sleep finished") } }; Ok::<(), ClientError>(()) } }); CoupGame::delete_message(&state, game.block.take()).await?; CoupGame::delete_message(&state, game.contest.take()).await?; game.contest_block = Some(interaction.token.clone()); Ok(interaction.defer_update(&state).await?) } } #[derive(Debug, Clone)] struct ContestButton { ability: FullAbility, claim: Card, claimer: UserId, } #[async_trait] impl ButtonCommand for ContestButton { type Bot = Bot; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<ButtonPressData, Unused>, ) -> Result<InteractionUse<ButtonPressData, Used>, BotError> { let guild = interaction.guild().unwrap(); let contester = interaction.user().id; let mut game_guard = state.bot.coup_games.write().await; let Coup::Game(game) = game_guard.get_mut(&guild).unwrap() else { return send_config_error(&state, interaction).await; }; game.update_token(&interaction); game.wait_state.delete_messages(&state).await?; let Some(contester) = game.get_player(contester) else { return send_non_player_error(&state, interaction, &contester).await; }; let contester_token = contester.token.clone(); let claimer = game.get_player(self.claimer).unwrap(); let claimer_token = claimer.token.clone(); let interaction = if claimer.cards.contains(&self.claim) { // does have the card, so contester loses an influence let content = format!( "{c} contested that {} had {}, but they did!\n{c} will now lose an influence.", self.claimer.ping(), self.claim, c = contester.ping(), ); let interaction = interaction.respond(&state, content).await?; // give the contester a menu to choose which influence to lose // does have the card, so it should resolve if it's a use, not if its a block (?) let ability = self.ability.is_use().then_some(self.ability); let message = LostInfluenceMenu::create(&state, contester, ability).await?; // todo idk if this is right? game.lost_influence = Some(interaction.token.clone()); game.lose_influence = Some((contester_token, message.id)); { // the claimer draws a new influence now let claimer_idx = game.players.iter().position(|p| p.id() == self.claimer).unwrap(); let mut claimer = game.players.remove(claimer_idx); let card_idx = claimer.cards.iter().position(|c| *c == self.claim).unwrap(); let card = claimer.cards.remove(card_idx); game.card_pile.push(card); { let mut rng = rand::thread_rng(); game.card_pile.shuffle(&mut rng); } let new_card = game.card_pile.swap_remove(0); claimer.cards.push(new_card); claimer.send_roles(&state).await?; game.players.insert(claimer_idx, claimer); } interaction } else { // does not have the card, so claimer loses an influence let content = format!( "{} contested that {c} had {}, and they didn't!\n{c} will now lose an influence.", contester.ping(), self.claim, c = self.claimer.ping(), ); let interaction = interaction.respond(&state, content).await?; // give the claimer a menu to choose which influence to lose // doesn't have the card, so it should resolve if it's a use, not if its a block (?) let ability = self.ability.is_block().then_some(self.ability.ability()).map(FullAbility::Use); let message = LostInfluenceMenu::create(&state, claimer, ability).await?; // todo idk if this is right? game.lost_influence = Some(interaction.token.clone()); game.lose_influence = Some((claimer_token, message.id)); interaction }; CoupGame::delete_message(&state, game.block.take()).await?; CoupGame::delete_message(&state, game.contest.take()).await?; if let Some(token) = game.contest_block.take() { state.client.delete_interaction_response(state.application_id(), token).await?; } game.lost_influence = Some(interaction.token.clone()); Ok(interaction) } } #[derive(Debug, Clone)] struct LostInfluenceMenu(UserId, Option<FullAbility>); impl LostInfluenceMenu { async fn create(state: &BotState<Bot>, player: &CoupPlayer, ability: Option<FullAbility>) -> ClientResult<Message> { player.token.followup(&state, webhook_message(|m| { m.ephemeral(); m.content("Choose an influence to lose"); // todo don't make them choose if they only have one influence left m.menu(state, Self(player.id(), ability), |m| { m.placeholder("Choose an influence..."); m.options(player.cards.iter().copied().map(Card::into_option).collect()); }); })).await } } #[async_trait] impl MenuCommand for LostInfluenceMenu { type Bot = Bot; type Data = Card; async fn run( &self, state: Arc<BotState<Self::Bot>>, interaction: InteractionUse<MenuSelectData, Unused>, mut data: Vec<Self::Data>, ) -> Result<InteractionUse<MenuSelectData, Used>, BotError> { let lost = data.remove(0); let guild = interaction.guild().unwrap(); let mut game_guard = state.bot.coup_games.write().await; let Coup::Game(game) = game_guard.get_mut(&guild).unwrap() else { return send_config_error(&state, interaction).await; }; // game.update_token(&interaction); game.wait_state.delete_messages(&state).await?; let loser = game.get_player_mut(self.0).unwrap(); let idx = loser.cards.iter() .position(|c| *c == lost) .expect("card that is lost is only given the loser's cards"); let card = loser.cards.remove(idx); loser.lost_cards.push(card); let interaction = interaction.respond(&state, message(|m| { m.content(format!( "{} has revealed {card}. {}", loser.ping(), if loser.cards.is_empty() { "They have no influence and are out of the game!" } else { "They have one influence left!" } )); m.attach(card.image()); })).await?; loser.send_roles(&state).await?; if let Some(token) = game.lost_influence.take() { state.client.delete_interaction_response(state.application_id(), token).await?; } CoupGame::delete_message(&state, game.lose_influence.take()).await?; game.influence_pic = Some(interaction.token.clone()); if let Some(ability) = self.1 { game.resolve_ability(&state, ability).await?; } else { game.next_turn(&state).await?; } Ok(interaction) } } #[derive(Debug, Clone)] struct CoupPlayer { member: GuildMember, token: Token, coins: usize, cards: Vec<Card>, lost_cards: Vec<Card>, cards_display: Option<(Token, MessageId)>, is_exchanging: Option<(Token, MessageId)>, } impl CoupPlayer { fn name(&self) -> String { self.member.nick .clone() .unwrap_or_else(|| self.member.user.username.clone()) } async fn roles_message(&mut self, state: &BotState<Bot>) -> ClientResult<WebhookMessage> { CoupGame::delete_message(state, self.cards_display.take()).await?; let message = webhook_message(|m| { m.ephemeral(); self.cards.iter() .copied() .map(Card::image) .enumerate() // named so that both 2 attachments appear if both cards are the same .for_each(|(i, path)| m.attach((format!("role{i}.png"), path))); let roles_str = self.cards.iter() // .rev() .copied() .map(Card::name) .list_grammatically(TextMarkup::bold, "and"); let coins = self.coins.to_string().bold(); m.content(format!("Your influence: {roles_str}. You have {coins} coins.")); }); Ok(message) } async fn send_roles(&mut self, state: &Arc<BotState<Bot>>) -> ClientResult<()> { // always delete let message = self.roles_message(state).await?; if !self.cards.is_empty() { let message = self.token.followup(&state, message).await?; self.cards_display = Some((self.token.clone(), message.id)); } Ok(()) } fn win_message(&self, state: &BotState<Bot>, restart_enabled: bool) -> InteractionMessage { message(|m| { m.embed(|e| { let name = self.member.nick.clone().unwrap_or_else(|| self.member.user.username.clone()); e.title(format!("🎉 {name} Wins! 🎉")); e.description(format!("They had {} left.", self.cards.iter().list_grammatically(Card::to_string, "and"))); e.color(Color::GOLD); e.authored_by(&self.member.user); }); m.button(state, RestartButton, |b| { b.label("Restart"); if !restart_enabled { b.disable(); } }); }) } } impl PartialEq for CoupPlayer { fn eq(&self, other: &Self) -> bool { self.id() == other.id() } } impl Id for CoupPlayer { type Id = UserId; fn id(&self) -> Self::Id { self.member.id() } } #[derive(Debug, Copy, Clone, Eq, PartialEq, MenuCommand)] pub enum Card { Duke, Assassin, Ambassador, Captain, Contessa, } impl Card { fn from_int(c: usize) -> Self { match c { 0 => Self::Duke, 1 => Self::Assassin, 2 => Self::Ambassador, 3 => Self::Captain, 4 => Self::Contessa, _ => unreachable!(), } } pub const fn name(self) -> &'static str { match self { Self::Duke => "Duke", Self::Assassin => "Assassin", Self::Ambassador => "Ambassador", Self::Captain => "Captain", Self::Contessa => "Contessa", } } fn image(self) -> &'static Path { match self { Self::Duke => Path::new("images/coup/DukeSmall.jpg"), Self::Assassin => Path::new("images/coup/AssassinSmall.jpg"), Self::Ambassador => Path::new("images/coup/AmbassadorSmall.jpg"), Self::Captain => Path::new("images/coup/CaptainSmall.jpg"), Self::Contessa => Path::new("images/coup/ContessaSmall.jpg"), } } }
use std::collections::HashSet; #[derive(Debug, PartialEq)] pub struct CustomSet<T> { set: Vec<T> } impl<T: std::fmt::Debug + std::clone::Clone + std::cmp::Ord> CustomSet<T> { pub fn new(_input: &[T]) -> Self { let mut input = _input.clone().to_vec(); input.sort(); input.dedup(); CustomSet { set: input } } pub fn contains(&self, _element: &T) -> bool { self.set.contains(_element) } pub fn add(&mut self, _element: T) { self.set.push(_element); self.set.sort(); self.set.dedup(); } pub fn is_subset(&self, _other: &Self) -> bool { if self.set.len() == 0 { true } else if _other.set.len() == 0 { false } else { match _other.set.windows(self.set.len()).position(|window| window.to_vec() == self.set) { Some(_x) => true, None => false } } } pub fn is_empty(&self) -> bool { self.set.is_empty() } pub fn is_disjoint(&self, _other: &Self) -> bool { println!("{:?} - {:?}", self.set, _other.set); if self.set.len() == 0 && _other.set.len() == 0 { true } else { self.intersection(_other).set.len() == 0 } } pub fn intersection(&self, _other: &Self) -> Self { let mut intersection_vec = Vec::new(); for _element in self.set.clone() { match _other.set.contains(&_element) { true => { intersection_vec.push(_element); } false => { } } } CustomSet::new(intersection_vec.as_slice()) } pub fn difference(&self, _other: &Self) -> Self { let mut difference_vec = Vec::new(); for _element in self.set.clone() { match _other.set.contains(&_element) { true => { } false => { difference_vec.push(_element); } } } CustomSet::new(difference_vec.as_slice()) } pub fn union(&self, _other: &Self) -> Self { let mut out = self.set.clone(); let mut _other_set = _other.set.clone(); out.append(&mut _other_set); CustomSet::new(out.as_slice()) } }
use pinetime_common::embedded_graphics::{ geometry::Size, image::ImageRaw, mono_font::{mapping::StrGlyphMapping, DecorationDimensions, MonoFont}, }; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub enum Icon { Plug, BatteryFull, BatteryEmpty, BatteryOneQuarter, BatteryHalf, BatteryThreeQuarter, } impl Icon { pub fn as_text(self) -> &'static str { use Icon::*; match self { Plug => "\u{F1E6}", BatteryFull => "\u{F240}", BatteryEmpty => "\u{F244}", BatteryOneQuarter => "\u{F243}", BatteryHalf => "\u{F242}", BatteryThreeQuarter => "\u{F241}", } } pub fn battery_icon_from_percent_remaining(percent_remaining: u8) -> Self { match percent_remaining { p if p > 87 => Icon::BatteryFull, p if p > 62 => Icon::BatteryThreeQuarter, p if p > 37 => Icon::BatteryHalf, p if p > 12 => Icon::BatteryOneQuarter, _ => Icon::BatteryEmpty, } } } const GLYPH_MAPPING: StrGlyphMapping = StrGlyphMapping::new("\u{F001}\u{F015}\u{F017}\u{F024}\u{F027}\u{F028}\u{F029}\u{F03A}\u{F048}\u{F04B}\u{F04C}\u{F04D}\u{F051}\u{F069}\u{F06E}\u{F095}\u{F129}\u{F185}\u{F1E6}\u{F1FC}\u{F201}\u{F21E}\u{F240}\u{F241}\u{F242}\u{F243}\u{F244}\u{F252}\u{F293}\u{F294}\u{F2F2}\u{F3DD}\u{F3FD}\u{F45D}\u{F54B}\u{F54B}\u{F560}\u{F569}\u{F59F}\u{F5A0}\u{F6A9}", '\u{F001}' as _); /// 27x21 pixel 20 point size monospace icons pub const FONT_AWESOME_ICONS_20_POINT: MonoFont = MonoFont { image: ImageRaw::new_binary( include_bytes!("../../res/fonts/font_awesome_icons_20.raw"), 16 * 27, ), glyph_mapping: &GLYPH_MAPPING, character_size: Size::new(27, 21), character_spacing: 0, baseline: 21, underline: DecorationDimensions::new(22, 1), strikethrough: DecorationDimensions::new(18, 1), }; #[derive(Debug)] pub struct Icons { pub p20: &'static MonoFont<'static>, } // dyn GlyphMapping + 'static)` cannot be shared between threads safely unsafe impl Sync for Icons {} unsafe impl Send for Icons {} impl Icons { pub const fn new() -> Self { Icons { p20: &FONT_AWESOME_ICONS_20_POINT, } } } impl Default for Icons { fn default() -> Self { Icons::new() } }
///// chapter 4 "structuring data and matching patterns" ///// program section: // fn main() { let thor = ("thor", true, 3500u32); let (name, _, power) = thor; println!("{} has {} points of power", name, power); } ///// output should be: /* */// end of output
use DocId; use docset::{DocSet, SkipResult}; use postings::{Postings, SegmentPostings}; use query::{Intersection, Scorer}; struct PostingsWithOffset { offset: u32, segment_postings: SegmentPostings, } impl PostingsWithOffset { pub fn new(segment_postings: SegmentPostings, offset: u32) -> PostingsWithOffset { PostingsWithOffset { offset, segment_postings, } } } impl Postings for PostingsWithOffset { fn term_freq(&self) -> u32 { self.segment_postings.term_freq() } fn positions(&self) -> &[u32] { self.segment_postings.positions() } } impl DocSet for PostingsWithOffset { fn advance(&mut self) -> bool { self.segment_postings.advance() } fn skip_next(&mut self, target: DocId) -> SkipResult { self.segment_postings.skip_next(target) } fn doc(&self) -> DocId { self.segment_postings.doc() } fn size_hint(&self) -> u32 { self.segment_postings.size_hint() } } pub struct PhraseScorer { intersection_docset: Intersection<PostingsWithOffset>, } impl PhraseScorer { pub fn new(term_postings: Vec<SegmentPostings>) -> PhraseScorer { let postings_with_offsets: Vec<_> = term_postings .into_iter() .enumerate() .map(|(offset, postings)| PostingsWithOffset::new(postings, offset as u32)) .collect(); PhraseScorer { intersection_docset: Intersection::from(postings_with_offsets), } } fn phrase_match(&self) -> bool { // TODO maybe we could avoid decoding positions lazily for all terms // when there is > 2 terms. // // For instance for the query "A B C", the position of "C" do not need // to be decoded if "A B" had no match. let docsets = self.intersection_docset.docsets(); let mut positions_arr: Vec<&[u32]> = vec![&[]; docsets.len()]; for docset in docsets { positions_arr[docset.offset as usize] = docset.positions(); } let num_postings = positions_arr.len() as u32; let mut ord = 1u32; let mut pos_candidate = positions_arr[0][0]; positions_arr[0] = &(positions_arr[0])[1..]; let mut count_matching = 1; #[cfg_attr(feature = "cargo-clippy", allow(never_loop))] 'outer: loop { let target = pos_candidate + ord; let positions = positions_arr[ord as usize]; for (i, pos_i) in positions.iter().cloned().enumerate() { if pos_i < target { continue; } if pos_i == target { count_matching += 1; if count_matching == num_postings { return true; } } else if pos_i > target { count_matching = 1; pos_candidate = positions[i] - ord; positions_arr[ord as usize] = &(positions_arr[ord as usize])[(i + 1)..]; } ord += 1; if ord == num_postings { ord = 0; } continue 'outer; } return false; } } } impl DocSet for PhraseScorer { fn advance(&mut self) -> bool { while self.intersection_docset.advance() { if self.phrase_match() { return true; } } false } fn skip_next(&mut self, target: DocId) -> SkipResult { if self.intersection_docset.skip_next(target) == SkipResult::End { return SkipResult::End; } if self.phrase_match() { if self.doc() == target { return SkipResult::Reached; } else { return SkipResult::OverStep; } } if self.advance() { SkipResult::OverStep } else { SkipResult::End } } fn doc(&self) -> DocId { self.intersection_docset.doc() } fn size_hint(&self) -> u32 { self.intersection_docset.size_hint() } } impl Scorer for PhraseScorer { fn score(&mut self) -> f32 { 1f32 } }
use crate::headers::{Header, HeaderName, HeaderValue, Headers, SOURCE_MAP}; use crate::{bail_status as bail, Status, Url}; use std::convert::TryInto; /// Links to a file that maps transformed source to the original source. /// /// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/SourceMap) /// /// # Specifications /// /// - [Source Map Revision 3](https://sourcemaps.info/spec.html) /// /// # Examples /// /// ``` /// # fn main() -> http_types::Result<()> { /// # /// use http_types::{Response, Url}; /// use http_types::other::SourceMap; /// /// let source_map = SourceMap::new(Url::parse("https://example.net/")?); /// /// let mut res = Response::new(200); /// res.insert_header(&source_map, &source_map); /// /// let base_url = Url::parse("https://example.net/")?; /// let source_map = SourceMap::from_headers(base_url, res)?.unwrap(); /// assert_eq!(source_map.location(), &Url::parse("https://example.net/")?); /// # /// # Ok(()) } /// ``` #[derive(Debug)] pub struct SourceMap { location: Url, } impl SourceMap { /// Create a new instance of `SourceMap` header. pub fn new(location: Url) -> Self { Self { location } } /// Create a new instance from headers. pub fn from_headers<U>(base_url: U, headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> where U: TryInto<Url>, U::Error: std::fmt::Debug, { let headers = match headers.as_ref().get(SOURCE_MAP) { Some(headers) => headers, None => return Ok(None), }; // If we successfully parsed the header then there's always at least one // entry. We want the last entry. let header_value = headers.iter().last().unwrap(); let url = match Url::parse(header_value.as_str()) { Ok(url) => url, Err(_) => match base_url.try_into() { Ok(base_url) => base_url.join(header_value.as_str().trim()).status(500)?, Err(_) => bail!(500, "Invalid base url provided"), }, }; Ok(Some(Self { location: url })) } /// Get the url. pub fn location(&self) -> &Url { &self.location } /// Set the url. pub fn set_location<U>(&mut self, location: U) -> Result<(), U::Error> where U: TryInto<Url>, U::Error: std::fmt::Debug, { self.location = location.try_into()?; Ok(()) } } impl Header for SourceMap { fn header_name(&self) -> HeaderName { SOURCE_MAP } fn header_value(&self) -> HeaderValue { let output = self.location.to_string(); // SAFETY: the internal string is validated to be ASCII. unsafe { HeaderValue::from_bytes_unchecked(output.into()) } } } #[cfg(test)] mod test { use super::*; use crate::headers::Headers; #[test] fn smoke() -> crate::Result<()> { let source_map = SourceMap::new(Url::parse("https://example.net/test.json")?); let mut headers = Headers::new(); source_map.apply_header(&mut headers); let base_url = Url::parse("https://example.net/")?; let source_map = SourceMap::from_headers(base_url, headers)?.unwrap(); assert_eq!( source_map.location(), &Url::parse("https://example.net/test.json")? ); Ok(()) } #[test] fn bad_request_on_parse_error() { let mut headers = Headers::new(); headers.insert(SOURCE_MAP, "htt://<nori ate the tag. yum.>"); let err = SourceMap::from_headers(Url::parse("https://example.net").unwrap(), headers) .unwrap_err(); assert_eq!(err.status(), 500); } #[test] fn fallback_works() -> crate::Result<()> { let mut headers = Headers::new(); headers.insert(SOURCE_MAP, "/test.json"); let base_url = Url::parse("https://fallback.net/")?; let source_map = SourceMap::from_headers(base_url, headers)?.unwrap(); assert_eq!( source_map.location(), &Url::parse("https://fallback.net/test.json")? ); let mut headers = Headers::new(); headers.insert(SOURCE_MAP, "https://example.com/test.json"); let base_url = Url::parse("https://fallback.net/")?; let source_map = SourceMap::from_headers(base_url, headers)?.unwrap(); assert_eq!( source_map.location(), &Url::parse("https://example.com/test.json")? ); Ok(()) } }
use std::fmt; use std::collections::HashMap; use metainfo::Metainfo; #[derive(Debug)] pub struct Params { params: HashMap<&'static str, String>, } impl Params { fn escape(buffer: &Vec<u8>) -> String { let mut result = String::with_capacity(3 * buffer.len()); for byte in buffer { result += "%"; result += &format!("{:02X}", byte); } result } pub fn from(metainfo: &Metainfo, id: &String) -> Self { let length = metainfo.info.length.unwrap_or_default().to_string(); let mut params = HashMap::new(); params.insert("left", length); params.insert("info_hash", Self::escape(&metainfo.info_hash())); params.insert("downloaded", String::from("0")); params.insert("uploaded", String::from("0")); params.insert("event", String::from("started")); params.insert("peer_id", id.clone()); params.insert("compact", String::from("1")); params.insert("port", String::from("6886")); return Params { params }; } fn query(&self) -> String { let param_strings: Vec<String> = self.params .iter() .map(|(k, v)| format!("{}={}", k, v)) .collect(); param_strings.join("&") } } impl fmt::Display for Params { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "{}", &self.query()) } }
use cocoa::base::id; use std::mem; use std::ops::Deref; use sys::MTLRenderPassStencilAttachmentDescriptor; use RenderPassAttachmentDescriptor; pub struct RenderPassStencilAttachmentDescriptor(id); impl RenderPassStencilAttachmentDescriptor { pub fn clear_stencil(&self) -> u32 { unsafe { self.0.clearStencil() } } pub fn set_clear_stencil(&mut self, stencil: u32) { unsafe { self.0.setClearStencil(stencil) } } } impl Deref for RenderPassStencilAttachmentDescriptor { type Target = RenderPassAttachmentDescriptor; fn deref(&self) -> &Self::Target { unsafe { mem::transmute(self) } } } impl_from_into_raw!(RenderPassStencilAttachmentDescriptor, of class "MTLRenderPassStencilAttachmentDescriptor");
fn main() { proconio::input! { m: usize, h: usize, } println!("{}", if h % m == 0 {"Yes"} else {"No"}); }
fn main(){ let mut a = Vec::new(); a.push(1); a.push(1); a.push(2); print!("{} {} {}", a[0], a[1], a[2]); }
use crate::appkit::NSImage; #[derive(Clone, Copy, Debug)] pub enum Image<'i> { File(&'i str), Url(&'i str), } impl Into<NSImage> for Image<'_> { fn into(self) -> NSImage { let image = NSImage::alloc(); match self { Image::File(file) => image.with_contents(file), Image::Url(url) => image.with_url(url), } } }
use glutin::{PossiblyCurrent, event_loop::ControlFlow}; use crate::tracked_window::{TrackedWindow, TrackedWindowControl}; use crate::MultiWindow; use egui_glow::EguiGlow; pub mod popup_window; pub mod root; #[enum_dispatch(TrackedWindow)] pub enum MyWindows { Root(root::RootWindow), Popup(popup_window::PopupWindow) }
use util::*; fn main() -> Result<(), Box<dyn std::error::Error>> { let timer = Timer::new(); let input = input::lines::<String>(&std::env::args().nth(1).unwrap()); let start: usize = input[0].parse().unwrap(); let departures: Vec<usize> = input[1] .split(',') .filter_map(|n| n.parse::<usize>().ok()) .collect(); let earliest: Vec<usize> = departures .iter() .map(|d| { let mut n = *d; while n < start { n += d } n }) .collect(); let mut index = 0; let mut min = usize::MAX; for (i, d) in earliest.iter().enumerate() { if *d < min { index = i; min = *d; } } timer.print(); println!("{}", (earliest[index] - start) * departures[index]); Ok(()) }