content
stringlengths
12
12.8k
id
int64
0
359
fn test_expression() { // 6.1 // expression // 5 * (fahr-32) / 9; /* statement for (; begin != end; ++begin) { if (*begin == target) break; } */ /* pixels[r * bounds.0 + c] = match escapes(Complex { re: point.0, im: point.1 }, 255) { None => 0, Some(count) => 255 - count as u8 }; */ /* let status = if cpu.temperature <= MAX_TEMP { HttpStatus::Ok } else { HttpStatus::ServerError }; */ /* println!("Inside the vat, you see {}.", match vat.contents { Some(brain) => brain.desc(), None => "nothing of interest" }); */ // 6.2 /* let display_name = match post.author() { Some(author) => author.name(), None => { let network_info = post.get_network_metadata()?; let ip = network_info.client_address(); ip.to_string() } }; */ /* let msg = { // let-declaration: semicolon is always required let dandelion_control = puffball.open(); // expression + semicolon: method is called, return value dropped dandelion_control.release_all_seeds(launch_codes); // expression with no semicolon: method is called, // return value stored in `msg` dandelion_control.get_status() } */ // 6.3 /* loop { work(); play(); ; // <-- empty statement } */ /* * let name: type = expr; */ /* let name; if user.has_nickname() { name = user.nickname(); } else { name = generate_unique_name(); user.register(&name); } */ /* use std::io; use std::cmp::Ordering; fn show_files() -> io::Result<()> { let mut v = vec![]; ... fn cmp_by_timestamp_then_name(a: &FileInfo, b: &FileInfo) -> Ordering { a.timestamp.cmp(&b.timestamp) .reverse() .then(a.path.cmp(&b.path)) } v.sort_by(cmp_by_timestamp_then_name); } */ // 6.4 /* if condition1 { block1 } else if condition2 { block2 } else { block_n } */ /* match value { pattern => expr, ... } */ let code = 2; match code { 0 => println!("OK"), 1 => println!("Wires Tangled"), 2 => println!("User Asleep"), _ => println!("Unrecognized Error {}", code), } /* match params.get("name") { Some(name) => println!("Hello, {}!", name), None => println!("Greetings, stranger.") } */ /* let score = match card.rank { Jack => 10, Queen = > 10, Ace = 11 }; // error: nonexhaustive patterns */ /* let suggested_pet = if with_wings { Pet::Buzzard } else { Pet::Hyena }; //ok let favorite_number = if user.is_hobbit() { "eleventy-one" } else { 9 }; //error let best_sports_team = if is_hockey_season() { "Predators" }; // error */ /* let suggested_per = match favotites.elements { Fire => Pet::RedPanda, Air => Pet::Buffalo, Water => Pet::Orca, _ => None // error: incompatible types } */ // 6.4.1 /* if let pattern = expr { block1 } else { block2 } match expr { pattern => { block1 } _ => { block2 } */ /* if let Some(cookie) = request.session_cookie { return restore_session(cookie); } if let Err(err) = present_cheesy_anti_robot_task() { log_robot_attempt(err); politely_accuse_user_of_being_a_robot(); } else { session.mark_as_human(); } */ // 6.5 loop /* while condition { block } while let pattern = expr { block } loop { block } for pattern in collection { block } */ for i in 0..20 { println!("{}", i); } /* let strings: Vec<String> = error_messages(); for s in strings { // each String is moved into s here println!("{}", s); } // ...and dropped here println("{} error(s)", strings.len()); // error: use of moved value */ /* for rs in &strings { println!("String {:?} is at address {:p}.", *rs, rs); // ok } */ /* for rs in &mut strings { // tye type of rs is &mut String rs.push('\n'); // add a newline to each string } */ /* for line in input_lines { let trimmed = trim_comments_and_whitespac(line); if trimmed.is_empty() { continue; } ... } */ /* 'seach: for room in apartment { for stop in room.hiding_spots() { if spot.contains(keys) { println!("Your keys are {} in the {}.", spot, room); break 'search; } } } */ // 6.6 return fn f() { // return type omitted: default to () return; // return value comitted: default to () } assert_eq!(f(), ()); /* let output = File::create(filename)?; let output = match File::create(filename) { Ok(f) => f, Err(err) => return Err(err) }; */ // 6.7 /* fn wait_for_process(process: &mut Process) -> i32 { while true { if process.wait() { return process.exit_code(); } } } // error: not all control paths return a value */ /* fn serve_forever(socket: ServerSocket, handler: ServerHandler) -> ! { socket.listen(); loop { let s = socket.accept(); handler.handle(s); } } */ // 6.8 /* let x = gcd(1302, 462); // function call let room = player.location(); // method call let mut numbers = Vec::new(); // static method call Iron::new(router).http("localhost:3000").unwrap(); return Vec<i32>::with_capacity(1000); // error: something about chanined comparisons let ramp = (0 .. n).collect<Vec<i32>>(); // same error return Vec::<i32>::with_capacity(1000); // ok, using ::< let ramp = (0 .. n).collect::<Vec<i32>>(); // ok, using ::< return Vec::with_capacity(10); // ok, if the fn return type is Vec<i32> let ramp: Vec<i32> = (0 .. n).collect(); // ok, variable's type is given */ // 6.9 /* game.black_pawns // struct field coords.1 // tuple element pieces[i] // array element, they are lvalue fn quicksort<T: Ord>(slice: &mut [T]) { if slice.len() <= 1 { return; // Nothing to sort. } // Partition the slice into two parts, front and back. let pivot_index = partition(slice); // Recursively sort the front half of `slice`. quicksort(&mut slice[.. pivot_index]); // And the back half. quicksort(&mut slice[pivot_index + 1 ..]); } */ // 6.10 /* let padovan: Vec<u64> = compute_padovan_sequence(n); for elem in &padovan { draw_triangle(turtle, *elem); } */ // 6.11 /* println!("{}", -100); // -100 println!("{}", -100u32); // error: can't apply unary '-' to type 'u32' println!("{}", +100); // error: expected expression, found '+' let x = 1234.567 % 10.0; // approximetely 4.567 let hi: u8 = 0xe0; let lo = !hi; // 0x1f */ // 6.12 /* total += item.price; // rust does not have increment operator and decrement operator. */ // 6.13 /* let x = 17; // x is type i32 let index = x as usize; // convert to usize */ // 6.14 /* let is_even = |x| x % 2 == 0; let is_evan = |x: u64| -> bool x % 2 == 0; // error */ let is_even = |x: u64| -> bool { x % 2 == 0 }; // ok assert_eq!(is_even(14), true); }
300
fn a_table_should_read_what_was_put() { let mut table = HashMapOfTreeMap::new(); table.write(0, &[Row { k: 0, v: 1 }]); let mut vs = [Value::default(); 1]; table.read (1, &[0], &mut vs); assert_eq!(vs, [Value { v: 1, t: 1 }]); }
301
pub fn test_rvc_pageend() { // The last instruction of a executable memory page is an RVC instruction. let buffer = fs::read("tests/programs/rvc_pageend").unwrap().into(); let core_machine = DefaultCoreMachine::<u64, SparseMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value()); let mut machine = DefaultMachineBuilder::new(core_machine).build(); machine .load_program(&buffer, &vec!["rvc_end".into()]) .unwrap(); let anchor_pc: u64 = 69630; // Ensure that anchor_pc is in the end of the page assert_eq!(anchor_pc as usize % RISCV_PAGESIZE, RISCV_PAGESIZE - 2); let memory = machine.memory_mut(); // Ensure that the data segment is located at anchor_pc + 2 let data0 = memory.load16(&(anchor_pc + 2)).unwrap().to_u32(); assert_eq!(data0, 4); let data1 = memory.load16(&(anchor_pc + 6)).unwrap().to_u32(); assert_eq!(data1, 2); // Ensure that the anchor instruction is "c.jr a0" let anchor_inst = memory.load16(&anchor_pc).unwrap().to_u16(); assert_eq!(anchor_inst, 0x8502); let result = machine.run(); assert!(result.is_ok()); assert_eq!(result.unwrap(), 0); }
302
fn main() { // Variables can be type annotated. let i: i32 = 10; println!("Hello, world!, {}", i); }
303
async fn main() -> std::io::Result<()> { // Set keep-alive to 75 seconds let _one = HttpServer::new(app).keep_alive(Duration::from_secs(75)); // Use OS's keep-alive (usually quite long) let _two = HttpServer::new(app).keep_alive(KeepAlive::Os); // Disable keep-alive let _three = HttpServer::new(app).keep_alive(None); Ok(()) }
304
fn char_test() { assert_eq!('*'.is_alphabetic(), false); assert_eq!('β'.is_alphabetic(), true); assert_eq!('8'.to_digit(10), Some(8)); assert_eq!('\u{CA0}'.len_utf8(), 3); assert_eq!(std::char::from_digit(2, 10), Some('2')); }
305
pub fn channel_take_raw(target: CAddr) -> u64 { let result = channel_take_nonpayload(target); match result { ChannelMessage::Raw(v) => return v, _ => panic!(), }; }
306
async fn retrieve_pairs() { let exchange = init().await; let pairs = exchange.refresh_market_info().await.unwrap(); println!("{:?}", pairs); }
307
fn hard_fault(ef: &ExceptionFrame) -> ! { panic!("Hardfault... : {:#?}", ef); }
308
fn main() { let num = input("Ingrese un número: ") .unwrap() .parse::<i32>() .expect("Expected a number"); if num % 2 == 0 { println!("`{}` es un número par.", num); } else { println!("`{}` es un número impar", num); } }
309
fn main() { // Resolve Directories let root = env::current_dir() .unwrap() .join("..") .canonicalize() .unwrap(); let i_path = root.join("data/input").canonicalize().unwrap(); let o_path = root.join("data/rs").canonicalize().unwrap(); // File Names let mut names = fs::read_dir(i_path) .unwrap() .map(|res| res.map(|e| e.path())) .collect::<Result<Vec<_>, io::Error>>() .unwrap(); names.sort(); // Read Files for name in names { // File Content let read = fs::read_to_string(name.clone()).unwrap(); // Parse and Sort Numbers let mut numbers: Vec<u64> = read.lines().map(|s| s.parse::<u64>().unwrap()).collect(); numbers.sort(); // Stringify Numbers let data: Vec<String> = numbers.iter().map(|n| format!("{:0>8}", n)).collect(); // Create File fs::write(o_path.join(name.file_name().unwrap()), data.join("\n")).unwrap(); // Sum Numbers let sum: u64 = numbers.iter().sum(); println!("{}", sum); } }
310
async fn order_shoes(mut req: Request<()>) -> tide::Result { let Animal { name, legs } = req.body_json().await?; Ok(format!("Hello, {} Order for {} shoes", name, legs).into()) }
311
fn get_default_database_paths() -> Vec<PathBuf> { get_platform_dependent_data_dirs() .into_iter() .map(|dir| dir.join("grafen").join(DEFAULT_DBNAME)) .collect() }
312
fn into_rdf(body: &[u8], content_type: &str) -> Result<Graph, Berr> { fn parse<P>(p: P) -> Result<Graph, Berr> where P: TriplesParser, <P as TriplesParser>::Error: 'static, { p.into_iter(|t| -> Result<_, Berr> { Ok(triple(t)?) }) .collect::<Result<Vec<om::Triple>, Berr>>()? .into_iter() .pipe(Graph::new) .pipe(Ok) } match content_type { "text/turtle; charset=utf-8" => parse(TurtleParser::new(Cursor::new(body), None)), _ => Err("unknown content-type".into()), } }
313
fn main() -> ! { let p = stm32::Peripherals::take().unwrap(); let gpio_a = p.GPIOA.split(); let btn_a = gpio_a.pa4.into_pull_up_input(); let btn_b = gpio_a.pa10.into_pull_up_input(); let gpio_b = p.GPIOB.split(); let gpio_c = p.GPIOC.split(); let mut r = gpio_b.pb4.into_push_pull_output(); let mut g = gpio_b.pb3.into_push_pull_output(); let mut b = gpio_c.pc7.into_push_pull_output(); let rcc = p.RCC.constrain(); let clocks = rcc.cfgr.freeze(); let i2c = stm32f4xx_hal::i2c::I2c::i2c1( p.I2C1, ( gpio_b.pb8.into_alternate_af4_open_drain(), gpio_b.pb9.into_alternate_af4_open_drain(), ), stm32f4xx_hal::time::KiloHertz(400).into(), clocks, ); let interface = I2CDIBuilder::new().init(i2c); let mut disp: Screen = ssd1306::Builder::new().connect(interface).into(); disp.init().unwrap(); disp.flush().unwrap(); let mut i = 0u8; set_led(i, &mut r, &mut g, &mut b); set_screen(i, &mut disp); loop { asm::delay(2_000_000); let a_pressed = btn_a.is_high().unwrap(); let b_pressed = btn_b.is_high().unwrap(); if a_pressed == b_pressed { continue; } if btn_a.is_high().unwrap() { i += 1; } if btn_b.is_high().unwrap() { if i == 0 { i = 6; } else { i -= 1; } } if i > 6 { i = 0; } set_led(i, &mut r, &mut g, &mut b); set_screen(i, &mut disp); } }
314
fn assert_memory_store_empty_bytes<M: Memory>(memory: &mut M) { assert!(memory.store_byte(0, 0, 42).is_ok()); assert!(memory.store_bytes(0, &[]).is_ok()); }
315
fn test_empty_blob ( ) - > Result < ( ) > { let db = checked_memory_handle ( ) ? ; let empty = vec ! [ ] ; db . execute ( " INSERT INTO foo ( b ) VALUES ( ? 1 ) " [ & empty ] ) ? ; let v : Vec < u8 > = db . one_column ( " SELECT b FROM foo " ) ? ; assert_eq ! ( v empty ) ; Ok ( ( ) ) }
316
fn assert_memory_load_bytes_all<R: Rng>( rng: &mut R, max_memory: usize, buf_size: usize, addr: u64, ) { assert_memory_load_bytes( rng, &mut SparseMemory::<u64>::new_with_memory(max_memory), buf_size, addr, ); assert_memory_load_bytes( rng, &mut FlatMemory::<u64>::new_with_memory(max_memory), buf_size, addr, ); assert_memory_load_bytes( rng, &mut WXorXMemory::new(FlatMemory::<u64>::new_with_memory(max_memory)), buf_size, addr, ); #[cfg(has_asm)] assert_memory_load_bytes( rng, &mut AsmCoreMachine::new(ISA_IMC, VERSION0, 200_000), buf_size, addr, ); }
317
fn read_dir<P: AsRef<Path>>(path: P, recursive: bool) -> io::Result<Vec<DirEntry>> { let path = path.as_ref(); let mut entries = Vec::new(); for entry in fs::read_dir(path)? { let entry = entry?; let path = entry.path().to_str().unwrap().to_string(); let children = if recursive && entry.file_type()?.is_dir() { Some(read_dir(&path, true)?) } else { None }; entries.push(DirEntry { path, children }); } Ok(entries) }
318
async fn order_book() { let exchange = init().await; let req = OrderBookRequest { market_pair: "eth_btc".to_string(), }; let resp = exchange.order_book(&req).await.unwrap(); println!("{:?}", resp); }
319
fn parse_instruction(line: &str) -> Instruction { let pieces: Vec<&str> = line.split_whitespace().collect(); let register = String::from(pieces[0]); let increase = match pieces[1] { "inc" => true, "dec" => false, _ => panic!("Expected 'inc' or 'dec'."), }; let value = pieces[2].parse::<i32>().expect("Could not parse instruction value as i32."); let condition_register = String::from(pieces[4]); let condition_operator = match pieces[5] { "<" => Operator::LessThan, "<=" => Operator::LessThanOrEqual, ">" => Operator::GreaterThan, ">=" => Operator::GreaterThanOrEqual, "==" => Operator::Equal, "!=" => Operator::NotEqual, _ => panic!("Unexpected condition operator."), }; let condition_value = pieces[6].parse::<i32>().expect("Could not parse condition value as i32."); Instruction { register, increase, value, condition: Condition { register: condition_register, operator: condition_operator, value: condition_value, }, } }
320
fn curiosity() -> Curiosity { Curiosity::create( [ "SELECT DISTINCT ?s WHERE { GRAPH ?g { ?s ?p ?o } }", "SELECT DISTINCT ?p WHERE { GRAPH ?g { ?s ?p ?o } }", "SELECT DISTINCT ?o WHERE { GRAPH ?g { ?s ?p ?o } }", "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }", ] .iter() .map(|a| a.parse().unwrap()) .collect(), ) .unwrap() }
321
pub async fn get_semaphored_connection<'a>() -> SemaphoredDbConnection<'a> { let _semaphore_permit = semaphore().acquire().await.unwrap(); let connection = establish_connection(); SemaphoredDbConnection { _semaphore_permit, connection, } }
322
fn die(err: impl Error) -> ! { println!("{}", err); std::process::exit(1); }
323
fn find_common_id() -> Option<String> { let input = fs::File::open("input.txt") .expect("Something went wrong reading the file"); let reader = io::BufReader::new(input); let mut box_ids: Vec<String> = reader.lines().map(|l| l.unwrap()).collect(); box_ids.sort(); for i in 0..box_ids.len() { let mut diff = 0; if i != box_ids.len() - 1 { for (a, b) in box_ids[i].chars().zip(box_ids[i+1].chars()) { if a != b { diff += 1; } } if diff == 1 { return Some(get_common_chars(&box_ids[i], &box_ids[i+1])); } } } None }
324
fn help() { cargo_fuzz().arg("help").assert().success(); }
325
pub fn solve2(input: &str) -> Option<Box<usize>> { let sum_of_counts = input .trim_end() .split("\n\n") .map(|group| { let answers_per_person = group .split_ascii_whitespace() .map(|person| person.chars().collect::<HashSet<_>>()) .collect::<Vec<_>>(); answers_per_person .iter() .fold(answers_per_person[0].clone(), |all_yes, persons_answers| { all_yes.intersection(persons_answers).cloned().collect() }) .len() }) .sum(); Some(Box::new(sum_of_counts)) }
326
fn a_table_should_read_0_for_any_key() { let mut table = HashMapOfTreeMap::new(); let mut vs = [Value::default(); 1]; table.read (0, &[0], &mut vs); match vs { [Value { v: 0, t: 0}] => (), _ => assert!(false) } }
327
pub fn acrn_create_dir(path: &str, recursive: bool) -> Result<(), String> { if recursive { fs::create_dir_all(path).map_err(|e| e.to_string()) } else { fs::create_dir(path).map_err(|e| e.to_string()) } }
328
pub fn quick_sort<T: PartialOrd + Debug>(v: &mut [T]) { if v.len() <= 1 { return; } let p = pivot(v); println!("{:?}", v); let (a, b) = v.split_at_mut(p); quick_sort(a); quick_sort(&mut b[1..]); }
329
fn main() { println!("Run via `cargo run-wasm --example visualiser_for_wasm`"); }
330
fn main() -> Result<(), std::io::Error> { let mut token = std::ptr::null_mut(); let r = unsafe {OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut token) }; if r == 0 { return Err(std::io::Error::last_os_error()); } set_privilege(token, SE_RESTORE_NAME)?; set_privilege(token, SE_BACKUP_NAME)?; let hive_key = Hive::LocalMachine.load("example", r"C:\Users\Default\NTUSER.DAT", Security::Read | Security::Write).unwrap(); let keys: Vec<_> = hive_key .keys() .map(|k| k.unwrap().to_string()) .collect(); println!("{:?}", keys); Ok(()) }
331
fn process_instructions(instructions: &Vec<Instruction>) -> (HashMap<&str, i32>, i32) { let mut registers: HashMap<&str, i32> = HashMap::new(); let mut max = 0; for instruction in instructions { let current = *registers.entry(&instruction.condition.register).or_insert(0); let condition_satisfied = match instruction.condition.operator { Operator::LessThan => current < instruction.condition.value, Operator::LessThanOrEqual => current <= instruction.condition.value, Operator::GreaterThan => current > instruction.condition.value, Operator::GreaterThanOrEqual => current >= instruction.condition.value, Operator::Equal => current == instruction.condition.value, Operator::NotEqual => current != instruction.condition.value, }; if !condition_satisfied { continue; } let delta = match instruction.increase { true => instruction.value, false => -1 * instruction.value, }; let entry = registers.entry(&instruction.register).or_insert(0); *entry += delta; let new_value = *entry; if new_value > max { max = new_value; } } (registers, max) }
332
pub fn map_raw_page_free(vaddr: usize, untyped: CAddr, toplevel_table: CAddr, page: CAddr) { system_call(SystemCall::MapRawPageFree { untyped: untyped, toplevel_table: toplevel_table, request: (vaddr, page), }); }
333
fn run_with_coverage() { let target = "with_coverage"; let project = project("run_with_coverage") .with_fuzz() .fuzz_target( target, r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { println!("{:?}", data); }); "#, ) .build(); project .cargo_fuzz() .arg("run") .arg(target) .arg("--") .arg("-runs=100") .assert() .stderr(predicate::str::contains("Done 100 runs")) .success(); project .cargo_fuzz() .arg("coverage") .arg(target) .assert() .stderr(predicate::str::contains("Coverage data merged and saved")) .success(); let profdata_file = project.fuzz_coverage_dir(target).join("coverage.profdata"); assert!(profdata_file.exists(), "Coverage data file not generated"); }
334
fn test_mismatched_types ( ) - > Result < ( ) > { fn is_invalid_column_type ( err : Error ) - > bool { matches ! ( err Error : : InvalidColumnType ( . . ) ) } let db = checked_memory_handle ( ) ? ; db . execute ( " INSERT INTO foo ( b t i f ) VALUES ( X ' 0102 ' ' text ' 1 1 . 5 ) " [ ] ) ? ; let mut stmt = db . prepare ( " SELECT b t i f n FROM foo " ) ? ; let mut rows = stmt . query ( [ ] ) ? ; let row = rows . next ( ) ? . unwrap ( ) ; assert_eq ! ( vec ! [ 1 2 ] row . get : : < _ Vec < u8 > > ( 0 ) ? ) ; assert_eq ! ( " text " row . get : : < _ String > ( 1 ) ? ) ; assert_eq ! ( 1 row . get : : < _ c_int > ( 2 ) ? ) ; assert ! ( ( 1 . 5 - row . get : : < _ c_double > ( 3 ) ? ) . abs ( ) < f64 : : EPSILON ) ; assert_eq ! ( row . get : : < _ Option < c_int > > ( 4 ) ? None ) ; assert_eq ! ( row . get : : < _ Option < c_double > > ( 4 ) ? None ) ; assert_eq ! ( row . get : : < _ Option < String > > ( 4 ) ? None ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_int > ( 0 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_int > ( 0 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ i64 > ( 0 ) . err ( ) . unwrap ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_double > ( 0 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ String > ( 0 ) . unwrap_err ( ) ) ) ; # [ cfg ( feature = " time " ) ] assert ! ( is_invalid_column_type ( row . get : : < _ time : : OffsetDateTime > ( 0 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Option < c_int > > ( 0 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_int > ( 1 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ i64 > ( 1 ) . err ( ) . unwrap ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_double > ( 1 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Vec < u8 > > ( 1 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Option < c_int > > ( 1 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ String > ( 2 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Vec < u8 > > ( 2 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Option < String > > ( 2 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_int > ( 3 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ i64 > ( 3 ) . err ( ) . unwrap ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ String > ( 3 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Vec < u8 > > ( 3 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Option < c_int > > ( 3 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_int > ( 4 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ i64 > ( 4 ) . err ( ) . unwrap ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ c_double > ( 4 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ String > ( 4 ) . unwrap_err ( ) ) ) ; assert ! ( is_invalid_column_type ( row . get : : < _ Vec < u8 > > ( 4 ) . unwrap_err ( ) ) ) ; # [ cfg ( feature = " time " ) ] assert ! ( is_invalid_column_type ( row . get : : < _ time : : OffsetDateTime > ( 4 ) . unwrap_err ( ) ) ) ; Ok ( ( ) ) }
335
fn pool() -> &'static Pool<ConnectionManager<PgConnection>> { POOL.get_or_init(|| { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let manager = ConnectionManager::<PgConnection>::new(database_url); Pool::builder() .max_size(*pool_connection_number() as u32) .build(manager) .unwrap() }) }
336
fn build_author_map( repo: &Repository, reviewers: &Reviewers, mailmap: &Mailmap, from: &str, to: &str, ) -> Result<AuthorMap, Box<dyn std::error::Error>> { match build_author_map_(repo, reviewers, mailmap, from, to) { Ok(o) => Ok(o), Err(err) => Err(ErrorContext( format!( "build_author_map(repo={}, from={:?}, to={:?})", repo.path().display(), from, to ), err, ))?, } }
337
fn init_servo(robot: &mut Robot) { let servos = ServoManager::new(); let m2 = servos[0xFE].reboot(); for b in m2 { block!(robot.servo_tx.write(b)).unwrap(); } for _ in 0..5 { robot.delay.delay_ms(70 as u32); } let m2 = servos[0xFE].ram_write(WritableRamAddr::AckPolicy(2)); for b in m2 { block!(robot.servo_tx.write(b)).unwrap(); } let m1 = servos[0xFE].enable_torque(); for b in m1 { block!(robot.servo_tx.write(b)).unwrap(); } }
338
fn main() { input! { n:usize, } let n = n * 108 / 100; if n < 206 { println!("Yay!"); } else if n == 206 { println!("so-so"); } else { println!(":("); } }
339
fn main() { env_logger::init().unwrap_or_else( |err| panic!("unable to initiate env logger: {}", err) ); match core::start() { Ok(()) => info!("game exiting"), Err(err) => error!("core start error: {}", err), } }
340
extern "C" fn gatt_svr_chr_access_device_info( _conn_handle: u16, _attr_handle: u16, ctxt: *mut ble_gatt_access_ctxt, _arg: *mut ::core::ffi::c_void, ) -> i32 { let uuid: u16 = unsafe { ble_uuid_u16((*(*ctxt).__bindgen_anon_1.chr).uuid) }; if uuid == GATT_MODEL_NUMBER_UUID { let rc: i32 = unsafe { os_mbuf_append( (*ctxt).om, MODEL_NUM.as_ptr() as *const c_void, MODEL_NUM.len() as u16, ) }; return if rc == 0 { 0 } else { BLE_ATT_ERR_INSUFFICIENT_RES as i32 }; } if uuid == GATT_MANUFACTURER_NAME_UUID { let rc: i32 = unsafe { os_mbuf_append( (*ctxt).om, MANUF_NAME.as_ptr() as *const c_void, MANUF_NAME.len() as u16, ) }; return if rc == 0 { 0 } else { BLE_ATT_ERR_INSUFFICIENT_RES as i32 }; } return BLE_ATT_ERR_UNLIKELY as i32; }
341
fn test_blob ( ) - > Result < ( ) > { let db = checked_memory_handle ( ) ? ; let v1234 = vec ! [ 1u8 2 3 4 ] ; db . execute ( " INSERT INTO foo ( b ) VALUES ( ? 1 ) " [ & v1234 ] ) ? ; let v : Vec < u8 > = db . one_column ( " SELECT b FROM foo " ) ? ; assert_eq ! ( v v1234 ) ; Ok ( ( ) ) }
342
pub fn current_time() -> DateTime<Utc> { Utc::now().round_subsecs(0) }
343
pub fn test_wxorx_crash_64() { let buffer = fs::read("tests/programs/wxorx_crash_64").unwrap().into(); let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["wxorx_crash_64".into()]); assert_eq!(result.err(), Some(Error::MemOutOfBound)); }
344
fn santa(instruction: &String) -> i32 { // if '(' up else if ')' down let mut floor: i32 = 0; for paren in instruction.chars() { println!("{}", paren); match paren { '(' => floor += 1, ')' => floor -= 1, _ => panic!(), } } floor }
345
fn copy_test() { { /* struct Label { number: u32, } fn print(l: Label) { println!("STAMP: {}", l.number); } let l = Label { number: 3 }; print(l); println!("My label number is: {}", l.number); // error */ #[derive(Copy, Clone)] struct Label { number: u32, } fn print(l: Label) { println!("STAMP: {}", l.number); } let l = Label { number: 3 }; print(l); println!("My label number is: {}", l.number); /* #[derive(Copy, Clone)] struct StringLabel { name: String, } */ } }
346
fn build_one() { let project = project("build_one").with_fuzz().build(); // Create some targets. project .cargo_fuzz() .arg("add") .arg("build_one_a") .assert() .success(); project .cargo_fuzz() .arg("add") .arg("build_one_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_one_a"); let b_bin = build_dir.join("build_one_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 we can build one and not the other. project .cargo_fuzz() .arg("build") .arg("build_one_a") .assert() .success(); assert!(a_bin.is_file()); assert!(!b_bin.is_file()); }
347
pub fn debug_format(input: String) -> String { if input.len() <= 20 { return input; } input .chars() .take(8) .chain("...".chars()) .chain(input.chars().skip(input.len() - 8)) .collect() }
348
pub fn main() { let opts = TileOptions { parent_x: 108, parent_y: 54, width: 10, height: 10, max_value: 10.0, min_value: 0.0, mean: 5.0, std_dev: 2.0, }; let t = NormalDistTile::new(opts); println!(" {:?}", t.subtiles); println!("{}", t.get(0, 0)); println!("{}", t.get(1, 0)); println!("{}", t.get(2, 0)); println!("{}", t.get(3, 0)); println!("{}", t.get(0, 5)); println!("{}", t.get(1, 5)); println!("{}", t.get(2, 5)); println!("{}", t.get(3, 5)); println!("{}", t.get((t.width - 4) as u8, (t.height - 1) as u8)); println!("{}", t.get((t.width - 3) as u8, (t.height - 1) as u8)); println!("{}", t.get((t.width - 2) as u8, (t.height - 1) as u8)); println!("{}", t.get((t.width - 1) as u8, (t.height - 1) as u8)); }
349
pub fn parse(buf_reader: &mut dyn BufRead, strict: bool) -> Result<Cue, CueError> { let verbose = env::var_os("RCUE_LOG").map(|s| s == "1").unwrap_or(false); macro_rules! fail_if_strict { ($line_no:ident, $line:ident, $reason:expr) => { if strict { if verbose { println!( "Strict mode failure: did not parse line {}: {}\n\tReason: {:?}", $line_no + 1, $line, $reason ); } return Err(CueError::Parse(format!("strict mode failure: {}", $reason))); } }; } let mut cue = Cue::new(); fn last_file(cue: &mut Cue) -> Option<&mut CueFile> { cue.files.last_mut() } fn last_track(cue: &mut Cue) -> Option<&mut Track> { last_file(cue).and_then(|f| f.tracks.last_mut()) } for (i, line) in buf_reader.lines().enumerate() { if let Ok(ref l) = line { let token = tokenize_line(l); match token { Ok(Command::CdTextFile(path)) => { cue.cd_text_file = Some(path); } Ok(Command::Flags(flags)) => { if last_track(&mut cue).is_some() { last_track(&mut cue).unwrap().flags = flags; } else { fail_if_strict!(i, l, "FLAG assigned to no TRACK"); } } Ok(Command::Isrc(isrc)) => { if last_track(&mut cue).is_some() { last_track(&mut cue).unwrap().isrc = Some(isrc); } else { fail_if_strict!(i, l, "ISRC assigned to no TRACK"); } } Ok(Command::Rem(field, value)) => { let comment = (field, value); if last_track(&mut cue).is_some() { last_track(&mut cue).unwrap().comments.push(comment); } else if last_file(&mut cue).is_some() { last_file(&mut cue).unwrap().comments.push(comment); } else { cue.comments.push(comment); } } Ok(Command::File(file, format)) => { cue.files.push(CueFile::new(&file, &format)); } Ok(Command::Track(idx, mode)) => { if let Some(file) = last_file(&mut cue) { file.tracks.push(Track::new(&idx, &mode)); } else { fail_if_strict!(i, l, "TRACK assigned to no FILE"); } } Ok(Command::Title(title)) => { if last_track(&mut cue).is_some() { last_track(&mut cue).unwrap().title = Some(title); } else { cue.title = Some(title) } } Ok(Command::Performer(performer)) => { // this double check might be able to go away under non-lexical lifetimes if last_track(&mut cue).is_some() { last_track(&mut cue).unwrap().performer = Some(performer); } else { cue.performer = Some(performer); } } Ok(Command::Songwriter(songwriter)) => { if last_track(&mut cue).is_some() { last_track(&mut cue).unwrap().songwriter = Some(songwriter); } else { cue.songwriter = Some(songwriter); } } Ok(Command::Index(idx, time)) => { if let Some(track) = last_track(&mut cue) { if let Ok(duration) = timestamp_to_duration(&time) { track.indices.push((idx, duration)); } else { fail_if_strict!(i, l, "bad INDEX timestamp"); } } else { fail_if_strict!(i, l, "INDEX assigned to no track"); } } Ok(Command::Pregap(time)) => { if last_track(&mut cue).is_some() { if let Ok(duration) = timestamp_to_duration(&time) { last_track(&mut cue).unwrap().pregap = Some(duration); } else { fail_if_strict!(i, l, "bad PREGAP timestamp"); } } else { fail_if_strict!(i, l, "PREGAP assigned to no track"); } } Ok(Command::Postgap(time)) => { if last_track(&mut cue).is_some() { if let Ok(duration) = timestamp_to_duration(&time) { last_track(&mut cue).unwrap().postgap = Some(duration); } else { fail_if_strict!(i, l, "bad PREGAP timestamp"); } } else { fail_if_strict!(i, l, "POSTGAP assigned to no track"); } } Ok(Command::Catalog(id)) => { cue.catalog = Some(id); } Ok(Command::Unknown(line)) => { fail_if_strict!(i, l, &format!("unknown token -- {}", &line)); if last_track(&mut cue).is_some() { last_track(&mut cue).unwrap().unknown.push(line); } else { cue.unknown.push(line) } } _ => { fail_if_strict!(i, l, &format!("bad line -- {:?}", &line)); if verbose { println!("Bad line - did not parse line {}: {:?}", i + 1, l); } } } } } Ok(cue) }
350
fn read_num(cursor: &mut Cursor<Vec<u8>>) -> Result<u32, Box<std::error::Error>> { let mut v: Vec<u8> = vec![]; let mut c: [u8; 1] = [0]; // consume whitespace loop { cursor.read(&mut c)?; match &c { b" " | b"\t" | b"\n" => { }, _ => { cursor.seek(std::io::SeekFrom::Current(-1)); break; } } } // read number loop { cursor.read(&mut c)?; match c[0] { b'0' ... b'9' => { v.push(c[0]); }, b' ' | b'\t' | b'\n' => { cursor.seek(std::io::SeekFrom::Current(-1)); break; }, _ => { bail!("Parse error") } } } let num_str = std::str::from_utf8(&v)?; let num = num_str.parse::<u32>()?; Ok(num) }
351
pub fn threaded_quick_sort<T: 'static + PartialOrd + Debug + Send>(v: &mut [T]) { if v.len() <= 1 { return; } let p = pivot(v); println!("{:?}", v); let (a, b) = v.split_at_mut(p); let raw_a = a as *mut [T]; let raw_s = RawSend(raw_a); unsafe { let handle = std::thread::spawn(move || { threaded_quick_sort(&mut *raw_s.0); }); threaded_quick_sort(&mut b[1..]); // compiler doesn't know that we join these // We do handle.join().ok(); } }
352
pub fn parse_opts() -> Result<CliStatus, Error> { let opt = Opt::from_args(); log::debug!("Cli opts are: {:?}", opt); match opt.cmd { Command::Generate => { generate_empty_config().context("Failed to generate config")?; log::info!("config.yml generated"); Ok(CliStatus::Exit) } Command::Run { config, twil_sid, twil_token, twil_from, } => { if twil_sid.is_none() || twil_token.is_none() || twil_from.is_none() { bail!("TWIL_ACCOUNT_SID, TWIL_AUTH_TOKEN & TWIL_FROM env variables must be set, or passed via --twil-sid, --twil-token & --twil-from"); } let twil_sid = twil_sid.unwrap(); let twil_token = twil_token.unwrap(); let twil_from = twil_from.unwrap(); let app_config = AppConfig::new(config, twil_sid, twil_token, twil_from) .context("Failed to get config")?; Ok(CliStatus::Continue(app_config)) } } }
353
fn add_twice() { 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()); project .cargo_fuzz() .arg("add") .arg("new_fuzz_target") .assert() .stderr( predicate::str::contains("could not add target") .and(predicate::str::contains("File exists (os error 17)")), ) .failure(); }
354
fn reference_test() { use std::collections::HashMap; type Table = HashMap<String, Vec<String>>; let mut table = Table::new(); table.insert( "Gesualdo".to_string(), vec![ "many madrigals".to_string(), "Tenebrae Responsoria".to_string(), ], ); table.insert( "Caravaggio".to_string(), vec![ "The Musicians".to_string(), "The Calling of St. Matthew".to_string(), ], ); table.insert( "Cellini".to_string(), vec![ "Perseus with the head of Medusa".to_string(), "a salt cellar".to_string(), ], ); fn show(table: Table) { for (artist, works) in table { println!("works by {}", artist); for work in works { println!(" {}", work); } } } fn show_with_ref(table: &Table) { for (artist, works) in table { println!("works by {}", artist); for work in works { println!(" {}", work); } } } fn sort_works(table: &mut Table) { for (_artist, works) in table { works.sort(); } } show_with_ref(&table); assert_eq!(table["Gesualdo"][0], "many madrigals"); // OK sort_works(&mut table); assert_eq!(table["Gesualdo"][1], "many madrigals"); // OK show(table); // assert_eq!(table["Cellini"][0], "a salt cellar"); // error, use of moved value // implicitily borrows struct Anime { name: &'static str, bechdel_pass: bool, }; let aria = Anime { name: "Aria: The Animation", bechdel_pass: true, }; let anime_ref = &aria; assert_eq!(anime_ref.name, "Aria: The Animation"); assert_eq!((*anime_ref).name, "Aria: The Animation"); assert_eq!((*anime_ref).bechdel_pass, true); let mut v = vec![1973, 1968]; v.sort(); (&mut v).sort(); let mut x = 10; let mut y = 20; let mut r = &x; let b = true; if b { r = &y; } assert!(*r == 20); struct Point { x: i32, y: i32, } let point = Point { x: 1000, y: 729 }; let r: &Point = &point; let rr: &&Point = &r; let rrr: &&&Point = &rr; assert_eq!(rrr.x, 1000); assert_eq!(rrr.y, 729); x = 10; y = 10; let rx = &x; let ry = &y; let rrx = &rx; let rry = &ry; // assert!(rrx <= rry); assert!(rrx == rry); assert!(!std::ptr::eq(rrx, rry)); fn factorial(n: usize) -> usize { (1..n + 1).fold(1, |a, b| a * b) } let f = &factorial(6); assert_eq!(f + &1009, 1729); { let r; { let x = 1; r = &x; assert_eq!(*r, 1); // OK } // assert_eq!(*r, 1); // error; } static mut STASH: &i32 = &128; // fn test_func(p: &i32) { // error // fn test_func<'a>(p: &'a &i32) { // error too, this is the same as the above definition fn test_func(p: &'static i32) { // OK unsafe { STASH = p; } } static WORTH_POINTING_AT: i32 = 1000; test_func(&WORTH_POINTING_AT); unsafe { assert_eq!(STASH, &1000); } fn smallest(v: &[i32]) -> &i32 { let mut s = &v[0]; for r in &v[1..] { if *r < *s { s = r; } } s } { let parabola = [9, 4, 1, 0, 1, 4, 9]; let s = smallest(&parabola); assert_eq!(*s, 0); } /* struct S { r: &i32, } let s; { let x = 10; s = S { r: &x }; } */ // assert_eq!(*s, 10); // error /* struct S<'a, 'b> { x: &'a i32, y: &'b i32, } // fn sum_r_xy<'a, 'b, 'c>(r: &'a &i32, s: S<'b, 'c>) -> i32 { fn sum_r_xy(r: &i32, s: S) -> i32 { r + s.x + s.y } // fn first_third<'a>(point: &'a &[i32; 3]) -> (&'a i32, &'a i32) { fn first_third(point: &[i32; 3]) -> (&i32, &i32) { (&point[0], &point[2]) } struct StringTable { elements: Vec<String>, } impl StringTable { // fn find_by_prefix<'a, 'b>(&'a self, prefix: &'b str) -> Option<&'a String> { fn find_by_prefix(&self, prefix: &str) -> Option<&String> { for i in 0..self.elements.len() { if self.elements[i].starts_with(prefix) { return Some(&self.elements[i]); } } None } } */ { /* let v = vec![4, 8, 19, 27, 34, 10]; let r = &v; let aside = v; r[0]; // error */ let v = vec![4, 8, 19, 27, 34, 10]; { let r = &v; r[0]; } let aside = v; assert_eq!(aside[0], 4); } { fn extend(vec: &mut Vec<f64>, slice: &[f64]) { for elt in slice { vec.push(*elt); } } let mut wave = Vec::new(); let head = vec![0.0, 1.0]; let tail = [0.0, -1.0]; extend(&mut wave, &head); extend(&mut wave, &tail); assert_eq!(wave, vec![0.0, 1.0, 0.0, -1.0]); // extend(&mut wave, &wave); // error } { let mut x = 10; { let r1 = &x; let r2 = &x; assert_eq!(r1, r2); // x += 10; // error, it is borrowed } x += 10; assert_eq!(x, 20); // let m = &mut x; // error, it is also borrowed as immutable let mut y = 20; let m1 = &mut y; // let m2 = &mut y; // error, cannot borrow as mutable more than once // let z = y; // error, cannot use 'y' because it was mutably borrowed assert_eq!(&20, m1); { let mut w = (107, 109); w.0 = 108; let r = &w; let r0 = &r.0; // let m1 = &mut r.1; // error: can't reborrow shared as mutable assert_eq!(r0, &108); assert_eq!(w, (108, 109)); } } }
355
async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { // axum logs rejections from built-in extractors with the `axum::rejection` // target, at `TRACE` level. `axum::rejection=trace` enables showing those events "example_tracing_aka_logging=debug,tower_http=debug,axum::rejection=trace".into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); // build our application with a route let app = Router::new() .route("/", get(handler)) // `TraceLayer` is provided by tower-http so you have to add that as a dependency. // It provides good defaults but is also very customizable. // // See https://docs.rs/tower-http/0.1.1/tower_http/trace/index.html for more details. // // If you want to customize the behavior using closures here is how. .layer( TraceLayer::new_for_http() .make_span_with(|request: &Request<_>| { // Log the matched route's path (with placeholders not filled in). // Use request.uri() or OriginalUri if you want the real path. let matched_path = request .extensions() .get::<MatchedPath>() .map(MatchedPath::as_str); info_span!( "http_request", method = ?request.method(), matched_path, some_other_field = tracing::field::Empty, ) }) .on_request(|_request: &Request<_>, _span: &Span| { // You can use `_span.record("some_other_field", value)` in one of these // closures to attach a value to the initially empty field in the info_span // created above. }) .on_response(|_response: &Response, _latency: Duration, _span: &Span| { // ... }) .on_body_chunk(|_chunk: &Bytes, _latency: Duration, _span: &Span| { // ... }) .on_eos( |_trailers: Option<&HeaderMap>, _stream_duration: Duration, _span: &Span| { // ... }, ) .on_failure( |_error: ServerErrorsFailureClass, _latency: Duration, _span: &Span| { // ... }, ), ); // run it let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); tracing::debug!("listening on {}", listener.local_addr().unwrap()); axum::serve(listener, app).await.unwrap(); }
356
pub fn debug_test_succeed() { system_call(SystemCall::DebugTestSucceed); loop {} }
357
pub fn star1(lines: &Vec<String>) -> String { let days = initialize(lines); let mut guard_map = HashMap::new(); for day in days { guard_map.entry(day.guard_id) .or_insert(vec![]) .push(day); } let (&sleepiest_guard_id, sleepiest_guard_days) = guard_map.iter() .max_by_key(|(_, v)| v.iter() .map(|day| 60 - day.minutes_awake) .sum::<i32>() ).unwrap(); let mut sleepiest_guard_awake_by_minutes = vec![0; 60]; for day in sleepiest_guard_days { // println!("Day: {:?}", day); for minute in 0..60 { sleepiest_guard_awake_by_minutes[minute] += i32::from(day.minutes[minute]); } } let (max_minute, _) = sleepiest_guard_awake_by_minutes.iter().enumerate().min_by_key(|(_, times)| *times).unwrap(); println!("Min minute: {}, max guard: {}", max_minute, sleepiest_guard_id); (sleepiest_guard_id * max_minute as i32).to_string() }
358
pub fn pivot<T: PartialOrd>(v: &mut [T]) -> usize { let mut p = rand::read(v.len()); v.swap(p, 0); p = 0; for i in 1..v.len() { if v[i] < v[p] { // move our pivot forward 1, and put this element before it v.swap(p+1, i); v.swap(p, p+1); p += 1 } } p }
359